A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: a trackpad pinch zooms in the macOS player (#1845)
Eyal Golanbc826a80826a
diff --git a/changelog.d/mac-trackpad-pinch-zoom.md b/changelog.d/mac-trackpad-pinch-zoom.mdnew file mode 100644index 000000000..485ff9341--- /dev/null+++ b/changelog.d/mac-trackpad-pinch-zoom.md@@ -0,0 +1,4 @@+### Fixed++- A trackpad pinch zooms the map in the macOS player, as it does in the browser: the player passed the pinch to+ nothing, so it did not zoom at all. The wheel, a two-finger scroll and the zoom keys already zoomed there.diff --git a/unity/Assets/Scripts/Map/CameraController.cs b/unity/Assets/Scripts/Map/CameraController.csindex d522f860c..0721a663f 100644--- a/unity/Assets/Scripts/Map/CameraController.cs+++ b/unity/Assets/Scripts/Map/CameraController.cs@@ -86,6 +86,12 @@ namespace Statecraft.Game.Mappublic Func<bool>? HoldsMouseDrag;/// <summary>The same for a one-finger drag and a tap (MapPointer.TouchTapCandidate).</summary>public Func<bool>? HoldsTouchDrag;+ /// <summary>The trackpad pinch since the last frame, as the summed NSEvent magnification (positive = the fingers+ /// spread). macOS sends a pinch as magnify events, which Unity's player passes to neither the Input System nor the+ /// wheel (the owner found zooming did nothing in the macOS player, 27 Oct 2026), so TrackpadPinch.mm collects them+ /// in the macOS player; elsewhere there is none (0). In the browser a pinch arrives as a wheel event instead+ /// (WheelInput.jslib). Test seam (internal): an edit-mode test cannot make a Cocoa magnify event.</summary>+ internal Func<float> TrackpadMagnification = DrainTrackpadMagnification;CameraRig rig = null!;InputAction? pan, dragPan, zoom, zoomKeys, orbit;@@ -109,6 +115,7 @@ namespace Statecraft.Game.MaptouchPosition.performed += ctx => touchDrag.Move(ctx.ReadValue<Vector2>());mousePress.Enable(); mousePosition.Enable(); touchPress.Enable(); touchPosition.Enable();DrainWheel(); // events from while the camera was off (a menu) are not a zoom+ TrackpadMagnification(); // nor is a pinch from thenvar map = InputSystem.actions?.FindActionMap("Camera", throwIfNotFound: true);if (map == null) return;@@ -144,7 +151,7 @@ namespace Statecraft.Game.Mapvar mouseGated = HoldsMouseDrag != null;var drag = mouseGated ? mouseDrag.Take(HoldsMouseDrag!()) : dragPan.ReadValue<Vector2>();var fromUi = down && mouseDrag.FromUi;- var zoomRaw = WheelOr(zoom.ReadValue<float>());+ var zoomRaw = WheelOr(zoom.ReadValue<float>()) + MagnifyNotches(TrackpadMagnification());var ts = Touchscreen.current;if (ts != null){@@ -284,6 +291,26 @@ namespace Statecraft.Game.Map#endif}+ /// <summary>A trackpad pinch in wheel notches, positive = in: <paramref name="magnification"/> is the summed NSEvent+ /// magnification, which scales the view by 1 + m, so the camera comes 1 + m times closer, as far as the fingers+ /// moved ((1 - ZoomPerStep)^notches = 1 / (1 + m)). A sum at or below -1 (no real pinch sends one) counts as the+ /// farthest step out that 1 + m = 0.01 gives, never a NaN.</summary>+ public static float MagnifyNotches(float magnification) =>+ magnification == 0f ? 0f : -Mathf.Log(Mathf.Max(1f + magnification, 0.01f)) / Mathf.Log(1f - ZoomPerStep);++ static float DrainTrackpadMagnification()+ {+#if UNITY_STANDALONE_OSX && !UNITY_EDITOR+ return StatecraftMagnifyDrain();+#else+ return 0f;+#endif+ }++#if UNITY_STANDALONE_OSX && !UNITY_EDITOR+ [System.Runtime.InteropServices.DllImport("__Internal")] static extern float StatecraftMagnifyDrain();+#endif+void DrainWheel(){#if UNITY_WEBGL && !UNITY_EDITORdiff --git a/unity/Assets/Scripts/Map/TrackpadPinch.mm b/unity/Assets/Scripts/Map/TrackpadPinch.mmnew file mode 100644index 000000000..eec75c167--- /dev/null+++ b/unity/Assets/Scripts/Map/TrackpadPinch.mm@@ -0,0 +1,32 @@+// A macOS trackpad pinch for CameraController (the macOS player only; see its TrackpadMagnification). macOS sends a pinch+// as magnify events (NSEventTypeMagnify), and Unity's player passes them to neither the Input System nor the wheel, so a+// pinch did nothing in the macOS player (owner, 27 Oct 2026) while the browser build zooms on one (the browser sends it+// as a wheel event). An app-local monitor adds each event's magnification to a running sum, which C# takes once a frame.+//+// The monitor only reads: it returns every event unchanged, so the rest of the app still gets it. It is installed on the+// first drain, from CameraController's OnEnable, and never removed; the player installs it once. AppKit runs local+// monitors on the main thread, where Unity's player loop runs on macOS, so the sum needs no lock.+//+// NSEvent is looked up at run time (objc_getClass) rather than linked: Unity links GameAssembly.dylib, which this file is+// compiled into, without AppKit, so a direct [NSEvent ...] fails to link (_OBJC_CLASS_$_NSEvent undefined). The player+// process has AppKit loaded already; were the class missing, the message would go to nil and the sum stay 0.+#import <AppKit/AppKit.h>+#import <objc/runtime.h>++static double statecraftMagnifySum = 0;+static bool statecraftMagnifyListening = false;++extern "C" float StatecraftMagnifyDrain(void)+{+ if (!statecraftMagnifyListening)+ {+ statecraftMagnifyListening = true;+ [objc_getClass("NSEvent") addLocalMonitorForEventsMatchingMask:NSEventMaskMagnify handler:^NSEvent* (NSEvent* event) {+ statecraftMagnifySum += event.magnification;+ return event;+ }];+ }+ double sum = statecraftMagnifySum;+ statecraftMagnifySum = 0;+ return (float)sum;+}diff --git a/unity/Assets/Scripts/Map/TrackpadPinch.mm.meta b/unity/Assets/Scripts/Map/TrackpadPinch.mm.metanew file mode 100644index 000000000..1b49fc64f--- /dev/null+++ b/unity/Assets/Scripts/Map/TrackpadPinch.mm.meta@@ -0,0 +1,32 @@+fileFormatVersion: 2+guid: 825cc6af2a764dd4b6eb16d78ffe726b+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:+ Standalone: OSXUniversal+ second:+ enabled: 1+ settings: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Tests/EditMode/CameraInputTests.cs b/unity/Assets/Tests/EditMode/CameraInputTests.csindex 39298f3fa..093cbda9e 100644--- a/unity/Assets/Tests/EditMode/CameraInputTests.cs+++ b/unity/Assets/Tests/EditMode/CameraInputTests.cs@@ -901,3 +901,92 @@ public class PressOriginCameraInputTests : InputTestFixtureAssert.That(rig.View.LookAt.x, Is.EqualTo(498800).Within(0.1f), "ungated source pans all ten pixels");}}++/// <summary>Zoom from a pointing device through CameraController's frame (Tick, which Update calls), as the zoom keys are+/// tested above: the wheel through the Input System's test fixture and the project-wide Camera actions, and a macOS+/// trackpad pinch through the magnification the player's window received (TrackpadMagnification: TrackpadPinch.mm+/// in the macOS player, a stand-in here, since an edit-mode test cannot make a Cocoa magnify event). The owner found+/// on 27 Oct 2026 that zooming did nothing in the macOS player: the wheel, a two-finger scroll and the keys did zoom+/// there, but a pinch never reached the Input System at all.</summary>+public class CameraPointerZoomThroughTheFrameTests : InputTestFixture+{+ static void Send(Object o, string message) =>+ o.GetType().GetMethod(message, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!+ .Invoke(o, null);++ static CameraController NewController(out CameraRig rig)+ {+ InputSystem.actions = AssetDatabase.LoadAssetAtPath<InputActionAsset>("Assets/InputSystem_Actions.inputactions");+ var go = new GameObject("PointerZoomTest", typeof(Camera));+ rig = go.AddComponent<CameraRig>();+ rig.LookAt = new Vector3(500000, 0, 500000); rig.Distance = 100000f;+ var c = go.AddComponent<CameraController>();+ c.Bounds = new Rect(0, 0, 1000000, 1000000); // far larger than the view: no view clamp here+ Send(c, "Awake"); Send(c, "OnEnable");+ return c;+ }++ static void Dispose(CameraController c) { Send(c, "OnDisable"); Object.DestroyImmediate(c.gameObject); }++ [TestCase(1f)]+ [TestCase(-1f)]+ public void AWheelNotchZoomsOneStepInOrOut(float notches)+ {+ var mouse = InputSystem.AddDevice<Mouse>();+ var c = NewController(out var rig);+ try+ {+ Set(mouse.position, new Vector2(400, 400)); c.Tick(0.016f);+ Set(mouse.scroll, new Vector2(0, notches)); c.Tick(0.016f);+ Assert.AreEqual(100000f * Mathf.Pow(1f - CameraController.ZoomPerStep, notches), rig.Distance, 1f,+ notches > 0 ? "a notch up zooms in 10%" : "a notch down zooms out");+ }+ finally { Dispose(c); }+ }++ [TestCase(0.05f)]+ [TestCase(-0.05f)]+ public void ATrackpadPinchScalesTheViewByItsMagnification(float magnification)+ {+ InputSystem.AddDevice<Mouse>();+ var c = NewController(out var rig);+ try+ {+ var pending = magnification;+ c.TrackpadMagnification = () => { var m = pending; pending = 0f; return m; };+ c.Tick(0.016f);+ // Fingers spread by 5% (magnification +0.05): the map shows 5% larger, so the camera is 1.05 times closer.+ Assert.AreEqual(100000f / (1f + magnification), rig.Distance, 1f, "the pinch zooms as far as the fingers moved");+ c.Tick(0.016f);+ Assert.AreEqual(100000f / (1f + magnification), rig.Distance, 1f, "a pinch is taken once, not every frame");+ }+ finally { Dispose(c); }+ }++ [Test]+ public void APinchOverTheUiIsTheUisAsTheWheelIs()+ {+ var mouse = InputSystem.AddDevice<Mouse>();+ var c = NewController(out var rig);+ try+ {+ c.IsOverUi = _ => true;+ Set(mouse.position, new Vector2(400, 400));+ c.TrackpadMagnification = () => 0.05f;+ c.Tick(0.016f);+ Assert.AreEqual(100000f, rig.Distance, 1e-3, "over a panel a pinch does not zoom the map");+ }+ finally { Dispose(c); }+ }++ [Test]+ public void ThePinchPluginIsBuiltIntoTheMacPlayerOnly()+ {+ var plugin = (PluginImporter)AssetImporter.GetAtPath("Assets/Scripts/Map/TrackpadPinch.mm");+ Assert.IsNotNull(plugin, "TrackpadPinch.mm is imported as a native plugin");+ Assert.IsTrue(plugin.GetCompatibleWithPlatform(BuildTarget.StandaloneOSX), "the macOS player compiles it");+ Assert.IsFalse(plugin.GetCompatibleWithEditor(), "the editor has no such symbol: CameraController asks only in the player");+ foreach (var other in new[] { BuildTarget.StandaloneWindows64, BuildTarget.StandaloneLinux64, BuildTarget.WebGL })+ Assert.IsFalse(plugin.GetCompatibleWithPlatform(other), other + " does not build AppKit code");+ }+}