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 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
mod dynamic_asset_systems;
mod systems;
/// Configuration of loading states
pub mod config;
use bevy::app::{App, Plugin};
use bevy::asset::{Asset, UntypedHandle};
use bevy::ecs::{
schedule::{
common_conditions::in_state, InternedScheduleLabel, IntoSystemConfigs,
IntoSystemSetConfigs, NextState, OnEnter, ScheduleLabel, State, States, SystemSet,
},
system::Resource,
world::FromWorld,
};
use bevy::prelude::{StateTransition, Update};
use bevy::utils::{default, HashMap, HashSet};
use std::any::TypeId;
use std::marker::PhantomData;
use crate::asset_collection::AssetCollection;
use crate::dynamic_asset::{DynamicAssetCollection, DynamicAssetCollections};
use config::{ConfigureLoadingState, LoadingStateConfig};
use dynamic_asset_systems::{
check_dynamic_asset_collections, load_dynamic_asset_collections,
resume_to_loading_asset_collections,
};
use systems::{
check_loading_collection, finish_loading_state, init_resource, initialize_loading_state,
reset_loading_state, resume_to_finalize, start_loading_collection,
};
#[cfg(feature = "standard_dynamic_assets")]
use bevy_common_assets::ron::RonAssetPlugin;
#[cfg(feature = "standard_dynamic_assets")]
use crate::standard_dynamic_asset::{StandardDynamicAsset, StandardDynamicAssetCollection};
#[cfg(feature = "progress_tracking")]
use iyes_progress::TrackedProgressSet;
use crate::dynamic_asset::{DynamicAsset, DynamicAssets};
use crate::loading_state::systems::{apply_internal_state_transition, run_loading_state};
/// A Bevy plugin to configure automatic asset loading
///
/// ```edition2021
/// # use bevy_asset_loader::prelude::*;
/// # use bevy::prelude::*;
/// # use bevy::asset::AssetPlugin;
///
/// fn main() {
/// App::new()
/// .init_state::<GameState>()
/// .add_plugins((MinimalPlugins, AssetPlugin::default()))
/// # .init_resource::<iyes_progress::ProgressCounter>()
/// .add_loading_state(LoadingState::new(GameState::Loading)
/// .continue_to_state(GameState::Menu)
/// .load_collection::<AudioAssets>()
/// .load_collection::<ImageAssets>()
/// )
/// .add_systems(OnEnter(GameState::Menu), play_audio)
/// # .set_runner(|mut app| app.update())
/// .run();
/// }
///
/// fn play_audio(mut commands: Commands, audio_assets: Res<AudioAssets>) {
/// commands.spawn(AudioBundle {
/// source: audio_assets.background.clone(),
/// ..default()
/// });
/// }
///
/// #[derive(Clone, Eq, PartialEq, Debug, Hash, Default, States)]
/// enum GameState {
/// #[default]
/// Loading,
/// Menu
/// }
///
/// #[derive(AssetCollection, Resource)]
/// pub struct AudioAssets {
/// #[asset(path = "audio/background.ogg")]
/// pub background: Handle<AudioSource>,
/// }
///
/// #[derive(AssetCollection, Resource)]
/// pub struct ImageAssets {
/// #[asset(path = "images/player.png")]
/// pub player: Handle<Image>,
/// #[asset(path = "images/tree.png")]
/// pub tree: Handle<Image>,
/// }
/// ```
pub struct LoadingState<State: States> {
next_state: Option<State>,
failure_state: Option<State>,
loading_state: State,
dynamic_assets: HashMap<String, Box<dyn DynamicAsset>>,
#[cfg(feature = "standard_dynamic_assets")]
standard_dynamic_asset_collection_file_endings: Vec<&'static str>,
config: LoadingStateConfig<State>,
}
impl<S> LoadingState<S>
where
S: States,
{
/// Create a new [`LoadingState`]
///
/// This function takes a [`State`] during which all asset collections will
/// be loaded and inserted as resources.
/// ```edition2021
/// # use bevy_asset_loader::prelude::*;
/// # use bevy::prelude::*;
/// # use bevy::asset::AssetPlugin;
/// # fn main() {
/// App::new()
/// # .init_state::<GameState>()
/// # .add_plugins((MinimalPlugins, AssetPlugin::default()))
/// # .init_resource::<iyes_progress::ProgressCounter>()
/// .add_loading_state(
/// LoadingState::new(GameState::Loading)
/// .continue_to_state(GameState::Menu)
/// .load_collection::<AudioAssets>()
/// .load_collection::<ImageAssets>()
/// )
/// # .set_runner(|mut app| app.update())
/// # .run();
/// # }
/// # #[derive(Clone, Eq, PartialEq, Debug, Hash, Default, States)]
/// # enum GameState {
/// # #[default]
/// # Loading,
/// # Menu
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct AudioAssets {
/// # #[asset(path = "audio/background.ogg")]
/// # pub background: Handle<AudioSource>,
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct ImageAssets {
/// # #[asset(path = "images/player.png")]
/// # pub player: Handle<Image>,
/// # #[asset(path = "images/tree.png")]
/// # pub tree: Handle<Image>,
/// # }
/// ```
#[must_use]
pub fn new(load: S) -> LoadingState<S> {
Self {
next_state: None,
failure_state: None,
loading_state: load.clone(),
dynamic_assets: HashMap::default(),
#[cfg(feature = "standard_dynamic_assets")]
standard_dynamic_asset_collection_file_endings: vec!["assets.ron"],
config: LoadingStateConfig::new(load),
}
}
/// The [`LoadingState`] will set this Bevy [`State`] after all asset collections
/// are loaded and inserted as resources.
/// ```edition2021
/// # use bevy_asset_loader::prelude::*;
/// # use bevy::prelude::*;
/// # use bevy::asset::AssetPlugin;
/// # fn main() {
/// App::new()
/// # .init_state::<GameState>()
/// # .add_plugins((MinimalPlugins, AssetPlugin::default()))
/// # .init_resource::<iyes_progress::ProgressCounter>()
/// .add_loading_state(
/// LoadingState::new(GameState::Loading)
/// .continue_to_state(GameState::Menu)
/// .load_collection::<AudioAssets>()
/// .load_collection::<ImageAssets>()
/// )
/// # .set_runner(|mut app| app.update())
/// # .run();
/// # }
/// # #[derive(Clone, Eq, PartialEq, Debug, Hash, Default, States)]
/// # enum GameState {
/// # #[default]
/// # Loading,
/// # Menu
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct AudioAssets {
/// # #[asset(path = "audio/background.ogg")]
/// # pub background: Handle<AudioSource>,
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct ImageAssets {
/// # #[asset(path = "images/player.png")]
/// # pub player: Handle<Image>,
/// # #[asset(path = "images/tree.png")]
/// # pub tree: Handle<Image>,
/// # }
/// ```
#[must_use]
pub fn continue_to_state(mut self, next: S) -> Self {
self.next_state = Some(next);
self
}
/// The [`LoadingState`] will set this Bevy [`State`] if an asset fails to load.
/// ```edition2021
/// # use bevy_asset_loader::prelude::*;
/// # use bevy::prelude::*;
/// # use bevy::asset::AssetPlugin;
/// # fn main() {
/// App::new()
/// # .init_state::<GameState>()
/// # .add_plugins((MinimalPlugins, AssetPlugin::default()))
/// # .init_resource::<iyes_progress::ProgressCounter>()
/// .add_loading_state(
/// LoadingState::new(GameState::Loading)
/// .continue_to_state(GameState::Menu)
/// .on_failure_continue_to_state(GameState::Error)
/// .load_collection::<MyAssets>()
/// )
/// # .set_runner(|mut app| app.update())
/// # .run();
/// # }
/// # #[derive(Clone, Eq, PartialEq, Debug, Hash, Default, States)]
/// # enum GameState {
/// # #[default]
/// # Loading,
/// # Error,
/// # Menu
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct MyAssets {
/// # #[asset(path = "audio/background.ogg")]
/// # pub background: Handle<AudioSource>,
/// # }
/// ```
#[must_use]
pub fn on_failure_continue_to_state(mut self, next: S) -> Self {
self.failure_state = Some(next);
self
}
/// Insert a map of asset keys with corresponding standard dynamic assets
#[must_use]
#[cfg(feature = "standard_dynamic_assets")]
#[cfg_attr(docsrs, doc(cfg(feature = "standard_dynamic_assets")))]
pub fn add_standard_dynamic_assets(
mut self,
mut dynamic_assets: HashMap<String, StandardDynamicAsset>,
) -> Self {
dynamic_assets.drain().for_each(|(key, value)| {
self.dynamic_assets.insert(key, Box::new(value));
});
self
}
/// Set all file endings that should be loaded as [`StandardDynamicAssetCollection`].
///
/// The default file ending is `.assets`
#[must_use]
#[cfg_attr(docsrs, doc(cfg(feature = "standard_dynamic_assets")))]
#[cfg(feature = "standard_dynamic_assets")]
pub fn set_standard_dynamic_asset_collection_file_endings(
mut self,
endings: Vec<&'static str>,
) -> Self {
self.standard_dynamic_asset_collection_file_endings = endings;
self
}
/// Finish configuring the [`LoadingState`]
///
/// Calling this function is required to set up the asset loading.
/// Most of the time you do not want to call this method directly though, but complete the setup
/// using [`LoadingStateAppExt::add_loading_state`].
/// ```edition2021
/// # use bevy_asset_loader::prelude::*;
/// # use bevy::prelude::*;
/// # use bevy::asset::AssetPlugin;
/// # fn main() {
/// App::new()
/// # .init_state::<GameState>()
/// # .add_plugins((MinimalPlugins, AssetPlugin::default()))
/// # .init_resource::<iyes_progress::ProgressCounter>()
/// .add_loading_state(
/// LoadingState::new(GameState::Loading)
/// .continue_to_state(GameState::Menu)
/// .load_collection::<AudioAssets>()
/// .load_collection::<ImageAssets>()
/// )
/// # .set_runner(|mut app| app.update())
/// # .run();
/// # }
/// # #[derive(Clone, Eq, PartialEq, Debug, Hash, Default, States)]
/// # enum GameState {
/// # #[default]
/// # Loading,
/// # Menu
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct AudioAssets {
/// # #[asset(path = "audio/background.ogg")]
/// # pub background: Handle<AudioSource>,
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct ImageAssets {
/// # #[asset(path = "images/player.png")]
/// # pub player: Handle<Image>,
/// # #[asset(path = "images/tree.png")]
/// # pub tree: Handle<Image>,
/// # }
/// ```
#[allow(unused_mut)]
pub fn build(mut self, app: &mut App) {
app.init_resource::<AssetLoaderConfiguration<S>>();
{
let mut asset_loader_configuration = app
.world
.get_resource_mut::<AssetLoaderConfiguration<S>>()
.unwrap();
let mut loading_config = asset_loader_configuration
.state_configurations
.remove(&self.loading_state)
.unwrap_or_default();
if self.next_state.is_some() {
loading_config.next = self.next_state;
}
if self.failure_state.is_some() {
loading_config.failure = self.failure_state;
}
asset_loader_configuration
.state_configurations
.insert(self.loading_state.clone(), loading_config);
}
app.init_resource::<State<InternalLoadingState<S>>>();
app.init_resource::<NextState<InternalLoadingState<S>>>();
app.init_resource::<DynamicAssetCollections<S>>();
#[cfg(feature = "standard_dynamic_assets")]
if !app.is_plugin_added::<RonAssetPlugin<StandardDynamicAssetCollection>>() {
app.add_plugins(RonAssetPlugin::<StandardDynamicAssetCollection>::new(
&self.standard_dynamic_asset_collection_file_endings,
));
}
if !app.is_plugin_added::<InternalAssetLoaderPlugin<S>>() {
app.add_plugins(InternalAssetLoaderPlugin::<S>::new());
}
app.init_resource::<LoadingStateSchedules<S>>();
let loading_state_schedule = LoadingStateSchedule(self.loading_state.clone());
let configure_loading_state = app.get_schedule(loading_state_schedule.clone()).is_none();
app.init_schedule(loading_state_schedule.clone())
.init_schedule(OnEnterInternalLoadingState(
self.loading_state.clone(),
InternalLoadingState::LoadingAssets,
))
.init_schedule(OnEnterInternalLoadingState(
self.loading_state.clone(),
InternalLoadingState::LoadingDynamicAssetCollections,
))
.init_schedule(OnEnterInternalLoadingState(
self.loading_state.clone(),
InternalLoadingState::Finalize,
));
if configure_loading_state {
app.add_systems(
loading_state_schedule.clone(),
(
resume_to_loading_asset_collections::<S>
.in_set(InternalLoadingStateSet::ResumeDynamicAssetCollections),
initialize_loading_state::<S>.in_set(InternalLoadingStateSet::Initialize),
resume_to_finalize::<S>.in_set(InternalLoadingStateSet::CheckAssets),
finish_loading_state::<S>.in_set(InternalLoadingStateSet::Finalize),
),
)
.add_systems(
OnEnter(self.loading_state.clone()),
reset_loading_state::<S>,
)
.configure_sets(Update, LoadingStateSet(self.loading_state.clone()));
let mut loading_state_schedule = app.get_schedule_mut(loading_state_schedule).unwrap();
loading_state_schedule
.configure_sets(
InternalLoadingStateSet::Initialize
.run_if(in_state(InternalLoadingState::<S>::Initialize)),
)
.configure_sets(
InternalLoadingStateSet::CheckDynamicAssetCollections.run_if(in_state(
InternalLoadingState::<S>::LoadingDynamicAssetCollections,
)),
)
.configure_sets(
InternalLoadingStateSet::ResumeDynamicAssetCollections
.after(InternalLoadingStateSet::CheckDynamicAssetCollections)
.run_if(in_state(
InternalLoadingState::<S>::LoadingDynamicAssetCollections,
)),
)
.configure_sets(
InternalLoadingStateSet::CheckAssets
.run_if(in_state(InternalLoadingState::<S>::LoadingAssets)),
)
.configure_sets(
InternalLoadingStateSet::Finalize
.run_if(in_state(InternalLoadingState::<S>::Finalize)),
);
#[cfg(feature = "standard_dynamic_assets")]
{
self.config = self
.config
.register_dynamic_asset_collection::<StandardDynamicAssetCollection>();
}
#[cfg(feature = "progress_tracking")]
app.add_systems(
Update,
run_loading_state::<S>
.in_set(TrackedProgressSet)
.in_set(LoadingStateSet(self.loading_state.clone()))
.run_if(in_state(self.loading_state)),
);
#[cfg(not(feature = "progress_tracking"))]
app.add_systems(
Update,
run_loading_state::<S>
.in_set(LoadingStateSet(self.loading_state.clone()))
.run_if(in_state(self.loading_state)),
);
}
app.init_resource::<DynamicAssets>();
let mut dynamic_assets = app.world.get_resource_mut::<DynamicAssets>().unwrap();
for (key, asset) in self.dynamic_assets {
dynamic_assets.register_asset(key, asset);
}
self.config.build(app);
}
}
impl<S: States> ConfigureLoadingState for LoadingState<S> {
fn load_collection<A: AssetCollection>(mut self) -> Self {
self.config = self.config.load_collection::<A>();
self
}
fn init_resource<R: Resource + FromWorld>(mut self) -> Self {
self.config = self.config.init_resource::<R>();
self
}
fn register_dynamic_asset_collection<C: DynamicAssetCollection + Asset>(mut self) -> Self {
self.config = self.config.register_dynamic_asset_collection::<C>();
self
}
fn with_dynamic_assets_file<C: DynamicAssetCollection + Asset>(mut self, file: &str) -> Self {
self.config
.with_dynamic_assets_type_id(file, TypeId::of::<C>());
self
}
}
/// Systems in this set check the loading state of assets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, SystemSet)]
pub struct LoadingStateSet<S: States>(pub S);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, SystemSet)]
pub(crate) enum InternalLoadingStateSet {
Initialize,
CheckDynamicAssetCollections,
ResumeDynamicAssetCollections,
CheckAssets,
Finalize,
}
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct OnEnterInternalLoadingState<S: States>(pub S, pub InternalLoadingState<S>);
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct LoadingStateSchedule<S: States>(pub S);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, States)]
pub(crate) enum InternalLoadingState<S: States> {
/// Starting point. Here it will be decided whether or not dynamic asset collections need to be loaded.
#[default]
Initialize,
/// Load dynamic asset collections and configure their key <-> asset mapping
LoadingDynamicAssetCollections,
/// Load the actual asset collections and check their status every frame.
LoadingAssets,
/// All collections are loaded and inserted. Time to e.g. run custom [insert_resource](bevy_asset_loader::AssetLoader::insert_resource).
Finalize,
/// A 'parking' state in case no next state is defined
Done(PhantomData<S>),
}
/// This resource is used for handles from asset collections and loading dynamic asset collection files.
/// The generic will be the [`AssetCollection`] type for the first and the [`DynamicAssetCollection`] for the second.
#[derive(Resource)]
pub(crate) struct LoadingAssetHandles<T> {
handles: Vec<UntypedHandle>,
marker: PhantomData<T>,
}
impl<T> Default for LoadingAssetHandles<T> {
fn default() -> Self {
LoadingAssetHandles {
handles: Default::default(),
marker: Default::default(),
}
}
}
#[derive(Resource)]
pub(crate) struct AssetLoaderConfiguration<State: States> {
state_configurations: HashMap<State, LoadingConfiguration<State>>,
}
impl<State: States> Default for AssetLoaderConfiguration<State> {
fn default() -> Self {
AssetLoaderConfiguration {
state_configurations: HashMap::default(),
}
}
}
struct LoadingConfiguration<State: States> {
next: Option<State>,
failure: Option<State>,
loading_failed: bool,
loading_collections: usize,
loading_dynamic_collections: HashSet<TypeId>,
}
impl<State: States> Default for LoadingConfiguration<State> {
fn default() -> Self {
LoadingConfiguration {
next: None,
failure: None,
loading_failed: false,
loading_collections: 0,
loading_dynamic_collections: default(),
}
}
}
/// Resource to store the schedules for loading states
#[derive(Resource)]
pub struct LoadingStateSchedules<State: States> {
/// Map to store a schedule per loading state
pub schedules: HashMap<State, InternedScheduleLabel>,
}
impl<State: States> Default for LoadingStateSchedules<State> {
fn default() -> Self {
LoadingStateSchedules {
schedules: HashMap::default(),
}
}
}
/// Extension trait for Bevy Apps to add loading states idiomatically
pub trait LoadingStateAppExt {
/// Add a loading state to your app
fn add_loading_state<S: States>(&mut self, loading_state: LoadingState<S>) -> &mut Self;
/// Configure an existing loading state with, for example, additional asset collections.
fn configure_loading_state<S: States>(
&mut self,
configuration: LoadingStateConfig<S>,
) -> &mut Self;
/// Add an [`AssetCollection`] to the [`LoadingState`]
///
/// The added collection will be loaded and inserted into your Bevy app as a resource.
/// ```edition2021
/// # use bevy_asset_loader::prelude::*;
/// # use bevy::prelude::*;
/// # use bevy::asset::AssetPlugin;
/// # fn main() {
/// App::new()
/// # .init_state::<GameState>()
/// # .add_plugins((MinimalPlugins, AssetPlugin::default()))
/// # .init_resource::<iyes_progress::ProgressCounter>()
/// .add_loading_state(
/// LoadingState::new(GameState::Loading)
/// .continue_to_state(GameState::Menu)
/// .load_collection::<AudioAssets>()
/// .load_collection::<ImageAssets>()
/// )
/// # .set_runner(|mut app| app.update())
/// # .run();
/// # }
/// # #[derive(Clone, Eq, PartialEq, Debug, Hash, Default, States)]
/// # enum GameState {
/// # #[default]
/// # Loading,
/// # Menu
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct AudioAssets {
/// # #[asset(path = "audio/background.ogg")]
/// # pub background: Handle<AudioSource>,
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct ImageAssets {
/// # #[asset(path = "images/player.png")]
/// # pub player: Handle<Image>,
/// # #[asset(path = "images/tree.png")]
/// # pub tree: Handle<Image>,
/// # }
/// ```
#[deprecated(
since = "0.19.0",
note = "Use `LoadingStateConfig::load_collection` or `LoadingState::load_collection` instead."
)]
fn add_collection_to_loading_state<S: States, A: AssetCollection>(
&mut self,
loading_state: S,
) -> &mut Self;
/// Register a new [`DynamicAssetCollection`] to be handled in the loading state
///
/// You do not need to call this for [`StandardDynamicAssetCollection`], only if you want to use
/// your own dynamic asset collection types.
#[deprecated(
since = "0.19.0",
note = "Use `LoadingStateConfig::register_dynamic_asset_collection` or `LoadingState::register_dynamic_asset_collection` instead."
)]
fn register_dynamic_asset_collection<S: States, C: DynamicAssetCollection + Asset>(
&mut self,
loading_state: S,
) -> &mut Self;
/// Register files to be loaded as a certain type of [`DynamicAssetCollection`]
///
/// During the loading state, the given dynamic asset collections will be loaded and their
/// content registered. This will happen before trying to resolve any dynamic assets
/// as part of asset collections.
///
/// You need to register a loader for your asset type yourself.
/// If you want to see some code, take a look at the `custom_dynamic_assets` example.
#[deprecated(
since = "0.19.0",
note = "Use `LoadingState::with_dynamic_assets_file` or `LoadingStateConfig::with_dynamic_assets_file` instead."
)]
fn add_dynamic_collection_to_loading_state<S: States, C: DynamicAssetCollection + Asset>(
&mut self,
loading_state: S,
file: &str,
) -> &mut Self;
/// Add any [`FromWorld`] resource to be initialized after all asset collections are loaded.
/// ```edition2021
/// # use bevy_asset_loader::prelude::*;
/// # use bevy::prelude::*;
/// # use bevy::asset::AssetPlugin;
/// # fn main() {
/// App::new()
/// # .add_plugins((MinimalPlugins, AssetPlugin::default()))
/// # .init_state::<GameState>()
/// # .init_resource::<iyes_progress::ProgressCounter>()
/// .add_loading_state(
/// LoadingState::new(GameState::Loading)
/// .continue_to_state(GameState::Menu)
/// .load_collection::<TextureForAtlas>()
/// .init_resource::<TextureAtlasLayoutFromWorld>()
/// )
/// # .set_runner(|mut app| app.update())
/// # .run();
/// # }
/// # #[derive(Clone, Eq, PartialEq, Debug, Hash, Default, States)]
/// # enum GameState {
/// # #[default]
/// # Loading,
/// # Menu
/// # }
/// # #[derive(Resource)]
/// # struct TextureAtlasLayoutFromWorld {
/// # atlas_layout: Handle<TextureAtlasLayout>
/// # }
/// # impl FromWorld for TextureAtlasLayoutFromWorld {
/// # fn from_world(world: &mut World) -> Self {
/// # let cell = world.cell();
/// # let mut layouts = cell.get_resource_mut::<Assets<TextureAtlasLayout>>().expect("TextureAtlasLayouts missing");
/// # TextureAtlasLayoutFromWorld {
/// # atlas_layout: layouts.add(TextureAtlasLayout::from_grid(Vec2::new(250., 250.), 1, 4, None, None))
/// # }
/// # }
/// # }
/// # #[derive(AssetCollection, Resource)]
/// # pub struct TextureForAtlas {
/// # #[asset(path = "images/female_adventurer.ogg")]
/// # pub array: Handle<Image>,
/// # }
/// ```
#[deprecated(
since = "0.19.0",
note = "Use `LoadingState::init_resource` or `LoadingStateConfig::init_resource` instead."
)]
fn init_resource_after_loading_state<S: States, A: Resource + FromWorld>(
&mut self,
loading_state: S,
) -> &mut Self;
}
impl LoadingStateAppExt for App {
fn add_loading_state<S: States>(&mut self, loading_state: LoadingState<S>) -> &mut Self {
loading_state.build(self);
self
}
fn configure_loading_state<S: States>(
&mut self,
configuration: LoadingStateConfig<S>,
) -> &mut Self {
configuration.build(self);
self
}
fn add_collection_to_loading_state<S: States, A: AssetCollection>(
&mut self,
loading_state: S,
) -> &mut Self {
self.add_systems(
OnEnterInternalLoadingState(loading_state.clone(), InternalLoadingState::LoadingAssets),
start_loading_collection::<S, A>,
)
.add_systems(
LoadingStateSchedule(loading_state),
check_loading_collection::<S, A>.in_set(InternalLoadingStateSet::CheckAssets),
)
}
fn register_dynamic_asset_collection<S: States, C: DynamicAssetCollection + Asset>(
&mut self,
loading_state: S,
) -> &mut Self {
self.add_systems(
OnEnterInternalLoadingState(
loading_state.clone(),
InternalLoadingState::LoadingDynamicAssetCollections,
),
load_dynamic_asset_collections::<S, C>,
)
.add_systems(
LoadingStateSchedule(loading_state),
check_dynamic_asset_collections::<S, C>
.in_set(InternalLoadingStateSet::CheckDynamicAssetCollections),
)
}
fn add_dynamic_collection_to_loading_state<S: States, C: DynamicAssetCollection + Asset>(
&mut self,
loading_state: S,
file: &str,
) -> &mut Self {
let mut dynamic_asset_collections = self
.world
.get_resource_mut::<DynamicAssetCollections<S>>()
.unwrap();
dynamic_asset_collections.register_file::<C>(loading_state.clone(), file);
self
}
fn init_resource_after_loading_state<S: States, A: Resource + FromWorld>(
&mut self,
loading_state: S,
) -> &mut Self {
self.add_systems(
OnEnterInternalLoadingState(loading_state, InternalLoadingState::Finalize),
init_resource::<A>,
)
}
}
struct InternalAssetLoaderPlugin<S> {
_state_marker: PhantomData<S>,
}
impl<S> InternalAssetLoaderPlugin<S>
where
S: States,
{
fn new() -> Self {
InternalAssetLoaderPlugin {
_state_marker: PhantomData,
}
}
}
impl<S> Plugin for InternalAssetLoaderPlugin<S>
where
S: States,
{
fn build(&self, app: &mut App) {
app.add_systems(StateTransition, apply_internal_state_transition::<S>);
}
}