forked from flipcomputing/flock
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathflock.js
More file actions
2325 lines (2108 loc) · 59.6 KB
/
flock.js
File metadata and controls
2325 lines (2108 loc) · 59.6 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
// 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";
import { flockCSG, setFlockReference as setFlockCSG } from "./api/csg";
import {
flockAnimate,
setFlockReference as setFlockAnimate,
} from "./api/animate";
import { flockSound, setFlockReference as setFlockSound } from "./api/sound";
import { flockUI, setFlockReference as setFlockUI } from "./api/ui";
import {
flockMovement,
setFlockReference as setFlockMovement,
} from "./api/movement";
import { flockModels, setFlockReference as setFlockModels } from "./api/models";
import { flockShapes, setFlockReference as setFlockShapes } from "./api/shapes";
import {
flockTransform,
setFlockReference as setFlockTransform,
} from "./api/transform";
import {
flockMaterial,
setFlockReference as setFlockMaterial,
} from "./api/material";
import {
flockEffects,
setFlockReference as setFlockEffects,
} from "./api/effects";
import {
flockPhysics,
setFlockReference as setFlockPhysics,
} from "./api/physics";
import { flockScene, setFlockReference as setFlockScene } from "./api/scene";
import { flockMesh, setFlockReference as setFlockMesh } from "./api/mesh";
import { flockCamera, setFlockReference as setFlockCamera } from "./api/camera";
// Helper functions to make flock.BABYLON js easier to use in Flock
console.log("Flock helpers loading");
export const flock = {
callbackMode: true,
separateAnimations: false,
memoryDebug: false,
maxMeshes: 5000,
console: console,
modelPath: "./models/",
soundPath: "./sounds/",
imagePath: "./images/",
texturePath: "./textures/",
engine: null,
engineReady: false,
modelReadyPromises: new Map(),
pendingMeshCreations: 0,
pendingTriggers: new Map(),
_animationFileCache: {},
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,
...flockCSG,
...flockAnimate,
...flockSound,
...flockUI,
...flockMovement,
...flockModels,
...flockShapes,
...flockTransform,
...flockMaterial,
...flockEffects,
...flockPhysics,
...flockScene,
...flockMesh,
...flockCamera,
// Enhanced error reporting with block context
createEnhancedError(error, code) {
const lines = code.split("\n");
const errorContext = {
message: error.message,
stack: error.stack,
codeSnippet: null,
suggestion: null,
};
// Try to extract line number from error
const lineMatch = error.stack?.match(/at .*:(\d+):\d+/);
if (lineMatch) {
const lineNum = parseInt(lineMatch[1]) - 1;
if (lineNum >= 0 && lineNum < lines.length) {
const start = Math.max(0, lineNum - 2);
const end = Math.min(lines.length, lineNum + 3);
errorContext.codeSnippet = lines
.slice(start, end)
.map((line, idx) => {
const actualLine = start + idx;
const marker = actualLine === lineNum ? ">>> " : " ";
return `${marker}${actualLine + 1}: ${line}`;
})
.join("\n");
}
}
// Add common error suggestions
if (error.message.includes("is not defined")) {
errorContext.suggestion =
"Check if the variable or function name is spelled correctly and has been declared.";
} else if (error.message.includes("Cannot read property")) {
errorContext.suggestion =
"Check if the object exists before accessing its properties.";
}
return errorContext;
},
createVector3(x, y, z) {
return new flock.BABYLON.Vector3(x, y, z);
},
maxMeshesReached() {
const scene = flock?.scene;
if (!scene || typeof flock.maxMeshes !== "number") return false;
const meshCount = scene.meshes.length;
const max = flock.maxMeshes;
if (meshCount >= max) {
flock.printText?.(
`⚠️ Limit reached: You can only have ${max} meshes in your world.`,
30,
"#ff0000",
);
return true;
}
return false;
},
getTotalSceneVertices() {
return flock.scene.meshes.reduce((total, mesh) => {
return total + mesh.getTotalVertices();
}, 0);
},
checkMemoryUsage() {
if (!performance.memory) {
return; // Not available in all browsers
}
const used = performance.memory.usedJSHeapSize / 1024 / 1024;
const total = performance.memory.totalJSHeapSize / 1024 / 1024;
const limit = performance.memory.jsHeapSizeLimit / 1024 / 1024;
// Log to console (you might want to display in UI instead)
console.log(
`Memory: ${used.toFixed(1)}MB used / ${total.toFixed(1)}MB allocated / ${limit.toFixed(1)}MB limit`,
);
// Warn if approaching limits
const usagePercent = (used / limit) * 100;
if (usagePercent > 80) {
console.warn(
`High memory usage: ${usagePercent.toFixed(1)}% of limit`,
);
// Maybe show user warning in your UI
this.printText(
`Warning: High memory usage (${usagePercent.toFixed(1)}%)`,
3,
"#ff9900",
);
}
// Count Babylon.js objects for more specific monitoring
if (flock.scene) {
const counts = {
meshes: flock.scene.meshes.length,
geometries: Object.keys(flock.geometryCache).length,
vertices: flock.getTotalSceneVertices(),
materials: flock.scene.materials.length,
cachedMaterials: Object.keys(flock.materialCache).length,
textures: flock.scene.textures.length,
animationGroups: flock.scene.animationGroups.length,
};
console.log("Scene objects:", counts);
}
},
startMemoryMonitoring() {
// Clear any existing monitoring
if (this.memoryMonitorInterval) {
clearInterval(flock.memoryMonitorInterval);
}
// Get the abort signal
const signal = flock.abortController?.signal;
if (signal?.aborted) {
return; // Don't start if already aborted
}
// Monitor every 5 seconds
flock.memoryMonitorInterval = setInterval(() => {
// Check if aborted before each check
if (signal?.aborted) {
clearInterval(flock.memoryMonitorInterval);
this.memoryMonitorInterval = null;
return;
}
flock.checkMemoryUsage();
}, 5000);
// Clean up when aborted
signal?.addEventListener("abort", () => {
if (flock.memoryMonitorInterval) {
clearInterval(flock.memoryMonitorInterval);
flock.memoryMonitorInterval = null;
}
});
},
validateCode(code) {
if (typeof code !== "string") {
throw new Error("Code must be a string");
}
// Length check (reasonable)
if (code.length > 100000) {
throw new Error("Code too long (max 100KB)");
}
// Basic syntax check
try {
new Function(code); // Just check if it parses
} catch (e) {
throw new Error(`Syntax error: ${e.message}`);
}
// Optional: Warn about patterns (don't block)
const warnings = [];
if (/eval\s*\(/.test(code)) {
warnings.push(
"Warning: eval() detected - this won't work in the sandbox",
);
}
if (warnings.length > 0) {
console.warn(warnings.join("\n"));
}
return true;
},
async runCode2(code) {
let iframe = document.getElementById("flock-iframe");
try {
// Validate code first
this.validateCode(code);
// Dispose old scene if iframe exists
if (iframe) {
try {
iframe.contentWindow.flock?.disposeOldScene();
delete iframe.contentWindow.flock;
} catch (error) {
console.warn("Error disposing old scene in iframe:", error);
}
} else {
// Create a new iframe if not found
iframe = document.createElement("iframe");
iframe.id = "flock-iframe";
iframe.style.display = "none";
document.body.appendChild(iframe);
}
// Wait for iframe to load with stricter CSP
await new Promise((resolve, reject) => {
iframe.onload = () => resolve();
iframe.onerror = () =>
reject(new Error("Failed to load iframe"));
iframe.srcdoc = `
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-eval' 'unsafe-inline';">
</head>
<body></body>
</html>`;
});
const iframeWindow = iframe.contentWindow;
if (!iframeWindow) throw new Error("Iframe window is unavailable");
// Define API methods list once to avoid duplication
const apiMethods = [
// Core
"initialize",
"createEngine",
"createScene",
// Animation & Movement
"playAnimation",
"switchAnimation",
"glideTo",
"createAnimation",
"animateFrom",
"playAnimationGroup",
"pauseAnimationGroup",
"stopAnimationGroup",
"animateKeyFrames",
"setPivotPoint",
"rotate",
"lookAt",
"moveTo",
"rotateTo",
"rotateCamera",
"rotateAnim",
"animateProperty",
"positionAt",
"moveForward",
"moveSideways",
"strafe",
// Audio
"playSound",
"stopAllSounds",
"playNotes",
"setBPM",
"createInstrument",
"speak",
// Effects
"highlight",
"glow",
"tint",
"setAlpha",
"clearEffects",
"stopAnimations",
// 3D Objects
"createCharacter",
"createObject",
"createParticleEffect",
"create3DText",
"createModel",
"createBox",
"createSphere",
"createCylinder",
"createCapsule",
"createPlane",
// Mesh Operations
"cloneMesh",
"parentChild",
"setParent",
"mergeMeshes",
"subtractMeshes",
"intersectMeshes",
"createHull",
"hold",
"drop",
"makeFollow",
"stopFollow",
"removeParent",
// Environment
"createGround",
"createMap",
"createCustomMap",
"setSky",
"lightIntensity",
"setFog",
// Camera & Controls
"buttonControls",
"getCamera",
"cameraControl",
"setCameraBackground",
"setXRMode",
"attachCamera",
"canvasControls",
// Physics
"applyForce",
"moveByVector",
"setPhysics",
"setPhysicsShape",
"checkMeshesTouching",
// Particles
"startParticleSystem",
"stopParticleSystem",
"resetParticleSystem",
// Utilities
"distanceTo",
"wait",
"safeLoop",
"waitUntil",
"show",
"hide",
"dispose",
"keyPressed",
"isTouchingSurface",
"seededRandom",
"randomColour",
"scale",
"resize",
// Materials & Colors
"changeColor",
"changeColorMesh",
"changeMaterial",
"setMaterial",
"createMaterial",
"textMaterial",
// Events & Interaction
"say",
"onTrigger",
"onEvent",
"broadcastEvent",
"start",
"forever",
"whenKeyEvent",
"onIntersect",
// UI
"printText",
"UIText",
"UIButton",
"UIInput",
"UISlider",
// Utilities & Data
"randomInteger",
"getProperty",
"exportMesh",
"abortSceneExecution",
"ensureUniqueGeometry",
"createVector3",
"disposeOldScene",
];
// Create API object dynamically
const flockAPI = {};
apiMethods.forEach((method) => {
if (typeof this[method] === "function") {
flockAPI[method] = (...args) => this[method](...args);
}
});
// Initialize new scene in iframe context
await this.initializeNewScene();
if (flock.memoryDebug) this.startMemoryMonitoring();
// Create and execute sandboxed function more directly
const sandboxFunction = new iframeWindow.Function(
"flock",
`
"use strict";
// Destructure the API for clean user access
const {
${apiMethods.join(",\n ")}
} = flock;
// Add some safety measures
const setTimeout = undefined;
const setInterval = undefined;
const clearTimeout = undefined;
const clearInterval = undefined;
// Wrap user code in async function with better error handling
return (async function() {
try {
${code}
} catch (error) {
// Enhanced error reporting with line numbers
const stack = error.stack || '';
const match = stack.match(/<anonymous>:(\\d+):(\\d+)/);
const lineNumber = match ? parseInt(match[1]) - 20 : 'unknown'; // Adjust for wrapper code
console.error(\`User code error at line \${lineNumber}:\`, error.message);
throw new Error(\`Line \${lineNumber}: \${error.message}\`);
}
})();
`,
);
// Execute with better error context
try {
await sandboxFunction(flockAPI);
} catch (sandboxError) {
throw new Error(
`Code execution failed: ${sandboxError.message}`,
);
}
// Focus render canvas
document.getElementById("renderCanvas")?.focus();
} catch (error) {
// Enhanced error reporting
const enhancedError = this.createEnhancedError(error, code);
console.error("Enhanced error details:", enhancedError);
// Show user-friendly error
this.printText(`Error: ${error.message}`, 5, "#ff0000");
// Clean up on error
try {
this.audioContext?.close();
this.engine?.stopRenderLoop();
this.removeEventListeners();
} catch (cleanupError) {
console.error("Error during cleanup:", cleanupError);
}
throw error;
}
},
async runCode(code) {
let iframe = document.getElementById("flock-iframe");
try {
// Validate code first
this.validateCode(code);
// Step 1: Dispose old scene if iframe exists
if (iframe) {
try {
await iframe.contentWindow?.flock?.disposeOldScene();
} catch (error) {
console.warn("Error disposing old scene in iframe:", error);
}
} 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");
// Copy flock reference to iframe
iframeWindow.flock = this;
// Initialize new scene in iframe context
await this.initializeNewScene();
// Step 5: Create sandboxed function with all flock API methods
const sandboxFunction = new iframeWindow.Function(`
"use strict";
const {
initialize,
createEngine,
createScene,
playAnimation,
playSound,
stopAllSounds,
playNotes,
setBPM,
createInstrument,
speak,
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,
scale,
resize,
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,
UIInput,
UISlider,
onIntersect,
getProperty,
exportMesh,
abortSceneExecution,
ensureUniqueGeometry,
createVector3,
} = flock;
${code}
`);
// Execute sandboxed code
try {
await sandboxFunction();
} catch (sandboxError) {
throw new Error(
`Sandbox execution failed: ${sandboxError.message}`,
);
}
// Focus render canvas
document.getElementById("renderCanvas")?.focus();
} catch (error) {
// Enhanced error reporting
const enhancedError = this.createEnhancedError(error, code);
console.error("Enhanced error details:", enhancedError);
// Show user-friendly error
this.printText(`Error: ${error.message}`, 5, "#ff0000");
// Clean up on error
try {
this.audioContext?.close();
this.engine?.stopRenderLoop();
this.removeEventListeners();
} catch (cleanupError) {
console.error("Error during cleanup:", cleanupError);
}
throw error;
}
},
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();
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, {
preserveDrawingBuffer: true,
stencil: true,
powerPreference: "default",
});
flock.engine.enableOfflineSupport = false;
flock.engine.setHardwareScalingLevel(1 / window.devicePixelRatio);
},
async disposeOldScene() {
console.log("Disposing old scene");
flock.flockNotReady = true;
if (flock.scene) {
// Stop all sounds and animations first
flock.stopAllSounds();
flock.engine.stopRenderLoop();
// Abort any ongoing operations
if (flock.abortController) {
flock.abortController.abort();
}
// Stop all animations and dispose animation groups
flock.scene.stopAllAnimations();
if (flock.scene.animationGroups) {
flock.scene.animationGroups.forEach((group) => {
if (group) {
try {
group.stop();
group.dispose();
} catch (error) {
console.warn(
"Error disposing animation group:",
error,
);
}
}
});
}
// Clear all observables and event listeners
flock.removeEventListeners();
// Dispose UI elements
flock.controlsTexture?.dispose();
flock.controlsTexture = null;
// Clear main UI texture and all its controls
if (flock.scene.UITexture) {
flock.scene.UITexture.dispose();
flock.scene.UITexture = null;
}
// Clear advanced texture and stack panel
if (flock.advancedTexture) {
flock.advancedTexture.dispose();
flock.advancedTexture = null;
}
if (flock.stackPanel) {
flock.stackPanel.dispose();
flock.stackPanel = null;
}
flock.gridKeyPressObservable?.clear();
flock.gridKeyReleaseObservable?.clear();
// Dispose effects
flock.highlighter?.dispose();
flock.highlighter = null;
flock.glowLayer?.dispose();
flock.glowLayer = null;
// Dispose lighting
flock.mainLight?.dispose();
flock.mainLight = null;
// Dispose all meshes and their action managers
const meshesToDispose = flock.scene.meshes
? [...flock.scene.meshes]
: [];
meshesToDispose.forEach((mesh) => {
if (mesh && mesh.actionManager) {
mesh.actionManager.dispose();
}
if (
mesh &&
mesh.material &&
mesh.material.dispose &&
typeof mesh.material.dispose === "function"
) {
try {
mesh.material.dispose();
} catch (error) {
console.warn("Error disposing material:", error);
}
}
if (
mesh &&
mesh.dispose &&
typeof mesh.dispose === "function"
) {
try {
mesh.dispose();
} catch (error) {
console.warn("Error disposing mesh:", error);
}
}
});
// Clear camera
flock.scene.activeCamera?.inputs?.clear();
flock.scene.activeCamera?.dispose();
// Wait for async operations to complete
await new Promise((resolve) => setTimeout(resolve, 100));
// Clear all references
flock.events = {};
flock.modelCache = {};
flock.globalSounds = [];
flock.modelsBeingLoaded = {};
flock.originalModelTransformations = {};
flock.geometryCache = {};
flock.materialCache = {};
flock.pendingTriggers = new Map();
flock._animationFileCache = {};
flock.ground = null;
flock.sky = null;
// Dispose particle systems
const particleSystems = flock.scene.particleSystems
? [...flock.scene.particleSystems]
: [];
particleSystems.forEach((system) => {
if (system && system.dispose) {
system.dispose();
}
});
// Dispose textures
const textures = flock.scene.textures
? [...flock.scene.textures]
: [];
textures.forEach((texture) => {
if (
texture &&
texture.dispose &&
typeof texture.dispose === "function"
) {
try {
texture.dispose();
} catch (error) {
console.warn("Error disposing texture:", error);
}
}
});
// Dispose materials that weren't caught earlier
const materials = flock.scene.materials
? [...flock.scene.materials]
: [];