codecraft 0.1.1

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, an immediate-mode UI, audio and gamepad haptics
Documentation
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
//! The outliner: a live list of what is in the scene.
//!
//! Everything carrying a [`SceneItem`] is listed and nothing else. The board's
//! tiles, the pieces and the lamps are scene *content*; the panels this list
//! is drawn on are entities too, and are not.
//!
//! A row is an icon and a name. The icon comes from the object's kind and is
//! tinted by its category, so what a row *is* reads at a glance rather than
//! by reading the name -- a light and a rook are different colours before
//! they are different words.
//!
//! The list is rebuilt from scratch whenever the scene's shape changes rather
//! than diffed. At the handful of objects a scene holds, a rebuild is cheaper
//! than the bookkeeping needed to avoid one, and it cannot drift out of step
//! with the world.
//!
//! Reference: `substrate/src/ui/outliner.rs` in the robot2 tree, which does
//! this with selection, drag-to-reparent and a per-row eye. This is the list.

use bevy_ecs::prelude::*;

use super::color::Color;
use super::geometry::{Background, Icon, Label, LabelSize, Position, Size};
use super::layout::{self, Anchor, Metrics};
use super::panel::{Closed, ClosesPanel, Dragging, Movable, PanelChild, PanelMarker, TitleBar};
use super::rect::Rect;
use super::resources::ScreenSize;
use crate::sceneobjects::{Category, SceneItem};

/// How tall one row is, and how much of it the icon takes.
const ROW_HEIGHT: f32 = 17.0;
const ICON_SIZE: f32 = 13.0;
/// Room either side of the icon, and between it and the name.
const PADDING: f32 = 5.0;
const LABEL_SIZE: f32 = 1.5;
/// How wide the panel is. Wide enough for a name, narrow enough to sit beside
/// a scene rather than over it.
const WIDTH: f32 = 200.0;
/// How far down the panel starts, clear of whatever a game keeps in its own
/// top-left corner -- chessrs has a MENU button there. A dev panel is a guest
/// on somebody else's screen.
const TOP: f32 = 64.0;

/// The last row says how much is above and below what is showing. A board is
/// 32 pieces, 64 squares and 4 lamps, so something always is.
const OVERFLOW_ROW: f32 = 1.0;

/// Marks the outliner panel and every row in it, so the whole thing can be
/// taken down together.
#[derive(Component, Clone, Copy, Debug)]
pub struct OutlinerEntity;

/// Whether the outliner is up, and what it last listed.
#[derive(Resource, Default)]
pub struct Outliner {
    pub open: bool,
    /// Where the panel's top-left corner is. Remembered across rebuilds --
    /// the rows are made again from scratch every time the scene changes, and
    /// a panel that snapped back to the corner every time a piece moved would
    /// be unusable.
    origin: Option<(f32, f32)>,
    /// The first row showing. A board has a hundred objects in it and a
    /// screen has room for thirty.
    pub scroll: usize,
    /// The panel and its rows, in spawn order.
    entities: Vec<Entity>,
    /// What the last rebuild listed, to notice when the scene changes.
    listed: Vec<Entity>,
    /// Where the list had got to last rebuild, so a scroll rebuilds it.
    scrolled: usize,
}

impl Outliner {
    pub fn is_open(&self) -> bool {
        self.open
    }

    pub fn toggle(&mut self) {
        self.open = !self.open;
    }
}

