codecraft 0.2.0

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, a yakui-drawn UI, audio and gamepad haptics; its binary maps any folder, and the symbols of its Rust files, as a 3D wall of boxes
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
610
611
612
//! Dev mode: the F12 switch, its badge and menu, and the F9/F10/F11 keys.
//!
//! ```no_run
//! # use codecraft::AppState;
//! # fn demo(app: &mut AppState) {
//! if app.dev_mode() {
//!     // show the working
//! }
//! # }
//! ```
use bevy_ecs::prelude::*;
use yakui::widgets::{Layer, List, Pad, Reflow};
use yakui::{Alignment, CrossAxisAlignment, Dim2, Pivot, WidgetId};

use crate::ecs::{Application, IntoScheduleConfigs, Plugin};
use crate::input::{KeyCode, Keys};
use crate::ui::icons::path;
use crate::ui::{self, MouseInput, Outliner, PointerCapture, Profiler};

/// The key that turns it on and off.
pub const TOGGLE: KeyCode = KeyCode::F12;

/// The key that shows and hides the outliner, while dev mode is on.
pub const OUTLINER: KeyCode = KeyCode::F11;

/// The key that steps through the five faces the UI can be drawn in.
pub const FONT: KeyCode = KeyCode::F10;

/// The key that shows and hides the frame profiler, while dev mode is on.
pub const PROFILER: KeyCode = KeyCode::F9;

/// Whether dev mode is on.
#[derive(Resource, Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DevMode(pub bool);

impl DevMode {
    pub fn is_on(self) -> bool {
        self.0
    }
}

/// The dev menu's state, and where its parts were drawn last frame.
#[derive(Resource, Default)]
pub struct DevMenu {
    pub open: bool,
    submenu: Option<usize>,
    pub(crate) badge: Option<WidgetId>,
    pub(crate) tops: Vec<WidgetId>,
    pub(crate) entries: Vec<WidgetId>,
}

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

/// Flips dev mode on F12.
pub fn dev_mode_system(keys: Res<Keys>, mut commands: Commands) {
    if keys.just_pressed(TOGGLE) {
        commands.queue(|world: &mut World| {
            let on = !world.resource::<DevMode>().is_on();
            set(world, on);
        });
    }
}

/// Turns dev mode on or off; going off closes the menu and the outliner.
pub fn set(world: &mut World, on: bool) {
    let was = std::mem::replace(&mut world.resource_mut::<DevMode>().0, on);
    if was != on {
        log::info!("dev mode {}", if on { "on" } else { "off" });
    }
    if !on {
        let mut menu = world.resource_mut::<DevMenu>();
        menu.open = false;
        menu.submenu = None;
        world.resource_mut::<Outliner>().open = false;
    }
}

/// Shows and hides the outliner on [`OUTLINER`], while dev mode is on.
pub fn outliner_key_system(keys: Res<Keys>, dev: Res<DevMode>, mut outliner: ResMut<Outliner>) {
    if !dev.is_on() || !keys.just_pressed(OUTLINER) {
        return;
    }
    outliner.toggle();
    log::info!(
        "outliner {}",
        match outliner.is_open() {
            true => "up",
            false => "down",
        },
    );
}

/// Shows and hides the frame profiler on [`PROFILER`], while dev mode is on.
pub fn profiler_key_system(keys: Res<Keys>, dev: Res<DevMode>, mut profiler: ResMut<Profiler>) {
    if dev.is_on() && keys.just_pressed(PROFILER) {
        profiler.on = !profiler.on;
        log::info!(
            "profiler {}",
            match profiler.on {
                true => "on",
                false => "off",
            }
        );
    }
}

/// Steps through the five Monaspace faces on [`FONT`], while dev mode is on.
pub fn font_key_system(keys: Res<Keys>, dev: Res<DevMode>, mut font: ResMut<ui::Font>) {
    if dev.is_on() && keys.just_pressed(FONT) {
        font.cycle();
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Action {
    Nothing,
    Outliner,
    Exit,
}

struct Top {
    label: &'static str,
    entries: &'static [(&'static str, Action)],
}

// No Create menu yet: it would build itself from a registry this renderer lacks.
const MENU: &[Top] = &[
    Top {
        label: "APP",
        entries: &[
            ("PLAY", Action::Nothing),
            ("EDIT", Action::Nothing),
            ("CONNECTIONS", Action::Nothing),
            ("SETTINGS", Action::Nothing),
            ("ABOUT", Action::Nothing),
            ("EXIT", Action::Exit),
        ],
    },
    Top {
        label: "FILE",
        entries: &[
            ("IMPORT MODEL", Action::Nothing),
            ("OPEN SCENE", Action::Nothing),
            ("SAVE SCENE AS", Action::Nothing),
        ],
    },
    Top {
        label: "VIEW",
        entries: &[
            ("OUTLINER", Action::Outliner),
            ("INSTANCES", Action::Nothing),
            ("PROPERTIES", Action::Nothing),
            ("TIMELINE", Action::Nothing),
            ("ACTIONS", Action::Nothing),
            ("SCREENSHOT", Action::Nothing),
            ("RECENTER VIEW", Action::Nothing),
        ],
    },
];

