mittens-engine 0.7.0

A Vulkan and OpenXR scene engine with ECS, reactive signals, and Meow Meow scripting
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
use crate::engine::ecs::ComponentId;
use crate::engine::ecs::World;
use crate::engine::ecs::component::{
    ComponentRef, ForwardAxis, InputComponent, InputTransformModeComponent, QueryRootMode,
    RollAxis, TransformComponent, resolve_component_ref,
};
use crate::engine::ecs::system::System;
use crate::engine::graphics::VisualWorld;
use crate::engine::user_input::InputState;
use crate::utils::math;
use std::collections::HashMap;
use winit::event::MouseButton;
use winit::keyboard::{Key, NamedKey};

/// System that processes input components and updates transforms based on WASD input.
///
/// Intended topology (simple one-way data flow):
/// InputComponent -> TransformComponent -> (Camera2DComponent, RenderableComponent, ...)
#[derive(Debug, Default)]
pub struct InputSystem {
    inputs: Vec<ComponentId>,

    // FPS mode needs stable yaw/pitch/bank without per-frame extraction.
    // Keyed by the controlled TransformComponent id.
    fps_yaw_pitch_roll: HashMap<ComponentId, (f32, f32, f32)>,
}

impl InputSystem {
    pub fn new() -> Self {
        Self {
            inputs: Vec::new(),
            fps_yaw_pitch_roll: HashMap::new(),
        }
    }

    /// Register an InputComponent.
    pub fn register_input(&mut self, component: ComponentId) {
        if !self.inputs.iter().any(|c| *c == component) {
            self.inputs.push(component);
        }
    }

    fn compute_rotation(
        &self,
        roll_axis: RollAxis,
        input: &InputState,
        dt_sec: f32,
        rotation: &mut [f32; 4],
    ) {
        // Roll keys.
        let q = input.key_down(&Key::Character("q".into()));
        let e = input.key_down(&Key::Character("e".into()));

        // Right-button drag rotates the rig (yaw + pitch).
        let (drag_dx, drag_dy) = input.mouse_drag_delta_button(MouseButton::Right);

        // Sensitivity is radians per pixel.
        const MOUSE_SENS_RAD_PER_PX: f32 = 0.003;
        let yaw_delta = drag_dx * MOUSE_SENS_RAD_PER_PX;
        let pitch_delta = drag_dy * MOUSE_SENS_RAD_PER_PX;

        // Relative/flight-style semantics: apply local incremental rotations.
        if yaw_delta != 0.0 {
            let q_yaw = math::quat_from_axis_angle([0.0, 1.0, 0.0], yaw_delta);
            *rotation = math::quat_mul(*rotation, q_yaw);
        }
        if pitch_delta != 0.0 {
            let q_pitch = math::quat_from_axis_angle([1.0, 0.0, 0.0], pitch_delta);
            *rotation = math::quat_mul(*rotation, q_pitch);
        }

        if q || e {
            const ROT_SPEED_RAD_PER_SEC: f32 = 1.5;
            let dir = (q as i32) as f32 - (e as i32) as f32;
            let dtheta = dir * ROT_SPEED_RAD_PER_SEC * dt_sec;
            let axis = match roll_axis {
                RollAxis::X => [1.0, 0.0, 0.0],
                RollAxis::Y => [0.0, 1.0, 0.0],
                RollAxis::Z => [0.0, 0.0, 1.0],
            };
            let q_roll = math::quat_from_axis_angle(axis, dtheta);
            *rotation = math::quat_mul(*rotation, q_roll);
        }
    }

