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

ThreeViewer.ts 46KB

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