-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathflock.js
8736 lines (7800 loc) · 240 KB
/
flock.js
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
// Flock - Creative coding in 3D
// Dr Tracy Gardner - https://github.com/tracygardner
// Flip Computing Limited - flipcomputing.com
import HavokPhysics from "@babylonjs/havok";
import * as BABYLON from "@babylonjs/core";
import * as BABYLON_GUI from "@babylonjs/gui";
import "@babylonjs/loaders";
import { GradientMaterial } from "@babylonjs/materials";
import * as BABYLON_EXPORT from "@babylonjs/serializers";
import { FlowGraphLog10Block, SetMaterialIDBlock } from "babylonjs";
import "@fontsource/asap";
import "@fontsource/asap/500.css";
import "@fontsource/asap/600.css";
import earcut from "earcut";
import { characterNames } from "./config";
// Helper functions to make flock.BABYLON js easier to use in Flock
console.log("Flock helpers loading");
export const flock = {
console: console,
modelPath: "./models/",
soundPath: "./sounds/",
imagePath: "./images/",
texturePath: "./textures/",
engine: null,
engineReady: false,
characterNames: characterNames,
alert: alert,
BABYLON: BABYLON,
GradientMaterial: GradientMaterial,
scene: null,
highlighter: null,
glowLayer: null,
mainLight: null,
hk: null,
havokInstance: null,
ground: null,
sky: null,
GUI: null,
EXPORT: null,
controlsTexture: null,
canvas: {
pressedKeys: null,
},
abortController: null,
document: document,
disposed: null,
events: {},
modelCache: {},
globalSounds: [],
originalModelTransformations: {},
modelsBeingLoaded: {},
geometryCache: {},
materialCache: {},
flockNotReady: true,
lastFrameTime: 0,
savedCamera: null,
async runCode(code) {
let iframe = document.getElementById("flock-iframe");
try {
// Step 1: Dispose old scene if iframe exists
if (iframe) {
await iframe.contentWindow?.flock?.disposeOldScene();
} else {
// Step 2: Create a new iframe if not found
iframe = document.createElement("iframe");
iframe.id = "flock-iframe";
iframe.style.display = "none";
document.body.appendChild(iframe);
}
// Step 3: Wait for iframe to load
await new Promise((resolve, reject) => {
iframe.onload = () => resolve();
iframe.onerror = () =>
reject(new Error("Failed to load iframe"));
iframe.src = "about:blank";
});
// Step 4: Access iframe window and set up flock
const iframeWindow = iframe.contentWindow;
if (!iframeWindow) throw new Error("Iframe window is unavailable");
iframeWindow.flock = flock;
await iframeWindow.flock.initializeNewScene();
// Step 6: Create sandboxed function
const sandboxFunction = new iframeWindow.Function(`
"use strict";
const {
initialize,
createEngine,
createScene,
playAnimation,
playSound,
stopAllSounds,
playNotes,
setBPM,
createInstrument,
switchAnimation,
highlight,
glow,
createCharacter,
createObject,
createParticleEffect,
create3DText,
createModel,
createBox,
createSphere,
createCylinder,
createCapsule,
createPlane,
cloneMesh,
parentChild,
setParent,
mergeMeshes,
subtractMeshes,
intersectMeshes,
createHull,
hold,
drop,
makeFollow,
stopFollow,
removeParent,
createGround,
createMap,
createCustomMap,
setSky,
lightIntensity,
buttonControls,
getCamera,
cameraControl,
setCameraBackground,
setXRMode,
applyForce,
moveByVector,
glideTo,
createAnimation,
animateFrom,
playAnimationGroup,
pauseAnimationGroup,
stopAnimationGroup,
startParticleSystem,
stopParticleSystem,
resetParticleSystem,
animateKeyFrames,
setPivotPoint,
rotate,
lookAt,
moveTo,
rotateTo,
rotateCamera,
rotateAnim,
animateProperty,
positionAt,
distanceTo,
wait,
safeLoop,
waitUntil,
show,
hide,
clearEffects,
stopAnimations,
tint,
setAlpha,
dispose,
setFog,
keyPressed,
isTouchingSurface,
seededRandom,
randomColour,
scaleMesh,
resizeMesh,
changeColor,
changeColorMesh,
changeMaterial,
setMaterial,
createMaterial,
textMaterial,
createDecal,
placeDecal,
moveForward,
moveSideways,
strafe,
attachCamera,
canvasControls,
setPhysics,
setPhysicsShape,
checkMeshesTouching,
say,
onTrigger,
onEvent,
broadcastEvent,
Mesh,
start,
forever,
whenKeyEvent,
randomInteger,
printText,
UIText,
UIButton,
onIntersect,
getProperty,
exportMesh,
abortSceneExecution,
ensureUniqueGeometry,
} = flock;
${code}
`);
try {
sandboxFunction();
} catch (sandboxError) {
throw new Error(
`Sandbox execution failed: ${sandboxError.message}`,
);
}
} catch (error) {
// General Error Handling
console.error("Error during scene setup or code execution:", error);
// Clean up resources and stop execution
try {
flock.audioContext.close();
flock.engine.stopRenderLoop();
flock.removeEventListeners();
} catch (cleanupError) {
console.error("Error during cleanup:", cleanupError);
}
}
},
async initialize() {
flock.BABYLON = BABYLON;
flock.GUI = BABYLON_GUI;
flock.EXPORT = BABYLON_EXPORT;
flock.document = document;
flock.canvas = flock.document.getElementById("renderCanvas");
flock.scene = null;
flock.havokInstance = null;
flock.ground = null;
flock.sky = null;
flock.engineReady = false;
flock.meshLoaders = new Map();
flock.audioContext = flock.getAudioContext();
const gridKeyPressObservable = new flock.BABYLON.Observable();
const gridKeyReleaseObservable = new flock.BABYLON.Observable();
flock.gridKeyPressObservable = gridKeyPressObservable;
flock.gridKeyReleaseObservable = gridKeyReleaseObservable;
flock.canvas.pressedButtons = new Set();
flock.canvas.pressedKeys = new Set();
const displayScale = (window.devicePixelRatio || 1) * 0.75; // Get the device pixel ratio, default to 1 if not available
flock.displayScale = displayScale;
flock.BABYLON.Database.IDBStorageEnabled = true;
flock.BABYLON.Engine.CollisionsEpsilon = 0.00005;
flock.havokInstance = await HavokPhysics();
await flock.document.fonts.ready; // Wait for all fonts to be loaded
flock.abortController = new AbortController();
try {
await flock.BABYLON.InitializeCSG2Async();
} catch (error) {
console.error("Error initializing CSG2:", error);
}
flock.canvas.addEventListener(
"touchend",
(event) => {
//flock.printText(`Canvas: Touch End ${event.touches.length}`, 5);
//logTouchDetails(event);
if (event.touches.length === 0) {
const input =
flock.scene.activeCamera.inputs?.attached?.pointers;
// Add null check for input itself
if (
input &&
(input._pointA !== null ||
input._pointB !== null ||
input._isMultiTouch === true)
) {
//flock.printText("Stuck state detected!");
flock.scene.activeCamera.detachControl(flock.canvas);
setTimeout(() => {
flock.scene.activeCamera.attachControl(
flock.canvas,
true,
);
//console.log("Camera inputs reset!");
}, 100); // Small delay
}
}
},
{ passive: false },
);
flock.canvas.addEventListener("keydown", function (event) {
flock.canvas.currentKeyPressed = event.key;
flock.canvas.pressedKeys.add(event.key);
});
flock.canvas.addEventListener("keyup", function (event) {
flock.canvas.pressedKeys.delete(event.key);
});
flock.canvas.addEventListener("blur", () => {
// Clear all pressed keys when window loses focus
flock.canvas.pressedKeys.clear();
flock.canvas.pressedButtons.clear();
});
flock.engineReady = true;
},
createEngine() {
flock.engine?.dispose();
flock.engine = null;
flock.engine = new flock.BABYLON.Engine(flock.canvas, true, {
stencil: true,
deterministicLockstep: true,
audioEngine: true,
});
flock.engine.enableOfflineSupport = false;
flock.engine.setHardwareScalingLevel(1 / window.devicePixelRatio);
},
async disposeOldScene() {
console.log("Disposing old scene");
flock.flockNotReady = true;
if (flock.scene) {
flock.engine.stopRenderLoop();
flock.scene.meshes.forEach((mesh) => {
if (mesh.actionManager) {
mesh.actionManager.dispose(); // Dispose the action manager to remove all actions
}
});
flock.scene.activeCamera?.inputs?.clear();
flock.events = null;
flock.modelCache = null;
flock.globalSounds = [];
flock.modelsBeingLoaded = null;
flock.originalModelTransformations = null;
flock.geometryCache = null;
flock.materialCache = null;
flock.ground = null;
flock.sky = null;
// Abort any ongoing operations if applicable
if (flock.abortController) {
flock.abortController.abort(); // Abort any pending operations
flock.scene.stopAllAnimations();
// Wait briefly to ensure all asynchronous tasks complete
await new Promise((resolve) => setTimeout(resolve, 50));
}
// Remove event listeners before disposing of the scene
flock.removeEventListeners();
flock.controlsTexture?.dispose();
flock.controlsTexture = null;
flock.gridKeyPressObservable?.clear();
flock.gridKeyReleaseObservable?.clear();
flock.highlighter?.dispose();
flock.highlighter = null;
flock.glowLayer?.dispose();
flock.glowLayer = null;
flock.mainLight?.dispose();
flock.mainLight = null;
// Dispose of the scene directly
flock.scene.activeCamera?.inputs?.clear();
flock.scene.dispose();
flock.scene = null;
flock.hk?.dispose();
flock.hk = null;
if (flock.audioContext?.state !== "closed") {
flock.audioContext?.close();
}
flock.audioContext = null;
}
},
async initializeNewScene() {
// Stop existing render loop or create a new engine
flock.engine ? flock.engine.stopRenderLoop() : flock.createEngine();
// Reset scene-wide state
flock.events = {};
flock.modelCache = {};
flock.globalSounds = [];
flock.modelsBeingLoaded = {};
flock.originalModelTransformations = {};
flock.geometryCache = {};
flock.materialCache = {};
flock.disposed = false;
// Create the new scene
flock.scene = new flock.BABYLON.Scene(flock.engine);
// Abort controller for clean-up
flock.abortController = new AbortController();
// Start the render loop
flock.engine.runRenderLoop(() => {
flock.scene.render();
});
// Enable physics
flock.hk = new flock.BABYLON.HavokPlugin(true, flock.havokInstance);
flock.scene.enablePhysics(
new flock.BABYLON.Vector3(0, -9.81, 0),
flock.hk,
);
// Add highlight layer
flock.highlighter = new flock.BABYLON.HighlightLayer(
"highlighter",
flock.scene,
);
// Set up a new camera
const camera = new flock.BABYLON.FreeCamera(
"camera",
new flock.BABYLON.Vector3(0, 3, -10),
flock.scene,
);
flock.savedCamera = camera;
camera.minZ = 0;
camera.setTarget(flock.BABYLON.Vector3.Zero());
camera.rotation.x = flock.BABYLON.Tools.ToRadians(0);
camera.angularSensibilityX = 2000;
camera.angularSensibilityY = 2000;
camera.speed = 0.25;
flock.scene.activeCamera = camera;
camera.attachControl(flock.canvas, false);
// Set up lighting
const hemisphericLight = new flock.BABYLON.HemisphericLight(
"hemisphericLight",
new flock.BABYLON.Vector3(1, 1, 0),
flock.scene,
);
hemisphericLight.intensity = 1.0;
hemisphericLight.diffuse = new flock.BABYLON.Color3(1, 1, 1);
hemisphericLight.groundColor = new flock.BABYLON.Color3(0.5, 0.5, 0.5);
flock.mainLight = hemisphericLight;
// Enable collisions
flock.scene.collisionsEnabled = true;
const isTouchScreen =
"ontouchstart" in window ||
navigator.maxTouchPoints > 0 ||
window.matchMedia("(pointer: coarse)").matches;
if (isTouchScreen) {
flock.controlsTexture =
flock.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
flock.createArrowControls("white");
flock.createButtonControls("white");
}
// Create the UI
flock.advancedTexture =
flock.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
// Stack panel for text
flock.stackPanel = new flock.GUI.StackPanel();
flock.stackPanel.width = "100%"; // Fixed width for the panel
flock.stackPanel.horizontalAlignment =
flock.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; // Align to the left
flock.stackPanel.verticalAlignment =
flock.GUI.Control.VERTICAL_ALIGNMENT_TOP; // Align to the top
flock.stackPanel.isVertical = true;
flock.advancedTexture.addControl(flock.stackPanel);
// Observable for audio updates
flock.globalStartTime = flock.getAudioContext().currentTime;
flock.scene.onBeforeRenderObservable.add(() => {
const context = flock.getAudioContext();
flock.updateListenerPositionAndOrientation(
context,
flock.scene.activeCamera,
);
});
// Mark scene as ready
flock.flockNotReady = false;
// Reset XR helper
flock.xrHelper = null;
},
randomInteger(a, b) {
if (a > b) {
// Swap a and b to ensure a is smaller.
var c = a;
a = b;
b = c;
}
return Math.floor(Math.random() * (b - a + 1) + a);
},
printText(text, duration = 30, color = "white") {
if (!flock.scene || !flock.stackPanel) return;
console.log(text);
try {
// Create a rectangle container for the text
const bg = new flock.GUI.Rectangle("textBackground");
bg.background = "rgba(255, 255, 255, 0.5)";
bg.adaptWidthToChildren = true; // Adjust width to fit the text
bg.adaptHeightToChildren = true; // Adjust height to fit the text
bg.cornerRadius = 2; // Match the original corner rounding
bg.thickness = 0; // No border
bg.horizontalAlignment =
flock.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; // Align the container to the left
bg.verticalAlignment = flock.GUI.Control.VERTICAL_ALIGNMENT_TOP; // Align to the top
bg.left = "5px"; // Preserve original spacing
bg.top = "5px";
// Create the text block inside the rectangle
const textBlock = new flock.GUI.TextBlock("textBlock", text);
textBlock.color = color;
textBlock.fontSize = "20"; // Match the original font size
textBlock.fontFamily = "Asap"; // Retain original font
textBlock.height = "25px"; // Match the original height
textBlock.paddingLeft = "10px"; // Padding for left alignment
textBlock.paddingRight = "10px";
textBlock.paddingTop = "2px";
textBlock.paddingBottom = "2px";
textBlock.textHorizontalAlignment =
flock.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT; // Left align the text
textBlock.textVerticalAlignment =
flock.GUI.Control.VERTICAL_ALIGNMENT_CENTER; // Center vertically within the rectangle
textBlock.textWrapping = flock.GUI.TextWrapping.WordWrap; // Enable word wrap
textBlock.resizeToFit = true; // Allow resizing
textBlock.forceResizeWidth = true;
// Add the text block to the rectangle
bg.addControl(textBlock);
// Add the rectangle to the stack panel
flock.stackPanel.addControl(bg);
// Remove the text after the specified duration
const timeoutId = setTimeout(() => {
if (flock.scene) {
// Ensure the scene is still valid
flock.stackPanel.removeControl(bg);
}
}, duration * 1000);
// Handle cleanup in case of scene disposal
flock.abortController.signal.addEventListener("abort", () => {
clearTimeout(timeoutId);
});
} catch (error) {
console.warn("Unable to print text:", error);
}
},
async initializeXR(mode) {
if (flock.xrHelper) return; // Avoid reinitializing
if (mode === "VR") {
flock.xrHelper = await flock.scene.createDefaultXRExperienceAsync();
} else if (mode === "AR") {
flock.xrHelper = await flock.scene.createDefaultXRExperienceAsync({
uiOptions: { sessionMode: "immersive-ar" },
});
} else if (mode === "MAGIC_WINDOW") {
let camera = flock.scene.activeCamera;
if (!camera.inputs.attached.deviceOrientation) {
camera.inputs.addDeviceOrientation();
}
}
// Create a UI plane for the wrist
flock.uiPlane = flock.BABYLON.MeshBuilder.CreatePlane(
"uiPlane",
{ size: 0.4 },
flock.scene,
); // Smaller size for wrist UI
flock.uiPlane.isVisible = false; // Start hidden
const planeMaterial = new flock.BABYLON.StandardMaterial(
"uiPlaneMaterial",
flock.scene,
);
planeMaterial.disableDepthWrite = true;
flock.uiPlane.material = planeMaterial;
flock.meshTexture = flock.GUI.AdvancedDynamicTexture.CreateForMesh(
flock.uiPlane,
);
// Ensure the UI plane follows the wrist (using a controller or camera offset)
flock.xrHelper.input.onControllerAddedObservable.add((controller) => {
if (controller.inputSource.handedness === "left") {
// Attach the UI plane to the left-hand controller
flock.uiPlane.parent = controller.grip || controller.pointer;
// Position the UI plane to simulate a watch
flock.uiPlane.position.set(0.1, -0.05, 0); // Slightly to the side, closer to the wrist
flock.uiPlane.rotation.set(Math.PI / 2, 0, 0); // Rotate to face the user
}
});
// Handle XR state changes
flock.xrHelper.baseExperience.onStateChangedObservable.add((state) => {
if (state === flock.BABYLON.WebXRState.ENTERING_XR) {
flock.advancedTexture.removeControl(flock.stackPanel);
flock.meshTexture.addControl(flock.stackPanel);
flock.uiPlane.isVisible = true;
// Update alignment for wrist UI
flock.stackPanel.horizontalAlignment =
flock.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
flock.stackPanel.verticalAlignment =
flock.GUI.Control.VERTICAL_ALIGNMENT_TOP;
flock.advancedTexture.isVisible = false; // Hide fullscreen UI
} else if (state === flock.BABYLON.WebXRState.EXITING_XR) {
flock.meshTexture.removeControl(flock.stackPanel);
flock.advancedTexture.addControl(flock.stackPanel);
flock.uiPlane.isVisible = false;
// Restore alignment for non-XR
flock.stackPanel.width = "100%";
flock.stackPanel.horizontalAlignment =
flock.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
flock.stackPanel.verticalAlignment =
flock.GUI.Control.VERTICAL_ALIGNMENT_TOP;
flock.advancedTexture.rootContainer.isVisible = true;
}
});
},
async resetScene() {
// Dispose of the old scene
await flock.disposeOldScene();
// Initialize the new scene
await flock.initializeNewScene();
},
UIText(text, x, y, fontSize, color, duration, id = null) {
// Ensure flock.scene and flock.GUI are initialized
if (!flock.scene || !flock.GUI) {
throw new Error("flock.scene or flock.GUI is not initialized.");
}
// Ensure UITexture and controls exist
flock.scene.UITexture ??=
flock.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
flock.scene.UITexture.controls ??= [];
flock.abortController ??= new AbortController();
// Generate a unique ID if none is provided
const textBlockId =
id ||
`textBlock_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
// Get canvas dimensions
const maxWidth = flock.scene.getEngine().getRenderWidth();
const maxHeight = flock.scene.getEngine().getRenderHeight();
// Adjust negative coordinates
const adjustedX = x < 0 ? maxWidth + x : x;
const adjustedY = y < 0 ? maxHeight + y : y;
// Check if a TextBlock with the given ID already exists
let textBlock = flock.scene.UITexture.getControlByName(textBlockId);
if (textBlock) {
// Reuse the existing TextBlock and update its properties
textBlock.text = text;
textBlock.color = color || "white"; // Default color
textBlock.fontSize = fontSize || 24; // Default font size
textBlock.left = adjustedX;
textBlock.top = adjustedY;
textBlock.isVisible = true; // Ensure the text block is visible
} else {
textBlock = new flock.GUI.TextBlock(textBlockId); // Assign the ID as the name
flock.scene.UITexture.addControl(textBlock);
flock.scene.UITexture.controls.push(textBlock);
// Set initial text properties
textBlock.text = text;
textBlock.color = color || "white"; // Default color
textBlock.fontSize = fontSize || 24; // Default font size
textBlock.textHorizontalAlignment =
flock.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
textBlock.textVerticalAlignment =
flock.GUI.Control.VERTICAL_ALIGNMENT_TOP;
textBlock.left = adjustedX;
textBlock.top = adjustedY;
}
// Ensure the text disappears after the duration
if (duration > 0) {
setTimeout(() => {
if (flock.scene.UITexture.controls.includes(textBlock)) {
textBlock.isVisible = false; // Hide the text block
} else {
console.warn(
`TextBlock "${textBlockId}" not found in controls array.`,
);
}
}, duration * 1000);
}
// Return the ID for future reference
return textBlockId;
},
UIButton(
text,
x,
y,
width,
textSize,
textColor,
backgroundColor,
buttonId,
) {
// Ensure flock.scene and flock.GUI are initialized
if (!flock.scene || !flock.GUI) {
throw new Error("flock.scene or flock.GUI is not initialized.");
}
// Ensure UITexture exists
flock.scene.UITexture ??=
flock.GUI.AdvancedDynamicTexture.CreateFullscreenUI("UI");
// Validate buttonId
if (!buttonId || typeof buttonId !== "string") {
throw new Error("buttonId must be a valid non-empty string.");
}
// Create a Babylon.js GUI button
const button = flock.GUI.Button.CreateSimpleButton(buttonId, text);
// Preset button sizes for consistency
const buttonSizes = {
SMALL: { width: "100px", height: "40px" },
MEDIUM: { width: "150px", height: "50px" },
LARGE: { width: "200px", height: "60px" },
};
// Validate and apply the selected size
if (typeof width !== "string") {
throw new Error(
"Invalid button size. Please provide a valid size: 'SMALL', 'MEDIUM', or 'LARGE'.",
);
}
const size = buttonSizes[width.toUpperCase()] || buttonSizes["SMALL"];
button.width = size.width;
button.height = size.height;
// Configure text block settings
if (button.textBlock) {
button.textBlock.textWrapping = true;
button.textBlock.resizeToFit = true;
button.textBlock.fontSize = textSize ? `${textSize}px` : "16px"; // Default font size
} else {
console.warn(
"No textBlock found for the button. Text-related settings will not be applied.",
);
}
// Set button text color and background color
button.color = textColor || "white";
button.background = backgroundColor || "blue";
// Validate x and y positions
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("x and y must be numbers.");
}
// Set button alignment
button.left = `${x}px`;
button.top = `${y}px`;
button.horizontalAlignment =
x < 0
? flock.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT
: flock.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT;
button.verticalAlignment =
y < 0
? flock.GUI.Control.VERTICAL_ALIGNMENT_BOTTOM
: flock.GUI.Control.VERTICAL_ALIGNMENT_TOP;
// Add the button to the UI
flock.scene.UITexture.addControl(button);
// Return the buttonId for future reference
return buttonId;
},
removeEventListeners() {
flock.scene.eventListeners?.forEach(({ event, handler }) => {
flock.document.removeEventListener(event, handler);
});
if (flock.scene && flock.scene.eventListeners)
flock.scene.eventListeners.length = 0; // Clear the array
},
async *modelReadyGenerator(
meshId,
maxAttempts = 100,
initialInterval = 100,
maxInterval = 2000,
) {
let attempt = 1;
let interval = initialInterval;
const { signal } = flock.abortController;
while (attempt <= maxAttempts) {
if (flock.disposed || !flock.scene || flock.scene.isDisposed) {
console.warn(
"Scene has been disposed or generator invalidated.",
);
return;
}
if (flock.scene) {
if (meshId === "__active_camera__") {
yield flock.scene.activeCamera;
return;
} else {
const mesh = flock.scene.getMeshByName(meshId);
if (mesh) {
yield mesh;
return;
}
}
}
try {
await new Promise((resolve, reject) => {
const timeoutId = setTimeout(resolve, interval);
// Reject the promise if the abort signal is triggered
const onAbort = () => {
clearTimeout(timeoutId);
reject(new Error("Wait aborted"));
};
signal.addEventListener("abort", onAbort, { once: true });
// Ensure the event listener is cleaned up after resolving
signal.addEventListener(
"abort",
() => signal.removeEventListener("abort", onAbort),
{ once: true },
);
});
} catch (error) {
console.log("Timeout aborted:", error);
// Properly exit if the wait was aborted to prevent further processing
return;
}
interval = Math.min(interval * 2, maxInterval);
attempt++;
//console.log(`Attempt ${attempt}: Retrying in ${interval}ms...`);
}
console.warn(
`Mesh with ID '${meshId}' not found after ${maxAttempts} attempts.`,
);
},
whenModelReady(targetId, callback) {
// Check if the target (mesh or GUI button) is immediately available
if (flock.scene) {
let target = flock.scene.getMeshByName(targetId);
if (!target && flock.scene.UITexture) {
target = flock.scene.UITexture.getControlByName(targetId);
}
// Check animation groups if still not found
if (!target) {
target = flock.scene.animationGroups.find(
(group) => group.name === targetId,
);
}
// Check particle systems if still not found
if (!target) {
target = flock.scene.particleSystems.find(
(system) => system.name === targetId,
);
}
if (target) {
if (flock.abortController.signal.aborted) {
return; // If already aborted, stop here
}
// Target is available immediately, invoke the callback synchronously
callback(target);
return; // Return immediately, no Promise needed
}
}
// If the target is not immediately available, fall back to the generator and return a Promise
return (async () => {
const generator = flock.modelReadyGenerator(targetId);
try {
for await (const target of generator) {
if (flock.abortController.signal.aborted) {
console.log(`Aborted waiting for target: ${targetId}`);
return; // Exit the loop if the operation was aborted
}
await callback(target);
}
} catch (err) {
if (flock.abortController.signal.aborted) {
console.log(`Operation was aborted: ${targetId}`);
} else {
console.error(`Error in whenModelReady: ${err}`);
}
}
})();
},
stopAnimationsTargetingMesh(scene, mesh) {
scene.animationGroups.forEach(function (animationGroup) {
let targets = animationGroup.targetedAnimations.map(
function (targetedAnimation) {
return targetedAnimation.target;
},
);
if (
targets.includes(mesh) ||
flock.animationGroupTargetsDescendant(animationGroup, mesh)
) {
animationGroup.stop();
}
});
},
animationGroupTargetsDescendant(animationGroup, parentMesh) {
let descendants = parentMesh.getDescendants();
for (let targetedAnimation of animationGroup.targetedAnimations) {
let target = targetedAnimation.target;
if (descendants.includes(target)) {
return true;
}
}
return false;
},
switchToAnimation(
scene,
mesh,
animationName,
loop = true,
restart = false,
) {
const newAnimationName = animationName;
if (!mesh) {
console.error(`Mesh ${mesh.name} not found.`);
return null;
}
if (flock.flockNotReady) return null;
let targetAnimationGroup = flock.scene?.animationGroups?.find(
(group) =>
group.name === newAnimationName &&
flock.animationGroupTargetsDescendant(group, mesh),
);
if (!targetAnimationGroup) {
console.error(`Animation "${newAnimationName}" not found.`);
return null;
}
if (!mesh.animationGroups) {
mesh.animationGroups = [];
flock.stopAnimationsTargetingMesh(scene, mesh);
}
if (
mesh.animationGroups[0] &&
mesh.animationGroups[0].name !== newAnimationName
) {
flock.stopAnimationsTargetingMesh(scene, mesh);
mesh.animationGroups[0].stop();
mesh.animationGroups = [];
}