hecs-hierarchy
hecs-hierarchy
Hierarchy implementation for hecs ECS.
Features
- Iterate children of parent
- Lookup parent of child
- Traverse hierarchy depth first
- Traverse hierarchy breadth first
- Traverse ancestors
- Detach child from hierarchy
- Reverse iteration
- Sorting
- (Optional) associated data to relation
Getting Started
Include both hecs
and hecs-hierarchy
as dependencies in your Cargo.toml
.
hecs-hierarchy
does not re-export hecs
[]
= 0.5
= 0.1
Motivation
An ECS is a fantastic design principle for designing software which allows a
data oriented design. Most of the time, the ECS is flat with maybe a few
components referencing each other via Entity
ids. Sometimes however, the need
to create and manage proper, well behaved graphs, arises.
This is were hecs-hierarchy comes in and gives the ability to manage directed graphs that can connect entities. This is very useful when developing a UI library using the ECS design pattern, or purely for grouping entities together from the same model.
Usage
Import the Hierarchy trait which extends hecs::World
The trait Hierarchy extends hecs::World with functions for manipulating and iterating the hierarchy tree.
The hierarchy uses a marker type which makes it possible for a single entity to belong to several hierarchy trees.
See the documentation, more specifically the Hierarchy trait
Example usage:
use Hierarchy;
// Marker type which allows several hierarchies.
;
let mut world = default;
// Create a root entity, there can be several.
let root = world.spawn;
// Create a loose entity
let child = world.spawn;
// Attaches the child to a parent, in this case `root`
world..unwrap;
// Iterate children
for child in world.
// Add a grandchild
world..unwrap;
// Iterate recursively
for child in world.
// Detach `child` and `grandchild`
world..unwrap;
let child2 = world..unwrap;
// Reattach as a child of `child2`
world..unwrap;
world..unwrap;
// Hierarchy now looks like this:
// Root
// |-------- Child 3
// |-------- Child 2
// |-------- Child 1
// |-------- Grandchild
Inspiration
This project is heavily inspired by Shipyard
's hierarchy implementation and
exposes a similar API.