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