moirai-for-games 0.1.0

A small deterministic no_std ECS for constrained and headless games
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Component [`Bundle`] insertion for spawn and deferred commands.
//!
//! [`BundleWriter`] routes writes through immediate world mutation, queued commands,
//! or query-side command enqueue depending on the active spawn path.

use crate::command::{CommandOp, ErasedComponentValue};
use crate::component::ComponentId;
use crate::entity::EntityId;
use crate::world::{World, WorldError};
use alloc::boxed::Box;
use alloc::vec::Vec;

/// Write one or more components onto an entity through [`BundleWriter`].
pub trait Bundle {
    fn write(self, writer: &mut BundleWriter<'_>) -> Result<(), WorldError>;
}

/// Runtime-assembled bundle of validated [`ComponentId`] entries and owned values.
pub struct DynamicBundle {
    entries: Vec<DynamicEntry>,
}

struct DynamicEntry {
    component_id: ComponentId,
    value: Option<Box<dyn ErasedComponentValue>>,
}

impl DynamicBundle {
    /// Empty dynamic bundle.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Append typed component `T` resolved against `world`'s registry.
    pub fn push<T: 'static>(&mut self, world: &World, value: T) -> Result<(), WorldError> {
        let component_id = world.component_id::<T>()?;
        if world.is_tag_component(&component_id) {
            return Err(WorldError::WrongStorageKind {
                name: alloc::string::String::from("tag components cannot carry values"),
            });
        }
        self.push_entry(component_id, Some(Box::new(value)))
    }

    /// Append tag component without a stored value.
    pub fn push_tag(&mut self, tag: &ComponentId) -> Result<(), WorldError> {
        self.push_entry(tag.clone(), None)
    }

    fn push_entry(
        &mut self,
        component_id: ComponentId,
        value: Option<Box<dyn ErasedComponentValue>>,
    ) -> Result<(), WorldError> {
        if self
            .entries
            .iter()
            .any(|entry| entry.component_id.index() == component_id.index())
        {
            return Err(WorldError::WrongStorageKind {
                name: alloc::string::String::from("duplicate component in dynamic bundle"),
            });
        }
        self.entries.push(DynamicEntry {
            component_id,
            value,
        });
        Ok(())
    }
}

impl Default for DynamicBundle {
    fn default() -> Self {
        Self::new()
    }
}

impl Bundle for DynamicBundle {
    fn write(self, writer: &mut BundleWriter<'_>) -> Result<(), WorldError> {
        for entry in self.entries {
            entry.component_id.validate_owner(writer.world_owner())?;
            if writer.is_tag_component(&entry.component_id) {
                if entry.value.is_some() {
                    return Err(WorldError::WrongStorageKind {
                        name: alloc::string::String::from("tag components cannot carry values"),
                    });
                }
                writer.insert_tag_id(entry.component_id)?;
            } else if let Some(value) = entry.value {
                writer.insert_dynamic(entry.component_id, value)?;
            } else {
                return Err(WorldError::WrongStorageKind {
                    name: alloc::string::String::from("table/sparse components require values"),
                });
            }
        }
        Ok(())
    }
}

/// Checked bundle write surface for immediate, deferred, and query enqueue paths.
pub struct BundleWriter<'w> {
    entity: EntityId,
    target: BundleTarget<'w>,
}

