Skip to content

Instantly share code, notes, and snippets.

@HackerFoo
Created August 9, 2021 17:02
Show Gist options
  • Save HackerFoo/24ff001d217d1efad1944eb08c9dd916 to your computer and use it in GitHub Desktop.
Save HackerFoo/24ff001d217d1efad1944eb08c9dd916 to your computer and use it in GitHub Desktop.
// relation stuff
pub trait Relation: Component {
type Iter: Iterator<Item = Entity>;
fn entities(&self) -> Self::Iter;
fn insert_indicies(&self,
entity: Entity,
query: &mut Query<&mut RelationIndex>) {
for e in self.entities() {
if let Ok(mut index) = query.get_mut(e) {
index.0.insert(entity);
}
}
}
fn remove_indicies(&self,
entity: Entity,
query: &mut Query<&mut RelationIndex>) {
for e in self.entities() {
if let Ok(mut index) = query.get_mut(e) {
index.0.remove(&entity);
}
}
}
}
#[derive(Debug, Clone, Deref, DerefMut)]
pub struct RelationIndex(HashSet<Entity>);
impl RelationIndex
{
pub fn new() -> Self {
Self(HashSet::new())
}
pub fn remove<T>(&self,
commands: &mut Commands,
q_index: &mut Query<&mut RelationIndex>,
q_rel: &Query<&T>)
where T: Relation
{
for e in &self.0 {
if let Ok(rel) = q_rel.get(*e) {
rel.remove_indicies(*e, q_index);
commands.entity(*e).despawn()
}
}
}
pub fn relations<'a, T, B>(&self,
q_rel: &Query<&T>) -> B
where T: Relation,
B: FromIterator<Entity>
{
self.iter().filter_map(move |e| q_rel.get(*e).ok().map(|_| *e)).collect()
}
}
// impl for Operation
#[derive(Debug, Clone, Copy)]
struct Operation {
op: Op,
a: Entity,
b: Entity,
intersecting: bool
}
impl Relation for Operation {
type Iter = impl Iterator<Item = Entity>;
fn entities(&self) -> Self::Iter {
once(self.a).chain(once(self.b))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment