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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
use core::{any::type_name, marker::PhantomData};
use crate::{
action::LocalActionEncoder,
archetype::Archetype,
bundle::{Bundle, ComponentBundle, DynamicBundle, DynamicComponentBundle},
component::ComponentRegistry,
entity::{Entity, EntityId, EntityLoc, EntityRef, EntitySet, Location},
epoch::EpochId,
type_id, Component, NoSuchEntity,
};
use super::{
assert_registered_bundle, assert_registered_one, register_bundle, register_one, World,
WorldLocal,
};
/// Limits on reserving of space for entities and components
/// in archetypes when `spawn_batch` is used.
const MAX_SPAWN_RESERVE: usize = 1024;
impl World {
/// Reserves new entity.
///
/// The entity will be materialized before first mutation on the world happens.
/// Until then entity is alive and belongs to a dummy archetype.
/// Entity will be alive until despawned.
///
/// # Panics
///
/// Panics if new id cannot be allocated.
///
/// # Example
///
/// ```
/// # use edict::world::World;
/// let mut world = World::new();
/// let entity = world.allocate().id();
/// assert!(world.is_alive(entity));
/// world.despawn(entity).unwrap();
/// assert!(!world.is_alive(entity));
/// ```
#[inline(always)]
pub fn allocate(&self) -> EntityLoc<'_> {
self.entities.alloc()
}
/// Spawns a new entity in this world without components.
/// Returns [`EntityRef`] for the newly spawned entity.
/// Entity will be alive until [`World::despawn`] is called with [`EntityId`] of the spawned entity,
/// or despawn command recorded and executed by the [`World`].
///
/// # Panics
///
/// If new id cannot be allocated.
/// If too many entities are spawned.
/// Currently limit is set to `u32::MAX` entities per archetype and `usize::MAX` overall.
///
/// # Example
///
/// ```
/// # use edict::{World, ExampleComponent};
/// let mut world = World::new();
/// let mut entity = world.spawn_empty();
/// assert!(!entity.has_component::<ExampleComponent>());
/// ```
#[inline(always)]
pub fn spawn_empty(&mut self) -> EntityRef<'_> {
self.maintenance();
let (id, loc) = self
.entities
.spawn(0, |id| self.archetypes[0].spawn_empty(id));
unsafe { EntityRef::from_parts(id, loc, self.local()) }
}
/// Spawns a new entity in this world with provided component.
/// Returns [`EntityRef`] for the newly spawned entity.
/// Entity will be alive until [`World::despawn`] is called with [`EntityId`] of the spawned entity,
/// or despawn command recorded and executed by the [`World`].
///
/// # Panics
///
/// If new id cannot be allocated.
/// If too many entities are spawned.
/// Currently limit is set to `u32::MAX` entities per archetype and `usize::MAX` overall.
///
/// # Example
///
/// ```
/// # use edict::{World, ExampleComponent};
/// let mut world = World::new();
/// let mut entity = world.spawn_one(ExampleComponent);
/// assert!(entity.has_component::<ExampleComponent>());
/// let ExampleComponent = entity.remove().unwrap();
/// assert!(!entity.has_component::<ExampleComponent>());
/// ```
#[inline(always)]
pub fn spawn_one<T>(&mut self, component: T) -> EntityRef<'_>
where
T: Component,
{
self.maintenance();
let arch_idx = self.edges.insert(
&mut self.registry,
&mut self.archetypes,
0,
type_id::<T>(),
register_one::<T>,
);
let epoch = self.epoch.next_mut();
let (id, loc) = self.entities.spawn(arch_idx, |id| {
self.archetypes[arch_idx as usize].spawn_one(id, component, epoch)
});
unsafe { EntityRef::from_parts(id, loc, self.local()) }
}
/// Spawns a new entity in this world with provided component.
/// Returns [`EntityRef`] for the newly spawned entity.
/// Entity will be alive until [`World::despawn`] is called with [`EntityId`] of the spawned entity,
/// or despawn command recorded and executed by the [`World`].
///
/// Component must be previously registered.
/// If component implements [`Component`] it could be registered implicitly
/// on first call to [`World::spawn`], [`World::spawn_one`], [`World::spawn_batch`], [`World::insert`] or [`World::insert_bundle`] and their deferred versions.
/// Otherwise component must be pre-registered explicitly by [`WorldBuilder::register_component`](crate::world::WorldBuilder::register_component) or later by [`World::ensure_component_registered`].
/// Non [`Component`] type must be pre-registered by [`WorldBuilder::register_external`](crate::world::WorldBuilder::register_external) or later by [`World::ensure_external_registered`].
///
/// # Panics
///
/// If new id cannot be allocated.
/// If too many entities are spawned.
/// Currently limit is set to `u32::MAX` entities per archetype and `usize::MAX` overall.
///
/// # Example
///
/// ```
/// # use edict::World;
/// let mut world = World::new();
/// world.ensure_external_registered::<u32>();
/// let mut entity = world.spawn_one_external(42u32);
/// assert!(entity.has_component::<u32>());
/// ```
#[inline(always)]
pub fn spawn_one_external<T>(&mut self, component: T) -> EntityRef<'_>
where
T: 'static,
{
self.maintenance();
let arch_idx = self.edges.insert(
&mut self.registry,
&mut self.archetypes,
0,
type_id::<T>(),
assert_registered_one::<T>,
);
let epoch = self.epoch.next_mut();
let (id, loc) = self.entities.spawn(arch_idx, |id| {
self.archetypes[arch_idx as usize].spawn_one(id, component, epoch)
});
unsafe { EntityRef::from_parts(id, loc, self.local()) }
}
/// Spawns a new entity in this world with provided bundle of components.
/// Returns [`EntityRef`] for the newly spawned entity.
/// Entity will be alive until [`World::despawn`] is called with [`EntityId`] of the spawned entity,
/// or despawn command recorded and executed by the [`World`].
///
/// # Panics
///
/// If new id cannot be allocated.
/// If too many entities are spawned.
/// Currently limit is set to `u32::MAX` entities per archetype and `usize::MAX` overall.
///
/// # Example
///
/// ```
/// # use edict::{World, ExampleComponent};
/// let mut world = World::new();
/// let mut entity = world.spawn((ExampleComponent,));
/// assert!(entity.has_component::<ExampleComponent>());
/// let ExampleComponent = entity.remove().unwrap();
/// assert!(!entity.has_component::<ExampleComponent>());
/// ```
#[inline(always)]
pub fn spawn<B>(&mut self, bundle: B) -> EntityRef<'_>
where
B: DynamicComponentBundle,
{
self.maintenance();
self._spawn(bundle, register_bundle::<B>)
}
/// Spawns a new entity in this world with specific ID and bundle of components.
/// The `World` must be configured to never allocate this ID.
/// Spawned entity is populated with all components from the bundle.
/// Entity will be alive until [`World::despawn`] is called with the same [`EntityId`].
///
/// # Panics
///
/// Panics if the id is already used by the world.
///
/// # Example
///
/// ```
/// # use edict::{World, ExampleComponent, EntityId};
/// let mut world = World::new();
/// let id = EntityId::from_bits(42).unwrap();
/// let mut entity = world.spawn_at(id, (ExampleComponent,));
/// assert!(entity.has_component::<ExampleComponent>());
/// let ExampleComponent = entity.remove().unwrap();
/// assert!(!entity.has_component::<ExampleComponent>());
/// ```
#[inline(always)]
pub fn spawn_at<B>(&mut self, id: EntityId, bundle: B) -> EntityRef<'_>
where
B: DynamicComponentBundle,
{
self.maintenance();
let (spawned, entity) = self._spawn_at(id, bundle, register_bundle::<B>);
assert!(spawned);
entity
}
/// Spawns a new entity in this world with specific ID and bundle of components.
/// The `World` must be configured to never allocate this ID.
/// Spawned entity is populated with all components from the bundle.
/// Entity will be alive until [`World::despawn`] is called with the same [`EntityId`].
///
/// # Panics
///
/// Panics if the id is already used by the world.
///
/// # Example
///
/// ```
/// # use edict::{World, ExampleComponent, EntityId};
/// let mut world = World::new();
/// let id = EntityId::from_bits(42).unwrap();
/// let mut entity = world.spawn_or_insert(id, (ExampleComponent,));
/// assert!(entity.has_component::<ExampleComponent>());
/// let ExampleComponent = entity.remove().unwrap();
/// assert!(!entity.has_component::<ExampleComponent>());
/// ```
#[inline(always)]
pub fn spawn_or_insert<B>(&mut self, id: EntityId, bundle: B) -> EntityRef<'_>
where
B: DynamicComponentBundle,
{
self.maintenance();
let (_spawned, entity) = self._spawn_at(id, bundle, register_bundle::<B>);
entity
}
/// Spawns a new entity in this world with provided bundle of components.
/// Returns [`EntityRef`] handle to the newly spawned entity.
/// Spawned entity is populated with all components from the bundle.
/// Entity will be alive until despawned.
///
/// Components must be previously registered.
/// If component implements [`Component`] it could be registered implicitly
/// on first call to [`World::spawn`], [`World::spawn_one`], [`World::spawn_batch`], [`World::insert`] or [`World::insert_bundle`] and their deferred versions.
/// Otherwise component must be pre-registered explicitly by [`WorldBuilder::register_component`](crate::world::WorldBuilder::register_component) or later by [`World::ensure_component_registered`].
/// Non [`Component`] type must be pre-registered by [`WorldBuilder::register_external`](crate::world::WorldBuilder::register_external) or later by [`World::ensure_external_registered`].
///
/// # Panics
///
/// Panics if new id cannot be allocated.
///
/// # Example
///
/// ```
/// # use edict::{World, ExampleComponent};
/// let mut world = World::new();
/// world.ensure_external_registered::<u32>();
/// world.ensure_component_registered::<ExampleComponent>();
/// let mut entity = world.spawn_external((42u32, ExampleComponent));
/// assert!(entity.has_component::<u32>());
/// assert_eq!(entity.remove(), Some(42u32));
/// assert!(!entity.has_component::<u32>());
/// ```
#[inline(always)]
pub fn spawn_external<B>(&mut self, bundle: B) -> EntityRef<'_>
where
B: DynamicBundle,
{
self.maintenance();
self._spawn(bundle, assert_registered_bundle::<B>)
}
/// Spawns a new entity in this world with provided bundle of components.
/// The id must be unused by the world.
/// Spawned entity is populated with all components from the bundle.
/// Entity will be alive until despawned.
///
/// Components must be previously registered.
/// If component implements [`Component`] it could be registered implicitly
/// on first call to [`World::spawn`], [`World::spawn_one`], [`World::spawn_batch`], [`World::insert`] or [`World::insert_bundle`] and their deferred versions.
/// Otherwise component must be pre-registered explicitly by [`WorldBuilder::register_component`](crate::world::WorldBuilder::register_component) or later by [`World::ensure_component_registered`].
/// Non [`Component`] type must be pre-registered by [`WorldBuilder::register_external`](crate::world::WorldBuilder::register_external) or later by [`World::ensure_external_registered`].
///
/// # Panics
///
/// Panics if the id is already used by the world.
///
/// # Example
///
/// ```
/// # use edict::{World, ExampleComponent};
/// let mut world = World::new();
/// world.ensure_external_registered::<u32>();
/// world.ensure_component_registered::<ExampleComponent>();
/// let mut entity = world.spawn_external((42u32, ExampleComponent));
/// assert!(entity.has_component::<u32>());
/// assert_eq!(entity.remove(), Some(42u32));
/// assert!(!entity.has_component::<u32>());
/// ```
#[inline(always)]
pub fn spawn_external_at<B>(&mut self, id: EntityId, bundle: B) -> EntityRef<'_>
where
B: DynamicBundle,
{
self.maintenance();
let (spawned, entity) = self._spawn_at(id, bundle, assert_registered_bundle::<B>);
assert!(spawned);
entity
}
/// Umbrella method for spawning entity with new ID.
fn _spawn<B, F>(&mut self, bundle: B, register_bundle: F) -> EntityRef<'_>
where
B: DynamicBundle,
F: FnOnce(&mut ComponentRegistry, &B),
{
if !bundle.valid() {
panic!(
"Specified bundle `{}` is not valid. Check for duplicate component types",
type_name::<B>()
);
}
let arch_idx = self.edges.insert_bundle(
&mut self.registry,
&mut self.archetypes,
0,
&bundle,
|registry| register_bundle(registry, &bundle),
);
let epoch = self.epoch.next_mut();
let (id, loc) = self.entities.spawn(arch_idx, |id| {
self.archetypes[arch_idx as usize].spawn(id, bundle, epoch)
});
unsafe { EntityRef::from_parts(id, loc, self.local()) }
}
/// Umbrella method for spawning entity with existing ID.
/// Returns tuple of boolean flag indicating if entity was actually spawned
/// and [`EntityRef`] handle to the newly spawned entity.
///
/// If entity is not spawned, bundle is dropped.
fn _spawn_at<B, F>(
&mut self,
id: EntityId,
bundle: B,
register_bundle: F,
) -> (bool, EntityRef<'_>)
where
B: DynamicBundle,
F: FnOnce(&mut ComponentRegistry, &B),
{
if !bundle.valid() {
panic!(
"Specified bundle `{}` is not valid. Check for duplicate component types",
type_name::<B>()
);
}
let arch_idx = self.edges.insert_bundle(
&mut self.registry,
&mut self.archetypes,
0,
&bundle,
|registry| register_bundle(registry, &bundle),
);
let epoch = self.epoch.next_mut();
let (spawned, loc) = self.entities.spawn_at(id, arch_idx, || {
self.archetypes[arch_idx as usize].spawn(id, bundle, epoch)
});
(spawned, unsafe {
EntityRef::from_parts(id, loc, self.local())
})
}
/// Returns an iterator which spawns and yield entities
/// using bundles yielded from provided bundles iterator.
///
/// When bundles iterator returns `None`, returned iterator returns `None` too.
///
/// If bundles iterator is fused, returned iterator is fused too.
/// If bundles iterator is double-ended, returned iterator is double-ended too.
/// If bundles iterator has exact size, returned iterator has exact size too.
///
/// Skipping items on returned iterator will cause bundles iterator skip bundles and not spawn entities.
///
/// Returned iterator attempts to optimize storage allocation for entities
/// if consumed with functions like `fold`, `rfold`, `for_each` or `collect`.
///
/// When returned iterator is dropped, no more entities will be spawned
/// even if bundles iterator has items left.
#[inline(always)]
pub fn spawn_batch<B, I>(&mut self, bundles: I) -> SpawnBatch<'_, I::IntoIter>
where
I: IntoIterator<Item = B>,
B: ComponentBundle,
{
self.spawn_batch_impl(bundles, |registry| {
register_bundle(registry, &PhantomData::<B>)
})
}
/// Returns an iterator which spawns and yield entities
/// using bundles yielded from provided bundles iterator.
///
/// When bundles iterator returns `None`, returned iterator returns `None` too.
///
/// If bundles iterator is fused, returned iterator is fused too.
/// If bundles iterator is double-ended, returned iterator is double-ended too.
/// If bundles iterator has exact size, returned iterator has exact size too.
///
/// Skipping items on returned iterator will cause bundles iterator skip bundles and not spawn entities.
///
/// Returned iterator attempts to optimize storage allocation for entities
/// if consumed with functions like `fold`, `rfold`, `for_each` or `collect`.
///
/// When returned iterator is dropped, no more entities will be spawned
/// even if bundles iterator has items left.
///
/// Components must be previously registered.
/// If component implements [`Component`] it could be registered implicitly
/// on first call to [`World::spawn`], [`World::spawn_one`], [`World::spawn_batch`], [`World::insert`] or [`World::insert_bundle`] and their deferred versions.
/// Otherwise component must be pre-registered explicitly by [`WorldBuilder::register_component`](crate::world::WorldBuilder::register_component) or later by [`World::ensure_component_registered`].
/// Non [`Component`] type must be pre-registered by [`WorldBuilder::register_external`](crate::world::WorldBuilder::register_external) or later by [`World::ensure_external_registered`].
#[inline(always)]
pub fn spawn_batch_external<B, I>(&mut self, bundles: I) -> SpawnBatch<'_, I::IntoIter>
where
I: IntoIterator<Item = B>,
B: Bundle,
{
self.spawn_batch_impl(bundles, |registry| {
assert_registered_bundle(registry, &PhantomData::<B>)
})
}
fn spawn_batch_impl<B, I, F>(
&mut self,
bundles: I,
register_bundle: F,
) -> SpawnBatch<'_, I::IntoIter>
where
I: IntoIterator<Item = B>,
B: Bundle,
F: FnOnce(&mut ComponentRegistry),
{
if !B::static_valid() {
panic!(
"Specified bundle `{}` is not valid. Check for duplicate component types",
type_name::<B>()
);
}
self.maintenance();
let arch_idx = self.edges.insert_bundle(
&mut self.registry,
&mut self.archetypes,
0,
&PhantomData::<I::Item>,
register_bundle,
);
let epoch = self.epoch.next_mut();
let archetype = &mut self.archetypes[arch_idx as usize];
let entities = &mut self.entities;
SpawnBatch {
bundles: bundles.into_iter(),
epoch,
arch_idx,
archetype,
entities,
}
}
pub(crate) fn spawn_reserve<B>(&mut self, additional: u32)
where
B: Bundle,
{
self.entities.reserve(additional);
let arch_idx = self.edges.insert_bundle(
&mut self.registry,
&mut self.archetypes,
0,
&PhantomData::<B>,
|registry| assert_registered_bundle(registry, &PhantomData::<B>),
);
let archetype = &mut self.archetypes[arch_idx as usize];
archetype.reserve(additional);
}
/// Despawns an entity with specified id.
/// Returns [`Err(NoSuchEntity)`] if entity does not exists.
///
/// # Example
///
/// ```
/// # use edict::{World, ExampleComponent};
/// let mut world = World::new();
/// let entity = world.spawn((ExampleComponent,)).id();
/// assert!(world.despawn(entity).is_ok(), "Entity should be despawned by this call");
/// assert!(world.despawn(entity).is_err(), "Already despawned");
/// ```
#[inline(always)]
pub fn despawn(&mut self, entity: impl Entity) -> Result<(), NoSuchEntity> {
self.maintenance();
let loc = self.entities.despawn(entity.id()).ok_or(NoSuchEntity)?;
let encoder = LocalActionEncoder::new(self.action_buffer.get_mut(), &self.entities);
let opt_id = unsafe {
self.archetypes[loc.arch as usize].despawn_unchecked(entity.id(), loc.idx, encoder)
};
if let Some(id) = opt_id {
self.entities.set_location(id, loc)
}
self.execute_local_actions();
Ok(())
}
/// Special-case despawn method for [`EntityRef::despawn`].
/// This method uses branch elimination for non-existent entity case
/// and prevents data dependencies between removing entity from
/// `EntitySet` and `Archetype`.
#[inline(always)]
pub(crate) unsafe fn despawn_ref(&mut self, id: EntityId, loc: Location) {
self.maintenance();
let real_loc = self.entities.despawn(id).unwrap_unchecked();
debug_assert_eq!(real_loc, loc, "Entity location mismatch");
let encoder = LocalActionEncoder::new(self.action_buffer.get_mut(), &self.entities);
let opt_id =
unsafe { self.archetypes[loc.arch as usize].despawn_unchecked(id, loc.idx, encoder) };
if let Some(id) = opt_id {
self.entities.set_location(id, loc)
}
self.execute_local_actions();
}
}
/// Spawning iterator. Produced by [`World::spawn_batch`].
pub struct SpawnBatch<'a, I> {
bundles: I,
epoch: EpochId,
arch_idx: u32,
archetype: &'a mut Archetype,
entities: &'a mut EntitySet,
}
impl<B, I> SpawnBatch<'_, I>
where
I: Iterator<Item = B>,
B: Bundle,
{
/// Spawns the rest of the entities.
/// The bundles iterator will be exhausted.
/// If bundles iterator is fused, calling this method again will
/// never spawn entities.
///
/// This method won't return IDs of spawned entities.
#[inline(always)]
pub fn spawn_all(&mut self) {
let additional = iter_reserve_hint(&self.bundles);
self.entities.reserve(additional);
self.archetype.reserve(additional);
let entities = &mut self.entities;
let archetype = &mut self.archetype;
let arch_idx = self.arch_idx;
let epoch = self.epoch;
self.bundles.by_ref().for_each(|bundle| {
entities.spawn(arch_idx, |id| archetype.spawn(id, bundle, epoch));
})
}
}
impl<'a, B, I> Iterator for SpawnBatch<'a, I>
where
I: Iterator<Item = B>,
B: Bundle,
{
type Item = EntityLoc<'a>;
#[inline(always)]
fn next(&mut self) -> Option<EntityLoc<'a>> {
let bundle = self.bundles.next()?;
let (id, loc) = self.entities.spawn(self.arch_idx, |id| {
self.archetype.spawn(id, bundle, self.epoch)
});
Some(EntityLoc::from_parts(id, loc))
}
#[inline(always)]
fn nth(&mut self, n: usize) -> Option<EntityLoc<'a>> {
// `SpawnBatch` explicitly does NOT spawn entities that are skipped.
let bundle = self.bundles.nth(n)?;
let (id, loc) = self.entities.spawn(self.arch_idx, |id| {
self.archetype.spawn(id, bundle, self.epoch)
});
Some(EntityLoc::from_parts(id, loc))
}
#[inline(always)]
fn size_hint(&self) -> (usize, Option<usize>) {
self.bundles.size_hint()
}
#[inline(always)]
fn fold<T, F>(mut self, init: T, mut f: F) -> T
where
F: FnMut(T, EntityLoc<'a>) -> T,
{
let additional = iter_reserve_hint(&self.bundles);
self.entities.reserve(additional);
self.archetype.reserve(additional);
let entities = &mut self.entities;
let archetype = &mut self.archetype;
let arch_idx = self.arch_idx;
let epoch = self.epoch;
self.bundles.fold(init, |acc, bundle| {
let (id, loc) = entities.spawn(arch_idx, |id| archetype.spawn(id, bundle, epoch));
f(acc, EntityLoc::from_parts(id, loc))
})
}
#[inline(always)]
fn collect<T>(self) -> T
where
T: FromIterator<EntityLoc<'a>>,
{
// `FromIterator::from_iter` would probably just call `fn next()`
// until the end of the iterator.
//
// Hence we should reserve space in archetype here.
let additional = iter_reserve_hint(&self.bundles);
self.entities.reserve(additional);
self.archetype.reserve(additional);
FromIterator::from_iter(self)
}
}
impl<B, I> ExactSizeIterator for SpawnBatch<'_, I>
where
I: ExactSizeIterator<Item = B>,
B: Bundle,
{
#[inline(always)]
fn len(&self) -> usize {
self.bundles.len()
}
}
impl<'a, B, I> DoubleEndedIterator for SpawnBatch<'a, I>
where
I: DoubleEndedIterator<Item = B>,
B: Bundle,
{
fn next_back(&mut self) -> Option<EntityLoc<'a>> {
let bundle = self.bundles.next_back()?;
let (id, loc) = self.entities.spawn(self.arch_idx, |id| {
self.archetype.spawn(id, bundle, self.epoch)
});
Some(EntityLoc::from_parts(id, loc))
}
fn nth_back(&mut self, n: usize) -> Option<EntityLoc<'a>> {
// No reason to create entities
// for which the only reference is immediately dropped
let bundle = self.bundles.nth_back(n)?;
let (id, loc) = self.entities.spawn(self.arch_idx, |id| {
self.archetype.spawn(id, bundle, self.epoch)
});
Some(EntityLoc::from_parts(id, loc))
}
fn rfold<T, F>(mut self, init: T, mut f: F) -> T
where
Self: Sized,
F: FnMut(T, EntityLoc<'a>) -> T,
{
self.archetype.reserve(iter_reserve_hint(&self.bundles));
let entities = &mut self.entities;
let archetype = &mut self.archetype;
let arch_idx = self.arch_idx;
let epoch = self.epoch;
self.bundles.rfold(init, |acc, bundle| {
let (id, loc) = entities.spawn(arch_idx, |id| archetype.spawn(id, bundle, epoch));
f(acc, EntityLoc::from_parts(id, loc))
})
}
}
impl<B, I> core::iter::FusedIterator for SpawnBatch<'_, I>
where
I: core::iter::FusedIterator<Item = B>,
B: Bundle,
{
}
pub(crate) fn iter_reserve_hint(iter: &impl Iterator) -> u32 {
let (lower, upper) = iter.size_hint();
match (lower, upper) {
(lower, None) => lower.min(u32::MAX as usize) as u32,
(lower, Some(upper)) => {
// Iterator is consumed in full, so reserve at least `lower`.
lower
.max(upper.min(MAX_SPAWN_RESERVE))
.min(u32::MAX as usize) as u32
}
}
}
impl WorldLocal {
/// Spawns a new entity in this world with provided component.
/// Returns [`EntityRef`] for the newly spawned entity.
/// Entity will be alive until [`World::despawn`] is called with [`EntityId`] of the spawned entity,
/// or despawn command recorded and executed by the [`World`].
///
/// # Panics
///
/// If new id cannot be allocated.
/// If too many entities are spawned.
/// Currently limit is set to `u32::MAX` entities per archetype and `usize::MAX` overall.
///
/// This is deferred version of [`World::spawn_one`].
/// It can be used on shared `WorldLocal` reference.
/// Entity is created immediatelly in reserved state.
/// And spawning operation is enqueued to be executed when [`World::run_deferred`] is called
/// or when mutable operation is performed on the world.
///
/// # Example
///
/// ```
/// # use edict::{world::WorldLocal, ExampleComponent};
/// let mut world = WorldLocal::new();
/// let entity = world.spawn_one_defer(ExampleComponent);
///
/// // Entity is alive when reserved.
/// assert!(world.is_alive(entity));
/// assert!(!world.try_has_component::<ExampleComponent>(entity).unwrap());
///
/// world.run_deferred();
///
/// assert!(world.is_alive(entity));
/// assert!(world.try_has_component::<ExampleComponent>(entity).unwrap());
/// ```
#[inline(always)]
pub fn spawn_one_defer<T>(&self, component: T) -> EntityId
where
T: Component,
{
let id = self.allocate().id();
self.insert_defer(id, component);
id
}
/// Spawns a new entity in this world with provided component.
/// Returns [`EntityRef`] for the newly spawned entity.
/// Entity will be alive until [`World::despawn`] is called with [`EntityId`] of the spawned entity,
/// or despawn command recorded and executed by the [`World`].
///
/// Component must be previously registered.
/// If component implements [`Component`] it could be registered implicitly
/// on first call to [`World::spawn`], [`World::spawn_one`], [`World::spawn_batch`], [`World::insert`] or [`World::insert_bundle`] and their deferred versions.
/// Otherwise component must be pre-registered explicitly by [`WorldBuilder::register_component`](crate::world::WorldBuilder::register_component) or later by [`World::ensure_component_registered`].
/// Non [`Component`] type must be pre-registered by [`WorldBuilder::register_external`](crate::world::WorldBuilder::register_external) or later by [`World::ensure_external_registered`].
///
/// # Panics
///
/// If new id cannot be allocated.
/// If too many entities are spawned.
/// Currently limit is set to `u32::MAX` entities per archetype and `usize::MAX` overall.
///
/// This is deferred version of [`World::spawn_one_external`].
/// It can be used on shared `WorldLocal` reference.
/// Entity is created immediatelly in reserved state.
/// And spawning operation is enqueued to be executed when [`World::run_deferred`] is called
/// or when mutable operation is performed on the world.
///
/// # Example
///
/// ```
/// # use edict::world::{WorldLocal};
/// let mut world = WorldLocal::new();
/// world.ensure_external_registered::<u32>();
/// let mut entity = world.spawn_one_external_defer(42u32);
///
/// assert!(world.is_alive(entity));
/// assert!(!world.try_has_component::<u32>(entity).unwrap());
///
/// world.run_deferred();
///
/// assert!(world.try_has_component::<u32>(entity).unwrap());
/// ```
#[inline(always)]
pub fn spawn_one_external_defer<T>(&self, component: T) -> EntityId
where
T: 'static,
{
let id = self.allocate().id();
self.insert_external_defer(id, component);
id
}
/// Spawns a new entity in this world with provided bundle of components.
/// Returns [`EntityRef`] for the newly spawned entity.
/// Entity will be alive until [`World::despawn`] is called with [`EntityId`] of the spawned entity,
/// or despawn command recorded and executed by the [`World`].
///
/// Component must be previously registered.
/// If component implements [`Component`] it could be registered implicitly
/// on first call to [`World::spawn`], [`World::spawn_one`], [`World::spawn_batch`], [`World::insert`] or [`World::insert_bundle`] and their deferred versions.
/// Otherwise component must be pre-registered explicitly by [`WorldBuilder::register_component`](crate::world::WorldBuilder::register_component) or later by [`World::ensure_component_registered`].
///
/// This is deferred version of [`World::spawn`].
/// It can be used on shared `WorldLocal` reference.
/// Entity is created immediatelly in reserved state.
/// And spawning operation is enqueued to be executed when [`World::run_deferred`] is called
/// or when mutable operation is performed on the world.
///
/// # Panics
///
/// If new id cannot be allocated.
/// If too many entities are spawned.
/// Currently limit is set to `u32::MAX` entities per archetype and `usize::MAX` overall.
///
/// # Example
///
/// ```
/// # use edict::{world::WorldLocal, ExampleComponent};
/// let mut world = WorldLocal::new();
/// let mut entity = world.spawn_defer((ExampleComponent,));
///
/// assert!(world.is_alive(entity));
/// assert!(!world.try_has_component::<ExampleComponent>(entity).unwrap());
///
/// world.run_deferred();
///
/// assert!(world.try_has_component::<ExampleComponent>(entity).unwrap());
/// ```
#[inline(always)]
pub fn spawn_defer<B>(&self, bundle: B) -> EntityId
where
B: DynamicComponentBundle,
{
let id = self.allocate().id();
self.insert_bundle_defer(id, bundle);
id
}
/// Spawns a new entity in this world with provided bundle of components.
/// Returns [`EntityRef`] handle to the newly spawned entity.
/// Spawned entity is populated with all components from the bundle.
/// Entity will be alive until despawned.
///
/// Components must be previously registered.
/// If component implements [`Component`] it could be registered implicitly
/// on first call to [`World::spawn`], [`World::spawn_one`], [`World::spawn_batch`], [`World::insert`] or [`World::insert_bundle`] and their deferred versions.
/// Otherwise component must be pre-registered explicitly by [`WorldBuilder::register_component`](crate::world::WorldBuilder::register_component) or later by [`World::ensure_component_registered`].
/// Non [`Component`] type must be pre-registered by [`WorldBuilder::register_external`](crate::world::WorldBuilder::register_external) or later by [`World::ensure_external_registered`].
///
/// This is deferred version of [`World::spawn_external`].
/// It can be used on shared `WorldLocal` reference.
/// Entity is created immediatelly in reserved state.
/// And spawning operation is enqueued to be executed when [`World::run_deferred`] is called
/// or when mutable operation is performed on the world.
///
/// # Panics
///
/// Panics if new id cannot be allocated.
///
/// # Example
///
/// ```
/// # use edict::world::WorldLocal;
/// let mut world = WorldLocal::new();
/// world.ensure_external_registered::<u32>();
/// let mut entity = world.spawn_external_defer((42u32,));
///
/// assert!(world.is_alive(entity));
/// assert!(!world.try_has_component::<u32>(entity).unwrap());
///
/// world.run_deferred();
///
/// assert!(world.try_has_component::<u32>(entity).unwrap());
/// ```
#[inline(always)]
pub fn spawn_external_defer<B>(&self, bundle: B) -> EntityId
where
B: DynamicBundle + 'static,
{
let id = self.allocate().id();
self.insert_external_bundle_defer(id, bundle);
id
}
/// Returns an iterator which spawns and yield entities
/// using bundles yielded from provided bundles iterator.
///
/// When bundles iterator returns `None`, returned iterator returns `None` too.
///
/// If bundles iterator is fused, returned iterator is fused too.
/// If bundles iterator is double-ended, returned iterator is double-ended too.
/// If bundles iterator has exact size, returned iterator has exact size too.
///
/// Skipping items on returned iterator will cause bundles iterator skip bundles and not spawn entities.
///
/// Returned iterator attempts to optimize storage allocation for entities
/// if consumed with functions like `fold`, `rfold`, `for_each` or `collect`.
///
/// When returned iterator is dropped, no more entities will be spawned
/// even if bundles iterator has items left.
///
/// This is deferred version of [`World::spawn_batch`].
/// It can be used on shared `WorldLocal` reference.
/// Operation is queued to be executed when [`World::run_deferred`] is called
/// or when mutable operation is performed on the world.
#[inline(always)]
pub fn spawn_batch_defer<B, I>(&self, bundles: I)
where
I: IntoIterator<Item = B> + 'static,
B: ComponentBundle,
{
self.defer(|world| {
let _ = world.spawn_batch(bundles);
})
}
/// Returns an iterator which spawns and yield entities
/// using bundles yielded from provided bundles iterator.
///
/// When bundles iterator returns `None`, returned iterator returns `None` too.
///
/// If bundles iterator is fused, returned iterator is fused too.
/// If bundles iterator is double-ended, returned iterator is double-ended too.
/// If bundles iterator has exact size, returned iterator has exact size too.
///
/// Skipping items on returned iterator will cause bundles iterator skip bundles and not spawn entities.
///
/// Returned iterator attempts to optimize storage allocation for entities
/// if consumed with functions like `fold`, `rfold`, `for_each` or `collect`.
///
/// When returned iterator is dropped, no more entities will be spawned
/// even if bundles iterator has items left.
///
/// Components must be previously registered.
/// If component implements [`Component`] it could be registered implicitly
/// on first call to [`World::spawn`], [`World::spawn_one`], [`World::spawn_batch`], [`World::insert`] or [`World::insert_bundle`] and their deferred versions.
/// Otherwise component must be pre-registered explicitly by [`WorldBuilder::register_component`](crate::world::WorldBuilder::register_component) or later by [`World::ensure_component_registered`].
/// Non [`Component`] type must be pre-registered by [`WorldBuilder::register_external`](crate::world::WorldBuilder::register_external) or later by [`World::ensure_external_registered`].
///
/// This is deferred version of [`World::spawn_batch_external`].
/// It can be used on shared `WorldLocal` reference.
/// Operation is queued to be executed when [`World::run_deferred`] is called
/// or when mutable operation is performed on the world.
#[inline(always)]
pub fn spawn_batch_external_defer<B, I>(&self, bundles: I)
where
I: IntoIterator<Item = B> + 'static,
B: Bundle,
{
self.defer(|world| {
let _ = world.spawn_batch_external(bundles);
})
}
/// Despawns an entity with specified id.
/// Returns [`Err(NoSuchEntity)`] if entity does not exists.
///
/// This is deferred version of [`World::despawn`].
/// It can be used on shared `WorldLocal` reference.
/// Operation is queued to be executed when [`World::run_deferred`] is called
/// or when mutable operation is performed on the world.
///
/// # Example
///
/// ```
/// # use edict::{World, ExampleComponent};
/// let mut world = World::new();
/// let entity = world.spawn((ExampleComponent,)).id();
/// assert!(world.despawn(entity).is_ok(), "Entity should be despawned by this call");
/// assert!(world.despawn(entity).is_err(), "Already despawned");
/// ```
#[inline(always)]
pub fn despawn_defer(&self, entity: impl Entity) {
let id = entity.id();
self.defer(move |world| {
let _ = world.despawn(id);
})
}
}