enum BundleTarget<'w> {
    Immediate(&'w mut World),
    Deferred(&'w mut World),
    Query {
        allocator: &'w crate::entity::EntityAllocator,
        queue: &'w mut crate::command::CommandQueue,
    },
}

impl<'w> BundleWriter<'w> {
    pub(crate) fn new(world: &'w mut World, entity: EntityId) -> Self {
        Self {
            entity,
            target: BundleTarget::Immediate(world),
        }
    }

    pub(crate) fn deferred(world: &'w mut World, entity: EntityId) -> Self {
        Self {
            entity,
            target: BundleTarget::Deferred(world),
        }
    }

    pub(crate) fn query(
        allocator: &'w crate::entity::EntityAllocator,
        queue: &'w mut crate::command::CommandQueue,
        entity: EntityId,
    ) -> Self {
        Self {
            entity,
            target: BundleTarget::Query { allocator, queue },
        }
    }

    /// Insert component `T` for the bundle's target entity.
    pub fn insert<T: 'static>(&mut self, value: T) -> Result<(), WorldError> {
        match &mut self.target {
            BundleTarget::Immediate(world) => world.insert(self.entity, value).map(|_| ()),
            BundleTarget::Deferred(world) => {
                world.ensure_mutable()?;
                world.ensure_command_target(self.entity)?;
                world.command_queue_mut().enqueue_insert(self.entity, value)
            }
            BundleTarget::Query { allocator, queue } => {
                ensure_query_target(allocator, self.entity)?;
                queue.enqueue_insert(self.entity, value)
            }
        }
    }

    pub(crate) fn insert_dynamic(
        &mut self,
        component_id: ComponentId,
        value: Box<dyn ErasedComponentValue>,
    ) -> Result<(), WorldError> {
        match &mut self.target {
            BundleTarget::Immediate(world) => world
                .insert_dynamic(self.entity, component_id, value)
                .map(|_| ()),
            BundleTarget::Deferred(world) => {
                world.ensure_mutable()?;
                world.ensure_command_target(self.entity)?;
                world.validate_component_insert(
                    self.entity,
                    component_id.index() as u32,
                    value.as_ref().type_id(),
                )?;
                world.command_queue_mut().push(CommandOp::Insert {
                    entity: self.entity,
                    component_index: component_id.index() as u32,
                    value,
                });
                Ok(())
            }
            BundleTarget::Query { allocator, queue } => {
                ensure_query_target(allocator, self.entity)?;
                queue.enqueue_dynamic_insert(self.entity, component_id.index(), value)
            }
        }
    }

    pub(crate) fn insert_tag_id(&mut self, component_id: ComponentId) -> Result<(), WorldError> {
        match &mut self.target {
            BundleTarget::Immediate(world) => world.add_tag_id(self.entity, component_id),
            BundleTarget::Deferred(world) => {
                world.ensure_mutable()?;
                world.ensure_command_target(self.entity)?;
                world
                    .command_queue_mut()
                    .enqueue_tag(self.entity, component_id.index())
            }
            BundleTarget::Query { allocator, queue } => {
                ensure_query_target(allocator, self.entity)?;
                queue.enqueue_tag(self.entity, component_id.index())
            }
        }
    }

    pub(crate) fn world_owner(&self) -> &crate::world::WorldOwner {
        match &self.target {
            BundleTarget::Immediate(world) | BundleTarget::Deferred(world) => world.owner(),
            BundleTarget::Query { queue, .. } => queue.owner(),
        }
    }

    pub(crate) fn is_tag_component(&self, component_id: &ComponentId) -> bool {
        match &self.target {
            BundleTarget::Immediate(world) | BundleTarget::Deferred(world) => {
                world.is_tag_component(component_id)
            }
            BundleTarget::Query { queue, .. } => queue.is_tag_component(component_id.index()),
        }
    }

    #[cfg(test)]
    pub(crate) fn test_entity(&self) -> EntityId {
        self.entity
    }

    #[cfg(test)]
    pub(crate) fn test_world(&mut self) -> &mut World {
        match &mut self.target {
            BundleTarget::Immediate(world) | BundleTarget::Deferred(world) => world,
            BundleTarget::Query { .. } => panic!("query bundle writer has no world"),
        }
    }
}

fn ensure_query_target(
    allocator: &crate::entity::EntityAllocator,
    entity: EntityId,
) -> Result<(), WorldError> {
    if allocator.is_alive(entity) || allocator.is_reserved(entity) {
        Ok(())
    } else {
        Err(WorldError::StaleEntity { entity })
    }
}

macro_rules! impl_bundle_tuple {
    ($($name:ident),+) => {
        #[allow(non_snake_case)]
        impl<$($name: 'static),+> Bundle for ($($name,)+) {
            fn write(self, writer: &mut BundleWriter<'_>) -> Result<(), WorldError> {
                let ($($name,)+) = self;
                $(writer.insert($name)?;)+
                Ok(())
            }
        }
    };
}

