Skip to content

Commit 9267c66

Browse files
committed
Add cleanup system to destroy dead entities
1 parent 33f6807 commit 9267c66

3 files changed

Lines changed: 30 additions & 0 deletions

File tree

src/ecs/ecs.zig

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@ pub fn initSystems(world: *World) !void {
8383
try world.addSystem("physics", systems.physics_system.run, .update, 50);
8484
try world.addSystem("animation", systems.animation_system.run, .update, 60);
8585

86+
// Post-update phase - cleanup dead entities
87+
try world.addSystem("cleanup", systems.cleanup_system.run, .post_update, 0);
88+
8689
// Render prep phase
8790
try world.addSystem("render_prep", systems.render_prep_system.run, .render_prep, 0);
8891
}

src/ecs/systems/cleanup_system.zig

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const World = @import("../world.zig").World;
2+
const Tags = @import("../components/tags.zig").Tags;
3+
const EntityId = @import("../entity.zig").EntityId;
4+
5+
/// Cleanup system - destroys entities marked for removal
6+
/// Runs in post_update phase after all game logic has finished
7+
pub fn run(world: *World) void {
8+
// Collect entities to destroy (avoid mutating during iteration)
9+
var to_destroy: [256]EntityId = undefined;
10+
var count: usize = 0;
11+
12+
var entity_iter = world.entities.iterator();
13+
while (entity_iter.next()) |id| {
14+
const tags = world.getComponent(Tags, id) orelse continue;
15+
if (tags.marked_for_removal) {
16+
if (count < to_destroy.len) {
17+
to_destroy[count] = id;
18+
count += 1;
19+
}
20+
}
21+
}
22+
23+
for (to_destroy[0..count]) |id| {
24+
world.destroyEntity(id);
25+
}
26+
}

src/ecs/systems/systems.zig

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ pub const physics_system = @import("physics_system.zig");
1010
pub const render_prep_system = @import("render_prep_system.zig");
1111
pub const player_input_system = @import("player_input_system.zig");
1212
pub const player_movement_system = @import("player_movement_system.zig");
13+
pub const cleanup_system = @import("cleanup_system.zig");

0 commit comments

Comments
 (0)