1use std::{
10 any::TypeId,
11 error::Error,
12 fmt,
13 ops::{Deref, DerefMut},
14};
15
16use bevy_ecs::{
17 change_detection::DetectChanges,
18 prelude::{Res, ResMut, Resource},
19 system::SystemParam,
20 world::World,
21};
22
23use crate::system::Stage;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ApplicationResourceError {
28 Duplicate {
30 resource: &'static str,
32 },
33 LimitExceeded {
35 limit: usize,
37 },
38}
39
40impl fmt::Display for ApplicationResourceError {
41 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
42 match self {
43 Self::Duplicate { resource } => {
44 write!(
45 formatter,
46 "Application Resource `{resource}` is already registered"
47 )
48 }
49 Self::LimitExceeded { limit } => write!(
50 formatter,
51 "Application Resource registry reached its limit of {limit} types"
52 ),
53 }
54 }
55}
56
57impl Error for ApplicationResourceError {}
58
59#[derive(Resource)]
60struct StoredApplicationResource<T: Send + Sync + 'static>(T);
61
62#[derive(SystemParam)]
72pub struct AppRes<'w, T: Send + Sync + 'static> {
73 inner: Res<'w, StoredApplicationResource<T>>,
74}
75
76impl<T: Send + Sync + 'static> Deref for AppRes<'_, T> {
77 type Target = T;
78
79 fn deref(&self) -> &Self::Target {
80 &self.inner.0
81 }
82}
83
84impl<T: Send + Sync + 'static> AppRes<'_, T> {
85 pub fn is_changed(&self) -> bool {
90 self.inner.is_changed()
91 }
92
93 pub fn is_added(&self) -> bool {
98 self.inner.is_added()
99 }
100}
101
102#[derive(SystemParam)]
110pub struct AppResMut<'w, T: Send + Sync + 'static> {
111 inner: ResMut<'w, StoredApplicationResource<T>>,
112}
113
114impl<T: Send + Sync + 'static> Deref for AppResMut<'_, T> {
115 type Target = T;
116
117 fn deref(&self) -> &Self::Target {
118 &self.inner.0
119 }
120}
121
122impl<T: Send + Sync + 'static> DerefMut for AppResMut<'_, T> {
123 fn deref_mut(&mut self) -> &mut Self::Target {
124 &mut self.inner.0
125 }
126}
127
128impl<T: Send + Sync + 'static> AppResMut<'_, T> {
129 pub fn is_changed(&self) -> bool {
134 self.inner.is_changed()
135 }
136
137 pub fn is_added(&self) -> bool {
142 self.inner.is_added()
143 }
144}
145
146type InitialInstaller = Box<dyn FnOnce(&mut World) + Send + 'static>;
147
148struct Registration {
149 type_id: TypeId,
150 initial: Option<InitialInstaller>,
151 contains: fn(&World) -> bool,
152 move_between: fn(&mut World, &mut World),
153}
154
155#[derive(Clone, Copy)]
156struct Requirement {
157 type_id: TypeId,
158 type_name: &'static str,
159 stage: Stage,
160 system: &'static str,
161}
162
163#[derive(Default)]
165pub(crate) struct ApplicationResourceRegistry {
166 registrations: Vec<Registration>,
167 requirements: Vec<Requirement>,
168}
169
170impl ApplicationResourceRegistry {
171 pub(crate) fn insert<T: Send + Sync + 'static>(
172 &mut self,
173 value: T,
174 limit: usize,
175 ) -> Result<(), ApplicationResourceError> {
176 let type_id = TypeId::of::<T>();
177 let type_name = std::any::type_name::<T>();
178 if self
179 .registrations
180 .iter()
181 .any(|registration| registration.type_id == type_id)
182 {
183 return Err(ApplicationResourceError::Duplicate {
184 resource: type_name,
185 });
186 }
187 if self.registrations.len() >= limit {
188 return Err(ApplicationResourceError::LimitExceeded { limit });
189 }
190
191 self.registrations.push(Registration {
192 type_id,
193 initial: Some(Box::new(move |world| {
194 world.insert_resource(StoredApplicationResource(value));
195 })),
196 contains: contains::<T>,
197 move_between: move_between::<T>,
198 });
199 Ok(())
200 }
201
202 pub(crate) fn require<T: Send + Sync + 'static>(&mut self, stage: Stage, system: &'static str) {
203 let type_id = TypeId::of::<T>();
204 if self
205 .requirements
206 .iter()
207 .all(|requirement| requirement.type_id != type_id)
208 {
209 self.requirements.push(Requirement {
210 type_id,
211 type_name: std::any::type_name::<T>(),
212 stage,
213 system,
214 });
215 }
216 }
217
218 pub(crate) fn first_missing_requirement(&self) -> Option<(&'static str, Stage, &'static str)> {
219 self.requirements
220 .iter()
221 .find(|requirement| {
222 self.registrations
223 .iter()
224 .all(|registration| registration.type_id != requirement.type_id)
225 })
226 .map(|requirement| (requirement.type_name, requirement.stage, requirement.system))
227 }
228
229 pub(crate) fn install_initial(&mut self, world: &mut World) -> bool {
230 if self
231 .registrations
232 .iter()
233 .any(|registration| registration.initial.is_none())
234 {
235 return false;
236 }
237
238 for registration in &mut self.registrations {
239 let Some(install) = registration.initial.take() else {
240 return false;
241 };
242 install(world);
243 }
244 true
245 }
246
247 pub(crate) fn can_transfer(&self, source: &World, target: &World) -> bool {
250 self.registrations
251 .iter()
252 .all(|registration| (registration.contains)(source) && !(registration.contains)(target))
253 }
254
255 pub(crate) fn transfer_prevalidated(&self, source: &mut World, target: &mut World) {
261 for registration in &self.registrations {
262 (registration.move_between)(source, target);
263 }
264 }
265
266 pub(crate) fn get<'a, T: Send + Sync + 'static>(&self, world: &'a World) -> Option<&'a T> {
267 world
268 .get_resource::<StoredApplicationResource<T>>()
269 .map(|resource| &resource.0)
270 }
271
272 pub(crate) fn with_mut<T: Send + Sync + 'static, R>(
273 &self,
274 world: &mut World,
275 update: impl FnOnce(&mut T) -> R,
276 ) -> Option<R> {
277 let mut resource = world.get_resource_mut::<StoredApplicationResource<T>>()?;
278 Some(update(&mut resource.0))
279 }
280}
281
282fn contains<T: Send + Sync + 'static>(world: &World) -> bool {
283 world.contains_resource::<StoredApplicationResource<T>>()
284}
285
286fn move_between<T: Send + Sync + 'static>(source: &mut World, target: &mut World) {
287 assert!(
288 !target.contains_resource::<StoredApplicationResource<T>>(),
289 "prevalidated Application Resource target became occupied"
290 );
291 let resource = source
292 .remove_resource::<StoredApplicationResource<T>>()
293 .expect("prevalidated Application Resource source became empty");
294 target.insert_resource(resource);
295}
296
297#[cfg(test)]
298mod tests {
299 use bevy_ecs::prelude::Resource;
300
301 use super::*;
302
303 #[derive(Debug, PartialEq, Eq, Resource)]
304 struct Score(u32);
305
306 #[test]
307 fn rejects_duplicate_types_without_replacing_the_first_value() {
308 let mut registry = ApplicationResourceRegistry::default();
309 assert!(registry.insert(Score(7), 2).is_ok());
310 assert!(matches!(
311 registry.insert(Score(99), 2),
312 Err(ApplicationResourceError::Duplicate { .. })
313 ));
314
315 let mut world = World::new();
316 assert!(registry.install_initial(&mut world));
317 assert_eq!(registry.get::<Score>(&world), Some(&Score(7)));
318 }
319
320 #[test]
321 fn enforces_the_frozen_type_limit() {
322 let mut registry = ApplicationResourceRegistry::default();
323 assert!(registry.insert(Score(7), 1).is_ok());
324 assert!(matches!(
325 registry.insert("settings", 1),
326 Err(ApplicationResourceError::LimitExceeded { limit: 1 })
327 ));
328 }
329
330 #[test]
331 fn application_and_world_resource_namespaces_are_distinct() {
332 let mut registry = ApplicationResourceRegistry::default();
333 assert!(registry.insert(Score(7), 1).is_ok());
334 let mut world = World::new();
335 world.insert_resource(Score(99));
336 assert!(registry.install_initial(&mut world));
337
338 assert_eq!(registry.get::<Score>(&world), Some(&Score(7)));
339 assert_eq!(world.resource::<Score>(), &Score(99));
340 }
341
342 #[test]
343 fn transfer_moves_identity_without_cloning() {
344 let mut registry = ApplicationResourceRegistry::default();
345 assert!(registry.insert(Score(7), 1).is_ok());
346 let mut first = World::new();
347 let mut second = World::new();
348 assert!(registry.install_initial(&mut first));
349
350 assert!(registry.can_transfer(&first, &second));
351 registry.transfer_prevalidated(&mut first, &mut second);
352 assert!(registry.get::<Score>(&first).is_none());
353 assert_eq!(registry.get::<Score>(&second), Some(&Score(7)));
354 }
355
356 #[test]
357 fn rejected_transfer_does_not_partially_move_values() {
358 let mut registry = ApplicationResourceRegistry::default();
359 assert!(registry.insert(Score(7), 2).is_ok());
360 assert!(registry.insert(String::from("live"), 2).is_ok());
361 let mut first = World::new();
362 let mut second = World::new();
363 assert!(registry.install_initial(&mut first));
364 second.insert_resource(StoredApplicationResource(String::from("collision")));
365
366 assert!(!registry.can_transfer(&first, &second));
367 assert_eq!(registry.get::<Score>(&first), Some(&Score(7)));
368 assert_eq!(
369 registry.get::<String>(&first).map(String::as_str),
370 Some("live")
371 );
372 }
373}