threepipe
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ThreeViewer.ts 48KB

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