euv_core/game/ecs/impl.rs
1use super::*;
2
3/// Default identity transform at world origin.
4impl Default for EntityTransform {
5 /// Creates an identity `EntityTransform` at `(0, 0)` with unit scale.
6 ///
7 /// # Returns
8 ///
9 /// - `Self` - Identity transform.
10 fn default() -> Self {
11 Self {
12 position: Point::new(0.0, 0.0),
13 rotation_rad: 0.0,
14 scale: Size::new(1.0, 1.0),
15 }
16 }
17}
18
19/// Render-time continuous interpolation helpers for `EntityTransform`.
20impl EntityTransform {
21 /// Linearly interpolates position, scale, and shortest-arc rotation between `self` and `other`.
22 ///
23 /// # Arguments
24 ///
25 /// - `Self` - Previous fixed-step transform.
26 /// - `Self` - Current fixed-step transform.
27 /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
28 ///
29 /// # Returns
30 ///
31 /// - `Self` - Interpolated 2D transform.
32 #[must_use]
33 pub fn lerp(self, other: Self, alpha: f32) -> Self {
34 let k: f32 = alpha.clamp(0.0, 1.0);
35 let p0: Point = self.get_position();
36 let p1: Point = other.get_position();
37 let s0: Size = self.get_scale();
38 let s1: Size = other.get_scale();
39 let raw_delta: f32 = (other.get_rotation_rad() - self.get_rotation_rad()).rem_euclid(TAU);
40 let shortest_delta: f32 = if raw_delta > PI {
41 raw_delta - TAU
42 } else {
43 raw_delta
44 };
45 Self {
46 position: Point::new(
47 p0.get_x() + (p1.get_x() - p0.get_x()) * k,
48 p0.get_y() + (p1.get_y() - p0.get_y()) * k,
49 ),
50 rotation_rad: self.get_rotation_rad() + shortest_delta * k,
51 scale: Size::new(
52 s0.get_width() + (s1.get_width() - s0.get_width()) * k,
53 s0.get_height() + (s1.get_height() - s0.get_height()) * k,
54 ),
55 }
56 }
57}
58
59/// Convenience constructors for `RigidBody2D`.
60impl RigidBody2D {
61 /// Creates a dynamic rigid body with `mass`, `restitution`, and `linear_drag`.
62 ///
63 /// # Arguments
64 ///
65 /// - `f32` - Positive mass in kilograms.
66 /// - `f32` - Restitution bounciness in `[0.0, 1.0]`.
67 /// - `f32` - Linear velocity drag per second.
68 ///
69 /// # Returns
70 ///
71 /// - `Self` - Dynamic rigid body component.
72 #[must_use]
73 pub fn dynamic(mass: f32, restitution: f32, linear_drag: f32) -> Self {
74 Self {
75 kind: BodyKind::Dynamic,
76 inv_mass: 1.0 / mass.max(0.001),
77 restitution: restitution.clamp(0.0, 1.0),
78 linear_drag: linear_drag.max(0.0),
79 gravity_scale: 1.0,
80 }
81 }
82
83 /// Creates an immovable static body with zero inverse mass.
84 ///
85 /// # Arguments
86 ///
87 /// - `f32` - Surface restitution bounciness in `[0.0, 1.0]`.
88 ///
89 /// # Returns
90 ///
91 /// - `Self` - Static rigid body component.
92 #[must_use]
93 pub fn static_body(restitution: f32) -> Self {
94 Self {
95 kind: BodyKind::Static,
96 inv_mass: 0.0,
97 restitution: restitution.clamp(0.0, 1.0),
98 linear_drag: 0.0,
99 gravity_scale: 0.0,
100 }
101 }
102
103 /// Creates a kinematic body driven directly by velocity without impulse reaction.
104 ///
105 /// # Returns
106 ///
107 /// - `Self` - Kinematic rigid body component.
108 #[must_use]
109 pub fn kinematic() -> Self {
110 Self {
111 kind: BodyKind::Kinematic,
112 inv_mass: 0.0,
113 restitution: 0.5,
114 linear_drag: 0.0,
115 gravity_scale: 0.0,
116 }
117 }
118}
119
120/// World-space bounding box queries for `Collider2D`.
121impl Collider2D {
122 /// Creates a solid circle collider on layer `layer` colliding with `mask`.
123 ///
124 /// # Arguments
125 ///
126 /// - `f32` - Circle radius in world units.
127 /// - `u32` - Collision layer bitmask.
128 /// - `u32` - Interaction mask.
129 /// - `bool` - Whether this collider acts as a trigger volume.
130 ///
131 /// # Returns
132 ///
133 /// - `Self` - Configured circle collider.
134 #[must_use]
135 pub fn circle(radius: f32, layer: u32, mask: u32, is_trigger: bool) -> Self {
136 Self {
137 shape: ColliderShape::Circle {
138 radius: radius.max(0.5),
139 },
140 layer,
141 mask,
142 is_trigger,
143 }
144 }
145
146 /// Creates an axis-aligned box collider on layer `layer` colliding with `mask`.
147 ///
148 /// # Arguments
149 ///
150 /// - `f32` - Full box width in world units.
151 /// - `f32` - Full box height in world units.
152 /// - `u32` - Collision layer bitmask.
153 /// - `u32` - Interaction mask.
154 /// - `bool` - Whether this collider acts as a trigger volume.
155 ///
156 /// # Returns
157 ///
158 /// - `Self` - Configured AABB collider.
159 #[must_use]
160 pub fn aabb(width: f32, height: f32, layer: u32, mask: u32, is_trigger: bool) -> Self {
161 Self {
162 shape: ColliderShape::Aabb {
163 width: width.max(1.0),
164 height: height.max(1.0),
165 },
166 layer,
167 mask,
168 is_trigger,
169 }
170 }
171
172 /// Computes the world-space axis-aligned bounding rectangle of this collider centered at `center`.
173 ///
174 /// # Arguments
175 ///
176 /// - `&Self` - Collider reference.
177 /// - `Point` - Entity world center position.
178 ///
179 /// # Returns
180 ///
181 /// - `Rect` - World-space AABB rectangle.
182 #[must_use]
183 pub fn world_aabb(&self, center: Point) -> Rect {
184 match self.get_shape() {
185 ColliderShape::Aabb { width, height } => Rect::new(
186 center.get_x() - width * 0.5,
187 center.get_y() - height * 0.5,
188 width,
189 height,
190 ),
191 ColliderShape::Circle { radius } => Rect::new(
192 center.get_x() - radius,
193 center.get_y() - radius,
194 radius * 2.0,
195 radius * 2.0,
196 ),
197 }
198 }
199}
200
201/// Optional component accessors for `EntityRecord`.
202impl EntityRecord {
203 /// Returns the attached `RigidBody2D` component if present.
204 ///
205 /// # Arguments
206 ///
207 /// - `&Self` - Entity record reference.
208 ///
209 /// # Returns
210 ///
211 /// - `Option<RigidBody2D>` - Rigid-body component value.
212 #[must_use]
213 pub fn body_component(&self) -> Option<RigidBody2D> {
214 let Self { body, .. } = self;
215 *body
216 }
217
218 /// Returns the attached `Collider2D` component if present.
219 ///
220 /// # Arguments
221 ///
222 /// - `&Self` - Entity record reference.
223 ///
224 /// # Returns
225 ///
226 /// - `Option<Collider2D>` - Collider component value.
227 #[must_use]
228 pub fn collider_component(&self) -> Option<Collider2D> {
229 let Self { collider, .. } = self;
230 *collider
231 }
232
233 /// Returns the attached `Sprite2D` component if present.
234 ///
235 /// # Arguments
236 ///
237 /// - `&Self` - Entity record reference.
238 ///
239 /// # Returns
240 ///
241 /// - `Option<Sprite2D>` - Sprite component value.
242 #[must_use]
243 pub fn sprite_component(&self) -> Option<Sprite2D> {
244 let Self { sprite, .. } = self;
245 *sprite
246 }
247
248 /// Returns remaining lifetime in seconds if the entity is time-limited.
249 ///
250 /// # Arguments
251 ///
252 /// - `&Self` - Entity record reference.
253 ///
254 /// # Returns
255 ///
256 /// - `Option<f32>` - Remaining TTL seconds.
257 #[must_use]
258 pub fn ttl_value(&self) -> Option<f32> {
259 let Self { ttl_secs, .. } = self;
260 *ttl_secs
261 }
262
263 /// Computes the world-space visual bounding box of this entity.
264 ///
265 /// # Arguments
266 ///
267 /// - `&Self` - Entity record reference.
268 ///
269 /// # Returns
270 ///
271 /// - `Rect` - World-space bounding rectangle.
272 #[must_use]
273 pub fn world_bounds(&self) -> Rect {
274 let pos: Point = self.get_transform().get_position();
275 if let Some(sp) = self.sprite_component() {
276 let w: f32 = sp.get_size().get_width() * self.get_transform().get_scale().get_width();
277 let h: f32 = sp.get_size().get_height() * self.get_transform().get_scale().get_height();
278 Rect::new(pos.get_x() - w * 0.5, pos.get_y() - h * 0.5, w, h)
279 } else if let Some(col) = self.collider_component() {
280 col.world_aabb(pos)
281 } else {
282 Rect::new(pos.get_x(), pos.get_y(), 1.0, 1.0)
283 }
284 }
285}
286
287/// Entity spawning, recycling, Structure-of-Arrays synchronization, querying, and lifetime ticking for `GameWorld`.
288impl GameWorld {
289 /// Allocates a `GameWorld` pre-sized for `capacity` entities with zero initial allocations during play.
290 ///
291 /// # Arguments
292 ///
293 /// - `usize` - Initial entity slot capacity.
294 ///
295 /// # Returns
296 ///
297 /// - `Self` - Pre-allocated game world.
298 #[must_use]
299 pub fn with_capacity(capacity: usize) -> Self {
300 Self {
301 entities: Vec::with_capacity(capacity),
302 transforms: Vec::with_capacity(capacity),
303 velocities: Vec::with_capacity(capacity),
304 cold_meta: Vec::with_capacity(capacity),
305 free_list: Vec::with_capacity(capacity / 4),
306 live_count: 0,
307 tick: 0,
308 }
309 }
310
311 /// Synchronizes the dense SoA `transforms`, `velocities`, and `cold_meta` arrays from `entities`.
312 ///
313 /// # Arguments
314 ///
315 /// - `&Self` - Mutable game world.
316 pub fn sync_soa_from_entities(&mut self) {
317 let Self {
318 entities,
319 transforms,
320 velocities,
321 cold_meta,
322 ..
323 } = self;
324 let len: usize = entities.len();
325 transforms.resize(len, EntityTransform::default());
326 velocities.resize(len, Velocity2D::default());
327 cold_meta.resize(
328 len,
329 EntityColdMeta {
330 id: EntityId::default(),
331 alive: false,
332 tag: EntityTag::Generic,
333 health: 0.0,
334 max_health: 0.0,
335 ttl_secs: None,
336 user_data: 0,
337 teleport_epoch: 0,
338 spawn_tick: 0,
339 },
340 );
341 for (idx, ent) in entities.iter().enumerate() {
342 transforms[idx] = ent.get_transform();
343 velocities[idx] = ent.get_velocity();
344 cold_meta[idx] = EntityColdMeta {
345 id: ent.get_id(),
346 alive: ent.get_alive(),
347 tag: ent.get_tag(),
348 health: ent.get_health(),
349 max_health: ent.get_max_health(),
350 ttl_secs: ent.ttl_value(),
351 user_data: ent.get_user_data(),
352 teleport_epoch: ent.get_teleport_epoch(),
353 spawn_tick: ent.get_spawn_tick(),
354 };
355 }
356 }
357
358 /// Writes updated SoA `transforms` and `velocities` back into the `entities` mirror.
359 ///
360 /// # Arguments
361 ///
362 /// - `&Self` - Mutable game world.
363 pub fn sync_entities_from_soa(&mut self) {
364 let Self {
365 entities,
366 transforms,
367 velocities,
368 ..
369 } = self;
370 let count: usize = entities.len().min(transforms.len()).min(velocities.len());
371 for idx in 0..count {
372 entities[idx].set_transform(transforms[idx]);
373 entities[idx].set_velocity(velocities[idx]);
374 }
375 }
376
377 /// Spawns a new entity at `position` with `tag` and returns its generational `EntityId`.
378 ///
379 /// # Arguments
380 ///
381 /// - `&Self` - Mutable game world.
382 /// - `EntityTag` - Semantic gameplay tag.
383 /// - `Point` - Initial world-space position.
384 ///
385 /// # Returns
386 ///
387 /// - `EntityId` - Generation-checked entity handle.
388 pub fn spawn(&mut self, tag: EntityTag, position: Point) -> EntityId {
389 let transform: EntityTransform = EntityTransform::new(position, 0.0, Size::new(1.0, 1.0));
390 let spawn_tick: u64 = self.get_tick();
391 let id: EntityId = if let Some(index) = self.get_mut_free_list().pop() {
392 let slot_idx: usize = index as usize;
393 let next_gen: u32 = self.get_entities()[slot_idx]
394 .get_id()
395 .get_generation()
396 .wrapping_add(1)
397 .max(1);
398 let next_id: EntityId = EntityId::new(index, next_gen);
399 let meta: EntityColdMeta = EntityColdMeta {
400 id: next_id,
401 alive: true,
402 tag,
403 health: 100.0,
404 max_health: 100.0,
405 ttl_secs: None,
406 user_data: 0,
407 teleport_epoch: 0,
408 spawn_tick,
409 };
410 self.get_mut_entities()[slot_idx] = EntityRecord {
411 id: next_id,
412 alive: true,
413 tag,
414 transform,
415 velocity: Velocity2D::default(),
416 body: None,
417 collider: None,
418 sprite: None,
419 health: 100.0,
420 max_health: 100.0,
421 ttl_secs: None,
422 user_data: 0,
423 teleport_epoch: 0,
424 spawn_tick,
425 };
426 if slot_idx < self.get_transforms().len() {
427 self.get_mut_transforms()[slot_idx] = transform;
428 self.get_mut_velocities()[slot_idx] = Velocity2D::default();
429 self.get_mut_cold_meta()[slot_idx] = meta;
430 }
431 next_id
432 } else {
433 let index: u32 = self.get_entities().len() as u32;
434 let next_id: EntityId = EntityId::new(index, 1);
435 let meta: EntityColdMeta = EntityColdMeta {
436 id: next_id,
437 alive: true,
438 tag,
439 health: 100.0,
440 max_health: 100.0,
441 ttl_secs: None,
442 user_data: 0,
443 teleport_epoch: 0,
444 spawn_tick,
445 };
446 self.get_mut_entities().push(EntityRecord {
447 id: next_id,
448 alive: true,
449 tag,
450 transform,
451 velocity: Velocity2D::default(),
452 body: None,
453 collider: None,
454 sprite: None,
455 health: 100.0,
456 max_health: 100.0,
457 ttl_secs: None,
458 user_data: 0,
459 teleport_epoch: 0,
460 spawn_tick,
461 });
462 self.get_mut_transforms().push(transform);
463 self.get_mut_velocities().push(Velocity2D::default());
464 self.get_mut_cold_meta().push(meta);
465 next_id
466 };
467 let next_live: usize = self.get_live_count().saturating_add(1);
468 self.set_live_count(next_live);
469 id
470 }
471
472 /// Teleports a live entity directly to `position`, incrementing `teleport_epoch` so snapshot interpolation snaps cleanly.
473 ///
474 /// # Arguments
475 ///
476 /// - `&Self` - Mutable game world.
477 /// - `EntityId` - Target entity handle.
478 /// - `Point` - Destination world coordinates.
479 ///
480 /// # Returns
481 ///
482 /// - `bool` - `true` when the entity was alive and teleported.
483 pub fn teleport_entity(&mut self, id: EntityId, position: Point) -> bool {
484 let idx: usize = id.get_index() as usize;
485 let Some(ent) = self.get_entity_mut(id) else {
486 return false;
487 };
488 let mut tr: EntityTransform = ent.get_transform();
489 tr.set_position(position);
490 ent.set_transform(tr);
491 let next_epoch: u32 = ent.get_teleport_epoch().wrapping_add(1);
492 ent.set_teleport_epoch(next_epoch);
493 if idx < self.get_transforms().len() {
494 self.get_mut_transforms()[idx] = tr;
495 self.get_mut_cold_meta()[idx].set_teleport_epoch(next_epoch);
496 }
497 true
498 }
499
500 /// Despawns `id` in O(1), invalidating stale handles and recycling its arena slot.
501 ///
502 /// # Arguments
503 ///
504 /// - `&Self` - Mutable game world.
505 /// - `EntityId` - Target entity handle.
506 ///
507 /// # Returns
508 ///
509 /// - `bool` - `true` if the entity was alive and removed.
510 pub fn despawn(&mut self, id: EntityId) -> bool {
511 let idx: usize = id.get_index() as usize;
512 let removed: bool = match self.get_mut_entities().get_mut(idx) {
513 Some(slot) if slot.get_alive() && slot.get_id() == id => {
514 slot.set_alive(false);
515 true
516 }
517 _ => false,
518 };
519 if removed {
520 if idx < self.get_cold_meta().len() {
521 self.get_mut_cold_meta()[idx].set_alive(false);
522 }
523 self.get_mut_free_list().push(id.get_index());
524 let next_live: usize = self.get_live_count().saturating_sub(1);
525 self.set_live_count(next_live);
526 }
527 removed
528 }
529
530 /// Returns `true` when `id` refers to a currently alive entity.
531 ///
532 /// # Arguments
533 ///
534 /// - `&Self` - Game world reference.
535 /// - `EntityId` - Entity handle to validate.
536 ///
537 /// # Returns
538 ///
539 /// - `bool` - Live status.
540 #[must_use]
541 pub fn is_alive(&self, id: EntityId) -> bool {
542 self.get_entity(id).is_some()
543 }
544
545 /// Returns an immutable reference to the live entity matching `id`.
546 ///
547 /// # Arguments
548 ///
549 /// - `&Self` - Game world reference.
550 /// - `EntityId` - Entity handle.
551 ///
552 /// # Returns
553 ///
554 /// - `Option<&EntityRecord>` - Live entity reference.
555 #[must_use]
556 pub fn get_entity(&self, id: EntityId) -> Option<&EntityRecord> {
557 let slot: &EntityRecord = self.get_entities().get(id.get_index() as usize)?;
558 if slot.get_alive() && slot.get_id() == id {
559 Some(slot)
560 } else {
561 None
562 }
563 }
564
565 /// Returns a mutable reference to the live entity matching `id`.
566 ///
567 /// # Arguments
568 ///
569 /// - `&Self` - Mutable game world.
570 /// - `EntityId` - Entity handle.
571 ///
572 /// # Returns
573 ///
574 /// - `Option<&mut EntityRecord>` - Mutable live entity reference.
575 pub fn get_entity_mut(&mut self, id: EntityId) -> Option<&mut EntityRecord> {
576 let slot: &mut EntityRecord = self.get_mut_entities().get_mut(id.get_index() as usize)?;
577 if slot.get_alive() && slot.get_id() == id {
578 Some(slot)
579 } else {
580 None
581 }
582 }
583
584 /// Decrements `ttl_secs` across all time-limited entities and despawns expired ones in-place without heap allocation.
585 ///
586 /// # Arguments
587 ///
588 /// - `&Self` - Mutable game world.
589 /// - `f32` - Elapsed timestep in seconds.
590 ///
591 /// # Returns
592 ///
593 /// - `usize` - Number of entities expired and despawned.
594 pub fn tick_lifetimes(&mut self, dt_secs: f32) -> usize {
595 let Self {
596 entities,
597 cold_meta,
598 free_list,
599 live_count,
600 tick,
601 ..
602 } = self;
603 let mut removed: usize = 0;
604 for (idx, slot) in entities.iter_mut().enumerate() {
605 if !slot.get_alive() {
606 continue;
607 }
608 if let Some(rem) = slot.ttl_value() {
609 let next: f32 = rem - dt_secs;
610 if next <= 0.0 {
611 slot.set_alive(false);
612 if idx < cold_meta.len() {
613 cold_meta[idx].set_alive(false);
614 }
615 free_list.push(idx as u32);
616 removed += 1;
617 } else {
618 slot.set_ttl_secs(Some(next));
619 if idx < cold_meta.len() {
620 cold_meta[idx].set_ttl_secs(Some(next));
621 }
622 }
623 }
624 }
625 *live_count = live_count.saturating_sub(removed);
626 *tick = tick.wrapping_add(1);
627 removed
628 }
629
630 /// Clears all entities while retaining arena backing allocations.
631 ///
632 /// # Arguments
633 ///
634 /// - `&Self` - Mutable game world.
635 pub fn clear(&mut self) {
636 self.get_mut_entities().clear();
637 self.get_mut_transforms().clear();
638 self.get_mut_velocities().clear();
639 self.get_mut_cold_meta().clear();
640 self.get_mut_free_list().clear();
641 self.set_live_count(0);
642 }
643
644 /// Counts all live entities matching `tag`.
645 ///
646 /// # Arguments
647 ///
648 /// - `&Self` - Game world reference.
649 /// - `EntityTag` - Target gameplay tag.
650 ///
651 /// # Returns
652 ///
653 /// - `usize` - Live entity count matching `tag`.
654 #[must_use]
655 pub fn count_by_tag(&self, tag: EntityTag) -> usize {
656 if self.get_cold_meta().len() == self.get_entities().len() {
657 self.get_cold_meta()
658 .iter()
659 .filter(|m: &&EntityColdMeta| m.get_alive() && m.get_tag() == tag)
660 .count()
661 } else {
662 self.get_entities()
663 .iter()
664 .filter(|e: &&EntityRecord| e.get_alive() && e.get_tag() == tag)
665 .count()
666 }
667 }
668}