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
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! # Tiny ECS //! //! The intention of this crate is that a basic ECS is provided, where //! you will be required to exercise a little additional control. This is //! somewhat due to some limitations, and also due to trying to maintain //! as little overhead as possible - this means no unneccesary copies/clones. //! //! Where most other ECS crates provide a mechanism for inserting "systems" //! in to the ECS to run against entities, this one leaves it out - you can //! think of it as a "system for entity/components". You will need to create //! external systems; these can be a function, a loop, or anything else. //! //! The basis of this ECS is the use of `bitmasks`. Each entity ID is in //! practice an internal index number in to an array which contains bitmasks. //! The bitmasks themselves keep track of what components the entity has. //! For the most part, bitmasks are handled for you, and some helper methods //! are available to hide their use, but there are also methods to get the //! bitmask for any ID if you are inclined to do some manual management. //! //! **Note:** defaults to bitmask of `u64` size (so 64 components). If you //! need a smaller mask the feature `bitmask_max_32` can be enabled for //! mask of `u32` size. //! //! **Attention:** borrows of `ComponentMap` are checked at runtime. //! //! # Examples //! //! ## Init with a capacity //! //! This is good to do if you know the size required //! as it will prevent many reallocs/moves as data is added. This affects //! both the entity and component map allocs (they will be equal in length). //! //! ``` //! use tiny_ecs::Entities; //! //! let mut entities = Entities::new(Some(1000), Some(24)); //! ``` //! //! ## Demonstrating use //! //! ``` //! use tiny_ecs::Entities; //! //! // These are the "components" we will use //! struct Vector1 { //! x: i32, //! } //! struct Vector2 { //! x: i32, //! y: i32, //! } //! struct Vector3 { //! x: i32, //! y: i32, //! z: i32, //! } //! //! // Initialize the Entity collection //! let mut entities = Entities::new(Some(3), Some(3)); //! //! // To create an entity you only need to add the first component using //! // a free slot //! let entity_1 = entities.add_entity(); //! assert!(entities.add_part(entity_1, Vector1 { x: 42 }).is_ok()); //! // And you can add more components to it //! // The entity is only considered newly created if no components existed before //! entities.add_part(entity_1, //! Vector3 { x: 3, //! y: 10, //! z: -12 }); //! //! // To add another entity you need another free slot //! let entity_2 = entities.add_entity(); //! assert!(entities.add_part(entity_2, Vector2 { x: 66, y: 6 }).is_ok()); //! assert!(entities.add_part(entity_2, Vector1 { x: 6 }).is_ok()); //!``` //! //! ## Access an entities part of type `<T>` //! ``` //! # use tiny_ecs::{Entities, ComponentMap}; //! # struct Vector3 {x: i32, y: i32, z: i32 } //! # let mut entities = Entities::new(Some(3), Some(3)); //! # let entity_1 = entities.add_entity(); //! # assert!(entities.add_part(entity_1, Vector3 { x: 3, y: 10, z: -12 }).is_ok()); //! // To get access to a part belonging to an entity you need //! // first to get the component map created for the part type //! // You need to 'anchor' this with a let or the ref is //! // dropped before you can use it //! let mut components = entities //! .borrow_mut::<Vector3>() //! .unwrap(); //! // You can then use the part by getting a reference //! let mut part = components.get_part_mut(entity_1).unwrap(); //! assert_eq!(part.z, -12); //! ``` //! //! ## Check if `Entity` contains a part type + remove part //! ``` //! # use tiny_ecs::Entities; //! # struct Vector1 {x: i32 } //! # let mut entities = Entities::new(Some(3), Some(3)); //! # let entity_1 = entities.add_entity(); //! # assert!(entities.add_part(entity_1, Vector1 { x: 3 }).is_ok()); //! // You can check if an entity contains a part with the type signature //! if entities.entity_contains::<Vector1>(entity_1) { //! assert!(entities.rm_part::<Vector1>(entity_1).is_ok()); //! } //! assert_eq!(entities.entity_contains::<Vector1>(entity_1), false); //! ``` //! //! ## A system that uses an `get_mut()` //! ``` //! # use tiny_ecs::{Entities, ComponentMap}; //! # struct Vector1 {x: i32 } //! # let mut entities = Entities::new(Some(3), Some(3)); //! # let entity_1 = entities.add_entity(); //! # assert!(entities.add_part(entity_1, Vector1 { x: 3 }).is_ok()); //! //! // Make a system of some form that takes a `ComponentMap<T>` arg //! fn some_system(mut components: &mut ComponentMap<Vector1>) { //! // You can then iterate over the components directly //! for (k, v) in components.get_mut() { //! v.x += 1; //! assert!(v.x > k as i32); //! } //! } //! # let mut components = entities.borrow_mut::<Vector1>().unwrap(); //! some_system(&mut components); //! ``` //! //! ## Get components for an entity ID list //! ``` //! # use tiny_ecs::{Entities, ComponentMap}; //! # struct Vector1 {x: i32 } //! # let mut entities = Entities::new(Some(3), Some(3)); //! # let entity_1 = entities.add_entity(); //! # assert!(entities.add_part(entity_1, Vector1 { x: 3 }).is_ok()); //! //! // A system that fetches the components for only the entities you are require //! fn second_system(active: &[usize], mut v1_map: &mut ComponentMap<Vector1>) { //! for id in active { //! if let Ok(part) = v1_map.get_part_mut(*id) { //! part.x = 42; //! } //! } //! } //! # let mut components = entities.borrow_mut::<Vector1>().unwrap(); //! second_system(&[0, 1, 2], &mut components); //! ``` //! //! ## A more complex system using ComponentMaps directly //! ``` //! # use tiny_ecs::{Entities, ComponentMap}; //! # struct Vector1 {x: i32 } //! # struct Vector2 {x: i32, y: i32 } //! # let mut entities = Entities::new(Some(3), Some(3)); //! # let entity_1 = entities.add_entity(); //! # assert!(entities.add_part(entity_1, Vector1 { x: 3 }).is_ok()); //! # assert!(entities.add_part(entity_1, Vector2 { x: 3, y: 3 }).is_ok()); //! //! // Or a system handles the `Entities` container directly //! fn other_system(active_ents: &[usize], entities: &mut Entities) { //! // You can mutably borrow multiple part types at once //! let mut v1_components = entities //! .borrow_mut::<Vector1>() //! .unwrap(); //! //! let mut v2_components = entities //! .borrow_mut::<Vector2>() //! .unwrap(); //! //! // But not have a mutable borrow and immutable borrow to the same //! // Fails at runtime! //! // let v2_components = entities.borrow::<Vector2>().unwrap(); //! // But you can have multiple immutable references to the same part //! for id in active_ents { //! if entities.entity_contains::<Vector1>(*id) && //! entities.entity_contains::<Vector2>(*id) { //! let v1_part = v1_components.get_part_mut(*id).unwrap(); //! let v2_part = v2_components.get_part_mut(*id).unwrap(); //! v1_part.x = 42; //! assert_ne!(v1_part.x, 43); //! assert_eq!(v1_part.x, 42); //! } //! } //! } //! other_system(&[0, 1, 2], &mut entities); //! ``` use std::any::{Any, TypeId}; use std::cell::{Ref, RefCell, RefMut}; use std::collections::HashMap; use std::error::Error; use std::fmt; use std::fmt::{Debug, Display}; use std::ops::{Deref, DerefMut}; use vec_map; use vec_map::VecMap; #[cfg(feature = "bitmask_max_32")] type BITMASK = u32; #[cfg(not(feature = "bitmask_max_32"))] type BITMASK = u64; #[cfg(feature = "bitmask_max_32")] const BITMASK_MAX: u32 = 32; #[cfg(not(feature = "bitmask_max_32"))] const BITMASK_MAX: u64 = 64; // Bitmask used to fill the initial mask list, and replace deleted entities pub const EMPTY: BITMASK = 0; pub enum ECSError { Borrow, BorrowMut, Downcast, DowncastMut, PtrRef, PtrMut, NoComponentMap, NoComponentForEntity, NoTypeMask, } impl Debug for ECSError { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(self.description(), f) } } impl Display for ECSError { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(self.description(), f) } } impl Error for ECSError { fn description(&self) -> &str { match self { ECSError::Borrow => "already borrowed", ECSError::BorrowMut => "already mutably borrowed", ECSError::Downcast => "could not downcast to ref", ECSError::DowncastMut => "could not downcast to mut ref", ECSError::PtrRef => "failed to convert pointer to ref", ECSError::PtrMut => "failed to convert pointer to mut", ECSError::NoComponentMap => "no part map for part type", ECSError::NoComponentForEntity => "part map does not contain part for entity", ECSError::NoTypeMask => "no type-mask for type", } } } /// Immutable reference container for `ComponentMap` #[derive(Debug)] pub struct MapRef<'a, T> { _borrow: Ref<'a, dyn Any>, value: &'a ComponentMap<T>, } impl<'a, T: 'static> MapRef<'a, T> { fn new(value: &'a RefCell<Box<dyn Any>>) -> Result<MapRef<'a, T>, ECSError> { let v = (unsafe { value.as_ptr().as_ref().ok_or(ECSError::PtrRef)? }) .downcast_ref::<ComponentMap<T>>() .ok_or(ECSError::Downcast)?; Ok(MapRef { value: v, _borrow: value.try_borrow().or(Err(ECSError::Borrow))?, }) } } impl<'a, T> Deref for MapRef<'a, T> { type Target = ComponentMap<T>; #[inline] fn deref(&self) -> &ComponentMap<T> { self.value } } /// Mutbale reference container for `ComponentMap` #[derive(Debug)] pub struct MapRefMut<'a, T> { _borrow: RefMut<'a, dyn Any>, value: &'a mut ComponentMap<T>, } impl<'a, T: 'static> MapRefMut<'a, T> { fn new(value: &'a RefCell<Box<dyn Any>>) -> Result<MapRefMut<'a, T>, ECSError> { let v = (unsafe { value.as_ptr().as_mut().ok_or(ECSError::PtrMut)? }) .downcast_mut::<ComponentMap<T>>() .ok_or(ECSError::DowncastMut)?; Ok(MapRefMut { value: v, _borrow: value.try_borrow_mut().or(Err(ECSError::BorrowMut))?, }) } } impl<'a, T> Deref for MapRefMut<'a, T> { type Target = ComponentMap<T>; #[inline] fn deref(&self) -> &ComponentMap<T> { self.value } } impl<'a, T> DerefMut for MapRefMut<'a, T> { #[inline] fn deref_mut(&mut self) -> &mut ComponentMap<T> { self.value } } /// `ComponentMap` is a container type for the components used by entities #[derive(Debug)] pub struct ComponentMap<T> { map: VecMap<T>, } impl<T> ComponentMap<T> { #[inline(always)] fn new(init_size: usize) -> ComponentMap<T> { ComponentMap { map: VecMap::with_capacity(init_size), } } #[inline(always)] fn insert(&mut self, id: usize, part: T) { self.map.insert(id, part); } #[inline(always)] fn remove(&mut self, id: usize) { self.map.remove(id); } /// Getting a reference to an entity part requires the entity ID #[inline(always)] pub fn get_part_ref(&self, id: usize) -> Result<&T, ECSError> { if let Some(part) = self.map.get(id) { return Ok(part); } Err(ECSError::NoComponentForEntity) } /// Getting a mutable reference to an entity part requires the entity ID /// /// # Example /// /// ``` /// # use tiny_ecs::{Entities, ComponentMap}; /// #[derive(Debug, PartialEq)] /// struct Test1 {} /// /// # let mut entities = Entities::new(Some(3), Some(3)); /// # let entity_1 = entities.add_entity(); /// # assert!(entities.add_part(entity_1, Test1 {}).is_ok()); /// let components = entities.borrow::<Test1>().unwrap(); /// let part = components.get_part_ref(entity_1).unwrap(); /// assert_eq!(part, &Test1 {}); /// // or /// let part = components.get_part_ref(entity_1).unwrap(); /// assert_eq!(part, &Test1 {}); /// ``` #[inline(always)] pub fn get_part_mut(&mut self, id: usize) -> Result<&mut T, ECSError> { if let Some(part) = self.map.get_mut(id) { return Ok(part); } Err(ECSError::NoComponentForEntity) } /// Returns a borrow of the inner hashmap of components #[inline(always)] pub fn get(&self) -> &VecMap<T> { &self.map } /// Returns a mutable borrow of the inner hashmap of components #[inline(always)] pub fn get_mut(&mut self) -> &mut VecMap<T> { &mut self.map } } /// This is the root of the ECS implementation #[derive(Debug)] pub struct Entities { entity_masks: Vec<BITMASK>, components: HashMap<BITMASK, RefCell<Box<dyn Any>>>, next_free_entity: usize, vacated_slots: Vec<usize>, type_masks: HashMap<TypeId, BITMASK>, next_typemask: BITMASK, } impl Default for Entities { /// Create a new `Entities` struct with no pre-allocated memory for maps fn default() -> Self { Entities::new(None, None) } } impl Entities { /// Create a new root entity container. /// /// - `entity_count` will initialize the entity map and new /// component maps to this size. This is a good thing to do to /// prevent unnecessary (re)allocations if you know the total /// active entity count. Entity removals will free up slots which /// are then reused instead of expanding the map. /// - `part_count` is as above, for total part types/kinds, there is /// a maximum of either 32 or 64 individual parts you can add of /// which the index starts at 0 to n-1 pub fn new(entity_count: Option<usize>, part_count: Option<usize>) -> Entities { if let Some(part_count) = part_count { if part_count as BITMASK > BITMASK_MAX { panic!( "Initial part count too large. Maximum of {} allowed", BITMASK_MAX ); } } Entities { entity_masks: vec![EMPTY; entity_count.unwrap_or(0)], components: HashMap::with_capacity(part_count.unwrap_or(0)), next_free_entity: 0, vacated_slots: Vec::new(), type_masks: HashMap::with_capacity(part_count.unwrap_or(0)), next_typemask: 1, } } /// Find the first `EMPTY` ID number to use /// /// As entities are only created by actually inserting new components in to /// the Entity structure, this should be called to find the first /// available entity slot. Slot states are determined by the mask /// it holds. #[inline] pub fn add_entity(&mut self) -> usize { // TODO: Use a recently freed list for faster vacated slot finding if let Some(slot) = self.vacated_slots.pop() { return slot; } self.entity_masks.push(EMPTY); self.next_free_entity += 1; return self.next_free_entity - 1; } /// Returns the mask of the requested entity enabling you to manually /// check composition using bitmasks. #[inline] pub fn get_entity_mask(&self, id: usize) -> BITMASK { self.entity_masks[id] } /// Returns the mask associated with the requested type. #[inline] pub fn get_type_mask<T: 'static>(&self) -> Result<BITMASK, ECSError> { if let Some(mask) = self.type_masks.get(&TypeId::of::<T>()) { return Ok(*mask); } Err(ECSError::NoTypeMask) } #[inline(always)] pub fn entity_contains<T: 'static>(&self, id: usize) -> bool { if let Some(entity_mask) = self.entity_masks.get(id) { if let Some(type_mask) = self.type_masks.get(&TypeId::of::<T>()) { if entity_mask & type_mask == *type_mask { return true; } } } false } /// Adding a part requires a valid slot along with the initialised data /// to use with the entity. Effectively creates the entity if the slot is /// currently empty. /// /// A bitmask is created internally for each data type added (only one per type). /// /// # Example /// /// ``` /// # use tiny_ecs::Entities; /// struct Test1 {} /// const TEST1: u32 = 1 << 2; /// /// # let mut entities = Entities::new(Some(3), Some(3)); /// let entity_1 = entities.add_entity(); /// assert!(entities.add_part(entity_1, Test1 {}).is_ok()); /// ``` #[inline] pub fn add_part<T: 'static>(&mut self, id: usize, part: T) -> Result<(), ECSError> { let tid = TypeId::of::<T>(); if (self.type_masks.len() as BITMASK) >= BITMASK_MAX { panic!("Out of bitmasks to assign to component type"); } if !self.type_masks.contains_key(&tid) { self.type_masks.insert(tid, self.next_typemask); let mask = self.next_typemask << 1; self.next_typemask = mask; } let type_mask = self.type_masks[&tid]; // add HashMap for these components if not exist let len = self.entity_masks.len(); self.components .entry(type_mask) .or_insert_with(|| RefCell::new(Box::new(ComponentMap::<T>::new(len)))); if let Some(col) = self.components.get_mut(&type_mask) { col.borrow_mut() .downcast_mut::<ComponentMap<T>>() .ok_or(ECSError::DowncastMut)? .insert(id, part); let old = self.entity_masks[id]; self.entity_masks[id] = old | type_mask; return Ok(()); } Err(ECSError::NoComponentMap) } /// Remove an entities part. If no components are left after part removal then /// the entity is considered deleted and an `EMPTY` (0) mask is inserted in /// its place. /// /// Removal requires the ID of the entity and the components type signature. /// /// # Example /// /// ``` /// # use tiny_ecs::{Entities, EMPTY}; /// #[derive(Debug, PartialEq)] /// struct Test1 {} /// /// # let mut entities = Entities::new(Some(3), Some(3)); /// # let entity_1 = entities.add_entity(); /// # assert!(entities.add_part(entity_1, Test1 {}).is_ok()); /// assert!(entities.rm_part::<Test1>(entity_1).is_ok()); /// assert_eq!(entities.get_entity_mask(entity_1), EMPTY); /// ``` #[inline] pub fn rm_part<T: 'static>(&mut self, id: usize) -> Result<(), ECSError> { let type_mask = self.type_masks[&TypeId::of::<T>()]; if let Some(map) = self.components.get_mut(&type_mask) { map.borrow_mut() .downcast_mut::<ComponentMap<T>>() .ok_or(ECSError::DowncastMut)? .remove(id); self.entity_masks[id] ^= type_mask; if self.entity_masks[id] == EMPTY { self.vacated_slots.push(id) } return Ok(()); } Err(ECSError::NoComponentMap) } /// Get a plain reference to the selected entity part map /// /// You may have multiple immutable references to the requested `ComponentMap` /// **type** but no mutable references if the same **typed** `ComponentMap` /// is currently referenced. /// /// - `Option` is whether or not there is a part of `<T>` for that entity. /// - Borrowing (`Ref`) is checked at runtime. /// /// # Example /// ``` /// # use tiny_ecs::{Entities, ComponentMap}; /// # struct Test1 { x: u32 } /// # let mut entities = Entities::new(Some(3), Some(3)); /// # let entity_1 = entities.add_entity(); /// # assert!(entities.add_part(entity_1, Test1 { x: 666 }).is_ok()); /// let components = entities /// .borrow::<Test1>() /// .unwrap(); /// let part = components.get_part_ref(entity_1).unwrap(); /// ``` #[inline(always)] pub fn borrow<T: 'static>(&self) -> Result<MapRef<T>, ECSError> { if let Some(type_mask) = self.type_masks.get(&TypeId::of::<T>()) { if let Some(components) = self.components.get(&type_mask) { return Ok(MapRef::new(components)?); } } Err(ECSError::NoComponentMap) } /// Get a mutable reference to the selected entity part map /// /// You may have only one mutable reference to the requested `ComponentMap` /// **type** and no immutable references. You can however, have multiple /// mutable references to different **types** of `ComponentMap` /// /// - `Result` covers if the map was able to be borrowed mutably or not. /// - Borrowing is checked at runtime. /// /// # Example /// ``` /// # use tiny_ecs::{Entities, ComponentMap}; /// # #[derive(Debug, PartialEq)] /// # struct Test1 { x: u32 } /// # let mut entities = Entities::new(Some(3), Some(3)); /// # let entity_1 = entities.add_entity(); /// # assert!(entities.add_part(entity_1, Test1 { x: 0 }).is_ok()); /// // Because we later need a ref to the same `Type` of map, the mut ref /// // will need to be scoped. If the later ref was of a different type, /// // eg: Vector2, then it wouldn't need scoping. /// { /// let mut components = entities /// .borrow_mut::<Test1>() /// .unwrap(); /// for id in 0..5 { /// if let Ok(part) = components.get_part_mut(id) { /// part.x = 42; /// } /// } /// } /// /// // Now get a ref to the modified part /// let components = entities.borrow::<Test1>().unwrap(); /// let part = components.get_part_ref(entity_1).unwrap(); /// assert_eq!(part.x, 42); /// ``` #[inline(always)] pub fn borrow_mut<T: 'static>(&self) -> Result<MapRefMut<T>, ECSError> { if let Some(type_mask) = self.type_masks.get(&TypeId::of::<T>()) { if let Some(components) = self.components.get(&type_mask) { return Ok(MapRefMut::new(components)?); } } Err(ECSError::NoComponentMap) } } #[cfg(test)] mod tests { use crate::Entities; #[test] fn add_entity_and_part_check_contains_and_mask() { struct Test1 {} struct Test2 {} struct Test3 {} let mut entities = Entities::new(Some(3), Some(3)); // Creating a new entity should find the next free slot // and then insert a new blank bitmask // Return entity number let entity_1 = entities.add_entity(); assert_eq!(entity_1, 0); assert!(entities.add_part(entity_1, Test1 {}).is_ok()); let entity_1_mask = entities.get_entity_mask(entity_1); // The mask for this entity should have been updated let type_mask = entities.get_type_mask::<Test1>().unwrap(); assert_eq!(entity_1_mask, type_mask); assert!(entities.entity_contains::<Test1>(entity_1)); assert!(!entities.entity_contains::<Test2>(entity_1)); assert!(entities.add_part(entity_1, Test3 {}).is_ok()); assert!(entities.entity_contains::<Test3>(entity_1)); // should increment entities.next_free_entity let e2 = entities.add_entity(); assert_eq!(e2, 1); } #[test] fn get_part_map_for_type_as_ref() { struct Test1 {} let mut entities = Entities::new(Some(3), Some(3)); // Should return None { let m = entities.borrow::<Test1>(); assert!(m.is_err()); } let entity_1 = entities.add_entity(); assert!(entities.add_part(entity_1, Test1 {}).is_ok()); // Should return the HashMap let map = entities.borrow::<Test1>(); assert!(map.is_ok()); let map = entities.borrow::<Test1>().unwrap(); assert!(map.get_part_ref(entity_1).is_ok()); } #[test] fn get_part_map_for_type_as_mut() { struct Test1 {} let mut entities = Entities::new(Some(3), Some(3)); // Should return None { let m = entities.borrow_mut::<Test1>(); assert!(m.is_err()); } let entity_1 = entities.add_entity(); assert!(entities.add_part(entity_1, Test1 {}).is_ok()); // Should return the HashMap let map = entities.borrow_mut::<Test1>(); assert!(map.is_ok()); let mut map = map.unwrap(); assert!(map.get_part_mut(entity_1).is_ok()); } #[test] fn components_ref_and_mut_diff_components_and_modify() { #[derive(Debug, PartialEq)] struct Test1 { x: u32, } #[derive(Debug, PartialEq)] struct Test2 { x: u32, } let mut entities = Entities::new(Some(3), Some(3)); let entity_1 = entities.add_entity(); assert!(entities.add_part(entity_1, Test1 { x: 66 }).is_ok()); assert!(entities.add_part(entity_1, Test2 { x: 42 }).is_ok()); let components = entities.borrow::<Test1>().unwrap(); let part = components.get_part_ref(entity_1).unwrap(); assert_eq!(part, &Test1 { x: 66 }); assert!(entities.entity_contains::<Test1>(entity_1)); { let mut components = entities.borrow_mut::<Test2>().unwrap(); let part = components.get_part_mut(entity_1).unwrap(); assert_eq!(part.x, 42); part.x = 666; assert_ne!(part.x, 42); } let mut _p = entities.borrow_mut::<Test2>().unwrap(); assert!(entities.borrow_mut::<Test2>().is_err()); } #[test] fn components_iter_ref() { struct Test1 { x: usize, } let mut entities = Entities::new(Some(3), Some(3)); let mut ids = Vec::new(); // 1 let id = entities.add_entity(); assert!(entities.add_part(id, Test1 { x: id }).is_ok()); ids.push(id); // 2 let id = entities.add_entity(); assert!(entities.add_part(id, Test1 { x: id }).is_ok()); ids.push(id); // 3 let id = entities.add_entity(); assert!(entities.add_part(id, Test1 { x: id }).is_ok()); ids.push(id); let components = entities.borrow::<Test1>().unwrap(); for (k, v) in components.get() { assert!(v.x == k); } } #[test] fn components_get_mut() { struct Test1 { x: usize, } let mut entities = Entities::new(Some(3), Some(3)); let mut ids = Vec::new(); // 1 let id = entities.add_entity(); assert!(entities.add_part(id, Test1 { x: id }).is_ok()); ids.push(id); // 2 let id = entities.add_entity(); assert!(entities.add_part(id, Test1 { x: id }).is_ok()); ids.push(id); // 3 let id = entities.add_entity(); assert!(entities.add_part(id, Test1 { x: id }).is_ok()); ids.push(id); let mut components = entities.borrow_mut::<Test1>().unwrap(); for (k, v) in components.get_mut() { v.x += 1; assert!(v.x > k); } } #[test] fn remove_components_then_entity() { #[derive(Debug, PartialEq)] struct Test1 {} #[derive(Debug, PartialEq)] struct Test2 { x: u32, } let mut entities = Entities::new(Some(3), Some(3)); let entity_1 = entities.add_entity(); assert!(entities.add_part(entity_1, Test1 {}).is_ok()); assert!(entities.add_part(entity_1, Test2 { x: 42 }).is_ok()); // rm and check entity components assert!(entities.entity_contains::<Test1>(entity_1)); assert!(entities.rm_part::<Test1>(entity_1).is_ok()); assert!(!entities.entity_contains::<Test1>(entity_1)); assert!(entities.entity_contains::<Test2>(entity_1)); // check masks let type_mask_2 = entities.get_type_mask::<Test2>().unwrap(); assert_eq!(entities.get_entity_mask(entity_1), type_mask_2); // Removing all components erases the entity assert!(entities.rm_part::<Test2>(entity_1).is_ok()); assert_eq!(entities.get_entity_mask(entity_1), 0); } }