Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
WinFormsTouchAdapter.cs
1using System.Runtime.InteropServices;
4
6
17public sealed class WinFormsTouchAdapter : ITouchAdapter, IDisposable
18{
19 private const int WmTouch = 0x0240;
20 private const int WmParentNotify = 0x0210;
21 private const int WmCreate = 0x0001;
22 private const int WmDestroy = 0x0002;
23 private const int WmNcDestroy = 0x0082;
24 private const uint TouchDown = 0x0002;
25 private const uint TouchUp = 0x0004;
26
27 private readonly Control _surface;
28 private readonly WinFormsTouchState _state = new();
29 private readonly Dictionary<Control, TouchWindowHook> _hooks = [];
30 private readonly Dictionary<IntPtr, NativeChildHook> _nativeChildren = [];
31 private bool _refreshingNativeChildren;
32 private bool _disposed;
33
35 public WinFormsTouchAdapter(Control surface)
36 {
37 _surface = surface ?? throw new ArgumentNullException(nameof(surface));
38
39 if (_surface.InvokeRequired)
40 throw new InvalidOperationException("Initialize WinForms touch on the control's UI thread.");
41
42 Watch(_surface);
43 _surface.SizeChanged += OnSurfaceSizeChanged;
44 RefreshNativeChildren();
45 }
46
48 public IReadOnlyList<TouchPoint> ActiveTouches => _state.ActiveTouches;
49
51 public IReadOnlyList<TouchPoint> ConsumeBeganTouches() => _state.ConsumeBeginnings();
52
54 public IReadOnlyList<TouchPoint> ConsumeEndedTouches() => _state.ConsumeEndings();
55
57 public bool IsRegistered => !_disposed &&
58 (_hooks.Values.Any(static hook => hook.IsRegistered) ||
59 _nativeChildren.Values.Any(static hook => hook.IsRegistered));
60
65 internal static bool IsNativeTouchMouseMessage(Control surface)
66 {
68 !adapter.IsRegistered || !ReferenceEquals(adapter._surface, surface))
69 return false;
70
71 return WinFormsTouchState.IsPromotedTouchMouseMessage(GetMessageExtraInfo().ToInt64());
72 }
73
74 private void Watch(Control control)
75 {
76 if (_hooks.ContainsKey(control))
77 return;
78
79 var hook = new TouchWindowHook(this, control);
80 _hooks.Add(control, hook);
81 control.ControlAdded += OnControlAdded;
82 control.ControlRemoved += OnControlRemoved;
83
84 foreach (Control child in control.Controls)
85 Watch(child);
86 }
87
88 private void Unwatch(Control control)
89 {
90 foreach (Control child in control.Controls.Cast<Control>().ToArray())
91 Unwatch(child);
92
93 control.ControlAdded -= OnControlAdded;
94 control.ControlRemoved -= OnControlRemoved;
95
96 if (_hooks.Remove(control, out TouchWindowHook? hook))
97 hook.Dispose();
98 }
99
100 // OpenTK may recreate its drawable independently of managed Control events.
101 // The native parent-notify hooks are primary; resize provides a fallback
102 // for hosts that suppress native child creation notifications.
103 private void OnSurfaceSizeChanged(object? sender, EventArgs e)
104 => RefreshNativeChildren();
105
106 private void OnControlAdded(object? sender, ControlEventArgs e)
107 {
108 Watch(e.Control);
109 RefreshNativeChildren();
110 }
111
112 private void OnControlRemoved(object? sender, ControlEventArgs e)
113 {
114 Unwatch(e.Control);
115 RefreshNativeChildren();
116 _state.CancelAll();
117 }
118
124 private void RefreshNativeChildren()
125 {
126 if (_disposed || !_surface.IsHandleCreated || _refreshingNativeChildren)
127 return;
128
129 _refreshingNativeChildren = true;
130
131 try
132 {
133 var descendants = new HashSet<IntPtr>();
134
135 EnumChildWindows(
136 _surface.Handle,
137 (hwnd, _) =>
138 {
139 descendants.Add(hwnd);
140 return true;
141 },
142 IntPtr.Zero);
143
144 var managedHandles = _hooks.Values
145 .Where(static hook => hook.Handle != IntPtr.Zero)
146 .Select(static hook => hook.Handle)
147 .ToHashSet();
148
149 foreach (IntPtr hwnd in _nativeChildren.Keys.ToArray())
150 {
151 if (descendants.Contains(hwnd) && !managedHandles.Contains(hwnd))
152 continue;
153
154 _nativeChildren.Remove(hwnd, out NativeChildHook? stale);
155 stale?.Dispose();
156 }
157
158 foreach (IntPtr hwnd in descendants)
159 {
160 if (managedHandles.Contains(hwnd) || _nativeChildren.ContainsKey(hwnd))
161 continue;
162
163 _nativeChildren.Add(hwnd, new NativeChildHook(this, hwnd));
164 }
165 }
166 finally
167 {
168 _refreshingNativeChildren = false;
169 }
170 }
171
172 private void ForgetNativeChild(IntPtr hwnd)
173 {
174 if (_nativeChildren.Remove(hwnd, out NativeChildHook? hook))
175 hook.Dispose();
176
177 _state.CancelAll();
178 }
179
180 private bool HandleTouchMessage(IntPtr wParam, IntPtr lParam)
181 {
182 int count = unchecked((ushort)(wParam.ToInt64() & 0xFFFF));
183
184 try
185 {
186 if (count == 0)
187 return true;
188
189 var inputs = new TouchInput[count];
190
191 if (!GetTouchInputInfo(
192 lParam,
193 (uint)count,
194 inputs,
195 Marshal.SizeOf<TouchInput>()))
196 return true;
197
198 foreach (TouchInput input in inputs)
199 {
200 // TOUCHINPUT coordinates are physical screen pixels in hundredths.
201 // Convert through the surface's WinForms client space, and then
202 // through the existing presentation transform to logical ScreenPx.
203 var physical = new Point(
204 (int)Math.Round(input.X / 100d),
205 (int)Math.Round(input.Y / 100d));
206
207 Point local = _surface.PointToClient(physical);
208
209 Point position = _surface switch
210 {
211 WinFormGpuRenderSurfaceControl gpu when gpu.Host is not null =>
212 gpu.Adapter.AdapterPxToScreenPx(local),
213 WinFormBitmapRenderSurfaceControl bitmap when bitmap.Host is not null =>
214 bitmap.Adapter.AdapterPxToScreenPx(local),
215 _ => local
216 };
217
218 int id = unchecked((int)input.Id);
219
220 if ((input.Flags & TouchDown) != 0)
221 _state.Begin(id, position);
222 else if ((input.Flags & TouchUp) != 0)
223 _state.End(id, position);
224 else
225 _state.Move(id, position);
226 }
227
228 return true;
229 }
230 finally
231 {
232 // Once handled, WM_TOUCH must not be passed to DefWindowProc.
233 CloseTouchInputHandle(lParam);
234 }
235 }
236
238 public void Dispose()
239 {
240 if (_disposed)
241 return;
242
243 _disposed = true;
244 _surface.SizeChanged -= OnSurfaceSizeChanged;
245 Unwatch(_surface);
246
247 foreach (NativeChildHook hook in _nativeChildren.Values.ToArray())
248 hook.Dispose();
249
250 _nativeChildren.Clear();
251 _state.CancelAll();
252 }
253
254 private sealed class TouchWindowHook : NativeWindow, IDisposable
255 {
256 private readonly WinFormsTouchAdapter _owner;
257 private readonly Control _control;
258
259 internal bool IsRegistered { get; private set; }
260
261 internal TouchWindowHook(WinFormsTouchAdapter owner, Control control)
262 {
263 _owner = owner;
264 _control = control;
265 _control.HandleCreated += OnHandleCreated;
266 _control.HandleDestroyed += OnHandleDestroyed;
267
268 if (_control.IsHandleCreated)
269 Attach();
270 }
271
272 private void OnHandleCreated(object? sender, EventArgs e)
273 {
274 Attach();
275 _owner.RefreshNativeChildren();
276 }
277
278 private void OnHandleDestroyed(object? sender, EventArgs e)
279 {
280 Detach();
281 _owner.RefreshNativeChildren();
282 _owner._state.CancelAll();
283 }
284
285 private void Attach()
286 {
287 if (Handle != IntPtr.Zero || !_control.IsHandleCreated)
288 return;
289
290 AssignHandle(_control.Handle);
291 IsRegistered = RegisterTouchWindow(Handle, 0);
292 }
293
294 private void Detach()
295 {
296 if (Handle == IntPtr.Zero)
297 return;
298
299 if (IsRegistered)
300 UnregisterTouchWindow(Handle);
301
302 IsRegistered = false;
303 ReleaseHandle();
304 }
305
306 protected override void WndProc(ref Message m)
307 {
308 if (m.Msg == WmTouch && IsRegistered &&
309 _owner.HandleTouchMessage(m.WParam, m.LParam))
310 {
311 m.Result = IntPtr.Zero;
312 return;
313 }
314
315 base.WndProc(ref m);
316
317 // Native children may be created by OpenTK rather than Control.Controls.
318 if (m.Msg == WmParentNotify &&
319 ((m.WParam.ToInt64() & 0xFFFF) is WmCreate or WmDestroy))
320 _owner.RefreshNativeChildren();
321 }
322
323 public void Dispose()
324 {
325 _control.HandleCreated -= OnHandleCreated;
326 _control.HandleDestroyed -= OnHandleDestroyed;
327 Detach();
328 }
329 }
330
335 private sealed class NativeChildHook : NativeWindow, IDisposable
336 {
337 private readonly WinFormsTouchAdapter _owner;
338
339 internal bool IsRegistered { get; private set; }
340
341 internal NativeChildHook(WinFormsTouchAdapter owner, IntPtr hwnd)
342 {
343 _owner = owner;
344 AssignHandle(hwnd);
345 IsRegistered = RegisterTouchWindow(hwnd, 0);
346 }
347
348 protected override void WndProc(ref Message m)
349 {
350 if (m.Msg == WmTouch && IsRegistered &&
351 _owner.HandleTouchMessage(m.WParam, m.LParam))
352 {
353 m.Result = IntPtr.Zero;
354 return;
355 }
356
357 IntPtr hwnd = Handle;
358 base.WndProc(ref m);
359
360 if (m.Msg == WmParentNotify &&
361 ((m.WParam.ToInt64() & 0xFFFF) is WmCreate or WmDestroy))
362 _owner.RefreshNativeChildren();
363
364 if (m.Msg == WmNcDestroy)
365 _owner.ForgetNativeChild(hwnd);
366 }
367
368 public void Dispose()
369 {
370 if (Handle == IntPtr.Zero)
371 return;
372
373 if (IsRegistered)
374 UnregisterTouchWindow(Handle);
375
376 IsRegistered = false;
377 ReleaseHandle();
378 }
379 }
380
381 // Win32 TOUCHINPUT, including pointer-sized HANDLE/ULONG_PTR fields.
382 [StructLayout(LayoutKind.Sequential)]
383 private struct TouchInput
384 {
385 internal int X;
386 internal int Y;
387 internal IntPtr Source;
388 internal uint Id;
389 internal uint Flags;
390 internal uint Mask;
391 internal uint Time;
392 internal UIntPtr ExtraInfo;
393 internal uint ContactWidth;
394 internal uint ContactHeight;
395 }
396
397 private delegate bool EnumWindowsCallback(IntPtr hwnd, IntPtr lParam);
398
399 [DllImport("user32.dll")]
400 [return: MarshalAs(UnmanagedType.Bool)]
401 private static extern bool EnumChildWindows(
402 IntPtr parent,
403 EnumWindowsCallback callback,
404 IntPtr lParam);
405
406 [DllImport("user32.dll", SetLastError = true)]
407 [return: MarshalAs(UnmanagedType.Bool)]
408 private static extern bool RegisterTouchWindow(IntPtr hwnd, uint flags);
409
410 [DllImport("user32.dll", SetLastError = true)]
411 [return: MarshalAs(UnmanagedType.Bool)]
412 private static extern bool UnregisterTouchWindow(IntPtr hwnd);
413
414 [DllImport("user32.dll", SetLastError = true)]
415 [return: MarshalAs(UnmanagedType.Bool)]
416 private static extern bool GetTouchInputInfo(
417 IntPtr handle,
418 uint count,
419 [Out] TouchInput[] inputs,
420 int size);
421
422 [DllImport("user32.dll")]
423 [return: MarshalAs(UnmanagedType.Bool)]
424 private static extern bool CloseTouchInputHandle(IntPtr handle);
425
426 [DllImport("user32.dll")]
427 private static extern IntPtr GetMessageExtraInfo();
428}
ITouchAdapter? TouchAdapter
Gets or sets the touch adapter responsible for providing raw touch state to the engine.
Represents the core game engine singleton responsible for managing the main update loop,...
Definition Engine.cs:36
static Engine Instance
Gets the singleton instance of the Engine.
Definition Engine.cs:49
EngineInputSystems Input
Gets the collection of input subsystems for keyboard, mouse, touch, and gamepad input.
Definition Engine.cs:992
Captures native Windows touchscreen contacts (WM_TOUCH) from a WinForms render control and its child ...
bool IsRegistered
Whether a native window has successfully registered for touch.
WinFormsTouchAdapter(Control surface)
Creates the adapter and registers existing and future child HWNDs.
IReadOnlyList< TouchPoint > ConsumeEndedTouches()
Drains and returns all touch contacts that ended (lifted or cancelled) since the last call....
IReadOnlyList< TouchPoint > ActiveTouches
Gets the list of touch contact points that are currently active (in contact with the surface)....
IReadOnlyList< TouchPoint > ConsumeBeganTouches()
Drains and returns all touch contacts that began since the last call. Keeping beginnings in a queue p...
Defines a passive adapter interface for accessing touch device state. Implementations update their in...