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