encompass-zig/src/entity_manager.zig

58 lines
1.4 KiB
Zig

const IDManager = @import("id_manager.zig").IDManager;
const Entity = @import("entity.zig").Entity;
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const Allocator = mem.Allocator;
pub const EntityManager = struct {
const Self = @This();
allocator: *Allocator,
idManager: IDManager,
ids: std.AutoHashMap(usize, bool),
pub fn init(allocator: *Allocator) Self {
return Self {
.allocator = allocator,
.idManager = IDManager.init(allocator),
.ids = std.AutoHashMap(usize, bool).init(allocator)
};
}
pub fn deinit(self: *Self) void {
self.idManager.deinit();
self.ids.deinit();
}
pub fn create(self: *Self) !Entity {
const id = self.idManager.next();
var entity = Entity { .ID = id };
self.ids.put(id, true) catch |err| return err;
return entity;
}
pub fn exists(self: Self, entityID: usize) bool {
return self.ids.contains(entityID);
}
};
test "create" {
var entity_manager = EntityManager.init(std.testing.allocator);
defer entity_manager.deinit();
var entity = try entity_manager.create();
testing.expect(entity.ID == 0);
}
test "exists" {
var entity_manager = EntityManager.init(std.testing.allocator);
defer entity_manager.deinit();
var entity = try entity_manager.create();
testing.expect(entity_manager.exists(0));
}