threepipe
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

3 роки тому
3 роки тому
2 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
3 роки тому
2 роки тому
2 роки тому
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995
  1. # ThreePipe
  2. A new way to work with three.js, 3D models and rendering on the web.
  3. [ThreePipe](https://threepipe.org/) —
  4. [Github](https://github.com/repalash/threepipe) —
  5. [Examples](https://threepipe.org/examples/) —
  6. [API Reference](https://threepipe.org/docs/) —
  7. [WebGi](https://webgi.xyz/docs/)
  8. [![NPM Package](https://img.shields.io/npm/v/threepipe.svg)](https://www.npmjs.com/package/threepipe)
  9. [![Discord Server](https://img.shields.io/discord/956788102473584660?label=Discord&logo=discord)](https://discord.gg/apzU8rUWxY)
  10. [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-green.svg)](https://opensource.org/license/apache-2-0/)
  11. [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/repalash.svg?style=social&label=Follow%20%40repalash)](https://twitter.com/repalash)
  12. ThreePipe is a 3D framework built on top of [three.js](https://threejs.org/) in TypeScript with a focus on rendering quality, modularity, and extensibility.
  13. Key features include:
  14. - Simple, intuitive API for creating 3D model viewers/configurators/editors on web pages, with many built-in presets for common workflows and use-cases.
  15. - Companion [editor](https://threepipe.org/examples/tweakpane-editor/) to create, edit and configure 3D scenes in the browser.
  16. - Modular architecture that allows you to easily extend the viewer, scene objects, materials, shaders, rendering, post-processing and serialization with custom functionality.
  17. - Plugin system along with a rich library of built-in plugins that allows you to easily add new features to the viewer.
  18. - [uiconfig](https://github.com/repalash/uiconfig.js) compatibility to automatically generate configuration UIs in the browser.
  19. - Modular rendering pipeline with built-in deferred rendering, post-processing, RGBM HDR rendering, etc.
  20. - Material extension framework to modify/inject/build custom shader code into existing materials at runtime from plugins.
  21. - Extendable asset import, export and management pipeline with built-in support for gltf, glb, obj+mtl, fbx, materials(pmat/bmat), json, zip, png, jpeg, svg, webp, ktx2, ply, 3dm and many more.
  22. - Automatic serialization of all viewer and plugin settings in GLB(with custom extensions) and JSON formats.
  23. - Automatic disposal of all three.js resources with built-in reference management.
  24. ## Examples
  25. Code samples and demos covering various usecases and test are present in the [examples](./examples/) folder.
  26. Try them: https://threepipe.org/examples/
  27. View the source code by pressing the code button on the top left of the example page.
  28. To make changes and run the example, click on the CodePen button on the top right of the source code.
  29. ## Table of Contents
  30. - [ThreePipe](#threepipe)
  31. - [Examples](https://threepipe.org/examples/)
  32. - [Table of Contents](#table-of-contents)
  33. - [Getting Started](#getting-started)
  34. - [HTML/JS Quickstart (CDN)](#htmljs-quickstart-cdn)
  35. - [NPM/YARN Package](#npmyarn)
  36. - [Installation](#installation)
  37. - [Loading a 3D Model](#loading-a-3d-model)
  38. - [License](#license)
  39. - [Status](#status)
  40. - [Documentation (API Reference)](#documentation)
  41. - [WebGi](#webgi)
  42. - [Contributing](#contributing)
  43. - [Features](#features)
  44. - [File Formats](#file-formats)
  45. - [Loading files](#loading-files)
  46. - [3D models](#3d-models)
  47. - [Materials](#materials)
  48. - [Images/Textures](#imagestextures)
  49. - [zip files](#zip-files)
  50. - [txt, json files](#txt-json-files)
  51. - [Data URLs](#data-urls)
  52. - [Local files, File and Blob](#local-files-file-and-blob)
  53. - [Background, Environment maps](#background-environment-maps)
  54. - [SVG strings](#svg-strings)
  55. - [Exporting files](#exporting-files)
  56. - [Exporting 3D models](#exporting-3d-models)
  57. - [Exporting Materials](#exporting-materials)
  58. - [Exporting Canvas Images](#exporting-canvas-images)
  59. - [Exporting Images/Textures](#exporting-imagestextures)
  60. - [Exporting Render Targets](#exporting-render-targets)
  61. - [Render Pipeline](#render-pipeline)
  62. - [Material Extension](#material-extension)
  63. - [UI Configuration](#ui-configuration)
  64. - [Serialization](#serialization)
  65. - [Plugin System](#plugin-system)
  66. - [Viewer API](#viewer-api)
  67. - [ThreeViewer](#threeviewer)
  68. - [RenderManager](#rendermanager)
  69. - [RootScene](#rootscene)
  70. - [ICamera](#icamera)
  71. - [AssetManager](#assetmanager)
  72. - [AssetImporter](#assetimporter)
  73. - [AssetExporter](#assetexporter)
  74. - [MaterialManager](#materialmanager)
  75. - [Plugins](#threepipe-plugins)
  76. - [TonemapPlugin](#tonemapplugin) - Add tonemap to the final screen pass
  77. - [DropzonePlugin](#dropzoneplugin) - Drag and drop local files to import and load
  78. - [ProgressivePlugin](#progressiveplugin) - Post-render pass to blend the last frame with the current frame
  79. - [DepthBufferPlugin](#depthbufferplugin) - Pre-rendering of depth buffer
  80. - [NormalBufferPlugin](#normalbufferplugin) - Pre-rendering of normal buffer
  81. - [GBufferPlugin](#depthnormalbufferplugin) - Pre-rendering of depth and normal buffers in a single pass buffer
  82. - [PickingPlugin](#pickingplugin) - Adds support for selecting objects in the viewer with user interactions and selection widgets
  83. - [GLTFAnimationPlugin](#gltfanimationplugin) - Add support for playing and seeking gltf animations
  84. - [PopmotionPlugin](#popmotionplugin) - Integrates with popmotion.io library for animation/tweening
  85. - [CameraViewPlugin](#cameraviewplugin) - Add support for saving, loading, animating, looping between camera views
  86. - [RenderTargetPreviewPlugin](#rendertargetpreviewplugin) - Preview any render target in a UI panel over the canvas
  87. - [GeometryUVPreviewPlugin](#geometryuvpreviewplugin) - Preview UVs of any geometry in a UI panel over the canvas
  88. - [FrameFadePlugin](#framefadeplugin) - Post-render pass to smoothly fade to a new rendered frame over time
  89. - [VignettePlugin](#vignetteplugin) - Add Vignette effect by patching the final screen pass
  90. - [ChromaticAberrationPlugin](#chromaticaberrationplugin) - Add Chromatic Aberration effect by patching the final screen pass
  91. - [FilmicGrainPlugin](#filmicgrainplugin) - Add Filmic Grain effect by patching the final screen pass
  92. - [NoiseBumpMaterialPlugin](#noisebumpmaterialplugin) - Sparkle Bump/Noise Bump material extension for PhysicalMaterial
  93. - [CustomBumpMapPlugin](#custombumpmapplugin) - Custom Bump Map material extension for PhysicalMaterial
  94. - [ClearcoatTintPlugin](#clearcoattintplugin) - Clearcoat Tint material extension for PhysicalMaterial
  95. - [FragmentClippingExtensionPlugin](#fragmentclippingextensionplugin) - Fragment/SDF Clipping material extension for PhysicalMaterial
  96. - [HDRiGroundPlugin](#hdrigroundplugin) - Add support for ground projected hdri/skybox to the webgl background shader.
  97. - [VirtualCamerasPlugin](#virtualcamerasplugin) - Add support for rendering virtual cameras before the main one every frame.
  98. - [Rhino3dmLoadPlugin](#rhino3dmloadplugin) - Add support for loading .3dm files
  99. - [PLYLoadPlugin](#plyloadplugin) - Add support for loading .ply files
  100. - [STLLoadPlugin](#stlloadplugin) - Add support for loading .stl files
  101. - [KTX2LoadPlugin](#ktx2loadplugin) - Add support for loading .ktx2 files
  102. - [KTXLoadPlugin](#ktxloadplugin) - Add support for loading .ktx files
  103. - [Packages](#threepipe-packages)
  104. - [@threepipe/plugin-tweakpane](#threepipeplugin-tweakpane) Tweakpane UI Plugin
  105. - [@threepipe/plugin-tweakpane-editor](#threepipeplugin-tweakpane-editor) - Tweakpane Editor Plugin
  106. - [@threepipe/plugin-extra-importers](#threepipeplugin-extra-importers) - Plugin for loading more file types supported by loaders in three.js
  107. - [@threepipe/plugin-blend-importer](#threepipeplugin-blend-importer) - Blender to add support for loading .blend file
  108. ## Getting Started
  109. ### HTML/JS Quickstart (CDN)
  110. ```html
  111. <canvas id="three-canvas" style="width: 800px; height: 600px;"></canvas>
  112. <script type="module">
  113. import {ThreeViewer, DepthBufferPlugin} from 'https://threepipe.org/dist/index.mjs'
  114. const viewer = new ThreeViewer({canvas: document.getElementById('three-canvas')})
  115. // Add some plugins
  116. viewer.addPluginSync(new DepthBufferPlugin())
  117. // Load an environment map
  118. const envPromise = viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr')
  119. const modelPromise = viewer.load('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf', {
  120. autoCenter: true,
  121. autoScale: true,
  122. })
  123. Promise.all([envPromise, modelPromise]).then(([env, model]) => {
  124. console.log('Loaded', model, env, viewer)
  125. })
  126. </script>
  127. ```
  128. Check it in action: https://threepipe.org/examples/#html-sample/
  129. Check out the details about the [ThreeViewer API](#viewer-api) and more [plugins](#threepipe-plugins) below.
  130. ### NPM/YARN
  131. ### Installation
  132. ```bash
  133. npm install threepipe
  134. ```
  135. ### Loading a 3D Model
  136. First, create a canvas element in your HTML page:
  137. ```html
  138. <canvas id="three-canvas" style="width: 800px; height: 600px;"></canvas>
  139. ```
  140. Then, import the viewer and create a new instance:
  141. ```typescript
  142. import {ThreeViewer, IObject3D} from 'threepipe'
  143. // Create a viewer
  144. const viewer = new ThreeViewer({canvas: document.getElementById('three-canvas') as HTMLCanvasElement})
  145. // Load an environment map
  146. await viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr')
  147. // Load a model
  148. const result = await viewer.load<IObject3D>('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf', {
  149. autoCenter: true,
  150. autoScale: true,
  151. })
  152. ```
  153. That's it! You should now see a 3D model on your page.
  154. The 3D model can be opened in the [editor](TODO) to view and edit the scene settings, objects, materials, lights, cameras, post-processing, etc. and exported as a GLB file. All settings are automatically serialized and saved in the GLB file, which can be loaded into the viewer. Any plugins used in the editor can be added to the viewer to add the same functionality. The plugin data is automatically loaded(if the plugin is added) when the model is added to the scene.
  155. The viewer initializes with a Scene, Camera, Camera controls(Orbit Controls), several importers, exporters and a default rendering pipeline. Additional functionality can be added with plugins.
  156. Check out the GLTF Load example to see it in action or to check the JS equivalent code: https://threepipe.org/examples/#gltf-load/
  157. Check out the [Plugins](#plugins) section below to learn how to add additional functionality to the viewer.
  158. ## License
  159. The core framework([src](https://github.com/repalash/threepipe/tree/master/src), [dist](https://github.com/repalash/threepipe/tree/master/dist), [examples](https://github.com/repalash/threepipe/tree/master/examples) folders) and any [plugins](https://github.com/repalash/threepipe/tree/master/plugins) without a separate license are under the Free [Apache 2.0 license](https://github.com/repalash/threepipe/tree/master/LICENSE).
  160. Some plugins(in the [plugins](https://github.com/repalash/threepipe/tree/master/plugins) folder) might have different licenses. Check the individual plugin documentation and the source folder/files for more details.
  161. ## Status
  162. The project is in `alpha` stage and under active development. Many features will be added but the core API will not change significantly in future releases.
  163. Check out [WebGi](https://webgi.xyz/) for an advanced tailor-made solution for e-commerce, jewelry, automobile, apparel, furniture etc.
  164. ## Documentation
  165. Check the list of all functions, classes and types in the [API Reference Docs](https://threepipe.org/docs/).
  166. ## WebGi
  167. Check out WebGi - Premium Photo-realistic 3D rendering framework and tools for web applications and online commerce along with custom modules and rendering solutions for e-commerce, jewelry, automobile, apparel, furniture and other retail applications.
  168. [Homepage](https://webgi.xyz/) &mdash; [Docs](https://webgi.xyz/docs/)
  169. [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/repalash.svg?style=social&label=Follow%20%40pixotronics)](https://twitter.com/pixotronics)
  170. ## Contributing
  171. Contributions to ThreePipe are welcome and encouraged! Feel free to open issues and pull requests on the GitHub repository.
  172. # Features
  173. ## File Formats
  174. ThreePipe Asset Manager supports the import of the following file formats out of the box:
  175. * **Models**: gltf, glb, obj+mtl, fbx, drc
  176. * **Materials**: mat, pmat, bmat (json based), registered material template slugs
  177. * **Images**: webp, png, jpeg, jpg, svg, ico, avif, hdr, exr
  178. * **Misc**: json, vjson, zip, txt
  179. Plugins can add additional formats:
  180. * Models
  181. * 3dm - Using [Rhino3dmLoadPlugin](#Rhino3dmLoadPlugin)
  182. * ply - Using [PLYLoadPlugin](#PLYLoadPlugin)
  183. * usdz - Using [USDZLoadPlugin](#USDZLoadPlugin)
  184. * stl - Using [STLLoadPlugin](#STLLoadPlugin)
  185. * ktx - Using [KTXLoadPlugin](#KTXLoadPlugin)
  186. * ktx2 - Using [KTX2LoadPlugin](#KTX2LoadPlugin)
  187. Plugins to support more model formats are available in the package [@threepipe/plugin-extra-importers](#threepipeplugin-extra-importers) including .3ds,
  188. .3mf, .collada, .amf, .bvh, .vox, .gcode, .mdd, .pcd, .tilt, .wrl, .mpd, .vtk, .xyz
  189. ## Loading files
  190. ThreePipe uses the [AssetManager](https://threepipe.org/docs/classes/AssetManager.html) to load files.
  191. The AssetManager has support for loading files from URLs, local files and data URLs.
  192. 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.
  193. [viewer.load()](https://threepipe.org/docs/classes/ThreeViewer.html#load) is a high-level wrapper for loading files from the AssetManager.
  194. It automatically adds the loaded object to the scene and returns a promise that resolves to the loaded object,
  195. the materials are also automatically registered to the material manager.
  196. AssetManager internally uses [AssetImporter](https://threepipe.org/docs/classes/AssetImporter.html),
  197. which provides a low-level API
  198. for managing three.js [LoadingManager](https://threejs.org/docs/#api/en/loaders/LoadingManager)
  199. and adding and registering loaders for different file types.
  200. 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
  201. to import files from the `AssetImporter`.
  202. viewer.assetManager.loadImported()](https://threepipe.org/docs/classes/AssetManager.html#loadImported)
  203. can then be called to load the imported files after any processing.
  204. The `viewer.load()`, `viewer.assetManager.addAsset()`
  205. and `viewer.assetManager.addAssetSingle()` methods perform combination of `import` and `loadImported`.
  206. ### 3D models
  207. The 3d models are added to `viewer.scene.modelRoot` on `viewer.load` unless some option is specified.
  208. ```typescript
  209. const objectGlb = await viewer.load<IObject3D>('https://example.com/file.glb')
  210. const objectFbx = await viewer.load<IObject3D>('https://example.com/file.fbx')
  211. const objectObj = await viewer.load<IObject3D>('https://example.com/file.obj') // .mtl referenced in obj is automatically loaded
  212. // ... load any 3d model file as an object
  213. ```
  214. Here, we are casting to [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html) type
  215. to get the proper type and autocomplete for the object.
  216. `IObject3D` inherits [Object3D](https://threejs.org/docs/#api/en/core/Object3D) from three.js and adds some additional properties.
  217. For JavaScript, the type can be omitted.
  218. ```javascript
  219. const objectGlb = await viewer.load('https://example.com/file.glb')
  220. ```
  221. 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.
  222. ### Materials
  223. The materials downloaded as PMAT/BMAT/JSON etc from threepipe,
  224. webgi or the editor can be loaded
  225. and registered with the [MaterialManager](https://threepipe.org/docs/classes/MaterialManager)
  226. using the `viewer.load` method.
  227. Custom material types can also be registered by plugins(like dmat for diamonds), which can also be loaded automatically using the `viewer.load` method.
  228. ```typescript
  229. const pMaterial = await viewer.load<PhysicalMaterial>('https://example.com/file.pmat')
  230. const bMaterial = await viewer.load<UnlitMaterial>('https://example.com/file.bmat')
  231. // ... load any material file as a material
  232. ```
  233. 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.
  234. To assign the material on any object, set it to `object.material`
  235. ```typescript
  236. // find a loaded mesh in the scene
  237. const object = viewer.scene.getObjectByName('objectName');
  238. // assign the material
  239. object.material = pMaterial;
  240. ```
  241. To copy the properties without changing the material reference, use `material.copy()` or `material.setValues()` methods.
  242. ```typescript
  243. object.material.copy(pMaterial);
  244. // or use material manager to apply to multiple materials.
  245. viewer.assetManager.materialManager.applyMaterial(pMaterial, 'METAL') // apply props to all materials/objects with the name METAL
  246. ```
  247. TODO: add examples for material load and copy
  248. ### Images/Textures
  249. Images can be loaded using the `viewer.load` method.
  250. 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.
  251. More formats like ktx2, ktx, etc. can be added using plugins.
  252. ```typescript
  253. const texture = await viewer.load<ITexture>('https://example.com/file.png')
  254. // ... load any image file as a texture
  255. ```
  256. Casting to [ITexture](https://threepipe.org/docs/interfaces/ITexture.html) is optional
  257. but recommended to get the proper type and autocomplete for the texture.
  258. It inherits from three.js [Texture](https://threejs.org/docs/#api/en/textures/Texture) and adds some additional properties.
  259. To assign the texture on any material, set it to `material.map`
  260. ```typescript
  261. // find a loaded mesh in the scene
  262. const object = viewer.scene.getObjectByName('objectName');
  263. const material = object.material as PhysicalMaterial;
  264. // assign the texture
  265. material.map = texture;
  266. 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.
  267. ```
  268. Check out the image load example to see it in action or to check the JS equivalent code: https://threepipe.org/examples/#image-load/
  269. ### Zip files
  270. .zip files are automatically unzipped and the files are sent to re-load recursively when loaded with `viewer.load`.
  271. Any level of zip hierarchy is flattened.
  272. Loading files like .gltf with references to assets inside the zip file,
  273. any relative references are also automatically resolved.
  274. This is supported for file types like gltf, glb, obj,
  275. etc which support references to external files and has `root` set to `true in [IImporter](https://threepipe.org/docs/interfaces/IImporter.html).
  276. ```typescript
  277. const objectGltf = await viewer.load<IObject3D>('https://example.com/model.gltf.zip')
  278. ```
  279. 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.
  280. 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.
  281. ```typescript
  282. const textures = await viewer.assetManager.addAsset<ITexture[]>('https://example.com/textures.zip')
  283. const materials = await viewer.assetManager.addAsset<IMaterial[]>('https://example.com/materials.zip')
  284. ```
  285. The auto import of zip contents can be disabled to get the files and blobs in the zip
  286. ```typescript
  287. const zip = await viewer.load<any>('https://example.com/file.zip', {autoImportZipContents: false})
  288. ```
  289. TODO - add example for loading zip files.
  290. ### txt, json files
  291. Text and JSON files can be loaded using the `viewer.load` method and return strings and objects respectively.
  292. ```typescript
  293. const text = await viewer.load<string>('https://example.com/file.txt')
  294. const json = await viewer.load<any>('https://example.com/file.json')
  295. ```
  296. ### Data URLs
  297. 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.
  298. ```typescript
  299. const dataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' // ... some data url
  300. const texture = await viewer.load<ITexture>(dataUrl)
  301. ```
  302. ### Local files, File and Blob
  303. 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.
  304. ```typescript
  305. const file: File|Blob = fileObject // create a new file, blob or get from input element
  306. const text = await viewer.load<IObject>({
  307. // a path/name is required to determine the proper importer by extension. `file.name` can also be used if available
  308. path: 'file.glb',
  309. file
  310. })
  311. ```
  312. The same can be done for any file type.
  313. 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.
  314. ### Background, Environment maps
  315. 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.
  316. ```typescript
  317. await viewer.setEnvironmentMap('https://example.com/file.hdr')
  318. await viewer.setBackgroundMap('https://example.com/file.png')
  319. ```
  320. The same texture can be set to both by setting `setBackground` or `setEnvironment` to true in the options:
  321. ```typescript
  322. await viewer.setEnvironmentMap('https://example.com/file.hdr', {setBackground: true})
  323. ```
  324. Check the HDR Load example to see it in action: https://threepipe.org/examples/#hdr-load/
  325. ### SVG strings
  326. SVG strings can be converted to data urls using the [svgUrl](https://repalash.com/ts-browser-helpers/functions/svgUrl.html) string template function
  327. ```typescript
  328. const svgDataUrl = svgUrl`<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> ... </svg>`;
  329. const texture = await viewer.load<ITexture>(dataUrl)
  330. ```
  331. ### Custom file types
  332. Custom file importers/loaders can be registered to the `AssetImporter` using the `addImporter` method.
  333. ```typescript
  334. class CustomLoader extends FileLoader implements ILoader{
  335. constructor(manager?: LoadingManager) {
  336. super(manager);
  337. }
  338. load(url: string, onLoad: (data: any) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): Mesh {
  339. this.setResponseType('json')
  340. return super.load(url, (json: any)=>{
  341. const mat = new PhysicalMaterial(json)
  342. onLoad?.(mat)
  343. }, onProgress, onError)
  344. }
  345. }
  346. viewer.assetManager.importer.addImporter(new Importer(CustomLoader, ['ext'], ['mime/type'], false))
  347. // load the file
  348. const mat = await viewer.load<PhysicalMaterial>('https://example.com/file.ext')
  349. ```
  350. ## Exporting files
  351. Threepipe has support for exporting various asset type with AssetManager,
  352. as well as support to export viewer and plugin configuration, arbitrary objects etc using the [serialization](#serialization) system.
  353. [viewer.export()](https://threepipe.org/docs/classes/ThreeViewer.html#export) is a high-level wrapper for exporting scene objects, materials, textures, render targets, viewer/scene configuration and plugin configurations.
  354. AssetManager internally uses [AssetExporter](https://threepipe.org/docs/classes/AssetExporter.html) to export files.
  355. AssetExporter includes some basic exporters for glb, exr, textures,
  356. and materials and a system to register exporters for different file types with plugins or custom exporters.
  357. ### Exporting 3D models
  358. Export the root scene as glb
  359. ```typescript
  360. const blob = await viewer.exportScene({
  361. viewerConfig: true, // default = true. export all viewer and plugin configuration. if false only the model root object is exported.
  362. })
  363. // download the file
  364. downloadBlob(blob, 'scene.glb')
  365. ```
  366. Export a single object from the scene as glb
  367. ```typescript
  368. const object = viewer.scene.getObjectByName('objectName');
  369. const glb: Blob = await viewer.export(object, {
  370. exportExt: 'glb', // default = glb for models
  371. embedUrlImages: true, // default = false. embed images in glb even when url is available.
  372. })
  373. // download the file
  374. downloadBlob(glb, 'object.glb')
  375. ```
  376. Check the example [glb-export](https://threepipe.org/examples/#glb-export/) to see a demo.
  377. ### Exporting Materials
  378. Export a material
  379. ```typescript
  380. const material = viewer.assetManager.materialManager.findMaterialsByName('materialName')[0];
  381. // or
  382. // const material = viewer.scene.getObjectByName('objectName').material;
  383. const blob = await viewer.export(material)
  384. // download the file
  385. downloadBlob(blob, 'material.' + blob.ext)
  386. ```
  387. Check the example [pmat-material-export](https://threepipe.org/examples/#pmat-material-export/) to see a demo.
  388. ### Exporting Canvas Images
  389. Canvas Screenshot/snapshot can be exported as png, jpeg or webp(if supported by the browser)
  390. ```typescript
  391. const blob = await viewer.getScreenshotBlob({mimeType: 'image/' + type, quality: 0.85})
  392. // or to get data url:
  393. // const dataUrl = await viewer.getScreenshotDataUrl({mimeType: 'image/' + type, quality: 0.85})
  394. // download the file
  395. downloadBlob(blob, 'screenshot.' + blob.ext)
  396. ```
  397. Check the example [image-snapshot-export](https://threepipe.org/examples/#image-snapshot-export/) to see a demo.
  398. ### Exporting Textures
  399. Textures can be exported to JSON using `viewer.export` or `AssetExporter`
  400. ```typescript
  401. const texture = await viewer.load('https://example.com/file.jpeg')
  402. const blob = await viewer.export(texture)
  403. downloadBlob(blob, texture.name + '.' + blob.ext)
  404. ```
  405. Render target textures can be exported with `viewer.renderManager.exportRenderTarget` or `viewer.export`,
  406. read about [Exporting Render Targets](#exporting-render-targets) below.
  407. TODO: add examples for texture export
  408. Textures and Uint8 Data Textures can be exported as a data url or copied to a new canvas
  409. ```typescript
  410. // get a base64 data url
  411. const dataUrl = textureToDataUrl(texture, 4096, false, 'image/png') // texture or data texture, max-size, flipY, mimeType
  412. // or copy to a new canvas
  413. const canvas = textureToCanvas(texture, 4096) // texture or data texture, max-size
  414. ```
  415. Data Textures of type Half float and Float can be exported with `viewer.export`
  416. ```typescript
  417. const dataTex = await viewer.load('https://example.com/file.hdr')
  418. const blob = await viewer.export(dataTexture, {exportExt: 'exr'})
  419. ```
  420. Check the example [hdr-to-exr](https://threepipe.org/examples/#hdr-to-exr/) to see a demo of HDR to EXR conversion.
  421. TODO: add support to export unsigned byte textures as png, jpeg, webp
  422. ### Exporting Images
  423. Exporting Textures as Images with image of types ImageBitmap, HTMLImageElement,
  424. HTMLOrSVGImageElement, CanvasImageSource, HTMLCanvasElement,
  425. OffscreenCanvas can be exported to png data urls with [imageBitmapToBase64](https://repalash.com/ts-browser-helpers/functions/imageBitmapToBase64.html) function.
  426. ```typescript
  427. const texture = await viewer.load('https://example.com/file.jpeg')
  428. const dataUrl = await imageBitmapToBase64(texture.image, 'image/png', 0.85);
  429. ```
  430. TODO: add support for texture export as images in AssetExporter
  431. ### Exporting Render Targets
  432. Unsigned byte render targets can be exported as png, jpeg or webp(if supported by the browser)
  433. ```typescript
  434. const depthPlugin = viewer.addPluginSync(DepthBufferPlugin, UnsignedByteType)
  435. // wait for the first render
  436. const blob = await viewer.export(depthPlugin.target!, {exportExt: 'png'})
  437. if (blob) downloadBlob(blob, target.texture.name + '.' + blob.ext)
  438. ```
  439. Half float and float render targets can be exported as exr
  440. ```typescript
  441. const depthPlugin = viewer.addPluginSync(DepthBufferPlugin, HalfFloatType)
  442. // wait for the first render
  443. const blob = await viewer.export(depthPlugin.target!, {exportExt: 'exr'})
  444. if (blob) downloadBlob(blob, target.texture.name + '.' + blob.ext)
  445. ```
  446. Note: `exportExt` is determined automatically if not specified.
  447. ## Render pipeline
  448. Threepipe includes a [RenderManager](https://threepipe.org/docs/classes/RenderManager.html) for managing the composition pipeline, and provides helpers for rendering and render target management.
  449. The RenderManager includes a [EffectComposer](https://threejs.org/docs/#api/en/postprocessing/EffectComposer) from three.js for rendering passes and a [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer) for rendering,
  450. but the pass management and sorting is managed by the RenderManager itself.
  451. The RenderManager inherits from [RenderTargetManager](https://threepipe.org/docs/classes/RenderTargetManager.html)
  452. which provides utilities for creating, tracking and destroying dedicated and temporary render targets.
  453. ### Render Targets
  454. Render targets can be created
  455. using the `viewer.renderManager.createTarget` and `viewer.renderManager.createTargetCustom` methods.
  456. These can then be disposed using the `viewer.renderManager.disposeTarget` method when not needed anymore.
  457. Or to create temp targets for one time use `viewer.renderManager.getTempTarget` and `viewer.renderManager.releaseTempTarget` methods.
  458. can be used.
  459. All created render targets are tracked in the RenderManager,
  460. and are resized and disposed automatically when needed along with the viewer.
  461. ```typescript
  462. const newTarget = viewer.renderManager.createTarget({sizeMultiplier: 1})
  463. // or
  464. const newTarget2 = viewer.renderManager.createTarget({size: {
  465. width: 1024,
  466. height: 1024,
  467. },
  468. type: HalfFloatType
  469. })
  470. // or clone an existing target
  471. const newTarget3 = viewer.renderManager.composerTarget.clone()
  472. // for multi-sample render target
  473. const newTarget4 = viewer.renderManager.createTarget({sizeMultiplier: 1, samples: 4})
  474. // or create a custom target
  475. const newTarget5 = viewer.renderManager.createTargetCustom(
  476. {width: 1024, height: 1024},
  477. {type: HalfFloatType},
  478. WebGLCubeRenderTarget
  479. )
  480. // dispose targets
  481. viewer.renderManager.disposeTarget(newTarget)
  482. viewer.renderManager.disposeTarget(newTarget2)
  483. viewer.renderManager.disposeTarget(newTarget3)
  484. viewer.renderManager.disposeTarget(newTarget4)
  485. viewer.renderManager.disposeTarget(newTarget5)
  486. // get a temporary target
  487. const tempTarget = viewer.renderManager.getTempTarget({sizeMultiplier: 1})
  488. // release the temporary target
  489. viewer.renderManager.releaseTempTarget(tempTarget)
  490. ```
  491. Note: Render targets created with a sizeMultiplier are automatically resized when the canvas is resized.
  492. ### Passes
  493. By default, the render pipeline includes 2 passes -
  494. [RenderPass](https://threejs.org/docs/#api/en/postprocessing/RenderPass) for rendering the scene hierarchy and [ScreenPass](https://threejs.org/docs/#api/en/postprocessing/ShaderPass)
  495. for rendering the final output on the canvas.
  496. More passes can be added and removed from the pipeline
  497. using the [registerPass](https://threepipe.org/docs/classes/RenderManager.html#registerPass) and [unregisterPass](https://threepipe.org/docs/classes/RenderManager.html#unregisterPass) methods.
  498. The pipeline passes need
  499. to follow the interface of [IPipelinePass](https://threepipe.org/docs/interfaces/IPipelinePass.html) and [IPipelinePassPlugin](https://threepipe.org/docs/interfaces/IPipelinePassPlugin.html).
  500. Which adds some important parameters over the three.js Pass,
  501. like pass id and support for defining where the pass should be added in the pipeline and it's dependants.
  502. ```typescript
  503. const pass = new GBufferRenderPass('customPass', viewer.renderManager.createTarget({sizeMultiplier: 1}))
  504. pass.before = ['render'] // Add the pass before the render pass
  505. pass.after = [] // Add the pass after these passes (none in this case)
  506. pass.required = ['render'] // render pass is required to be in the pipeline for this
  507. viewer.renderManager.registerPass(pass)
  508. ```
  509. Note:
  510. See [PipelinePassPlugin](https://threepipe.org/docs/classes/PipelinePassPlugin.html) for an abstract plugin
  511. that provides the boilerplate to create a plugin that registers a custom pass in the pipeline.
  512. Check [NormalBufferPlugin](https://threepipe.org/docs/classes/NormalBufferPlugin.html) for an example of that.
  513. Note: All effects in post-processing or material extension need not be a separate pass in the pipeline.
  514. Most effects can be achieved with either extending the scene object material shaders or the Screen Pass material shader
  515. using [Material extension](#material-extension) system
  516. ## Material Extension
  517. Threepipe includes a Material extension system along with a material manager.
  518. The material manager is used to register materials and material extensions.
  519. The material extensions are used to extend any material in the scene,
  520. or any plugin/pass with additional uniforms, defines, shader snippets and provides hooks.
  521. The material extensions are automatically applied to all materials in the scene that are compatible,
  522. when the extension is registered or when the material is added to the scene.
  523. Threepipe includes several built-in materials like
  524. [PhysicalMaterial](https://threepipe.org/docs/classes/PhysicalMaterial.html),
  525. [UnlitMaterial](https://threepipe.org/docs/classes/UnlitMaterial.html),
  526. [ExtendedShaderMaterial](https://threepipe.org/docs/classes/ExtendedShaderMaterial.html), [LegacyPhongMaterial](https://threepipe.org/docs/classes/LegacyPhongMaterial.html),
  527. that include support for extending the material.
  528. Any three.js material can be made extendable,
  529. check the `ShaderPass2` class for a simple example that adds support for material extension to three.js ShaderPass.
  530. The material extensions must follow the [MaterialExtension](https://threepipe.org/docs/interfaces/MaterialExtension.html) interface.
  531. Many plugins create their own material extensions either for the scene materials or shader passes(like the screen pass).
  532. Some plugins like `DepthBufferPlugin` also provides helper material extensions for other custom plugins
  533. to fetch value in the depth buffer.
  534. A sample material extension
  535. ```typescript
  536. const extension: MaterialExtension = {
  537. shaderExtender: (shader)=> {
  538. // change the shader properties like shader.fragmentShader, etc
  539. },
  540. parsFragmentSnippet: ` // add some code before the main function in the fragment shader
  541. uniform sampler2D tTexture;
  542. uniform float opacity;
  543. `,
  544. extraUniforms: {
  545. tTexture: ()=>({value: getTexture()}),
  546. opacity: {value: 1}
  547. // add additional uniforms, these can be IUniform or functions that return IUniform
  548. },
  549. extraDefines: {
  550. ['DEPTH_PACKING']: BasicDepthPacking,
  551. ['SOME_DEFINE']: ()=>"1",
  552. // add additional defines, these can be values or functions that return values
  553. },
  554. priority: 100, // priority when using multiple extensions on the same material
  555. isCompatible: (material) => material.isMeshBasicMaterial, // check if the material is compatible with this extension,
  556. computeCacheKey: (material) => material.uuid, // a custom cache key for the material extension. Shader is recompiled when this is changed
  557. onObjectRender: (object: Object3D, material: IMaterial) => {
  558. // called when some object is rendererd which has a material with this extension.
  559. },
  560. // uiConfig
  561. // check more properties and hooks in the MaterialExtension interface
  562. }
  563. // The extension can be registered to all the materials using the MaterialManager
  564. viewer.assetManager.materialManager.registerMaterialExtension(extension)
  565. // or register it on a single material (like the Screen Pass)
  566. viewer.renderManager.screenPass.material.registerMaterialExtensions([extension])
  567. ```
  568. ## UI Configuration
  569. Most of the classes and plugins in Threepipe include [uiconfig.js](https://repalash.com/uiconfig.js/) support
  570. and can be used to create configuration UIs, 3d configurators and even full-editors.
  571. The UIs are automatically generated based on the configuration object under `.uiConfig` property on all objects.
  572. These are of type [UiObjectConfig](https://repalash.com/uiconfig.js/interfaces/UiObjectConfig.html).
  573. In some classes, the ui configs are also generated using typescript decorators.
  574. The `uiConfig` is also added to all three.js objects and materials when they are added to the scene.
  575. The UIs can be generated at runtime using any of the UI plugins like [TweakpaneUIPlugin](#threepipeplugin-tweakpane).
  576. An example showing how to create a UI for a material
  577. ```typescript
  578. const ui = viewer.addPluginSync(TweakpaneUiPlugin)
  579. const object = viewer.scene.getObjectByName('objectName');
  580. const material = object.material as PhysicalMaterial;
  581. ui.appendChild(material.uiConfig)
  582. ```
  583. See it in action: https://threepipe.org/examples/#material-uiconfig/
  584. Check more examples showing [Viewer UI](https://threepipe.org/examples/#viewer-uiconfig/),
  585. [Scene UI](https://threepipe.org/examples/#scene-uiconfig/),
  586. [Object UI](https://threepipe.org/examples/#object-uiconfig/), [Camera UI](https://threepipe.org/examples/#camera-uiconfig/)
  587. [TweakpaneEditorPlugin](#threepipeplugin-tweakpane-editor) further uses the Tweakpane configuration panel along with various plugins to create an 3d editor.
  588. Custom UI configuration can be created to generate custom UI for the editor or tweaking.
  589. This can be done by using typescript decorators or defining the UI in javascript as a [UiObjectConfig](https://repalash.com/uiconfig.js/interfaces/UiObjectConfig.html) object.
  590. Here is a sample of extending the orbit controls class with decorators to automatically generate UI.
  591. ```typescript
  592. @uiPanelContainer('Orbit Controls')
  593. export class OrbitControlsWithUi extends OrbitControls implements IUiConfigContainer {
  594. // for autocomplete
  595. uiConfig?: UiObjectConfig<void, 'panel'>
  596. @uiToggle() enabled = true
  597. @uiToggle() dollyZoom = false
  598. @uiToggle() enableDamping = true
  599. @uiInput() dampingFactor = 0.08
  600. @uiToggle() autoRotate = false
  601. @uiInput() autoRotateSpeed = 2.0
  602. @uiToggle() enableZoom = true
  603. @uiInput() zoomSpeed = 0.15
  604. @uiInput() maxZoomSpeed = 0.20
  605. @uiToggle() enableRotate = true
  606. @uiInput() rotateSpeed = 2.0
  607. @uiToggle() enablePan = true
  608. @uiInput() panSpeed = 1.0
  609. @uiInput() autoPushTarget = false
  610. @uiInput() autoPullTarget = false
  611. @uiInput() minDistance = 0.35
  612. @uiInput() maxDistance = 1000
  613. @uiInput() minZoom = 0.01
  614. @uiInput() maxZoom = 1000
  615. @uiInput() minPolarAngle = 0
  616. @uiInput() maxPolarAngle = Math.PI
  617. @uiInput() minAzimuthAngle = -10000 // should be -Infinity but this breaks the UI
  618. @uiInput() maxAzimuthAngle = 10000
  619. }
  620. ```
  621. Check out the full source code:
  622. [./src/three/controls/OrbitControls3.ts](./src/three/controls/OrbitControls3.ts) for proper implementation
  623. See it in action: https://threepipe.org/examples/#camera-uiconfig/ Open the Camera UI and click on the Orbit Controls panel.
  624. There are many available decorators like `uiToggle`, `uiSlider`, `uiInput`, `uiNumber`, `uiColor`, `uiImage`.
  625. Check the complete list in the [uiconfig.js documentation](https://repalash.com/uiconfig.js/).
  626. The UI configuration can also be created using json objects in both typescript and javascript
  627. ```javascript
  628. const viewer = new ThreeViewer({...})
  629. const ui = viewer.addPluginSync(TweakpaneUiPlugin)
  630. const state = {
  631. position: new Vector3(),
  632. scale: 1,
  633. }
  634. ui.appendChild({
  635. type: 'folder',
  636. label: 'Custom UI',
  637. children: [
  638. {
  639. type: 'vec3',
  640. label: 'Position',
  641. property: [state, 'position']
  642. },
  643. {
  644. type: 'slider',
  645. label: ()=>'Scale', // everything can be a function as well.
  646. property: [state, 'scale'],
  647. bounds: [1, 2],
  648. stepSize: 0.1,
  649. }
  650. ]
  651. })
  652. ```
  653. TODO: create example/codepen for this
  654. ## Serialization
  655. Easy serialization of all threepipe and most three.js objects are supported out of the box using the Asset Manager.
  656. Fine control over serialization is also supported
  657. using the [ThreeSerialization](https://threepipe.org/docs/classes/ThreeSerialization.html) class
  658. Call `ThreeSerialization.serialize` on any object to serialize it.
  659. and `ThreeSerialization.deserialize` to deserialize the serialized object.
  660. This is done by performing a nested serialization of all the properties of the object.
  661. It's possible to implement custom serializers for custom types and classes and is done for three.js primitives,
  662. objects and plugins in threepipe
  663. To make a custom data class that is serializable,
  664. mark it using `@serializable` decorator and any properties using `@serialize` decorator.
  665. ```typescript
  666. @serializable('DataClass')
  667. class DataClass{
  668. @serialize() prop1 = 1
  669. @serialize() prop2 = 'string'
  670. @serialize() prop3 = new Vector3()
  671. @serialize() prop4 = new PhysicalMaterial()
  672. @serialize() prop4 = {
  673. prop1: 1,
  674. prop2: 'string',
  675. prop3: new Vector3(),
  676. prop4: new PhysicalMaterial(),
  677. }
  678. }
  679. const data = new DataClass()
  680. const serialized = ThreeSerialization.serialize(data)
  681. const deserialized = ThreeSerialization.deserialize(serialized)
  682. ```
  683. The classes without a `@serializable` decorator are serialized as plain objects.
  684. These can still include `@serialize` decorator to mark the properties are serializable
  685. but these classes cannot be deserialized into a new instance of the class.
  686. The ThreeViewer and plugins are an example of these.
  687. When deserialized they need an object to deserialize into.
  688. This ensures there is always just one instance.
  689. With this, the serialization system works like `toJSON` and `fromJSON` methods in three.js.
  690. Check the [plugin system](#plugin-system) below for more details on how to mark properties as serializable for plugins.
  691. ```typescript
  692. class CustomClass{
  693. @serialize() prop1 = 1
  694. @serialize() prop2 = 'string'
  695. @serialize() prop3 = new Vector3()
  696. @serialize() prop4 = new PhysicalMaterial()
  697. }
  698. const obj = new DataClass()
  699. const serialized = ThreeSerialization.serialize(data)
  700. // now to deserialize we need to pass in the object to deserialize into
  701. ThreeSerialization.deserialize(serialized, obj)
  702. ```
  703. ## Plugin System
  704. Threepipe includes a plugin system for adding additional features to the viewer in a modular way.
  705. The plugins can be added synchronously or asynchronously using `viewer.addPluginSync` and `viewer.addPlugin` methods respectively.
  706. It is recommended to create custom plugins for reusable features,
  707. as they provide built-in features for ui configuration,
  708. serialization, integration with editors etc and are easy to manage and tree-shake in the code.
  709. Check out the list of plugins in the [Plugin List](#threepipe-plugins) section below.
  710. To create new plugins,
  711. simply implement the `IViewerPlugin` interface or extend the [AViewerPluginSync](https://threepipe.org/docs/classes/AViewerPluginSync.html) or [AViewerPluginAsync](https://threepipe.org/docs/classes/AViewerPluginAsync.html) classes.
  712. The only difference is that in async the `onAdded` and `onRemove` functions are async
  713. Here is a sample plugin
  714. ```typescript
  715. @uiFolder("Sample Plugin") // This creates a folder in the Ui. (Supported by TweakpaneUiPlugin)
  716. export class SamplePlugin extends AViewerPluginSync<"sample-1" | "sample-2"> {
  717. // These are the list of events that this plugin can dispatch.
  718. static readonly PluginType = "SamplePlugin"; // This is required for serialization and handling plugins. Also used in viewer.getPluginByType()
  719. @uiToggle() // This creates a checkbox in the Ui. (Supported by TweakpaneUiPlugin)
  720. @serialize() // Adds this property to the list of serializable. This is also used when serializing to glb in AssetExporter.
  721. enabled = true;
  722. // A plugin can have custom properties.
  723. @uiSlider("Some Number", [0, 100], 1) // Adds a slider to the Ui, with custom bounds and step size (Supported by TweakpaneUiPlugin)
  724. @serialize("someNumber")
  725. @onChange(SamplePlugin.prototype._updateParams) // this function will be called whenevr this value changes.
  726. val1 = 0;
  727. // A plugin can have custom properties.
  728. @uiInput("Some Text") // Adds a slider to the Ui, with custom bounds and step size (Supported by TweakpaneUiPlugin)
  729. @onChange(SamplePlugin.prototype._updateParams) // this function will be called whenevr this value changes.
  730. @serialize()
  731. val2 = "Hello";
  732. @uiButton("Print Counters") // Adds a button to the Ui. (Supported by TweakpaneUiPlugin)
  733. public printValues = () => {
  734. console.log(this.val1, this.val2);
  735. this.dispatchEvent({ type: "sample-1", detail: { sample: this.val1 } }); // This will dispatch an event.
  736. }
  737. constructor() {
  738. super();
  739. this._updateParams = this._updateParams.bind(this);
  740. }
  741. private _updateParams() {
  742. console.log("Parameters updated.");
  743. this.dispatchEvent({ type: "sample-2" }); // This will dispatch an event.
  744. }
  745. onAdded(v: ThreeViewer): void {
  746. super.onAdded(v);
  747. // Do some initialization here.
  748. this.val1 = 0;
  749. this.val2 = "Hello";
  750. v.addEventListener("preRender", this._preRender);
  751. v.addEventListener("postRender", this._postRender);
  752. v.addEventListener("preFrame", this._preFrame);
  753. v.addEventListener("postFrame", this._postFrame);
  754. this._viewer!.scene.addEventListener("addSceneObject", this._objectAdded); // this._viewer can also be used while this plugin is attached.
  755. }
  756. onRemove(v: ThreeViewer): void {
  757. // remove dispose objects
  758. v.removeEventListener("preRender", this._preRender);
  759. v.removeEventListener("postRender", this._postRender);
  760. v.removeEventListener("preFrame", this._preFrame);
  761. v.removeEventListener("postFrame", this._postFrame);
  762. this._viewer!.scene.removeEventListener("addSceneObject", this._objectAdded); // this._viewer can also be used while this plugin is attached.
  763. super.onRemove(v);
  764. }
  765. private _objectAdded = (ev: IEvent<any>) => {
  766. console.log("A new object, texture or material is added to the scene.", ev.object);
  767. };
  768. private _preFrame = (ev: IEvent<any>) => {
  769. // This function will be called before each frame. This is called even if the viewer is not dirty, so it's a good place to do viewer.setDirty()
  770. };
  771. private _preRender = (ev: IEvent<any>) => {
  772. // This is called before each frame is rendered, only when the viewer is dirty.
  773. };
  774. // postFrame and postRender work the same way as preFrame and preRender.
  775. }
  776. ```
  777. Notes:
  778. * All plugins that are present in the dependencies array when the plugin is added to the viewer, are created and attached to the viewer in `super.onAdded`
  779. * Custom events can be dispatched with `this.dispatchEvent`, and subscribed to with `plugin.addEventListener`. The event type must be described in the class signature for typescript autocomplete to work.
  780. * Event listeners and other hooks can be added and removed in `onAdded` and `onRemove` functions for the viewer and other plugins.
  781. * To the viewer render the next frame, `viewer.setDirty()` can be called, or set `this.dirty = true` in preFrame and reset in postFrame to stop the rendering. (Note that rendering may continue if some other plugin sets the viewer dirty like `ProgressivePlugin` or any of the animation plugins). Check `isConverged` in `ProgressivePlugin` to check if its the final frame.
  782. * All Plugins which inherit from AViewerPlugin support serialisation. Create property `serializeWithViewer = false` to disable serialisation with the viewer in config and glb or `toJSON: any = undefined` to disable serialisation entirely
  783. * `plugin.toJSON()` and `plugin.fromJSON()` or `ThreeSerialization` can be used to serialize and deserialize plugins. `viewer.exportPluginConfig` and `viewer.importPluginConfig` also exist for this.
  784. * @serialize('label') decorator can be used to mark any public/private variable as serializable. label (optional) corresponds to the key in JSON.
  785. * @serialize supports instances of ITexture, IMaterial, all primitive types, simple JS objects, three.js math classes(Vector2, Vector3, Matrix3...), and some more.
  786. * uiDecorators can be used to mark properties and functions that will be shown in the Ui. The Ui shows up automatically when TweakpaneUiPlugin is added to the viewer. Plugins have special features in the UI for download preset and saving state.
  787. Check various plugins in the source code for more examples.
  788. # Viewer API
  789. [ThreeViewer](https://threepipe.org/docs/classes/ThreeViewer.html) - is the main entry point to 3d rendering on the canvas.
  790. - `.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
  791. - `.renderer`: [IWebGLRenderer](https://threepipe.org/docs/interfaces/IWebGLRenderer.html) - for rendering. Instance of three.js [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer)
  792. - `.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)
  793. - `.context`: [WebGLRenderingContext](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext) - WebGL rendering context
  794. - `.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
  795. - `.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.
  796. - `.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)
  797. - `.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)
  798. - `.assetManager`: [AssetManager](https://threepipe.org/docs/classes/AssetManager.html) - Asset manager for loading, managing and exporting assets
  799. - `.importer`: [AssetImporter](https://threepipe.org/docs/classes/AssetImporter.html) - for importing assets
  800. - `.exporter`: [AssetExporter](https://threepipe.org/docs/classes/AssetExporter.html) - for exporting assets
  801. - `.materialManager`: [MaterialManager](https://threepipe.org/docs/classes/MaterialManager.html) - for managing materials and material extensions
  802. - `.plugins`: `Record`<`string`, [IViewerPlugin](https://threepipe.org/docs/interfaces/IViewerPlugin.html)> - Plugins added to the viewer
  803. - `.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.
  804. ## ThreeViewer
  805. Source Code: [src/viewer/ThreeViewer.ts](./src/viewer/ThreeViewer.ts)
  806. API Reference: [ThreeViewer](https://threepipe.org/docs/classes/ThreeViewer.html)
  807. `ThreeViewer` is the main entry point to the viewer. It provides all the API for managing the scene, camera, rendering, plugins, etc.
  808. It is initialized with either a canvas element or a `HTMLElement` for the container.
  809. The canvas element is used for rendering, and the options are used to configure the viewer.
  810. If the canvas element is not provided, a new canvas element is created and appended to the container.
  811. More options can be passed in the constructor to configure various built-in plugins and rendering features in the viewer.
  812. ### Constructor
  813. ```typescript
  814. import {ThreeViewer, CameraViewPlugin} from 'threepipe'
  815. // Create a viewer. All options except canvas/container are optional
  816. const viewer = new ThreeViewer({
  817. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  818. // or a container like:
  819. // container: document.getElementById('mcontainer'),
  820. // container: document.body,
  821. // Set the render scale to render at device resolution
  822. renderScale: window.devicePixelRatio,
  823. // modify the screen shader: See ScreenPass and ScreenPass.glsl for more details
  824. screenShader: `diffuseColor = diffuseColor * 2.0;`,
  825. // Add TonemapPlugin
  826. tonemap: true,
  827. // Use MSAA(anti-aliasing)
  828. msaa: false,
  829. // Use Uint8 RGBM HDR Render Pipeline. Provides better performance with post-processing. RenderManager Uses Half-float if set to false.
  830. rgbm: true,
  831. // Use rendered gbuffer as depth-prepass / z-prepass.
  832. zPrepass: false,
  833. // Options for AssetManager
  834. assetManager: {
  835. // Use a custom CacheStorage
  836. storage: caches.open('threepipe-assetmanager'),
  837. },
  838. // Use DropzonePlugin to add support for file drag and drop
  839. // Enable and set properties
  840. dropzone: {
  841. // Set allowed extensions
  842. allowedExtensions: ['png', 'glb', 'gltf'],
  843. // Automatically add downloaded assets
  844. autoAdd: true
  845. // autoImport: true,
  846. // domElement: document.body,
  847. // addOptions: { ... }
  848. // importOptions: { ... }
  849. },
  850. // By default its false
  851. // dropzone: false,
  852. // To Enable without options
  853. // dropzone: true
  854. // Add some plugins after viewer creation.
  855. plugins: [CameraViewPlugin, new CustomPlugin()],
  856. // Shorthand to load files immediately after viewer initialization
  857. load: {
  858. src: 'https://example.com/file.glb',
  859. environment: 'https://example.com/file.hdr',
  860. background: 'https://example.com/file.png',
  861. },
  862. onLoad: (viewer) => {
  863. // Called when all the files are loaded
  864. },
  865. })
  866. ```
  867. Check the interface [ThreeViewerOptions](https://threepipe.org/docs/interfaces/ThreeViewerOptions.html) for all the options.
  868. To dispose off the viewer and all its resources call [`viewer.dispose()`](https://threepipe.org/docs/classes/ThreeViewer.html#dispose) method.
  869. To dispose only the scene objects and not the complete viewer, use `viewer.scene.disposeSceneModels()`
  870. ### Plugin Functions
  871. ```typescript
  872. import {ThreeViewer, TonemapPlugin, DepthBufferPlugin, NormalBufferPlugin} from 'threepipe'
  873. const viewer = new ThreeViewer({...})
  874. // Add a plugin
  875. const plugin = viewer.addPluginSync(new TonemapPlugin())
  876. // plugins can be added with just the class also
  877. const plugin2 = viewer.addPluginSync(TonemapPlugin)
  878. // Add multiple plugins at once
  879. viewer.addPluginsSync([
  880. TonemapPlugin,
  881. new NormalBufferPlugin(),
  882. DepthBufferPlugin,
  883. // ...
  884. ])
  885. // Get a plugin
  886. const plugin3 = viewer.getPlugin(TonemapPlugin)
  887. // Get or add a plugin, when not sure if the plugin is already added
  888. const plugin4 = viewer.getOrAddPluginSync(TonemapPlugin)
  889. // Remove a plugin
  890. viewer.removePluginSync(TonemapPlugin)
  891. ```
  892. Note: all sync functions above have async counterparts like `addPlugin`, `getOrAddPlugin`,
  893. `removePlugin` that are used for async plugins.
  894. There are no async plugins built-in to threepipe yet.
  895. ### Import/Export Functions
  896. ```typescript
  897. import {ThreeViewer} from 'threepipe'
  898. const viewer = new ThreeViewer({...})
  899. // Load a 3d model
  900. const object = await viewer.load<IObject3D>('https://example.com/file.glb')
  901. // Load a material
  902. const material = await viewer.load<PhysicalMaterial>('https://example.com/file.pmat')
  903. // Load an image
  904. const texture = await viewer.load<ITexture>('https://example.com/file.png')
  905. // Import a model without adding to the scene
  906. const imported = await viewer.import('https://example.com/file.glb')
  907. // Export the complete scene with viewer configuraion
  908. const exportedScene = await viewer.exportScene({})
  909. // Export an object
  910. const exported = await viewer.export(object)
  911. // Export a material
  912. const exportedMaterial = await viewer.export(material)
  913. // Export a texture
  914. const exportedTexture = await viewer.export(texture)
  915. // Export viewer and plugins configurations
  916. const exportedConfig = await viewer.export(viewer)
  917. // Export plugin configuration
  918. const exportedPlugin = await viewer.exportPlugin(viewer.getPlugin(PluginClass))
  919. // Set Background Image
  920. await viewer.setBackgroundMap('https://example.com/file.png')
  921. // Set Environment Map
  922. await viewer.setEnvironmentMap('https://example.com/file.hdr')
  923. // Add an imported object or a created three.js object to the scene
  924. viewer.addSceneObject(imported)
  925. ```
  926. [`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.
  927. [`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.
  928. [`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.
  929. [`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.
  930. [`viewer.exportPlugin`](https://threepipe.org/docs/classes/ThreeViewer.html#exportPlugin) - Exports a plugin configuration and returns a blob.
  931. [`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.
  932. [`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.
  933. [`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.
  934. ### Frame/Rendering Events
  935. ```typescript
  936. import {ThreeViewer} from 'threepipe'
  937. const viewer = new ThreeViewer({...})
  938. // Add a callback to be called before every frame, irrespective of whether enything is being rendered that frame
  939. viewer.addEventListener('preFrame', (ev)=>{
  940. console.log(ev);
  941. // change something
  942. viewer.setDirty() // let the viewer know to re-render the scene from this frame
  943. })
  944. // Add a callback to be called after every frame, irrespective of whether enything was rendered that frame
  945. viewer.addEventListener('postFrame', (ev)=>{
  946. console.log(ev);
  947. // change something
  948. viewer.setDirty() // let the viewer know to re-render the scene from next frame
  949. })
  950. // Add a callback to be called before every render, only if something is being rendered that frame
  951. viewer.addEventListener('preRender', (ev)=>{
  952. // canvas is about to be rendered, or re-rendered for progressive rendering
  953. console.log(ev, viewer.renderManager.frameCount);
  954. })
  955. // Add a callback to be called after every render, only if something was rendered that frame
  956. viewer.addEventListener('postRender', (ev)=>{
  957. // canvas is rendered, or re-rendered for progressive rendering
  958. console.log(ev);
  959. })
  960. // Listen to viewer.setDirty() calls
  961. viewer.addEventListener('update', (ev)=>{
  962. // viewer.setDirty() was called by some plugin or code
  963. console.log(ev);
  964. })
  965. // to remove an event listener, first keep a reference to the callback
  966. const callback = (ev)=>{ return }
  967. viewer.addEventListener('preFrame', callback)
  968. // then remove it
  969. viewer.removeEventListener('preFrame', callback)
  970. // Add a callback to be called only once for an event
  971. viewer.doOnce('postFrame', () => viewer.canvas.toDataURL('image/png'))
  972. // Enable/disable rendering in the viewer
  973. viewer.renderEnabled = false
  974. // do something with the canvas or load assets
  975. await viewer.load('https://example.com/file.glb')
  976. await viewer.load('https://example.com/file1.glb')
  977. await viewer.load('https://example.com/file2.glb')
  978. viewer.renderEnabled = true // all the assets will be rendered together in the next frame
  979. ```
  980. Check the [IViewerEvent](https://threepipe.org/docs/interfaces/IViewerEvent.html) interface for all the event types.
  981. [`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.
  982. [`viewer.removeEventListener`](https://threepipe.org/docs/classes/ThreeViewer.html#removeEventListener) - Removes a callback from the given event.
  983. [`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.
  984. ### Utility Functions
  985. ```typescript
  986. import {ThreeViewer} from 'threepipe'
  987. const viewer = new ThreeViewer({...})
  988. // Set size
  989. viewer.setSize({width: 800, height: 600})
  990. // Traverse scene objects
  991. viewer.traverseSceneObjects((object) => {
  992. console.log(object)
  993. // do something with object
  994. })
  995. // If the size is set by css or manually by javascript use `resize` to update the viewer
  996. viewer.resize()
  997. // Trigger re-render with `setDirty` when something changes and viewer is not notified internally
  998. viewer.setDirty()
  999. // Get snapshot of the canvas as a blob
  1000. const blob = await viewer.getScreenshotBlob({mimeTye: 'image/png', quality: 90})
  1001. // Get snapshot of the canvas as a data url
  1002. const dataUrl = await viewer.getScreenshotDataUrl({mimeTye: 'image/jpeg', quality: 85})
  1003. // Dispose viewer and all resources
  1004. viewer.canvas.remove() // canvas needs to be removed separately from the DOM
  1005. viewer.dispose()
  1006. ```
  1007. [`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.
  1008. [`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.
  1009. [`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.
  1010. [`viewer.setDirty`](https://threepipe.org/docs/classes/ThreeViewer.html#setDirty) - Triggers re-render on next `requestAnimationFrame` call.
  1011. [`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.
  1012. [`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.
  1013. [`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.
  1014. ## RenderManager
  1015. Source Code: [src/viewer/ViewerRenderManager.ts](./src/viewer/ViewerRenderManager.ts), [src/rendering/RenderManager.ts](./src/rendering/RenderManager.ts), [src/rendering/RenderTargetManager.ts](./src/rendering/RenderTargetManager.ts)
  1016. 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)
  1017. It manages the rendering, composition/postprocessing of the scene and provides helpers for rendering and render target management.
  1018. ```typescript
  1019. const viewer = new ThreeViewer({...})
  1020. const renderManager = viewer.renderManager
  1021. // Get the effect composer
  1022. const composer = renderManager.composer
  1023. // Get the three.js webgl renderer
  1024. const renderer = renderManager.renderer
  1025. // Get the main Render Pass in the pipeline
  1026. const renderPass = renderManager.renderPass
  1027. // Get the main Screen Pass in the pipeline
  1028. const screenPass = renderManager.screenPass
  1029. // Set the render scale
  1030. renderManager.renderScale = Math.min(window.devicePixelRatio, 2)
  1031. // Register a custom composer pass
  1032. const customPass: IPipelinePass = new CustomPass()
  1033. renderManager.registerPass(customPass)
  1034. // Unregister a custom composer pass
  1035. renderManager.unregisterPass(customPass)
  1036. // The pipeline is automatically created and sorted based on dependencies in pipeline pass.
  1037. // To check the built pipeline
  1038. console.log(renderManager.pipeline)
  1039. // Set a custom render pipeline
  1040. renderManager.autoBuildPipeline = false
  1041. renderManager.pipeline = ['depth', 'render', 'screen']
  1042. // Check the total frames rendererd
  1043. console.log(renderManager.totalFrameCount)
  1044. // Get the current frame count in progressive rendering
  1045. console.log(renderManager.frameCount)
  1046. // Force reset shadows when some object is moved
  1047. renderManager.resetShadows()
  1048. // Render Target Management
  1049. // Get the main composer target
  1050. const composerTarget = renderManager.composerTarget
  1051. // clone the target to get a copy of the target with all the default options
  1052. const clonedTarget = composeTarget.clone()
  1053. // Create a render target, same size as the canvas. The target are automatically resized when the canvas is resized
  1054. const renderTarget = renderManager.createTarget({
  1055. sizeMultiplier: 1, // size multiplier from the canvas. 0.5 will be half width and height of the canvas
  1056. type: UnsignedByteType,
  1057. // ... // See CreateRenderTargetOptions for all options
  1058. })
  1059. // Create a render target of custom size
  1060. const renderTarget = renderManager.createTarget({
  1061. size: {
  1062. width: 1024,
  1063. height: 1024,
  1064. },
  1065. type: HalfFloatType,
  1066. // ...
  1067. })
  1068. // Dispose the render target
  1069. renderManager.disposeTarget(renderTarget)
  1070. // Create and release temporary targets for in-pass rendering.
  1071. const tempTarget = renderManager.getTempTarget({
  1072. sizeMultiplier: 0.5,
  1073. type: HalfFloatType,
  1074. // ...
  1075. })
  1076. // do something
  1077. renderManager.releaseTempTarget(tempTarget)
  1078. // Set how many temporary targets can remain in memory for a specific set of options
  1079. renderManager.maxTempPerKey = 10 // default = 5
  1080. // Copy/Blit a texture to the canvas or another render target with standard or a custom material
  1081. renderManager.blit(destination, {source: sourceTexture})
  1082. // Clear color of the canvas
  1083. renderManager.clearColor({r: 0, g: 0, b: 0, a: 1, depth: true, viewport: new Vector4(...)})
  1084. // Clear of a render target
  1085. renderManager.clearColor(renderTarget, {r: 0, g: 0, b: 0, a: 1, target: renderTarget})
  1086. // Export a render target to a blob. The type is automatically picked from exr to png based on the render target
  1087. const blob = renderManager.exportRenderTarget(renderTarget, 'auto')
  1088. // Export a render target to png/jpeg data url. This will clamp any floating point targets to fit in png/jpeg
  1089. const dataUrl = renderManager.renderTargetToDataUrl(renderTarget, 'image/png')
  1090. // Read render target pixels to array buffer. Returns Uint8Array|Uint16Array|Float32Array based on the render target type
  1091. const buffer = renderManager.renderTargetToBuffer(renderTarget)
  1092. ```
  1093. [`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.
  1094. [`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
  1095. [`renderManager.context`](https://threepipe.org/docs/classes/ViewerRenderManager.html#context) - Access the WebGL rendering context for the canvas.
  1096. [`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.
  1097. [`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
  1098. [`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.
  1099. [`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.
  1100. ### Rendering Pipeline
  1101. [`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.
  1102. [`renderManager.unregisterPass`](https://threepipe.org/docs/classes/RenderManager.html#unregisterPass) - Unregisters a custom composer pass from the render pipeline.
  1103. [`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.
  1104. [`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`.
  1105. [`renderManager.totalFrameCount`](https://threepipe.org/docs/classes/RenderManager.html#totalFrameCount) - The total frames rendered since the render manager was created.
  1106. [`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.
  1107. ### Render Targets management
  1108. [`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)
  1109. [`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
  1110. [`renderManager.disposeTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#disposeTarget) - Disposes a render target and removes it from the render target manager.
  1111. [`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
  1112. [`renderManager.releaseTempTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#releaseTempTarget) - Releases a temporary render target and adds it back to the render target manager.
  1113. [`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`.
  1114. ### Helpers
  1115. [`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.
  1116. [`renderManager.clearColor`](https://threepipe.org/docs/classes/RenderManager.html#clearColor) - Clears the color of the canvas or a render target.
  1117. [`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.
  1118. [`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.
  1119. [`renderManager.renderTargetToBuffer`](https://threepipe.org/docs/classes/RenderManager.html#renderTargetToBuffer) - Reads render target pixels to a Uint8Array|Uint16Array|Float32Array array buffer.
  1120. ## RootScene
  1121. Source Code: [src/core/object/RootScene.ts](./src/core/object/RootScene.ts)
  1122. API Reference: [RootScene](https://threepipe.org/docs/classes/RootScene.html)
  1123. RootScene is the main scene that is rendered in the canvas.
  1124. 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,
  1125. backgroundColor, background map and background intensity,
  1126. environment map rotation and intensity, fixed env map direction patch, event bubbling in the scene hierarchy, scene config serialization, main camera management,
  1127. automatic active near far management based on scene bounds, disposing complete scene hierarchy, etc
  1128. ```typescript
  1129. const viewer = new ThreeViewer({...})
  1130. const scene = viewer.scene
  1131. // List oll loaded objects in the model root
  1132. console.log(scene.modelRoot.children)
  1133. // Set the background color
  1134. scene.setBackgroundColor('#ffffff')
  1135. // or
  1136. // scene.backgroundColor = new Color('#ffffff')
  1137. // or
  1138. // scene.backgroundColor.set('#ffffff')
  1139. // scene.onBackgroundChange() // this must be called when not using a setter or set function.
  1140. // Set a texture as background (or use viewer.setBackgroundMap). When both color and texture are set, they are multiplied
  1141. scene.background = customTexture
  1142. // Set the background same as the environment map
  1143. scene.background = 'environment' // background is automatically changed when the environment changes.
  1144. // or
  1145. // scene.background = scene.environment
  1146. // Set the background intensity
  1147. scene.backgroundIntensity = 2
  1148. // Set a texture as environment map (or use viewer.setEnvironmentMap)
  1149. scene.environment = customTexture
  1150. // Set the environment intensity
  1151. scene.envMapIntensity = 2
  1152. // Set the environment map rotation
  1153. scene.environment.rotation = Math.PI / 2
  1154. // Set Fixed env direction (rotate environment according the the camera)
  1155. scene.fixedEnvMapDirection = true
  1156. // Get the main camera used for rendering
  1157. const camera: PerspectiveCamera2 = scene.mainCamera
  1158. // Set camera props
  1159. camera.position.set(0, 0, 10)
  1160. camera.target.set(0, 0, 0)
  1161. camera.setDirty() // this needs to be called to notify the viewer to re-render the scene
  1162. // Traverse the model root hierarchy (or just use viewer.traverseSceneObjects)
  1163. scene.modelRoot.traverse((object) => {
  1164. console.log(object)
  1165. // do something with object
  1166. })
  1167. // Access the default camera (same as mainCamera if not changed explicitly)
  1168. const defaultCamera: ICamera = scene.defaultCamera
  1169. // Dispose all assets in the modelRoot
  1170. scene.disposeSceneModels()
  1171. // Remove all objects from the modelRoot
  1172. scene.clearSceneModels()
  1173. // Dispose the scene and all its resources and children
  1174. scene.dispose()
  1175. // Get bounds of the scene model root
  1176. const bounds = scene.getBounds(true, true) // true for precise bounds and ignore invisible
  1177. // Add an object to the scene or its model root depending on the options (or just use viewer.addSceneObject)
  1178. scene.addObject(object, {addToRoot: false}) // adds to the scene directly when addToRoot is true
  1179. // Load an imported model root from the asset importer
  1180. scene.loadModelRoot(object)
  1181. // notify that something has changed in the scene for re-render
  1182. scene.setDirty()
  1183. // notify that some object has changed in the scene for scene refresh(like shadow refresh, ground etc) and re-render
  1184. scene.refreshScene()
  1185. // or
  1186. scene.setDirty({refreshScene: true})
  1187. // set geometryChanged: false to prevent shadow recompute
  1188. scene.refreshScene({geometryChanged: false})
  1189. // refresh active near far. (in most cases this is done automatically and need not be called)
  1190. scene.refreshActiveNearFar()
  1191. ```
  1192. [`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.
  1193. [`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.
  1194. [`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.
  1195. [`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.
  1196. [`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.
  1197. [`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.
  1198. `scene.environment.rotation` - The rotation of the environment map around the y-axis.
  1199. [`scene.envMapIntensity`](https://threepipe.org/docs/classes/RootScene.html#envMapIntensity) - The environment intensity of the scene.
  1200. [`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.
  1201. [`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.
  1202. [`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.
  1203. [`scene.disposeSceneModels`](https://threepipe.org/docs/classes/RootScene.html#disposeSceneModels) - Disposes all assets in the modelRoot.
  1204. [`scene.clearSceneModels`](https://threepipe.org/docs/classes/RootScene.html#clearSceneModels) - Removes all objects from the modelRoot.
  1205. [`scene.dispose`](https://threepipe.org/docs/classes/RootScene.html#dispose) - Disposes the scene and all its resources and children.
  1206. [`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.
  1207. [`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.
  1208. [`scene.setDirty`](https://threepipe.org/docs/classes/RootScene.html#setDirty) - Notifies that something has changed in the scene for re-render.
  1209. [`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.
  1210. [`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)
  1211. [`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.
  1212. ### Scene Events
  1213. RootScene dispatches many events that are useful when writing app logic or plugins
  1214. `'sceneUpdate'` - Listen to `refreshScene` called in RootScene. When some object changes.
  1215. `'addSceneObject'` - When a new object is added to the scene
  1216. `'mainCameraChange'` - When the main camera is changed to some other camera.
  1217. `'mainCameraUpdate'` - When some properties in the current main camera has changed.
  1218. `'environmentChanged'` - When the environment map changes
  1219. `'backgroundChanged'` - When the background map or color changes
  1220. `'materialUpdate`' - When a material in the scene has updated. (setDirty called on the material)
  1221. `'objectUpdate`' - When a object in the scene has updated. (setDirty called on the object)
  1222. `'textureUpdate`' - When a texture in the scene has updated. (setDirty called on the texture)
  1223. `'cameraUpdate`' - When a camera in the scene has updated.
  1224. (setDirty called on the camera)
  1225. `'geometryUpdate`' - When a geometry in the scene has updated.
  1226. (setDirty called on the geometry)
  1227. `'geometryChanged`' - When a geometry is changed on any mesh
  1228. `'materialChanged'` - When a material is changed on any mesh
  1229. Check [IObject3DEventTypes](https://threepipe.org/docs/interfaces/IObject3DEventTypes.html) and[ISceneEventTypes](https://threepipe.org/docs/interfaces/ISceneEventTypes.html) for more information.
  1230. ## ICamera
  1231. Source Code: [src/core/camera/PerspectiveCamera2.ts](./src/core/camera/PerspectiveCamera2.ts), [src/core/ICamera.ts](./src/core/ICamera.ts)
  1232. API Reference: [PerspectiveCamera2](https://threepipe.org/docs/classes/PerspectiveCamera2.html), [ICamera](https://threepipe.org/docs/interfaces/ICamera.html)
  1233. ICamera is an interface for a camera that extends the three.js [Camera](https://threejs.org/docs/#api/en/cameras/Camera).
  1234. PerspectiveCamera2 implements the interface,
  1235. 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.
  1236. ```typescript
  1237. import {OrbitControls3} from './OrbitControls3'
  1238. const viewer = new ThreeViewer({...})
  1239. const camera: PerspectiveCamera2 = viewer.scene.mainCamera
  1240. // Set the camera position
  1241. camera.position.set(0, 0, 10)
  1242. // Set the camera target (where the camera looks at)
  1243. camera.target.set(0, 0, 0)
  1244. // Set the camera fov
  1245. camera.fov = 45
  1246. // Set the camera aspect ratio
  1247. camera.autoAspect = false // disable automatic aspect management based on the canvas size
  1248. camera.aspect = 1
  1249. // Set camera near far bounds.
  1250. // Near, Far plane will be calculated automatically within these limits
  1251. // Try changing these values when encountering z-fighting issues or far-plane clipping
  1252. camera.minNearPlane = 0.5 // min near plane
  1253. camera.maxFarPlane = 10 // max far plane
  1254. // Set a custom camera near far
  1255. camera.autoNearFar = false // disable automatic near far management based on the scene bounds
  1256. camera.minNearPlane = 0.1 // near plane
  1257. camera.maxFarPlane = 1000 // far plane
  1258. // this needs to be called to notify the viewer to re-render the scene
  1259. // in most cases this is done internally. But calling this does not have much impact
  1260. camera.setDirty()
  1261. // Check if user can interact with the camera. Also checks if its the main camera.
  1262. console.log(camera.canUserInteract)
  1263. // Get the camera controls (orbit controls for the default camera)
  1264. const controls: OrbitControls3 = camera.controls
  1265. // Disable controls
  1266. controls.enabled = false
  1267. // Change the controls mode
  1268. camera.controlsMode = 'none' // this will remove the current controls.
  1269. // Register a custom camera controls
  1270. camera.setControlsCtor('customOrbit', (camera, domElement) => new CustomOrbitControls(camera, domElement))
  1271. // Set the camera controls
  1272. camera.controlsMode = 'customOrbit' // this will initialize the controls with the customOrbit constructor and set it on the camera
  1273. // Disable interactions to the camera. (eg when animating)
  1274. camera.interactionsEnabled = false
  1275. // Force refresh aspect ratio (this is done automatically with a ResizeObserver on the canvas in the viewer)
  1276. camera.refreshAspect()
  1277. // Set the camera as the main camera
  1278. camera.activateMain()
  1279. // Deactivate the camera as the main camera
  1280. camera.deactivateMain()
  1281. ```
  1282. [`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.
  1283. [`camera.autoAspect`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#autoAspect) - If `true`, the aspect ratio is automatically calculated based on the canvas size.
  1284. [`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`.
  1285. [`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
  1286. [`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
  1287. [`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.
  1288. [`camera.setDirty`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#setDirty) - Notifies that something has changed in the camera for re-render.
  1289. [`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.
  1290. [`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`
  1291. [`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.
  1292. [`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.
  1293. [`camera.interactionsEnabled`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#interactionsEnabled) - 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.
  1294. [`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)
  1295. [`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.
  1296. [`camera.deactivateMain`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#deactivateMain) - Deactivate the camera as the main camera.
  1297. See also [CameraViewPlugin](#cameraviewplugin) for camera focus animation.
  1298. ## AssetManager
  1299. Source Code: [src/assetmanager/AssetManager.ts](./src/assetmanager/AssetManager.ts)
  1300. API Reference: [AssetManager](https://threepipe.org/docs/classes/AssetManager.html)
  1301. `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.
  1302. ```typescript
  1303. const viewer = new ThreeViewer({...})
  1304. const assetManager = viewer.assetManager
  1305. // Add an asset or an asset bundle
  1306. const assets = await assetManager.addAsset('https://example.com/model.zip')
  1307. // or
  1308. const assets = await assetManager.addAsset({
  1309. path: 'https://example.com/model.zip',
  1310. file: blob,
  1311. })
  1312. // Get the storage used in the asset manager for caching
  1313. const storage: Cache | Storage = assetManager.storage
  1314. // Get the importer. Provides low level functions to import assets
  1315. const importer = assetManager.importer
  1316. // import a file by asset or url
  1317. const file = await importer.import('https://example.com/model.gltf')
  1318. // Import a Map<string, File> from drag drop
  1319. const res = await importer.importFiles(mapOfFiles, {})
  1320. // Register a custom path that maps to a File object. Useful when some file types have path references to other files.
  1321. importer.registerFile('/myFile.png', file) // this returns the three.js loader for that kind of file.
  1322. // Unregister the path
  1323. importer.unregisterFile('/myFile.png')
  1324. // Unregister all files and clear the loader cache(memory, not storage)
  1325. importer.clearCache()
  1326. // Add custom importers (check extra load plugins for more examples)
  1327. importer.addImporter(new Importer(class extends PLYLoader implements ILoader {
  1328. transform(res: BufferGeometry, _: AnyOptions): Mesh | undefined {
  1329. return res ? new Mesh(res, new PhysicalMaterial({color: new Color(1, 1, 1)})) : undefined
  1330. }
  1331. }, ['ply'], ['text/plain+ply'], false))
  1332. // Get the exporter. Provides low level functions to export assets
  1333. const exporter = assetManager.exporter
  1334. // Export any IObject3D, IMaterial, ITexture, IRenderTarget
  1335. const exported = exporter.exportObject(obj, options)
  1336. // Add a custom exporter
  1337. exporter.addExporter({
  1338. ext: ['gltf', 'glb'], // file extensions
  1339. extensions: [], // extensions for the exporter
  1340. ctor: (assetExporter, iexporter) => {
  1341. return new GLTFExporter2()
  1342. }
  1343. })
  1344. // Material Manager
  1345. const materialManager = assetManager.materialManager
  1346. // Create a material of type
  1347. const mat = materialManager.create('physical')
  1348. const mat2 = materialManager.create('unlit')
  1349. // find or create a material by uuid
  1350. const mat = materialManager.findOrCreate('00000000-0000-0000-0000-000000000000', {color: '#ffffff'})
  1351. // find a material creation template
  1352. const template = materialManager.findTemplate('physical')
  1353. // Get all materials
  1354. const materials = materialManager.getAllMaterials()
  1355. // Get all materials of type
  1356. const materials = materialManager.getMaterialsOfType(PhysicalMaterial.TypeSlug)
  1357. // register a custom material to the manager for tracking and extensions
  1358. // Note all materials created in threepipe internally are registered automatically on creation or when added to any scene object.
  1359. materialManager.registerMaterial(customMat)
  1360. // unregister
  1361. materialManager.unregisterMaterial(customMat)
  1362. // clear all material references
  1363. materialManager.clearMaterials()
  1364. // Register a custom material template
  1365. materialManager.registerTemplate({
  1366. generator: (params: any) => new PhysicalMaterial(params),
  1367. name: 'custom',
  1368. materialType: PhysicalMaterial.TYPE,
  1369. params: {
  1370. color: '#ffffff',
  1371. roughness: 0.5,
  1372. metalness: 0.5,
  1373. },
  1374. })
  1375. const mat3 = materialManager.create('custom')
  1376. // convert a standard three.js material to threepipe material
  1377. const mat4 = materialManager.convertToIMaterial(new ShadowMaterial(), {materialTemplate: 'test'})
  1378. // register a custom material extension for all materials in the viewer
  1379. materialManager.registerMaterialExtension(customExtension)
  1380. // unregister
  1381. materialManager.unregisterMaterialExtension(customExtension)
  1382. // remove all extensions
  1383. materialManager.clearExtensions()
  1384. // Apply a material properties to other material(s) in the scene by name or uuid
  1385. materialManager.applyMaterial(goldMaterial, 'METAL') // this will copy the properties from goldMaterial to all the materials(or objects) in the viewer with the name METAL.
  1386. // export a material as JSON. Note: use AssetExporter instead to export all the embedded assets and properties properly.
  1387. const blob = materialManager.exportMaterial(mat)
  1388. // dispose manager and all materials.
  1389. materialManager.dispose()
  1390. ```
  1391. [`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.
  1392. [`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.
  1393. [`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).
  1394. [`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).
  1395. ### AssetImporter
  1396. [`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.
  1397. [`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.
  1398. [`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.
  1399. [`importer.unregisterFile`](https://threepipe.org/docs/classes/AssetImporter.html#unregisterFile) - Unregister the path.
  1400. [`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).
  1401. [`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.
  1402. ### AssetExporter
  1403. [`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.
  1404. [`exporter.addExporter`](https://threepipe.org/docs/classes/AssetExporter.html#addExporter) - Add a custom exporter for a custom file type.
  1405. ### MaterialManager
  1406. [`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).
  1407. [`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.
  1408. [`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.
  1409. [`materialManager.getAllMaterials`](https://threepipe.org/docs/classes/MaterialManager.html#getAllMaterials) - Get all materials registered with the manager.
  1410. [`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.
  1411. [`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
  1412. [`materialManager.unregisterMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#unregisterMaterial) - Unregister a material from the manager.
  1413. [`materialManager.clearMaterials`](https://threepipe.org/docs/classes/MaterialManager.html#clearMaterials) - Clear all registered material references.
  1414. [`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.
  1415. [`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).
  1416. [`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.
  1417. [`materialManager.unregisterMaterialExtension`](https://threepipe.org/docs/classes/MaterialManager.html#unregisterMaterialExtension) - Unregister a material extension from the manager.
  1418. [`materialManager.clearExtensions`](https://threepipe.org/docs/classes/MaterialManager.html#clearExtensions) - Remove all material extensions from the manager.
  1419. [`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.
  1420. [`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.
  1421. [`materialManager.dispose`](https://threepipe.org/docs/classes/MaterialManager.html#dispose) - Dispose manager and all materials.
  1422. # Threepipe Plugins
  1423. ThreePipe has a simple plugin system that allows you to easily add new features to the viewer. Plugins can be added to the viewer using the `addPlugin` and `addPluginSync` methods. The plugin system is designed to be modular and extensible. Plugins can be added to the viewer at any time and can be removed using the `removePlugin` and `removePluginSync` methods.
  1424. ## TonemapPlugin
  1425. [//]: # (todo: image)
  1426. Example: https://threepipe.org/examples/#tonemap-plugin/
  1427. Source Code: [src/plugins/postprocessing/TonemapPlugin.ts](./src/plugins/postprocessing/TonemapPlugin.ts)
  1428. API Reference: [TonemapPlugin](https://threepipe.org/docs/classes/TonemapPlugin.html)
  1429. TonemapPlugin adds a post-processing material extension to the ScreenPass in render manager
  1430. that applies tonemapping to the color. The tonemapping operator can be changed
  1431. by setting the `toneMapping` property of the plugin. The default tonemapping operator is `ACESFilmicToneMapping`.
  1432. Other Tonemapping properties can be like `exposure`, `contrast` and `saturation`
  1433. TonemapPlugin is added by default in ThreeViewer unless `tonemap` is set to `false` in the options.
  1434. ## DropzonePlugin
  1435. [//]: # (todo: image)
  1436. Example: https://threepipe.org/examples/#dropzone-plugin/
  1437. Source Code: [src/plugins/interaction/DropzonePlugin.ts](./src/plugins/interaction/DropzonePlugin.ts)
  1438. API Reference: [DropzonePlugin](https://threepipe.org/docs/classes/DropzonePlugin.html)
  1439. DropzonePlugin adds support for drag and drop of local files to automatically import, process and load them into the viewer.
  1440. DropzonePlugin can be added by default in ThreeViewer
  1441. by setting the `dropzone` property to `true` or an object of `DropzonePluginOptions` in the options.
  1442. ```typescript
  1443. import {DropzonePlugin, ThreeViewer} from 'threepipe'
  1444. const viewer = new ThreeViewer({
  1445. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  1446. dropzone: true, // just set to true to enable drag drop functionatility in the viewer
  1447. })
  1448. ```
  1449. To set custom options,
  1450. pass an object of [DropzonePluginOptions](https://threepipe.org/docs/interfaces/DropzonePluginOptions.html) type to the `dropzone` property.
  1451. ```typescript
  1452. import {DropzonePlugin, ThreeViewer} from 'threepipe'
  1453. const viewer = new ThreeViewer({
  1454. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  1455. dropzone: { // this can also be set to true and configured by getting a reference to the DropzonePlugin
  1456. allowedExtensions: ['gltf', 'glb', 'hdr', 'png', 'jpg', 'json', 'fbx', 'obj', 'bin', 'exr'], // only allow these file types. If undefined, all files are allowed.
  1457. addOptions: {
  1458. disposeSceneObjects: true, // auto dispose of old scene objects
  1459. autoSetEnvironment: true, // when hdr is dropped
  1460. autoSetBackground: true, // when any image is dropped
  1461. autoCenter: true, // auto center the object
  1462. autoScale: true, // auto scale according to radius
  1463. autoScaleRadius: 2,
  1464. license: 'Imported from dropzone', // Any license to set on imported objects
  1465. importConfig: true, // import config from file
  1466. },
  1467. // check more options in the DropzonePluginOptions interface
  1468. },
  1469. })
  1470. ```
  1471. ## ProgressivePlugin
  1472. [//]: # (todo: image)
  1473. Example: https://threepipe.org/examples/#progressive-plugin/
  1474. Source Code: [src/plugins/postprocessing/ProgressivePlugin.ts](./src/plugins/pipeline/ProgressivePlugin.ts)
  1475. API Reference: [ProgressivePlugin](https://threepipe.org/docs/classes/ProgressivePlugin.html)
  1476. Progressive Plugin adds a post-render pass to blend the last frame with the current frame.
  1477. This is used as a dependency in other plugins for progressive rendering effect which is useful for progressive shadows, gi, denoising, baking, anti-aliasing, and many other effects.
  1478. ## DepthBufferPlugin
  1479. [//]: # (todo: image)
  1480. Example: https://threepipe.org/examples/#depth-buffer-plugin/
  1481. Source Code: [src/plugins/pipeline/DepthBufferPlugin.ts](./src/plugins/pipeline/DepthBufferPlugin.ts)
  1482. API Reference: [DepthBufferPlugin](https://threepipe.org/docs/classes/DepthBufferPlugin.html)
  1483. Depth Buffer Plugin adds a pre-render pass to the render manager and renders a depth buffer to a target. The render target can be accessed by other plugins throughout the rendering pipeline to create effects like depth of field, SSAO, SSR, etc.
  1484. ```typescript
  1485. import {ThreeViewer, DepthBufferPlugin} from 'threepipe'
  1486. const viewer = new ThreeViewer({...})
  1487. const depthPlugin = viewer.addPluginSync(new DepthBufferPlugin(HalfFloatType))
  1488. const depthTarget = depthPlugin.target;
  1489. // Use the depth target by accesing `depthTarget.texture`.
  1490. ```
  1491. The depth values are based on camera near far values, which are controlled automatically by the viewer. To manually specify near, far values and limits, it can be set in the camera userData. Check the [example](https://threepipe.org/examples/#depth-buffer-plugin/) for more details.
  1492. ## NormalBufferPlugin
  1493. [//]: # (todo: image)
  1494. Example: https://threepipe.org/examples/#normal-buffer-plugin/
  1495. Source Code: [src/plugins/pipeline/NormalBufferPlugin.ts](./src/plugins/pipeline/NormalBufferPlugin.ts)
  1496. API Reference: [NormalBufferPlugin](https://threepipe.org/docs/classes/NormalBufferPlugin.html)
  1497. Normal Buffer Plugin adds a pre-render pass to the render manager and renders a normal buffer to a target. The render target can be accessed by other plugins throughout the rendering pipeline to create effects like SSAO, SSR, etc.
  1498. Note: Use [`DepthNormalBufferPlugin`](#DepthNormalBufferPlugin) if using both `DepthBufferPlugin` and `NormalBufferPlugin` to render both depth and normal buffers in a single pass.
  1499. ```typescript
  1500. import {ThreeViewer, NormalBufferPlugin} from 'threepipe'
  1501. const viewer = new ThreeViewer({...})
  1502. const normalPlugin = viewer.addPluginSync(new NormalBufferPlugin())
  1503. const normalTarget = normalPlugin.target;
  1504. // Use the normal target by accessing `normalTarget.texture`.
  1505. ```
  1506. ## GBufferPlugin
  1507. todo
  1508. ## PickingPlugin
  1509. [//]: # (todo: image)
  1510. Example: https://threepipe.org/examples/#picking-plugin/
  1511. Source Code: [src/plugins/pipeline/PickingPlugin.ts](./src/plugins/interaction/PickingPlugin.ts)
  1512. API Reference: [PickingPlugin](https://threepipe.org/docs/classes/PickingPlugin.html)
  1513. Picking Plugin adds support for selecting and hovering over objects in the viewer with user interactions and selection widgets.
  1514. When the plugin is added to the viewer, it starts listening to the mouse move and click events over the canvas.
  1515. When an object is clicked, it is selected,
  1516. and if a UI plugin is added, the uiconfig for the selected object is populated in the interface.
  1517. The events `selectedObjectChanged`, `hoverObjectChanged`, and `hitObject` can be listened to on the plugin.
  1518. Picking plugin internally uses [ObjectPicker](https://threepipe.org/docs/classes/ObjectPicker.html),
  1519. check out the documentation or source code for more information.
  1520. ```typescript
  1521. import {ThreeViewer, PickingPlugin} from 'threepipe'
  1522. const viewer = new ThreeViewer({...})
  1523. const pickingPlugin = viewer.addPluginSync(new PickingPlugin())
  1524. // Hovering events are also supported, but since its computationally expensive for large scenes it is disabled by default.
  1525. pickingPlugin.hoverEnabled = true
  1526. pickingPlugin.addEventListener('hitObject', (e)=>{
  1527. // This is fired when the user clicks on the canvas.
  1528. // The selected object hasn't been changed yet, and we have the option to change it or disable selection at this point.
  1529. // e.intersects.selectedObject contains the object that the user clicked on.
  1530. console.log('Hit: ', e.intersects.selectedObject)
  1531. // It can be changed here
  1532. // e.intersects.selectedObject = e.intersects.selectedObject.parent // select the parent
  1533. // e.intersects.selectedObject = null // unselect
  1534. // Check other properties on the event like intersects, mouse position, normal etc.
  1535. console.log(e)
  1536. })
  1537. pickingPlugin.addEventListener('selectedObjectChanged', (e)=>{
  1538. // This is fired when the selected object is changed.
  1539. // e.object contains the new selected object. It can be null if nothing is selected.
  1540. console.log('Selected: ', e.object)
  1541. })
  1542. // Objects can be programmatically selected and unselected
  1543. // to select
  1544. pickingPlugin.setSelectedObject(object)
  1545. // get the selected object
  1546. console.log(pickingPlugin.getSelectedObject())
  1547. // to unselect
  1548. pickingPlugin.setSelectedObject(null)
  1549. // Select object with camera animation to the object
  1550. pickingPlugin.setSelectedObject(object, true)
  1551. pickingPlugin.addEventListener('hoverObjectChanged', (e)=>{
  1552. // This is fired when the hovered object is changed.
  1553. // e.object contains the new hovered object.
  1554. console.log('Hovering: ', e.object)
  1555. })
  1556. ```
  1557. ## GLTFAnimationPlugin
  1558. [//]: # (todo: image)
  1559. Example: https://threepipe.org/examples/#gltf-animation-plugin/
  1560. Source Code: [src/plugins/animation/GLTFAnimationPlugin.ts](./src/plugins/animation/GLTFAnimationPlugin.ts)
  1561. API Reference: [GLTFAnimationPlugin](https://threepipe.org/docs/classes/GLTFAnimationPlugin.html)
  1562. Manages playback of GLTF animations.
  1563. The GLTF animations can be created in any 3d software that supports GLTF export like Blender.
  1564. If animations from multiple files are loaded, they will be merged in a single root object and played together.
  1565. The time playback is managed automatically, but can be controlled manually by setting {@link autoIncrementTime} to false and using {@link setTime} to set the time.
  1566. This plugin is made for playing, pausing, stopping, all the animations at once, while it is possible to play individual animations, it is not recommended.
  1567. To play individual animations, with custom choreography, use the {@link GLTFAnimationPlugin.animations} property to get reference to the animation clips and actions. Create your own mixers and control the animation playback like in three.js
  1568. ## PopmotionPlugin
  1569. [//]: # (todo: image)
  1570. Example: https://threepipe.org/examples/#popmotion-plugin/
  1571. Source Code: [src/plugins/animation/PopmotionPlugin.ts](./src/plugins/animation/PopmotionPlugin.ts)
  1572. API Reference: [PopmotionPlugin](https://threepipe.org/docs/classes/PopmotionPlugin.html)
  1573. Provides animation/tweening capabilities to the viewer using the [popmotion.io](https://popmotion.io/) library.
  1574. Overrides the driver in popmotion to sync with the viewer and provide ways to store and stop animations.
  1575. ```typescript
  1576. import {PopmotionPlugin, ThreeViewer} from 'threepipe'
  1577. const viewer = new ThreeViewer({...})
  1578. const cube = viewer.scene.getObjectByName('cube');
  1579. const popmotion = viewer.addPluginSync(new PopmotionPlugin())
  1580. // Move the object cube 1 unit up.
  1581. const anim = popmotion.animateTarget(cube, 'position', {
  1582. to: cube.position.clone().add(new Vector3(0,1,0)),
  1583. duration: 500, // ms
  1584. onComplete: () => isMovedUp = true,
  1585. onStop: () => throw(new Error('Animation stopped')),
  1586. })
  1587. // Alternatively, set the property directly in onUpdate.
  1588. const anim1 = popmotion.animate({
  1589. from: cube.position.y,
  1590. to: cube.position.y + 1,
  1591. duration: 500, // ms
  1592. onUpdate: (v) => {
  1593. cube.position.setY(v)
  1594. cube.setDirty()
  1595. },
  1596. onComplete: () => isMovedUp = true,
  1597. onStop: () => throw(new Error('Animation stopped')),
  1598. onEnd: () => console.log('Animation ended'), // This runs after both onComplete and onStop
  1599. })
  1600. // await for animation. This promise will reject only if an exception is thrown in onStop or onComplete. onStop rejects if throwOnStop is true
  1601. await anim.promise.catch((e)=>{
  1602. console.log(e, 'animation stopped before completion')
  1603. });
  1604. // or stop the animation
  1605. // anim.stop()
  1606. // Animate the color
  1607. await popmotion.animateAsync({ // Also await for the animation.
  1608. from: '#' + cube.material.color.getHexString(),
  1609. to: '#' + new Color().setHSL(Math.random(), 1, 0.5).getHexString(),
  1610. duration: 1000, // 1s
  1611. onUpdate: (v) => {
  1612. cube.material.color.set(v)
  1613. cube.material.setDirty()
  1614. },
  1615. })
  1616. ```
  1617. Note: The animation is started when the animate or animateAsync function is called.
  1618. ## CameraViewPlugin
  1619. [//]: # (todo: image)
  1620. Example: https://threepipe.org/examples/#camera-view-plugin/
  1621. Source Code: [src/plugins/animation/CameraViewPlugin.ts](./src/plugins/animation/CameraViewPlugin.ts)
  1622. API Reference: [CameraViewPlugin](https://threepipe.org/docs/classes/CameraViewPlugin.html)
  1623. CameraViewPlugin adds support to save and load camera views, which can then be animated to.
  1624. It uses PopmotionPlugin internally to animate any camera to a saved view or to loop through all the saved views.
  1625. It also provides a UI to manage the views.
  1626. ```typescript
  1627. import {CameraViewPlugin, ThreeViewer, CameraView, Vector3, Quaternion, EasingFunctions, timeout} from 'threepipe'
  1628. const viewer = new ThreeViewer({...})
  1629. const cameraViewPlugin = viewer.addPluginSync(new CameraViewPlugin())
  1630. const intialView = cameraViewPlugin.getView()
  1631. // or = viewer.scene.mainCamera.getView()
  1632. // create a new view
  1633. const view = new CameraView(
  1634. 'My View', // name
  1635. new Vector3(0, 0, 10), // position
  1636. new Vector3(0, 0, 0), // target
  1637. new Quaternion(0, 0, 0, 1), // quaternion rotation
  1638. 1 // zoom
  1639. )
  1640. // or clone a view
  1641. const view2 = intialView.clone()
  1642. view2.position.add(new Vector3(0, 5, 0)) // move up 5 units
  1643. // animate the main camera to a view
  1644. await cameraViewPlugin.animateToView(
  1645. view,
  1646. 2000, // in ms, = 2sec
  1647. EasingFunctions.easeInOut,
  1648. ).catch(()=>console.log('Animation stopped'))
  1649. // stop any/all animations
  1650. cameraViewPlugin.stopAllAnimations()
  1651. // add views to the plugin
  1652. cameraViewPlugin.addView(view)
  1653. cameraViewPlugin.addView(view2)
  1654. cameraViewPlugin.addView(intialView)
  1655. cameraViewPlugin.addCurrentView() // adds the current view of the main camera
  1656. // loop through all the views once
  1657. cameraViewPlugin.animDuration = 2000 // default duration
  1658. cameraViewPlugin.animEase = EasingFunctions.easeInOutSine // default easing
  1659. await cameraViewPlugin.animateAllViews()
  1660. // loop through all the views forever
  1661. cameraViewPlugin.viewLooping = true
  1662. await timeout(10000) // wait for some time
  1663. // stop looping
  1664. cameraViewPlugin.viewLooping = false
  1665. ```
  1666. ## RenderTargetPreviewPlugin
  1667. [//]: # (todo: image)
  1668. Example: https://threepipe.org/examples/#render-target-preview/
  1669. Source Code: [src/plugins/ui/RenderTargetPreviewPlugin.ts](./src/plugins/ui/RenderTargetPreviewPlugin.ts)
  1670. API Reference: [RenderTargetPreviewPlugin](https://threepipe.org/docs/classes/RenderTargetPreviewPlugin.html)
  1671. RenderTargetPreviewPlugin is a useful development and debugging plugin that renders any registered render-target to the screen in small collapsable panels.
  1672. ```typescript
  1673. import {ThreeViewer, RenderTargetPreviewPlugin, NormalBufferPlugin} from 'threepipe'
  1674. const viewer = new ThreeViewer({...})
  1675. const normalPlugin = viewer.addPluginSync(new NormalBufferPlugin(HalfFloatType))
  1676. const previewPlugin = viewer.addPluginSync(new RenderTargetPreviewPlugin())
  1677. // Show the normal buffer in a panel
  1678. previewPlugin.addTarget(()=>normalPlugin.target, 'normal', false, false)
  1679. ```
  1680. ## GeometryUVPreviewPlugin
  1681. [//]: # (todo: image)
  1682. Example: https://threepipe.org/examples/#geometry-uv-preview/
  1683. Source Code: [src/plugins/ui/GeometryUVPreviewPlugin.ts](./src/plugins/ui/GeometryUVPreviewPlugin.ts)
  1684. API Reference: [GeometryUVPreviewPlugin](https://threepipe.org/docs/classes/GeometryUVPreviewPlugin.html)
  1685. GeometryUVPreviewPlugin is a useful development and debugging plugin
  1686. that adds a panel to the viewer to show the UVs of a geometry.
  1687. ```typescript
  1688. import {ThreeViewer, GeometryUVPreviewPlugin, SphereGeometry} from 'threepipe'
  1689. const viewer = new ThreeViewer({...})
  1690. const previewPlugin = viewer.addPluginSync(new GeometryUVPreviewPlugin())
  1691. const geometry = new SphereGeometry(1, 32, 32)
  1692. // Show the normal buffer in a panel
  1693. previewPlugin.addGeometry(geometry, 'sphere')
  1694. ```
  1695. ## FrameFadePlugin
  1696. [//]: # (todo: image)
  1697. Example: https://threepipe.org/examples/#frame-fade-plugin/
  1698. Source Code: [src/plugins/pipeline/FrameFadePlugin.ts](./src/plugins/pipeline/FrameFadePlugin.ts)
  1699. API Reference: [FrameFadePlugin](https://threepipe.org/docs/classes/FrameFadePlugin.html)
  1700. FrameFadePlugin adds a post-render pass to the render manager and blends the last frame with the current frame over time. This is useful for creating smooth transitions between frames for example when changing the camera position, material, object properties, etc to avoid a sudden jump.
  1701. ```typescript
  1702. import {ThreeViewer, FrameFadePlugin} from 'threepipe'
  1703. const viewer = new ThreeViewer({...})
  1704. const fadePlugin = viewer.addPluginSync(new FrameFadePlugin())
  1705. // Make some changes in the scene (any visual change that needs to be faded)
  1706. // Start transition and wait for it to finish
  1707. await fadePlugin.startTransition(400) // duration in ms
  1708. ```
  1709. To stop a transition, call `fadePlugin.stopTransition()`. This will immediately set the current frame to the last frame and stop the transition. The transition is also automatically stopped when the camera is moved or some pointer event occurs on the canvas.
  1710. The plugin automatically tracks `setDirty()` function calls in objects, materials and the scene. It can be triggerred by calling `setDirty` on any material or object in the scene. Check the [example](https://threepipe.org/examples/#frame-fade-plugin/) for a demo. This can be disabled by options in the plugin.
  1711. ## VignettePlugin
  1712. [//]: # (todo: image)
  1713. Example: https://threepipe.org/examples/#vignette-plugin/
  1714. Source Code: [src/plugins/postprocessing/VignettePlugin.ts](./src/plugins/postprocessing/VignettePlugin.ts)
  1715. API Reference: [VignettePlugin](https://threepipe.org/docs/classes/VignettePlugin.html)
  1716. VignettePlugin adds a post-processing material extension to the ScreenPass in render manager
  1717. that applies a vignette effect to the final render. The parameters `power` and `color` can be changed to customize the effect.
  1718. ```typescript
  1719. import {ThreeViewer, VignettePlugin} from 'threepipe'
  1720. const viewer = new ThreeViewer({...})
  1721. const vignettePlugin = viewer.addPluginSync(VignettePlugin)
  1722. // Change the vignette color
  1723. vignettePlugin.power = 1
  1724. vignettePlugin.color = new Color(0.5, 0, 0)
  1725. // or
  1726. // vignettePlugin.color.set('#ff0000'); vignettePlugin.setDirty() // Call setDirty to tell the plugin that color has changed
  1727. ```
  1728. ## ChromaticAberrationPlugin
  1729. [//]: # (todo: image)
  1730. Example: https://threepipe.org/examples/#chromatic-aberration-plugin/
  1731. Source Code: [src/plugins/postprocessing/ChromaticAberrationPlugin.ts](./src/plugins/postprocessing/ChromaticAberrationPlugin.ts)
  1732. API Reference: [ChromaticAberrationPlugin](https://threepipe.org/docs/classes/ChromaticAberrationPlugin.html)
  1733. ChromaticAberrationPlugin adds a post-processing material extension to the ScreenPass in render manager
  1734. that applies a chromatic-aberration effect to the final render. The parameter `intensity` can be changed to customize the effect.
  1735. ```typescript
  1736. import {ThreeViewer, ChromaticAberrationPlugin} from 'threepipe'
  1737. const viewer = new ThreeViewer({...})
  1738. const chromaticAberrationPlugin = viewer.addPluginSync(ChromaticAberrationPlugin)
  1739. // Change the chromaticAberration color
  1740. chromaticAberrationPlugin.intensity = 0.5
  1741. ```
  1742. ## FilmicGrainPlugin
  1743. [//]: # (todo: image)
  1744. Example: https://threepipe.org/examples/#filmic-grain-plugin/
  1745. Source Code: [src/plugins/postprocessing/FilmicGrainPlugin.ts](./src/plugins/postprocessing/FilmicGrainPlugin.ts)
  1746. API Reference: [FilmicGrainPlugin](https://threepipe.org/docs/classes/FilmicGrainPlugin.html)
  1747. FilmicGrainPlugin adds a post-processing material extension to the ScreenPass in render manager
  1748. that applies a filmic-grain effect to the final render. The parameters `power` and `color` can be changed to customize the effect.
  1749. ```typescript
  1750. import {ThreeViewer, FilmicGrainPlugin} from 'threepipe'
  1751. const viewer = new ThreeViewer({...})
  1752. const filmicGrainPlugin = viewer.addPluginSync(FilmicGrainPlugin)
  1753. // Change the filmicGrain color
  1754. filmicGrainPlugin.intensity = 10
  1755. filmicGrainPlugin.multiply = false
  1756. ```
  1757. ## NoiseBumpMaterialPlugin
  1758. [//]: # (todo: image)
  1759. Example: https://threepipe.org/examples/#noise-bump-material-plugin/
  1760. Source Code: [src/plugins/material/NoiseBumpMaterialPlugin.ts](./src/plugins/material/NoiseBumpMaterialPlugin.ts)
  1761. API Reference: [NoiseBumpMaterialPlugin](https://threepipe.org/docs/classes/NoiseBumpMaterialPlugin.html)
  1762. NoiseBumpMaterialPlugin adds a material extension to PhysicalMaterial to add support for sparkle bump / noise bump by creating procedural bump map from noise to simulate sparkle flakes.
  1763. It uses voronoise function from blender along with several additions to generate the noise for the generation.
  1764. It also adds a UI to the material to edit the settings.
  1765. It uses `WEBGI_materials_noise_bump` glTF extension to save the settings in glTF/glb files.
  1766. ```typescript
  1767. import {ThreeViewer, NoiseBumpMaterialPlugin} from 'threepipe'
  1768. const viewer = new ThreeViewer({...})
  1769. const noiseBump = viewer.addPluginSync(NoiseBumpMaterialPlugin)
  1770. // Add noise bump to a material
  1771. NoiseBumpMaterialPlugin.AddNoiseBumpMaterial(material, {
  1772. flakeScale: 300,
  1773. })
  1774. // Change properties with code or use the UI
  1775. material.userData._noiseBumpMat!.bumpNoiseParams = [1, 1]
  1776. material.setDirty()
  1777. // Disable
  1778. material.userData._noiseBumpMat!.hasBump = false
  1779. material.setDirty()
  1780. ```
  1781. ## CustomBumpMapPlugin
  1782. [//]: # (todo: image)
  1783. Example: https://threepipe.org/examples/#custom-bump-map-plugin/
  1784. Source Code: [src/plugins/material/CustomBumpMapPlugin.ts](./src/plugins/material/CustomBumpMapPlugin.ts)
  1785. API Reference: [CustomBumpMapPlugin](https://threepipe.org/docs/classes/CustomBumpMapPlugin.html)
  1786. CustomBumpMapPlugin adds a material extension to PhysicalMaterial to support custom bump maps.
  1787. A Custom bump map is similar to the built-in bump map, but allows using an extra bump map and scale to give a combined effect.
  1788. This plugin also has support for bicubic filtering of the custom bump map and is enabled by default.
  1789. It also adds a UI to the material to edit the settings.
  1790. It uses `WEBGI_materials_custom_bump_map` glTF extension to save the settings in glTF/glb files.
  1791. ```typescript
  1792. import {ThreeViewer, CustomBumpMapPlugin} from 'threepipe'
  1793. const viewer = new ThreeViewer({...})
  1794. const customBump = viewer.addPluginSync(CustomBumpMapPlugin)
  1795. // Add noise bump to a material
  1796. customBump.enableCustomBump(material, bumpMap, 0.2)
  1797. // Change properties with code or use the UI
  1798. material.userData._customBumpMat = texture
  1799. material.setDirty()
  1800. // Disable
  1801. material.userData._hasCustomBump = false
  1802. // or
  1803. material.userData._customBumpMat = null
  1804. material.setDirty()
  1805. ```
  1806. ## ClearcoatTintPlugin
  1807. [//]: # (todo: image)
  1808. Example: https://threepipe.org/examples/#clearcoat-tint-plugin/
  1809. Source Code: [src/plugins/material/ClearcoatTintPlugin.ts](./src/plugins/material/ClearcoatTintPlugin.ts)
  1810. API Reference: [ClearcoatTintPlugin](https://threepipe.org/docs/classes/ClearcoatTintPlugin.html)
  1811. ClearcoatTintPlugin adds a material extension to PhysicalMaterial which adds tint and thickness to the built-in clearcoat properties.
  1812. It also adds a UI to the material to edit the settings.
  1813. It uses `WEBGI_materials_clearcoat_tint` glTF extension to save the settings in glTF/glb files.
  1814. ```typescript
  1815. import {ThreeViewer, ClearcoatTintPlugin} from 'threepipe'
  1816. const viewer = new ThreeViewer({...})
  1817. const clearcoatTint = viewer.addPluginSync(ClearcoatTintPlugin)
  1818. material.clearcoat = 1
  1819. // add initial properties
  1820. ClearcoatTintPlugin.AddClearcoatTint(material, {
  1821. tintColor: '#ff0000',
  1822. thickness: 1,
  1823. })
  1824. // Change properties with code or use the UI
  1825. material.userData._clearcoatTint!.tintColor = '#ff0000'
  1826. material.setDirty()
  1827. // Disable
  1828. material.userData._clearcoatTint.enableTint = false
  1829. material.setDirty()
  1830. ```
  1831. ## FragmentClippingExtensionPlugin
  1832. [//]: # (todo: image)
  1833. Example: https://threepipe.org/examples/#fragment-clipping-extension-plugin/
  1834. Source Code: [src/plugins/materials/FragmentClippingExtensionPlugin.ts](./src/plugins/material/FragmentClippingExtensionPlugin.ts)
  1835. API Reference: [FragmentClippingExtensionPlugin](https://threepipe.org/docs/classes/FragmentClippingExtensionPlugin.html)
  1836. FragmentClippingExtensionPlugin adds a material extension to PhysicalMaterial to add support for fragment clipping.
  1837. Fragment clipping allows to clip fragments of the material in screen space or world space based on a circle, rectangle, plane, sphere, etc.
  1838. It uses fixed SDFs with params defined by the user for clipping.
  1839. It also adds a UI to the material to edit the settings.
  1840. It uses `WEBGI_materials_fragment_clipping_extension` glTF extension to save the settings in glTF/glb files.
  1841. ```typescript
  1842. import {ThreeViewer, FragmentClippingExtensionPlugin} from 'threepipe'
  1843. const viewer = new ThreeViewer({...})
  1844. const fragmentClipping = viewer.addPluginSync(FragmentClippingExtensionPlugin)
  1845. // add initial properties
  1846. FragmentClippingExtensionPlugin.AddFragmentClipping(material, {
  1847. clipPosition: new Vector4(0.5, 0.5, 0, 0),
  1848. clipParams: new Vector4(0.1, 0.05, 0, 1),
  1849. })
  1850. // Change properties with code or use the UI
  1851. material.userData._fragmentClipping!.clipPosition.set(0, 0, 0, 0)
  1852. material.setDirty()
  1853. // Disable
  1854. material.userData._clearcoatTint.clipEnabled = false
  1855. material.setDirty()
  1856. ```
  1857. ## HDRiGroundPlugin
  1858. [//]: # (todo: image)
  1859. Example: https://threepipe.org/examples/#hdri-ground-plugin/
  1860. Source Code: [src/plugins/extras/HDRiGroundPlugin.ts](./src/plugins/extras/HDRiGroundPlugin.ts)
  1861. API Reference: [HDRiGroundPlugin](https://threepipe.org/docs/classes/HDRiGroundPlugin.html)
  1862. HDRiGroundPlugin patches the background shader in the renderer to add support for ground projected environment map/skybox. Works simply by setting the background same as the environemnt and enabling the plugin.
  1863. The world radius, tripod height, and origin position(center offset) can be set in the plugin.
  1864. The plugin is disabled by default when added. Set `.enabled` to enable it or pass `true` in the constructor.
  1865. If the background is not the same as the environment when enabled, the user will be prompted for this, unless `promptOnBackgroundMismatch` is set to `false` in the plugin.
  1866. ```typescript
  1867. import {ThreeViewer, HDRiGrounPlugin} from 'threepipe'
  1868. const viewer = new ThreeViewer({...})
  1869. const hdriGround = viewer.addPluginSync(new HDRiGrounPlugin())
  1870. // Load an hdr environment map
  1871. await viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr')
  1872. // set background to environment
  1873. viewer.scene.background = 'environment'
  1874. // or
  1875. // viewer.scene.background = viewer.scene.environemnt
  1876. // enable the plugin
  1877. hdriGround.enabled = true
  1878. ```
  1879. Check the [example](https://threepipe.org/examples/#hdri-ground-plugin/) for a demo.
  1880. ## VirtualCamerasPlugin
  1881. [//]: # (todo: image)
  1882. Example: https://threepipe.org/examples/#virtual-cameras-plugin/
  1883. Source Code: [src/plugins/rendering/VirtualCamerasPlugin.ts](./src/plugins/rendering/VirtualCamerasPlugin.ts)
  1884. API Reference: [VirtualCamerasPlugin](https://threepipe.org/docs/classes/VirtualCamerasPlugin.html)
  1885. VirtualCamerasPlugin adds support for rendering to multiple virtual cameras in the viewer. These cameras are rendered in preRender callback just before the main camera is rendered. The virtual cameras can be added to the plugin and removed from it.
  1886. The feed to the virtual camera is rendered to a Render Target texture which can be accessed and re-rendered in the scene or used in other plugins.
  1887. ```typescript
  1888. import {ThreeViewer, VirtualCamerasPlugin} from 'threepipe'
  1889. const viewer = new ThreeViewer({...})
  1890. const hdriGround = viewer.addPluginSync(new VirtualCamerasPlugin())
  1891. const camera = new PerspectiveCamera2('orbit', viewer.canvas, false, 45, 1)
  1892. camera.name = name
  1893. camera.position.set(0, 5, 0)
  1894. camera.target.set(0, 0.25, 0)
  1895. camera.userData.autoLookAtTarget = true // automatically look at the target (in setDirty)
  1896. camera.setDirty()
  1897. camera.addEventListener('update', ()=>{
  1898. viewer.setDirty() // if the camera is not added to the scene it wont update automatically when camera.setDirty is called(like from the UI)
  1899. })
  1900. const vCam = virtualCameras.addCamera(camera)
  1901. console.log(vCam.target) // target is a WebGLRenderTarget/IRenderTarget
  1902. ```
  1903. Check the [virtual camera](https://threepipe.org/examples/#hdri-ground-plugin/) example for using the texture in the scene.
  1904. ## Rhino3dmLoadPlugin
  1905. Example: https://threepipe.org/examples/#rhino3dm-load/
  1906. Source Code: [src/plugins/import/Rhino3dmLoadPlugin.ts](./src/plugins/import/Rhino3dmLoadPlugin.ts)
  1907. API Reference: [Rhino3dmLoadPlugin](https://threepipe.org/docs/classes/Rhino3dmLoadPlugin.html)
  1908. Adds support for loading .3dm files generated by [Rhino 3D](https://www.rhino3d.com/). This plugin includes some changes with how 3dm files are loaded in three.js. The changes are around loading layer and primitive properties when set as reference in the 3dm files.
  1909. It also adds some helpful options to process the model after load.
  1910. ```typescript
  1911. import {Rhino3dmLoadPlugin} from 'threepipe'
  1912. const rhino3dmPlugin = viewer.addPluginSync(new Rhino3dmLoadPlugin())
  1913. rhino3dmPlugin.importMaterials = true // import materials source from 3dm file
  1914. rhino3dmPlugin.forceLayerMaterials = true // force material source to be layer in 3dm file.
  1915. rhino3dmPlugin.hideLineMesh = true // hide all lines and points in the model.
  1916. rhino3dmPlugin.replaceWithInstancedMesh = true // replace meshes with the same parent, geometry and material with a single instance mesh.
  1917. const mesh = await viewer.load('file.3dm')
  1918. ```
  1919. ## PLYLoadPlugin
  1920. Example: https://threepipe.org/examples/#ply-load/
  1921. Source Code: [src/plugins/import/PLYLoadPlugin.ts](./src/plugins/import/PLYLoadPlugin.ts)
  1922. API Reference: [PLYLoadPlugin](https://threepipe.org/docs/classes/PLYLoadPlugin.html)
  1923. Adds support for loading .ply ([Polygon file format](https://en.wikipedia.org/wiki/PLY_(file_format))) files.
  1924. ```typescript
  1925. import {PLYLoadPlugin} from 'threepipe'
  1926. viewer.addPluginSync(new PLYLoadPlugin())
  1927. const mesh = await viewer.load('file.ply')
  1928. ```
  1929. ## USDZLoadPlugin
  1930. Example: https://threepipe.org/examples/#usdz-load/
  1931. Source Code: [src/plugins/import/USDZLoadPlugin.ts](./src/plugins/import/USDZLoadPlugin.ts)
  1932. API Reference: [USDZLoadPlugin](https://threepipe.org/docs/classes/USDZLoadPlugin.html)
  1933. Adds support for loading .usdz and .usda ([Universal Scene Description](https://graphics.pixar.com/usd/docs/index.html)) files.
  1934. ```typescript
  1935. import {USDZLoadPlugin} from 'threepipe'
  1936. viewer.addPluginSync(new USDZLoadPlugin())
  1937. const mesh = await viewer.load('file.usdz')
  1938. const mesh2 = await viewer.load('file.usda')
  1939. ```
  1940. ## STLLoadPlugin
  1941. Example: https://threepipe.org/examples/#stl-load/
  1942. Source Code: [src/plugins/import/STLLoadPlugin.ts](./src/plugins/import/STLLoadPlugin.ts)
  1943. API Reference: [STLLoadPlugin](https://threepipe.org/docs/classes/STLLoadPlugin.html)
  1944. Adds support for loading .stl ([Stereolithography](https://en.wikipedia.org/wiki/STL_(file_format))) files.
  1945. ```typescript
  1946. import {STLLoadPlugin} from 'threepipe'
  1947. viewer.addPluginSync(new STLLoadPlugin())
  1948. const mesh = await viewer.load('file.stl')
  1949. ```
  1950. ## KTX2LoadPlugin
  1951. Example: https://threepipe.org/examples/#ktx2-load/
  1952. Source Code: [src/plugins/import/KTX2LoadPlugin.ts](./src/plugins/import/KTX2LoadPlugin.ts)
  1953. API Reference: [KTX2LoadPlugin](https://threepipe.org/docs/classes/KTX2LoadPlugin.html)
  1954. Adds support for loading .ktx2 ([Khronos Texture](https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/) files.
  1955. KTX2LoadPlugin also adds support for exporting loaded .ktx2 files in glTF files with the [KHR_texture_basisu](https://www.khronos.org/registry/KHR/textures/2.0-extensions/KHR_texture_basisu/) extension.
  1956. ```typescript
  1957. import {KTX2LoadPlugin} from 'threepipe'
  1958. viewer.addPluginSync(new KTX2LoadPlugin())
  1959. const texture = await viewer.load('file.ktx2')
  1960. ```
  1961. ## KTXLoadPlugin
  1962. Example: https://threepipe.org/examples/#ktx-load/
  1963. Source Code: [src/plugins/import/KTXLoadPlugin.ts](./src/plugins/import/KTXLoadPlugin.ts)
  1964. API Reference: [KTXLoadPlugin](https://threepipe.org/docs/classes/KTXLoadPlugin.html)
  1965. Adds support for loading .ktx ([Khronos Texture](https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/) files.
  1966. Note: This plugin only adds support for loading .ktx file, and not exporting them in the bundled .glb. Use .ktx2 files instead of .ktx files for better compression and performance.
  1967. ```typescript
  1968. import {KTXLoadPlugin} from 'threepipe'
  1969. viewer.addPluginSync(new KTXLoadPlugin())
  1970. const texture = await viewer.load('file.ktx')
  1971. ```
  1972. # @threepipe Packages
  1973. Additional plugins can be found in the [plugins](plugins/) directory.
  1974. These add support for integrating with other libraries, adding new features, and other functionality with different licenses.
  1975. ## @threepipe/plugin-tweakpane
  1976. Tewakpane UI plugin for ThreePipe
  1977. [//]: # (todo: image)
  1978. Example: https://threepipe.org/examples/#viewer-uiconfig/
  1979. Source Code: [plugins/tweakpane/src/TweakpaneUiPlugin.ts](plugins/tweakpane/src/TweakpaneUiPlugin.ts)
  1980. API Reference: [TweakpaneUiPlugin](https://threepipe.org/plugins/tweakpane/docs/classes/TweakpaneUiPlugin.html)
  1981. NPM: `npm install @threepipe/plugin-tweakpane`
  1982. CDN: https://threepipe.org/plugins/tweakpane/dist/index.mjs
  1983. TweakpaneUiPlugin adds support for using [uiconfig-tweakpane](https://github.com/repalash/uiconfig-tweakpane)
  1984. to create a configuration UI in applications using the [Tweakpane](https://cocopon.github.io/tweakpane/) library.
  1985. The plugin takes the [uiconfig](https://github.com/repalash/uiconfig.js)
  1986. that's defined in the viewer and all the objects to automatically render a UI in the browser.
  1987. ```typescript
  1988. import {IObject3D, ThreeViewer, TonemapPlugin} from 'threepipe'
  1989. import {TweakpaneUiPlugin} from '@threepipe/plugin-tweakpane'
  1990. const viewer = new ThreeViewer({...})
  1991. // Add the plugin
  1992. const plugin = viewer.addPluginSync(new TweakpaneUiPlugin(true)) // true to show expanded the UI by default
  1993. // Add the UI for the viewer
  1994. plugin.appendChild(viewer.uiConfig)
  1995. // Add UI for some plugins
  1996. plugin.setupPlugins(TonemapPlugin, DropzonePlugin)
  1997. ```
  1998. ## @threepipe/plugin-tweakpane-editor
  1999. Tweakpane Editor Plugin for ThreePipe
  2000. [//]: # (todo: image)
  2001. Example: https://threepipe.org/examples/#tweakpane-editor/
  2002. Source Code: [plugins/tweakpane-editor/src/TweakpaneEditorPlugin.ts](plugins/tweakpane-editor/src/TweakpaneEditorPlugin.ts)
  2003. API Reference: [TweakpaneEditorPlugin](https://threepipe.org/plugins/tweakpane-editor/docs/classes/TweakpaneEditorPlugin.html)
  2004. NPM: `npm install @threepipe/plugin-tweakpane-editor`
  2005. CDN: https://threepipe.org/plugins/tweakpane-editor/dist/index.mjs
  2006. TweakpaneEditorPlugin uses TweakpaneUiPlugin to create an editor for editing viewer,
  2007. plugins, model and material configurations in the browser.
  2008. ```typescript
  2009. import {IObject3D, ThreeViewer, TonemapPlugin} from 'threepipe'
  2010. import {TweakpaneEditorPlugin} from '@threepipe/plugin-tweakpane-editor'
  2011. const viewer = new ThreeViewer({...})
  2012. viewer.addPluginSync(new TweakpaneUiPlugin(true))
  2013. const editor = viewer.addPluginSync(new TweakpaneEditorPlugin())
  2014. // Add some plugins to the viewer
  2015. await viewer.addPlugins([
  2016. new ViewerUiConfigPlugin(),
  2017. // new SceneUiConfigPlugin(), // this is already in ViewerUiPlugin
  2018. new DepthBufferPlugin(HalfFloatType, true, true),
  2019. new NormalBufferPlugin(HalfFloatType, false),
  2020. new RenderTargetPreviewPlugin(false),
  2021. ])
  2022. // Load the plugin UI in the editor and tweakpane ui with categories.
  2023. editor.loadPlugins({
  2024. ['Viewer']: [ViewerUiConfigPlugin, SceneUiConfigPlugin, DropzonePlugin, FullScreenPlugin],
  2025. ['GBuffer']: [DepthBufferPlugin, NormalBufferPlugin],
  2026. ['Post-processing']: [TonemapPlugin],
  2027. ['Debug']: [RenderTargetPreviewPlugin],
  2028. })
  2029. ```
  2030. ## @threepipe/plugin-extra-importers
  2031. Exports several plugins to add support for various file types.
  2032. Example: https://threepipe.org/examples/#extra-importer-plugins/
  2033. Source Code: [plugins/extra-importers/src/index.ts](plugins/extra-importers/src/index.ts)
  2034. API Reference: [@threepipe/plugin-extra-importers](https://threepipe.org/plugins/extra-importers/docs)
  2035. NPM: `npm install @threepipe/plugin-extra-importers`
  2036. CDN: https://threepipe.org/plugins/extra-importers/dist/index.mjs
  2037. This package exports several plugins to add support for several file types using the following plugins
  2038. - [TDSLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/TDSLoadPlugin.html) - Load 3DS Max (.3ds) files
  2039. - [ThreeMFLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/ThreeMFLoadPlugin.html) - Load 3MF (.3mf) files
  2040. - [ColladaLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/ColladaLoadPlugin.html) - Load Collada (.dae) files
  2041. - [AMFLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/AMFLoadPlugin.html) - Load AMF (.amf) files
  2042. - [BVHLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/BVHLoadPlugin.html) - Load BVH (.bvh) files
  2043. - [VOXLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/VOXLoadPlugin.html) - Load MagicaVoxel (.vox) files
  2044. - [GCodeLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/GCodeLoadPlugin.html) - Load GCode (.gcode) files
  2045. - [MDDLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/MDDLoadPlugin.html) - Load MDD (.mdd) files
  2046. - [PCDLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/PCDLoadPlugin.html) - Load Point cloud data (.pcd) files
  2047. - [TiltLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/TiltLoadPlugin.html) - Load Tilt Brush (.tilt) files
  2048. - [VRMLLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/VRMLLoadPlugin.html) - Load VRML (.wrl) files
  2049. - [MPDLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/MPDLoadPlugin.html) - Load LDraw (.mpd) files
  2050. - [VTKLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/VTKLoadPlugin.html) - Load VTK (.vtk) files
  2051. - [XYZLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/XYZLoadPlugin.html) - Load XYZ (.xyz) files
  2052. To add all the plugins at once use `extraImporters`. This adds support for loading all the above file types.
  2053. ```typescript
  2054. import {ThreeViewer} from 'threepipe'
  2055. import {extraImporters} from '@threepipe/plugin-extra-importers'
  2056. const viewer = new ThreeViewer({...})
  2057. viewer.addPluginsSync(extraImporters)
  2058. // Now load any file as is.
  2059. const model = await viewer.load<IObject3D>('file.3mf')
  2060. // To load the file as a data url, use the correct mimetype
  2061. const model1 = await viewer.load<IObject3D>('data:model/3mf;base64,...')
  2062. ```
  2063. Remove the `<IObject3D>` if using javascript and not typescript.
  2064. ## @threepipe/plugin-blend-importer
  2065. Exports [BlendImporterPlugin](https://threepipe.org/plugins/blend-importer/docs/classes/BlendLoadPlugin.html) which adds support for loading .blend files.
  2066. It uses [js.blend](https://github.com/acweathersby/js.blend) for parsing blend file structure.
  2067. Note: This is still a WIP.
  2068. Currently working: `Mesh`, `BufferGeometry` and basic `PointLight`.
  2069. To be added: `PhysicalMaterial`, `UnlitMaterial` (similar to blender-gltf-io plugin)
  2070. Example: https://threepipe.org/examples/#blend-load/
  2071. Source Code: [plugins/blend-importer/src/index.ts](plugins/blend-importer/src/index.ts)
  2072. API Reference: [@threepipe/plugin-blend-importer](https://threepipe.org/plugins/blend-importer/docs)
  2073. NPM: `npm install @threepipe/plugin-blend-importer`
  2074. ```typescript
  2075. import {ThreeViewer} from 'threepipe'
  2076. import {BlendLoadPlugin} from '@threepipe/plugin-blend-importer'
  2077. const viewer = new ThreeViewer({...})
  2078. viewer.addPluginSync(BlendLoadPlugin)
  2079. // Now load any .blend file.
  2080. const model = await viewer.load<IObject3D>('path/to/file.blend')
  2081. // To load the file as a data url, use the correct mimetype
  2082. const model1 = await viewer.load<IObject3D>('data:application/x-blender;base64,...')
  2083. ```
  2084. [//]: # ( TODO: The plugin should parse and references to other assets and find them relative to the .blend file or the current location.)