forked from BabylonJS/Babylon.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workbench.tsx
1119 lines (996 loc) · 47.9 KB
/
workbench.tsx
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
import * as React from "react";
import { DragOverLocation, GlobalState } from "../globalState";
import { Nullable } from "babylonjs/types";
import { Control } from "babylonjs-gui/2D/controls/control";
import { AdvancedDynamicTexture } from "babylonjs-gui/2D/advancedDynamicTexture";
import { Vector2, Vector3 } from "babylonjs/Maths/math.vector";
import { Engine } from "babylonjs/Engines/engine";
import { Scene } from "babylonjs/scene";
import { Color4 } from "babylonjs/Maths/math.color";
import { ArcRotateCamera } from "babylonjs/Cameras/arcRotateCamera";
import { HemisphericLight } from "babylonjs/Lights/hemisphericLight";
import { Axis } from "babylonjs/Maths/math.axis";
import { PointerEventTypes } from "babylonjs/Events/pointerEvents";
import { IWheelEvent } from "babylonjs/Events/deviceInputEvents";
import { Epsilon } from "babylonjs/Maths/math.constants";
import { Container } from "babylonjs-gui/2D/controls/container";
import { Rectangle } from "babylonjs-gui/2D/controls/rectangle";
import { KeyboardEventTypes, KeyboardInfo } from "babylonjs/Events/keyboardEvents";
import { Line } from "babylonjs-gui/2D/controls/line";
import { DataStorage } from "babylonjs/Misc/dataStorage";
import { Grid } from "babylonjs-gui/2D/controls/grid";
import { Tools } from "../tools";
import { Observer } from "babylonjs/Misc/observable";
import { ISize } from "babylonjs/Maths/math";
import { Texture } from "babylonjs/Materials/Textures/texture";
require("./workbenchCanvas.scss");
export interface IWorkbenchComponentProps {
globalState: GlobalState;
}
export enum ConstraintDirection {
NONE = 0,
X = 2, // Horizontal constraint
Y = 3, // Vertical constraint
}
export class WorkbenchComponent extends React.Component<IWorkbenchComponentProps> {
private _rootContainer: React.RefObject<HTMLCanvasElement>;
private _setConstraintDirection: boolean = false;
private _mouseStartPointX: Nullable<number> = null;
private _mouseStartPointY: Nullable<number> = null;
public _scene: Scene;
private _selectedGuiNodes: Control[] = [];
private _ctrlKeyIsPressed = false;
private _altKeyIsPressed = false;
private _constraintDirection = ConstraintDirection.NONE;
private _forcePanning = false;
private _forceZooming = false;
private _forceSelecting = true;
private _outlines = false;
private _panning: boolean;
private _canvas: HTMLCanvasElement;
private _responsive: boolean;
private _isOverGUINode: Control[] = [];
private _clipboard: Control[] = [];
private _selectAll: boolean = false;
private _pasted: boolean;
private _engine: Engine;
private _liveRenderObserver: Nullable<Observer<AdvancedDynamicTexture>>;
private _guiRenderObserver: Nullable<Observer<AdvancedDynamicTexture>>;
private _mainSelection: Nullable<Control> = null;
private _selectionDepth = 0;
private _doubleClick: Nullable<Control> = null;
private _lockMainSelection: boolean = false;
public _liveGuiTextureRerender: boolean = true;
private _anyControlClicked = true;
private _visibleRegionContainer : Container;
private _panAndZoomContainer: Container;
public get visibleRegionContainer() {
return this._visibleRegionContainer;
}
private _trueRootContainer: Container;
public set trueRootContainer(value: Container) {
if (value === this._trueRootContainer) return;
this._visibleRegionContainer.children.forEach(child => this._visibleRegionContainer.removeControl(child));
this._visibleRegionContainer.addControl(value);
this._trueRootContainer = value;
this._trueRootContainer.isPointerBlocker = false;
value._host = this.props.globalState.guiTexture;
}
public get trueRootContainer() {
return this._trueRootContainer;
}
private _nextLiveGuiRender = -1;
private _liveGuiRerenderDelay = 100;
private _defaultGUISize: ISize = {width: 1024, height: 1024};
private _initialPanningOffset: Vector2 = new Vector2(0,0);
private _panningOffset = new Vector2(0,0);
private _zoomFactor = 1;
private _zoomModeIncrement = 0.2;
private _guiSize = this._defaultGUISize;
public get guiSize() {
return this._guiSize;
}
// sets the size of the GUI and makes all neccessary adjustments
public set guiSize(value: ISize) {
this._guiSize = {...value};
this._visibleRegionContainer.widthInPixels = this._guiSize.width;
this._visibleRegionContainer.heightInPixels = this._guiSize.height;
this.globalState.onResizeObservable.notifyObservers(this._guiSize);
this.globalState.onFitToWindowObservable.notifyObservers();
this.globalState.onArtBoardUpdateRequiredObservable.notifyObservers();
}
public applyEditorTransformation() {
const adt = this.globalState.guiTexture;
if (adt._rootContainer != this._panAndZoomContainer) {
adt._rootContainer = this._panAndZoomContainer;
this._visibleRegionContainer.addControl(this._trueRootContainer);
}
if (adt.getSize().width !== this._engine.getRenderWidth() || adt.getSize().height !== this._engine.getRenderHeight()) {
adt.scaleTo(this._engine.getRenderWidth(), this._engine.getRenderHeight());
}
this._trueRootContainer.clipContent = false;
this._trueRootContainer.clipChildren = false;
}
public removeEditorTransformation() {
const adt = this.globalState.guiTexture;
if (adt._rootContainer != this._trueRootContainer) {
this._visibleRegionContainer.removeControl(this._trueRootContainer);
adt._rootContainer = this._trueRootContainer;
}
this._trueRootContainer.clipContent = true;
this._trueRootContainer.clipChildren = true;
}
public get globalState() {
return this.props.globalState;
}
public get nodes() {
return this.globalState.guiTexture.getChildren()[0].children;
}
public get selectedGuiNodes() {
return this._selectedGuiNodes;
}
// given a control gets the parent up the tree selectionDepth times. Selection depth is altered as we go down the tree.
private _getParentWithDepth(control: Control) {
--this._selectionDepth;
let parent = control;
for (let i = 0; i < this._selectionDepth; ++i) {
if (!parent.parent) {
break;
}
parent = parent.parent;
}
return parent;
}
//gets the higher parent of a given control.
private _getMaxParent(control: Control, maxParent: Control) {
let parent = control;
this._selectionDepth = 0;
while (parent.parent && parent.parent !== maxParent) {
parent = parent.parent;
++this._selectionDepth;
}
return parent;
}
constructor(props: IWorkbenchComponentProps) {
super(props);
this._rootContainer = React.createRef();
this._responsive = DataStorage.ReadBoolean("Responsive", true);
props.globalState.onSelectionChangedObservable.add((selection) => {
if (!selection) {
this.changeSelectionHighlight(false);
this._selectedGuiNodes = [];
this._selectAll = false;
this._mainSelection = null;
} else {
if (selection instanceof Control) {
if (this._ctrlKeyIsPressed) {
let index = this._selectedGuiNodes.indexOf(selection);
if (index === -1) {
this._selectedGuiNodes.push(selection);
} else {
this.changeSelectionHighlight(false);
this._selectedGuiNodes.splice(index, 1);
}
} else if (this._selectedGuiNodes.length <= 1) {
this.changeSelectionHighlight(false);
this._selectedGuiNodes = [selection];
if (!this._lockMainSelection && selection != this.props.globalState.guiTexture._rootContainer) {
//incase the selection did not come from the canvas and mouse
this._mainSelection = selection;
}
this._lockMainSelection = false;
this._selectAll = false;
}
this.changeSelectionHighlight(true);
}
}
});
props.globalState.onPanObservable.add(() => {
this._forcePanning = !this._forcePanning;
this._forceSelecting = false;
this._forceZooming = false;
if (!this._forcePanning) {
this.globalState.onSelectionButtonObservable.notifyObservers();
} else {
this._canvas.style.cursor = "grab";
}
this.updateHitTest(this.globalState.guiTexture.getChildren()[0], this._forceSelecting);
// this.artBoardBackground.isHitTestVisible = true;
});
props.globalState.onSelectionButtonObservable.add(() => {
this._forceSelecting = !this._forceSelecting;
this._forcePanning = false;
this._forceZooming = false;
this._canvas.style.cursor = "default";
this.updateHitTest(this.globalState.guiTexture.getChildren()[0], this._forceSelecting);
// this.artBoardBackground.isHitTestVisible = true;
});
props.globalState.onZoomObservable.add(() => {
this._forceZooming = !this._forceZooming;
this._forcePanning = false;
this._forceSelecting = false;
if (!this._forceZooming) {
this.globalState.onSelectionButtonObservable.notifyObservers();
} else {
this._canvas.style.cursor = "zoom-in";
}
this.updateHitTest(this.globalState.guiTexture.getChildren()[0], this._forceSelecting);
// this.artBoardBackground.isHitTestVisible = true;
});
props.globalState.onFitToWindowObservable.add(() => {
this._panningOffset = new Vector2(0,0);
const xFactor = this._engine.getRenderWidth() / this.guiSize.width;
const yFactor = this._engine.getRenderHeight() / this.guiSize.height;
this._zoomFactor = Math.min(xFactor, yFactor) * 0.9;
});
props.globalState.onOutlinesObservable.add(() => {
this._outlines = !this._outlines;
});
props.globalState.onParentingChangeObservable.add((control) => {
this.parent(control);
});
props.globalState.onResponsiveChangeObservable.add((value) => {
this._responsive = value;
});
this.props.globalState.hostDocument!.addEventListener("keyup", this.keyEvent, false);
// Hotkey shortcuts
this.props.globalState.hostDocument!.addEventListener("keydown", this.keyEvent, false);
this.props.globalState.hostDocument!.defaultView!.addEventListener("blur", this.blurEvent, false);
props.globalState.onWindowResizeObservable.add(() => {
this.props.globalState.onGizmoUpdateRequireObservable.notifyObservers();
this.props.globalState.onArtBoardUpdateRequiredObservable.notifyObservers();
this._engine.resize();
});
this.props.globalState.workbench = this;
}
determineMouseSelection(selection: Nullable<Control>) {
if (selection && this._selectedGuiNodes.length <= 1) {
// if we're still on the same main selection, got down the tree.
if (selection === this._selectedGuiNodes[0] || selection === this._mainSelection) {
selection = this._getParentWithDepth(selection);
} else { // get the start of our tree by getting our max parent and storing our main selected control
if (this._isMainSelectionParent(selection) && this._mainSelection) {
selection = this._getParentWithDepth(selection);
}
else {
selection = this._getMaxParent(selection, this.trueRootContainer);
}
this._mainSelection = selection;
}
}
this._lockMainSelection = true;
this.props.globalState.onSelectionChangedObservable.notifyObservers(selection);
}
keyEvent = (evt: KeyboardEvent) => {
this._ctrlKeyIsPressed = evt.ctrlKey;
this._altKeyIsPressed = evt.altKey;
if (evt.shiftKey) {
this._setConstraintDirection = this._constraintDirection === ConstraintDirection.NONE;
} else {
this._setConstraintDirection = false;
this._constraintDirection = ConstraintDirection.NONE;
}
if (evt.key === "Delete" || evt.key === "Backspace") {
if (!this.props.globalState.lockObject.lock) {
this._selectedGuiNodes.forEach((guiNode) => {
if (guiNode !== this.globalState.guiTexture.getChildren()[0]) {
this.props.globalState.guiTexture.removeControl(guiNode);
this.props.globalState.liveGuiTexture?.removeControl(guiNode);
guiNode.dispose();
}
});
this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
}
}
if (this._ctrlKeyIsPressed && !this.props.globalState.lockObject.lock) {
if (evt.key === "a") {
this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
let index = 0;
this.nodes.forEach((node) => {
if (index++) {
//skip the first node, the background
this.selectAllGUI(node);
}
});
} else if (evt.key === "c") {
this.copyToClipboard();
} else if (evt.key === "v" && !this._pasted) {
this.globalState.onSelectionChangedObservable.notifyObservers(null);
this.pasteFromClipboard();
this._pasted = true;
}
} else if (!this._ctrlKeyIsPressed) {
this._pasted = false;
}
if (this._forceZooming) {
this._canvas.style.cursor = this._altKeyIsPressed ? "zoom-out" : "zoom-in";
}
};
private updateHitTest(guiControl: Control, value: boolean) {
guiControl.isHitTestVisible = value;
if (guiControl instanceof Container) {
(guiControl as Container).children.forEach((child) => {
this.updateHitTest(child, value);
});
}
}
private updateHitTestForSelection(value: boolean) {
if (this._forceSelecting && !value) return;
this.selectedGuiNodes.forEach((control) => {
control.isHitTestVisible = value;
});
}
public copyToClipboard() {
this._clipboard = [];
if (this._selectAll) {
let index = 0;
this.nodes.forEach((node) => {
if (index++) {
//skip the first node, the background
this._clipboard.push(node);
}
});
} else {
this._clipboard = this.selectedGuiNodes;
}
}
public pasteFromClipboard() {
this._clipboard.forEach((control) => {
this.CopyGUIControl(control);
});
}
public CopyGUIControl(original: Control) {
const serializationObject = {};
original.serialize(serializationObject);
const newControl = Control.Parse(serializationObject, this.props.globalState.guiTexture);
if (newControl) {
//insert the new control into the adt or parent container
this.props.globalState.workbench.appendBlock(newControl);
this.props.globalState.guiTexture.removeControl(newControl);
if (original.parent?.typeName === "Grid") {
const cell = Tools.getCellInfo(original.parent as Grid, original);
(original.parent as Grid).addControl(newControl, cell.x, cell.y);
} else {
original.parent?.addControl(newControl);
}
let index = 1;
while (
this.props.globalState.guiTexture.getDescendants(false).filter(
//search if there are any copies
(control) => control.name === `${newControl.name} Copy ${index}`
).length
) {
index++;
}
newControl.name = `${newControl.name} Copy ${index}`;
this.props.globalState.onSelectionChangedObservable.notifyObservers(newControl);
}
}
private selectAllGUI(node: Control) {
this.globalState.onSelectionChangedObservable.notifyObservers(node);
if (node instanceof Container) {
(node as Container).children.forEach((child) => {
this.selectAllGUI(child);
});
}
this._selectAll = true;
}
blurEvent = () => {
this._ctrlKeyIsPressed = false;
this._constraintDirection = ConstraintDirection.NONE;
this.props.globalState.guiGizmo.onUp();
};
componentWillUnmount() {
this.props.globalState.hostDocument!.removeEventListener("keyup", this.keyEvent);
this.props.globalState.hostDocument!.removeEventListener("keydown", this.keyEvent);
this.props.globalState.hostDocument!.defaultView!.removeEventListener("blur", this.blurEvent);
if (this.props.globalState.liveGuiTexture) {
this.props.globalState.liveGuiTexture.onEndRenderObservable.remove(this._liveRenderObserver);
this.props.globalState.guiTexture.onBeginRenderObservable.remove(this._guiRenderObserver);
this.props.globalState.guiTexture.getDescendants(false).forEach(control => {
if (!control.metadata || !control.metadata.guiEditor) {
return;
}
control.onPointerUpObservable.remove(control.metadata.onPointerUp);
control.onPointerDownObservable.remove(control.metadata.onPointerDown);
control.onPointerEnterObservable.remove(control.metadata.onPointerEnter);
control.onPointerOutObservable.remove(control.metadata.onPointerOut);
control.onDisposeObservable.remove(control.metadata.onDispose);
control.highlightLineWidth = control.metadata.highlightLineWidth;
control.isHighlighted = control.metadata.isHighlighted;
control.metadata = control.metadata.metadata;
})
}
this._engine.dispose();
}
loadFromJson(serializationObject: any) {
this.removeEditorTransformation();
this.globalState.onSelectionChangedObservable.notifyObservers(null);
if (this.props.globalState.liveGuiTexture) {
this.globalState.liveGuiTexture?.parseContent(serializationObject, true);
this.synchronizeLiveGUI();
} else {
this.globalState.guiTexture.parseContent(serializationObject, true);
}
this.trueRootContainer = this.props.globalState.guiTexture._rootContainer;
this.guiSize = this.globalState.guiTexture.getSize();
this.loadToEditor();
}
async loadFromSnippet(snippetId: string) {
this.removeEditorTransformation();
this.globalState.onSelectionChangedObservable.notifyObservers(null);
if (this.props.globalState.liveGuiTexture) {
await this.globalState.liveGuiTexture?.parseFromSnippetAsync(snippetId, true);
this.synchronizeLiveGUI();
} else {
await this.globalState.guiTexture.parseFromSnippetAsync(snippetId, true);
}
this.trueRootContainer = this.props.globalState.guiTexture._rootContainer;
this.guiSize = this.globalState.guiTexture.getSize();
this.loadToEditor();
if (this.props.globalState.customLoad) {
this.props.globalState.customLoad.action(this.globalState.guiTexture.snippetId).catch((err) => {
alert("Unable to load your GUI");
});
}
this.globalState.onSelectionChangedObservable.notifyObservers(null);
}
loadToEditor() {
this.globalState.guiTexture.rootContainer.children.forEach((guiElement) => {
if (guiElement.name === "Art-Board-Background" && guiElement.typeName === "Rectangle") {
// this.artBoardBackground = guiElement as Rectangle;
return;
}
this.createNewGuiNode(guiElement);
});
if (this.props.globalState.guiTexture.getChildren()[0].children.length) {
// this.props.globalState.guiTexture.getChildren()[0].children.unshift(this.props.globalState.workbench.artBoardBackground);
} else {
// this.props.globalState.guiTexture.getChildren()[0].children.push(this.props.globalState.workbench.artBoardBackground);
}
this._isOverGUINode = [];
}
changeSelectionHighlight(value: boolean) {
this._selectedGuiNodes.forEach((node) => {
if (this._outlines) {
node.isHighlighted = true;
node.highlightLineWidth = 5;
} else {
node.isHighlighted = value && node.typeName === "Grid";
node.highlightLineWidth = 5
}
});
this.updateHitTestForSelection(value);
}
findNodeFromGuiElement(guiControl: Control) {
return this.nodes.filter((n) => n === guiControl)[0];
}
appendBlock(guiElement: Control) {
if (this.globalState.liveGuiTexture) {
this.globalState.liveGuiTexture.addControl(guiElement);
}
var newGuiNode = this.createNewGuiNode(guiElement);
this.trueRootContainer.addControl(guiElement);
return newGuiNode;
}
//is the
private _isMainSelectionParent(control: Nullable<Control>) {
do {
if (this._mainSelection === control) {
return true;
};
control = control?.parent || null;
} while (control);
return false;
}
createNewGuiNode(guiControl: Control) {
const onPointerUp = guiControl.onPointerUpObservable.add((evt) => {
this.clicked = false;
});
const onPointerDown = guiControl.onPointerDownObservable.add((evt) => {
this._anyControlClicked = true;
if (!this.isUp || evt.buttonIndex > 0) return;
if (this._forceSelecting) {
// if this is our first click and the clicked control is a child the of the main selected control.
if (!this._doubleClick && this._isMainSelectionParent(guiControl)) {
this._doubleClick = guiControl;
window.setTimeout(() => {
this._doubleClick = null;
}, Scene.DoubleClickDelay);
}
else { //function will either select our new main control or contrue down the tree.
this.determineMouseSelection(guiControl);
this._doubleClick = null;
}
this.isUp = false;
}
});
const onPointerEnter = guiControl.onPointerEnterObservable.add((evt) => {
if (this._isOverGUINode.indexOf(guiControl) === -1) {
this._isOverGUINode.push(guiControl);
}
});
const onPointerOut = guiControl.onPointerOutObservable.add((evt) => {
const index = this._isOverGUINode.indexOf(guiControl);
if (index !== -1) {
this._isOverGUINode.splice(index, 1);
}
});
const onDispose = guiControl.onDisposeObservable.add((evt) => {
const index = this._isOverGUINode.indexOf(guiControl);
if (index !== -1) {
this._isOverGUINode.splice(index, 1);
}
});
// use metadata to keep track of things we need to cleanup/restore when the gui editor closes
// also stores the old metadata
guiControl.metadata = {
guiEditor: true,
metadata: guiControl.metadata,
isHighlighted: guiControl.isHighlighted,
highlightLineWidth: guiControl.highlightLineWidth,
isReadOnly: guiControl.isReadOnly,
isHitTestVisible: guiControl.isHitTestVisible,
onPointerUp,
onPointerDown,
onPointerEnter,
onPointerOut,
onDispose
}
guiControl.highlightLineWidth = 5;
guiControl.isHighlighted = false;
guiControl.isReadOnly = true;
guiControl.isHitTestVisible = true;
guiControl.getDescendants(true).forEach((child) => {
this.createNewGuiNode(child);
});
return guiControl;
}
private parent(dropLocationControl: Nullable<Control>) {
const draggedControl = this.props.globalState.draggedControl;
const draggedControlParent = draggedControl?.parent;
if (draggedControlParent && draggedControl) {
if (this._isNotChildInsert(dropLocationControl, draggedControl)) {
//checking to make sure the element is not being inserted into a child
if (dropLocationControl != null) {
//the control you are dragging onto top
if (
dropLocationControl instanceof Container && //dropping inside a contrainer control
this.props.globalState.draggedControlDirection === DragOverLocation.CENTER
) {
draggedControlParent.removeControl(draggedControl);
(dropLocationControl as Container).addControl(draggedControl);
const stackPanel = dropLocationControl.typeName === "StackPanel" || dropLocationControl.typeName === "VirtualKeyboard";
if (stackPanel) {
this._convertToPixels(draggedControl, dropLocationControl as Container);
}
} else if (dropLocationControl.parent) {
//dropping inside the controls parent container
if (dropLocationControl.parent.typeName != "Grid") {
draggedControlParent.removeControl(draggedControl);
let index = dropLocationControl.parent.children.indexOf(dropLocationControl);
const reversed = dropLocationControl.parent.typeName === "StackPanel" || dropLocationControl.parent.typeName === "VirtualKeyboard";
index = this._adjustParentingIndex(index, reversed); //adjusting index to be before or after based on where the control is over
dropLocationControl.parent.children.splice(index, 0, draggedControl);
draggedControl.parent = dropLocationControl.parent;
if (reversed) {
this._convertToPixels(draggedControl, draggedControl.parent);
}
} else if (dropLocationControl.parent === draggedControlParent) {
//special case for grid
this._reorderGrid(dropLocationControl.parent as Grid, draggedControl, dropLocationControl);
} else {
draggedControlParent.removeControl(draggedControl);
(dropLocationControl.parent as Container).addControl(draggedControl);
this._reorderGrid(dropLocationControl.parent as Grid, draggedControl, dropLocationControl);
}
} else {
draggedControlParent.removeControl(draggedControl);
this.trueRootContainer.addControl(draggedControl);
}
} else {
//starting at index 1 because of object "Art-Board-Background" must be at index 0
draggedControlParent.removeControl(draggedControl);
draggedControlParent.children.splice(1, 0, draggedControl);
draggedControl.parent = draggedControlParent;
}
}
}
this.globalState.draggedControl = null;
this.globalState.onPropertyGridUpdateRequiredObservable.notifyObservers();
}
private _convertToPixels(draggedControl: Control, parent: Container) {
const width = draggedControl.widthInPixels + "px";
const height = draggedControl.heightInPixels + "px";
if (draggedControl.width !== width || draggedControl.height !== height) {
draggedControl.width = width;
draggedControl.height = height;
this.props.globalState.hostWindow.alert("Warning: Parenting to stack panel will convert control to pixel value");
}
}
private _reorderGrid(grid: Grid, draggedControl: Control, dropLocationControl: Control) {
const cellInfo = Tools.getCellInfo(grid, draggedControl);
grid.removeControl(draggedControl);
let index = grid.children.indexOf(dropLocationControl);
index = this._adjustParentingIndex(index);
Tools.reorderGrid(grid, index, draggedControl, cellInfo);
}
private _isNotChildInsert(control: Nullable<Control>, draggedControl: Nullable<Control>) {
while (control?.parent) {
if (control.parent == draggedControl) {
return false;
}
control = control.parent;
}
return true;
}
private _adjustParentingIndex(index: number, reversed: boolean = false) {
switch (this.props.globalState.draggedControlDirection) {
case DragOverLocation.ABOVE:
return reversed ? index : index + 1;
case DragOverLocation.BELOW:
case DragOverLocation.CENTER:
return reversed ? index + 1 : index;
}
return index;
}
public isSelected(value: boolean, guiNode: Control) {
this.globalState.onSelectionChangedObservable.notifyObservers(guiNode);
}
public clicked: boolean;
public _onMove(guiControl: Control, evt: Vector2, startPos: Vector2, ignorClick: boolean = false) {
this._liveGuiTextureRerender = false;
let newX = evt.x - startPos.x;
let newY = evt.y - startPos.y;
if (this._setConstraintDirection) {
this._setConstraintDirection = false;
this._constraintDirection = Math.abs(newX) >= Math.abs(newY) ? ConstraintDirection.X : ConstraintDirection.Y;
}
if (this._constraintDirection === ConstraintDirection.X) {
newY = 0;
} else if (this._constraintDirection === ConstraintDirection.Y) {
newX = 0;
}
if (guiControl.typeName === "Line") {
let line = guiControl as Line;
const x1 = (line.x1 as string).substr(0, (line.x1 as string).length - 2); //removing the 'px'
const x2 = (line.x2 as string).substr(0, (line.x2 as string).length - 2);
const y1 = (line.y1 as string).substr(0, (line.y1 as string).length - 2);
const y2 = (line.y2 as string).substr(0, (line.y2 as string).length - 2);
line.x1 = Number(x1) + newX;
line.x2 = Number(x2) + newX;
line.y1 = Number(y1) + newY;
line.y2 = Number(y2) + newY;
return true;
}
guiControl.leftInPixels += newX;
guiControl.topInPixels += newY;
//convert to percentage
if (this._responsive) {
this.convertToPercentage(guiControl, false);
}
this.props.globalState.onPropertyGridUpdateRequiredObservable.notifyObservers();
return true;
}
convertToPercentage(guiControl: Control, includeScale: boolean) {
let ratioX = 1;//this._textureMesh.scaling.x;
let ratioY = 1;//this._textureMesh.scaling.z;
if (guiControl.parent) {
if (guiControl.parent.typeName === "Grid") {
const cellInfo = (guiControl.parent as Grid).getChildCellInfo(guiControl);
const cell = (guiControl.parent as Grid).cells[cellInfo];
ratioX = cell.widthInPixels;
ratioY = cell.heightInPixels;
} else if (guiControl.parent.typeName === "Rectangle" || guiControl.parent.typeName === "Button") {
const thickness = (guiControl.parent as Rectangle).thickness * 2;
ratioX = guiControl.parent._currentMeasure.width - thickness;
ratioY = guiControl.parent._currentMeasure.height - thickness;
} else {
ratioX = guiControl.parent._currentMeasure.width;
ratioY = guiControl.parent._currentMeasure.height;
}
}
const left = (guiControl.leftInPixels * 100) / ratioX;
const top = (guiControl.topInPixels * 100) / ratioY;
guiControl.left = `${left.toFixed(2)}%`;
guiControl.top = `${top.toFixed(2)}%`;
if (includeScale) {
const width = (guiControl.widthInPixels * 100) / ratioX;
const height = (guiControl.heightInPixels * 100) / ratioY;
guiControl.width = `${width.toFixed(2)}%`;
guiControl.height = `${height.toFixed(2)}%`;
}
}
onMove(evt: React.PointerEvent) {
var pos = this.getScaledPointerPosition();
// Move or guiNodes
if (this._mouseStartPointX != null && this._mouseStartPointY != null && !this._panning) {
var x = this._mouseStartPointX;
var y = this._mouseStartPointY;
let selected = false;
this.selectedGuiNodes.forEach((element) => {
if (pos) {
selected = this._onMove(element, new Vector2(pos.x, pos.y), new Vector2(x, y), false) || selected;
}
});
this._mouseStartPointX = pos ? pos.x : this._mouseStartPointX;
this._mouseStartPointY = pos ? pos.y : this._mouseStartPointY;
}
}
private _screenToTexturePosition(screenPos: Vector2) {
const zoomVector = new Vector2(this._zoomFactor, this._zoomFactor);
return screenPos.divideInPlace(zoomVector).add(this._panningOffset);
}
private getScaledPointerPosition() {
return this._screenToTexturePosition(new Vector2(this._scene.pointerX, this._scene.pointerY));
}
onDown(evt: React.PointerEvent<HTMLElement>) {
this._rootContainer.current?.setPointerCapture(evt.pointerId);
if (this._isOverGUINode.length === 0 && !evt.button) {
if (this._forceSelecting) {
this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
}
return;
}
var pos = this.getScaledPointerPosition();
if (this._forceSelecting) {
this._mouseStartPointX = pos ? pos.x : this._mouseStartPointX;
this._mouseStartPointY = pos ? pos.y : this._mouseStartPointY;
}
}
public isUp: boolean = true;
onUp(evt: React.PointerEvent) {
this._mouseStartPointX = null;
this._mouseStartPointY = null;
this._constraintDirection = ConstraintDirection.NONE;
this._rootContainer.current?.releasePointerCapture(evt.pointerId);
this.isUp = true;
}
public createGUICanvas() {
// Get the canvas element from the DOM.
const canvas = this._rootContainer.current as HTMLCanvasElement;
this._canvas = canvas;
// Associate a Babylon Engine to it.
this._engine = new Engine(canvas);
// Create our first scene.
this._scene = new Scene(this._engine);
const clearColor = 204 / 255.0;
this._scene.clearColor = new Color4(clearColor, clearColor, clearColor, 0.0);
const light = new HemisphericLight("light1", Axis.Y, this._scene);
light.intensity = 0.9;
this._guiSize = this._defaultGUISize;
this._panAndZoomContainer = new Container("panAndZoom");
this._panAndZoomContainer.clipContent = false;
this._panAndZoomContainer.clipChildren = false;
this._visibleRegionContainer = new Container("visibleRegion");
this._visibleRegionContainer.clipChildren = false;
this._visibleRegionContainer.clipContent = false;
this._visibleRegionContainer.widthInPixels = this.guiSize.width;
this._visibleRegionContainer.heightInPixels = this.guiSize.height;
this._panAndZoomContainer.addControl(this._visibleRegionContainer);
const adt =
this.globalState.guiTexture =
this._visibleRegionContainer._host =
this._panAndZoomContainer._host =
AdvancedDynamicTexture.CreateFullscreenUI("guiTexture", true, this._scene, Texture.NEAREST_NEAREST_MIPNEAREST, false);
adt.useInvalidateRectOptimization = false;
this.trueRootContainer = adt.rootContainer;
adt.onEndRenderObservable.add(() => this.props.globalState.onGizmoUpdateRequireObservable.notifyObservers());
this.synchronizeLiveGUI();
new ArcRotateCamera("Camera", 0, 0, 0, Vector3.Zero(), this._scene);
// This attaches the mouse controls
this.addControls(this._scene);
this._scene.getEngine().onCanvasPointerOutObservable.clear();
this._scene.doNotHandleCursors = true;
// Watch for browser/canvas resize events
this.globalState.hostWindow.addEventListener("resize", () => {
this.props.globalState.onWindowResizeObservable.notifyObservers();
});
this._engine.resize();
this.globalState.guiTexture.onBeginRenderObservable.add(() => {
this.applyEditorTransformation();
})
this.globalState.onPropertyChangedObservable.add((ev) => {
(ev.object as Control).markAsDirty(false);
})
// Every time the original ADT re-renders, we must also re-render, so that layout information is computed correctly
// also, every time *we* re-render (due to a change in the GUI), we must re-render the original ADT
// to prevent an infite loop, we flip a boolean flag
if (this.globalState.liveGuiTexture) {
this._guiRenderObserver = this.globalState.guiTexture.onBeginRenderObservable.add(() => {
if (this._liveGuiTextureRerender) {
this._nextLiveGuiRender = Date.now() + this._liveGuiRerenderDelay;
}
this._liveGuiTextureRerender = true;
});
this._liveRenderObserver = this.globalState.liveGuiTexture.onEndRenderObservable.add(() => {
// return the GUI to the editor mode
this.globalState.guiTexture?.markAsDirty();
this._liveGuiTextureRerender = false;
});
this._scene.onAfterRenderObservable.add(() => {
if (this._nextLiveGuiRender > 0 && Date.now() > this._nextLiveGuiRender) {
this._nextLiveGuiRender = -1;
this.globalState.liveGuiTexture?.markAsDirty();
}
})
}
this.props.globalState.onErrorMessageDialogRequiredObservable.notifyObservers(
`Welcome to the GUI Editor Alpha. This editor is still a work in progress. Icons are currently temporary. Please submit feedback using the "Give feedback" button in the menu. `
);
this._engine.runRenderLoop(() => {
this._scene.render();
});
this.globalState.onNewSceneObservable.notifyObservers(this.globalState.guiTexture.getScene());
this.globalState.onPropertyGridUpdateRequiredObservable.notifyObservers();
this.props.globalState.onFitToWindowObservable.notifyObservers();
}
// removes all controls from both GUIs, and re-adds the controls from the original to the GUI editor
synchronizeLiveGUI() {
if (this.globalState.liveGuiTexture) {
this.globalState.guiTexture._rootContainer.getDescendants().filter(desc => desc.name !== "Art-Board-Background").forEach(desc => desc.dispose());
this.globalState.liveGuiTexture.rootContainer.getDescendants(true).forEach(desc => {
this.globalState.liveGuiTexture?.removeControl(desc);
this.appendBlock(desc);
})
this.globalState.guiTexture.snippetId = this.globalState.liveGuiTexture.snippetId;
}
}
//Add zoom and pan controls
addControls(scene: Scene) {
const zoomFnScrollWheel = (e: IWheelEvent) => {
const delta = this.zoomWheel(e);
this.zooming(1 + (delta / 1000));
};
const panningFn = () => this.panning();
const startPanning = () => {
this._scene.onPointerObservable.add(panningFn, PointerEventTypes.POINTERMOVE);
this._panning = true;
this._initialPanningOffset = this.getScaledPointerPosition();
this._panAndZoomContainer.getDescendants().forEach(desc => {
desc.metadata.isPointerBlocker = desc.isPointerBlocker;
desc.isPointerBlocker = false;
})
}
const endPanning = () => {
this._panning = false;
this._panAndZoomContainer.getDescendants().forEach(desc => {
if (desc.metadata.isPointerBlocker !== undefined) {
desc.isPointerBlocker = desc.metadata.isPointerBlocker;
delete desc.metadata.isPointerBlocker;
}
})
}
const removeObservers = () => {
scene.onPointerObservable.removeCallback(panningFn);
};
this._rootContainer.current?.addEventListener("wheel", zoomFnScrollWheel);
this._rootContainer.current?.addEventListener("pointerdown", (event) => {
console.log(event);
removeObservers();
if (event.button !== 0 || this._forcePanning) {
startPanning();
} else {
if (this._forceZooming) {
this.zooming(1.0 + (this._altKeyIsPressed ? -this._zoomModeIncrement : this._zoomModeIncrement));
}
endPanning();
// if we click in the scene and we don't hit any controls, deselect all
this._scene.onAfterRenderObservable.addOnce(() => {
if (!this._anyControlClicked) {
this.props.globalState.onSelectionChangedObservable.notifyObservers(null);
}
this._anyControlClicked = false;
});
}
});
this._rootContainer.current?.addEventListener("pointerup", (event) => {
this._panning = false;
removeObservers();