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, 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 free_list: Vec::with_capacity(capacity / 4),
303 live_count: 0,
304 tick: 0,
305 }
306 }
307
308 /// Spawns a new entity at `position` with `tag` and returns its generational `EntityId`.
309 ///
310 /// # Arguments
311 ///
312 /// - `&Self` - Mutable game world.
313 /// - `EntityTag` - Semantic gameplay tag.
314 /// - `Point` - Initial world-space position.
315 ///
316 /// # Returns
317 ///
318 /// - `EntityId` - Generation-checked entity handle.
319 pub fn spawn(&mut self, tag: EntityTag, position: Point) -> EntityId {
320 let transform: EntityTransform = EntityTransform::new(position, 0.0, Size::new(1.0, 1.0));
321 let spawn_tick: u64 = self.get_tick();
322 let id: EntityId = if let Some(index) = self.get_mut_free_list().pop() {
323 let slot: &mut EntityRecord = &mut self.get_mut_entities()[index as usize];
324 let next_gen: u32 = slot.get_id().get_generation().wrapping_add(1).max(1);
325 let next_id: EntityId = EntityId::new(index, next_gen);
326 *slot = EntityRecord {
327 id: next_id,
328 alive: true,
329 tag,
330 transform,
331 velocity: Velocity2D::default(),
332 body: None,
333 collider: None,
334 sprite: None,
335 health: 100.0,
336 max_health: 100.0,
337 ttl_secs: None,
338 user_data: 0,
339 teleport_epoch: 0,
340 spawn_tick,
341 };
342 next_id
343 } else {
344 let index: u32 = self.get_entities().len() as u32;
345 let next_id: EntityId = EntityId::new(index, 1);
346 self.get_mut_entities().push(EntityRecord {
347 id: next_id,
348 alive: true,
349 tag,
350 transform,
351 velocity: Velocity2D::default(),
352 body: None,
353 collider: None,
354 sprite: None,
355 health: 100.0,
356 max_health: 100.0,
357 ttl_secs: None,
358 user_data: 0,
359 teleport_epoch: 0,
360 spawn_tick,
361 });
362 next_id
363 };
364 let next_live: usize = self.get_live_count().saturating_add(1);
365 self.set_live_count(next_live);
366 id
367 }
368
369 /// Teleports a live entity directly to `position`, incrementing `teleport_epoch` so snapshot interpolation snaps cleanly.
370 ///
371 /// # Arguments
372 ///
373 /// - `&Self` - Mutable game world.
374 /// - `EntityId` - Target entity handle.
375 /// - `Point` - Destination world coordinates.
376 ///
377 /// # Returns
378 ///
379 /// - `bool` - `true` when the entity was alive and teleported.
380 pub fn teleport_entity(&mut self, id: EntityId, position: Point) -> bool {
381 let Some(ent) = self.get_entity_mut(id) else {
382 return false;
383 };
384 let mut tr: EntityTransform = ent.get_transform();
385 tr.set_position(position);
386 ent.set_transform(tr);
387 let next_epoch: u32 = ent.get_teleport_epoch().wrapping_add(1);
388 ent.set_teleport_epoch(next_epoch);
389 true
390 }
391
392 /// Despawns `id` in O(1), invalidating stale handles and recycling its arena slot.
393 ///
394 /// # Arguments
395 ///
396 /// - `&Self` - Mutable game world.
397 /// - `EntityId` - Target entity handle.
398 ///
399 /// # Returns
400 ///
401 /// - `bool` - `true` if the entity was alive and removed.
402 pub fn despawn(&mut self, id: EntityId) -> bool {
403 let idx: usize = id.get_index() as usize;
404 let removed: bool = match self.get_mut_entities().get_mut(idx) {
405 Some(slot) if slot.get_alive() && slot.get_id() == id => {
406 slot.set_alive(false);
407 true
408 }
409 _ => false,
410 };
411 if removed {
412 self.get_mut_free_list().push(id.get_index());
413 let next_live: usize = self.get_live_count().saturating_sub(1);
414 self.set_live_count(next_live);
415 }
416 removed
417 }
418
419 /// Returns `true` when `id` refers to a currently alive entity.
420 ///
421 /// # Arguments
422 ///
423 /// - `&Self` - Game world reference.
424 /// - `EntityId` - Entity handle to validate.
425 ///
426 /// # Returns
427 ///
428 /// - `bool` - Live status.
429 #[must_use]
430 pub fn is_alive(&self, id: EntityId) -> bool {
431 self.get_entity(id).is_some()
432 }
433
434 /// Returns an immutable reference to the live entity matching `id`.
435 ///
436 /// # Arguments
437 ///
438 /// - `&Self` - Game world reference.
439 /// - `EntityId` - Entity handle.
440 ///
441 /// # Returns
442 ///
443 /// - `Option<&EntityRecord>` - Live entity reference.
444 #[must_use]
445 pub fn get_entity(&self, id: EntityId) -> Option<&EntityRecord> {
446 let slot: &EntityRecord = self.get_entities().get(id.get_index() as usize)?;
447 if slot.get_alive() && slot.get_id() == id {
448 Some(slot)
449 } else {
450 None
451 }
452 }
453
454 /// Returns a mutable reference to the live entity matching `id`.
455 ///
456 /// # Arguments
457 ///
458 /// - `&Self` - Mutable game world.
459 /// - `EntityId` - Entity handle.
460 ///
461 /// # Returns
462 ///
463 /// - `Option<&mut EntityRecord>` - Mutable live entity reference.
464 pub fn get_entity_mut(&mut self, id: EntityId) -> Option<&mut EntityRecord> {
465 let slot: &mut EntityRecord = self.get_mut_entities().get_mut(id.get_index() as usize)?;
466 if slot.get_alive() && slot.get_id() == id {
467 Some(slot)
468 } else {
469 None
470 }
471 }
472
473 /// Decrements `ttl_secs` across all time-limited entities and despawns expired ones in-place without heap allocation.
474 ///
475 /// # Arguments
476 ///
477 /// - `&Self` - Mutable game world.
478 /// - `f32` - Elapsed timestep in seconds.
479 ///
480 /// # Returns
481 ///
482 /// - `usize` - Number of entities expired and despawned.
483 pub fn tick_lifetimes(&mut self, dt_secs: f32) -> usize {
484 let Self {
485 entities,
486 free_list,
487 live_count,
488 tick,
489 ..
490 } = self;
491 let mut removed: usize = 0;
492 for (idx, slot) in entities.iter_mut().enumerate() {
493 if !slot.get_alive() {
494 continue;
495 }
496 if let Some(rem) = slot.ttl_value() {
497 let next: f32 = rem - dt_secs;
498 if next <= 0.0 {
499 slot.set_alive(false);
500 free_list.push(idx as u32);
501 removed += 1;
502 } else {
503 slot.set_ttl_secs(Some(next));
504 }
505 }
506 }
507 *live_count = live_count.saturating_sub(removed);
508 *tick = tick.wrapping_add(1);
509 removed
510 }
511
512 /// Clears all entities while retaining arena backing allocations.
513 ///
514 /// # Arguments
515 ///
516 /// - `&Self` - Mutable game world.
517 pub fn clear(&mut self) {
518 self.get_mut_entities().clear();
519 self.get_mut_free_list().clear();
520 self.set_live_count(0);
521 }
522
523 /// Counts all live entities matching `tag`.
524 ///
525 /// # Arguments
526 ///
527 /// - `&Self` - Game world reference.
528 /// - `EntityTag` - Target gameplay tag.
529 ///
530 /// # Returns
531 ///
532 /// - `usize` - Live entity count matching `tag`.
533 #[must_use]
534 pub fn count_by_tag(&self, tag: EntityTag) -> usize {
535 self.get_entities()
536 .iter()
537 .filter(|e: &&EntityRecord| e.get_alive() && e.get_tag() == tag)
538 .count()
539 }
540}