module: change state to avoid undefined, remove global allocator

Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
This commit is contained in:
Stephen Gutekanst 2024-04-05 17:05:48 -07:00 committed by Stephen Gutekanst
parent 5dbf9ece3b
commit cf883f5544
11 changed files with 271 additions and 222 deletions

View file

@ -83,17 +83,11 @@ test "example" {
try world.init(allocator);
defer world.deinit(allocator);
// TODO: better module initialization location
world.mod.physics.entities = &world.entities;
world.mod.physics.allocator = world.entities.allocator;
world.mod.renderer.entities = &world.entities;
world.mod.renderer.allocator = world.entities.allocator;
// Initialize module state.
var physics = &world.mod.physics;
var renderer = &world.mod.renderer;
physics.state = .{ .pointer = 123 };
_ = physics.state.pointer; // == 123
physics.init(.{ .pointer = 123 });
_ = physics.state().pointer; // == 123
const player1 = try physics.newEntity();
const player2 = try physics.newEntity();

View file

@ -39,20 +39,23 @@ pub const Engine = struct {
fn init(engine: *Mod) !void {
core.allocator = allocator;
try core.init(.{});
const state = &engine.state;
state.device = core.device;
state.queue = core.device.getQueue();
state.should_exit = false;
state.encoder = state.device.createCommandEncoder(&gpu.CommandEncoder.Descriptor{
.label = "engine.state.encoder",
engine.init(.{
.device = core.device,
.queue = core.device.getQueue(),
.should_exit = false,
.pass = undefined,
.encoder = core.device.createCommandEncoder(&gpu.CommandEncoder.Descriptor{
.label = "engine.state.encoder",
}),
});
engine.sendGlobal(.init, .{});
}
fn deinit(engine: *Mod) void {
const state = engine.state();
// TODO: this triggers a device loss error, which we should handle correctly
// engine.state.device.release();
engine.state.queue.release();
// state.device.release();
state.queue.release();
engine.sendGlobal(.deinit, .{});
core.deinit();
}
@ -60,7 +63,8 @@ pub const Engine = struct {
// Engine module's exit handler
fn exit(engine: *Mod) void {
engine.sendGlobal(.exit, .{});
engine.state.should_exit = true;
const state = engine.state();
state.should_exit = true;
}
fn beginPass(engine: *Mod, clear_color: gpu.Color) void {
@ -78,21 +82,23 @@ pub const Engine = struct {
.color_attachments = &.{color_attachment},
});
engine.state.pass = engine.state.encoder.beginRenderPass(&pass_info);
const state = engine.state();
state.pass = state.encoder.beginRenderPass(&pass_info);
}
fn endPass(engine: *Mod) void {
const state = engine.state();
// End this pass
engine.state.pass.end();
engine.state.pass.release();
state.pass.end();
state.pass.release();
var command = engine.state.encoder.finish(null);
var command = state.encoder.finish(null);
defer command.release();
engine.state.encoder.release();
engine.state.queue.submit(&[_]*gpu.CommandBuffer{command});
state.encoder.release();
state.queue.submit(&[_]*gpu.CommandBuffer{command});
// Prepare for next pass
engine.state.encoder = engine.state.device.createCommandEncoder(&gpu.CommandEncoder.Descriptor{
state.encoder = state.device.createCommandEncoder(&gpu.CommandEncoder.Descriptor{
.label = "engine.state.encoder",
});
}
@ -125,6 +131,6 @@ pub const App = struct {
app.modules.mod.engine.sendGlobal(.tick, .{});
try app.modules.dispatch(); // dispatch .tick
try app.modules.dispatch(); // dispatch any events produced by .tick
return app.modules.mod.engine.state.should_exit;
return app.modules.mod.engine.state().should_exit;
}
};

View file

@ -12,8 +12,11 @@ const Vec3 = math.Vec3;
const Mat3x3 = math.Mat3x3;
const Mat4x4 = math.Mat4x4;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
/// Internal state
pipelines: std.AutoArrayHashMapUnmanaged(u32, Pipeline),
pipelines: std.AutoArrayHashMapUnmanaged(u32, Pipeline) = .{},
allocator: std.mem.Allocator,
pub const name = .mach_gfx_sprite;
pub const Mod = mach.Mod(@This());
@ -137,18 +140,15 @@ pub const PipelineOptions = struct {
pipeline_layout: ?*gpu.PipelineLayout = null,
};
fn deinit(sprite_mod: *Mod) !void {
for (sprite_mod.state.pipelines.entries.items(.value)) |*pipeline| pipeline.deinit();
sprite_mod.state.pipelines.deinit(sprite_mod.allocator);
fn init(sprite_mod: *Mod) void {
sprite_mod.init(.{
.allocator = gpa.allocator(),
});
}
fn init(
sprite_mod: *Mod,
) !void {
sprite_mod.state = .{
// TODO: struct default value initializers don't work
.pipelines = .{},
};
fn deinit(sprite_mod: *Mod) !void {
for (sprite_mod.state().pipelines.entries.items(.value)) |*pipeline| pipeline.deinit();
sprite_mod.state().pipelines.deinit(sprite_mod.state().allocator);
}
fn initPipeline(
@ -156,9 +156,9 @@ fn initPipeline(
sprite_mod: *Mod,
opt: PipelineOptions,
) !void {
const device = engine.state.device;
const device = engine.state().device;
const pipeline = try sprite_mod.state.pipelines.getOrPut(engine.allocator, opt.pipeline);
const pipeline = try sprite_mod.state().pipelines.getOrPut(sprite_mod.state().allocator, opt.pipeline);
if (pipeline.found_existing) {
pipeline.value_ptr.*.deinit();
}
@ -296,8 +296,8 @@ fn updated(
sprite_mod: *Mod,
pipeline_id: u32,
) !void {
const pipeline = sprite_mod.state.pipelines.getPtr(pipeline_id).?;
const device = engine.state.device;
const pipeline = sprite_mod.state().pipelines.getPtr(pipeline_id).?;
const device = engine.state().device;
// TODO: make sure these entities only belong to the given pipeline
// we need a better tagging mechanism
@ -337,7 +337,7 @@ fn updated(
var command = encoder.finish(null);
defer command.release();
engine.state.queue.submit(&[_]*gpu.CommandBuffer{command});
engine.state().queue.submit(&[_]*gpu.CommandBuffer{command});
}
fn preRender(
@ -345,7 +345,7 @@ fn preRender(
sprite_mod: *Mod,
pipeline_id: u32,
) !void {
const pipeline = sprite_mod.state.pipelines.get(pipeline_id).?;
const pipeline = sprite_mod.state().pipelines.get(pipeline_id).?;
// Update uniform buffer
const proj = Mat4x4.projection2D(.{
@ -365,7 +365,7 @@ fn preRender(
),
};
engine.state.encoder.writeBuffer(pipeline.uniforms, 0, &[_]Uniforms{uniforms});
engine.state().encoder.writeBuffer(pipeline.uniforms, 0, &[_]Uniforms{uniforms});
}
fn render(
@ -373,10 +373,10 @@ fn render(
sprite_mod: *Mod,
pipeline_id: u32,
) !void {
const pipeline = sprite_mod.state.pipelines.get(pipeline_id).?;
const pipeline = sprite_mod.state().pipelines.get(pipeline_id).?;
// Draw the sprite batch
const pass = engine.state.pass;
const pass = engine.state().pass;
const total_vertices = pipeline.num_sprites * 6;
pass.setPipeline(pipeline.render);
// TODO: remove dynamic offsets?

View file

@ -15,8 +15,11 @@ const vec4 = math.vec4;
const Mat3x3 = math.Mat3x3;
const Mat4x4 = math.Mat4x4;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
/// Internal state
pipelines: std.AutoArrayHashMapUnmanaged(u32, Pipeline),
pipelines: std.AutoArrayHashMapUnmanaged(u32, Pipeline) = .{},
allocator: std.mem.Allocator,
pub const name = .mach_gfx_text;
pub const Mod = mach.Mod(@This());
@ -198,17 +201,14 @@ pub const PipelineOptions = struct {
};
fn deinit(text_mod: *Mod) !void {
for (text_mod.state.pipelines.entries.items(.value)) |*pipeline| pipeline.deinit(text_mod.allocator);
text_mod.state.pipelines.deinit(text_mod.allocator);
for (text_mod.state().pipelines.entries.items(.value)) |*pipeline| pipeline.deinit(text_mod.state().allocator);
text_mod.state().pipelines.deinit(text_mod.state().allocator);
}
fn init(
text_mod: *Mod,
) !void {
text_mod.state = .{
// TODO: struct default value initializers don't work
.pipelines = .{},
};
fn init(text_mod: *Mod) void {
text_mod.init(.{
.allocator = gpa.allocator(),
});
}
fn initPipeline(
@ -216,11 +216,11 @@ fn initPipeline(
text_mod: *Mod,
opt: PipelineOptions,
) !void {
const device = engine.state.device;
const device = engine.state().device;
const pipeline = try text_mod.state.pipelines.getOrPut(engine.allocator, opt.pipeline);
const pipeline = try text_mod.state().pipelines.getOrPut(text_mod.state().allocator, opt.pipeline);
if (pipeline.found_existing) {
pipeline.value_ptr.*.deinit(engine.allocator);
pipeline.value_ptr.*.deinit(text_mod.state().allocator);
}
// Prepare texture for the font atlas.
@ -235,7 +235,7 @@ fn initPipeline(
},
});
const texture_atlas = try gfx.Atlas.init(
engine.allocator,
text_mod.state().allocator,
img_size.width,
.rgba,
);
@ -376,8 +376,8 @@ fn updated(
text_mod: *Mod,
pipeline_id: u32,
) !void {
const pipeline = text_mod.state.pipelines.getPtr(pipeline_id).?;
const device = engine.state.device;
const pipeline = text_mod.state().pipelines.getPtr(pipeline_id).?;
const device = engine.state().device;
// TODO: make sure these entities only belong to the given pipeline
// we need a better tagging mechanism
@ -425,7 +425,7 @@ fn updated(
_ = font_name; // TODO: actually use font name
const font_bytes = @import("font-assets").fira_sans_regular_ttf;
var font = try gfx.Font.initBytes(font_bytes);
defer font.deinit(engine.allocator);
defer font.deinit(text_mod.state().allocator);
const font_size = engine.entities.getComponent(style, .mach_gfx_text, .font_size).?;
const font_weight = engine.entities.getComponent(style, .mach_gfx_text, .font_weight);
@ -450,16 +450,16 @@ fn updated(
const codepoint = segment[glyph.cluster];
// TODO: use flags(?) to detect newline, or at least something more reliable?
if (codepoint != '\n') {
const region = try pipeline.regions.getOrPut(engine.allocator, .{
const region = try pipeline.regions.getOrPut(text_mod.state().allocator, .{
.index = glyph.glyph_index,
.size = @bitCast(font_size),
});
if (!region.found_existing) {
const rendered_glyph = try font.render(engine.allocator, glyph.glyph_index, .{
const rendered_glyph = try font.render(text_mod.state().allocator, glyph.glyph_index, .{
.font_size_px = run.font_size_px,
});
if (rendered_glyph.bitmap) |bitmap| {
var glyph_atlas_region = try pipeline.texture_atlas.reserve(engine.allocator, rendered_glyph.width, rendered_glyph.height);
var glyph_atlas_region = try pipeline.texture_atlas.reserve(text_mod.state().allocator, rendered_glyph.width, rendered_glyph.height);
pipeline.texture_atlas.set(glyph_atlas_region, @as([*]const u8, @ptrCast(bitmap.ptr))[0 .. bitmap.len * 4]);
texture_update = true;
@ -484,7 +484,7 @@ fn updated(
const r = region.value_ptr.*;
const size = vec2(@floatFromInt(r.width), @floatFromInt(r.height));
try glyphs.append(engine.allocator, .{
try glyphs.append(text_mod.state().allocator, .{
.pos = vec2(
origin_x + glyph.offset.x(),
origin_y - (size.y() - glyph.offset.y()),
@ -509,7 +509,7 @@ fn updated(
// TODO: could writeBuffer check for zero?
if (glyphs.items.len > 0) encoder.writeBuffer(pipeline.glyphs, 0, glyphs.items);
defer glyphs.deinit(engine.allocator);
defer glyphs.deinit(text_mod.state().allocator);
if (texture_update) {
// rgba32_pixels
// TODO: use proper texture dimensions here
@ -518,7 +518,7 @@ fn updated(
.bytes_per_row = @as(u32, @intCast(img_size.width * 4)),
.rows_per_image = @as(u32, @intCast(img_size.height)),
};
engine.state.queue.writeTexture(
engine.state().queue.writeTexture(
&.{ .texture = pipeline.texture },
&data_layout,
&img_size,
@ -529,7 +529,7 @@ fn updated(
var command = encoder.finish(null);
defer command.release();
engine.state.queue.submit(&[_]*gpu.CommandBuffer{command});
engine.state().queue.submit(&[_]*gpu.CommandBuffer{command});
}
fn preRender(
@ -537,7 +537,7 @@ fn preRender(
text_mod: *Mod,
pipeline_id: u32,
) !void {
const pipeline = text_mod.state.pipelines.get(pipeline_id).?;
const pipeline = text_mod.state().pipelines.get(pipeline_id).?;
// Update uniform buffer
const proj = Mat4x4.projection2D(.{
@ -557,7 +557,7 @@ fn preRender(
),
};
engine.state.encoder.writeBuffer(pipeline.uniforms, 0, &[_]Uniforms{uniforms});
engine.state().encoder.writeBuffer(pipeline.uniforms, 0, &[_]Uniforms{uniforms});
}
fn render(
@ -565,10 +565,10 @@ fn render(
text_mod: *Mod,
pipeline_id: u32,
) !void {
const pipeline = text_mod.state.pipelines.get(pipeline_id).?;
const pipeline = text_mod.state().pipelines.get(pipeline_id).?;
// Draw the text batch
const pass = engine.state.pass;
const pass = engine.state().pass;
const total_vertices = pipeline.num_glyphs * 6;
pass.setPipeline(pipeline.render);
// TODO: remove dynamic offsets?

View file

@ -4,6 +4,7 @@ const testing = @import("testing.zig");
const Entities = @import("ecs/entities.zig").Entities;
const EntityID = @import("ecs/entities.zig").EntityID;
const is_debug = @import("ecs/comptime.zig").is_debug;
// TODO: make sendToModule the default name for sending events? and sendGlobal always secondary? Or vice-versa?
@ -71,6 +72,16 @@ pub fn Modules(comptime modules: anytype) type {
errdefer m.args_queue.deinit(allocator);
errdefer m.events.deinit();
try m.events.ensureTotalCapacity(1024);
// Default initialize m.mod
inline for (@typeInfo(@TypeOf(m.mod)).Struct.fields) |field| {
const Mod2 = @TypeOf(@field(m.mod, field.name));
@field(m.mod, field.name) = Mod2{
.__is_initialized = false,
.__state = undefined,
.entities = &m.entities,
};
}
}
pub fn deinit(m: *@This(), allocator: std.mem.Allocator) void {
@ -99,6 +110,7 @@ pub fn Modules(comptime modules: anytype) type {
}
}
// TODO: docs
fn moduleToGlobalEvent(
comptime M: type,
comptime EventEnumM: anytype,
@ -106,9 +118,7 @@ pub fn Modules(comptime modules: anytype) type {
comptime event_name: EventEnumM(M),
) EventEnum(modules) {
for (@typeInfo(EventEnum(modules)).Enum.fields) |gfield| {
if (std.mem.eql(u8, @tagName(event_name), gfield.name)) {
return @enumFromInt(gfield.value);
}
if (std.mem.eql(u8, @tagName(event_name), gfield.name)) return @enumFromInt(gfield.value);
}
unreachable;
}
@ -118,12 +128,14 @@ pub fn Modules(comptime modules: anytype) type {
m: *@This(),
// TODO: is a variant of this function where event_name is not comptime known, but asserted to be a valid enum, useful?
comptime module_name: ModuleName(modules),
comptime event_name: GlobalEventEnumM(@TypeOf(@field(m.mod, @tagName(module_name)).state)),
args: GlobalArgsM(@TypeOf(@field(m.mod, @tagName(module_name)).state), event_name),
// TODO: cleanup comptime
comptime event_name: GlobalEventEnumM(@TypeOf(@field(m.mod, @tagName(module_name)).__state)),
args: GlobalArgsM(@TypeOf(@field(m.mod, @tagName(module_name)).__state), event_name),
) void {
// TODO: comptime safety/debugging
const event_name_g: GlobalEvent = comptime moduleToGlobalEvent(
@TypeOf(@field(m.mod, @tagName(module_name)).state),
// TODO: cleanup comptime
@TypeOf(@field(m.mod, @tagName(module_name)).__state),
GlobalEventEnumM,
GlobalEventEnum,
event_name,
@ -136,12 +148,14 @@ pub fn Modules(comptime modules: anytype) type {
m: *@This(),
// TODO: is a variant of this function where module_name/event_name is not comptime known, but asserted to be a valid enum, useful?
comptime module_name: ModuleName(modules),
comptime event_name: LocalEventEnumM(@TypeOf(@field(m.mod, @tagName(module_name)).state)),
args: LocalArgsM(@TypeOf(@field(m.mod, @tagName(module_name)).state), event_name),
// TODO: cleanup comptime
comptime event_name: LocalEventEnumM(@TypeOf(@field(m.mod, @tagName(module_name)).__state)),
args: LocalArgsM(@TypeOf(@field(m.mod, @tagName(module_name)).__state), event_name),
) void {
// TODO: comptime safety/debugging
const event_name_g: LocalEvent = comptime moduleToGlobalEvent(
@TypeOf(@field(m.mod, @tagName(module_name)).state),
// TODO: cleanup comptime
@TypeOf(@field(m.mod, @tagName(module_name)).__state),
LocalEventEnumM,
LocalEventEnum,
event_name,
@ -197,10 +211,6 @@ pub fn Modules(comptime modules: anytype) type {
inline for (@typeInfo(ModsByName(modules)).Struct.fields) |injectable_field| {
if (*injectable_field.type == field.type) {
@field(injectable, field.name) = &@field(m.mod, injectable_field.name);
// TODO: better module initialization location
@field(injectable, field.name).entities = &m.entities;
@field(injectable, field.name).allocator = m.entities.allocator;
continue :outer;
}
}
@ -344,26 +354,52 @@ pub fn ModsByName(comptime modules: anytype) type {
// Mod() -> Modules()
//
pub fn ModSet(comptime modules: anytype) type {
const NSComponents = ComponentTypesByName(modules);
return struct {
pub fn Mod(comptime M: anytype) type {
const module_tag = M.name;
const components = ComponentTypesM(M){};
return struct {
state: M,
entities: *Entities(NSComponents{}),
// TODO: eliminate this global allocator and/or rethink allocation strategies for modules
allocator: std.mem.Allocator,
entities: *Entities(ComponentTypesByName(modules){}),
/// Private/internal fields
__is_initialized: bool,
__state: M,
pub const IsInjectedArgument = void;
/// Initializes the module's state
pub inline fn init(m: *@This(), s: M) void {
m.__state = s;
m.__is_initialized = true;
}
/// Returns a mutable pointer to the module's state (literally the struct type of the module.)
///
/// A panic will occur if m.init(M{}) was not called previously.
pub inline fn state(m: *@This()) *M {
if (is_debug) if (!m.__is_initialized) @panic("mach: module ." ++ @tagName(M.name) ++ " state is not initialized, ensure foo_mod.init(.{}) is called!");
return &m.__state;
}
/// Returns a read-only version of the module's state. If an event handler is
/// read-only (i.e. only ever reads state/components/entities), then its events can
/// be skipped during e.g. record-and-replay of events from disk.
///
/// Only use this if the module state being serialized and deserialized after the
/// event handler runs would accurately reproduce the state of the event handler
/// being run.
pub inline fn stateReadOnly(m: *@This()) *const M {
if (is_debug) if (!m.__is_initialized) @panic("mach: module ." ++ @tagName(M.name) ++ " state is not initialized, ensure mod.init(.{}) is called!");
return &m.__state;
}
/// Returns a new entity.
pub fn newEntity(m: *@This()) !EntityID {
pub inline fn newEntity(m: *@This()) !EntityID {
return m.entities.new();
}
/// Removes an entity.
pub fn removeEntity(m: *@This(), entity: EntityID) !void {
pub inline fn removeEntity(m: *@This(), entity: EntityID) !void {
try m.entities.removeEntity(entity);
}