beet_core 0.0.8

Core utilities and types for other beet crates
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use crate::prelude::*;
use bevy::ecs::change_detection::MaybeLocation;
use bevy::ecs::component::ComponentInfo;
use bevy::ecs::message::MessageCursor;
use bevy::ecs::query::QueryData;
use bevy::ecs::query::QueryFilter;
#[cfg(feature = "multi_threaded")]
use bevy::ecs::schedule::ExecutorKind;
use bevy::ecs::system::IntoObserverSystem;
use bevy::prelude::*;
use extend::ext;
use std::marker::PhantomData;

/// system version
pub fn log_component_names(entity: In<Entity>, world: &mut World) {
	world.log_component_names(*entity);
}


/// common trait for 'App' and 'World'
pub trait IntoWorld {
	#[allow(unused)]
	fn into_world(&self) -> &World;
	fn into_world_mut(&mut self) -> &mut World;
}
impl IntoWorld for World {
	fn into_world(&self) -> &World { self }
	fn into_world_mut(&mut self) -> &mut World { self }
}
impl IntoWorld for App {
	fn into_world(&self) -> &World { self.world() }
	fn into_world_mut(&mut self) -> &mut World { self.world_mut() }
}
#[ext(name=WorldExt)]
pub impl World {
	fn with_resource<T: Resource>(&mut self, resource: T) -> &mut Self {
		self.insert_resource(resource);
		self
	}

	fn await_event<E: Event, B: Bundle>(
		&mut self,
	) -> impl Future<Output = &mut Self> {
		// TODO cleaner but we get messy accessed threadlocal panic
		// async move {
		// 	self.run_async_then(async |world| {
		// 		world.await_event::<E, B>().await;
		// 	})
		// 	.await;
		// 	self
		// }


		let (send, recv) = async_channel::bounded(1);
		self.add_observer(move |ev: On<E, B>, mut commands: Commands| {
			send.try_send(()).ok();
			commands.entity(ev.observer()).despawn();
		});
		async move {
			AsyncRunner::poll_and_update(
				|| {
					self.update_local();
				},
				recv,
			)
			.await;
			self
		}
	}

	/// The world equivelent of [`App::update`].
	///
	/// In multi_threaded mode, this temporarily sets all schedules to use
	/// single-threaded execution to avoid deadlocks when called from within
	/// async tasks on IoTaskPool.
	fn update_local(&mut self) {
		#[cfg(feature = "multi_threaded")]
		{
			// Temporarily force single-threaded execution for all schedules
			// to avoid deadlock when called from within a spawn_local task.
			self.force_single_threaded_schedules();
			self.run_schedule(Main);
			self.clear_trackers();
		}
		#[cfg(not(feature = "multi_threaded"))]
		{
			self.run_schedule(Main);
			self.clear_trackers();
		}
	}

	/// Force all schedules in the world to use single-threaded execution.
	/// This is necessary when running schedules from within async tasks
	/// to avoid deadlocks with bevy's parallel schedule executor.
	#[cfg(feature = "multi_threaded")]
	fn force_single_threaded_schedules(&mut self) {
		self.resource_scope(|_world, mut schedules: Mut<Schedules>| {
			for (_label, schedule) in schedules.iter_mut() {
				if schedule.get_executor_kind() == ExecutorKind::MultiThreaded {
					schedule.set_executor_kind(ExecutorKind::SingleThreaded);
				}
			}
		});
	}
	/// The world equivelent of [`App::should_exit`]
	fn should_exit(&self) -> Option<AppExit> {
		let mut reader = MessageCursor::default();

		let events = self.get_resource::<Messages<AppExit>>()?;
		let mut events = reader.read(events);

		if events.len() != 0 {
			return Some(
				events
					.find(|exit| exit.is_error())
					.cloned()
					.unwrap_or(AppExit::Success),
			);
		}

		None
	}
}


pub struct QueryOnce<D: QueryData, F: QueryFilter = ()> {
	items: Vec<D::Item<'static, 'static>>,
	_phantom: PhantomData<F>,
}

impl<D: QueryData, F: QueryFilter> std::ops::Deref for QueryOnce<D, F> {
	type Target = Vec<D::Item<'static, 'static>>;
	fn deref(&self) -> &Self::Target { &self.items }
}

impl<D: QueryData, F: QueryFilter> std::ops::DerefMut for QueryOnce<D, F> {
	fn deref_mut(&mut self) -> &mut Self::Target { &mut self.items }
}

impl<D: QueryData, F: QueryFilter> QueryOnce<D, F> {
	pub fn new<T: IntoWorld>(world: &mut T) -> Self {
		let world = world.into_world_mut();
		let mut query = world.query_filtered::<D, F>();
		let items = query.iter_mut(world).collect::<Vec<_>>();
		// SAFETY: We're extending the lifetime to 'static because we own the data
		// The query items are collected into owned data structures
		let items = unsafe { std::mem::transmute(items) };
		Self {
			items,
			_phantom: PhantomData,
		}
	}
}

impl<D: QueryData, F: QueryFilter> IntoIterator for QueryOnce<D, F> {
	type Item = D::Item<'static, 'static>;
	type IntoIter = std::vec::IntoIter<Self::Item>;

	fn into_iter(self) -> Self::IntoIter { self.items.into_iter() }
}

impl<'a, D: QueryData, F: QueryFilter> IntoIterator for &'a QueryOnce<D, F> {
	type Item = &'a D::Item<'static, 'static>;
	type IntoIter = std::slice::Iter<'a, D::Item<'static, 'static>>;

	fn into_iter(self) -> Self::IntoIter { self.items.iter() }
}

impl<'a, D: QueryData, F: QueryFilter> IntoIterator
	for &'a mut QueryOnce<D, F>
{
	type Item = &'a mut D::Item<'static, 'static>;
	type IntoIter = std::slice::IterMut<'a, D::Item<'static, 'static>>;

	fn into_iter(self) -> Self::IntoIter { self.items.iter_mut() }
}

#[ext(name=IntoWorldMutExt)]
/// Matcher extensions for `bevy::World`
pub impl<W: IntoWorld> W {
	fn component_names(&self, entity: Entity) -> Vec<String> {
		let world = self.into_world();
		world
			.inspect_entity(entity)
			.map(|ent| {
				ent.map(|comp| self.pretty_name(comp)).collect::<Vec<_>>()
			})
			.unwrap_or_default()
	}
	fn direct_component_names_related<R: RelationshipTarget>(
		&self,
		entity: Entity,
	) -> Vec<Vec<String>> {
		let world = self.into_world();
		world
			.entity(entity)
			.get::<R>()
			.map(|related| {
				related
					.iter()
					.filter_map(|entity| world.inspect_entity(entity).ok())
					.map(|component_iter| {
						component_iter
							.map(|component| self.pretty_name(component))
							.collect::<Vec<_>>()
					})
					.collect::<Vec<_>>()
			})
			.unwrap_or_default()
	}

	/// Try to get the short name of a component, otherwise return the full name.
	fn pretty_name(&self, component: &ComponentInfo) -> String {
		let id = component.type_id();
		if let Some(id) = id {
			if let Some(type_registry) =
				self.into_world().get_resource::<AppTypeRegistry>()
			{
				if let Some(info) = type_registry.read().get_type_info(id) {
					return info.ty().short_path().to_string();
				}
			}
		}
		component.name().to_string()
	}


	fn log_component_names(&self, entity: Entity) {
		let names = self.component_names_related::<Children>(entity);
		let str = names.iter_to_string_indented();
		println!("Component names for {entity}: \n{str}");
		// bevy::log::info!("Component names for {entity}: \n{str}");
	}

