encompass-zig/src/entity_manager.zig

61 lines
1.5 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 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 arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var entity_manager = EntityManager.init(allocator);
var entity = try entity_manager.create();
testing.expect(entity.ID == 0);
}
test "exists" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var entity_manager = EntityManager.init(allocator);
var entity = try entity_manager.create();
testing.expect(entity_manager.exists(0));
}