concinnity-engine 0.19.0

Runtime engine for Concinnity: ECS schedule, graphics, spawn, streaming
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
// src/gfx/camera_controller.rs
//
// First-person / fly-through camera controller. An internal system (not a
// declarable asset): `World::start` constructs one when the world has a
// `Camera3D` whose `controller` is set, reading that controller's config. It
// turns mouse/keyboard input into a `Camera3D` orientation and a movement
// intent for the player's `RigidBody`.

use crate::components::{Camera3D, CameraController, FrameInput, Interactable, Transform};
use crate::ecs::{Entity, PipelineContext, StepResult, System};
use std::time::Instant;

// Reach distance for interacting with a Prop, in world units.
const INTERACT_REACH: f32 = 3.0;
// Minimum facing dot product (~60-degree cone) for an interaction.
const INTERACT_MIN_DOT: f32 = 0.5;

/// First-person / fly-through controller behavior. Constructed internally by
/// `World::start` from the controlling `Camera3D`'s `CameraController`;
/// never a world-declared asset.
#[derive(Debug)]
pub struct Camera3DSystem {
    free_fly: bool,
    move_speed: f32,
    sprint_multiplier: f32,
    mouse_sensitivity: f32,
    // Gamepad look speed in radians per second at full stick deflection
    // (rate-based, unlike the per-pixel mouse sensitivity).
    gamepad_look_sensitivity: f32,
    player_radius: f32,
    bounds_min: [f32; 3],
    bounds_max: [f32; 3],
    last_step: Option<Instant>,
    // smoothed horizontal velocity; lerped toward the target each tick so
    // WASD movement accelerates and decelerates instead of snapping
    velocity: [f32; 3],
    // Interactable entities (those carrying the Interactable tag), collected at
    // init so step() rotates only their Transforms on interact.
    interactable_entities: Vec<Entity>,
    // Cursor into the Events<ControlsCommand> queue (live settings changes).
    controls_cursor: crate::ecs::EventCursor,
}

impl Camera3DSystem {
    // Build a controller from a `Camera3D`'s controller settings.
    pub(crate) fn new(c: CameraController) -> Self {
        Self {
            free_fly: c.free_fly,
            move_speed: c.move_speed,
            sprint_multiplier: c.sprint_multiplier,
            mouse_sensitivity: c.mouse_sensitivity,
            gamepad_look_sensitivity: crate::gfx::settings::DEFAULT_GAMEPAD_LOOK_SENSITIVITY,
            player_radius: c.player_radius,
            bounds_min: c.bounds_min,
            bounds_max: c.bounds_max,
            last_step: None,
            velocity: [0.0; 3],
            interactable_entities: Vec::new(),
            controls_cursor: crate::ecs::EventCursor::default(),
        }
    }

    /// Zero the smoothed movement velocity. Called when an external source (the
    /// cn debug `camera-set` command) teleports the camera, so free-fly velocity
    /// integration does not drift the new pose on the next step. Only reached
    /// from the binary-only debug drive, hence dead in a `--lib` build.
    pub fn reset_velocity(&mut self) {
        self.velocity = [0.0; 3];
    }
}

impl System for Camera3DSystem {
    fn access(&self) -> crate::ecs::Access {
        crate::ecs::Access::new()
            .reads_components(crate::component_mask![crate::components::FrameInput])
            .writes_components(crate::component_mask![
                crate::components::Camera3D,
                crate::components::Transform,
            ])
            .reads_resources(crate::resource_mask![
                crate::ecs::decompose::EntityByName,
                crate::components::ControlsCommand,
            ])
            .writes_resources(crate::resource_mask![crate::components::InteractEvent])
    }

    fn init(&mut self, ctx: &mut PipelineContext) {
        self.last_step = Some(Instant::now());

        crate::gfx::look_controls::apply_persisted(
            ctx,
            crate::gfx::look_controls::Look {
                mouse_sensitivity: &mut self.mouse_sensitivity,
                gamepad_look_sensitivity: &mut self.gamepad_look_sensitivity,
            },
        );

        // Collect interact targets: every entity carrying the Interactable tag.
        self.interactable_entities = ctx
            .query_with_entity::<Interactable>()
            .map(|(entity, _)| entity)
            .collect();

        let registered = self.interactable_entities.len();
        if registered > 0 {
            tracing::debug!(
                "Camera3DSystem: registered {} interactable prop(s)",
                registered
            );
        }
    }

