-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditorGameSplineEditorService.cs
More file actions
1150 lines (1028 loc) · 48.9 KB
/
Copy pathEditorGameSplineEditorService.cs
File metadata and controls
1150 lines (1028 loc) · 48.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
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using SplineTest.GameStudioExt.Assets;
using SplineTest.GameStudioExt.StrideEditorExt;
using SplineTest.GameStudioExt.StrideEditorExt.StrideAssetTransaction;
using SplineTest.Rendering;
using SplineTest.Splines.Rendering.GizmoMarker;
using SplineTest.Splines.Rendering.LineVisualizer;
using Stride.Assets.Presentation.AssetEditors.GameEditor.Game;
using Stride.Assets.Presentation.AssetEditors.GameEditor.Services;
using Stride.Assets.Presentation.AssetEditors.Gizmos;
using Stride.Assets.Presentation.AssetEditors.Gizmos.Splines;
using Stride.Assets.Presentation.AssetEditors.SceneEditor.Game;
using Stride.Assets.Presentation.AssetEditors.SceneEditor.Services;
using Stride.Assets.Presentation.ViewModel;
using Stride.Core;
using Stride.Core.Annotations;
using Stride.Core.Assets.Editor.ViewModel;
using Stride.Core.Assets.Quantum;
using Stride.Core.Mathematics;
using Stride.Core.Presentation.Services;
using Stride.Core.Quantum;
using Stride.Editor.EditorGame.Game;
using Stride.Engine;
using Stride.Engine.Splines.Components;
using Stride.Engine.Splines.Models;
using Stride.Games;
using Stride.Input;
using Stride.Rendering;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Stride.Assets.Presentation.AssetEditors.EntityHierarchyEditor.Game;
/// <summary>
/// A class that manages spline control & tangent points editing.
/// </summary>
public class EditorGameSplineEditorService : EditorGameServiceBase
{
private static readonly Color4 CurveColor = Color.Aqua.ToColor4();
private readonly StrideEditorService strideEditorService;
private readonly SceneEditorController sceneEditorController;
private Interaction inputInteraction;
private bool isInputInteractionFinished;
private EntityHierarchyEditorGame game;
private Scene editorScene;
private IUndoRedoService undoRedoService;
private AssetPropertyGraph scenePropertyGraph;
private InputManager inputManager;
private IEditorGameEntitySelectionService entitySelectionService;
private IStrideEditorMouseService editorMouseService;
private IEditorGameCameraService cameraService;
private IEditorGameComponentGizmoService editorGameComponentGizmoService;
private TranslationGizmo pointTransformGizmo;
private SplineComponent? activeSplineComponent;
private int activeControlPointIndex = -1;
private SplinePointEditingSelectionType activePointEditingSelectionType;
private Entity activePointAnchorEntity = null;
private readonly List<Entity> activePointAnchorEntityList = []; // Only used for pointTransformGizmo.ModifiedEntities
private bool refreshAnchorPosition = false;
private bool isSplineChangedUpdateRequired = false;
private Vector3 prevGizmoRootPosition = new Vector3(float.MinValue);
public Entity splineEditingGizmoRootEntity;
private readonly List<SplineControlPointGizmo> controlPointGizmos = [];
private bool isAddingControlPoint = false; // HACK: need to prevent multiple adds in a single 'click'
private SplineControlPointGizmo mouseHoverControlPointGizmo = null;
private int mouseHoverControlPointIndex = -1;
private readonly List<Vector3> splineSamplePoints = [];
internal SplineComponent? ActiveSplineComponent => activeSplineComponent;
public override IEnumerable<Type> Dependencies => [
typeof(IEditorGameCameraService),
typeof(IEditorGameComponentGizmoService)
];
public EditorGameSplineEditorService(StrideEditorService strideEditorService, SceneEditorController sceneEditorController)
{
this.strideEditorService = strideEditorService;
this.sceneEditorController = sceneEditorController;
}
protected override Task<bool> Initialize([NotNull] EditorServiceGame editorGame)
{
if (IsInitialized)
{
return Task.FromResult(true);
}
game = (EntityHierarchyEditorGame)editorGame;
editorScene = game.EditorScene;
undoRedoService = SessionViewModel.Instance.UndoRedoService;
inputManager = game.Services.GetService<InputManager>();
entitySelectionService = game.EditorServices.Get<IEditorGameEntitySelectionService>();
entitySelectionService?.SelectionUpdated += OnEntitySelectionService_SelectionUpdated;
editorMouseService = StrideEditorMouseService.GetOrCreate(game.Services);
splineEditingGizmoRootEntity = new Entity("Spline Editing Root");
editorScene.Entities.Add(splineEditingGizmoRootEntity);
activePointAnchorEntity = new Entity("Edit Spline Point Anchor"); // Entity to be moved by the TranslationGizmo
activePointAnchorEntityList.Add(activePointAnchorEntity);
activePointAnchorEntity.Scene = editorScene;
pointTransformGizmo = new TranslationGizmo();
pointTransformGizmo.Initialize(game.Services, editorScene);
pointTransformGizmo.IsEnabled = false; // Must disable AFTER Initialize
pointTransformGizmo.AnchorEntity = activePointAnchorEntity;
pointTransformGizmo.TransformationEnded += OnTransformGizmo_TransformationEnded;
pointTransformGizmo.ModifiedEntities = activePointAnchorEntityList;
game.Script.AddTask(OnGameUpdate, priority: 1000);
// HACK: Take AssetViewModel/SceneViewModel from game controller because we can't get it ourselves
{
var getAssetViewModel_FieldInfo = typeof(EditorGameController<EntityHierarchyEditorGame>).GetField("Asset", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
var sceneViewModel = getAssetViewModel_FieldInfo.GetValue(sceneEditorController) as SceneViewModel;
scenePropertyGraph = sceneViewModel.PropertyGraph;
scenePropertyGraph.Changed += OnScenePropertyGraphChanged;
scenePropertyGraph.ItemChanged += OnScenePropertyGraphItemChanged;
}
return Task.FromResult(true);
}
private void OnEntitySelectionService_SelectionUpdated(object sender, EntitySelectionEventArgs e)
{
var activeSplineEntity = activeSplineComponent?.Entity;
if (activeSplineEntity is not null
&& !e.NewSelection.Contains(activeSplineEntity))
{
DeactivateEditSpline();
}
else if (e.NewSelection.Count == 1)
{
var selectedEntity = e.NewSelection.First();
var splineComp = selectedEntity.Get<SplineComponent>();
if (splineComp is not null && activeSplineEntity != selectedEntity)
{
if (activeSplineEntity is not null)
{
DeactivateEditSpline();
}
ActivateSplinePointEditing(splineComp, controlPointIndex: -1, editingSelectionType: SplinePointEditingSelectionType.None);
}
}
}
private void OnTransformGizmo_TransformationEnded(object sender, EventArgs e)
{
strideEditorService.Invoke(() =>
{
using (strideEditorService.CreateUndoRedoTransaction("Update Spline " + activePointEditingSelectionType.ToString()))
{
var runtimeSpline = activeSplineComponent.Spline;
var assetSplineComp = strideEditorService.GetAssetComponent(activeSplineComponent);
var assetSpline = assetSplineComp.Spline;
var assetTransactionBuilder = AssetTransactionBuilder.Begin(assetSplineComp);
if (runtimeSpline.TryGetPreviousControlPointIndex(activeControlPointIndex, out int prevIndex))
{
assetSpline[prevIndex] = runtimeSpline[prevIndex];
}
assetSpline[activeControlPointIndex] = runtimeSpline[activeControlPointIndex];
if (runtimeSpline.TryGetNextControlPointIndex(activeControlPointIndex, out int nextIndex))
{
assetSpline[nextIndex] = runtimeSpline[nextIndex];
}
var nodeContainer = SessionViewModel.Instance.AssetNodeContainer;
var assetTransaction = assetTransactionBuilder.CreateTransaction(nodeContainer);
assetTransactionBuilder.RevertAssetState(nodeContainer);
assetTransaction.Execute();
}
});
}
private void OnScenePropertyGraphChanged(object sender, AssetMemberNodeChangeEventArgs e)
{
if (undoRedoService.TransactionInProgress)
{
string memberName = e.Member.Name;
if (e.ChangeType == ContentChangeType.ValueChange)
{
if (IsControlPointModification(e.Member, out var assetSplineComp, out int controlPointIndex))
{
if (memberName == nameof(SplineControlPoint.Position))
{
var assetTransactionBuilder = AssetTransactionBuilder.Begin(assetSplineComp);
bool hasChanged = TryUpdateAutoTangents(assetSplineComp.Spline, controlPointIndex);
if (hasChanged)
{
var nodeContainer = SessionViewModel.Instance.AssetNodeContainer;
var assetTransaction = assetTransactionBuilder.CreateTransaction(nodeContainer);
assetTransactionBuilder.RevertAssetState(nodeContainer);
assetTransaction.Execute();
}
}
else if (memberName == nameof(SplineControlPoint.TangentIn)
|| memberName == nameof(SplineControlPoint.TangentOut))
{
var assetTransactionBuilder = AssetTransactionBuilder.Begin(assetSplineComp);
var spline = assetSplineComp.Spline;
bool isTangentIn = memberName == nameof(SplineControlPoint.TangentIn);
bool hasChanged = TryUpdateTangentsConstraint(isTangentIn, spline, controlPointIndex);
if (hasChanged)
{
var nodeContainer = SessionViewModel.Instance.AssetNodeContainer;
var assetTransaction = assetTransactionBuilder.CreateTransaction(nodeContainer);
assetTransactionBuilder.RevertAssetState(nodeContainer);
assetTransaction.Execute();
}
}
else if (memberName == nameof(SplineControlPoint.Roll)
|| memberName == nameof(SplineControlPoint.OverrideUpDirection))
{
// No real additional modifications, just reevaluated the curve
isSplineChangedUpdateRequired = true;
}
else if (memberName == nameof(SplineControlPoint.Type))
{
var assetTransactionBuilder = AssetTransactionBuilder.Begin(assetSplineComp);
var spline = assetSplineComp.Spline;
var newControlPointType = (SplineControlPointType)e.NewValue;
bool hasChanged = false;
switch (newControlPointType)
{
case SplineControlPointType.Auto:
hasChanged = TryUpdateAutoTangentsSingleControlPoint(spline, controlPointIndex);
break;
case SplineControlPointType.Linear:
hasChanged = TryUpdateLinearTangents(spline, controlPointIndex);
break;
case SplineControlPointType.Mirrored:
case SplineControlPointType.Aligned:
bool isTangentIn = false; // Arbitrary handle to pick...
hasChanged = TryUpdateTangentsConstraint(isTangentIn, spline, controlPointIndex);
break;
case SplineControlPointType.Free:
default:
// Nothing
break;
}
if (hasChanged)
{
var nodeContainer = SessionViewModel.Instance.AssetNodeContainer;
var assetTransaction = assetTransactionBuilder.CreateTransaction(nodeContainer);
assetTransactionBuilder.RevertAssetState(nodeContainer);
assetTransaction.Execute();
}
isSplineChangedUpdateRequired = true;
}
}
}
}
}
private void OnScenePropertyGraphItemChanged(object sender, AssetItemNodeChangeEventArgs e)
{
if (undoRedoService.TransactionInProgress)
{
if (e.ChangeType == ContentChangeType.CollectionRemove)
{
if (e.OldValue is SplineControlPoint
&& TryGetSplineByModifiedControlPoints(e.Collection, e.Index, out var assetSplineComp, out int removedControlPointIndex))
{
var assetTransactionBuilder = AssetTransactionBuilder.Begin(assetSplineComp);
var spline = assetSplineComp.Spline;
bool hasChanged = false;
if (spline.TryGetPreviousControlPointIndex(removedControlPointIndex, out int prevIndex))
{
if (spline[prevIndex].Type == SplineControlPointType.Auto)
{
hasChanged = TryUpdateAutoTangentsSingleControlPoint(spline, prevIndex) || hasChanged;
}
}
if (spline.TryGetNextControlPointIndex(removedControlPointIndex - 1, out int nextIndex) && nextIndex != prevIndex)
{
if (spline[nextIndex].Type == SplineControlPointType.Auto)
{
hasChanged = TryUpdateAutoTangentsSingleControlPoint(spline, nextIndex) || hasChanged;
}
}
if (hasChanged)
{
var nodeContainer = SessionViewModel.Instance.AssetNodeContainer;
var assetTransaction = assetTransactionBuilder.CreateTransaction(nodeContainer);
assetTransactionBuilder.RevertAssetState(nodeContainer);
assetTransaction.Execute();
}
}
}
else if (e.ChangeType == ContentChangeType.CollectionAdd)
{
if (e.NewValue is SplineControlPoint
&& TryGetSplineByModifiedControlPoints(e.Collection, e.Index, out var assetSplineComp, out int addedControlPointIndex))
{
var assetTransactionBuilder = AssetTransactionBuilder.Begin(assetSplineComp);
var spline = assetSplineComp.Spline;
bool hasChanged = TryUpdateAutoTangents(spline, addedControlPointIndex);
if (hasChanged)
{
var nodeContainer = SessionViewModel.Instance.AssetNodeContainer;
var assetTransaction = assetTransactionBuilder.CreateTransaction(nodeContainer);
assetTransactionBuilder.RevertAssetState(nodeContainer);
assetTransaction.Execute();
}
}
}
}
}
private bool IsControlPointModification(
IMemberNode memberNode,
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out SplineComponent? assetSplineComponent,
out int controlPointIndex)
{
assetSplineComponent = null;
controlPointIndex = -1;
if (memberNode.Parent.Type != typeof(SplineControlPoint))
{
return false;
}
string memberName = memberNode.Name;
if (memberName != nameof(SplineControlPoint.Position)
&& memberName != nameof(SplineControlPoint.TangentIn)
&& memberName != nameof(SplineControlPoint.TangentOut)
&& memberName != nameof(SplineControlPoint.Roll)
&& memberName != nameof(SplineControlPoint.OverrideUpDirection)
&& memberName != nameof(SplineControlPoint.Scale)
&& memberName != nameof(SplineControlPoint.Type))
{
return false;
}
var nodePathFinderGraphVisitor = new NodePathFinderGraphVisitor(memberNode);
nodePathFinderGraphVisitor.Visit(scenePropertyGraph.RootNode);
if (nodePathFinderGraphVisitor.FoundPath is null)
{
return false;
}
var subPaths = nodePathFinderGraphVisitor.FoundPath.Decompose();
// SplineComponent.Spline.ControlPoints[i].Position -> at least 5 sub-paths required
if (subPaths.Count < 5 || subPaths[^1].MemberDescriptor?.DeclaringType != typeof(SplineControlPoint))
{
return false;
}
// This really is SplineControlPoint.Property being edited
var splineCompObjPath = nodePathFinderGraphVisitor.FoundPath.Clone();
splineCompObjPath.Pop(); // SplineComponent.Spline.ControlPoints[i]
controlPointIndex = (int)splineCompObjPath.GetIndex();
splineCompObjPath.Pop(); // SplineComponent.Spline.ControlPoints
splineCompObjPath.Pop(); // SplineComponent.Spline
splineCompObjPath.Pop(); // SplineComponent
assetSplineComponent = splineCompObjPath.GetValue(scenePropertyGraph.RootNode.Retrieve()) as SplineComponent;
return assetSplineComponent is not null;
}
private bool TryGetSplineByModifiedControlPoints(
IObjectNode collection, NodeIndex nodeIndex,
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out SplineComponent? assetSplineComponent,
out int controlPointIndex)
{
assetSplineComponent = null;
controlPointIndex = -1;
if (!nodeIndex.IsInt)
{
return false;
}
controlPointIndex = nodeIndex.Int;
var nodePathFinderGraphVisitor = new NodePathFinderGraphVisitor(collection);
nodePathFinderGraphVisitor.Visit(scenePropertyGraph.RootNode);
if (nodePathFinderGraphVisitor.FoundPath is null)
{
return false;
}
var subPaths = nodePathFinderGraphVisitor.FoundPath.Decompose();
// SplineComponent.Spline.ControlPoints -> at least 3 sub-paths required
if (subPaths.Count < 3 || subPaths[^1].MemberDescriptor?.Name != nameof(Spline.ControlPoints))
{
return false;
}
// This really is SplineComponent.Spline.ControlPoints
var splineCompObjPath = nodePathFinderGraphVisitor.FoundPath.Clone();
splineCompObjPath.Pop(); // SplineComponent.Spline
splineCompObjPath.Pop(); // SplineComponent
assetSplineComponent = splineCompObjPath.GetValue(scenePropertyGraph.RootNode.Retrieve()) as SplineComponent;
return assetSplineComponent is not null;
}
public override ValueTask DisposeAsync()
{
if (activeSplineComponent is not null)
{
DeactivateEditSpline();
}
entitySelectionService?.SelectionUpdated -= OnEntitySelectionService_SelectionUpdated;
if (splineEditingGizmoRootEntity is not null)
{
splineEditingGizmoRootEntity.Scene = null;
splineEditingGizmoRootEntity.Dispose();
splineEditingGizmoRootEntity = null;
}
scenePropertyGraph?.Changed -= OnScenePropertyGraphChanged;
scenePropertyGraph?.ItemChanged -= OnScenePropertyGraphItemChanged;
scenePropertyGraph = null;
return base.DisposeAsync();
}
public override void UpdateGraphicsCompositor(EditorServiceGame game)
{
base.UpdateGraphicsCompositor(game);
if (game is SceneEditorGame sceneEditorGame)
{
var gfxComp = sceneEditorGame.EditorSceneSystem?.GraphicsCompositor;
var fwdRenderer = gfxComp?.Editor as Stride.Rendering.Compositing.ForwardRenderer;
if (gfxComp is not null && fwdRenderer is not null)
{
if (!gfxComp.RenderFeatures.Any(x => x is LineVisualizerRenderFeature))
{
gfxComp.RenderFeatures.Add(new LineVisualizerRenderFeature
{
RenderStageSelectors =
{
new LineVisualizerRenderStageSelector
{
EffectName = "Test",
OpaqueRenderStage = fwdRenderer?.OpaqueRenderStage,
TransparentRenderStage = fwdRenderer?.TransparentRenderStage,
RenderGroup = RenderGroupMask.All,
},
},
});
}
if (!gfxComp.RenderFeatures.Any(x => x is GizmoMarkerRenderFeature))
{
gfxComp.RenderFeatures.Add(new GizmoMarkerRenderFeature
{
RenderStageSelectors =
{
new GizmoMarkerRenderStageSelector
{
EffectName = "Test",
//OpaqueRenderStage = fwdRenderer?.OpaqueRenderStage,
TransparentRenderStage = fwdRenderer?.TransparentRenderStage,
RenderGroup = RenderGroupMask.All,
},
},
});
}
}
}
}
private async Task OnGameUpdate()
{
while (!IsDisposed)
{
if (IsActive)
{
//if (IsMouseAvailable)
//{
//}
if (activeSplineComponent is not null && activeSplineComponent.Entity is null)
{
// Component was removed from the entity
DeactivateEditSpline();
}
if (activeSplineComponent?.Entity is Entity splineEntity)
{
splineEntity.Transform.WorldMatrix.Decompose(out var scale, out Quaternion rotation, out var rootPosition);
splineEditingGizmoRootEntity.Transform.Position = rootPosition;
splineEditingGizmoRootEntity.Transform.Rotation = rotation;
splineEditingGizmoRootEntity.Transform.Scale = scale;
splineEditingGizmoRootEntity.Transform.UpdateWorldMatrix();
if (prevGizmoRootPosition != rootPosition)
{
isSplineChangedUpdateRequired = true;
}
prevGizmoRootPosition = rootPosition;
}
UpdateActiveControlPointGizmos();
if (isSplineChangedUpdateRequired)
{
if (activeSplineComponent is not null)
{
if (activeControlPointIndex >= activeSplineComponent.Spline.Count)
{
DeactivateEditSpline(deselectSpline: false);
}
else if (activeControlPointIndex >= 0)
{
var activeCtrlPoint = activeSplineComponent.Spline.ControlPoints[activeControlPointIndex];
bool isEditingTangent = activePointEditingSelectionType == SplinePointEditingSelectionType.TangentIn
|| activePointEditingSelectionType == SplinePointEditingSelectionType.TangentOut;
if (isEditingTangent && !activeCtrlPoint.Type.IsTangentUserControllable())
{
DeactivateEditSpline(deselectSpline: false);
}
else
{
refreshAnchorPosition = true; // Refresh changes in the next update
}
}
}
RegenerateSplineVisualizer();
isSplineChangedUpdateRequired = false;
}
if (activeSplineComponent is not null)
{
await UpdateTransformGizmoChangesAsync();
UpdateControlPointEditingState();
}
}
await game.Script.NextFrame();
}
}
private void UpdateActiveControlPointGizmos()
{
int ctrlPointCount = activeSplineComponent?.Spline?.Count ?? 0;
if (controlPointGizmos.Count != ctrlPointCount)
{
isSplineChangedUpdateRequired = true;
}
if (controlPointGizmos.Count < ctrlPointCount)
{
// Populate new gizmos
int controlPointStartIndex = controlPointGizmos.Count;
int addControlPointCount = ctrlPointCount - controlPointStartIndex;
for (int i = 0; i < addControlPointCount; i++)
{
var controlPointGizmo = new SplineControlPointGizmo(controlPointStartIndex + i, activeSplineComponent);
controlPointGizmo.Initialize(game.Services, editorScene);
controlPointGizmos.Add(controlPointGizmo);
controlPointGizmo.IsEnabled = true;
if (controlPointGizmo.IsEnabled)
{
controlPointGizmo.GizmoRootEntity?.SetParent(splineEditingGizmoRootEntity);
}
}
}
else if (controlPointGizmos.Count > ctrlPointCount)
{
// Remove excess gizmos
int controlPointEndIndex = ctrlPointCount;
for (int i = controlPointGizmos.Count - 1; i >= controlPointEndIndex; i--)
{
var controlPointGizmo = controlPointGizmos[i];
controlPointGizmo.IsEnabled = false;
controlPointGizmo.GizmoRootEntity?.SetParent(null);
controlPointGizmo.Dispose();
if (mouseHoverControlPointGizmo == controlPointGizmo)
{
mouseHoverControlPointGizmo = null;
}
controlPointGizmos.RemoveAt(i);
}
}
}
private void RegenerateSplineVisualizer()
{
splineSamplePoints.Clear();
if (activeSplineComponent is not null)
{
SplineExtensions.CollectSplineSamplePositionsByResolution(activeSplineComponent.Spline, splineSamplePoints, sampleResolutionPerCurve: 64);
}
var lineVisualizerComponent = splineEditingGizmoRootEntity.Get<LineVisualizerComponent>();
if (lineVisualizerComponent is null)
{
lineVisualizerComponent = new LineVisualizerComponent();
lineVisualizerComponent.LineSet.OccludedStyle = LineOccludedStyle.Checkered;
splineEditingGizmoRootEntity.Add(lineVisualizerComponent);
}
else
{
lineVisualizerComponent.LineSet.Segments.Clear();
}
var splineSamplePointsSpan = CollectionsMarshal.AsSpan(splineSamplePoints);
for (int i = 0; i < splineSamplePointsSpan.Length - 1; i++)
{
var lineStartPos = splineSamplePointsSpan[i];
var lineNextPos = splineSamplePointsSpan[i + 1];
var instData = new LineSegment
{
StartPosition = lineStartPos,
EndPosition = lineNextPos,
StartColor = CurveColor,
EndColor = CurveColor,
LineThicknessPx = 3
};
lineVisualizerComponent.LineSet.Segments.Add(instData);
}
for (int i = 0; i < controlPointGizmos.Count; i++)
{
var controlPointGizmo = controlPointGizmos[i];
controlPointGizmo.InvalidateVisual();
}
}
private void UpdateControlPointEditingState()
{
var spline = activeSplineComponent.Spline;
if (spline is null)
{
return;
}
// Lazy get camera service for TryGetMouseRay
cameraService ??= Services.Get<IEditorGameCameraService>();
bool isShiftKeyDown = inputManager.IsKeyDown(Keys.LeftShift) || inputManager.IsKeyDown(Keys.RightShift);
bool isAltKeyDown = inputManager.IsKeyDown(Keys.LeftAlt) || inputManager.IsKeyDown(Keys.RightAlt);
bool isCtrlKeyDown = inputManager.IsKeyDown(Keys.LeftCtrl) || inputManager.IsKeyDown(Keys.RightCtrl);
// Hover
{
SplineControlPointGizmo? raycastHitControlPointGizmo = null;
int raycastHitControlPointIndex = -1;
var raycastHitControlPointEditingSelectionType = SplinePointEditingSelectionType.None;
if (TryGetMouseRay(out var mouseRay))
{
var raycastFilterFlags = SplinePointRaycastFilterFlags.All;
if (isAltKeyDown)
{
raycastFilterFlags = SplinePointRaycastFilterFlags.ControlPoint;
}
else if (isCtrlKeyDown)
{
raycastFilterFlags = SplinePointRaycastFilterFlags.Tangents;
}
float minHitDistance = float.PositiveInfinity;
for (int i = 0; i < controlPointGizmos.Count; i++)
{
var controlPointGizmo = controlPointGizmos[i];
if (controlPointGizmo.TryRaycastOnHandle(mouseRay, raycastFilterFlags, ref minHitDistance, ref raycastHitControlPointEditingSelectionType))
{
raycastHitControlPointGizmo = controlPointGizmo;
raycastHitControlPointIndex = i;
}
}
}
if (mouseHoverControlPointGizmo != raycastHitControlPointGizmo)
{
mouseHoverControlPointGizmo?.EditingSelectionType = SplinePointEditingSelectionType.None;
mouseHoverControlPointGizmo = raycastHitControlPointGizmo;
mouseHoverControlPointIndex = raycastHitControlPointIndex;
mouseHoverControlPointGizmo?.EditingSelectionType = raycastHitControlPointEditingSelectionType;
}
else if (mouseHoverControlPointGizmo is not null
&& mouseHoverControlPointGizmo.EditingSelectionType != raycastHitControlPointEditingSelectionType)
{
mouseHoverControlPointGizmo.EditingSelectionType = raycastHitControlPointEditingSelectionType;
mouseHoverControlPointGizmo.InvalidateVisual();
}
}
bool canControlMouse = editorMouseService.IsMouseAvailable;
bool isControllingMouse = canControlMouse && (isShiftKeyDown || isAltKeyDown || isCtrlKeyDown);
if (canControlMouse && inputManager.IsMouseButtonPressed(MouseButton.Left))
{
editorGameComponentGizmoService ??= Services.Get<IEditorGameComponentGizmoService>();
var gizmoCompEnity = editorGameComponentGizmoService.GetContentEntityUnderMouse();
if (gizmoCompEnity is null && inputInteraction is null && !isAddingControlPoint)
{
inputInteraction = new Interaction(this);
inputInteraction.Start();
}
}
if (isInputInteractionFinished)
{
inputInteraction = null;
isInputInteractionFinished = false;
editorMouseService.SetIsControllingMouse(false, owner: this);
}
if (inputInteraction is not null)
{
bool isContinuing = inputInteraction.Update(game.UpdateTime);
if (!isContinuing)
{
inputInteraction.End();
isInputInteractionFinished = true;
}
}
for (int i = 0; i < controlPointGizmos.Count; i++)
{
var controlPointGizmo = controlPointGizmos[i];
controlPointGizmo.Update();
}
}
private async Task UpdateTransformGizmoChangesAsync()
{
if (!pointTransformGizmo.IsEnabled
|| activeControlPointIndex < 0 || activeControlPointIndex >= activeSplineComponent.Spline.Count)
{
return;
}
var spline = activeSplineComponent.Spline;
var controlPoint = spline[activeControlPointIndex];
if (refreshAnchorPosition)
{
UpdateAnchorEntityPosition(controlPoint);
refreshAnchorPosition = false;
}
await pointTransformGizmo.Update();
var anchorEntityPos = activePointAnchorEntity.Transform.Position;
Matrix.Invert(ref activeSplineComponent.Entity.Transform.WorldMatrix, out var splineWorldInverseMatrix);
Vector3.Transform(in anchorEntityPos, in splineWorldInverseMatrix, out Vector3 anchorLocalPos);
if (activePointEditingSelectionType == SplinePointEditingSelectionType.ControlPoint)
{
if (controlPoint.Position != anchorLocalPos)
{
TryMoveControlPoint(spline, activeControlPointIndex, anchorLocalPos);
}
}
else if (activePointEditingSelectionType == SplinePointEditingSelectionType.TangentIn)
{
if (controlPoint.TangentInPosition != anchorLocalPos)
{
var newPosition = anchorLocalPos - controlPoint.Position;
TryMoveTangentHandle(isTangentIn: true, spline, activeControlPointIndex, newPosition);
}
}
else if (activePointEditingSelectionType == SplinePointEditingSelectionType.TangentOut)
{
if (controlPoint.TangentOutPosition != anchorLocalPos)
{
var newPosition = anchorLocalPos - controlPoint.Position;
TryMoveTangentHandle(isTangentIn: false, spline, activeControlPointIndex, newPosition);
}
}
}
private static bool TryMoveControlPoint(Spline spline, int controlPointIndex, Vector3 newPosition)
{
var controlPoint = spline[controlPointIndex];
bool hasChanged = false;
SetIfChanged(ref controlPoint.Position, newPosition, ref hasChanged);
if (!hasChanged)
{
return false;
}
spline[controlPointIndex] = controlPoint;
TryUpdateAutoTangents(spline, controlPointIndex);
return true;
}
private static bool TryMoveTangentHandle(bool isTangentIn, Spline spline, int controlPointIndex, Vector3 newPosition)
{
var controlPoint = spline[controlPointIndex];
bool hasChanged = false;
if (isTangentIn)
{
SetIfChanged(ref controlPoint.TangentIn, newPosition, ref hasChanged);
}
else
{
SetIfChanged(ref controlPoint.TangentOut, newPosition, ref hasChanged);
}
if (hasChanged)
{
spline[controlPointIndex] = controlPoint;
TryUpdateTangentsConstraint(isTangentIn, spline, controlPointIndex);
}
return hasChanged;
}
private static bool TryUpdateAutoTangents(Spline spline, int centerControlPointIndex)
{
bool hasChanged = false;
if (spline.TryGetPreviousControlPointIndex(centerControlPointIndex, out int prevIndex))
{
if (spline[prevIndex].Type == SplineControlPointType.Auto)
{
hasChanged = TryUpdateAutoTangentsSingleControlPoint(spline, prevIndex) || hasChanged;
}
}
if (spline[centerControlPointIndex].Type == SplineControlPointType.Auto)
{
hasChanged = TryUpdateAutoTangentsSingleControlPoint(spline, centerControlPointIndex) || hasChanged;
}
if (spline.TryGetNextControlPointIndex(centerControlPointIndex, out int nextIndex))
{
if (spline[nextIndex].Type == SplineControlPointType.Auto)
{
hasChanged = TryUpdateAutoTangentsSingleControlPoint(spline, nextIndex) || hasChanged;
}
}
return hasChanged;
}
private static bool TryUpdateAutoTangentsSingleControlPoint(Spline spline, int controlPointIndex)
{
Vector3? prevCtrlPointPosition = null;
Vector3? nextCtrlPointPosition = null;
if (spline.TryGetPreviousControlPointIndex(controlPointIndex, out int prevCtrlPointIndex))
{
prevCtrlPointPosition = spline[prevCtrlPointIndex].Position;
}
if (spline.TryGetNextControlPointIndex(controlPointIndex, out int nextCtrlPointIndex))
{
nextCtrlPointPosition = spline[nextCtrlPointIndex].Position;
}
var controlPoint = spline[controlPointIndex];
SplineUtil.CalculateAutoTangents(
controlPoint.Position, prevCtrlPointPosition, nextCtrlPointPosition, strength: SplineUtil.DefaultAutoTangentStrength,
out var newTangentIn, out var newTangentOut);
bool hasChanged = false;
SetIfChanged(ref controlPoint.TangentIn, newTangentIn, ref hasChanged);
SetIfChanged(ref controlPoint.TangentOut, newTangentOut, ref hasChanged);
if (hasChanged)
{
spline[controlPointIndex] = controlPoint;
}
return hasChanged;
}
private static bool TryUpdateLinearTangents(Spline spline, int controlPointIndex)
{
var controlPoint = spline[controlPointIndex];
bool hasChanged = false;
// Tangents are not relevant for linear type, so just set to zero
SetIfChanged(ref controlPoint.TangentIn, Vector3.Zero, ref hasChanged);
SetIfChanged(ref controlPoint.TangentOut, Vector3.Zero, ref hasChanged);
if (hasChanged)
{
spline[controlPointIndex] = controlPoint;
}
return hasChanged;
}
private static bool TryUpdateTangentsConstraint(bool isTangentInModified, Spline spline, int controlPointIndex)
{
bool hasChanged = false;
var controlPoint = spline[controlPointIndex];
switch (controlPoint.Type)
{
case SplineControlPointType.Mirrored:
// Mirror the other handle
if (isTangentInModified)
{
SetIfChanged(ref controlPoint.TangentOut, -controlPoint.TangentIn, ref hasChanged);
}
else
{
SetIfChanged(ref controlPoint.TangentIn, -controlPoint.TangentOut, ref hasChanged);
}
break;
case SplineControlPointType.Aligned:
if (isTangentInModified)
{
var newTangentPosition = SplineUtil.CalculateAlignedHandle(controlPoint.TangentIn, controlPoint.TangentOut);
SetIfChanged(ref controlPoint.TangentOut, newTangentPosition, ref hasChanged);
}
else
{
var newTangentPosition = SplineUtil.CalculateAlignedHandle(controlPoint.TangentOut, controlPoint.TangentIn);
SetIfChanged(ref controlPoint.TangentIn, newTangentPosition, ref hasChanged);
}
break;
case SplineControlPointType.Auto:
case SplineControlPointType.Linear:
case SplineControlPointType.Free:
default:
// Not applicable
return false;
}
if (hasChanged)
{
spline[controlPointIndex] = controlPoint;
}
return hasChanged;
}
private static void SetIfChanged<T>(ref T backingField, T newValue, ref bool hasChanged)
where T : IEquatable<T>
{
if (!backingField.Equals(newValue))
{
backingField = newValue;
hasChanged = true;
}
}
private EditorGameEntityTransformService transformService;
private void ActivateSplinePointEditing(SplineComponent splineComponent, int controlPointIndex, SplinePointEditingSelectionType editingSelectionType)
{
bool hasChangedActiveSpline = activeSplineComponent != splineComponent;
activeSplineComponent = splineComponent;
if (hasChangedActiveSpline)
{
activeSplineComponent.SplinePropertyChanged += OnSplineChanged;
activeSplineComponent.ControlPointsChanged += OnSplineChanged;
}
activeControlPointIndex = controlPointIndex;
activePointEditingSelectionType = editingSelectionType;
if (editingSelectionType != SplinePointEditingSelectionType.None)
{
pointTransformGizmo.IsEnabled = true;
var splinePosition = activeSplineComponent.Entity.Transform.WorldMatrix.TranslationVector;
activePointAnchorEntity.Transform.Position = splinePosition;
var controlPoint = activeSplineComponent.Spline[activeControlPointIndex];
UpdateAnchorEntityPosition(controlPoint);
transformService ??= game.EditorServices.Get<EditorGameEntityTransformService>();
if (transformService is not null)
{
transformService.ActiveTransformationGizmo.IsEnabled = false;
}
}
}
private void DeactivateEditSpline(bool deselectSpline = true)
{
if (deselectSpline)
{
activeSplineComponent.SplinePropertyChanged -= OnSplineChanged;
activeSplineComponent.ControlPointsChanged -= OnSplineChanged;
activeSplineComponent = null;
}
activeControlPointIndex = -1;
activePointEditingSelectionType = SplinePointEditingSelectionType.None;
activePointAnchorEntity.Scene = null;
pointTransformGizmo.IsEnabled = false;
for (int i = 0; i < controlPointGizmos.Count; i++)
{
var controlPointGizmo = controlPointGizmos[i];
controlPointGizmo.IsEnabled = false;
controlPointGizmo.GizmoRootEntity?.SetParent(null);
controlPointGizmo.Dispose();
}
controlPointGizmos.Clear();
isSplineChangedUpdateRequired = true;
}
private void UpdateAnchorEntityPosition(SplineControlPoint controlPoint)
{