use std::any::type_name;
use std::collections::VecDeque;
use std::sync::Arc;
use bevy_app::{App, Plugin, PostUpdate};
use bevy_ecs::prelude::{Commands, ResMut, Resource, World};
use crate::direction::EdgeDirection;
use crate::query::SemanticCommand;
use crate::registry::{canonicalize_name, hash_canonical_name};
use crate::{Kind, SemanticError, SemanticRegistry, SemanticSnapshot, Weight};
#[derive(Resource, Debug, Clone, Default)]
pub struct Semantics(SemanticRegistry);
impl std::ops::Deref for Semantics {
type Target = SemanticRegistry;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for Semantics {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Semantics {
pub fn edit(&mut self) -> SemanticEdit<'_> {
SemanticEdit::new(self)
}
pub fn register_kind(&mut self, name: impl AsRef<str>) -> Result<Kind, SemanticError> {
self.0.register_kind(name)
}
pub fn typed_kind<T>(&mut self) -> Result<Kind, SemanticError>
where
T: 'static,
{
self.0.typed_kind::<T>()
}
pub fn typed_kind_named<T>(&mut self, name: impl AsRef<str>) -> Result<Kind, SemanticError>
where
T: 'static,
{
self.0.typed_kind_named::<T>(name)
}
pub fn unregister_kind(&mut self, kind: Kind) -> Result<bool, SemanticError> {
self.0.unregister_kind(kind)
}
pub fn core(&self) -> crate::registry::Core {
self.0.core()
}
pub fn unregister_namespace(
&mut self,
namespace: impl AsRef<str>,
) -> Result<bool, SemanticError> {
self.0.unregister_namespace(namespace)
}
pub fn kind(&self, name: impl AsRef<str>) -> Result<Kind, SemanticError> {
let canonical = canonicalize_name(name.as_ref())?;
self.0
.kind(canonical.as_ref())
.ok_or_else(|| SemanticError::UnknownKind {
kind: hash_canonical_name(canonical.as_ref()),
})
}
pub fn kind_of<T>(&self) -> Result<Kind, SemanticError>
where
T: 'static,
{
self.0
.kind_of::<T>()
.ok_or_else(|| SemanticError::UnknownKind {
kind: hash_canonical_name(type_name::<T>()),
})
}
pub fn snapshot(&self) -> Arc<SemanticSnapshot> {
self.0.snapshot_cached()
}
pub fn is_a(&self, subject: Kind, target: Kind) -> bool {
self.snapshot().is_a(subject, target)
}
pub fn has_edge(&self, subject: Kind, relation: Kind, target: Kind) -> bool {
self.0.has_edge(subject, relation, target)
}
pub fn targets(&self, subject: Kind, relation: Kind) -> Vec<Kind> {
self.snapshot().targets(subject, relation).to_vec()
}
pub fn subjects(&self, relation: Kind, target: Kind) -> Vec<Kind> {
self.snapshot().subjects(relation, target).to_vec()
}
pub fn neighbors(&self, kind: Kind, relation: Kind, direction: EdgeDirection) -> Vec<Kind> {
self.snapshot().neighbors(kind, relation, direction)
}
pub fn reachable(
&self,
kind: Kind,
relation: Kind,
direction: EdgeDirection,
depth: usize,
) -> Vec<Kind> {
self.snapshot().reachable(kind, relation, direction, depth)
}
pub fn can_reach(&self, start: Kind, relation: Kind, target: Kind, depth: usize) -> bool {
self.snapshot().can_reach(start, relation, target, depth)
}
pub fn add_edge(
&mut self,
subject: Kind,
relation: Kind,
target: Kind,
) -> Result<bool, SemanticError> {
self.0.add_edge(subject, relation, target)
}
pub fn add_edge_weighted(
&mut self,
subject: Kind,
relation: Kind,
target: Kind,
weight: impl Into<Weight>,
) -> Result<bool, SemanticError> {
self.0
.add_edge_weighted(subject, relation, target, weight.into())
}
pub fn remove_edge(
&mut self,
subject: Kind,
relation: Kind,
target: Kind,
) -> Result<bool, SemanticError> {
self.0.remove_edge(subject, relation, target)
}
}
#[must_use = "finish the edit chain with .expect(...) or .finish()"]
#[derive(Debug)]
pub struct SemanticEdit<'a> {
semantics: &'a mut Semantics,
error: Result<(), SemanticError>,
}
impl<'a> SemanticEdit<'a> {
fn new(semantics: &'a mut Semantics) -> Self {
Self {
semantics,
error: Ok(()),
}
}
pub fn register_kind(mut self, name: impl Into<Arc<str>>) -> Self {
if self.error.is_ok() {
let name = name.into();
self.error = self.semantics.0.register_kind(name.as_ref()).map(|_| ());
}
self
}
pub fn unregister_kind(mut self, kind: Kind) -> Self {
if self.error.is_ok() {
self.error = self.semantics.0.unregister_kind(kind).map(|_| ());
}
self
}
pub fn unregister_namespace(mut self, namespace: impl Into<Arc<str>>) -> Self {
if self.error.is_ok() {
let namespace = namespace.into();
self.error = self
.semantics
.0
.unregister_namespace(namespace.as_ref())
.map(|_| ());
}
self
}
pub fn typed_kind<T>(mut self) -> Self
where
T: 'static,
{
if self.error.is_ok() {
self.error = self.semantics.0.typed_kind::<T>().map(|_| ());
}
self
}
pub fn typed_kind_named<T>(mut self, name: impl Into<Arc<str>>) -> Self
where
T: 'static,
{
if self.error.is_ok() {
let name = name.into();
self.error = self
.semantics
.0
.typed_kind_named::<T>(name.as_ref())
.map(|_| ());
}
self
}
pub fn add_edge(mut self, subject: Kind, relation: Kind, target: Kind) -> Self {
if self.error.is_ok() {
self.error = self
.semantics
.0
.add_edge(subject, relation, target)
.map(|_| ());
}
self
}
pub fn add_edge_weighted(
mut self,
subject: Kind,
relation: Kind,
target: Kind,
weight: impl Into<Weight>,
) -> Self {
if self.error.is_ok() {
let weight = weight.into();
self.error = self
.semantics
.0
.add_edge_weighted(subject, relation, target, weight)
.map(|_| ());
}
self
}
pub fn remove_edge(mut self, subject: Kind, relation: Kind, target: Kind) -> Self {
if self.error.is_ok() {
self.error = self
.semantics
.0
.remove_edge(subject, relation, target)
.map(|_| ());
}
self
}
pub fn expect(self, message: &str) -> &'a mut Semantics {
if let Err(error) = self.error {
panic!("{message}: {error}");
}
self.semantics
}
pub fn finish(self) -> Result<&'a mut Semantics, SemanticError> {
self.error.map(|()| self.semantics)
}
}
#[derive(Resource, Debug, Default)]
pub struct SemanticPlaybackQueue {
batches: VecDeque<Vec<SemanticCommand>>,
}
impl SemanticPlaybackQueue {
pub fn enqueue(&mut self, commands: impl IntoIterator<Item = SemanticCommand>) {
self.batches.push_back(commands.into_iter().collect());
}
pub fn is_empty(&self) -> bool {
self.batches.is_empty()
}
pub fn playback(&mut self, semantics: &mut SemanticRegistry) -> Result<bool, SemanticError> {
let mut changed = false;
while let Some(batch) = self.batches.pop_front() {
changed |= semantics.apply_commands(batch)?;
}
Ok(changed)
}
}
#[derive(Resource, Debug, Default)]
struct SemanticCommandQueue(pub Vec<SemanticCommand>);
impl SemanticCommandQueue {
pub fn push(&mut self, command: SemanticCommand) {
self.0.push(command);
}
pub fn drain(&mut self) -> Vec<SemanticCommand> {
std::mem::take(&mut self.0)
}
}
pub struct SemanticsPlugin;
impl Plugin for SemanticsPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<Semantics>()
.init_resource::<SemanticPlaybackQueue>()
.init_resource::<SemanticCommandQueue>()
.add_systems(PostUpdate, apply_semantic_commands);
}
}
#[doc(hidden)]
pub trait SemanticCommandsExt<'w, 's> {
fn register_kind(&mut self, name: impl Into<Arc<str>>) -> &mut Self;
fn unregister_kind(&mut self, kind: Kind) -> &mut Self;
fn unregister_namespace(&mut self, namespace: impl Into<Arc<str>>) -> &mut Self;
fn typed_kind<T>(&mut self) -> &mut Self
where
T: 'static;
fn typed_kind_named<T>(&mut self, name: impl Into<Arc<str>>) -> &mut Self
where
T: 'static;
fn add_edge(&mut self, subject: Kind, relation: Kind, target: Kind) -> &mut Self;
fn add_edge_weighted(
&mut self,
subject: Kind,
relation: Kind,
target: Kind,
weight: impl Into<Weight>,
) -> &mut Self;
fn remove_edge(&mut self, subject: Kind, relation: Kind, target: Kind) -> &mut Self;
}
impl<'w, 's> SemanticCommandsExt<'w, 's> for Commands<'w, 's> {
fn register_kind(&mut self, name: impl Into<Arc<str>>) -> &mut Self {
let name = name.into();
self.queue(move |world: &mut World| {
let mut queue = world
.get_resource_mut::<SemanticCommandQueue>()
.expect("semantic command buffer is missing; add SemanticsPlugin first");
queue.push(SemanticCommand::RegisterKind { name });
});
self
}
fn unregister_kind(&mut self, kind: Kind) -> &mut Self {
self.queue(move |world: &mut World| {
let mut queue = world
.get_resource_mut::<SemanticCommandQueue>()
.expect("semantic command buffer is missing; add SemanticsPlugin first");
queue.push(SemanticCommand::UnregisterKind { kind });
});
self
}
fn unregister_namespace(&mut self, namespace: impl Into<Arc<str>>) -> &mut Self {
let namespace = namespace.into();
self.queue(move |world: &mut World| {
let mut queue = world
.get_resource_mut::<SemanticCommandQueue>()
.expect("semantic command buffer is missing; add SemanticsPlugin first");
queue.push(SemanticCommand::UnregisterNamespace { namespace });
});
self
}
fn typed_kind<T>(&mut self) -> &mut Self
where
T: 'static,
{
let name: Arc<str> = Arc::from(type_name::<T>());
self.queue(move |world: &mut World| {
let mut queue = world
.get_resource_mut::<SemanticCommandQueue>()
.expect("semantic command buffer is missing; add SemanticsPlugin first");
queue.push(SemanticCommand::RegisterTypedKind {
type_id: std::any::TypeId::of::<T>(),
name: Some(name),
});
});
self
}
fn typed_kind_named<T>(&mut self, name: impl Into<Arc<str>>) -> &mut Self
where
T: 'static,
{
let name = name.into();
self.queue(move |world: &mut World| {
let mut queue = world
.get_resource_mut::<SemanticCommandQueue>()
.expect("semantic command buffer is missing; add SemanticsPlugin first");
queue.push(SemanticCommand::RegisterTypedKind {
type_id: std::any::TypeId::of::<T>(),
name: Some(name),
});
});
self
}
fn add_edge(&mut self, subject: Kind, relation: Kind, target: Kind) -> &mut Self {
self.queue(move |world: &mut World| {
let mut queue = world
.get_resource_mut::<SemanticCommandQueue>()
.expect("semantic command buffer is missing; add SemanticsPlugin first");
queue.push(SemanticCommand::AddEdge {
subject,
relation,
target,
weight: None,
});
});
self
}
fn add_edge_weighted(
&mut self,
subject: Kind,
relation: Kind,
target: Kind,
weight: impl Into<Weight>,
) -> &mut Self {
let weight = Some(weight.into());
self.queue(move |world: &mut World| {
let mut queue = world
.get_resource_mut::<SemanticCommandQueue>()
.expect("semantic command buffer is missing; add SemanticsPlugin first");
queue.push(SemanticCommand::AddEdge {
subject,
relation,
target,
weight,
});
});
self
}
fn remove_edge(&mut self, subject: Kind, relation: Kind, target: Kind) -> &mut Self {
self.queue(move |world: &mut World| {
let mut queue = world
.get_resource_mut::<SemanticCommandQueue>()
.expect("semantic command buffer is missing; add SemanticsPlugin first");
queue.push(SemanticCommand::RemoveEdge {
subject,
relation,
target,
});
});
self
}
}
pub use SemanticCommandsExt as CommandsExt;
fn apply_semantic_commands(
mut semantics: ResMut<'_, Semantics>,
mut queue: ResMut<'_, SemanticCommandQueue>,
) {
let commands = queue.drain();
semantics
.apply_commands(commands)
.unwrap_or_else(|error| panic!("failed to apply semantic command: {error}"));
}