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
//! A readout of what the controller is sending, on a panel in the corner.
//!
//! [`ps::State::render`] already prints this to a log, which is no use while
//! you are holding the pad and looking at the window. Same numbers, drawn on
//! screen instead — and rewritten in place every frame, which is why the
//! lines are [`TextLine`]s at fixed positions rather than centred headings
//! that would shuffle sideways as the readout grew a word.
use bevy_ecs::prelude::*;
use bevy_ecs::schedule::IntoScheduleConfigs;

use super::{GamepadState, ps};
use crate::ecs::{Application, Plugin};
use crate::scene::SceneEntity;
use crate::ui::{
    Background, Color, PanelMarker, Position, Size, Text, TextLine, Widget, font, layout,
};

/// How wide the readout is, in characters. The panel is sized from this, and
/// the list of held buttons is wrapped to it.
const COLUMNS: usize = 30;

/// The fixed lines, before the held buttons: model and battery, the two
/// sticks, the triggers and hat, the touchpad, and the same sticks as the
/// game sees them.
const FIXED_LINES: usize = 6;

/// Room for every button the pad has, at this width.
const HELD_LINES: usize = 3;

const LINES: usize = FIXED_LINES + HELD_LINES;

/// Marks one line of the readout, so the update system knows which is which.
#[derive(Component, Clone, Copy, Debug)]
pub struct HidDebugLine(pub usize);

/// The controller readout: a panel of text showing sticks, triggers, battery
/// and whatever is held.
///
/// ```no_run
/// # use codecraft::{AppState, hid::HIDDebugOverlay};
/// # fn demo(app: &mut AppState) {
/// app.spawn(HIDDebugOverlay::new());
/// # }
/// ```
///
/// It reads [`GamepadState`], which the host app republishes every frame, so
/// there is nothing to poll and nothing to keep alive: spawn it in a scene
/// that wants it and it goes away with that scene.
pub struct HIDDebugOverlay {
    x: f32,
    y: f32,
    pixel_size: f32,
    color: Color,
    background: Color,
}

impl Default for HIDDebugOverlay {
    fn default() -> Self {
        Self {
            x: layout::SCREEN_MARGIN,
            y: layout::SCREEN_MARGIN,
            pixel_size: 2.0,
            color: Color::srgb(0.85, 0.88, 0.95),
            background: Color::srgba(0.06, 0.06, 0.09, 0.80),
        }
    }
}

impl HIDDebugOverlay {
    pub fn new() -> Self {
        Self::default()
    }

    /// Top-left corner of the panel, in pixels.
    pub fn at(mut self, x: f32, y: f32) -> Self {
        self.x = x;
        self.y = y;
        self
    }

    /// Size of one bitmap-font pixel; the whole panel scales with it.
    pub fn pixel_size(mut self, pixel_size: f32) -> Self {
        self.pixel_size = pixel_size;
        self
    }

    pub fn color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub fn background(mut self, color: Color) -> Self {
        self.background = color;
        self
    }

    fn padding(&self) -> f32 {
        self.pixel_size * 4.0
    }

    fn line_height(&self) -> f32 {
        font::text_height(self.pixel_size) + self.pixel_size * 3.0
    }
}

/// The panel and its lines, for a scene that wants to take the overlay down
/// again without ending the scene.
#[derive(Component, Clone, Debug)]
pub struct HidOverlay {
    pub panel: Entity,
    pub lines: Vec<Entity>,
}

impl HidOverlay {
    pub fn entities(&self) -> impl Iterator<Item = Entity> + '_ {
        std::iter::once(self.panel).chain(self.lines.iter().copied())
    }
}

impl Widget for HIDDebugOverlay {
    type Output = HidOverlay;

