#Creating node graph component

2 messages · Page 1 of 1 (latest)

lethal mirage
#

I'm trying to create a bevy component which acts as a node graph, liking together multiple entities like so:

#[derive(Component)]
pub struct KmpNode {
    pub prev_nodes: Vec<Entity>,
    pub next_nodes: Vec<Entity>,
}

I've created these functions implemented on the KmpNode type:

    pub fn add_next_node(
        &mut self,
        next_node_entity: Entity,
        self_entity: Entity,
        kmp_node_query: &mut Query<&mut KmpNode>,
    ) {
        if !self.next_nodes.contains(&next_node_entity) {
            self.next_nodes.push(next_node_entity);
            let mut next_node = kmp_node_query.get_mut(next_node_entity).unwrap();
            next_node.add_previous_node(self_entity, next_node_entity, kmp_node_query);
        }
    }
    pub fn add_previous_node(
        &mut self,
        prev_node_entity: Entity,
        self_entity: Entity,
        kmp_node_query: &mut Query<&mut KmpNode>,
    ) {
        if !self.prev_nodes.contains(&prev_node_entity) {
            self.prev_nodes.push(prev_node_entity);
            let mut prev_node = kmp_node_query.get_mut(prev_node_entity).unwrap();
            prev_node.add_next_node(self_entity, prev_node_entity, kmp_node_query);
        }
    }

However, the rust compiler gives me an error when I try to pass in kmp_node_query to the add next/previous node functions at the bottom of each function, because it is already mutably borrowed.
How can I correctly implement this without having borrow checker errors?

midnight cipher
#

If you're determined to use add_next and add_prev, I would just remove the dependency on &mut self. You probably wouldn't be able to pass in that query and obtain a mutable reference to your node anyways.

I would probably just combine them both into a function link_nodes(kmp_node_query: Query<..>, first: Entity, second:Entity) -> bool