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
use bevy_ecs::prelude::*;

use super::button::{ButtonColors, ButtonMarker, OnClick};
use super::color::{Color, linear_rgba};
use super::font;
use super::geometry::{
    Background, ButtonIcons, Icon, Label, LabelAlign, LabelSize, Position, Size, TextColor,
};
use super::heading::HeadingText;
use super::atlas::Atlas;
use super::font::Font;
use super::interaction::Interaction;
use super::layout::{self, LABEL_PIXEL_SIZE};
use super::outliner::OutlinerRow;
use super::panel::{Closed, ClosesPanel, Dragging, Movable, PanelChild, PanelMarker, TitleBar};
use super::progress::{OnFull, Progress};
use super::renderer2d::{NO_ICON, QuadInstance};
use super::rect::Rect;
use super::resources::{
    CursorPosition, MenuLayout, MouseInput, PointerCapture, ScreenSize, UiDrawList,
};
use super::text::TextLine;
use super::visibility::{Visibility, visible};
use crate::time::Time;

/// Repositions the menu's panel and buttons whenever [`ScreenSize`] changes,
/// so a window resize doesn't leave them laid out for the old size.
pub fn relayout_menu_system(
    screen: Res<ScreenSize>,
    menus: Query<&MenuLayout>,
    mut positions: Query<&mut Position>,
    mut sizes: Query<&mut Size>,
) {
    if !screen.is_changed() {
        return;
    }

    for menu in &menus {
        // The same sum `Panel::spawn` did, with the same offset and the same
        // room left for a title bar. Anything left out here is something that
        // moves the first time the window is resized and never moves back.
        let (panel_rect, button_rects) = layout::vertical_menu_offset(
            screen.width,
            screen.height,
            menu.buttons.len(),
            menu.anchor,
            menu.metrics,
            menu.offset,
        );
        let panel_rect = Rect::new(
            panel_rect.x,
            panel_rect.y,
            panel_rect.width,
            panel_rect.height + menu.bar_height,
        );

        let mut place = |entity: Entity, rect: Rect| {
            if let Ok(mut pos) = positions.get_mut(entity) {
                (pos.x, pos.y) = (rect.x, rect.y);
            }
            if let Ok(mut size) = sizes.get_mut(entity) {
                (size.width, size.height) = (rect.width, rect.height);
            }
        };
        place(menu.panel, panel_rect);

        if let Some(bar) = menu.bar {
            let rect = Rect::new(
                panel_rect.x,
                panel_rect.y,
                panel_rect.width,
                menu.bar_height,
            );
            place(bar, rect);
            if let Some(close) = menu.close {
                let side = menu.bar_height - layout::TITLE_INSET * 2.0;
                place(
                    close,
                    Rect::new(
                        rect.x + rect.width - side - layout::TITLE_INSET,
                        rect.y + layout::TITLE_INSET,
                        side,
                        side,
                    ),
                );
            }
        }

        for (&entity, rect) in menu.buttons.iter().zip(button_rects) {
            place(
                entity,
                Rect::new(rect.x, rect.y + menu.bar_height, rect.width, rect.height),
            );
        }
    }
}

/// Advances every self-filling progress bar (see [`Progress::fill_over`]).
pub fn advance_progress_system(time: Res<Time>, mut bars: Query<&mut Progress>) {
    for mut bar in &mut bars {
        if bar.fill_over.is_some() {
            bar.advance(time.delta);
        }
    }
}

/// Runs the callback on every bar that has just reached full.
pub fn dispatch_progress_full_system(mut bars: Query<(&Progress, &mut OnFull)>) {
    for (progress, mut on_full) in &mut bars {
        // Read before touching it mutably, so a bar sitting at full does not
        // report a change every frame.
        if progress.value >= 1.0 && on_full.is_armed() {
            on_full.fire();
        }
    }
}

/// Refreshes `hovered`/`pressed`/`clicked` on every button from the current
/// cursor position and mouse button state.
pub fn update_interaction_system(
    cursor: Res<CursorPosition>,
    mouse: Res<MouseInput>,
    mut buttons: Query<
        (&Position, &Size, &mut Interaction, Option<&Visibility>),
        With<ButtonMarker>,
    >,
) {
    for (pos, size, mut interaction, visibility) in &mut buttons {
        let hovered = visible(visibility) && pos.rect(size).contains(cursor.x, cursor.y);
        interaction.hovered = hovered;
        interaction.pressed = hovered && mouse.left_down;
        interaction.clicked = hovered && mouse.just_pressed;
    }
}

