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.

loading-files.md 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. ---
  2. prev:
  3. text: 'Features'
  4. link: './features'
  5. next:
  6. text: 'Exporting Files'
  7. link: './exporting-files'
  8. ---
  9. # Loading files
  10. ThreePipe uses the [AssetManager](https://threepipe.org/docs/classes/AssetManager.html) to load files.
  11. The AssetManager has support for loading files from URLs, local files and data URLs.
  12. The AssetManager also adds support for loading files from a zip archive. The zip files are automatically unzipped, and the files are loaded from the zip archive.
  13. [`viewer.load()`](https://threepipe.org/docs/classes/ThreeViewer.html#load) is a simple wrapper for loading files from the AssetManager.
  14. It automatically adds the loaded object to the scene(if possible) and returns a promise that resolves to the loaded object, the materials are also automatically registered to the material manager.
  15. ::: details AssetManager
  16. AssetManager internally uses [AssetImporter](https://threepipe.org/docs/classes/AssetImporter.html), which provides an API for managing three.js [LoadingManager](https://threejs.org/docs/#api/en/loaders/LoadingManager) and adding and registering loaders for different file types.
  17. If the purpose is not to add files to the scene then [`viewer.assetManager.importer.import()`](https://threepipe.org/docs/classes/AssetImporter.html#import) method can be used to import files from the `AssetImporter`. [`viewer.assetManager.loadImported()`](https://threepipe.org/docs/classes/AssetManager.html#loadImported)
  18. can then be called to load the imported files after any processing.
  19. The `viewer.load()`, `viewer.assetManager.addAsset()`
  20. and `viewer.assetManager.addAssetSingle()` methods perform combination of `import` and `loadImported`.
  21. :::
  22. ::: tip Caching
  23. The `AssetManager` automatically caches any loaded files in the browser's `CacheStorage`. This can be controlled by passing a custom storage or `false` to the `assetManager.storage` option in the viewer constructor.
  24. ```typescript
  25. const viewer = new ThreeViewer({
  26. assetManager: {
  27. storage: await caches.open('my-cache-storage'), // custom storage
  28. // storage: false // or disable caching
  29. }
  30. })
  31. ```
  32. Caching should be disabled if the server sets proper [cache-control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control) headers, as the browser will automatically cache the files.
  33. Note that using a different query parameter in the URL will bypass the cache and load the file again.
  34. :::
  35. ## 3D models
  36. The 3d models are added to `viewer.scene.modelRoot` on `viewer.load` unless some option is specified.
  37. ```typescript
  38. const objectGlb = await viewer.load<IObject3D>('https://example.com/file.glb')
  39. const objectFbx = await viewer.load<IObject3D>('https://example.com/file.fbx')
  40. const objectObj = await viewer.load<IObject3D>('https://example.com/file.obj') // .mtl referenced in obj is automatically loaded
  41. // ... load any 3d model file as an object
  42. ```
  43. Here, we are casting to [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html) type
  44. to get the proper type and autocomplete for the object.
  45. `IObject3D` inherits [Object3D](https://threejs.org/docs/#api/en/core/Object3D) from three.js and adds some additional properties.
  46. For JavaScript, the type can be omitted.
  47. ```javascript
  48. const objectGlb = await viewer.load('https://example.com/file.glb')
  49. ```
  50. When loading models, several options can be passed to automatically process the model first time, like `autoScale`, `autoCenter`, `addToRoot` etc. Check [AddObjectOptions](https://threepipe.org/docs/interfaces/AddObjectOptions.html) and [ImportAddOptions](https://threepipe.org/docs/interfaces/ImportAddOptions.html) for more details.
  51. ::: tip
  52. Loaders for some file types are already added, add more loaders using plugins or by registering custom loaders.
  53. ```typescript
  54. viewer.addPluginSync(Rhino3dmLoadPlugin)
  55. ```
  56. Check the [model-viewer](https://threepipe.org/examples/#model-viewer/) example for a list of plugins that can be used.
  57. :::
  58. ## Materials
  59. The materials downloaded as PMAT/BMAT/JSON etc from threepipe,
  60. webgi or the editor can be loaded
  61. and registered with the [MaterialManager](https://threepipe.org/docs/classes/MaterialManager)
  62. using the `viewer.load` method.
  63. Custom material types can also be registered by plugins(like dmat for diamonds), which can also be loaded automatically using the `viewer.load` method.
  64. ```typescript
  65. const pMaterial = await viewer.load<PhysicalMaterial>('https://example.com/file.pmat')
  66. const bMaterial = await viewer.load<UnlitMaterial>('https://example.com/file.bmat')
  67. // ... load any material file as a material
  68. ```
  69. Casting to [PhysicalMaterial](https://threepipe.org/docs/classes/PhysicalMaterial) or [UnlitMaterial](https://threepipe.org/docs/classes/UnlitMaterial) is optional but recommended to get the proper type and autocomplete for the material.
  70. To assign the material on any object, set it to `object.material`
  71. ```typescript
  72. // find a loaded mesh in the scene
  73. const object = viewer.scene.getObjectByName('objectName');
  74. // assign the material
  75. object.material = pMaterial;
  76. ```
  77. To copy the properties without changing the material reference, use `material.copy()` or `material.setValues()` methods.
  78. ```typescript
  79. object.material.copy(pMaterial);
  80. // or use material manager to apply to multiple materials.
  81. viewer.assetManager.materialManager.applyMaterial(pMaterial, 'METAL') // apply props to all materials/objects with the name METAL
  82. ```
  83. TODO: add examples for material load and copy
  84. ## Images/Textures
  85. Images can be loaded using the `viewer.load` method.
  86. There is built-in support for loading all image formats supported by the browser (webp, png, jpeg, jpg, svg, ico, avif) and hdr, exr, hdr.png formats for all browsers.
  87. More formats like ktx2, ktx, etc. can be added using plugins.
  88. ```typescript
  89. const texture = await viewer.load<ITexture>('https://example.com/file.png')
  90. // ... load any image file as a texture
  91. ```
  92. Casting to [ITexture](https://threepipe.org/docs/interfaces/ITexture.html) is optional
  93. but recommended to get the proper type and autocomplete for the texture.
  94. It inherits from three.js [Texture](https://threejs.org/docs/#api/en/textures/Texture) and adds some additional properties.
  95. To assign the texture on any material, set it to `material.map`
  96. ```typescript
  97. // find a loaded mesh in the scene
  98. const object = viewer.scene.getObjectByName('objectName');
  99. const material = object.material as PhysicalMaterial;
  100. // assign the texture
  101. material.map = texture;
  102. material.setDirty() // to let the viewer know that the material has changed and needs to re-render the scene. This will also trigger fade effect if FrameFadePlugin is added.
  103. ```
  104. Check out the image load example to see it in action or to check the JS equivalent code: https://threepipe.org/examples/#image-load/
  105. ## Zip files
  106. .zip files are automatically unzipped and the files are sent to re-load recursively when loaded with `viewer.load`.
  107. Any level of zip hierarchy is flattened.
  108. Loading files like .gltf with references to assets inside the zip file,
  109. any relative references are also automatically resolved.
  110. This is supported for file types like gltf, glb, obj,
  111. etc which support references to external files and has `root` set to `true in [IImporter](https://threepipe.org/docs/interfaces/IImporter.html).
  112. ```typescript
  113. const objectGltf = await viewer.load<IObject3D>('https://example.com/model.gltf.zip')
  114. ```
  115. If we know that the zip file contains a single gltf with all the assets, we can cast the result to [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html) type.
  116. To load multiple assets from zip files like multiple textures or materials, use `viewer.assetManager.addAsset` method which returns a promise of array of loaded assets.
  117. ```typescript
  118. const textures = await viewer.assetManager.addAsset<ITexture[]>('https://example.com/textures.zip')
  119. const materials = await viewer.assetManager.addAsset<IMaterial[]>('https://example.com/materials.zip')
  120. ```
  121. The auto import of zip contents can be disabled to get the files and blobs in the zip
  122. ```typescript
  123. const zip = await viewer.load<any>('https://example.com/file.zip', {autoImportZipContents: false})
  124. ```
  125. TODO - add example for loading zip files.
  126. ## txt, json files
  127. Text and JSON files can be loaded using the `viewer.load` method and return strings and objects respectively.
  128. ```typescript
  129. const text = await viewer.load<string>('https://example.com/file.txt')
  130. const json = await viewer.load<any>('https://example.com/file.json')
  131. ```
  132. ## Data URLs
  133. Data URLs can be loaded using the `viewer.load` method. The correct mime-type is required to be set in the data URL for finding the correct importer.
  134. ```typescript
  135. const dataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' // ... some data url
  136. const texture = await viewer.load<ITexture>(dataUrl)
  137. ```
  138. ## Local files, File and Blob
  139. Local files can be loaded using the `viewer.load` method by passing a [IAsset](https://threepipe.org/docs/interfaces/IAsset) object with [File](https://developer.mozilla.org/en-US/docs/Web/API/File) or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object.
  140. ```typescript
  141. const file: File|Blob = fileObject // create a new file, blob or get from input element
  142. const text = await viewer.load<IObject>({
  143. // a path/name is required to determine the proper importer by extension. `file.name` can also be used if available
  144. path: 'file.glb',
  145. file
  146. })
  147. ```
  148. The same can be done for any file type.
  149. To load a `Map` of files(like when multiple files are dragged and dropped on the webpage) with internal references to other files, use `viewer.assetManager.importer.importFiles` method. Check the source for [DropzonePlugin](#dropzoneplugin) for an example.
  150. ## Background, Environment maps
  151. The background and environment maps can be set using the `viewer.setBackgroundMap` and `viewer.setEnvironmentMap` methods respectively. These accept both loaded textures from `viewer.load` and direct URLs. Files can be of any image format including hdr, exr.
  152. ```typescript
  153. await viewer.setEnvironmentMap('https://example.com/file.hdr')
  154. await viewer.setBackgroundMap('https://example.com/file.png')
  155. ```
  156. The same texture can be set to both by setting `setBackground` or `setEnvironment` to true in the options:
  157. ```typescript
  158. await viewer.setEnvironmentMap('https://example.com/file.hdr', {setBackground: true})
  159. ```
  160. Check the HDR Load example to see it in action: https://threepipe.org/examples/#hdr-load/
  161. ## SVG strings
  162. SVG strings can be converted to data urls using the [svgUrl](https://repalash.com/ts-browser-helpers/functions/svgUrl.html) string template function
  163. ```typescript
  164. const svgDataUrl = svgUrl`<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> ... </svg>`;
  165. const texture = await viewer.load<ITexture>(dataUrl)
  166. ```
  167. ## Custom file types
  168. Custom file importers/loaders can be registered to the `AssetImporter` using the `addImporter` method.
  169. ```typescript
  170. class CustomLoader extends FileLoader implements ILoader{
  171. constructor(manager?: LoadingManager) {
  172. super(manager);
  173. }
  174. load(url: string, onLoad: (data: any) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): Mesh {
  175. this.setResponseType('json')
  176. return super.load(url, (json: any)=>{
  177. const mat = new PhysicalMaterial(json)
  178. onLoad?.(mat)
  179. }, onProgress, onError)
  180. }
  181. }
  182. viewer.assetManager.importer.addImporter(new Importer(CustomLoader, ['ext'], ['mime/type'], false))
  183. // load the file
  184. const mat = await viewer.load<PhysicalMaterial>('https://example.com/file.ext')
  185. ```