    fn spawn(self, world: &mut World, _screen_width: f32, _screen_height: f32) -> HidOverlay {
        let padding = self.padding();
        let line_height = self.line_height();
        // Sized for the widest line it could ever hold rather than for what
        // is in it now, so the panel does not breathe as the pad is used.
        let width = font::text_width(&"M".repeat(COLUMNS), self.pixel_size) + padding * 2.0;
        let height = line_height * LINES as f32 + padding * 2.0;

        let panel = world
            .spawn((
                Position {
                    x: self.x,
                    y: self.y,
                },
                Size { width, height },
                Background(self.background),
                PanelMarker,
                SceneEntity,
                Name::new("HIDDebugOverlay"),
            ))
            .id();

        let lines = (0..LINES)
            .map(|index| {
                let entity = Text::at(
                    self.x + padding,
                    self.y + padding + line_height * index as f32,
                    "",
                )
                .pixel_size(self.pixel_size)
                .color(self.color)
                .spawn(world, 0.0, 0.0);
                world.entity_mut(entity).insert(HidDebugLine(index));
                entity
            })
            .collect::<Vec<_>>();

        let overlay = HidOverlay { panel, lines };
        world.entity_mut(panel).insert(overlay.clone());
        overlay
    }
}

/// Rewrites the readout from this frame's [`GamepadState`].
pub fn update_hid_overlay_system(
    pad: Res<GamepadState>,
    mut lines: Query<(&HidDebugLine, &mut TextLine)>,
) {
    let text = readout(&pad);
    for (line, mut target) in &mut lines {
        let wanted = text.get(line.0).map(String::as_str).unwrap_or("");
        // Compared before writing: change detection is per-component, and a
        // readout that is rewritten every frame is one that reports a change
        // every frame.
        if target.text != wanted {
            target.text.clear();
            target.text.push_str(wanted);
        }
    }
}

/// The whole readout, one string per line.
///
/// The bitmap font has no brackets or percent sign, so this is spelled out in
/// the characters it does have rather than borrowing
/// [`ps::State::render`]'s layout.
fn readout(pad: &GamepadState) -> Vec<String> {
    let mut lines = Vec::with_capacity(LINES);

    let mut header = format!("PAD:{}", pad.name());
    if let Some(battery) = pad.state.battery.filter(|_| pad.connected) {
        let charge = match battery.charge {
            ps::Charge::Discharging => "",
            ps::Charge::Charging => " CHG",
            ps::Charge::Full => " FULL",
            ps::Charge::Error => " ERR",
        };
        header.push_str(&format!(" BATT:{}{}", battery.percent, charge));
    }
    lines.push(header);

    if !pad.connected {
        // Nothing to say, but the lines still exist: they are entities, and
        // clearing them is what makes the panel empty rather than stale.
        lines.resize(LINES, String::new());
        return lines;
    }

    let state = &pad.state;
    lines.push(format!(
        "LX:{:3} LY:{:3} RX:{:3} RY:{:3}",
        state.lx, state.ly, state.rx, state.ry
    ));
    lines.push(format!(
        "L2:{:3} R2:{:3} DPAD:{}",
        state.l2,
        state.r2,
        state.dpad_name()
    ));

    // Fixed-width, and both slots, so a second finger landing does not shove
    // the first one's numbers along the line.
    let touch = state
        .touch
        .iter()
        .flatten()
        .map(|touch| format!("{:04},{:04}", touch.x, touch.y))
        .collect::<Vec<_>>();
    lines.push(match touch.is_empty() {
        true => "TOUCH:-".to_string(),
        false => format!("TOUCH:{}", touch.join(" ")),
    });

    let (move_axis, look_axis) = (state.move_axis(), state.look_axis());
    lines.push(format!(
        "MOVE:{:+.2},{:+.2} LIFT:{:+.2}",
        move_axis.x,
        move_axis.y,
        state.lift()
    ));
    lines.push(format!("LOOK:{:+.2},{:+.2}", look_axis.x, look_axis.y));

    let held = ps::button::NAMES
        .iter()
        .filter(|(mask, _)| state.held(*mask))
        .map(|(_, name)| *name)
        .collect::<Vec<_>>();
    lines.extend(wrap(&held, COLUMNS - "HELD:".len(), "HELD:", HELD_LINES));

    lines.resize(LINES, String::new());
    lines
}

