Bevy Developer Network
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Feature name: `minimal-relations-api` ## Summary Relations allow users to create logical connection between entities. Each source entity can have multiple kinds of relations, each with their own data, and multiple relations of the same kind pointing to a different target entity. Queries are expanded to allow efficient filtering of entities by the relations they have or the targets of these relations. This RFC covers the very first step of a minimal user facing API for relations that can replace the current `Parent`/`Children` hierarchy that is in use. It does not make decisions on implementation issues, nor does it make decisions between fragmenting and non-fragmenting relations. It should be future-proof in the sense that we estimate that there's a reasonable path forward from it without breaking backward compatibility too badly, but it is not meant to solve the full set of challenges around a relations API. ## Motivation Relations have been talked about for a long time in Bevy, and a lot of work has been done towards them, but the long term solution is gated behind a lot of implementation issues. At the same time, many people have tried to make incremental improvements to the current situation, which have been largely thwarted by them not aligning with the long term solution. Yet, the requirements set by the long term solution have not been written down, and there isn't a generally accepted consensus as to what they exactly are. This puts everybody that tries to work with relations against an impossible task of adhering to requirements that are unstated. The primary motivation for this RFC is meant to break that deadlock by explicitly specifying the requirements for the relations API, so that any incremental improvement that fulfills those requirements can avoid having the design discussions mixed in with the implementation discussions in the same pull request. This means it can be very incremental from the current hierarchy implementation in Bevy, as long as it enables movement forward in this space. A secondary motivation for this RFC is making the design constraints explicit on the long term relations implementation. For example, there are varying opinions on the expected level of consistency under different types of mutation operations, directly exposing components to users, interaction with reflection and so on. Without specifying these design constraints clearly, the same sort of issues will happen also for the long term plans where different expectations on the design get mixed up with the implementation and performance issues. It is not a goal for this specification to solve all the use cases around relations or to specify advanced query APIs that do not exist today. The aim is to avoid spending time thinking about things which are better discussed as concrete implementation proposals or further specifications, but instead to just set the sandbox inside which these proposals live. ## Guide-level explanation ## Reference-level explanation ## Drawbacks ## Rationale and alternatives ### Q1: Should relation changes be atomic? When relations are changed (added, removed, replaced, etc.), should all the related changes be immediately visible or can there be a delay? Concretely for example if changing the `Parent` of an entity, should corresponding `Children` change immediately, or only after a flush, or after some scheduled systems have had a change to run? Alternatively, should there be any cases where an inconsistent view of relations is observable, or should every change immediately be made consistent so that there is no way to see the world in an inconsistent state? In the past, Bevy has had `Parent`/`Children` implemented through systems that used change detection events, which meant that if you manually changed some things, not everything was immediately updated. Today, all changes to hierarchy must be done through commands and independent hierarchy APIs that atomically do modifications. Manually changing the components is not supported. **Suggestion:** All relationship modifications are required to be atomic. The world should never be observable in an inconsistent state, except perhaps during the execution of hooks. ### Should any components used in the implementation of relations be private and unmodifiable by users except through explicitly bypassing API safeguards? *Note: just a sample description so far, not decided upon.* Currently, components such as `Parent` and `Children` are public, even though their data fields are not. This allows the user to manually insert, replace or remove them. In the actual relations implementation, components might not be the storage for relations at all, and even if it is, the logic and consistency of that implementation might not support the user manually changing these instead of going through an API. Keeping backward compatibility with the component based approach might be especially difficult if we continue to allow them to be public, or even bless more ways to manually manipulate them. Hence, it is better to treat all concrete components used in relations as implementation details and hide them as much as possible. For backward compatibility, we should provide `QueryData` and `Bundle` for the existing components, but deprecate that usage in the long term. **Decision:** Components on entities for relations should be treated as implementation details and not exposed to users. ### Should children of an entity be treated ordered or unordered? *Fill in explanation and alternatives.* **Decision:** *Fill in decision.* ## Prior art [`Flecs`](https://github.com/SanderMertens/flecs), an advanced C++ ECS framework, has a similar feature, which they call "relationships". These are somewhat different, they use an elaborate query domain-specific language along with being more feature rich. You can read more about them in the [docs](https://github.com/SanderMertens/flecs/blob/master/docs/Queries.md) or [corresponding PR](https://github.com/SanderMertens/flecs/pull/358). You can, of course, build similar data structures using the ECS itself. Here's a look at the complexities involved in doing so in [EnTT](https://skypjack.github.io/2019-06-25-ecs-baf-part-4/). ## Unresolved questions ## Future possibilities # SCRATCHSPACE :rainbow: Edit and add whatever below here, used just a workspace for keeping things around. ## Current hierarchy API - `despawn_with_children_recursive` - `ChildBuilder` / `WorldChildBuilder` / `ChildBuild` - `spawn` - `spawn_empty` - `parent_entity` - `enqueue_command` - `HierarchyEvent` - `ChildAdded { child: Entity, parent: Entity }` - `ChildRemoved { child: Entity, parent: Entity }` - `ChildMoved { child: Entity, previous_parent: Entity, new_parent: Entity }` - `BuildChildren` / `BuildWorldChildren` - `with_children` - `with_child` - `add_children` - `insert_children` - `remove_children` - `add_child` - `clear_children` - `replace_children` - `set_parent` - `remove_parent` - `DespawnRecursiveExt` - `despawn_recursive` - `despawn_descendants` - `try_despawn_recursive` - `try_despawn_descendants` - `HierarchyQueryExt` - `parent` -> `Option<Entity>` - `children` -> `&[Entity]` - `root_ancestor` -> `Entity` - `iter_leaves` -> `Iterator<Item=Entity>` - `iter_siblings` -> `Iterator<Item=Entity>` - `iter_descendants` -> `Iterator<Item=Entity>` - `iter_descendants_depth_first` -> `Iterator<Item=Entity>` - `iter_ancestors` -> `Iterator<Item=Entity>` - `Parent` - `get` - `as_slice` - `Deref<Target=Entity>` - `Children` - `sort_by` - `sort_by_cached_key` - `sort_by_key` - `sort_unstable_by` - `sort_unstable_by_key` - `swap` - `Deref<Target=[Entity]>` - `VisitEntities` / `VisitEntitiesMut` - `Traversal` Notes: - `Children`/`Parent` have no constructors, and the entity is private, so the expectation is that they are read-only and the "blessed API" is used to make changes ## Private vs Public Relationship Types While the components of a relationship should be considered an implementation detail, and thus be private, the relationship itself is public. In other words, the `Parent` component should be private, but knowing that one entity is the parent of another is public. A possible mechanism to support this distinction is to have public marker types (e.g, `ChildOf`), and private storage. for example: ```rust pub struct ChildOf; #[derive(Component)] struct Relationship<T> { entity: Entity, _phantom: PhantomData<T>, } ``` Note that in the above example, `Relationship` is an implementation detail, and could be replaced with any other storage mechanism (e.g., resources). Actionable takeaway: relationships need a public name. A simple solution for that name is a ZST component. ```rust #[derive(Component)] pub struct Eats; ``` Open Question: Should relationship markers be allowed to include data (a non-ZST)? ## Relationship Invariants Certain types of relationships may have invariants that should be encoded into the relationship system where possible. Typical invariants include: - Acyclic (e.g., no entity is its own ancestor in a parent/child hierarchy) - Tree-Like (e.g., acyclic and all entities share a common ancestor) - One-to-One (e.g., if A points to B, then B points to A) ## Relevant documentation from Flecs - https://www.flecs.dev/flecs/md_docs_2ComponentTraits.html - https://www.flecs.dev/flecs/md_docs_2Relationships.html - https://www.flecs.dev/flecs/md_docs_2FlecsQueryLanguage.html - https://ajmmertens.medium.com/building-games-in-ecs-with-entity-relationships-657275ba2c6c - https://ajmmertens.medium.com/a-roadmap-to-entity-relationships-5b1d11ebb4eb

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully