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

ThreeViewer.ts 48KB

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