From 9354c178eb199640a6bfabf0904649e3dd323747 Mon Sep 17 00:00:00 2001 From: David Vanderson Date: Wed, 8 Jun 2022 16:19:26 -0400 Subject: [PATCH] native: switch to setWaitEvent() --- src/Engine.zig | 22 ++++++++++++++++++++++ src/platform/native.zig | 24 ++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/Engine.zig b/src/Engine.zig index ca2ef42f..67c8e7d6 100644 --- a/src/Engine.zig +++ b/src/Engine.zig @@ -53,10 +53,28 @@ pub fn setOptions(engine: *Engine, options: structs.Options) !void { engine.options = options; } +// Signals mach to stop the update loop. pub fn setShouldClose(engine: *Engine, value: bool) void { engine.internal.setShouldClose(value); } +// Signals mach to wait for an event with timeout before calling update() +// again. Mach resets to null, so call during each update() if needed. +// +// timeout is in seconds (null disables waiting) +// - pass std.math.floatMax(f64) to wait with no timeout +// +// update() can be called earlier than timeout if an event happens (key press, +// mouse motion, etc.) +// +// update() can be called a bit later than timeout due to timer precision and +// process scheduling. +// +// Calling this multiple times means the last call's value is used. +pub fn setWaitEvent(engine: *Engine, timeout: ?f64) void { + engine.internal.setWaitEvent(timeout); +} + // Returns the framebuffer size, in subpixel units. // // e.g. returns 1280x960 on macOS for a window that is 640x480 @@ -71,6 +89,10 @@ pub fn getWindowSize(engine: *Engine) structs.Size { return engine.internal.getWindowSize(); } +pub fn hasEvent(engine: *Engine) !bool { + return engine.internal.hasEvent(); +} + pub fn pollEvent(engine: *Engine) ?structs.Event { return engine.internal.pollEvent(); } diff --git a/src/platform/native.zig b/src/platform/native.zig index a64dbdbf..3c60cf7c 100644 --- a/src/platform/native.zig +++ b/src/platform/native.zig @@ -17,6 +17,7 @@ pub const Platform = struct { last_window_size: structs.Size, last_framebuffer_size: structs.Size, + waitEventTimeout: ?f64 = null, native_instance: gpu.NativeInstance, @@ -305,6 +306,15 @@ pub const Platform = struct { return platform.last_window_size; } + pub fn hasEvent(platform: *Platform) !bool { + try glfw.pollEvents(); + return platform.events.first != null; + } + + pub fn setWaitEvent(platform: *Platform, timeout: ?f64) void { + platform.waitEventTimeout = timeout; + } + pub fn pollEvent(platform: *Platform) ?structs.Event { if (platform.events.popFirst()) |n| { defer platform.allocator.destroy(n); @@ -512,5 +522,19 @@ pub fn main() !void { } try app.update(&engine); + + if (engine.internal.waitEventTimeout) |timeout| { + // wait for an event + if (timeout == std.math.floatMax(f64)) { + // no timeout + try glfw.waitEvents(); + } + else { + // with a timeout + try glfw.waitEventsTimeout(timeout); + } + + engine.internal.waitEventTimeout = null; + } } }