Skip to main content

pebble/assets/
deps.rs

1use crate::{ecs::resources::Resources, ecs::system::Res};
2
3/// A set of resources required by an [`Asset`](crate::assets::upload::Asset)
4/// implementation before it can be uploaded to the backend.
5///
6/// Implement this trait for `()` (no deps), a single `Res<T>`, or a tuple of
7/// `Res<T>` values (up to 8). The sync system calls [`try_gather`] each tick
8/// and skips the upload if any dependency is not yet present.
9pub trait Dependencies<'a>: Sized {
10    /// Attempt to gather all required resources from the world.
11    ///
12    /// Returns `None` if any dependency is missing, deferring the upload to
13    /// the next tick.
14    fn try_gather(world: &'a hecs::World, resources: &'a Resources) -> Option<Self>;
15}
16
17impl<'a> Dependencies<'a> for () {
18    fn try_gather(_world: &'a hecs::World, _resources: &'a Resources) -> Option<Self> {
19        Some(())
20    }
21}
22
23impl<'a, A: 'static + Send + Sync> Dependencies<'a> for Res<'a, A> {
24    fn try_gather(world: &'a hecs::World, resources: &'a Resources) -> Option<Self> {
25        if !resources.has_resource::<A>(world) {
26            return None;
27        }
28        Some(Res {
29            data: resources.get_resource(world),
30        })
31    }
32}
33
34/// Implements [`Dependencies`] for a tuple of `Res<'a, T>` values.
35///
36/// Invoked once per arity (2 through 8); each invocation lists the generic
37/// type parameters for that tuple's elements.
38macro_rules! impl_dependencies_tuple {
39    ($($T:ident),+ $(,)?) => {
40        impl<'a, $($T),+> Dependencies<'a> for ($(Res<'a, $T>),+,)
41        where
42            $($T: 'static + Send + Sync),+
43        {
44            fn try_gather(world: &'a hecs::World, resources: &'a Resources) -> Option<Self> {
45                if $(!resources.has_resource::<$T>(world))||+ {
46                    return None;
47                }
48                Some((
49                    $(
50                        Res::<$T> {
51                            data: resources.get_resource(world),
52                        }
53                    ),+,
54                ))
55            }
56        }
57    };
58}
59
60impl_dependencies_tuple!(A, B);
61impl_dependencies_tuple!(A, B, C);
62impl_dependencies_tuple!(A, B, C, D);
63impl_dependencies_tuple!(A, B, C, D, E);
64impl_dependencies_tuple!(A, B, C, D, E, F);
65impl_dependencies_tuple!(A, B, C, D, E, F, G);
66impl_dependencies_tuple!(A, B, C, D, E, F, G, H);