concinnity-engine 0.19.53

Runtime engine for Concinnity: ECS schedule, graphics, spawn, streaming
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
//! Scene-loading overlay: shows the LoadingOverlay's screen while the scene a
//! jump targets still streams content, drives its progress bar and label, and
//! fades the backdrop out to reveal the scene once it is resident. Runs after
//! StreamingSystem (it reads the residency status published this tick) and
//! before UiInputSystem (its screen commands apply the same tick); the elements
//! it writes are drawn by the next overlay build, like every HUD system.

use concinnity_core::components::LoadingOverlay;
use concinnity_core::components::ScreenCommand;
use concinnity_core::components::Sprite;
use concinnity_core::components::TextLabel;
use concinnity_core::ecs::Ref;
use concinnity_core::ecs::asset_id::AssetId;
use concinnity_core::ecs::{Access, FrameTime, PipelineContext, ScreenStack, StepResult, System};
use concinnity_core::render::scene_flow::FadePhase;
use concinnity_core::render::scene_residency::SceneLoadState;

// Seconds the backdrop takes to fade out over the freshly resident scene.
const FADE_OUT_SECS: f32 = 0.35;

#[derive(Debug)]
enum Phase {
    Hidden,
    Shown,
    // Seconds of frame time since the fade-out began.
    FadingOut { secs: f32 },
}

#[derive(Debug)]
pub(crate) struct LoadingOverlaySystem {
    screen: Option<AssetId>,
    backdrop: Option<AssetId>,
    track: Option<AssetId>,
    fill: Option<AssetId>,
    label: Option<AssetId>,
    phase: Phase,
    // The backdrop's authored tint alpha, captured on first show so the
    // fade-out animation can restore it for the next load.
    backdrop_alpha: Option<f32>,
}

impl LoadingOverlaySystem {
    // Build the overlay from a world's `LoadingOverlay` request component.
    pub(crate) fn new(config: LoadingOverlay) -> Self {
        Self {
            screen: config.screen.map(Ref::id),
            backdrop: config.backdrop.map(Ref::id),
            track: config.track.map(Ref::id),
            fill: config.fill.map(Ref::id),
            label: config.label.map(Ref::id),
            phase: Phase::Hidden,
            backdrop_alpha: None,
        }
    }

    fn sprite_mut<'a>(ctx: &'a mut PipelineContext, id: Option<AssetId>) -> Option<&'a mut Sprite> {
        ctx.get_mut_by_id::<Sprite>(id?)
    }

    fn set_visible(ctx: &mut PipelineContext, id: Option<AssetId>, visible: bool) {
        if let Some(sprite) = Self::sprite_mut(ctx, id) {
            sprite.visible = visible;
        }
    }

    fn set_backdrop_alpha(&self, ctx: &mut PipelineContext, alpha: f32) {
        if let Some(sprite) = Self::sprite_mut(ctx, self.backdrop) {
            sprite.tint[3] = alpha;
        }
    }

    // Restore the overlay's elements to their shown state: the backdrop at its
    // authored alpha (captured here on first show), the bar visible.
    fn show(&mut self, ctx: &mut PipelineContext, progress: f32) {
        if self.backdrop_alpha.is_none() {
            self.backdrop_alpha = Self::sprite_mut(ctx, self.backdrop).map(|s| s.tint[3]);
        }
        if let Some(alpha) = self.backdrop_alpha {
            self.set_backdrop_alpha(ctx, alpha);
        }
        Self::set_visible(ctx, self.track, true);
        if let Some(id) = self.label
            && let Some(label) = ctx.get_mut_by_id::<TextLabel>(id)
        {
            label.visible = true;
        }
        self.update_bar(ctx, progress);
    }

    // Size the fill against the track and refresh the percentage label.
    fn update_bar(&self, ctx: &mut PipelineContext, progress: f32) {
        let progress = progress.clamp(0.0, 1.0);
        let track = self
            .track
            .and_then(|id| ctx.get_by_id::<Sprite>(id))
            .map(|s| (s.x, s.width));
        if let Some(fill) = Self::sprite_mut(ctx, self.fill) {
            if let Some((x, width)) = track {
                fill.x = x;
                fill.width = width * progress;
            }
            fill.visible = progress > 0.0;
        }
        if let Some(id) = self.label
            && let Some(label) = ctx.get_mut_by_id::<TextLabel>(id)
        {
            label.content = format!("Loading {:.0}%", progress * 100.0);
        }
    }

    // Hide the bar and label, leaving only the backdrop to fade out.
    fn hide_bar(&self, ctx: &mut PipelineContext) {
        Self::set_visible(ctx, self.track, false);
        Self::set_visible(ctx, self.fill, false);
        if let Some(id) = self.label
            && let Some(label) = ctx.get_mut_by_id::<TextLabel>(id)
        {
            label.visible = false;
        }
    }

    // Whether the overlay's screen currently draws on top of the stack.
    // `None` when the screen is not in the stack at all.
    fn screen_on_top(&self, ctx: &PipelineContext) -> Option<bool> {
        let screen = self.screen?;
        let stack = ctx.resource::<ScreenStack>()?;
        let mine = *stack.layers.get(&screen)?;
        Some(stack.layers.values().all(|&layer| layer <= mine))
    }
}

impl System for LoadingOverlaySystem {
    fn access(&self) -> Access {
        Access::new()
            .writes_components(crate::component_mask![Sprite, TextLabel])
            .reads_resources(crate::resource_mask![
                concinnity_core::ecs::EntityById,
                crate::ecs::ActiveSceneFlow,
                crate::ecs::SceneResidencyStatus,
                ScreenStack,
                FrameTime,
            ])
            .writes_resources(crate::resource_mask![ScreenCommand])
    }

    fn step(&mut self, ctx: &mut PipelineContext) -> StepResult {
        // The scene the player is headed to: the fade target mid-jump, else
        // the active scene.
        let target = ctx
            .resource::<crate::ecs::ActiveSceneFlow>()
            .and_then(|slot| slot.flow.as_ref())
            .map(|flow| match flow.fade {
                FadePhase::ToBlack { next, .. } => next,
                _ => flow.current,
            });
        let status = target.and_then(|t| {
            ctx.resource::<crate::ecs::SceneResidencyStatus>()
                .and_then(|s| s.scenes.iter().find(|(id, ..)| *id == t))
                .copied()
        });
        let loading = matches!(status, Some((_, SceneLoadState::Loading, _)));
        let progress = status.map(|(_, _, p)| p).unwrap_or(1.0);

        match self.phase {
            Phase::Hidden => {
                // Defer to an already-open pausing screen (a menu): the
                // overlay fronts a load only when nothing else covers the
                // world.
                let menu_up = ctx
                    .resource::<ScreenStack>()
                    .is_some_and(|s| s.pauses_world);
                if loading
                    && !menu_up
                    && let Some(screen) = self.screen
                {
                    ctx.events_mut::<ScreenCommand>()
                        .send(ScreenCommand::Push(screen));
                    self.show(ctx, progress);
                    self.phase = Phase::Shown;
                }
            }
            Phase::Shown => {
                if loading {
                    // A scene jump dismisses every open screen; if that took
                    // the overlay down mid-load (a fresh jump), re-open it.
                    if self.screen_on_top(ctx).is_none()
                        && let Some(screen) = self.screen
                    {
                        ctx.events_mut::<ScreenCommand>()
                            .send(ScreenCommand::Push(screen));
                    }
                    self.update_bar(ctx, progress);
                } else {
                    self.hide_bar(ctx);
                    self.phase = Phase::FadingOut { secs: 0.0 };
                }
            }
            Phase::FadingOut { ref mut secs } => {
                if loading {
                    // A new jump began before the reveal finished.
                    self.show(ctx, progress);
                    self.phase = Phase::Shown;
                    return StepResult::Continue;
                }
                *secs += ctx
                    .resource::<FrameTime>()
                    .copied()
                    .unwrap_or_default()
                    .dt
                    .max(0.0);
                let faded = fade_remaining(*secs);
                if faded > 0.0 {
                    let base = self.backdrop_alpha.unwrap_or(1.0);
                    self.set_backdrop_alpha(ctx, base * faded);
                    return StepResult::Continue;
                }
                // Fully faded: pop the screen once it is on top (beneath a
                // later-pushed screen it stays, invisible, until then).
                match self.screen_on_top(ctx) {
                    Some(true) => {
                        ctx.events_mut::<ScreenCommand>().send(ScreenCommand::Hide);
                        self.phase = Phase::Hidden;
                    }
                    Some(false) => self.set_backdrop_alpha(ctx, 0.0),
                    // Dismissed externally (a scene jump's screen clear).
                    None => self.phase = Phase::Hidden,
                }
            }
        }
        StepResult::Continue
    }
}

// The backdrop's remaining opacity fraction `elapsed` into the fade-out; at or
// below zero once the fade has finished.
fn fade_remaining(elapsed_secs: f32) -> f32 {
    1.0 - elapsed_secs / FADE_OUT_SECS
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ecs::SYSTEMS;
    use concinnity_core::components::Screen;
    use concinnity_core::ecs::Ref;
    use concinnity_core::ecs::World;
    use concinnity_core::render::scene_flow::SceneFlow;

    const SCREEN: AssetId = AssetId(1);
    const BACKDROP: AssetId = AssetId(2);
    const TRACK: AssetId = AssetId(3);
    const FILL: AssetId = AssetId(4);
    const LABEL: AssetId = AssetId(5);
    const SCENE: AssetId = AssetId(9);

    fn overlay_config() -> LoadingOverlay {
        LoadingOverlay {
            screen: Some(Ref::new(SCREEN)),
            backdrop: Some(Ref::new(BACKDROP)),
            track: Some(Ref::new(TRACK)),
            fill: Some(Ref::new(FILL)),
            label: Some(Ref::new(LABEL)),
        }
    }

    // The overlay's screen, elements and scene flow, plus the `LoadingOverlay`
    // component that schedules the engine's own system.
    fn overlay_world() -> World {
        let mut world = World::new();
        world.add_component(overlay_config());
        world.push_identified(SCREEN, Screen::default());
        world.push_identified(
            BACKDROP,
            Sprite {
                tint: [0.0, 0.0, 0.0, 1.0],
                screen: Some(Ref::new(SCREEN)),
                ..Default::default()
            },
        );
        world.push_identified(
            TRACK,
            Sprite {
                x: 400.0,
                width: 480.0,
                screen: Some(Ref::new(SCREEN)),
                ..Default::default()
            },
        );
        world.push_identified(
            FILL,
            Sprite {
                x: 400.0,
                width: 0.0,
                visible: false,
                screen: Some(Ref::new(SCREEN)),
                ..Default::default()
            },
        );
        world.push_identified(
            LABEL,
            TextLabel {
                screen: Some(Ref::new(SCREEN)),
                ..Default::default()
            },
        );
        world.insert_resource(crate::ecs::ActiveSceneFlow::new(Some(SceneFlow {
            scenes: vec![SCENE],
            current: SCENE,
            fade: FadePhase::None,
        })));
        world
    }

    fn set_status(world: &mut World, state: SceneLoadState, progress: f32) {
        world.insert_resource(crate::ecs::SceneResidencyStatus {
            scenes: vec![(SCENE, state, progress)],
        });
    }

    fn shown(world: &World) -> bool {
        world
            .resource::<ScreenStack>()
            .is_some_and(|s| s.layers.contains_key(&SCREEN))
    }

    fn sprite(world: &World, id: AssetId) -> &Sprite {
        world.get_by_id::<Sprite>(id).unwrap()
    }

    #[test]
    fn loading_scene_shows_the_overlay_and_drives_the_bar() {
        let mut world = overlay_world();
        set_status(&mut world, SceneLoadState::Loading, 0.25);
        world.start(SYSTEMS).unwrap();
        world.step();

        assert!(shown(&world), "overlay screen should be on the stack");
        let fill = sprite(&world, FILL);
        assert!(fill.visible);
        assert!((fill.width - 480.0 * 0.25).abs() < 1e-3);
        let label = world.get_by_id::<TextLabel>(LABEL).unwrap();
        assert_eq!(label.content, "Loading 25%");
    }

    #[test]
    fn resident_scene_never_shows_the_overlay() {
        let mut world = overlay_world();
        set_status(&mut world, SceneLoadState::Resident, 1.0);
        world.start(SYSTEMS).unwrap();
        world.step();
        assert!(!shown(&world));
    }

    #[test]
    fn missing_residency_status_never_shows_the_overlay() {
        let mut world = overlay_world();
        world.start(SYSTEMS).unwrap();
        world.step();
        assert!(!shown(&world));
    }

    #[test]
    fn an_open_pausing_screen_defers_the_overlay() {
        let mut world = overlay_world();
        world.push_identified(
            AssetId(20),
            Screen {
                initial: true,
                ..Default::default()
            },
        );
        set_status(&mut world, SceneLoadState::Loading, 0.5);
        world.start(SYSTEMS).unwrap();
        // Two steps: the first publishes the initial screen's stack, the
        // second is the earliest the overlay could react to it.
        world.step();
        world.step();
        assert!(!shown(&world), "overlay must not cover an open menu");
    }

    #[test]
    fn fade_remaining_runs_from_one_to_zero_over_the_fade() {
        assert_eq!(fade_remaining(0.0), 1.0);
        let half = fade_remaining(FADE_OUT_SECS / 2.0);
        assert!((half - 0.5).abs() < 1e-6);
        assert!(fade_remaining(FADE_OUT_SECS) <= 0.0);
    }

    #[test]
    fn resident_target_fades_the_overlay_out_and_hides_it() {
        let mut world = overlay_world();
        set_status(&mut world, SceneLoadState::Loading, 0.5);
        world.start(SYSTEMS).unwrap();
        world.step();
        assert!(shown(&world));

        // The load completes: the bar hides first, then the backdrop fades.
        set_status(&mut world, SceneLoadState::Resident, 1.0);
        world.step();
        assert!(!sprite(&world, FILL).visible);
        assert!(!sprite(&world, TRACK).visible);
        assert!(shown(&world), "backdrop still fading");

        // The backdrop fades by frame time, then the screen pops off the stack.
        world.insert_resource(FrameTime {
            dt: FADE_OUT_SECS * 0.6,
            elapsed: 0.0,
        });
        world.step();
        assert!((sprite(&world, BACKDROP).tint[3] - 0.4).abs() < 1e-4);
        assert!(shown(&world), "backdrop still fading");
        world.step();
        assert!(!shown(&world));

        // A later jump restores the full overlay, opaque again.
        set_status(&mut world, SceneLoadState::Loading, 0.1);
        world.step();
        assert!(shown(&world));
        assert_eq!(sprite(&world, BACKDROP).tint[3], 1.0);
        assert!(sprite(&world, TRACK).visible);
    }
}