bevy/crates/bevy_scene/src/scene_loader.rs
Zhixing Zhang 2aaaed7f69
Make bevy_render an optional dependency of bevy_scene (#8136)
# Objective

bevy-scene does not have a reason to depend on bevy-render except to
include the `Visibility` and `ComputedVisibility` components. Including
that in the dependency chain is unnecessary for people not using
`bevy_render`.

Also fixed a problem where compilation fails when the `serialize`
feature was not enabled.

## Solution

This was added in #5335 to address some of the problems caused by #5310.

Imo the user just always have to remember to include `VisibilityBundle`
when they spawn `SceneBundle` or `DynamicSceneBundle`, but that will be
a breaking change. This PR makes `bevy_render` an optional dependency of
`bevy_scene` instead to respect the existing behavior.
2023-04-03 21:23:26 +00:00

59 lines
1.7 KiB
Rust

#[cfg(feature = "serialize")]
use crate::serde::SceneDeserializer;
use anyhow::{anyhow, Result};
use bevy_app::AppTypeRegistry;
use bevy_asset::{AssetLoader, LoadContext, LoadedAsset};
use bevy_ecs::world::{FromWorld, World};
use bevy_reflect::TypeRegistryArc;
use bevy_utils::BoxedFuture;
#[cfg(feature = "serialize")]
use serde::de::DeserializeSeed;
#[derive(Debug)]
pub struct SceneLoader {
type_registry: TypeRegistryArc,
}
impl FromWorld for SceneLoader {
fn from_world(world: &mut World) -> Self {
let type_registry = world.resource::<AppTypeRegistry>();
SceneLoader {
type_registry: type_registry.0.clone(),
}
}
}
#[cfg(feature = "serialize")]
impl AssetLoader for SceneLoader {
fn load<'a>(
&'a self,
bytes: &'a [u8],
load_context: &'a mut LoadContext,
) -> BoxedFuture<'a, Result<()>> {
Box::pin(async move {
let mut deserializer = ron::de::Deserializer::from_bytes(bytes)?;
let scene_deserializer = SceneDeserializer {
type_registry: &self.type_registry.read(),
};
let scene = scene_deserializer
.deserialize(&mut deserializer)
.map_err(|e| {
let span_error = deserializer.span_error(e);
anyhow!(
"{} at {}:{}",
span_error.code,
load_context.path().to_string_lossy(),
span_error.position,
)
})?;
load_context.set_default_asset(LoadedAsset::new(scene));
Ok(())
})
}
fn extensions(&self) -> &[&str] {
&["scn", "scn.ron"]
}
}