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#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
356pub struct RenderSettings {
357    pub quality: QualityProfile,
358    pub vsync: bool,
359    pub limit_fps: bool,
360    pub max_fps: u32,
361    pub render_scale: f32,
362    /// RGBA color used to clear the game render target before drawing.
363    pub background_color: [f32; 4],
364    pub culling: CullingMode,
365}
366
367impl Default for RenderSettings {
368    fn default() -> Self {
369        Self {
370            quality: QualityProfile::Auto,
371            vsync: false,
372            limit_fps: false,
373            max_fps: 120,
374            render_scale: 1.0,
375            background_color: [0.025, 0.04, 0.07, 1.0],
376            culling: CullingMode::Auto,
377        }
378    }
379}
380
381#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
382pub struct PhysicsSettings {
383    pub gravity: [f32; 3],
384    pub enabled: bool,
385}
386
387/// Reports which physics backends are connected to the ECS scene runner.
388/// The compatibility engine facade has its own legacy GPU path and does not
389/// use this resource.
390#[derive(
391    bevy_ecs::prelude::Resource, Clone, Copy, Debug, Default, PartialEq, Eq,
392)]
393pub struct PhysicsBackendStatus {
394    pub gameplay_available: bool,
395    pub gpu_dynamic_available: bool,
396}
397
398impl Default for PhysicsSettings {
399    fn default() -> Self {
400        Self {
401            gravity: [0.0, -9.81, 0.0],
402            enabled: true,
403        }
404    }
405}
406
407/// Says where the newest runtime physics state of an entity lives.
408#[derive(
409    Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
410)]
411pub enum SimulationClass {
412    /// No simulation; the body is ignored by every solver.
413    None,
414    /// Never moves; a collider for both the CPU and the GPU solvers.
415    Static,
416    /// Simulated on the CPU, so gameplay reads current state directly.
417    #[default]
418    #[serde(alias = "Gameplay")]
419    Cpu,
420    /// Simulated on the GPU; the CPU sees events and selected readbacks.
421    #[serde(alias = "GpuDynamic")]
422    Gpu,
423}
424
425#[allow(non_upper_case_globals)]
426impl SimulationClass {
427    #[deprecated(note = "renamed to `SimulationClass::Cpu`")]
428    pub const Gameplay: Self = Self::Cpu;
429    #[deprecated(note = "renamed to `SimulationClass::Gpu`")]
430    pub const GpuDynamic: Self = Self::Gpu;
431}
432
433/// Built-in GPU compute profile, or a project-provided compute shader.
434#[derive(
435    Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
436)]
437pub enum PhysicsSolver {
438    #[default]
439    Full,
440    Simplified,
441    NoCollision,
442    Space,
443    Custom,
444}
445
446/// Semantic physics configuration authored by the editor.
447///
448/// Static and disabled bodies are deliberately excluded from dynamic compute
449/// dispatches. Custom shader paths are project-relative and validated by the
450/// editor before they are saved.
451#[derive(Component, Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
452pub struct PhysicsBody {
453    pub simulation: SimulationClass,
454    pub solver: PhysicsSolver,
455    pub custom_shader: Option<String>,
456}
457
458impl Default for PhysicsBody {
459    fn default() -> Self {
460        Self {
461            simulation: SimulationClass::Cpu,
462            solver: PhysicsSolver::Full,
463            custom_shader: None,
464        }
465    }
466}
467
468impl PhysicsBody {
469    #[must_use]
470    pub fn participates_in_dynamic_simulation(&self) -> bool {
471        matches!(self.simulation, SimulationClass::Cpu | SimulationClass::Gpu)
472    }
473
474    #[must_use]
475    pub fn uses_gpu(&self) -> bool {
476        self.simulation == SimulationClass::Gpu
477    }
478}
479
480#[derive(
481    Component,
482    Clone,
483    Copy,
484    Debug,
485    Default,
486    Deserialize,
487    PartialEq,
488    Eq,
489    Serialize,
490)]
491pub enum RigidBodyKind {
492    Fixed,
493    #[default]
494    Dynamic,
495    Kinematic,
496}
497
498#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
499pub struct RigidBody {
500    pub kind: RigidBodyKind,
501    pub mass: f32,
502    pub linear_velocity: [f32; 3],
503    pub angular_velocity: [f32; 3],
504    pub gravity_scale: f32,
505}
506
507impl Default for RigidBody {
508    fn default() -> Self {
509        Self {
510            kind: RigidBodyKind::Dynamic,
511            mass: 1.0,
512            linear_velocity: [0.0; 3],
513            angular_velocity: [0.0; 3],
514            gravity_scale: 1.0,
515        }
516    }
517}
518
519#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
520pub enum ColliderShape {
521    Box {
522        half_extents: [f32; 3],
523    },
524    Sphere {
525        radius: f32,
526    },
527    Capsule {
528        half_height: f32,
529        radius: f32,
530    },
531    /// The convex hull of the entity's `MeshRenderer` mesh, scaled by its
532    /// transform. Dynamic bodies may use it.
533    ConvexMesh,
534    /// The triangles of the entity's `MeshRenderer` mesh, scaled by its
535    /// transform. Static only: a body with it never moves.
536    TriangleMesh,
537}
538
539#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
540pub struct Collider {
541    pub shape: ColliderShape,
542    pub friction: f32,
543    pub restitution: f32,
544    pub sensor: bool,
545}
546
547impl Default for Collider {
548    fn default() -> Self {
549        Self {
550            shape: ColliderShape::Box {
551                half_extents: [0.5; 3],
552            },
553            friction: 0.5,
554            restitution: 0.0,
555            sensor: false,
556        }
557    }
558}
559
560#[derive(
561    Component, Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize,
562)]
563pub struct CollisionLayers {
564    pub memberships: u32,
565    pub filters: u32,
566}
567
568impl Default for CollisionLayers {
569    fn default() -> Self {
570        Self {
571            memberships: u32::MAX,
572            filters: u32::MAX,
573        }
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580    use bevy_ecs::{component::Component, resource::Resource};
581
582    fn assert_component<T: Component>() {}
583    fn assert_resource<T: Resource>() {}
584
585    #[test]
586    fn canonical_types_implement_bevy_ecs_traits() {
587        assert_component::<SceneId>();
588        assert_component::<GlobalTransform>();
589        assert_component::<Parent>();
590        assert_component::<Children>();
591        assert_component::<Camera>();
592        assert_component::<Name>();
593        assert_component::<ObjectClasses>();
594        assert_component::<DirectionalLight>();
595        assert_component::<PointLight>();
596        assert_component::<SpotLight>();
597        assert_component::<AmbientLight>();
598        assert_component::<SkyLight>();
599        assert_component::<ToneMapping>();
600        assert_component::<RenderBounds>();
601        assert_component::<Visibility>();
602        assert_component::<PhysicsBody>();
603        assert_component::<RigidBodyKind>();
604        assert_component::<RigidBody>();
605        assert_component::<Collider>();
606        assert_component::<CollisionLayers>();
607
608        assert_resource::<RenderSettings>();
609        assert_resource::<PhysicsSettings>();
610        assert_resource::<PhysicsBackendStatus>();
611    }
612
613    #[test]
614    fn defaults_are_ready_for_a_basic_scene() {
615        let identity: [[f32; 4]; 4] =
616            nalgebra::Matrix4::<f32>::identity().into();
617        assert_eq!(GlobalTransform::default().matrix, identity);
618        assert!(Visibility::default().visible);
619        assert_eq!(RigidBody::default().mass, 1.0);
620        assert_eq!(PhysicsSettings::default().gravity, [0.0, -9.81, 0.0]);
621        assert_eq!(CollisionLayers::default().memberships, u32::MAX);
622        assert_eq!(RenderSettings::default().quality, QualityProfile::Auto);
623    }
624
625    #[test]
626    fn render_bounds_stay_conservative_under_transforms() {
627        use nalgebra::{Matrix4, Rotation3, Vector3};
628        let matrix: [[f32; 4]; 4] =
629            (Matrix4::new_translation(&Vector3::new(10.0, 0.0, 0.0))
630                * Rotation3::from_axis_angle(
631                    &Vector3::z_axis(),
632                    std::f32::consts::FRAC_PI_4,
633                )
634                .to_homogeneous()
635                * Matrix4::new_nonuniform_scaling(&Vector3::new(
636                    2.0, 1.0, 3.0,
637                )))
638            .into();
639        let RenderBounds::Sphere { center, radius } = (RenderBounds::Sphere {
640            center: [1.0, 0.0, 0.0],
641            radius: 1.0,
642        })
643        .transformed(&matrix) else {
644            panic!("a sphere stays a sphere");
645        };
646        let half = std::f32::consts::FRAC_1_SQRT_2;
647        let expected = [10.0 + 2.0 * half, 2.0 * half, 0.0];
648        for (value, expected) in center.iter().zip(expected) {
649            assert!((value - expected).abs() < 1e-5, "{center:?}");
650        }
651        assert!((radius - 3.0).abs() < 1e-5, "largest axis scale");
652
653        let RenderBounds::Aabb { min, max } = (RenderBounds::Aabb {
654            min: [-1.0; 3],
655            max: [1.0; 3],
656        })
657        .transformed(&matrix) else {
658            panic!("a box stays a box");
659        };
660        // The 2x1 face rotated 45 degrees spans (2 + 1) / sqrt(2) on x and
661        // y; z only scales.
662        let reach = 3.0 * half;
663        let expected_min = [10.0 - reach, -reach, -3.0];
664        let expected_max = [10.0 + reach, reach, 3.0];
665        for axis in 0..3 {
666            assert!((min[axis] - expected_min[axis]).abs() < 1e-5, "{min:?}");
667            assert!((max[axis] - expected_max[axis]).abs() < 1e-5, "{max:?}");
668        }
669    }
670
671    #[test]
672    fn object_classes_clean_and_edit_names() {
673        let mut classes =
674            ObjectClasses::new([" gravity ", "", "gravity", "enemy"]);
675        assert_eq!(classes.names, ["gravity", "enemy"]);
676        assert!(classes.contains("gravity"));
677        assert!(!classes.add("enemy"));
678        assert!(classes.remove("enemy"));
679        assert!(!classes.contains("enemy"));
680    }
681
682    #[test]
683    fn physics_body_helpers_follow_simulation_class() {
684        let mut body = PhysicsBody::default();
685        assert!(body.participates_in_dynamic_simulation());
686        assert!(!body.uses_gpu());
687
688        body.simulation = SimulationClass::Gpu;
689        assert!(body.participates_in_dynamic_simulation());
690        assert!(body.uses_gpu());
691
692        body.simulation = SimulationClass::Static;
693        assert!(!body.participates_in_dynamic_simulation());
694        assert!(!body.uses_gpu());
695    }
696}