diff --git a/Wasm.Dom/Dom/Navigator.cs b/Wasm.Dom/Dom/Navigator.cs index a63f535..af12139 100644 --- a/Wasm.Dom/Dom/Navigator.cs +++ b/Wasm.Dom/Dom/Navigator.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Reflection; using Microsoft.JSInterop.WebAssembly; using nkast.Wasm.Input; @@ -11,8 +12,7 @@ public class Navigator : JSObject { private readonly Window _window; static Gamepad[] _emptyGamepadArray = new Gamepad[0]; - - private Dictionary _gamepadMap = new Dictionary(); + Dictionary _prevGamepads = new Dictionary(); public string UserAgent { @@ -41,36 +41,30 @@ public Gamepad[] GetGamepads() for (int index = 0; index < strs.Length; index++) { - int gpuid = int.Parse(strs[index]); - if (gpuid == 0) + int uid = int.Parse(strs[index]); + if (Gamepad._uidMap.TryGetValue(uid, out WeakReference jsObjRef)) { - gamepads[index] = null; + if (jsObjRef.TryGetTarget(out JSObject jsObj)) + { + gamepads[index] = (Gamepad)jsObj; + continue; + } + else + Gamepad._uidMap.Remove(uid); } - else - { - if (!_gamepadMap.ContainsKey(gpuid)) - _gamepadMap[gpuid] = new Gamepad(gpuid); - gamepads[index] = _gamepadMap[gpuid]; - } + if (uid != 0) + gamepads[index] = new Gamepad(uid); } - List keys = new List(_gamepadMap.Keys); - for (int index = 0; index < keys.Count; index++) + foreach(int key in _prevGamepads.Keys) { - bool found = false; - for (int k = 0; k < strs.Length; k++) - { - int gpuid = int.Parse(strs[k]); - if (keys[index] == gpuid) - { - found = true; - break; - } - } - if (!found) - _gamepadMap.Remove(keys[index]); + if (!gamepads.Contains(_prevGamepads[key])) + _prevGamepads[key].Dispose(); } + _prevGamepads.Clear(); + for (int index = 0; index < gamepads.Length; index++) + _prevGamepads.Add(index, gamepads[index]); return gamepads; } diff --git a/Wasm.Dom/Input/Gamepad.cs b/Wasm.Dom/Input/Gamepad.cs index c3b40e0..9c3896f 100644 --- a/Wasm.Dom/Input/Gamepad.cs +++ b/Wasm.Dom/Input/Gamepad.cs @@ -10,6 +10,8 @@ namespace nkast.Wasm.Input { public class Gamepad : JSObject { + static internal Dictionary> _uidMap = new Dictionary>(); + public bool Connected { get { return InvokeRet("nkGamepad.GetConnected"); } @@ -99,8 +101,20 @@ public GamepadHapticActuator VibrationActuator internal Gamepad(int uid) : base(uid) { + _uidMap.Add(Uid, new WeakReference(this)); } + protected override void Dispose(bool disposing) + { + if (disposing) + { + + } + + _uidMap.Remove(Uid); + + base.Dispose(disposing); + } } public struct GamepadButton