/// Rebuilds the list when the scene's shape changes, and takes it down when
/// the panel closes.
///
/// Exclusive rather than a normal system: a row is a panel entity, an icon
/// entity and a label entity spawned together, and the whole list is torn
/// down and rebuilt in one go. Doing that through `Commands` would spread one
/// rebuild across two frames and show a half-built list in between.
pub fn rebuild_outliner_system(world: &mut World) {
    let mut outliner = world.remove_resource::<Outliner>().unwrap_or_default();

    let items: Vec<Entity> = {
        let mut query = world.query::<(Entity, &SceneItem)>();
        let mut items: Vec<(Entity, Category, &str)> = query
            .iter(world)
            .map(|(entity, item)| (entity, item.category(), item.name.as_str()))
            .collect();
        // By category and then by name: the tint already groups a row by what
        // it is, so the order should too, and within a group a name is what
        // somebody is scanning for. Spawn order is neither, and is not even
        // stable across rebuilds.
        items.sort_by(|a, b| (a.1 as u8, a.2).cmp(&(b.1 as u8, b.2)));
        items.into_iter().map(|(entity, _, _)| entity).collect()
    };

    // Where the panel has got to, and whether its X has been clicked: both
    // have to be read off the panel that is up before it is taken down.
    let was = outliner.origin;
    let mut dragging = false;
    if let Some(&panel) = outliner.entities.first() {
        if world.get::<Closed>(panel).is_some() {
            outliner.open = false;
        }
        if let Some(pos) = world.get::<Position>(panel) {
            outliner.origin = Some((pos.x, pos.y));
        }
        dragging = world.get::<Dragging>(panel).is_some();
    }

    let wanted = outliner.open;
    // A panel dragged somewhere new is a rebuild -- how many rows fit depends
    // on how far down the screen it starts -- but *not while the drag is
    // still going*. Rebuilding despawns the panel, and the drag lives on the
    // panel: rebuilding mid-drag drops the drag on the floor, and the panel
    // moves one frame and stops dead under the pointer.
    let changed = items != outliner.listed
        || outliner.scroll != outliner.scrolled
        || (outliner.origin != was && !dragging);
    if wanted && (!changed || dragging) && !outliner.entities.is_empty() {
        world.insert_resource(outliner);
        return;
    }

    for entity in outliner.entities.drain(..) {
        if let Ok(entity) = world.get_entity_mut(entity) {
            entity.despawn();
        }
    }
    outliner.listed = items.clone();
    outliner.scrolled = outliner.scroll;

    if wanted {
        let (width, height) = {
            let screen = world.resource::<ScreenSize>();
            (screen.width, screen.height)
        };
        let origin = outliner.origin.unwrap_or((layout::SCREEN_MARGIN, TOP));
        let (entities, clamped) = spawn_list(world, &items, outliner.scroll, origin, width, height);
        outliner.entities = entities;
        // Scrolling past the end sticks rather than showing a blank list.
        outliner.scroll = clamped;
        outliner.scrolled = clamped;
    }
    world.insert_resource(outliner);
}

