bevy-convars 0.2.0

An implementation of convars (config or console variables) for configuring your Bevy application.
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
#![deny(missing_docs)]
//! Provides an implementation of ConVars (henceforth CVars), a form of global configuration for an application.
//!
//! Intended for full applications, not for libraries!
//! If you're a library author, the easiest and best way to integrate is simply to make your library configurable, and allow the end user to create convars themselves.
//!

#![cfg_attr(all(feature = "config_loader_asset", feature = "config_loader_fs"), doc = include_str!("examples.md"))]

use bevy_app::App;
use bevy_app::prelude::*;
use bevy_ecs::component::ComponentId;
use bevy_ecs::prelude::*;
use bevy_platform_support::collections::HashMap;
use bevy_reflect::{TypeRegistration, prelude::*};
#[cfg(feature = "config_loader")]
use builtin::ConfigLoaderCVarsPlugin;
use builtin::CoreCVarsPlugin;
use builtin::LogCVarChanges;
#[cfg(feature = "parse_cvars")]
use parse::CVarOverride;
use reflect::CVarMeta;
use serde::Deserializer;
#[cfg(feature = "parse_cvars")]
use serde::de::IntoDeserializer as _;

pub mod defaults;
mod error;
mod macros;
mod types;
pub use error::*;
pub use types::*;
pub mod builtin;
#[cfg(feature = "config_loader")]
pub mod loader;
#[cfg(feature = "parse_cvars")]
pub mod parse;
#[cfg(feature = "parse_cvars")]
pub mod save;
pub mod prelude;
pub mod reflect;

#[cfg(test)]
mod tests;

/// Internal re-exports to avoid depending on the user's scope.
#[doc(hidden)]
pub mod reexports {
    pub use bevy_app;
    pub use bevy_ecs;
    pub use bevy_reflect;
    pub mod jank {
        pub use crate::reflect::ReflectCVar as ReflectCVar__MACRO_JANK;
        pub use bevy_ecs::reflect::ReflectResource as ReflectResource__MACRO_JANK;
        pub use bevy_reflect::prelude::ReflectDefault as ReflectDefault__MACRO_JANK;
    }
}

/// Core plugin for providing CVars.
/// # Remarks
/// Needs to be registered before any of the generated plugins to ensure [CVarManagement] is available.
pub struct CVarsPlugin;

#[derive(Debug)]
pub(crate) enum CVarTreeNode {
    Leaf {
        name: &'static str,
        reg: ComponentId,
    },
    Branch {
        descendants: HashMap<&'static str, CVarTreeNode>,
    },
}

impl Default for CVarTreeNode {
    fn default() -> Self {
        CVarTreeNode::Branch {
            descendants: Default::default(),
        }
    }
}

struct CVarTreeEditContext {
    new_cvar: &'static str,
}

impl CVarTreeNode {
    pub fn children(&self) -> Option<impl Iterator<Item = (&'_ &'static str, &'_ CVarTreeNode)>> {
        match self {
            CVarTreeNode::Leaf { name: _, reg: _ } => None,
            CVarTreeNode::Branch { descendants } => Some(descendants.iter()),
        }
    }

    pub fn is_leaf(&self) -> bool {
        matches!(self, CVarTreeNode::Leaf { .. })
    }

    pub fn insert(&mut self, name: &'static str, id: ComponentId) {
        let segments: Vec<&'static str> = name.split('.').collect();
        let edit_ctx = CVarTreeEditContext { new_cvar: name };

        let mut cur = self;
        for (idx, segment) in segments.iter().enumerate() {
            if idx == segments.len() - 1 {
                let _ = cur.insert_leaf(segment, id, &edit_ctx);
                return;
            } else {
                cur = cur.get_or_insert_branch(segment, &edit_ctx);
            }
        }
    }

    #[must_use]
    fn get_or_insert_branch(
        &mut self,
        key: &'static str,
        ctx: &CVarTreeEditContext,
    ) -> &mut CVarTreeNode {
        match self {
            CVarTreeNode::Leaf { name, reg: _ } => panic!(
                "Tried to insert branch {name} into a terminating node. A CVar cannot be both a value and table. CVar in question is {}",
                ctx.new_cvar
            ),
            CVarTreeNode::Branch { descendants } => {
                descendants.entry(key).or_insert(CVarTreeNode::Branch {
                    descendants: Default::default(),
                })
            }
        }
    }