/// Lays `names` out over at most `limit` lines of `columns` characters, with
/// `prefix` on the first and blanks under it on the rest.
///
/// Every button held at once does not fit on one line at this width, and a
/// line that runs off the panel is worse than one that wraps.
fn wrap(names: &[&str], columns: usize, prefix: &str, limit: usize) -> Vec<String> {
    let indent = " ".repeat(prefix.len());
    let mut lines: Vec<String> = Vec::new();
    let mut current = String::new();

    for name in names {
        let needed = if current.is_empty() {
            name.len()
        } else {
            current.len() + 1 + name.len()
        };
        if needed > columns && !current.is_empty() {
            lines.push(std::mem::take(&mut current));
            if lines.len() == limit {
                break;
            }
        }
        if !current.is_empty() {
            current.push(' ');
        }
        current.push_str(name);
    }
    if lines.len() < limit && !current.is_empty() {
        lines.push(current);
    }
    if lines.is_empty() {
        lines.push("-".to_string());
    }

    lines
        .into_iter()
        .enumerate()
        .map(|(i, line)| {
            if i == 0 {
                format!("{prefix}{line}")
            } else {
                format!("{indent}{line}")
            }
        })
        .collect()
}

/// Registers the readout's per-frame update.
pub struct HidPlugin;

impl Plugin for HidPlugin {
    fn build(&self, app: &mut Application) {
        app.insert_resource(GamepadState::default());
        // The readout has to be rewritten before the frame's quads are
        // gathered from it, or the panel is always a frame behind.
        app.add_update_systems(
            update_hid_overlay_system.before(crate::ui::systems::collect_quads_system),
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn connected(state: ps::State) -> GamepadState {
        GamepadState {
            connected: true,
            model: Some(ps::Model::DualSense),
            state,
        }
    }

    #[test]
    fn there_is_one_string_per_line_whatever_is_held() {
        assert_eq!(readout(&GamepadState::default()).len(), LINES);
        assert_eq!(readout(&connected(ps::State::default())).len(), LINES);

        let everything = ps::State {
            buttons: u32::MAX,
            ..ps::State::default()
        };
        assert_eq!(readout(&connected(everything)).len(), LINES);
    }

    #[test]
    fn an_absent_pad_says_so_and_leaves_the_rest_blank() {
        let lines = readout(&GamepadState::default());
        assert_eq!(lines[0], "PAD:NOT CONNECTED");
        assert!(lines[1..].iter().all(String::is_empty), "{lines:?}");
    }

    #[test]
    fn what_is_held_is_named() {
        let state = ps::State {
            buttons: ps::button::CROSS | ps::button::L1,
            ..ps::State::default()
        };
        let lines = readout(&connected(state));
        assert_eq!(lines[FIXED_LINES], "HELD:X L1");

        let lines = readout(&connected(ps::State::default()));
        assert_eq!(lines[FIXED_LINES], "HELD:-", "nothing held still reads");
    }

    #[test]
    fn the_touchpad_shows_both_fingers_and_says_so_when_there_are_none() {
        let lines = readout(&connected(ps::State::default()));
        assert_eq!(lines[3], "TOUCH:-");

        let one = ps::State {
            touch: [
                Some(ps::Touch {
                    id: 1,
                    x: 12,
                    y: 340,
                }),
                None,
            ],
            ..ps::State::default()
        };
        assert_eq!(readout(&connected(one))[3], "TOUCH:0012,0340");
    }

    #[test]
    fn nothing_ever_runs_off_the_panel() {
        let everything = ps::State {
            buttons: u32::MAX,
            lx: 255,
            ly: 255,
            rx: 255,
            ry: 255,
            l2: 255,
            r2: 255,
            dpad: 1,
            battery: Some(ps::Battery {
                percent: 100,
                charge: ps::Charge::Full,
            }),
            touch: [
                Some(ps::Touch {
                    id: 1,
                    x: 1919,
                    y: 1079,
                }),
                Some(ps::Touch {
                    id: 2,
                    x: 1919,
                    y: 1079,
                }),
            ],
        };
        for line in readout(&connected(everything)) {
            assert!(line.len() <= COLUMNS, "{} chars: {line:?}", line.len());
        }
    }

    #[test]
    fn a_wrapped_list_keeps_every_name_and_lines_up_under_the_prefix() {
        let names = ["AAAA", "BBBB", "CCCC"];
        let lines = wrap(&names, 9, "HELD:", 3);
        assert_eq!(
            lines,
            vec!["HELD:AAAA BBBB".to_string(), "     CCCC".to_string()]
        );
    }
}