-
Notifications
You must be signed in to change notification settings - Fork 304
/
InputManager.cs
2801 lines (2378 loc) · 124 KB
/
InputManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine.Experimental.Input.Composites;
using UnityEngine.Experimental.Input.Controls;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Profiling;
using UnityEngine.Experimental.Input.LowLevel;
using UnityEngine.Experimental.Input.Processors;
using UnityEngine.Experimental.Input.Interactions;
using UnityEngine.Experimental.Input.Utilities;
using Unity.Collections;
using UnityEngine.Experimental.Input.Layouts;
#if !(NET_4_0 || NET_4_6 || NET_STANDARD_2_0 || UNITY_WSA)
using UnityEngine.Experimental.Input.Net35Compatibility;
#endif
////TODO: work towards InputManager having no direct knowledge of actions
////TODO: allow pushing events into the system any which way; decouple from the buffer in NativeInputSystem being the only source
////TODO: merge InputManager into InputSystem and have InputSystemObject store SerializedState directly
////REVIEW: change the event properties over to using IObservable?
////REVIEW: instead of RegisterInteraction and RegisterControlProcessor, have a generic RegisterInterface (or something)?
////REVIEW: can we do away with the 'previous == previous frame' and simply buffer flip on every value write?
namespace UnityEngine.Experimental.Input
{
using DeviceChangeListener = Action<InputDevice, InputDeviceChange>;
using LayoutChangeListener = Action<string, InputControlLayoutChange>;
using EventListener = Action<InputEventPtr>;
using UpdateListener = Action<InputUpdateType>;
public delegate string DeviceFindControlLayoutCallback(int deviceId, ref InputDeviceDescription description, string matchedLayout,
IInputRuntime runtime);
/// <summary>
/// Hub of the input system.
/// </summary>
/// <remarks>
/// Not exposed. Use <see cref="InputSystem"/> as the public entry point to the system.
///
/// Manages devices, layouts, and event processing.
/// </remarks>
internal class InputManager
{
public ReadOnlyArray<InputDevice> devices
{
get { return new ReadOnlyArray<InputDevice>(m_Devices); }
}
public TypeTable processors
{
get { return m_Processors; }
}
public TypeTable interactions
{
get { return m_Interactions; }
}
public TypeTable composites
{
get { return m_Composites; }
}
public InputMetrics metrics
{
get
{
var result = m_Metrics;
if (m_Runtime != null)
result.totalFrameCount = m_Runtime.frameCount;
return result;
}
}
public InputUpdateType updateMask
{
get { return m_UpdateMask; }
set
{
if (m_UpdateMask == value)
return;
// In editor, we don't allow disabling editor updates.
#if UNITY_EDITOR
value |= InputUpdateType.Editor;
#endif
m_UpdateMask = value;
// Tell runtime.
if (m_Runtime != null)
m_Runtime.updateMask = m_UpdateMask;
// Recreate state buffers.
if (m_Devices != null)
ReallocateStateBuffers();
}
}
public float pollingFrequency
{
get { return m_PollingFrequency; }
set
{
////REVIEW: allow setting to zero to turn off polling altogether?
if (value <= 0)
throw new ArgumentException("Polling frequency must be greater than zero", "value");
m_PollingFrequency = value;
if (m_Runtime != null)
m_Runtime.pollingFrequency = value;
}
}
public event DeviceChangeListener onDeviceChange
{
add { m_DeviceChangeListeners.Append(value); }
remove { m_DeviceChangeListeners.Remove(value); }
}
public event DeviceFindControlLayoutCallback onFindControlLayoutForDevice
{
add { m_DeviceFindLayoutCallbacks.Append(value); }
remove { m_DeviceFindLayoutCallbacks.Remove(value); }
}
public event LayoutChangeListener onLayoutChange
{
add { m_LayoutChangeListeners.Append(value); }
remove { m_LayoutChangeListeners.Remove(value); }
}
////TODO: add InputEventBuffer struct that uses NativeArray underneath
////TODO: make InputEventTrace use NativeArray
////TODO: introduce an alternative that consumes events in bulk
public event EventListener onEvent
{
add { m_EventListeners.Append(value); }
remove { m_EventListeners.Remove(value); }
}
public event UpdateListener onBeforeUpdate
{
add
{
InstallBeforeUpdateHookIfNecessary();
m_BeforeUpdateListeners.Append(value);
}
remove { m_BeforeUpdateListeners.Remove(value); }
}
public event UpdateListener onAfterUpdate
{
add { m_AfterUpdateListeners.Append(value); }
remove { m_AfterUpdateListeners.Remove(value); }
}
////TODO: when registering a layout that exists as a layout of a different type (type vs string vs constructor),
//// remove the existing registration
// Add a layout constructed from a type.
// If a layout with the same name already exists, the new layout
// takes its place.
public void RegisterControlLayout(string name, Type type)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("name");
if (type == null)
throw new ArgumentNullException("type");
// Note that since InputDevice derives from InputControl, isDeviceLayout implies
// isControlLayout to be true as well.
var isDeviceLayout = typeof(InputDevice).IsAssignableFrom(type);
var isControlLayout = typeof(InputControl).IsAssignableFrom(type);
if (!isDeviceLayout && !isControlLayout)
throw new ArgumentException("Types used as layouts have to be InputControls or InputDevices",
"type");
var internedName = new InternedString(name);
var isReplacement = DoesLayoutExist(internedName);
// All we do is enter the type into a map. We don't construct an InputControlLayout
// from it until we actually need it in an InputDeviceBuilder to create a device.
// This not only avoids us creating a bunch of objects on the managed heap but
// also avoids us laboriously constructing a XRController layout, for example,
// in a game that never uses XR.
m_Layouts.layoutTypes[internedName] = type;
////TODO: make this independent of initialization order
////TODO: re-scan base type information after domain reloads
// Walk class hierarchy all the way up to InputControl to see
// if there's another type that's been registered as a layhout.
// If so, make it a base layout for this one.
string baseLayout = null;
for (var baseType = type.BaseType; baseLayout == null && baseType != typeof(InputControl);
baseType = baseType.BaseType)
{
foreach (var entry in m_Layouts.layoutTypes)
if (entry.Value == baseType)
{
baseLayout = entry.Key;
break;
}
}
PerformLayoutPostRegistration(internedName, new InlinedArray<InternedString>(new InternedString(baseLayout)),
isReplacement, isKnownToBeDeviceLayout: isDeviceLayout);
}
public void RegisterControlLayout(string json, string name = null, bool isOverride = false)
{
if (string.IsNullOrEmpty(json))
throw new ArgumentException("json");
////REVIEW: as long as no one has instantiated the layout, the base layout information is kinda pointless
// Parse out name, device description, and base layout.
InternedString nameFromJson;
InlinedArray<InternedString> baseLayouts;
InputDeviceMatcher deviceMatcher;
InputControlLayout.ParseHeaderFieldsFromJson(json, out nameFromJson, out baseLayouts,
out deviceMatcher);
// Decide whether to take name from JSON or from code.
var internedLayoutName = new InternedString(name);
if (internedLayoutName.IsEmpty())
{
internedLayoutName = nameFromJson;
// Make sure we have a name.
if (internedLayoutName.IsEmpty())
throw new ArgumentException("Layout name has not been given and is not set in JSON layout",
"name");
}
// If it's an override, it must have a layout the overrides apply to.
if (isOverride && baseLayouts.length == 0)
{
throw new ArgumentException(
string.Format(
"Layout override '{0}' must have 'extend' property mentioning layout to which to apply the overrides", internedLayoutName),
"json");
}
// Add it to our records.
var isReplacement = DoesLayoutExist(internedLayoutName);
m_Layouts.layoutStrings[internedLayoutName] = json;
if (isOverride)
{
for (var i = 0; i < baseLayouts.length; ++i)
{
InternedString[] overrideList;
var baseLayoutName = baseLayouts[i];
m_Layouts.layoutOverrides.TryGetValue(baseLayoutName, out overrideList);
ArrayHelpers.Append(ref overrideList, internedLayoutName);
m_Layouts.layoutOverrides[baseLayoutName] = overrideList;
}
}
PerformLayoutPostRegistration(internedLayoutName, baseLayouts,
isReplacement: isReplacement, isOverride: isOverride);
// If the layout contained a device matcher, register it.
if (!deviceMatcher.empty)
RegisterControlLayoutMatcher(internedLayoutName, deviceMatcher);
}
public void RegisterControlLayoutBuilder(MethodInfo method, object instance, string name,
string baseLayout = null)
{
if (method == null)
throw new ArgumentNullException("method");
if (method.IsGenericMethod)
throw new ArgumentException(string.Format("Method must not be generic ({0})", method), "method");
if (method.GetParameters().Length > 0)
throw new ArgumentException(string.Format("Method must not take arguments ({0})", method), "method");
if (!typeof(InputControlLayout).IsAssignableFrom(method.ReturnType))
throw new ArgumentException(string.Format("Method must return InputControlLayout ({0})", method), "method");
if (string.IsNullOrEmpty(name))
throw new ArgumentException("name");
// If we have an instance, make sure it is [Serializable].
if (instance != null)
{
var type = instance.GetType();
if (type.GetCustomAttribute<SerializableAttribute>(true) == null)
throw new ArgumentException(
string.Format(
"Instance used with {0} to construct a layout must be [Serializable] but {1} is not",
method, type),
"instance");
}
var internedLayoutName = new InternedString(name);
var internedBaseLayoutName = new InternedString(baseLayout);
var isReplacement = DoesLayoutExist(internedLayoutName);
m_Layouts.layoutBuilders[internedLayoutName] = new InputControlLayout.BuilderInfo
{
method = method,
instance = instance
};
PerformLayoutPostRegistration(internedLayoutName, new InlinedArray<InternedString>(internedBaseLayoutName),
isReplacement);
}
private void PerformLayoutPostRegistration(InternedString layoutName, InlinedArray<InternedString> baseLayouts,
bool isReplacement, bool isKnownToBeDeviceLayout = false, bool isOverride = false)
{
++m_LayoutRegistrationVersion;
// For layouts that aren't overrides, add the name of the base
// layout to the lookup table.
if (!isOverride && baseLayouts.length > 0)
{
if (baseLayouts.length > 1)
throw new NotSupportedException(string.Format(
"Layout '{0}' has multiple base layouts; this is only supported on layout overrides",
layoutName));
var baseLayoutName = baseLayouts[0];
if (!baseLayoutName.IsEmpty())
m_Layouts.baseLayoutTable[layoutName] = baseLayoutName;
}
// Recreate any devices using the layout. If it's an override, recreate devices using any of the base layouts.
if (isOverride)
{
for (var i = 0; i < baseLayouts.length; ++i)
RecreateDevicesUsingLayout(baseLayouts[i], isKnownToBeDeviceLayout: isKnownToBeDeviceLayout);
}
else
{
RecreateDevicesUsingLayout(layoutName, isKnownToBeDeviceLayout: isKnownToBeDeviceLayout);
}
// Let listeners know.
var change = isReplacement ? InputControlLayoutChange.Replaced : InputControlLayoutChange.Added;
for (var i = 0; i < m_LayoutChangeListeners.length; ++i)
m_LayoutChangeListeners[i](layoutName.ToString(), change);
}
private void RecreateDevicesUsingLayout(InternedString layout, bool isKnownToBeDeviceLayout = false)
{
if (m_Devices == null)
return;
List<InputDevice> devicesUsingLayout = null;
// Find all devices using the layout.
for (var i = 0; i < m_Devices.Length; ++i)
{
var device = m_Devices[i];
bool usesLayout;
if (isKnownToBeDeviceLayout)
usesLayout = IsControlUsingLayout(device, layout);
else
usesLayout = IsControlOrChildUsingLayoutRecursive(device, layout);
if (usesLayout)
{
if (devicesUsingLayout == null)
devicesUsingLayout = new List<InputDevice>();
devicesUsingLayout.Add(device);
}
}
// If there's none, we're good.
if (devicesUsingLayout == null)
return;
// Remove and re-add the matching devices.
var setup = new InputDeviceBuilder(m_Layouts);
for (var i = 0; i < devicesUsingLayout.Count; ++i)
{
////TODO: preserve state where possible
var device = devicesUsingLayout[i];
RecreateDevice(device, device.m_Layout, setup);
}
}
private bool IsControlOrChildUsingLayoutRecursive(InputControl control, InternedString layout)
{
// Check control itself.
if (IsControlUsingLayout(control, layout))
return true;
// Check children.
var children = control.children;
for (var i = 0; i < children.Count; ++i)
if (IsControlOrChildUsingLayoutRecursive(children[i], layout))
return true;
return false;
}
private bool IsControlUsingLayout(InputControl control, InternedString layout)
{
// Check direct match.
if (control.layout == layout)
return true;
// Check base layout chain.
var baseLayout = control.m_Layout;
while (m_Layouts.baseLayoutTable.TryGetValue(baseLayout, out baseLayout))
if (baseLayout == layout)
return true;
return false;
}
public void RegisterControlLayoutMatcher(string layoutName, InputDeviceMatcher matcher)
{
if (string.IsNullOrEmpty(layoutName))
throw new ArgumentNullException("layoutName");
if (matcher.empty)
throw new ArgumentException("Matcher cannot be empty", "matcher");
// Add to table.
var internedLayoutName = new InternedString(layoutName);
m_Layouts.AddMatcher(internedLayoutName, matcher);
// Recreate any device that we match better than its current layout.
RecreateDevicesUsingLayoutWithInferiorMatch(matcher);
// See if we can make sense of any device we couldn't make sense of before.
AddAvailableDevicesMatchingDescription(matcher, internedLayoutName);
}
private void RecreateDevicesUsingLayoutWithInferiorMatch(InputDeviceMatcher deviceMatcher)
{
if (m_Devices == null)
return;
InputDeviceBuilder builder = null;
var deviceCount = m_Devices.Length;
for (var i = 0; i < deviceCount; ++i)
{
var device = m_Devices[i];
var deviceDescription = device.description;
if (deviceDescription.empty || !(deviceMatcher.MatchPercentage(deviceDescription) > 0))
continue;
var layoutName = TryFindMatchingControlLayout(ref deviceDescription, device.id);
if (layoutName != device.m_Layout)
{
device.m_Description = deviceDescription;
if (builder == null)
builder = new InputDeviceBuilder(m_Layouts);
RecreateDevice(device, layoutName, builder);
// We're removing devices in the middle of the array and appending
// them at the end. Adjust our index and device count to make sure
// we're not iterating all the way into already processed devices.
--i;
--deviceCount;
}
}
}
private InputDevice RecreateDevice(InputDevice device, InternedString newLayout, InputDeviceBuilder builder)
{
// Remove.
RemoveDevice(device);
// Re-setup device.
builder.Setup(newLayout, device.m_Variants, deviceDescription: device.m_Description,
existingDevice: device);
var newDevice = builder.Finish();
// Re-add.
AddDevice(newDevice);
return newDevice;
}
private void AddAvailableDevicesMatchingDescription(InputDeviceMatcher matcher, InternedString layout)
{
// See if the new description to layout mapping allows us to make
// sense of a device we couldn't make sense of so far.
for (var i = 0; i < m_AvailableDeviceCount; ++i)
{
var deviceId = m_AvailableDevices[i].deviceId;
if (TryGetDeviceById(deviceId) != null)
continue;
if (matcher.MatchPercentage(m_AvailableDevices[i].description) > 0f)
{
// Try to create InputDevice instance.
try
{
AddDevice(layout, deviceId, deviceDescription: m_AvailableDevices[i].description,
deviceFlags: m_AvailableDevices[i].isNative ? InputDevice.DeviceFlags.Native : 0);
}
catch (Exception exception)
{
Debug.LogError(string.Format(
"Layout '{0}' matches existing device '{1}' but failed to instantiate: {2}", layout,
m_AvailableDevices[i].description, exception));
Debug.LogException(exception);
continue;
}
// Re-enable device.
var command = EnableDeviceCommand.Create();
m_Runtime.DeviceCommand(deviceId, ref command);
}
}
}
public void RemoveControlLayout(string name, string @namespace = null)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("name");
if (@namespace != null)
name = string.Format("{0}::{1}", @namespace, name);
var internedName = new InternedString(name);
// Remove all devices using the layout.
for (var i = 0; m_Devices != null && i < m_Devices.Length;)
{
var device = m_Devices[i];
if (IsControlOrChildUsingLayoutRecursive(device, internedName))
{
RemoveDevice(device);
}
else
{
++i;
}
}
// Remove layout record.
m_Layouts.layoutTypes.Remove(internedName);
m_Layouts.layoutStrings.Remove(internedName);
m_Layouts.layoutBuilders.Remove(internedName);
m_Layouts.baseLayoutTable.Remove(internedName);
////TODO: check all layout inheritance chain for whether they are based on the layout and if so
//// remove those layouts, too
// Let listeners know.
for (var i = 0; i < m_LayoutChangeListeners.length; ++i)
m_LayoutChangeListeners[i](name, InputControlLayoutChange.Removed);
}
public InputControlLayout TryLoadControlLayout(InternedString name)
{
return m_Layouts.TryLoadLayout(name);
}
////FIXME: allowing the descripting to be modified as part of this is surprising; find a better way
public InternedString TryFindMatchingControlLayout(ref InputDeviceDescription deviceDescription, int deviceId = InputDevice.kInvalidDeviceId)
{
////TODO: this will want to take overrides into account
// See if we can match by description.
var layoutName = m_Layouts.TryFindMatchingLayout(deviceDescription);
if (layoutName.IsEmpty())
{
// No, so try to match by device class. If we have a "Gamepad" layout,
// for example, a device that classifies itself as a "Gamepad" will match
// that layout.
//
// NOTE: Have to make sure here that we get a device layout and not a
// control layout.
if (!string.IsNullOrEmpty(deviceDescription.deviceClass))
{
var deviceClassLowerCase = new InternedString(deviceDescription.deviceClass);
var type = m_Layouts.GetControlTypeForLayout(deviceClassLowerCase);
if (type != null && typeof(InputDevice).IsAssignableFrom(type))
layoutName = new InternedString(deviceDescription.deviceClass);
}
}
////REVIEW: listeners registering new layouts from in here may potentially lead to the creation of devices; should we disallow that?
// Give listeners a shot to select/create a layout.
for (var i = 0; i < m_DeviceFindLayoutCallbacks.length; ++i)
{
var newLayout = m_DeviceFindLayoutCallbacks[i](deviceId, ref deviceDescription, layoutName, m_Runtime);
if (!string.IsNullOrEmpty(newLayout))
{
layoutName = new InternedString(newLayout);
break;
}
}
return layoutName;
}
private bool DoesLayoutExist(InternedString name)
{
return m_Layouts.layoutTypes.ContainsKey(name) ||
m_Layouts.layoutStrings.ContainsKey(name) ||
m_Layouts.layoutBuilders.ContainsKey(name);
}
public int ListControlLayouts(List<string> layouts, string basedOn = null)
{
if (layouts == null)
throw new ArgumentNullException("layouts");
var countBefore = layouts.Count;
////FIXME: this may add a name twice
////REVIEW: are we handling layout overrides correctly here? they shouldn't end up on the list
if (!string.IsNullOrEmpty(basedOn))
{
var internedBasedOn = new InternedString(basedOn);
foreach (var entry in m_Layouts.layoutTypes)
if (m_Layouts.IsBasedOn(internedBasedOn, entry.Key))
layouts.Add(entry.Key);
foreach (var entry in m_Layouts.layoutStrings)
if (m_Layouts.IsBasedOn(internedBasedOn, entry.Key))
layouts.Add(entry.Key);
foreach (var entry in m_Layouts.layoutBuilders)
if (m_Layouts.IsBasedOn(internedBasedOn, entry.Key))
layouts.Add(entry.Key);
}
else
{
foreach (var entry in m_Layouts.layoutTypes)
layouts.Add(entry.Key.ToString());
foreach (var entry in m_Layouts.layoutStrings)
layouts.Add(entry.Key.ToString());
foreach (var entry in m_Layouts.layoutBuilders)
layouts.Add(entry.Key.ToString());
}
return layouts.Count - countBefore;
}
// Processes a path specification that may match more than a single control.
// Adds all controls that match to the given list.
// Returns true if at least one control was matched.
// Must not generate garbage!
public bool TryGetControls(string path, List<InputControl> controls)
{
throw new NotImplementedException();
}
// Return the first match for the given path or null if no control matches.
// Must not generate garbage!
public InputControl TryGetControl(string path)
{
throw new NotImplementedException();
}
public InputControl GetControl(string path)
{
throw new NotImplementedException();
}
// Adds all controls that match the given path spec to the given list.
// Returns number of controls added to the list.
// NOTE: Does not create garbage.
/// <summary>
/// Adds to the given list all controls that match the given <see cref="InputControlPath">path spec</see>
/// and are assignable to the given type.
/// </summary>
/// <param name="path"></param>
/// <param name="controls"></param>
/// <typeparam name="TControl"></typeparam>
/// <returns></returns>
public int GetControls<TControl>(string path, ref InputControlList<TControl> controls)
where TControl : InputControl
{
if (string.IsNullOrEmpty(path))
return 0;
if (m_Devices == null)
return 0;
var deviceCount = m_Devices.Length;
var numMatches = 0;
for (var i = 0; i < deviceCount; ++i)
{
var device = m_Devices[i];
numMatches += InputControlPath.TryFindControls(device, path, 0, ref controls);
}
return numMatches;
}
public void SetLayoutVariant(InputControl control, string variant)
{
if (control == null)
throw new ArgumentNullException("control");
if (string.IsNullOrEmpty(variant))
variant = "Default";
//how can we do this efficiently without having to take the control's device out of the system?
throw new NotImplementedException();
}
public void SetUsage(InputDevice device, InternedString usage)
{
if (device == null)
throw new ArgumentNullException("device");
device.SetUsage(usage);
// Notify listeners.
for (var i = 0; i < m_DeviceChangeListeners.length; ++i)
m_DeviceChangeListeners[i](device, InputDeviceChange.UsageChanged);
// Usage may affect current device so update.
device.MakeCurrent();
}
////TODO: make sure that no device or control with a '/' in the name can creep into the system
public InputDevice AddDevice(Type type, string name = null)
{
if (type == null)
throw new ArgumentNullException("type");
// Find the layout name that the given type was registered with.
var layoutName = m_Layouts.TryFindLayoutForType(type);
if (layoutName.IsEmpty())
{
// Automatically register the given type as a layout.
if (layoutName.IsEmpty())
{
layoutName = new InternedString(type.Name);
RegisterControlLayout(type.Name, type);
}
}
Debug.Assert(!layoutName.IsEmpty(), name);
// Note that since we go through the normal by-name lookup here, this will
// still work if the layout from the type was override with a string layout.
return AddDevice(layoutName);
}
// Creates a device from the given layout and adds it to the system.
// NOTE: Creates garbage.
public InputDevice AddDevice(string layout, string name = null, InternedString variants = new InternedString())
{
if (string.IsNullOrEmpty(layout))
throw new ArgumentException("layout");
var internedLayoutName = new InternedString(layout);
var setup = new InputDeviceBuilder(m_Layouts);
setup.Setup(internedLayoutName, variants);
var device = setup.Finish();
if (!string.IsNullOrEmpty(name))
device.m_Name = new InternedString(name);
AddDevice(device);
return device;
}
// Add device with a forced ID. Used when creating devices reported to us by native.
private InputDevice AddDevice(InternedString layout, int deviceId,
InputDeviceDescription deviceDescription = new InputDeviceDescription(),
InputDevice.DeviceFlags deviceFlags = 0,
InternedString variants = default(InternedString))
{
var setup = new InputDeviceBuilder(m_Layouts);
setup.Setup(new InternedString(layout), deviceDescription: deviceDescription, variants: variants);
var device = setup.Finish();
device.m_Id = deviceId;
device.m_Description = deviceDescription;
device.m_DeviceFlags |= deviceFlags;
// Default display name to product name.
if (!string.IsNullOrEmpty(deviceDescription.product))
device.m_DisplayName = deviceDescription.product;
AddDevice(device);
return device;
}
public void AddDevice(InputDevice device)
{
if (device == null)
throw new ArgumentNullException("device");
if (string.IsNullOrEmpty(device.layout))
throw new ArgumentException("Device has no associated layout", "device");
// Ignore if the same device gets added multiple times.
if (ArrayHelpers.Contains(m_Devices, device))
return;
MakeDeviceNameUnique(device);
AssignUniqueDeviceId(device);
// Add to list.
device.m_DeviceIndex = ArrayHelpers.Append(ref m_Devices, device);
////REVIEW: Not sure a full-blown dictionary is the right way here. Alternatives are to keep
//// a sparse array that directly indexes using the linearly increasing IDs (though that
//// may get large over time). Or to just do a linear search through m_Devices (but
//// that may end up tapping a bunch of memory locations in the heap to find the right
//// device; could be improved by sorting m_Devices by ID and picking a good starting
//// point based on the ID we have instead of searching from [0] always).
m_DevicesById[device.id] = device;
// Let InputStateBuffers know this device doesn't have any associated state yet.
device.m_StateBlock.byteOffset = InputStateBlock.kInvalidOffset;
// Update state buffers.
ReallocateStateBuffers();
InitializeDefaultState(device);
// Update metrics.
m_Metrics.maxNumDevices = Mathf.Max(m_Devices.Length, m_Metrics.maxNumDevices);
m_Metrics.maxStateSizeInBytes = Mathf.Max((int)m_StateBuffers.totalSize, m_Metrics.maxStateSizeInBytes);
////REVIEW: we may want to suppress this during the initial device discovery phase
// Let actions re-resolve their paths.
if (!m_SuppressReResolvingOfActions)
InputActionMapState.ReResolveAllEnabledActions();
// If the device wants automatic callbacks before input updates,
// put it on the list.
var beforeUpdateCallbackReceiver = device as IInputUpdateCallbackReceiver;
if (beforeUpdateCallbackReceiver != null)
onBeforeUpdate += beforeUpdateCallbackReceiver.OnUpdate;
// If the device has state callbacks, make a note of it.
var stateCallbackReceiver = device as IInputStateCallbackReceiver;
if (stateCallbackReceiver != null)
{
InstallBeforeUpdateHookIfNecessary();
device.m_DeviceFlags |= InputDevice.DeviceFlags.HasStateCallbacks;
m_HaveDevicesWithStateCallbackReceivers = true;
}
// If the device wants before-render updates, enable them if they
// aren't already.
if (device.updateBeforeRender)
updateMask |= InputUpdateType.BeforeRender;
InputNoiseFilter interactionFilter = device.userInteractionFilter;
interactionFilter.Apply(device);
// Notify device.
device.NotifyAdded();
// Make the device current.
device.MakeCurrent();
// Notify listeners.
for (var i = 0; i < m_DeviceChangeListeners.length; ++i)
m_DeviceChangeListeners[i](device, InputDeviceChange.Added);
}
public InputDevice AddDevice(InputDeviceDescription description)
{
return AddDevice(description, throwIfNoLayoutFound: true);
}
public InputDevice AddDevice(InputDeviceDescription description, bool throwIfNoLayoutFound,
int deviceId = InputDevice.kInvalidDeviceId, InputDevice.DeviceFlags deviceFlags = 0)
{
// Look for matching layout.
var layout = TryFindMatchingControlLayout(ref description, deviceId);
// If no layout was found, bail out.
if (layout.IsEmpty())
{
if (throwIfNoLayoutFound)
throw new ArgumentException(string.Format("Cannot find layout matching device description '{0}'", description), "description");
// If it's a device coming from the runtime, disable it.
if (deviceId != InputDevice.kInvalidDeviceId)
{
var command = DisableDeviceCommand.Create();
m_Runtime.DeviceCommand(deviceId, ref command);
}
return null;
}
var device = AddDevice(layout, deviceId, description, deviceFlags);
device.m_Description = description;
return device;
}
public void RemoveDevice(InputDevice device)
{
if (device == null)
throw new ArgumentNullException("device");
// If device has not been added, ignore.
if (device.m_DeviceIndex == InputDevice.kInvalidDeviceIndex)
return;
// Remove state monitors while device index is still valid.
RemoveStateChangeMonitors(device);
// Remove from device array.
var deviceIndex = device.m_DeviceIndex;
var deviceId = device.id;
ArrayHelpers.EraseAt(ref m_Devices, deviceIndex);
device.m_DeviceIndex = InputDevice.kInvalidDeviceIndex;
m_DevicesById.Remove(deviceId);
if (m_Devices != null)
{
var oldDeviceIndices = new int[m_Devices.Length];
for (var i = 0; i < m_Devices.Length; ++i)
{
oldDeviceIndices[i] = m_Devices[i].m_DeviceIndex;
m_Devices[i].m_DeviceIndex = i;
}
// Remove from state buffers.
ReallocateStateBuffers(oldDeviceIndices);
}
else
{
// No more devices. Kill state buffers.
m_StateBuffers.FreeAll();
}
// Remove from list of available devices if it's a device coming from
// the runtime.
if (device.native)
{
for (var i = 0; i < m_AvailableDeviceCount; ++i)
{
if (m_AvailableDevices[i].deviceId == deviceId)
{
ArrayHelpers.EraseAtByMovingTail(m_AvailableDevices, ref m_AvailableDeviceCount, i);
break;
}
}
}
// Unbake offset into global state buffers.
device.BakeOffsetIntoStateBlockRecursive((uint)(-device.m_StateBlock.byteOffset));
// Force enabled actions to remove controls from the device.
// We've already set the device index to be invalid so we any attempts
// by actions to uninstall state monitors will get ignored.
if (!m_SuppressReResolvingOfActions)
InputActionMapState.ReResolveAllEnabledActions();
// Kill before update callback, if applicable.
var beforeUpdateCallbackReceiver = device as IInputUpdateCallbackReceiver;
if (beforeUpdateCallbackReceiver != null)
onBeforeUpdate -= beforeUpdateCallbackReceiver.OnUpdate;
// Disable before-render updates if this was the last device
// that requires them.
if (device.updateBeforeRender)
{
var haveDeviceRequiringBeforeRender = false;
if (m_Devices != null)
for (var i = 0; i < m_Devices.Length; ++i)
if (m_Devices[i].updateBeforeRender)
{
haveDeviceRequiringBeforeRender = true;
break;
}
if (!haveDeviceRequiringBeforeRender)
updateMask &= ~InputUpdateType.BeforeRender;
}
// Let device know.
device.NotifyRemoved();
// Let listeners know.
for (var i = 0; i < m_DeviceChangeListeners.length; ++i)
m_DeviceChangeListeners[i](device, InputDeviceChange.Removed);
}
public InputDevice TryGetDevice(string nameOrLayout)
{
if (string.IsNullOrEmpty(nameOrLayout))
throw new ArgumentException("nameOrLayout");