feat(ecs): added a simple prefab system

This commit is contained in:
lisk77 2025-07-14 01:54:53 +02:00
parent fef128f8a7
commit e1597e6fa4
10 changed files with 416 additions and 257 deletions

0
crates/comet_ecs/Cargo.toml Normal file → Executable file
View file

0
crates/comet_ecs/component_derive/Cargo.toml Normal file → Executable file
View file

0
crates/comet_ecs/component_derive/src/lib.rs Normal file → Executable file
View file

0
crates/comet_ecs/src/archetypes.rs Normal file → Executable file
View file

0
crates/comet_ecs/src/entity.rs Normal file → Executable file
View file

0
crates/comet_ecs/src/id.rs Normal file → Executable file
View file

21
crates/comet_ecs/src/lib.rs Normal file → Executable file
View file

@ -1,12 +1,15 @@
pub use entity::*;
pub use component::*;
pub use scene::*;
pub use id::*;
pub use component_derive::*;
pub use comet_math as math;
pub use component::*;
pub use component_derive::*;
pub use entity::*;
pub use id::*;
pub use prefabs::PrefabFactory;
pub use scene::*;
mod entity;
mod component;
mod scene;
mod id;
mod archetypes;
mod component;
mod entity;
mod id;
mod prefabs;
mod scene;

View file

@ -0,0 +1,46 @@
use comet_structs::FlatMap;
pub type PrefabFactory = fn(&mut crate::Scene) -> usize;
pub(crate) struct PrefabManager {
pub(crate) prefabs: FlatMap<String, PrefabFactory>,
}
impl PrefabManager {
pub fn new() -> Self {
Self {
prefabs: FlatMap::new(),
}
}
pub fn register(&mut self, name: &str, factory: PrefabFactory) {
self.prefabs.insert(name.to_string(), factory);
}
pub fn has_prefab(&self, name: &str) -> bool {
self.prefabs.contains(&name.to_string())
}
}
#[macro_export]
macro_rules! register_prefab {
($scene:expr, $name:expr, $($component:expr),* $(,)?) => {
{
fn prefab_factory(scene: &mut $crate::Scene) -> usize {
let entity = scene.new_entity() as usize;
$(
scene.add_component(entity, $component);
)*
entity
}
$scene.register_prefab($name, prefab_factory);
}
};
}
#[macro_export]
macro_rules! spawn_prefab {
($scene:expr, $name:expr) => {
$scene.spawn_prefab($name)
};
}

View file

