owned this note
owned this note
Published
Linked with GitHub
# Library Relations
## Summary
relations is a useful feature which previous was thought to require a bunch of sweeping changes to internals but can actually be implemented as "solely" a 3rd party library with a small addition to `bevy_ecs`.
The only thing this relies on is `on_remove_from_despawn` described [here](https://hackmd.io/7npDczZqTdK2gqHV1q9Rfw?view#Hooks).
## Impl steps
We have to make `Children` and `Parent` private types, this means that downstream crates cannot write `&Parent/Children` or `&mut Parent/Children`. This also forbids `.remove::<Parent/Children>` and `.insert::<Parent/Children>` which means our hierarchy cannot be mutated by downstream users.
It is a bit useless of a hierarchy if users cannot immutably query for parent/children relationships so to allow that we introduce custom worldqueries that mimic the functionality of `&Parent`/`&Children`.
The last thing we need to do is use `on_remove_from_despawn` to clean up `Parent`/`Children` components on other entities when an entity is despawned with any of those components. I.e. if `foo` is a parent of `bar` then if `foo` is despawned we should use the `on_remove_from_despawn` hook to remove the `Parent` component from `foo`.
## More complex impl
previous designs for "library relations" relied on having `MutPerm` and `InsertHook`/`RemoveHook` which would allow for having `Parent`/`Children` be public types and making `.insert::<Parent>` Just Do The Right Thing. see [this](https://hackmd.io/7npDczZqTdK2gqHV1q9Rfw?view) for reading on those proposed features.
## Not Really Relations
this doc mostly just describes "how to make parent/child robust" rather than a _general mechanism for relations_ but that can be done outside of bevy_ecs in a 3rd party crate (which is a really good thing because it takes a while for things to get merged into bevy and also rfcs suck and this is gonna take enough of them). It ought to be "fairly" simple to make a crate for this but not gonna design that in my head yet.
for general purpose relations we want to store data "with" each relation and allow mutation of it. to allow this we can introduce a custom worldquery which acts like `&mut Children/Parent` but only gives access to the user data not the relation target that should be considered immutable. (note: for `Parent`/`Child` there is no data associated with each relation)
---
Note: the rest of this doc is just leftoever from what was here before, I dont wanna remove it because i cant be bothered to read it all so idk if there is valuable stuff in here that we dont want to lose. It's not really intended to be read with the rest of this document but i can't stop you if you want to:
## Component Permissions
"Library relations" are a nice abstraction on top of bevy. We need a way to provide components that can only be read by ?downstream?(expand) users, that is not mutated or (added or removed).
Add associated types `AddRemovePerm` and `MutatePerm` to the `Component` trait to allow plugin authors to restrict how operations are able to be performed on their components such that it is possible to make it so downstream systems and plugins can ONLY read the component NOT add/remove/mutate.
```rust
trait Component {
... // other stuff
type AddRemovePerm;
type MutatePerm;
}
```
#### Sample Impl
```rust
impl<T: Component<MutPerm = ()>> Mut<T> {
fn deref_mut(&mut self) -> &mut T
}
impl<T: Component> Mut<T> {
fn deref_mut_with_perm(&mut self, T::MutPerm) -> &mut T
}
```
?Significance of now having `#[derive(Component)]` now?
This is enables us to define things like the `Children` and `Parent` components in such a way that it is impossible for users to sabotage the parent/child heirarchy by mutating or add/removing the components out of sync with eachother.
We can implment this by changing the impl of DerefMut and the into_inner method on Mut to only work when `T: Component<Perm = ()>` where Perm is one of the two new associated types of Component, and add some other methods that take T::Perm. All existing code would continue to work perfectly. You will only notice a change if you use a plugin that has restricted some of their exposed `Component`'s Component::AddRemovePerm or MutatePerm associated type paramters. All current bevy code assumes no separation of mutabilty concerns, and with the default associated types being `()` this continues to work just as before.
I think this idea is better than custom query accessors because things will just work™️ as you expect &Parent will work plus you dont need to go looking for docs on how to access &Parent it just works™️. Alice: "And unsurprisingly, this would be killer for indexes, assuming you want to do live updating"
#### Simple impl process
- add the two associated types to component trait
- and then find every API that allows adding/removing components
- and every API that lets you mutate a component
- and make it work with T: Component<AddRemovePerm|MutatePerm = ()> instead of T: Component etc
In usual *bevy* style, what we taketh internally we giveth to app/plugin authors. Users too can now define 'read-only' components, that are mutable within their plugin but not by external plugins. This according to @alice-i-cecile does good things for app/plugin composability. "This design would do very interesting things to plugin safety, FYI" "Good things. Plugins will be able to make internal intermediate types read-only but public, which is useful for debugging and triggering downstream effects"
@therawmeatball "<shameless-plug>seems kinda relevant https://github.com/bevyengine/bevy/pull/2363</shameless-plug>, it lets you bypass change detection inside of your crate with similar token stuff without derive(Component). It lets you be notified if a user modifies your resource / component, but then lets you handle that modification without further triggering change detection"
@boxy "we have to allow Query<&mut T> when MutatePerm is not () because it doesnt necessarily mean you cant mutate it, you could actually have that token, for example our Noitaler<T> likely has a MutatePerm = PrivateBevyType which it uses to change the parent"
@therawmeatball and @boxy
"I guess we could add another assoc type for like type BypassChangeDetectionPerm that could be neat so in that PR you just have a trait for T: CanBeGottenUntracked which is kind of similar to a T: Component<BypassChangeDetectionPerm = ()> i guess"
@boxy
"regardless I dont think AddRemovePerm or MutatePerm can use that way of doing things, so unifying them would mean that your BypassChangeDetection would have to change, rather than this stuff changing to be like that" "AddRemove is just a bound on the commands for add/remove
(and on the direct world methods/entitymut)"
"add/remove implies the ability to mutate
mutate doesnt necessarily imply add/remove though
so I think the distinction is useful
we can add a CleanBundle trait
becuase you can be sure that an entity still has a component
there is likely a way yeah
(almost certainly tbh)
I dont think theres any way around the fact that a bundle with an AddRemovePerm not () will be a pain to use
like, the bundle would have to end up with an addremoveperm which is just a tuple of all its fields' AddRemovePerms
I feel like bundles not supporting stuf with ADdRemovePerm really isnt a big deal though
a large amount of stuff with an ADdRemovePerm is likely going to have its add/removes encapsulated in a library instead of exposed"
t's literally just subtly changing the add/remove graph on archetypes
"it is not a big performance problem
we can probably figure something out for this anyway
even if the damn ADdRemovePerm token for a bundle is like
(Field1::AddRemovePerm, Field2::AddRemovePerm, ... FieldN::AddRemovePerm)"
right so
Query doesnt care about any of this
if we have a type with MutatePerm = Blaaaaa
then Query<&mut T> would still be a valid type to use in your system
and it'd still return a Mut<T> when iterating
it's up to the author of the library/wahtever to choose how people get ahold of the tokens
so
for Noitaler as an example
we'd make the token be a private type that is not exposed
and have it be a ZST so we can just create it out of thin air
that way only bevy can add/remove/mutate Noitaler<T> as we are the only ones who can create the token
you'd get a compile error if you tried to deref a Mut<T> without the token
because Mut<T> wouldnt implement DerefMut if T: Component<MutatePerm = ()> didnt hold
I think that Children would also have AddRemovePerm and MutatePerm set to not-()
because changing the contents of Children should go through commands so that we can update the RelationGraph<Children>
when we add/remove the Children component we need to sync up with Noitaler and RelationGraph so that perm would have to be set to soemthing bevy-only
and mutatng too so that people cant change the list of children without updating Noitaler and RelationGraph
once we have the Perm stuff implemented, adding relations is just a matter of designing RelationGraph and then adding some Commands for manipulating collections
we can figure that stuff out way later though I think, dont wanna get too far ahead 😅
cart and I have talked about it before so it's definitely doable so no point delaying the perm stuff to figure that out 🤔
## Collections Trait