use bevy::platform::collections::{HashMap, HashSet};
use bevy::prelude::*;
use bevy::reflect::serde::{TypedReflectDeserializer, TypedReflectSerializer};
use bevy::reflect::TypeRegistryArc;
use serde::de::DeserializeSeed;
use crate::stage::manager::{StageId, StageManager, StageRoot, StageStatus};
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Reflect)]
#[reflect(Component)]
pub struct StageNodeId(pub u32);
#[derive(Component)]
pub struct Restored;
#[derive(Resource, Default)]
pub struct PersistedComponents {
types: Vec<String>,
}
impl PersistedComponents {
pub fn register<T: Component + Reflect + bevy::reflect::TypePath>(&mut self) {
let path = T::type_path().to_string();
if !self.types.contains(&path) {
self.types.push(path);
}
}
pub fn iter(&self) -> impl Iterator<Item = &String> {
self.types.iter()
}
}
#[derive(Debug, Clone, Default)]
pub struct StageDelta {
present: HashSet<StageNodeId>,
components: HashMap<StageNodeId, Vec<(String, String)>>,
}
impl StageDelta {
pub fn is_present(&self, node: StageNodeId) -> bool {
self.present.contains(&node)
}
pub fn len(&self) -> usize {
self.components.len()
}
pub fn is_empty(&self) -> bool {
self.components.is_empty() && self.present.is_empty()
}
}
#[derive(Resource, Debug, Default)]
pub struct StageDeltas {
levels: HashMap<String, StageDelta>,
}
impl StageDeltas {
pub fn get(&self, path: &str) -> Option<&StageDelta> {
self.levels.get(path)
}
pub fn clear(&mut self, path: &str) {
self.levels.remove(path);
}
pub fn clear_all(&mut self) {
self.levels.clear();
}
pub fn is_empty(&self) -> bool {
self.levels.is_empty()
}
}
pub fn capture_unloading_stages(world: &mut World) {
let pending: Vec<StageId> = world.resource::<StageManager>().pending_unloads().to_vec();
if pending.is_empty() {
return;
}
let roots: Vec<(String, Entity)> = pending
.iter()
.filter_map(|id| {
let entity = world.resource::<StageManager>().entity(*id)?;
let path = world.get::<StageRoot>(entity)?.path.clone();
Some((path, entity))
})
.collect();
let registry = world.resource::<AppTypeRegistry>().clone();
let type_paths: Vec<String> = world
.resource::<PersistedComponents>()
.iter()
.cloned()
.collect();
let mut captured: Vec<(String, StageDelta)> = Vec::new();
for (path, root) in roots {
let nodes = collect_nodes(world, root);
captured.push((path, snapshot(world, ®istry, &type_paths, &nodes)));
}
let mut deltas = world.resource_mut::<StageDeltas>();
for (path, delta) in captured {
deltas.levels.insert(path, delta);
}
}
pub fn restore_spawned_stages(world: &mut World) {
let pending: Vec<(Entity, String)> = {
let mut query = world.query_filtered::<(Entity, &StageRoot), Without<Restored>>();
query
.iter(world)
.filter(|(_, root)| matches!(root.status, StageStatus::Ready))
.map(|(entity, root)| (entity, root.path.clone()))
.collect()
};
if pending.is_empty() {
return;
}
let registry = world.resource::<AppTypeRegistry>().clone();
for (root, path) in pending {
world.entity_mut(root).insert(Restored);
let Some(delta) = world.resource::<StageDeltas>().levels.get(&path).cloned() else {
continue;
};
let nodes = collect_nodes(world, root);
apply(world, ®istry, &delta, &nodes);
}
}
fn collect_nodes(world: &mut World, root: Entity) -> Vec<(Entity, StageNodeId)> {
let mut found = Vec::new();
let mut stack = vec![root];
while let Some(entity) = stack.pop() {
if let Some(id) = world.get::<StageNodeId>(entity) {
found.push((entity, *id));
}
if let Some(children) = world.get::<Children>(entity) {
stack.extend(children.iter());
}
}
found
}
fn snapshot(
world: &World,
registry: &TypeRegistryArc,
type_paths: &[String],
nodes: &[(Entity, StageNodeId)],
) -> StageDelta {
let types = registry.read();
let mut delta = StageDelta::default();
for (entity, node) in nodes {
delta.present.insert(*node);
let entity_ref = world.entity(*entity);
let mut values = Vec::new();
for type_path in type_paths {
let Some(registration) = types.get_with_type_path(type_path) else {
continue;
};
let Some(reflect_component) = registration.data::<ReflectComponent>() else {
continue;
};
let Some(value) = reflect_component.reflect(entity_ref) else {
continue;
};
match ron::ser::to_string(&TypedReflectSerializer::new(
value.as_partial_reflect(),
&types,
)) {
Ok(text) => values.push((type_path.clone(), text)),
Err(error) => warn!("bevy_stage: could not remember `{type_path}`: {error}"),
}
}
if !values.is_empty() {
delta.components.insert(*node, values);
}
}
delta
}
fn apply(
world: &mut World,
registry: &TypeRegistryArc,
delta: &StageDelta,
nodes: &[(Entity, StageNodeId)],
) {
let types = registry.read();
for (entity, node) in nodes {
if !delta.present.contains(node) {
world.entity_mut(*entity).despawn();
continue;
}
let Some(values) = delta.components.get(node) else {
continue;
};
for (type_path, text) in values {
let Some(registration) = types.get_with_type_path(type_path) else {
continue;
};
let Some(reflect_component) = registration.data::<ReflectComponent>() else {
continue;
};
let Ok(mut deserializer) = ron::Deserializer::from_str(text) else {
continue;
};
match TypedReflectDeserializer::new(registration, &types).deserialize(&mut deserializer)
{
Ok(value) => {
let mut entity_mut = world.entity_mut(*entity);
reflect_component.insert(&mut entity_mut, value.as_partial_reflect(), &types);
}
Err(error) => warn!("bevy_stage: could not restore `{type_path}`: {error}"),
}
}
}
}