nadir_assets/asset.rs
1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The asset types' side: decoding, then finalizing on the main thread.
16
17use std::any::{Any, type_name};
18
19use nadir_codec::Limits;
20
21use crate::AssetError;
22
23/// A kind of asset: a texture, a sound, a level.
24///
25/// Loading one has two steps:
26///
27/// 1. [`Asset::decode`] turns the file's bytes into data, on one of the
28/// server's worker threads, so it reaches nothing but the bytes and the
29/// [`DecodeCtx`].
30/// 2. [`Asset::finalize`] makes the asset from that data on the main thread,
31/// with the resources in the [`FinalizeCtx`]: a texture is uploaded to
32/// the GPU there.
33///
34/// Once every scope it was loaded in is unloaded, [`Asset::release`] frees
35/// it on the main thread. A reload
36/// ([`AssetServer::reload`](crate::AssetServer::reload)) makes a new value
37/// the same way, and releases the one it replaces.
38pub trait Asset: Sized + Send + 'static {
39 /// What [`Asset::decode`] makes.
40 type Decoded: Send + 'static;
41
42 /// The extensions, without the dot, that a path of this type ends in.
43 const EXTENSIONS: &'static [&'static str];
44
45 /// Decodes a file's bytes.
46 ///
47 /// # Errors
48 ///
49 /// Any [`AssetError`]; usually [`AssetError::Decode`] or
50 /// [`AssetError::Invalid`].
51 fn decode(bytes: &[u8], ctx: &DecodeCtx<'_>) -> Result<Self::Decoded, AssetError>;
52
53 /// Makes the asset from what [`Asset::decode`] made.
54 ///
55 /// # Errors
56 ///
57 /// Any [`AssetError`]; usually [`AssetError::MissingContext`] or
58 /// [`AssetError::Invalid`].
59 fn finalize(decoded: Self::Decoded, ctx: &mut FinalizeCtx<'_>) -> Result<Self, AssetError>;
60
61 /// Makes the stand-in for an asset that failed to load, when the server
62 /// shows placeholders ([`OnFailure::Placeholder`](crate::OnFailure)).
63 /// None by default.
64 ///
65 /// # Errors
66 ///
67 /// [`AssetError::NoPlaceholder`] if the type has none, or why it could
68 /// not be made.
69 fn placeholder(ctx: &mut FinalizeCtx<'_>) -> Result<Self, AssetError> {
70 let _ = ctx;
71 Err(AssetError::NoPlaceholder)
72 }
73
74 /// Frees what the asset holds outside the server, such as its GPU
75 /// texture, once every scope it was loaded in is unloaded. The next
76 /// [`AssetServer::finish_completed_loads`](crate::AssetServer::finish_completed_loads)
77 /// calls it, with that frame's context; a placeholder is freed the same
78 /// way. A reload's finish calls it too, on the value, or the
79 /// placeholder, that the reload replaces, while the handle stays and
80 /// names the new value. By default the asset is only dropped.
81 ///
82 /// # Errors
83 ///
84 /// Any [`AssetError`]; usually [`AssetError::MissingContext`]. The
85 /// server logs it with the asset's path, and drops the asset.
86 fn release(self, ctx: &mut FinalizeCtx<'_>) -> Result<(), AssetError> {
87 let _ = ctx;
88 Ok(())
89 }
90}
91
92/// What [`Asset::decode`] may know besides the bytes.
93#[derive(Clone, Copy, Debug)]
94pub struct DecodeCtx<'a> {
95 path: &'a str,
96 limits: Limits,
97}
98
99impl<'a> DecodeCtx<'a> {
100 /// A context for decoding the asset at `path`. The server makes one for
101 /// each load; tests and tools can make their own.
102 pub fn new(path: &'a str, limits: Limits) -> Self {
103 Self { path, limits }
104 }
105
106 /// The asset's path, for labels and messages.
107 pub fn path(&self) -> &str {
108 self.path
109 }
110
111 /// The limits that decoding must keep to.
112 pub fn limits(&self) -> Limits {
113 self.limits
114 }
115}
116
117/// The resources [`Asset::finalize`] makes assets with, such as the GPU
118/// device, by type. It holds at most [`FinalizeCtx::CAPACITY`] of them, and
119/// allocates nothing, so a game can make one every frame.
120///
121/// ```
122/// use nadir_assets::FinalizeCtx;
123///
124/// struct Device;
125/// let mut device = Device;
126/// let mut ctx = FinalizeCtx::new().with(&mut device);
127/// assert!(ctx.get_mut::<Device>().is_ok());
128/// assert!(ctx.get_mut::<u32>().is_err());
129/// ```
130pub struct FinalizeCtx<'a> {
131 resources: [Option<&'a mut dyn Any>; FinalizeCtx::CAPACITY],
132}
133
134impl<'a> FinalizeCtx<'a> {
135 /// The most resources a context holds.
136 pub const CAPACITY: usize = 4;
137
138 /// A context with no resources.
139 pub fn new() -> Self {
140 Self {
141 resources: [const { None }; Self::CAPACITY],
142 }
143 }
144
145 /// The context with `resource` too. It replaces a resource of the same
146 /// type.
147 ///
148 /// A resource past [`FinalizeCtx::CAPACITY`] is not kept, so
149 /// [`FinalizeCtx::get_mut`] does not find it; debug builds panic
150 /// instead.
151 #[must_use]
152 pub fn with<R: Any>(mut self, resource: &'a mut R) -> Self {
153 let held =
154 |slot: &Option<&'a mut dyn Any>| slot.as_deref().is_some_and(|held| held.is::<R>());
155 let index = (self.resources.iter().position(held))
156 .or_else(|| self.resources.iter().position(Option::is_none));
157 match index {
158 Some(index) => self.resources[index] = Some(resource),
159 None => debug_assert!(
160 false,
161 "a FinalizeCtx holds at most {} resources",
162 Self::CAPACITY
163 ),
164 }
165 self
166 }
167
168 /// The resource of type `R`.
169 ///
170 /// # Errors
171 ///
172 /// [`AssetError::MissingContext`] if the context holds none.
173 pub fn get_mut<R: Any>(&mut self) -> Result<&mut R, AssetError> {
174 self.resources
175 .iter_mut()
176 .flatten()
177 .find_map(|resource| resource.downcast_mut::<R>())
178 .ok_or(AssetError::MissingContext(type_name::<R>()))
179 }
180}
181
182impl Default for FinalizeCtx<'_> {
183 fn default() -> Self {
184 Self::new()
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 #[test]
193 fn resources_are_found_by_type() {
194 let (mut a, mut b, mut c) = (1u32, 2u64, String::from("x"));
195 let mut ctx = FinalizeCtx::new().with(&mut a).with(&mut b).with(&mut c);
196 *ctx.get_mut::<u32>().expect("held") += 10;
197 assert_eq!(*ctx.get_mut::<u64>().expect("held"), 2);
198 assert_eq!(ctx.get_mut::<String>().expect("held"), "x");
199 assert_eq!(
200 ctx.get_mut::<i8>().map(drop),
201 Err(AssetError::MissingContext("i8"))
202 );
203 assert_eq!(a, 11);
204 }
205
206 #[test]
207 fn a_resource_of_a_held_type_replaces_it() {
208 let (mut first, mut second) = (1u32, 2u32);
209 let mut ctx = FinalizeCtx::new().with(&mut first).with(&mut second);
210 assert_eq!(*ctx.get_mut::<u32>().expect("held"), 2);
211 assert_eq!(ctx.resources.iter().flatten().count(), 1);
212 }
213
214 #[test]
215 fn a_context_holds_up_to_its_capacity() {
216 let (mut a, mut b, mut c, mut d) = (1u8, 2u16, 3u32, 4u64);
217 let mut ctx = FinalizeCtx::new()
218 .with(&mut a)
219 .with(&mut b)
220 .with(&mut c)
221 .with(&mut d);
222 assert_eq!(*ctx.get_mut::<u8>().expect("held"), 1);
223 assert_eq!(*ctx.get_mut::<u64>().expect("held"), 4);
224 }
225
226 #[test]
227 #[should_panic(expected = "a FinalizeCtx holds at most 4 resources")]
228 #[cfg(debug_assertions)]
229 fn one_resource_too_many_panics_in_debug_builds() {
230 let (mut a, mut b, mut c, mut d, mut e) = (1u8, 2u16, 3u32, 4u64, 5i8);
231 let _ = FinalizeCtx::new()
232 .with(&mut a)
233 .with(&mut b)
234 .with(&mut c)
235 .with(&mut d)
236 .with(&mut e);
237 }
238}