bevy_asset/
meta.rs

1use crate::{
2    self as bevy_asset, loader::AssetLoader, processor::Process, Asset, AssetPath,
3    DeserializeMetaError, VisitAssetDependencies,
4};
5use bevy_utils::tracing::error;
6use downcast_rs::{impl_downcast, Downcast};
7use ron::ser::PrettyConfig;
8use serde::{Deserialize, Serialize};
9
10pub const META_FORMAT_VERSION: &str = "1.0";
11pub type MetaTransform = Box<dyn Fn(&mut dyn AssetMetaDyn) + Send + Sync>;
12
13/// Asset metadata that informs how an [`Asset`] should be handled by the asset system.
14///
15/// `L` is the [`AssetLoader`] (if one is configured) for the [`AssetAction`]. This can be `()` if it is not required.
16/// `P` is the [`Process`] processor, if one is configured for the [`AssetAction`]. This can be `()` if it is not required.
17#[derive(Serialize, Deserialize)]
18pub struct AssetMeta<L: AssetLoader, P: Process> {
19    /// The version of the meta format being used. This will change whenever a breaking change is made to
20    /// the meta format.
21    pub meta_format_version: String,
22    /// Information produced by the [`AssetProcessor`] _after_ processing this asset.
23    /// This will only exist alongside processed versions of assets. You should not manually set it in your asset source files.
24    ///
25    /// [`AssetProcessor`]: crate::processor::AssetProcessor
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub processed_info: Option<ProcessedInfo>,
28    /// How to handle this asset in the asset system. See [`AssetAction`].
29    pub asset: AssetAction<L::Settings, P::Settings>,
30}
31
32impl<L: AssetLoader, P: Process> AssetMeta<L, P> {
33    pub fn new(asset: AssetAction<L::Settings, P::Settings>) -> Self {
34        Self {
35            meta_format_version: META_FORMAT_VERSION.to_string(),
36            processed_info: None,
37            asset,
38        }
39    }
40
41    /// Deserializes the given serialized byte representation of the asset meta.
42    pub fn deserialize(bytes: &[u8]) -> Result<Self, DeserializeMetaError> {
43        Ok(ron::de::from_bytes(bytes)?)
44    }
45}
46
47/// Configures how an asset source file should be handled by the asset system.
48#[derive(Serialize, Deserialize)]
49pub enum AssetAction<LoaderSettings, ProcessSettings> {
50    /// Load the asset with the given loader and settings
51    /// See [`AssetLoader`].
52    Load {
53        loader: String,
54        settings: LoaderSettings,
55    },
56    /// Process the asset with the given processor and settings.
57    /// See [`Process`] and [`AssetProcessor`].
58    ///
59    /// [`AssetProcessor`]: crate::processor::AssetProcessor
60    Process {
61        processor: String,
62        settings: ProcessSettings,
63    },
64    /// Do nothing with the asset
65    Ignore,
66}
67
68/// Info produced by the [`AssetProcessor`] for a given processed asset. This is used to determine if an
69/// asset source file (or its dependencies) has changed.
70///
71/// [`AssetProcessor`]: crate::processor::AssetProcessor
72#[derive(Serialize, Deserialize, Default, Debug, Clone)]
73pub struct ProcessedInfo {
74    /// A hash of the asset bytes and the asset .meta data
75    pub hash: AssetHash,
76    /// A hash of the asset bytes, the asset .meta data, and the `full_hash` of every `process_dependency`
77    pub full_hash: AssetHash,
78    /// Information about the "process dependencies" used to process this asset.
79    pub process_dependencies: Vec<ProcessDependencyInfo>,
80}
81
82/// Information about a dependency used to process an asset. This is used to determine whether an asset's "process dependency"
83/// has changed.
84#[derive(Serialize, Deserialize, Debug, Clone)]
85pub struct ProcessDependencyInfo {
86    pub full_hash: AssetHash,
87    pub path: AssetPath<'static>,
88}
89
90/// This is a minimal counterpart to [`AssetMeta`] that exists to speed up (or enable) serialization in cases where the whole [`AssetMeta`] isn't
91/// necessary.
92// PERF:
93// Currently, this is used when retrieving asset loader and processor information (when the actual type is not known yet). This could probably
94// be replaced (and made more efficient) by a custom deserializer that reads the loader/processor information _first_, then deserializes the contents
95// using a type registry.
96#[derive(Serialize, Deserialize)]
97pub struct AssetMetaMinimal {
98    pub asset: AssetActionMinimal,
99}
100
101/// This is a minimal counterpart to [`AssetAction`] that exists to speed up (or enable) serialization in cases where the whole [`AssetAction`]
102/// isn't necessary.
103#[derive(Serialize, Deserialize)]
104pub enum AssetActionMinimal {
105    Load { loader: String },
106    Process { processor: String },
107    Ignore,
108}
109
110/// This is a minimal counterpart to [`ProcessedInfo`] that exists to speed up serialization in cases where the whole [`ProcessedInfo`] isn't
111/// necessary.
112#[derive(Serialize, Deserialize)]
113pub struct ProcessedInfoMinimal {
114    pub processed_info: Option<ProcessedInfo>,
115}
116
117/// A dynamic type-erased counterpart to [`AssetMeta`] that enables passing around and interacting with [`AssetMeta`] without knowing
118/// its type.
119pub trait AssetMetaDyn: Downcast + Send + Sync {
120    /// Returns a reference to the [`AssetLoader`] settings, if they exist.
121    fn loader_settings(&self) -> Option<&dyn Settings>;
122    /// Returns a mutable reference to the [`AssetLoader`] settings, if they exist.
123    fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings>;
124    /// Serializes the internal [`AssetMeta`].
125    fn serialize(&self) -> Vec<u8>;
126    /// Returns a reference to the [`ProcessedInfo`] if it exists.
127    fn processed_info(&self) -> &Option<ProcessedInfo>;
128    /// Returns a mutable reference to the [`ProcessedInfo`] if it exists.
129    fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo>;
130}
131
132impl<L: AssetLoader, P: Process> AssetMetaDyn for AssetMeta<L, P> {
133    fn loader_settings(&self) -> Option<&dyn Settings> {
134        if let AssetAction::Load { settings, .. } = &self.asset {
135            Some(settings)
136        } else {
137            None
138        }
139    }
140    fn loader_settings_mut(&mut self) -> Option<&mut dyn Settings> {
141        if let AssetAction::Load { settings, .. } = &mut self.asset {
142            Some(settings)
143        } else {
144            None
145        }
146    }
147    fn serialize(&self) -> Vec<u8> {
148        ron::ser::to_string_pretty(&self, PrettyConfig::default())
149            .expect("type is convertible to ron")
150            .into_bytes()
151    }
152    fn processed_info(&self) -> &Option<ProcessedInfo> {
153        &self.processed_info
154    }
155    fn processed_info_mut(&mut self) -> &mut Option<ProcessedInfo> {
156        &mut self.processed_info
157    }
158}
159
160impl_downcast!(AssetMetaDyn);
161
162/// Settings used by the asset system, such as by [`AssetLoader`], [`Process`], and [`AssetSaver`]
163///
164/// [`AssetSaver`]: crate::saver::AssetSaver
165pub trait Settings: Downcast + Send + Sync + 'static {}
166
167impl<T: 'static> Settings for T where T: Send + Sync {}
168
169impl_downcast!(Settings);
170
171/// The () processor should never be called. This implementation exists to make the meta format nicer to work with.
172impl Process for () {
173    type Settings = ();
174    type OutputLoader = ();
175
176    async fn process(
177        &self,
178        _context: &mut bevy_asset::processor::ProcessContext<'_>,
179        _meta: AssetMeta<(), Self>,
180        _writer: &mut bevy_asset::io::Writer,
181    ) -> Result<(), bevy_asset::processor::ProcessError> {
182        unreachable!()
183    }
184}
185
186impl Asset for () {}
187
188impl VisitAssetDependencies for () {
189    fn visit_dependencies(&self, _visit: &mut impl FnMut(bevy_asset::UntypedAssetId)) {
190        unreachable!()
191    }
192}
193
194/// The () loader should never be called. This implementation exists to make the meta format nicer to work with.
195impl AssetLoader for () {
196    type Asset = ();
197    type Settings = ();
198    type Error = std::io::Error;
199    async fn load(
200        &self,
201        _reader: &mut dyn crate::io::Reader,
202        _settings: &Self::Settings,
203        _load_context: &mut crate::LoadContext<'_>,
204    ) -> Result<Self::Asset, Self::Error> {
205        unreachable!();
206    }
207
208    fn extensions(&self) -> &[&str] {
209        unreachable!();
210    }
211}
212
213pub(crate) fn meta_transform_settings<S: Settings>(
214    meta: &mut dyn AssetMetaDyn,
215    settings: &(impl Fn(&mut S) + Send + Sync + 'static),
216) {
217    if let Some(loader_settings) = meta.loader_settings_mut() {
218        if let Some(loader_settings) = loader_settings.downcast_mut::<S>() {
219            settings(loader_settings);
220        } else {
221            error!(
222                "Configured settings type {} does not match AssetLoader settings type",
223                core::any::type_name::<S>(),
224            );
225        }
226    }
227}
228
229pub(crate) fn loader_settings_meta_transform<S: Settings>(
230    settings: impl Fn(&mut S) + Send + Sync + 'static,
231) -> MetaTransform {
232    Box::new(move |meta| meta_transform_settings(meta, &settings))
233}
234
235pub type AssetHash = [u8; 32];
236
237/// NOTE: changing the hashing logic here is a _breaking change_ that requires a [`META_FORMAT_VERSION`] bump.
238pub(crate) fn get_asset_hash(meta_bytes: &[u8], asset_bytes: &[u8]) -> AssetHash {
239    let mut hasher = blake3::Hasher::new();
240    hasher.update(meta_bytes);
241    hasher.update(asset_bytes);
242    *hasher.finalize().as_bytes()
243}
244
245/// NOTE: changing the hashing logic here is a _breaking change_ that requires a [`META_FORMAT_VERSION`] bump.
246pub(crate) fn get_full_asset_hash(
247    asset_hash: AssetHash,
248    dependency_hashes: impl Iterator<Item = AssetHash>,
249) -> AssetHash {
250    let mut hasher = blake3::Hasher::new();
251    hasher.update(&asset_hash);
252    for hash in dependency_hashes {
253        hasher.update(&hash);
254    }
255    *hasher.finalize().as_bytes()
256}