@ -1,17 +1,17 @@
use std::any::TypeId;
use crate::{
entity, Component, Entity, IdQueue
};
use crate::archetypes::Archetypes;
use crate::prefabs::PrefabManager;
use crate::{Component, Entity, IdQueue};
use comet_log::*;
use comet_structs::*;
use crate::archetypes::Archetypes;
use std::any::TypeId;
pub struct Scene {
id_queue: IdQueue,
next_id: u32,
entities: Vec<Option<Entity>>,
components: ComponentStorage,
archetypes: Archetypes
archetypes: Archetypes,
prefabs: PrefabManager,
}
impl Scene {
@ -21,7 +21,8 @@ impl Scene {
next_id: 0,
entities: Vec::new(),
components: ComponentStorage::new(),
archetypes: Archetypes::new()
archetypes: Archetypes::new(),
prefabs: PrefabManager::new(),
}
}
@ -35,7 +36,9 @@ impl Scene {
self.next_id = self.entities.len() as u32;
return;
}
if self.next_id > self.id_queue.front().unwrap() || self.entities[self.next_id as usize] != None {
if self.next_id > self.id_queue.front().unwrap()
|| self.entities[self.next_id as usize] != None
{
self.next_id = self.id_queue.dequeue().unwrap();
}
}
@ -72,12 +75,14 @@ impl Scene {
/// Deletes an entity by its ID.
pub fn delete_entity(&mut self, entity_id: usize) {
self.remove_entity_from_archetype_subsets(entity_id as u32, self.get_component_set(entity_id));
self.remove_entity_from_archetype_subsets(
entity_id as u32,
self.get_component_set(entity_id),
);
self.entities[entity_id] = None;
info!("Deleted entity! ID: {}", entity_id);
for (_, value) in self.components.iter_mut() {
value.remove::<u8>(entity_id);
}
self.id_queue.sorted_enqueue(entity_id as u32);
self.get_next_id();
@ -86,54 +91,48 @@ impl Scene {
fn create_archetype(&mut self, components: ComponentSet) {
self.archetypes.create_archetype(components.clone());
// Collect entities that match the component set first to avoid borrow checker issues
let mut matching_entities = Vec::new();
for (entity_id, entity_option) in self.entities.iter().enumerate() {
if let Some(_entity) = entity_option {
let entity_component_set = self.get_component_set(entity_id);
// If the entity has all the required components (components is subset of entity's components)
if components.is_subset(&entity_component_set) {
matching_entities.push(entity_id as u32);
}
}
}
// Add all matching entities to the archetype
for entity_id in matching_entities {
self.add_entity_to_archetype(entity_id, components.clone());
}
}
fn remove_archetype(&mut self, components: ComponentSet) {
self.archetypes.remove_archetype(&components);
}
fn get_keys(&self, components: ComponentSet) -> Vec<ComponentSet> {
let component_sets = self.archetypes.component_sets();
component_sets.iter()
component_sets
.iter()
.enumerate()
.filter_map(|(i, &ref elem)| if elem.is_subset(&components) { Some(i) } else { None })
.filter_map(|(i, &ref elem)| {
if elem.is_subset(&components) {
Some(i)
} else {
None
}
})
.collect::<Vec<usize>>()
.iter()
.map(|index| component_sets[*index].clone())
.collect::<Vec<ComponentSet>>()
}
fn remove_archetype_subsets(&mut self, components: ComponentSet) {
let keys = self.get_keys(components);
for key in keys {
self.remove_archetype(key.clone());
}
}
fn add_entity_to_archetype(&mut self, entity_id: u32, components: ComponentSet) {
self.archetypes.add_entity_to_archetype(&components, entity_id);
self.archetypes
.add_entity_to_archetype(&components, entity_id);
}
fn remove_entity_from_archetype(&mut self, entity_id: u32, components: ComponentSet) {
self.archetypes.remove_entity_from_archetype(&components, entity_id);
self.archetypes
.remove_entity_from_archetype(&components, entity_id);
}
fn remove_entity_from_archetype_subsets(&mut self, entity_id: u32, components: ComponentSet) {
@ -163,7 +162,10 @@ impl Scene {
}
};
let type_ids = components.iter().map(|index| self.components.keys()[*index]).collect::<Vec<TypeId>>();
let type_ids = components
.iter()
.map(|index| self.components.keys()[*index])
.collect::<Vec<TypeId>>();
ComponentSet::from_ids(type_ids)
}
@ -197,8 +199,15 @@ impl Scene {
}
self.components.set_component(entity_id, component);
let component_index = self.components.keys().iter_mut().position(|x| *x == C::type_id()).unwrap();
self.get_entity_mut(entity_id).unwrap().add_component(component_index);
let component_index = self
.components
.keys()
.iter_mut()
.position(|x| *x == C::type_id())
.unwrap();
self.get_entity_mut(entity_id)
.unwrap()
.add_component(component_index);
let new_component_set = self.get_component_set(entity_id);
@ -218,7 +227,11 @@ impl Scene {
self.add_entity_to_archetype(entity_id as u32, component_set);
}
info!("Added component {} to entity {}!", C::type_name(), entity_id);
info!(
"Added component {} to entity {}!",
C::type_name(),
entity_id
);
}
pub fn remove_component<C: Component + 'static>(&mut self, entity_id: usize) {
@ -226,8 +239,15 @@ impl Scene {
self.remove_entity_from_archetype_subsets(entity_id as u32, old_component_set);
self.components.remove_component::<C>(entity_id);
let component_index = self.components.keys().iter().position(|x| *x == C::type_id()).unwrap();
self.get_entity_mut(entity_id).unwrap().remove_component(component_index);
let component_index = self
.components
.keys()
.iter()
.position(|x| *x == C::type_id())
.unwrap();
self.get_entity_mut(entity_id)
.unwrap()
.remove_component(component_index);
let new_component_set = self.get_component_set(entity_id);
@ -249,7 +269,11 @@ impl Scene {
}
}
info!("Removed component {} from entity {}!", C::type_name(), entity_id);
info!(
"Removed component {} from entity {}!",
C::type_name(),
entity_id
);
}
/// Returns a reference to a component of an entity by its ID.
@ -257,7 +281,10 @@ impl Scene {
self.components.get_component::<C>(entity_id)
}
pub fn get_component_mut<C: Component + 'static>(&mut self, entity_id: usize) -> Option<&mut C> {
pub fn get_component_mut<C: Component + 'static>(
&mut self,
entity_id: usize,
) -> Option<&mut C> {
self.components.get_component_mut::<C>(entity_id)
}
@ -269,7 +296,14 @@ impl Scene {
pub fn get_entities_with(&self, components: Vec<TypeId>) -> Vec<usize> {
let component_set = ComponentSet::from_ids(components);
if self.archetypes.contains_archetype(&component_set) {
return self.archetypes.get_archetype(&component_set).unwrap().clone().iter().map(|x| *x as usize).collect();
return self
.archetypes
.get_archetype(&component_set)
.unwrap()
.clone()
.iter()
.map(|x| *x as usize)
.collect();
}
Vec::new()
}
@ -283,7 +317,7 @@ impl Scene {
}
/// Iterates over all entities that have the given components and calls the given function.
pub fn foreach<C: Component, K: Component>(&mut self, func: fn(&mut C,&mut K)) {
pub fn foreach<C: Component, K: Component>(&mut self, func: fn(&mut C, &mut K)) {
let entities = self.get_entities_with(vec![C::type_id(), K::type_id()]);
for entity in entities {
let c_ptr = self.get_component_mut::<C>(entity).unwrap() as *mut C;
@ -294,4 +328,28 @@ impl Scene {
}
}
}
/// Registers a prefab with the given name and factory function.
pub fn register_prefab(&mut self, name: &str, factory: crate::prefabs::PrefabFactory) {
self.prefabs.register(name, factory);
}
/// Spawns a prefab with the given name.
pub fn spawn_prefab(&mut self, name: &str) -> Option<usize> {
if self.prefabs.has_prefab(name) {
if let Some(factory) = self.prefabs.prefabs.get(&name.to_string()) {
let factory = *factory; // Copy the function pointer
Some(factory(self))
} else {
None
}
} else {
None
}
}
/// Checks if a prefab with the given name exists.
pub fn has_prefab(&self, name: &str) -> bool {
self.prefabs.has_prefab(name)
}
}

52
examples/prefabs.rs Normal file
View file

@ -0,0 +1,52 @@
use comet::prelude::*;
fn setup(app: &mut App, renderer: &mut Renderer2D) {
// Initialize the texture atlas
renderer.initialize_atlas();
// Register components
app.register_component::<Position2D>();
app.register_component::<Color>();
// Register prefabs
register_prefab!(
app,
"player",
Position2D::from_vec(v2::new(0.0, 0.0)),
Color::new(0.0, 1.0, 0.0, 1.0) // Green player
);
register_prefab!(
app,
"enemy",
Position2D::from_vec(v2::new(5.0, 5.0)),
Color::new(1.0, 0.0, 0.0, 1.0) // Red enemy
);
register_prefab!(
app,
"pickup",
Position2D::from_vec(v2::new(-5.0, -5.0)),
Color::new(1.0, 1.0, 0.0, 1.0) // Yellow pickup
);
if let Some(player_id) = app.spawn_prefab("player") {
debug!("Spawned player with ID: {}", player_id);
}
if let Some(enemy_id) = app.spawn_prefab("enemy") {
debug!("Spawned enemy with ID: {}", enemy_id);
}
if let Some(pickup_id) = app.spawn_prefab("pickup") {
debug!("Spawned pickup with ID: {}", pickup_id);
}
}
fn update(app: &mut App, renderer: &mut Renderer2D, dt: f32) {}
fn main() {
App::new()
.with_title("Prefabs Example")
.run::<Renderer2D>(setup, update);
}