Skip to main content

concinnity_engine/app/
dev_flags.rs

1//! Process-wide flags shared between the engine loop (library) and the
2//! binary-only `cn debug` subsystem. Only the flags the library itself names
3//! live here; the world.jsonl / shader-stage "changed" flags and the decal /
4//! emitter spawn queue moved fully into the binary-only debug tree
5//! (`crate::debug`), since nothing in the library references them.
6//!
7//!   ENABLED              "are we running under a dev-loop entry point?" Set
8//!                        once by main.rs's `Commands::Debug` / `Commands::Editor`
9//!                        arms before world build; read by `GraphicsSystem::init`
10//!                        / `AnimationSystem` / the draw list builder to enable
11//!                        disk-first shader loading + the hot-reload source
12//!                        capture. `cn run` leaves it false so production keeps
13//!                        the static `include_str!`-baked path with no
14//!                        filesystem dependency.
15//!   PENDING_ANIMATIONS   "an Animation source changed." Set by the cn debug
16//!                        watcher / WS `reload-assets` handler; consumed by the
17//!                        editor crate's `anim_reload::reload_clips_if_pending`,
18//!                        which the debug drive calls each frame to re-import
19//!                        file-backed clips. The flag lives here (in the runtime
20//!                        crate) because it bridges the runtime AnimationSystem,
21//!                        which reads ENABLED, and the editor-driven hot-reload.
22//!   VALIDATION           "did the launch request graphics validation?" Set by
23//!                        the CLI `--validation` flag (`cn run` / `cn debug`).
24//!                        Tri-state: unset defers to the build profile (on for
25//!                        debug, off for release). `resolve_validation` settles
26//!                        the two, and `GraphicsSystem::init` enables the
27//!                        DirectX / Vulkan debug layers from the result. Metal's
28//!                        validation layer cannot be toggled from a running
29//!                        process, so the CLI re-execs with the env var instead;
30//!                        this flag does not drive Metal.
31//!   QUALITY_PRESET       "did the launch force a master quality preset?" Set by
32//!                        the CLI `--quality-preset` flag. Outranks the persisted
33//!                        settings-menu choice at `GraphicsSystem::init` and is
34//!                        never written back, so a probe / CI run can force a
35//!                        preset (e.g. `ultra`, the only tier whose ceiling
36//!                        permits ray-traced reflections) without touching
37//!                        settings.bin. Unset leaves the persisted choice.
38//!   RT_DYNAMIC           "how should the ray-tracing acceleration structure
39//!                        track moving props?" Set by the CLI `--rt-dynamic`
40//!                        flag; travels to the backends through
41//!                        `PostSettings::rt_dynamic`. Unset resolves to `Auto`,
42//!                        the shipping dirty-gated rebuild.
43//!   RT_SKINNED_GEOMETRY  "may skinned meshes join the ray-tracing acceleration
44//!                        structure?" Set by the CLI `--rt-skinned-geometry`
45//!                        flag; travels to the backends through
46//!                        `PostSettings::rt_skinned_geometry`. Unset leaves them
47//!                        in, so clearing it isolates the skinned trace path.
48//!   WORLD_JSONL_PATH     the world.jsonl the dev host is running. Set by the
49//!                        editor's `cn debug` / `cn editor` entry once the world
50//!                        path is resolved; read by `GraphicsSystem::init` (only
51//!                        under ENABLED) so the Prop-transform hot-reload watcher
52//!                        knows which file to subscribe to. world.jsonl discovery
53//!                        is authoring I/O that lives in `concinnity-cook`, which
54//!                        the runtime does not link, so the dev host resolves the
55//!                        path and hands it in rather than the engine looking it
56//!                        up. Left None for `cn run` and embedded preview.
57//!
58//! A static is the pragmatic shape here: the flags are process-wide because the
59//! rendering backend is too (a single context per process owns the GPU), and
60//! plumbing them through the public `App` / `run_interpreted` signatures would
61//! touch far more code for the same observable behaviour.
62
63use std::sync::Mutex;
64use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
65
66pub use crate::gfx::quality_preset::QualityPreset;
67pub use concinnity_core::render::rt_geom::RtDynamicMode;
68
69use crate::gfx::quality_preset::{preset_at, preset_index};
70
71static ENABLED: AtomicBool = AtomicBool::new(false);
72static PENDING_ANIMATIONS: AtomicBool = AtomicBool::new(false);
73// "keep the presented frame blit-readable for an exit screenshot." Set by
74// `cn run --screenshot` before world build; read by `GraphicsSystem::init`.
75// The dev loop's ENABLED implies capture without this flag.
76static CAPTURE: AtomicBool = AtomicBool::new(false);
77
78// Tri-state validation request: 0 = unset (use the build-profile default),
79// 1 = explicitly off, 2 = explicitly on.
80static VALIDATION: AtomicU8 = AtomicU8::new(0);
81
82// Launch-forced master quality preset: 0 = unset, otherwise the preset's cycle
83// index plus one.
84static QUALITY_PRESET: AtomicU8 = AtomicU8::new(0);
85
86// Launch-forced ray-tracing update mode: 0 = unset, otherwise `RT_DYNAMIC_ORDER`
87// index plus one.
88static RT_DYNAMIC: AtomicU8 = AtomicU8::new(0);
89
90// The modes `RT_DYNAMIC` encodes, in encoding order.
91const RT_DYNAMIC_ORDER: [RtDynamicMode; 4] = [
92    RtDynamicMode::Off,
93    RtDynamicMode::Auto,
94    RtDynamicMode::Rebuild,
95    RtDynamicMode::Tlas,
96];
97
98// Tri-state skinned-RT-geometry request: 0 = unset, 1 = excluded, 2 = included.
99static RT_SKINNED_GEOMETRY: AtomicU8 = AtomicU8::new(0);
100
101// Path to the world.jsonl the dev host is running, or None outside a dev host.
102static WORLD_JSONL_PATH: Mutex<Option<String>> = Mutex::new(None);
103
104/// Mark this process as running under a dev-loop entry point. Call once
105/// before world build; the library only reads the flag.
106pub fn set_enabled(v: bool) {
107    ENABLED.store(v, Ordering::SeqCst);
108}
109
110// True when the process is running under a dev-loop entry point that wants
111// shader hot-reload. False for `cn run` and any embedded preview.
112pub(crate) fn enabled() -> bool {
113    ENABLED.load(Ordering::SeqCst)
114}
115
116// Arm frame capture for a production run that wants an exit screenshot.
117// Called by `start_runtime` before world build when a screenshot path was
118// requested.
119pub(crate) fn set_capture(v: bool) {
120    CAPTURE.store(v, Ordering::SeqCst);
121}
122
123// True when a production run armed frame capture (`cn run --screenshot`).
124pub(crate) fn capture() -> bool {
125    CAPTURE.load(Ordering::SeqCst)
126}
127
128/// Raise the "Animation source changed" flag. Called by the asset hot-reload
129/// watcher and the WS `reload-assets` handler; the library only reads it.
130pub fn set_pending_animations() {
131    PENDING_ANIMATIONS.store(true, Ordering::SeqCst);
132}
133
134/// Swap the "Animation source changed" flag to `false`, returning whether it
135/// was set. The editor crate's `anim_reload::reload_clips_if_pending` calls
136/// this; a `true` result kicks the per-clip re-import pass.
137pub fn take_pending_animations() -> bool {
138    PENDING_ANIMATIONS.swap(false, Ordering::SeqCst)
139}
140
141/// Record the CLI `--validation` request. `None` leaves the build-profile
142/// default in effect; `Some` forces validation on or off. The library only
143/// reads it.
144pub fn set_validation(v: Option<bool>) {
145    let encoded = match v {
146        None => 0,
147        Some(false) => 1,
148        Some(true) => 2,
149    };
150    VALIDATION.store(encoded, Ordering::SeqCst);
151}
152
153// The CLI validation request, or `None` when the launch did not specify one.
154pub(crate) fn validation() -> Option<bool> {
155    match VALIDATION.load(Ordering::SeqCst) {
156        1 => Some(false),
157        2 => Some(true),
158        _ => None,
159    }
160}
161
162// Settle the graphics-validation request: the CLI `--validation` flag if the
163// launch passed one, otherwise the build profile. Running a debug layer is a
164// launch concern, so no world can ask for it.
165pub(crate) fn resolve_validation() -> bool {
166    validation().unwrap_or(cfg!(debug_assertions))
167}
168
169/// Record the CLI `--quality-preset` request. `None` leaves the persisted
170/// settings-menu choice in effect. The library only reads it.
171pub fn set_quality_preset(preset: Option<QualityPreset>) {
172    let encoded = preset.map_or(0, |p| preset_index(p) as u8 + 1);
173    QUALITY_PRESET.store(encoded, Ordering::SeqCst);
174}
175
176// The CLI quality-preset request, or `None` when the launch did not force one.
177pub(crate) fn quality_preset() -> Option<QualityPreset> {
178    match QUALITY_PRESET.load(Ordering::SeqCst) {
179        0 => None,
180        n => Some(preset_at(n as usize - 1)),
181    }
182}
183
184// Settle the master quality preset: the CLI `--quality-preset` flag if the
185// launch passed one, otherwise the persisted settings-menu choice. `None` means
186// neither exists, which is a first launch the caller seeds.
187pub(crate) fn resolve_quality_preset(persisted: Option<QualityPreset>) -> Option<QualityPreset> {
188    quality_preset().or(persisted)
189}
190
191/// Record the CLI `--rt-dynamic` request. `None` leaves the default `Auto`
192/// update mode in effect. The library only reads it.
193pub fn set_rt_dynamic(mode: Option<RtDynamicMode>) {
194    let encoded = mode.map_or(0, |m| {
195        RT_DYNAMIC_ORDER
196            .iter()
197            .position(|&candidate| candidate == m)
198            .expect("RT_DYNAMIC_ORDER covers every mode") as u8
199            + 1
200    });
201    RT_DYNAMIC.store(encoded, Ordering::SeqCst);
202}
203
204// The CLI ray-tracing update-mode request, or `None` when the launch passed one.
205pub(crate) fn rt_dynamic() -> Option<RtDynamicMode> {
206    RT_DYNAMIC_ORDER
207        .get(RT_DYNAMIC.load(Ordering::SeqCst).wrapping_sub(1) as usize)
208        .copied()
209}
210
211// Settle how the acceleration structure tracks moving props: the CLI
212// `--rt-dynamic` flag if the launch passed one, otherwise `Auto`.
213pub(crate) fn resolve_rt_dynamic() -> RtDynamicMode {
214    rt_dynamic().unwrap_or_default()
215}
216
217/// Record the CLI `--rt-skinned-geometry` request. `None` leaves skinned meshes
218/// in the acceleration structure. The library only reads it.
219pub fn set_rt_skinned_geometry(v: Option<bool>) {
220    let encoded = match v {
221        None => 0,
222        Some(false) => 1,
223        Some(true) => 2,
224    };
225    RT_SKINNED_GEOMETRY.store(encoded, Ordering::SeqCst);
226}
227
228// The CLI skinned-RT-geometry request, or `None` when the launch did not pass one.
229pub(crate) fn rt_skinned_geometry() -> Option<bool> {
230    match RT_SKINNED_GEOMETRY.load(Ordering::SeqCst) {
231        1 => Some(false),
232        2 => Some(true),
233        _ => None,
234    }
235}
236
237// Settle whether skinned meshes join the acceleration structure: the CLI
238// `--rt-skinned-geometry` flag if the launch passed one, otherwise in.
239pub(crate) fn resolve_rt_skinned_geometry() -> bool {
240    rt_skinned_geometry().unwrap_or(true)
241}
242
243/// Record the world.jsonl path the dev host resolved, so the hot-reload watcher
244/// can subscribe to it. Called by the editor's `cn debug` / `cn editor` entry
245/// before world build; the library only reads it.
246pub fn set_world_jsonl_path(path: Option<String>) {
247    *WORLD_JSONL_PATH.lock().unwrap() = path;
248}
249
250// The world.jsonl path the dev host handed in, or None outside a dev host. Read
251// by `GraphicsSystem::init` to seed the Prop-transform reload watcher.
252pub(crate) fn world_jsonl_path() -> Option<String> {
253    WORLD_JSONL_PATH.lock().unwrap().clone()
254}
255
256// Shared flag access for a test whose code path reads a flag. Held for as long
257// as the read matters: for graphics init, across the whole `run_init`.
258//
259// The lock is the workspace's one process-global lock rather than a private
260// static, so a flag written here cannot race a test in another crate that
261// reaches these same flags through a different guard.
262#[cfg(test)]
263pub(crate) fn read_access() -> concinnity_testing::SharedAccess {
264    concinnity_testing::shared()
265}
266
267// Exclusive flag access for a test that writes one. Restores every flag graphics
268// init reads when it drops, so a panicking test cannot leak one into the rest of
269// the binary. Poison is ignored: the test holding it has already failed, and
270// erroring every later lock buries that failure under a cascade. Not reentrant,
271// so a test holding this must not also take `read_access`.
272#[cfg(test)]
273pub(crate) struct WriteAccess {
274    _guard: concinnity_testing::ExclusiveAccess,
275    enabled: bool,
276    validation: Option<bool>,
277    quality_preset: Option<QualityPreset>,
278    rt_dynamic: Option<RtDynamicMode>,
279    rt_skinned_geometry: Option<bool>,
280    world_jsonl_path: Option<String>,
281}
282
283#[cfg(test)]
284pub(crate) fn write_access() -> WriteAccess {
285    WriteAccess {
286        _guard: concinnity_testing::exclusive(),
287        enabled: enabled(),
288        validation: validation(),
289        quality_preset: quality_preset(),
290        rt_dynamic: rt_dynamic(),
291        rt_skinned_geometry: rt_skinned_geometry(),
292        world_jsonl_path: world_jsonl_path(),
293    }
294}
295
296#[cfg(test)]
297impl Drop for WriteAccess {
298    fn drop(&mut self) {
299        set_enabled(self.enabled);
300        set_validation(self.validation);
301        set_quality_preset(self.quality_preset);
302        set_rt_dynamic(self.rt_dynamic);
303        set_rt_skinned_geometry(self.rt_skinned_geometry);
304        set_world_jsonl_path(self.world_jsonl_path.take());
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    #[test]
313    fn defaults_off_and_round_trips() {
314        let _flags = write_access();
315        set_enabled(false);
316        assert!(!enabled());
317        set_enabled(true);
318        assert!(enabled());
319    }
320
321    #[test]
322    fn validation_tristate_round_trips() {
323        let _flags = write_access();
324        set_validation(None);
325        assert_eq!(validation(), None);
326        set_validation(Some(true));
327        assert_eq!(validation(), Some(true));
328        set_validation(Some(false));
329        assert_eq!(validation(), Some(false));
330    }
331
332    #[test]
333    fn every_quality_preset_round_trips_through_the_flag() {
334        let _flags = write_access();
335        set_quality_preset(None);
336        assert_eq!(quality_preset(), None);
337        for preset in QualityPreset::ALL {
338            set_quality_preset(Some(preset));
339            assert_eq!(quality_preset(), Some(preset));
340        }
341    }
342
343    #[test]
344    fn the_quality_flag_outranks_the_persisted_choice() {
345        let _flags = write_access();
346
347        // No flag: the persisted settings-menu choice decides, unchanged.
348        set_quality_preset(None);
349        assert_eq!(resolve_quality_preset(None), None);
350        assert_eq!(
351            resolve_quality_preset(Some(QualityPreset::Auto)),
352            Some(QualityPreset::Auto)
353        );
354
355        // The flag wins over any persisted value, and over none.
356        set_quality_preset(Some(QualityPreset::Ultra));
357        assert_eq!(
358            resolve_quality_preset(Some(QualityPreset::Auto)),
359            Some(QualityPreset::Ultra)
360        );
361        assert_eq!(resolve_quality_preset(None), Some(QualityPreset::Ultra));
362    }
363
364    #[test]
365    fn every_rt_dynamic_mode_round_trips_and_unset_is_auto() {
366        let _flags = write_access();
367        set_rt_dynamic(None);
368        assert_eq!(rt_dynamic(), None);
369        assert_eq!(resolve_rt_dynamic(), RtDynamicMode::Auto);
370        for mode in RT_DYNAMIC_ORDER {
371            set_rt_dynamic(Some(mode));
372            assert_eq!(rt_dynamic(), Some(mode));
373            assert_eq!(resolve_rt_dynamic(), mode);
374        }
375    }
376
377    #[test]
378    fn skinned_rt_geometry_is_in_unless_the_flag_clears_it() {
379        let _flags = write_access();
380        set_rt_skinned_geometry(None);
381        assert_eq!(rt_skinned_geometry(), None);
382        assert!(resolve_rt_skinned_geometry());
383        set_rt_skinned_geometry(Some(true));
384        assert!(resolve_rt_skinned_geometry());
385        set_rt_skinned_geometry(Some(false));
386        assert!(!resolve_rt_skinned_geometry());
387    }
388
389    #[test]
390    fn the_launch_flag_outranks_the_build_profile() {
391        let _flags = write_access();
392
393        // No flag: the build profile decides.
394        set_validation(None);
395        assert_eq!(resolve_validation(), cfg!(debug_assertions));
396
397        // An explicit flag decides instead, either way.
398        set_validation(Some(false));
399        assert!(!resolve_validation());
400        set_validation(Some(true));
401        assert!(resolve_validation());
402    }
403}