From 1a07a5388c18f4e7bb73d1d5bf72679b2231a186 Mon Sep 17 00:00:00 2001 From: Peterino2 Date: Sat, 24 Oct 2026 13:32:04 -0700 Subject: [PATCH] working on serializer format now --- README.md | 2 +- engine/lib/bh/build.zig | 6 +- engine/lib/p2/src/p2.zig | 7 +- engine/lib/p2/src/structures/bump-arena.zig | 8 ++- engine/lib/p2/src/structures/string-pool.zig | 2 +- engine/lib/p2/src/utils/shell.zig | 10 +-- engine/lib/slugger/src/slugger.zig | 76 ++++++++++++-------- engine/lib/slugger/src/sluggerformat.zig | 58 ++++++++++++++- engine/tools/interface-parser.zig | 2 +- 9 files changed, 124 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index fc08261..07c2867 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ -# Ribtech +# Riblab This is a chance to start completely clean and fresh, we will be building new game engine leveraging components diff --git a/engine/lib/bh/build.zig b/engine/lib/bh/build.zig index 730621f..656fd90 100644 --- a/engine/lib/bh/build.zig +++ b/engine/lib/bh/build.zig @@ -57,12 +57,12 @@ pub const Options = struct { box3d_validate: ?bool = null, }; -// standard set of options that all RibTech modules and dependenices shall use. +// standard set of options that all riblab modules and dependenices shall use. pub fn declareOptions(b: *std.Build) Options { return .{ .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}), - .monolithic = b.option(bool, "monolithic", "builds RibTech dependencies for static linking") orelse false, + .monolithic = b.option(bool, "monolithic", "builds RibLab dependencies for static linking") orelse false, .tracy = b.option(bool, "tracy", "builds with tracy support") orelse false, .renderer = b.option([]const u8, "renderer", "renderer backend: sgpu_main, gl_low_spec, headless") orelse "sgpu_main", .box3d_validate = b.option(bool, "box3d-validate", "enable heavy Box3D validation"), @@ -129,7 +129,7 @@ pub fn isEngineDependency(name: []const u8) bool { pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - const monolithic = b.option(bool, "monolithic", "builds RibTech dependencies for static linking") orelse false; + const monolithic = b.option(bool, "monolithic", "builds RibLab dependencies for static linking") orelse false; const r = MakeModlib(b, .{ .name = "bh", diff --git a/engine/lib/p2/src/p2.zig b/engine/lib/p2/src/p2.zig index 87a06b8..53f7900 100644 --- a/engine/lib/p2/src/p2.zig +++ b/engine/lib/p2/src/p2.zig @@ -186,7 +186,7 @@ test "multi-sparse-basic" { std.debug.print("handle2: {any}\n", .{testSet.get(sparseHandle2, .field1).?.*}); } -// As RibTech is primarily a playground for me to learn and practice programming, +// As RibLab is primarily a playground for me to learn and practice programming, // There will be some implementations of basic data structures. For fun ofc pub fn AppendToArrayListUnique(list: anytype, value: anytype) !void { for (list.items) |v| { @@ -374,17 +374,16 @@ test "managed ring queue uses stored io mutex" { } test "spin child process echo" { - const io = std.testing.io; { std.debug.print("spin child process\n", .{}); - const process = try shell.ShellProcess.init(std.testing.allocator, io, &.{ "echo", "lmao 2 nova" }); + const process = try shell.ShellProcess.init(std.testing.allocator, &.{ "echo", "lmao 2 nova" }); defer process.deinit(); std.debug.print("child process created: {any}\n", .{process.argv}); } { std.debug.print("spin child process 2\n", .{}); - const process = try shell.ShellProcess.initCmd(std.testing.allocator, io, "echo lmao2nova -target='lmao 3 nova'"); + const process = try shell.ShellProcess.initCmd(std.testing.allocator, "echo lmao2nova -target='lmao 3 nova'"); defer process.deinit(); std.debug.print("{any}\n", .{process.argv}); } diff --git a/engine/lib/p2/src/structures/bump-arena.zig b/engine/lib/p2/src/structures/bump-arena.zig index 7c7f47e..80b8a2f 100644 --- a/engine/lib/p2/src/structures/bump-arena.zig +++ b/engine/lib/p2/src/structures/bump-arena.zig @@ -1,7 +1,8 @@ const std = @import("std"); const stats = @import("stats.zig"); -// fast bump-only allocator, not threadsafe. see BumpArenaThreaded for the mutex based version. +// fast bump-only allocator with checkpoints, not threadsafe. for a threadsafe arena +// use std.heap.ArenaAllocator. // // memory comes from a linked list of blocks taken from the backing allocator. // blocks are never returned to the backing allocator until reset(.free_all) or @@ -256,6 +257,7 @@ pub const BumpCheckpoint = struct { // mutex based, threadsafe BumpArenaAdvanced. does not support checkpoints, // rewinding would release other threads' allocations. +/// Deprecated: use std.heap.ArenaAllocator, its allocator is lock-free and threadsafe. pub const BumpArenaThreaded = struct { arena: BumpArenaAdvanced, io_context: std.Io, @@ -321,12 +323,12 @@ pub const BumpArenaThreaded = struct { }; test "bump-it-uppp" { - var arena = BumpArenaThreaded.init(std.testing.allocator, std.testing.io); + var arena = BumpArenaAdvanced.init(std.testing.allocator); defer arena.deinit(); } test "reset clears usage" { - var arena = BumpArenaThreaded.init(std.testing.allocator, std.testing.io); + var arena = BumpArenaAdvanced.init(std.testing.allocator); defer arena.deinit(); const allocator = arena.allocator(); diff --git a/engine/lib/p2/src/structures/string-pool.zig b/engine/lib/p2/src/structures/string-pool.zig index ff17fcc..fc65f16 100644 --- a/engine/lib/p2/src/structures/string-pool.zig +++ b/engine/lib/p2/src/structures/string-pool.zig @@ -648,7 +648,7 @@ test "concatSlice" { const joined = try left.concatSlice("tech"); defer joined.drop(); - try std.testing.expectEqualStrings("ribtech", joined.getUtf8()); + try std.testing.expectEqualStrings("riblab", joined.getUtf8()); try std.testing.expectEqualStrings("rib", left.getUtf8()); } diff --git a/engine/lib/p2/src/utils/shell.zig b/engine/lib/p2/src/utils/shell.zig index 26bec36..08e4a41 100644 --- a/engine/lib/p2/src/utils/shell.zig +++ b/engine/lib/p2/src/utils/shell.zig @@ -6,14 +6,14 @@ pub const ShellProcess = struct { argv: []const []const u8 = undefined, ownedArgs: ?[][]u8 = null, - stringArena: p2.BumpArenaThreaded = undefined, + stringArena: std.heap.ArenaAllocator = undefined, // initialize the shellprocess from a windows cmd string - pub fn initCmd(alloc: std.mem.Allocator, io: std.Io, cmd: []const u8) !*@This() { + pub fn initCmd(alloc: std.mem.Allocator, cmd: []const u8) !*@This() { const self = try alloc.create(@This()); self.* = .{ .backingAllocator = alloc, - .stringArena = p2.BumpArenaThreaded.init(alloc, io), + .stringArena = .init(alloc), }; try self.splitArgsFromCmd(cmd); @@ -21,11 +21,11 @@ pub const ShellProcess = struct { return self; } - pub fn init(alloc: std.mem.Allocator, io: std.Io, argv: []const []const u8) !*@This() { + pub fn init(alloc: std.mem.Allocator, argv: []const []const u8) !*@This() { const self = try alloc.create(@This()); self.* = .{ .backingAllocator = alloc, - .stringArena = p2.BumpArenaThreaded.init(alloc, io), + .stringArena = .init(alloc), }; try self.setArgsOwned(argv); diff --git a/engine/lib/slugger/src/slugger.zig b/engine/lib/slugger/src/slugger.zig index 5dbbb42..2a4b322 100644 --- a/engine/lib/slugger/src/slugger.zig +++ b/engine/lib/slugger/src/slugger.zig @@ -351,17 +351,16 @@ pub const LogMem = struct { start_utc_time: std.Io.Clock.Timestamp = undefined, // Consumer-owned registries; producers only reference static descriptors. - logMap: std.AutoHashMapUnmanaged(*const LogSite, u32) = .empty, - loggerStates: std.AutoHashMapUnmanaged(*const LoggerState, u32) = .empty, - loggerStatesById: std.ArrayList(*const LoggerState) = .empty, - logSites: std.ArrayList(LogSite) = .empty, + logSitesByPtr: std.AutoHashMapUnmanaged(*const LogSite, u32) = .empty, + logSites: std.ArrayList(*const LogSite) = .empty, + loggersByPtr: std.AutoHashMapUnmanaged(*const LoggerState, u32) = .empty, + loggers: std.ArrayList(*const LoggerState) = .empty, + + // Entries and their payloads are owned by whoever filled them, e.g. the + // logger system's flush arena or a LogMemFile's arena. entries: std.ArrayList(StructuredLog) = .empty, - pub fn deinit(self: *@This(), payload_allocator: std.mem.Allocator) void { - for (self.entries.items) |entry| payload_allocator.free(entry.serialized_args); - } - pub fn init(self: *@This(), io: std.Io) void { self.start_time = .now(io, .awake); self.start_utc_time = .now(io, .real); @@ -381,26 +380,30 @@ pub const LogMem = struct { } fn getOrRegisterSite(self: *@This(), allocator: std.mem.Allocator, site: *const LogSite) !u32 { - if (self.logMap.get(site)) |id| return id; + if (self.loggerSitesBy.get(site)) |id| return id; - try self.logMap.ensureUnusedCapacity(allocator, 1); + try self.logSitesByPtr.ensureUnusedCapacity(allocator, 1); try self.logSites.ensureUnusedCapacity(allocator, 1); const id = std.math.cast(u32, self.logSites.items.len) orelse return error.TooManySites; // Site metadata is static; hot-reloaded modules remain loaded. - self.logSites.appendAssumeCapacity(site.*); - self.logMap.putAssumeCapacity(site, id); + self.logSites.appendAssumeCapacity(site); + self.logSitesByPtr.putAssumeCapacity(site, id); return id; } - fn accept(self: *@This(), allocator: std.mem.Allocator, pending: PendingLog) !StructuredLog { + /// Registers the event's logger and site in `registry` and copies its payload + /// into `payloads`. The caller still owns `pending.serialized_args`. + fn accept(self: *@This(), registry: std.mem.Allocator, payloads: std.mem.Allocator, pending: PendingLog) !StructuredLog { + const loggerId = try self.getOrRegisterLoggerState(registry, pending.logger); + const sourceId = try self.getOrRegisterSite(registry, pending.site); return .{ - .serialized_args = pending.serialized_args, + .serialized_args = try payloads.dupe(u8, pending.serialized_args), .verbosity = pending.verbosity, .usSinceStart = pending.usSinceStart, - .loggerId = try self.getOrRegisterLoggerState(allocator, pending.logger), - .sourceId = try self.getOrRegisterSite(allocator, pending.site), + .loggerId = loggerId, + .sourceId = sourceId, }; } }; @@ -414,7 +417,10 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type { stdout_file_writer: std.Io.File.Writer = undefined, stdout_writer: *std.Io.Writer = undefined, io: std.Io = undefined, + // Registries and writers; lives until deinit. arena: std.heap.ArenaAllocator = undefined, + // Drained entries and their payloads; dropped all at once by resetFlushArena. + flushArena: std.heap.ArenaAllocator = undefined, backing: std.mem.Allocator = undefined, payload_allocator: std.mem.Allocator = undefined, queue_buffer: []PendingLog = undefined, @@ -496,7 +502,7 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type { var count: usize = 0; while (count < self.queue_buffer.len) : (count += 1) { - try self.mem.entries.ensureUnusedCapacity(self.arena.allocator(), 1); + try self.mem.entries.ensureUnusedCapacity(self.flushArena.allocator(), 1); var pending: [1]PendingLog = undefined; const n = self.queue.getUncancelable(self.io, &pending, 0) catch |err| switch (err) { error.Closed => break, @@ -505,9 +511,10 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type { if (n == 0) break; const entry = pending[0]; - // If registration fails, this dequeued payload must still be freed. - const log = self.mem.accept(self.arena.allocator(), entry) catch |err| { - self.payload_allocator.free(entry.serialized_args); + // The payload is copied into the flush arena, so the producer's + // copy is freed whether or not accept succeeds. + defer self.payload_allocator.free(entry.serialized_args); + const log = self.mem.accept(self.arena.allocator(), self.flushArena.allocator(), entry) catch |err| { _ = self.dropped.fetchAdd(1, .monotonic); return err; }; @@ -528,6 +535,15 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type { return count; } + /// Drops every drained entry and its payload, starting a new generation. + /// Write entries out first if they should be kept. Invalidates every + /// StructuredLog drained so far; registries are kept. + pub fn resetFlushArena(self: *@This()) void { + self.mem.entries = .empty; + _ = self.flushArena.reset(.retain_capacity); + self.stats.bytesUsed = 0; + } + /// Stop accepting events. Already queued events can still be drained. pub fn close(self: *@This()) void { self.queue.close(self.io); @@ -541,7 +557,8 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type { @panic("Check failed"); } - /// Producer allocations must be thread-safe, independently of the consumer arena. + /// `payload_allocator` must be thread-safe and free in any order: producers + /// allocate payloads, the consumer frees each one as soon as it is drained. pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator, payload_allocator: std.mem.Allocator) void { check(options.queue_capacity >= 64, "queue capacity abnormally small {d}", .{options.queue_capacity}); check(options.queue_capacity <= 10000, "queue capacity abnormally large {d}", .{options.queue_capacity}); @@ -552,6 +569,7 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type { self.backing = allocator; self.payload_allocator = payload_allocator; self.arena = std.heap.ArenaAllocator.init(allocator); + self.flushArena = std.heap.ArenaAllocator.init(allocator); self.queue_buffer = allocator.alloc(PendingLog, options.queue_capacity) catch { std.debug.print("queue_buffer_alloc failed {d}", .{options.queue_capacity}); @panic("Check failed"); @@ -562,7 +580,7 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type { self.mem.init(io); } - /// Producers must have finished. Frees both drained and undrained payloads. + /// Producers must have finished. Frees undrained payloads and the flush arena. pub fn deinit(self: *@This()) void { self.close(); var pending: [16]PendingLog = undefined; @@ -571,8 +589,8 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type { if (n == 0) break; for (pending[0..n]) |entry| self.payload_allocator.free(entry.serialized_args); } - self.mem.deinit(self.payload_allocator); self.backing.free(self.queue_buffer); + self.flushArena.deinit(); self.arena.deinit(); } }; @@ -644,7 +662,6 @@ pub const LogRef = struct { pub const LoggerState = struct { name: []const u8, verbosity: std.atomic.Value(Verbosity), - stdout: bool = false, // mirrors it's output to stdout }; pub const LoggerOptions = struct { @@ -992,7 +1009,6 @@ pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptio pub var loggerState: LoggerState = .{ .name = LoggerName, .verbosity = .init(opts.verbosity), - .stdout = opts.has_stdout, }; pub fn setVerbosity(v: Verbosity) void { @@ -1217,9 +1233,13 @@ test "testing" { defer y.deinit(std.testing.allocator); std.debug.print("log>\n{s}\nlength={d}\nbytesUsed={d}\n", .{ y.items, y.items.len, gLoggerSystem.stats.bytesUsed }); - var serializer: sluggerformat.LogMemSerializer = undefined; - try serializer.init(std.testing.io, std.testing.allocator, &gLoggerSystem.mem, .write); - defer serializer.deinit(); + // testing serializer + { + var serializer: sluggerformat.LogMemSerializer = undefined; + try serializer.init(std.testing.io, std.testing.allocator, &gLoggerSystem.mem, .write); + defer serializer.deinit(); + try serializer.populateForWrite(); + } } pub const sluggerformat = @import("sluggerformat.zig"); diff --git a/engine/lib/slugger/src/sluggerformat.zig b/engine/lib/slugger/src/sluggerformat.zig index b45c6c4..9285aa9 100644 --- a/engine/lib/slugger/src/sluggerformat.zig +++ b/engine/lib/slugger/src/sluggerformat.zig @@ -60,6 +60,12 @@ pub const LogMemSerializer = struct { logSitesByPtr: std.AutoHashMapUnmanaged(*LogSite, u32) = .empty, logSites: std.ArrayList(*LogSite) = .empty, + loggersByPtr: std.AutoHashMapUnmanaged(*LoggerState, u32) = .empty, + loggers: std.ArrayList(*LoggerState) = .empty, + + enumListByPtr: std.ArrayList(*EnumEntry, u32) = .empty, + enumList: std.ArrayList(EnumEntry) = .empty, + io: std.Io, pub const Mode = enum { @@ -77,16 +83,65 @@ pub const LogMemSerializer = struct { }; } - pub fn addOrRegisterLogSite(self: *@This(), logSite: *LogSite) !u32 { + pub fn populateForWrite(self: *@This()) !void { + // will do this oppurtunistically later + for (self.mem.logSites.items) |logSite| { + _ = try self.addOrRegisterLogSite(logSite); + } + + for (self.mem.loggerStatesById.items) |loggerState| { + _ = try self.addOrRegisterLogger(loggerState); + } + + for (self.mem.) + } + + pub fn addOrRegisterEnumEntry(self: *@This(), state: *const EnumEntry) !u32 + { + } + + pub fn addOrRegisterLogger(self: *@This(), state: *const LoggerState) !u32 { + if (self.mode == .read) + return error.ReadOnlySerializer; + + try self.logSitesByPtr.ensureUnusedCapacity(self.backing, 1); + try self..ensureUnusedCapacity(self.backing, 1); + + const allocator = self.arena.allocator(); + const newState = try allocator.create(LoggerState); + + newState.* = .{ + .verbosity = state.verbosity.load(.monotonic), + .name = try allocator.dupe(u8, state.name), + }; + + const id: u32 = @intCast(self.loggers.items.len); + self.loggersByPtr.putAssumeCapacity(self.backing, state, id); + self.loggers.appendAssumeCapacity(self.backing, state, id); + + return id; + } + + pub fn addOrRegisterLogSite(self: *@This(), logSite: *const LogSite) !u32 { if (self.mode == .read) return error.ReadOnlySerializer; const allocator = self.arena.allocator(); const newSite = try allocator.create(LogSite); try deepCopyLogSite(allocator, logSite, newSite); + + const id: u32 = @intCast(self.logSites.items.len); + self.logSitesByPtr.putAssumeCapacity(self.backing, newSite, id); + self.logSites.appendAssumeCapacity(self.backing, newSite); + + return id; } pub fn deinit(self: *@This()) void { + self.logSites.deinit(self.backing); + self.logSitesByPtr.deinit(self.backing); + self.loggers.deinit(self.backing); + self.loggersByPtr.deinit(self.backing); self.arena.deinit(); } }; @@ -100,6 +155,7 @@ const EnumTable = slugger.EnumTable; const EnumEntry = slugger.EnumEntry; const ArgsDecoderOp = slugger.ArgsDecoderOp; const RenderOp = slugger.RenderOp; +const LoggerSystem = slugger.LoggerSystem; const LogMem = slugger.LogMem; const p2 = @import("p2"); diff --git a/engine/tools/interface-parser.zig b/engine/tools/interface-parser.zig index a817c24..6c72515 100644 --- a/engine/tools/interface-parser.zig +++ b/engine/tools/interface-parser.zig @@ -1,4 +1,4 @@ -// this thing eats a ribtech top level zig file and generates a C header +// this thing eats a riblab top level zig file and generates a C header pub fn main(init: std.process.Init) !void { const args = init.minimal.args;