use crate::{SetupKey, SetupTracker, validate_setup_graph};
use bevy_app::{App, Plugin, Startup, Update};
use bevy_ecs::schedule::{InternedScheduleLabel, ScheduleLabel};
use bevy_ecs::{prelude::*, schedule::Condition, system::SystemParamFunction};
use bevy_log::{debug, error};
use bevy_platform::collections::HashSet;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::sync::Mutex;
pub struct SetupTrackingPlugin<
K: SetupKey,
C: Condition<M>,
M,
Fin: SystemParamFunction<Marker, In = (), Out = ()>,
Marker,
> {
condition: Mutex<Option<C>>,
on_finished: Mutex<Option<Fin>>,
schedule: InternedScheduleLabel,
_marker: PhantomData<(K, M, Marker)>,
}
impl<K: SetupKey, C: Condition<M>, M, Fin: SystemParamFunction<Marker, In = (), Out = ()>, Marker>
SetupTrackingPlugin<K, C, M, Fin, Marker>
{
pub fn new(condition: C, on_finished: Fin) -> Self {
Self::new_in_schedule(Update, condition, on_finished)
}
pub fn new_in_schedule(schedule: impl ScheduleLabel, condition: C, on_finished: Fin) -> Self {
Self {
condition: Mutex::new(Some(condition)),
on_finished: Mutex::new(Some(on_finished)),
schedule: schedule.intern(),
_marker: PhantomData,
}
}
pub fn in_schedule(self, schedule: impl ScheduleLabel) -> Self {
Self {
schedule: schedule.intern(),
..self
}
}
}
impl<
K: SetupKey + Debug,
C: Condition<M> + Send + 'static,
M: Send + Sync + 'static,
Fin: SystemParamFunction<Marker, In = (), Out = ()> + Send + 'static,
Marker: Send + Sync + 'static,
> Plugin for SetupTrackingPlugin<K, C, M, Fin, Marker>
{
fn build(&self, app: &mut App) {
let on_finished = self.on_finished.lock().unwrap().take().unwrap();
let fin = app.register_system(IntoSystem::into_system(on_finished));
app.insert_resource(SetupTracker::<K>::new(fin))
.add_systems(Startup, validate_setup_graph::<K>)
.add_systems(
self.schedule,
advance_setup::<K>.run_if(self.condition.lock().unwrap().take().unwrap()),
);
}
}
pub fn advance_setup<K: SetupKey>(world: &mut World) {
world.resource_scope::<SetupTracker<K>, _>(|world, mut tracker| {
let mut pending = HashSet::new();
let ready = tracker
.entries
.iter()
.filter_map(|(key, checker)| {
if world.run_system(*checker).unwrap().finished() {
Some(key.clone())
} else {
pending.insert(key.clone());
None
}
})
.collect::<HashSet<_>>();
let should_run = move |info: &crate::ProviderInfo<K>| {
for provision in info.provides() {
if ready.contains(provision) {
return false;
}
}
for requirement in info.requires() {
if !ready.contains(requirement) {
return false;
}
}
true
};
for (system, info) in tracker.providers.iter() {
if should_run(info) {
if let Err(e) = world.run_system(*system) {
error!("Failed to run setup system: {e}");
}
}
}
let progress = tracker.progress(world);
debug!(?progress);
if progress.finished() {
world.run_system(tracker.on_finished).unwrap();
}
if tracker.last_progress != progress {
tracker.last_progress = progress;
}
});
}