added hot reloading mechanisms

This commit is contained in:
Peterino 2026-11-23 18:33:49 -07:00
parent 8c9c158415
commit a654f8d302
11 changed files with 506 additions and 34 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
archive/ archive/
.zig-cache/ .zig-cache/
zig-out/ zig-out/
.modulecache/

View File

@ -1,10 +1,13 @@
const std = @import("std"); const std = @import("std");
const program = @import("build/programs.zig");
pub fn build(b: *std.Build) void { pub fn build(b: *std.Build) void {
const optimize = b.standardOptimizeOption(.{}); const optimize = b.standardOptimizeOption(.{});
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
const slugger = b.dependency("slugger", .{ .target = target, .optimize = optimize }); const slugger = b.dependency("slugger", .{ .target = target, .optimize = optimize });
const p2 = b.dependency("p2", .{ .target = target, .optimize = optimize });
const xxd = b.dependency("xxd", .{ .target = target, .optimize = optimize });
const core = b.addModule("core", .{ const core = b.addModule("core", .{
.root_source_file = b.path("src/core/core.zig"), .root_source_file = b.path("src/core/core.zig"),
@ -12,6 +15,8 @@ pub fn build(b: *std.Build) void {
.optimize = optimize, .optimize = optimize,
.imports = &.{.{ .name = "slugger", .module = slugger.module("slugger") }}, .imports = &.{.{ .name = "slugger", .module = slugger.module("slugger") }},
}); });
core.addImport("p2", p2.module("p2"));
core.addImport("xxd", xxd.module("xxd"));
const core_tests = b.addTest(.{ .root_module = core }); const core_tests = b.addTest(.{ .root_module = core });
b.step("test", "Run core tests").dependOn(&b.addRunArtifact(core_tests).step); b.step("test", "Run core tests").dependOn(&b.addRunArtifact(core_tests).step);
@ -59,4 +64,50 @@ pub fn build(b: *std.Build) void {
build_tools.dependOn(&install.step); build_tools.dependOn(&install.step);
} }
// create a small program
// this will contain two parts
// 1. the 'engine' once it goes up it creates several engine objects including the engine
// itself and it constructs api structs for programs to consume
//
// 2. the 'program' hot reloadable dynamic library.
// links nothing but the interfaces provided by the 'engine'
//
// and exports it's own interfaces to the engine. engine calls it's 'entry point'
{
const exe = b.addExecutable(.{ .name = "testmain", .root_module = b.createModule(.{
.optimize = optimize,
.target = target,
.root_source_file = b.path("src/main.zig"),
}) });
b.installArtifact(exe);
exe.root_module.addImport("core", core);
const testmain = b.addRunArtifact(exe);
testmain.addArg("--cli-test");
testmain.step.dependOn(b.getInstallStep());
b.step("run-testmain", "testing the testmain").dependOn(&testmain.step);
// now that we've built main it's time to build a hot library
const hotlib = b.addLibrary(.{
.name = "game",
.root_module = b.createModule(.{
.optimize = optimize,
.target = target,
.root_source_file = b.path("programs/sample-program.zig"),
}),
.linkage = .dynamic, // todo static builds
});
const inst = b.addInstallArtifact(hotlib, .{
.dest_sub_path = b.fmt("{s}.pod{s}", .{
"game",
target.result.dynamicLibSuffix(),
}),
.dest_dir = .{ .override = .{
.custom = "pods",
} },
});
b.getInstallStep().dependOn(&inst.step);
}
} }

View File

@ -4,9 +4,10 @@
.version = "0.0.0", .version = "0.0.0",
.minimum_zig_version = "0.17.0", .minimum_zig_version = "0.17.0",
.dependencies = .{ .dependencies = .{
.slugger = .{ .path = "lib/slugger" }, .slugger = .{ .path = "pkg/slugger" },
.p2 = .{ .path = "lib/p2" }, .p2 = .{ .path = "pkg/p2" },
.lz4 = .{ .path = "lib/lz4" }, .lz4 = .{ .path = "pkg/lz4" },
.xxd = .{ .path = "pkg/xxd" },
}, },
.paths = .{ "build.zig", "build.zig.zon", "src", "lib", "tools", "programs" }, .paths = .{ "build.zig", "build.zig.zon", "src", "lib", "tools", "programs" },
} }

