@needle-tools/engine 2.67.6-pre → 2.67.8-pre

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/needle-engine.js +5787 -5768
  3. package/dist/needle-engine.umd.cjs +83 -83
  4. package/lib/engine/engine_context.d.ts +170 -0
  5. package/lib/engine/engine_context.js +855 -0
  6. package/lib/engine/engine_context.js.map +1 -0
  7. package/lib/engine/engine_mainloop_utils.js +4 -1
  8. package/lib/engine/engine_mainloop_utils.js.map +1 -1
  9. package/lib/engine/engine_setup.d.ts +1 -166
  10. package/lib/engine/engine_setup.js +2 -839
  11. package/lib/engine/engine_setup.js.map +1 -1
  12. package/lib/engine/engine_time.d.ts +2 -0
  13. package/lib/engine/engine_time.js +4 -1
  14. package/lib/engine/engine_time.js.map +1 -1
  15. package/lib/engine-components/AnimatorController.js.map +1 -1
  16. package/lib/engine-components/ui/Canvas.d.ts +4 -1
  17. package/lib/engine-components/ui/Canvas.js +17 -1
  18. package/lib/engine-components/ui/Canvas.js.map +1 -1
  19. package/lib/engine-components/ui/EventSystem.js +1 -2
  20. package/lib/engine-components/ui/EventSystem.js.map +1 -1
  21. package/lib/engine-components/ui/Text.js +4 -0
  22. package/lib/engine-components/ui/Text.js.map +1 -1
  23. package/lib/engine-components/ui/Utils.js +6 -4
  24. package/lib/engine-components/ui/Utils.js.map +1 -1
  25. package/package.json +1 -1
  26. package/plugins/vite/drop.js +1 -0
  27. package/plugins/vite/editor-connection.js +1 -1
  28. package/plugins/vite/poster.js +1 -1
  29. package/plugins/vite/reload.js +1 -1
  30. package/src/engine/engine_context.ts +957 -0
  31. package/src/engine/engine_mainloop_utils.ts +4 -2
  32. package/src/engine/engine_setup.ts +2 -941
  33. package/src/engine/engine_time.ts +4 -1
  34. package/src/engine-components/AnimatorController.ts +2 -2
  35. package/src/engine-components/postprocessing/Volume.ts +213 -213
  36. package/src/engine-components/ui/Canvas.ts +19 -1
  37. package/src/engine-components/ui/EventSystem.ts +1 -2
  38. package/src/engine-components/ui/Text.ts +3 -0
  39. package/src/engine-components/ui/Utils.ts +6 -4