/// Draws the badge, the menu, the outliner and the profiler, and acts on what was clicked.
pub fn dev_ui_system(world: &mut World) {
    if !world.resource::<DevMode>().is_on() {
        return;
    }
    let mouse = *world.resource::<MouseInput>();
    let over_panel = world.resource::<PointerCapture>().over_panel;
    let mut menu = world.remove_resource::<DevMenu>().unwrap_or_default();
    if menu.open && mouse.just_pressed && !over_panel {
        menu.open = false;
    }

    let mut chosen: Option<Action> = None;
    let mut toggle_badge = false;
    let mut hovered_top: Option<usize> = None;
    let mut over_submenu = false;
    menu.tops.clear();
    menu.entries.clear();

    // Its own layer, so the dev UI takes the pointer before a game panel under it.
    Layer::new().show(|| {
        ui::screen(|| {
            ui::outliner::show(world);
            world.resource::<Profiler>().show();

            ui::place(1.0, 1.0, Pivot::BOTTOM_RIGHT, || {
                yakui::pad(Pad::all(ui::SCREEN_MARGIN), || {
                    // Badge first, menu hung off it: yakui widget identity is tree position, and a badge that moved would lose its click.
                    let mut stack = List::column();
                    stack.main_axis_size = yakui::MainAxisSize::Min;
                    stack.cross_axis_alignment = CrossAxisAlignment::End;
                    stack.show(|| {
                        let caret = match menu.open {
                            true => path::CARET_DOWN,
                            false => path::CARET_UP,
                        };
                        ui::rows(|| {
                            let badge = ui::menu_row("DEV", Some(path::WRENCH), Some(caret));
                            menu.badge = Some(badge.id);
                            toggle_badge = badge.clicked;
                        });

                        Reflow::new(Alignment::TOP_RIGHT, Pivot::BOTTOM_RIGHT, Dim2::ZERO).show(
                            || {
                                if !menu.open {
                                    return;
                                }
                                ui::rows(|| {
                                    for (index, top) in MENU.iter().enumerate() {
                                        let mut row = List::row();
                                        row.main_axis_size = yakui::MainAxisSize::Min;
                                        row.show(|| {
                                            let response = ui::menu_row(
                                                top.label,
                                                None,
                                                Some(path::CARET_LEFT),
                                            );
                                            menu.tops.push(response.id);
                                            if response.hovering {
                                                hovered_top = Some(index);
                                            }
                                            if menu.submenu == Some(index) {
                                                submenu(
                                                    top,
                                                    &mut menu,
                                                    &mut chosen,
                                                    &mut over_submenu,
                                                );
                                            }
                                        });
                                    }
                                });
                            },
                        );
                    });
                });
            });
        });
    });

    // Hovering a row wins; else the open submenu stays while the pointer is inside it, so it can travel from row to submenu.
    menu.submenu = hovered_top.or(match over_submenu {
        true => menu.submenu,
        false => None,
    });
    if toggle_badge {
        menu.open = !menu.open;
    }
    if let Some(action) = chosen {
        menu.open = false;
        menu.submenu = None;
        match action {
            Action::Nothing => {}
            Action::Outliner => world.resource_mut::<Outliner>().toggle(),
            Action::Exit => std::process::exit(0),
        }
    }
    if !menu.open {
        menu.submenu = None;
    }
    world.insert_resource(menu);
}

// The hover region sits inside the panel: the opaque panel would hide the pointer from anything wrapped round it.
fn submenu(top: &Top, menu: &mut DevMenu, chosen: &mut Option<Action>, over_submenu: &mut bool) {
    Reflow::new(
        Alignment::BOTTOM_LEFT,
        Pivot::BOTTOM_RIGHT,
        Dim2::pixels(-ui::PANEL_PADDING, 0.0),
    )
    .show(|| {
        Layer::new().show(|| {
            ui::panel(|| {
                let region = ui::clickable(None, || {
                    let mut column = List::column();
                    column.main_axis_size = yakui::MainAxisSize::Min;
                    column.show(|| {
                        for (label, action) in top.entries {
                            let entry = ui::menu_row(*label, None, None);
                            menu.entries.push(entry.id);
                            if entry.clicked {
                                *chosen = Some(*action);
                            }
                        }
                    });
                });
                *over_submenu |= region.hovering;
            });
        });
    });
}