/// Works out whether the pointer is over any panel, for everything that has
/// to decide whether the mouse belongs to the UI or to the world.
///
/// Panels rather than buttons: the gaps between a menu's buttons are inside
/// the menu, and a wheel turned over one has not been turned over the world.
pub fn update_pointer_capture_system(
    cursor: Res<CursorPosition>,
    panels: Query<(&Position, &Size, Option<&Visibility>), With<PanelMarker>>,
    mut capture: ResMut<PointerCapture>,
) {
    capture.over_panel = panels.iter().any(|(pos, size, visibility)| {
        visible(visibility) && pos.rect(size).contains(cursor.x, cursor.y)
    });
}

/// Runs each clicked button's [`OnClick`] callback.
pub fn dispatch_clicks_system(mut buttons: Query<(&Interaction, &mut OnClick)>) {
    for (interaction, mut on_click) in &mut buttons {
        if interaction.clicked {
            (on_click.0)();
        }
    }
}

/// Marks a panel [`Closed`] when its close button is clicked.
///
/// The panel is marked rather than despawned: whatever put it up owns its
/// lifetime, and the outliner in particular rebuilds its own rows and would
/// rather be told it was closed than find itself gone.
pub fn dispatch_panel_close_system(
    buttons: Query<(&Interaction, &ClosesPanel)>,
    mut commands: Commands,
) {
    for (interaction, closes) in &buttons {
        if interaction.clicked {
            commands.entity(closes.0).insert(Closed);
        }
    }
}

/// Drags a movable panel around by its title bar.
///
/// The panel and everything it spawned move together, which is what
/// [`PanelChild`] is for: a panel has one level of contents and a list on the
/// panel would have to be kept in step with rows that are rebuilt from
/// scratch.
pub fn drag_panel_system(
    mouse: Res<MouseInput>,
    cursor: Res<CursorPosition>,
    movable: Query<(), With<Movable>>,
    dragging: Query<(Entity, &Dragging)>,
    children: Query<(Entity, &PanelChild)>,
    // A title bar has a `Position` of its own and moves with its panel, so
    // reading the bars and writing the positions are the same component and
    // have to take turns.
    mut rects: ParamSet<(Query<(&Position, &Size, &TitleBar)>, Query<&mut Position>)>,
    mut commands: Commands,
) {
    // A drag ends where the button comes up, wherever the pointer is: letting
    // go outside the bar is the ordinary way to stop.
    if !mouse.left_down {
        for (panel, _) in &dragging {
            commands.entity(panel).remove::<Dragging>();
        }
        return;
    }

    // Starting one, on the frame the button went down over a bar.
    if mouse.just_pressed && dragging.is_empty() {
        let grabbed = rects
            .p0()
            .iter()
            .find(|(pos, size, bar)| {
                pos.rect(size).contains(cursor.x, cursor.y) && movable.get(bar.panel).is_ok()
            })
            .map(|(_, _, bar)| bar.panel);
        if let Some(panel) = grabbed {
            if let Ok(origin) = rects.p1().get(panel) {
                commands.entity(panel).insert(Dragging {
                    from: (cursor.x, cursor.y),
                    origin: (origin.x, origin.y),
                });
            }
        }
        return;
    }

    for (panel, drag) in &dragging {
        let mut positions = rects.p1();
        let Ok(current) = positions.get(panel) else {
            continue;
        };
        // Against where the panel started rather than the last frame, so a
        // dropped frame cannot make the panel drift away from the pointer.
        let wanted = (
            drag.origin.0 + cursor.x - drag.from.0,
            drag.origin.1 + cursor.y - drag.from.1,
        );
        let by = (wanted.0 - current.x, wanted.1 - current.y);
        if by == (0.0, 0.0) {
            continue;
        }

        let moving: Vec<Entity> = std::iter::once(panel)
            .chain(
                children
                    .iter()
                    .filter(|(_, child)| child.0 == panel)
                    .map(|(entity, _)| entity),
            )
            .collect();
        for entity in moving {
            if let Ok(mut pos) = positions.get_mut(entity) {
                pos.x += by.0;
                pos.y += by.1;
            }
        }
    }
}

