1use crate::{
2 app::SystemStage,
3 assets::{
4 deps::Dependencies,
5 storage::{Assets, ProcessedAssets},
6 upload::Asset,
7 },
8 ecs::{
9 plugin::Plugin,
10 resources::Resources,
11 system::{Res, ResMut},
12 },
13};
14
15pub struct AssetPlugin<B, T: Asset<B>> {
32 _marker: std::marker::PhantomData<(B, T)>,
33}
34
35impl<B, T: Asset<B>> AssetPlugin<B, T> {
36 pub fn new() -> Self {
37 Self {
38 _marker: std::marker::PhantomData,
39 }
40 }
41}
42
43impl<B, T> Plugin for AssetPlugin<B, T>
44where
45 B: 'static + Send + Sync,
46 T: Asset<B>,
47{
48 fn build(&self, app: &mut crate::app::App) {
49 app.try_insert_resource(Assets::<T::Source>::new());
50 app.try_insert_resource(ProcessedAssets::<T>::new());
51 app.add_system(SystemStage::AssetSync, sync_assets::<B, T>);
52 app.required.provides::<ProcessedAssets<T>>();
53 }
54}
55
56fn sync_assets<B, T>(
62 mut cpu: ResMut<Assets<T::Source>>,
63 mut processed: ResMut<ProcessedAssets<T>>,
64 backend: Option<Res<B>>,
65 world: &hecs::World,
66 resources: &Resources,
67) where
68 B: 'static + Send + Sync,
69 T: Asset<B>,
70{
71 let Some(backend) = backend else {
72 log_waiting::<B, T>(&cpu, "backend");
73 return;
74 };
75 let Some(deps) = T::Deps::try_gather(world, resources) else {
76 log_waiting::<B, T>(&cpu, "dependencies");
77 return;
78 };
79
80 let mut still_pending = Vec::new();
81
82 for handle in cpu.take_dirty() {
83 let Some(source) = cpu.get(handle) else {
84 continue;
85 };
86 match T::upload(source, &backend, &deps) {
87 Some(value) => {
88 if let Some(name) = cpu.name_for_handle(handle) {
89 processed.names.insert(name.to_string(), handle);
90 }
91 processed.insert(handle, value);
92 }
93 None => {
94 tracing::trace!(
95 "{}: {handle:?} not ready yet (dependency exists but entry missing), requeued",
96 std::any::type_name::<T>()
97 );
98 still_pending.push(handle);
99 }
100 }
101 }
102
103 if !still_pending.is_empty() {
104 tracing::trace!(
105 "{}: {} handle(s) requeued this tick",
106 std::any::type_name::<T>(),
107 still_pending.len()
108 );
109 }
110
111 cpu.requeue(still_pending);
112}
113
114fn log_waiting<D, T>(cpu: &Assets<T::Source>, what: &str)
115where
116 D: 'static + Send + Sync,
117 T: Asset<D>,
118{
119 if !cpu.dirty_is_empty() {
120 tracing::trace!(
121 "{}: waiting on {what}, {} pending",
122 std::any::type_name::<T>(),
123 cpu.dirty_len()
124 );
125 }
126}