pub struct DevPlugin;

impl Plugin for DevPlugin {
    fn build(&self, app: &mut Application) {
        app.init_resource::<DevMode>();
        app.init_resource::<DevMenu>();
        app.init_resource::<Outliner>();
        app.init_resource::<ui::Font>();
        app.init_resource::<Profiler>();
        app.add_update_systems(dev_mode_system);
        app.add_update_systems(outliner_key_system);
        app.add_update_systems(font_key_system);
        app.add_update_systems(profiler_key_system);
        // It reads this frame's click, so it goes before the edge is spent.
        app.add_update_systems(dev_ui_system.before(ui::clear_input_edge_system));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ui::{CursorPosition, ScreenSize, Ui, UiPlugin};
    use yakui::geometry::Vec2;

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

    fn frame(app: &mut Application) {
        Ui::begin_frame(&mut app.world);
        app.update();
        Ui::end_frame(&mut app.world);
    }

    fn press(app: &mut Application, key: KeyCode) {
        app.world.resource_mut::<Keys>().press(key, false);
        frame(app);
        let mut keys = app.world.resource_mut::<Keys>();
        keys.end_frame();
        keys.release(key);
    }

    fn press_f12(app: &mut Application) {
        press(app, TOGGLE);
    }

    fn outliner_open(app: &Application) -> bool {
        app.world.resource::<Outliner>().is_open()
    }

    fn menu_open(app: &Application) -> bool {
        app.world.resource::<DevMenu>().is_open()
    }

    fn rect_of(app: &Application, id: WidgetId) -> yakui::geometry::Rect {
        app.world
            .non_send::<Ui>()
            .rect_of(id)
            .expect("it was drawn last frame")
    }

    fn badge(app: &Application) -> yakui::geometry::Rect {
        let id = app.world.resource::<DevMenu>().badge.expect("a badge");
        rect_of(app, id)
    }

    fn hover(app: &mut Application, at: Vec2) {
        app.world
            .insert_resource(CursorPosition { x: at.x, y: at.y });
        frame(app);
    }

    fn click(app: &mut Application, at: Vec2) {
        app.world
            .insert_resource(CursorPosition { x: at.x, y: at.y });
        app.world.insert_resource(MouseInput {
            left_down: true,
            just_pressed: true,
            ..MouseInput::default()
        });
        frame(app);
        app.world.insert_resource(MouseInput {
            just_released: true,
            ..MouseInput::default()
        });
        frame(app);
    }

    fn center(rect: yakui::geometry::Rect) -> Vec2 {
        rect.pos() + rect.size() * 0.5
    }

    #[test]
    fn f12_turns_it_on_and_off_again() {
        let mut app = app();
        assert!(
            !app.world.resource::<DevMode>().is_on(),
            "off to start with"
        );

        press_f12(&mut app);
        assert!(app.world.resource::<DevMode>().is_on());

        press_f12(&mut app);
        assert!(!app.world.resource::<DevMode>().is_on());
    }

    #[test]
    fn the_badge_is_drawn_only_while_it_is_on() {
        let mut app = app();
        frame(&mut app);
        assert!(app.world.resource::<DevMenu>().badge.is_none());

        press_f12(&mut app);
        frame(&mut app);
        let badge = badge(&app);
        assert!(
            badge.pos().x > 1000.0 && badge.pos().y > 700.0,
            "in the bottom-right corner: {badge:?}"
        );
    }

    #[test]
    fn the_badge_opens_the_menu_and_closes_it_again() {
        let mut app = app();
        press_f12(&mut app);
        frame(&mut app);

        assert!(!menu_open(&app));
        let at = center(badge(&app));
        click(&mut app, at);
        assert!(menu_open(&app), "one click opens");

        let at = center(badge(&app));
        click(&mut app, at);
        assert!(!menu_open(&app), "and the next one closes");
    }

    #[test]
    fn clicking_away_from_the_menu_closes_it() {
        let mut app = app();
        press_f12(&mut app);
        frame(&mut app);
        let at = center(badge(&app));
        click(&mut app, at);
        assert!(menu_open(&app));

        click(&mut app, Vec2::new(20.0, 20.0));
        assert!(
            !menu_open(&app),
            "a click on the game is not a click on the menu"
        );
    }

    #[test]
    fn a_submenu_opens_on_hover_to_the_left_and_stays_while_the_pointer_is_in_it() {
        let mut app = app();
        press_f12(&mut app);
        frame(&mut app);
        let at = center(badge(&app));
        click(&mut app, at);
        frame(&mut app);

        let tops = app.world.resource::<DevMenu>().tops.clone();
        assert_eq!(tops.len(), MENU.len(), "a row per top-level entry");
        assert!(
            app.world.resource::<DevMenu>().entries.is_empty(),
            "closed until the pointer arrives"
        );

        let row = rect_of(&app, tops[2]);
        let at = center(row);
        hover(&mut app, at);
        frame(&mut app);
        let entries = app.world.resource::<DevMenu>().entries.clone();
        assert_eq!(
            entries.len(),
            MENU[2].entries.len(),
            "hovering the row opens it"
        );
        let first = rect_of(&app, entries[0]);
        assert!(
            first.pos().x + first.size().x <= row.pos().x + 1.0,
            "a menu in the right-hand corner opens its submenus to the left: \
             entry at {first:?} against a row at {row:?}",
        );

        let at = center(rect_of(&app, entries[3]));
        hover(&mut app, at);
        frame(&mut app);
        assert!(
            !app.world.resource::<DevMenu>().entries.is_empty(),
            "and stays open once the pointer is in it"
        );

        hover(&mut app, Vec2::new(10.0, 10.0));
        frame(&mut app);
        assert!(
            app.world.resource::<DevMenu>().entries.is_empty(),
            "and closes once the pointer leaves both"
        );
        assert!(menu_open(&app), "hovering away is not a click away");
    }

    #[test]
    fn choosing_an_entry_acts_on_it_and_closes_the_menu() {
        let mut app = app();
        press_f12(&mut app);
        frame(&mut app);
        let at = center(badge(&app));
        click(&mut app, at);
        frame(&mut app);

        let view = app.world.resource::<DevMenu>().tops[2];
        let at = center(rect_of(&app, view));
        hover(&mut app, at);
        frame(&mut app);
        let outliner = app.world.resource::<DevMenu>().entries[0];
        let at = center(rect_of(&app, outliner));
        click(&mut app, at);

        assert!(outliner_open(&app), "VIEW > OUTLINER puts it up");
        assert!(!menu_open(&app), "picking from a menu puts it away");
    }

    #[test]
    fn f11_shows_the_outliner_and_hides_it_again() {
        let mut app = app();
        press_f12(&mut app);
        assert!(!outliner_open(&app), "down to start with");

        press(&mut app, OUTLINER);
        assert!(outliner_open(&app), "one press puts it up");

        press(&mut app, OUTLINER);
        assert!(!outliner_open(&app), "and the next takes it down");
    }

    #[test]
    fn f11_does_nothing_outside_dev_mode() {
        let mut app = app();
        press(&mut app, OUTLINER);
        assert!(!outliner_open(&app), "no outliner without the working");
    }

    #[test]
    fn leaving_dev_mode_takes_the_menu_and_the_outliner_with_it() {
        let mut app = app();
        press_f12(&mut app);
        press(&mut app, OUTLINER);
        frame(&mut app);
        let at = center(badge(&app));
        click(&mut app, at);
        assert!(menu_open(&app) && outliner_open(&app));

        press_f12(&mut app);
        assert!(!menu_open(&app), "the menu cannot outlive the mode");
        assert!(!outliner_open(&app), "nor can the outliner");
    }

    #[test]
    fn f10_steps_through_the_faces() {
        use crate::ui::{Family, Font};

        let mut app = app();
        press_f12(&mut app);
        assert_eq!(app.world.resource::<Font>().family(), Family::Neon);

        press(&mut app, FONT);
        assert_eq!(app.world.resource::<Font>().family(), Family::Neon.next());

        for _ in 1..Family::ALL.len() {
            press(&mut app, FONT);
        }
        assert_eq!(app.world.resource::<Font>().family(), Family::Neon);
    }

    #[test]
    fn f10_does_nothing_outside_dev_mode() {
        use crate::ui::{Family, Font};

        let mut app = app();
        press(&mut app, FONT);
        assert_eq!(app.world.resource::<Font>().family(), Family::Neon);
    }

    #[test]
    fn f9_puts_the_profiler_up_while_it_is_on() {
        let mut app = app();
        press(&mut app, PROFILER);
        assert!(!app.world.resource::<Profiler>().on, "not outside dev mode");

        press_f12(&mut app);
        press(&mut app, PROFILER);
        assert!(app.world.resource::<Profiler>().on);
        frame(&mut app);
    }

    #[test]
    fn nothing_happens_on_the_frames_between() {
        let mut app = app();
        press_f12(&mut app);

        frame(&mut app);
        frame(&mut app);
        assert!(app.world.resource::<DevMode>().is_on());
    }
}