Struct veloren_client::World

pub struct World {
    resources: AHashMap<ResourceId, AtomicRefCell<Box<dyn Resource>>>,
}
Expand description

A [Resource] container, which provides methods to insert, access and manage the contained 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.

Use with Specs

If you’re using this from the Specs ECS library, there are two things to be aware of:

  1. There are many utility methods Specs provides. To use them, you need to import specs::WorldExt.
  2. You should not use World::empty, but rather specs::WorldExt::new. The latter can simply be called using World::new(), as long as WorldExt is imported.

Resource Ids

Resources are identified by ResourceIds, which consist of a TypeId.

Fields§

§resources: AHashMap<ResourceId, AtomicRefCell<Box<dyn Resource>>>

Implementations§

§

impl World

pub fn empty() -> World

Creates a new, empty resource container.

Note that if you’re using Specs, you should use WorldExt::new instead.

pub fn insert<R>(&mut self, r: R)
where R: Resource,

Inserts a resource into this container. If the resource existed before, it will be overwritten.

Examples

Every type satisfying Any + Send + Sync automatically implements Resource, thus can be added:

struct MyRes(i32);

When you have a resource, simply insert it like this:

use shred::World;

let mut world = World::empty();
world.insert(MyRes(5));

pub fn remove<R>(&mut self) -> Option<R>
where R: Resource,

Removes a resource of type R from the World and returns its ownership to the caller. In case there is no such resource in this World, None will be returned.

Use this method with caution; other functions and systems might assume this resource still exists. Thus, only use this if you’re sure no system will try to access this resource after you removed it (or else you will get a panic).

pub fn has_value<R>(&self) -> bool
where R: Resource,

Returns true if the specified resource type R exists in self.

pub fn has_value_raw(&self, id: ResourceId) -> bool

Returns true if the specified resource type exists in self.

pub fn entry<R>(&mut self) -> Entry<'_, R>
where R: Resource,

Returns an entry for the resource with type R.

pub fn system_data<'a, T>(&'a self) -> T
where T: SystemData<'a>,

Gets SystemData T from the World. This can be used to retrieve data just like in Systems.

This will not setup the system data, i.e. resources fetched here must exist already.

Examples

// NOTE: If you use Specs, use `World::new` instead.
let mut world = World::empty();
world.insert(Timer);
world.insert(AnotherResource);
let system_data: (Read<Timer>, Read<AnotherResource>) = world.system_data();
Panics
  • Panics if T is already borrowed in an incompatible way.

pub fn setup<'a, T>(&mut self)
where T: SystemData<'a>,

Sets up system data T for fetching afterwards.

Most SystemData implementations will insert a sensible default value, by implementing [SystemData::setup]. However, it is not guaranteed to do that; if there is no sensible default, setup might not do anything.

Examples
use shred::{Read, World};

#[derive(Default)]
struct MyCounter(u32);

// NOTE: If you use Specs, use `World::new` instead.
let mut world = World::empty();
assert!(!world.has_value::<MyCounter>());

// `Read<MyCounter>` requires a `Default` implementation, and uses
// that to initialize the resource
world.setup::<Read<MyCounter>>();
assert!(world.has_value::<MyCounter>());

Here’s another example, showing the case where no resource gets initialized:

use shred::{ReadExpect, World};

struct MyCounter(u32);

// NOTE: If you use Specs, use `World::new` instead.
let mut world = World::empty();

world.setup::<ReadExpect<MyCounter>>();

pub fn exec<'a, F, R, T>(&'a mut self, f: F) -> R
where F: FnOnce(T) -> R, T: SystemData<'a>,

Executes f once, right now and with the specified system data.

This sets up the system data f expects, fetches it and then executes f. This is essentially like a one-time System.

This is especially useful if you either need a lot of system data or, with Specs, if 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:

{
    // note the extra scope
    world.setup::<MySystemData>();
    let my_data: MySystemData = world.system_data();
    my_data.do_something();
}
Examples
// NOTE: If you use Specs, use `World::new` instead.
let mut world = World::empty();

#[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.fetch::<MyRes>().field, 5);