/// The panel, and a row for each of `items` that still has a [`SceneItem`].
fn spawn_list(
    world: &mut World,
    items: &[Entity],
    scroll: usize,
    origin: (f32, f32),
    width: f32,
    height: f32,
) -> (Vec<Entity>, usize) {
    let all: Vec<(String, &'static str, Color)> = items
        .iter()
        .filter_map(|&entity| {
            let item = world.get::<SceneItem>(entity)?;
            Some((item.name.clone(), item.icon(), item.category().color()))
        })
        .collect();

    // As many rows as the screen has room for, keeping the last one for the
    // count of what is off the ends.
    let room =
        (((height - origin.1 - layout::SCREEN_MARGIN - PADDING * 2.0 - layout::TITLE_HEIGHT)
            / ROW_HEIGHT)
            .floor()
            - OVERFLOW_ROW)
            .max(1.0) as usize;
    let scroll = scroll.min(all.len().saturating_sub(room));
    let below = all.len().saturating_sub(scroll + room);
    let mut rows: Vec<(String, &'static str, Color)> =
        all.into_iter().skip(scroll).take(room).collect();
    if scroll > 0 || below > 0 {
        rows.push((
            format!("{scroll} ABOVE, {below} BELOW"),
            super::icons::path::LIST_BULLETS,
            Color::srgb(0.55, 0.55, 0.60),
        ));
    }

    let panel_height = rows.len() as f32 * ROW_HEIGHT + PADDING * 2.0 + layout::TITLE_HEIGHT;
    let panel = Rect::new(origin.0, origin.1, WIDTH, panel_height);
    let (pos, size): (Position, Size) = panel.into();

    let panel_entity = world
        .spawn((
            pos,
            size,
            Background(Color::srgba(0.08, 0.08, 0.11, 0.94)),
            PanelMarker,
            Movable,
            OutlinerEntity,
            Name::new("Outliner"),
        ))
        .id();
    let mut spawned = vec![panel_entity];

    // The bar: the name of the panel, the handle it moves by, and the X.
    let bar = Rect::new(panel.x, panel.y, panel.width, layout::TITLE_HEIGHT);
    let (bar_pos, bar_size): (Position, Size) = bar.into();
    spawned.push(
        world
            .spawn((
                bar_pos,
                bar_size,
                Background(Color::srgba(0.16, 0.16, 0.21, 0.96)),
                Label("OUTLINER".into()),
                LabelSize(layout::TITLE_LABEL_SIZE),
                TitleBar {
                    panel: panel_entity,
                },
                PanelChild(panel_entity),
                OutlinerEntity,
            ))
            .id(),
    );
    let side = layout::TITLE_HEIGHT - layout::TITLE_INSET * 2.0;
    let close = Rect::new(
        bar.x + bar.width - side - layout::TITLE_INSET,
        bar.y + layout::TITLE_INSET,
        side,
        side,
    );
    let (close_pos, close_size): (Position, Size) = close.into();
    spawned.push(
        world
            .spawn((
                close_pos,
                close_size,
                super::button::ButtonColors::close(),
                Icon::new(super::icons::path::X),
                super::interaction::Interaction::default(),
                super::button::ButtonMarker,
                ClosesPanel(panel_entity),
                PanelChild(panel_entity),
                OutlinerEntity,
            ))
            .id(),
    );

    for (index, (name, icon, color)) in rows.into_iter().enumerate() {
        let y = panel.y + layout::TITLE_HEIGHT + PADDING + index as f32 * ROW_HEIGHT;

        spawned.push(
            world
                .spawn((
                    Position {
                        x: panel.x + PADDING,
                        y: y + (ROW_HEIGHT - ICON_SIZE) * 0.5,
                    },
                    Size {
                        width: ICON_SIZE,
                        height: ICON_SIZE,
                    },
                    Icon::tinted(icon, color),
                    PanelChild(panel_entity),
                    OutlinerEntity,
                ))
                .id(),
        );

        // The name is drawn as a label on a rect that starts after the icon,
        // so every name in the list lines up whatever its icon is.
        spawned.push(
            world
                .spawn((
                    Position {
                        x: panel.x + PADDING * 2.0 + ICON_SIZE,
                        y,
                    },
                    Size {
                        width: WIDTH - ICON_SIZE - PADDING * 3.0,
                        height: ROW_HEIGHT,
                    },
                    Label(name),
                    LabelSize(LABEL_SIZE),
                    OutlinerRow,
                    PanelChild(panel_entity),
                    OutlinerEntity,
                ))
                .id(),
        );
    }

    let _ = width;
    (spawned, scroll)
}

/// Scrolls the list with the wheel, while the pointer is over it.
///
/// The wheel is spent by [`super::systems::clear_input_edge_system`] at the
/// end of the frame, so this reads it before then and only when the pointer
/// is actually on the panel -- otherwise scrolling anywhere on screen would
/// move a list in the corner.
pub fn scroll_outliner_system(
    mouse: Res<super::resources::MouseInput>,
    cursor: Res<super::resources::CursorPosition>,
    panels: Query<(&Position, &Size), (With<PanelMarker>, With<OutlinerEntity>)>,
    mut outliner: ResMut<Outliner>,
) {
    if mouse.scroll == 0.0 || !outliner.open {
        return;
    }
    let over = panels
        .iter()
        .any(|(pos, size)| pos.rect(size).contains(cursor.x, cursor.y));
    if !over {
        return;
    }
    // Away from the user goes up the list, which is the direction the content
    // moves rather than the direction the wheel turns.
    let by = mouse.scroll.round() as i32 * 3;
    outliner.scroll = (outliner.scroll as i32 - by).max(0) as usize;
}

/// A row's name. Drawn left-aligned inside its rect rather than centred like
/// a button's label, because a column of centred names is unreadable.
#[derive(Component, Clone, Copy, Debug)]
pub struct OutlinerRow;

/// The metrics the outliner draws its names at, for anything that has to
/// measure one.
pub fn row_metrics() -> Metrics {
    Metrics {
        button_width: WIDTH,
        button_height: ROW_HEIGHT,
        spacing: 0.0,
        label_size: LABEL_SIZE,
    }
}

/// Where the outliner sits, for tests and for anything that has to keep clear
/// of it.
pub fn anchor() -> Anchor {
    Anchor::TopLeft
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::AppState;
    use crate::ecs::{Application, Entity};
    use crate::sceneobjects::{Category, SceneObject};
    use crate::ui::icons::path;
    use crate::ui::plugin::UiPlugin;

    struct Lamp;
    impl SceneObject for Lamp {
        fn label(&self) -> &'static str {
            "Lamp"
        }
        fn icon(&self) -> &'static str {
            path::LAMP
        }
        fn category(&self) -> Category {
            Category::Light
        }
        // These two are here to be *listed*, so an outliner row has a kind to
        // read its label and icon off. Nothing spawns one.
        fn spawn(&self, app: &mut AppState) -> Entity {
            app.spawn_entity(())
        }
    }

    struct Block;
    impl SceneObject for Block {
        fn label(&self) -> &'static str {
            "Block"
        }
        fn icon(&self) -> &'static str {
            path::CUBE
        }
        fn category(&self) -> Category {
            Category::Mesh
        }
        fn spawn(&self, app: &mut AppState) -> Entity {
            app.spawn_entity(())
        }
    }

    fn app() -> Application {
        let mut app = Application::new();
        app.add_plugin(UiPlugin);
        app.world.insert_resource(ScreenSize {
            width: 1280.0,
            height: 800.0,
        });
        app
    }

    fn names(app: &mut Application) -> Vec<String> {
        let mut rows: Vec<(f32, String)> = app
            .world
            .query_filtered::<(&Position, &Label), With<OutlinerRow>>()
            .iter(&app.world)
            .map(|(pos, label)| (pos.y, label.0.clone()))
            .collect();
        rows.sort_by(|a, b| a.0.total_cmp(&b.0));
        rows.into_iter().map(|(_, name)| name).collect()
    }

    #[test]
    fn nothing_is_listed_until_it_is_opened() {
        let mut app = app();
        app.world.spawn(SceneItem::new(&Lamp, "Lamp 1"));
        app.update();
        assert!(names(&mut app).is_empty());

        app.world.resource_mut::<Outliner>().toggle();
        app.update();
        assert_eq!(names(&mut app), ["Lamp 1"]);
    }

    /// The tint already groups a row by what it is, so the order should too.
    #[test]
    fn rows_are_grouped_by_category_then_named_in_order() {
        let mut app = app();
        app.world.spawn(SceneItem::new(&Block, "Zebra"));
        app.world.spawn(SceneItem::new(&Lamp, "Key"));
        app.world.spawn(SceneItem::new(&Block, "Apple"));
        app.world.spawn(SceneItem::new(&Lamp, "Fill"));
        app.world.resource_mut::<Outliner>().toggle();
        app.update();

        // Lights before meshes, and alphabetical inside each.
        assert_eq!(names(&mut app), ["Fill", "Key", "Apple", "Zebra"]);
    }

    #[test]
    fn a_row_carries_its_kind_s_icon_tinted_by_its_category() {
        let mut app = app();
        app.world.spawn(SceneItem::new(&Lamp, "Lamp 1"));
        app.world.resource_mut::<Outliner>().toggle();
        app.update();

        // The close button in the title bar has an icon too, so this asks
        // only for the ones on rows.
        let icons: Vec<Icon> = app
            .world
            .query_filtered::<&Icon, Without<crate::ui::panel::ClosesPanel>>()
            .iter(&app.world)
            .copied()
            .collect();
        assert_eq!(icons.len(), 1);
        assert_eq!(icons[0].path, path::LAMP);
        assert_eq!(icons[0].color, Category::Light.color());
    }

    #[test]
    fn the_list_follows_the_scene() {
        let mut app = app();
        let lamp = app.world.spawn(SceneItem::new(&Lamp, "Lamp 1")).id();
        app.world.resource_mut::<Outliner>().toggle();
        app.update();
        assert_eq!(names(&mut app).len(), 1);

        app.world.spawn(SceneItem::new(&Block, "Block 1"));
        app.update();
        assert_eq!(names(&mut app).len(), 2, "a new object appears");

        app.world.despawn(lamp);
        app.update();
        assert_eq!(names(&mut app), ["Block 1"], "and a gone one leaves");
    }

    #[test]
    fn closing_it_takes_every_row_with_it() {
        let mut app = app();
        app.world.spawn(SceneItem::new(&Lamp, "Lamp 1"));
        app.world.resource_mut::<Outliner>().toggle();
        app.update();
        assert!(!names(&mut app).is_empty());

        app.world.resource_mut::<Outliner>().toggle();
        app.update();
        assert!(names(&mut app).is_empty());
        assert_eq!(
            app.world.query::<&Icon>().iter(&app.world).count(),
            0,
            "and its icons, and the X in its bar",
        );
    }

    /// More objects than rows: the list shows a window onto them and says how
    /// much is off each end.
    /// The wheel over a panel belongs to the panel. Without this the list
    /// scrolls *and* the camera zooms, which is the bug the capture exists
    /// to stop.
    #[test]
    fn the_wheel_over_the_panel_is_the_panel_s() {
        use crate::ui::resources::{CursorPosition, PointerCapture};

        let mut app = app();
        app.world.spawn(SceneItem::new(&Lamp, "Lamp 1"));
        app.world.resource_mut::<Outliner>().toggle();
        app.update();

        let panel = app
            .world
            .query_filtered::<(&Position, &Size), (With<PanelMarker>, With<OutlinerEntity>)>()
            .iter(&app.world)
            .next()
            .map(|(pos, size)| pos.rect(size))
            .expect("the outliner panel");

        app.world.insert_resource(CursorPosition {
            x: panel.center_x(),
            y: panel.center_y(),
        });
        app.update();
        assert!(
            app.world.resource::<PointerCapture>().taken(),
            "the pointer is on the panel, so the mouse is the UI's",
        );

        // And off it, the world gets the mouse back.
        app.world.insert_resource(CursorPosition {
            x: panel.x + panel.width + 50.0,
            y: panel.y,
        });
        app.update();
        assert!(!app.world.resource::<PointerCapture>().taken());
    }

    #[test]
    fn the_x_in_its_bar_closes_it() {
        let mut app = app();
        app.world.spawn(SceneItem::new(&Lamp, "Lamp 1"));
        app.world.resource_mut::<Outliner>().toggle();
        app.update();
        assert!(!names(&mut app).is_empty());

        let x = app
            .world
            .query::<(Entity, &ClosesPanel)>()
            .iter(&app.world)
            .next()
            .map(|(entity, _)| entity)
            .expect("an X in the bar");
        let rect = {
            let pos = app.world.get::<Position>(x).unwrap();
            let size = app.world.get::<Size>(x).unwrap();
            pos.rect(size)
        };
        app.world
            .insert_resource(crate::ui::resources::CursorPosition {
                x: rect.center_x(),
                y: rect.center_y(),
            });
        app.world.insert_resource(crate::ui::resources::MouseInput {
            left_down: true,
            just_pressed: true,
            ..Default::default()
        });
        app.update();
        app.update();

        assert!(!app.world.resource::<Outliner>().is_open());
        assert!(names(&mut app).is_empty(), "and its rows went with it");
    }

    #[test]
    fn a_long_list_scrolls_and_says_what_it_is_hiding() {
        let mut app = app();
        for i in 0..100 {
            app.world
                .spawn(SceneItem::new(&Block, format!("Block {i:03}")));
        }
        app.world.resource_mut::<Outliner>().toggle();
        app.update();

        let first = names(&mut app);
        assert!(
            first.len() < 100,
            "the whole list cannot fit: {}",
            first.len()
        );
        assert_eq!(first[0], "Block 000");
        let counts = first.last().expect("a row saying what is hidden");
        assert!(counts.starts_with("0 ABOVE, "), "{counts}");

        app.world.resource_mut::<Outliner>().scroll = 10;
        app.update();
        let scrolled = names(&mut app);
        assert_eq!(scrolled[0], "Block 010", "it moved down the list");
        assert!(scrolled.last().unwrap().starts_with("10 ABOVE, "));

        // Past the end sticks at the end rather than showing a blank panel.
        app.world.resource_mut::<Outliner>().scroll = 1000;
        app.update();
        let end = names(&mut app);
        assert!(!end.is_empty(), "scrolling past the end left nothing");
        assert!(end.last().unwrap().ends_with("0 BELOW"), "{:?}", end.last());
    }
}