pi_world/
world.rs

1/// system上只能看到Query等SystemParm参数,SystemParm参数一般包含:事件、单例和多例资源、实体、组件
2/// world上包含了全部的资源和实体,及实体原型。 加一个监听管理器,
3/// world上的数据(资源、实体和原型)的线程安全的保护仅在于保护容器,
4/// 由调度器生成的执行图,来保证正确的读写。
5/// 执行图会注册监听器来监听新增的原型
6/// 比如一个原型不可被多线程同时读写,是由执行图时分析依赖,先执行写的sys,再执行读的sys。
7/// 由于sys会进行组件的增删,导致实体对于的原型会变化,执行图可能会产生变化,执行图本身保证对原型的访问是安全的读写。
8/// 整理操作时,一般是在整个执行图执行完毕后,进行进行相应的调整。举例:
9///
10/// 如果sys上通过Alter来增删组件,则可以在entity插入时,分析出sys的依赖。除了首次原型创建时,时序不确定,其余的增删,sys会保证先写后读。
11/// 如果sys通过是MultiRes实现的CmdQueue来延迟动态增删组件,则sys就不会因此产生依赖,动态增删的结果就只能在可能在下一帧才会看到。
12///
13///
14use crate::alter::{AlterState, QueryAlterState};
15use crate::archetype::{
16    Archetype, ArchetypeIndex, ArchetypeInfo, ComponentInfo, Row, ShareArchetype,
17};
18use crate::column::{BlobRef, Column};
19#[cfg(debug_assertions)]
20use crate::column::{ARCHETYPE_INDEX, COMPONENT_INDEX};
21use crate::editor::{EditorState, EntityEditor};
22use crate::fetch::{ColumnTick, FetchComponents};
23use crate::filter::FilterComponents;
24use crate::insert::{Bundle, InsertState};
25use crate::listener::{EventListKey, ListenerMgr};
26use crate::multi_res::ResVec;
27use crate::prelude::Mut;
28use crate::query::{QueryError, QueryState};
29use crate::single_res::TickRes;
30use crate::system::{SystemMeta, TypeInfo};
31use crate::world_ptr::Ptr;
32use core::fmt::*;
33use core::result::Result;
34use std::marker::PhantomData;
35use dashmap::mapref::entry::Entry;
36use dashmap::DashMap;
37use fixedbitset::FixedBitSet;
38use pi_append_vec::{SafeVec, SafeVecIter};
39use pi_key_alloter::new_key_type;
40use std::any::{Any, TypeId};
41use std::borrow::Cow;
42use std::collections::{hash_map::Entry as StdEntry, HashMap};
43use std::mem::{self, size_of, transmute, ManuallyDrop};
44use std::ops::Deref;
45use std::ptr;
46use std::sync::atomic::Ordering;
47// use pi_map::hashmap::HashMap;
48// use pi_map::Map;
49use pi_null::Null;
50use pi_share::{Share, ShareUsize};
51use pi_slot::{Iter, SlotMap};
52
53new_key_type! {
54    pub struct Entity;
55}
56
57#[derive(Debug, Clone, Copy, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
58pub struct ComponentIndex(pub(crate) u32);
59impl ComponentIndex {
60    pub fn index(&self) -> usize {
61        self.0 as usize
62    }
63}
64impl From<u32> for ComponentIndex {
65    fn from(index: u32) -> Self {
66        Self(index)
67    }
68}
69impl From<usize> for ComponentIndex {
70    fn from(index: usize) -> Self {
71        Self(index as u32)
72    }
73}
74impl pi_null::Null for ComponentIndex {
75    fn null() -> Self {
76        Self(u32::null())
77    }
78    fn is_null(&self) -> bool {
79        self.0 == u32::null()
80    }
81}
82#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
83pub struct Tick(u32);
84impl Tick {
85    pub fn index(&self) -> usize {
86        self.0 as usize
87    }
88    pub fn max() -> Self {
89        Self(u32::MAX)
90    }
91}
92impl Deref for Tick {
93    type Target = u32;
94    fn deref(&self) -> &Self::Target {
95        &self.0
96    }
97}
98impl Null for Tick {
99    fn null() -> Self {
100        Self(0)
101    }
102    fn is_null(&self) -> bool {
103        self.0 == 0
104    }
105}
106impl From<u32> for Tick {
107    fn from(v: u32) -> Self {
108        Self(v)
109    }
110}
111impl From<usize> for Tick {
112    fn from(v: usize) -> Self {
113        Self(v as u32)
114    }
115}
116
117#[derive(Clone, Debug)]
118pub struct ArchetypeInit<'a>(pub &'a ShareArchetype, pub &'a World);
119#[derive(Clone, Debug)]
120pub struct ArchetypeOk<'a>(pub &'a ShareArchetype, pub ArchetypeIndex, pub &'a World);
121
122
123pub struct World {
124    pub(crate) single_res_map: HashMap<TypeId, usize>,
125    pub(crate) single_res_arr: Vec<Option<Share<dyn TickMut>>>,
126    pub(crate) multi_res_map: HashMap<TypeId, (Share<dyn Any + Send + Sync>, Share<ShareUsize>)>,
127    pub(crate) event_map: HashMap<TypeId, Share<dyn Settle>>, // 事件表
128    pub(crate) component_map: HashMap<TypeId, ComponentIndex>,
129    pub(crate) component_arr: Vec<Share<Column>>,
130    pub(crate) entities: SlotMap<Entity, EntityAddr>,
131    pub(crate) archetype_map: DashMap<u64, ShareArchetype>,
132    pub(crate) archetype_arr: SafeVec<ShareArchetype>,
133    pub(crate) archetype_arr_len: usize,
134    pub(crate) empty_archetype: ShareArchetype,
135    pub(crate) entity_editor_state: EditorState,
136    pub(crate) listener_mgr: ListenerMgr,
137    archetype_init_key: EventListKey,
138    archetype_ok_key: EventListKey,
139    // 世界当前的tick
140    tick: ShareUsize,
141    default_system_meta: SystemMeta,
142}
143impl Debug for World {
144    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
145        f.debug_struct("World")
146            .field("entitys", &self.entities)
147            .field("component_arr", &self.component_arr)
148            .field("archetype_arr", &self.archetype_arr)
149            .finish()
150    }
151}
152impl World {
153    #[inline]
154    pub fn create() -> Box<Self> {
155        // TODO, 这么做依然无法阻止Self发生移动,但会规避很多情况
156        Box::new(Self::new())
157    }
158    
159    fn new() -> Self {
160        #[cfg(debug_assertions)]
161        match std::env::var("ECS_DEBUG") {
162            Ok(r) => {
163                let r = r.split(",").map(|r| {
164                    if r == "*" {
165                        std::usize::MAX
166                    } else {
167                        r.parse::<usize>().unwrap()
168                    }
169
170                }).collect::<Vec<usize>>();
171                if r.len() == 2 {
172                    ARCHETYPE_INDEX.store(r[0], Ordering::Relaxed);
173                    COMPONENT_INDEX.store(r[1], Ordering::Relaxed); 
174                }
175            },
176            _ => (),
177        };
178
179        let listener_mgr = ListenerMgr::default();
180        let archetype_init_key = listener_mgr.init_register_event::<ArchetypeInit>();
181        let archetype_ok_key = listener_mgr.init_register_event::<ArchetypeOk>();
182        let mut empty = Archetype::new(Default::default());
183        empty.set_index(0usize.into());
184        empty.ready.store(true, Ordering::Relaxed);
185        let empty_archetype = ShareArchetype::new(empty);
186        let archetype_map = DashMap::new();
187        archetype_map.insert(0, empty_archetype.clone());
188        let archetype_arr = SafeVec::with_capacity(1);
189        archetype_arr.insert(empty_archetype.clone());
190        Self {
191            single_res_map: Default::default(),
192            single_res_arr: Default::default(),
193            multi_res_map: Default::default(),
194            event_map: Default::default(),
195            entities: Default::default(),
196            component_map: Default::default(),
197            component_arr: Default::default(),
198            archetype_map,
199            archetype_arr,
200            archetype_arr_len: 1,
201            empty_archetype,
202            listener_mgr,
203            archetype_init_key,
204            archetype_ok_key,
205            tick: ShareUsize::new(1),
206            entity_editor_state: Default::default(),
207            default_system_meta: SystemMeta::new(TypeInfo::of::<()>()),
208        }
209    }
210    // 获得世界当前的tick
211    pub fn tick(&self) -> Tick {
212        self.tick.load(Ordering::Relaxed).into()
213    }
214    // 递增世界当前的tick,一般是每执行图执行时递增
215    pub fn increment_tick(&self) -> Tick {
216        self.tick.fetch_add(1, Ordering::Relaxed).into()
217    }
218    // /// 批量插入
219    // pub fn batch_insert<'w, I, Ins>(&'w mut self, iter: I) -> InsertBatchIter<'w, I, Ins>
220    // where
221    //     I: Iterator<Item = Ins>,
222    //     Ins: Bundle,
223    // {
224    //     InsertBatchIter::new(self, iter.into_iter())
225    // }
226    // /// 创建一个插入器 todo 移除
227    // pub fn make_inserter<I: Bundle>(&mut self) -> Inserter<I> {
228    //     let components = I::components(Vec::new());
229    //     let ar = self.find_ar(components);
230    //     let s = I::init_item(self, &ar);
231    //     Inserter::new(self, InsertState::new(ar, s), self.tick())
232    // }
233    /// 获得实体的原型信息
234    pub fn get_entity_prototype(&self, entity: Entity) ->  Option<(&Cow<'static, str>, ArchetypeIndex)> {
235        self.entities.get(entity).map(|e| {
236            let ar_index = e.archetype_index();
237            let ar = self.archetype_arr.get(ar_index.index()).unwrap();
238            (ar.name(), ar_index.into())
239        })
240    }
241    /// 是否存在实体
242    pub fn contains(&self, entity: Entity) -> bool {
243        self.entities.contains_key(entity)
244    }
245    /// 获得指定组件的索引
246    pub fn get_component_index(&self, component_type_id: &TypeId) -> ComponentIndex {
247        self.component_map
248            .get(component_type_id)
249            .map_or(ComponentIndex::null(), |r| *r)
250    }
251    /// 获得指定组件的索引
252    pub fn add_component_indexs(
253        &mut self,
254        components: Vec<ComponentInfo>,
255        result: &mut Vec<(ComponentIndex, bool)>,
256        result_add: bool,
257    ) {
258        for c in components {
259            result.push((self.add_component_info(c).0, result_add));
260        }
261    }
262    /// 获得指定组件的索引
263    pub fn get_column_by_id(&self, component_type_id: &TypeId) -> Option<&Share<Column>> {
264        self.get_column(self.get_component_index(component_type_id))
265    }
266    /// 获得指定组件的索引
267    pub fn get_column(&self, index: ComponentIndex) -> Option<&Share<Column>> {
268        self.component_arr.get(index.index())
269    }
270    /// 获得指定组件的索引
271    pub unsafe fn get_column_unchecked(&self, index: ComponentIndex) -> &Share<Column> {
272        self.component_arr.get_unchecked(index.index())
273    }
274    /// 添加组件信息,如果重复,则返回原有的索引及是否tick变化 todo 改成mut
275    pub fn add_component_info(
276        &mut self,
277        mut info: ComponentInfo,
278    ) -> (ComponentIndex, Share<Column>) {
279        let tick_info = info.tick_info;
280        let index: ComponentIndex = match self.component_map.entry(*info.type_id()) {
281            StdEntry::Occupied(entry) => *entry.get(),
282            StdEntry::Vacant(entry) => {
283                let index = self.component_arr.len().into();
284                info.index = index;
285                let c = Share::new(Column::new(info));
286                self.component_arr.push(c.clone());
287                entry.insert(index);
288                return (index, c);
289            }
290        };
291        let column = unsafe { self.component_arr.get_unchecked_mut(index.index()) };
292        let c = unsafe { Share::get_mut_unchecked(column) };
293        let t = c.info.tick_info | tick_info;
294        if t != c.info.tick_info {
295            let tick = self.tick.load(Ordering::Relaxed).into();
296            c.info.info.tick_info = tick_info;
297            // 扫描当前列,将已有的实体设置tick
298            c.update(&self.archetype_arr, |r, row, _| {
299                r.set_tick_unchecked(row, tick);
300            });
301        }
302        (index, column.clone())
303    }
304    /// 初始化指定组件
305    pub fn init_component<T: 'static>(&mut self) -> ComponentIndex {
306        self.add_component_info(ComponentInfo::of::<T>(0)).0
307    }
308    /// 计算所有原型信息,设置了所有组件的索引,按索引大小进行排序
309    pub(crate) fn archetype_info(&mut self, components: Vec<ComponentInfo>) -> ArchetypeInfo {
310        let vec: Vec<Share<Column>> = components
311            .into_iter()
312            .map(|c| self.add_component_info(c).1)
313            .collect();
314        ArchetypeInfo::sort(vec)
315    }
316    /// 创建一个插入器
317    pub fn make_insert<B: Bundle>(&mut self) -> InsertState<B> {
318        let components = B::components(Vec::new());
319        let ar = self.find_ar(components);
320        let s = B::init_item(self, &ar);
321        InsertState::new(ar, s, Ptr::new(&mut self.default_system_meta), Ptr::new(self))
322    }
323    /// 兼容bevy的接口,提供query
324    pub fn query<Q: FetchComponents + 'static, F: FilterComponents + 'static = ()>(
325        &mut self,
326    ) -> QueryState<Q, F> {
327        self.make_query()
328    }
329    /// 创建一个查询器
330    pub fn make_query<Q: FetchComponents + 'static, F: FilterComponents + 'static = ()>(
331        &mut self,
332    ) -> QueryState<Q, F> {
333        self.default_system_meta.this_run = self.tick();
334        let meta = Ptr::new(&mut self.default_system_meta);
335        let mut state = QueryState::create(self, meta);
336        state.align();
337        state
338    }
339    /// 创建一个改变器
340    pub fn make_alter<
341        Q: FetchComponents + 'static,
342        F: FilterComponents + 'static,
343        A: Bundle + 'static,
344        D: Bundle + 'static,
345    >(
346        &mut self,
347    ) -> QueryAlterState<Q, F, A, D> {
348        self.default_system_meta.this_run = self.tick();
349        let meta = Ptr::new(&mut self.default_system_meta);
350        let mut query_state = QueryState::create(self, meta);
351        let mut alter_state =
352            AlterState::make(self, A::components(Vec::new()), D::components(Vec::new()));
353        query_state.align();
354        // 将新多出来的原型,创建原型空映射
355        alter_state.align(self,  &query_state.archetypes);
356        QueryAlterState(query_state, alter_state, Ptr::new(self), PhantomData)
357    }
358    /// 创建一个实体编辑器
359    pub fn make_entity_editor(&mut self) -> EntityEditor {
360        EntityEditor::new(self)
361    }
362
363    pub fn unsafe_world<'a>(&self) -> ManuallyDrop<&'a mut World> {
364        unsafe { transmute(self) }
365    }
366
367    pub(crate) fn empty_archetype(&self) -> &ShareArchetype {
368        &self.empty_archetype
369    }
370    pub fn len<'a>(&'a self) -> usize {
371        self.entities.len()
372    }
373
374    pub fn entities_iter<'a>(&'a self) -> Iter<'a, Entity, EntityAddr> {
375        self.entities.iter()
376    }
377    /// 插入指定的单例资源,返回索引
378    pub fn insert_single_res<T: 'static>(&mut self, value: T) -> usize {
379        let tid = TypeId::of::<T>();
380        let (flag, index) = self._insert_single_res(tid);
381        if flag {
382            self.single_res_arr[index] = Some(Share::new(TickRes::new(value)));
383        }
384        // let index = *self.single_res_map.entry(tid).or_insert_with(|| {
385        //     let index = self.single_res_arr.len();
386        //     self.single_res_arr.push(None);
387        //     index
388        // });
389        // if self.single_res_arr[index].is_none() {
390        //     self.single_res_arr[index] = Some(Share::new(TickRes::new(value)));
391        // }
392        index
393    }
394    
395    fn _insert_single_res(&mut self, tid: TypeId) -> (bool, usize) {
396        let index = *self.single_res_map.entry(tid).or_insert_with(|| {
397            let index = self.single_res_arr.len();
398            self.single_res_arr.push(None);
399            index
400        });
401        (self.single_res_arr[index].is_none(), index)
402    }
403
404    // 如果不存在单例类型, 则注册指定的单例资源(不插入具体值,只添加类型),返回索引
405    pub fn or_register_single_res(&mut self, type_info: TypeInfo) -> usize {
406        *self
407            .single_res_map
408            .entry(type_info.type_id)
409            .or_insert_with(|| {
410                let index = self.single_res_arr.len();
411                self.single_res_arr.push(None);
412                index
413            })
414    }
415
416    pub fn register_single_res<T: 'static>(&mut self) -> usize {
417        self._register_single_res(TypeId::of::<T>())
418    }
419    
420    pub fn _register_single_res(&mut self, tid: TypeId) -> usize {
421        *self
422            .single_res_map
423            .entry(tid)
424            .or_insert_with(|| {
425                let index = self.single_res_arr.len();
426                self.single_res_arr.push(None);
427                index
428            })
429    }
430
431    /// 如果单例不存在, 插入单例默认值
432    pub fn init_single_res<T: 'static + FromWorld>(&mut self) -> usize {
433        let tid = TypeId::of::<T>();
434        let (flag, index) = self._init_single_res(tid);
435        if flag {
436            let value = T::from_world(self);
437            self.single_res_arr[index] = Some(Share::new(TickRes::new(value)));
438        }
439        // let index = *self.single_res_map.entry(tid).or_insert_with(|| {
440        //     let index = self.single_res_arr.len();
441        //     self.single_res_arr.push(None);
442        //     index
443        // });
444        // if self.single_res_arr[index].is_none() {
445        //     let value = T::from_world(self);
446        //     self.single_res_arr[index] = Some(Share::new(TickRes::new(value)));
447        // }
448        index
449    }
450    pub fn _init_single_res(&mut self, tid: TypeId) -> (bool, usize) {
451        let index = *self.single_res_map.entry(tid).or_insert_with(|| {
452            let index = self.single_res_arr.len();
453            self.single_res_arr.push(None);
454            index
455        });
456        (self.single_res_arr[index].is_none(), index)
457    }
458
459    /// 用索引获得指定的只读单例资源
460    #[inline]
461    pub fn index_single_res<T: 'static>(&self, index: usize) -> Option<&TickRes<T>> {
462        // self.single_res_arr.get(index).map_or(None, |r| {
463        //     match r {
464        //         Some(r) => r.as_any().downcast_ref(),
465        //         None => None,
466        //     }
467        // })
468        match self._index_single_res(index) {
469            Some(r) => r.downcast_ref(),
470            None => None,
471        }
472    }
473    
474    // #[inline]
475    fn _index_single_res(&self, index: usize) -> Option<&dyn Any> {
476        self.single_res_arr.get(index).map_or(None, |r| {
477            match r {
478                Some(r) => Some(r.as_any()),
479                None => None,
480            }
481        })
482    }
483    /// 用索引获得指定的可变单例资源
484    #[inline]
485    pub fn index_single_res_mut<T: 'static>(
486        &mut self,
487        index: usize,
488    ) -> Option<&mut TickRes<T>> {
489        // self.single_res_arr.get_mut(index).map_or(None, |r| {
490        //     match r {
491        //         Some(r) => unsafe { Share::get_mut_unchecked(r).as_any_mut().downcast_mut() },
492        //         None => None,
493        //     }
494        // })
495        match self._index_single_res_mut(index) {
496            Some(r) => r.downcast_mut(),
497            None => None,
498        }
499    }
500    fn _index_single_res_mut(
501        &mut self,
502        index: usize,
503    ) -> Option<&mut dyn Any> {
504        self.single_res_arr.get_mut(index).map_or(None, |r| {
505            match r {
506                Some(r) => unsafe { Some(Share::get_mut_unchecked(r).as_any_mut()) },
507                None => None,
508            }
509        })
510    }
511    /// 获得指定的单例资源
512    // #[inline]
513    pub fn get_share_single_res<T: 'static>(&self) -> Option<Share<TickRes<T>>> {
514        let tid = TypeId::of::<T>();
515        self.get_single_res_any(&tid).map(|r| Share::downcast(r.clone().into_any()).unwrap())
516    }
517
518    /// 获得指定的单例资源
519    #[inline]
520    pub fn get_single_res<T: 'static>(&self) -> Option<&TickRes<T>> {
521        let tid = TypeId::of::<T>();
522        match self._get_single_res(&tid) {
523            Some(val) => val.downcast_ref(),
524            None => return None,
525        }
526    }
527    fn _get_single_res(&self, tid: &TypeId) -> Option<&dyn Any> {
528        match self.single_res_map.get(tid) {
529            Some(index) => self._index_single_res(*index),
530            None => return None,
531        }
532    }
533    /// 获得指定的单例资源
534    // #[inline]
535    pub fn get_single_res_mut<T: 'static>(&mut self) -> Option<&mut TickRes<T>> {
536        let tid = TypeId::of::<T>();
537        match self._get_single_res_mut(&tid) {
538            Some(index) => index.downcast_mut(),
539            None => return None,
540        }
541    }
542    fn _get_single_res_mut(&mut self, tid: &TypeId) -> Option<&mut dyn Any> {
543        match self.single_res_map.get(tid) {
544            Some(index) => self._index_single_res_mut(*index),
545            None => return None,
546        }
547    }
548    pub(crate) fn get_single_res_any(&self, tid: &TypeId) -> Option<&Share<dyn TickMut>> {
549        match self.single_res_map.get(tid) {
550            Some(index) => self.index_single_res_any(*index),
551            None => return None,
552        }
553    }
554    pub(crate) fn index_single_res_any(&self, index: usize) -> Option<&Share<dyn TickMut>> {
555        self.single_res_arr.get(index).map_or(None, |r| r.as_ref())
556    }
557
558    /// 初始化指定类型的多例资源
559    pub fn init_multi_res(&mut self, type_id: TypeId, vec: Share<dyn Any + Send + Sync>) -> (Share<dyn Any + Send + Sync>, Share<ShareUsize>) {
560        self.multi_res_map.entry(type_id).or_insert_with(|| (vec, Share::new(ShareUsize::new(0)))).clone()
561    }
562    /// 获得指定类型的多例资源
563    pub fn get_multi_res<T>(&self) -> Option<(Share<ResVec<T>>, Share<ShareUsize>)> {
564        let tid = TypeId::of::<T>();
565        self.multi_res_map.get(&tid).map(|(r, t)| {
566            (Share::downcast(r.clone()).unwrap(), t.clone())
567        })
568    }
569
570    /// 初始化事件记录
571    pub(crate) fn init_event_record(
572        &mut self,
573        type_id: TypeId,
574        event_record: Share<dyn Settle>,
575    ) -> Share<dyn Settle> {
576        let r = self
577            .event_map
578            .entry(type_id)
579            .or_insert_with(|| event_record);
580        r.clone()
581    }
582    /// 获得事件记录
583    pub(crate) fn get_event_record(&self, type_id: &TypeId) -> Option<Share<dyn Settle>> {
584        self.event_map.get(type_id).map(|r| r.clone())
585    }
586
587    /// 获得指定实体的指定组件
588    pub fn get_component<T: 'static>(&self, e: Entity) -> Result<&T, QueryError> {
589        let index = self.get_component_index(&TypeId::of::<T>());
590        self.get_component_by_index(e, index)
591    }
592    /// 获得指定实体的指定组件
593    pub fn get_component_mut<T: 'static>(
594        &mut self,
595        e: Entity,
596    ) -> Result<Mut<'static, T>, QueryError> {
597        let index = self.get_component_index(&TypeId::of::<T>());
598        self.get_component_mut_by_index(e, index)
599    }
600
601    /// 获得指定实体的指定组件
602    pub fn get_component_by_index<T: 'static>(
603        &self,
604        e: Entity,
605        index: ComponentIndex,
606    ) -> Result<&T, QueryError> {
607        // let addr = match self.entities.get(e) {
608        //     Some(v) => v,
609        //     None => return Err(QueryError::NoSuchEntity(e)),
610        // };
611        // let column = match self.get_column(index) {
612        //     Some(c) => c,
613        //     None => return Err(QueryError::NoSuchComponent(index)),
614        // };
615        // let column = column.blob_ref(addr.archetype_index());
616        // match column {
617        //     Some(c) => Ok(c.get::<T>(addr.row, e)),
618        //     None => Err(QueryError::MissingComponent(index, addr.archetype_index())),
619        // }
620        match self._get_component_by_index(e, index) {
621            Ok((c, addr)) => match c {
622                Some(c) => Ok(c.get::<T>(addr.row, e)),
623                None => Err(QueryError::MissingComponent(index, addr.archetype_index())),
624            },
625            Err(e) => Err(e),
626        }
627    }
628    
629    fn _get_component_by_index<'w>(
630        &'w self,
631        e: Entity,
632        index: ComponentIndex,
633    ) -> Result<(Option<BlobRef<'_>>, &'w EntityAddr), QueryError> {
634        let addr = match self.entities.get(e) {
635            Some(v) => v,
636            None => return Err(QueryError::NoSuchEntity(e)),
637        };
638        let column = match self.get_column(index) {
639            Some(c) => c,
640            None => return Err(QueryError::NoSuchComponent(index)),
641        };
642        let column = column.blob_ref(addr.archetype_index());
643        return Ok((column, addr));
644    }
645    /// 获得指定实体的指定组件
646    pub fn get_component_mut_by_index<T: 'static>(
647        &mut self,
648        e: Entity,
649        index: ComponentIndex,
650    ) -> Result<Mut<'static, T>, QueryError> {
651        let addr = match self.entities.get(e) {
652            Some(v) => v,
653            None => return Err(QueryError::NoSuchEntity(e)),
654        };
655        let column = match self.get_column(index) {
656            Some(c) => c,
657            None => return Err(QueryError::NoSuchComponent(index)),
658        };
659        let column = column.blob_ref(addr.archetype_index());
660        match column {
661            Some(c) => {
662                let t = self.tick();
663                let value: Mut<T> = Mut::new(&ColumnTick::new(c, t, t), e, addr.row);
664                Ok(unsafe { transmute(value) })
665            },
666            None => Err(QueryError::MissingComponent(index, addr.archetype_index())),
667        }
668    }
669
670    pub fn get_archetype(&self, index: ArchetypeIndex) -> Option<&ShareArchetype> {
671        self.archetype_arr.get(index.0 as usize)
672    }
673    pub(crate) unsafe fn get_archetype_unchecked(&self, index: ArchetypeIndex) -> &ShareArchetype {
674        self.archetype_arr.get_unchecked(index.0 as usize)
675    }
676    pub fn archetype_list<'a>(&'a self) -> SafeVecIter<'a, ShareArchetype> {
677        self.archetype_arr.iter()
678    }
679    // 返回原型及是否新创建 todo 改成mut
680    pub(crate) fn find_ar(&mut self, infos: Vec<ComponentInfo>) -> ShareArchetype {
681        let info = self.archetype_info(infos);
682        self.find_archtype(info)
683    }
684    // 返回原型及是否新创建
685    pub(crate) fn find_archtype(&self, info: ArchetypeInfo) -> ShareArchetype {
686        // 如果world上没有找到对应的原型,则创建并放入world中
687        let (mut ar, b) = match self.archetype_map.entry(info.id) {
688            Entry::Occupied(entry) => (entry.get().clone(), false),
689            Entry::Vacant(entry) => {
690                let ar = Share::new(Archetype::new(info));
691                entry.insert(ar.clone());
692                (ar, true)
693            }
694        };
695        if b {
696            // 通知原型创建,让各查询过滤模块初始化原型的记录列表,通知执行图更新
697            self.listener_mgr
698                .notify_event(self.archetype_init_key, ArchetypeInit(&ar, &self));
699            // 通知后,让原型就绪, 其他线程也就可以获得该原型
700            let ar_index = self.archtype_ok(&mut ar);
701            // println!("add archtype: {:?}", (ar.name(), ar_index));
702            self.listener_mgr
703                .notify_event(self.archetype_ok_key, ArchetypeOk(&ar, ar_index, &self));
704            ar
705        } else {
706            // 循环等待原型就绪
707            loop {
708                if !ar.ready() {
709                    std::hint::spin_loop();
710                }
711                return ar;
712            }
713        }
714    }
715    // 先事件通知调度器,将原型放入数组,之后其他system可以看到该原型
716    pub(crate) fn archtype_ok(&self, ar: &mut ShareArchetype) -> ArchetypeIndex {
717        let entry = self.archetype_arr.alloc_entry();
718        let index = entry.index();
719        let mut_ar = unsafe { Share::get_mut_unchecked(ar) };
720        mut_ar.set_index(index.into());
721        mut_ar.init_blobs(); // 初始化原型中的blob
722        ar.ready.store(true, Ordering::Relaxed);
723        entry.insert(ar.clone()); // entry销毁后, 其他线程通过archetype_arr就可以看见该原型
724        index.into()
725    }
726    /// 插入一个新的EntityAddr
727    // #[inline(always)]
728    pub(crate) fn insert_addr(&self, ar_index: ArchetypeIndex, row: Row) -> Entity {
729        self.entities.insert(EntityAddr::new(ar_index, row))
730    }
731    /// 替换Entity的原型及行
732    // #[inline(always)]
733    pub(crate) fn replace(&self, e: Entity, ar_index: ArchetypeIndex, row: Row) -> EntityAddr {
734        let addr = unsafe { self.entities.load_unchecked(e) };
735        mem::replace(addr, EntityAddr::new(ar_index, row))
736    }
737    /// 判断指定的实体是否存在
738    pub fn contains_entity(&self, e: Entity) -> bool {
739        self.entities.get(e).is_some()
740    }
741    /// 销毁指定的实体
742    pub fn destroy_entity(&mut self, e: Entity) -> Result<(), QueryError> {
743        let addr = match self.entities.get(e) {
744            Some(v) => *v,
745            None => return Err(QueryError::NoSuchEntity(e)),
746        };
747        if addr.row.is_null() {
748            self.entities.remove(e).unwrap();
749            return Ok(());
750        }
751        let ar = unsafe {
752            self.archetype_arr
753                .get_unchecked(addr.archetype_index().index())
754        };
755        let e = ar.destroy(addr.row);
756        if e.is_null() {
757            return Err(QueryError::NoSuchRow(addr.row));
758        }
759        self.entities.remove(e).unwrap();
760        Ok(())
761    }
762
763    /// 创建一个新的空实体
764    pub fn spawn_empty(&self) -> Entity {
765        self.entities
766            .insert(EntityAddr::new(0usize.into(), Row::null()))
767    }
768    /// 替换Entity的原型及行
769    // #[inline(always)]
770    pub(crate) fn replace_row(&self, e: Entity, row: Row) {
771        let addr = unsafe { self.entities.load_unchecked(e) };
772        addr.row = row;
773    }
774    /// 获得内存大小
775    pub fn mem_size(&self) -> usize {
776        let mut size = self.entities.mem_size();
777        // size += self.component_arr.capacity() * size_of::<Column>();
778        self.component_arr.iter().for_each(|item| {
779            size += item.memsize();
780        });
781        size += (self.component_arr.capacity() - self.component_arr.len()) * size_of::<Column>();
782        size += self.archetype_arr.capacity() * size_of::<Archetype>();
783        for ar in self.archetype_arr.iter() {
784            size += ar.mem_size();
785        }
786        size += self.listener_mgr.memsize();
787        size += self.archetype_arr_len;
788        size += self.archetype_map.len();
789        size += self.component_map.len();
790        size += self.single_res_arr.len();
791        size
792    }
793    /// 只有主调度完毕后,才能调用的整理方法,必须保证调用时没有其他线程读写world
794    pub fn settle(&mut self) {
795        self.settle_by(&mut Vec::new(), &mut FixedBitSet::new())
796    }
797    /// 只有全部的插件都注册完毕,准备开始运行前调用。如果单独有个注册过程,则add_component_info等都使用&mut self。 则可以使用普通vec,不再需要整理
798    pub fn init_ok(&mut self) {
799        // todo 整理 self.listener_mgr.settle(0);
800    }
801    /// 只有主调度完毕后,才能调用的整理方法,必须保证调用时没有其他线程读写world
802    pub fn settle_by(&mut self, action: &mut Vec<(Row, Row)>, set: &mut FixedBitSet) {
803        // 整理实体
804        self.entities.settle(0);
805        // 整理原型数组
806        self.archetype_arr.settle(0);
807        let len = self.archetype_arr.len();
808        if self.archetype_arr_len < len {
809            // 原型增加,则整理所有的列
810            for c in self.component_arr.iter_mut() {
811                let c = unsafe { Share::get_mut_unchecked(c) };
812                c.settle();
813            }
814            self.archetype_arr_len = len;
815        }
816        // 整理事件列表
817        for aer in self.event_map.values_mut() {
818            let er = unsafe { Share::get_mut_unchecked(aer) };
819            er.settle();
820        }
821        // 整理每个原型
822        // #[cfg(not(feature="rc"))]
823        for ar in self.archetype_arr.iter() {
824            let archetype = unsafe { Share::get_mut_unchecked(ar) };
825            archetype.settle(self, action, set);
826        }
827    }
828}
829unsafe impl Send for World {}
830unsafe impl Sync for World {}
831impl Default for World {
832    fn default() -> Self {
833        Self::new()
834    }
835}
836
837pub trait Downcast {
838    fn into_any(self: Share<Self>) -> Share<dyn Any + Send + Sync>;
839    fn into_box_any(self: Box<Self>) -> Box<dyn Any>;
840    fn as_any(&self) -> &dyn Any;
841    fn as_any_mut(&mut self) -> &mut dyn Any;
842}
843
844pub trait TickMut: Downcast {
845    fn get_tick(&self) -> Tick;
846    fn set_tick(&mut self, tick: Tick);
847}
848
849pub trait Settle: Downcast {
850    fn settle(&mut self);
851}
852
853/// Creates an instance of the type this trait is implemented for
854/// using data from the supplied [World].
855///
856/// This can be helpful for complex initialization or context-aware defaults.
857pub trait FromWorld {
858    /// Creates `Self` using data from the given [World]
859    fn from_world(world: &mut World) -> Self;
860}
861
862impl<T: Default> FromWorld for T {
863    default fn from_world(_world: &mut World) -> Self {
864        T::default()
865    }
866}
867
868pub trait SetFromWorld {
869    fn set_fn() -> Option<fn(&mut World, *mut u8)>;
870}
871impl<T> SetFromWorld for T {
872    default fn set_fn() -> Option<fn(&mut World, *mut u8)> {
873        None
874    }
875}
876impl<T: FromWorld> SetFromWorld for T {
877    fn set_fn() -> Option<fn(&mut World, *mut u8)> {
878        Some(|world, ptr| unsafe { ptr::write(ptr as *mut T, T::from_world(world)) })
879    }
880}
881
882
883#[derive(Debug, Default, Clone, Copy)]
884pub struct EntityAddr {
885    index: ArchetypeIndex,
886    pub(crate) row: Row,
887}
888unsafe impl Sync for EntityAddr {}
889unsafe impl Send for EntityAddr {}
890
891impl EntityAddr {
892    // #[inline(always)]
893    pub(crate) fn new(index: ArchetypeIndex, row: Row) -> Self {
894        EntityAddr {
895            index,
896            row,
897        }
898    }
899    #[inline(always)]
900    pub(crate) fn is_mark(&self) -> bool {
901        self.index.0 < 0
902    }
903    // #[inline(always)]
904    pub(crate) fn mark(&mut self) {
905        self.index = ArchetypeIndex(-self.index.0 - 1);
906    }
907    // #[inline(always)]
908    pub fn archetype_index(&self) -> ArchetypeIndex {
909        if self.index.0 >= 0 || self.index.is_null() {
910            self.index
911        } else {
912            ArchetypeIndex(-self.index.0 - 1)
913        }
914    }
915}