impl_bundle_tuple!(A);
impl_bundle_tuple!(A, B);
impl_bundle_tuple!(A, B, C);
impl_bundle_tuple!(A, B, C, D);
impl_bundle_tuple!(A, B, C, D, E);
impl_bundle_tuple!(A, B, C, D, E, F);
impl_bundle_tuple!(A, B, C, D, E, F, G);
impl_bundle_tuple!(A, B, C, D, E, F, G, H);
impl_bundle_tuple!(A, B, C, D, E, F, G, H, I);
impl_bundle_tuple!(A, B, C, D, E, F, G, H, I, J);
impl_bundle_tuple!(A, B, C, D, E, F, G, H, I, J, K);
impl_bundle_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_bundle_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_bundle_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_bundle_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_bundle_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::component::ComponentOptions;
    use crate::world::WorldBuilder;
    use alloc::vec;

    #[derive(Clone, Copy)]
    struct Health(i32);

    #[derive(Clone, Copy)]
    struct Marker;

    #[test]
    fn dynamic_bundle_default_and_write_validation_errors() {
        assert_eq!(DynamicBundle::default().entries.len(), 0);
        let mut builder = WorldBuilder::new();
        let tag = builder
            .register_component::<Marker>(ComponentOptions::tag())
            .expect("tag");
        builder
            .register_component::<Health>(ComponentOptions::sparse())
            .expect("health");
        let mut world = builder.build().expect("build");
        let entity = world.spawn().expect("spawn");

        let mut tag_with_value = DynamicBundle::new();
        tag_with_value.push_tag(&tag).expect("tag");
        tag_with_value.entries[0].value = Some(Box::new(Health(1)));
        assert!(matches!(
            tag_with_value.write(&mut BundleWriter::new(&mut world, entity)),
            Err(WorldError::WrongStorageKind { .. })
        ));

        let health_id = world.component_id::<Health>().expect("health");
        let mut missing_value = DynamicBundle::new();
        missing_value.push_entry(health_id, None).expect("entry");
        assert!(matches!(
            missing_value.write(&mut BundleWriter::new(&mut world, entity)),
            Err(WorldError::WrongStorageKind { .. })
        ));
    }

    #[test]
    fn deferred_bundle_writer_queues_inserts() {
        let mut builder = WorldBuilder::new();
        builder
            .register_component::<Health>(ComponentOptions::sparse())
            .expect("health");
        let mut world = builder.build().expect("build");
        let entity = world
            .commands()
            .expect("commands")
            .spawn()
            .expect("reserve");
        BundleWriter::deferred(&mut world, entity)
            .insert(Health(3))
            .expect("queue");
        assert!(world.has_pending_commands());
    }

    #[test]
    fn deferred_dynamic_bundle_queues_validated_erased_value() {
        let mut builder = WorldBuilder::new();
        builder
            .register_component::<Health>(ComponentOptions::sparse())
            .expect("health");
        let mut world = builder.build().expect("world");
        let health = world.component_id::<Health>().expect("id");
        let entity = world
            .commands()
            .expect("commands")
            .spawn()
            .expect("reserve");
        let mut dynamic = DynamicBundle::new();
        dynamic
            .push_entry(health, Some(Box::new(Health(7))))
            .expect("entry");
        dynamic
            .write(&mut BundleWriter::deferred(&mut world, entity))
            .expect("deferred dynamic");

        let mut wrong = DynamicBundle::new();
        wrong
            .push_entry(
                world.component_id::<Health>().expect("health id"),
                Some(Box::new(7_u32)),
            )
            .expect("wrong entry");
        assert!(matches!(
            wrong.write(&mut BundleWriter::deferred(&mut world, entity)),
            Err(WorldError::WrongStorageKind { .. })
        ));
    }

    #[test]
    fn tuple_bundle_writes_components() {
        let mut builder = WorldBuilder::new();
        builder
            .register_component::<Health>(ComponentOptions::sparse())
            .expect("health");
        let mut world = builder.build().expect("build");
        let entity = world.spawn().expect("spawn");
        (Health(4),)
            .write(&mut BundleWriter::new(&mut world, entity))
            .expect("tuple");
        assert_eq!(
            world.get::<Health>(entity).expect("get").map(|h| h.0),
            Some(4)
        );
    }

    #[test]
    fn query_bundle_writer_validates_and_enqueues_all_component_shapes() {
        let mut builder = WorldBuilder::new();
        let health = builder
            .register_component::<Health>(ComponentOptions::sparse())
            .expect("health");
        let marker = builder
            .register_component::<Marker>(ComponentOptions::tag())
            .expect("marker");
        let mut world = builder.build().expect("world");
        let entity = world.spawn().expect("entity");
        let mut queue = crate::command::CommandQueue::configured(
            world.owner.clone(),
            vec![
                (Some(core::any::TypeId::of::<Health>()), false),
                (None, true),
            ],
        );

        let mut writer = BundleWriter::query(&world.allocator, &mut queue, entity);
        assert_eq!(writer.test_entity(), entity);
        assert!(writer.world_owner().same(world.owner()));
        assert!(!writer.is_tag_component(&health));
        assert!(writer.is_tag_component(&marker));
        writer.insert(Health(1)).expect("typed insert");
        writer
            .insert_dynamic(health, Box::new(Health(2)))
            .expect("dynamic insert");
        writer.insert_tag_id(marker).expect("tag insert");

        let stale = EntityId::from_parts(99, 1);
        let mut stale_writer = BundleWriter::query(&world.allocator, &mut queue, stale);
        assert!(matches!(
            stale_writer.insert(Health(3)),
            Err(WorldError::StaleEntity { .. })
        ));
    }

    #[test]
    #[should_panic(expected = "query bundle writer has no world")]
    fn query_bundle_test_world_rejects_world_access() {
        let mut world = WorldBuilder::new().build().expect("world");
        let entity = world.spawn().expect("entity");
        let mut queue = crate::command::CommandQueue::configured(world.owner.clone(), vec![]);
        BundleWriter::query(&world.allocator, &mut queue, entity).test_world();
    }
}