/// Clears the single-frame input edges, so a click — or a turn of the wheel —
/// is only ever observed once.
pub fn clear_input_edge_system(mut mouse: ResMut<MouseInput>) {
    mouse.just_pressed = false;
    mouse.just_released = false;
    mouse.scroll = 0.0;
}

/// Rebuilds the flat quad list ([`UiDrawList`]) from every panel, button,
/// heading, text line and progress bar this frame: panel backgrounds, button backgrounds (colored by
/// interaction state) and their bitmap-font labels.
pub fn collect_quads_system(
    screen: Res<ScreenSize>,
    headings: Query<&HeadingText>,
    lines: Query<&TextLine>,
    progress_bars: Query<&Progress>,
    panels: Query<(&Position, &Size, &Background, Option<&Visibility>), With<PanelMarker>>,
    bars: Query<(&Position, &Size, &Background), With<TitleBar>>,
    icons: Query<(&Position, &Size, &Icon, Option<&Visibility>)>,
    rows: Query<
        (
            &Position,
            &Size,
            &Label,
            Option<&LabelSize>,
            Option<&TextColor>,
        ),
        With<OutlinerRow>,
    >,
    titles: Query<(&Position, &Size, &Label, Option<&LabelSize>), With<TitleBar>>,
    mut atlas: ResMut<Atlas>,
    mut font: ResMut<Font>,
    buttons: Query<
        (
            &Position,
            &Size,
            &ButtonColors,
            &Label,
            &Interaction,
            Option<&TextColor>,
            Option<&LabelSize>,
            Option<&Visibility>,
            Option<&LabelAlign>,
            Option<&ButtonIcons>,
        ),
        With<ButtonMarker>,
    >,
    mut draw_list: ResMut<UiDrawList>,
) {
    // A new face means everything rasterised from the old one is wrong, and
    // the font has no way to reach the texture to say so itself.
    if font.take_changed() {
        atlas.forget_glyphs();
    }
    let face = font.face();

    let quads = &mut draw_list.0;
    quads.clear();

    for (pos, size, background, visibility) in &panels {
        if visible(visibility) {
            quads.push(colored_quad(pos, size, background.0));
        }
    }

    for (pos, size, background) in &bars {
        quads.push(colored_quad(pos, size, background.0));
    }

    // Icons after the panels they sit on and before the buttons, so a row's
    // background never covers its own icon.
    for (pos, size, icon, visibility) in &icons {
        if !visible(visibility) {
            continue;
        }
        let Some(uv) = atlas.icon(icon.path) else {
            continue;
        };
        quads.push(QuadInstance {
            pos: [pos.x, pos.y],
            size: [size.width, size.height],
            color: linear_rgba(icon.color),
            uv: [uv.min[0], uv.min[1], uv.max[0], uv.max[1]],
        });
    }

    for (pos, size, colors, label, interaction, text_color, label_size, visibility, align, icons) in
        &buttons
    {
        if !visible(visibility) {
            continue;
        }
        let color = colors.current(interaction.hovered, interaction.pressed);
        quads.push(colored_quad(pos, size, color));

        let text_color = text_color.map(|c| c.0).unwrap_or(Color::WHITE);
        let label_size = label_size.map(|size| size.0).unwrap_or(LABEL_PIXEL_SIZE);
        let label_width = font::text_width(&label.0, label_size);
        let label_height = font::text_height(label_size);

        // The icons either side, drawn square and centred on the row. The
        // scale is taken from the type rather than the row height so an icon
        // beside words is always the same size as the words.
        let icons = icons.copied().unwrap_or_default();
        let icon_side = (label_size / layout::MENU_LABEL_SIZE) * layout::MENU_ICON;
        let margin = (label_size / layout::MENU_LABEL_SIZE) * layout::MENU_ROW_MARGIN;
        let gap = (label_size / layout::MENU_LABEL_SIZE) * layout::MENU_ICON_GAP;
        let icon_y = pos.y + size.height * 0.5 - icon_side * 0.5;
        let mut icon_quad = |x: f32, path: &'static str, atlas: &mut Atlas| {
            if let Some(uv) = atlas.icon(path) {
                quads.push(QuadInstance {
                    pos: [x, icon_y],
                    size: [icon_side, icon_side],
                    color: linear_rgba(text_color),
                    uv: [uv.min[0], uv.min[1], uv.max[0], uv.max[1]],
                });
            }
        };
        if let Some(leading) = icons.leading {
            icon_quad(pos.x + margin, leading, atlas.as_mut());
        }
        if let Some(trailing) = icons.trailing {
            icon_quad(
                pos.x + size.width - margin - icon_side,
                trailing,
                atlas.as_mut(),
            );
        }

        // A button centres its label because a button is a target. A menu row
        // reads down its left edge, past whatever icon it wears.
        let label_x = match align.copied().unwrap_or_default() {
            LabelAlign::Center => pos.x + size.width * 0.5 - label_width * 0.5,
            LabelAlign::Left => {
                pos.x
                    + margin
                    + match icons.leading {
                        Some(_) => icon_side + gap,
                        None => 0.0,
                    }
            }
        };
        font::push_text(
            quads,
            atlas.as_mut(),
            face,
            &label.0,
            label_x,
            pos.y + size.height * 0.5 - label_height * 0.5,
            label_size,
            text_color,
        );
    }

    // A panel's title, left-aligned in its bar.
    for (pos, size, label, label_size) in &titles {
        let label_size = label_size
            .map(|size| size.0)
            .unwrap_or(layout::TITLE_LABEL_SIZE);
        let height = font::text_height(label_size);
        font::push_text(
            quads,
            atlas.as_mut(),
            face,
            &label.0,
            pos.x + layout::PANEL_PADDING * 2.0,
            pos.y + size.height * 0.5 - height * 0.5,
            label_size,
            Color::srgb(0.82, 0.82, 0.88),
        );
    }

    // A list row's name, left-aligned against its rect. A button centres its
    // label because a button is a target; a column of centred names is
    // unreadable, so a row does not.
    for (pos, size, label, label_size, text_color) in &rows {
        let label_size = label_size.map(|size| size.0).unwrap_or(LABEL_PIXEL_SIZE);
        let height = font::text_height(label_size);
        font::push_text(
            quads,
            atlas.as_mut(),
            face,
            &label.0,
            pos.x,
            pos.y + size.height * 0.5 - height * 0.5,
            label_size,
            text_color.map(|c| c.0).unwrap_or(Color::WHITE),
        );
    }

    for heading in &headings {
        let width = font::text_width(&heading.text, heading.pixel_size);
        let height = font::text_height(heading.pixel_size);
        font::push_text(
            quads,
            atlas.as_mut(),
            face,
            &heading.text,
            screen.width * heading.x_ratio - width * 0.5,
            screen.height * heading.y_ratio + heading.y_offset - height * 0.5,
            heading.pixel_size,
            heading.color,
        );
    }

    for line in &lines {
        font::push_text(
            quads,
            atlas.as_mut(),
            face,
            &line.text,
            line.x,
            line.y,
            line.pixel_size,
            line.color,
        );
    }

    for progress in &progress_bars {
        let width = screen.width * progress.width_ratio;
        let x = screen.width * 0.5 - width * 0.5;
        let y = screen.height * progress.y_ratio + progress.y_offset - progress.height * 0.5;
        quads.push(quad(x, y, width, progress.height, progress.track));

        let filled = progress.filled_width(width);
        if filled > 0.0 {
            quads.push(quad(
                x + progress.padding,
                y + progress.padding,
                filled,
                (progress.height - progress.padding * 2.0).max(0.0),
                progress.fill,
            ));
        }
    }
}

fn quad(x: f32, y: f32, width: f32, height: f32, color: Color) -> QuadInstance {
    QuadInstance {
        pos: [x, y],
        size: [width, height],
        color: linear_rgba(color),
        uv: NO_ICON,
    }
}

fn colored_quad(pos: &Position, size: &Size, color: Color) -> QuadInstance {
    QuadInstance {
        pos: [pos.x, pos.y],
        size: [size.width, size.height],
        color: linear_rgba(color),
        uv: NO_ICON,
    }
}