use bevy::prelude::*;
use bevy::platform::prelude::{String, ToOwned};
use bevy::platform::sync::Arc;
use crate::types::{self, ActionContext, AiEntity, CraniumKvMap, CraniumRwLock, PawnEntityRef};
use crate::identifiers::ContextFetcherIdentifier;
pub type ContextFetcherInputs = bevy::prelude::In<(
AiEntity,
PawnEntityRef,
)>;
pub type ContextFetcherOutputs = crate::types::CraniumList<ActionContext>;
pub trait ContextFetcherSystem: bevy::ecs::system::ReadOnlySystem<
In = ContextFetcherInputs,
Out = ContextFetcherOutputs,
> {}
impl<
ROS: bevy::ecs::system::ReadOnlySystem<
In = ContextFetcherInputs,
Out = ContextFetcherOutputs,
>
> ContextFetcherSystem for ROS {}
pub trait IntoContextFetcherSystem<Marker>: IntoSystem<
ContextFetcherInputs,
ContextFetcherOutputs,
Marker,
> {}
impl<
CS: ContextFetcherSystem,
Marker,
IS: IntoSystem<
ContextFetcherInputs,
ContextFetcherOutputs,
Marker,
System = CS
>
> IntoContextFetcherSystem<Marker> for IS {}
#[derive(Clone)]
pub struct ContextFetcherMappedToSystem {
pub context_fetcher_system: Result<Arc<CraniumRwLock<dyn ContextFetcherSystem>>, ()>,
}
#[derive(Resource, Default)]
pub struct ContextFetcherKeyToSystemMap {
pub mapping: CraniumKvMap<
types::ContextFetcherKey,
Arc<CraniumRwLock<dyn ContextFetcherSystem>>
>
}
pub trait AcceptsContextFetcherRegistrations {
fn register_context_fetcher<
CS: ContextFetcherSystem,
Marker,
F: IntoContextFetcherSystem<Marker, System = CS> + 'static,
IS: Into<String>,
>(
&mut self,
context_fetcher: F,
key: IS,
) -> &mut Self;
}
impl AcceptsContextFetcherRegistrations for App {
fn register_context_fetcher<
CS: ContextFetcherSystem,
Marker,
F: IntoContextFetcherSystem<Marker, System = CS> + 'static,
IS: Into<String>,
>(
&mut self,
context_fetcher: F,
key: IS,
) -> &mut Self {
self.world_mut().register_context_fetcher(context_fetcher, key);
self
}
}
impl AcceptsContextFetcherRegistrations for World {
fn register_context_fetcher<
CS: ContextFetcherSystem,
Marker,
F: IntoContextFetcherSystem<Marker, System = CS> + 'static,
IS: Into<String>,
>(
&mut self,
context_fetcher: F,
key: IS,
) -> &mut Self {
let system = F::into_system(context_fetcher);
let system_key = ContextFetcherIdentifier::from(key);
let mut system_registry = self.get_resource_or_init::<ContextFetcherKeyToSystemMap>();
let old = system_registry.mapping.insert(
system_key.to_owned(),
Arc::new(CraniumRwLock::new(
system
)));
match old {
None => {},
Some(_) => {
#[cfg(feature = "logging")]
bevy::log::warn!(
"Detected a key collision for key {:?}. Ejecting previous registration...",
system_key
);
}
}
self
}
}
#[derive(Resource, Debug)]
pub struct ShouldReinitCfQueries(bool);
impl ShouldReinitCfQueries {
pub fn get(&self) -> bool {
self.0
}
pub fn set(&mut self, val: bool) {
self.0 = val;
}
}
impl Default for ShouldReinitCfQueries {
fn default() -> Self {
Self(true)
}
}
pub fn reinit_cf_queries(world: &mut World) {
let world_cell = world.as_unsafe_world_cell();
let should_reinit_res = unsafe {
world_cell.get_resource::<ShouldReinitCfQueries>()
};
let should_reinit = match should_reinit_res {
None => true,
Some(reinit_mark) => reinit_mark.get()
};
if !should_reinit {
return
};
let registry = unsafe {
world_cell.get_resource_mut::<ContextFetcherKeyToSystemMap>()
};
let mut registry = match registry {
None => return,
Some(r) => r,
};
registry.mapping.iter_mut().for_each(|(_key, system_lock)| {
let write_state = system_lock.write();
{
match write_state {
Ok(mut system) => {
#[cfg(feature = "logging")]
bevy::log::debug!("reinit_consideration_queries: Reinitializing System {:?}", _key);
system.initialize(unsafe { world_cell.world_mut() });
},
Err(e) => panic!("{:?}", e)
}
}
});
}
pub struct ContextFetcherPlugin;
impl Plugin for ContextFetcherPlugin {
fn build(&self, app: &mut App) {
app
.init_resource::<ShouldReinitCfQueries>()
.init_resource::<ContextFetcherKeyToSystemMap>()
.add_systems(Startup, reinit_cf_queries)
.add_systems(FixedFirst, reinit_cf_queries)
.add_observer(crate::decision_loop::disable_consideration_reinit)
;
}
}