View File

@ -9,10 +9,7 @@ pub const BumpArenaAdvanced = @import("structures/bump-arena.zig").BumpArenaAdva
pub const BumpCheckpoint = @import("structures/bump-arena.zig").BumpCheckpoint; pub const BumpCheckpoint = @import("structures/bump-arena.zig").BumpCheckpoint;
pub const pscopes = @import("structures/pscopes.zig"); pub const pscopes = @import("structures/pscopes.zig");
pub const ScopesContext = pscopes.ScopesContext;
pub const xxd = @import("structures/xxd.zig");
pub const xxdWrite = xxd.xxdWrite;
const ArrayList = std.ArrayList; const ArrayList = std.ArrayList;
const ArrayListUnmanaged = std.ArrayListUnmanaged; const ArrayListUnmanaged = std.ArrayListUnmanaged;
@ -78,7 +75,6 @@ pub fn sharedLibNameAlloc(allocator: std.mem.Allocator, s: []const u8) ![]u8 {
} }
comptime { comptime {
std.testing.refAllDecls(xxd);
std.testing.refAllDecls(ring_queue); std.testing.refAllDecls(ring_queue);
std.testing.refAllDecls(index_pool); std.testing.refAllDecls(index_pool);
std.testing.refAllDecls(concurrent_queue); std.testing.refAllDecls(concurrent_queue);

View File

@ -262,6 +262,7 @@ pub fn xxdWrite(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions)
addr += stride; addr += stride;
} }
} }
inline fn writeByteAsHex2(byte: u8, writer: *std.Io.Writer, lower: bool) std.Io.Writer.Error!void { inline fn writeByteAsHex2(byte: u8, writer: *std.Io.Writer, lower: bool) std.Io.Writer.Error!void {
const digits = if (lower) "0123456789abcdef" else "0123456789ABCDEF"; const digits = if (lower) "0123456789abcdef" else "0123456789ABCDEF";
try writer.writeAll(&.{ digits[byte >> 4], digits[byte & 0xf] }); try writer.writeAll(&.{ digits[byte >> 4], digits[byte & 0xf] });

View File

@ -0,0 +1,49 @@
const std = @import("std");
//req: lets discuss- wh
// hand bombed zig version of the api
pub const Verbosity = enum(c_int) {
verbose,
info,
warn,
err,
};
/// desc: a thing representing a zig slice
pub const Slice = extern struct {
ptr: [*c]const u8,
len: usize,
pub fn make(s: []const u8) @This() {
return .{ .ptr = s.ptr, .len = s.len };
}
pub fn bytes(self: @This()) []const u8 {
var s: []const u8 = undefined;
s.len = self.len;
s.ptr = @ptrCast(self.ptr);
return s;
}
};
const expected_version: u32 = 0;
const core_api = extern struct {
version: u32,
get_engine: *const fn () callconv(.c) ?*anyopaque,
get_tag_registry: *const fn () callconv(.c) ?*anyopaque,
start: *const fn () callconv(.c) void,
shutdown: *const fn () callconv(.c) void,
declare_logging_category: *const fn (name: Slice, default_verbosity: Verbosity) callconv(.c) u32,
log_puts: *const fn (category: u32, verbosity: Verbosity, string: Slice) callconv(.c) void,
};
var core: *core_api = undefined;
// -- end of handbomb
pub export fn entrypoint(_core: *core_api) callconv(.c) i32 {
core = _core;
const category = core.declare_logging_category(Slice.make("test"), .warn);
core.log_puts(category, .info, Slice.make("lmao 2 nova"));
return 0;
}

View File

@ -4,17 +4,33 @@
// - snake_case for functions intended to be exported to the api // - snake_case for functions intended to be exported to the api
// //
// a file like core.zig (this file) exists so we can generate a c api from it later. // a file like core.zig (this file) exists so we can generate a c api from it later.
//
// some notes about the c api generation
//
// /// 3 comment slashes are used to denote that it is
/// General verbosity level of logging
pub const Verbosity = enum(c_int) {
verbose,
info,
warn,
err,
pub fn toString(self: @This()) []const u8 {
return @tagName(self);
}
};
/// desc: a thing representing a zig slice /// desc: a thing representing a zig slice
pub const Slice = extern struct { pub const SliceMutable = extern struct {
ptr: [*c]u8, ptr: [*c]u8,
len: usize, len: usize,
pub fn fromZ(s: []const u8) @This() { pub fn make(s: []const u8) @This() {
return .{ .ptr = s.ptr, .len = s.len }; return .{ .ptr = s.ptr, .len = s.len };
} }
pub fn toSlice(self: @This()) []u8 { pub fn bytes(self: @This()) []u8 {
var s: []u8 = undefined; var s: []u8 = undefined;
s.len = self.len; s.len = self.len;
s.ptr = @ptrCast(self.ptr); s.ptr = @ptrCast(self.ptr);
@ -22,6 +38,23 @@ pub const Slice = extern struct {
} }
}; };
/// desc: a thing representing a zig slice
pub const Slice = extern struct {
ptr: [*c]const u8,
len: usize,
pub fn make(s: []const u8) @This() {
return .{ .ptr = s.ptr, .len = s.len };
}
pub fn bytes(self: @This()) []const u8 {
var s: []const u8 = undefined;
s.len = self.len;
s.ptr = @ptrCast(self.ptr);
return s;
}
};
/// desc: gets a pointer to the actual engine instance /// desc: gets a pointer to the actual engine instance
/// ///
/// this will be used by dynamically loaded modules discover and register functionality /// this will be used by dynamically loaded modules discover and register functionality
@ -35,7 +68,9 @@ pub export fn get_tag_registry() callconv(.c) ?*anyopaque {
return null; return null;
} }
pub export fn core_start() callconv(.c) void { pub export fn start() callconv(.c) void {
// eng.init();
//
// const eng = engine.get(); // const eng = engine.get();
// const io = eng.io; // const io = eng.io;
// const allocator = eng.systemAllocator; // const allocator = eng.systemAllocator;
@ -43,35 +78,96 @@ pub export fn core_start() callconv(.c) void {
// _ = allocator; // _ = allocator;
} }
pub export fn core_declare_logging_category(name: [*c]u8, default_verbosity: Verbosity) void { pub export fn declare_logging_category(name: Slice, default_verbosity: Verbosity) callconv(.c) u32 {
_ = name; println("logging category defined: {s} default verbosity: {s}", .{ name.bytes(), @tagName(default_verbosity) });
_ = default_verbosity; return 0;
} }
pub const Verbosity = enum(c_int) { var writeBuffer: [4096]u8 = undefined;
verbose, var fwriter: std.Io.File.Writer = undefined;
info,
warn, pub fn setupPrint(io: std.Io) void {
err, fwriter = std.Io.File.stdout().writer(io, &writeBuffer);
}; }
pub fn println(comptime fmt: []const u8, args: anytype) void {
fwriter.interface.print(fmt ++ "\n", args) catch return;
fwriter.interface.flush() catch {};
}
/// desc: pushes a string to the logging system /// desc: pushes a string to the logging system
pub export fn core_log_puts(category: u32, verbosity: Verbosity, string: [*c]u8) callconv(.c) void { pub export fn log_puts(category: u32, verbosity: Verbosity, string: Slice) callconv(.c) void {
_ = category; _ = category;
_ = verbosity; // using this for now.
_ = string; println("[{s:>6}][{s:>4}]: {s}", .{ "debug", verbosity.toString(), string.bytes() });
} }
pub export fn core_shutdown() callconv(.c) void {} pub export fn shutdown() callconv(.c) void {
engine.gEngine.deinit();
}
pub const core_api = extern struct {
version: u32,
get_engine: *const fn () callconv(.c) ?*anyopaque,
get_tag_registry: *const fn () callconv(.c) ?*anyopaque,
start: *const fn () callconv(.c) void,
shutdown: *const fn () callconv(.c) void,
declare_logging_category: *const fn (name: Slice, default_verbosity: Verbosity) callconv(.c) u32,
log_puts: *const fn (category: u32, verbosity: Verbosity, string: Slice) callconv(.c) void,
};
pub var gApi: core_api = undefined;
// non exported functions below here, used by the zig runtime. // non exported functions below here, used by the zig runtime.
pub fn startEngine(io: std.Io, systemAllocator: std.mem.Allocator) void { // get minimal from juicymain's init.minimal
pub fn startEngine(io: std.Io, systemAllocator: std.mem.Allocator, minimal: std.process.Init.Minimal) !void {
// create the engine registry // create the engine registry
engine.initialize(io, systemAllocator); try engine.gEngine.init(io, systemAllocator, minimal);
gApi = .{
.version = 0, // these really won't matter until much later.
.shutdown = shutdown,
.get_engine = get_engine,
.get_tag_registry = get_tag_registry,
.start = start,
.declare_logging_category = declare_logging_category,
.log_puts = log_puts,
};
} }
const engine = @import("engine.zig"); pub fn getEngine() *engine.Engine {
return &engine.gEngine;
}
pub const SmallString = extern struct {
buffer: [64]u8,
len: u8,
pub fn bytes(self: *const @This()) []const u8 {
return self.buffer[0..self.len];
}
pub fn fmt(comptime format: []const u8, args: anytype) !@This() {
var s: @This() = undefined;
const x = try std.fmt.bufPrint(&s.buffer, format, args);
s.len = @intCast(x.len);
return s;
}
};
pub const TinyString = extern struct {
buffer: [32]u8,
len: u8,
pub inline fn bytes(self: *const @This()) []const u8 {
return self.buffer[0..self.len];
}
pub inline fn fmt(comptime format: []const u8, args: anytype) !@This() {
var s: @This() = undefined;
const x = try std.fmt.bufPrint(&s.buffer, format, args);
s.len = @intCast(x.len);
return s;
}
};
pub const engine = @import("engine.zig");
pub const slugger = @import("slugger"); pub const slugger = @import("slugger");
pub const p2 = @import("p2"); pub const p2 = @import("p2");
pub const DeclareTagPool = p2.DeclareTagPool;
const std = @import("std"); const std = @import("std");

View File

@ -15,10 +15,53 @@
// modify and tear down systems for modification // modify and tear down systems for modification
pub const Engine = struct { pub const Engine = struct {
io: std.Io, io: std.Io,
scopes: *p2.ScopesContext,
backing: std.mem.Allocator,
safe: std.heap.SafeAllocator, // safe validating allocator for most things.
arena: std.heap.ArenaAllocator, // TODO [assign tags]: build a memory profiling tracker that wraps this one
engineObjects: std.ArrayList(EngineObject) = .empty,
// engineObjects: std.ArrayList(EngineObjectRef), lastFrameStampNs: i96,
dt: f64 = 0,
minimal: std.process.Init.Minimal,
frameCount: u64 = 0,
// incomming allocator must be threadsafe
pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator, minimal: std.process.Init.Minimal) !void {
self.* = .{
.io = io,
.backing = allocator,
.minimal = minimal,
.arena = std.heap.ArenaAllocator.init(allocator),
.safe = std.heap.SafeAllocator.init(allocator, .{
.stack_trace_frames = 20,
}),
.scopes = undefined,
.lastFrameStampNs = std.Io.Clock.Timestamp.now(io, .awake).raw.nanoseconds,
};
self.scopes = try .create(self.safe.allocator(), io);
}
pub fn tick(self: *@This()) void {
const newTime = std.Io.Clock.Timestamp.now(self.io, .awake);
const delta = newTime.raw.nanoseconds - self.lastFrameStampNs;
self.lastFrameStampNs = newTime.raw.nanoseconds;
self.dt = @as(f64, @floatFromInt(delta)) / 1e9;
std.debug.print("frame: {} deltaTime: {}\n", .{ self.frameCount, self.dt });
self.frameCount += 1;
}
pub fn deinit(self: *@This()) void {
self.scopes.destroy();
self.arena.deinit();
_ = self.safe.deinitLog(true);
}
}; };
const EngineObjectRef = struct {}; pub var gEngine: Engine = undefined;
const EngineObject = @import("types/EngineObject.zig");
const std = @import("std"); const std = @import("std");
const p2 = @import("p2");

View File

@ -1,5 +1,13 @@
ptr: *anyopaque, ptr: *anyopaque,
interface: *EngineObjectInterface,
name: TagPool.Tag, name: TagPool.Tag,
const EngineObjectInterface = extern struct {
init: *const fn (*anyopaque, *EngineContext) callconv(.c) bool,
deinit: *const fn (*anyopaque) callconv(.c) void,
};
const EngineContext = opaque {};
const TagPool = core.DeclareTagPool("EngineObject"); const TagPool = core.DeclareTagPool("EngineObject");
const core = @import("../core.zig"); const core = @import("../core.zig");

223
engine/src/main.zig Normal file
View File

@ -0,0 +1,223 @@
fn ensureInputTxt(io: std.Io) !void {
const cwd = std.Io.Dir.cwd();
const fpath = try cwd.createDirPathOpen(io, "zig-out", .{});
const s = fpath.statFile(io, "input.txt", .{}) catch {
_ = try fpath.createFile(io, "input.txt", .{});
return;
};
_ = s;
}
pub fn main(init: std.process.Init) !void {
const io = init.io;
const allocator = std.heap.page_allocator;
// engine level initialization
try core.startEngine(io, allocator, init.minimal);
defer core.shutdown();
core.setupPrint(io);
println("press h or 'help' for help \n> ", .{});
var cliTest: bool = false;
for (init.minimal.args.vector) |a| {
if (std.mem.startsWith(u8, std.mem.span(a), "--cli-test")) cliTest = true;
}
var readBuffer: [4096]u8 = undefined;
var openedFile: ?std.Io.File = null;
const f = f: {
if (!cliTest) {
break :f std.Io.File.stdin();
}
try ensureInputTxt(io);
openedFile = try std.Io.Dir.cwd().openFile(io, "zig-out/input.txt", .{});
break :f openedFile.?;
};
var freader = f.reader(io, &readBuffer);
var r = &freader.interface;
loadedFingerPrints = .init(init.arena.allocator());
loop: while (true) {
const l = try r.takeDelimiter('\n') orelse continue;
const line = std.mem.trim(u8, l, "\n ");
core.engine.gEngine.tick();
if (line.len > 0) {
if (Command.parse(line)) |c| {
if (mem.eql(u8, c.name, "quit")) {
break :loop;
} else if (mem.eql(u8, c.name, "help")) {
usage();
} else if (c.func) |func| {
const args = blk: {
const x = std.mem.cutScalar(u8, line, ' ') orelse break :blk "";
break :blk x[1];
};
const result = func(args);
if (result != 0)
println("Error! code: {d}", .{result});
}
} else {
println("Error! unknown command {s}", .{line});
usage();
}
}
if (cliTest and core.engine.gEngine.frameCount == 10)
break :loop;
println("> ", .{});
}
}
const commands = [_]Command{
.{
.name = "quit",
.desc = "exits the engine",
},
.{
.name = "help",
.desc = "prints this help dialogue",
},
.{
.name = "list",
.desc = "lists available pods for hot reloading (default; searches zig-out/pods)",
.func = listPods,
},
.{
.name = "load",
.desc = "loads the selected pod by name",
.func = loadPod,
},
};
const Command = struct {
name: []const u8,
desc: []const u8,
func: ?*const fn (line: []const u8) i32 = null,
pub fn parse(line: []const u8) ?*const @This() {
for (&commands) |*cmd| {
if (checkCommand(line, cmd.name)) {
return cmd;
}
}
return null;
}
};
fn usage() void {
for (commands) |cmd| {
println("{s}/{s} - {s}", .{ cmd.name, cmd.name[0..1], cmd.desc });
}
}
fn checkCommand(line: []const u8, arg: []const u8) bool {
const startsWith = std.mem.startsWith;
return startsWith(u8, line, arg) or (startsWith(u8, line, arg[0..1]) and line.len == 1);
}
var podLexoCountId: u32 = 1;
var loadedFingerPrints: std.AutoHashMap(u32, void) = undefined;
fn loadPod(args: []const u8) i32 {
var buffer: [64]u8 = undefined;
const podName = args;
const io = core.getEngine().io;
const cwd = std.Io.Dir.cwd();
println("loading pod `{s}` ...", .{args});
const podsDir = cwd.openDir(io, "zig-out/pods", .{}) catch return -1;
const podFile = std.fmt.bufPrint(&buffer, "{s}.pod{s}", .{ args, builtin.target.dynamicLibSuffix() }) catch {
println("pod file name too long", .{});
return -1;
};
const stat = podsDir.statFile(io, podFile, .{}) catch {
println("Unable to load pod: '{s}' '{s}'", .{ args, podFile });
return -1;
};
// write me a function to turn a u32 into a 8 digit hex
const fingerprint: u32 = @intCast(((stat.mtime.nanoseconds >> 32) & 0xfffffff) ^ (stat.mtime.nanoseconds & 0xffffff));
if (loadedFingerPrints.contains(fingerprint)) {
println("skipping load, already loaded fingerprint: {s}", .{hex8(fingerprint)});
return 0;
}
loadedFingerPrints.put(fingerprint, {}) catch return -1;
const sizeinfloat: f64 = @floatFromInt(stat.size);
println("pod found {s} mtimeHash: {s} size: {d} kb", .{ podFile, hex8(fingerprint)[0..], sizeinfloat / 1024 });
const modCachePath = core.TinyString.fmt(".modulecache/{s}", .{podName}) catch return -1;
const targetDir = cwd.createDirPathOpen(io, modCachePath.bytes(), .{}) catch return -1;
const lexograph = blk: {
var lexo: core.TinyString = core.TinyString.fmt("a{d}", .{podLexoCountId}) catch return -1;
const digits: u8 = @intCast(std.math.log10(podLexoCountId));
lexo.buffer[0] = 'a' + digits;
break :blk lexo;
};
const outputPath = core.SmallString.fmt("{s}-{s}", .{ lexograph.bytes(), podFile }) catch return -1;
println("will be installed as {s}", .{outputPath.bytes()});
podsDir.copyFile(podFile, targetDir, outputPath.bytes(), io, .{}) catch return -1;
podLexoCountId += 1;
var fullFileBuffer: [4096]u8 = undefined;
var ffba = std.heap.FixedBufferAllocator.init(&fullFileBuffer);
const fullPath = targetDir.realPathFileAlloc(io, outputPath.bytes(), ffba.allocator()) catch return -1;
println("loading file {s}", .{fullPath});
var lib = std.DynLib.open(fullPath) catch return -1;
const entrypointFn = *const fn (_core: *core.core_api) callconv(.c) i32;
if (lib.lookup(entrypointFn, "entrypoint")) |func| {
if (func(&core.gApi) == 0)
println("module load success!", .{});
}
return 0;
}
fn hex8(value: u32) [8]u8 {
var out: [8]u8 = undefined;
_ = std.fmt.bufPrint(&out, "{x:0>8}", .{value}) catch unreachable; // always exactly 8 bytes
return out;
}
fn listPods(args: []const u8) i32 {
_ = args; // not used for this one
const io = core.getEngine().io;
const cwd = std.Io.Dir.cwd();
const podsDir = cwd.openDir(io, "zig-out/pods", .{ .iterate = true }) catch return -1;
var podCount: usize = 0;
var iterate = podsDir.iterate();
while (iterate.next(io) catch return -1) |entry| {
if (entry.kind != .file) {
continue;
}
if (mem.find(u8, entry.name, ".pod")) |offset| {
_ = offset;
println("pod found stat: {s}", .{entry.name});
podCount += 1;
}
}
println("{d} pod(s) found", .{podCount});
return 0;
}
const mem = std.mem;
const core = @import("core");
const println = core.println;
const std = @import("std");
const builtin = @import("builtin");

View File

@ -6,11 +6,14 @@ Chapter 1: core tech
- structured logging - done - structured logging - done
- compression and streaming - done - compression and streaming - done
- structured logging loading utilities - done - structured logging loading utilities - done
- logging cli and tools directory - simple repl - done
- logging task (game thread)
- API generation
- Hot Reloading - Hot Reloading
- Command API - module loading via cli infrastructure - done
- API generation
- generating the handbomb from the parser
- API generation
- logging cli and tools directory - done
- logging task (game thread)
- IO and threadpool - IO and threadpool
- logging task - logging task
- Allocations and memory pooling - Allocations and memory pooling