    fn step(&mut self, ctx: &mut PipelineContext) -> StepResult {
        // Live settings-menu changes sent this tick by GraphicsSystem, which runs
        // first. FOV is written in the camera loop below, which holds the
        // mutable Camera3D borrow.
        let pending_fov = crate::gfx::look_controls::drain_commands(
            ctx,
            &mut self.controls_cursor,
            crate::gfx::look_controls::Look {
                mouse_sensitivity: &mut self.mouse_sensitivity,
                gamepad_look_sensitivity: &mut self.gamepad_look_sensitivity,
            },
        );

        // Read (not drain) the input snapshot deposited by GraphicsSystem this
        // frame, so UiInputSystem can read the same snapshot (e.g. for a pause
        // menu over this camera). GraphicsSystem clears it before the next push.
        let input = match ctx.query::<FrameInput>().next().cloned() {
            Some(i) => i,
            // no input means GraphicsSystem hasn't run yet or there is no
            // graphics backend -- nothing to do this tick
            None => return StepResult::Continue,
        };

        let now = Instant::now();
        let dt = self
            .last_step
            .map(|t| now.duration_since(t).as_secs_f32().min(0.1))
            .unwrap_or(0.0);
        self.last_step = Some(now);

        // update every Camera3D in the world (normally exactly one)
        for camera in ctx.query_mut::<Camera3D>() {
            // A live FOV change (settings-menu slider) applies to the camera's
            // projection on the next rendered frame.
            if let Some(fov) = pending_fov {
                camera.fov_y_degrees = fov;
            }
            // Look: pixel-based mouse deltas plus the rate-based right stick
            // (deflection x radians/second x dt, so it is frame-rate correct).
            let look_dx = input.mouse_dx * self.mouse_sensitivity
                + input.look_axis[0] * self.gamepad_look_sensitivity * dt;
            let look_dy = input.mouse_dy * self.mouse_sensitivity
                + input.look_axis[1] * self.gamepad_look_sensitivity * dt;
            camera.yaw -= look_dx;
            camera.pitch = (camera.pitch - look_dy).clamp(
                -std::f32::consts::FRAC_PI_2 + 0.01,
                std::f32::consts::FRAC_PI_2 - 0.01,
            );

            let speed = if input.sprint {
                self.move_speed * self.sprint_multiplier
            } else {
                self.move_speed
            };

            // Two movement modes share the same input/decay/screen-matrix
            // outer loop; only the basis vectors and how velocity is
            // committed differ. Free-fly drives the camera position
            // directly and adds a vertical component; the FPS walker keeps
            // motion horizontal and delegates to PhysicsSystem.
            let (fwd, right) = if self.free_fly {
                let cp = camera.pitch.cos();
                (
                    [
                        -camera.yaw.sin() * cp,
                        camera.pitch.sin(),
                        -camera.yaw.cos() * cp,
                    ],
                    [camera.yaw.cos(), 0.0_f32, -camera.yaw.sin()],
                )
            } else {
                (
                    [-camera.yaw.sin(), 0.0_f32, -camera.yaw.cos()],
                    [camera.yaw.cos(), 0.0_f32, -camera.yaw.sin()],
                )
            };

            // build the target velocity from current key state
            let mut target = [0.0_f32; 3];
            if input.forward {
                target[0] += fwd[0] * speed;
                target[1] += fwd[1] * speed;
                target[2] += fwd[2] * speed;
            }
            if input.backward {
                target[0] -= fwd[0] * speed;
                target[1] -= fwd[1] * speed;
                target[2] -= fwd[2] * speed;
            }
            if input.right {
                target[0] += right[0] * speed;
                target[2] += right[2] * speed;
            }
            if input.left {
                target[0] -= right[0] * speed;
                target[2] -= right[2] * speed;
            }
            // The left stick rides the same bases: partial deflection walks
            // proportionally slower (the axis magnitude is at most 1).
            target[0] += (fwd[0] * input.move_axis[1] + right[0] * input.move_axis[0]) * speed;
            target[1] += fwd[1] * input.move_axis[1] * speed;
            target[2] += (fwd[2] * input.move_axis[1] + right[2] * input.move_axis[0]) * speed;
            // Free-fly: jump is "rise"; no down key, descend by pitching down + W.
            if self.free_fly && input.jump {
                target[1] += speed;
            }

            // exponential decay toward target -- time-correct so frame rate does not
            // affect the feel. half_life controls how quickly speed builds/drops.
            let half_life = 0.08_f32; // seconds to reach ~50% of target speed
            let decay = 1.0 - 2.0_f32.powf(-dt / half_life);
            self.velocity[0] += (target[0] - self.velocity[0]) * decay;
            self.velocity[1] += (target[1] - self.velocity[1]) * decay;
            self.velocity[2] += (target[2] - self.velocity[2]) * decay;

            if self.free_fly {
                // Apply directly; no PhysicsSystem, no bounds, no gravity.
                camera.position[0] += self.velocity[0] * dt;
                camera.position[1] += self.velocity[1] * dt;
                camera.position[2] += self.velocity[2] * dt;
                camera.desired_move = [0.0; 3];
                camera.jump_requested = false;
            } else {
                // soft containment: pull the camera back inside the bounds box.
                // PhysicsSystem owns the position, so this is a one-frame-lagged
                // correction applied before it runs.
                let r = self.player_radius;
                camera.position[0] =
                    camera.position[0].clamp(self.bounds_min[0] + r, self.bounds_max[0] - r);
                camera.position[2] =
                    camera.position[2].clamp(self.bounds_min[2] + r, self.bounds_max[2] - r);

                // hand the movement intent to PhysicsSystem, which resolves it
                // against the world and writes the final camera position back
                camera.desired_move = self.velocity;
                camera.jump_requested = input.jump;
            }
            camera.interact_requested = input.interact;

            // write the view matrix as a fallback for worlds with no
            // PhysicsSystem; PhysicsSystem overwrites it once it has moved.
            camera.view_matrix =
                crate::gfx::camera::view_matrix(camera.position, camera.yaw, camera.pitch);
        }

        // interactable props: press the interact key while facing one to rotate
        // it 45 degrees. Pickup/drop is handled by PhysicsSystem. The target
        // rotation lives on the entity's Transform.
        if input.interact && !self.interactable_entities.is_empty() {
            let (cam_pos, cam_yaw) = ctx
                .query::<Camera3D>()
                .next()
                .map(|c| (c.position, c.yaw))
                .unwrap_or(([0.0; 3], 0.0));
            let fwd = [-cam_yaw.sin(), 0.0_f32, -cam_yaw.cos()];

            // nearest interactable entity within reach the player faces
            let mut best: Option<(f32, Entity)> = None;
            for &entity in &self.interactable_entities {
                if let Some(t) = ctx.get::<Transform>(entity) {
                    let dx = t.position[0] - cam_pos[0];
                    let dz = t.position[2] - cam_pos[2];
                    let dist = (dx * dx + dz * dz).sqrt();
                    if dist < INTERACT_REACH && dist > 0.0 {
                        let dot = (fwd[0] * dx + fwd[2] * dz) / dist;
                        if dot > INTERACT_MIN_DOT && best.is_none_or(|(d, _)| dist < d) {
                            best = Some((dist, entity));
                        }
                    }
                }
            }
            if let Some((_, entity)) = best {
                if let Some(t) = ctx.get_mut::<Transform>(entity) {
                    t.rotation_deg[1] = (t.rotation_deg[1] + 45.0) % 360.0;
                    tracing::info!(
                        "interacted with prop, yaw now {:.0}\u{00b0}",
                        t.rotation_deg[1]
                    );
                }
                // Announce the press for declarative logic (Behavior interact
                // sources); an unnamed entity has no addressable identity to
                // announce.
                let target = ctx
                    .resource::<crate::ecs::decompose::EntityByName>()
                    .and_then(|n| {
                        n.0.iter()
                            .find(|(_, e)| **e == entity)
                            .map(|(&name, _)| name)
                    });
                if let Some(target) = target {
                    ctx.events_mut::<crate::components::InteractEvent>()
                        .send(crate::components::InteractEvent { target });
                }
            }
        }

        StepResult::Continue
    }
}

