threepipe
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AssetManager.ts 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import {ImportAssetOptions, ImportResult, ProcessRawOptions, RootSceneImportResult} from './IAssetImporter'
  2. import {
  3. BaseEvent,
  4. Cache as threeCache,
  5. Camera,
  6. EventDispatcher,
  7. LinearFilter,
  8. LinearMipmapLinearFilter,
  9. LoadingManager,
  10. PerspectiveCamera,
  11. TextureLoader,
  12. } from 'three'
  13. import {ISerializedConfig, IViewerPlugin, ThreeViewer} from '../viewer'
  14. import {AssetImporter} from './AssetImporter'
  15. import {generateUUID, getTextureDataType, overrideThreeCache} from '../three'
  16. import {IAsset} from './IAsset'
  17. import {
  18. AddObjectOptions,
  19. ICamera,
  20. iCameraCommons,
  21. IMaterial,
  22. iMaterialCommons,
  23. IObject3D,
  24. iObjectCommons,
  25. ISceneEvent,
  26. ITexture,
  27. PerspectiveCamera2,
  28. upgradeTexture,
  29. } from '../core'
  30. import {Importer} from './Importer'
  31. import {MaterialManager} from './MaterialManager'
  32. import {DRACOLoader2, GLTFLoader2, JSONMaterialLoader, MTLLoader2, OBJLoader2, ZipLoader} from './import'
  33. import {RGBELoader} from 'three/examples/jsm/loaders/RGBELoader.js'
  34. import {FBXLoader} from 'three/examples/jsm/loaders/FBXLoader.js'
  35. import {EXRLoader} from 'three/examples/jsm/loaders/EXRLoader.js'
  36. import {Class, ValOrArr} from 'ts-browser-helpers'
  37. import {ILoader} from './IImporter'
  38. import {AssetExporter} from './AssetExporter'
  39. import {IExporter} from './IExporter'
  40. import {GLTFExporter2} from './export'
  41. export interface AssetManagerOptions{
  42. /**
  43. * simple memory based cache for downloaded files, default = false
  44. */
  45. simpleCache?: boolean
  46. /**
  47. * Cache Storage for downloaded files, can use with `caches.open`
  48. * When true and by default uses `caches.open('threepipe-assetmanager')`, set to false to disable
  49. * @default true
  50. */
  51. storage?: Cache | Storage | boolean
  52. }
  53. export type AddAssetOptions = AddObjectOptions & {
  54. /**
  55. * Automatically set any loaded HDR, EXR file as the scene environment map
  56. * @default true
  57. */
  58. autoSetEnvironment?: boolean
  59. /**
  60. * Automatically set any loaded image(ITexture) file as the scene background
  61. */
  62. autoSetBackground?: boolean
  63. }
  64. export type ImportAddOptions = ImportAssetOptions & AddAssetOptions
  65. export type AddRawOptions = ProcessRawOptions & AddAssetOptions
  66. /**
  67. * Asset Manager
  68. *
  69. * Utility class to manage import, export, and material management.
  70. * @category Asset Manager
  71. */
  72. export class AssetManager extends EventDispatcher<BaseEvent&{data: ImportResult}, 'loadAsset'> {
  73. readonly viewer: ThreeViewer
  74. readonly importer: AssetImporter
  75. readonly exporter: AssetExporter
  76. readonly materials: MaterialManager
  77. private _storage?: Cache | Storage
  78. get storage() {return this._storage}
  79. constructor(viewer: ThreeViewer, {simpleCache = false, storage}: AssetManagerOptions = {}) {
  80. super()
  81. this._sceneUpdated = this._sceneUpdated.bind(this)
  82. this.addAsset = this.addAsset.bind(this)
  83. this.addRaw = this.addRaw.bind(this)
  84. this.addImported = this.addImported.bind(this)
  85. this.importer = new AssetImporter(!!viewer.getPlugin('debug'))
  86. this.exporter = new AssetExporter()
  87. this.materials = new MaterialManager()
  88. this.viewer = viewer
  89. this.viewer.scene.addEventListener('addSceneObject', this._sceneUpdated)
  90. this.viewer.scene.addEventListener('materialChanged', this._sceneUpdated)
  91. this.viewer.scene.addEventListener('beforeDeserialize', this._sceneUpdated)
  92. this._initCacheStorage(simpleCache, storage ?? true)
  93. this.importer.addEventListener('processRaw', (event)=>{
  94. // console.log('preprocess mat', mat)
  95. const mat = event.data as IMaterial
  96. if (!mat || !mat.isMaterial || !mat.uuid) return
  97. if (this.materials?.findMaterial(mat.uuid)) {
  98. console.warn('imported material uuid already exists, creating new uuid')
  99. mat.uuid = generateUUID()
  100. if (mat.userData.uuid) mat.userData.uuid = mat.uuid
  101. }
  102. // todo: check for name exists also
  103. this.materials.registerMaterial(mat)
  104. })
  105. this.importer.addEventListener('processRawStart', (event)=>{
  106. // console.log('preprocess mat', mat)
  107. const res = event.data!
  108. // if (!res.assetType) {
  109. // if (res.isBufferGeometry) { // for eg stl todo
  110. // res = new Mesh(res, new MeshStandardMaterial())
  111. // }
  112. // if (res.isObject3D) {
  113. // }
  114. // }
  115. if (res.isObject3D) {
  116. // todo replace lights
  117. // if (res.isLight) {
  118. // res = upgradeThreejsLight(res)
  119. // } else {
  120. // const lights: any[] = []
  121. // res.traverse((rr: any)=>{
  122. // if (rr !== res && rr.isLight) lights.push(rr)
  123. // })
  124. // for (const light of lights) {
  125. // upgradeThreejsLight(light)
  126. // }
  127. // res = new Object3DModel(res, options as any)
  128. // }
  129. const cameras: Camera[] = []
  130. res.traverse((obj: any) => {
  131. if (obj.material) {
  132. const materials = Array.isArray(obj.material) ? obj.material : [obj.material]
  133. const newMaterials = []
  134. for (const material of materials) {
  135. const mat = this.materials.convertToIMaterial(material) || material
  136. mat.uuid = material.uuid
  137. mat.userData.uuid = material.uuid
  138. newMaterials.push(mat)
  139. }
  140. if (Array.isArray(obj.material)) obj.material = newMaterials
  141. else obj.material = newMaterials[0]
  142. }
  143. if (obj.isCamera) cameras.push(obj)
  144. })
  145. for (const camera of cameras) {
  146. // todo: OrthographicCamera
  147. if (!(camera as PerspectiveCamera).isPerspectiveCamera || !camera.parent) {
  148. iCameraCommons.upgradeCamera.call(camera)
  149. } else {
  150. const newCamera: ICamera = (camera as any).iCamera ?? new PerspectiveCamera2('', this.viewer.canvas)
  151. if (camera === newCamera) continue
  152. camera.parent.children.splice(camera.parent.children.indexOf(camera), 1, newCamera)
  153. newCamera.parent = camera.parent as any
  154. newCamera.copy(camera as any)
  155. camera.parent = null
  156. ;(newCamera as any).uuid = camera.uuid
  157. newCamera.userData.uuid = camera.uuid
  158. ;(camera as any).iCamera = newCamera
  159. // console.log('replacing camera', camera, newCamera)
  160. }
  161. }
  162. iObjectCommons.upgradeObject3D.call(res)
  163. } else if (res.isMaterial) {
  164. iMaterialCommons.upgradeMaterial.call(res)
  165. // todo update res by generating new material?
  166. } else if (res.isTexture) {
  167. upgradeTexture.call(res)
  168. if (event?.options?.generateMipmaps !== undefined)
  169. res.generateMipmaps = event?.options.generateMipmaps
  170. if (!res.generateMipmaps && !res.isRenderTargetTexture) { // todo: do we need to check more?
  171. res.minFilter = res.minFilter === LinearMipmapLinearFilter ? LinearFilter : res.minFilter
  172. res.magFilter = res.magFilter === LinearMipmapLinearFilter ? LinearFilter : res.magFilter
  173. }
  174. }
  175. // todo other asset/object types?
  176. })
  177. this._addImporters()
  178. this._addExporters()
  179. }
  180. async addAsset<T extends ImportResult = ImportResult>(assetOrPath?: string | IAsset | IAsset[], options?: ImportAddOptions): Promise<(T|undefined)[]> {
  181. if (!this.importer || !this.viewer) return []
  182. const imported = await this.importer.import<T>(assetOrPath, options)
  183. if (!imported) {
  184. console.warn('Unable to import', assetOrPath, imported)
  185. return []
  186. }
  187. return this.loadImported<(T|undefined)[]>(imported, options)
  188. }
  189. // materials: IMaterial[] = []
  190. // textures: ITexture[] = []
  191. async loadImported<T extends ValOrArr<ImportResult|undefined> = ImportResult>(imported: T, {autoSetEnvironment = true, autoSetBackground = false, ...options}: AddAssetOptions = {}): Promise<T | never[]> {
  192. const arr: (ImportResult|undefined)[] = Array.isArray(imported) ? imported : [imported]
  193. let ret: T = Array.isArray(imported) ? [] : undefined as any
  194. for (const obj of arr) {
  195. if (!obj) {
  196. if (Array.isArray(ret)) ret.push(undefined)
  197. continue
  198. }
  199. let r = obj
  200. switch (obj.assetType) {
  201. case 'material':
  202. this.materials.registerMaterial(<IMaterial>obj)
  203. break
  204. case 'texture':
  205. if (autoSetEnvironment && (
  206. obj.__rootPath?.endsWith('.hdr') || obj.__rootPath?.endsWith('.exr')
  207. )) this.viewer.scene.environment = <ITexture>obj
  208. if (autoSetBackground) this.viewer.scene.background = <ITexture>obj
  209. break
  210. case 'model':
  211. case 'light':
  212. case 'camera':
  213. r = await this.viewer.addSceneObject(<IObject3D|RootSceneImportResult>obj, options) // todo update references in scene update event
  214. break
  215. case 'config':
  216. if (options?.importConfig !== false) await this.viewer.importConfig(<ISerializedConfig>obj)
  217. break
  218. default:
  219. // legacy
  220. if (obj.type && typeof obj.type === 'string' && (Array.isArray((obj as any).plugins) ||
  221. (obj as any).type === 'ThreeViewer' || this.viewer.getPlugin((obj as any).type))) {
  222. await this.viewer.importConfig(<ISerializedConfig>obj)
  223. }
  224. break
  225. }
  226. this.dispatchEvent({type: 'loadAsset', data: obj})
  227. if (Array.isArray(ret)) ret.push(r)
  228. else ret = r as T
  229. }
  230. return ret || []
  231. }
  232. /**
  233. * same as {@link loadImported}
  234. * @param imported
  235. * @param options
  236. */
  237. async addProcessedAssets<T extends ImportResult|undefined = ImportResult>(imported: (T|undefined)[], options?: AddAssetOptions): Promise<(T | undefined)[]> {
  238. return this.loadImported(imported, options)
  239. }
  240. async addAssetSingle<T extends ImportResult = ImportResult>(asset?: IAsset | string, options?: ImportAssetOptions): Promise<T|undefined> {
  241. return !asset ? undefined : (await this.addAsset<T>(asset, options))?.[0]
  242. }
  243. // processAndAddObjects
  244. async addRaw<T extends (ImportResult|undefined) = ImportResult>(res: T|T[], options: AddRawOptions = {}): Promise<(T|undefined)[]> {
  245. const r = await this.importer.processRaw<T>(res, options)
  246. return this.loadImported<T[]>(r, options)
  247. }
  248. async addRawSingle<T extends ImportResult|undefined = ImportResult|undefined>(res: T, options: AddRawOptions = {}): Promise<T|undefined> {
  249. return (await this.addRaw<T>(res, options))?.[0]
  250. }
  251. private _sceneUpdated(event: ISceneEvent) { // todo: check if objects are added some other way.
  252. if (event.type === 'addSceneObject') {
  253. const target = event.object as ImportResult
  254. switch (target.assetType) {
  255. case 'material':
  256. this.materials.registerMaterial(<IMaterial>target)
  257. break
  258. case 'texture':
  259. break
  260. case 'model':
  261. case 'light':
  262. case 'camera':
  263. break
  264. default:
  265. break
  266. }
  267. } else if (event.type === 'materialChanged') {
  268. const target = event.material as IMaterial | IMaterial[] | undefined
  269. const targets = Array.isArray(target) ? target : target ? [target] : []
  270. for (const t of targets) {
  271. this.materials.registerMaterial(t)
  272. }
  273. } else if (event.type === 'beforeDeserialize') {
  274. // object/material/texture to be deserialized
  275. const data = event.data
  276. const meta = event.meta
  277. if (!data.metadata) {
  278. console.warn('Invalid data(no metadata)', data)
  279. }
  280. console.log(data, event)
  281. if (event.material) {
  282. if (data.metadata?.type !== 'Material') {
  283. console.warn('Invalid material data', data)
  284. }
  285. JSONMaterialLoader.DeserializeMaterialJSON(data, this.viewer, meta, event.material).then(()=>{
  286. //
  287. })
  288. }
  289. } else {
  290. console.error('Unexpected')
  291. }
  292. }
  293. dispose() {
  294. this.importer.dispose()
  295. this.materials.dispose()
  296. this.viewer.scene.removeEventListener('addSceneObject', this._sceneUpdated)
  297. this.viewer.scene.removeEventListener('materialChanged', this._sceneUpdated)
  298. this.exporter.dispose()
  299. }
  300. protected _addImporters() {
  301. const viewer = this.viewer
  302. if (!viewer) return
  303. const importers: Importer[] = [
  304. new Importer(TextureLoader, ['webp', 'png', 'jpeg', 'jpg', 'svg', 'ico', 'data:image', 'avif'], [
  305. 'image/webp', 'image/png', 'image/jpeg', 'image/svg+xml', 'image/gif', 'image/bmp', 'image/tiff', 'image/x-icon', 'image/avif',
  306. ], false), // todo: use ImageBitmapLoader if supported (better performance)
  307. new Importer<JSONMaterialLoader>(JSONMaterialLoader,
  308. ['mat', ...this.materials.templates.map(t=>t.typeSlug!).filter(v=>v)], // todo add others
  309. [], false, (loader)=>{
  310. if (loader) loader.viewer = this.viewer
  311. return loader
  312. }),
  313. new Importer(class extends RGBELoader {
  314. constructor(manager: LoadingManager) {
  315. super(manager)
  316. this.setDataType(getTextureDataType(viewer.renderManager.renderer))
  317. }
  318. }, ['hdr'], ['image/vnd.radiance'], false),
  319. new Importer(class extends EXRLoader {
  320. constructor(manager: LoadingManager) {
  321. super(manager)
  322. this.setDataType(getTextureDataType(viewer.renderManager.renderer))
  323. }
  324. }, ['exr'], ['image/x-exr'], false),
  325. new Importer(FBXLoader, ['fbx'], ['model/fbx'], true),
  326. new Importer(ZipLoader, ['zip'], ['application/zip'], true),
  327. new Importer(OBJLoader2 as any as Class<ILoader>, ['obj'], ['model/obj'], true),
  328. new Importer(MTLLoader2 as any as Class<ILoader>, ['mtl'], ['model/mtl'], false),
  329. new Importer<GLTFLoader2>(GLTFLoader2, ['gltf', 'glb', 'data:model/gltf'], ['model/gltf', 'model/gltf+json', 'model/gltf-binary'], true, (l, _, i) => l?.setup(this.viewer, i.extensions)),
  330. new Importer(DRACOLoader2, ['drc'], ['model/mesh+draco'], true),
  331. ]
  332. this.importer.addImporter(...importers)
  333. }
  334. protected _addExporters() {
  335. const exporters: IExporter[] = [
  336. {ext: ['gltf', 'glb'], extensions: [], ctor: (_, exporter)=>{
  337. const ex = new GLTFExporter2()
  338. // This should be added at the end.
  339. ex.setup(this.viewer, exporter.extensions)
  340. return ex
  341. }},
  342. ]
  343. this.exporter.addExporter(...exporters)
  344. }
  345. private _initCacheStorage(simpleCache?: boolean, storage?: Cache | Storage | boolean) {
  346. if (storage === true && window?.caches) {
  347. window.caches.open?.('threepipe-assetmanager').then(c => {
  348. this._initCacheStorage(simpleCache, c)
  349. this._storage = c
  350. })
  351. return
  352. }
  353. if (simpleCache || storage) {
  354. // three.js built-in simple memory cache. used in FileLoader.js todo: use local storage somehow
  355. if (simpleCache) threeCache.enabled = true
  356. if (storage && window.Cache && typeof window.Cache === 'function' && storage instanceof window.Cache) {
  357. overrideThreeCache(storage)
  358. // todo: clear cache
  359. }
  360. }
  361. this._storage = typeof storage === 'boolean' ? undefined : storage
  362. }
  363. // region deprecated
  364. /**
  365. * @deprecated use addRaw instead
  366. * @param res
  367. * @param options
  368. */
  369. async addImported<T extends (ImportResult|undefined) = ImportResult>(res: T|T[], options: AddRawOptions = {}): Promise<(T|undefined)[]> {
  370. console.error('addImported is deprecated, use addRaw instead')
  371. return this.addRaw(res, options)
  372. }
  373. /**
  374. * @deprecated use addAsset instead
  375. * @param path
  376. * @param options
  377. */
  378. public async addFromPath(path: string, options: ImportAddOptions = {}): Promise<any[]> {
  379. console.error('addFromPath is deprecated, use addAsset instead')
  380. return this.addAsset(path, options)
  381. }
  382. /**
  383. * @deprecated use {@link ThreeViewer.exportConfig} instead
  384. * @param binary - if set to false, encodes all the array buffers to base64
  385. */
  386. exportViewerConfig(binary = true): Record<string, any> {
  387. if (!this.viewer) return {}
  388. console.error('exportViewerConfig is deprecated, use viewer.toJSON instead')
  389. return this.viewer.toJSON(binary, undefined)
  390. }
  391. /**
  392. * @deprecated use {@link ThreeViewer.exportPluginsConfig} instead
  393. * @param filter
  394. */
  395. exportPluginPresets(filter?: string[]) {
  396. console.error('exportPluginPresets is deprecated, use viewer.exportPluginsConfig instead')
  397. return this.viewer?.exportPluginsConfig(filter)
  398. }
  399. /**
  400. * @deprecated use {@link ThreeViewer.exportPluginConfig} instead
  401. * @param plugin
  402. */
  403. exportPluginPreset(plugin: IViewerPlugin) {
  404. console.error('exportPluginPreset is deprecated, use viewer.exportPluginConfig instead')
  405. return this.viewer?.exportPluginConfig(plugin)
  406. }
  407. /**
  408. * @deprecated use {@link ThreeViewer.importPluginConfig} instead
  409. * @param json
  410. * @param plugin
  411. */
  412. async importPluginPreset(json: any, plugin?: IViewerPlugin) {
  413. console.error('importPluginPreset is deprecated, use viewer.importPluginConfig instead')
  414. return this.viewer?.importPluginConfig(json, plugin)
  415. }
  416. // todo continue from here by moving functions to the viewer.
  417. /**
  418. * @deprecated use {@link ThreeViewer.importConfig} instead
  419. * @param viewerConfig
  420. */
  421. async importViewerConfig(viewerConfig: any) {
  422. return this.viewer?.importConfig(viewerConfig)
  423. }
  424. /**
  425. * @deprecated use {@link ThreeViewer.fromJSON} instead
  426. * @param viewerConfig
  427. */
  428. applyViewerConfig(viewerConfig: any, resources?: any) {
  429. console.error('applyViewerConfig is deprecated, use viewer.fromJSON instead')
  430. return this.viewer?.fromJSON(viewerConfig, resources)
  431. }
  432. /**
  433. * @deprecated moved to {@link ThreeViewer.loadConfigResources}
  434. * @param json
  435. * @param extraResources - preloaded resources in the format of viewer config resources.
  436. */
  437. async importConfigResources(json: any, extraResources?: any) {
  438. if (!this.importer) throw 'Importer not initialized yet.'
  439. if (json.__isLoadedResources) return json
  440. return this.viewer?.loadConfigResources(json, extraResources)
  441. }
  442. /**
  443. * @deprecated not a plugin anymore
  444. */
  445. static readonly PluginType = 'AssetManager'
  446. // endregion
  447. }