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}
74
75#[derive(Component, Clone, Debug, PartialEq, Eq)]
76pub struct Name(pub String);
77
78#[derive(
83 Component, Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
84)]
85pub struct ObjectClasses {
86 pub names: Vec<String>,
88}
89
90impl ObjectClasses {
91 #[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 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 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 #[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 pub inner_angle: f32,
157 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#[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#[derive(
220 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
221)]
222pub enum ToneMapper {
223 #[default]
225 Linear,
226 Reinhard,
228 Aces,
230}
231
232#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
236pub struct ToneMapping {
237 pub mapper: ToneMapper,
238 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#[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
260impl 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 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 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#[derive(
338 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize,
339)]
340pub enum CullingMode {
341 #[default]
344 Auto,
345 Disabled,
347 Frustum,
349 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 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#[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#[derive(Component, Clone, Copy, Debug, Default, PartialEq, Eq)]
409pub struct GpuEffectBody;
410
411#[derive(
413 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
414)]
415pub enum SimulationClass {
416 None,
417 Static,
418 #[default]
419 Gameplay,
420 GpuDynamic,
421}
422
423#[derive(
425 Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize,
426)]
427pub enum PhysicsSolver {
428 #[default]
429 Full,
430 Simplified,
431 NoCollision,
432 Space,
433 Custom,
434}
435
436#[derive(Component, Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
442pub struct PhysicsBody {
443 pub simulation: SimulationClass,
444 pub solver: PhysicsSolver,
445 pub custom_shader: Option<String>,
446}
447
448impl Default for PhysicsBody {
449 fn default() -> Self {
450 Self {
451 simulation: SimulationClass::Gameplay,
452 solver: PhysicsSolver::Full,
453 custom_shader: None,
454 }
455 }
456}
457
458impl PhysicsBody {
459 #[must_use]
460 pub fn participates_in_dynamic_simulation(&self) -> bool {
461 matches!(
462 self.simulation,
463 SimulationClass::Gameplay | SimulationClass::GpuDynamic
464 )
465 }
466
467 #[must_use]
468 pub fn uses_gpu(&self) -> bool {
469 self.simulation == SimulationClass::GpuDynamic
470 }
471}
472
473#[derive(
474 Component,
475 Clone,
476 Copy,
477 Debug,
478 Default,
479 Deserialize,
480 PartialEq,
481 Eq,
482 Serialize,
483)]
484pub enum RigidBodyKind {
485 Fixed,
486 #[default]
487 Dynamic,
488 Kinematic,
489}
490
491#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
492pub struct RigidBody {
493 pub kind: RigidBodyKind,
494 pub mass: f32,
495 pub linear_velocity: [f32; 3],
496 pub angular_velocity: [f32; 3],
497 pub gravity_scale: f32,
498}
499
500impl Default for RigidBody {
501 fn default() -> Self {
502 Self {
503 kind: RigidBodyKind::Dynamic,
504 mass: 1.0,
505 linear_velocity: [0.0; 3],
506 angular_velocity: [0.0; 3],
507 gravity_scale: 1.0,
508 }
509 }
510}
511
512#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
513pub enum ColliderShape {
514 Box { half_extents: [f32; 3] },
515 Sphere { radius: f32 },
516 Capsule { half_height: f32, radius: f32 },
517}
518
519#[derive(Component, Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
520pub struct Collider {
521 pub shape: ColliderShape,
522 pub friction: f32,
523 pub restitution: f32,
524 pub sensor: bool,
525}
526
527impl Default for Collider {
528 fn default() -> Self {
529 Self {
530 shape: ColliderShape::Box {
531 half_extents: [0.5; 3],
532 },
533 friction: 0.5,
534 restitution: 0.0,
535 sensor: false,
536 }
537 }
538}
539
540#[derive(
541 Component, Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize,
542)]
543pub struct CollisionLayers {
544 pub memberships: u32,
545 pub filters: u32,
546}
547
548impl Default for CollisionLayers {
549 fn default() -> Self {
550 Self {
551 memberships: u32::MAX,
552 filters: u32::MAX,
553 }
554 }
555}
556
557#[cfg(test)]
558mod tests {
559 use super::*;
560 use bevy_ecs::{component::Component, resource::Resource};
561
562 fn assert_component<T: Component>() {}
563 fn assert_resource<T: Resource>() {}
564
565 #[test]
566 fn canonical_types_implement_bevy_ecs_traits() {
567 assert_component::<SceneId>();
568 assert_component::<GlobalTransform>();
569 assert_component::<Parent>();
570 assert_component::<Children>();
571 assert_component::<Camera>();
572 assert_component::<Name>();
573 assert_component::<ObjectClasses>();
574 assert_component::<DirectionalLight>();
575 assert_component::<PointLight>();
576 assert_component::<SpotLight>();
577 assert_component::<AmbientLight>();
578 assert_component::<SkyLight>();
579 assert_component::<ToneMapping>();
580 assert_component::<RenderBounds>();
581 assert_component::<Visibility>();
582 assert_component::<GpuEffectBody>();
583 assert_component::<PhysicsBody>();
584 assert_component::<RigidBodyKind>();
585 assert_component::<RigidBody>();
586 assert_component::<Collider>();
587 assert_component::<CollisionLayers>();
588
589 assert_resource::<RenderSettings>();
590 assert_resource::<PhysicsSettings>();
591 assert_resource::<PhysicsBackendStatus>();
592 }
593
594 #[test]
595 fn defaults_are_ready_for_a_basic_scene() {
596 let identity: [[f32; 4]; 4] =
597 nalgebra::Matrix4::<f32>::identity().into();
598 assert_eq!(GlobalTransform::default().matrix, identity);
599 assert!(Visibility::default().visible);
600 assert_eq!(RigidBody::default().mass, 1.0);
601 assert_eq!(PhysicsSettings::default().gravity, [0.0, -9.81, 0.0]);
602 assert_eq!(CollisionLayers::default().memberships, u32::MAX);
603 assert_eq!(RenderSettings::default().quality, QualityProfile::Auto);
604 }
605
606 #[test]
607 fn render_bounds_stay_conservative_under_transforms() {
608 use nalgebra::{Matrix4, Rotation3, Vector3};
609 let matrix: [[f32; 4]; 4] =
610 (Matrix4::new_translation(&Vector3::new(10.0, 0.0, 0.0))
611 * Rotation3::from_axis_angle(
612 &Vector3::z_axis(),
613 std::f32::consts::FRAC_PI_4,
614 )
615 .to_homogeneous()
616 * Matrix4::new_nonuniform_scaling(&Vector3::new(
617 2.0, 1.0, 3.0,
618 )))
619 .into();
620 let RenderBounds::Sphere { center, radius } = (RenderBounds::Sphere {
621 center: [1.0, 0.0, 0.0],
622 radius: 1.0,
623 })
624 .transformed(&matrix) else {
625 panic!("a sphere stays a sphere");
626 };
627 let half = std::f32::consts::FRAC_1_SQRT_2;
628 let expected = [10.0 + 2.0 * half, 2.0 * half, 0.0];
629 for (value, expected) in center.iter().zip(expected) {
630 assert!((value - expected).abs() < 1e-5, "{center:?}");
631 }
632 assert!((radius - 3.0).abs() < 1e-5, "largest axis scale");
633
634 let RenderBounds::Aabb { min, max } = (RenderBounds::Aabb {
635 min: [-1.0; 3],
636 max: [1.0; 3],
637 })
638 .transformed(&matrix) else {
639 panic!("a box stays a box");
640 };
641 let reach = 3.0 * half;
644 let expected_min = [10.0 - reach, -reach, -3.0];
645 let expected_max = [10.0 + reach, reach, 3.0];
646 for axis in 0..3 {
647 assert!((min[axis] - expected_min[axis]).abs() < 1e-5, "{min:?}");
648 assert!((max[axis] - expected_max[axis]).abs() < 1e-5, "{max:?}");
649 }
650 }
651
652 #[test]
653 fn object_classes_clean_and_edit_names() {
654 let mut classes =
655 ObjectClasses::new([" gravity ", "", "gravity", "enemy"]);
656 assert_eq!(classes.names, ["gravity", "enemy"]);
657 assert!(classes.contains("gravity"));
658 assert!(!classes.add("enemy"));
659 assert!(classes.remove("enemy"));
660 assert!(!classes.contains("enemy"));
661 }
662
663 #[test]
664 fn physics_body_helpers_follow_simulation_class() {
665 let mut body = PhysicsBody::default();
666 assert!(body.participates_in_dynamic_simulation());
667 assert!(!body.uses_gpu());
668
669 body.simulation = SimulationClass::GpuDynamic;
670 assert!(body.participates_in_dynamic_simulation());
671 assert!(body.uses_gpu());
672
673 body.simulation = SimulationClass::Static;
674 assert!(!body.participates_in_dynamic_simulation());
675 assert!(!body.uses_gpu());
676 }
677}