#[cfg(test)]
mod tests {
    use crate::components::{Camera3D, CameraController};
    use crate::ecs::SYSTEMS;
    use crate::ecs::World;

    fn camera(controller: Option<CameraController>) -> Camera3D {
        Camera3D {
            fov_y_degrees: 75.0,
            near: 0.05,
            far: 200.0,
            view_matrix: [[0.0; 4]; 4],
            position: [0.0; 3],
            yaw: 0.0,
            pitch: 0.0,
            desired_move: [0.0; 3],
            jump_requested: false,
            interact_requested: false,
            controller,
        }
    }

    // A Camera3D whose `controller` is set spawns the internal controller.
    #[test]
    fn controlled_camera_spawns_internal_system() {
        let mut world = World::new();
        world.add_component(camera(Some(CameraController::default())));
        world.start(SYSTEMS).unwrap();

        let names: Vec<&str> = world.systems().iter().map(|s| s.name()).collect();
        assert_eq!(names, ["Camera3DSystem"]);
    }

    // `controller: null` opts out: a cutscene camera gets no controller.
    #[test]
    fn uncontrolled_camera_has_no_system() {
        let mut world = World::new();
        world.add_component(camera(None));
        world.start(SYSTEMS).unwrap();
        assert!(world.systems().is_empty());
    }

