threepipe
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

viewer-api.md 60KB

1 ano atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. ---
  2. prev:
  3. text: 'Features'
  4. link: './features'
  5. next:
  6. text: 'Core Plugins'
  7. link: './core-plugins'
  8. ---
  9. # Viewer API
  10. `viewer`: [`ThreeViewer`](https://threepipe.org/docs/classes/ThreeViewer.html) - is the main entry point to 3d rendering on the canvas.
  11. - `.scene`: [`RootScene`](https://threepipe.org/docs/classes/RootScene.html) - Main scene used for rendering. Instance of three.js [Scene](https://threejs.org/docs/#api/en/scenes/Scene)
  12. - `.mainCamera`: [`PerspectiveCamera2`](https://threepipe.org/docs/classes/PerspectiveCamera2.html) - Main camera currently being used for rendering. Instance of three.js [PerspectiveCamera](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera)
  13. - `.renderManager`: [`ViewerRenderManager`](https://threepipe.org/docs/classes/ViewerRenderManager.html) & [RenderManager](https://threepipe.org/docs/classes/RenderManager.html) & [RenderTargetManager](https://threepipe.org/docs/classes/RenderTargetManager.html) - Render manager for managing the rendering and composition pipeline, and provides helpers for rendering and render target management
  14. - `.renderer`: [`IWebGLRenderer`](https://threepipe.org/docs/interfaces/IWebGLRenderer.html) - for rendering. Instance of three.js [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer)
  15. - `.composer`: [`EffectComposer2`](https://threepipe.org/docs/classes/EffectComposer2.html) - for rendering passes. Instance of three.js [EffectComposer](https://threejs.org/docs/#api/en/postprocessing/EffectComposer)
  16. - `.context`: [`WebGLRenderingContext`](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext) - WebGL rendering context
  17. - `.renderPass`: [`ExtendedRenderPass`](https://threepipe.org/docs/classes/ExtendedRenderPass.html) - Render pass for rendering the scene. Instance of three.js [RenderPass](https://threejs.org/docs/#api/en/postprocessing/RenderPass) with extra features
  18. - `.screenPass`: [`ScreenPass`](https://threepipe.org/docs/classes/ScreenPass.html) - Screen pass for rendering the final output. Instance of three.js [ShaderPass](https://threejs.org/docs/#api/en/postprocessing/ShaderPass) with extra features.
  19. - `.assetManager`: [`AssetManager`](https://threepipe.org/docs/classes/AssetManager.html) - Asset manager for loading, managing and exporting assets
  20. - `.importer`: [`AssetImporter`](https://threepipe.org/docs/classes/AssetImporter.html) - for importing assets
  21. - `.exporter`: [`AssetExporter`](https://threepipe.org/docs/classes/AssetExporter.html) - for exporting assets
  22. - `.materialManager`: [`MaterialManager`](https://threepipe.org/docs/classes/MaterialManager.html) - for managing materials and material extensions
  23. - `.plugins`: `Record<string,`[`IViewerPlugin`](https://threepipe.org/docs/interfaces/IViewerPlugin.html)`>` - Plugins added to the viewer
  24. - `.uiConfig`: [`UiObjectConfig`](https://repalash.com/uiconfig.js/interfaces/UiObjectConfig.html) - UI confguration for the viewer. Used to automatically generate UIs for the viewer and plugins.
  25. ## ThreeViewer
  26. Source Code: [src/viewer/ThreeViewer.ts](https://github.com/repalash/threepipe/blob/master/src/viewer/ThreeViewer.ts)
  27. API Reference: [ThreeViewer](https://threepipe.org/docs/classes/ThreeViewer.html)
  28. `ThreeViewer` is the main entry point to the viewer. It provides all the API for managing the scene, camera, rendering, plugins, etc.
  29. It is initialized with either a canvas element or a `HTMLElement` for the container.
  30. The canvas element is used for rendering, and the options are used to configure the viewer.
  31. If the canvas element is not provided, a new canvas element is created and appended to the container.
  32. More options can be passed in the constructor to configure various built-in plugins and rendering features in the viewer.
  33. ### Constructor
  34. ```typescript
  35. import {ThreeViewer, CameraViewPlugin} from 'threepipe'
  36. // Create a viewer. All options except canvas/container are optional
  37. const viewer = new ThreeViewer({
  38. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  39. // or a container like:
  40. // container: document.getElementById('mcontainer'),
  41. // container: document.body,
  42. // Set the render scale to render at device resolution and clamp to max 2.
  43. renderScale: 'auto',
  44. // or Set the render scale to render at device resolution
  45. // renderScale: window.devicePixelRatio,
  46. // modify the screen shader: See ScreenPass and ScreenPass.glsl for more details
  47. screenShader: `diffuseColor = diffuseColor * 2.0;`,
  48. // Add TonemapPlugin
  49. tonemap: true,
  50. // Use MSAA(anti-aliasing)
  51. msaa: false,
  52. // Use Uint8 RGBM HDR Render Pipeline. Provides better performance with post-processing. RenderManager Uses Half-float if set to false.
  53. rgbm: true,
  54. // Use rendered gbuffer as depth-prepass / z-prepass.
  55. zPrepass: false,
  56. // Options for AssetManager
  57. assetManager: {
  58. // Use a custom CacheStorage
  59. storage: caches.open('threepipe-assetmanager'),
  60. },
  61. // Use DropzonePlugin to add support for file drag and drop
  62. // Enable and set properties
  63. dropzone: {
  64. // Set allowed extensions
  65. allowedExtensions: ['png', 'glb', 'gltf'],
  66. // Automatically add downloaded assets
  67. autoAdd: true
  68. // autoImport: true,
  69. // domElement: document.body,
  70. // addOptions: { ... }
  71. // importOptions: { ... }
  72. },
  73. // By default its false
  74. // dropzone: false,
  75. // To Enable without options
  76. // dropzone: true
  77. // Add some plugins after viewer creation.
  78. plugins: [CameraViewPlugin, new CustomPlugin()],
  79. // Shorthand to load files immediately after viewer initialization
  80. load: {
  81. src: 'https://example.com/file.glb',
  82. environment: 'https://example.com/file.hdr',
  83. background: 'https://example.com/file.png',
  84. },
  85. onLoad: (viewer) => {
  86. // Called when all the files are loaded
  87. },
  88. })
  89. ```
  90. Check the interface [ThreeViewerOptions](https://threepipe.org/docs/interfaces/ThreeViewerOptions.html) for all the options.
  91. To dispose off the viewer and all its resources call [`viewer.dispose()`](https://threepipe.org/docs/classes/ThreeViewer.html#dispose) method.
  92. To dispose only the scene objects and not the complete viewer, use `viewer.scene.disposeSceneModels()`
  93. ### Plugin Functions
  94. ```typescript
  95. import {ThreeViewer, TonemapPlugin, DepthBufferPlugin, NormalBufferPlugin} from 'threepipe'
  96. const viewer = new ThreeViewer({...})
  97. // Add a plugin
  98. const plugin = viewer.addPluginSync(new TonemapPlugin())
  99. // plugins can be added with just the class also
  100. const plugin2 = viewer.addPluginSync(TonemapPlugin)
  101. // Add multiple plugins at once
  102. viewer.addPluginsSync([
  103. TonemapPlugin,
  104. new NormalBufferPlugin(),
  105. DepthBufferPlugin,
  106. // ...
  107. ])
  108. // Get a plugin
  109. const plugin3 = viewer.getPlugin(TonemapPlugin)
  110. // Get or add a plugin, when not sure if the plugin is already added
  111. const plugin4 = viewer.getOrAddPluginSync(TonemapPlugin)
  112. // Remove a plugin
  113. viewer.removePluginSync(TonemapPlugin)
  114. ```
  115. ::: info Note
  116. All sync functions above have async counterparts like `addPlugin`, `getOrAddPlugin`,
  117. `removePlugin` that are used for async plugins.
  118. There are no async plugins built-in to threepipe yet.
  119. :::
  120. ### Import/Export Functions
  121. ```typescript
  122. import {ThreeViewer} from 'threepipe'
  123. const viewer = new ThreeViewer({...})
  124. // Load a 3d model
  125. const object = await viewer.load<IObject3D>('https://example.com/file.glb')
  126. // Load a material
  127. const material = await viewer.load<PhysicalMaterial>('https://example.com/file.pmat')
  128. // Load an image
  129. const texture = await viewer.load<ITexture>('https://example.com/file.png')
  130. // Import a model without adding to the scene
  131. const imported = await viewer.import('https://example.com/file.glb')
  132. // Export the complete scene with viewer configuraion
  133. const exportedScene = await viewer.exportScene({})
  134. // Export an object
  135. const exported = await viewer.export(object)
  136. // Export a material
  137. const exportedMaterial = await viewer.export(material)
  138. // Export a texture
  139. const exportedTexture = await viewer.export(texture)
  140. // Export viewer and plugins configurations
  141. const exportedConfig = await viewer.export(viewer)
  142. // Export plugin configuration
  143. const exportedPlugin = await viewer.exportPlugin(viewer.getPlugin(PluginClass))
  144. // Set Background Image
  145. await viewer.setBackgroundMap('https://example.com/file.png')
  146. // Set Environment Map
  147. await viewer.setEnvironmentMap('https://example.com/file.hdr')
  148. // Add an imported object or a created three.js object to the scene
  149. viewer.addSceneObject(imported)
  150. ```
  151. [`viewer.load`](https://threepipe.org/docs/classes/ThreeViewer.html#load) - Loads a single asset by path or [IAsset](https://threepipe.org/docs/interfaces/IAsset.html) object, and adds to the scene if its 3d object or loads it if it's a configuration It is the same as [AssetManager.addAssetSingle](https://threepipe.org/docs/classes/AssetManager.html#addAssetSingle). Use [AssetManager.addAsset](https://threepipe.org/docs/classes/AssetManager.html#addAsset) to load multiple assets from the same path like in case of zip bundles.
  152. [`viewer.import`](https://threepipe.org/docs/classes/ThreeViewer.html#import) - Load a single asset but does not add to the scene or load the configuration. It is the same as [AssetManager.importer.importSingle](https://threepipe.org/docs/classes/AssetImporter.html#importSingle). Use [AssetManager.importer.import](https://threepipe.org/docs/classes/AssetImporter.html#import) to import multiple assets from the same path like in case of zip bundles.
  153. [`viewer.export`](https://threepipe.org/docs/classes/ThreeViewer.html#export) - Exports an object, material, texture, render target or plugin configuration and returns a Blob. It is similar to [AssetManager.exporter.exportObject](https://threepipe.org/docs/classes/AssetExporter.html#exportObject) but adds support for exporting plugin and self(viewer) configs.
  154. [`viewer.exportScene`](https://threepipe.org/docs/classes/ThreeViewer.html#exportScene) - Exports the scene model root and all configurations into a bundled `glb` file and returns a blob.
  155. [`viewer.exportPlugin`](https://threepipe.org/docs/classes/ThreeViewer.html#exportPlugin) - Exports a plugin configuration and returns a blob.
  156. [`viewer.setBackgroundMap`](https://threepipe.org/docs/classes/ThreeViewer.html#setBackgroundMap) - Sets the background map to the given texture or url. Also sets it as environment map if `setEnvironment` is `true` in the options.
  157. [`viewer.setEnvironmentMap`](https://threepipe.org/docs/classes/ThreeViewer.html#setEnvironmentMap) - Sets the environment map to the given texture or url. Also sets it as background if `setBackground` is `true` in the options.
  158. [`viewer.addSceneObject`](https://threepipe.org/docs/classes/ThreeViewer.html#addSceneObject) - Adds an imported object or a created three.js object to the scene model root. If an imported scene model root is passed, it will be loaded with viewer configuration, unless `importConfig` is `false` in the options.
  159. ### Frame/Rendering Events
  160. ```typescript
  161. import {ThreeViewer} from 'threepipe'
  162. const viewer = new ThreeViewer({...})
  163. // Add a callback to be called before every frame, irrespective of whether enything is being rendered that frame
  164. viewer.addEventListener('preFrame', (ev)=>{
  165. console.log(ev);
  166. // change something
  167. viewer.setDirty() // let the viewer know to re-render the scene from this frame
  168. })
  169. // Add a callback to be called after every frame, irrespective of whether enything was rendered that frame
  170. viewer.addEventListener('postFrame', (ev)=>{
  171. console.log(ev);
  172. // change something
  173. viewer.setDirty() // let the viewer know to re-render the scene from next frame
  174. })
  175. // Add a callback to be called before every render, only if something is being rendered that frame
  176. viewer.addEventListener('preRender', (ev)=>{
  177. // canvas is about to be rendered, or re-rendered for progressive rendering
  178. console.log(ev, viewer.renderManager.frameCount);
  179. })
  180. // Add a callback to be called after every render, only if something was rendered that frame
  181. viewer.addEventListener('postRender', (ev)=>{
  182. // canvas is rendered, or re-rendered for progressive rendering
  183. console.log(ev);
  184. })
  185. // Listen to viewer.setDirty() calls
  186. viewer.addEventListener('update', (ev)=>{
  187. // viewer.setDirty() was called by some plugin or code
  188. console.log(ev);
  189. })
  190. // to remove an event listener, first keep a reference to the callback
  191. const callback = (ev)=>{ return }
  192. viewer.addEventListener('preFrame', callback)
  193. // then remove it
  194. viewer.removeEventListener('preFrame', callback)
  195. // Add a callback to be called only once for an event
  196. viewer.doOnce('postFrame', () => viewer.canvas.toDataURL('image/png'))
  197. // Enable/disable rendering in the viewer
  198. viewer.renderEnabled = false
  199. // do something with the canvas or load assets
  200. await viewer.load('https://example.com/file.glb')
  201. await viewer.load('https://example.com/file1.glb')
  202. await viewer.load('https://example.com/file2.glb')
  203. viewer.renderEnabled = true // all the assets will be rendered together in the next frame
  204. ```
  205. Check the [IViewerEvent](https://threepipe.org/docs/interfaces/IViewerEvent.html) interface for all the event types.
  206. [`viewer.addEventListener`](https://threepipe.org/docs/classes/ThreeViewer.html#addEventListener) - Adds a callback to be called on the given event. The callback is called with an [IViewerEvent](https://threepipe.org/docs/interfaces/IViewerEvent.html) object.
  207. [`viewer.removeEventListener`](https://threepipe.org/docs/classes/ThreeViewer.html#removeEventListener) - Removes a callback from the given event.
  208. [`viewer.doOnce`](https://threepipe.org/docs/classes/ThreeViewer.html#doOnce) - Adds a callback to be called only once for the given event. The listener will be added and automatically removed after the first call.
  209. ### Utility Functions
  210. ```typescript
  211. import {ThreeViewer} from 'threepipe'
  212. const viewer = new ThreeViewer({...})
  213. // Set the final render size directly and fit in container based on mode.
  214. viewer.setRenderSize({width: 800, height: 600}, 'cover')
  215. // Set size of the canvas
  216. viewer.setSize({width: 800, height: 600})
  217. // Set the render scale
  218. viewer.renderManager.renderScale = Math.min(window.devicePixelRatio, 2)
  219. // Traverse scene objects
  220. viewer.traverseSceneObjects((object) => {
  221. console.log(object)
  222. // do something with object
  223. })
  224. // If the size is set by css or manually by javascript use `resize` to update the viewer
  225. viewer.resize()
  226. // Trigger re-render with `setDirty` when something changes and viewer is not notified internally
  227. viewer.setDirty()
  228. // Get snapshot of the canvas as a blob
  229. const blob = await viewer.getScreenshotBlob({mimeTye: 'image/png', quality: 90})
  230. // Get snapshot of the canvas as a data url
  231. const dataUrl = await viewer.getScreenshotDataUrl({mimeTye: 'image/jpeg', quality: 85})
  232. // Dispose viewer and all resources
  233. viewer.canvas.remove() // canvas needs to be removed separately from the DOM
  234. viewer.dispose()
  235. ```
  236. [`viewer.setRenderSize`](https://threepipe.org/docs/classes/ThreeViewer.html#setRenderSize) - Sets the rendering resolution and fits the canvas in container based on the mode. The modes are `cover`, `contain`, `fill`, `scale-down` and `none`. The canvas size and render scale is calculated automatically to match the render render.
  237. [`viewer.setSize`](https://threepipe.org/docs/classes/ThreeViewer.html#setSize) - Sets the size of the canvas and updates the renderer and the camera. If no width/height is passed, canvas is set to 100% of the container.
  238. [`viewer.traverseSceneObjects`](https://threepipe.org/docs/classes/ThreeViewer.html#traverseSceneObjects) - Loop through all the objects in the scene model root hierarchy and calls the callback function with each object.
  239. [`viewer.resize`](https://threepipe.org/docs/classes/ThreeViewer.html#resize) - Mark that the canvas is resized. If the size is changed, the renderer and all render targets are resized.
  240. [`viewer.setDirty`](https://threepipe.org/docs/classes/ThreeViewer.html#setDirty) - Triggers re-render on next `requestAnimationFrame` call.
  241. [`viewer.getScreenshotBlob`](https://threepipe.org/docs/classes/ThreeViewer.html#getScreenshotBlob) - Returns a blob of the canvas screenshot. The blob can be used to download the screenshot or upload to a server.
  242. [`viewer.getScreenshotDataUrl`](https://threepipe.org/docs/classes/ThreeViewer.html#getScreenshotDataUrl) - Returns a data url of the canvas screenshot. The data url can be used to display the screenshot in an image element.
  243. [`viewer.dispose`](https://threepipe.org/docs/classes/ThreeViewer.html#dispose) - Disposes the viewer and all its resources. Use this to dispose the viewer when it is no longer needed. Note: the canvas element is not removed from the DOM and needs to be removed separately.
  244. ## RenderManager
  245. Source Code: [src/viewer/ViewerRenderManager.ts](https://github.com/repalash/threepipe/blob/master/src/viewer/ViewerRenderManager.ts), [src/rendering/RenderManager.ts](https://github.com/repalash/threepipe/blob/master/src/rendering/RenderManager.ts), [src/rendering/RenderTargetManager.ts](.https://github.com/repalash/threepipe/blob/master/src/rendering/RenderTargetManager.ts)
  246. API Reference: [ViewerRenderManager](https://threepipe.org/docs/classes/ViewerRenderManager.html), [RenderManager](https://threepipe.org/docs/classes/RenderManager.html), [RenderTargetManager](https://threepipe.org/docs/classes/RenderTargetManager.html)
  247. It manages the rendering, composition/postprocessing of the scene and provides helpers for rendering and render target management.
  248. ```typescript
  249. const viewer = new ThreeViewer({...})
  250. const renderManager = viewer.renderManager
  251. // Get the effect composer
  252. const composer = renderManager.composer
  253. // Get the three.js webgl renderer
  254. const renderer = renderManager.renderer
  255. // Get the main Render Pass in the pipeline
  256. const renderPass = renderManager.renderPass
  257. // Get the main Screen Pass in the pipeline
  258. const screenPass = renderManager.screenPass
  259. // Set the render scale
  260. renderManager.renderScale = Math.min(window.devicePixelRatio, 2)
  261. // Register a custom composer pass
  262. const customPass: IPipelinePass = new CustomPass()
  263. renderManager.registerPass(customPass)
  264. // Unregister a custom composer pass
  265. renderManager.unregisterPass(customPass)
  266. // The pipeline is automatically created and sorted based on dependencies in pipeline pass.
  267. // To check the built pipeline
  268. console.log(renderManager.pipeline)
  269. // Set a custom render pipeline
  270. renderManager.autoBuildPipeline = false
  271. renderManager.pipeline = ['depth', 'render', 'screen']
  272. // Check the total frames rendererd
  273. console.log(renderManager.totalFrameCount)
  274. // Get the current frame count in progressive rendering
  275. console.log(renderManager.frameCount)
  276. // Force reset shadows when some object is moved
  277. renderManager.resetShadows()
  278. // Render Target Management
  279. // Get the main composer target
  280. const composerTarget = renderManager.composerTarget
  281. // clone the target to get a copy of the target with all the default options
  282. const clonedTarget = composeTarget.clone()
  283. // Create a render target, same size as the canvas. The target are automatically resized when the canvas is resized
  284. const renderTarget = renderManager.createTarget({
  285. sizeMultiplier: 1, // size multiplier from the canvas. 0.5 will be half width and height of the canvas
  286. type: UnsignedByteType,
  287. // ... // See CreateRenderTargetOptions for all options
  288. })
  289. // Create a render target of custom size
  290. const renderTarget2 = renderManager.createTarget({
  291. size: {
  292. width: 1024,
  293. height: 1024,
  294. },
  295. type: HalfFloatType,
  296. // ...
  297. })
  298. // Dispose the render target
  299. renderManager.disposeTarget(renderTarget)
  300. // Create and release temporary targets for in-pass rendering.
  301. const tempTarget = renderManager.getTempTarget({
  302. sizeMultiplier: 0.5,
  303. type: HalfFloatType,
  304. // ...
  305. })
  306. // do something
  307. renderManager.releaseTempTarget(tempTarget)
  308. // Set how many temporary targets can remain in memory for a specific set of options
  309. renderManager.maxTempPerKey = 10 // default = 5
  310. // Copy/Blit a texture to the canvas or another render target with standard or a custom material
  311. renderManager.blit(destination, {source: sourceTexture})
  312. // Clear color of the canvas
  313. renderManager.clearColor({r: 0, g: 0, b: 0, a: 1, depth: true, viewport: new Vector4()})
  314. // Clear of a render target
  315. renderManager.clearColor(renderTarget, {r: 0, g: 0, b: 0, a: 1, target: renderTarget})
  316. // Export a render target to a blob. The type is automatically picked from exr to png based on the render target
  317. const blob = renderManager.exportRenderTarget(renderTarget, 'auto')
  318. // Export a render target to png/jpeg data url. This will clamp any floating point targets to fit in png/jpeg
  319. const dataUrl = renderManager.renderTargetToDataUrl(renderTarget, 'image/png')
  320. // Read render target pixels to array buffer. Returns Uint8Array|Uint16Array|Float32Array based on the render target type
  321. const buffer = renderManager.renderTargetToBuffer(renderTarget)
  322. ```
  323. [`renderManager.composer`](https://threepipe.org/docs/classes/ViewerRenderManager.html#composer) - The three.js [EffectComposer](https://threejs.org/docs/#api/en/postprocessing/EffectComposer) used for rendering the pipeline.
  324. [`renderManager.renderer`](https://threepipe.org/docs/classes/ViewerRenderManager.html#renderer) - The three.js [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer) used for rendering
  325. [`renderManager.context`](https://threepipe.org/docs/classes/ViewerRenderManager.html#context) - Access the WebGL rendering context for the canvas.
  326. [`renderManager.renderPass`](https://threepipe.org/docs/classes/ViewerRenderManager.html#renderPass) - The main render pass used in the render pipeline. Instance of three.js [RenderPass](https://threejs.org/docs/#api/en/postprocessing/RenderPass) with extra features like z prepass, rgbm rendering, blurred transmission, msaa and other optimizations.
  327. [`renderManager.screenPass`](https://threepipe.org/docs/classes/ViewerRenderManager.html#screenPass) - The main screen pass used in the render pipeline. Instance of three.js [ShaderPass](https://threejs.org/docs/#api/en/postprocessing/ShaderPass) with extra features like material extension, custom fragment, overriding read buffer, re-render to screen on change, etc
  328. [`renderManager.renderScale`](https://threepipe.org/docs/classes/RenderManager.html#renderScale) - Sets the render scale. All targets are scaled by this factor. This is equivalent to calling `EffectComposer.setPixelRatio` and `WebGLRenderer.setPixelRatio` in three.js.
  329. [`renderManager.resetShadows`](https://threepipe.org/docs/classes/RenderManager.html#resetShadows) - Resets all shadow maps in the scene. This is useful when some object is moved and the shadows need to be updated. This is automatically called when `scene.setDirty` or any `object.setDirty` is called, and during animation with plugins.
  330. ### Rendering Pipeline
  331. [`renderManager.registerPass`](https://threepipe.org/docs/classes/RenderManager.html#registerPass) - Registers a custom composer pass to the render pipeline. See [IPipelinePass](https://threepipe.org/docs/interfaces/IPipelinePass.html) interface.
  332. [`renderManager.unregisterPass`](https://threepipe.org/docs/classes/RenderManager.html#unregisterPass) - Unregisters a custom composer pass from the render pipeline.
  333. [`renderManager.pipeline`](https://threepipe.org/docs/classes/RenderManager.html#pipeline) - The render pipeline array. The array is automatically sorted based on dependencies in the pipeline passes.
  334. [`renderManager.autoBuildPipeline`](https://threepipe.org/docs/classes/RenderManager.html#autoBuildPipeline) - If `true`, the pipeline is automatically created and sorted based on dependencies in pipeline pass. If `false`, the pipeline is built only once and is not changed after that. The default value is `true`.
  335. [`renderManager.totalFrameCount`](https://threepipe.org/docs/classes/RenderManager.html#totalFrameCount) - The total frames rendered since the render manager was created.
  336. [`renderManager.frameCount`](https://threepipe.org/docs/classes/RenderManager.html#frameCount) - The current frame count in progressive rendering. This is useful for progressive rendering effects like progressive shadows, gi, denoising, baking, anti-aliasing, and many other effects.
  337. ### Render Targets management
  338. [`renderManager.composerTarget`](https://threepipe.org/docs/classes/RenderManager.html#composerTarget), [`renderManager.composerTarget1`](https://threepipe.org/docs/classes/RenderManager.html#composerTarget1) - The main targets used in [EffectComposer2](https://threepipe.org/docs/classes/EffectComposer2)
  339. [`renderManager.createTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#createTarget) - Creates a render target with the given options. The render target is automatically resized when the canvas is resized if `sizeMultiplier` is used. See [CreateRenderTargetOptions](https://threepipe.org/docs/interfaces/CreateRenderTargetOptions.html) for options
  340. [`renderManager.disposeTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#disposeTarget) - Disposes a render target and removes it from the render target manager.
  341. [`renderManager.getTempTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#getTempTarget) - Gets a temporary render target with the given options. The render target is automatically resized when the canvas is resized if `sizeMultiplier` is used. See [CreateRenderTargetOptions](https://threepipe.org/docs/interfaces/CreateRenderTargetOptions.html) for options
  342. [`renderManager.releaseTempTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#releaseTempTarget) - Releases a temporary render target and adds it back to the render target manager.
  343. [`renderManager.maxTempPerKey`](https://threepipe.org/docs/classes/RenderTargetManager.html#maxTempPerKey) - Sets how many temporary targets can remain in memory for a specific set of options. The default value is `5`.
  344. ### Helpers
  345. [`renderManager.blit`](https://threepipe.org/docs/classes/RenderManager.html#blit) - Blits a texture to the canvas or another render target with standard or a custom material. See [RendererBlitOptions](https://threepipe.org/docs/interfaces/RendererBlitOptions.html) for options.
  346. [`renderManager.clearColor`](https://threepipe.org/docs/classes/RenderManager.html#clearColor) - Clears the color of the canvas or a render target.
  347. [`renderManager.exportRenderTarget`](https://threepipe.org/docs/classes/RenderManager.html#exportRenderTarget) - Exports a render target to a blob. The type is automatically picked from exr to png based on the render target.
  348. [`renderManager.renderTargetToDataUrl`](https://threepipe.org/docs/classes/RenderManager.html#renderTargetToDataUrl) - Exports a render target to png/jpeg data url string. This will clamp any floating point targets to fit in png/jpeg. See [RenderTargetToDataUrlOptions](https://threepipe.org/docs/interfaces/RenderTargetToDataUrlOptions.html) for options.
  349. [`renderManager.renderTargetToBuffer`](https://threepipe.org/docs/classes/RenderManager.html#renderTargetToBuffer) - Reads render target pixels to a Uint8Array|Uint16Array|Float32Array array buffer.
  350. ## RootScene
  351. Source Code: [src/core/object/RootScene.ts](https://github.com/repalash/threepipe/blob/master/src/core/object/RootScene.ts)
  352. API Reference: [RootScene](https://threepipe.org/docs/classes/RootScene.html)
  353. RootScene is the main scene that is rendered in the canvas.
  354. It is an instance of three.js [Scene](https://threejs.org/docs/#api/en/scenes/Scene) with extra features including separation between model root and others,
  355. backgroundColor, background map and background intensity,
  356. environment map rotation and intensity, fixed env map direction patch, event bubbling in the scene hierarchy, scene config serialization, main camera management,
  357. automatic active near far management based on scene bounds, disposing complete scene hierarchy, etc
  358. ```typescript
  359. const viewer = new ThreeViewer({...})
  360. const scene = viewer.scene
  361. // List oll loaded objects in the model root
  362. console.log(scene.modelRoot.children)
  363. // Set the background color
  364. scene.setBackgroundColor('#ffffff')
  365. // or
  366. // scene.backgroundColor = new Color('#ffffff')
  367. // or
  368. // scene.backgroundColor.set('#ffffff')
  369. // scene.onBackgroundChange() // this must be called when not using a setter or set function.
  370. // Set a texture as background (or use viewer.setBackgroundMap). When both color and texture are set, they are multiplied
  371. scene.background = customTexture
  372. // Set the background same as the environment map
  373. scene.background = 'environment' // background is automatically changed when the environment changes.
  374. // or
  375. // scene.background = scene.environment
  376. // Set the background intensity
  377. scene.backgroundIntensity = 2
  378. // Set a texture as environment map (or use viewer.setEnvironmentMap)
  379. scene.environment = customTexture
  380. // Set the environment intensity
  381. scene.envMapIntensity = 2
  382. // Set the environment map rotation
  383. scene.environment.rotation = Math.PI / 2
  384. // Set Fixed env direction (rotate environment according the the camera)
  385. scene.fixedEnvMapDirection = true
  386. // Get the main camera used for rendering
  387. const camera: PerspectiveCamera2 = scene.mainCamera
  388. // Set camera props
  389. camera.position.set(0, 0, 10)
  390. camera.target.set(0, 0, 0)
  391. camera.setDirty() // this needs to be called to notify the viewer to re-render the scene
  392. // Traverse the model root hierarchy (or just use viewer.traverseSceneObjects)
  393. scene.modelRoot.traverse((object) => {
  394. console.log(object)
  395. // do something with object
  396. })
  397. // Access the default camera (same as mainCamera if not changed explicitly)
  398. const defaultCamera: ICamera = scene.defaultCamera
  399. // Dispose all assets in the modelRoot
  400. scene.disposeSceneModels()
  401. // Remove all objects from the modelRoot
  402. scene.clearSceneModels()
  403. // Dispose the scene and all its resources and children
  404. scene.dispose()
  405. // Get bounds of the scene model root
  406. const bounds = scene.getBounds(true, true) // true for precise bounds and ignore invisible
  407. // Add an object to the scene or its model root depending on the options (or just use viewer.addSceneObject)
  408. scene.addObject(object, {addToRoot: false}) // adds to the scene directly when addToRoot is true
  409. // Load an imported model root from the asset importer
  410. scene.loadModelRoot(object)
  411. // notify that something has changed in the scene for re-render
  412. scene.setDirty()
  413. // notify that some object has changed in the scene for scene refresh(like shadow refresh, ground etc) and re-render
  414. scene.refreshScene()
  415. // or
  416. scene.setDirty({refreshScene: true})
  417. // set geometryChanged: false to prevent shadow recompute
  418. scene.refreshScene({geometryChanged: false})
  419. // refresh active near far. (in most cases this is done automatically and need not be called)
  420. scene.refreshActiveNearFar()
  421. ```
  422. [`scene.modelRoot`](https://threepipe.org/docs/classes/RootScene.html#modelRoot) - The root object. All the objects loaded in the viewer are added to this object. And this is exported when exporting the gltf. Everything else like meta or UI objects can be added outside this.
  423. [`scene.backgroundColor`](https://threepipe.org/docs/classes/RootScene.html#backgroundColor) - The background color of the scene. Can be a `Color | null`. This is not the same as `scene.background`. When both backgroundColor and background are set, they are multiplied.
  424. [`scene.background`](https://threepipe.org/docs/classes/RootScene.html#background) - The background of the scene. This is the same as `scene.background` in three.js. This can be a texture or a color or null, but it's preferred to use `scene.backgroundColor` for color, and this for texture, then both can be used together.
  425. [`scene.setBackgroundColor`](https://threepipe.org/docs/classes/RootScene.html#setBackgroundColor) - Set the background color from a string, number or color. Same as setting `backgroundColor` to a new color value.
  426. [`scene.backgroundIntensity`](https://threepipe.org/docs/classes/RootScene.html#backgroundIntensity) - The background intensity of the scene. This is the same as `scene.backgroundIntensity` in three.js.
  427. [`scene.environment`](https://threepipe.org/docs/classes/RootScene.html#environment) - The environment map of the scene. This is the same as `scene.environment` in three.js.
  428. `scene.environment.rotation` - The rotation of the environment map around the y-axis.
  429. [`scene.envMapIntensity`](https://threepipe.org/docs/classes/RootScene.html#envMapIntensity) - The environment intensity of the scene.
  430. [`scene.fixedEnvMapDirection`](https://threepipe.org/docs/classes/RootScene.html#fixedEnvMapDirection) - If `true`, the environment map is rotated according to the camera. This is the same as `scene.fixedEnvMapDirection` in three.js.
  431. [`scene.mainCamera`](https://threepipe.org/docs/classes/RootScene.html#mainCamera) - The main camera used for rendering. This is the same as `scene.mainCamera` in three.js.
  432. [`scene.defaultCamera`](https://threepipe.org/docs/classes/RootScene.html#defaultCamera) - The default camera used for rendering. This is the same as `scene.defaultCamera` in three.js.
  433. [`scene.disposeSceneModels`](https://threepipe.org/docs/classes/RootScene.html#disposeSceneModels) - Disposes all assets in the modelRoot.
  434. [`scene.clearSceneModels`](https://threepipe.org/docs/classes/RootScene.html#clearSceneModels) - Removes all objects from the modelRoot.
  435. [`scene.dispose`](https://threepipe.org/docs/classes/RootScene.html#dispose) - Disposes the scene and all its resources and children.
  436. [`scene.getBounds`](https://threepipe.org/docs/classes/RootScene.html#getBounds) - Gets the bounds of the scene model root. Returns an instance of three.js [Box3](https://threejs.org/docs/#api/en/math/Box3) with min and max bounds according to parameters.
  437. [`scene.addObject`](https://threepipe.org/docs/classes/RootScene.html#addObject) - Adds an object to the scene or its model root depending on the options. If `addToRoot` is `true`, the object is added to the model root, else it is added to the scene directly.
  438. [`scene.setDirty`](https://threepipe.org/docs/classes/RootScene.html#setDirty) - Notifies that something has changed in the scene for re-render.
  439. [`scene.refreshScene`](https://threepipe.org/docs/classes/RootScene.html#refreshScene) - Notifies that some object has changed in the scene for scene refresh(like shadow refresh, ground etc) and re-render. Slower than `setDirty`, as it refreshes shadows, updates bounds, etc.
  440. [`scene.refreshActiveNearFar`](https://threepipe.org/docs/classes/RootScene.html#refreshActiveNearFar) - Refreshes active near far. (in most cases this is done automatically and need not be called)
  441. [`scene.loadModelRoot`](https://threepipe.org/docs/classes/RootScene.html#loadModelRoot) - Loads an imported model root from the asset importer. This is used internally and in most cases, you don't need to call this.
  442. ### Scene Events
  443. RootScene dispatches many events that are useful when writing app logic or plugins
  444. `'sceneUpdate'` - Listen to `refreshScene` called in RootScene. When some object changes.
  445. `'addSceneObject'` - When a new object is added to the scene
  446. `'mainCameraChange'` - When the main camera is changed to some other camera.
  447. `'mainCameraUpdate'` - When some properties in the current main camera has changed.
  448. `'environmentChanged'` - When the environment map changes
  449. `'backgroundChanged'` - When the background map or color changes
  450. `'materialUpdate`' - When a material in the scene has updated. (setDirty called on the material)
  451. `'objectUpdate`' - When a object in the scene has updated. (setDirty called on the object)
  452. `'textureUpdate`' - When a texture in the scene has updated. (setDirty called on the texture)
  453. `'cameraUpdate`' - When a camera in the scene has updated.
  454. (setDirty called on the camera)
  455. `'geometryUpdate`' - When a geometry in the scene has updated.
  456. (setDirty called on the geometry)
  457. `'geometryChanged`' - When a geometry is changed on any mesh
  458. `'materialChanged'` - When a material is changed on any mesh
  459. Check [IObject3DEventTypes](https://threepipe.org/docs/interfaces/IObject3DEventTypes.html) and[ISceneEventTypes](https://threepipe.org/docs/interfaces/ISceneEventTypes.html) for more information.
  460. ## ICamera
  461. Source Code: [src/core/camera/PerspectiveCamera2.ts](https://github.com/repalash/threepipe/blob/master/src/core/camera/PerspectiveCamera2.ts), [src/core/ICamera.ts](https://github.com/repalash/threepipe/blob/master/src/core/ICamera.ts)
  462. API Reference: [PerspectiveCamera2](https://threepipe.org/docs/classes/PerspectiveCamera2.html), [ICamera](https://threepipe.org/docs/interfaces/ICamera.html)
  463. ICamera is an interface for a camera that extends the three.js [Camera](https://threejs.org/docs/#api/en/cameras/Camera).
  464. PerspectiveCamera2 implements the interface,
  465. extending from three.js [PerspectiveCamera](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera) with extra features like target, automatic aspect management, automatic near far management(from RootScene), camera control attachment and hooks(like OrbitControls) and the ability to set as the main camera in the root scene.
  466. ```typescript
  467. import {OrbitControls3} from './OrbitControls3'
  468. const viewer = new ThreeViewer({...})
  469. const camera: PerspectiveCamera2 = viewer.scene.mainCamera
  470. // Set the camera position
  471. camera.position.set(0, 0, 10)
  472. // Set the camera target (where the camera looks at)
  473. camera.target.set(0, 0, 0)
  474. // Set the camera fov
  475. camera.fov = 45
  476. // Set the camera aspect ratio
  477. camera.autoAspect = false // disable automatic aspect management based on the canvas size
  478. camera.aspect = 1
  479. // Set camera near far bounds.
  480. // Near, Far plane will be calculated automatically within these limits
  481. // Try changing these values when encountering z-fighting issues or far-plane clipping
  482. camera.minNearPlane = 0.5 // min near plane
  483. camera.maxFarPlane = 10 // max far plane
  484. // Set a custom camera near far
  485. camera.autoNearFar = false // disable automatic near far management based on the scene bounds
  486. camera.minNearPlane = 0.1 // near plane
  487. camera.maxFarPlane = 1000 // far plane
  488. // this needs to be called to notify the viewer to re-render the scene
  489. // in most cases this is done internally. But calling this does not have much impact
  490. camera.setDirty()
  491. // Check if user can interact with the camera. Also checks if its the main camera.
  492. console.log(camera.canUserInteract)
  493. // Get the camera controls (orbit controls for the default camera)
  494. const controls: OrbitControls3 = camera.controls
  495. // Disable controls
  496. controls.enabled = false
  497. // Change the controls mode
  498. camera.controlsMode = 'none' // this will remove the current controls.
  499. // Register a custom camera controls
  500. camera.setControlsCtor('customOrbit', (camera, domElement) => new CustomOrbitControls(camera, domElement))
  501. // Set the camera controls
  502. camera.controlsMode = 'customOrbit' // this will initialize the controls with the customOrbit constructor and set it on the camera
  503. // Disable interactions to the camera. (eg when animating)
  504. camera.setInteractions(false, 'animation')
  505. // Enable interactions back
  506. camera.setInteractions(true, 'animation') // this will enable interactions when all the keys have been set to true(which were set to false earlier)
  507. // Force refresh aspect ratio (this is done automatically with a ResizeObserver on the canvas in the viewer)
  508. camera.refreshAspect()
  509. // Set the camera as the main camera
  510. camera.activateMain()
  511. // Deactivate the camera as the main camera
  512. camera.deactivateMain()
  513. ```
  514. [`camera.target`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#target) - The target of the camera. This is the same as `controls.target` in three.js. The target is always in world-space coordinates, as opposed to position, rotation, and scale which are always relative to their parent.
  515. [`camera.autoAspect`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#autoAspect) - If `true`, the aspect ratio is automatically calculated based on the canvas size.
  516. [`camera.aspect`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#aspect) - The aspect ratio of the camera. This is the same as `camera.aspect` in three.js. This is only used when `camera.autoAspect` is `false`.
  517. [`camera.minNearPlane`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#minNearPlane) - The minimum near plane of the camera. This is the same as `camera.near` in three.js when `camera.autoNearFar` is `false`, otherwise it is the minimum near plane distance from the camera allowed when computing automatically
  518. [`camera.maxFarPlane`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#maxFarPlane) - The maximum far plane of the camera. This is the same as `camera.far` in three.js when `camera.autoNearFar` is `false`, otherwise it is the maximum far plane distance from the camera allowed when computing automatically
  519. [`camera.autoNearFar`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#autoNearFar) - If `true` (default), the near and far planes are automatically calculated based on the scene bounds.
  520. [`camera.setDirty`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#setDirty) - Notifies that something has changed in the camera for re-render.
  521. [`camera.canUserInteract`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#canUserInteract) - Checks if user can interact with the camera. Also checks if it's the main camera.
  522. [`camera.controls`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#controls) - Get the current camera controls set on the camera. This can be changed by changing `controlsMode`
  523. [`camera.controlsMode`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#controlsMode) - Get or set the current controls that are attached to the camera. More modes can be registered with `setControlsCtor`. Default for the default camera is `orbit` and `none` for any new cameras.
  524. [`camera.setControlsCtor`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#setControlsCtor) - Register a custom camera controls constructor. The controls can be set by setting `controlsMode` to the key/name of the controls.
  525. [`camera.setInteractions`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#setInteractions) - If `true`, the camera can be interacted with. This is useful when animating the camera or using the window scroll or programmatically automating the viewer. Using this multiple plugins can disable interactions and it will be enabled again when all of them enable it back.
  526. [`camera.refreshAspect`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#refreshAspect) - Force refresh aspect ratio (this is done automatically with a ResizeObserver on the canvas in the viewer or when `viewer.resize()` is called)
  527. [`camera.activateMain`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#activateMain) - Set the camera as the main camera. This is the same as doing `scene.mainCamera = camera`. The camera needs to be in the scene hierarchy for this to work.
  528. [`camera.deactivateMain`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#deactivateMain) - Deactivate the camera as the main camera.
  529. See also [CameraViewPlugin](#cameraviewplugin) for camera focus animation.
  530. ::: info Note
  531. The constructor signature of `PerspectiveCamera2` is different `PerspectiveCamera`(from three.js), since it requires the canvas and the controlsMode during creation.
  532. Because of this `PerspectiveCamera0` is provided with the same signature as `PerspectiveCamera` for compatibility, in case the controls functionality is not required.
  533. :::
  534. ## AssetManager
  535. Source Code: [src/assetmanager/AssetManager.ts](https://github.com/repalash/threepipe/blob/master/src/assetmanager/AssetManager.ts)
  536. API Reference: [AssetManager](https://threepipe.org/docs/classes/AssetManager.html)
  537. `AssetManager` is a class that manages the loading and exporting of assets and provides helpers for caching assets. It is used internally in the viewer and can be used to load assets outside the viewer. It provides a modular framework for adding more asset loaders and exporters.
  538. ```typescript
  539. const viewer = new ThreeViewer({...})
  540. const assetManager = viewer.assetManager
  541. // Add an asset or an asset bundle
  542. const assets = await assetManager.addAsset('https://example.com/model.zip')
  543. // or
  544. const assets1 = await assetManager.addAsset({
  545. path: 'https://example.com/model.zip',
  546. file: blob,
  547. })
  548. // Get the storage used in the asset manager for caching
  549. const storage: Cache | Storage = assetManager.storage
  550. // Get the importer. Provides low level functions to import assets
  551. const importer = assetManager.importer
  552. // import a file by asset or url
  553. const file = await importer.import('https://example.com/model.gltf')
  554. // Import a Map<string, File> from drag drop
  555. const res = await importer.importFiles(mapOfFiles, {})
  556. // Register a custom path that maps to a File object. Useful when some file types have path references to other files.
  557. importer.registerFile('/myFile.png', file) // this returns the three.js loader for that kind of file.
  558. // Unregister the path
  559. importer.unregisterFile('/myFile.png')
  560. // Unregister all files and clear the loader cache(memory, not storage)
  561. importer.clearCache()
  562. // Add custom importers (check extra load plugins for more examples)
  563. importer.addImporter(new Importer(class extends PLYLoader implements ILoader {
  564. transform(res: BufferGeometry, _: AnyOptions): Mesh | undefined {
  565. return res ? new Mesh(res, new PhysicalMaterial({color: new Color(1, 1, 1)})) : undefined
  566. }
  567. }, ['ply'], ['text/plain+ply'], false))
  568. // Get the exporter. Provides low level functions to export assets
  569. const exporter = assetManager.exporter
  570. // Export any IObject3D, IMaterial, ITexture, IRenderTarget
  571. const exported = exporter.exportObject(obj, options)
  572. // Add a custom exporter
  573. exporter.addExporter({
  574. ext: ['gltf', 'glb'], // file extensions
  575. extensions: [], // extensions for the exporter
  576. ctor: (assetExporter, iexporter) => {
  577. return new GLTFExporter2()
  578. }
  579. })
  580. // Material Manager
  581. const materialManager = assetManager.materialManager
  582. // Create a material of type
  583. const mat1 = materialManager.create('physical')
  584. const mat2 = materialManager.create('unlit')
  585. // find or create a material by uuid
  586. const mat3 = materialManager.findOrCreate('00000000-0000-0000-0000-000000000000', {color: '#ffffff'})
  587. // find a material creation template
  588. const template = materialManager.findTemplate('physical')
  589. // Get all materials
  590. const materials = materialManager.getAllMaterials()
  591. // Get all materials of type
  592. const materials2 = materialManager.getMaterialsOfType(PhysicalMaterial.TypeSlug)
  593. // register a custom material to the manager for tracking and extensions
  594. // Note all materials created in threepipe internally are registered automatically on creation or when added to any scene object.
  595. materialManager.registerMaterial(customMat)
  596. // unregister
  597. materialManager.unregisterMaterial(customMat)
  598. // clear all material references
  599. materialManager.clearMaterials()
  600. // Register a custom material template
  601. materialManager.registerTemplate({
  602. generator: (params: any) => new PhysicalMaterial(params),
  603. name: 'custom',
  604. materialType: PhysicalMaterial.TYPE,
  605. params: {
  606. color: '#ffffff',
  607. roughness: 0.5,
  608. metalness: 0.5,
  609. },
  610. })
  611. const mat4 = materialManager.create('custom')
  612. // convert a standard three.js material to threepipe material
  613. const mat5 = materialManager.convertToIMaterial(new ShadowMaterial(), {materialTemplate: 'test'})
  614. // register a custom material extension for all materials in the viewer
  615. materialManager.registerMaterialExtension(customExtension)
  616. // unregister
  617. materialManager.unregisterMaterialExtension(customExtension)
  618. // remove all extensions
  619. materialManager.clearExtensions()
  620. // Apply a material properties to other material(s) in the scene by name or uuid
  621. materialManager.applyMaterial(goldMaterial, 'METAL') // this will copy the properties from goldMaterial to all the materials(or objects) in the viewer with the name METAL.
  622. // export a material as JSON. Note: use AssetExporter instead to export all the embedded assets and properties properly.
  623. const blob = materialManager.exportMaterial(mat)
  624. // dispose manager and all materials.
  625. materialManager.dispose()
  626. ```
  627. [`assetManager.addAsset`](https://threepipe.org/docs/classes/AssetManager.html#addAsset) - Add an asset or an asset bundle. Returns a promise that resolves to an array of asset objects. An asset can contain multiple objects, hence an array is returned. Use shorthand `viewer.load(path)` to load a single asset from a single file.
  628. [`assetManager.storage`](https://threepipe.org/docs/classes/AssetManager.html#storage) - Get the storage used in the asset manager for caching. This is the storage that can be passed in the `ThreeViewer` contructor options.
  629. [`assetManager.importer`](https://threepipe.org/docs/classes/AssetManager.html#importer) - Get the importer. Provides low-level functions to import assets. This is an instance of [AssetImporter](https://threepipe.org/docs/classes/AssetImporter.html).
  630. [`assetManager.exporter`](https://threepipe.org/docs/classes/AssetManager.html#exporter) - Get the exporter. Provides low-level functions to export assets. This is an instance of [AssetExporter](https://threepipe.org/docs/classes/AssetExporter.html).
  631. ### AssetImporter
  632. [`importer.import`](https://threepipe.org/docs/classes/AssetImporter.html#import) - Import a file by asset or url. Returns a promise that resolves to a [File](https://threepipe.org/docs/classes/File.html) object.
  633. [`importer.importFiles`](https://threepipe.org/docs/classes/AssetImporter.html#importFiles) - Import a Map<string, File> from drag and drop. Returns a promise that resolves to a Map<string, any[]> of imported object arrays.
  634. [`importer.registerFile`](https://threepipe.org/docs/classes/AssetImporter.html#registerFile) - Register a custom path that maps to a File object. Useful when some file types have path references to other files. Like when importing a .zip with a .gltf file that references a .bin file, or when loading remote files from custom local cache implementation.
  635. [`importer.unregisterFile`](https://threepipe.org/docs/classes/AssetImporter.html#unregisterFile) - Unregister the path.
  636. [`importer.clearCache`](https://threepipe.org/docs/classes/AssetImporter.html#clearCache) - Unregister all the registered files and clear the loader cache(memory cache, not cache-storage).
  637. [`importer.addImporter`](https://threepipe.org/docs/classes/AssetImporter.html#addImporter) - Add custom importers (check extra load plugins for more examples). This allows to pass a class to a ILoader, that is used to import assets. Loaders are only created when a file is being loaded of that type. And they remain in the loader cache until `clearCache` or `clearLoaderCache` is called.
  638. ### AssetExporter
  639. [`exporter.exportObject`](https://threepipe.org/docs/classes/AssetExporter.html#exportObject) - Export any IObject3D, IMaterial, ITexture, IRenderTarget. Returns a promise that resolves to an exported object. Use `viewer.export` or `AssetExporterPlugin`, which provide more features and shortcuts to export viewer, scene and plugins as well.
  640. [`exporter.addExporter`](https://threepipe.org/docs/classes/AssetExporter.html#addExporter) - Add a custom exporter for a custom file type.
  641. ### MaterialManager
  642. [`materialManager.create`](https://threepipe.org/docs/classes/MaterialManager.html#create) - Create a new material of a given type and with passed properties. Returns an implementation of [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  643. [`materialManager.findOrCreate`](https://threepipe.org/docs/classes/MaterialManager.html#findOrCreate) - Find or create a material by uuid. Returns an instance of [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html). If a material with the uuid exists, it is returned, else a new material is created with the passed properties.
  644. [`materialManager.findTemplate`](https://threepipe.org/docs/classes/MaterialManager.html#findTemplate) - Find a material creation template. Returns an instance of [IMaterialTemplate](https://threepipe.org/docs/interfaces/IMaterialTemplate.html). Material templates are used to create materials of a given type with default properties.
  645. [`materialManager.getAllMaterials`](https://threepipe.org/docs/classes/MaterialManager.html#getAllMaterials) - Get all materials registered with the manager.
  646. [`materialManager.getMaterialsOfType`](https://threepipe.org/docs/classes/MaterialManager.html#getMaterialsOfType) - Get all materials of a specific type. Pass in the typeslug from the class like `pmat` or `dmat` to identify the material.
  647. [`materialManager.registerMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#registerMaterial) - Register a new material to the manager for tracking and extensions. Note: all materials created in threepipe internally or any that are set to any object in the scene are registered automatically on creation or when used
  648. [`materialManager.unregisterMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#unregisterMaterial) - Unregister a material from the manager.
  649. [`materialManager.clearMaterials`](https://threepipe.org/docs/classes/MaterialManager.html#clearMaterials) - Clear all registered material references.
  650. [`materialManager.registerTemplate`](https://threepipe.org/docs/classes/MaterialManager.html#registerTemplate) - Register a custom material template. Requires an instance of [IMaterialTemplate](https://threepipe.org/docs/interfaces/IMaterialTemplate.html). Material templates are used to create materials of a given type with default properties.
  651. [`materialManager.convertToIMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#convertToIMaterial) - Convert/upgrade a standard three.js material to threepipe material, by making it conform to [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  652. [`materialManager.registerMaterialExtension`](https://threepipe.org/docs/classes/MaterialManager.html#registerMaterialExtension) - Register a custom material extension for all materials in the viewer. Requires an instance of [IMaterialExtension](https://threepipe.org/docs/interfaces/IMaterialExtension.html). Material extensions are used to add custom properties, methods, uniforms, defines, shader patches etc to predefined materials. The extensions are added to the material when the mateiral or extension is registered to the manager.
  653. [`materialManager.unregisterMaterialExtension`](https://threepipe.org/docs/classes/MaterialManager.html#unregisterMaterialExtension) - Unregister a material extension from the manager.
  654. [`materialManager.clearExtensions`](https://threepipe.org/docs/classes/MaterialManager.html#clearExtensions) - Remove all material extensions from the manager.
  655. [`materialManager.applyMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#applyMaterial) - Apply a material properties to other material(s) in the scene by name or uuid. This is useful when you want to change the properties of all materials with a given name or uuid. This can also be a regex, in that case a regex.match will be performed on the material/object name.
  656. [`materialManager.exportMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#exportMaterial) - Export a material as JSON. Note: use `viewer.export` or `AssetExporter` instead to export all the embedded assets properly.
  657. [`materialManager.dispose`](https://threepipe.org/docs/classes/MaterialManager.html#dispose) - Dispose manager and all materials.
  658. ## Other classes and interfaces
  659. Threepipe provides various interfaces and classes for for three.js objects with upgraded features like UI events, serialization, etc.
  660. These can be used while developing new apps to get better developer experience and features.
  661. When standard three.js instances are added to the scene, they are automatically upgraded automatically at runtime to make them work with the rest of the framework.
  662. Some important interfaces:
  663. * [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html) - Interface for an extended version of three.js [Object3D](https://threejs.org/docs/#api/en/core/Object3D).
  664. * [ILight](https://threepipe.org/docs/interfaces/ILight.html) - Interface for an extended version of three.js [Light](https://threejs.org/docs/#api/en/lights/Light).
  665. * [ICamera](https://threepipe.org/docs/interfaces/ICamera.html) - Interface for an extended version of three.js [Camera](https://threejs.org/docs/#api/en/cameras/Camera).
  666. * [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html) - Interface for an extended version of three.js [Material](https://threejs.org/docs/#api/en/materials/Material).
  667. * [ITexture](https://threepipe.org/docs/interfaces/ITexture.html) - Interface for an extended version of three.js [Texture](https://threejs.org/docs/#api/en/textures/Texture).
  668. * [IRenderTarget](https://threepipe.org/docs/interfaces/IRenderTarget.html) - Interface for an extended version of three.js [WebGLRenderTarget](https://threejs.org/docs/#api/en/renderers/WebGLRenderTarget).
  669. * [IGeometry](https://threepipe.org/docs/interfaces/IGeometry.html) - Interface for an extended version of three.js [BufferGeometry](https://threejs.org/docs/#api/en/core/BufferGeometry).
  670. * [IScene](https://threepipe.org/docs/interfaces/IScene.html) - Interface for an extended version of three.js [Scene](https://threejs.org/docs/#api/en/scenes/Scene).
  671. * [IRenderManager](https://threepipe.org/docs/interfaces/IRenderManager.html) - Interface for rendering and render target manager.
  672. Some important classes
  673. * [Mesh2](https://threepipe.org/docs/classes/Mesh2.html) - Extends three.js [Mesh](https://threejs.org/docs/#api/en/objects/Mesh) and implements [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html).
  674. * [PerspectiveCamera2](https://threepipe.org/docs/classes/PerspectiveCamera2.html) - Extends three.js [PerspectiveCamera](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera) and implements [ICamera](https://threepipe.org/docs/interfaces/ICamera.html). (different constructor than PerspectiveCamera)
  675. * [PerspectiveCamera0](https://threepipe.org/docs/classes/PerspectiveCamera0.html) - Extends three.js [PerspectiveCamera](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera) and implements [ICamera](https://threepipe.org/docs/interfaces/ICamera.html). (same constructor than PerspectiveCamera)
  676. * [BufferGeometry2](https://threepipe.org/docs/classes/BufferGeometry2.html) - Extends three.js [BufferGeometry](https://threejs.org/docs/#api/en/core/BufferGeometry) and implements [IGeometry](https://threepipe.org/docs/interfaces/IGeometry.html).
  677. * [RootScene](https://threepipe.org/docs/classes/RootScene.html) - Extends three.js [Scene](https://threejs.org/docs/#api/en/scenes/Scene) and implements [IScene](https://threepipe.org/docs/interfaces/IScene.html).
  678. * [RenderManager](https://threepipe.org/docs/classes/RenderManager.html) - Implements [IRenderManager](https://threepipe.org/docs/interfaces/IRenderManager.html).
  679. * [PhysicalMaterial](https://threepipe.org/docs/classes/PhysicalMaterial.html) - Extends three.js [MeshPhysicalMaterial](https://threejs.org/docs/#api/en/materials/MeshPhysicalMaterial) and implements [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  680. * [UnlitMaterial](https://threepipe.org/docs/classes/UnlitMaterial.html) - Extends three.js [MeshBasicMaterial](https://threejs.org/docs/#api/en/materials/MeshBasicMaterial) and implements [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  681. * [LineMaterial2](https://threepipe.org/docs/classes/LineMaterial2.html) - Extends three.js [LineMaterial](https://threejs.org/docs/#api/en/materials/LineMaterial) and implements [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  682. * [UnlitLineMaterial](https://threepipe.org/docs/classes/UnlitLineMaterial.html) - Extends three.js [LineBasicMaterial](https://threejs.org/docs/#api/en/materials/LineBasicMaterial) and implements [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  683. * [DirectionalLight2](https://threepipe.org/docs/classes/DirectionalLight2.html) - Extends three.js [DirectionalLight](https://threejs.org/docs/#api/en/lights/DirectionalLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  684. * [SpotLight2](https://threepipe.org/docs/classes/SpotLight2.html) - Extends three.js [SpotLight](https://threejs.org/docs/#api/en/lights/SpotLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  685. * [PointLight2](https://threepipe.org/docs/classes/PointLight2.html) - Extends three.js [PointLight](https://threejs.org/docs/#api/en/lights/PointLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  686. * [HemisphereLight2](https://threepipe.org/docs/classes/HemisphereLight2.html) - Extends three.js [HemisphereLight](https://threejs.org/docs/#api/en/lights/HemisphereLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  687. * [AmbientLight2](https://threepipe.org/docs/classes/AmbientLight2.html) - Extends three.js [AmbientLight](https://threejs.org/docs/#api/en/lights/AmbientLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  688. * [RectAreaLight2](https://threepipe.org/docs/classes/RectAreaLight2.html) - Extends three.js [RectAreaLight](https://threejs.org/docs/#api/en/lights/RectAreaLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).