1use alloc::{
2 boxed::Box,
3 string::{String, ToString},
4 vec::Vec,
5};
6use futures_lite::AsyncReadExt;
7
8use crate::{
9 io::{AssetReaderError, Reader},
10 loader::AssetLoader,
11 processor::Process,
12 Asset, AssetPath, DeserializeMetaError, VisitAssetDependencies,
13};
14use downcast_rs::{impl_downcast, Downcast};
15use ron::ser::PrettyConfig;
16use serde::{Deserialize, Serialize};
17use tracing::error;
18
19pub const META_FORMAT_VERSION: &str = "1.0";
20pub type MetaTransform = Box<dyn Fn(&mut dyn AssetMetaDyn) + Send + Sync>;
21
22#[derive(Serialize, Deserialize)]
27pub struct AssetMeta<L: AssetLoader, P: Process> {
28 pub meta_format_version: String,
31 #[serde(skip_serializing_if = "Option::is_none")]
36 pub processed_info: Option<ProcessedInfo>,
37 pub asset: AssetAction<L::Settings, P::Settings>,
39}
40
41impl<L: AssetLoader, P: Process> AssetMeta<L, P> {
42 pub fn new(asset: AssetAction<L::Settings, P::Settings>) -> Self {
43 Self {
44 meta_format_version: META_FORMAT_VERSION.to_string(),
45 processed_info: None,
46 asset,
47 }
48 }
49
50 pub fn deserialize(bytes: &[u8]) -> Result<Self, DeserializeMetaError> {
52 Ok(ron::de::from_bytes(bytes)?)
53 }
54}
55
56#[derive(Serialize, Deserialize)]
58pub enum AssetAction<LoaderSettings, ProcessSettings> {
59 Load {
62 loader: String,
63 settings: LoaderSettings,
64 },
65 Process {
70 processor: String,
71 settings: ProcessSettings,
72 },
73 Ignore,
75}
76
77#[derive(Serialize, Deserialize, Default, Debug, Clone)]
82pub struct ProcessedInfo {
83 pub hash: AssetHash,
85 pub full_hash: AssetHash,
87 pub process_dependencies: Vec<ProcessDependencyInfo>,
89}
90
91#[derive(Serialize, Deserialize, Debug, Clone)]
94pub struct ProcessDependencyInfo {
95 pub full_hash: AssetHash,
96 pub path: AssetPath<'static>,
97}
98
99#[derive(Serialize, Deserialize)]
106pub struct AssetMetaMinimal {
107 pub asset: AssetActionMinimal,
108}
109
110#[derive(Serialize, Deserialize)]
113pub enum AssetActionMinimal {
114 Load { loader: String },
115 Process { processor: String },
116 Ignore,
117}
118
119#[derive(Serialize, Deserialize)]
122pub struct ProcessedInfoMinimal {
123 pub processed_info: Option<ProcessedInfo>,
124}
125
126pub trait AssetMetaDyn: Downcast + Send + Sync {
129 fn loader_settings(&self) -> Option<&dyn Settings>;
131 fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings>;
133 fn process_settings(&self) -> Option<&dyn Settings>;
135 fn serialize(&self) -> Vec<u8>;
137 fn processed_info(&self) -> &Option<ProcessedInfo>;
139 fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo>;
141}
142
143impl<L: AssetLoader, P: Process> AssetMetaDyn for AssetMeta<L, P> {
144 fn loader_settings(&self) -> Option<&dyn Settings> {
145 if let AssetAction::Load { settings, .. } = &self.asset {
146 Some(settings)
147 } else {
148 None
149 }
150 }
151 fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings> {
152 if let AssetAction::Load { settings, .. } = &mut self.asset {
153 Some(settings)
154 } else {
155 None
156 }
157 }
158 fn process_settings(&self) -> Option<&dyn Settings> {
159 if let AssetAction::Process { settings, .. } = &self.asset {
160 Some(settings)
161 } else {
162 None
163 }
164 }
165 fn serialize(&self) -> Vec<u8> {
166 ron::ser::to_string_pretty(
167 &self,
168 PrettyConfig::default().new_line("\n"),
171 )
172 .expect("type is convertible to ron")
173 .into_bytes()
174 }
175 fn processed_info(&self) -> &Option<ProcessedInfo> {
176 &self.processed_info
177 }
178 fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo> {
179 &mut self.processed_info
180 }
181}
182
183impl_downcast!(AssetMetaDyn);
184
185pub trait Settings: Downcast + Send + Sync + 'static {}
189
190impl<T: 'static> Settings for T where T: Send + Sync {}
191
192impl_downcast!(Settings);
193
194impl Process for () {
196 type Settings = ();
197 type OutputLoader = ();
198
199 async fn process(
200 &self,
201 _context: &mut bevy_asset::processor::ProcessContext<'_>,
202 _settings: &Self::Settings,
203 _writer: &mut bevy_asset::io::Writer,
204 ) -> Result<(), bevy_asset::processor::ProcessError> {
205 unreachable!()
206 }
207}
208
209impl Asset for () {}
210
211impl VisitAssetDependencies for () {
212 fn visit_dependencies(&self, _visit: &mut impl FnMut(bevy_asset::UntypedAssetId)) {
213 unreachable!()
214 }
215}
216
217impl AssetLoader for () {
219 type Asset = ();
220 type Settings = ();
221 type Error = std::io::Error;
222 async fn load(
223 &self,
224 _reader: &mut dyn Reader,
225 _settings: &Self::Settings,
226 _load_context: &mut crate::LoadContext<'_>,
227 ) -> Result<Self::Asset, Self::Error> {
228 unreachable!();
229 }
230
231 fn extensions(&self) -> &[&str] {
232 unreachable!();
233 }
234}
235
236pub(crate) fn meta_transform_settings<S: Settings>(
237 meta: &mut dyn AssetMetaDyn,
238 settings: &(impl Fn(&mut S) + Send + Sync + 'static),
239) {
240 if let Some(loader_settings) = meta.loader_settings_mut() {
241 if let Some(loader_settings) = loader_settings.downcast_mut::<S>() {
242 settings(loader_settings);
243 } else {
244 error!(
245 "Configured settings type {} does not match AssetLoader settings type",
246 core::any::type_name::<S>(),
247 );
248 }
249 }
250}
251
252pub(crate) fn loader_settings_meta_transform<S: Settings>(
253 settings: impl Fn(&mut S) + Send + Sync + 'static,
254) -> MetaTransform {
255 Box::new(move |meta| meta_transform_settings(meta, &settings))
256}
257
258pub type AssetHash = [u8; 32];
259
260pub(crate) async fn get_asset_hash(
262 meta_bytes: &[u8],
263 asset_reader: &mut impl Reader,
264) -> Result<AssetHash, AssetReaderError> {
265 let mut hasher = blake3::Hasher::new();
266 hasher.update(meta_bytes);
267 let mut buffer = [0; blake3::CHUNK_LEN];
268 loop {
269 let bytes_read = asset_reader.read(&mut buffer).await?;
270 hasher.update(&buffer[..bytes_read]);
271 if bytes_read == 0 {
272 break;
274 }
275 }
276 Ok(*hasher.finalize().as_bytes())
277}
278
279pub(crate) fn get_full_asset_hash(
281 asset_hash: AssetHash,
282 dependency_hashes: impl Iterator<Item = AssetHash>,
283) -> AssetHash {
284 let mut hasher = blake3::Hasher::new();
285 hasher.update(&asset_hash);
286 for hash in dependency_hashes {
287 hasher.update(&hash);
288 }
289 *hasher.finalize().as_bytes()
290}