    fn compute_rotation_fps(
        &mut self,
        transform_cid: ComponentId,
        roll_axis: RollAxis,
        input: &InputState,
        dt_sec: f32,
        rotation: &mut [f32; 4],
    ) {
        // Roll keys.
        let q = input.key_down(&Key::Character("q".into()));
        let e = input.key_down(&Key::Character("e".into()));

        // Right-button drag rotates the rig (yaw + pitch).
        let (drag_dx, drag_dy) = input.mouse_drag_delta_button(MouseButton::Right);

        // Sensitivity is radians per pixel.
        const MOUSE_SENS_RAD_PER_PX: f32 = 0.003;
        let yaw_delta = drag_dx * MOUSE_SENS_RAD_PER_PX;
        let pitch_delta = drag_dy * MOUSE_SENS_RAD_PER_PX;

        // Allow Q/E rotation even without mouse drag.
        let qe_delta = if q || e {
            const ROT_SPEED_RAD_PER_SEC: f32 = 1.5;
            let dir = (q as i32) as f32 - (e as i32) as f32;
            dir * ROT_SPEED_RAD_PER_SEC * dt_sec
        } else {
            0.0
        };

        if yaw_delta == 0.0 && pitch_delta == 0.0 && qe_delta == 0.0 {
            return;
        }

        // Initialize once from current rotation.
        let (mut yaw, mut pitch, mut roll) = self
            .fps_yaw_pitch_roll
            .get(&transform_cid)
            .copied()
            .unwrap_or_else(|| {
                let right =
                    math::vec3_normalize(math::quat_rotate_vec3(*rotation, [1.0, 0.0, 0.0]));
                let fwd = math::vec3_normalize(math::quat_rotate_vec3(*rotation, [0.0, 0.0, -1.0]));

                // Yaw is global (world up): angle around +Y.
                let yaw = right[2].atan2(right[0]);
                // Pitch comes from forward Y.
                let pitch = fwd[1].clamp(-1.0, 1.0).asin();
                // Note: roll isn't extracted currently; it starts at 0 and is preserved
                // once the user rolls with Q/E.
                (yaw, pitch, 0.0)
            });

        // Apply deltas.
        yaw += yaw_delta;
        pitch += pitch_delta;

        // Q/E rotates around the configured axis.
        match roll_axis {
            RollAxis::Y => yaw += qe_delta,
            RollAxis::X => pitch += qe_delta,
            RollAxis::Z => roll += qe_delta,
        }

        const MAX_PITCH: f32 = 1.55; // ~88.8deg
        pitch = pitch.clamp(-MAX_PITCH, MAX_PITCH);

        // Persist state.
        self.fps_yaw_pitch_roll
            .insert(transform_cid, (yaw, pitch, roll));

        // Rebuild rotation from yaw/pitch/bank.
        // Yaw: global axis. Pitch: relative to yaw (around yaw-rotated right).
        // Bank (roll): around camera-forward axis.
        let q_yaw = math::quat_from_axis_angle([0.0, 1.0, 0.0], yaw);
        let right = math::quat_rotate_vec3(q_yaw, [1.0, 0.0, 0.0]);
        let q_pitch = math::quat_from_axis_angle(right, pitch);

        let q_base = math::quat_mul(q_pitch, q_yaw);
        let fwd_world = math::vec3_normalize(math::quat_rotate_vec3(q_base, [0.0, 0.0, -1.0]));
        let q_bank = math::quat_from_axis_angle(fwd_world, roll);

        *rotation = math::quat_mul(q_bank, q_base);
    }

