pub struct AssetRef { /* private fields */ }Expand description
A reference to an asset in the asset database.
AssetRef encapsulates a reference to an asset, identified by its path,
with an optional handle that can be lazily resolved or explicitly set.
Implementations§
Source§impl AssetRef
impl AssetRef
Sourcepub fn new(path: impl Into<AssetPathStatic>) -> Self
pub fn new(path: impl Into<AssetPathStatic>) -> Self
Creates a new AssetRef with the given asset path.
§Arguments
path: The path to the asset.
§Returns
An instance of AssetRef.
Examples found in repository?
examples/ingame.rs (line 80)
62 fn default() -> Self {
63 Self {
64 context: Default::default(),
65 timer: Instant::now(),
66 assets: AssetDatabase::default()
67 // Text protocol for shader sources.
68 .with_protocol(TextAssetProtocol)
69 // Group protocol for loading many assets at once.
70 .with_protocol(GroupAssetProtocol)
71 // Custom shader protocol.
72 .with_protocol(BundleAssetProtocol::new("shader", ShaderAssetProcessor))
73 // Custom texture protocol.
74 .with_protocol(BundleAssetProtocol::new("texture", TextureAssetProcessor))
75 // Load all data from file system asynchronously.
76 .with_fetch(DeferredAssetFetch::new(
77 FileAssetFetch::default().with_root("resources"),
78 )),
79 // Stored asset references for cached asset handles.
80 image_shader: AssetRef::new("shader://image.shader"),
81 ferris_texture: AssetRef::new("texture://ferris.png"),
82 }
83 }Sourcepub fn new_resolved(
path: impl Into<AssetPathStatic>,
handle: AssetHandle,
) -> Self
pub fn new_resolved( path: impl Into<AssetPathStatic>, handle: AssetHandle, ) -> Self
Sourcepub fn invalidate(&self) -> Result<(), Box<dyn Error>>
pub fn invalidate(&self) -> Result<(), Box<dyn Error>>
Invalidates the asset handle, making the AssetRef unresolved.
§Returns
An error if the handle could not be invalidated.
Sourcepub fn path(&self) -> &AssetPathStatic
pub fn path(&self) -> &AssetPathStatic
Examples found in repository?
More examples
examples/ingame.rs (line 233)
228 fn process_bytes(
229 &mut self,
230 bytes: Vec<u8>,
231 ) -> Result<BundleWithDependencies<Self::Bundle>, Box<dyn Error>> {
232 let asset = serde_json::from_slice::<ShaderAssetInfo>(&bytes)?;
233 let vertex = asset.vertex.path().clone();
234 let fragment = asset.fragment.path().clone();
235
236 println!("* Shader asset processed: {asset:#?}");
237 Ok(BundleWithDependencies::new((asset,))
238 .dependency(vertex)
239 .dependency(fragment))
240 }
241
242 fn maintain(&mut self, storage: &mut World) -> Result<(), Box<dyn Error>> {
243 let mut commands = CommandBuffer::default();
244 let mut lookup = storage.lookup_access::<true, &String>();
245
246 // We scan for decoded shader info and if dependencies are loaded,
247 // then turn them into shader asset.
248 for (entity, info, dependencies) in
249 storage.query::<true, (Entity, &ShaderAssetInfo, &Relation<AssetDependency>)>()
250 {
251 if dependencies
252 .entities()
253 .all(|entity| storage.has_entity_component::<String>(entity))
254 {
255 let vertex = lookup
256 .access(storage.find_by::<true, _>(info.vertex.path()).unwrap())
257 .unwrap()
258 .to_owned();
259 let fragment = lookup
260 .access(storage.find_by::<true, _>(info.fragment.path()).unwrap())
261 .unwrap()
262 .to_owned();
263
264 let asset = ShaderAsset { vertex, fragment };
265 commands.command(InsertCommand::new(entity, (asset,)));
266 commands.command(RemoveCommand::<(ShaderAssetInfo,)>::new(entity));
267 }
268 }
269 drop(lookup);
270
271 commands.execute(storage);
272
273 Ok(())
274 }Sourcepub fn handle(&self) -> Result<AssetHandle, Box<dyn Error>>
pub fn handle(&self) -> Result<AssetHandle, Box<dyn Error>>
Gets the resolved handle for the asset.
§Returns
The resolved AssetHandle, or an error if it has not been resolved.
Sourcepub fn resolve<'a>(
&'a self,
database: &'a AssetDatabase,
) -> Result<AssetResolved<'a>, Box<dyn Error>>
pub fn resolve<'a>( &'a self, database: &'a AssetDatabase, ) -> Result<AssetResolved<'a>, Box<dyn Error>>
Resolves the asset handle using the asset database, if not already resolved.
§Arguments
database: Reference to theAssetDatabaseto resolve the asset.
§Returns
A resolved AssetResolved object, or an error if resolution fails.
Examples found in repository?
More examples
examples/ingame.rs (line 110)
102 fn on_redraw(&mut self, graphics: &mut Graphics<Vertex>, _: &mut AppControl) {
103 // Process assets periotically.
104 if self.timer.elapsed().as_secs_f32() > DELTA_TIME {
105 self.timer = Instant::now();
106 self.process_assets(graphics);
107 }
108
109 // Do not render unless we have shader loaded.
110 let Ok(image_shader) = self.image_shader.resolve(&self.assets) else {
111 return;
112 };
113 let Some(image_shader) = image_shader
114 .access_checked::<&AsyncHandle<Shader>>()
115 .map(|handle| handle.to_ref())
116 else {
117 return;
118 };
119
120 // Begin drawing objects.
121 self.context.begin_frame(graphics);
122 self.context.push_shader(&image_shader);
123 self.context.push_blending(GlowBlending::Alpha);
124
125 // Draw sprite only if texture asset is loaded.
126 if let Ok(texture) = self.ferris_texture.resolve(&self.assets)
127 && let Some(texture) = texture
128 .access_checked::<&AsyncHandle<Texture>>()
129 .map(|handle| handle.to_ref())
130 {
131 Sprite::single(SpriteTexture::new("u_image".into(), texture))
132 .pivot(0.5.into())
133 .draw(&mut self.context, graphics);
134 }
135
136 // Commit drawn objects.
137 self.context.end_frame();
138 }examples/17_smart_references.rs (line 19)
8fn main() -> Result<(), Box<dyn Error>> {
9 /* ANCHOR: main */
10 let mut database = AssetDatabase::default()
11 .with_protocol(TextAssetProtocol)
12 .with_fetch(FileAssetFetch::default().with_root("resources"));
13
14 /* ANCHOR: smart_reference */
15 // Load asset and mark its first reference.
16 let first = SmartAssetRef::new("text://lorem.txt", &mut database)?;
17 println!(
18 "Lorem Ipsum: {}",
19 first.resolve(&database)?.access::<&String>()
20 );
21 database.maintain()?;
22 assert_eq!(database.storage.len(), 1);
23 assert_eq!(
24 first
25 .resolve(&database)?
26 .access::<&AssetReferenceCounter>()
27 .counter(),
28 1
29 );
30
31 // Clone the asset and mark its second reference.
32 let second = first.clone();
33 database.maintain()?;
34 assert_eq!(database.storage.len(), 1);
35 assert_eq!(
36 second
37 .resolve(&database)?
38 .access::<&AssetReferenceCounter>()
39 .counter(),
40 2
41 );
42
43 // Ensure asset again from scratch and mark its third reference.
44 let third = SmartAssetRef::new("text://lorem.txt", &mut database)?;
45 database.maintain()?;
46 assert_eq!(database.storage.len(), 1);
47 assert_eq!(
48 third
49 .resolve(&database)?
50 .access::<&AssetReferenceCounter>()
51 .counter(),
52 3
53 );
54
55 // Drop the first reference and expect 2 references.
56 drop(first);
57 database.maintain()?;
58 assert_eq!(database.storage.len(), 1);
59 assert_eq!(
60 third
61 .resolve(&database)?
62 .access::<&AssetReferenceCounter>()
63 .counter(),
64 2
65 );
66
67 // Drop the second reference and expect 1 reference.
68 drop(second);
69 database.maintain()?;
70 assert_eq!(database.storage.len(), 1);
71 assert_eq!(
72 third
73 .resolve(&database)?
74 .access::<&AssetReferenceCounter>()
75 .counter(),
76 1
77 );
78
79 // Drop the third reference and expect no references and asset no more existing.
80 drop(third);
81 database.maintain()?;
82 assert_eq!(database.storage.len(), 0);
83 /* ANCHOR_END: smart_reference */
84 /* ANCHOR_END: main */
85
86 Ok(())
87}Sourcepub fn ensure<'a>(
&'a self,
database: &'a mut AssetDatabase,
) -> Result<AssetResolved<'a>, Box<dyn Error>>
pub fn ensure<'a>( &'a self, database: &'a mut AssetDatabase, ) -> Result<AssetResolved<'a>, Box<dyn Error>>
Trait Implementations§
Source§impl<'de> Deserialize<'de> for AssetRef
impl<'de> Deserialize<'de> for AssetRef
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
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 From<AssetPath<'static>> for AssetRef
impl From<AssetPath<'static>> for AssetRef
Source§fn from(path: AssetPathStatic) -> Self
fn from(path: AssetPathStatic) -> Self
Converts to this type from the input type.
Source§impl From<AssetRef> for AssetPathStatic
impl From<AssetRef> for AssetPathStatic
impl Eq for AssetRef
Auto Trait Implementations§
impl !Freeze for AssetRef
impl RefUnwindSafe for AssetRef
impl Send for AssetRef
impl Sync for AssetRef
impl Unpin for AssetRef
impl UnwindSafe for AssetRef
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to
key and return true if they are equal.