    // A ControlsCommand pushed mid-tick updates the live mouse sensitivity, so
    // the same frame's mouse-look uses the new value (not the init-time one).
    // This is the settings-menu sensitivity slider applying without a restart.
    #[test]
    fn controls_command_updates_sensitivity_live() {
        use crate::components::{ControlsCommand, FrameInput};

        let mut world = World::new();
        // Free-fly avoids the PhysicsSystem path; start from a known sensitivity.
        let ctrl = CameraController {
            free_fly: true,
            mouse_sensitivity: 0.001,
            ..CameraController::default()
        };
        world.add_component(camera(Some(ctrl)));
        world.start(SYSTEMS).unwrap();

        // GraphicsSystem would send this when the slider is dragged; the camera
        // reads it this tick. A mouse delta in the same frame must rotate by the
        // NEW sensitivity (0.005), not the controller's 0.001.
        world.events_mut::<ControlsCommand>().send(ControlsCommand {
            mouse_sensitivity: Some(0.005),
            ..Default::default()
        });
        world.add_component(FrameInput {
            mouse_dx: 10.0,
            ..Default::default()
        });
        world.step();

        let yaw = world.query::<Camera3D>().next().map(|c| c.yaw).unwrap();
        assert!(
            (yaw - (-10.0 * 0.005)).abs() < 1.0e-6,
            "yaw {yaw} should reflect the live sensitivity 0.005"
        );
    }

    // A ControlsCommand carrying a new FOV updates the Camera3D's fov_y_degrees
    // live (the projection is rebuilt from it each frame), and an event with
    // fov_y_degrees: None leaves the FOV untouched. This is the settings-menu FOV
    // slider applying without a restart.
    #[test]
    fn controls_command_updates_fov_live() {
        use crate::components::{ControlsCommand, FrameInput};

        let mut world = World::new();
        let ctrl = CameraController {
            free_fly: true,
            ..CameraController::default()
        };
        world.add_component(camera(Some(ctrl)));
        world.start(SYSTEMS).unwrap();

        // The camera starts at the authored 75 degrees.
        let fov0 = world
            .query::<Camera3D>()
            .next()
            .map(|c| c.fov_y_degrees)
            .unwrap();
        assert!((fov0 - 75.0).abs() < 1.0e-6);

        // A FOV-only command applies this tick; a sensitivity-only command does
        // not disturb the FOV.
        world.events_mut::<ControlsCommand>().send(ControlsCommand {
            fov_y_degrees: Some(90.0),
            ..Default::default()
        });
        world.add_component(FrameInput::default());
        world.step();
        let fov1 = world
            .query::<Camera3D>()
            .next()
            .map(|c| c.fov_y_degrees)
            .unwrap();
        assert!(
            (fov1 - 90.0).abs() < 1.0e-6,
            "fov {fov1} should reflect the live FOV 90"
        );

        world.events_mut::<ControlsCommand>().send(ControlsCommand {
            mouse_sensitivity: Some(0.004),
            ..Default::default()
        });
        world.step();
        let fov2 = world
            .query::<Camera3D>()
            .next()
            .map(|c| c.fov_y_degrees)
            .unwrap();
        assert!(
            (fov2 - 90.0).abs() < 1.0e-6,
            "fov {fov2} should be unchanged by a sensitivity-only command"
        );
    }