pub fn fetch<T>(&self) -> Fetch<'_, T>
where T: Resource,

Fetches the resource with the specified type T or panics if it doesn’t exist.

Panics

Panics if the resource doesn’t exist. Panics if the resource is being accessed mutably.

pub fn try_fetch<T>(&self) -> Option<Fetch<'_, T>>
where T: Resource,

Like fetch, but returns an Option instead of inserting a default value in case the resource does not exist.

pub fn try_fetch_by_id<T>(&self, id: ResourceId) -> Option<Fetch<'_, T>>
where T: Resource,

Like try_fetch, but fetches the resource by its ResourceId which allows using a dynamic ID.

This is usually not what you need; please read the type-level documentation of ResourceId.

Panics

This method panics if id refers to a different type ID than T.

pub fn fetch_mut<T>(&self) -> FetchMut<'_, T>
where T: Resource,

Fetches the resource with the specified type T mutably.

Please see fetch for details.

Panics

Panics if the resource doesn’t exist. Panics if the resource is already being accessed.

pub fn try_fetch_mut<T>(&self) -> Option<FetchMut<'_, T>>
where T: Resource,

Like fetch_mut, but returns an Option instead of inserting a default value in case the resource does not exist.

pub fn try_fetch_mut_by_id<T>(&self, id: ResourceId) -> Option<FetchMut<'_, T>>
where T: Resource,

Like try_fetch_mut, but fetches the resource by its ResourceId which allows using a dynamic ID.

This is usually not what you need; please read the type-level documentation of ResourceId.

Panics

This method panics if id refers to a different type ID than T.

pub fn insert_by_id<R>(&mut self, id: ResourceId, r: R)
where R: Resource,

Internal function for inserting resources, should only be used if you know what you’re doing.

This is useful for inserting resources with a custom ResourceId.

Panics

This method panics if id refers to a different type ID than R.

pub fn remove_by_id<R>(&mut self, id: ResourceId) -> Option<R>
where R: Resource,

Internal function for removing resources, should only be used if you know what you’re doing.

This is useful for removing resources with a custom ResourceId.

Panics

This method panics if id refers to a different type ID than R.

pub unsafe fn try_fetch_internal( &self, id: ResourceId ) -> Option<&AtomicRefCell<Box<dyn Resource>>>

Internal function for fetching resources, should only be used if you know what you’re doing.

Safety

If this is used to replace the Box<dyn Resource> with a different one, the new one must have a TypeId that matches the one in the ResourceId provided here.

pub fn get_mut<T>(&mut self) -> Option<&mut T>
where T: Resource,

Retrieves a resource without fetching, which is cheaper, but only available with &mut self.

