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    /// Part of the window this camera draws into, as fractions
74    /// `[x, y, width, height]` from the top-left corner. `None` fills the
75    /// window.
76    pub viewport: Option<[f32; 4]>,
77}
78
79#[derive(Component, Clone, Debug, PartialEq, Eq)]
80pub struct Name(pub String);
81
82impl Name {
83    #[must_use]
84    pub fn as_str(&self) -> &str {
85        &self.0
86    }
87}
88
89impl std::ops::Deref for Name {
90    type Target = str;
91
92    fn deref(&self) -> &str {
93        &self.0
94    }
95}
96
97/// Reusable classes assigned to one scene object.
98///
99/// Names identify one object. Classes select any number of objects, and one
100/// object can belong to several classes at the same time.
101#[derive(
102    Component, Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
103)]
104pub struct ObjectClasses {
105    /// Class names such as `gravity`, `enemy`, or `falling_cubes`.
106    pub names: Vec<String>,
107}
108
109impl ObjectClasses {
110    /// Creates a clean class list without empty or repeated names.
111    #[must_use]
112    pub fn new(classes: impl IntoIterator<Item = impl Into<String>>) -> Self {
113        let mut result = Self::default();
114        for class in classes {
115            result.add(class);
116        }
117        result
118    }
119
120    /// Adds a class if this object does not already have it.
121    pub fn add(&mut self, class: impl Into<String>) -> bool {
122        let class = class.into();
123        let class = class.trim();
124        if class.is_empty() || self.contains(class) {
125            return false;
126        }
127        self.names.push(class.to_owned());
128        true
129    }
130
131    /// Removes a class from this object.
132    pub fn remove(&mut self, class: &str) -> bool {
133        let old_len = self.names.len();
134        self.names.retain(|current| current != class);
135        self.names.len() != old_len
136    }
137
138    /// Returns true when this object belongs to the requested class.
139    #[must_use]
140    pub fn contains(&self, class: &str) -> bool {
141        self.names.iter().any(|current| current == class)
142    }
143}
144
145#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
146pub struct DirectionalLight {
147    pub color: [f32; 3],
148    pub illuminance: f32,
149    pub shadows: bool,
150}
151
152impl DirectionalLight {
153    /// Illuminance that lights a white surface facing the light at 1 before
154    /// exposure, like a point light of 1000 up close or ambient intensity 1.
155    pub const LUX_PER_UNIT: f32 = 100_000.0;
156}
157
158impl Default for DirectionalLight {
159    fn default() -> Self {
160        Self {
161            color: [1.0; 3],
162            illuminance: 100_000.0,
163            shadows: true,
164        }
165    }
166}
167
168#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
169pub struct PointLight {
170    pub color: [f32; 3],
171    pub intensity: f32,
172    pub range: f32,
173    /// Casts shadows through six cube faces of the shadow map. Only when
174    /// no directional or spot light in the frame casts shadows.
175    #[serde(default)]
176    pub shadows: bool,
177    /// Radius in metres of the glowing sphere. A larger source gives
178    /// wider, softer highlights on shiny surfaces; 0 is a point.
179    #[serde(default)]
180    pub radius: f32,
181}
182
183#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
184pub struct SpotLight {
185    pub color: [f32; 3],
186    pub intensity: f32,
187    pub range: f32,
188    /// Fully illuminated cone angle in radians.
189    pub inner_angle: f32,
190    /// Outer cone angle in radians where illumination reaches zero.
191    pub outer_angle: f32,
192    /// Casts shadows through one shadow map. A frame has one shadowed
193    /// light: a directional light with shadows wins over spot lights.
194    #[serde(default)]
195    pub shadows: bool,
196    /// Radius in metres of the glowing sphere. A larger source gives
197    /// wider, softer highlights on shiny surfaces; 0 is a point.
198    #[serde(default)]
199    pub radius: f32,
200}
201
202impl Default for SpotLight {
203    fn default() -> Self {
204        Self {
205            color: [1.0; 3],
206            intensity: 1_000.0,
207            range: 10.0,
208            inner_angle: 20.0_f32.to_radians(),
209            outer_angle: 35.0_f32.to_radians(),
210            shadows: false,
211            radius: 0.0,
212        }
213    }
214}
215
216impl Default for PointLight {
217    fn default() -> Self {
218        Self {
219            color: [1.0; 3],
220            intensity: 1_000.0,
221            range: 10.0,
222            shadows: false,
223            radius: 0.0,
224        }
225    }
226}
227
228#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
229pub struct AmbientLight {
230    pub color: [f32; 3],
231    pub intensity: f32,
232}
233
234impl Default for AmbientLight {
235    fn default() -> Self {
236        Self {
237            color: [1.0; 3],
238            intensity: 0.1,
239        }
240    }
241}
242
243/// Hemisphere environment light: surfaces facing +Y see `sky_color`,
244/// surfaces facing -Y see `ground_color`, and the two blend in between.
245/// Adds to any [`AmbientLight`].
246#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
247pub struct SkyLight {
248    pub sky_color: [f32; 3],
249    pub ground_color: [f32; 3],
250    pub intensity: f32,
251}
252
253impl Default for SkyLight {
254    fn default() -> Self {
255        Self {
256            sky_color: [0.6, 0.75, 1.0],
257            ground_color: [0.3, 0.25, 0.2],
258            intensity: 0.3,
259        }
260    }
261}
262
263/// Curve that maps HDR scene color into the displayable 0..1 range.
264#[derive(
265    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
266)]
267pub enum ToneMapper {
268    /// Clips at 1, like Godot's default. Leaves values below 1 unchanged.
269    #[default]
270    Linear,
271    /// `c / (1 + c)`: never clips, compresses highlights softly.
272    Reinhard,
273    /// Filmic ACES curve (Narkowicz fit): more contrast, saturated mids.
274    Aces,
275}
276
277/// Exposure and tone mapping applied to the lit scene before display, like
278/// the tonemap settings of Godot's `Environment`. The first one found in the
279/// world is used; without one the scene uses `Linear` at exposure 1.
280#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
281pub struct ToneMapping {
282    pub mapper: ToneMapper,
283    /// Scene color is multiplied by this before the curve.
284    pub exposure: f32,
285}
286
287impl Default for ToneMapping {
288    fn default() -> Self {
289        Self {
290            mapper: ToneMapper::Linear,
291            exposure: 1.0,
292        }
293    }
294}
295
296/// Render-only bounds used for visibility, separate from the physics
297/// `Collider`. Stored in the entity's local space; render extraction
298/// transforms them into world space every time the entity is extracted.
299#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
300pub enum RenderBounds {
301    Sphere { center: [f32; 3], radius: f32 },
302    Aabb { min: [f32; 3], max: [f32; 3] },
303}
304
305/// The built-in unit cube's box.
306impl Default for RenderBounds {
307    fn default() -> Self {
308        RenderBounds::Aabb {
309            min: [-0.5; 3],
310            max: [0.5; 3],
311        }
312    }
313}
314
315impl RenderBounds {
316    /// Returns the bounds of this volume after `matrix` (a column-major
317    /// `GlobalTransform` matrix). A sphere stays a sphere whose radius grows
318    /// by the largest axis scale; a box becomes the axis-aligned box around
319    /// its transformed corners, so both stay conservative under rotation and
320    /// non-uniform scale.
321    pub fn transformed(&self, matrix: &[[f32; 4]; 4]) -> RenderBounds {
322        let matrix = nalgebra::Matrix4::from(*matrix);
323        let linear = matrix.fixed_view::<3, 3>(0, 0);
324        let translation = matrix.fixed_view::<3, 1>(0, 3);
325        match *self {
326            RenderBounds::Sphere { center, radius } => {
327                let scale = (0..3)
328                    .map(|axis| linear.column(axis).norm())
329                    .fold(0.0_f32, f32::max);
330                let center =
331                    linear * nalgebra::Vector3::from(center) + translation;
332                RenderBounds::Sphere {
333                    center: center.into(),
334                    radius: radius * scale,
335                }
336            }
337            RenderBounds::Aabb { min, max } => {
338                // Arvo's method: each output axis takes the smaller and the
339                // larger product per input axis.
340                let mut world_min: [f32; 3] = translation.into();
341                let mut world_max = world_min;
342                for row in 0..3 {
343                    for column in 0..3 {
344                        let a = linear[(row, column)] * min[column];
345                        let b = linear[(row, column)] * max[column];
346                        world_min[row] += a.min(b);
347                        world_max[row] += a.max(b);
348                    }
349                }
350                RenderBounds::Aabb {
351                    min: world_min,
352                    max: world_max,
353                }
354            }
355        }
356    }
357}
358
359#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
360pub struct Visibility {
361    pub visible: bool,
362}
363
364impl Default for Visibility {
365    fn default() -> Self {
366        Self { visible: true }
367    }
368}
369
370#[derive(
371    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
372)]
373pub enum QualityProfile {
374    Auto,
375    Eco,
376    #[default]
377    Balanced,
378    High,
379}
380
381/// How the renderer skips objects outside the view.
382#[derive(
383    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
384)]
385pub enum CullingMode {
386    /// The renderer picks: small scenes draw everything, the rest cull by
387    /// frustum on the CPU or GPU.
388    #[default]
389    Auto,
390    /// Draw every visible object.
391    Disabled,
392    /// Skip objects whose world bounds lie outside the camera frustum.
393    Frustum,
394    /// Frustum culling plus GPU occlusion culling against a depth pyramid
395    /// of the objects visible last frame. Needs the GPU culling path, so it
396    /// always runs there, whatever the scene size.
397    FrustumAndOcclusion,
398}
399
400/// Anti-aliasing. `Auto` follows the quality profile: off on `Eco`, the
401/// most multisamples the device offers (up to 4) otherwise. A count the
402/// device lacks falls back to the next lower one. `Fxaa` renders one sample
403/// and smooths edges found in the final image instead: cheaper than MSAA,
404/// also smooths edges inside textures and alpha-cut leaves, a little softer.
405/// `Taa` renders one sample from a slightly different spot each frame and
406/// blends the frames: the smoothest edges, with some blur on fast motion.
407#[derive(
408    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
409)]
410pub enum Antialiasing {
411    #[default]
412    Auto,
413    Off,
414    Msaa2,
415    Msaa4,
416    Fxaa,
417    Taa,
418}
419
420/// Shadow map resolution, reach and sun cascades. `Auto` follows the
421/// quality profile.
422#[derive(
423    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
424)]
425pub enum ShadowQuality {
426    #[default]
427    Auto,
428    /// 1024 px map, 30 m reach, 2 cascades.
429    Low,
430    /// 2048 px map, 50 m reach, 3 cascades.
431    Medium,
432    /// 4096 px map, 80 m reach, 4 cascades.
433    High,
434}
435
436#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
437pub struct RenderSettings {
438    pub quality: QualityProfile,
439    pub vsync: bool,
440    pub limit_fps: bool,
441    pub max_fps: u32,
442    /// Fraction of the target size the 3D scene renders at, 0.25 to 2.0.
443    /// The frame is stretched over the target; UI stays at full resolution.
444    pub render_scale: f32,
445    /// Stretch a scaled frame with nearest-neighbour filtering, so a low
446    /// `render_scale` shows square pixels instead of blur.
447    pub pixelated: bool,
448    /// Above 0, a `render_scale` below 1 is stretched with an
449    /// edge-preserving filter and contrast-adaptive sharpening of this
450    /// strength (up to 1), like FSR 1, instead of a plain linear stretch.
451    pub upscale_sharpness: f32,
452    /// RGBA color used to clear the game render target before drawing.
453    pub background_color: [f32; 4],
454    pub culling: CullingMode,
455    pub antialiasing: Antialiasing,
456    pub shadows: ShadowQuality,
457    /// One shadow-map tap per pixel instead of 3x3 filtering: crisp,
458    /// stair-stepped shadow edges for a low-poly look.
459    pub hard_shadows: bool,
460    /// Metres of view the sun's shadow covers, overriding the reach of
461    /// `shadows`; 0 keeps that reach. The shadow fades out over the last
462    /// fifth of it. Farther spreads the same map over more ground.
463    pub shadow_distance: f32,
464    /// Sun shadow cascades, 1 to 4, overriding the count of `shadows`; 0
465    /// keeps that count. More cascades keep near shadows sharp when
466    /// `shadow_distance` is long, at the cost of drawing the casters again.
467    pub shadow_cascades: u32,
468    /// Screen-space reflections and refraction of the opaque scene. Off
469    /// skips the scene copy, mip chain and depth pyramid.
470    pub reflections: bool,
471    /// Largest texture side uploaded to the GPU, in pixels; 0 uploads
472    /// textures at full size. A larger texture is halved until it fits, so
473    /// 1024 loads only the 1K level of 2K textures on a low-memory GPU.
474    pub max_texture_size: u32,
475}
476
477impl Default for RenderSettings {
478    fn default() -> Self {
479        Self {
480            quality: QualityProfile::Auto,
481            vsync: false,
482            limit_fps: false,
483            max_fps: 120,
484            render_scale: 1.0,
485            pixelated: false,
486            upscale_sharpness: 0.0,
487            background_color: [0.025, 0.04, 0.07, 1.0],
488            culling: CullingMode::Auto,
489            antialiasing: Antialiasing::Auto,
490            shadows: ShadowQuality::Auto,
491            hard_shadows: false,
492            shadow_distance: 0.0,
493            shadow_cascades: 0,
494            reflections: true,
495            max_texture_size: 0,
496        }
497    }
498}
499
500/// Freezes a dynamic body's motion along world axes, like Godot's axis
501/// locks. A 2D body in the XY plane locks linear z and angular x and y.
502#[derive(
503    Component,
504    Clone,
505    Copy,
506    Debug,
507    Default,
508    PartialEq,
509    Eq,
510    Serialize,
511    Deserialize,
512)]
513#[serde(default)]
514pub struct AxisLock {
515    /// No movement along world x, y, z.
516    pub linear: [bool; 3],
517    /// No turning around world x, y, z.
518    pub angular: [bool; 3],
519}
520
521impl AxisLock {
522    /// The XY-plane lock of a 2D body.
523    pub const PLANE_XY: Self = Self {
524        linear: [false, false, true],
525        angular: [true, true, false],
526    };
527
528    /// Bits 0 to 2 lock linear x, y, z and bits 3 to 5 angular x, y, z.
529    #[must_use]
530    pub fn mask(&self) -> u32 {
531        self.linear
532            .iter()
533            .chain(&self.angular)
534            .enumerate()
535            .map(|(bit, &locked)| u32::from(locked) << bit)
536            .sum()
537    }
538}
539
540#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
541pub struct PhysicsSettings {
542    pub gravity: [f32; 3],
543    pub enabled: bool,
544    /// Loose dynamic CPU bodies below this height are despawned and send
545    /// `FellOut`; `None` keeps them falling.
546    pub kill_y: Option<f32>,
547    /// CPU solver substeps per fixed step. More substeps hold long joint
548    /// chains and heavy-on-light stacks tighter, at that many times the
549    /// solver cost.
550    pub substeps: u32,
551    /// Axis locks every GPU body shares; [`AxisLock::PLANE_XY`] keeps a 2D
552    /// game's GPU bodies in its plane. CPU bodies take their own
553    /// `rusting.axis_lock` instead.
554    pub gpu_locks: AxisLock,
555}
556
557/// Reports which physics backends are connected to the ECS scene runner.
558/// The compatibility engine facade has its own legacy GPU path and does not
559/// use this resource.
560#[derive(
561    bevy_ecs::prelude::Resource, Clone, Copy, Debug, Default, PartialEq, Eq,
562)]
563pub struct PhysicsBackendStatus {
564    pub gameplay_available: bool,
565    pub gpu_dynamic_available: bool,
566}
567
568impl Default for PhysicsSettings {
569    fn default() -> Self {
570        Self {
571            gravity: [0.0, -9.81, 0.0],
572            enabled: true,
573            kill_y: None,
574            substeps: 1,
575            gpu_locks: AxisLock::default(),
576        }
577    }
578}
579
580/// Says where the newest runtime physics state of an entity lives.
581#[derive(
582    Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
583)]
584pub enum SimulationClass {
585    /// No simulation; the body is ignored by every solver.
586    None,
587    /// Never moves; a collider for both the CPU and the GPU solvers.
588    Static,
589    /// Simulated on the CPU, so gameplay reads current state directly.
590    #[default]
591    #[serde(alias = "Gameplay")]
592    Cpu,
593    /// Simulated on the GPU; the CPU sees events and selected readbacks.
594    #[serde(alias = "GpuDynamic")]
595    Gpu,
596}
597
598#[allow(non_upper_case_globals)]
599impl SimulationClass {
600    #[deprecated(note = "renamed to `SimulationClass::Cpu`")]
601    pub const Gameplay: Self = Self::Cpu;
602    #[deprecated(note = "renamed to `SimulationClass::Gpu`")]
603    pub const GpuDynamic: Self = Self::Gpu;
604}
605
606/// Built-in GPU compute profile, or a project-provided compute shader.
607#[derive(
608    Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
609)]
610pub enum PhysicsSolver {
611    #[default]
612    Full,
613    Simplified,
614    NoCollision,
615    Space,
616    Custom,
617}
618
619/// Semantic physics configuration authored by the editor.
620///
621/// Static and disabled bodies are deliberately excluded from dynamic compute
622/// dispatches. Custom shader paths are project-relative and validated by the
623/// editor before they are saved.
624#[derive(Component, Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
625pub struct PhysicsBody {
626    pub simulation: SimulationClass,
627    pub solver: PhysicsSolver,
628    pub custom_shader: Option<String>,
629}
630
631impl Default for PhysicsBody {
632    fn default() -> Self {
633        Self {
634            simulation: SimulationClass::Cpu,
635            solver: PhysicsSolver::Full,
636            custom_shader: None,
637        }
638    }
639}
640
641impl PhysicsBody {
642    #[must_use]
643    pub fn participates_in_dynamic_simulation(&self) -> bool {
644        matches!(self.simulation, SimulationClass::Cpu | SimulationClass::Gpu)
645    }
646
647    #[must_use]
648    pub fn uses_gpu(&self) -> bool {
649        self.simulation == SimulationClass::Gpu
650    }
651}
652
653#[derive(
654    Component,
655    Clone,
656    Copy,
657    Debug,
658    Default,
659    Deserialize,
660    PartialEq,
661    Eq,
662    Serialize,
663)]
664pub enum RigidBodyKind {
665    Fixed,
666    #[default]
667    Dynamic,
668    Kinematic,
669}
670
671#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
672pub struct RigidBody {
673    pub kind: RigidBodyKind,
674    pub mass: f32,
675    pub linear_velocity: [f32; 3],
676    pub angular_velocity: [f32; 3],
677    pub gravity_scale: f32,
678}
679
680impl Default for RigidBody {
681    fn default() -> Self {
682        Self {
683            kind: RigidBodyKind::Dynamic,
684            mass: 1.0,
685            linear_velocity: [0.0; 3],
686            angular_velocity: [0.0; 3],
687            gravity_scale: 1.0,
688        }
689    }
690}
691
692#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
693pub enum ColliderShape {
694    Box {
695        half_extents: [f32; 3],
696    },
697    Sphere {
698        radius: f32,
699    },
700    Capsule {
701        half_height: f32,
702        radius: f32,
703    },
704    /// The convex hull of the entity's `MeshRenderer` mesh, scaled by its
705    /// transform. Dynamic bodies may use it.
706    ConvexMesh,
707    /// The triangles of the entity's `MeshRenderer` mesh, scaled by its
708    /// transform. Static only: a body with it never moves.
709    TriangleMesh,
710    /// The entity's `rusting.heightfield` height grid, scaled by its
711    /// transform. Static only, like `TriangleMesh`.
712    Heightfield,
713    /// The convex hull of the entity's `rusting.polygon` outline, extruded
714    /// along Z. Dynamic bodies may use it; the 2D convex polygon.
715    Polygon,
716    /// The segments of the entity's `rusting.polygon` outline as thin
717    /// walls, extruded along Z. Static only; the 2D segment chain.
718    Chain,
719}
720
721#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
722pub struct Collider {
723    pub shape: ColliderShape,
724    pub friction: f32,
725    pub restitution: f32,
726    pub sensor: bool,
727}
728
729impl Default for Collider {
730    fn default() -> Self {
731        Self {
732            shape: ColliderShape::Box {
733                half_extents: [0.5; 3],
734            },
735            friction: 0.5,
736            restitution: 0.0,
737            sensor: false,
738        }
739    }
740}
741
742#[derive(
743    Component, Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize,
744)]
745pub struct CollisionLayers {
746    pub memberships: u32,
747    pub filters: u32,
748}
749
750impl Default for CollisionLayers {
751    fn default() -> Self {
752        Self {
753            memberships: u32::MAX,
754            filters: u32::MAX,
755        }
756    }
757}
758
759#[cfg(test)]
760mod tests {
761    use super::*;
762    use bevy_ecs::{component::Component, resource::Resource};
763
764    fn assert_component<T: Component>() {}
765    fn assert_resource<T: Resource>() {}
766
767    #[test]
768    fn canonical_types_implement_bevy_ecs_traits() {
769        assert_component::<SceneId>();
770        assert_component::<GlobalTransform>();
771        assert_component::<Parent>();
772        assert_component::<Children>();
773        assert_component::<Camera>();
774        assert_component::<Name>();
775        assert_component::<ObjectClasses>();
776        assert_component::<DirectionalLight>();
777        assert_component::<PointLight>();
778        assert_component::<SpotLight>();
779        assert_component::<AmbientLight>();
780        assert_component::<SkyLight>();
781        assert_component::<ToneMapping>();
782        assert_component::<RenderBounds>();
783        assert_component::<Visibility>();
784        assert_component::<PhysicsBody>();
785        assert_component::<RigidBodyKind>();
786        assert_component::<RigidBody>();
787        assert_component::<Collider>();
788        assert_component::<CollisionLayers>();
789
790        assert_resource::<RenderSettings>();
791        assert_resource::<PhysicsSettings>();
792        assert_resource::<PhysicsBackendStatus>();
793    }
794
795    #[test]
796    fn defaults_are_ready_for_a_basic_scene() {
797        let identity: [[f32; 4]; 4] =
798            nalgebra::Matrix4::<f32>::identity().into();
799        assert_eq!(GlobalTransform::default().matrix, identity);
800        assert!(Visibility::default().visible);
801        assert_eq!(RigidBody::default().mass, 1.0);
802        assert_eq!(PhysicsSettings::default().gravity, [0.0, -9.81, 0.0]);
803        assert_eq!(CollisionLayers::default().memberships, u32::MAX);
804        assert_eq!(RenderSettings::default().quality, QualityProfile::Auto);
805    }
806
807    #[test]
808    fn render_bounds_stay_conservative_under_transforms() {
809        use nalgebra::{Matrix4, Rotation3, Vector3};
810        let matrix: [[f32; 4]; 4] =
811            (Matrix4::new_translation(&Vector3::new(10.0, 0.0, 0.0))
812                * Rotation3::from_axis_angle(
813                    &Vector3::z_axis(),
814                    std::f32::consts::FRAC_PI_4,
815                )
816                .to_homogeneous()
817                * Matrix4::new_nonuniform_scaling(&Vector3::new(
818                    2.0, 1.0, 3.0,
819                )))
820            .into();
821        let RenderBounds::Sphere { center, radius } = (RenderBounds::Sphere {
822            center: [1.0, 0.0, 0.0],
823            radius: 1.0,
824        })
825        .transformed(&matrix) else {
826            panic!("a sphere stays a sphere");
827        };
828        let half = std::f32::consts::FRAC_1_SQRT_2;
829        let expected = [10.0 + 2.0 * half, 2.0 * half, 0.0];
830        for (value, expected) in center.iter().zip(expected) {
831            assert!((value - expected).abs() < 1e-5, "{center:?}");
832        }
833        assert!((radius - 3.0).abs() < 1e-5, "largest axis scale");
834
835        let RenderBounds::Aabb { min, max } = (RenderBounds::Aabb {
836            min: [-1.0; 3],
837            max: [1.0; 3],
838        })
839        .transformed(&matrix) else {
840            panic!("a box stays a box");
841        };
842        // The 2x1 face rotated 45 degrees spans (2 + 1) / sqrt(2) on x and
843        // y; z only scales.
844        let reach = 3.0 * half;
845        let expected_min = [10.0 - reach, -reach, -3.0];
846        let expected_max = [10.0 + reach, reach, 3.0];
847        for axis in 0..3 {
848            assert!((min[axis] - expected_min[axis]).abs() < 1e-5, "{min:?}");
849            assert!((max[axis] - expected_max[axis]).abs() < 1e-5, "{max:?}");
850        }
851    }
852
853    #[test]
854    fn object_classes_clean_and_edit_names() {
855        let mut classes =
856            ObjectClasses::new([" gravity ", "", "gravity", "enemy"]);
857        assert_eq!(classes.names, ["gravity", "enemy"]);
858        assert!(classes.contains("gravity"));
859        assert!(!classes.add("enemy"));
860        assert!(classes.remove("enemy"));
861        assert!(!classes.contains("enemy"));
862    }
863
864    #[test]
865    fn physics_body_helpers_follow_simulation_class() {
866        let mut body = PhysicsBody::default();
867        assert!(body.participates_in_dynamic_simulation());
868        assert!(!body.uses_gpu());
869
870        body.simulation = SimulationClass::Gpu;
871        assert!(body.participates_in_dynamic_simulation());
872        assert!(body.uses_gpu());
873
874        body.simulation = SimulationClass::Static;
875        assert!(!body.participates_in_dynamic_simulation());
876        assert!(!body.uses_gpu());
877    }
878}