    #[must_use]
    fn insert_leaf(
        &mut self,
        key: &'static str,
        reg: ComponentId,
        ctx: &CVarTreeEditContext,
    ) -> &mut CVarTreeNode {
        match self {
            CVarTreeNode::Leaf { name, reg: _ } => {
                panic!(
                    "Tried to insert leaf {name} into a terminating node. Is there a duplicate or overlap? CVar in question is {}",
                    ctx.new_cvar
                )
            }
            CVarTreeNode::Branch { descendants } => {
                assert!(
                    descendants
                        .insert(
                            key,
                            CVarTreeNode::Leaf {
                                name: ctx.new_cvar,
                                reg
                            }
                        )
                        .is_none(),
                    "Attempted to insert a duplicate CVar. CVar in question is {}",
                    ctx.new_cvar
                );

                descendants.get_mut(key).unwrap()
            }
        }
    }

    #[must_use]
    pub fn get(&self, name: &str) -> Option<ComponentId> {
        let mut cur = self;
        for seg in name.split('.') {
            let CVarTreeNode::Branch { descendants } = cur else {
                return None;
            };

            cur = descendants.get(seg)?;
        }

        let CVarTreeNode::Leaf { name: _, reg } = cur else {
            return None;
        };

        Some(*reg)
    }
}

/// App resource that provides management information and functionality for CVars.
#[derive(Default, Resource)]
pub struct CVarManagement {
    /// An index of all cvar resources and their type registrations.
    pub(crate) resources: HashMap<ComponentId, TypeRegistration>,
    /// An index of all CVars and their types.
    pub(crate) tree: CVarTreeNode,
}

impl CVarManagement {
    /// Register a CVar of the given type to the internal storage.
    #[doc(hidden)]
    pub fn register_cvar<T: Reflect + Resource + CVarMeta>(&mut self, app: &mut App) {
        let registration = {
            let registry = app.world().resource::<AppTypeRegistry>();
            let registry = registry.read();
            registry.get(::std::any::TypeId::of::<T>()).unwrap().clone()
        };
        let cid = app.world().resource_id::<T>().unwrap();

        self.tree.insert(T::CVAR_PATH, cid);
        self.resources.insert(cid, registration);
    }

    /// Gets a CVar's value through reflection.
    /// # Remarks
    /// This returns the inner value, not the cvar resource itself.
    pub fn get_cvar_reflect<'a>(
        &self,
        world: &'a World,
        cvar: &str,
    ) -> Result<&'a dyn Reflect, CVarError> {
        let cid = self.tree.get(cvar).ok_or(CVarError::UnknownCVar)?;

        let ty_info = self.resources.get(&cid).ok_or(CVarError::UnknownCVar)?;

        let reflect_res = ty_info
            .data::<ReflectResource>()
            .ok_or(CVarError::BadCVarType)?;
        let reflect_cvar = ty_info
            .data::<reflect::ReflectCVar>()
            .ok_or(CVarError::BadCVarType)?;

        let res = reflect_res.reflect(world)?;

        reflect_cvar
            .reflect_inner(res.as_partial_reflect())
            .unwrap()
            .try_as_reflect()
            .ok_or(CVarError::BadCVarType)
    }

    /// Gets a CVar's value mutably through reflection.
    /// # Remarks
    /// This returns the inner value, not the cvar resource itself.
    /// A change-detection aware handle is returned.
    pub fn get_cvar_reflect_mut<'a>(
        &self,
        world: &'a mut World,
        cvar: &str,
    ) -> Result<Mut<'a, dyn Reflect>, CVarError> {
        let cid = self.tree.get(cvar).ok_or(CVarError::UnknownCVar)?;

        let ty_info = self.resources.get(&cid).ok_or(CVarError::UnknownCVar)?;

        let reflect_res = ty_info
            .data::<ReflectResource>()
            .ok_or(CVarError::BadCVarType)?;
        let reflect_cvar = ty_info
            .data::<reflect::ReflectCVar>()
            .ok_or(CVarError::BadCVarType)?;

        Ok(reflect_res.reflect_mut(world)?.map_unchanged(|x| {
            reflect_cvar
                .reflect_inner_mut(x.as_partial_reflect_mut())
                .unwrap()
                .try_as_reflect_mut()
                .unwrap()
        }))
    }

    /// Set a CVar to the given reflected value using reflection.
    /// # Remarks
    /// Use the WorldExtensions version if you can, it handles the invariants. This is harder to call than it looks due to needing mutable world.
    pub fn set_cvar_reflect(
        &self,
        world: &mut World,
        cvar: &str,
        value: &dyn Reflect,
    ) -> Result<(), CVarError> {
        let cid = self.tree.get(cvar).ok_or(CVarError::UnknownCVar)?;

        let ty_reg = self.resources.get(&cid).ok_or(CVarError::MissingCid)?;

        let reflect_cvar = ty_reg.data::<reflect::ReflectCVar>().unwrap();

        let reflect_res = ty_reg.data::<ReflectResource>().unwrap();

        let cvar = reflect_res.reflect_mut(world)?;

        reflect_cvar.reflect_apply(
            cvar.into_inner().as_partial_reflect_mut(),
            value.as_partial_reflect(),
        )?;

        Ok(())
    }

    /// Set a CVar to the given reflected value using reflection, without triggering change detection.
    /// # Remarks
    /// Use the WorldExtensions version if you can, it handles the invariants. This is harder to call than it looks due to needing mutable world.
    pub fn set_cvar_reflect_no_change(
        &self,
        world: &mut World,
        cvar: &str,
        value: &dyn Reflect,
    ) -> Result<(), CVarError> {
        let cid = self.tree.get(cvar).ok_or(CVarError::UnknownCVar)?;

        let ty_reg = self.resources.get(&cid).ok_or(CVarError::MissingCid)?;

        let reflect_cvar = ty_reg.data::<reflect::ReflectCVar>().unwrap();

        let reflect_res = ty_reg.data::<ReflectResource>().unwrap();

        let mut cvar = reflect_res.reflect_mut(world)?;

        reflect_cvar.reflect_apply(
            cvar.bypass_change_detection().as_partial_reflect_mut(),
            value.as_partial_reflect(),
        )?;

        Ok(())
    }

    /// Set a CVar to the given deserializable value using reflection.
    /// # Remarks
    /// Use the WorldExtensions version if you can, it handles the invariants. This is harder to call than it looks due to needing mutable world.
    pub fn set_cvar_deserialize<'w, 'a>(
        &self,
        world: &mut World,
        cvar: &str,
        value: impl Deserializer<'a>,
    ) -> Result<(), CVarError> {
        let cid = self.tree.get(cvar).ok_or(CVarError::UnknownCVar)?;

        let ty_reg = self.resources.get(&cid).ok_or(CVarError::MissingCid)?;

        let reflect_cvar = ty_reg.data::<reflect::ReflectCVar>().unwrap();

        let value_patch = {
            let field_0 = reflect_cvar.inner_type();

            let registry = world.resource::<AppTypeRegistry>().read();

            let deserializer = registry
                .get(field_0)
                .ok_or(CVarError::BadCVarType)?
                .data::<ReflectDeserialize>()
                .ok_or(CVarError::CannotDeserialize)?;

            deserializer
                .deserialize(value)
                .map_err(|e| CVarError::FailedDeserialize(format!("{e:?}")))?
        };

        let reflect_res = ty_reg.data::<ReflectResource>().unwrap();

        let cvar = reflect_res.reflect_mut(world)?;

        reflect_cvar.reflect_apply(
            cvar.into_inner().as_partial_reflect_mut(),
            value_patch.as_partial_reflect(),
        )?;

        Ok(())
    }

    /// Set a CVar to the given deserializable value using reflection, without triggering change detection.
    /// # Remarks
    /// Use the WorldExtensions version if you can, it handles the invariants. This is harder to call than it looks due to needing mutable world.
    pub fn set_cvar_deserialize_no_change<'w, 'a>(
        &self,
        world: &mut World,
        cvar: &str,
        value: impl Deserializer<'a>,
    ) -> Result<(), CVarError> {
        let cid = self.tree.get(cvar).ok_or(CVarError::UnknownCVar)?;

        let ty_reg = self.resources.get(&cid).ok_or(CVarError::MissingCid)?;

        let reflect_cvar = ty_reg.data::<reflect::ReflectCVar>().unwrap();

        let value_patch = {
            let field_0 = reflect_cvar.inner_type();

            let registry = world.resource::<AppTypeRegistry>().read();

            let deserializer = registry
                .get(field_0)
                .ok_or(CVarError::CannotDeserialize)?
                .data::<ReflectDeserialize>()
                .ok_or(CVarError::CannotDeserialize)?;

            deserializer
                .deserialize(value)
                .map_err(|e| CVarError::FailedDeserialize(format!("{e:?}")))?
        };

        let reflect_res = ty_reg.data::<ReflectResource>().unwrap();

        let mut cvar = reflect_res.reflect_mut(world)?;

        reflect_cvar.reflect_apply(
            cvar.bypass_change_detection().as_partial_reflect_mut(),
            value_patch.as_partial_reflect(),
        )?;

        Ok(())
    }

    /// Returns an iterator for all CVar type registrations.
    pub fn iterate_cvar_types(&self) -> impl Iterator<Item = &TypeRegistration> {
        self.resources.values()
    }
}

/// Provides extensions to the world for CVars.
pub trait WorldExtensions {
    #[doc(hidden)]
    fn as_world(&mut self) -> &mut World;

    /// Set a CVar on the world through reflection, by deserializing the provided data into it.
    fn set_cvar_deserialize<'a>(
        &mut self,
        cvar: &str,
        value: impl serde::Deserializer<'a>,
    ) -> Result<(), CVarError> {
        let cell = self.as_world();

        cell.resource_scope::<CVarManagement, _>(|w, management| {
            management.set_cvar_deserialize(w, cvar, value)
        })
    }

    /// Set a CVar on the world through reflection by deserializing the provided data into it, without triggering change detection.
    fn set_cvar_deserialize_no_change<'a>(
        &mut self,
        cvar: &str,
        value: impl serde::Deserializer<'a>,
    ) -> Result<(), CVarError> {
        let cell = self.as_world();

        cell.resource_scope::<CVarManagement, _>(|w, management| {
            management.set_cvar_deserialize_no_change(w, cvar, value)
        })
    }

    /// Set a CVar on the world through reflection
    fn set_cvar_reflect(&mut self, cvar: &str, value: &dyn Reflect) -> Result<(), CVarError> {
        let cell = self.as_world();

        cell.resource_scope::<CVarManagement, _>(|w, management| {
            management.set_cvar_reflect(w, cvar, value)
        })
    }

    /// Set a CVar on the world through reflection, without triggering change detection.
    fn set_cvar_reflect_no_change(
        &mut self,
        cvar: &str,
        value: &dyn Reflect,
    ) -> Result<(), CVarError> {
        let cell = self.as_world();

        cell.resource_scope::<CVarManagement, _>(|w, management| {
            management.set_cvar_reflect_no_change(w, cvar, value)
        })
    }

    /// Set a CVar on the world using the provided override.
    /// # Remarks
    /// CVar overrides, by design, bypass change detection to look like the default value of the CVar.
    #[cfg(feature = "parse_cvars")]
    fn set_cvar_with_override(&mut self, r#override: &CVarOverride) -> Result<(), CVarError> {
        let cell = self.as_world();

        cell.resource_scope::<CVarManagement, _>(|w, management| {
            management.set_cvar_deserialize_no_change(
                w,
                &r#override.0,
                r#override.1.clone().into_deserializer(),
            )
        })
    }
}

impl WorldExtensions for World {
    fn as_world(&mut self) -> &mut World {
        self
    }
}

impl Plugin for CVarsPlugin {
    fn build(&self, app: &mut bevy_app::App) {
        app.register_type::<CVarFlags>();

        app.insert_resource::<CVarManagement>(CVarManagement::default());
        app.add_plugins(CoreCVarsPlugin);
        #[cfg(feature = "config_loader")]
        {
            app.add_plugins(ConfigLoaderCVarsPlugin);
        }
    }
}

/// Internal function meant for the macros. Don't use this!
/// Handles reporting CVar changes if LogCVarChanges is set.
#[doc(hidden)]
pub fn cvar_modified_system<T: CVarMeta>(
    r: bevy_ecs::prelude::Res<T>,
    log_updates: Res<LogCVarChanges>,
) {
    use bevy_ecs::prelude::DetectChanges as _;

    if **log_updates && r.is_changed() {
        bevy_log::info!("CVar modified: {} = {:?}", T::CVAR_PATH, **r);
    }

    if !r.is_changed() {
        return;
    }

    if !T::flags().contains(CVarFlags::RUNTIME) && !r.is_added() {
        if T::flags().contains(CVarFlags::SAVED) {
            bevy_log::warn!("Non-runtime CVar was modified! Change will not apply until restart.");
        } else {
            bevy_log::error!("Non-runtime, non-saved CVar was modified! This will have NO EFFECT.");
        }
    }
}