pub fn get_mut_raw( &mut self, id: ResourceId ) -> Option<&mut (dyn Resource + 'static)>

Retrieves a resource without fetching, which is cheaper, but only available with &mut self.

Trait Implementations§

§

impl Default for World

§

fn default() -> World

Returns the “default value” for a type. Read more
§

impl WorldExt for World

§

fn new() -> World

Constructs a new World instance.
§

fn register<T>(&mut self)
where T: Component, <T as Component>::Storage: Default,

Registers a new component, adding the component storage. Read more
§

fn register_with_storage<F, T>(&mut self, storage: F)
where F: FnOnce() -> <T as Component>::Storage, T: Component,

Registers a new component with a given storage. Read more
§

fn add_resource<T>(&mut self, res: T)
where T: Resource,

👎Deprecated since 0.15.0: use World::insert instead
Adds a resource to the world. Read more
§

fn read_component<T>(&self) -> Storage<'_, T, Fetch<'_, MaskedStorage<T>>>
where T: Component,

Fetches a component storage for reading. Read more
§

fn write_component<T>(&self) -> Storage<'_, T, FetchMut<'_, MaskedStorage<T>>>
where T: Component,

Fetches a component storage for writing. Read more
§

fn read_resource<T>(&self) -> Fetch<'_, T>
where T: Resource,

Fetches a resource for reading. Read more
§

fn write_resource<T>(&self) -> FetchMut<'_, T>
where T: Resource,

Fetches a resource for writing. Read more
§

fn entities(&self) -> Read<'_, EntitiesRes>

Convenience method for fetching entities. Read more
§

fn entities_mut(&self) -> FetchMut<'_, EntitiesRes>

Convenience method for fetching entities.
§

fn create_entity(&mut self) -> EntityBuilder<'_>

Allows building an entity with its components. Read more
§

fn create_entity_unchecked(&self) -> EntityBuilder<'_>

Allows building an entity with its components. Read more
§

fn create_iter(&mut self) -> CreateIter<'_>

Returns an iterator for entity creation. This makes it easy to create a whole collection of them. Read more
§

fn delete_entity(&mut self, entity: Entity) -> Result<(), WrongGeneration>

Deletes an entity and its components.
§

fn delete_entities( &mut self, delete: &[Entity] ) -> Result<(), (WrongGeneration, usize)>

Deletes the specified entities and their components. Read more
§

fn delete_all(&mut self)

Deletes all entities and their components.
§

fn is_alive(&self, e: Entity) -> bool

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. Read more
§

fn maintain(&mut self)

Merges in the appendix, recording all the dynamically created and deleted entities into the persistent generations vector. Also removes all the abandoned components. Read more
§

fn read_storage<T>(&self) -> Storage<'_, T, Fetch<'_, MaskedStorage<T>>>
where T: Component,

Fetches a component storage for reading. Read more
§

fn write_storage<T>(&self) -> Storage<'_, T, FetchMut<'_, MaskedStorage<T>>>
where T: Component,

Fetches a component storage for writing. Read more
§

impl WorldSyncExt for World

§

fn delete_entity_and_clear_uid_mapping(&mut self, uid: Uid)

This method should be used from the client-side when processing network messages that delete entities.

Only used on the client.

§

fn uid_from_entity(&self, entity: Entity) -> Option<Uid>

Get the UID of an entity

§

fn entity_from_uid(&self, uid: Uid) -> Option<Entity>

Get an entity from a UID

§

fn register_sync_marker(&mut self)

§

fn register_synced<C>(&mut self)
where C: Component + Clone + Send + Sync, <C as Component>::Storage: Default + Tracked,

§

fn register_tracker<C>(&mut self)
where C: Component + Clone + Send + Sync, <C as Component>::Storage: Default + Tracked,

§

fn create_entity_synced(&mut self) -> EntityBuilder<'_>

§

fn apply_entity_package<P>( &mut self, entity_package: EntityPackage<P> ) -> Entity
where P: CompPacket,

§

fn apply_entity_sync_package( &mut self, package: EntitySyncPackage, client_uid: Option<Uid> )

§

fn apply_comp_sync_package<P>(&mut self, package: CompSyncPackage<P>)
where P: CompPacket,

Auto Trait Implementations§

§

impl !RefUnwindSafe for World

§

impl Send for World

§

impl Sync for World

§

impl Unpin for World

§

impl !UnwindSafe for World

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> GetSetFdFlags for T

§

fn get_fd_flags(&self) -> Result<FdFlags, Error>
where T: AsFilelike,

Query the “status” flags for the self file descriptor.
§

fn new_set_fd_flags(&self, fd_flags: FdFlags) -> Result<SetFdFlags<T>, Error>
where T: AsFilelike,

Create a new SetFdFlags value for use with set_fd_flags. Read more
§

fn set_fd_flags(&mut self, set_fd_flags: SetFdFlags<T>) -> Result<(), Error>
where T: AsFilelike,

Set the “status” flags for the self file descriptor. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Pointee for T

§

type Pointer = u32

§

fn debug( pointer: <T as Pointee>::Pointer, f: &mut Formatter<'_> ) -> Result<(), Error>

source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

impl<Context> SubContext<Context> for Context

§

fn sub_context(self) -> Context

§

impl<T> TryDefault for T
where T: Default,

§

fn try_default() -> Result<T, String>

Tries to create the default.
§

fn unwrap_default() -> Self

Calls try_default and panics on an error case.
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> Event for T
where T: Send + Sync + 'static,

§

impl<T> Resource for T
where T: Any + Send + Sync,