bevy_proto_backend/children/
builder.rs

1use std::path::Path;
2
3use bevy::asset::{AssetIo, Handle, LoadedAsset};
4
5use crate::load::{Loader, ProtoLoadContext};
6use crate::path::{ProtoPath, ProtoPathContext};
7use crate::proto::Prototypical;
8
9/// A helper struct for properly building out a [prototype's] children.
10///
11/// [prototype's]: Prototypical
12pub struct ProtoChildBuilder<'ctx, 'load_ctx, T: Prototypical, L: Loader<T>> {
13    pub(crate) context: ProtoLoadContext<'ctx, 'load_ctx, T, L>,
14}
15
16impl<'ctx, 'load_ctx, T: Prototypical, L: Loader<T>> ProtoChildBuilder<'ctx, 'load_ctx, T, L> {
17    pub(crate) fn new(context: ProtoLoadContext<'ctx, 'load_ctx, T, L>) -> Self {
18        Self { context }
19    }
20
21    /// Add the given child to the parent.
22    pub fn add_child(&mut self, child: T) -> Result<Handle<T>, L::Error> {
23        let (child, meta, deps) = self.context.preprocess_proto(child)?;
24
25        let child_handle = self.context.set_labeled_asset(
26            meta.path.label().expect("child should have an asset label"),
27            LoadedAsset::new(child).with_dependencies(deps),
28        );
29
30        self.context.increment_index();
31
32        Ok(child_handle)
33    }
34
35    /// Add the child with the given path to the parent.
36    pub fn add_child_path(&mut self, child_path: ProtoPath) -> Result<Handle<T>, L::Error> {
37        self.context
38            .child_paths_mut()
39            .push(child_path.asset_path().to_owned());
40
41        self.context.increment_index();
42
43        Ok(self.context.get_handle(child_path))
44    }
45
46    /// Access the current [`ProtoLoadContext`].
47    pub fn context(&self) -> &ProtoLoadContext<'ctx, 'load_ctx, T, L> {
48        &self.context
49    }
50
51    /// Access the current [`ProtoLoadContext`] mutably.
52    pub fn context_mut(&mut self) -> &mut ProtoLoadContext<'ctx, 'load_ctx, T, L> {
53        &mut self.context
54    }
55}
56
57impl<'ctx, 'load_ctx, T: Prototypical, L: Loader<T>> ProtoPathContext
58    for ProtoChildBuilder<'ctx, 'load_ctx, T, L>
59{
60    fn base_path(&self) -> &Path {
61        self.context.base_path()
62    }
63
64    fn asset_io(&self) -> &dyn AssetIo {
65        self.context.load_context().asset_io()
66    }
67
68    fn extensions(&self) -> &[&'static str] {
69        self.context.extensions()
70    }
71}