1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use aabb_quadtree::{ItemId, QuadTree};
use geom::{Bounds, Circle, Distance, Polygon, Pt2D};
use crate::mapspace::{ToggleZoomed, ToggleZoomedBuilder};
use crate::{Color, EventCtx, GeomBatch, GfxCtx, MultiKey, RewriteColor, Text};
pub struct World<ID: ObjectID> {
objects: HashMap<ID, Object<ID>>,
quadtree: QuadTree<ID>,
draw_master_batches: Vec<ToggleZoomed>,
hovering: Option<ID>,
dragging_from: Option<(Pt2D, bool)>,
}
#[derive(Clone)]
pub enum WorldOutcome<ID: ObjectID> {
ClickedFreeSpace(Pt2D),
Dragging {
obj: ID,
dx: f64,
dy: f64,
cursor: Pt2D,
},
Keypress(&'static str, ID),
ClickedObject(ID),
HoverChanged(Option<ID>, Option<ID>),
Nothing,
}
impl<I: ObjectID> WorldOutcome<I> {
pub fn maybe_map_id<O: ObjectID, F: Fn(I) -> Option<O>>(self, f: F) -> Option<WorldOutcome<O>> {
match self {
WorldOutcome::ClickedFreeSpace(pt) => Some(WorldOutcome::ClickedFreeSpace(pt)),
WorldOutcome::Dragging {
obj,
dx,
dy,
cursor,
} => Some(WorldOutcome::Dragging {
obj: f(obj)?,
dx,
dy,
cursor,
}),
WorldOutcome::Keypress(action, id) => Some(WorldOutcome::Keypress(action, f(id)?)),
WorldOutcome::ClickedObject(id) => Some(WorldOutcome::ClickedObject(f(id)?)),
WorldOutcome::HoverChanged(before, after) => {
let before = match before {
Some(x) => Some(f(x)?),
None => None,
};
let after = match after {
Some(x) => Some(f(x)?),
None => None,
};
Some(WorldOutcome::HoverChanged(before, after))
}
WorldOutcome::Nothing => Some(WorldOutcome::Nothing),
}
}
}
pub trait ObjectID: Clone + Copy + Debug + Eq + Hash {}
pub struct ObjectBuilder<'a, ID: ObjectID> {
world: &'a mut World<ID>,
id: ID,
hitbox: Option<Polygon>,
zorder: usize,
draw_normal: Option<ToggleZoomedBuilder>,
draw_hover: Option<ToggleZoomedBuilder>,
tooltip: Option<Text>,
clickable: bool,
draggable: bool,
keybindings: Vec<(MultiKey, &'static str)>,
}
impl<'a, ID: ObjectID> ObjectBuilder<'a, ID> {
pub fn hitbox(mut self, polygon: Polygon) -> Self {
assert!(self.hitbox.is_none(), "called hitbox twice");
self.hitbox = Some(polygon);
self
}
pub fn zorder(mut self, zorder: usize) -> Self {
assert!(self.zorder == 0, "called zorder twice");
self.zorder = zorder;
self
}
pub fn draw<I: Into<ToggleZoomedBuilder>>(mut self, normal: I) -> Self {
assert!(
self.draw_normal.is_none(),
"already specified how to draw normally"
);
self.draw_normal = Some(normal.into());
self
}
pub fn draw_color(self, color: Color) -> Self {
let hitbox = self.hitbox.clone().expect("call hitbox first");
self.draw(GeomBatch::from(vec![(color, hitbox)]))
}
pub fn draw_color_unzoomed(self, color: Color) -> Self {
let hitbox = self.hitbox.clone().expect("call hitbox first");
let mut draw = ToggleZoomed::builder();
draw.unzoomed.push(color, hitbox);
self.draw(draw)
}
pub fn drawn_in_master_batch(self) -> Self {
assert!(
self.draw_normal.is_none(),
"object is already drawn normally"
);
self.draw(GeomBatch::new())
}
pub fn draw_hovered<I: Into<ToggleZoomedBuilder>>(mut self, hovered: I) -> Self {
assert!(
self.draw_hover.is_none(),
"already specified how to draw hovered"
);
self.draw_hover = Some(hovered.into());
self
}
pub fn draw_hover_rewrite(self, rewrite: RewriteColor) -> Self {
let hovered = self
.draw_normal
.clone()
.expect("first specify how to draw normally")
.color(rewrite);
self.draw_hovered(hovered)
}
pub fn hover_alpha(self, alpha: f32) -> Self {
self.draw_hover_rewrite(RewriteColor::ChangeAlpha(alpha))
}
pub fn hover_outline(self, color: Color, thickness: Distance) -> Self {
let mut draw = self
.draw_normal
.clone()
.expect("first specify how to draw normally")
.draw_differently_zoomed();
let hitbox = self.hitbox.as_ref().expect("call hitbox first");
if let (Ok(unzoomed), Ok(zoomed)) = (
hitbox.to_outline(thickness),
hitbox.to_outline(thickness / 2.0),
) {
draw.unzoomed.push(color, unzoomed);
draw.zoomed.push(color.multiply_alpha(0.5), zoomed);
} else {
warn!(
"Can't hover_outline for {:?}. Falling back to a colored polygon",
self.id
);
draw = GeomBatch::from(vec![(
color.multiply_alpha(0.5),
self.hitbox.clone().unwrap(),
)])
.into();
}
self.draw_hovered(draw)
}
pub fn invisibly_hoverable(self) -> Self {
self.draw_hovered(GeomBatch::new())
}
pub fn tooltip(mut self, txt: Text) -> Self {
assert!(self.tooltip.is_none(), "already specified tooltip");
assert!(
self.draw_hover.is_some(),
"first specify how to draw hovered"
);
self.tooltip = Some(txt);
self
}
pub fn clickable(mut self) -> Self {
assert!(!self.clickable, "called clickable twice");
self.clickable = true;
self
}
pub fn set_clickable(mut self, clickable: bool) -> Self {
self.clickable = clickable;
self
}
pub fn draggable(mut self) -> Self {
assert!(!self.draggable, "called draggable twice");
self.draggable = true;
self
}
pub fn hotkey<I: Into<MultiKey>>(mut self, key: I, action: &'static str) -> Self {
self.keybindings.push((key.into(), action));
self
}
pub fn build(mut self, ctx: &EventCtx) {
let hitbox = self.hitbox.take().expect("didn't specify hitbox");
let bounds = hitbox.get_bounds();
let quadtree_id = self
.world
.quadtree
.insert_with_box(self.id, bounds.as_bbox());
self.world.objects.insert(
self.id,
Object {
_id: self.id,
quadtree_id,
hitbox,
zorder: self.zorder,
draw_normal: self
.draw_normal
.expect("didn't specify how to draw normally")
.build(ctx),
draw_hover: self.draw_hover.take().map(|draw| draw.build(ctx)),
tooltip: self.tooltip,
clickable: self.clickable,
draggable: self.draggable,
keybindings: self.keybindings,
},
);
}
}
struct Object<ID: ObjectID> {
_id: ID,
quadtree_id: ItemId,
hitbox: Polygon,
zorder: usize,
draw_normal: ToggleZoomed,
draw_hover: Option<ToggleZoomed>,
tooltip: Option<Text>,
clickable: bool,
draggable: bool,
keybindings: Vec<(MultiKey, &'static str)>,
}
impl<ID: ObjectID> World<ID> {
pub fn unbounded() -> World<ID> {
World {
objects: HashMap::new(),
quadtree: QuadTree::default(
Bounds::from(&[Pt2D::new(0.0, 0.0), Pt2D::new(std::f64::MAX, std::f64::MAX)])
.as_bbox(),
),
draw_master_batches: Vec::new(),
hovering: None,
dragging_from: None,
}
}
pub fn bounded(bounds: &Bounds) -> World<ID> {
World {
objects: HashMap::new(),
quadtree: QuadTree::default(bounds.as_bbox()),
draw_master_batches: Vec::new(),
hovering: None,
dragging_from: None,
}
}
pub fn add(&mut self, id: ID) -> ObjectBuilder<'_, ID> {
assert!(!self.objects.contains_key(&id), "duplicate object added");
ObjectBuilder {
world: self,
id,
hitbox: None,
zorder: 0,
draw_normal: None,
draw_hover: None,
tooltip: None,
clickable: false,
draggable: false,
keybindings: Vec::new(),
}
}
pub fn delete(&mut self, id: ID) {
if self.hovering == Some(id) {
self.hovering = None;
if self.dragging_from.is_some() {
panic!("Can't delete {:?} mid-drag", id);
}
}
self.delete_before_replacement(id);
}
pub fn delete_before_replacement(&mut self, id: ID) {
if let Some(obj) = self.objects.remove(&id) {
if self.quadtree.remove(obj.quadtree_id).is_none() {
warn!("{:?} wasn't in the quadtree", id);
}
} else {
panic!("Can't delete {:?}; it's not in the World", id);
}
}
pub fn maybe_delete(&mut self, id: ID) {
if self.hovering == Some(id) {
self.hovering = None;
if self.dragging_from.is_some() {
panic!("Can't delete {:?} mid-drag", id);
}
}
if let Some(obj) = self.objects.remove(&id) {
if self.quadtree.remove(obj.quadtree_id).is_none() {
warn!("{:?} wasn't in the quadtree", id);
}
}
}
pub fn initialize_hover(&mut self, ctx: &EventCtx) {
self.hovering = ctx
.canvas
.get_cursor_in_map_space()
.and_then(|cursor| self.calculate_hover(cursor));
}
pub fn hack_unset_hovering(&mut self) {
self.hovering = None;
}
pub fn rebuilt_during_drag(&mut self, prev_world: &World<ID>) {
if prev_world.dragging_from.is_some() {
self.dragging_from = prev_world.dragging_from;
self.hovering = prev_world.hovering;
assert!(self.objects.contains_key(self.hovering.as_ref().unwrap()));
}
}
pub fn draw_master_batch<I: Into<ToggleZoomedBuilder>>(&mut self, ctx: &EventCtx, draw: I) {
self.draw_master_batches.push(draw.into().build(ctx));
}
pub fn draw_master_batch_built(&mut self, draw: ToggleZoomed) {
self.draw_master_batches.push(draw);
}
pub fn event(&mut self, ctx: &mut EventCtx) -> WorldOutcome<ID> {
if let Some((drag_from, moved)) = self.dragging_from {
if ctx.input.left_mouse_button_released() {
self.dragging_from = None;
if !moved && self.objects[&self.hovering.unwrap()].clickable {
return WorldOutcome::ClickedObject(self.hovering.unwrap());
}
let before = self.hovering;
self.hovering = ctx
.canvas
.get_cursor_in_map_space()
.and_then(|cursor| self.calculate_hover(cursor));
return if before == self.hovering {
WorldOutcome::Nothing
} else {
WorldOutcome::HoverChanged(before, self.hovering)
};
}
if let Some((_, dy)) = ctx.input.get_mouse_scroll() {
ctx.canvas.zoom(dy, ctx.canvas.get_cursor());
}
if ctx.redo_mouseover() {
if let Some(cursor) = ctx.canvas.get_cursor_in_map_space() {
let dx = cursor.x() - drag_from.x();
let dy = cursor.y() - drag_from.y();
self.dragging_from = Some((cursor, true));
return WorldOutcome::Dragging {
obj: self.hovering.unwrap(),
dx,
dy,
cursor,
};
}
}
return WorldOutcome::Nothing;
}
let cursor = if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {
pt
} else {
let before = self.hovering.take();
return if before.is_some() {
WorldOutcome::HoverChanged(before, None)
} else {
WorldOutcome::Nothing
};
};
let mut neutral_outcome = WorldOutcome::Nothing;
if ctx.redo_mouseover() {
let before = self.hovering;
self.hovering = self.calculate_hover(cursor);
if before != self.hovering {
neutral_outcome = WorldOutcome::HoverChanged(before, self.hovering);
}
}
let mut allow_panning = true;
if let Some(id) = self.hovering {
let obj = &self.objects[&id];
if obj.clickable && ctx.normal_left_click() {
return WorldOutcome::ClickedObject(id);
}
if obj.draggable {
allow_panning = false;
if ctx.input.left_mouse_button_pressed() {
self.dragging_from = Some((cursor, false));
return neutral_outcome;
}
}
for (key, action) in &obj.keybindings {
if ctx.input.pressed(key.clone()) {
return WorldOutcome::Keypress(action, id);
}
}
}
if allow_panning {
ctx.canvas_movement();
if self.hovering.is_none() && ctx.normal_left_click() {
return WorldOutcome::ClickedFreeSpace(cursor);
}
} else if let Some((_, dy)) = ctx.input.get_mouse_scroll() {
ctx.canvas.zoom(dy, ctx.canvas.get_cursor());
}
neutral_outcome
}
fn calculate_hover(&self, cursor: Pt2D) -> Option<ID> {
let mut objects = Vec::new();
for &(id, _, _) in &self.quadtree.query(
Circle::new(cursor, Distance::meters(3.0))
.get_bounds()
.as_bbox(),
) {
objects.push(*id);
}
objects.sort_by_key(|id| self.objects[id].zorder);
objects.reverse();
for id in objects {
let obj = &self.objects[&id];
if obj.draw_hover.is_some() && obj.hitbox.contains_pt(cursor) {
return Some(id);
}
}
None
}
pub fn draw(&self, g: &mut GfxCtx) {
for draw in &self.draw_master_batches {
draw.draw(g);
}
let mut objects = Vec::new();
for &(id, _, _) in &self.quadtree.query(g.get_screen_bounds().as_bbox()) {
objects.push(*id);
}
objects.sort_by_key(|id| self.objects[id].zorder);
for id in objects {
let mut drawn = false;
let obj = &self.objects[&id];
if Some(id) == self.hovering {
if let Some(ref draw) = obj.draw_hover {
draw.draw(g);
drawn = true;
}
if let Some(ref txt) = obj.tooltip {
g.draw_mouse_tooltip(txt.clone());
}
}
if !drawn {
obj.draw_normal.draw(g);
}
}
}
pub fn get_hovering(&self) -> Option<ID> {
self.hovering
}
pub fn override_tooltip(&mut self, id: &ID, tooltip: Option<Text>) -> bool {
if let Some(obj) = self.objects.get_mut(id) {
obj.tooltip = tooltip;
true
} else {
false
}
}
pub fn calculate_hovering(&self, ctx: &EventCtx) -> Option<ID> {
ctx.canvas
.get_cursor_in_map_space()
.and_then(|cursor| self.calculate_hover(cursor))
}
pub fn get_hovered_keybindings(&self) -> Option<&Vec<(MultiKey, &'static str)>> {
Some(&self.objects[&self.hovering?].keybindings)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DummyID(usize);
impl ObjectID for DummyID {}
impl World<DummyID> {
pub fn add_unnamed(&mut self) -> ObjectBuilder<'_, DummyID> {
self.add(DummyID(self.objects.len()))
}
}