    fn compute_translation(
        &self,
        forward_axis: ForwardAxis,
        fps_rotation: bool,
        fps_yaw: Option<f32>,
        speed_units_per_sec: f32,
        input: &InputState,
        dt_sec: f32,
        rotation: [f32; 4],
        translation: &mut [f32; 3],
    ) {
        // Read movement keys.
        let w = input.key_down(&Key::Character("w".into()));
        let a = input.key_down(&Key::Character("a".into()));
        let s = input.key_down(&Key::Character("s".into()));
        let d = input.key_down(&Key::Character("d".into()));
        let r: bool = input.key_down(&Key::Character("r".into()));
        let f: bool = input.key_down(&Key::Character("f".into()));

        // Holding Shift increases movement speed.
        let speed_multiplier = if input.key_down(&Key::Named(NamedKey::Shift)) {
            3.0
        } else {
            1.0
        };

        let speed = speed_units_per_sec * speed_multiplier * dt_sec;

        match forward_axis {
            ForwardAxis::Y => {
                // Legacy 2D-style translation delta (x/y).
                let mut dx = 0.0f32;
                let mut dy = 0.0f32;

                if w {
                    dy += 1.0;
                }
                if s {
                    dy -= 1.0;
                }
                if a {
                    dx -= 1.0;
                }
                if d {
                    dx += 1.0;
                }

                // Normalize diagonal movement.
                let len = (dx * dx + dy * dy).sqrt();
                if len > 0.0 {
                    dx /= len;
                    dy /= len;
                }

                // Translate in the transform's local (rotated) axes.
                let v = math::quat_rotate_vec3(rotation, [dx, dy, 0.0]);
                translation[0] += v[0] * speed;
                translation[1] += v[1] * speed;
            }

            ForwardAxis::Z => {
                let mut dx = 0.0f32;
                let mut dy: f32 = 0.0f32;
                let mut dz = 0.0f32;

                if a {
                    dx -= 1.0;
                }
                if d {
                    dx += 1.0;
                }
                if r {
                    dy += 1.0;
                }
                if f {
                    dy -= 1.0;
                }
                if w {
                    dz -= 1.0;
                }
                if s {
                    dz += 1.0;
                }

                // Normalize diagonal movement.
                let len = (dx * dx + dy * dy + dz * dz).sqrt();
                if len > 0.0 {
                    dx /= len;
                    dy /= len;
                    dz /= len;
                }

                if fps_rotation {
                    // FPS: yaw drives horizontal movement; pitch doesn't.
                    let yaw = fps_yaw.unwrap_or_else(|| {
                        let right = math::quat_rotate_vec3(rotation, [1.0, 0.0, 0.0]);
                        right[2].atan2(right[0])
                    });
                    let q_yaw = math::quat_from_axis_angle([0.0, 1.0, 0.0], yaw);
                    let v = math::quat_rotate_vec3(q_yaw, [dx, 0.0, dz]);
                    translation[0] += v[0] * speed;
                    translation[1] += dy * speed;
                    translation[2] += v[2] * speed;
                } else {
                    // Flight/relative: full rotation drives movement.
                    let v = math::quat_rotate_vec3(rotation, [dx, dy, dz]);
                    translation[0] += v[0] * speed;
                    translation[1] += v[1] * speed;
                    translation[2] += v[2] * speed;
                }
            }
        }
    }

    fn resolve_translation_basis_rotation(
        &self,
        world: &World,
        mode_component: Option<ComponentId>,
        source: Option<&ComponentRef>,
        fallback_rotation: [f32; 4],
    ) -> [f32; 4] {
        let Some(source) = source else {
            return fallback_rotation;
        };
        let Some(target) =
            resolve_component_ref(world, source, mode_component, QueryRootMode::SelfSubtree)
        else {
            return fallback_rotation;
        };
        self.nearest_transform_world_rotation(world, target)
            .unwrap_or(fallback_rotation)
    }

    fn nearest_transform_world_rotation(
        &self,
        world: &World,
        start: ComponentId,
    ) -> Option<[f32; 4]> {
        let mut current = Some(start);
        while let Some(component) = current {
            if let Some(transform) = world.get_component_by_id_as::<TransformComponent>(component) {
                return Some(math::mat_to_quat(transform.transform.matrix_world));
            }
            current = world.parent_of(component);
        }
        None
    }

