-
Notifications
You must be signed in to change notification settings - Fork 333
Expand file tree
/
Copy pathCoreTests_State.cs
More file actions
1890 lines (1548 loc) · 71.9 KB
/
CoreTests_State.cs
File metadata and controls
1890 lines (1548 loc) · 71.9 KB
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.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.Scripting;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.TestTools;
#if UNITY_EDITOR
using UnityEngine.InputSystem.Editor;
#endif
partial class CoreTests
{
[Test]
[Category("State")]
public void State_CanGetCurrentUpdateType()
{
InputSystem.settings.updateMode = InputSettings.UpdateMode.ProcessEventsInDynamicUpdate;
Assert.That(InputState.currentUpdateType, Is.EqualTo(default(InputUpdateType)));
InputSystem.Update();
Assert.That(InputState.currentUpdateType, Is.EqualTo(InputUpdateType.Dynamic));
InputSystem.settings.updateMode = InputSettings.UpdateMode.ProcessEventsInFixedUpdate;
Assert.That(InputState.currentUpdateType, Is.EqualTo(InputUpdateType.Dynamic));
InputSystem.Update();
Assert.That(InputState.currentUpdateType, Is.EqualTo(InputUpdateType.Fixed));
InputSystem.settings.updateMode = InputSettings.UpdateMode.ProcessEventsManually;
Assert.That(InputState.currentUpdateType, Is.EqualTo(InputUpdateType.Fixed));
InputSystem.Update();
Assert.That(InputState.currentUpdateType, Is.EqualTo(InputUpdateType.Manual));
#if UNITY_EDITOR
runtime.onShouldRunUpdate = _ => true;
InputSystem.Update(InputUpdateType.Editor);
Assert.That(InputState.currentUpdateType, Is.EqualTo(InputUpdateType.Editor));
#endif
}
[Test]
[Category("State")]
public void State_CanGetUpdateCount()
{
Assert.That(InputState.updateCount, Is.Zero);
InputSystem.Update();
Assert.That(InputState.updateCount, Is.EqualTo(1));
InputSystem.Update();
Assert.That(InputState.updateCount, Is.EqualTo(2));
}
[Test]
[Category("State")]
[Ignore("TODO")]
public void TODO_State_CanGetUpdateCount_ForEditorUpdates()
{
InputSystem.Update(InputUpdateType.Editor);
Assert.That(InputState.updateCount, Is.EqualTo(1));
}
[Test]
[Category("State")]
public void State_CanComputeStateLayoutFromStateStructure()
{
var gamepad = InputDevice.Build<Gamepad>();
Assert.That(gamepad.stateBlock.sizeInBits, Is.EqualTo(UnsafeUtility.SizeOf<GamepadState>() * 8));
Assert.That(gamepad.leftStick.stateBlock.byteOffset,
Is.EqualTo(Marshal.OffsetOf(typeof(GamepadState), "leftStick").ToInt32()));
Assert.That(gamepad.dpad.stateBlock.byteOffset,
Is.EqualTo(Marshal.OffsetOf(typeof(GamepadState), "buttons").ToInt32()));
}
[Test]
[Category("State")]
public void State_CanComputeStateLayoutForNestedStateStructures()
{
InputSystem.RegisterLayout<CustomDevice>();
var device = InputDevice.Build<CustomDevice>();
var axis2 = device.GetChildControl("axis2");
var nestedOffset = Marshal.OffsetOf(typeof(CustomDeviceState), "nested").ToInt32();
var axis2Offset = nestedOffset + Marshal.OffsetOf(typeof(CustomNestedDeviceState), "axis2").ToInt32();
Assert.That(axis2.stateBlock.byteOffset, Is.EqualTo(axis2Offset));
}
[Test]
[Category("State")]
public void State_CanComputeStateLayoutForMultiByteBitfieldWithFixedOffset()
{
var keyboard = InputDevice.Build<Keyboard>();
var downArrow = keyboard.GetChildControl("DownArrow");
Assert.That(downArrow.stateBlock.bitOffset, Is.EqualTo((int)Key.DownArrow));
Assert.That(downArrow.stateBlock.byteOffset, Is.EqualTo(0));
Assert.That(keyboard.stateBlock.alignedSizeInBytes, Is.EqualTo(KeyboardState.kSizeInBytes));
}
[Test]
[Category("State")]
public void State_BeforeAddingDevice_OffsetsInStateLayoutsAreRelativeToRoot()
{
var device = InputDevice.Build<Gamepad>();
var leftStickOffset = Marshal.OffsetOf(typeof(GamepadState), "leftStick").ToInt32();
var leftStickXOffset = leftStickOffset;
var leftStickYOffset = leftStickOffset + 4;
Assert.That(device.leftStick.x.stateBlock.byteOffset, Is.EqualTo(leftStickXOffset));
Assert.That(device.leftStick.y.stateBlock.byteOffset, Is.EqualTo(leftStickYOffset));
}
[Test]
[Category("State")]
public void State_AfterAddingDevice_AllControlOffsetsAreRelativeToGlobalStateBuffer()
{
InputSystem.AddDevice("Gamepad");
var gamepad2 = InputSystem.AddDevice<Gamepad>();
var leftStickOffset = Marshal.OffsetOf(typeof(GamepadState), "leftStick").ToInt32();
var leftStickXOffset = leftStickOffset;
var leftStickYOffset = leftStickOffset + 4;
var gamepad2StartOffset = gamepad2.stateBlock.byteOffset;
Assert.That(gamepad2.leftStick.x.stateBlock.byteOffset, Is.EqualTo(gamepad2StartOffset + leftStickXOffset));
Assert.That(gamepad2.leftStick.y.stateBlock.byteOffset, Is.EqualTo(gamepad2StartOffset + leftStickYOffset));
}
[Test]
[Category("State")]
public void State_StateOfMultipleDevicesIsLaidOutSequentially()
{
var gamepad1 = InputSystem.AddDevice("Gamepad");
var gamepad2 = InputSystem.AddDevice("Gamepad");
var sizeofGamepadState = UnsafeUtility.SizeOf<GamepadState>();
Assert.That(gamepad1.stateBlock.byteOffset, Is.EqualTo(0));
Assert.That(gamepad2.stateBlock.byteOffset, Is.EqualTo(gamepad1.stateBlock.byteOffset + sizeofGamepadState));
}
[Test]
[Category("State")]
public void State_RunningUpdateSwapsCurrentAndPrevious()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
var oldState = new GamepadState
{
leftTrigger = 0.25f
};
var newState = new GamepadState
{
leftTrigger = 0.75f
};
InputSystem.QueueStateEvent(gamepad, oldState);
InputSystem.Update();
Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.25f).Within(0.000001));
InputSystem.QueueStateEvent(gamepad, newState);
InputSystem.Update();
Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.75f).Within(0.00001));
Assert.That(gamepad.leftTrigger.ReadValueFromPreviousFrame(), Is.EqualTo(0.25f).Within(0.00001));
}
// This test makes sure that a double-buffered state scheme does not lose state. In double buffering,
// this only works if either the entire state is refreshed each step -- which for us is not guaranteed
// as we don't know if a state event for a device will happen on a frame -- or if state is copied forward
// between the buffers.
[Test]
[Category("State")]
public void State_UpdateWithoutStateEventDoesNotAlterStateOfDevice()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
var state = new GamepadState
{
leftTrigger = 0.25f
};
InputSystem.QueueStateEvent(gamepad, state);
InputSystem.Update();
InputSystem.Update();
Assert.That(gamepad.leftTrigger.ReadValue(), Is.EqualTo(0.25f).Within(0.000001));
}
// The state layout for a given device is not fixed. Even though Gamepad, for example, specifies
// GamepadState as its state struct, this does not necessarily mean that an actual Gamepad instance
// will actually end up with that specific state layout. This is why Gamepad should not assume
// that 'currentValuePtr' is a pointer to a GamepadState.
//
// Layouts can be used to re-arrange the state layout of their base layout. One case where
// this is useful are HIDs. On OSX, for example, gamepad state data does not arrive in its own
// distinct format but rather comes in as the same generic state data as any other HID device.
// Yet we still want a gamepad to come out as a Gamepad and not as a generic InputDevice. If we
// weren't able to customize the state layout of a gamepad, we'd have to have code somewhere
// along the way that takes the incoming HID data, interprets it to determine that it is in
// fact coming from a gamepad HID, and re-arranges it into a GamepadState-compatible format
// (which requires knowledge of the specific layout used by the HID). By having flexible state
// layouts we can do this entirely through data using just layouts.
//
// A layout that customizes state layout can also "park" unused controls outside the block of
// data that will actually be sent in via state events. Space for the unused controls will still
// be allocated in the state buffers (since InputControls still refer to it) but InputManager
// is okay with sending StateEvents that are shorter than the full state block of a device.
////REVIEW: we might want to equip InputControls with the ability to be disabled (in which case they return default values)
[Test]
[Category("State")]
public void State_CanCustomizeStateLayoutOfDevice()
{
// Create a custom layout that moves the offsets of some controls around.
var jsonLayout = @"
{
""name"" : ""CustomGamepad"",
""extend"" : ""Gamepad"",
""format"" : ""CUST"",
""controls"" : [
{
""name"" : ""buttonSouth"",
""offset"" : 800
}
]
}
";
InputSystem.RegisterLayout(jsonLayout);
var device = InputDevice.Build<Gamepad>("CustomGamepad");
Assert.That(device.GetChildControl("buttonSouth").stateBlock.byteOffset, Is.EqualTo(800));
Assert.That(device.stateBlock.sizeInBits, Is.EqualTo(801 * 8)); // Button bitfield adds one byte.
}
[Test]
[Category("State")]
public void State_DoesNotNeedToBe4ByteAligned()
{
var jsonLayout = @"
{
""name"" : ""TestDevice"",
""format"" : ""CUST"",
""controls"" : [
{
""name"" : ""button1"",
""layout"" : ""Button""
}
]
}
";
InputSystem.RegisterLayout(jsonLayout);
var device1 = InputSystem.AddDevice("TestDevice");
var device2 = InputSystem.AddDevice("TestDevice");
// State block sizes should correspond exactly to what's on the device aligned
// to next byte offset.
Assert.That(device1.stateBlock.sizeInBits, Is.EqualTo(8));
Assert.That(device2.stateBlock.sizeInBits, Is.EqualTo(8));
// But offsets in the state buffers should be 4-byte aligned. This ensures that we
// comply to alignment restrictions on ARMs.
Assert.That(device1.stateBlock.byteOffset, Is.EqualTo(0));
Assert.That(device2.stateBlock.byteOffset, Is.EqualTo(4));
}
[Test]
[Category("State")]
public void State_CanStoreAxisAsShort()
{
// Make right trigger be represented as just a short and force it to different offset.
var jsonLayout = @"
{
""name"" : ""CustomGamepad"",
""extend"" : ""Gamepad"",
""controls"" : [
{
""name"" : ""rightTrigger"",
""format"" : ""SHRT"",
""offset"" : 0
}
]
}
";
InputSystem.RegisterLayout(jsonLayout);
var device = InputDevice.Build<Gamepad>("CustomGamepad");
Assert.That(device.rightTrigger.stateBlock.format, Is.EqualTo(InputStateBlock.FormatShort));
}
[Test]
[Category("State")]
[TestCase("Axis")]
[TestCase("Double")]
public void State_CanStoreControlAsMultiBitfield(string controlType)
{
var json = @"
{
""name"" : ""TestDevice"",
""controls"" : [
{
""name"" : ""max"",
""layout"" : ""__CONTROLTYPE__"",
""format"" : ""BIT"",
""offset"" : 0,
""sizeInBits"" : 7,
""defaultState"" : 127
},
{
""name"" : ""min"",
""layout"" : ""__CONTROLTYPE__"",
""format"" : ""BIT"",
""offset"" : 1,
""bit"" : 0,
""sizeInBits"" : 7,
""defaultState"" : 0
},
{
""name"" : ""mid"",
""layout"" : ""__CONTROLTYPE__"",
""format"" : ""BIT"",
""offset"" : 2,
""sizeInBits"" : 7,
""defaultState"" : 63
}
]
}".Replace("__CONTROLTYPE__", controlType);
InputSystem.RegisterLayout(json);
var device = InputSystem.AddDevice("TestDevice");
var min = device["min"];
var max = device["max"];
var mid = device["mid"];
var minValue = min.ReadValueAsObject();
var maxValue = max.ReadValueAsObject();
var midValue = mid.ReadValueAsObject();
Assert.That(minValue, Is.EqualTo(0).Within(0.00001));
Assert.That(maxValue, Is.EqualTo(1).Within(0.00001));
Assert.That(midValue, Is.EqualTo(0.5).Within(1 / 128f)); // Precision dictated by number of bits we have available.
}
[Test]
[Category("State")]
public void State_AppendsControlsWithoutForcedOffsetToEndOfState()
{
var json = @"
{
""name"" : ""MyDevice"",
""controls"" : [
{
""name"" : ""controlWithFixedOffset"",
""layout"" : ""Analog"",
""offset"" : ""10"",
""format"" : ""FLT""
},
{
""name"" : ""controlWithAutomaticOffset"",
""layout"" : ""Button""
}
]
}
";
InputSystem.RegisterLayout(json);
var device = InputDevice.Build<InputDevice>("MyDevice");
Assert.That(device.GetChildControl("controlWithAutomaticOffset").stateBlock.byteOffset, Is.EqualTo(14));
Assert.That(device.stateBlock.sizeInBits, Is.EqualTo(15 * 8));
}
[Test]
[Category("State")]
public void State_CanSpecifyBitOffsetsOnControlProperties()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
Assert.That(gamepad.dpad.right.stateBlock.bitOffset, Is.EqualTo((int)DpadControl.ButtonBits.Right));
Assert.That(gamepad.dpad.right.stateBlock.byteOffset, Is.EqualTo(gamepad.dpad.stateBlock.byteOffset));
}
// Using "offset = N" with an InputControlAttribute that doesn't specify a child path (or even then?)
// should add the base offset of the field itself.
[Test]
[Category("State")]
[Ignore("TODO")]
public void TODO_State_SpecifyingOffsetOnControlAttribute_AddsBaseOffset()
{
Assert.Fail();
}
[Test]
[Category("State")]
public void State_CanUpdateButtonStateUsingEvent()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
Assert.That(gamepad.buttonEast.isPressed, Is.False);
var newState = new GamepadState {buttons = 1 << (int)GamepadButton.B};
InputSystem.QueueStateEvent(gamepad, newState);
InputSystem.Update();
Assert.That(gamepad.buttonEast.isPressed, Is.True);
}
[Test]
[Category("State")]
public void State_CanDetectWhetherButtonStateHasChangedThisFrame()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
Assert.That(gamepad.buttonEast.wasPressedThisFrame, Is.False);
Assert.That(gamepad.buttonEast.wasReleasedThisFrame, Is.False);
var firstState = new GamepadState {buttons = 1 << (int)GamepadButton.B};
InputSystem.QueueStateEvent(gamepad, firstState);
InputSystem.Update();
Assert.That(gamepad.buttonEast.wasPressedThisFrame, Is.True);
Assert.That(gamepad.buttonEast.wasReleasedThisFrame, Is.False);
// Input update with no changes should make both properties go back to false.
InputSystem.Update();
Assert.That(gamepad.buttonEast.wasPressedThisFrame, Is.False);
Assert.That(gamepad.buttonEast.wasReleasedThisFrame, Is.False);
var secondState = new GamepadState {buttons = 0};
InputSystem.QueueStateEvent(gamepad, secondState);
InputSystem.Update();
Assert.That(gamepad.buttonEast.wasPressedThisFrame, Is.False);
Assert.That(gamepad.buttonEast.wasReleasedThisFrame, Is.True);
}
[Test]
[Category("State")]
[TestCase(true)]
[TestCase(false)]
public void State_PressingAndReleasingButtonInSameFrame_ShowsStateChange(bool usesReadValueCaching)
{
var originalSetting = InputSystem.settings.IsFeatureEnabled(InputFeatureNames.kUseReadValueCaching);
InputSystem.settings.SetInternalFeatureFlag(InputFeatureNames.kUseReadValueCaching, usesReadValueCaching);
var gamepad = InputSystem.AddDevice<Gamepad>();
var firstState = new GamepadState {buttons = 1 << (int)GamepadButton.B};
var secondState = new GamepadState {buttons = 0};
InputSystem.QueueStateEvent(gamepad, firstState);
InputSystem.QueueStateEvent(gamepad, secondState);
InputSystem.Update();
// We don't listen for inter-frame press/releases until we see them being requested, so the first time we try
// to detect it for a given device+ButtonControl, we'll miss the event.
Assert.That(gamepad.buttonEast.isPressed, Is.False);
Assert.That(gamepad.buttonEast.wasPressedThisFrame, Is.False);
Assert.That(gamepad.buttonEast.wasReleasedThisFrame, Is.False);
InputSystem.QueueStateEvent(gamepad, firstState);
InputSystem.QueueStateEvent(gamepad, secondState);
InputSystem.Update();
Assert.That(gamepad.buttonEast.isPressed, Is.False);
Assert.That(gamepad.buttonEast.wasPressedThisFrame, Is.True);
Assert.That(gamepad.buttonEast.wasReleasedThisFrame, Is.True);
InputSystem.QueueStateEvent(gamepad, firstState);
InputSystem.QueueStateEvent(gamepad, secondState);
InputSystem.QueueStateEvent(gamepad, firstState);
InputSystem.Update();
Assert.That(gamepad.buttonEast.isPressed, Is.True);
Assert.That(gamepad.buttonEast.wasPressedThisFrame, Is.True);
Assert.That(gamepad.buttonEast.wasReleasedThisFrame, Is.True);
InputSystem.QueueStateEvent(gamepad, firstState);
InputSystem.QueueStateEvent(gamepad, secondState);
InputSystem.QueueStateEvent(gamepad, firstState);
InputSystem.QueueStateEvent(gamepad, secondState);
InputSystem.QueueStateEvent(gamepad, firstState);
InputSystem.QueueStateEvent(gamepad, secondState);
InputSystem.Update();
Assert.That(gamepad.buttonEast.isPressed, Is.False);
Assert.That(gamepad.buttonEast.wasPressedThisFrame, Is.True);
Assert.That(gamepad.buttonEast.wasReleasedThisFrame, Is.True);
InputSystem.settings.SetInternalFeatureFlag(InputFeatureNames.kUseReadValueCaching, originalSetting);
}
[Test]
[Category("State")]
public void State_CanStoreButtonAsFloat()
{
// Turn buttonSouth into float and move to left/x offset (so we can use
// GamepadState to set it).
const string json = @"
{
""name"" : ""CustomGamepad"",
""extend"" : ""Gamepad"",
""controls"" : [
{
""name"" : ""buttonSouth"",
""format"" : ""FLT"",
""offset"" : 4,
""bit"" : 0
}
]
}
";
InputSystem.RegisterLayout(json);
var gamepad = (Gamepad)InputSystem.AddDevice("CustomGamepad");
var state = new GamepadState {leftStick = new Vector2(0.5f, 0.0f)};
InputSystem.QueueStateEvent(gamepad, state);
InputSystem.Update();
Assert.That(gamepad.buttonSouth.ReadValue(), Is.EqualTo(0.5f));
}
[Test]
[Category("State")]
public void State_CanListenForInputUpdates()
{
// Bypass InputManager.ShouldRunUpdate().
runtime.onShouldRunUpdate = _ => true;
var receivedUpdate = false;
InputSystem.onBeforeUpdate +=
() =>
{
Assert.That(receivedUpdate, Is.False);
receivedUpdate = true;
};
InputSystem.Update();
Assert.That(receivedUpdate, Is.True);
receivedUpdate = false;
// Before render. Disabled by default. Add a device that needs before-render updates
// so that the update gets enabled.
const string kBeforeRenderDevice = @"
{
""name"" : ""BeforeRenderGamepad"",
""extend"" : ""Gamepad"",
""beforeRender"" : ""Update""
}
";
InputSystem.RegisterLayout(kBeforeRenderDevice);
InputSystem.AddDevice("BeforeRenderGamepad");
InputSystem.Update(InputUpdateType.BeforeRender);
Assert.That(receivedUpdate, Is.True);
#if UNITY_EDITOR
receivedUpdate = false;
// Editor.
InputSystem.Update(InputUpdateType.Editor);
Assert.That(receivedUpdate, Is.True);
#endif
}
// To build systems that can respond to inputs changing value, there's support for setting
// up monitor on state (essentially locks around memory regions). This is used by the action
// system to build its entire machinery but the core mechanism is available to anyone.
[Test]
[Category("State")]
public void State_CanSetUpMonitorsForStateChanges()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
var monitorFired = false;
InputControl receivedControl = null;
double? receivedTime = null;
InputEventPtr? receivedEventPtr = null;
var monitor = InputState.AddChangeMonitor(gamepad.leftStick,
(control, time, eventPtr, monitorIndex) =>
{
Assert.That(!monitorFired);
monitorFired = true;
receivedControl = control;
receivedTime = time;
receivedEventPtr = eventPtr;
});
// Left stick only.
InputSystem.QueueStateEvent(gamepad, new GamepadState {leftStick = new Vector2(0.5f, 0.5f)}, 0.5);
InputSystem.Update();
Assert.That(monitorFired, Is.True);
Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
Assert.That(receivedTime.Value, Is.EqualTo(0.5).Within(0.000001));
Assert.That(receivedEventPtr.Value.deviceId, Is.EqualTo(gamepad.deviceId));
monitorFired = false;
receivedControl = null;
receivedTime = 0;
receivedEventPtr = null;
// Left stick again but with no value change.
InputSystem.QueueStateEvent(gamepad, new GamepadState {leftStick = new Vector2(0.5f, 0.5f)}, 0.6);
InputSystem.Update();
Assert.That(monitorFired, Is.False);
// Left and right stick.
InputSystem.QueueStateEvent(gamepad,
new GamepadState {rightStick = new Vector2(0.75f, 0.75f), leftStick = new Vector2(0.75f, 0.75f)}, 0.7);
InputSystem.Update();
Assert.That(monitorFired, Is.True);
Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
Assert.That(receivedTime.Value, Is.EqualTo(0.7).Within(0.000001));
Assert.That(receivedEventPtr.Value.deviceId, Is.EqualTo(gamepad.deviceId));
monitorFired = false;
receivedControl = null;
receivedTime = 0;
receivedEventPtr = null;
// Right stick only.
InputSystem.QueueStateEvent(gamepad,
new GamepadState {rightStick = new Vector2(0.5f, 0.5f), leftStick = new Vector2(0.75f, 0.75f)}, 0.8);
InputSystem.Update();
Assert.That(monitorFired, Is.False);
// Component control of left stick.
InputSystem.QueueStateEvent(gamepad, new GamepadState {leftStick = new Vector2(0.75f, 0.5f)}, 0.9);
InputSystem.Update();
Assert.That(monitorFired, Is.True);
////REVIEW: do we want to be able to detect the child control that actually changed? could be multiple, though
Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
Assert.That(receivedTime.Value, Is.EqualTo(0.9).Within(0.000001));
Assert.That(receivedEventPtr.Value.deviceId, Is.EqualTo(gamepad.deviceId));
// Remove state monitor and change leftStick again.
InputState.RemoveChangeMonitor(gamepad.leftStick, monitor);
monitorFired = false;
receivedControl = null;
receivedTime = 0;
receivedEventPtr = null;
InputSystem.QueueStateEvent(gamepad, new GamepadState {leftStick = new Vector2(0.0f, 0.0f)}, 1.0);
InputSystem.Update();
Assert.That(monitorFired, Is.False);
}
#if UNITY_EDITOR
[Test]
[Category("State")]
public void State_CanSetUpMonitorsForStateChanges_InEditor()
{
// InputTestFixture puts this at ExactlyAsInPlayer. Give us a setting that allows
// gamepad input to go through to the editor.
InputSystem.settings.editorInputBehaviorInPlayMode = InputSettings.EditorInputBehaviorInPlayMode.AllDevicesRespectGameViewFocus;
var gamepad = InputSystem.AddDevice<Gamepad>();
var monitorFired = false;
InputState.AddChangeMonitor(gamepad.leftStick,
(control, time, eventPtr, monitorIndex) => monitorFired = true);
ScheduleFocusChangedEvent(applicationHasFocus: false);
InputSystem.Update(InputUpdateType.Dynamic);
Set(gamepad.leftStick, new Vector2(0.123f, 0.234f), queueEventOnly: true);
InputSystem.Update(InputUpdateType.Editor);
Assert.That(monitorFired, Is.True);
}
#endif
struct StateWithMultiBitControl : IInputStateTypeInfo
{
// Dpad layout that is identical to how the PS4 DualShock controller sets up its Dpad.
// Offset the whole dpad by 3 bits to make sure we're not only supporting the case where
// the multi-bit value is byte-aligned.
[InputControl(name = "dpad", layout = "Dpad", sizeInBits = 4, bit = 3)]
[InputControl(name = "dpad/up", layout = "DiscreteButton", parameters = "minValue=7,maxValue=1,nullValue=8,wrapAtValue=7", bit = 3, sizeInBits = 4)]
[InputControl(name = "dpad/right", layout = "DiscreteButton", parameters = "minValue=1,maxValue=3", bit = 3, sizeInBits = 4)]
[InputControl(name = "dpad/down", layout = "DiscreteButton", parameters = "minValue=3,maxValue=5", bit = 3, sizeInBits = 4)]
[InputControl(name = "dpad/left", layout = "DiscreteButton", parameters = "minValue=5, maxValue=7", bit = 3, sizeInBits = 4)]
public int buttons;
// Add a whacky 23bit button that isn't byte aligned.
[InputControl(name = "data", layout = "DiscreteButton", bit = 4, sizeInBits = 23)]
public long data;
public StateWithMultiBitControl WithDpad(int value)
{
buttons |= value << 3;
return this;
}
public StateWithMultiBitControl WithData(int value)
{
data = value << 4 & (0x7fff << 4);
return this;
}
public FourCC format => new FourCC('T', 'E', 'S', 'T');
}
[InputControlLayout(stateType = typeof(StateWithMultiBitControl))]
private class TestDeviceWithMultiBitControl : InputDevice
{
}
[Test]
[Category("State")]
public void State_CanSetUpMonitorsForStateChanges_OnMultiBitFields()
{
var device = InputSystem.AddDevice<TestDeviceWithMultiBitControl>();
var monitorFired = false;
InputControl receivedControl = null;
void Callback(InputControl control, double time, InputEventPtr eventPtr, long monitorIndex)
{
Assert.That(!monitorFired);
monitorFired = true;
receivedControl = control;
}
InputState.AddChangeMonitor(device["dpad"], Callback);
InputState.AddChangeMonitor(device["data"], Callback);
InputSystem.QueueStateEvent(device, new StateWithMultiBitControl().WithDpad(3));
InputSystem.Update();
Assert.That(monitorFired);
Assert.That(receivedControl, Is.SameAs(device["dpad"]));
monitorFired = false;
receivedControl = null;
InputSystem.QueueStateEvent(device, new StateWithMultiBitControl().WithDpad(3).WithData(1234));
InputSystem.Update();
Assert.That(monitorFired);
Assert.That(receivedControl, Is.SameAs(device["data"]));
}
[Test]
[Category("State")]
public void State_CanRemoveStateChangeMonitorWithSpecificMonitorIndex()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
const int kLeftStick = 12345678;
const int kRightStick = 87654321;
var monitorFired = false;
long? receivedMonitorIndex = null;
var monitor = InputState.AddChangeMonitor(gamepad.leftStick,
(control, time, eventPtr, monitorIndex) =>
{
Assert.That(!monitorFired);
monitorFired = true;
receivedMonitorIndex = monitorIndex;
}, kLeftStick);
InputState.AddChangeMonitor(gamepad.rightStick, monitor, kRightStick);
InputSystem.QueueStateEvent(gamepad, new GamepadState {leftStick = Vector2.one});
InputSystem.Update();
Assert.That(monitorFired);
Assert.That(receivedMonitorIndex.Value, Is.EqualTo(kLeftStick));
monitorFired = false;
receivedMonitorIndex = null;
InputSystem.QueueStateEvent(gamepad, new GamepadState {rightStick = Vector2.one, leftStick = Vector2.one});
InputSystem.Update();
Assert.That(monitorFired);
Assert.That(receivedMonitorIndex.Value, Is.EqualTo(kRightStick));
InputState.RemoveChangeMonitor(gamepad.leftStick, monitor, kLeftStick);
monitorFired = false;
receivedMonitorIndex = null;
InputSystem.QueueStateEvent(gamepad, new GamepadState {rightStick = Vector2.one});
InputSystem.Update();
Assert.That(!monitorFired);
InputSystem.QueueStateEvent(gamepad, new GamepadState());
InputSystem.Update();
Assert.That(monitorFired);
Assert.That(receivedMonitorIndex.Value, Is.EqualTo(kRightStick));
}
[Test]
[Category("State")]
public void State_StateChangeMonitorsStayIntactWhenOtherDevicesAreRemoved()
{
InputSystem.AddDevice<Keyboard>(); // Noise.
var gamepad = InputSystem.AddDevice<Gamepad>();
var mouse = InputSystem.AddDevice<Mouse>();
var positionMonitorFired = false;
InputState.AddChangeMonitor(mouse.position, (control, d, arg3, arg4) => positionMonitorFired = true);
InputSystem.RemoveDevice(gamepad);
Set(mouse.position, new Vector2(123, 234));
Assert.That(positionMonitorFired);
}
[Test]
[Category("State")]
public void State_CurrentTimeTakesOffsetToRealtimeSinceStartupIntoAccount()
{
runtime.currentTime = 2;
runtime.currentTimeOffsetToRealtimeSinceStartup = 1;
Assert.That(InputState.currentTime, Is.EqualTo(1));
Assert.Greater(InputRuntime.s_Instance.currentTime, InputState.currentTime);
}
// For certain actions, we want to be able to tell whether a specific input arrives in time.
// For example, we may want to only trigger an action if a specific button was released within
// a certain amount of time. To support this, the system allows putting timeouts on individual
// state monitors. If the state monitor fires before the timeout expires, nothing happens. If,
// however, the timeout expires, NotifyTimerExpired() is called when the input system updates
// and the IInputRuntime's currentTime has advanced to or past the given time.
[Test]
[Category("State")]
public void State_CanWaitForStateChangeWithinGivenAmountOfTime()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
var monitorFired = false;
var timeoutFired = false;
double? receivedTime = null;
int? receivedTimerIndex = null;
InputControl receivedControl = null;
var monitor = InputState.AddChangeMonitor(gamepad.leftStick,
(control, time, eventPtr, monitorIndex) =>
{
Assert.That(!monitorFired);
monitorFired = true;
}, timerExpiredCallback:
(control, time, monitorIndex, timerIndex) =>
{
Assert.That(!timeoutFired);
timeoutFired = true;
receivedTime = time;
receivedTimerIndex = timerIndex;
receivedControl = control;
});
// Add and immediately expire timeout.
InputState.AddChangeMonitorTimeout(gamepad.leftStick, monitor, currentTime + 1,
timerIndex: 1234);
currentTime += 2;
InputSystem.Update();
Assert.That(timeoutFired);
Assert.That(!monitorFired);
Assert.That(receivedTimerIndex.Value, Is.EqualTo(1234));
Assert.That(receivedTime.Value, Is.EqualTo(currentTime).Within(0.00001));
Assert.That(receivedControl, Is.SameAs(gamepad.leftStick));
timeoutFired = false;
receivedTimerIndex = null;
receivedTime = null;
// Add timeout and perform a state change. Then advance past timeout time
// and make sure we *DO* get a notification.
InputState.AddChangeMonitorTimeout(gamepad.leftStick, monitor, currentTime + 1,
timerIndex: 4321);
InputSystem.QueueStateEvent(gamepad, new GamepadState {leftStick = Vector2.one});
InputSystem.Update();
Assert.That(monitorFired);
Assert.That(!timeoutFired);
monitorFired = false;
currentTime += 2;
InputSystem.Update();
Assert.That(!monitorFired);
Assert.That(timeoutFired);
timeoutFired = false;
// Add and remove timeout. Then advance past timeout time and make sure we *don't*
// get a notification.
InputState.AddChangeMonitorTimeout(gamepad.leftStick, monitor, currentTime + 1,
timerIndex: 1423);
InputState.RemoveChangeMonitorTimeout(monitor, timerIndex: 1423);
InputSystem.QueueStateEvent(gamepad, new GamepadState {leftStick = Vector2.one});
InputSystem.Update();
Assert.That(!timeoutFired);
}
// Actions will process interactions inside of monitor callbacks. Since interactions can add
// timeouts, make sure that they make it through properly.
[Test]
[Category("State")]
public void State_StateChangeMonitorTimeout_CanBeAddedFromMonitorCallback()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
var monitorFired = false;
var timeoutFired = false;
IInputStateChangeMonitor monitor = null;
monitor = InputState.AddChangeMonitor(gamepad.leftStick,
(control, time, eventPtr, monitorIndex) =>
{
Assert.That(!monitorFired);
monitorFired = true;
InputState.AddChangeMonitorTimeout(gamepad.leftStick, monitor,
InputState.currentTime + 1);
}, timerExpiredCallback:
(control, time, monitorIndex, timerIndex) =>
{
Assert.That(!timeoutFired);
timeoutFired = true;
});
// Trigger monitor callback.
InputSystem.QueueStateEvent(gamepad, new GamepadState {leftStick = Vector2.one});
InputSystem.Update();
Assert.That(monitorFired);
// Expire timer.
currentTime += 2;
InputSystem.Update();
Assert.That(timeoutFired);
}
[Test]
[Category("State")]
public void State_StateChangeMonitorTimeout_CanBeAddedFromTimeoutCallback()
{
var gamepad = InputSystem.AddDevice<Gamepad>();
var timeoutCount = 0;
IInputStateChangeMonitor monitor = null;
monitor = InputState.AddChangeMonitor(gamepad.buttonSouth,
(control, time, eventPtr, monitorIndex) => {},
timerExpiredCallback: (control, time, monitorIndex, timerIndex) =>