	fn component_names_related<R: RelationshipTarget>(
		&self,
		entity: Entity,
	) -> Tree<Vec<String>> {
		fn recurse<'a, R: RelationshipTarget>(
			world: &'a World,
			entity: Entity,
			visited: &mut std::collections::HashSet<Entity>,
		) -> Tree<Vec<String>> {
			if !visited.insert(entity) {
				return Tree::default(); // Prevent cycles
			}
			// Inspect the entity itself
			let value = world
				.inspect_entity(entity)
				.map(|component_iter| {
					component_iter
						.map(|component| world.pretty_name(component))
						.collect::<Vec<_>>()
				})
				.unwrap_or_default();
			// Recurse into related entities
			let children = world
				.entity(entity)
				.get::<R>()
				.map(|related| {
					related
						.iter()
						.map(|related_entity| {
							recurse::<R>(world, related_entity, visited)
						})
						.collect::<Vec<_>>()
				})
				.unwrap_or_default();
			Tree::new_with_children(value, children)
		}
		recurse::<R>(self.into_world(), entity, &mut default())
	}



	/// Shorthand for creating a query and immediatly collecting it into a Vec.
	/// This is less efficient than caching the [`QueryState`] so should only be
	/// used for one-off queries, otherwise [`World::query`] should be preferred.
	fn query_once<D: QueryData>(&mut self) -> QueryOnce<D, ()> {
		QueryOnce::new(self)
	}

	/// Shorthand for creating a query and immediatly collecting it into a Vec.
	/// This is less efficient than caching the [`QueryState`] so should only be
	/// used for one-off queries, otherwise [`World::query_filtered`] should be preferred.
	fn query_filtered_once<D: QueryData, F: QueryFilter>(
		&mut self,
	) -> QueryOnce<D, F> {
		QueryOnce::new(self)
	}

	fn all_entities(&mut self) -> Vec<Entity> {
		let world = self.into_world_mut();
		world.query::<Entity>().iter(world).collect()
	}

	/// Shorthand for removing all components of a given type.
	fn remove<C: Component>(&mut self) -> Vec<C> {
		let world = self.into_world_mut();
		world
			.query_filtered::<Entity, With<C>>()
			.iter(world)
			.collect::<Vec<_>>()
			.into_iter()
			.filter_map(|entity| world.entity_mut(entity).take::<C>())
			.collect()
	}

	/// Shorthand for building a serialized scene from the current world.
	#[cfg(feature = "bevy_scene")]
	fn build_scene(&mut self) -> String {
		self.build_scene_with_builder(|builder| {
			builder.deny_resource::<Time<Real>>()
		})
	}
	/// Shorthand for building a serialized scene from the current world.
	#[cfg(feature = "bevy_scene")]
	fn build_scene_with_builder(
		&mut self,
		func: impl FnOnce(DynamicSceneBuilder) -> DynamicSceneBuilder,
	) -> String {
		let all_entities = self.all_entities();
		let world = self.into_world();
		let dyn_scene = func(DynamicSceneBuilder::from_world(world))
			.extract_entities(all_entities.into_iter())
			.extract_resources()
			.build();


		self.build_scene_with(dyn_scene)
	}

	#[cfg(feature = "bevy_scene")]
	fn build_scene_with(&self, scene: DynamicScene) -> String {
		use bevy::scene::serde::SceneSerializer;
		use ron;

		let world = self.into_world();
		let type_registry = world.resource::<AppTypeRegistry>();
		let type_registry = type_registry.read();
		let scene_serializer = SceneSerializer::new(&scene, &type_registry);
		let pretty_config = ron::ser::PrettyConfig::default()
			.indentor("  ".to_string())
			.new_line("\n".to_string());
		let scene =
			ron::ser::to_string_pretty(&scene_serializer, pretty_config)
				.expect("failed to serialize scene");
		scene
	}
	#[cfg(feature = "bevy_scene")]
	fn load_scene(&mut self, scene: impl AsRef<str>) -> Result {
		self.load_scene_with(scene, &mut Default::default())
	}
	#[cfg(feature = "bevy_scene")]
	fn load_scene_with(
		&mut self,
		scene: impl AsRef<str>,
		entity_map: &mut bevy::ecs::entity::EntityHashMap<Entity>,
	) -> Result {
		let scene = scene.as_ref();
		let world = self.into_world_mut();
		let scene = {
			use serde::de::DeserializeSeed;
			let type_registry = world.resource::<AppTypeRegistry>();
			let mut deserializer = ron::de::Deserializer::from_str(scene)?;
			let scene_deserializer = bevy::scene::serde::SceneDeserializer {
				type_registry: &type_registry.read(),
			};

			scene_deserializer
				.deserialize(&mut deserializer)
				.map_err(|e| deserializer.span_error(e))
		}?;
		scene.write_to_world(world, entity_map)?;

		Ok(())
	}


	/// copied from world.trigger_ref_with_caller
	#[track_caller]
	fn trigger_ref_with_caller_pub<'a, E: Event>(
		&mut self,
		event: &mut E,
		trigger: &mut E::Trigger<'a>,
		caller: MaybeLocation,
	) {
		let world = self.into_world_mut();
		let event_key = world.register_event_key::<E>();
		// SAFETY: event_key was just registered and matches `event`
		unsafe {
			DeferredWorld::from(world)
				.trigger_raw(event_key, event, trigger, caller);
		}
	}
}



/// Ease-of-use extensions for `bevy::World`
#[ext(name=CoreWorldExt)]
pub impl World {
	fn with_observer<E: Event, B: Bundle, M>(
		mut self,
		system: impl IntoObserverSystem<E, B, M>,
	) -> Self {
		self.spawn(Observer::new(system));
		self
	}
	fn observing<E: Event, B: Bundle, M>(
		&mut self,
		system: impl IntoObserverSystem<E, B, M>,
	) -> &mut Self {
		self.spawn(Observer::new(system));
		self
	}

	// TODO deprecated, bevy 0.16 fixes this
	fn flush_trigger<'a, E: Event<Trigger<'a>: Default>>(
		&mut self,
		event: E,
	) -> &mut Self {
		self.flush();
		self.trigger(event);
		self.flush();
		self
	}
}

#[extend::ext]
pub impl<'w> EntityWorldMut<'w> {
	/// 1. Flushes
	/// 2. Triggers the given event for this entity, which will run any observers watching for it.
	/// 3. Flushes
	// #[deprecated = "world flushes automatically now"]
	fn flush_trigger<'a, E: Event<Trigger<'a>: Default>>(
		&mut self,
		event: E,
	) -> &mut Self {
		// let entity = self.id();
		unsafe {
			let world = self.world_mut();
			world.flush();
			world.trigger(event);
			world.flush();
		}
		self
	}
}


#[cfg(test)]
#[cfg(feature = "bevy_scene")]
mod test {
	use crate::prelude::*;

	#[test]
	fn serializes() {
		let mut app = App::new();
		app.add_plugins(MinimalPlugins);
		app.init();
		app.update();
		app.world_mut().build_scene().xpect_contains("Time");
	}
}