    /// Process input and queue at most one transform update per InputComponent.
    ///
    /// This only supports the intended topology:
    /// InputComponent -> TransformComponent (child)
    pub fn process_input(
        &mut self,
        world: &mut World,
        input: &InputState,
        emit: &mut dyn crate::engine::ecs::SignalEmitter,
        dt_sec: f32,
    ) {
        // We gate early to avoid scanning inputs if nothing relevant is pressed.
        let any_move = input.key_down(&Key::Character("w".into()))
            || input.key_down(&Key::Character("a".into()))
            || input.key_down(&Key::Character("s".into()))
            || input.key_down(&Key::Character("d".into()))
            || input.key_down(&Key::Character("r".into()))
            || input.key_down(&Key::Character("f".into()))
            || input.key_down(&Key::Character("q".into()))
            || input.key_down(&Key::Character("e".into()));

        let any_drag = input.mouse_dragging_button(MouseButton::Right);

        if !any_move && !any_drag {
            return;
        }

        let inputs = self.inputs.clone();
        for input_cid in inputs {
            let speed_units_per_sec =
                match world.get_component_by_id_as::<InputComponent>(input_cid) {
                    Some(input_comp) => input_comp.speed,
                    None => continue,
                };

            // Find TransformComponent child. If absent, we don't compute.
            let transform_child = world.children_of(input_cid).iter().copied().find(|&cid| {
                world
                    .get_component_by_id_as::<TransformComponent>(cid)
                    .is_some()
            });

            // Optional mode child.
            let (
                mode_component,
                forward_axis,
                roll_axis,
                rotation_enabled,
                fps_rotation,
                translation_basis_source,
            ) = world
                .children_of(input_cid)
                .iter()
                .copied()
                .find_map(|cid| {
                    world
                        .get_component_by_id_as::<InputTransformModeComponent>(cid)
                        .map(|m| {
                            (
                                Some(cid),
                                m.forward_axis,
                                m.roll_axis,
                                m.rotation_enabled,
                                m.fps_rotation,
                                m.translation_basis_source.clone(),
                            )
                        })
                })
                .unwrap_or((None, ForwardAxis::Y, RollAxis::Z, true, false, None));

            let Some(transform_cid) = transform_child else {
                continue;
            };

            let external_basis_rotation = translation_basis_source.as_ref().map(|source| {
                self.resolve_translation_basis_rotation(
                    world,
                    mode_component,
                    Some(source),
                    [0.0, 0.0, 0.0, 1.0],
                )
            });

            if let Some(transform_comp_mut) =
                world.get_component_by_id_as_mut::<TransformComponent>(transform_cid)
            {
                if rotation_enabled && fps_rotation {
                    self.compute_rotation_fps(
                        transform_cid,
                        roll_axis,
                        input,
                        dt_sec,
                        &mut transform_comp_mut.transform.rotation,
                    );
                } else if rotation_enabled {
                    self.compute_rotation(
                        roll_axis,
                        input,
                        dt_sec,
                        &mut transform_comp_mut.transform.rotation,
                    );
                }
                let fps_yaw = if fps_rotation {
                    self.fps_yaw_pitch_roll
                        .get(&transform_cid)
                        .map(|(y, _, _)| *y)
                } else {
                    None
                };
                let translation_basis_rotation =
                    external_basis_rotation.unwrap_or(transform_comp_mut.transform.rotation);
                self.compute_translation(
                    forward_axis,
                    fps_rotation,
                    fps_yaw,
                    speed_units_per_sec,
                    input,
                    dt_sec,
                    translation_basis_rotation,
                    &mut transform_comp_mut.transform.translation,
                );

                transform_comp_mut.transform.recompute_model();
                emit.push_intent_now(
                    transform_cid,
                    crate::engine::ecs::IntentValue::UpdateTransform {
                        component_id: transform_cid,
                        translation: transform_comp_mut.transform.translation,
                        rotation_quat_xyzw: transform_comp_mut.transform.rotation,
                        scale: transform_comp_mut.transform.scale,
                    },
                );
            }
        }
    }
}

impl System for InputSystem {
    fn tick(
        &mut self,
        _world: &mut World,
        _visuals: &mut VisualWorld,
        _input: &InputState,
        _dt_sec: f32,
    ) {
        // InputSystem is driven by SystemWorld::tick calling process_input with a CommandQueue.
    }
}