    // With both a controlled camera and a UiInputSystem (Screen + KeyBinding),
    // both systems read the same per-frame FrameInput: Camera3DSystem runs
    // first but no longer consumes it, so UiInputSystem still receives Escape
    // and toggles the menu. (Regression: Camera3DSystem drained the input,
    // starving the menu, so Escape did nothing over a captured camera.)
    #[test]
    fn camera_and_ui_share_frame_input() {
        use crate::components::{FrameInput, KeyBinding, Screen, ScreenCommand};
        use crate::ecs::asset_id::AssetId;

        let mut world = World::new();
        world.add_component(camera(Some(CameraController::default())));
        world.add_component(Screen {
            asset_id: AssetId(50),
            initial: false,
            fade_in_secs: 0.0,
            ..Default::default()
        });
        world.add_component(KeyBinding {
            key: "Escape".to_string(),
            action: "screen:toggle:50".to_string(),
            ..Default::default()
        });
        world.start(SYSTEMS).unwrap();

        let names: Vec<&str> = world.systems().iter().map(|s| s.name()).collect();
        assert!(names.contains(&"Camera3DSystem"));
        assert!(names.contains(&"UiInputSystem"));

        world.add_component(FrameInput {
            escape: true,
            ..Default::default()
        });
        world.step();

        let mut cursor = crate::ecs::EventCursor::default();
        let cmd = world
            .events::<ScreenCommand>()
            .and_then(|e| e.read(&mut cursor).next().cloned());
        assert!(
            matches!(cmd, Some(ScreenCommand::Toggle(AssetId(50)))),
            "UiInputSystem must still process Escape when a camera is present"
        );
    }

    // Build a free-fly camera at the origin facing -Z, plus an interactable prop
    // two units ahead (within reach and inside the facing cone), and a latched
    // interact input. Shared by the interact decomposition tests.
    fn interact_world() -> World {
        use crate::components::Prop;
        use crate::ecs::asset_id::AssetId;

        let mut world = World::new();
        let ctrl = CameraController {
            free_fly: true,
            ..CameraController::default()
        };
        world.add_component(camera(Some(ctrl)));
        world.add_component(Prop {
            asset_id: AssetId(1),
            position: [0.0, 0.0, -2.0],
            interactable: true,
            ..Default::default()
        });
        world
    }

    // Pressing interact rotates the target entity's Transform 45 degrees; the
    // Prop column was drained at load, so the rotation can only land on the
    // Transform.
    #[test]
    fn interact_rotates_transform() {
        use crate::components::{FrameInput, Interactable, Prop, Transform};

        let mut world = interact_world();
        world.start(SYSTEMS).unwrap();
        world.add_component(FrameInput {
            interact: true,
            ..Default::default()
        });
        world.step();

        let transform_yaw = world
            .join2::<Interactable, Transform>()
            .map(|(_, _, t)| t.rotation_deg[1])
            .next()
            .expect("interactable entity has a Transform");
        assert_eq!(transform_yaw, 45.0, "interact rotates the Transform");
        assert_eq!(
            world.query::<Prop>().count(),
            0,
            "the Prop column is drained at load"
        );
    }

    // A grounded (non-free-fly) camera clamps its position back inside the
    // bounds box and hands the movement intent + jump to PhysicsSystem instead
    // of moving itself, driving the FPS-walker basis and commit branch.
    #[test]
    fn fps_walker_clamps_bounds_and_hands_off_movement() {
        use crate::components::FrameInput;
        use crate::gfx::camera::view_matrix;

        let mut world = World::new();
        let ctrl = CameraController {
            free_fly: false,
            move_speed: 5.0,
            player_radius: 0.5,
            bounds_min: [-10.0, -10.0, -10.0],
            bounds_max: [10.0, 10.0, 10.0],
            ..CameraController::default()
        };
        let mut cam = camera(Some(ctrl));
        // Well outside the +X wall so the containment clamp is observable.
        cam.position = [100.0, 2.0, 0.0];
        world.add_component(cam);
        world.start(SYSTEMS).unwrap();

        world.add_component(FrameInput {
            forward: true,
            jump: true,
            ..Default::default()
        });
        world.step();

        let c = world.query::<Camera3D>().next().unwrap();
        // Pulled back to the wall minus the player radius (10 - 0.5).
        assert!(
            (c.position[0] - 9.5).abs() < 1e-4,
            "x clamped: {}",
            c.position[0]
        );
        // Jump is handed to physics rather than applied here.
        assert!(c.jump_requested, "jump intent handed off");
        // The FPS walker keeps the camera grounded: no direct vertical move.
        assert_eq!(
            c.position[1], 2.0,
            "grounded walker leaves height to physics"
        );
        // The view matrix was rebuilt from the (clamped) pose.
        assert_eq!(c.view_matrix, view_matrix(c.position, c.yaw, c.pitch));
    }

    // reset_velocity zeroes the smoothed movement velocity so a teleport does
    // not drift the next step.
    #[test]
    fn reset_velocity_zeroes_smoothed_velocity() {
        let mut sys = super::Camera3DSystem::new(CameraController::default());
        sys.velocity = [1.0, -2.0, 3.0];
        sys.reset_velocity();
        assert_eq!(sys.velocity, [0.0; 3]);
    }
}