1use bevy_ecs::component::Component;
2use bevy_ecs::entity::Entity;
3use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6#[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#[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 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#[derive(
102 Component, Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
103)]
104pub struct ObjectClasses {
105 pub names: Vec<String>,
107}
108
109impl ObjectClasses {
110 #[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 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 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 #[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 Default for DirectionalLight {
153 fn default() -> Self {
154 Self {
155 color: [1.0; 3],
156 illuminance: 100_000.0,
157 shadows: true,
158 }
159 }
160}
161
162#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
163pub struct PointLight {
164 pub color: [f32; 3],
165 pub intensity: f32,
166 pub range: f32,
167}
168
169#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
170pub struct SpotLight {
171 pub color: [f32; 3],
172 pub intensity: f32,
173 pub range: f32,
174 pub inner_angle: f32,
176 pub outer_angle: f32,
178}
179
180impl Default for SpotLight {
181 fn default() -> Self {
182 Self {
183 color: [1.0; 3],
184 intensity: 1_000.0,
185 range: 10.0,
186 inner_angle: 20.0_f32.to_radians(),
187 outer_angle: 35.0_f32.to_radians(),
188 }
189 }
190}
191
192impl Default for PointLight {
193 fn default() -> Self {
194 Self {
195 color: [1.0; 3],
196 intensity: 1_000.0,
197 range: 10.0,
198 }
199 }
200}
201
202#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
203pub struct AmbientLight {
204 pub color: [f32; 3],
205 pub intensity: f32,
206}
207
208impl Default for AmbientLight {
209 fn default() -> Self {
210 Self {
211 color: [1.0; 3],
212 intensity: 0.1,
213 }
214 }
215}
216
217#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
221pub struct SkyLight {
222 pub sky_color: [f32; 3],
223 pub ground_color: [f32; 3],
224 pub intensity: f32,
225}
226
227impl Default for SkyLight {
228 fn default() -> Self {
229 Self {
230 sky_color: [0.6, 0.75, 1.0],
231 ground_color: [0.3, 0.25, 0.2],
232 intensity: 0.3,
233 }
234 }
235}
236
237#[derive(
239 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
240)]
241pub enum ToneMapper {
242 #[default]
244 Linear,
245 Reinhard,
247 Aces,
249}
250
251#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
255pub struct ToneMapping {
256 pub mapper: ToneMapper,
257 pub exposure: f32,
259}
260
261impl Default for ToneMapping {
262 fn default() -> Self {
263 Self {
264 mapper: ToneMapper::Linear,
265 exposure: 1.0,
266 }
267 }
268}
269
270#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
274pub enum RenderBounds {
275 Sphere { center: [f32; 3], radius: f32 },
276 Aabb { min: [f32; 3], max: [f32; 3] },
277}
278
279impl Default for RenderBounds {
281 fn default() -> Self {
282 RenderBounds::Aabb {
283 min: [-0.5; 3],
284 max: [0.5; 3],
285 }
286 }
287}
288
289impl RenderBounds {
290 pub fn transformed(&self, matrix: &[[f32; 4]; 4]) -> RenderBounds {
296 let matrix = nalgebra::Matrix4::from(*matrix);
297 let linear = matrix.fixed_view::<3, 3>(0, 0);
298 let translation = matrix.fixed_view::<3, 1>(0, 3);
299 match *self {
300 RenderBounds::Sphere { center, radius } => {
301 let scale = (0..3)
302 .map(|axis| linear.column(axis).norm())
303 .fold(0.0_f32, f32::max);
304 let center =
305 linear * nalgebra::Vector3::from(center) + translation;
306 RenderBounds::Sphere {
307 center: center.into(),
308 radius: radius * scale,
309 }
310 }
311 RenderBounds::Aabb { min, max } => {
312 let mut world_min: [f32; 3] = translation.into();
315 let mut world_max = world_min;
316 for row in 0..3 {
317 for column in 0..3 {
318 let a = linear[(row, column)] * min[column];
319 let b = linear[(row, column)] * max[column];
320 world_min[row] += a.min(b);
321 world_max[row] += a.max(b);
322 }
323 }
324 RenderBounds::Aabb {
325 min: world_min,
326 max: world_max,
327 }
328 }
329 }
330 }
331}
332
333#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
334pub struct Visibility {
335 pub visible: bool,
336}
337
338impl Default for Visibility {
339 fn default() -> Self {
340 Self { visible: true }
341 }
342}
343
344#[derive(
345 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
346)]
347pub enum QualityProfile {
348 Auto,
349 Eco,
350 #[default]
351 Balanced,
352 High,
353}
354
355#[derive(
357 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
358)]
359pub enum CullingMode {
360 #[default]
363 Auto,
364 Disabled,
366 Frustum,
368 FrustumAndOcclusion,
372}
373
374#[derive(
378 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
379)]
380pub enum Antialiasing {
381 #[default]
382 Auto,
383 Off,
384 Msaa2,
385 Msaa4,
386}
387
388#[derive(
390 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
391)]
392pub enum ShadowQuality {
393 #[default]
394 Auto,
395 Low,
397 Medium,
399 High,
401}
402
403#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
404pub struct RenderSettings {
405 pub quality: QualityProfile,
406 pub vsync: bool,
407 pub limit_fps: bool,
408 pub max_fps: u32,
409 pub render_scale: f32,
412 pub pixelated: bool,
415 pub background_color: [f32; 4],
417 pub culling: CullingMode,
418 pub antialiasing: Antialiasing,
419 pub shadows: ShadowQuality,
420 pub reflections: bool,
423}
424
425impl Default for RenderSettings {
426 fn default() -> Self {
427 Self {
428 quality: QualityProfile::Auto,
429 vsync: false,
430 limit_fps: false,
431 max_fps: 120,
432 render_scale: 1.0,
433 pixelated: false,
434 background_color: [0.025, 0.04, 0.07, 1.0],
435 culling: CullingMode::Auto,
436 antialiasing: Antialiasing::Auto,
437 shadows: ShadowQuality::Auto,
438 reflections: true,
439 }
440 }
441}
442
443#[derive(bevy_ecs::prelude::Resource, Clone, Debug, PartialEq)]
444pub struct PhysicsSettings {
445 pub gravity: [f32; 3],
446 pub enabled: bool,
447}
448
449#[derive(
453 bevy_ecs::prelude::Resource, Clone, Copy, Debug, Default, PartialEq, Eq,
454)]
455pub struct PhysicsBackendStatus {
456 pub gameplay_available: bool,
457 pub gpu_dynamic_available: bool,
458}
459
460impl Default for PhysicsSettings {
461 fn default() -> Self {
462 Self {
463 gravity: [0.0, -9.81, 0.0],
464 enabled: true,
465 }
466 }
467}
468
469#[derive(
471 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
472)]
473pub enum SimulationClass {
474 None,
476 Static,
478 #[default]
480 #[serde(alias = "Gameplay")]
481 Cpu,
482 #[serde(alias = "GpuDynamic")]
484 Gpu,
485}
486
487#[allow(non_upper_case_globals)]
488impl SimulationClass {
489 #[deprecated(note = "renamed to `SimulationClass::Cpu`")]
490 pub const Gameplay: Self = Self::Cpu;
491 #[deprecated(note = "renamed to `SimulationClass::Gpu`")]
492 pub const GpuDynamic: Self = Self::Gpu;
493}
494
495#[derive(
497 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
498)]
499pub enum PhysicsSolver {
500 #[default]
501 Full,
502 Simplified,
503 NoCollision,
504 Space,
505 Custom,
506}
507
508#[derive(Component, Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
514pub struct PhysicsBody {
515 pub simulation: SimulationClass,
516 pub solver: PhysicsSolver,
517 pub custom_shader: Option<String>,
518}
519
520impl Default for PhysicsBody {
521 fn default() -> Self {
522 Self {
523 simulation: SimulationClass::Cpu,
524 solver: PhysicsSolver::Full,
525 custom_shader: None,
526 }
527 }
528}
529
530impl PhysicsBody {
531 #[must_use]
532 pub fn participates_in_dynamic_simulation(&self) -> bool {
533 matches!(self.simulation, SimulationClass::Cpu | SimulationClass::Gpu)
534 }
535
536 #[must_use]
537 pub fn uses_gpu(&self) -> bool {
538 self.simulation == SimulationClass::Gpu
539 }
540}
541
542#[derive(
543 Component,
544 Clone,
545 Copy,
546 Debug,
547 Default,
548 Deserialize,
549 PartialEq,
550 Eq,
551 Serialize,
552)]
553pub enum RigidBodyKind {
554 Fixed,
555 #[default]
556 Dynamic,
557 Kinematic,
558}
559
560#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
561pub struct RigidBody {
562 pub kind: RigidBodyKind,
563 pub mass: f32,
564 pub linear_velocity: [f32; 3],
565 pub angular_velocity: [f32; 3],
566 pub gravity_scale: f32,
567}
568
569impl Default for RigidBody {
570 fn default() -> Self {
571 Self {
572 kind: RigidBodyKind::Dynamic,
573 mass: 1.0,
574 linear_velocity: [0.0; 3],
575 angular_velocity: [0.0; 3],
576 gravity_scale: 1.0,
577 }
578 }
579}
580
581#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
582pub enum ColliderShape {
583 Box {
584 half_extents: [f32; 3],
585 },
586 Sphere {
587 radius: f32,
588 },
589 Capsule {
590 half_height: f32,
591 radius: f32,
592 },
593 ConvexMesh,
596 TriangleMesh,
599}
600
601#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
602pub struct Collider {
603 pub shape: ColliderShape,
604 pub friction: f32,
605 pub restitution: f32,
606 pub sensor: bool,
607}
608
609impl Default for Collider {
610 fn default() -> Self {
611 Self {
612 shape: ColliderShape::Box {
613 half_extents: [0.5; 3],
614 },
615 friction: 0.5,
616 restitution: 0.0,
617 sensor: false,
618 }
619 }
620}
621
622#[derive(
623 Component, Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize,
624)]
625pub struct CollisionLayers {
626 pub memberships: u32,
627 pub filters: u32,
628}
629
630impl Default for CollisionLayers {
631 fn default() -> Self {
632 Self {
633 memberships: u32::MAX,
634 filters: u32::MAX,
635 }
636 }
637}
638
639#[cfg(test)]
640mod tests {
641 use super::*;
642 use bevy_ecs::{component::Component, resource::Resource};
643
644 fn assert_component<T: Component>() {}
645 fn assert_resource<T: Resource>() {}
646
647 #[test]
648 fn canonical_types_implement_bevy_ecs_traits() {
649 assert_component::<SceneId>();
650 assert_component::<GlobalTransform>();
651 assert_component::<Parent>();
652 assert_component::<Children>();
653 assert_component::<Camera>();
654 assert_component::<Name>();
655 assert_component::<ObjectClasses>();
656 assert_component::<DirectionalLight>();
657 assert_component::<PointLight>();
658 assert_component::<SpotLight>();
659 assert_component::<AmbientLight>();
660 assert_component::<SkyLight>();
661 assert_component::<ToneMapping>();
662 assert_component::<RenderBounds>();
663 assert_component::<Visibility>();
664 assert_component::<PhysicsBody>();
665 assert_component::<RigidBodyKind>();
666 assert_component::<RigidBody>();
667 assert_component::<Collider>();
668 assert_component::<CollisionLayers>();
669
670 assert_resource::<RenderSettings>();
671 assert_resource::<PhysicsSettings>();
672 assert_resource::<PhysicsBackendStatus>();
673 }
674
675 #[test]
676 fn defaults_are_ready_for_a_basic_scene() {
677 let identity: [[f32; 4]; 4] =
678 nalgebra::Matrix4::<f32>::identity().into();
679 assert_eq!(GlobalTransform::default().matrix, identity);
680 assert!(Visibility::default().visible);
681 assert_eq!(RigidBody::default().mass, 1.0);
682 assert_eq!(PhysicsSettings::default().gravity, [0.0, -9.81, 0.0]);
683 assert_eq!(CollisionLayers::default().memberships, u32::MAX);
684 assert_eq!(RenderSettings::default().quality, QualityProfile::Auto);
685 }
686
687 #[test]
688 fn render_bounds_stay_conservative_under_transforms() {
689 use nalgebra::{Matrix4, Rotation3, Vector3};
690 let matrix: [[f32; 4]; 4] =
691 (Matrix4::new_translation(&Vector3::new(10.0, 0.0, 0.0))
692 * Rotation3::from_axis_angle(
693 &Vector3::z_axis(),
694 std::f32::consts::FRAC_PI_4,
695 )
696 .to_homogeneous()
697 * Matrix4::new_nonuniform_scaling(&Vector3::new(
698 2.0, 1.0, 3.0,
699 )))
700 .into();
701 let RenderBounds::Sphere { center, radius } = (RenderBounds::Sphere {
702 center: [1.0, 0.0, 0.0],
703 radius: 1.0,
704 })
705 .transformed(&matrix) else {
706 panic!("a sphere stays a sphere");
707 };
708 let half = std::f32::consts::FRAC_1_SQRT_2;
709 let expected = [10.0 + 2.0 * half, 2.0 * half, 0.0];
710 for (value, expected) in center.iter().zip(expected) {
711 assert!((value - expected).abs() < 1e-5, "{center:?}");
712 }
713 assert!((radius - 3.0).abs() < 1e-5, "largest axis scale");
714
715 let RenderBounds::Aabb { min, max } = (RenderBounds::Aabb {
716 min: [-1.0; 3],
717 max: [1.0; 3],
718 })
719 .transformed(&matrix) else {
720 panic!("a box stays a box");
721 };
722 let reach = 3.0 * half;
725 let expected_min = [10.0 - reach, -reach, -3.0];
726 let expected_max = [10.0 + reach, reach, 3.0];
727 for axis in 0..3 {
728 assert!((min[axis] - expected_min[axis]).abs() < 1e-5, "{min:?}");
729 assert!((max[axis] - expected_max[axis]).abs() < 1e-5, "{max:?}");
730 }
731 }
732
733 #[test]
734 fn object_classes_clean_and_edit_names() {
735 let mut classes =
736 ObjectClasses::new([" gravity ", "", "gravity", "enemy"]);
737 assert_eq!(classes.names, ["gravity", "enemy"]);
738 assert!(classes.contains("gravity"));
739 assert!(!classes.add("enemy"));
740 assert!(classes.remove("enemy"));
741 assert!(!classes.contains("enemy"));
742 }
743
744 #[test]
745 fn physics_body_helpers_follow_simulation_class() {
746 let mut body = PhysicsBody::default();
747 assert!(body.participates_in_dynamic_simulation());
748 assert!(!body.uses_gpu());
749
750 body.simulation = SimulationClass::Gpu;
751 assert!(body.participates_in_dynamic_simulation());
752 assert!(body.uses_gpu());
753
754 body.simulation = SimulationClass::Static;
755 assert!(!body.participates_in_dynamic_simulation());
756 assert!(!body.uses_gpu());
757 }
758}