-
Notifications
You must be signed in to change notification settings - Fork 12
/
ThreeViewer.ts
1380 lines (1231 loc) · 55.7 KB
/
ThreeViewer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
BaseEvent,
CanvasTexture,
Color,
Event,
EventDispatcher,
LinearSRGBColorSpace,
Object3D,
Quaternion,
Scene,
Vector2,
Vector3,
} from 'three'
import {Class, createCanvasElement, downloadBlob, onChange, serialize, ValOrArr} from 'ts-browser-helpers'
import {TViewerScreenShader} from '../postprocessing'
import {
AddObjectOptions,
IAnimationLoopEvent,
IMaterial,
IObject3D,
IObjectProcessor,
ITexture,
PerspectiveCamera2,
RootScene,
TCameraControlsMode,
} from '../core'
import {ViewerRenderManager} from './ViewerRenderManager'
import {
convertArrayBufferToStringsInMeta,
EasingFunctionType,
getEmptyMeta,
GLStatsJS,
IDialogWrapper,
jsonToBlob,
metaFromResources,
MetaImporter,
metaToResources,
SerializationMetaType,
SerializationResourcesType,
ThreeSerialization,
windowDialogWrapper,
} from '../utils'
import {
AssetManager,
AssetManagerOptions,
BlobExt,
ExportFileOptions,
IAsset,
ImportAddOptions,
ImportAssetOptions,
ImportResult,
RootSceneImportResult,
} from '../assetmanager'
import {IViewerPlugin, IViewerPluginSync} from './IViewerPlugin'
import {uiConfig, UiObjectConfig, uiPanelContainer} from 'uiconfig.js'
import {IRenderTarget} from '../rendering'
import type {CanvasSnapshotPlugin, FileTransferPlugin} from '../plugins'
import {CameraViewPlugin, ProgressivePlugin} from '../plugins'
// noinspection ES6PreferShortImport
import {DropzonePlugin, DropzonePluginOptions} from '../plugins/interaction/DropzonePlugin'
// noinspection ES6PreferShortImport
import {TonemapPlugin} from '../plugins/postprocessing/TonemapPlugin'
import {VERSION} from './version'
import {Easing} from 'popmotion'
import {OrbitControls3} from '../three'
export interface IViewerEvent extends BaseEvent, Partial<IAnimationLoopEvent> {
type: '*'|'update'|'preRender'|'postRender'|'preFrame'|'postFrame'|'dispose'|'addPlugin'|'renderEnabled'|'renderDisabled'
eType?: '*'|'update'|'preRender'|'postRender'|'preFrame'|'postFrame'|'dispose'|'addPlugin'|'renderEnabled'|'renderDisabled'
[p: string]: any
}
export type IViewerEventTypes = IViewerEvent['type']
export interface ISerializedConfig {
assetType: 'config',
type: string,
metadata?: {
generator: string,
version: number,
[key: string]: any
},
[key: string]: any
}
export interface ISerializedViewerConfig extends ISerializedConfig{
type: 'ThreeViewer'|'ViewerApp',
version: string,
plugins: ISerializedConfig[],
resources?: Partial<SerializationResourcesType> | SerializationMetaType
renderManager?: any // todo
scene?: any
[key: string]: any
}
export type IConsoleWrapper = Partial<Console> & Pick<Console, 'log'|'warn'|'error'>
/**
* Options for the ThreeViewer creation.
* @category Viewer
*/
export interface ThreeViewerOptions {
/**
* The canvas element to use for rendering. Only one of container and canvas must be specified.
*/
canvas?: HTMLCanvasElement,
/**
* The container for the canvas. A new canvas will be created in this container. Only one of container and canvas must be specified.
*/
container?: HTMLElement,
/**
* The fragment shader snippet to render on screen.
*/
screenShader?: TViewerScreenShader,
/**
* Use MSAA.
*/
msaa?: boolean,
/**
* Use Uint8 RGBM HDR Render Pipeline.
* Provides better performance with post-processing.
* RenderManager Uses Half-float if set to false.
*/
rgbm?: boolean
/**
* Use rendered gbuffer as depth-prepass / z-prepass. (Requires DepthBufferPlugin/GBufferPlugin)
* todo: It will be disabled when there are any transparent/transmissive objects with render to depth buffer enabled.
*/
zPrepass?: boolean
/**
* Force z-prepass even if there are transparent/transmissive objects with render to depth buffer enabled.
*/
forceZPrepass?: boolean // todo
/*
* Render scale, 1 = full resolution, 0.5 = half resolution, 2 = double resolution.
* Same as pixelRatio in three.js
* Can be set to `window.devicePixelRatio` to render at device resolution in browsers.
* An optimal value is `Math.min(2, window.devicePixelRatio)` to prevent issues on mobile. This is set when 'auto' is passed.
*/
renderScale?: number | 'auto'
debug?: boolean
/**
* Add initial plugins.
*/
plugins?: (IViewerPluginSync | Class<IViewerPluginSync>)[]
load?: {
/**
* Load one or more source files
*/
src?: ValOrArr<string | IAsset | null>
/**
* Load environment map
*/
environment?: string | IAsset | ITexture | undefined | null
/**
* Load background map
*/
background?: string | IAsset | ITexture | undefined | null
}
onLoad?: (results: any) => void
/**
* TonemapPlugin is added to the viewer if this is true.
* @default true
*/
tonemap?: boolean
camera?: {
controlsMode?: TCameraControlsMode,
position?: Vector3,
target?: Vector3,
}
/**
* Options for the asset manager.
*/
assetManager?: AssetManagerOptions
/**
* Add the dropzone plugin to the viewer, allowing to drag and drop files into the viewer over the canvas/container.
* Set to true/false to enable/disable the plugin, or pass options to configure the plugin. Assuming true if options are passed.
* @default - false
*/
dropzone?: boolean|DropzonePluginOptions
/**
* @deprecated use {@link msaa} instead
*/
isAntialiased?: boolean,
/**
* @deprecated use {@link rgbm} instead
*/
useRgbm?: boolean
/**
* @deprecated use {@link zPrepass} instead
*/
useGBufferDepth?: boolean
}
/**
* Three Viewer
*
* The ThreeViewer is the main class in the framework to manage a scene, render and add plugins to it.
* @category Viewer
*/
@uiPanelContainer('Viewer')
export class ThreeViewer extends EventDispatcher<IViewerEvent, IViewerEventTypes> {
public static readonly VERSION = VERSION
public static readonly ConfigTypeSlug = 'vjson'
uiConfig!: UiObjectConfig
static Console: IConsoleWrapper = {
log: console.log.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console),
}
static Dialog: IDialogWrapper = windowDialogWrapper
/**
* If the viewer is enabled. Set this `false` to disable RAF loop.
* @type {boolean}
*/
enabled = true
/**
* Enable or disable all rendering, Animation loop including any frame/render events won't be fired when this is false.
*/
@onChange(ThreeViewer.prototype._renderEnabledChanged)
renderEnabled = true
renderStats: GLStatsJS
readonly assetManager: AssetManager
@uiConfig() @serialize('renderManager')
readonly renderManager: ViewerRenderManager
get materialManager() {
return this.assetManager.materials
}
public readonly plugins: Record<string, IViewerPlugin> = {}
/**
* Scene with object hierarchy used for rendering
*/
get scene(): RootScene&Scene {
return this._scene as RootScene&Scene
}
/**
* Specifies how many frames to render in a single request animation frame. Keep to 1 for realtime rendering.
* Note: should be max (screen refresh rate / animation frame rate) like 60Hz / 30fps
* @type {number}
*/
public maxFramePerLoop = 1
readonly debug: boolean
/**
* Number of times to run composer render. If set to more than 1, preRender and postRender events will also be called multiple times.
*/
rendersPerFrame = 1
/**
* Get the HTML Element containing the canvas
* @returns {HTMLElement}
*/
get container(): HTMLElement {
// todo console.warn('container is deprecated, NOTE: subscribe to events when the canvas is moved to another container')
if (this._canvas.parentElement !== this._container) {
this.console.error('ThreeViewer: Canvas is not in the container, this might cause issues with some plugins.')
}
return this._container
}
/**
* Get the HTML Canvas Element where the viewer is rendering
* @returns {HTMLCanvasElement}
*/
get canvas(): HTMLCanvasElement {
return this._canvas
}
get console(): IConsoleWrapper {
return ThreeViewer.Console
}
get dialog(): IDialogWrapper {
return ThreeViewer.Dialog
}
@serialize() readonly type = 'ThreeViewer'
/**
* The ResizeObserver observing the canvas element. Add more elements to this observer to resize viewer on their size change.
* @type {ResizeObserver | undefined}
*/
readonly resizeObserver = window?.ResizeObserver ? new window.ResizeObserver(_ => this.resize()) : undefined
private readonly _canvas: HTMLCanvasElement
// this can be used by other plugins to add ui elements alongside the canvas
private readonly _container: HTMLElement // todo: add a way to move the canvas to a new container... and dispatch event...
/**
* The Scene attached to the viewer, this cannot be changed.
* @type {RootScene}
*/
@uiConfig() @serialize('scene')
private readonly _scene: RootScene
private _needsResize = false
private _isRenderingFrame = false
private _objectProcessor: IObjectProcessor = {
processObject: (object: IObject3D)=>{
if (object.material) {
if (Array.isArray(object.material)) this.assetManager.materials.registerMaterials(object.material)
else this.assetManager.materials.registerMaterial(object.material)
}
},
}
private _needsReset = true // renderer needs reset
// Helpers for tracking main camera change and setting dirty automatically
private _lastCameraPosition: Vector3 = new Vector3()
private _lastCameraQuat: Quaternion = new Quaternion()
private _lastCameraTarget: Vector3 = new Vector3()
private _tempVec: Vector3 = new Vector3()
private _tempQuat: Quaternion = new Quaternion()
/**
* If any of the viewers are in debug mode, this will be true.
* This is required for debugging/logging in some cases.
*/
public static ViewerDebugging = false // todo use in shaderReplaceString
/**
* Create a viewer instance for using the webgi viewer SDK.
* @param options - {@link ThreeViewerOptions}
*/
constructor({debug = false, ...options}: ThreeViewerOptions) {
super()
this.debug = debug
if (debug) ThreeViewer.ViewerDebugging = true
this._canvas = options.canvas || createCanvasElement()
let container = options.container
if (container && !options.canvas) container.appendChild(this._canvas)
if (!container) container = this._canvas.parentElement ?? undefined
if (!container) throw new Error('No container(or canvas).')
this._container = container
this.setDirty = this.setDirty.bind(this)
this._animationLoop = this._animationLoop.bind(this)
this._setActiveCameraView = this._setActiveCameraView.bind(this)
this.renderStats = new GLStatsJS(this._container)
if (debug) this.renderStats.show()
if (!(window as any).threeViewers) (window as any).threeViewers = [];
(window as any).threeViewers.push(this)
// camera
const camera = new PerspectiveCamera2(options.camera?.controlsMode ?? 'orbit', this._canvas)
camera.name = 'Default Camera'
options.camera?.position ? camera.position.copy(options.camera.position) : camera.position.set(0, 0, 5)
options.camera?.target ? camera.target.copy(options.camera.target) : camera.target.set(0, 0, 0)
camera.setDirty()
camera.userData.autoLookAtTarget = true // only for when controls are disabled / not available
// Update camera controls postFrame if allowed to interact
this.addEventListener('postFrame', () => { // todo: move inside RootScene.
const cam = this._scene.mainCamera
if (cam && cam.canUserInteract) {
const d = this.getPlugin<ProgressivePlugin>('ProgressivePlugin')?.postFrameConvergedRecordingDelta()
// if (d && d > 0) delta = d
if (d !== undefined && d === 0) return // not converged yet.
// if d < 0 or undefined: not recording, do nothing
cam.controls?.update()
}
})
// if camera position or target changed in last frame, call setDirty on camera
this.addEventListener('preFrame', () => { // todo: move inside RootScene.
const cam = this._scene.mainCamera
if (
cam.getWorldPosition(this._tempVec).sub(this._lastCameraPosition).lengthSq() // position is in local space
+ this._tempVec.subVectors(cam.target, this._lastCameraTarget).lengthSq() // target is in world space
+ cam.getWorldQuaternion(this._tempQuat).angleTo(this._lastCameraQuat)
> 0.000001) cam.setDirty()
})
// scene
this._scene = new RootScene(camera, this._objectProcessor)
this._scene.setBackgroundColor('#ffffff')
// this._scene.addEventListener('addSceneObject', this._addSceneObject)
this._scene.addEventListener('setView', this._setActiveCameraView)
this._scene.addEventListener('activateMain', this._setActiveCameraView)
this._scene.addEventListener('materialUpdate', (e) => this.setDirty(this._scene, e))
this._scene.addEventListener('materialChanged', (e) => this.setDirty(this._scene, e))
this._scene.addEventListener('objectUpdate', (e) => this.setDirty(this._scene, e))
this._scene.addEventListener('textureUpdate', (e) => this.setDirty(this._scene, e))
this._scene.addEventListener('sceneUpdate', (e) => {
this.setDirty(this._scene, e)
if (e.geometryChanged === false) return
this.renderManager.resetShadows()
})
this._scene.addEventListener('mainCameraUpdate', () => {
this._scene.mainCamera.getWorldPosition(this._lastCameraPosition)
this._lastCameraTarget.copy(this._scene.mainCamera.target)
this._scene.mainCamera.getWorldQuaternion(this._lastCameraQuat)
})
// render manager
if (options.isAntialiased !== undefined || options.useRgbm !== undefined || options.useGBufferDepth !== undefined) {
this.console.warn('isAntialiased, useRgbm and useGBufferDepth are deprecated, use msaa, rgbm and zPrepass instead.')
}
this.renderManager = new ViewerRenderManager({
canvas: this._canvas,
msaa: options.msaa ?? options.isAntialiased ?? false,
rgbm: options.rgbm ?? options.useRgbm ?? false,
zPrepass: options.zPrepass ?? options.useGBufferDepth ?? false,
depthBuffer: !(options.zPrepass ?? options.useGBufferDepth ?? false),
screenShader: options.screenShader,
renderScale: typeof options.renderScale === 'string' ? options.renderScale === 'auto' ?
Math.min(2, window.devicePixelRatio) : parseFloat(options.renderScale) :
options.renderScale,
})
this.renderManager.addEventListener('animationLoop', this._animationLoop as any)
this.renderManager.addEventListener('resize', ()=> this._scene.mainCamera.refreshAspect())
this.renderManager.addEventListener('update', (e) => {
if (e.change === 'registerPass' && e.pass?.materialExtension)
this.assetManager.materials.registerMaterialExtension(e.pass.materialExtension)
else if (e.change === 'unregisterPass' && e.pass?.materialExtension)
this.assetManager.materials.unregisterMaterialExtension(e.pass.materialExtension)
this.setDirty(this.renderManager, e)
})
this.assetManager = new AssetManager(this, options.assetManager)
if (this.resizeObserver) this.resizeObserver.observe(this._canvas)
// sometimes resize observer is late, so extra check
window && window.addEventListener('resize', this.resize)
this._canvas.addEventListener('webglcontextrestored', this._onContextRestore, false)
this._canvas.addEventListener('webglcontextlost', this._onContextLost, false)
if (options.dropzone) {
this.addPluginSync(new DropzonePlugin(typeof options.dropzone === 'object' ? options.dropzone : undefined))
}
if (options.tonemap !== false) {
this.addPluginSync(new TonemapPlugin())
}
for (const p of options.plugins ?? []) this.addPluginSync(p)
this.console.log('ThreePipe Viewer instance initialized, version: ', ThreeViewer.VERSION)
if (options.load) {
const sources = [options.load.src].flat().filter(s=> s)
const promises: Promise<any>[] = sources.map(async s=> s && this.load(s))
if (options.load.environment) promises.push(this.setEnvironmentMap(options.load.environment))
if (options.load.background) promises.push(this.setBackgroundMap(options.load.background))
Promise.all(promises).then(options.onLoad)
}
}
/**
* Add an object/model/material/viewer-config/plugin-preset/... to the viewer scene from url or an {@link IAsset} object.
* Same as {@link AssetManager.addAssetSingle}
* @param obj
* @param options
*/
async load<T extends ImportResult = ImportResult>(obj: string | IAsset | File | null, options?: ImportAddOptions) {
if (!obj) return
return await this.assetManager.addAssetSingle<T>(obj, options)
}
/**
* Imports an object/model/material/texture/viewer-config/plugin-preset/... to the viewer scene from url or an {@link IAsset} object.
* Same as {@link AssetImporter.importSingle}
* @param obj
* @param options
*/
async import<T extends ImportResult = ImportResult>(obj: string | IAsset | null, options?: ImportAddOptions) {
if (!obj) return
return await this.assetManager.importer.importSingle<T>(obj, options)
}
/**
* Set the environment map of the scene from url or an {@link IAsset} object.
* @param map
* @param setBackground - Set the background image of the scene from the same map.
* @param options - Options for importing the asset. See {@link ImportAssetOptions}
*/
async setEnvironmentMap(map: string | IAsset | null | ITexture | undefined, {setBackground = false, ...options}: ImportAssetOptions&{setBackground?: boolean} = {}): Promise<ITexture | null> {
this._scene.environment = map && !(<ITexture>map).isTexture ? await this.assetManager.importer.importSingle<ITexture>(map as string|IAsset, options) || null : <ITexture>map || null
if (setBackground) return this.setBackgroundMap(this._scene.environment)
return this._scene.environment
}
/**
* Set the background image of the scene from url or an {@link IAsset} object.
* @param map
* @param setEnvironment - Set the environment map of the scene from the same map.
* @param options - Options for importing the asset. See {@link ImportAssetOptions}
*/
async setBackgroundMap(map: string | IAsset | null | ITexture | undefined, {setEnvironment = false, ...options}: ImportAssetOptions&{setBackground?: boolean} = {}): Promise<ITexture | null> {
this._scene.background = map && !(<ITexture>map).isTexture ? await this.assetManager.importer.importSingle<ITexture>(map as string|IAsset, options) || null : <ITexture>map || null
if (setEnvironment) return this.setEnvironmentMap(this._scene.background)
return this._scene.background
}
/**
* Exports an object/mesh/material/texture/render-target/plugin-preset/viewer to a blob.
* If no object is given, a glb is exported with the current viewer state.
* @param obj
* @param options
*/
async export(obj?: IObject3D|IMaterial|ITexture|IRenderTarget|IViewerPlugin|(typeof this), options?: ExportFileOptions) {
if (!obj) obj = this._scene // this will export the glb with the scene and viewer config
if ((<typeof this>obj).type === this.type) return jsonToBlob((<typeof this>obj).exportConfig())
if ((<IViewerPlugin>obj).constructor?.PluginType) return jsonToBlob(this.exportPluginConfig(<IViewerPlugin>obj))
return await this.assetManager.exporter.exportObject(<IObject3D|IMaterial|ITexture|IRenderTarget>obj, options)
}
/**
* Export the scene to a file (default: glb with viewer config) and return a blob
* @param options
*/
async exportScene(options?: ExportFileOptions): Promise<BlobExt | undefined> {
return this.assetManager.exporter.exportObject(this._scene.modelRoot, options)
}
async getScreenshotBlob({mimeType = 'image/jpeg', quality = 90} = {}): Promise<Blob | null | undefined> {
const plugin = this.getPlugin<CanvasSnapshotPlugin>('CanvasSnapshotPlugin')
if (plugin) {
return plugin.getFile('snapshot.' + mimeType.split('/')[1], {mimeType, quality, waitForProgressive: true})
}
const blobPromise = async()=> new Promise<Blob|null>((resolve) => {
this._canvas.toBlob((blob) => {
resolve(blob)
}, mimeType, quality)
})
if (!this.renderEnabled) return blobPromise()
return await this.doOnce('postFrame', async() => {
this.renderEnabled = false
const blob = await blobPromise()
this.renderEnabled = true
return blob
})
}
async getScreenshotDataUrl({mimeType = 'image/jpeg', quality = 0.9} = {}): Promise<string | null | undefined> {
if (!this.renderEnabled) return this._canvas.toDataURL(mimeType, quality)
return await this.doOnce('postFrame', () => this._canvas.toDataURL(mimeType, quality))
}
/**
* Disposes the viewer and frees up all resource and events. Do not use the viewer after calling dispose.
* @note - If you want to reuse the viewer, set viewer.enabled to false instead, then set it to true again when required. To dispose all the objects, materials in the scene use `viewer.scene.disposeSceneModels()`
* This function is not fully implemented yet. There might be some memory leaks.
* @todo - return promise?
*/
public dispose(): void {
// todo: dispose stuff from constructor etc
for (const plugin of [...Object.values(this.plugins)]) {
this.removePlugin(plugin, true)
}
this._scene.dispose()
this.renderManager.dispose()
this._canvas.removeEventListener('webglcontextrestored', this._onContextRestore, false)
this._canvas.removeEventListener('webglcontextlost', this._onContextLost, false)
;(window as any).threeViewers?.splice((window as any).threeViewers.indexOf(this), 1)
if (this.resizeObserver) this.resizeObserver.unobserve(this._canvas)
else window.removeEventListener('resize', this.resize)
this.dispatchEvent({type: 'dispose'})
}
/**
* Mark that the canvas is resized. If the size is changed, the renderer and all render targets are resized. This happens before the render of the next frame.
*/
resize = () => {
this._needsResize = true
this.setDirty()
}
/**
* Set the viewer to dirty and trigger render of the next frame.
* @param source - The source of the dirty event. like plugin or 3d object
* @param event - The event that triggered the dirty event.
*/
setDirty(source?: any, event?: Event): void {
this._needsReset = true
source = source ?? this
this.dispatchEvent({...event ?? {}, type: 'update', source})
}
protected _animationLoop(event: IAnimationLoopEvent): void {
if (!this.enabled || !this.renderEnabled) return
if (this._isRenderingFrame) {
this.console.warn('animation loop: frame skip') // not possible actually, since this is not async
return
}
this._isRenderingFrame = true
this.renderStats.begin()
for (let i = 0; i < this.maxFramePerLoop; i++) {
if (this._needsReset) {
this.renderManager.reset()
this._needsReset = false
}
if (this._needsResize) {
const size = [this._canvas.clientWidth, this._canvas.clientHeight]
if (event.xrFrame) { // todo: find a better way to resize for XR.
const cam = this.renderManager.webglRenderer.xr.getCamera()?.cameras[0]?.viewport
if (cam) {
if (cam.x !== 0 || cam.y !== 0) {
this.console.warn('x and y must be 0?')
}
size[0] = cam.width
size[1] = cam.height
this.console.log('resize for xr', size)
} else {
this._needsResize = false
}
}
if (this._needsResize) {
this.renderManager.setSize(...size)
this._needsResize = false
}
}
this.dispatchEvent({...event, type: 'preFrame', target: this}) // event will have time, deltaTime and xrFrame
const dirtyPlugins = Object.values(this.plugins).filter(value => value.dirty)
if (dirtyPlugins.length > 0) {
// console.log('dirty plugins', dirtyPlugins)
this.setDirty(dirtyPlugins)
}
if (this._needsReset) {
this.renderManager.reset()
this._needsReset = false
}
// Check if the renderManger is dirty, which happens when it's reset above or if any pass in the composer is dirty
const needsRender = this.renderManager.needsRender
if (needsRender) {
for (let j = 0; j < this.rendersPerFrame; j++) {
this.dispatchEvent({type: 'preRender', target: this})
try {
const cam = this._scene.mainCamera
this._scene.renderCamera = cam
if (cam.visible) this.renderManager.render(this._scene, this.renderManager.defaultRenderToScreen)
} catch (e) {
this.console.error(e)
if (this.debug) throw e
// this.enabled = false
}
this.dispatchEvent({type: 'postRender', target: this})
}
}
this.dispatchEvent({type: 'postFrame', target: this})
this.renderManager.onPostFrame()
if (!needsRender) // break if no frame rendered
break
}
this.renderStats.end()
this._isRenderingFrame = false
}
/**
* Get the Plugin by a constructor type or by the string type.
* Use string type if the plugin is not a dependency and you don't want to bundle the plugin.
* @param type - The class of the plugin to get, or the string type of the plugin to get which is in the static PluginType property of the plugin
* @returns {T | undefined} - The plugin of the specified type.
*/
getPlugin<T extends IViewerPlugin>(type: Class<T>|string): T | undefined {
return this.plugins[typeof type === 'string' ? type : (type as any).PluginType] as T | undefined
}
/**
* Get the Plugin by a constructor type or add a new plugin of the specified type if it doesn't exist.
* @param type
* @param args - arguments for the constructor of the plugin, used when a new plugin is created.
*/
async getOrAddPlugin<T extends IViewerPlugin>(type: Class<T>, ...args: ConstructorParameters<Class<T>>): Promise<T> {
const plugin = this.getPlugin(type)
if (plugin) return plugin
return this.addPlugin(type, ...args)
}
/**
* Get the Plugin by a constructor type or add a new plugin to the viewer of the specified type if it doesn't exist(sync).
* @param type
* @param args - arguments for the constructor of the plugin, used when a new plugin is created.
*/
getOrAddPluginSync<T extends IViewerPluginSync>(type: Class<T>, ...args: ConstructorParameters<Class<T>>): T {
const plugin = this.getPlugin(type)
if (plugin) return plugin
return this.addPluginSync(type, ...args)
}
/**
* Add a plugin to the viewer.
* @param plugin - The instance of the plugin to add or the class of the plugin to add.
* @param args - Arguments for the constructor of the plugin, in case a class is passed.
* @returns {Promise<T>} - The plugin added.
*/
async addPlugin<T extends IViewerPlugin>(plugin: T | Class<T>, ...args: ConstructorParameters<Class<T>>): Promise<T> {
const p = this._resolvePluginOrClass(plugin, ...args)
const type = p.constructor.PluginType
if (!p.constructor.PluginType) {
this.console.error('PluginType is not defined for', p)
return p
}
for (const d of p.dependencies || []) {
await this.getOrAddPlugin(d)
}
if (this.plugins[type]) {
this.console.error(`Plugin of type ${type} already exists, removing and disposing old plugin. This might break functionality, ensure only one plugin of a type is added`, this.plugins[type], p)
await this.removePlugin(this.plugins[type])
}
this.plugins[type] = p
await p.onAdded(this)
this.dispatchEvent({type: 'addPlugin', target: this, plugin: p})
this.setDirty(p)
return p
}
/**
* Add a plugin to the viewer(sync).
* @param plugin
* @param args
*/
addPluginSync<T extends IViewerPluginSync>(plugin: T|Class<T>, ...args: ConstructorParameters<Class<T>>): T {
const p = this._resolvePluginOrClass(plugin, ...args)
const type = p.constructor.PluginType
if (!p.constructor.PluginType) {
this.console.error('PluginType is not defined for', p)
return p
}
for (const d of p.dependencies || []) {
this.getOrAddPluginSync(d)
}
if (this.plugins[type]) {
this.console.error(`Plugin of type ${type} already exists, removing and disposing old plugin. This might break functionality, ensure only one plugin of a type is added`, this.plugins[type], p)
this.removePluginSync(this.plugins[type])
}
this.plugins[type] = p
p.onAdded(this)
this.dispatchEvent({type: 'addPlugin', target: this, plugin: p})
this.setDirty(p)
return p
}
/**
* Add multiple plugins to the viewer.
* @param plugins - List of plugin instances or classes
*/
async addPlugins(plugins: (IViewerPlugin | Class<IViewerPlugin>)[]): Promise<void> {
for (const p of plugins) await this.addPlugin(p)
}
/**
* Add multiple plugins to the viewer(sync).
* @param plugins - List of plugin instances or classes
*/
addPluginsSync(plugins: (IViewerPluginSync | Class<IViewerPluginSync>)[]): void {
for (const p of plugins) this.addPluginSync(p)
}
/**
* Remove a plugin instance or a plugin class. Works similar to {@link ThreeViewer.addPlugin}
* @param p
* @param dispose
* @returns {Promise<void>}
*/
async removePlugin(p: IViewerPlugin<ThreeViewer, false>, dispose = true): Promise<void> {
const type = p.constructor.PluginType
if (!this.plugins[type]) return
await p.onRemove(this)
delete this.plugins[type]
if (dispose) await p.dispose() // todo await?
this.setDirty(p)
}
/**
* Remove a plugin instance or a plugin class(sync). Works similar to {@link ThreeViewer.addPluginSync}
* @param p
* @param dispose
*/
removePluginSync(p: IViewerPluginSync, dispose = true): void {
const type = p.constructor.PluginType
if (!this.plugins[type]) return
p.onRemove(this)
delete this.plugins[type]
if (dispose) p.dispose()
this.setDirty(p)
}
/**
* Set size of the canvas and update the renderer.
* If no size or width/height is passed, canvas is set to 100% of the container.
*
* See also {@link ThreeViewer.setRenderSize} to set the size of the render target by automatically calculating the renderScale and fitting in container.
*
* Note: Apps using this should ideally set `max-width: 100%` for the canvas in css.
* @param size
*/
setSize(size?: {width?: number, height?: number}) {
this._canvas.style.width = size?.width ? size.width + 'px' : '100%'
this._canvas.style.height = size?.height ? size.height + 'px' : '100%'
// this._canvas.style.maxWidth = '100%' // this is upto the app to do.
// this._canvas.style.maxHeight = '100%'
this.resize()
}
// todo make an example for this.
// todo make a constructor parameter for renderSize
// todo make getRenderSize or get renderSize
/**
* Set the render size of the viewer to fit in the container according to the specified mode, maintaining aspect ratio.
* Changes the renderScale accordingly.
* Note: the canvas needs to be centered in the container to work properly, this can be done with the following css on the container:
* ```css
* display: flex;
* justify-content: center;
* align-items: center;
* ```
* or in js:
* ```js
* viewer.container.style.display = 'flex';
* viewer.container.style.justifyContent = 'center';
* viewer.container.style.alignItems = 'center';
* ```
* Modes:
* 'contain': The canvas is scaled to fit within the container while maintaining its aspect ratio. The canvas will be fully visible, but there may be empty space around it.
* 'cover': The canvas is scaled to fill the entire container while maintaining its aspect ratio. Part of the canvas may be clipped to fit the container.
* 'fill': The canvas is stretched to completely fill the container, ignoring its aspect ratio.
* 'scale-down': The canvas is scaled down to fit within the container while maintaining its aspect ratio, but it won't be scaled up if it's smaller than the container.
* 'none': container size is ignored, but devicePixelRatio is used
* @param size - The size to set the render to. The canvas will render to this size.
* @param mode - 'contain', 'cover', 'fill', 'scale-down' or 'none'. Default is 'contain'.
* @param devicePixelRatio - typically set to `window.devicePixelRatio`, or `Math.min(1.5, window.devicePixelRatio)` for performance. Use this only when size is derived from dom elements.
* @param containerSize - (optional) The size of the container, if not passed, the bounding client rect of the container is used.
*/
setRenderSize(size: {width: number, height: number},
mode: 'contain' | 'cover' | 'fill' | 'scale-down' | 'none' = 'contain',
devicePixelRatio = 1,
containerSize?: {width: number, height: number}) {
// todo what about container resize?
const containerRect = containerSize || this.container.getBoundingClientRect()
const containerHeight = containerRect.height
const containerWidth = containerRect.width
const width = size.width
const height = size.height
const aspect = width / height
const containerAspect = containerWidth / containerHeight
const dpr = devicePixelRatio
let renderWidth, renderHeight
switch (mode) {
case 'contain':
if (containerAspect > aspect) {
renderWidth = containerHeight * aspect
renderHeight = containerHeight
} else {
renderWidth = containerWidth
renderHeight = containerWidth / aspect
}
break
case 'cover':
if (containerAspect > aspect) {
renderWidth = containerWidth
renderHeight = containerWidth / aspect
} else {
renderWidth = containerHeight * aspect
renderHeight = containerHeight
}
break
case 'fill':
renderWidth = containerWidth
renderHeight = containerHeight
break
case 'scale-down':
if (width < containerWidth && height < containerHeight) {
renderWidth = width
renderHeight = height
} else if (containerAspect > aspect) {
renderWidth = containerHeight * aspect
renderHeight = containerHeight
} else {
renderWidth = containerWidth
renderHeight = containerWidth / aspect
}
break
case 'none':
renderWidth = width
renderHeight = height
break
default:
throw new Error(`Invalid mode: ${mode}`)
}
this.setSize({width: renderWidth, height: renderHeight})
this.renderManager.renderScale = dpr * height / renderHeight
}
/**
* Traverse all objects in scene model root.
* @param callback
*/
traverseSceneObjects<T extends IObject3D = IObject3D>(callback: (o: T)=>void): void {
this._scene.modelRoot.traverse(callback)
}
/**
* Add an object to the scene model root.
* If an imported scene model root is passed, it will be loaded with viewer configuration, unless importConfig is false
* @param imported
* @param options
*/
async addSceneObject<T extends IObject3D|Object3D|RootSceneImportResult = RootSceneImportResult>(imported: T, options?: AddObjectOptions): Promise<T> {
if (imported.userData?.rootSceneModelRoot) {
const obj = <RootSceneImportResult>imported
if (obj.importedViewerConfig && options?.importConfig !== false) await this.importConfig(obj.importedViewerConfig)
this._scene.loadModelRoot(obj, options)
return this._scene.modelRoot as T
}
this._scene.addObject(imported, options)
return imported
}
/**
* Serialize all the plugins and their settings to save or create presets. Used in {@link toJSON}.
* @param meta - The meta object.
* @param filter - List of PluginType for the to include. If empty, no plugins will be serialized. If undefined, all plugins will be serialized.
* @returns {any[]}
*/
serializePlugins(meta: SerializationMetaType, filter?: string[]): any[] {
if (filter && filter.length === 0) return []
return Object.entries(this.plugins).map(p=> {
if (filter && !filter.includes(p[1].constructor.PluginType)) return
// if (!p[1].toJSON) this.console.log(`Plugin of type ${p[0]} is not serializable`)
return p[1].serializeWithViewer !== false ? p[1].toJSON?.(meta) : undefined
}).filter(p=> !!p)
}
/**
* Deserialize all the plugins and their settings from a preset. Used in {@link fromJSON}.
* @param plugins - The output of {@link serializePlugins}.
* @param meta - The meta object.
* @returns {this}
*/
deserializePlugins(plugins: any[], meta?: SerializationMetaType): this {
plugins.forEach(p=>{
if (!p.type) {
this.console.warn('Invalid plugin to import ', p)
return
}
const plugin = this.getPlugin(p.type)
if (!plugin) {
// this.console.warn(`Plugin of type ${p.type} is not added, cannot deserialize`)
return
}
plugin.fromJSON?.(p, meta)
})
return this
}
/**
* Serialize a single plugin settings.
*/
exportPluginConfig(plugin?: string|Class<IViewerPlugin>|IViewerPlugin): ISerializedConfig | Record<string, never> {
if (plugin && typeof plugin === 'string' || (plugin as any).PluginType) plugin = this.getPlugin(plugin as any)
if (!plugin) return {}
const meta = getEmptyMeta()
const data = (<IViewerPlugin>plugin).toJSON?.(meta)
if (!data) return {}
data.resources = metaToResources(meta)
return data