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
//! Entities, resources, components, and general world management. pub use self::comp::Component; pub use self::entity::{CreateIterAtomic, Entities, EntitiesRes, Entity, EntityResBuilder, Generation, Index}; pub use self::lazy::{LazyBuilder, LazyUpdate}; use self::entity::Allocator; use std::borrow::Borrow; use shred::{Fetch, FetchMut, MetaTable, Read, Resource, Resources, SystemData}; use error::WrongGeneration; use storage::{AnyStorage, DenseVecStorage, MaskedStorage, ReadStorage, WriteStorage}; mod comp; mod entity; mod lazy; #[cfg(test)] mod tests; /// An iterator for entity creation. /// Please note that you have to consume /// it because iterators are lazy. /// /// Returned from `World::create_iter`. pub struct CreateIter<'a>(FetchMut<'a, EntitiesRes>); impl<'a> Iterator for CreateIter<'a> { type Item = Entity; fn next(&mut self) -> Option<Entity> { Some(self.0.alloc.allocate()) } } /// A common trait for `EntityBuilder` and `LazyBuilder`, allowing either to be used. /// Entity is definitely alive, but the components may or may not exist before a call to /// `World::maintain`. pub trait Builder { /// Appends a component and associates it with the entity. /// /// # Panics /// /// Panics if the component hasn't been `register()`ed in the /// `World`. fn with<C: Component + Send + Sync>(self, c: C) -> Self; /// Finishes the building and returns the entity. fn build(self) -> Entity; } /// The entity builder, allowing to /// build an entity together with its components. /// /// ## Examples /// /// ``` /// use specs::prelude::*; /// use specs::storage::HashMapStorage; /// /// struct Health(f32); /// /// impl Component for Health { /// type Storage = HashMapStorage<Self>; /// } /// /// struct Pos { /// x: f32, /// y: f32, /// } /// /// impl Component for Pos { /// type Storage = DenseVecStorage<Self>; /// } /// /// let mut world = World::new(); /// world.register::<Health>(); /// world.register::<Pos>(); /// /// let entity = world /// .create_entity() // This call returns `EntityBuilder` /// .with(Health(4.0)) /// .with(Pos { x: 1.0, y: 3.0 }) /// .build(); // Returns the `Entity` /// ``` #[must_use = "Please call .build() on this to finish building it."] pub struct EntityBuilder<'a> { /// The (already created) entity for which components will be inserted. pub entity: Entity, /// A reference to the `World` for component insertions. pub world: &'a World, built: bool, } impl<'a> Builder for EntityBuilder<'a> { #[inline] fn with<T: Component>(self, c: T) -> Self { { let mut storage = self.world.write_storage(); // This can't fail. This is guaranteed by the lifetime 'a // in the EntityBuilder. storage.insert(self.entity, c).unwrap(); } self } /// Finishes the building and returns the entity. As opposed to `LazyBuilder`, /// the components are available immediately. #[inline] fn build(mut self) -> Entity { self.built = true; self.entity } } impl<'a> Drop for EntityBuilder<'a> { fn drop(&mut self) { if !self.built { self.world .read_resource::<EntitiesRes>() .delete(self.entity) .unwrap(); } } } /// The `World` struct contains the component storages and /// other resources. /// /// Many methods take `&self` which works because everything /// is stored with **interior mutability**. In case you violate /// the borrowing rules of Rust (multiple reads xor one write), /// you will get a panic. /// /// ## Examples /// /// ``` /// use specs::prelude::*; /// # #[derive(Debug, PartialEq)] /// # struct Pos { x: f32, y: f32, } impl Component for Pos { type Storage = VecStorage<Self>; } /// # #[derive(Debug, PartialEq)] /// # struct Vel { x: f32, y: f32, } impl Component for Vel { type Storage = VecStorage<Self>; } /// # struct DeltaTime(f32); /// /// let mut world = World::new(); /// world.register::<Pos>(); /// world.register::<Vel>(); /// /// world.add_resource(DeltaTime(0.02)); /// /// world /// .create_entity() /// .with(Pos { x: 1.0, y: 2.0 }) /// .with(Vel { x: -1.0, y: 0.0 }) /// .build(); /// /// let b = world /// .create_entity() /// .with(Pos { x: 3.0, y: 5.0 }) /// .with(Vel { x: 1.0, y: 0.0 }) /// .build(); /// /// let c = world /// .create_entity() /// .with(Pos { x: 0.0, y: 1.0 }) /// .with(Vel { x: 0.0, y: 1.0 }) /// .build(); /// /// { /// // `World::read_storage` returns a component storage. /// let pos_storage = world.read_storage::<Pos>(); /// let vel_storage = world.read_storage::<Vel>(); /// /// // `Storage::get` allows to get a component from it: /// assert_eq!(pos_storage.get(b), Some(&Pos { x: 3.0, y: 5.0 })); /// assert_eq!(vel_storage.get(c), Some(&Vel { x: 0.0, y: 1.0 })); /// } /// /// let empty = world.create_entity().build(); /// /// { /// // This time, we write to the `Pos` storage: /// let mut pos_storage = world.write_storage::<Pos>(); /// let vel_storage = world.read_storage::<Vel>(); /// /// assert!(pos_storage.get(empty).is_none()); /// /// // You can also insert components after creating the entity: /// pos_storage.insert(empty, Pos { x: 3.1, y: 4.15 }); /// /// assert!(pos_storage.get(empty).is_some()); /// } /// ``` pub struct World { /// The resources used for this world. pub res: Resources, } impl World { /// Creates a new empty `World`. pub fn new() -> World { Default::default() } /// Registers a new component, adding the component storage. /// /// Calls `register_with_storage` with `Default::default()`. /// /// Does nothing if the component was already /// registered. /// /// ## Examples /// /// ``` /// use specs::prelude::*; /// /// struct Pos { /// x: f32, /// y: f32, /// } /// /// impl Component for Pos { /// type Storage = DenseVecStorage<Self>; /// } /// /// let mut world = World::new(); /// world.register::<Pos>(); /// // Register all other components like this /// ``` pub fn register<T: Component>(&mut self) where T::Storage: Default, { self.register_with_storage::<_, T>(Default::default); } /// Registers a new component with a given storage. /// /// Does nothing if the component was already registered. pub fn register_with_storage<F, T>(&mut self, storage: F) where F: FnOnce() -> T::Storage, T: Component, { Self::register_with_storage_internal::<F, T>(&mut self.res, storage); } /// Registers a new component with a given storage. /// /// Does nothing if the component was already registered. pub(crate) fn register_with_storage_internal<F, T>(res: &mut Resources, storage: F) where F: FnOnce() -> T::Storage, T: Component, { res.entry() .or_insert_with(move || MaskedStorage::<T>::new(storage())); res.fetch_mut::<MetaTable<AnyStorage>>() .register(&*res.fetch::<MaskedStorage<T>>()); } /// Gets `SystemData` `T` from the `World`. /// /// # Examples /// /// ``` /// # use specs::prelude::*; /// # struct Pos; struct Vel; /// # impl Component for Pos { type Storage = VecStorage<Self>; } /// # impl Component for Vel { type Storage = VecStorage<Self>; } /// /// let mut world = World::new(); /// world.register::<Pos>(); /// world.register::<Vel>(); /// let storages: (WriteStorage<Pos>, ReadStorage<Vel>) = world.system_data(); /// ``` /// /// # Panics /// /// * Panics if `T` is already borrowed in an incompatible way. pub fn system_data<'a, T>(&'a self) -> T where T: SystemData<'a>, { SystemData::fetch(&self.res) } /// Sets up system data `T` for fetching afterwards. pub fn setup<'a, T: SystemData<'a>>(&mut self) { T::setup(&mut self.res); } /// Executes `f` once, right now with the specified system data. /// /// This sets up the system data `f` expects, fetches it and then /// executes `f`. You can see this like a system that only runs once. /// /// This is especially useful if you either need a lot of system data or /// you want to build an entity and for that you need to access resources first /// - just fetching the resources and building the entity would cause a double borrow. /// /// **Calling this method is equivalent to:** /// /// ``` /// # use specs::prelude::*; use specs::shred::ResourceId; /// # struct MySystemData; impl MySystemData { fn do_something(&self) {} } /// # impl<'a> SystemData<'a> for MySystemData { /// # fn fetch(res: &Resources) -> Self { MySystemData } /// # fn reads() -> Vec<ResourceId> { vec![] } /// # fn writes() -> Vec<ResourceId> { vec![] } /// # fn setup(res: &mut Resources) {} /// # } /// # let mut world = World::new(); /// { // note the extra scope /// world.setup::<MySystemData>(); /// let my_data: MySystemData = world.system_data(); /// my_data.do_something(); /// } /// ``` /// /// ## Examples /// /// ``` /// # use specs::prelude::*; /// let mut world = World::new(); /// /// struct MyComp; /// /// impl Component for MyComp { /// type Storage = DenseVecStorage<Self>; /// } /// /// #[derive(Default)] /// struct MyRes { /// field: i32, /// } /// /// world.exec(|(mut my_res,): (Write<MyRes>,)| { /// assert_eq!(my_res.field, 0); /// my_res.field = 5; /// }); /// /// assert_eq!(world.read_resource::<MyRes>().field, 5); /// ``` pub fn exec<'a, F, R, T>(&'a mut self, f: F) -> R where F: FnOnce(T) -> R, T: SystemData<'a>, { self.setup::<T>(); f(self.system_data()) } /// Adds a resource to the world. /// /// If the resource already exists it will be overwritten. /// /// ## Difference between resources and components /// /// While components exist per entity, resources are like globals in the `World`. /// Components are stored in component storages, which are resources themselves. /// /// Everything that is `Any + Send + Sync` can be a resource. /// /// ## Built-in resources /// /// There are two built-in resources: /// /// * `LazyUpdate` and /// * `EntitiesRes` /// /// Both of them should only be fetched immutably, which is why /// the latter one has a type def for convenience: `Entities` which /// is just `Fetch<EntitiesRes>`. Both resources are special and need /// to execute code at the end of the frame, which is done in `World::maintain`. /// /// ## Examples /// /// ``` /// use specs::prelude::*; /// /// # let timer = (); /// # let server_con = (); /// let mut world = World::new(); /// world.add_resource(timer); /// world.add_resource(server_con); /// ``` pub fn add_resource<T: Resource>(&mut self, res: T) { if self.res.has_value::<T>() { *self.res.fetch_mut() = res; } else { self.res.insert(res); } } /// Fetches a component's storage for reading. /// /// ## Panics /// /// Panics if it is already borrowed mutably. /// Panics if the component has not been registered. pub fn read_storage<T: Component>(&self) -> ReadStorage<T> { use shred::SystemData; SystemData::fetch(&self.res) } /// Fetches a component's storage for writing. /// /// ## Panics /// /// Panics if it is already borrowed (either immutably or mutably). /// Panics if the component has not been registered. pub fn write_storage<T: Component>(&self) -> WriteStorage<T> { use shred::SystemData; SystemData::fetch(&self.res) } /// Fetches a resource for reading. /// /// ## Panics /// /// Panics if it is already borrowed mutably. /// Panics if the resource has not been added. pub fn read_resource<T: Resource>(&self) -> Fetch<T> { self.res.fetch() } /// Fetches a resource for writing. /// /// # Panics /// /// Panics if it is already borrowed. /// Panics if the resource has not been added. pub fn write_resource<T: Resource>(&self) -> FetchMut<T> { self.res.fetch_mut() } /// Convenience method for fetching entities. /// /// Creation and deletion of entities with the `Entities` struct /// are atomically, so the actual changes will be applied /// with the next call to `maintain()`. pub fn entities(&self) -> Read<EntitiesRes> { Read::fetch(&self.res) } /// Convenience method for fetching entities. fn entities_mut(&self) -> FetchMut<EntitiesRes> { self.write_resource() } /// Allows building an entity with its components. /// /// This takes a mutable reference to the `World`, since no /// component storage this builder accesses may be borrowed. /// If it's necessary that you borrow a resource from the `World` /// while this builder is alive, you can use `create_entity_unchecked`. pub fn create_entity(&mut self) -> EntityBuilder { self.create_entity_unchecked() } /// Allows building an entity with its components. /// /// **You have to make sure that no component storage is borrowed /// during the building!** /// /// This variant is only recommended if you need to borrow a resource /// during the entity building. If possible, try to use `create_entity`. pub fn create_entity_unchecked(&self) -> EntityBuilder { let entity = self.entities_mut().alloc.allocate(); EntityBuilder { entity, world: self, built: false, } } /// Returns an iterator for entity creation. /// This makes it easy to create a whole collection /// of them. /// /// ## Examples /// /// ``` /// use specs::prelude::*; /// /// let mut world = World::new(); /// let five_entities: Vec<_> = world.create_iter().take(5).collect(); /// # /// # assert_eq!(five_entities.len(), 5); /// ``` pub fn create_iter(&mut self) -> CreateIter { CreateIter(self.entities_mut()) } /// Deletes an entity and its components. pub fn delete_entity(&mut self, entity: Entity) -> Result<(), WrongGeneration> { self.delete_entities(&[entity]) } /// Deletes the specified entities and their components. pub fn delete_entities(&mut self, delete: &[Entity]) -> Result<(), WrongGeneration> { self.delete_components(delete); self.entities_mut().alloc.kill(delete) } /// Deletes all entities and their components. pub fn delete_all(&mut self) { use join::Join; let entities: Vec<_> = self.entities().join().collect(); self.delete_entities(&entities).expect( "Bug: previously collected entities are not valid \ even though access should be exclusive", ); } /// Checks if an entity is alive. /// Please note that atomically created or deleted entities /// (the ones created / deleted with the `Entities` struct) /// are not handled by this method. Therefore, you /// should have called `maintain()` before using this /// method. /// /// If you want to get this functionality before a `maintain()`, /// you are most likely in a system; from there, just access the /// `Entities` resource and call the `is_alive` method. /// /// # Panics /// /// Panics if generation is dead. pub fn is_alive(&self, e: Entity) -> bool { assert!(e.gen().is_alive(), "Generation is dead"); let alloc: &Allocator = &self.entities().alloc; alloc .generations .get(e.id() as usize) .map(|&x| x == e.gen()) .unwrap_or(false) } /// Merges in the appendix, recording all the dynamically created /// and deleted entities into the persistent generations vector. /// Also removes all the abandoned components. /// /// Additionally, `LazyUpdate` will be merged. pub fn maintain(&mut self) { let deleted = self.entities_mut().alloc.merge(); if !deleted.is_empty() { self.delete_components(&deleted); } // we need to swap the queue out to be able to reborrow self mutable here let mut lazy = self.write_resource::<LazyUpdate>().take(); lazy.maintain(&mut *self); self.write_resource::<LazyUpdate>().restore(lazy); } fn delete_components(&mut self, delete: &[Entity]) { for storage in self.any_storages().iter_mut(&self.res) { storage.drop(delete); } } /// Adds the given bundle of resources/components. pub fn add_bundle<B>(&mut self, bundle: B) where B: Bundle, { bundle.add_to_world(self); } fn any_storages(&self) -> FetchMut<MetaTable<AnyStorage>> { self.res.fetch_mut::<MetaTable<AnyStorage>>() } } unsafe impl Send for World {} unsafe impl Sync for World {} impl Borrow<Resources> for World { fn borrow(&self) -> &Resources { &self.res } } impl Component for World { type Storage = DenseVecStorage<Self>; } impl Default for World { fn default() -> Self { let mut res = Resources::new(); res.insert(EntitiesRes::default()); res.insert(LazyUpdate::default()); res.insert(MetaTable::<AnyStorage>::new()); World { res } } } /// Trait used to bundle up resources/components for easy registration with `World`. pub trait Bundle { /// Add resources/components to `world`. fn add_to_world(self, world: &mut World); }