A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix: web wheel zoom counts the browser's events, so a touchpad no longer jumps (#43) (#528)
Eyal Golan877253e50d39
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 688e7ee7c..eba301256 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -397,6 +397,12 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB- Keyboard focus that lands on something scrolled out of view, such as a Cabinet card below the first row or acandidate far down the list, now scrolls its list to it (accessibility audit H1, refs #41). Focus that follows a mousepress leaves the list where it is. Presentation only: no golden moves.+- Wheel zoom in the web build: one small wheel delta, such as a touchpad's half pixel, made every later frame zoom 27%,+ since Unity's player takes the smallest delta it has seen as one notch. The camera now counts the browser's wheel+ events itself (`WheelInput.jslib`): a touchpad's small pixel deltas zoom by how far the fingers move (100 px to a+ notch), and a mouse notch zooms 10% whatever its size: any pixel event of 50 px or more, a macOS mouse tick, three+ lines or one page is one notch. The listener asks for the mode first so that Firefox keeps a mouse notch in lines+ (refs #43).- "The Mediator Assassinated" cites the Official Gazette text of the Prevention of Terrorism Ordinance for its number,No. 33 of 1948, which no source on the card gave. Comment and source row only (refs #442).- Five recorded contradictions settled from primary sources. "The Second Truce": the Acting Mediator's report ofdiff --git a/docs/m3-release.md b/docs/m3-release.mdindex 40af53953..de2965458 100644--- a/docs/m3-release.md+++ b/docs/m3-release.md@@ -175,11 +175,43 @@ Differences and notes:notch), so the three lines after it counted as 3/100 (3/200 in Chrome). Nothing in the game's code was changed forthis.- What the measurements do show is a different risk, not tested here with real hardware: one small delta sets the notch- for the rest of the session. A touchpad that sends a delta of a pixel or less (as touchpads can, in fractions) makes- every later delta several notches, so each frame of a swipe, or each mouse notch after it, zooms the clamped 27%- (three notches). Chaiky3's Windows touchpad gave 10% steps, so it did not happen there. A Mac trackpad in Chrome or- Safari, and a touchpad followed by a mouse, are still to be tried by hand.+ What the measurements did show is a different risk: one small delta sets the notch for the rest of the session.+ **Fixed (T45).** A scripted swipe of 31 events, 0.5 to 8 px about 16 ms apart (108 px in all, a trackpad's ramp and+ momentum), zoomed 95% (28 notches, three a frame, stopped by the 6 km limit) in Chrome and WebKit, on its own or after a+ mouse notch; after it, one 100 px notch out zoomed three notches. The camera now counts the browser's wheel events+ itself (`WheelInput.jslib` queues each event's `deltaY` and `deltaMode`, and `CameraController.WheelEventNotches`+ scales them):+ - a pixel event of 50 px or more is one notch, whatever its size. A mouse sends one event a notch, but its size+ varies: 100 px in Chrome and Edge on Windows, more with display scaling (125 or 150 px at 125% or 150%, if Chrome+ scales it; not measured), less at a page zoom above 100% (80 px at 125%), and 200 px from Chrome's synthetic+ wheel (Playwright and CDP send 100 and the page sees 200, at `devicePixelRatio` 1). The threshold is half of+ Chrome's 100 px notch, so a page zoom up to 200% still gives a notch;+ - a whole number of macOS mouse ticks (4.000244140625 px, what Chrome and Safari send on a Mac; an accelerated tick+ is several ticks' worth) is one notch;+ - three lines, or one page, is one notch;+ - smaller pixel events, as touchpads send, count 100 px to the notch. The measured swipe's events are 0.5 to 8 px.+ There is no documented ceiling for a real trackpad's events, and a fast flick can send events of tens of pixels or+ more; one of 50 px or more counts as one notch, so an event between 50 and 100 px zooms up to twice what its length+ would, and a bigger one less. Each frame is still clamped to three notches.++ The same swipe now zooms 1.08 notches (10.8%) over 30 or 31 frames, never more than 0.15 in a frame, and a notch of+ 100, 150 or 200 px or three lines, before or after it, zooms 10%. `uv run tools/headed.py wheel` repeats these cases+ in Chrome, and `pytest tools/tests/test_headed.py --headed` checks them, including Chrome's own 100 px notch.++ Firefox 88 and later report a mouse notch in lines only to a script that reads `deltaMode` before `deltaY`, and in+ pixels (three line heights) otherwise; Unity's own handler reads `deltaY` first. So the listener sits on `window` in+ the capture phase, ahead of Unity's handler, and reads the mode first; Firefox then keeps the notch in lines for+ both. That listener is what handles Firefox; the 50 px rule is only a backstop in case a notch still arrives in+ pixels. Not measured: Playwright's Firefox does not start on this Mac (headless: "Failed to launch the browser+ process"; headed and with a persistent profile: no window within 60 s). Were the notch to arrive in pixels after+ all, three line heights of 50 px or more would still be one notch. With a default font of 14 px or less, three line+ heights come to about 48 px, so such a notch would zoom about 0.48 of a step: too little, never too much.++ Known limits: a mouse notch below 50 px that is not a whole macOS tick counts in proportion, for instance a Mac mouse+ tick at 110% page zoom (3.64 px, 3.6%), a notch at a page zoom of 200% or more, or a Firefox notch in pixels with a+ default font of 14 px or less (about 48 px, 0.48 of a step). Still to be tried by hand: a Mac+ trackpad (including fast flicks) and a Mac mouse in Chrome and Safari, a mouse in Firefox (Windows, Linux, Mac),+ Chrome or Edge on Windows at 125% and 150% display scale (one notch), and a mouse on Linux.- **Aborted requests in Chrome.** At each start Chrome lists about 30 of the 51 content files (and the map files) as`net::ERR_ABORTED` in its network log. The files arrive whole: both browsers log the same `BOOT OK content` hash andthe goldens pass. WebKit lists none. Not a console error, so it is left as it is.@@ -190,8 +222,8 @@ Differences and notes:- Input in these runs is synthetic (Playwright's mouse, wheel and keys), not a physical mouse or touchpad.Still open: Safari itself (only its engine was run here), Firefox on a Mac, Chrome and Edge on Windows, a real mouse wheel-in Firefox, a touchpad (above), and the two-upload itch.io save test below. Each needs the owner's machines or the-project's itch.io account.+in Firefox, a real touchpad and a Mac mouse (above), and the two-upload itch.io save test below. Each needs the owner's+machines or the project's itch.io account.## OWNER STEP: sensitivity review before any shared buildSpec section 5.5 requires a recorded sensitivity review for events with sensitive tags (holocaust, terror, massacre,diff --git a/tools/headed.py b/tools/headed.pyindex 5e3cdbd80..7481f2d78 100644--- a/tools/headed.py+++ b/tools/headed.py@@ -11,17 +11,20 @@ serves a WebGL build with web_check's handler, and drives it over one browser-lenavpairs pairs of clicks on a screen button and a second target, d ms apart or in one frame, under ?navlogloadshot screenshots during the load and once ready (the loading line, or the boot-failure line)profile visual v1's ?vprofile in a headed 1920x1080 window at --dpr (frame rate uncapped)+ wheel wheel zoom under ?camlog (#43): a touchpad-like swipe, mouse notches in pixels and lines, over the map and a panelRun from the repo root, e.g.:uv run tools/headed.py boot --build unity/Builds/Web-disabled --cpu 8uv run tools/headed.py navpairs --build unity/Builds/Web-disabled --cpu 20uv run tools/headed.py boot --build unity/Builds/Web-disabled --runs 3 --baseline 450 --baseline-first-frame 9000+ uv run tools/headed.py wheel --build unity/Builds/Web-disabledCoordinates are CSS pixels for a 1568x752 window (the playtest window). Used for playtest 2 (P2-1, P2-4) and the finalreview evidence; the EditMode tests are the regression guard, this is the in-browser check."""import argparseimport asyncioimport base64+import mathimport statisticsimport jsonimport re@@ -43,6 +46,65 @@ WINDOW = (1568, 752)END_TURN, WHY, OPTION, MAP_UNDER_WHY = (1516, 42), (1389, 32), (608, 520), (1180, 300)+# For `wheel`, in a fixed 1568x752 CSS viewport (Playwright's, from the #43 browser runs): START_NEW, the start screen's+# New Game button; MAP, open map clear of the HUD; PANEL, the End Turn button in the top bar.+WHEEL_VIEWPORT, START_NEW, MAP, PANEL = (1568, 752), (784, 693), (300, 400), (1500, 44)+++def pad_swipe() -> list[float]:+ """A touchpad swipe in wheel pixels (zoom in: negative deltaY): a ramp up, a hold, then momentum decaying 12% an+ event down to half a pixel; 31 events, 108.2 px."""+ ramp = [0.5, 1, 2, 4, 6, 8, 8, 8, 8, 8]+ decay = [round(8 * 0.88 ** k, 2) for k in range(1, 40) if 8 * 0.88 ** k >= 0.5]+ return [-d for d in ramp + decay]+++# Each gesture: (deltaY list, deltaMode, ms between events). out_ = the same zooming out.+GESTURES = {"pad": (pad_swipe(), 0, 16), "px100": ([-100.0], 0, 0), "lines3": ([-3.0], 1, 0),+ "out_px100": ([100.0], 0, 0), "out_lines3": ([3.0], 1, 0), "px150": ([-150.0], 0, 0), "px200": ([-200.0], 0, 0),+ "px49": ([-49.0], 0, 0)}+# (label, [(gesture, where)]): each case runs on a fresh page.+WHEEL_CASES = [("pad", [("pad", "map")]), ("px100,pad", [("px100", "map"), ("pad", "map")]),+ ("lines3,pad", [("lines3", "map"), ("pad", "map")]),+ ("pad,out_px100", [("pad", "map"), ("out_px100", "map")]), ("pad,out_lines3", [("pad", "map"), ("out_lines3", "map")]),+ ("pad,px100@panel", [("pad", "panel"), ("px100", "panel")]), ("cdp100", [("cdp100", "map")]),+ ("pad,cdp100", [("pad", "map"), ("cdp100", "map")]),+ ("px150,px200,px49", [("px150", "map"), ("px200", "map"), ("px49", "map")])]+WHEEL_STREAM = """async ([x, y, deltas, mode, gap]) => { const c = document.querySelector('canvas');+ for (const d of deltas) { c.dispatchEvent(new WheelEvent('wheel', {deltaY: d, deltaMode: mode, clientX: x, clientY: y,+ bubbles: true, cancelable: true})); if (gap) await new Promise(r => setTimeout(r, gap)); } }"""+# Records what the page sees of every wheel event (deltaMode read first, as WheelInput.jslib does).+WHEEL_SEEN_SCRIPT = """window.__wheelSeen = []; window.addEventListener('wheel', e => { const m = e.deltaMode;+ window.__wheelSeen.push([e.deltaY, m, e.isTrusted]); }, {capture: true, passive: true});"""+CAMERA = re.compile(r"^CAMERA distance=(\d+)")+++MOUSE_NOTCH_MIN_PX = 50 # CameraController.MouseNotchMinPixels+++def ideal_notches(gesture: str) -> float:+ """What the gesture should zoom, in notches (positive = in): lines / 3; a pixel event of 50 px or more is one notch;+ smaller pixels count 100 to the notch. (Chrome's trusted 100 px notch, cdp100, arrives as 200 px: one notch.)"""+ if gesture == "cdp100":+ return 1.0+ deltas, mode, _ = GESTURES[gesture]+ if mode == 1:+ return -sum(deltas) / 3+ return sum(-math.copysign(1, d) if abs(d) >= MOUSE_NOTCH_MIN_PX else -d / 100 for d in deltas)+++def gesture_notches(d0: float, distances: list[float]) -> tuple[float, float]:+ """(total, largest single frame) in notches (one notch is 10%: d1 = d0 * 0.9^n) from the start distance and the+ distance logged in each frame that changed it."""+ total, largest, prev = 0.0, 0.0, d0+ for d in distances:+ step = math.log(d / prev) / math.log(0.9)+ largest, prev = max(largest, abs(step)), d+ if distances:+ total = math.log(distances[-1] / d0) / math.log(0.9)+ return total, largest++def burst_events(points):"""Mouse events for clicks at `points`, in order: move, press, release each. Sent at once, they land in one frame."""return [{"type": t, "x": x, "y": y, "button": "left", "clickCount": 1}@@ -314,9 +376,48 @@ async def loadshot(args):print(await b.shot(sid, args.out + "-after.png"))+async def wheel(args):+ """Each WHEEL_CASES case on a fresh page under ?camlog: returns {label: [(gesture, total, largest frame, seen)]},+ printing a line per gesture. Gestures are sent to the canvas by dispatchEvent (cdp100: one trusted 100 px notch+ through CDP's mouseWheel); "seen" is what the page saw of them ([deltaY, deltaMode, trusted] per event)."""+ results = {}+ for label, steps in WHEEL_CASES:+ async with Browser(args.build, viewport=WHEEL_VIEWPORT) as b:+ sid = await b.open("camlog", init_script=WHEEL_SEEN_SCRIPT)+ await b.wait_for(sid, r"^GAME OK")+ await asyncio.sleep(3)+ await b.click(sid, *START_NEW)+ await b.wait_for(sid, r"^CAMERA ")+ await asyncio.sleep(2)+ out = []+ for gesture, where in steps:+ x, y = MAP if where == "map" else PANEL+ await b.send("Input.dispatchMouseEvent", {"type": "mouseMoved", "x": x, "y": y}, session=sid)+ await asyncio.sleep(1)+ await b.send("Runtime.evaluate", {"expression": "window.__wheelSeen.length = 0"}, session=sid)+ cams = [CAMERA.match(t) for t in b.lines(sid)]+ d0 = float([m for m in cams if m][-1].group(1))+ n = len(b.lines(sid))+ if gesture == "cdp100":+ await b.send("Input.dispatchMouseEvent", {"type": "mouseWheel", "x": x, "y": y, "deltaX": 0, "deltaY": -100}, session=sid)+ else:+ deltas, mode, gap = GESTURES[gesture]+ expr = f"({WHEEL_STREAM})({json.dumps([x, y, deltas, mode, gap])})"+ await b.send("Runtime.evaluate", {"expression": expr, "awaitPromise": True}, session=sid)+ await asyncio.sleep(1.5)+ seen = (await b.send("Runtime.evaluate", {"expression": "window.__wheelSeen", "returnByValue": True}, session=sid))["result"]["value"]+ frames = [float(m.group(1)) for m in (CAMERA.match(t) for t in b.lines(sid)[n:]) if m]+ total, largest = gesture_notches(d0, frames)+ out.append((gesture, total, largest, seen))+ print(f"WHEEL {label} | {gesture}@{where}: {total:+.2f} notches over {len(frames)} frames, largest frame {largest:.2f}"+ + f" (ideal {ideal_notches(gesture):+.2f})" + (f" (seen {seen})" if gesture == "cdp100" else ""))+ results[label] = out+ return results++def main(argv=None):p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)- p.add_argument("command", choices=["boot", "navpairs", "loadshot", "profile"])+ p.add_argument("command", choices=["boot", "navpairs", "loadshot", "profile", "wheel"])p.add_argument("--build", default=str(REPO / "unity/Builds/Web-disabled"))p.add_argument("--cpu", type=float, default=1.0, help="CPU throttling rate (1 = none)")p.add_argument("--out", default="headed", help="screenshot path prefix (loadshot)")@@ -328,7 +429,7 @@ def main(argv=None):p.add_argument("--dpr", type=float, default=1.0, help="profile: device pixel ratio (2 = the fill-rate stress proxy)")p.add_argument("--timeout", type=float, default=1800, help="profile: seconds to wait for PROFILE visual done")args = p.parse_args(argv)- result = asyncio.run({"boot": boot, "navpairs": navpairs, "loadshot": loadshot, "profile": profile}[args.command](args))+ result = asyncio.run({"boot": boot, "navpairs": navpairs, "loadshot": loadshot, "profile": profile, "wheel": wheel}[args.command](args))return result if isinstance(result, int) else 0diff --git a/tools/tests/test_headed.py b/tools/tests/test_headed.pyindex 550a889ca..fb3043dd3 100644--- a/tools/tests/test_headed.py+++ b/tools/tests/test_headed.py@@ -95,3 +95,43 @@ def test_the_viewport_is_set_before_the_page_loads(tmp_path):import shutilfor browser in (b, plain):shutil.rmtree(browser.profile, ignore_errors=True)+++def test_the_pad_swipe_is_many_small_deltas():+ swipe = headed.pad_swipe()+ assert len(swipe) == 31 and all(-8 <= d <= -0.5 for d in swipe)+ assert headed.ideal_notches("pad") == pytest.approx(1.082, abs=1e-3)+ assert headed.ideal_notches("lines3") == 1 and headed.ideal_notches("out_px100") == -1+ assert headed.ideal_notches("px200") == 1 and headed.ideal_notches("px150") == 1 and headed.ideal_notches("cdp100") == 1+ assert headed.ideal_notches("px49") == pytest.approx(0.49)+++def test_gesture_notches_reads_the_camera_log():+ assert headed.gesture_notches(120000, [108000]) == pytest.approx((1.0, 1.0))+ total, largest = headed.gesture_notches(120000, [120000 * 0.9 ** 0.5, 120000 * 0.9 ** 0.7])+ assert total == pytest.approx(0.7) and largest == pytest.approx(0.5)+ assert headed.gesture_notches(120000, []) == (0.0, 0.0)++[email protected](not BUILD.exists(), reason="needs unity/Builds/Web-disabled")+def test_wheel_zoom_follows_a_swipe_and_keeps_a_notch_at_one_step():+ """#43 in a real browser (WheelInput.jslib and CameraController.WheelOr): a touchpad swipe zooms by its length with+ no frame near the clamp, before or after a mouse notch; a notch in pixels or lines is one step; nothing over a panel."""+ r = {label: {g: (total, largest) for g, total, largest, _ in steps} for label, steps in+ asyncio.run(headed.wheel(argparse.Namespace(build=str(BUILD)))).items()}+ pad = headed.ideal_notches("pad")+ for label in ("pad", "px100,pad", "lines3,pad", "pad,out_px100", "pad,out_lines3"):+ total, largest = r[label]["pad"]+ assert total == pytest.approx(pad, abs=0.05), label+ assert largest < 0.25, label+ assert r["px100,pad"]["px100"][0] == pytest.approx(1, abs=0.02)+ assert r["lines3,pad"]["lines3"][0] == pytest.approx(1, abs=0.02)+ assert r["pad,out_px100"]["out_px100"][0] == pytest.approx(-1, abs=0.02)+ assert r["pad,out_lines3"]["out_lines3"][0] == pytest.approx(-1, abs=0.02)+ assert r["pad,px100@panel"] == {"pad": (0.0, 0.0), "px100": (0.0, 0.0)}+ for label in ("cdp100", "pad,cdp100"): # Chrome's own 100 px notch, which arrives as 200 px: one step, not two+ assert r[label]["cdp100"][0] == pytest.approx(1, abs=0.02), label+ assert r["px150,px200,px49"]["px150"][0] == pytest.approx(1, abs=0.02)+ assert r["px150,px200,px49"]["px200"][0] == pytest.approx(1, abs=0.02)+ assert r["px150,px200,px49"]["px49"][0] == pytest.approx(0.49, abs=0.02)diff --git a/unity/Assets/Scripts/Map/CameraController.cs b/unity/Assets/Scripts/Map/CameraController.csindex 2b4c71409..ec9d77f01 100644--- a/unity/Assets/Scripts/Map/CameraController.cs+++ b/unity/Assets/Scripts/Map/CameraController.cs@@ -42,6 +42,25 @@ namespace Statecraft.Game.Map/// nothing changes. The promo and close-check poses all keep more (hero06judea, the least, 24%).</summary>public const float MinClearanceShare = 0.2f;+ /// <summary>The DOM WheelEvent deltaMode values.</summary>+ public const int WheelPixels = 0, WheelLines = 1, WheelPages = 2;+ /// <summary>Touchpad pixels in one notch (events below MouseNotchMinPixels): a 100 px swipe zooms as far as one+ /// mouse notch.</summary>+ public const float PixelsPerNotch = 100f;+ /// <summary>Lines in one notch: Firefox sends a mouse notch as three lines (WheelInput.jslib asks for the mode first,+ /// so Firefox keeps lines; otherwise it would send three line heights in pixels).</summary>+ public const float LinesPerNotch = 3f;+ /// <summary>One mouse tick on macOS, in pixels, in Chrome and Safari (Cocoa's 0.1000061 lines times 40 px). A delta+ /// that is a whole number of these is a mouse, not a trackpad (the test MapLibre and Mapbox GL use).</summary>+ public const double MacWheelTick = 4.000244140625;+ /// <summary>A pixel wheel event this big or bigger is one mouse notch, whatever its size (#528 review). A discrete+ /// wheel sends one event a notch: 100 px in Chrome and Edge on Windows, 120, 125 or 150 px with display scaling,+ /// 80 px at 125% page zoom, and 200 px from Chrome's synthetic (CDP and Playwright) wheel. A touchpad sends many+ /// small events: 0.5 to 8 px in the measured swipe, and a fast flick's biggest events are a few tens of pixels.+ /// Those below this count in proportion, 100 px to the notch; one above it counts as one notch, never more, so a+ /// flick cannot jump to the clamp either way.</summary>+ public const float MouseNotchMinPixels = 50f;+/// <summary>Answers "is the pointer over the UI?" for a screen position (y up). Null = never.</summary>public Func<Vector2, bool>? IsOverUi;/// <summary>The map rectangle on the ground (x, z), in world metres; the view is kept inside it (Step).</summary>@@ -59,6 +78,8 @@ namespace Statecraft.Game.Mapvoid OnEnable(){+ DrainWheel(); // events from while the camera was off (a menu) are not a zoom+var map = InputSystem.actions?.FindActionMap("Camera", throwIfNotFound: true);if (map == null) return;pan = map.FindAction("Pan", true); dragPan = map.FindAction("DragPan", true);@@ -75,7 +96,7 @@ namespace Statecraft.Game.Mapif (pan == null || dragPan == null || zoom == null || orbit == null) return;Vector2? pointer = Pointer.current != null ? Pointer.current.position.ReadValue() : (Vector2?)null;var down = Mouse.current != null && Mouse.current.rightButton.isPressed;- Step(rig, Gather(pan.ReadValue<Vector2>(), dragPan.ReadValue<Vector2>(), zoom.ReadValue<float>(),+ Step(rig, Gather(pan.ReadValue<Vector2>(), dragPan.ReadValue<Vector2>(), WheelOr(zoom.ReadValue<float>()),orbit.ReadValue<float>(), down, pointer), ClampDt(Time.unscaledDeltaTime), Bounds, Ground, GroundTop);}@@ -83,6 +104,59 @@ namespace Statecraft.Game.Map/// ground clearance as panning, so no frame shows the map's frame or the inside of a hill).</summary>public void Settle() => Step(GetComponent<CameraRig>(), default, 0f, Bounds, Ground, GroundTop);+ /// <summary>The frame's wheel in notches. In WebGL, from the browser's own events (WheelInput.jslib): Unity's player+ /// takes the smallest delta it has seen since the page loaded as one notch, whatever the mode, so a touchpad's+ /// 0.5 px event made every later frame zoom the clamped three notches (issue #43, T45). Elsewhere, the action's value.</summary>+ float WheelOr(float actionValue)+ {+#if UNITY_WEBGL && !UNITY_EDITOR+ float total = 0f; int n;+ while ((n = StatecraftWheelDrain(wheelDeltas, wheelModes, wheelDeltas.Length)) > 0)+ total += WheelNotches(wheelDeltas, wheelModes, n);+ return total;+#else+ return actionValue;+#endif+ }++ void DrainWheel()+ {+#if UNITY_WEBGL && !UNITY_EDITOR+ while (StatecraftWheelDrain(wheelDeltas, wheelModes, wheelDeltas.Length) > 0) { }+#endif+ }++#if UNITY_WEBGL && !UNITY_EDITOR+ readonly float[] wheelDeltas = new float[64]; readonly int[] wheelModes = new int[64];+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern int StatecraftWheelDrain(float[] deltaY, int[] mode, int capacity);+#endif++ /// <summary>One wheel event in notches, positive = in (a DOM deltaY below zero). Lines and pages are counted by the+ /// notch (three lines, one page). A pixel event is one notch when it is MouseNotchMinPixels or more, or a whole+ /// number of macOS mouse ticks (an accelerated tick, several ticks' worth, is still one physical notch);+ /// otherwise it counts 100 to the notch, so a touchpad zooms by how far the fingers move. Nothing is learned+ /// between events.</summary>+ public static float WheelEventNotches(float deltaY, int deltaMode)+ {+ if (deltaY == 0f) return 0f; // not -0: a stray zero event is no zoom, either way+ switch (deltaMode)+ {+ case WheelLines: return -deltaY / LinesPerNotch;+ case WheelPages: return -deltaY;+ }+ double ticks = deltaY / MacWheelTick;+ if (Mathf.Abs(deltaY) >= MouseNotchMinPixels || ticks == Math.Round(ticks)) return deltaY < 0f ? 1f : -1f;+ return -deltaY / PixelsPerNotch;+ }++ /// <summary>The first <paramref name="count"/> wheel events in notches (their sum; Gather clamps the frame).</summary>+ public static float WheelNotches(float[] deltaY, int[] deltaMode, int count)+ {+ float total = 0f;+ for (int i = 0; i < count; i++) total += WheelEventNotches(deltaY[i], deltaMode[i]);+ return total;+ }+public static float ClampDt(float dt) => Mathf.Min(dt, MaxFrameSeconds);/// <summary>Builds one frame of input from raw action values. The wheel is checked against the UI at the pointer every frame;@@ -96,8 +170,8 @@ namespace Statecraft.Game.Mapreturn new CameraInput{Pan = panValue, DragPan = dragValue,- // The Input System's default scroll behaviour (UniformAcrossAllPlatforms) gives 1 per notch on every platform- // (measured in headed Chrome on WebGL, Task 24: a 100 px notch -> 1.0); clamp bursts.+ // Notches: on desktop the Input System's default scroll behaviour (UniformAcrossAllPlatforms) gives 1 per+ // notch; in WebGL WheelOr counts the browser's events (#43). Clamp bursts.Zoom = Mathf.Clamp(zoomRaw, -3f, 3f),Orbit = orbitValue, OverUi = over, DragFromUi = dragFromUi,};diff --git a/unity/Assets/Scripts/Map/WheelInput.jslib b/unity/Assets/Scripts/Map/WheelInput.jslibnew file mode 100644index 000000000..9fd8658b6--- /dev/null+++ b/unity/Assets/Scripts/Map/WheelInput.jslib@@ -0,0 +1,38 @@+// The browser's wheel events on the canvas, for CameraController (issue #43, T45): Unity's player takes the smallest+// delta it has seen since the page loaded as one notch, so one small touchpad delta made later frames zoom far too much.+// Each event's deltaY and deltaMode are queued here and drained by C# once a frame, which does the scaling.+//+// The listener is on window in the capture phase, so it runs before Unity's own handler on the canvas, and it reads+// deltaMode before deltaY. Firefox (88 and later, dom.event.wheel-deltaMode-lines.disabled) reports a mouse notch in+// lines only to a script that asks for deltaMode first; once asked, the event stays in lines for every later reader,+// Unity's handler included. Unity counts the smallest delta it has seen as one notch whatever the mode, so its own+// readings (UI Toolkit scrolling) still give one notch per notch. Other browsers send the same event either way.+// It only reads (passive, no preventDefault) and ignores events whose target is not Unity's canvas.+//+// The listener is never removed: Unity's Quit() removes only the handlers Emscripten registered. This game creates+// the player once, and the queue is capped, so nothing grows. The HEAPF32/HEAP32 indexing assumes wasm32 pointers+// (Unity 6000.3's WebGL target).+mergeInto(LibraryManager.library, {+ $StatecraftWheel: { queue: [], listening: false },++ StatecraftWheelDrain__deps: ["$StatecraftWheel"],+ StatecraftWheelDrain: function (deltaY, mode, capacity) {+ var w = StatecraftWheel;+ if (!w.listening && typeof window !== "undefined") {+ w.listening = true;+ window.addEventListener("wheel", function (e) {+ if (e.target !== Module["canvas"]) return;+ var m = e.deltaMode | 0; // first: see above+ var dy = e.deltaY;+ if (dy !== 0 && w.queue.length < 1024) w.queue.push(dy, m);+ }, { capture: true, passive: true });+ }+ var n = Math.min(capacity, w.queue.length / 2);+ for (var i = 0; i < n; i++) {+ HEAPF32[(deltaY >> 2) + i] = w.queue[2 * i];+ HEAP32[(mode >> 2) + i] = w.queue[2 * i + 1];+ }+ w.queue.splice(0, 2 * n);+ return n;+ },+});diff --git a/unity/Assets/Scripts/Map/WheelInput.jslib.meta b/unity/Assets/Scripts/Map/WheelInput.jslib.metanew file mode 100644index 000000000..73e653574--- /dev/null+++ b/unity/Assets/Scripts/Map/WheelInput.jslib.meta@@ -0,0 +1,32 @@+fileFormatVersion: 2+guid: ee17b85c6fae4b5fa9774719deba2c61+PluginImporter:+ externalObjects: {}+ serializedVersion: 2+ iconMap: {}+ executionOrder: {}+ defineConstraints: []+ isPreloaded: 0+ isOverridable: 0+ isExplicitlyReferenced: 0+ validateReferences: 1+ platformData:+ - first:+ Any:+ second:+ enabled: 0+ settings: {}+ - first:+ Editor: Editor+ second:+ enabled: 0+ settings:+ DefaultValueInitialized: true+ - first:+ WebGL: WebGL+ second:+ enabled: 1+ settings: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Tests/EditMode/CameraInputTests.cs b/unity/Assets/Tests/EditMode/CameraInputTests.csindex 2f6e6a1e0..994a42f62 100644--- a/unity/Assets/Tests/EditMode/CameraInputTests.cs+++ b/unity/Assets/Tests/EditMode/CameraInputTests.cs@@ -1,3 +1,4 @@+using System.Collections.Generic;using System.Linq;using NUnit.Framework;using Statecraft.Game.Map;@@ -391,6 +392,119 @@ public class CameraInputTestsfinally { Object.DestroyImmediate(go); }}+ /// <summary>Issue #43 (T45): in WebGL the zoom counts the browser's wheel events itself. Unity's player took the smallest+ /// delta seen since load as one notch, so one 0.5 px touchpad event made every later frame zoom the clamped 27%. A+ /// mouse notch is still one step: 100 px, three lines, one page, or a macOS mouse tick (4.000244140625 px).</summary>+ [Test]+ public void AMouseNotchIsOneStepInEveryMode()+ {+ Assert.AreEqual(1f, CameraController.WheelEventNotches(-100f, CameraController.WheelPixels), 1e-5, "100 px up");+ Assert.AreEqual(-1f, CameraController.WheelEventNotches(100f, CameraController.WheelPixels), 1e-5, "100 px down");+ Assert.AreEqual(1f, CameraController.WheelEventNotches(-3f, CameraController.WheelLines), 1e-5, "3 lines");+ Assert.AreEqual(1f, CameraController.WheelEventNotches(-1f, CameraController.WheelPages), 1e-5, "1 page");+ Assert.AreEqual(1f, CameraController.WheelEventNotches(-4.000244140625f, CameraController.WheelPixels), 1e-5, "macOS tick");+ Assert.AreEqual(-1f, CameraController.WheelEventNotches(8.00048828125f, CameraController.WheelPixels), 1e-5,+ "an accelerated macOS tick (two ticks' worth) is still one notch");+ Assert.AreEqual(1f, CameraController.WheelEventNotches(-13 * 4.000244140625f, CameraController.WheelPixels), 1e-5,+ "a fast-spun macOS tick above the threshold is one notch");+ foreach (var mode in new[] { CameraController.WheelPixels, CameraController.WheelLines, CameraController.WheelPages })+ Assert.AreEqual(float.PositiveInfinity, 1f / CameraController.WheelEventNotches(0f, mode), $"0 in mode {mode} is +0, not -0");+ }++ /// <summary>#528 review: one discrete pixel notch is one step whatever its size. Chrome's synthetic 100 px notch+ /// arrives as 200 px, and display scaling or page zoom gives 80, 120, 125 or 150 px; every pixel event of+ /// MouseNotchMinPixels (50) or more is exactly one notch in its direction (DOM deltaY below zero = in = positive).</summary>+ [Test]+ public void APixelNotchIsOneStepWhateverItsSize()+ {+ foreach (var px in new[] { 50f, 80f, 100f, 120f, 125f, 150f, 200f, 360f })+ {+ Assert.AreEqual(1f, CameraController.WheelEventNotches(-px, CameraController.WheelPixels), 1e-6, $"-{px} px is one notch in");+ Assert.AreEqual(-1f, CameraController.WheelEventNotches(px, CameraController.WheelPixels), 1e-6, $"+{px} px is one notch out");+ }+ Assert.AreEqual(CameraController.MouseNotchMinPixels, 50f, "the threshold these cases assume");+ Assert.AreEqual(1f, CameraController.WheelEventNotches(-50f, CameraController.WheelPixels), 1e-6, "at the threshold: a notch");+ Assert.AreEqual(0.4999f, CameraController.WheelEventNotches(-49.99f, CameraController.WheelPixels), 1e-5, "just below: proportional");+ Assert.AreEqual(-0.49f, CameraController.WheelEventNotches(49f, CameraController.WheelPixels), 1e-6);+ Assert.AreEqual(2f, CameraController.WheelEventNotches(-6f, CameraController.WheelLines), 1e-6, "lines stay as they were: 6 are 2 notches");+ var rig = NewRig();+ try+ {+ rig.Distance = 120000f;+ CameraController.Step(rig, new CameraInput { Zoom = CameraController.WheelNotches(new[] { -200f }, new[] { 0 }, 1) }, 0.016f, Map);+ Assert.AreEqual(108000f, rig.Distance, 1f, "Chrome's synthetic 200 px notch zooms 10%");+ }+ finally { Object.DestroyImmediate(rig.gameObject); }+ }++ /// <summary>#528 review: a fast trackpad flick can send events of 50 to 100 px, which MouseNotchMinPixels counts as a+ /// whole notch each, up to twice their length. The over-count is bounded per frame by Gather's clamp: one 60 px event+ /// is one notch (proportional would be 0.6), and five in one frame are five notches, clamped to three (27%).</summary>+ [Test]+ public void A60PxFlickEventIsOneNotchAndAFrameOfThemIsClampedToThree()+ {+ Assert.AreEqual(1f, CameraController.WheelEventNotches(-60f, CameraController.WheelPixels), 1e-6, "one 60 px event");+ var frame = new[] { -60f, -60f, -60f, -60f, -60f };+ Assert.AreEqual(5f, CameraController.WheelNotches(frame, new int[frame.Length], frame.Length), 1e-6, "before the clamp");+ var c = NewController(out var go);+ try+ {+ var inp = c.Gather(Vector2.zero, Vector2.zero, CameraController.WheelNotches(frame, new int[frame.Length], frame.Length), 0, false,+ new Vector2(500, 0));+ Assert.AreEqual(3f, inp.Zoom, 1e-6, "clamped to three notches a frame");+ var rig = go.GetComponent<CameraRig>();+ rig.Distance = 120000f;+ CameraController.Step(rig, inp, 0.016f, Map);+ Assert.AreEqual(120000f * 0.729f, rig.Distance, 1f, "27.1% in that frame, no more");+ }+ finally { Object.DestroyImmediate(go); }+ }++ [Test]+ public void TouchpadPixelsZoomInProportionAndNothingIsLearned()+ {+ Assert.AreEqual(0.005f, CameraController.WheelEventNotches(-0.5f, CameraController.WheelPixels), 1e-6);+ Assert.AreEqual(0.04f, CameraController.WheelEventNotches(-4f, CameraController.WheelPixels), 1e-6, "4 px is not a tick");+ Assert.AreEqual(0.07f, CameraController.WheelEventNotches(-7f, CameraController.WheelPixels), 1e-6);+ // A swipe of many small deltas, then a mouse notch: the swipe zooms by its length, and the notch is still one step.+ var swipe = new float[] { -0.5f, -1, -2, -4, -6, -8, -8, -8, -6.2f, -4.8f, -3.1f, -1.4f, -0.6f };+ var modes = new int[swipe.Length];+ Assert.AreEqual(-swipe.Sum() / 100f, CameraController.WheelNotches(swipe, modes, swipe.Length), 1e-5);+ Assert.AreEqual(1f, CameraController.WheelNotches(new[] { -100f }, new[] { 0 }, 1), 1e-5);+ Assert.AreEqual(1f, CameraController.WheelNotches(new[] { -3f }, new[] { CameraController.WheelLines }, 1), 1e-5);+ Assert.AreEqual(0.4f, CameraController.WheelNotches(new[] { -40f, -100f }, new[] { 0, 0 }, 1), 1e-5, "only count events");+ // The swipe the browser runs use (tools/headed.py pad_swipe: a ramp, a hold, momentum decaying 12% an event).+ var pad = new List<float> { -0.5f, -1, -2, -4, -6, -8, -8, -8, -8, -8 };+ for (int k = 1; 8 * Mathf.Pow(0.88f, k) >= 0.5f; k++) pad.Add(-(float)System.Math.Round(8 * System.Math.Pow(0.88, k), 2));+ Assert.AreEqual(31, pad.Count);+ Assert.AreEqual(1.082f, CameraController.WheelNotches(pad.ToArray(), new int[pad.Count], pad.Count), 1e-3, "108.2 px is 1.08 notches");+ }++ [Test]+ public void ATouchpadSwipeZoomsSmoothlyAndStaysOffPanels()+ {+ var c = NewController(out var go);+ try+ {+ var rig = go.GetComponent<CameraRig>();+ rig.Distance = 120000f;+ foreach (var px in new[] { 0.5f, 2f, 8f, 8f, 4f, 1f }) // one frame's events each+ {+ var before = rig.Distance;+ var notches = CameraController.WheelNotches(new[] { -px }, new[] { 0 }, 1);+ CameraController.Step(rig, c.Gather(Vector2.zero, Vector2.zero, notches, 0, false, new Vector2(500, 0)), 0.016f, Map);+ Assert.AreEqual(before * Mathf.Pow(0.9f, px / 100f), rig.Distance, 1f, $"{px} px");+ }+ var held = rig.Distance;+ var swipe = new[] { -0.5f, -2f, -8f, -8f, -4f, -1f, -100f }; // a swipe and a mouse notch, over the panel+ var overPanel = CameraController.WheelNotches(swipe, new int[swipe.Length], swipe.Length);+ Assert.Greater(overPanel, 1f);+ CameraController.Step(rig, c.Gather(Vector2.zero, Vector2.zero, overPanel, 0, false, new Vector2(50, 0)), 0.016f, Map);+ Assert.AreEqual(held, rig.Distance, 1e-3, "no zoom over a panel");+ }+ finally { Object.DestroyImmediate(go); }+ }+/// <summary>Task 24 review M3: zooming in then out by the same notches returns to the same distance.</summary>[Test]public void ZoomingInThenOutReturnsToTheStart()diff --git a/unity/Assets/Tests/EditMode/HudTests.cs b/unity/Assets/Tests/EditMode/HudTests.csindex 588b54400..e084d23f6 100644--- a/unity/Assets/Tests/EditMode/HudTests.cs+++ b/unity/Assets/Tests/EditMode/HudTests.cs@@ -372,6 +372,7 @@ public class HudTests("MapShaderGlobals.cs", "RiftHazeTopM = -100f", "a real elevation in metres for the rift haze (shader input, not a displayed number)"),("SettlementKits.cs", "DefaultHouses = 100f", "the owner's symbolic scale for houses and trees (100x real size), not a displayed number"),("RouteLayer.cs", "CorridorMarginM = 100f", "a clearance in map metres that kit buildings and trees keep from a route (geometry, not a displayed number)"),+ ("CameraController.cs", "PixelsPerNotch = 100f", "wheel pixels in one mouse notch, to scale the browser's wheel events (input, not a displayed number)"),};[Test]