Skip to content

Commit

Permalink
Merge pull request #164 from yarn-slinger/bevy-12
Browse files Browse the repository at this point in the history
Update to Bevy 0.12
  • Loading branch information
janhohenheim authored Jan 23, 2024
2 parents 6d25427 + 4fc7875 commit fd89180
Show file tree
Hide file tree
Showing 38 changed files with 1,416 additions and 1,179 deletions.
1,851 changes: 1,023 additions & 828 deletions Cargo.lock

Large diffs are not rendered by default.

20 changes: 15 additions & 5 deletions crates/bevy_plugin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,38 @@ audio_assets = ["bevy/bevy_audio", "bevy/vorbis"]
[dependencies]
anyhow = "1"
csv = "1"
seldom_fn_plugin = "0.4"
seldom_fn_plugin = "0.5"
serde = { version = "1", features = ["derive"] }
yarn_slinger = { path = "../yarn_slinger", features = ["bevy", "serde"] }
sha2 = "0.10"
rand = { version = "0.8", features = ["small_rng"] }

[dependencies.bevy]
version = "0.11"

[target.'cfg(any(target_arch = "wasm32", target_os = "android"))'.dependencies.bevy]
version = "0.12"
default-features = false
features = ["bevy_asset", "serialize"]

[dev-dependencies]
tempfile = "3"

[dev-dependencies.bevy]
version = "0.11"
version = "0.12"
default-features = false
features = [
"bevy_core_pipeline",
"bevy_render",
"bevy_winit",
"filesystem_watcher",
"file_watcher",
"x11",
"bevy_audio",
"multi-threaded",
]

[target.'cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))'.dependencies.bevy]
version = "0.12"
default-features = false
features = ["bevy_asset", "serialize", "file_watcher",]

