From 99dc10e58a87fe8a1f8898f4bdbbddeb0538cc33 Mon Sep 17 00:00:00 2001 From: iddev5 Date: Sun, 5 Jun 2022 18:12:25 +0530 Subject: [PATCH] mach: wasm: Implement mouse press, release, motion and scroll events --- src/platform/mach.js | 20 ++++++++++++++++++++ src/platform/wasm.zig | 43 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/platform/mach.js b/src/platform/mach.js index 639f39bb..da61d1ca 100644 --- a/src/platform/mach.js +++ b/src/platform/mach.js @@ -191,6 +191,22 @@ const mach = { mach.events.push(...[2, convertKeyCode(ev.code)]); }); + canvas.addEventListener("mousemove", (ev) => { + mach.events.push(...[3, ev.clientX, ev.clientY]); + }); + + canvas.addEventListener("mousedown", (ev) => { + mach.events.push(...[4, ev.button]); + }); + + canvas.addEventListener("mouseup", (ev) => { + mach.events.push(...[5, ev.button]); + }); + + canvas.addEventListener("wheel", (ev) => { + mach.events.push(...[6, ev.deltaX, ev.deltaY]); + }); + document.body.appendChild(canvas); return mach.canvases.push({ canvas: canvas, title: undefined }) - 1; }, @@ -246,6 +262,10 @@ const mach = { return mach.events.shift(); }, + machEventShiftFloat() { + return mach.machEventShift(); + }, + machPerfNow() { return performance.now(); }, diff --git a/src/platform/wasm.zig b/src/platform/wasm.zig index 90bfa556..1bc72a80 100644 --- a/src/platform/wasm.zig +++ b/src/platform/wasm.zig @@ -13,7 +13,8 @@ const js = struct { extern fn machCanvasGetWindowHeight(canvas: CanvasId) u32; extern fn machCanvasGetFramebufferWidth(canvas: CanvasId) u32; extern fn machCanvasGetFramebufferHeight(canvas: CanvasId) u32; - extern fn machEventShift() u32; + extern fn machEventShift() i32; + extern fn machEventShiftFloat() f64; extern fn machPerfNow() f64; extern fn machLog(str: [*]const u8, len: u32) void; @@ -76,9 +77,49 @@ pub const Platform = struct { 2 => structs.Event{ .key_release = .{ .key = @intToEnum(enums.Key, js.machEventShift()) }, }, + 3 => structs.Event{ + .mouse_motion = .{ + .x = @intToFloat(f64, js.machEventShift()), + .y = @intToFloat(f64, js.machEventShift()), + }, + }, + 4 => structs.Event{ + .mouse_press = .{ + .button = toMachButton(js.machEventShift()), + }, + }, + 5 => structs.Event{ + .mouse_release = .{ + .button = toMachButton(js.machEventShift()), + }, + }, + 6 => structs.Event{ + .mouse_scroll = .{ + .xoffset = @floatCast(f32, sign(js.machEventShiftFloat())), + .yoffset = @floatCast(f32, sign(js.machEventShiftFloat())), + }, + }, else => null, }; } + + inline fn sign(val: f64) f64 { + return switch (val) { + 0.0 => 0.0, + else => -val, + }; + } + + fn toMachButton(button: i32) enums.MouseButton { + return switch (button) { + 0 => .left, + 1 => .middle, + 2 => .right, + 3 => .four, + 4 => .five, + else => unreachable, + }; + } }; pub const BackingTimer = struct {