Skip to main content

AssetNode

Struct AssetNode 

Source
pub struct AssetNode<T: AssetTree> { /* private fields */ }
Expand description

AssetNode represents a node in the asset graph, which is a reference to an asset that can be resolved to a specific component in asset.

Implementations§

Source§

impl<T: AssetTree> AssetNode<T>

Source

pub fn new(path: impl Into<AssetPathStatic>) -> Self

Creates a new AssetNode from a static asset path.

§Arguments
  • path: The path to the asset, which can be any type that can be converted into AssetPathStatic.
§Returns

A new AssetNode instance that references the asset at the given path.

Examples found in repository?
examples/hello_graph.rs (line 29)
14fn main() -> Result<(), Box<dyn Error>> {
15    // /* ANCHOR: main */
16    let mut database = AssetDatabase::default()
17        .with_protocol(BundleAssetProtocol::new(
18            "custom",
19            // AssetTreeProcessor handles deserialization of the custom asset
20            // as single component. That component will report its dependencies
21            // to load.
22            AssetTreeProcessor::<CustomAsset>::new(|bytes| {
23                Ok(serde_json::from_slice::<CustomAsset>(&bytes)?)
24            }),
25        ))
26        .with_fetch(FileAssetFetch::default().with_root("resources"));
27
28    // Create asset node and ensure it is being loaded.
29    let asset = AssetNode::<CustomAsset>::new("custom://part1.json");
30    asset.ensure(&mut database)?;
31
32    // Wait until the database is not busy, which means all assets are loaded.
33    while database.is_busy() {
34        database.maintain()?;
35    }
36
37    // Resolve the asset and read its contents.
38    // This will also resolve all dependencies of the asset.
39    let contents = asset
40        .resolve(&database)?
41        .read_unchecked()
42        .contents(&database);
43    println!("Custom chain contents: {contents:?}");
44    // /* ANCHOR_END: main */
45    Ok(())
46}
Source

pub fn from_ref(inner: AssetRef) -> Self

Creates a new AssetNode from an existing AssetRef.

§Arguments
  • inner: The AssetRef that this node will reference.
§Returns

A new AssetNode instance that wraps the provided AssetRef.

Source

pub fn as_ref(&self) -> AssetRef

Returns a reference to the inner AssetRef of this node.

Source

pub fn invalidate(&self) -> Result<(), Box<dyn Error>>

Invalidates the asset node, making internal AssetRef unresolved.

§Returns

A Result indicating success or failure. If successful, the asset node is marked as invalidated, and any future attempts to resolve it will require re-fetching or re-resolving the asset.

Source

pub fn path(&self) -> &AssetPathStatic

Returns the path of the asset node.

§Returns

A reference to the AssetPathStatic associated with this node.

Source

pub fn handle(&self) -> Result<AssetHandle, Box<dyn Error>>

Returns the handle of the asset node.

§Returns

A Result containing the AssetHandle if successful, or an error if the handle cannot be retrieved.

Source

pub fn resolve<'a>( &'a self, database: &'a AssetDatabase, ) -> Result<AssetNodeResolved<'a, T>, Box<dyn Error>>

Resolves the asset node to a specific component in the asset database.

§Arguments
  • database: A reference to the AssetDatabase where the asset is stored.
§Returns

A Result containing an AssetNodeResolved instance if successful, or an error if the resolution fails. The AssetNodeResolved provides access to the resolved component, allowing read and write operations.

