-
Notifications
You must be signed in to change notification settings - Fork 47
/
FContext.cs
1201 lines (960 loc) · 47.9 KB
/
FContext.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 UnityEngine;
using g3;
namespace f3 {
public delegate void ContextWindowResizeEvent();
/// <summary>
/// The universe
/// </summary>
public class FContext {
// [TODO] would like to get rid of this...but in a few places it was clunky to keep a reference
public static FContext ActiveContext_HACK;
// global events
public event ContextWindowResizeEvent OnWindowResized;
// global state
public static bool WindowHasFocus = true;
SceneOptions options;
FScene scene; // set of objects in our universe
ICursorController mouseCursor; // handles mouse cursor interaction
SpatialInputController spatialCursor; // handles spatial interaction in VR
CameraTracking camTracker; // tracks some camera stuff that we probably could just put here now...
TransformManager transformManager; // manages transform gizmos
ToolManager toolManager; // manages active tools
ICameraInteraction mouseCamControls; // camera hotkeys and interactions
bool bInCameraControl;
Capture captureMouse; // current object that is capturing mouse/gamepad input
Capture captureTouch; // current object that is capturing touch input
Capture captureLeft; // current object capturing left spatial controller input
Capture captureRight; // ditto right
Cockpit activeCockpit; // (optional) HUD that kind of sticks to view
Stack<Cockpit> cockpitStack;
InputBehaviorSet inputBehaviors; // behaviors that can capture left/right input
InputBehaviorSet overrideBehaviors; // behaviors that do not capture, just respond
// to specific events (like menu button)
ITextEntryTarget activeTextTarget; // current object that receives text input
// (there can be only one!)
ActionSet nextFrameActions; // actions that will be run in the next frame, before
// UI event handling, prerender(), etc
ActionSet everyFrameActions; // actions that will be run every frame until removed
public TransformManager TransformManager {
get { return this.transformManager; }
}
public ToolManager ToolManager {
get { return this.toolManager; }
}
// [RMS] why do it this way? can't we just create in Start?
public FScene Scene {
get { return GetScene (); }
}
public FScene GetScene() {
if (scene == null)
scene = new FScene (this);
return scene;
}
public fCamera ActiveCamera
{
get { return camTracker.MainCamera; }
}
// UI camera is orthographic projection, does not exist in VR contexts
public fCamera OrthoUICamera
{
get { return camTracker.OrthoUICamera; }
}
public CameraTracking CameraManager {
get { return camTracker; }
}
public Cockpit ActiveCockpit {
get { return activeCockpit; }
}
public ICursorController MouseController {
get {
if (mouseCursor == null) {
if (FPlatform.IsUsingVR())
mouseCursor = new VRMouseCursorController(ActiveCamera, this);
else if ( FPlatform.IsTouchDevice() )
mouseCursor = new TouchMouseCursorController(this);
else
mouseCursor = new SystemMouseCursorController(this);
}
return mouseCursor;
}
}
public SpatialInputController SpatialController
{
get {
if (spatialCursor == null) {
spatialCursor = new SpatialInputController(options.SpatialCameraRig, ActiveCamera, this);
}
return spatialCursor;
}
}
public InputDevice ActiveInputDevice = InputDevice.Mouse;
public ICameraInteraction MouseCameraController
{
get { return this.mouseCamControls; }
set { this.mouseCamControls = value; }
}
public bool Use2DCockpit
{
get { return options.Use2DCockpit; }
}
// Use this for initialization
public void Start(SceneOptions options)
{
this.options = options;
DebugUtil.LogLevel = options.LogLevel;
FPlatform.InitializeMainThreadID();
// initialize VR platform if VR is active
if (gs.VRPlatform.VREnabled) {
if (options.Use2DCockpit)
throw new Exception("FContext.Start: cannot use 2D Orthographic Cockpit with VR!");
if (options.SpatialCameraRig != null)
gs.VRPlatform.Initialize(options.SpatialCameraRig);
}
InputExtension.Get.Start();
nextFrameActions = new ActionSet();
everyFrameActions = new ActionSet();
// intialize camera stuff
camTracker = new CameraTracking();
camTracker.Initialize(this);
GetScene();
if (options.SceneInitializer != null)
options.SceneInitializer.Initialize(GetScene());
Scene.SelectionChangedEvent += OnSceneSelectionChanged;
if (options.DefaultGizmoBuilder != null)
transformManager = new TransformManager(options.DefaultGizmoBuilder);
else
transformManager = new TransformManager( new AxisTransformGizmoBuilder() );
if (options.EnableTransforms) {
transformManager.Initialize(this);
}
toolManager = new ToolManager();
toolManager.Initialize(this);
toolManager.OnToolActivationChanged += OnToolActivationChanged;
MouseController.Start();
SpatialController.Start();
// [RMS] hardcode starting cam target point to origin
ActiveCamera.SetTarget(Vector3f.Zero);
if (options.MouseCameraControls != null)
MouseCameraController = options.MouseCameraControls;
// apply initial transformation to scene
ActiveCamera.Manipulator().SceneTranslate(Scene, SceneGraphConfig.InitialSceneTranslate, true);
// create behavior sets
inputBehaviors = new InputBehaviorSet();
overrideBehaviors = new InputBehaviorSet();
// cockpit needs to go last because UI setup may depend on above
cockpitStack = new Stack<Cockpit>();
if (options.EnableCockpit)
PushCockpit(options.CockpitInitializer);
captureMouse = null;
captureTouch = null;
captureLeft = captureRight = null;
bInCameraControl = false;
// [RMS] this locks cursor to game unless user presses escape or exits
if ( FPlatform.IsUsingVR() || options.UseSystemMouseCursor == false )
Cursor.lockState = CursorLockMode.Locked;
// initialize line rendering manager
LineRenderingManager.Initialize();
// set hacky hackenstein global
ActiveContext_HACK = this;
startup_checks();
}
// sometimes we need the last valid InputState
// (should this be exposed somehow?)
InputState lastInputState;
// we use this as a guard to prevent calling things that would cancel current capture
bool inCapturingObjectCall = false;
// Update is called once per frame
public void Update() {
ThreadMailbox.ProcessMainThreadMail(); // is this the right spot to do this?
FPlatform.IncrementFrameCounter();
if (FPlatform.IsWindowResized()) {
ActiveCockpit.OnWindowResized();
// need to tell other cockpits about this...
foreach (Cockpit c in cockpitStack)
c.OnWindowResized();
FUtil.SafeSendAnyEvent(OnWindowResized);
}
// update our wrappers around various different Input modes
InputExtension.Get.Update();
// update cockpit tracking and let UI do per-frame rendering computations
if (options.EnableCockpit)
ActiveCockpit.Update();
// run per-frame actions
Action runAllOnceActions = null;
lock (nextFrameActions) {
runAllOnceActions = nextFrameActions.GetRunnable();
nextFrameActions.Clear();
}
if ( runAllOnceActions != null )
runAllOnceActions();
Action runAllEveryFrameActions = null;
lock (everyFrameActions) {
runAllEveryFrameActions = everyFrameActions.GetRunnable();
}
if (runAllEveryFrameActions != null)
runAllEveryFrameActions();
// can either use spacecontrols or mouse, but not both at same time
// [TODO] ask spatial input controller instead, it knows better (?)
if ( FPlatform.IsUsingVR() && SpatialController.CheckForSpatialInputActive() ) {
Configure_SpaceControllers();
HandleInput_SpaceControllers();
} else if ( FPlatform.IsTouchDevice() ) {
Configure_TouchInput();
HandleInput_Touch();
} else {
Configure_MouseOrGamepad();
HandleInput_MouseOrGamepad();
}
// after we have handled input, do per-frame rendering computations
if (options.EnableCockpit)
ActiveCockpit.PreRender();
ToolManager.PreRender();
Scene.PreRender();
}
void Configure_SpaceControllers()
{
SceneGraphConfig.ActiveDoubleClickDelay = SceneGraphConfig.TriggerDoubleClickDelay;
ActiveInputDevice = (gs.VRPlatform.CurrentVRDevice == gs.VRPlatform.Device.HTCVive) ?
InputDevice.HTCViveWands : InputDevice.OculusTouch;
}
void HandleInput_SpaceControllers()
{
// update cursors
SpatialController.Update();
MouseController.HideCursor();
// have to do this after cursor update in case hotkey uses mouse position
HandleKeyboardInput();
// create our super-input object (wraps all supported input types)
InputState input = new InputState();
input.Initialize_SpatialController(this);
lastInputState = input;
// run override behaviors
overrideBehaviors.SendOverrideInputs(input);
input.LeftCaptureActive = (captureLeft != null);
input.RightCaptureActive = (captureRight != null);
// update left-capture
if (captureLeft != null) {
inCapturingObjectCall = true;
Capture cap = Capture.End;
try {
cap = captureLeft.element.UpdateCapture(input, captureLeft.data);
}catch ( Exception e ) {
DebugUtil.Log(2, "FContext.HandleInput_SpaceControllers: exception in left UpdateCapture! " + e.Message);
captureLeft.element.ForceEndCapture(input, captureLeft.data);
captureLeft = null;
if (captureRight == captureLeft)
captureRight = null; // dual-capture
if (FPlatform.InUnityEditor())
throw;
}
inCapturingObjectCall = false;
if (cap.state == CaptureState.Continue) {
// (carry on)
} else if (cap.state == CaptureState.End) {
DebugUtil.Log(10, "[SceneController] released left capture " + captureLeft.element.CaptureIdentifier);
if (captureRight == captureLeft)
captureRight = null; // if we are doing a dual-capture, we only want to end once!!
captureLeft = null;
}
}
// update right-capture
// if we are doing a both-capture, we only want to send update once
if ( captureRight != null && captureRight != captureLeft ) {
inCapturingObjectCall = true;
Capture cap = Capture.End;
try {
cap = captureRight.element.UpdateCapture(input, captureRight.data);
} catch (Exception e) {
DebugUtil.Log(2, "FContext.HandleInput_SpaceControllers: exception in right UpdateCapture! " + e.Message);
captureRight.element.ForceEndCapture(input, captureRight.data);
captureRight = null;
if (FPlatform.InUnityEditor())
throw;
}
inCapturingObjectCall = false;
if (cap.state == CaptureState.Continue) {
// (carry on)
} else if (cap.state == CaptureState.End) {
DebugUtil.Log(10, "[SceneController] released right capture " + captureRight.element.CaptureIdentifier);
captureRight = null;
}
}
// if we have a free device, check for capture.
bool bCanCapture = (bInCameraControl == false);
if (bCanCapture && (captureLeft == null || captureRight == null) ) {
// collect up capture requests
List<CaptureRequest> vRequests = new List<CaptureRequest>();
inputBehaviors.CollectWantsCapture(input, vRequests);
if ( vRequests.Count > 0 ) {
// end outstanding hovers
TerminateHovers(input);
// select one of the capture requests. technically we could end
// up with none successfully Begin'ing, but behaviors should be
// doing those checks in WantCapture, not BeginCapture !!
vRequests.OrderBy(x => x.element.Priority);
Capture capReq = null;
for ( int i = 0; i < vRequests.Count && capReq == null; ++i ) {
// filter out invalid requests
CaptureSide eUseSide = vRequests[i].side;
if (eUseSide == CaptureSide.Any) // replace Any with Both. Does that make sense??
eUseSide = CaptureSide.Both;
if ( (eUseSide == CaptureSide.Left || eUseSide == CaptureSide.Both)
&& captureLeft != null)
continue;
if ( (eUseSide == CaptureSide.Right || eUseSide == CaptureSide.Both)
&& captureRight != null)
continue;
Capture c = vRequests[i].element.BeginCapture(input, eUseSide);
if (c.state == CaptureState.Begin)
capReq = c;
}
if (capReq != null) {
// technically we only should terminate hover on capture controller,
// but that seems really hard. This will clear hovers but they will
// come back next frame. Perhaps revisit if this is causing flicker...
TerminateHovers(input);
// [RMS] most of this checking is redundant now, but leaving because of debug logging
if (capReq.data.which == CaptureSide.Left) {
if (captureLeft != null) {
DebugUtil.Warning("[SceneController.HandleInput_SpaceControllers] received Capture request for Left side from {0}, but already capturing! Ignoring.", capReq.element.CaptureIdentifier);
} else {
captureLeft = capReq;
DebugUtil.Log(10, "[SceneController] began left-capture" + captureLeft.element.CaptureIdentifier);
}
} else if (capReq.data.which == CaptureSide.Right) {
if (captureRight != null) {
DebugUtil.Warning("[SceneController.HandleInput_SpaceControllers] received Capture request for Right side from {0}, but already capturing! Ignoring.", capReq.element.CaptureIdentifier);
} else {
captureRight = capReq;
DebugUtil.Log(10, "[SceneController] began right-capture" + captureRight.element.CaptureIdentifier);
}
} else if (capReq.data.which == CaptureSide.Both || capReq.data.which == CaptureSide.Any) {
if (captureLeft != null || captureRight != null) {
DebugUtil.Warning("[SceneController.HandleInput_SpaceControllers] received Capture request for both sides from {0}, but already capturing! Ignoring.", capReq.element.CaptureIdentifier);
} else {
captureLeft = captureRight = capReq;
DebugUtil.Log(10, "[SceneController] began both-capture " + captureLeft.element.CaptureIdentifier);
}
}
}
}
}
// update hover if we have a free device
if ( captureLeft == null || captureRight == null )
inputBehaviors.UpdateHover(input);
}
void Configure_TouchInput()
{
SceneGraphConfig.ActiveDoubleClickDelay = SceneGraphConfig.MouseDoubleClickDelay;
ActiveInputDevice = InputDevice.TabletFingers;
}
void HandleInput_Touch()
{
// update mouse/gamepad cursor
MouseController.Update();
// create our super-input object (wraps all supported input types)
InputState input = new InputState();
input.Initialize_TouchInput(this);
lastInputState = input;
// [RMS] not sure if this is 100% correct thing to do. We need to allow Platform UI
// layer (eg like Unity ui) to consume mouse events before we see them. However this
// only applies if they are "on top". It is a bit tricky...
if (FPlatformUI.IsConsumingMouseInput() && captureTouch == null ) {
return;
}
// run override behaviors
overrideBehaviors.SendOverrideInputs(input);
input.TouchCaptureActive = (captureTouch != null);
// update left-capture
if (captureTouch != null) {
inCapturingObjectCall = true;
Capture cap = Capture.End;
try {
cap = captureTouch.element.UpdateCapture(input, captureTouch.data);
} catch (Exception e) {
DebugUtil.Log(2, "FContext.HandleInput_Touch: exception in UpdateCapture! " + e.Message);
captureTouch.element.ForceEndCapture(input, captureTouch.data);
captureTouch = null;
if (FPlatform.InUnityEditor())
throw;
}
inCapturingObjectCall = false;
if (cap.state == CaptureState.Continue) {
// (carry on)
} else if (cap.state == CaptureState.End) {
DebugUtil.Log(10, "[SceneController] released touch capture " + captureTouch.element.CaptureIdentifier);
captureTouch = null;
}
}
// if we have a free device, check for capture.
bool bCanCapture = (bInCameraControl == false);
if (bCanCapture && captureTouch == null ) {
// collect up capture requests
List<CaptureRequest> vRequests = new List<CaptureRequest>();
inputBehaviors.CollectWantsCapture(input, vRequests);
if ( vRequests.Count > 0 ) {
// select one of the capture requests. technically we could end
// up with none successfully Begin'ing, but behaviors should be
// doing those checks in WantCapture, not BeginCapture !!
vRequests.OrderBy(x => x.element.Priority);
Capture capReq = null;
for ( int i = 0; i < vRequests.Count && capReq == null; ++i ) {
// filter out invalid requests
// (??)
// before we actually begin capture we will complete any text editing
// [RMS] perhaps this should be configurable for behavior? Some behaviors
// do not require this (eg view controls...)
completeTextEntryOnFocusChange();
Capture c = vRequests[i].element.BeginCapture(input, CaptureSide.Any);
if (c.state == CaptureState.Begin)
capReq = c;
}
if (capReq != null)
captureTouch = capReq;
}
}
}
void Configure_MouseOrGamepad()
{
SceneGraphConfig.ActiveDoubleClickDelay = SceneGraphConfig.MouseDoubleClickDelay;
ActiveInputDevice = InputDevice.Mouse | InputDevice.Gamepad;
}
void HandleInput_MouseOrGamepad()
{
// ignore input if we do not have focus
if (WindowHasFocus == false)
return;
// update mouse/gamepad cursor
MouseController.Update();
// have to do this after cursor update in case hotkey uses mouse position
HandleKeyboardInput();
// create our super-input object (wraps all supported input types)
InputState input = new InputState();
input.Initialize_MouseGamepad(this);
lastInputState = input;
// [RMS] not sure if this is 100% correct thing to do. We need to allow Platform UI
// layer (eg like Unity ui) to consume mouse events before we see them. However this
// only applies if they are "on top". It is a bit tricky...
if ( FPlatformUI.IsConsumingMouseInput() && captureMouse == null ) {
return;
}
CameraInteractionState eCamState = (MouseCameraController != null)
? MouseCameraController.CheckCameraControls(input) : CameraInteractionState.Ignore;
if (eCamState == CameraInteractionState.BeginCameraAction) {
TerminateHovers(input);
bInCameraControl = true;
ActiveCamera.SetTargetVisible(true);
} else if (eCamState == CameraInteractionState.EndCameraAction) {
bInCameraControl = false;
ActiveCamera.SetTargetVisible(false);
} else if (bInCameraControl) {
ActiveCamera.SetTargetVisible(true);
MouseCameraController.DoCameraControl(Scene, ActiveCamera, input);
} else {
// run override behaviors
overrideBehaviors.SendOverrideInputs(input);
input.MouseGamepadCaptureActive = (captureMouse != null);
if (InCaptureMouse) {
inCapturingObjectCall = true;
Capture cap = Capture.End;
try {
cap = captureMouse.element.UpdateCapture(input, captureMouse.data);
} catch (Exception e) {
DebugUtil.Log(2, "FContext.HandleInput_MouseOrGamepad: exception in UpdateCapture! " + e.Message);
captureMouse.element.ForceEndCapture(input, captureMouse.data);
captureMouse = null;
if (FPlatform.InUnityEditor())
throw;
}
inCapturingObjectCall = false;
if (cap.state == CaptureState.Continue) {
// (carry on)
} else if (cap.state == CaptureState.End) {
captureMouse = null;
}
} else {
// this is very simplistic...needs to be rewritten like space controllers
List<CaptureRequest> vRequests = new List<CaptureRequest>();
inputBehaviors.CollectWantsCapture(input, vRequests);
if (vRequests.Count > 0) {
// end outstanding hovers
TerminateHovers(input);
// select one of the capture requests. technically we could end
// up with none successfully Begin'ing, but behaviors should be
// doing those checks in WantCapture, not BeginCapture !!
vRequests.OrderBy(x => x.element.Priority);
Capture capReq = null;
for (int i = 0; i < vRequests.Count && capReq == null; ++i) {
if (vRequests[i].side != CaptureSide.Any)
continue; // not possible in mouse paths...
// before we actually begin capture we will complete any text editing
// [RMS] perhaps this should be configurable for behavior? Some behaviors
// do not require this (eg view controls...)
completeTextEntryOnFocusChange();
Capture c = vRequests[i].element.BeginCapture(input, vRequests[i].side);
if (c.state == CaptureState.Begin) {
capReq = c;
}
}
captureMouse = capReq;
}
}
// if we don't have a capture, do hover
if (captureMouse == null)
inputBehaviors.UpdateHover(input);
}
}
public bool InCaptureMouse {
get { return (captureMouse != null); }
}
public bool InCameraManipulation
{
get { return bInCameraControl; }
}
void TerminateHovers(InputState input)
{
inputBehaviors.EndHover(input);
}
void TerminateCaptures(InputState input)
{
if ( captureMouse != null ) {
captureMouse.element.ForceEndCapture(input, captureMouse.data);
captureMouse = null;
}
if ( captureTouch != null ) {
captureTouch.element.ForceEndCapture(input, captureTouch.data);
captureTouch = null;
}
if ( captureLeft != null ) {
captureLeft.element.ForceEndCapture(input, captureLeft.data);
captureLeft = null;
}
if ( captureRight != null ) {
captureRight.element.ForceEndCapture(input, captureRight.data);
captureRight = null;
}
}
void TerminateIfCapturing(IEnumerable<InputBehavior> behaviors, InputState input)
{
foreach ( InputBehavior b in behaviors ) {
if ( captureMouse != null && captureMouse.element == b) {
captureMouse.element.ForceEndCapture(lastInputState, captureMouse.data);
captureMouse = null;
}
if (captureTouch != null && captureTouch.element == b) {
captureTouch.element.ForceEndCapture(lastInputState, captureTouch.data);
captureTouch = null;
}
if (captureLeft != null && captureLeft.element == b) {
captureLeft.element.ForceEndCapture(lastInputState, captureLeft.data);
captureLeft = null;
}
if (captureRight != null && captureRight.element == b) {
captureRight.element.ForceEndCapture(lastInputState, captureRight.data);
captureRight = null;
}
}
}
// called when we lose window focus
public virtual void OnFocusChange(bool bFocused)
{
if (bFocused == false) {
TerminateHovers(lastInputState);
if ( captureMouse != null || captureTouch != null || captureLeft != null || captureRight != null ) {
if ( FPlatform.ShowingExternalPopup ) {
throw new Exception("TerminateCapture: Need to complete capture before showing external popup dialog. Use Context.RegisterNextFrameAction()");
}
}
TerminateCaptures(lastInputState);
if (bInCameraControl) {
bInCameraControl = false;
ActiveCamera.SetTargetVisible(false);
}
}
WindowHasFocus = bFocused;
}
public void PushCockpit(ICockpitInitializer initializer)
{
if (inCapturingObjectCall) {
DebugUtil.Log(2, "FContext.PushCockpit: called from inside Behaviour.UpdateCapture(). This is not permitted. Use FContext.RegisterNextFrameAction().");
throw new Exception("FContext.PushCockpit: called from inside Behaviour.UpdateCapture(). This is not permitted. Use FContext.RegisterNextFrameAction().");
}
Cockpit trackingInitializer = null;
if (activeCockpit != null) {
trackingInitializer = activeCockpit;
inputBehaviors.Remove(activeCockpit.InputBehaviors);
overrideBehaviors.Remove(activeCockpit.OverrideBehaviors);
activeCockpit.InputBehaviors.OnSetChanged -= on_cockpit_behaviors_changed;
activeCockpit.OverrideBehaviors.OnSetChanged -= on_cockpit_behaviors_changed;
cockpitStack.Push(activeCockpit);
activeCockpit.RootGameObject.SetVisible(false);
}
Cockpit c = new Cockpit(this);
activeCockpit = c;
if (Use2DCockpit) {
c.UIElementLayer = FPlatform.UILayer;
if (options.ConstantSize2DCockpit)
c.EnableConstantSize2DCockpit();
}
c.Start(initializer);
if (trackingInitializer != null)
c.InitializeTracking(trackingInitializer);
inputBehaviors.Add(c.InputBehaviors, "active_cockpit");
overrideBehaviors.Add(c.OverrideBehaviors, "active_cockpit_override");
activeCockpit.InputBehaviors.OnSetChanged += on_cockpit_behaviors_changed;
activeCockpit.OverrideBehaviors.OnSetChanged += on_cockpit_behaviors_changed;
mouseCursor.ResetCursorToCenter();
}
public void PopCockpit(bool bDestroy)
{
if (inCapturingObjectCall) {
DebugUtil.Log(2, "FContext.PopCockpit: called from inside Behaviour.UpdateCapture(). This is not permitted. Use FContext.RegisterNextFrameAction().");
throw new Exception("FContext.PopCockpit: called from inside Behaviour.UpdateCapture(). This is not permitted. Use FContext.RegisterNextFrameAction().");
}
if (activeCockpit != null) {
inputBehaviors.Remove(activeCockpit.InputBehaviors);
overrideBehaviors.Remove(activeCockpit.OverrideBehaviors);
activeCockpit.InputBehaviors.OnSetChanged -= on_cockpit_behaviors_changed;
activeCockpit.OverrideBehaviors.OnSetChanged -= on_cockpit_behaviors_changed;
activeCockpit.RootGameObject.SetVisible(false);
if (bDestroy)
activeCockpit.Destroy();
activeCockpit = null;
}
activeCockpit = cockpitStack.Pop();
if (activeCockpit != null) {
activeCockpit.RootGameObject.SetVisible(true);
inputBehaviors.Add(activeCockpit.InputBehaviors, "active_cockpit");
overrideBehaviors.Add(activeCockpit.OverrideBehaviors, "active_cockpit_override");
activeCockpit.InputBehaviors.OnSetChanged += on_cockpit_behaviors_changed;
activeCockpit.OverrideBehaviors.OnSetChanged += on_cockpit_behaviors_changed;
}
mouseCursor.ResetCursorToCenter();
}
protected virtual void OnToolActivationChanged(ITool tool, ToolSide eSide, bool bActivated)
{
if (bActivated) {
inputBehaviors.Add(tool.InputBehaviors, "active_tool");
tool.InputBehaviors.OnSetChanged += on_tool_behaviors_changed;
} else {
tool.InputBehaviors.OnSetChanged -= on_tool_behaviors_changed;
TerminateIfCapturing(tool.InputBehaviors, lastInputState);
inputBehaviors.Remove(tool.InputBehaviors);
}
}
void on_tool_behaviors_changed(InputBehaviorSet behaviors)
{
List<InputBehavior> removed = inputBehaviors.RemoveByGroup("active_tool");
TerminateIfCapturing(removed, lastInputState);
inputBehaviors.Add(behaviors, "active_tool");
}
InputBehaviorSource activeSOBehaviourSource;
protected virtual void OnSceneSelectionChanged(object sender, EventArgs e)
{
InputBehaviorSource newSource = (Scene.Selected.Count == 1) ? Scene.Selected[0] as InputBehaviorSource : null;
if ( (newSource != null && newSource == activeSOBehaviourSource) || (newSource == null && activeSOBehaviourSource == null) )
return; // did not actually change
// remove existing source that is no longer selected
if (newSource != activeSOBehaviourSource && activeSOBehaviourSource != null) {
activeSOBehaviourSource.InputBehaviors.OnSetChanged -= on_selected_so_behaviors_changed;
TerminateIfCapturing(activeSOBehaviourSource.InputBehaviors, lastInputState);
inputBehaviors.Remove(activeSOBehaviourSource.InputBehaviors);
activeSOBehaviourSource = null;
}
// if new selection has behaviors, register them
if (newSource != null) {
InputBehaviorSet newBehaviors = newSource.InputBehaviors;
if (newBehaviors.Count > 0) {
inputBehaviors.Add(newBehaviors, "active_so");
newBehaviors.OnSetChanged += on_selected_so_behaviors_changed;
activeSOBehaviourSource = newSource;
}
}
}
void on_selected_so_behaviors_changed(InputBehaviorSet behaviors)
{
List<InputBehavior> removed = inputBehaviors.RemoveByGroup("active_so");
TerminateIfCapturing(removed, lastInputState);
}
void on_cockpit_behaviors_changed(InputBehaviorSet behaviors)
{
activeCockpit.InputBehaviors.OnSetChanged -= on_cockpit_behaviors_changed;
activeCockpit.OverrideBehaviors.OnSetChanged -= on_cockpit_behaviors_changed;
// remove from global behavior set
List<InputBehavior> actives = inputBehaviors.RemoveByGroup("active_cockpit");
List<InputBehavior> overrides = inputBehaviors.RemoveByGroup("active_cockpit_override");
// if a Behavior that is currently capturing is no longer in active or override sets,
// we need to terminate that behavior.
actives.RemoveAll((x) => { return activeCockpit.InputBehaviors.Contains(x); });
TerminateIfCapturing(actives, lastInputState);
overrides.RemoveAll((x) => { return activeCockpit.OverrideBehaviors.Contains(x); });
TerminateIfCapturing(overrides, lastInputState);
inputBehaviors.Add(activeCockpit.InputBehaviors, "active_cockpit");
overrideBehaviors.Add(activeCockpit.OverrideBehaviors, "active_cockpit_override");
activeCockpit.InputBehaviors.OnSetChanged += on_cockpit_behaviors_changed;
activeCockpit.OverrideBehaviors.OnSetChanged += on_cockpit_behaviors_changed;
}
// remove all scene stuff and reset view to default
public void NewScene(bool bAnimated, bool bResetView = true)
{
if (InCameraManipulation)
return; // not supported yet
// disable tools, because they might refer to active selection
if (ToolManager.HasActiveTool(ToolSide.Left))
ToolManager.DeactivateTool(ToolSide.Left);
if (ToolManager.HasActiveTool(ToolSide.Right))
ToolManager.DeactivateTool(ToolSide.Right);
Scene.Reset();
UniqueNames.Reset();
if (bResetView)
ResetView(bAnimated);
// seems like a good time for this...
FPlatform.SuggestGarbageCollection();
}
public void ResetView(bool bAnimated)
{
Action resetAction = () => {
Scene.SetSceneScale(1.0f);
ActiveCamera.Manipulator().ResetSceneOrbit(Scene, true, true, true);
// [RMS] above should already do this, but sometimes it gets confused..
Scene.RootGameObject.SetRotation(Quaternion.identity);
ActiveCamera.Manipulator().ResetScenePosition(scene);
ActiveCamera.Manipulator().SceneTranslate(Scene, SceneGraphConfig.InitialSceneTranslate, true);
};
if (bAnimated)
ActiveCamera.Animator().DoActionDuringDipToBlack(resetAction, 0.5f);
else
resetAction();
}
public void ScaleView(Vector3f vCenterW, float fMeterSizeW )
{
//Vector3f camTarget = ActiveCamera.GetTarget();
//Vector3f localTarget = Scene.WorldFrame.ToFrameP(camTarget);
Vector3f vDeltaOrig = Scene.SceneFrame.ToFrameP(vCenterW);
ActiveCamera.Manipulator().ResetSceneOrbit(
Scene, false, true, true);
float fCurScale = Scene.GetSceneScale();
Frame3f cockpitF = ActiveCockpit.GetLevelViewFrame(CoordSpace.WorldCoords);
float fScale = 1.0f / fMeterSizeW;
vDeltaOrig *= fScale;
Frame3f deskF = cockpitF.Translated(1.2f, 2).Translated(-0.5f, 1).Translated(-vDeltaOrig);
Scene.SceneFrame = deskF;
Scene.SetSceneScale(fCurScale * fScale);
Vector3f newTarget = Scene.SceneFrame.Origin + vDeltaOrig;
ActiveCamera.SetTarget(newTarget);
}
// raycasts into 2D Cockpit if enabled
public bool Find2DCockpitUIHit(Ray3f orthoEyeRay, out UIRayHit bestHit)
{
if (Use2DCockpit == false)
throw new Exception("FContext.Find2DUIHit: 2D UI layer is not enabled!");
bestHit = null;
if (options.EnableCockpit)
return activeCockpit.FindUIRayIntersection(orthoEyeRay, out bestHit);
return false;
}
// see comment above
public bool Find2DCockpitUIHoverHit(Ray3f orthoEyeRay, out UIRayHit bestHit)
{
if (Use2DCockpit == false)
throw new Exception("FContext.Find2DUIHit: 2D UI layer is not enabled!");
bestHit = null;
if (options.EnableCockpit)
return activeCockpit.FindUIHoverRayIntersection(orthoEyeRay, out bestHit);
return false;
}
// raycasts into Scene and Cockpit for UIElement hits. Assumption is that cockpit is "closer"
// to eye than scene. This is **not strictly true**. Possibly we should explicitly
// break this into two separate functions, so that separate Behaviors can be
// used for Cockpit and Scene.
//
// Note also that if we are using 2D Cockpit, cockpit hits are disabled in this function.
public bool FindUIHit(Ray eyeRay, out UIRayHit bestHit)
{
bestHit = new UIRayHit();
UIRayHit sceneHit = null, cockpitHit = null;
bool bCockpitOnly = (options.EnableCockpit && activeCockpit.GrabFocus);
if (bCockpitOnly == false && scene.FindUIRayIntersection(eyeRay, out sceneHit) ) {
bestHit = sceneHit;
}
if ( Use2DCockpit == false && options.EnableCockpit
&& activeCockpit.FindUIRayIntersection(eyeRay, out cockpitHit) ) {
if ( cockpitHit.fHitDist < bestHit.fHitDist )
bestHit = cockpitHit;
}
return bestHit.IsValid;
}
// see comment as above
public bool FindUIHoverHit(Ray eyeRay, out UIRayHit bestHit)
{
bestHit = new UIRayHit();
UIRayHit sceneHit = null, cockpitHit = null;