diff --git a/src/world.zig b/src/world.zig index 85f5b4d..09d0237 100644 --- a/src/world.zig +++ b/src/world.zig @@ -95,6 +95,41 @@ pub fn World(comptime ctx: anytype) type { return Entity(ctx).fromRaw(self, result); } + /// Registers a singleton component of type `T` with the specified value. + /// + /// A singleton is a component which has itself added to its entity. + /// This allows looking up a value of `T` using its own type. Only one + /// singleton of each type can exist per world, but other entities may + /// still have this component added to them. + /// + /// Use `get()` and `set()` to get and set the value of this singleton. + /// + /// Returns the created component entity. + pub fn singleton(self: *Self, comptime T: type, value: T) !Entity(ctx) { + const single = try component(self, T); + single.set(T, value); + return single; + } + + /// Gets the value of the singleton component with type `T`. + /// + /// Returns `error.IsNotAlive` if the entity is missing. + /// Returns `error.ComponentMissing` if the component is missing. + /// Both of these may occur from not calling `singleton()` first. + pub fn get(self: *Self, comptime T: type) !T { + const e = try self.lookupByType(T); + return e.get(T) orelse error.ComponentMissing; + } + + /// Sets the value of the singleton component with type `T`. + /// + /// Returns `error.IsNotAlive` if the entity is missing. + /// This may occur from not calling `singleton()` first. + pub fn set(self: *Self, comptime T: type, value: T) !void { + const e = try self.lookupByType(T); + e.set(T, value); + } + pub fn system( self: *Self, name: [:0]const u8,