Examples found in repository?
examples/hello_graph.rs (line 40)
14fn main() -> Result<(), Box<dyn Error>> {
15    // /* ANCHOR: main */
16    let mut database = AssetDatabase::default()
17        .with_protocol(BundleAssetProtocol::new(
18            "custom",
19            // AssetTreeProcessor handles deserialization of the custom asset
20            // as single component. That component will report its dependencies
21            // to load.
22            AssetTreeProcessor::<CustomAsset>::new(|bytes| {
23                Ok(serde_json::from_slice::<CustomAsset>(&bytes)?)
24            }),
25        ))
26        .with_fetch(FileAssetFetch::default().with_root("resources"));
27
28    // Create asset node and ensure it is being loaded.
29    let asset = AssetNode::<CustomAsset>::new("custom://part1.json");
30    asset.ensure(&mut database)?;
31
32    // Wait until the database is not busy, which means all assets are loaded.
33    while database.is_busy() {
34        database.maintain()?;
35    }
36
37    // Resolve the asset and read its contents.
38    // This will also resolve all dependencies of the asset.
39    let contents = asset
40        .resolve(&database)?
41        .read_unchecked()
42        .contents(&database);
43    println!("Custom chain contents: {contents:?}");
44    // /* ANCHOR_END: main */
45    Ok(())
46}
47
48/* ANCHOR: custom_asset */
49// This example demonstrates how to create a custom asset type that can
50// have dependencies on other assets. The `CustomAsset` struct is defined
51// with a `content` field and an optional `next` field that points to another
52// `CustomAsset`.
53#[derive(Debug, Default, Serialize, Deserialize, AssetTree)]
54struct CustomAsset {
55    content: String,
56    // The `next` field is annotated with `#[asset_deps]` to indicate that it is
57    // an asset dependency that has to be loaded along with this asset.
58    #[serde(default)]
59    #[asset_deps]
60    next: Option<AssetNode<CustomAsset>>,
61}
62
63impl CustomAsset {
64    fn contents(&self, database: &AssetDatabase) -> String {
65        let mut result = self.content.as_str().to_owned();
66        if let Some(next) = self.next.as_ref() {
67            result.push(' ');
68            if let Ok(resolved) = next.resolve(database) {
69                result.push_str(&resolved.read_unchecked().contents(database));
70            }
71        }
72        result
73    }
Source

pub fn ensure<'a>( &'a self, database: &'a mut AssetDatabase, ) -> Result<AssetNodeResolved<'a, T>, Box<dyn Error>>

Ensures that the asset node is resolved and available in the asset database.

§Arguments
  • database: A mutable reference to the AssetDatabase where the asset is stored.
§Returns

A Result containing an AssetNodeResolved instance if successful, or an error if the resolution fails. The AssetNodeResolved provides access to the resolved component, allowing read and write operations.

Examples found in repository?
examples/hello_graph.rs (line 30)
14fn main() -> Result<(), Box<dyn Error>> {
15    // /* ANCHOR: main */
16    let mut database = AssetDatabase::default()
17        .with_protocol(BundleAssetProtocol::new(
18            "custom",
19            // AssetTreeProcessor handles deserialization of the custom asset
20            // as single component. That component will report its dependencies
21            // to load.
22            AssetTreeProcessor::<CustomAsset>::new(|bytes| {
23                Ok(serde_json::from_slice::<CustomAsset>(&bytes)?)
24            }),
25        ))
26        .with_fetch(FileAssetFetch::default().with_root("resources"));
27
28    // Create asset node and ensure it is being loaded.
29    let asset = AssetNode::<CustomAsset>::new("custom://part1.json");
30    asset.ensure(&mut database)?;
31
32    // Wait until the database is not busy, which means all assets are loaded.
33    while database.is_busy() {
34        database.maintain()?;
35    }
36
37    // Resolve the asset and read its contents.
38    // This will also resolve all dependencies of the asset.
39    let contents = asset
40        .resolve(&database)?
41        .read_unchecked()
42        .contents(&database);
43    println!("Custom chain contents: {contents:?}");
44    // /* ANCHOR_END: main */
45    Ok(())
46}

Trait Implementations§

Source§

impl<T: AssetTree> AssetTree for AssetNode<T>

Source§

fn asset_dependencies(&self) -> impl IntoIterator<Item = AssetPathStatic>

Returns an iterator over the asset dependencies of this component. Read more
Source§

impl<T: AssetTree> Clone for AssetNode<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + AssetTree> Debug for AssetNode<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de, T: AssetTree> Deserialize<'de> for AssetNode<T>

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T: AssetTree> From<AssetNode<T>> for AssetPathStatic

Source§

fn from(value: AssetNode<T>) -> Self

Converts to this type from the input type.
Source§

impl<T: AssetTree> From<AssetPath<'static>> for AssetNode<T>

Source§

fn from(path: AssetPathStatic) -> Self

Converts to this type from the input type.
Source§

impl<T: PartialEq + AssetTree> PartialEq for AssetNode<T>

Source§

fn eq(&self, other: &AssetNode<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: AssetTree> Serialize for AssetNode<T>

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<T: Eq + AssetTree> Eq for AssetNode<T>

Source§

impl<T: AssetTree> StructuralPartialEq for AssetNode<T>

Auto Trait Implementations§

§

impl<T> !Freeze for AssetNode<T>

§

impl<T> RefUnwindSafe for AssetNode<T>

§

impl<T> Send for AssetNode<T>

§

impl<T> Sync for AssetNode<T>

§

impl<T> Unpin for AssetNode<T>

§

impl<T> UnwindSafe for AssetNode<T>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> Finalize for T

Source§

unsafe fn finalize_raw(data: *mut ())

Safety Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

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

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

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.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

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>,

Source§

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.
Source§

impl<T> WithSubscriber for T

Source§

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
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

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

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,