@@ -0,0 +1,855 @@
1
+ import { Clock, DepthTexture, WebGLRenderer } from 'three';
2
+ import * as THREE from 'three';
3
+ import { Input } from './engine_input';
4
+ import { Physics } from './engine_physics';
5
+ import { Time } from './engine_time';
6
+ import { NetworkConnection } from './engine_networking';
7
+ import * as looputils from './engine_mainloop_utils';
8
+ import * as utils from "./engine_utils";
9
+ import { RenderPass } from "postprocessing";
10
+ import { AssetDatabase } from './engine_assetdatabase';
11
+ import { logHierarchy } from './engine_three_utils';
12
+ import * as Stats from 'three/examples/jsm/libs/stats.module';
13
+ import { RendererData } from './engine_rendererdata';
14
+ import { Addressables } from './engine_addressables';
15
+ import { Application } from './engine_application';
16
+ import { LightDataRegistry } from './engine_lightdata';
17
+ import { PlayerViewManager } from './engine_playerview';
18
+ import { destroy, foreachComponent } from './engine_gameobject';
19
+ import { ContextEvent, ContextRegistry } from './engine_context_registry';
20
+ // import { createCameraWithOrbitControl } from '../engine-components/CameraUtils';
21
+ const debug = utils.getParam("debugSetup");
22
+ const stats = utils.getParam("stats");
23
+ const debugActive = utils.getParam("debugactive");
24
+ const debugframerate = utils.getParam("debugframerate");
25
+ // this is where functions that setup unity scenes will be pushed into
26
+ // those will be accessed from our custom html element to load them into their context
27
+ export const build_scene_functions = {};
28
+ export class ContextArgs {
29
+ name;
30
+ alias;
31
+ domElement;
32
+ renderer = undefined;
33
+ hash;
34
+ constructor(domElement) {
35
+ this.domElement = domElement ?? document.body;
36
+ }
37
+ }
38
+ export var FrameEvent;
39
+ (function (FrameEvent) {
40
+ FrameEvent[FrameEvent["EarlyUpdate"] = 0] = "EarlyUpdate";
41
+ FrameEvent[FrameEvent["Update"] = 1] = "Update";
42
+ FrameEvent[FrameEvent["LateUpdate"] = 2] = "LateUpdate";
43
+ FrameEvent[FrameEvent["OnBeforeRender"] = 3] = "OnBeforeRender";
44
+ FrameEvent[FrameEvent["OnAfterRender"] = 4] = "OnAfterRender";
45
+ FrameEvent[FrameEvent["PrePhysicsStep"] = 9] = "PrePhysicsStep";
46
+ FrameEvent[FrameEvent["PostPhysicsStep"] = 10] = "PostPhysicsStep";
47
+ FrameEvent[FrameEvent["Undefined"] = -1] = "Undefined";
48
+ })(FrameEvent || (FrameEvent = {}));
49
+ export var XRSessionMode;
50
+ (function (XRSessionMode) {
51
+ XRSessionMode["ImmersiveVR"] = "immersive-vr";
52
+ XRSessionMode["ImmersiveAR"] = "immersive-ar";
53
+ })(XRSessionMode || (XRSessionMode = {}));
54
+ export function registerComponent(script, context) {
55
+ if (!script)
56
+ return;
57
+ const new_scripts = context?.new_scripts ?? Context.Current.new_scripts;
58
+ if (!new_scripts.includes(script)) {
59
+ new_scripts.push(script);
60
+ }
61
+ }
62
+ export class Context {
63
+ static _current;
64
+ static get Current() {
65
+ return this._current;
66
+ }
67
+ static set Current(context) {
68
+ ContextRegistry.Current = context;
69
+ this._current = context;
70
+ }
71
+ name;
72
+ alias;
73
+ isManagedExternally = false;
74
+ isPaused = false;
75
+ runInBackground = false;
76
+ targetFrameRate;
77
+ /** used to append to loaded assets */
78
+ hash;
79
+ domElement;
80
+ get resolutionScaleFactor() { return this._resolutionScaleFactor; }
81
+ /** use to scale the resolution up or down of the renderer. default is 1 */
82
+ set resolutionScaleFactor(val) {
83
+ if (val === this._resolutionScaleFactor)
84
+ return;
85
+ if (typeof val !== "number")
86
+ return;
87
+ if (val <= 0) {
88
+ console.error("Invalid resolution scale factor", val);
89
+ return;
90
+ }
91
+ this._resolutionScaleFactor = val;
92
+ this.updateSize();
93
+ }
94
+ _resolutionScaleFactor = 1;
95
+ // domElement.clientLeft etc doesnt return absolute position
96
+ _boundingClientRectFrame = -1;
97
+ _boundingClientRect = null;
98
+ _domX;
99
+ _domY;
100
+ calculateBoundingClientRect() {
101
+ // workaround for mozilla webXR viewer
102
+ if (this.isInAR) {
103
+ this._domX = 0;
104
+ this._domY = 0;
105
+ return;
106
+ }
107
+ if (this._boundingClientRectFrame === this.time.frame)
108
+ return;
109
+ this._boundingClientRectFrame = this.time.frame;
110
+ this._boundingClientRect = this.domElement.getBoundingClientRect();
111
+ this._domX = this._boundingClientRect.x;
112
+ this._domY = this._boundingClientRect.y;
113
+ }
114
+ get domWidth() {
115
+ // for mozilla XR
116
+ if (this.isInAR)
117
+ return window.innerWidth;
118
+ return this.domElement.clientWidth;
119
+ }
120
+ get domHeight() {
121
+ // for mozilla XR
122
+ if (this.isInAR)
123
+ return window.innerHeight;
124
+ return this.domElement.clientHeight;
125
+ }
126
+ get domX() {
127
+ this.calculateBoundingClientRect();
128
+ return this._domX;
129
+ }
130
+ get domY() {
131
+ this.calculateBoundingClientRect();
132
+ return this._domY;
133
+ }
134
+ get isInXR() { return this.renderer.xr?.isPresenting || false; }
135
+ xrSessionMode = undefined;
136
+ get isInVR() { return this.xrSessionMode === XRSessionMode.ImmersiveVR; }
137
+ get isInAR() { return this.xrSessionMode === XRSessionMode.ImmersiveAR; }
138
+ get xrSession() { return this.renderer.xr?.getSession(); }
139
+ get arOverlayElement() {
140
+ const el = this.domElement;
141
+ if (typeof el.getAROverlayContainer === "function")
142
+ return el.getAROverlayContainer();
143
+ return this.domElement;
144
+ }
145
+ /** Current event of the update cycle */
146
+ get currentFrameEvent() {
147
+ return this._currentFrameEvent;
148
+ }
149
+ _currentFrameEvent = FrameEvent.Undefined;
150
+ scene;
151
+ renderer;
152
+ composer = null;
153
+ // all scripts
154
+ scripts = [];
155
+ scripts_pausedChanged = [];
156
+ // scripts with update event
157
+ scripts_earlyUpdate = [];
158
+ scripts_update = [];
159
+ scripts_lateUpdate = [];
160
+ scripts_onBeforeRender = [];
161
+ scripts_onAfterRender = [];
162
+ scripts_WithCorroutines = [];
163
+ coroutines = {};
164
+ get mainCamera() {
165
+ if (this.mainCameraComponent) {
166
+ const cam = this.mainCameraComponent;
167
+ if (!cam.cam)
168
+ cam.buildCamera();
169
+ return cam.cam;
170
+ }
171
+ return null;
172
+ }
173
+ mainCameraComponent;
174
+ post_setup_callbacks = [];
175
+ pre_update_callbacks = [];
176
+ pre_render_callbacks = [];
177
+ post_render_callbacks = [];
178
+ new_scripts = [];
179
+ new_script_start = [];
180
+ new_scripts_pre_setup_callbacks = [];
181
+ new_scripts_post_setup_callbacks = [];
182
+ application;
183
+ time;
184
+ input;
185
+ physics;
186
+ connection;
187
+ /**
188
+ * @deprecated AssetDataBase is deprecated
189
+ */
190
+ assets;
191
+ mainLight = null;
192
+ rendererData;
193
+ addressables;
194
+ lightmaps;
195
+ players;
196
+ get isCreated() { return this._isCreated; }
197
+ _sizeChanged = false;
198
+ _isCreated = false;
199
+ _isVisible = false;
200
+ _stats = stats ? Stats.default() : null;
201
+ constructor(args) {
202
+ this.name = args?.name || "";
203
+ this.alias = args?.alias;
204
+ this.domElement = args?.domElement || document.body;
205
+ this.hash = args?.hash;
206
+ if (args?.renderer) {
207
+ this.renderer = args.renderer;
208
+ this.isManagedExternally = true;
209
+ }
210
+ else {
211
+ this.renderer = new WebGLRenderer({
212
+ antialias: true
213
+ });
214
+ // some tonemapping other than "NONE" is required for adjusting exposure with EXR environments
215
+ this.renderer.toneMappingExposure = 1; // range [0...inf] instead of the usual -15..15
216
+ this.renderer.toneMapping = THREE.NoToneMapping; // could also set to LinearToneMapping, ACESFilmicToneMapping
217
+ this.renderer.setClearColor(new THREE.Color('lightgrey'), 0);
218
+ // @ts-ignore
219
+ this.renderer.antialias = true;
220
+ // @ts-ignore
221
+ this.renderer.alpha = false;
222
+ this.renderer.shadowMap.enabled = true;
223
+ this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
224
+ this.renderer.setSize(this.domWidth, this.domHeight);
225
+ this.renderer.outputEncoding = THREE.sRGBEncoding;
226
+ this.renderer.physicallyCorrectLights = true;
227
+ }
228
+ this.scene = new THREE.Scene();
229
+ ContextRegistry.register(this);
230
+ this.application = new Application(this);
231
+ this.time = new Time();
232
+ this.input = new Input(this);
233
+ this.physics = new Physics(this);
234
+ this.connection = new NetworkConnection(this);
235
+ this.assets = new AssetDatabase();
236
+ this.rendererData = new RendererData(this);
237
+ this.addressables = new Addressables(this);
238
+ this.lightmaps = new LightDataRegistry(this);
239
+ this.players = new PlayerViewManager(this);
240
+ const resizeCallback = () => this._sizeChanged = true;
241
+ window.addEventListener('resize', resizeCallback);
242
+ this._disposeCallbacks.push(() => window.removeEventListener('resize', resizeCallback));
243
+ const resizeObserver = new ResizeObserver(_ => this._sizeChanged = true);
244
+ resizeObserver.observe(this.domElement);
245
+ this._disposeCallbacks.push(() => resizeObserver.disconnect());
246
+ this._intersectionObserver = new IntersectionObserver(entries => {
247
+ this._isVisible = entries[0].isIntersecting;
248
+ });
249
+ this._disposeCallbacks.push(() => this._intersectionObserver?.disconnect());
250
+ }
251
+ _intersectionObserver = null;
252
+ internalOnUpdateVisible() {
253
+ this._intersectionObserver?.disconnect();
254
+ this._intersectionObserver?.observe(this.domElement);
255
+ }
256
+ _disposeCallbacks = [];
257
+ // private _requestSizeUpdate : boolean = false;
258
+ updateSize() {
259
+ if (!this.isManagedExternally && !this.renderer.xr.isPresenting) {
260
+ this._sizeChanged = false;
261
+ const scaleFactor = this.resolutionScaleFactor;
262
+ const width = this.domWidth * scaleFactor;
263
+ const height = this.domHeight * scaleFactor;
264
+ const camera = this.mainCamera;
265
+ this.updateAspect(camera);
266
+ this.renderer.setSize(width, height);
267
+ this.renderer.setPixelRatio(window.devicePixelRatio);
268
+ // avoid setting pixel values here since this can cause pingpong updates
269
+ // e.g. when system scale is set to 125%
270
+ // https://github.com/needle-tools/needle-engine-support/issues/69
271
+ this.renderer.domElement.style.width = "100%";
272
+ this.renderer.domElement.style.height = "100%";
273
+ if (this.composer) {
274
+ this.composer.setSize?.call(this.composer, width, height);
275
+ if ("setPixelRatio" in this.composer && typeof this.composer.setPixelRatio === "function")
276
+ this.composer.setPixelRatio?.call(this.composer, window.devicePixelRatio);
277
+ }
278
+ }
279
+ }
280
+ updateAspect(camera, width, height) {
281
+ if (!camera)
282
+ return;
283
+ if (width === undefined)
284
+ width = this.domWidth;
285
+ if (height === undefined)
286
+ height = this.domHeight;
287
+ const pa = camera.aspect;
288
+ camera.aspect = width / height;
289
+ if (pa !== camera.aspect)
290
+ camera.updateProjectionMatrix();
291
+ }
292
+ onCreate(buildScene, opts) {
293
+ if (this._isCreated) {
294
+ console.warn("Context already created");
295
+ return null;
296
+ }
297
+ this._isCreated = true;
298
+ return this.internalOnCreate(buildScene, opts);
299
+ }
300
+ onDestroy() {
301
+ if (!this._isCreated)
302
+ return;
303
+ this._isCreated = false;
304
+ destroy(this.scene, true);
305
+ this.renderer?.setAnimationLoop(null);
306
+ if (!this.isManagedExternally) {
307
+ this.renderer?.dispose();
308
+ }
309
+ for (const cb of this._disposeCallbacks) {
310
+ try {
311
+ cb();
312
+ }
313
+ catch (e) {
314
+ console.error("Error in on dispose callback:", e, cb);
315
+ }
316
+ }
317
+ if (this.domElement?.parentElement) {
318
+ this.domElement.parentElement.removeChild(this.domElement);
319
+ }
320
+ ContextRegistry.dispatchCallback(ContextEvent.ContextDestroyed, this);
321
+ ContextRegistry.unregister(this);
322
+ }
323
+ registerCoroutineUpdate(script, coroutine, evt) {
324
+ if (!this.coroutines[evt])
325
+ this.coroutines[evt] = [];
326
+ this.coroutines[evt].push({ comp: script, main: coroutine });
327
+ return coroutine;
328
+ }
329
+ unregisterCoroutineUpdate(coroutine, evt) {
330
+ if (!this.coroutines[evt])
331
+ return;
332
+ const idx = this.coroutines[evt].findIndex(c => c.main === coroutine);
333
+ if (idx >= 0)
334
+ this.coroutines[evt].splice(idx, 1);
335
+ }
336
+ stopAllCoroutinesFrom(script) {
337
+ for (const evt in this.coroutines) {
338
+ const rout = this.coroutines[evt];
339
+ for (let i = rout.length - 1; i >= 0; i--) {
340
+ const r = rout[i];
341
+ if (r.comp === script) {
342
+ rout.splice(i, 1);
343
+ }
344
+ }
345
+ }
346
+ }
347
+ _cameraStack = [];
348
+ setCurrentCamera(cam) {
349
+ if (!cam)
350
+ return;
351
+ if (!cam.cam)
352
+ cam.buildCamera(); // < to build camera
353
+ if (!cam.cam) {
354
+ console.warn("Camera component is missing camera", cam);
355
+ return;
356
+ }
357
+ const index = this._cameraStack.indexOf(cam);
358
+ if (index >= 0)
359
+ this._cameraStack.splice(index, 1);
360
+ this._cameraStack.push(cam);
361
+ this.mainCameraComponent = cam;
362
+ const camera = cam.cam;
363
+ if (camera.isPerspectiveCamera)
364
+ this.updateAspect(camera);
365
+ this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera();
366
+ }
367
+ removeCamera(cam) {
368
+ if (!cam)
369
+ return;
370
+ const index = this._cameraStack.indexOf(cam);
371
+ if (index >= 0)
372
+ this._cameraStack.splice(index, 1);
373
+ if (this.mainCameraComponent === cam) {
374
+ this.mainCameraComponent = undefined;
375
+ if (this._cameraStack.length > 0) {
376
+ const last = this._cameraStack[this._cameraStack.length - 1];
377
+ this.setCurrentCamera(last);
378
+ }
379
+ }
380
+ }
381
+ _onBeforeRenderListeners = {};
382
+ /** use this to subscribe to onBeforeRender events on threejs objects */
383
+ addBeforeRenderListener(target, callback) {
384
+ if (!this._onBeforeRenderListeners[target.uuid]) {
385
+ this._onBeforeRenderListeners[target.uuid] = [];
386
+ const onBeforeRenderCallback = (renderer, scene, camera, geometry, material, group) => {
387
+ const arr = this._onBeforeRenderListeners[target.uuid];
388
+ if (!arr)
389
+ return;
390
+ for (let i = 0; i < arr.length; i++) {
391
+ const fn = arr[i];
392
+ fn(renderer, scene, camera, geometry, material, group);
393
+ }
394
+ };
395
+ target.onBeforeRender = onBeforeRenderCallback;
396
+ }
397
+ this._onBeforeRenderListeners[target.uuid].push(callback);
398
+ }
399
+ removeBeforeRenderListener(target, callback) {
400
+ if (this._onBeforeRenderListeners[target.uuid]) {
401
+ const arr = this._onBeforeRenderListeners[target.uuid];
402
+ const idx = arr.indexOf(callback);
403
+ if (idx >= 0)
404
+ arr.splice(idx, 1);
405
+ }
406
+ }
407
+ _requireDepthTexture = false;
408
+ _requireColorTexture = false;
409
+ _renderTarget;
410
+ _isRendering = false;
411
+ get isRendering() { return this._isRendering; }
412
+ setRequireDepth(val) {
413
+ this._requireDepthTexture = val;
414
+ }
415
+ setRequireColor(val) {
416
+ this._requireColorTexture = val;
417
+ }
418
+ get depthTexture() {
419
+ return this._renderTarget?.depthTexture || null;
420
+ }
421
+ get opaqueColorTexture() {
422
+ return this._renderTarget?.texture || null;
423
+ }
424
+ /** returns true if the dom element is visible on screen */
425
+ get isVisibleToUser() {
426
+ if (this.isInXR)
427
+ return true;
428
+ if (!this._isVisible)
429
+ return false;
430
+ const style = getComputedStyle(this.domElement);
431
+ return style.visibility !== "hidden" && style.display !== "none" && style.opacity !== "0";
432
+ }
433
+ async internalOnCreate(buildScene, opts) {
434
+ // TODO: we could configure if we need physics
435
+ await this.physics.createWorld();
436
+ // load and create scene
437
+ let prepare_succeeded = true;
438
+ try {
439
+ Context.Current = this;
440
+ if (buildScene)
441
+ await buildScene(this, opts);
442
+ }
443
+ catch (err) {
444
+ console.error(err);
445
+ prepare_succeeded = false;
446
+ }
447
+ if (!prepare_succeeded)
448
+ return;
449
+ this.internalOnUpdateVisible();
450
+ // console.log(prepare_succeeded);
451
+ if (!this.isManagedExternally)
452
+ this.domElement.prepend(this.renderer.domElement);
453
+ Context._current = this;
454
+ // Setup
455
+ Context._current = this;
456
+ for (let i = 0; i < this.new_scripts.length; i++) {
457
+ const script = this.new_scripts[i];
458
+ if (script.gameObject !== undefined && script.gameObject !== null) {
459
+ if (script.gameObject.userData === undefined)
460
+ script.gameObject.userData = {};
461
+ if (script.gameObject.userData.components === undefined)
462
+ script.gameObject.userData.components = [];
463
+ const arr = script.gameObject.userData.components;
464
+ if (!arr.includes(script))
465
+ arr.push(script);
466
+ }
467
+ // if (script.gameObject && !this.raycastTargets.includes(script.gameObject)) {
468
+ // this.raycastTargets.push(script.gameObject);
469
+ // }
470
+ }
471
+ // const context = new SerializationContext(this.scene);
472
+ // for (let i = 0; i < this.new_scripts.length; i++) {
473
+ // const script = this.new_scripts[i];
474
+ // const ser = script as unknown as ISerializable;
475
+ // if (ser.$serializedTypes === undefined) continue;
476
+ // context.context = this;
477
+ // context.object = script.gameObject;
478
+ // deserializeObject(ser, script, context);
479
+ // }
480
+ // resolve post setup callbacks (things that rely on threejs objects having references to components)
481
+ if (this.post_setup_callbacks) {
482
+ for (let i = 0; i < this.post_setup_callbacks.length; i++) {
483
+ Context._current = this;
484
+ await this.post_setup_callbacks[i](this);
485
+ }
486
+ }
487
+ if (!this.mainCamera) {
488
+ Context._current = this;
489
+ let camera = null;
490
+ foreachComponent(this.scene, comp => {
491
+ const cam = comp;
492
+ if (cam?.isCamera) {
493
+ looputils.updateActiveInHierarchyWithoutEventCall(cam.gameObject);
494
+ if (!cam.activeAndEnabled)
495
+ return undefined;
496
+ if (cam.tag === "MainCamera") {
497
+ camera = cam;
498
+ return true;
499
+ }
500
+ else
501
+ camera = cam;
502
+ }
503
+ return undefined;
504
+ });
505
+ if (camera) {
506
+ this.setCurrentCamera(camera);
507
+ }
508
+ else {
509
+ ContextRegistry.dispatchCallback(ContextEvent.MissingCamera, this);
510
+ if (!this.mainCamera && !this.isManagedExternally)
511
+ console.error("MISSING camera", this);
512
+ }
513
+ }
514
+ Context._current = this;
515
+ looputils.processNewScripts(this);
516
+ // const mainCam = this.mainCameraComponent as Camera;
517
+ // if (mainCam) {
518
+ // mainCam.applyClearFlagsIfIsActiveCamera();
519
+ // }
520
+ if (!this.isManagedExternally && this.composer && this.mainCamera) {
521
+ const renderPass = new RenderPass(this.scene, this.mainCamera);
522
+ this.renderer.setSize(this.domWidth, this.domHeight);
523
+ this.composer.addPass(renderPass);
524
+ this.composer.setSize(this.domWidth, this.domHeight);
525
+ }
526
+ this._sizeChanged = true;
527
+ if (this._stats) {
528
+ this._stats.showPanel(1);
529
+ this.domElement.appendChild(this._stats.dom);
530
+ }
531
+ this.renderer.setAnimationLoop(this.render.bind(this));
532
+ if (debug)
533
+ logHierarchy(this.scene, true);
534
+ ContextRegistry.dispatchCallback(ContextEvent.ContextCreated, this);
535
+ }
536
+ _accumulatedTime = 0;
537
+ _framerateClock = new Clock();
538
+ render(_, frame) {
539
+ this._currentFrameEvent = FrameEvent.Undefined;
540
+ if (this.isInXR === false && this.targetFrameRate !== undefined) {
541
+ this._accumulatedTime += this._framerateClock.getDelta();
542
+ if (this._accumulatedTime < (1 / this.targetFrameRate)) {
543
+ return;
544
+ }
545
+ this._accumulatedTime = 0;
546
+ }
547
+ this._stats?.begin();
548
+ Context._current = this;
549
+ if (this.onHandlePaused())
550
+ return;
551
+ Context._current = this;
552
+ this.time.update();
553
+ if (debugframerate)
554
+ console.log("FPS", (this.time.smoothedFps).toFixed(0));
555
+ looputils.processNewScripts(this);
556
+ looputils.updateIsActive(this.scene);
557
+ looputils.processStart(this);
558
+ while (this._cameraStack.length > 0 && (!this.mainCameraComponent || this.mainCameraComponent.destroyed)) {
559
+ this._cameraStack.splice(this._cameraStack.length - 1, 1);
560
+ const last = this._cameraStack[this._cameraStack.length - 1];
561
+ this.setCurrentCamera(last);
562
+ }
563
+ if (this.pre_update_callbacks) {
564
+ for (const i in this.pre_update_callbacks) {
565
+ this.pre_update_callbacks[i]();
566
+ }
567
+ }
568
+ this._currentFrameEvent = FrameEvent.EarlyUpdate;
569
+ for (let i = 0; i < this.scripts_earlyUpdate.length; i++) {
570
+ const script = this.scripts_earlyUpdate[i];
571
+ if (!script.activeAndEnabled)
572
+ continue;
573
+ if (script.earlyUpdate !== undefined) {
574
+ Context._current = this;
575
+ script.earlyUpdate();
576
+ }
577
+ }
578
+ this.executeCoroutines(FrameEvent.EarlyUpdate);
579
+ if (this.onHandlePaused())
580
+ return;
581
+ this._currentFrameEvent = FrameEvent.Update;
582
+ for (let i = 0; i < this.scripts_update.length; i++) {
583
+ const script = this.scripts_update[i];
584
+ if (!script.activeAndEnabled)
585
+ continue;
586
+ if (script.update !== undefined) {
587
+ Context._current = this;
588
+ script.update();
589
+ }
590
+ }
591
+ this.executeCoroutines(FrameEvent.Update);
592
+ if (this.onHandlePaused())
593
+ return;
594
+ this._currentFrameEvent = FrameEvent.LateUpdate;
595
+ for (let i = 0; i < this.scripts_lateUpdate.length; i++) {
596
+ const script = this.scripts_lateUpdate[i];
597
+ if (!script.activeAndEnabled)
598
+ continue;
599
+ if (script.lateUpdate !== undefined) {
600
+ Context._current = this;
601
+ script.lateUpdate();
602
+ }
603
+ }
604
+ // this.mainLight = null;
605
+ this.executeCoroutines(FrameEvent.LateUpdate);
606
+ if (this.onHandlePaused())
607
+ return;
608
+ const physicsSteps = 1;
609
+ const dt = this.time.deltaTime / physicsSteps;
610
+ for (let i = 0; i < physicsSteps; i++) {
611
+ this._currentFrameEvent = FrameEvent.PrePhysicsStep;
612
+ this.executeCoroutines(FrameEvent.PrePhysicsStep);
613
+ this.physics.step(dt);
614
+ this._currentFrameEvent = FrameEvent.PostPhysicsStep;
615
+ this.executeCoroutines(FrameEvent.PostPhysicsStep);
616
+ }
617
+ this.physics.postStep();
618
+ if (this.onHandlePaused())
619
+ return;
620
+ if (this.isVisibleToUser) {
621
+ this._currentFrameEvent = FrameEvent.OnBeforeRender;
622
+ // should we move these callbacks in the regular three onBeforeRender events?
623
+ for (let i = 0; i < this.scripts_onBeforeRender.length; i++) {
624
+ const script = this.scripts_onBeforeRender[i];
625
+ if (!script.activeAndEnabled)
626
+ continue;
627
+ // if(script.isActiveAndEnabled === false) continue;
628
+ if (script.onBeforeRender !== undefined) {
629
+ Context._current = this;
630
+ script.onBeforeRender(frame);
631
+ }
632
+ }
633
+ this.executeCoroutines(FrameEvent.OnBeforeRender);
634
+ if (this._sizeChanged)
635
+ this.updateSize();
636
+ if (this.pre_render_callbacks) {
637
+ for (const i in this.pre_render_callbacks) {
638
+ this.pre_render_callbacks[i]();
639
+ }
640
+ }
641
+ if (!this.isManagedExternally) {
642
+ looputils.runPrewarm(this);
643
+ this._currentFrameEvent = FrameEvent.Undefined;
644
+ this.renderNow();
645
+ this._currentFrameEvent = FrameEvent.OnAfterRender;
646
+ }
647
+ for (let i = 0; i < this.scripts_onAfterRender.length; i++) {
648
+ const script = this.scripts_onAfterRender[i];
649
+ if (!script.activeAndEnabled)
650
+ continue;
651
+ if (script.onAfterRender !== undefined) {
652
+ Context._current = this;
653
+ script.onAfterRender();
654
+ }
655
+ }
656
+ this.executeCoroutines(FrameEvent.OnAfterRender);
657
+ if (this.post_render_callbacks) {
658
+ for (const i in this.post_render_callbacks) {
659
+ this.post_render_callbacks[i]();
660
+ }
661
+ }
662
+ }
663
+ this._currentFrameEvent = -1;
664
+ this.connection.sendBufferedMessagesNow();
665
+ this._stats?.end();
666
+ if (this.time.frame === 1) {
667
+ this.domElement.dispatchEvent(new CustomEvent("ready"));
668
+ }
669
+ }
670
+ renderNow(camera) {
671
+ if (!camera) {
672
+ camera = this.mainCamera;
673
+ if (!camera)
674
+ return false;
675
+ }
676
+ this._isRendering = true;
677
+ this.renderRequiredTextures();
678
+ // if (camera === this.mainCameraComponent?.cam) {
679
+ // if (this.mainCameraComponent.activeTexture) {
680
+ // }
681
+ // }
682
+ if (this.composer && !this.isInXR) {
683
+ this.composer.render(this.time.deltaTime);
684
+ }
685
+ else if (camera) {
686
+ this.renderer.render(this.scene, camera);
687
+ }
688
+ this._isRendering = false;
689
+ return true;
690
+ }
691
+ /** returns true if we should return out of the frame loop */
692
+ _wasPaused = false;
693
+ onHandlePaused() {
694
+ const paused = this.evaluatePaused();
695
+ if (this._wasPaused !== paused) {
696
+ if (debugActive)
697
+ console.log("Paused?", paused, "context:" + this.alias);
698
+ for (let i = 0; i < this.scripts_pausedChanged.length; i++) {
699
+ const script = this.scripts_pausedChanged[i];
700
+ if (!script.activeAndEnabled)
701
+ continue;
702
+ if (script.onPausedChanged !== undefined) {
703
+ Context._current = this;
704
+ script.onPausedChanged(paused, this._wasPaused);
705
+ }
706
+ }
707
+ }
708
+ this._wasPaused = paused;
709
+ return paused;
710
+ }
711
+ evaluatePaused() {
712
+ if (this.isInXR)
713
+ return false;
714
+ if (this.isPaused)
715
+ return true;
716
+ // if the element is not visible use the runInBackground flag to determine if we should continue
717
+ if (this.runInBackground) {
718
+ return false;
719
+ }
720
+ const paused = !this.isVisibleToUser;
721
+ return paused;
722
+ }
723
+ renderRequiredTextures() {
724
+ if (!this.mainCamera)
725
+ return;
726
+ if (!this._requireDepthTexture && !this._requireColorTexture)
727
+ return;
728
+ if (!this._renderTarget) {
729
+ this._renderTarget = new THREE.WebGLRenderTarget(this.domWidth, this.domHeight);
730
+ if (this._requireDepthTexture) {
731
+ const dt = new DepthTexture(this.domWidth, this.domHeight);
732
+ ;
733
+ this._renderTarget.depthTexture = dt;
734
+ }
735
+ if (this._requireColorTexture) {
736
+ this._renderTarget.texture = new THREE.Texture();
737
+ this._renderTarget.texture.generateMipmaps = false;
738
+ this._renderTarget.texture.minFilter = THREE.NearestFilter;
739
+ this._renderTarget.texture.magFilter = THREE.NearestFilter;
740
+ this._renderTarget.texture.format = THREE.RGBAFormat;
741
+ }
742
+ }
743
+ const rt = this._renderTarget;
744
+ if (rt.texture) {
745
+ rt.texture.encoding = this.renderer.outputEncoding;
746
+ }
747
+ const prevTarget = this.renderer.getRenderTarget();
748
+ this.renderer.setRenderTarget(rt);
749
+ this.renderer.render(this.scene, this.mainCamera);
750
+ this.renderer.setRenderTarget(prevTarget);
751
+ }
752
+ executeCoroutines(evt) {
753
+ if (this.coroutines[evt]) {
754
+ const evts = this.coroutines[evt];
755
+ for (let i = 0; i < evts.length; i++) {
756
+ try {
757
+ const evt = evts[i];
758
+ // TODO we might want to keep coroutines playing even if the component is disabled or inactive
759
+ const remove = !evt.comp || evt.comp.destroyed || !evt.main || evt.comp["enabled"] === false;
760
+ if (remove) {
761
+ evts.splice(i, 1);
762
+ --i;
763
+ continue;
764
+ }
765
+ const iter = evt.chained;
766
+ if (iter && iter.length > 0) {
767
+ const last = iter[iter.length - 1];
768
+ const res = last.next();
769
+ if (res.done) {
770
+ iter.pop();
771
+ }
772
+ if (isGenerator(res)) {
773
+ if (!evt.chained)
774
+ evt.chained = [];
775
+ evt.chained.push(res.value);
776
+ }
777
+ if (!res.done)
778
+ continue;
779
+ }
780
+ const res = evt.main.next();
781
+ if (res.done === true) {
782
+ evts.splice(i, 1);
783
+ --i;
784
+ continue;
785
+ }
786
+ const val = res.value;
787
+ if (isGenerator(val)) {
788
+ // invoke once if its a generator
789
+ // this means e.g. WaitForFrame(1) works and will capture
790
+ // the frame it was created
791
+ const gen = val;
792
+ const res = gen.next();
793
+ if (res.done)
794
+ continue;
795
+ if (!evt.chained)
796
+ evt.chained = [];
797
+ evt.chained.push(val);
798
+ }
799
+ }
800
+ catch (e) {
801
+ console.error(e);
802
+ }
803
+ }
804
+ }
805
+ function isGenerator(val) {
806
+ if (val) {
807
+ if (val.next && val.return) {
808
+ return true;
809
+ }
810
+ }
811
+ return false;
812
+ }
813
+ }
814
+ }
815
+ // const scene = new THREE.Scene();
816
+ // const useComposer = utils.getParam("postfx");
817
+ // const renderer = new WebGLRenderer({ antialias: true });
818
+ // const composer = useComposer ? new EffectComposer(renderer) : undefined;
819
+ // renderer.setClearColor(new THREE.Color('lightgrey'), 0)
820
+ // renderer.antialias = true;
821
+ // renderer.alpha = false;
822
+ // renderer.shadowMap.enabled = true;
823
+ // renderer.shadowMap.type = THREE.PCFSoftShadowMap;
824
+ // renderer.setSize(window.innerWidth, window.innerHeight);
825
+ // renderer.outputEncoding = THREE.sRGBEncoding;
826
+ // renderer.physicallyCorrectLights = true;
827
+ // document.body.appendChild(renderer.domElement);
828
+ // // generation pushes loading requests in this array
829
+ // const sceneData: {
830
+ // mainCamera: THREE.Camera | undefined
831
+ // } = {
832
+ // preparing: [],
833
+ // resolving: [],
834
+ // scripts: [],
835
+ // raycastTargets: [],
836
+ // mainCamera: undefined,
837
+ // mainCameraComponent: undefined,
838
+ // };
839
+ // // contains a list of functions to be called after loading is done
840
+ // const post_setup_callbacks = [];
841
+ // const pre_render_Callbacks = [];
842
+ // const post_render_callbacks = [];
843
+ // const new_scripts = [];
844
+ // const new_scripts_post_setup_callbacks = [];
845
+ // const new_scripts_pre_setup_callbacks = [];
846
+ // export {
847
+ // scene, renderer, composer,
848
+ // new_scripts,
849
+ // new_scripts_post_setup_callbacks, new_scripts_pre_setup_callbacks,
850
+ // sceneData,
851
+ // post_setup_callbacks,
852
+ // pre_render_Callbacks,
853
+ // post_render_callbacks
854
+ // }
855
+ //# sourceMappingURL=engine_context.js.map