mirror of
https://github.com/bevyengine/bevy
synced 2024-11-10 07:04:33 +00:00
Add a readme to bevy_ecs (#2028)
[RENDERED](https://github.com/NiklasEi/bevy/blob/ecs_readme/crates/bevy_ecs/README.md) Since I am trying to learn more about Bevy ECS at the moment, I thought this issue is a perfect fit. This PR adds a readme to the `bevy_ecs` crate containing a minimal running example of stand alone `bevy_ecs`. Unique features like customizable component storage, Resources or change detection are introduced. For each of these features the readme links to an example in a newly created examples directory inside the `bevy_esc` crate. Resolves #2008 Co-authored-by: Carter Anderson <mcanders1@gmail.com>
This commit is contained in:
parent
21330a7217
commit
cebb553bff
6 changed files with 540 additions and 0 deletions
|
@ -32,3 +32,19 @@ downcast-rs = "1.2"
|
|||
parking_lot = "0.11"
|
||||
rand = "0.8"
|
||||
serde = "1"
|
||||
|
||||
[[example]]
|
||||
name = "events"
|
||||
path = "examples/events.rs"
|
||||
|
||||
[[example]]
|
||||
name = "component_storage"
|
||||
path = "examples/component_storage.rs"
|
||||
|
||||
[[example]]
|
||||
name = "resources"
|
||||
path = "examples/resources.rs"
|
||||
|
||||
[[example]]
|
||||
name = "change_detection"
|
||||
path = "examples/change_detection.rs"
|
||||
|
|
248
crates/bevy_ecs/README.md
Normal file
248
crates/bevy_ecs/README.md
Normal file
|
@ -0,0 +1,248 @@
|
|||
# Bevy ECS
|
||||
|
||||
[![Crates.io](https://img.shields.io/crates/v/bevy_ecs.svg)](https://crates.io/crates/bevy_ecs)
|
||||
[![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/bevyengine/bevy/blob/HEAD/LICENSE)
|
||||
[![Discord](https://img.shields.io/discord/691052431525675048.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/gMUk5Ph)
|
||||
|
||||
## What is Bevy ECS?
|
||||
|
||||
Bevy ECS is an Entity Component System custom-built for the [Bevy][bevy] game engine. It aims to be simple to use, ergonomic, fast, massively parallel, opinionated, and featureful. It was created specifically for Bevy's needs, but it can easily be used as a standalone crate in other projects.
|
||||
|
||||
## ECS
|
||||
|
||||
All app logic in Bevy uses the Entity Component System paradigm, which is often shortened to ECS. ECS is a software pattern that involves breaking your program up into Entities, Components, and Systems. Entities are unique "things" that are assigned groups of Components, which are then processed using Systems.
|
||||
|
||||
For example, one entity might have a `Position` and `Velocity` component, whereas another entity might have a `Position` and `UI` component. You might have a movement system that runs on all entities with a Position and Velocity component.
|
||||
|
||||
The ECS pattern encourages clean, decoupled designs by forcing you to break up your app data and logic into its core components. It also helps make your code faster by optimizing memory access patterns and making parallelism easier.
|
||||
|
||||
## Concepts
|
||||
|
||||
Bevy ECS is Bevy's implementation of the ECS pattern. Unlike other Rust ECS implementations, which often require complex lifetimes, traits, builder patterns, or macros, Bevy ECS uses normal Rust data types for all of these concepts:
|
||||
|
||||
### Components
|
||||
|
||||
Components are normal Rust structs. They are data stored in a `World` and specific instances of Components correlate to Entities.
|
||||
|
||||
```rust
|
||||
struct Position { x: f32, y: f32 }
|
||||
```
|
||||
|
||||
### Worlds
|
||||
|
||||
Entities, Components, and Resources are stored in a `World`. Worlds, much like Rust std collections like HashSet and Vec, expose operations to insert, read, write, and remove the data they store.
|
||||
|
||||
```rust
|
||||
let world = World::default();
|
||||
```
|
||||
|
||||
### Entities
|
||||
|
||||
Entities are unique identifiers that correlate to zero or more Components.
|
||||
|
||||
```rust
|
||||
let entity = world.spawn()
|
||||
.insert(Position { x: 0.0, y: 0.0 })
|
||||
.insert(Velocity { x: 1.0, y: 0.0 })
|
||||
.id();
|
||||
|
||||
let entity_ref = world.entity(entity);
|
||||
let position = entity_ref.get::<Position>().unwrap();
|
||||
let velocity = entity_ref.get::<Velocity>().unwrap();
|
||||
```
|
||||
|
||||
### Systems
|
||||
|
||||
Systems are normal Rust functions. Thanks to the Rust type system, Bevy ECS can use function parameter types to determine what data needs to be sent to the system. It also uses this "data access" information to determine what Systems can run in parallel with each other.
|
||||
|
||||
```rust
|
||||
fn print_position(query: Query<(Entity, &Position)>) {
|
||||
for (entity, position) in query.iter() {
|
||||
println!("Entity {:?} is at position: x {}, y {}", entity, position.x, position.y);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Resources
|
||||
|
||||
Apps often require unique resources, such as asset collections, renderers, audio servers, time, etc. Bevy ECS makes this pattern a first class citizen. `Resource` is a special kind of component that does not belong to any entity. Instead, it is identified uniquely by its type:
|
||||
|
||||
```rust
|
||||
#[derive(Default)]
|
||||
struct Time {
|
||||
seconds: f32,
|
||||
}
|
||||
|
||||
world.insert_resource(Time::default());
|
||||
|
||||
let time = world.get_resource::<Time>().unwrap();
|
||||
|
||||
// You can also access resources from Systems
|
||||
fn print_time(time: Res<Time>) {
|
||||
println!("{}", time.seconds);
|
||||
}
|
||||
```
|
||||
|
||||
The [`resources.rs`](examples/resources.rs) example illustrates how to read and write a Counter resource from Systems.
|
||||
|
||||
### Schedules
|
||||
|
||||
Schedules consist of zero or more Stages, which run a set of Systems according to some execution strategy. Bevy ECS provides a few built in Stage implementations (ex: parallel, serial), but you can also implement your own! Schedules run Stages one-by-one in an order defined by the user.
|
||||
|
||||
The built in "parallel stage" considers dependencies between systems and (by default) run as many of them in parallel as possible. This maximizes performance, while keeping the system execution safe. You can also define explicit dependencies between systems.
|
||||
|
||||
## Using Bevy ECS
|
||||
|
||||
Bevy ECS should feel very natural for those familiar with Rust syntax:
|
||||
|
||||
```rust
|
||||
use bevy_ecs::prelude::*;
|
||||
|
||||
struct Velocity {
|
||||
x: f32,
|
||||
y: f32,
|
||||
}
|
||||
|
||||
struct Position {
|
||||
x: f32,
|
||||
y: f32,
|
||||
}
|
||||
|
||||
// This system moves each entity with a Position and Velocity component
|
||||
fn movement(query: Query<(&mut Position, &Velocity)>) {
|
||||
for (mut position, velocity) in query.iter_mut() {
|
||||
position.x += velocity.x;
|
||||
position.y += velocity.y;
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Create a new empty World to hold our Entities and Components
|
||||
let mut world = World::new();
|
||||
|
||||
// Spawn an entity with Position and Velocity components
|
||||
world.spawn()
|
||||
.insert(Position { x: 0.0, y: 0.0 })
|
||||
.insert(Velocity { x: 1.0, y: 0.0 });
|
||||
|
||||
// Create a new Schedule, which defines an execution strategy for Systems
|
||||
let mut schedule = Schedule::default();
|
||||
|
||||
// Add a Stage to our schedule. Each Stage in a schedule runs all of its systems
|
||||
// before moving on to the next Stage
|
||||
schedule.add_stage("update", SystemStage::parallel()
|
||||
.with_system(movement.system())
|
||||
);
|
||||
|
||||
// Run the schedule once. If your app has a "loop", you would run this once per loop
|
||||
schedule.run(&mut world);
|
||||
}
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
### Query Filters
|
||||
|
||||
```rust
|
||||
// Gets the Position component of all Entities with Player component and without the RedTeam component
|
||||
fn system(query: Query<&Position, (With<Player>, Without<RedTeam>)>) {
|
||||
for position in query.iter() {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Change Detection
|
||||
|
||||
Bevy ECS tracks _all_ changes to Components and Resources.
|
||||
|
||||
Queries can filter for changed Components:
|
||||
|
||||
```rust
|
||||
// Gets the Position component of all Entities whose Velocity has changed since the last run of the System
|
||||
fn system(query: Query<&Position, Changed<Velocity>>) {
|
||||
for position in query.iter() {
|
||||
}
|
||||
}
|
||||
|
||||
// Gets the Position component of all Entities that had a Velocity component added since the last run of the System
|
||||
fn system(query: Query<&Position, Added<Velocity>>) {
|
||||
for position in query.iter() {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Resources also expose change state:
|
||||
|
||||
```rust
|
||||
// Prints "time changed!" if the Time resource has changed since the last run of the System
|
||||
fn system(time: Res<Time>) {
|
||||
if time.is_changed() {
|
||||
println!("time changed!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The [`change_detection.rs`](examples/change_detection.rs) example shows how to query only for updated entities and react on changes in resources.
|
||||
|
||||
### Component Storage
|
||||
|
||||
Bevy ECS supports multiple component storage types.
|
||||
|
||||
Components can be stored in:
|
||||
|
||||
* **Tables**: Fast and cache friendly iteration, but slower adding and removing of components. This is the default storage type.
|
||||
* **Sparse Sets**: Fast adding and removing of components, but slower iteration.
|
||||
|
||||
Component storage types are configurable, and they default to table storage if the storage is not manually defined. The [`component_storage.rs`](examples/component_storage.rs) example shows how to configure the storage type for a component.
|
||||
|
||||
```rust
|
||||
// store Position components in Sparse Sets
|
||||
world.register_component(ComponentDescriptor::new::<Position>(StorageType::SparseSet));
|
||||
```
|
||||
|
||||
### Component Bundles
|
||||
|
||||
Define sets of Components that should be added together.
|
||||
|
||||
```rust
|
||||
#[derive(Bundle, Default)]
|
||||
struct PlayerBundle {
|
||||
player: Player,
|
||||
position: Position,
|
||||
velocity: Velocity,
|
||||
}
|
||||
|
||||
// Spawn a new entity and insert the default PlayerBundle
|
||||
world.spawn().insert_bundle(PlayerBundle::default());
|
||||
|
||||
// Bundles play well with Rust's struct update syntax
|
||||
world.spawn().insert_bundle(PlayerBundle {
|
||||
position: Position { x: 1.0, y: 1.0 },
|
||||
..Default::default()
|
||||
});
|
||||
```
|
||||
|
||||
### Events
|
||||
|
||||
Events offer a communication channel between one or more systems. Events can be sent using the system parameter `EventWriter` and received with `EventReader`.
|
||||
|
||||
```rust
|
||||
struct MyEvent {
|
||||
message: String,
|
||||
}
|
||||
|
||||
fn writer(mut writer: EventWriter<MyEvent>) {
|
||||
writer.send(MyEvent {
|
||||
message: "hello!".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
fn reader(mut reader: EventReader<MyEvent>) {
|
||||
for event in reader.iter() {
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A minimal set up using events can be seen in [`events.rs`](examples/events.rs).
|
||||
|
||||
[bevy]: https://bevyengine.org/
|
120
crates/bevy_ecs/examples/change_detection.rs
Normal file
120
crates/bevy_ecs/examples/change_detection.rs
Normal file
|
@ -0,0 +1,120 @@
|
|||
use bevy_ecs::prelude::*;
|
||||
use rand::Rng;
|
||||
use std::ops::Deref;
|
||||
|
||||
// In this example we will simulate a population of entities. In every tick we will:
|
||||
// 1. spawn a new entity with a certain possibility
|
||||
// 2. age all entities
|
||||
// 3. despawn entities with age > 2
|
||||
//
|
||||
// To demonstrate change detection, there are some console outputs based on changes in
|
||||
// the EntityCounter resource and updated Age components
|
||||
fn main() {
|
||||
// Create a new empty World to hold our Entities, Components and Resources
|
||||
let mut world = World::new();
|
||||
|
||||
// Add the counter resource to remember how many entities where spawned
|
||||
world.insert_resource(EntityCounter { value: 0 });
|
||||
|
||||
// Create a new Schedule, which defines an execution strategy for Systems
|
||||
let mut schedule = Schedule::default();
|
||||
// Create a Stage to add to our Schedule. Each Stage in a schedule runs all of its systems
|
||||
// before moving on to the next Stage
|
||||
let mut update = SystemStage::parallel();
|
||||
|
||||
// Add systems to the Stage to execute our app logic
|
||||
// We can label our systems to force a specific run-order between some of them
|
||||
update.add_system(spawn_entities.system().label(SimulationSystem::Spawn));
|
||||
update.add_system(
|
||||
print_counter_when_changed
|
||||
.system()
|
||||
.after(SimulationSystem::Spawn),
|
||||
);
|
||||
update.add_system(age_all_entities.system().label(SimulationSystem::Age));
|
||||
update.add_system(remove_old_entities.system().after(SimulationSystem::Age));
|
||||
update.add_system(print_changed_entities.system().after(SimulationSystem::Age));
|
||||
// Add the Stage with our systems to the Schedule
|
||||
schedule.add_stage("update", update);
|
||||
|
||||
// Simulate 10 frames in our world
|
||||
for iteration in 1..=10 {
|
||||
println!("Simulating frame {}/10", iteration);
|
||||
schedule.run(&mut world);
|
||||
}
|
||||
}
|
||||
|
||||
// This struct will be used as a Resource keeping track of the total amount of spawned entities
|
||||
#[derive(Debug)]
|
||||
struct EntityCounter {
|
||||
pub value: i32,
|
||||
}
|
||||
|
||||
// This struct represents a Component and holds the age in frames of the entity it gets assigned to
|
||||
#[derive(Default, Debug)]
|
||||
struct Age {
|
||||
frames: i32,
|
||||
}
|
||||
|
||||
// System labels to enforce a run order of our systems
|
||||
#[derive(SystemLabel, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
enum SimulationSystem {
|
||||
Spawn,
|
||||
Age,
|
||||
}
|
||||
|
||||
// This system randomly spawns a new entity in 60% of all frames
|
||||
// The entity will start with an age of 0 frames
|
||||
// If an entity gets spawned, we increase the counter in the EntityCounter resource
|
||||
fn spawn_entities(mut commands: Commands, mut entity_counter: ResMut<EntityCounter>) {
|
||||
if rand::thread_rng().gen_bool(0.6) {
|
||||
let entity_id = commands.spawn().insert(Age::default()).id();
|
||||
println!(" spawning {:?}", entity_id);
|
||||
entity_counter.value += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// This system prints out changes in our entity collection
|
||||
// For every entity that just got the Age component added we will print that it's the
|
||||
// entities first birthday. These entities where spawned in the previous frame.
|
||||
// For every entity with a changed Age component we will print the new value.
|
||||
// In this example the Age component is changed in every frame, so we don't actually
|
||||
// need the `Changed` here, but it is still used for the purpose of demonstration.
|
||||
fn print_changed_entities(
|
||||
entity_with_added_component: Query<Entity, Added<Age>>,
|
||||
entity_with_mutated_component: Query<(Entity, &Age), Changed<Age>>,
|
||||
) {
|
||||
for entity in entity_with_added_component.iter() {
|
||||
println!(" {:?} has it's first birthday!", entity);
|
||||
}
|
||||
for (entity, value) in entity_with_mutated_component.iter() {
|
||||
println!(" {:?} is now {:?} frames old", entity, value);
|
||||
}
|
||||
}
|
||||
|
||||
// This system iterates over all entities and increases their age in every frame
|
||||
fn age_all_entities(mut entities: Query<&mut Age>) {
|
||||
for mut age in entities.iter_mut() {
|
||||
age.frames += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// This system iterates over all entities in every frame and despawns entities older than 2 frames
|
||||
fn remove_old_entities(mut commands: Commands, entities: Query<(Entity, &Age)>) {
|
||||
for (entity, age) in entities.iter() {
|
||||
if age.frames > 2 {
|
||||
println!(" despawning {:?} due to age > 2", entity);
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This system will print the new counter value everytime it was changed since
|
||||
// the last execution of the system.
|
||||
fn print_counter_when_changed(entity_counter: Res<EntityCounter>) {
|
||||
if entity_counter.is_changed() {
|
||||
println!(
|
||||
" total number of entities spawned: {}",
|
||||
entity_counter.deref().value
|
||||
);
|
||||
}
|
||||
}
|
39
crates/bevy_ecs/examples/component_storage.rs
Normal file
39
crates/bevy_ecs/examples/component_storage.rs
Normal file
|
@ -0,0 +1,39 @@
|
|||
use bevy_ecs::{
|
||||
component::{ComponentDescriptor, StorageType},
|
||||
prelude::*,
|
||||
};
|
||||
|
||||
// This example shows how to configure the storage of Components.
|
||||
// A system demonstrates that querying for components is independent of their storage type.
|
||||
fn main() {
|
||||
let mut world = World::new();
|
||||
|
||||
// Store components of type `i32` in a Sparse set
|
||||
world
|
||||
.register_component(ComponentDescriptor::new::<i32>(StorageType::SparseSet))
|
||||
.expect("The component of type i32 is already in use");
|
||||
|
||||
// Components of type i32 will have the above configured Sparse set storage,
|
||||
// while f64 components will have the default table storage
|
||||
world.spawn().insert(1).insert(0.1);
|
||||
world.spawn().insert(2);
|
||||
world.spawn().insert(0.2);
|
||||
|
||||
// Setup a schedule and stage to add a system querying for the just spawned entities
|
||||
let mut schedule = Schedule::default();
|
||||
let mut update = SystemStage::parallel();
|
||||
update.add_system(query_entities.system());
|
||||
schedule.add_stage("update", update);
|
||||
|
||||
schedule.run(&mut world);
|
||||
}
|
||||
|
||||
// The storage type does not matter for how to query in systems
|
||||
fn query_entities(entities_with_i32: Query<&i32>, entities_with_f64: Query<&f64>) {
|
||||
for value in entities_with_i32.iter() {
|
||||
println!("Got entity with i32: {}", value);
|
||||
}
|
||||
for value in entities_with_f64.iter() {
|
||||
println!("Got entity with f64: {}", value);
|
||||
}
|
||||
}
|
67
crates/bevy_ecs/examples/events.rs
Normal file
67
crates/bevy_ecs/examples/events.rs
Normal file
|
@ -0,0 +1,67 @@
|
|||
use bevy_ecs::{event::Events, prelude::*};
|
||||
|
||||
// In this example a system sends a custom event with a 50/50 chance during any frame.
|
||||
// If an event was send, it will be printed by the console in a receiving system.
|
||||
fn main() {
|
||||
// Create a new empty world and add the event as a resource
|
||||
let mut world = World::new();
|
||||
world.insert_resource(Events::<MyEvent>::default());
|
||||
|
||||
// Create a schedule and a stage
|
||||
let mut schedule = Schedule::default();
|
||||
|
||||
// Events need to be updated in every frame. This update should happen before we use
|
||||
// the events. To guarantee this, we can let the update run in an earlier stage than our logic.
|
||||
// Here we will use a stage called "first" that will always run it's systems before the Stage
|
||||
// called "second". In "first" we update the events and in "second" we run our systems
|
||||
// sending and receiving events.
|
||||
let mut first = SystemStage::parallel();
|
||||
first.add_system(Events::<MyEvent>::update_system.system());
|
||||
schedule.add_stage("first", first);
|
||||
|
||||
// Add systems sending and receiving events to a "second" Stage
|
||||
let mut second = SystemStage::parallel();
|
||||
second.add_system(sending_system.system().label(EventSystem::Sending));
|
||||
second.add_system(receiving_system.system().after(EventSystem::Sending));
|
||||
|
||||
// Run the "second" Stage after the "first" Stage, so our Events always get updated before we use them
|
||||
schedule.add_stage_after("first", "second", second);
|
||||
|
||||
// Simulate 10 frames of our world
|
||||
for iteration in 1..=10 {
|
||||
println!("Simulating frame {}/10", iteration);
|
||||
schedule.run(&mut world);
|
||||
}
|
||||
}
|
||||
|
||||
// System label to enforce a run order of our systems
|
||||
#[derive(SystemLabel, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
enum EventSystem {
|
||||
Sending,
|
||||
}
|
||||
|
||||
// This is our event that we will send and receive in systems
|
||||
#[derive(Debug)]
|
||||
struct MyEvent {
|
||||
pub message: String,
|
||||
pub random_value: f32,
|
||||
}
|
||||
|
||||
// In every frame we will send an event with a 50/50 chance
|
||||
fn sending_system(mut event_writer: EventWriter<MyEvent>) {
|
||||
let random_value: f32 = rand::random();
|
||||
if random_value > 0.5 {
|
||||
event_writer.send(MyEvent {
|
||||
message: "A random event with value > 0.5".to_string(),
|
||||
random_value,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// This system listens for events of the type MyEvent
|
||||
// If an event is received it will be printed to the console
|
||||
fn receiving_system(mut event_reader: EventReader<MyEvent>) {
|
||||
for my_event in event_reader.iter() {
|
||||
println!(" Received: {:?}", *my_event);
|
||||
}
|
||||
}
|
50
crates/bevy_ecs/examples/resources.rs
Normal file
50
crates/bevy_ecs/examples/resources.rs
Normal file
|
@ -0,0 +1,50 @@
|
|||
use bevy_ecs::prelude::*;
|
||||
use rand::Rng;
|
||||
use std::ops::Deref;
|
||||
|
||||
// In this example we add a counter resource and increase it's value in one system,
|
||||
// while a different system prints the current count to the console.
|
||||
fn main() {
|
||||
// Create a world
|
||||
let mut world = World::new();
|
||||
|
||||
// Add the counter resource
|
||||
world.insert_resource(Counter { value: 0 });
|
||||
|
||||
// Create a schedule and a stage
|
||||
let mut schedule = Schedule::default();
|
||||
let mut update = SystemStage::parallel();
|
||||
|
||||
// Add systems to increase the counter and to print out the current value
|
||||
update.add_system(increase_counter.system().label(CounterSystem::Increase));
|
||||
update.add_system(print_counter.system().after(CounterSystem::Increase));
|
||||
schedule.add_stage("update", update);
|
||||
|
||||
for iteration in 1..=10 {
|
||||
println!("Simulating frame {}/10", iteration);
|
||||
schedule.run(&mut world);
|
||||
}
|
||||
}
|
||||
|
||||
// Counter resource to be increased and read by systems
|
||||
#[derive(Debug)]
|
||||
struct Counter {
|
||||
pub value: i32,
|
||||
}
|
||||
|
||||
// System label to enforce a run order of our systems
|
||||
#[derive(SystemLabel, Debug, Clone, PartialEq, Eq, Hash)]
|
||||
enum CounterSystem {
|
||||
Increase,
|
||||
}
|
||||
|
||||
fn increase_counter(mut counter: ResMut<Counter>) {
|
||||
if rand::thread_rng().gen_bool(0.5) {
|
||||
counter.value += 1;
|
||||
println!(" Increased counter value");
|
||||
}
|
||||
}
|
||||
|
||||
fn print_counter(counter: Res<Counter>) {
|
||||
println!(" {:?}", counter.deref());
|
||||
}
|
Loading…
Reference in a new issue