Skip to main content

rusting_core/
components.rs

1use bevy_ecs::component::Component;
2use bevy_ecs::entity::Entity;
3use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6/// Persistent scene identity. Unlike a Bevy [`Entity`], this survives saving,
7/// loading, and a new process.
8#[derive(Component, Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub struct SceneId(pub Uuid);
10
11impl SceneId {
12    #[must_use]
13    pub fn new() -> Self {
14        Self(Uuid::new_v4())
15    }
16}
17
18impl Default for SceneId {
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24/// World-space transform derived from [`crate::transform::Transform`] and hierarchy.
25#[derive(Component, Clone, Copy, Debug, PartialEq)]
26pub struct GlobalTransform {
27    pub matrix: [[f32; 4]; 4],
28}
29
30impl Default for GlobalTransform {
31    fn default() -> Self {
32        Self {
33            matrix: nalgebra::Matrix4::<f32>::identity().into(),
34        }
35    }
36}
37
38#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
39pub struct Parent(pub Entity);
40
41#[derive(Component, Clone, Debug, Default, PartialEq, Eq)]
42pub struct Children(pub Vec<Entity>);
43
44#[derive(Clone, Copy, Debug, PartialEq)]
45pub enum Projection {
46    Perspective {
47        vertical_fov_radians: f32,
48        near: f32,
49        far: f32,
50    },
51    Orthographic {
52        vertical_size: f32,
53        near: f32,
54        far: f32,
55    },
56}
57
58impl Default for Projection {
59    fn default() -> Self {
60        Self::Perspective {
61            vertical_fov_radians: std::f32::consts::FRAC_PI_3,
62            near: 0.1,
63            far: 1_000.0,
64        }
65    }
66}
67
68#[derive(Component, Clone, Copy, Debug, Default, PartialEq)]
69pub struct Camera {
70    pub projection: Projection,
71    pub active: bool,
72    pub priority: i32,
73}
74
75#[derive(Component, Clone, Debug, PartialEq, Eq)]
76pub struct Name(pub String);
77
78/// Reusable classes assigned to one scene object.
79///
80/// Names identify one object. Classes select any number of objects, and one
81/// object can belong to several classes at the same time.
82#[derive(
83    Component, Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
84)]
85pub struct ObjectClasses {
86    /// Class names such as `gravity`, `enemy`, or `falling_cubes`.
87    pub names: Vec<String>,
88}
89
90impl ObjectClasses {
91    /// Creates a clean class list without empty or repeated names.
92    #[must_use]
93    pub fn new(classes: impl IntoIterator<Item = impl Into<String>>) -> Self {
94        let mut result = Self::default();
95        for class in classes {
96            result.add(class);
97        }
98        result
99    }
100
101    /// Adds a class if this object does not already have it.
102    pub fn add(&mut self, class: impl Into<String>) -> bool {
103        let class = class.into();
104        let class = class.trim();
105        if class.is_empty() || self.contains(class) {
106            return false;
107        }
108        self.names.push(class.to_owned());
109        true
110    }
111
112    /// Removes a class from this object.
113    pub fn remove(&mut self, class: &str) -> bool {
114        let old_len = self.names.len();
115        self.names.retain(|current| current != class);
116        self.names.len() != old_len
117    }
118
119    /// Returns true when this object belongs to the requested class.
120    #[must_use]
121    pub fn contains(&self, class: &str) -> bool {
122        self.names.iter().any(|current| current == class)
123    }
124}
125
126#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
127pub struct DirectionalLight {
128    pub color: [f32; 3],
129    pub illuminance: f32,
130    pub shadows: bool,
131}
132
133impl Default for DirectionalLight {
134    fn default() -> Self {
135        Self {
136            color: [1.0; 3],
137            illuminance: 100_000.0,
138            shadows: true,
139        }
140    }
141}
142
143#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
144pub struct PointLight {
145    pub color: [f32; 3],
146    pub intensity: f32,
147    pub range: f32,
148}
149
150#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
151pub struct SpotLight {
152    pub color: [f32; 3],
153    pub intensity: f32,
154    pub range: f32,
155    /// Fully illuminated cone angle in radians.
156    pub inner_angle: f32,
157    /// Outer cone angle in radians where illumination reaches zero.
158    pub outer_angle: f32,
159}
160
161impl Default for SpotLight {
162    fn default() -> Self {
163        Self {
164            color: [1.0; 3],
165            intensity: 1_000.0,
166            range: 10.0,
167            inner_angle: 20.0_f32.to_radians(),
168            outer_angle: 35.0_f32.to_radians(),
169        }
170    }
171}
172
173impl Default for PointLight {
174    fn default() -> Self {
175        Self {
176            color: [1.0; 3],
177            intensity: 1_000.0,
178            range: 10.0,
179        }
180    }
181}
182
183#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
184pub struct AmbientLight {
185    pub color: [f32; 3],
186    pub intensity: f32,
187}
188
189impl Default for AmbientLight {
190    fn default() -> Self {
191        Self {
192            color: [1.0; 3],
193            intensity: 0.1,
194        }
195    }
196}
197
198/// Hemisphere environment light: surfaces facing +Y see `sky_color`,
199/// surfaces facing -Y see `ground_color`, and the two blend in between.
200/// Adds to any [`AmbientLight`].
201#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
202pub struct SkyLight {
203    pub sky_color: [f32; 3],
204    pub ground_color: [f32; 3],
205    pub intensity: f32,
206}
207
208impl Default for SkyLight {
209    fn default() -> Self {
210        Self {
211            sky_color: [0.6, 0.75, 1.0],
212            ground_color: [0.3, 0.25, 0.2],
213            intensity: 0.3,
214        }
215    }
216}
217
218/// Curve that maps HDR scene color into the displayable 0..1 range.
219#[derive(
220    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
221)]
222pub enum ToneMapper {
223    /// Clips at 1, like Godot's default. Leaves values below 1 unchanged.
224    #[default]
225    Linear,
226    /// `c / (1 + c)`: never clips, compresses highlights softly.
227    Reinhard,
228    /// Filmic ACES curve (Narkowicz fit): more contrast, saturated mids.
229    Aces,
230}
231
232/// Exposure and tone mapping applied to the lit scene before display, like
233/// the tonemap settings of Godot's `Environment`. The first one found in the
234/// world is used; without one the scene uses `Linear` at exposure 1.
235#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
236pub struct ToneMapping {
237    pub mapper: ToneMapper,
238    /// Scene color is multiplied by this before the curve.
239    pub exposure: f32,
240}
241
242impl Default for ToneMapping {
243    fn default() -> Self {
244        Self {
245            mapper: ToneMapper::Linear,
246            exposure: 1.0,
247        }
248    }
249}
250
251/// Render-only bounds used for visibility, separate from the physics
252/// `Collider`. Stored in the entity's local space; render extraction
253/// transforms them into world space every time the entity is extracted.
254#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
255pub enum RenderBounds {
256    Sphere { center: [f32; 3], radius: f32 },
257    Aabb { min: [f32; 3], max: [f32; 3] },
258}
259
260/// The built-in unit cube's box.
261impl Default for RenderBounds {
262    fn default() -> Self {
263        RenderBounds::Aabb {
264            min: [-0.5; 3],
265            max: [0.5; 3],
266        }
267    }
268}
269
270impl RenderBounds {
271    /// Returns the bounds of this volume after `matrix` (a column-major
272    /// `GlobalTransform` matrix). A sphere stays a sphere whose radius grows
273    /// by the largest axis scale; a box becomes the axis-aligned box around
274    /// its transformed corners, so both stay conservative under rotation and
275    /// non-uniform scale.
276    pub fn transformed(&self, matrix: &[[f32; 4]; 4]) -> RenderBounds {
277        let matrix = nalgebra::Matrix4::from(*matrix);
278        let linear = matrix.fixed_view::<3, 3>(0, 0);
279        let translation = matrix.fixed_view::<3, 1>(0, 3);
280        match *self {
281            RenderBounds::Sphere { center, radius } => {
282                let scale = (0..3)
283                    .map(|axis| linear.column(axis).norm())
284                    .fold(0.0_f32, f32::max);
285                let center =
286                    linear * nalgebra::Vector3::from(center) + translation;
287                RenderBounds::Sphere {
288                    center: center.into(),
289                    radius: radius * scale,
290                }
291            }
292            RenderBounds::Aabb { min, max } => {
293                // Arvo's method: each output axis takes the smaller and the
294                // larger product per input axis.
295                let mut world_min: [f32; 3] = translation.into();
296                let mut world_max = world_min;
297                for row in 0..3 {
298                    for column in 0..3 {
299                        let a = linear[(row, column)] * min[column];
300                        let b = linear[(row, column)] * max[column];
301                        world_min[row] += a.min(b);
302                        world_max[row] += a.max(b);
303                    }
304                }
305                RenderBounds::Aabb {
306                    min: world_min,
307                    max: world_max,
308                }
309            }
310        }
311    }
312}
313
314#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
315pub struct Visibility {
316    pub visible: bool,
317}
318
319impl Default for Visibility {
320    fn default() -> Self {
321        Self { visible: true }
322    }
323}
324
325#[derive(
326    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
327)]
328pub enum QualityProfile {
329    Auto,
330    Eco,
331    #[default]
332    Balanced,
333    High,
334}
335
336/// How the renderer skips objects outside the view.
337#[derive(
338    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
339)]
340pub enum CullingMode {
341    /// The renderer picks: small scenes draw everything, the rest cull by
342    /// frustum on the CPU or GPU.
343    #[default]
344    Auto,
345    /// Draw every visible object.
346    Disabled,
347    /// Skip objects whose world bounds lie outside the camera frustum.
348    Frustum,
349    /// Frustum culling plus GPU occlusion culling against a depth pyramid
350    /// of the objects visible last frame. Needs the GPU culling path, so it
351    /// always runs there, whatever the scene size.
352    FrustumAndOcclusion,
353}
354
355/// Multisample anti-aliasing. `Auto` follows the quality profile: off on
356/// `Eco`, the most samples the device offers (up to 4) otherwise. A count
357/// the device lacks falls back to the next lower one.
358#[derive(
359    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
360)]
361pub enum Antialiasing {
362    #[default]
363    Auto,
364    Off,
365    Msaa2,
366    Msaa4,
367}
368
369/// Shadow map resolution and reach. `Auto` follows the quality profile.
370#[derive(
371    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
372)]
373pub enum ShadowQuality {
374    #[default]
375    Auto,
376    /// 1024 px map, 30 m reach.
377    Low,
378    /// 2048 px map, 50 m reach.
379    Medium,
380    /// 4096 px map, 80 m reach.
381    High,
382}
383
384#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
385pub struct RenderSettings {
386    pub quality: QualityProfile,
387    pub vsync: bool,
388    pub limit_fps: bool,
389    pub max_fps: u32,
390    pub render_scale: f32,
391    /// RGBA color used to clear the game render target before drawing.
392    pub background_color: [f32; 4],
393    pub culling: CullingMode,
394    pub antialiasing: Antialiasing,
395    pub shadows: ShadowQuality,
396}
397
398impl Default for RenderSettings {
399    fn default() -> Self {
400        Self {
401            quality: QualityProfile::Auto,
402            vsync: false,
403            limit_fps: false,
404            max_fps: 120,
405            render_scale: 1.0,
406            background_color: [0.025, 0.04, 0.07, 1.0],
407            culling: CullingMode::Auto,
408            antialiasing: Antialiasing::Auto,
409            shadows: ShadowQuality::Auto,
410        }
411    }
412}
413
414#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
415pub struct PhysicsSettings {
416    pub gravity: [f32; 3],
417    pub enabled: bool,
418}
419
420/// Reports which physics backends are connected to the ECS scene runner.
421/// The compatibility engine facade has its own legacy GPU path and does not
422/// use this resource.
423#[derive(
424    bevy_ecs::prelude::Resource, Clone, Copy, Debug, Default, PartialEq, Eq,
425)]
426pub struct PhysicsBackendStatus {
427    pub gameplay_available: bool,
428    pub gpu_dynamic_available: bool,
429}
430
431impl Default for PhysicsSettings {
432    fn default() -> Self {
433        Self {
434            gravity: [0.0, -9.81, 0.0],
435            enabled: true,
436        }
437    }
438}
439
440/// Says where the newest runtime physics state of an entity lives.
441#[derive(
442    Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
443)]
444pub enum SimulationClass {
445    /// No simulation; the body is ignored by every solver.
446    None,
447    /// Never moves; a collider for both the CPU and the GPU solvers.
448    Static,
449    /// Simulated on the CPU, so gameplay reads current state directly.
450    #[default]
451    #[serde(alias = "Gameplay")]
452    Cpu,
453    /// Simulated on the GPU; the CPU sees events and selected readbacks.
454    #[serde(alias = "GpuDynamic")]
455    Gpu,
456}
457
458#[allow(non_upper_case_globals)]
459impl SimulationClass {
460    #[deprecated(note = "renamed to `SimulationClass::Cpu`")]
461    pub const Gameplay: Self = Self::Cpu;
462    #[deprecated(note = "renamed to `SimulationClass::Gpu`")]
463    pub const GpuDynamic: Self = Self::Gpu;
464}
465
466/// Built-in GPU compute profile, or a project-provided compute shader.
467#[derive(
468    Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
469)]
470pub enum PhysicsSolver {
471    #[default]
472    Full,
473    Simplified,
474    NoCollision,
475    Space,
476    Custom,
477}
478
479/// Semantic physics configuration authored by the editor.
480///
481/// Static and disabled bodies are deliberately excluded from dynamic compute
482/// dispatches. Custom shader paths are project-relative and validated by the
483/// editor before they are saved.
484#[derive(Component, Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
485pub struct PhysicsBody {
486    pub simulation: SimulationClass,
487    pub solver: PhysicsSolver,
488    pub custom_shader: Option<String>,
489}
490
491impl Default for PhysicsBody {
492    fn default() -> Self {
493        Self {
494            simulation: SimulationClass::Cpu,
495            solver: PhysicsSolver::Full,
496            custom_shader: None,
497        }
498    }
499}
500
501impl PhysicsBody {
502    #[must_use]
503    pub fn participates_in_dynamic_simulation(&self) -> bool {
504        matches!(self.simulation, SimulationClass::Cpu | SimulationClass::Gpu)
505    }
506
507    #[must_use]
508    pub fn uses_gpu(&self) -> bool {
509        self.simulation == SimulationClass::Gpu
510    }
511}
512
513#[derive(
514    Component,
515    Clone,
516    Copy,
517    Debug,
518    Default,
519    Deserialize,
520    PartialEq,
521    Eq,
522    Serialize,
523)]
524pub enum RigidBodyKind {
525    Fixed,
526    #[default]
527    Dynamic,
528    Kinematic,
529}
530
531#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
532pub struct RigidBody {
533    pub kind: RigidBodyKind,
534    pub mass: f32,
535    pub linear_velocity: [f32; 3],
536    pub angular_velocity: [f32; 3],
537    pub gravity_scale: f32,
538}
539
540impl Default for RigidBody {
541    fn default() -> Self {
542        Self {
543            kind: RigidBodyKind::Dynamic,
544            mass: 1.0,
545            linear_velocity: [0.0; 3],
546            angular_velocity: [0.0; 3],
547            gravity_scale: 1.0,
548        }
549    }
550}
551
552#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
553pub enum ColliderShape {
554    Box {
555        half_extents: [f32; 3],
556    },
557    Sphere {
558        radius: f32,
559    },
560    Capsule {
561        half_height: f32,
562        radius: f32,
563    },
564    /// The convex hull of the entity's `MeshRenderer` mesh, scaled by its
565    /// transform. Dynamic bodies may use it.
566    ConvexMesh,
567    /// The triangles of the entity's `MeshRenderer` mesh, scaled by its
568    /// transform. Static only: a body with it never moves.
569    TriangleMesh,
570}
571
572#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
573pub struct Collider {
574    pub shape: ColliderShape,
575    pub friction: f32,
576    pub restitution: f32,
577    pub sensor: bool,
578}
579
580impl Default for Collider {
581    fn default() -> Self {
582        Self {
583            shape: ColliderShape::Box {
584                half_extents: [0.5; 3],
585            },
586            friction: 0.5,
587            restitution: 0.0,
588            sensor: false,
589        }
590    }
591}
592
593#[derive(
594    Component, Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize,
595)]
596pub struct CollisionLayers {
597    pub memberships: u32,
598    pub filters: u32,
599}
600
601impl Default for CollisionLayers {
602    fn default() -> Self {
603        Self {
604            memberships: u32::MAX,
605            filters: u32::MAX,
606        }
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use super::*;
613    use bevy_ecs::{component::Component, resource::Resource};
614
615    fn assert_component<T: Component>() {}
616    fn assert_resource<T: Resource>() {}
617
618    #[test]
619    fn canonical_types_implement_bevy_ecs_traits() {
620        assert_component::<SceneId>();
621        assert_component::<GlobalTransform>();
622        assert_component::<Parent>();
623        assert_component::<Children>();
624        assert_component::<Camera>();
625        assert_component::<Name>();
626        assert_component::<ObjectClasses>();
627        assert_component::<DirectionalLight>();
628        assert_component::<PointLight>();
629        assert_component::<SpotLight>();
630        assert_component::<AmbientLight>();
631        assert_component::<SkyLight>();
632        assert_component::<ToneMapping>();
633        assert_component::<RenderBounds>();
634        assert_component::<Visibility>();
635        assert_component::<PhysicsBody>();
636        assert_component::<RigidBodyKind>();
637        assert_component::<RigidBody>();
638        assert_component::<Collider>();
639        assert_component::<CollisionLayers>();
640
641        assert_resource::<RenderSettings>();
642        assert_resource::<PhysicsSettings>();
643        assert_resource::<PhysicsBackendStatus>();
644    }
645
646    #[test]
647    fn defaults_are_ready_for_a_basic_scene() {
648        let identity: [[f32; 4]; 4] =
649            nalgebra::Matrix4::<f32>::identity().into();
650        assert_eq!(GlobalTransform::default().matrix, identity);
651        assert!(Visibility::default().visible);
652        assert_eq!(RigidBody::default().mass, 1.0);
653        assert_eq!(PhysicsSettings::default().gravity, [0.0, -9.81, 0.0]);
654        assert_eq!(CollisionLayers::default().memberships, u32::MAX);
655        assert_eq!(RenderSettings::default().quality, QualityProfile::Auto);
656    }
657
658    #[test]
659    fn render_bounds_stay_conservative_under_transforms() {
660        use nalgebra::{Matrix4, Rotation3, Vector3};
661        let matrix: [[f32; 4]; 4] =
662            (Matrix4::new_translation(&Vector3::new(10.0, 0.0, 0.0))
663                * Rotation3::from_axis_angle(
664                    &Vector3::z_axis(),
665                    std::f32::consts::FRAC_PI_4,
666                )
667                .to_homogeneous()
668                * Matrix4::new_nonuniform_scaling(&Vector3::new(
669                    2.0, 1.0, 3.0,
670                )))
671            .into();
672        let RenderBounds::Sphere { center, radius } = (RenderBounds::Sphere {
673            center: [1.0, 0.0, 0.0],
674            radius: 1.0,
675        })
676        .transformed(&matrix) else {
677            panic!("a sphere stays a sphere");
678        };
679        let half = std::f32::consts::FRAC_1_SQRT_2;
680        let expected = [10.0 + 2.0 * half, 2.0 * half, 0.0];
681        for (value, expected) in center.iter().zip(expected) {
682            assert!((value - expected).abs() < 1e-5, "{center:?}");
683        }
684        assert!((radius - 3.0).abs() < 1e-5, "largest axis scale");
685
686        let RenderBounds::Aabb { min, max } = (RenderBounds::Aabb {
687            min: [-1.0; 3],
688            max: [1.0; 3],
689        })
690        .transformed(&matrix) else {
691            panic!("a box stays a box");
692        };
693        // The 2x1 face rotated 45 degrees spans (2 + 1) / sqrt(2) on x and
694        // y; z only scales.
695        let reach = 3.0 * half;
696        let expected_min = [10.0 - reach, -reach, -3.0];
697        let expected_max = [10.0 + reach, reach, 3.0];
698        for axis in 0..3 {
699            assert!((min[axis] - expected_min[axis]).abs() < 1e-5, "{min:?}");
700            assert!((max[axis] - expected_max[axis]).abs() < 1e-5, "{max:?}");
701        }
702    }
703
704    #[test]
705    fn object_classes_clean_and_edit_names() {
706        let mut classes =
707            ObjectClasses::new([" gravity ", "", "gravity", "enemy"]);
708        assert_eq!(classes.names, ["gravity", "enemy"]);
709        assert!(classes.contains("gravity"));
710        assert!(!classes.add("enemy"));
711        assert!(classes.remove("enemy"));
712        assert!(!classes.contains("enemy"));
713    }
714
715    #[test]
716    fn physics_body_helpers_follow_simulation_class() {
717        let mut body = PhysicsBody::default();
718        assert!(body.participates_in_dynamic_simulation());
719        assert!(!body.uses_gpu());
720
721        body.simulation = SimulationClass::Gpu;
722        assert!(body.participates_in_dynamic_simulation());
723        assert!(body.uses_gpu());
724
725        body.simulation = SimulationClass::Static;
726        assert!(!body.participates_in_dynamic_simulation());
727        assert!(!body.uses_gpu());
728    }
729}