[target.'cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))'.dependencies]
glob = "0.3.1"
4 changes: 1 addition & 3 deletions crates/bevy_plugin/src/commands/command_registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,9 @@ mod tests {

#[test]
fn executes_task() {
AsyncComputeTaskPool::init(TaskPool::new);

let mut methods = YarnCommands::default();
methods.add_command("test", |_: In<()>| -> Task<()> {
let thread_pool = AsyncComputeTaskPool::get();
let thread_pool = AsyncComputeTaskPool::get_or_init(TaskPool::new);
thread_pool.spawn(async move { sleep(Duration::from_millis(500)) })
});
let method = methods.get_mut("test").unwrap();
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_plugin/src/commands/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn clone_events(
reader: &mut ManualEventReader<ExecuteCommandEvent>,
) -> Vec<ExecuteCommandEvent> {
let events = world.resource::<Events<ExecuteCommandEvent>>();
reader.iter(events).cloned().collect()
reader.read(events).cloned().collect()
}

fn clone_command(
Expand Down
19 changes: 13 additions & 6 deletions crates/bevy_plugin/src/dialogue_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::line_provider::LineAssets;
use crate::prelude::*;
use crate::UnderlyingYarnLine;
use anyhow::{anyhow, bail};
use bevy::asset::LoadedUntypedAsset;
use bevy::utils::HashSet;
use bevy::{prelude::*, utils::HashMap};
pub(crate) use runtime_interaction::DialogueExecutionSystemSet;
Expand Down Expand Up @@ -61,7 +62,7 @@ impl DialogueRunner {
///
/// Note that the actual advancement of the dialogue will be postponed until the following conditions are met:
/// - The text provider has finished loading its lines, indicated by [`TextProvider::are_lines_available`](yarn_slinger::prelude::TextProvider::are_lines_available) returning `true`.
/// - The asset providers have finished loading their assets, indicated by all [`AssetProvider::are_assets_available`] calls returning `true`.
/// - The asset providers have finished loading their assets, indicated by all [`AssetProvider::update_asset_availability`] calls returning `true`.
/// - All previously called [`YarnCommand`]s are finished, indicated by their return type's [`TaskFinishedIndicator::is_finished`] returning `true`.
pub fn continue_in_next_update(&mut self) -> &mut Self {
if !self.is_running {
Expand Down Expand Up @@ -201,8 +202,11 @@ impl DialogueRunner {

/// Returns whether both the text and asset providers have loaded all their lines.
#[must_use]
pub fn are_lines_available(&self) -> bool {
self.are_texts_available() && self.are_assets_available()
pub fn update_line_availability(
&mut self,
loaded_untyped_assets: &Assets<LoadedUntypedAsset>,
) -> bool {
self.are_texts_available() && self.update_asset_availability(loaded_untyped_assets)
}

/// Returns whether the text provider has loaded all its lines.
Expand All @@ -214,10 +218,13 @@ impl DialogueRunner {
/// Returns whether all asset providers have loaded all their assets.
/// If no asset providers where added via [`DialogueRunnerBuilder::add_asset_provider`], this will always return `true`.
#[must_use]
fn are_assets_available(&self) -> bool {
fn update_asset_availability(
&mut self,
loaded_untyped_assets: &Assets<LoadedUntypedAsset>,
) -> bool {
self.asset_providers
.values()
.all(|provider| provider.are_assets_available())
.values_mut()
.all(|provider| provider.update_asset_availability(loaded_untyped_assets))
}

/// Sets the language of both the text and asset providers. Same as calling [`DialogueRunner::set_text_language`] and [`DialogueRunner::set_asset_language`].
Expand Down
6 changes: 4 additions & 2 deletions crates/bevy_plugin/src/dialogue_runner/runtime_interaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::events::*;
use crate::line_provider::LineProviderSystemSet;
use crate::prelude::*;
use anyhow::bail;
use bevy::asset::LoadedUntypedAsset;
use bevy::prelude::*;
use bevy::utils::HashMap;

Expand Down Expand Up @@ -38,6 +39,7 @@ fn continue_runtime(
mut dialogue_complete_events: EventWriter<DialogueCompleteEvent>,
mut dialogue_start_events: EventWriter<DialogueStartEvent>,
mut last_options: Local<HashMap<Entity, Vec<DialogueOption>>>,
loaded_untyped_assets: Res<Assets<LoadedUntypedAsset>>,
project: Res<YarnProject>,
) -> SystemResult {
for (source, mut dialogue_runner) in dialogue_runners.iter_mut() {
Expand All @@ -58,7 +60,7 @@ fn continue_runtime(

if !(dialogue_runner.will_continue_in_next_update
&& dialogue_runner.poll_tasks_and_check_if_done()
&& dialogue_runner.are_lines_available())
&& dialogue_runner.update_line_availability(&loaded_untyped_assets))
{
continue;
}
Expand Down Expand Up @@ -146,7 +148,7 @@ fn accept_line_hints(
mut events: EventReader<LineHintsEvent>,
mut dialogue_runners: Query<&mut DialogueRunner>,
) {
for event in events.iter() {
for event in events.read() {
let mut dialogue_runner = dialogue_runners.get_mut(event.source).unwrap();
for asset_provider in dialogue_runner.asset_providers.values_mut() {
asset_provider.accept_line_hints(&event.line_ids);
Expand Down
7 changes: 1 addition & 6 deletions crates/bevy_plugin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,14 @@
//!
//! ```no_run
//! // src/main.rs
//! use bevy::{prelude::*, asset::ChangeWatcher, utils::Duration};
//! use bevy::{prelude::*, utils::Duration};
//! use bevy_yarn_slinger::prelude::*;
//! // Use the example dialogue view to see the dialogue in action. Requires the `bevy_yarn_slinger_example_dialogue_view` crate.
//! // use bevy_yarn_slinger_example_dialogue_view::prelude::*;
//!
//! fn main() {
//! let mut app = App::new();
//! app.add_plugins((
//! DefaultPlugins.set(AssetPlugin {
//! // Activate hot reloading
//! watch_for_changes: ChangeWatcher::with_delay(Duration::from_millis(200)),
//! ..default()
//! }),
//! // Add the Yarn Slinger plugin.
//! // As soon as this plugin is built, a Yarn project will be compiled
//! // from all Yarn files found under assets/dialog/*.yarn
Expand Down
47 changes: 27 additions & 20 deletions crates/bevy_plugin/src/line_provider/asset_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use crate::prelude::*;
use crate::UnderlyingYarnLine;
#[cfg(feature = "audio_assets")]
pub use audio_asset_provider_plugin::AudioAssetProvider;
use bevy::asset::Asset;
use bevy::asset::{Asset, LoadedUntypedAsset};
use bevy::prelude::*;
use bevy::utils::{HashMap, Uuid};
use bevy::utils::HashMap;
pub use file_extension_asset_provider_plugin::{file_extensions, FileExtensionAssetProvider};
use std::any::Any;
use std::fmt::Debug;
Expand All @@ -27,9 +27,11 @@ pub trait AssetProvider: Debug + Send + Sync {
/// Returns the type as a [`dyn Any`]. Used for polymorphism. Should be implemented like this:
/// ```
/// # use std::any::Any;
/// # use bevy::asset::AssetServer;
/// # use bevy::asset::LoadedUntypedAsset;
/// # use bevy::prelude::*;
/// # use bevy_yarn_slinger::prelude::*;
/// # use bevy_yarn_slinger::UnderlyingYarnLine;
///
/// # #[derive(Debug)]
/// # struct Foo;
/// # impl AssetProvider for Foo {
Expand Down Expand Up @@ -57,7 +59,7 @@ pub trait AssetProvider: Debug + Send + Sync {
/// # unreachable!()
/// # }
/// #
/// # fn are_assets_available(&self) -> bool {
/// # fn update_asset_availability(&mut self, loaded_untyped_assets: &Assets<LoadedUntypedAsset>) -> bool {
/// # unreachable!()
/// # }
/// #
Expand All @@ -75,7 +77,8 @@ pub trait AssetProvider: Debug + Send + Sync {
/// Returns the type as a mutable [`dyn Any`]. Used for polymorphism. Should be implemented like this:
/// ```
/// # use std::any::Any;
/// # use bevy::asset::AssetServer;
/// # use bevy::asset::LoadedUntypedAsset;
/// # use bevy::prelude::*;
/// # use bevy_yarn_slinger::prelude::*;
/// # use bevy_yarn_slinger::UnderlyingYarnLine;
/// # #[derive(Debug)]
Expand Down Expand Up @@ -105,7 +108,7 @@ pub trait AssetProvider: Debug + Send + Sync {
/// # unreachable!()
/// # }
/// #
/// # fn are_assets_available(&self) -> bool {
/// # fn update_asset_availability(&mut self, loaded_untyped_assets: &Assets<LoadedUntypedAsset>) -> bool {
/// # unreachable!()
/// # }
/// #
Expand Down Expand Up @@ -134,27 +137,31 @@ pub trait AssetProvider: Debug + Send + Sync {
fn set_asset_server(&mut self, asset_server: AssetServer);

/// Returns whether the assets for all lines announced by [`AssetProvider::accept_line_hints`] are available, i.e. have been loaded and are ready to be used.
fn are_assets_available(&self) -> bool;
/// This method is allowed to process already loaded assets to make them ready for delivery.
fn update_asset_availability(
&mut self,
loaded_untyped_assets: &Assets<LoadedUntypedAsset>,
) -> bool;

/// Passes the [`LineId`]s that this [`AssetProvider`] should soon provide assets for. These are the [`LineId`]s that are contained in the current node and are not required to be actually reached.
fn accept_line_hints(&mut self, line_ids: &[LineId]);

/// Returns the [`LineAssets`] for the given [`UnderlyingYarnLine`]. Will only be called if [`AssetProvider::are_assets_available`] returns `true`,
/// Returns the [`LineAssets`] for the given [`UnderlyingYarnLine`]. Will only be called if [`AssetProvider::update_asset_availability`] returns `true`,
/// so an implementor is expected to panic if the assets are not available.
fn get_assets(&self, line: &UnderlyingYarnLine) -> LineAssets;
}

/// Assets that were provided by one or more [`AssetProvider`]s. Stores them in the form of [`Handle`]s.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LineAssets(HashMap<Uuid, HandleUntyped>);
pub struct LineAssets(HashMap<&'static str, UntypedHandle>);
impl LineAssets {
/// Creates a new empty [`LineAssets`] struct.
pub fn new() -> Self {
Self(HashMap::new())
}

/// Creates a new [`LineAssets`] struct from an iterator of untyped [`Handle`]s and the [`Uuid`] of the [`Asset`] they reference.
pub fn with_assets(handles: impl IntoIterator<Item = (Uuid, HandleUntyped)>) -> Self {
/// Creates a new [`LineAssets`] struct from an iterator of untyped [`Handle`]s and the [`TypePath::type_path`] of the [`Asset`] they reference.
pub fn with_assets(handles: impl IntoIterator<Item = (&'static str, UntypedHandle)>) -> Self {
Self(handles.into_iter().collect())
}

Expand All @@ -164,7 +171,7 @@ impl LineAssets {
T: Asset,
{
self.0.iter().find_map(|(type_id, handle)| {
(T::TYPE_UUID == *type_id).then(|| handle.clone().typed())
(T::type_path() == *type_id).then(|| handle.clone().typed())
})
}

Expand All @@ -179,15 +186,15 @@ impl LineAssets {
}
}

impl From<HashMap<Uuid, HandleUntyped>> for LineAssets {
fn from(h: HashMap<Uuid, HandleUntyped>) -> Self {
impl From<HashMap<&'static str, UntypedHandle>> for LineAssets {
fn from(h: HashMap<&'static str, UntypedHandle>) -> Self {
Self(h)
}
}

impl IntoIterator for LineAssets {
type Item = <HashMap<Uuid, HandleUntyped> as IntoIterator>::Item;
type IntoIter = <HashMap<Uuid, HandleUntyped> as IntoIterator>::IntoIter;
type Item = <HashMap<&'static str, UntypedHandle> as IntoIterator>::Item;
type IntoIter = <HashMap<&'static str, UntypedHandle> as IntoIterator>::IntoIter;

fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
Expand All @@ -203,14 +210,14 @@ impl Extend<LineAssets> for LineAssets {
}
}

impl Extend<(Uuid, HandleUntyped)> for LineAssets {
fn extend<T: IntoIterator<Item = (Uuid, HandleUntyped)>>(&mut self, iter: T) {
impl Extend<(&'static str, UntypedHandle)> for LineAssets {
fn extend<T: IntoIterator<Item = (&'static str, UntypedHandle)>>(&mut self, iter: T) {
self.0.extend(iter)
}
}

impl FromIterator<(Uuid, HandleUntyped)> for LineAssets {
fn from_iter<T: IntoIterator<Item = (Uuid, HandleUntyped)>>(iter: T) -> Self {
impl FromIterator<(&'static str, UntypedHandle)> for LineAssets {
fn from_iter<T: IntoIterator<Item = (&'static str, UntypedHandle)>>(iter: T) -> Self {
Self(HashMap::from_iter(iter))
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::default_impl::file_extensions;
use crate::prelude::*;
use bevy::asset::LoadedUntypedAsset;
use bevy::prelude::*;
use std::any::Any;
use std::fmt::Debug;
Expand All @@ -19,7 +19,7 @@ pub struct AudioAssetProvider(FileExtensionAssetProvider);
impl Default for AudioAssetProvider {
fn default() -> Self {
Self(
FileExtensionAssetProvider::new().with_file_extensions(file_extensions! {
FileExtensionAssetProvider::new().with_file_extensions(crate::file_extensions! {
AudioSource: ["mp3", "ogg", "wav"],
}),
)
Expand Down Expand Up @@ -58,8 +58,11 @@ impl AssetProvider for AudioAssetProvider {
self.0.set_asset_server(asset_server)
}

fn are_assets_available(&self) -> bool {
self.0.are_assets_available()
fn update_asset_availability(
&mut self,
loaded_untyped_assets: &Assets<LoadedUntypedAsset>,
) -> bool {
self.0.update_asset_availability(loaded_untyped_assets)
}

fn accept_line_hints(&mut self, line_ids: &[LineId]) {
Expand Down
Loading

0 comments on commit fd89180

Please sign in to comment.