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