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

README.md 195KB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085
  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. - [React](#react)
  36. - [Vue.js](#vuejs)
  37. - [Svelte](#svelte)
  38. - [NPM/YARN Package](#npmyarn)
  39. - [Installation](#installation)
  40. - [Loading a 3D Model](#loading-a-3d-model)
  41. - [License](#license)
  42. - [Status](#status)
  43. - [Documentation (API Reference)](#documentation)
  44. - [WebGi](#webgi)
  45. - [Contributing](#contributing)
  46. - [Features](#features)
  47. - [File Formats](#file-formats)
  48. - [Loading files](#loading-files)
  49. - [3D models](#3d-models)
  50. - [Materials](#materials)
  51. - [Images/Textures](#imagestextures)
  52. - [zip files](#zip-files)
  53. - [txt, json files](#txt-json-files)
  54. - [Data URLs](#data-urls)
  55. - [Local files, File and Blob](#local-files-file-and-blob)
  56. - [Background, Environment maps](#background-environment-maps)
  57. - [SVG strings](#svg-strings)
  58. - [Exporting files](#exporting-files)
  59. - [Exporting 3D models](#exporting-3d-models)
  60. - [Exporting Materials](#exporting-materials)
  61. - [Exporting Canvas Images](#exporting-canvas-images)
  62. - [Exporting Images/Textures](#exporting-imagestextures)
  63. - [Exporting Render Targets](#exporting-render-targets)
  64. - [Render Pipeline](#render-pipeline)
  65. - [Material Extension](#material-extension)
  66. - [UI Configuration](#ui-configuration)
  67. - [Serialization](#serialization)
  68. - [Plugin System](#plugin-system)
  69. - [Viewer API](#viewer-api)
  70. - [ThreeViewer](#threeviewer)
  71. - [RenderManager](#rendermanager)
  72. - [RootScene](#rootscene)
  73. - [ICamera](#icamera)
  74. - [AssetManager](#assetmanager)
  75. - [AssetImporter](#assetimporter)
  76. - [AssetExporter](#assetexporter)
  77. - [MaterialManager](#materialmanager)
  78. - [Other classes and interfaces](#other-classes-and-interfaces)
  79. - [Plugins](#threepipe-plugins)
  80. - [TonemapPlugin](#tonemapplugin) - Add tonemap to the final screen pass
  81. - [DropzonePlugin](#dropzoneplugin) - Drag and drop local files to import and load
  82. - [ProgressivePlugin](#progressiveplugin) - Post-render pass to blend the last frame with the current frame
  83. - [SSAAPlugin](#ssaaplugin) - Add Super Sample Anti-Aliasing by applying jitter to the camera.
  84. - [DepthBufferPlugin](#depthbufferplugin) - Pre-rendering of depth buffer
  85. - [NormalBufferPlugin](#normalbufferplugin) - Pre-rendering of normal buffer
  86. - [GBufferPlugin](#gbufferplugin) - Pre-rendering of depth-normal and flags buffers in a single pass
  87. - [SSAOPlugin](#ssaoplugin) - Add SSAO(Screen Space Ambient Occlusion) for physical materials.
  88. - [CanvasSnapshotPlugin](#canvassnapshotplugin) - Add support for taking snapshots of the canvas
  89. - [PickingPlugin](#pickingplugin) - Adds support for selecting objects in the viewer with user interactions and selection widgets
  90. - [AssetExporterPlugin](#assetexporterplugin) - Provides options and methods to export the scene, object GLB or Viewer Configuration.
  91. - [LoadingScreenPlugin](#loadingscreenplugin) - Shows a configurable loading screen overlay over the canvas.
  92. - [FullScreenPlugin](#fullscreenplugin) - Adds support for moving the canvas or the container fullscreen mode in browsers
  93. - [InteractionPromptPlugin](#interactionpromptplugin) - Adds an animated hand icon over canvas to prompt the user to interact
  94. - [TransformControlsPlugin](#transformcontrolsplugin) - Adds support for moving, rotating and scaling objects in the viewer with interactive widgets
  95. - [ContactShadowGroundPlugin](#contactshadowgroundplugin) - Adds a ground plane at runtime with contact shadows
  96. - [GLTFAnimationPlugin](#gltfanimationplugin) - Add support for playing and seeking gltf animations
  97. - [PopmotionPlugin](#popmotionplugin) - Integrates with popmotion.io library for animation/tweening
  98. - [CameraViewPlugin](#cameraviewplugin) - Add support for saving, loading, animating, looping between camera views
  99. - [RenderTargetPreviewPlugin](#rendertargetpreviewplugin) - Preview any render target in a UI panel over the canvas
  100. - [GeometryUVPreviewPlugin](#geometryuvpreviewplugin) - Preview UVs of any geometry in a UI panel over the canvas
  101. - [FrameFadePlugin](#framefadeplugin) - Post-render pass to smoothly fade to a new rendered frame over time
  102. - [VignettePlugin](#vignetteplugin) - Add Vignette effect by patching the final screen pass
  103. - [ChromaticAberrationPlugin](#chromaticaberrationplugin) - Add Chromatic Aberration effect by patching the final screen pass
  104. - [FilmicGrainPlugin](#filmicgrainplugin) - Add Filmic Grain effect by patching the final screen pass
  105. - [NoiseBumpMaterialPlugin](#noisebumpmaterialplugin) - Sparkle Bump/Noise Bump material extension for PhysicalMaterial
  106. - [CustomBumpMapPlugin](#custombumpmapplugin) - Custom Bump Map material extension for PhysicalMaterial
  107. - [ClearcoatTintPlugin](#clearcoattintplugin) - Clearcoat Tint material extension for PhysicalMaterial
  108. - [FragmentClippingExtensionPlugin](#fragmentclippingextensionplugin) - Fragment/SDF Clipping material extension for PhysicalMaterial
  109. - [ParallaxMappingPlugin](#parallaxmappingplugin) - Relief Parallax Bump Mapping extension for PhysicalMaterial
  110. - [HDRiGroundPlugin](#hdrigroundplugin) - Add support for ground projected hdri/skybox to the webgl background shader.
  111. - [VirtualCamerasPlugin](#virtualcamerasplugin) - Add support for rendering virtual cameras before the main one every frame.
  112. - [EditorViewWidgetPlugin](#editorviewwidgetplugin) - Adds an interactive ViewHelper/AxisHelper that syncs with the main camera.
  113. - [Object3DWidgetsPlugin](#object3dwidgetsplugin) - Automatically create light and camera helpers/gizmos when they are added to the scene.
  114. - [Object3DGeneratorPlugin](#object3dwidgetsplugin) - Provides UI and API to create scene objects like lights, cameras, meshes, etc.
  115. - [DeviceOrientationControlsPlugin](#deviceorientationcontrolsplugin) - Adds a controlsMode to the mainCamera for device orientation controls(gyroscope rotation control).
  116. - [PointerLockControlsPlugin](#pointerlockcontrolsplugin) - Adds a controlsMode to the mainCamera for pointer lock controls.
  117. - [ThreeFirstPersonControlsPlugin](#threefirstpersoncontrolsplugin) - Adds a controlsMode to the mainCamera for first person controls from threejs.
  118. - [GLTFKHRMaterialVariantsPlugin](#gltfkhrmaterialvariantsplugin) - Support using for variants from KHR_materials_variants extension in gltf models.
  119. - [Rhino3dmLoadPlugin](#rhino3dmloadplugin) - Add support for loading .3dm files
  120. - [PLYLoadPlugin](#plyloadplugin) - Add support for loading .ply files
  121. - [STLLoadPlugin](#stlloadplugin) - Add support for loading .stl files
  122. - [KTX2LoadPlugin](#ktx2loadplugin) - Add support for loading .ktx2 files
  123. - [KTXLoadPlugin](#ktxloadplugin) - Add support for loading .ktx files
  124. - [GLTFMeshOptDecodePlugin](#gltfmeshoptdecodeplugin) - Decode gltf files with EXT_meshopt_compression extension.
  125. - [SimplifyModifierPlugin](#simplifymodifierplugin) - Boilerplate for plugin to simplify geometries
  126. - [MeshOptSimplifyModifierPlugin](#meshoptsimplifymodifierplugin) - Simplify geometries using meshoptimizer library
  127. - [Packages](#threepipe-packages)
  128. - [@threepipe/plugin-tweakpane](#threepipeplugin-tweakpane) Tweakpane UI Plugin
  129. - [@threepipe/plugin-blueprintjs](#threepipeplugin-blueprintjs) BlueprintJs UI Plugin
  130. - [@threepipe/plugin-tweakpane-editor](#threepipeplugin-tweakpane-editor) - Tweakpane Editor Plugin
  131. - [@threepipe/plugin-configurator](#threepipeplugin-configurator) - Provides Material Configurator and Switch Node Plugin to allow users to select variations
  132. - [@threepipe/plugins-extra-importers](#threepipeplugins-extra-importers) - Plugin for loading more file types supported by loaders in three.js
  133. - [@threepipe/plugin-blend-importer](#threepipeplugin-blend-importer) - Blender to add support for loading .blend file
  134. - [@threepipe/plugin-geometry-generator](#threepipeplugin-geometry-generator) - Generate parametric geometry types that can be re-generated from UI/API.
  135. - [@threepipe/plugin-gaussian-splatting](#threepipeplugin-gaussian-splatting) - Gaussian Splatting plugin for loading and rendering splat files
  136. ## Getting Started
  137. ### HTML/JS Quickstart (CDN)
  138. ```html
  139. <canvas id="three-canvas" style="width: 800px; height: 600px;"></canvas>
  140. <script type="module">
  141. import {ThreeViewer, DepthBufferPlugin} from 'https://threepipe.org/dist/index.mjs'
  142. const viewer = new ThreeViewer({canvas: document.getElementById('three-canvas')})
  143. // Add some plugins
  144. viewer.addPluginSync(new DepthBufferPlugin())
  145. // Load an environment map
  146. const envPromise = viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr')
  147. const modelPromise = viewer.load('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf', {
  148. autoCenter: true,
  149. autoScale: true,
  150. })
  151. Promise.all([envPromise, modelPromise]).then(([env, model]) => {
  152. console.log('Loaded', model, env, viewer)
  153. })
  154. </script>
  155. ```
  156. Check it in action: https://threepipe.org/examples/#html-js-sample/
  157. Check out the details about the [ThreeViewer API](#viewer-api) and more [plugins](#threepipe-plugins) below.
  158. ### React
  159. A sample [react](https://react.dev) component in tsx to render a model with an environment map.
  160. ```tsx
  161. import React from 'react'
  162. function ThreeViewerComponent({src, env}: {src: string, env: string}) {
  163. const canvasRef = React.useRef(null)
  164. React.useEffect(() => {
  165. const viewer = new ThreeViewer({canvas: canvasRef.current})
  166. const envPromise = viewer.setEnvironmentMap(env)
  167. const modelPromise = viewer.load(src)
  168. Promise.all([envPromise, modelPromise])
  169. return () => {
  170. viewer.dispose()
  171. }
  172. }, [])
  173. return (
  174. <canvas id="three-canvas" style={{width: 800, height: 600}} ref={canvasRef} />
  175. )
  176. }
  177. ```
  178. Check it in action: https://threepipe.org/examples/#react-tsx-sample/
  179. Other examples in js: https://threepipe.org/examples/#react-js-sample/ and jsx: https://threepipe.org/examples/#react-jsx-sample/
  180. ### Vue.js
  181. A sample [vue.js](https://vuejs.org/) component in js to render a model with an environment map.
  182. ```js
  183. const ThreeViewerComponent = {
  184. setup() {
  185. const canvasRef = ref(null);
  186. onMounted(() => {
  187. const viewer = new ThreeViewer({ canvas: canvasRef.value });
  188. const envPromise = viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr');
  189. const modelPromise = viewer.load('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf');
  190. Promise.all([envPromise, modelPromise])
  191. onBeforeUnmount(() => {
  192. viewer.dispose();
  193. });
  194. });
  195. return { canvasRef };
  196. },
  197. };
  198. ```
  199. Check it in action: https://threepipe.org/examples/#vue-html-sample/
  200. Another example with Vue SFC(Single file component): https://threepipe.org/examples/#vue-sfc-sample/
  201. ### Svelte
  202. A sample [svelte](https://svelte.dev/) component in js to render a model with an environment map.
  203. ```html
  204. <script>
  205. import {onDestroy, onMount} from 'svelte';
  206. import {ThreeViewer} from 'threepipe';
  207. let canvasRef;
  208. let viewer;
  209. onMount(() => {
  210. viewer = new ThreeViewer({canvas: canvasRef});
  211. const envPromise = viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr');
  212. const modelPromise = viewer.load('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf');
  213. Promise.all([envPromise, modelPromise])
  214. });
  215. onDestroy(() => viewer.dispose())
  216. </script>
  217. <canvas bind:this={canvasRef} id="three-canvas" style="width: 800px; height: 600px"></canvas>
  218. ```
  219. Check it in action: https://threepipe.org/examples/#svelte-sample/
  220. ### NPM/YARN
  221. ### Installation
  222. ```bash
  223. npm install threepipe
  224. ```
  225. ### Loading a 3D Model
  226. First, create a canvas element in your HTML page:
  227. ```html
  228. <canvas id="three-canvas" style="width: 800px; height: 600px;"></canvas>
  229. ```
  230. Then, import the viewer and create a new instance:
  231. ```typescript
  232. import {ThreeViewer, IObject3D} from 'threepipe'
  233. // Create a viewer
  234. const viewer = new ThreeViewer({canvas: document.getElementById('three-canvas') as HTMLCanvasElement})
  235. // Load an environment map
  236. await viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr')
  237. // Load a model
  238. const result = await viewer.load<IObject3D>('https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf', {
  239. autoCenter: true,
  240. autoScale: true,
  241. })
  242. ```
  243. That's it! You should now see a 3D model on your page.
  244. The 3D model can be opened in the [editor](https://threepipe.org/examples/tweakpane-editor/) 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.
  245. 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.
  246. Check out the GLTF Load example to see it in action or to check the JS equivalent code: https://threepipe.org/examples/#gltf-load/
  247. Check out the [Plugins](#plugin-system) section below to learn how to add additional functionality to the viewer.
  248. ## License
  249. 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).
  250. 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.
  251. ## Status
  252. 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.
  253. Check out [WebGi](https://webgi.xyz/) for an advanced tailor-made solution for e-commerce, jewelry, automobile, apparel, furniture etc.
  254. ## Documentation
  255. Check the list of all functions, classes and types in the [API Reference Docs](https://threepipe.org/docs/).
  256. ## WebGi
  257. 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.
  258. [Homepage](https://webgi.xyz/) &mdash; [Docs](https://webgi.xyz/docs/)
  259. [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/repalash.svg?style=social&label=Follow%20%40pixotronics)](https://twitter.com/pixotronics)
  260. ## Contributing
  261. Contributions to ThreePipe are welcome and encouraged! Feel free to open issues and pull requests on the GitHub repository.
  262. # Features
  263. ## File Formats
  264. ThreePipe Asset Manager supports the import of the following file formats out of the box:
  265. * **Models**: gltf, glb, obj+mtl, fbx, drc
  266. * **Materials**: mat, pmat, bmat (json based), registered material template slugs
  267. * **Images**: webp, png, jpeg, jpg, svg, ico, avif, hdr, exr
  268. * **Misc**: json, vjson, zip, txt
  269. Plugins can add additional formats:
  270. * Models
  271. * 3dm - Using [Rhino3dmLoadPlugin](#Rhino3dmLoadPlugin)
  272. * ply - Using [PLYLoadPlugin](#PLYLoadPlugin)
  273. * usdz - Using [USDZLoadPlugin](#USDZLoadPlugin)
  274. * stl - Using [STLLoadPlugin](#STLLoadPlugin)
  275. * ktx - Using [KTXLoadPlugin](#KTXLoadPlugin)
  276. * ktx2 - Using [KTX2LoadPlugin](#KTX2LoadPlugin)
  277. Plugins to support more model formats are available in the package [@threepipe/plugins-extra-importers](#threepipeplugins-extra-importers) including .3ds,
  278. .3mf, .collada, .amf, .bvh, .vox, .gcode, .mdd, .pcd, .tilt, .wrl, .mpd, .vtk, .xyz
  279. ## Loading files
  280. ThreePipe uses the [AssetManager](https://threepipe.org/docs/classes/AssetManager.html) to load files.
  281. The AssetManager has support for loading files from URLs, local files and data URLs.
  282. 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.
  283. [viewer.load()](https://threepipe.org/docs/classes/ThreeViewer.html#load) is a high-level wrapper for loading files from the AssetManager.
  284. It automatically adds the loaded object to the scene and returns a promise that resolves to the loaded object,
  285. the materials are also automatically registered to the material manager.
  286. AssetManager internally uses [AssetImporter](https://threepipe.org/docs/classes/AssetImporter.html),
  287. which provides a low-level API
  288. for managing three.js [LoadingManager](https://threejs.org/docs/#api/en/loaders/LoadingManager)
  289. and adding and registering loaders for different file types.
  290. 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
  291. to import files from the `AssetImporter`.
  292. viewer.assetManager.loadImported()](https://threepipe.org/docs/classes/AssetManager.html#loadImported)
  293. can then be called to load the imported files after any processing.
  294. The `viewer.load()`, `viewer.assetManager.addAsset()`
  295. and `viewer.assetManager.addAssetSingle()` methods perform combination of `import` and `loadImported`.
  296. ### 3D models
  297. The 3d models are added to `viewer.scene.modelRoot` on `viewer.load` unless some option is specified.
  298. ```typescript
  299. const objectGlb = await viewer.load<IObject3D>('https://example.com/file.glb')
  300. const objectFbx = await viewer.load<IObject3D>('https://example.com/file.fbx')
  301. const objectObj = await viewer.load<IObject3D>('https://example.com/file.obj') // .mtl referenced in obj is automatically loaded
  302. // ... load any 3d model file as an object
  303. ```
  304. Here, we are casting to [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html) type
  305. to get the proper type and autocomplete for the object.
  306. `IObject3D` inherits [Object3D](https://threejs.org/docs/#api/en/core/Object3D) from three.js and adds some additional properties.
  307. For JavaScript, the type can be omitted.
  308. ```javascript
  309. const objectGlb = await viewer.load('https://example.com/file.glb')
  310. ```
  311. 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.
  312. ### Materials
  313. The materials downloaded as PMAT/BMAT/JSON etc from threepipe,
  314. webgi or the editor can be loaded
  315. and registered with the [MaterialManager](https://threepipe.org/docs/classes/MaterialManager)
  316. using the `viewer.load` method.
  317. Custom material types can also be registered by plugins(like dmat for diamonds), which can also be loaded automatically using the `viewer.load` method.
  318. ```typescript
  319. const pMaterial = await viewer.load<PhysicalMaterial>('https://example.com/file.pmat')
  320. const bMaterial = await viewer.load<UnlitMaterial>('https://example.com/file.bmat')
  321. // ... load any material file as a material
  322. ```
  323. 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.
  324. To assign the material on any object, set it to `object.material`
  325. ```typescript
  326. // find a loaded mesh in the scene
  327. const object = viewer.scene.getObjectByName('objectName');
  328. // assign the material
  329. object.material = pMaterial;
  330. ```
  331. To copy the properties without changing the material reference, use `material.copy()` or `material.setValues()` methods.
  332. ```typescript
  333. object.material.copy(pMaterial);
  334. // or use material manager to apply to multiple materials.
  335. viewer.assetManager.materialManager.applyMaterial(pMaterial, 'METAL') // apply props to all materials/objects with the name METAL
  336. ```
  337. TODO: add examples for material load and copy
  338. ### Images/Textures
  339. Images can be loaded using the `viewer.load` method.
  340. 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.
  341. More formats like ktx2, ktx, etc. can be added using plugins.
  342. ```typescript
  343. const texture = await viewer.load<ITexture>('https://example.com/file.png')
  344. // ... load any image file as a texture
  345. ```
  346. Casting to [ITexture](https://threepipe.org/docs/interfaces/ITexture.html) is optional
  347. but recommended to get the proper type and autocomplete for the texture.
  348. It inherits from three.js [Texture](https://threejs.org/docs/#api/en/textures/Texture) and adds some additional properties.
  349. To assign the texture on any material, set it to `material.map`
  350. ```typescript
  351. // find a loaded mesh in the scene
  352. const object = viewer.scene.getObjectByName('objectName');
  353. const material = object.material as PhysicalMaterial;
  354. // assign the texture
  355. material.map = texture;
  356. 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.
  357. ```
  358. Check out the image load example to see it in action or to check the JS equivalent code: https://threepipe.org/examples/#image-load/
  359. ### Zip files
  360. .zip files are automatically unzipped and the files are sent to re-load recursively when loaded with `viewer.load`.
  361. Any level of zip hierarchy is flattened.
  362. Loading files like .gltf with references to assets inside the zip file,
  363. any relative references are also automatically resolved.
  364. This is supported for file types like gltf, glb, obj,
  365. etc which support references to external files and has `root` set to `true in [IImporter](https://threepipe.org/docs/interfaces/IImporter.html).
  366. ```typescript
  367. const objectGltf = await viewer.load<IObject3D>('https://example.com/model.gltf.zip')
  368. ```
  369. 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.
  370. 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.
  371. ```typescript
  372. const textures = await viewer.assetManager.addAsset<ITexture[]>('https://example.com/textures.zip')
  373. const materials = await viewer.assetManager.addAsset<IMaterial[]>('https://example.com/materials.zip')
  374. ```
  375. The auto import of zip contents can be disabled to get the files and blobs in the zip
  376. ```typescript
  377. const zip = await viewer.load<any>('https://example.com/file.zip', {autoImportZipContents: false})
  378. ```
  379. TODO - add example for loading zip files.
  380. ### txt, json files
  381. Text and JSON files can be loaded using the `viewer.load` method and return strings and objects respectively.
  382. ```typescript
  383. const text = await viewer.load<string>('https://example.com/file.txt')
  384. const json = await viewer.load<any>('https://example.com/file.json')
  385. ```
  386. ### Data URLs
  387. 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.
  388. ```typescript
  389. const dataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' // ... some data url
  390. const texture = await viewer.load<ITexture>(dataUrl)
  391. ```
  392. ### Local files, File and Blob
  393. 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.
  394. ```typescript
  395. const file: File|Blob = fileObject // create a new file, blob or get from input element
  396. const text = await viewer.load<IObject>({
  397. // a path/name is required to determine the proper importer by extension. `file.name` can also be used if available
  398. path: 'file.glb',
  399. file
  400. })
  401. ```
  402. The same can be done for any file type.
  403. 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.
  404. ### Background, Environment maps
  405. 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.
  406. ```typescript
  407. await viewer.setEnvironmentMap('https://example.com/file.hdr')
  408. await viewer.setBackgroundMap('https://example.com/file.png')
  409. ```
  410. The same texture can be set to both by setting `setBackground` or `setEnvironment` to true in the options:
  411. ```typescript
  412. await viewer.setEnvironmentMap('https://example.com/file.hdr', {setBackground: true})
  413. ```
  414. Check the HDR Load example to see it in action: https://threepipe.org/examples/#hdr-load/
  415. ### SVG strings
  416. SVG strings can be converted to data urls using the [svgUrl](https://repalash.com/ts-browser-helpers/functions/svgUrl.html) string template function
  417. ```typescript
  418. const svgDataUrl = svgUrl`<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> ... </svg>`;
  419. const texture = await viewer.load<ITexture>(dataUrl)
  420. ```
  421. ### Custom file types
  422. Custom file importers/loaders can be registered to the `AssetImporter` using the `addImporter` method.
  423. ```typescript
  424. class CustomLoader extends FileLoader implements ILoader{
  425. constructor(manager?: LoadingManager) {
  426. super(manager);
  427. }
  428. load(url: string, onLoad: (data: any) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): Mesh {
  429. this.setResponseType('json')
  430. return super.load(url, (json: any)=>{
  431. const mat = new PhysicalMaterial(json)
  432. onLoad?.(mat)
  433. }, onProgress, onError)
  434. }
  435. }
  436. viewer.assetManager.importer.addImporter(new Importer(CustomLoader, ['ext'], ['mime/type'], false))
  437. // load the file
  438. const mat = await viewer.load<PhysicalMaterial>('https://example.com/file.ext')
  439. ```
  440. ## Exporting files
  441. Threepipe has support for exporting various asset type with AssetManager,
  442. as well as support to export viewer and plugin configuration, arbitrary objects etc using the [serialization](#serialization) system.
  443. [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.
  444. AssetManager internally uses [AssetExporter](https://threepipe.org/docs/classes/AssetExporter.html) to export files.
  445. AssetExporter includes some basic exporters for glb, exr, textures,
  446. and materials and a system to register exporters for different file types with plugins or custom exporters.
  447. ### Exporting 3D models
  448. Export the root scene as glb
  449. ```typescript
  450. const blob = await viewer.exportScene({
  451. viewerConfig: true, // default = true. export all viewer and plugin configuration. if false only the model root object is exported.
  452. })
  453. // download the file
  454. downloadBlob(blob, 'scene.glb')
  455. ```
  456. Export a single object from the scene as glb
  457. ```typescript
  458. const object = viewer.scene.getObjectByName('objectName');
  459. const glb: Blob = await viewer.export(object, {
  460. exportExt: 'glb', // default = glb for models
  461. embedUrlImages: true, // default = false. embed images in glb even when url is available.
  462. })
  463. // download the file
  464. downloadBlob(glb, 'object.glb')
  465. ```
  466. Check the example [glb-export](https://threepipe.org/examples/#glb-export/) to see a demo.
  467. ### Exporting Materials
  468. Export a material
  469. ```typescript
  470. const material = viewer.assetManager.materialManager.findMaterialsByName('materialName')[0];
  471. // or
  472. // const material = viewer.scene.getObjectByName('objectName').material;
  473. const blob = await viewer.export(material)
  474. // download the file
  475. downloadBlob(blob, 'material.' + blob.ext)
  476. ```
  477. Check the example [pmat-material-export](https://threepipe.org/examples/#pmat-material-export/) to see a demo.
  478. ### Exporting Canvas Images
  479. Canvas Screenshot/snapshot can be exported as png, jpeg or webp(if supported by the browser)
  480. ```typescript
  481. const blob = await viewer.getScreenshotBlob({mimeType: 'image/' + type, quality: 0.85})
  482. // or to get data url:
  483. // const dataUrl = await viewer.getScreenshotDataUrl({mimeType: 'image/' + type, quality: 0.85})
  484. // download the file
  485. downloadBlob(blob, 'screenshot.' + blob.ext)
  486. ```
  487. Check the example [image-snapshot-export](https://threepipe.org/examples/#image-snapshot-export/) to see a demo.
  488. ### Exporting Textures
  489. Textures can be exported to JSON using `viewer.export` or `AssetExporter`
  490. ```typescript
  491. const texture = await viewer.load('https://example.com/file.jpeg')
  492. const blob = await viewer.export(texture)
  493. downloadBlob(blob, texture.name + '.' + blob.ext)
  494. ```
  495. Render target textures can be exported with `viewer.renderManager.exportRenderTarget` or `viewer.export`,
  496. read about [Exporting Render Targets](#exporting-render-targets) below.
  497. TODO: add examples for texture export
  498. Textures and Uint8 Data Textures can be exported as a data url or copied to a new canvas
  499. ```typescript
  500. // get a base64 data url
  501. const dataUrl = textureToDataUrl(texture, 4096, false, 'image/png') // texture or data texture, max-size, flipY, mimeType
  502. // or copy to a new canvas
  503. const canvas = textureToCanvas(texture, 4096) // texture or data texture, max-size
  504. ```
  505. Data Textures of type Half float and Float can be exported with `viewer.export`
  506. ```typescript
  507. const dataTex = await viewer.load('https://example.com/file.hdr')
  508. const blob = await viewer.export(dataTexture, {exportExt: 'exr'})
  509. ```
  510. Check the example [hdr-to-exr](https://threepipe.org/examples/#hdr-to-exr/) to see a demo of HDR to EXR conversion.
  511. TODO: add support to export unsigned byte textures as png, jpeg, webp
  512. ### Exporting Images/Textures
  513. Exporting Textures as Images with image of types ImageBitmap, HTMLImageElement,
  514. HTMLOrSVGImageElement, CanvasImageSource, HTMLCanvasElement,
  515. OffscreenCanvas can be exported to png data urls with [imageBitmapToBase64](https://repalash.com/ts-browser-helpers/functions/imageBitmapToBase64.html) function.
  516. ```typescript
  517. const texture = await viewer.load('https://example.com/file.jpeg')
  518. const dataUrl = await imageBitmapToBase64(texture.image, 'image/png', 0.85);
  519. ```
  520. TODO: add support for texture export as images in AssetExporter
  521. ### Exporting Render Targets
  522. Unsigned byte render targets can be exported as png, jpeg or webp(if supported by the browser)
  523. ```typescript
  524. const depthPlugin = viewer.addPluginSync(DepthBufferPlugin, UnsignedByteType)
  525. // wait for the first render
  526. const blob = await viewer.export(depthPlugin.target!, {exportExt: 'png'})
  527. if (blob) downloadBlob(blob, target.texture.name + '.' + blob.ext)
  528. ```
  529. Half float and float render targets can be exported as exr
  530. ```typescript
  531. const depthPlugin = viewer.addPluginSync(DepthBufferPlugin, HalfFloatType)
  532. // wait for the first render
  533. const blob = await viewer.export(depthPlugin.target!, {exportExt: 'exr'})
  534. if (blob) downloadBlob(blob, target.texture.name + '.' + blob.ext)
  535. ```
  536. Note: `exportExt` is determined automatically if not specified.
  537. ## Render pipeline
  538. 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.
  539. 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,
  540. but the pass management and sorting is managed by the RenderManager itself.
  541. The RenderManager inherits from [RenderTargetManager](https://threepipe.org/docs/classes/RenderTargetManager.html)
  542. which provides utilities for creating, tracking and destroying dedicated and temporary render targets.
  543. ### Render Targets
  544. Render targets can be created
  545. using the `viewer.renderManager.createTarget` and `viewer.renderManager.createTargetCustom` methods.
  546. These can then be disposed using the `viewer.renderManager.disposeTarget` method when not needed anymore.
  547. Or to create temp targets for one time use `viewer.renderManager.getTempTarget` and `viewer.renderManager.releaseTempTarget` methods.
  548. can be used.
  549. All created render targets are tracked in the RenderManager,
  550. and are resized and disposed automatically when needed along with the viewer.
  551. ```typescript
  552. const newTarget = viewer.renderManager.createTarget({sizeMultiplier: 1})
  553. // or
  554. const newTarget2 = viewer.renderManager.createTarget({size: {
  555. width: 1024,
  556. height: 1024,
  557. },
  558. type: HalfFloatType
  559. })
  560. // or clone an existing target
  561. const newTarget3 = viewer.renderManager.composerTarget.clone()
  562. // for multi-sample render target
  563. const newTarget4 = viewer.renderManager.createTarget({sizeMultiplier: 1, samples: 4})
  564. // or create a custom target
  565. const newTarget5 = viewer.renderManager.createTargetCustom(
  566. {width: 1024, height: 1024},
  567. {type: HalfFloatType},
  568. WebGLCubeRenderTarget
  569. )
  570. // dispose targets
  571. viewer.renderManager.disposeTarget(newTarget)
  572. viewer.renderManager.disposeTarget(newTarget2)
  573. viewer.renderManager.disposeTarget(newTarget3)
  574. viewer.renderManager.disposeTarget(newTarget4)
  575. viewer.renderManager.disposeTarget(newTarget5)
  576. // get a temporary target
  577. const tempTarget = viewer.renderManager.getTempTarget({sizeMultiplier: 1})
  578. // release the temporary target
  579. viewer.renderManager.releaseTempTarget(tempTarget)
  580. ```
  581. Note: Render targets created with a sizeMultiplier are automatically resized when the canvas is resized.
  582. ### Passes
  583. By default, the render pipeline includes 2 passes -
  584. [RenderPass](https://threejs.org/docs/#api/en/postprocessing/RenderPass) for rendering the scene hierarchy and [ScreenPass](https://threejs.org/docs/#api/en/postprocessing/ShaderPass)
  585. for rendering the final output on the canvas.
  586. More passes can be added and removed from the pipeline
  587. using the [registerPass](https://threepipe.org/docs/classes/RenderManager.html#registerPass) and [unregisterPass](https://threepipe.org/docs/classes/RenderManager.html#unregisterPass) methods.
  588. The pipeline passes need
  589. to follow the interface of [IPipelinePass](https://threepipe.org/docs/interfaces/IPipelinePass.html) and [IPipelinePassPlugin](https://threepipe.org/docs/interfaces/IPipelinePassPlugin.html).
  590. Which adds some important parameters over the three.js Pass,
  591. like pass id and support for defining where the pass should be added in the pipeline and it's dependants.
  592. ```typescript
  593. const pass = new GBufferRenderPass('customPass', viewer.renderManager.createTarget({sizeMultiplier: 1}))
  594. pass.before = ['render'] // Add the pass before the render pass
  595. pass.after = [] // Add the pass after these passes (none in this case)
  596. pass.required = ['render'] // render pass is required to be in the pipeline for this
  597. viewer.renderManager.registerPass(pass)
  598. ```
  599. Note:
  600. See [PipelinePassPlugin](https://threepipe.org/docs/classes/PipelinePassPlugin.html) for an abstract plugin
  601. that provides the boilerplate to create a plugin that registers a custom pass in the pipeline.
  602. Check [NormalBufferPlugin](https://threepipe.org/docs/classes/NormalBufferPlugin.html) for an example of that.
  603. Note: All effects in post-processing or material extension need not be a separate pass in the pipeline.
  604. Most effects can be achieved with either extending the scene object material shaders or the Screen Pass material shader
  605. using [Material extension](#material-extension) system
  606. ## Material Extension
  607. Threepipe includes a Material extension system along with a material manager.
  608. The material manager is used to register materials and material extensions.
  609. The material extensions are used to extend any material in the scene,
  610. or any plugin/pass with additional uniforms, defines, shader snippets and provides hooks.
  611. The material extensions are automatically applied to all materials in the scene that are compatible,
  612. when the extension is registered or when the material is added to the scene.
  613. Threepipe includes several built-in materials like
  614. [PhysicalMaterial](https://threepipe.org/docs/classes/PhysicalMaterial.html),
  615. [UnlitMaterial](https://threepipe.org/docs/classes/UnlitMaterial.html),
  616. [ExtendedShaderMaterial](https://threepipe.org/docs/classes/ExtendedShaderMaterial.html), [LegacyPhongMaterial](https://threepipe.org/docs/classes/LegacyPhongMaterial.html),
  617. that include support for extending the material.
  618. Any three.js material can be made extendable,
  619. check the `ShaderPass2` class for a simple example that adds support for material extension to three.js ShaderPass.
  620. The material extensions must follow the [MaterialExtension](https://threepipe.org/docs/interfaces/MaterialExtension.html) interface.
  621. Many plugins create their own material extensions either for the scene materials or shader passes(like the screen pass).
  622. Some plugins like `DepthBufferPlugin` also provides helper material extensions for other custom plugins
  623. to fetch value in the depth buffer.
  624. A sample material extension
  625. ```typescript
  626. const extension: MaterialExtension = {
  627. shaderExtender: (shader)=> {
  628. // change the shader properties like shader.fragmentShader, etc
  629. },
  630. parsFragmentSnippet: ` // add some code before the main function in the fragment shader
  631. uniform sampler2D tTexture;
  632. uniform float opacity;
  633. `,
  634. extraUniforms: {
  635. tTexture: ()=>({value: getTexture()}),
  636. opacity: {value: 1}
  637. // add additional uniforms, these can be IUniform or functions that return IUniform
  638. },
  639. extraDefines: {
  640. ['DEPTH_PACKING']: BasicDepthPacking,
  641. ['SOME_DEFINE']: ()=>"1",
  642. // add additional defines, these can be values or functions that return values
  643. },
  644. priority: 100, // priority when using multiple extensions on the same material
  645. isCompatible: (material) => material.isMeshBasicMaterial, // check if the material is compatible with this extension,
  646. computeCacheKey: (material) => material.uuid, // a custom cache key for the material extension. Shader is recompiled when this is changed
  647. onObjectRender: (object: Object3D, material: IMaterial) => {
  648. // called when some object is rendererd which has a material with this extension.
  649. },
  650. // uiConfig
  651. // check more properties and hooks in the MaterialExtension interface
  652. }
  653. // The extension can be registered to all the materials using the MaterialManager
  654. viewer.assetManager.materialManager.registerMaterialExtension(extension)
  655. // or register it on a single material (like the Screen Pass)
  656. viewer.renderManager.screenPass.material.registerMaterialExtensions([extension])
  657. ```
  658. ## UI Configuration
  659. Most of the classes and plugins in Threepipe include [uiconfig.js](https://repalash.com/uiconfig.js/) support
  660. and can be used to create configuration UIs, 3d configurators and even full-editors.
  661. The UIs are automatically generated based on the configuration object under `.uiConfig` property on all objects.
  662. These are of type [UiObjectConfig](https://repalash.com/uiconfig.js/interfaces/UiObjectConfig.html).
  663. In some classes, the ui configs are also generated using typescript decorators.
  664. The `uiConfig` is also added to all three.js objects and materials when they are added to the scene.
  665. The UIs can be generated at runtime using any of the UI plugins like [TweakpaneUIPlugin](#threepipeplugin-tweakpane), [BlueprintJsUiPlugin](#threepipeplugin-blueprintjs)
  666. An example showing how to create a UI for a material
  667. ```typescript
  668. const ui = viewer.addPluginSync(TweakpaneUiPlugin)
  669. const object = viewer.scene.getObjectByName('objectName');
  670. const material = object.material as PhysicalMaterial;
  671. ui.appendChild(material.uiConfig)
  672. ```
  673. See it in action: https://threepipe.org/examples/#material-uiconfig/
  674. Check more examples showing [Viewer UI](https://threepipe.org/examples/#viewer-uiconfig/),
  675. [Scene UI](https://threepipe.org/examples/#scene-uiconfig/),
  676. [Object UI](https://threepipe.org/examples/#object-uiconfig/), [Camera UI](https://threepipe.org/examples/#camera-uiconfig/)
  677. [TweakpaneEditorPlugin](#threepipeplugin-tweakpane-editor) further uses the Tweakpane configuration panel along with various plugins to create an 3d editor.
  678. Custom UI configuration can be created to generate custom UI for the editor or tweaking.
  679. 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.
  680. Here is a sample of extending the orbit controls class with decorators to automatically generate UI.
  681. ```typescript
  682. @uiPanelContainer('Orbit Controls')
  683. export class OrbitControlsWithUi extends OrbitControls implements IUiConfigContainer {
  684. // for autocomplete
  685. uiConfig?: UiObjectConfig<void, 'panel'>
  686. @uiToggle() enabled = true
  687. @uiToggle() dollyZoom = false
  688. @uiToggle() enableDamping = true
  689. @uiInput() dampingFactor = 0.08
  690. @uiToggle() autoRotate = false
  691. @uiInput() autoRotateSpeed = 2.0
  692. @uiToggle() enableZoom = true
  693. @uiInput() zoomSpeed = 0.15
  694. @uiInput() maxZoomSpeed = 0.20
  695. @uiToggle() enableRotate = true
  696. @uiInput() rotateSpeed = 2.0
  697. @uiToggle() enablePan = true
  698. @uiInput() panSpeed = 1.0
  699. @uiInput() autoPushTarget = false
  700. @uiInput() autoPullTarget = false
  701. @uiInput() minDistance = 0.35
  702. @uiInput() maxDistance = 1000
  703. @uiInput() minZoom = 0.01
  704. @uiInput() maxZoom = 1000
  705. @uiInput() minPolarAngle = 0
  706. @uiInput() maxPolarAngle = Math.PI
  707. @uiInput() minAzimuthAngle = -10000 // should be -Infinity but this breaks the UI
  708. @uiInput() maxAzimuthAngle = 10000
  709. }
  710. ```
  711. Check out the full source code:
  712. [./src/three/controls/OrbitControls3.ts](./src/three/controls/OrbitControls3.ts) for proper implementation
  713. See it in action: https://threepipe.org/examples/#camera-uiconfig/ Open the Camera UI and click on the Orbit Controls panel.
  714. There are many available decorators like `uiToggle`, `uiSlider`, `uiInput`, `uiNumber`, `uiColor`, `uiImage`.
  715. Check the complete list in the [uiconfig.js documentation](https://repalash.com/uiconfig.js/).
  716. The UI configuration can also be created using json objects in both typescript and javascript
  717. ```javascript
  718. const viewer = new ThreeViewer({...})
  719. const ui = viewer.addPluginSync(TweakpaneUiPlugin)
  720. const state = {
  721. position: new Vector3(),
  722. scale: 1,
  723. }
  724. ui.appendChild({
  725. type: 'folder',
  726. label: 'Custom UI',
  727. children: [
  728. {
  729. type: 'vec3',
  730. label: 'Position',
  731. property: [state, 'position']
  732. },
  733. {
  734. type: 'slider',
  735. label: ()=>'Scale', // everything can be a function as well.
  736. property: [state, 'scale'],
  737. bounds: [1, 2],
  738. stepSize: 0.1,
  739. }
  740. ]
  741. })
  742. ```
  743. TODO: create example/codepen for this
  744. ## Serialization
  745. Easy serialization of all threepipe and most three.js objects are supported out of the box using the Asset Manager.
  746. Fine control over serialization is also supported
  747. using the [ThreeSerialization](https://threepipe.org/docs/classes/ThreeSerialization.html) class
  748. Call `ThreeSerialization.serialize` on any object to serialize it.
  749. and `ThreeSerialization.deserialize` to deserialize the serialized object.
  750. This is done by performing a nested serialization of all the properties of the object.
  751. It's possible to implement custom serializers for custom types and classes and is done for three.js primitives,
  752. objects and plugins in threepipe
  753. To make a custom data class that is serializable,
  754. mark it using `@serializable` decorator and any properties using `@serialize` decorator.
  755. ```typescript
  756. @serializable('DataClass')
  757. class DataClass{
  758. @serialize() prop1 = 1
  759. @serialize() prop2 = 'string'
  760. @serialize() prop3 = new Vector3()
  761. @serialize() prop4 = new PhysicalMaterial()
  762. @serialize() prop4 = {
  763. prop1: 1,
  764. prop2: 'string',
  765. prop3: new Vector3(),
  766. prop4: new PhysicalMaterial(),
  767. }
  768. }
  769. const data = new DataClass()
  770. const serialized = ThreeSerialization.serialize(data)
  771. const deserialized = ThreeSerialization.deserialize(serialized)
  772. ```
  773. The classes without a `@serializable` decorator are serialized as plain objects.
  774. These can still include `@serialize` decorator to mark the properties are serializable
  775. but these classes cannot be deserialized into a new instance of the class.
  776. The ThreeViewer and plugins are an example of these.
  777. When deserialized they need an object to deserialize into.
  778. This ensures there is always just one instance.
  779. With this, the serialization system works like `toJSON` and `fromJSON` methods in three.js.
  780. Check the [plugin system](#plugin-system) below for more details on how to mark properties as serializable for plugins.
  781. ```typescript
  782. class CustomClass{
  783. @serialize() prop1 = 1
  784. @serialize() prop2 = 'string'
  785. @serialize() prop3 = new Vector3()
  786. @serialize() prop4 = new PhysicalMaterial()
  787. }
  788. const obj = new DataClass()
  789. const serialized = ThreeSerialization.serialize(data)
  790. // now to deserialize we need to pass in the object to deserialize into
  791. ThreeSerialization.deserialize(serialized, obj)
  792. ```
  793. ## Plugin System
  794. Threepipe includes a plugin system for adding additional features to the viewer in a modular way.
  795. The plugins can be added synchronously or asynchronously using `viewer.addPluginSync` and `viewer.addPlugin` methods respectively.
  796. It is recommended to create custom plugins for reusable features,
  797. as they provide built-in features for ui configuration,
  798. serialization, integration with editors etc and are easy to manage and tree-shake in the code.
  799. Check out the list of plugins in the [Plugin List](#threepipe-plugins) section below.
  800. To create new plugins,
  801. 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.
  802. The only difference is that in async the `onAdded` and `onRemove` functions are async
  803. Here is a sample plugin
  804. ```typescript
  805. @uiFolder("Sample Plugin") // This creates a folder in the Ui. (Supported by TweakpaneUiPlugin)
  806. export class SamplePlugin extends AViewerPluginSync<"sample-1" | "sample-2"> {
  807. // These are the list of events that this plugin can dispatch.
  808. static readonly PluginType = "SamplePlugin"; // This is required for serialization and handling plugins. Also used in viewer.getPluginByType()
  809. @uiToggle() // This creates a checkbox in the Ui. (Supported by TweakpaneUiPlugin)
  810. @serialize() // Adds this property to the list of serializable. This is also used when serializing to glb in AssetExporter.
  811. enabled = true;
  812. // A plugin can have custom properties.
  813. @uiSlider("Some Number", [0, 100], 1) // Adds a slider to the Ui, with custom bounds and step size (Supported by TweakpaneUiPlugin)
  814. @serialize("someNumber")
  815. @onChange(SamplePlugin.prototype._updateParams) // this function will be called whenevr this value changes.
  816. val1 = 0;
  817. // A plugin can have custom properties.
  818. @uiInput("Some Text") // Adds a slider to the Ui, with custom bounds and step size (Supported by TweakpaneUiPlugin)
  819. @onChange(SamplePlugin.prototype._updateParams) // this function will be called whenevr this value changes.
  820. @serialize()
  821. val2 = "Hello";
  822. @uiButton("Print Counters") // Adds a button to the Ui. (Supported by TweakpaneUiPlugin)
  823. public printValues = () => {
  824. console.log(this.val1, this.val2);
  825. this.dispatchEvent({ type: "sample-1", detail: { sample: this.val1 } }); // This will dispatch an event.
  826. }
  827. constructor() {
  828. super();
  829. this._updateParams = this._updateParams.bind(this);
  830. }
  831. private _updateParams() {
  832. console.log("Parameters updated.");
  833. this.dispatchEvent({ type: "sample-2" }); // This will dispatch an event.
  834. }
  835. onAdded(v: ThreeViewer): void {
  836. super.onAdded(v);
  837. // Do some initialization here.
  838. this.val1 = 0;
  839. this.val2 = "Hello";
  840. v.addEventListener("preRender", this._preRender);
  841. v.addEventListener("postRender", this._postRender);
  842. v.addEventListener("preFrame", this._preFrame);
  843. v.addEventListener("postFrame", this._postFrame);
  844. this._viewer!.scene.addEventListener("addSceneObject", this._objectAdded); // this._viewer can also be used while this plugin is attached.
  845. }
  846. onRemove(v: ThreeViewer): void {
  847. // remove dispose objects
  848. v.removeEventListener("preRender", this._preRender);
  849. v.removeEventListener("postRender", this._postRender);
  850. v.removeEventListener("preFrame", this._preFrame);
  851. v.removeEventListener("postFrame", this._postFrame);
  852. this._viewer!.scene.removeEventListener("addSceneObject", this._objectAdded); // this._viewer can also be used while this plugin is attached.
  853. super.onRemove(v);
  854. }
  855. private _objectAdded = (ev: IEvent<any>) => {
  856. console.log("A new object, texture or material is added to the scene.", ev.object);
  857. };
  858. private _preFrame = (ev: IEvent<any>) => {
  859. // 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()
  860. };
  861. private _preRender = (ev: IEvent<any>) => {
  862. // This is called before each frame is rendered, only when the viewer is dirty.
  863. };
  864. // postFrame and postRender work the same way as preFrame and preRender.
  865. }
  866. ```
  867. Notes:
  868. * 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`
  869. * 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.
  870. * Event listeners and other hooks can be added and removed in `onAdded` and `onRemove` functions for the viewer and other plugins.
  871. * 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.
  872. * 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
  873. * `plugin.toJSON()` and `plugin.fromJSON()` or `ThreeSerialization` can be used to serialize and deserialize plugins. `viewer.exportPluginConfig` and `viewer.importPluginConfig` also exist for this.
  874. * @serialize('label') decorator can be used to mark any public/private variable as serializable. label (optional) corresponds to the key in JSON.
  875. * @serialize supports instances of ITexture, IMaterial, all primitive types, simple JS objects, three.js math classes(Vector2, Vector3, Matrix3...), and some more.
  876. * uiDecorators can be used to mark properties and functions that will be shown in the Ui. The Ui shows up automatically when TweakpaneUiPlugin/BlueprintJsUiPlugin is added to the viewer. Plugins have special features in the UI for download preset and saving state.
  877. Check various plugins in the source code for more examples.
  878. # Viewer API
  879. [ThreeViewer](https://threepipe.org/docs/classes/ThreeViewer.html) - is the main entry point to 3d rendering on the canvas.
  880. - `.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
  881. - `.renderer`: [IWebGLRenderer](https://threepipe.org/docs/interfaces/IWebGLRenderer.html) - for rendering. Instance of three.js [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer)
  882. - `.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)
  883. - `.context`: [WebGLRenderingContext](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext) - WebGL rendering context
  884. - `.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
  885. - `.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.
  886. - `.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)
  887. - `.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)
  888. - `.assetManager`: [AssetManager](https://threepipe.org/docs/classes/AssetManager.html) - Asset manager for loading, managing and exporting assets
  889. - `.importer`: [AssetImporter](https://threepipe.org/docs/classes/AssetImporter.html) - for importing assets
  890. - `.exporter`: [AssetExporter](https://threepipe.org/docs/classes/AssetExporter.html) - for exporting assets
  891. - `.materialManager`: [MaterialManager](https://threepipe.org/docs/classes/MaterialManager.html) - for managing materials and material extensions
  892. - `.plugins`: `Record`<`string`, [IViewerPlugin](https://threepipe.org/docs/interfaces/IViewerPlugin.html)> - Plugins added to the viewer
  893. - `.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.
  894. ## ThreeViewer
  895. Source Code: [src/viewer/ThreeViewer.ts](./src/viewer/ThreeViewer.ts)
  896. API Reference: [ThreeViewer](https://threepipe.org/docs/classes/ThreeViewer.html)
  897. `ThreeViewer` is the main entry point to the viewer. It provides all the API for managing the scene, camera, rendering, plugins, etc.
  898. It is initialized with either a canvas element or a `HTMLElement` for the container.
  899. The canvas element is used for rendering, and the options are used to configure the viewer.
  900. If the canvas element is not provided, a new canvas element is created and appended to the container.
  901. More options can be passed in the constructor to configure various built-in plugins and rendering features in the viewer.
  902. ### Constructor
  903. ```typescript
  904. import {ThreeViewer, CameraViewPlugin} from 'threepipe'
  905. // Create a viewer. All options except canvas/container are optional
  906. const viewer = new ThreeViewer({
  907. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  908. // or a container like:
  909. // container: document.getElementById('mcontainer'),
  910. // container: document.body,
  911. // Set the render scale to render at device resolution and clamp to max 2.
  912. renderScale: 'auto',
  913. // or Set the render scale to render at device resolution
  914. // renderScale: window.devicePixelRatio,
  915. // modify the screen shader: See ScreenPass and ScreenPass.glsl for more details
  916. screenShader: `diffuseColor = diffuseColor * 2.0;`,
  917. // Add TonemapPlugin
  918. tonemap: true,
  919. // Use MSAA(anti-aliasing)
  920. msaa: false,
  921. // Use Uint8 RGBM HDR Render Pipeline. Provides better performance with post-processing. RenderManager Uses Half-float if set to false.
  922. rgbm: true,
  923. // Use rendered gbuffer as depth-prepass / z-prepass.
  924. zPrepass: false,
  925. // Options for AssetManager
  926. assetManager: {
  927. // Use a custom CacheStorage
  928. storage: caches.open('threepipe-assetmanager'),
  929. },
  930. // Use DropzonePlugin to add support for file drag and drop
  931. // Enable and set properties
  932. dropzone: {
  933. // Set allowed extensions
  934. allowedExtensions: ['png', 'glb', 'gltf'],
  935. // Automatically add downloaded assets
  936. autoAdd: true
  937. // autoImport: true,
  938. // domElement: document.body,
  939. // addOptions: { ... }
  940. // importOptions: { ... }
  941. },
  942. // By default its false
  943. // dropzone: false,
  944. // To Enable without options
  945. // dropzone: true
  946. // Add some plugins after viewer creation.
  947. plugins: [CameraViewPlugin, new CustomPlugin()],
  948. // Shorthand to load files immediately after viewer initialization
  949. load: {
  950. src: 'https://example.com/file.glb',
  951. environment: 'https://example.com/file.hdr',
  952. background: 'https://example.com/file.png',
  953. },
  954. onLoad: (viewer) => {
  955. // Called when all the files are loaded
  956. },
  957. })
  958. ```
  959. Check the interface [ThreeViewerOptions](https://threepipe.org/docs/interfaces/ThreeViewerOptions.html) for all the options.
  960. To dispose off the viewer and all its resources call [`viewer.dispose()`](https://threepipe.org/docs/classes/ThreeViewer.html#dispose) method.
  961. To dispose only the scene objects and not the complete viewer, use `viewer.scene.disposeSceneModels()`
  962. ### Plugin Functions
  963. ```typescript
  964. import {ThreeViewer, TonemapPlugin, DepthBufferPlugin, NormalBufferPlugin} from 'threepipe'
  965. const viewer = new ThreeViewer({...})
  966. // Add a plugin
  967. const plugin = viewer.addPluginSync(new TonemapPlugin())
  968. // plugins can be added with just the class also
  969. const plugin2 = viewer.addPluginSync(TonemapPlugin)
  970. // Add multiple plugins at once
  971. viewer.addPluginsSync([
  972. TonemapPlugin,
  973. new NormalBufferPlugin(),
  974. DepthBufferPlugin,
  975. // ...
  976. ])
  977. // Get a plugin
  978. const plugin3 = viewer.getPlugin(TonemapPlugin)
  979. // Get or add a plugin, when not sure if the plugin is already added
  980. const plugin4 = viewer.getOrAddPluginSync(TonemapPlugin)
  981. // Remove a plugin
  982. viewer.removePluginSync(TonemapPlugin)
  983. ```
  984. Note: all sync functions above have async counterparts like `addPlugin`, `getOrAddPlugin`,
  985. `removePlugin` that are used for async plugins.
  986. There are no async plugins built-in to threepipe yet.
  987. ### Import/Export Functions
  988. ```typescript
  989. import {ThreeViewer} from 'threepipe'
  990. const viewer = new ThreeViewer({...})
  991. // Load a 3d model
  992. const object = await viewer.load<IObject3D>('https://example.com/file.glb')
  993. // Load a material
  994. const material = await viewer.load<PhysicalMaterial>('https://example.com/file.pmat')
  995. // Load an image
  996. const texture = await viewer.load<ITexture>('https://example.com/file.png')
  997. // Import a model without adding to the scene
  998. const imported = await viewer.import('https://example.com/file.glb')
  999. // Export the complete scene with viewer configuraion
  1000. const exportedScene = await viewer.exportScene({})
  1001. // Export an object
  1002. const exported = await viewer.export(object)
  1003. // Export a material
  1004. const exportedMaterial = await viewer.export(material)
  1005. // Export a texture
  1006. const exportedTexture = await viewer.export(texture)
  1007. // Export viewer and plugins configurations
  1008. const exportedConfig = await viewer.export(viewer)
  1009. // Export plugin configuration
  1010. const exportedPlugin = await viewer.exportPlugin(viewer.getPlugin(PluginClass))
  1011. // Set Background Image
  1012. await viewer.setBackgroundMap('https://example.com/file.png')
  1013. // Set Environment Map
  1014. await viewer.setEnvironmentMap('https://example.com/file.hdr')
  1015. // Add an imported object or a created three.js object to the scene
  1016. viewer.addSceneObject(imported)
  1017. ```
  1018. [`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.
  1019. [`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.
  1020. [`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.
  1021. [`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.
  1022. [`viewer.exportPlugin`](https://threepipe.org/docs/classes/ThreeViewer.html#exportPlugin) - Exports a plugin configuration and returns a blob.
  1023. [`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.
  1024. [`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.
  1025. [`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.
  1026. ### Frame/Rendering Events
  1027. ```typescript
  1028. import {ThreeViewer} from 'threepipe'
  1029. const viewer = new ThreeViewer({...})
  1030. // Add a callback to be called before every frame, irrespective of whether enything is being rendered that frame
  1031. viewer.addEventListener('preFrame', (ev)=>{
  1032. console.log(ev);
  1033. // change something
  1034. viewer.setDirty() // let the viewer know to re-render the scene from this frame
  1035. })
  1036. // Add a callback to be called after every frame, irrespective of whether enything was rendered that frame
  1037. viewer.addEventListener('postFrame', (ev)=>{
  1038. console.log(ev);
  1039. // change something
  1040. viewer.setDirty() // let the viewer know to re-render the scene from next frame
  1041. })
  1042. // Add a callback to be called before every render, only if something is being rendered that frame
  1043. viewer.addEventListener('preRender', (ev)=>{
  1044. // canvas is about to be rendered, or re-rendered for progressive rendering
  1045. console.log(ev, viewer.renderManager.frameCount);
  1046. })
  1047. // Add a callback to be called after every render, only if something was rendered that frame
  1048. viewer.addEventListener('postRender', (ev)=>{
  1049. // canvas is rendered, or re-rendered for progressive rendering
  1050. console.log(ev);
  1051. })
  1052. // Listen to viewer.setDirty() calls
  1053. viewer.addEventListener('update', (ev)=>{
  1054. // viewer.setDirty() was called by some plugin or code
  1055. console.log(ev);
  1056. })
  1057. // to remove an event listener, first keep a reference to the callback
  1058. const callback = (ev)=>{ return }
  1059. viewer.addEventListener('preFrame', callback)
  1060. // then remove it
  1061. viewer.removeEventListener('preFrame', callback)
  1062. // Add a callback to be called only once for an event
  1063. viewer.doOnce('postFrame', () => viewer.canvas.toDataURL('image/png'))
  1064. // Enable/disable rendering in the viewer
  1065. viewer.renderEnabled = false
  1066. // do something with the canvas or load assets
  1067. await viewer.load('https://example.com/file.glb')
  1068. await viewer.load('https://example.com/file1.glb')
  1069. await viewer.load('https://example.com/file2.glb')
  1070. viewer.renderEnabled = true // all the assets will be rendered together in the next frame
  1071. ```
  1072. Check the [IViewerEvent](https://threepipe.org/docs/interfaces/IViewerEvent.html) interface for all the event types.
  1073. [`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.
  1074. [`viewer.removeEventListener`](https://threepipe.org/docs/classes/ThreeViewer.html#removeEventListener) - Removes a callback from the given event.
  1075. [`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.
  1076. ### Utility Functions
  1077. ```typescript
  1078. import {ThreeViewer} from 'threepipe'
  1079. const viewer = new ThreeViewer({...})
  1080. // Set the final render size directly and fit in container based on mode.
  1081. viewer.setRenderSize({width: 800, height: 600}, 'cover')
  1082. // Set size of the canvas
  1083. viewer.setSize({width: 800, height: 600})
  1084. // Set the render scale
  1085. viewer.renderManager.renderScale = Math.min(window.devicePixelRatio, 2)
  1086. // Traverse scene objects
  1087. viewer.traverseSceneObjects((object) => {
  1088. console.log(object)
  1089. // do something with object
  1090. })
  1091. // If the size is set by css or manually by javascript use `resize` to update the viewer
  1092. viewer.resize()
  1093. // Trigger re-render with `setDirty` when something changes and viewer is not notified internally
  1094. viewer.setDirty()
  1095. // Get snapshot of the canvas as a blob
  1096. const blob = await viewer.getScreenshotBlob({mimeTye: 'image/png', quality: 90})
  1097. // Get snapshot of the canvas as a data url
  1098. const dataUrl = await viewer.getScreenshotDataUrl({mimeTye: 'image/jpeg', quality: 85})
  1099. // Dispose viewer and all resources
  1100. viewer.canvas.remove() // canvas needs to be removed separately from the DOM
  1101. viewer.dispose()
  1102. ```
  1103. [`viewer.setRenderSize`](https://threepipe.org/docs/classes/ThreeViewer.html#setRenderSize) - Sets the rendering resolution and fits the canvas in container based on the mode. The modes are `cover`, `contain`, `fill`, `scale-down` and `none`. The canvas size and render scale is calculated automatically to match the render render.
  1104. [`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.
  1105. [`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.
  1106. [`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.
  1107. [`viewer.setDirty`](https://threepipe.org/docs/classes/ThreeViewer.html#setDirty) - Triggers re-render on next `requestAnimationFrame` call.
  1108. [`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.
  1109. [`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.
  1110. [`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.
  1111. ## RenderManager
  1112. 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)
  1113. 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)
  1114. It manages the rendering, composition/postprocessing of the scene and provides helpers for rendering and render target management.
  1115. ```typescript
  1116. const viewer = new ThreeViewer({...})
  1117. const renderManager = viewer.renderManager
  1118. // Get the effect composer
  1119. const composer = renderManager.composer
  1120. // Get the three.js webgl renderer
  1121. const renderer = renderManager.renderer
  1122. // Get the main Render Pass in the pipeline
  1123. const renderPass = renderManager.renderPass
  1124. // Get the main Screen Pass in the pipeline
  1125. const screenPass = renderManager.screenPass
  1126. // Set the render scale
  1127. renderManager.renderScale = Math.min(window.devicePixelRatio, 2)
  1128. // Register a custom composer pass
  1129. const customPass: IPipelinePass = new CustomPass()
  1130. renderManager.registerPass(customPass)
  1131. // Unregister a custom composer pass
  1132. renderManager.unregisterPass(customPass)
  1133. // The pipeline is automatically created and sorted based on dependencies in pipeline pass.
  1134. // To check the built pipeline
  1135. console.log(renderManager.pipeline)
  1136. // Set a custom render pipeline
  1137. renderManager.autoBuildPipeline = false
  1138. renderManager.pipeline = ['depth', 'render', 'screen']
  1139. // Check the total frames rendererd
  1140. console.log(renderManager.totalFrameCount)
  1141. // Get the current frame count in progressive rendering
  1142. console.log(renderManager.frameCount)
  1143. // Force reset shadows when some object is moved
  1144. renderManager.resetShadows()
  1145. // Render Target Management
  1146. // Get the main composer target
  1147. const composerTarget = renderManager.composerTarget
  1148. // clone the target to get a copy of the target with all the default options
  1149. const clonedTarget = composeTarget.clone()
  1150. // Create a render target, same size as the canvas. The target are automatically resized when the canvas is resized
  1151. const renderTarget = renderManager.createTarget({
  1152. sizeMultiplier: 1, // size multiplier from the canvas. 0.5 will be half width and height of the canvas
  1153. type: UnsignedByteType,
  1154. // ... // See CreateRenderTargetOptions for all options
  1155. })
  1156. // Create a render target of custom size
  1157. const renderTarget2 = renderManager.createTarget({
  1158. size: {
  1159. width: 1024,
  1160. height: 1024,
  1161. },
  1162. type: HalfFloatType,
  1163. // ...
  1164. })
  1165. // Dispose the render target
  1166. renderManager.disposeTarget(renderTarget)
  1167. // Create and release temporary targets for in-pass rendering.
  1168. const tempTarget = renderManager.getTempTarget({
  1169. sizeMultiplier: 0.5,
  1170. type: HalfFloatType,
  1171. // ...
  1172. })
  1173. // do something
  1174. renderManager.releaseTempTarget(tempTarget)
  1175. // Set how many temporary targets can remain in memory for a specific set of options
  1176. renderManager.maxTempPerKey = 10 // default = 5
  1177. // Copy/Blit a texture to the canvas or another render target with standard or a custom material
  1178. renderManager.blit(destination, {source: sourceTexture})
  1179. // Clear color of the canvas
  1180. renderManager.clearColor({r: 0, g: 0, b: 0, a: 1, depth: true, viewport: new Vector4(...)})
  1181. // Clear of a render target
  1182. renderManager.clearColor(renderTarget, {r: 0, g: 0, b: 0, a: 1, target: renderTarget})
  1183. // Export a render target to a blob. The type is automatically picked from exr to png based on the render target
  1184. const blob = renderManager.exportRenderTarget(renderTarget, 'auto')
  1185. // Export a render target to png/jpeg data url. This will clamp any floating point targets to fit in png/jpeg
  1186. const dataUrl = renderManager.renderTargetToDataUrl(renderTarget, 'image/png')
  1187. // Read render target pixels to array buffer. Returns Uint8Array|Uint16Array|Float32Array based on the render target type
  1188. const buffer = renderManager.renderTargetToBuffer(renderTarget)
  1189. ```
  1190. [`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.
  1191. [`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
  1192. [`renderManager.context`](https://threepipe.org/docs/classes/ViewerRenderManager.html#context) - Access the WebGL rendering context for the canvas.
  1193. [`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.
  1194. [`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
  1195. [`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.
  1196. [`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.
  1197. ### Rendering Pipeline
  1198. [`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.
  1199. [`renderManager.unregisterPass`](https://threepipe.org/docs/classes/RenderManager.html#unregisterPass) - Unregisters a custom composer pass from the render pipeline.
  1200. [`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.
  1201. [`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`.
  1202. [`renderManager.totalFrameCount`](https://threepipe.org/docs/classes/RenderManager.html#totalFrameCount) - The total frames rendered since the render manager was created.
  1203. [`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.
  1204. ### Render Targets management
  1205. [`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)
  1206. [`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
  1207. [`renderManager.disposeTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#disposeTarget) - Disposes a render target and removes it from the render target manager.
  1208. [`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
  1209. [`renderManager.releaseTempTarget`](https://threepipe.org/docs/classes/RenderTargetManager.html#releaseTempTarget) - Releases a temporary render target and adds it back to the render target manager.
  1210. [`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`.
  1211. ### Helpers
  1212. [`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.
  1213. [`renderManager.clearColor`](https://threepipe.org/docs/classes/RenderManager.html#clearColor) - Clears the color of the canvas or a render target.
  1214. [`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.
  1215. [`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.
  1216. [`renderManager.renderTargetToBuffer`](https://threepipe.org/docs/classes/RenderManager.html#renderTargetToBuffer) - Reads render target pixels to a Uint8Array|Uint16Array|Float32Array array buffer.
  1217. ## RootScene
  1218. Source Code: [src/core/object/RootScene.ts](./src/core/object/RootScene.ts)
  1219. API Reference: [RootScene](https://threepipe.org/docs/classes/RootScene.html)
  1220. RootScene is the main scene that is rendered in the canvas.
  1221. 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,
  1222. backgroundColor, background map and background intensity,
  1223. environment map rotation and intensity, fixed env map direction patch, event bubbling in the scene hierarchy, scene config serialization, main camera management,
  1224. automatic active near far management based on scene bounds, disposing complete scene hierarchy, etc
  1225. ```typescript
  1226. const viewer = new ThreeViewer({...})
  1227. const scene = viewer.scene
  1228. // List oll loaded objects in the model root
  1229. console.log(scene.modelRoot.children)
  1230. // Set the background color
  1231. scene.setBackgroundColor('#ffffff')
  1232. // or
  1233. // scene.backgroundColor = new Color('#ffffff')
  1234. // or
  1235. // scene.backgroundColor.set('#ffffff')
  1236. // scene.onBackgroundChange() // this must be called when not using a setter or set function.
  1237. // Set a texture as background (or use viewer.setBackgroundMap). When both color and texture are set, they are multiplied
  1238. scene.background = customTexture
  1239. // Set the background same as the environment map
  1240. scene.background = 'environment' // background is automatically changed when the environment changes.
  1241. // or
  1242. // scene.background = scene.environment
  1243. // Set the background intensity
  1244. scene.backgroundIntensity = 2
  1245. // Set a texture as environment map (or use viewer.setEnvironmentMap)
  1246. scene.environment = customTexture
  1247. // Set the environment intensity
  1248. scene.envMapIntensity = 2
  1249. // Set the environment map rotation
  1250. scene.environment.rotation = Math.PI / 2
  1251. // Set Fixed env direction (rotate environment according the the camera)
  1252. scene.fixedEnvMapDirection = true
  1253. // Get the main camera used for rendering
  1254. const camera: PerspectiveCamera2 = scene.mainCamera
  1255. // Set camera props
  1256. camera.position.set(0, 0, 10)
  1257. camera.target.set(0, 0, 0)
  1258. camera.setDirty() // this needs to be called to notify the viewer to re-render the scene
  1259. // Traverse the model root hierarchy (or just use viewer.traverseSceneObjects)
  1260. scene.modelRoot.traverse((object) => {
  1261. console.log(object)
  1262. // do something with object
  1263. })
  1264. // Access the default camera (same as mainCamera if not changed explicitly)
  1265. const defaultCamera: ICamera = scene.defaultCamera
  1266. // Dispose all assets in the modelRoot
  1267. scene.disposeSceneModels()
  1268. // Remove all objects from the modelRoot
  1269. scene.clearSceneModels()
  1270. // Dispose the scene and all its resources and children
  1271. scene.dispose()
  1272. // Get bounds of the scene model root
  1273. const bounds = scene.getBounds(true, true) // true for precise bounds and ignore invisible
  1274. // Add an object to the scene or its model root depending on the options (or just use viewer.addSceneObject)
  1275. scene.addObject(object, {addToRoot: false}) // adds to the scene directly when addToRoot is true
  1276. // Load an imported model root from the asset importer
  1277. scene.loadModelRoot(object)
  1278. // notify that something has changed in the scene for re-render
  1279. scene.setDirty()
  1280. // notify that some object has changed in the scene for scene refresh(like shadow refresh, ground etc) and re-render
  1281. scene.refreshScene()
  1282. // or
  1283. scene.setDirty({refreshScene: true})
  1284. // set geometryChanged: false to prevent shadow recompute
  1285. scene.refreshScene({geometryChanged: false})
  1286. // refresh active near far. (in most cases this is done automatically and need not be called)
  1287. scene.refreshActiveNearFar()
  1288. ```
  1289. [`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.
  1290. [`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.
  1291. [`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.
  1292. [`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.
  1293. [`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.
  1294. [`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.
  1295. `scene.environment.rotation` - The rotation of the environment map around the y-axis.
  1296. [`scene.envMapIntensity`](https://threepipe.org/docs/classes/RootScene.html#envMapIntensity) - The environment intensity of the scene.
  1297. [`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.
  1298. [`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.
  1299. [`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.
  1300. [`scene.disposeSceneModels`](https://threepipe.org/docs/classes/RootScene.html#disposeSceneModels) - Disposes all assets in the modelRoot.
  1301. [`scene.clearSceneModels`](https://threepipe.org/docs/classes/RootScene.html#clearSceneModels) - Removes all objects from the modelRoot.
  1302. [`scene.dispose`](https://threepipe.org/docs/classes/RootScene.html#dispose) - Disposes the scene and all its resources and children.
  1303. [`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.
  1304. [`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.
  1305. [`scene.setDirty`](https://threepipe.org/docs/classes/RootScene.html#setDirty) - Notifies that something has changed in the scene for re-render.
  1306. [`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.
  1307. [`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)
  1308. [`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.
  1309. ### Scene Events
  1310. RootScene dispatches many events that are useful when writing app logic or plugins
  1311. `'sceneUpdate'` - Listen to `refreshScene` called in RootScene. When some object changes.
  1312. `'addSceneObject'` - When a new object is added to the scene
  1313. `'mainCameraChange'` - When the main camera is changed to some other camera.
  1314. `'mainCameraUpdate'` - When some properties in the current main camera has changed.
  1315. `'environmentChanged'` - When the environment map changes
  1316. `'backgroundChanged'` - When the background map or color changes
  1317. `'materialUpdate`' - When a material in the scene has updated. (setDirty called on the material)
  1318. `'objectUpdate`' - When a object in the scene has updated. (setDirty called on the object)
  1319. `'textureUpdate`' - When a texture in the scene has updated. (setDirty called on the texture)
  1320. `'cameraUpdate`' - When a camera in the scene has updated.
  1321. (setDirty called on the camera)
  1322. `'geometryUpdate`' - When a geometry in the scene has updated.
  1323. (setDirty called on the geometry)
  1324. `'geometryChanged`' - When a geometry is changed on any mesh
  1325. `'materialChanged'` - When a material is changed on any mesh
  1326. Check [IObject3DEventTypes](https://threepipe.org/docs/interfaces/IObject3DEventTypes.html) and[ISceneEventTypes](https://threepipe.org/docs/interfaces/ISceneEventTypes.html) for more information.
  1327. ## ICamera
  1328. Source Code: [src/core/camera/PerspectiveCamera2.ts](./src/core/camera/PerspectiveCamera2.ts), [src/core/ICamera.ts](./src/core/ICamera.ts)
  1329. API Reference: [PerspectiveCamera2](https://threepipe.org/docs/classes/PerspectiveCamera2.html), [ICamera](https://threepipe.org/docs/interfaces/ICamera.html)
  1330. ICamera is an interface for a camera that extends the three.js [Camera](https://threejs.org/docs/#api/en/cameras/Camera).
  1331. PerspectiveCamera2 implements the interface,
  1332. 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.
  1333. ```typescript
  1334. import {OrbitControls3} from './OrbitControls3'
  1335. const viewer = new ThreeViewer({...})
  1336. const camera: PerspectiveCamera2 = viewer.scene.mainCamera
  1337. // Set the camera position
  1338. camera.position.set(0, 0, 10)
  1339. // Set the camera target (where the camera looks at)
  1340. camera.target.set(0, 0, 0)
  1341. // Set the camera fov
  1342. camera.fov = 45
  1343. // Set the camera aspect ratio
  1344. camera.autoAspect = false // disable automatic aspect management based on the canvas size
  1345. camera.aspect = 1
  1346. // Set camera near far bounds.
  1347. // Near, Far plane will be calculated automatically within these limits
  1348. // Try changing these values when encountering z-fighting issues or far-plane clipping
  1349. camera.minNearPlane = 0.5 // min near plane
  1350. camera.maxFarPlane = 10 // max far plane
  1351. // Set a custom camera near far
  1352. camera.autoNearFar = false // disable automatic near far management based on the scene bounds
  1353. camera.minNearPlane = 0.1 // near plane
  1354. camera.maxFarPlane = 1000 // far plane
  1355. // this needs to be called to notify the viewer to re-render the scene
  1356. // in most cases this is done internally. But calling this does not have much impact
  1357. camera.setDirty()
  1358. // Check if user can interact with the camera. Also checks if its the main camera.
  1359. console.log(camera.canUserInteract)
  1360. // Get the camera controls (orbit controls for the default camera)
  1361. const controls: OrbitControls3 = camera.controls
  1362. // Disable controls
  1363. controls.enabled = false
  1364. // Change the controls mode
  1365. camera.controlsMode = 'none' // this will remove the current controls.
  1366. // Register a custom camera controls
  1367. camera.setControlsCtor('customOrbit', (camera, domElement) => new CustomOrbitControls(camera, domElement))
  1368. // Set the camera controls
  1369. camera.controlsMode = 'customOrbit' // this will initialize the controls with the customOrbit constructor and set it on the camera
  1370. // Disable interactions to the camera. (eg when animating)
  1371. camera.setInteractions(false, 'animation')
  1372. // Enable interactions back
  1373. camera.setInteractions(true, 'animation') // this will enable interactions when all the keys have been set to true(which were set to false earlier)
  1374. // Force refresh aspect ratio (this is done automatically with a ResizeObserver on the canvas in the viewer)
  1375. camera.refreshAspect()
  1376. // Set the camera as the main camera
  1377. camera.activateMain()
  1378. // Deactivate the camera as the main camera
  1379. camera.deactivateMain()
  1380. ```
  1381. [`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.
  1382. [`camera.autoAspect`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#autoAspect) - If `true`, the aspect ratio is automatically calculated based on the canvas size.
  1383. [`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`.
  1384. [`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
  1385. [`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
  1386. [`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.
  1387. [`camera.setDirty`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#setDirty) - Notifies that something has changed in the camera for re-render.
  1388. [`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.
  1389. [`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`
  1390. [`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.
  1391. [`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.
  1392. [`camera.setInteractions`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#setInteractions) - If `true`, the camera can be interacted with. This is useful when animating the camera or using the window scroll or programmatically automating the viewer. Using this multiple plugins can disable interactions and it will be enabled again when all of them enable it back.
  1393. [`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)
  1394. [`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.
  1395. [`camera.deactivateMain`](https://threepipe.org/docs/classes/PerspectiveCamera2.html#deactivateMain) - Deactivate the camera as the main camera.
  1396. See also [CameraViewPlugin](#cameraviewplugin) for camera focus animation.
  1397. Note: The constructor signature of `PerspectiveCamera2` is different `PerspectiveCamera`(from three.js), since it requires the canvas and the controlsMode during creation.
  1398. Because of this `PerspectiveCamera0` is provided with the same signature as `PerspectiveCamera` for compatibility, in case the controls functionality is not required.
  1399. ## AssetManager
  1400. Source Code: [src/assetmanager/AssetManager.ts](./src/assetmanager/AssetManager.ts)
  1401. API Reference: [AssetManager](https://threepipe.org/docs/classes/AssetManager.html)
  1402. `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.
  1403. ```typescript
  1404. const viewer = new ThreeViewer({...})
  1405. const assetManager = viewer.assetManager
  1406. // Add an asset or an asset bundle
  1407. const assets = await assetManager.addAsset('https://example.com/model.zip')
  1408. // or
  1409. const assets1 = await assetManager.addAsset({
  1410. path: 'https://example.com/model.zip',
  1411. file: blob,
  1412. })
  1413. // Get the storage used in the asset manager for caching
  1414. const storage: Cache | Storage = assetManager.storage
  1415. // Get the importer. Provides low level functions to import assets
  1416. const importer = assetManager.importer
  1417. // import a file by asset or url
  1418. const file = await importer.import('https://example.com/model.gltf')
  1419. // Import a Map<string, File> from drag drop
  1420. const res = await importer.importFiles(mapOfFiles, {})
  1421. // Register a custom path that maps to a File object. Useful when some file types have path references to other files.
  1422. importer.registerFile('/myFile.png', file) // this returns the three.js loader for that kind of file.
  1423. // Unregister the path
  1424. importer.unregisterFile('/myFile.png')
  1425. // Unregister all files and clear the loader cache(memory, not storage)
  1426. importer.clearCache()
  1427. // Add custom importers (check extra load plugins for more examples)
  1428. importer.addImporter(new Importer(class extends PLYLoader implements ILoader {
  1429. transform(res: BufferGeometry, _: AnyOptions): Mesh | undefined {
  1430. return res ? new Mesh(res, new PhysicalMaterial({color: new Color(1, 1, 1)})) : undefined
  1431. }
  1432. }, ['ply'], ['text/plain+ply'], false))
  1433. // Get the exporter. Provides low level functions to export assets
  1434. const exporter = assetManager.exporter
  1435. // Export any IObject3D, IMaterial, ITexture, IRenderTarget
  1436. const exported = exporter.exportObject(obj, options)
  1437. // Add a custom exporter
  1438. exporter.addExporter({
  1439. ext: ['gltf', 'glb'], // file extensions
  1440. extensions: [], // extensions for the exporter
  1441. ctor: (assetExporter, iexporter) => {
  1442. return new GLTFExporter2()
  1443. }
  1444. })
  1445. // Material Manager
  1446. const materialManager = assetManager.materialManager
  1447. // Create a material of type
  1448. const mat1 = materialManager.create('physical')
  1449. const mat2 = materialManager.create('unlit')
  1450. // find or create a material by uuid
  1451. const mat3 = materialManager.findOrCreate('00000000-0000-0000-0000-000000000000', {color: '#ffffff'})
  1452. // find a material creation template
  1453. const template = materialManager.findTemplate('physical')
  1454. // Get all materials
  1455. const materials = materialManager.getAllMaterials()
  1456. // Get all materials of type
  1457. const materials2 = materialManager.getMaterialsOfType(PhysicalMaterial.TypeSlug)
  1458. // register a custom material to the manager for tracking and extensions
  1459. // Note all materials created in threepipe internally are registered automatically on creation or when added to any scene object.
  1460. materialManager.registerMaterial(customMat)
  1461. // unregister
  1462. materialManager.unregisterMaterial(customMat)
  1463. // clear all material references
  1464. materialManager.clearMaterials()
  1465. // Register a custom material template
  1466. materialManager.registerTemplate({
  1467. generator: (params: any) => new PhysicalMaterial(params),
  1468. name: 'custom',
  1469. materialType: PhysicalMaterial.TYPE,
  1470. params: {
  1471. color: '#ffffff',
  1472. roughness: 0.5,
  1473. metalness: 0.5,
  1474. },
  1475. })
  1476. const mat4 = materialManager.create('custom')
  1477. // convert a standard three.js material to threepipe material
  1478. const mat5 = materialManager.convertToIMaterial(new ShadowMaterial(), {materialTemplate: 'test'})
  1479. // register a custom material extension for all materials in the viewer
  1480. materialManager.registerMaterialExtension(customExtension)
  1481. // unregister
  1482. materialManager.unregisterMaterialExtension(customExtension)
  1483. // remove all extensions
  1484. materialManager.clearExtensions()
  1485. // Apply a material properties to other material(s) in the scene by name or uuid
  1486. materialManager.applyMaterial(goldMaterial, 'METAL') // this will copy the properties from goldMaterial to all the materials(or objects) in the viewer with the name METAL.
  1487. // export a material as JSON. Note: use AssetExporter instead to export all the embedded assets and properties properly.
  1488. const blob = materialManager.exportMaterial(mat)
  1489. // dispose manager and all materials.
  1490. materialManager.dispose()
  1491. ```
  1492. [`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.
  1493. [`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.
  1494. [`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).
  1495. [`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).
  1496. ### AssetImporter
  1497. [`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.
  1498. [`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.
  1499. [`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.
  1500. [`importer.unregisterFile`](https://threepipe.org/docs/classes/AssetImporter.html#unregisterFile) - Unregister the path.
  1501. [`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).
  1502. [`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.
  1503. ### AssetExporter
  1504. [`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.
  1505. [`exporter.addExporter`](https://threepipe.org/docs/classes/AssetExporter.html#addExporter) - Add a custom exporter for a custom file type.
  1506. ### MaterialManager
  1507. [`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).
  1508. [`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.
  1509. [`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.
  1510. [`materialManager.getAllMaterials`](https://threepipe.org/docs/classes/MaterialManager.html#getAllMaterials) - Get all materials registered with the manager.
  1511. [`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.
  1512. [`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
  1513. [`materialManager.unregisterMaterial`](https://threepipe.org/docs/classes/MaterialManager.html#unregisterMaterial) - Unregister a material from the manager.
  1514. [`materialManager.clearMaterials`](https://threepipe.org/docs/classes/MaterialManager.html#clearMaterials) - Clear all registered material references.
  1515. [`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.
  1516. [`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).
  1517. [`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.
  1518. [`materialManager.unregisterMaterialExtension`](https://threepipe.org/docs/classes/MaterialManager.html#unregisterMaterialExtension) - Unregister a material extension from the manager.
  1519. [`materialManager.clearExtensions`](https://threepipe.org/docs/classes/MaterialManager.html#clearExtensions) - Remove all material extensions from the manager.
  1520. [`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.
  1521. [`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.
  1522. [`materialManager.dispose`](https://threepipe.org/docs/classes/MaterialManager.html#dispose) - Dispose manager and all materials.
  1523. ## Other classes and interfaces
  1524. Threepipe provides various interfaces and classes for for three.js objects with upgraded features like UI events, serialization, etc.
  1525. These can be used while developing new apps to get better developer experience and features.
  1526. When standard three.js instances are added to the scene, they are automatically upgraded automatically at runtime to make them work with the rest of the framework.
  1527. Some important interfaces:
  1528. * [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html) - Interface for an extended version of three.js [Object3D](https://threejs.org/docs/#api/en/core/Object3D).
  1529. * [ILight](https://threepipe.org/docs/interfaces/ILight.html) - Interface for an extended version of three.js [Light](https://threejs.org/docs/#api/en/lights/Light).
  1530. * [ICamera](https://threepipe.org/docs/interfaces/ICamera.html) - Interface for an extended version of three.js [Camera](https://threejs.org/docs/#api/en/cameras/Camera).
  1531. * [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html) - Interface for an extended version of three.js [Material](https://threejs.org/docs/#api/en/materials/Material).
  1532. * [ITexture](https://threepipe.org/docs/interfaces/ITexture.html) - Interface for an extended version of three.js [Texture](https://threejs.org/docs/#api/en/textures/Texture).
  1533. * [IRenderTarget](https://threepipe.org/docs/interfaces/IRenderTarget.html) - Interface for an extended version of three.js [WebGLRenderTarget](https://threejs.org/docs/#api/en/renderers/WebGLRenderTarget).
  1534. * [IGeometry](https://threepipe.org/docs/interfaces/IGeometry.html) - Interface for an extended version of three.js [BufferGeometry](https://threejs.org/docs/#api/en/core/BufferGeometry).
  1535. * [IScene](https://threepipe.org/docs/interfaces/IScene.html) - Interface for an extended version of three.js [Scene](https://threejs.org/docs/#api/en/scenes/Scene).
  1536. * [IRenderManager](https://threepipe.org/docs/interfaces/IRenderManager.html) - Interface for rendering and render target manager.
  1537. Some important classes
  1538. * [Mesh2](https://threepipe.org/docs/classes/Mesh2.html) - Extends three.js [Mesh](https://threejs.org/docs/#api/en/objects/Mesh) and implements [IObject3D](https://threepipe.org/docs/interfaces/IObject3D.html).
  1539. * [PerspectiveCamera2](https://threepipe.org/docs/classes/PerspectiveCamera2.html) - Extends three.js [PerspectiveCamera](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera) and implements [ICamera](https://threepipe.org/docs/interfaces/ICamera.html). (different constructor than PerspectiveCamera)
  1540. * [PerspectiveCamera0](https://threepipe.org/docs/classes/PerspectiveCamera0.html) - Extends three.js [PerspectiveCamera](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera) and implements [ICamera](https://threepipe.org/docs/interfaces/ICamera.html). (same constructor than PerspectiveCamera)
  1541. * [BufferGeometry2](https://threepipe.org/docs/classes/BufferGeometry2.html) - Extends three.js [BufferGeometry](https://threejs.org/docs/#api/en/core/BufferGeometry) and implements [IGeometry](https://threepipe.org/docs/interfaces/IGeometry.html).
  1542. * [RootScene](https://threepipe.org/docs/classes/RootScene.html) - Extends three.js [Scene](https://threejs.org/docs/#api/en/scenes/Scene) and implements [IScene](https://threepipe.org/docs/interfaces/IScene.html).
  1543. * [RenderManager](https://threepipe.org/docs/classes/RenderManager.html) - Implements [IRenderManager](https://threepipe.org/docs/interfaces/IRenderManager.html).
  1544. * [PhysicalMaterial](https://threepipe.org/docs/classes/PhysicalMaterial.html) - Extends three.js [MeshPhysicalMaterial](https://threejs.org/docs/#api/en/materials/MeshPhysicalMaterial) and implements [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  1545. * [UnlitMaterial](https://threepipe.org/docs/classes/UnlitMaterial.html) - Extends three.js [MeshBasicMaterial](https://threejs.org/docs/#api/en/materials/MeshBasicMaterial) and implements [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  1546. * [LineMaterial2](https://threepipe.org/docs/classes/LineMaterial2.html) - Extends three.js [LineMaterial](https://threejs.org/docs/#api/en/materials/LineMaterial) and implements [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  1547. * [UnlitLineMaterial](https://threepipe.org/docs/classes/UnlitLineMaterial.html) - Extends three.js [LineBasicMaterial](https://threejs.org/docs/#api/en/materials/LineBasicMaterial) and implements [IMaterial](https://threepipe.org/docs/interfaces/IMaterial.html).
  1548. * [DirectionalLight2](https://threepipe.org/docs/classes/DirectionalLight2.html) - Extends three.js [DirectionalLight](https://threejs.org/docs/#api/en/lights/DirectionalLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  1549. * [SpotLight2](https://threepipe.org/docs/classes/SpotLight2.html) - Extends three.js [SpotLight](https://threejs.org/docs/#api/en/lights/SpotLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  1550. * [PointLight2](https://threepipe.org/docs/classes/PointLight2.html) - Extends three.js [PointLight](https://threejs.org/docs/#api/en/lights/PointLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  1551. * [HemisphereLight2](https://threepipe.org/docs/classes/HemisphereLight2.html) - Extends three.js [HemisphereLight](https://threejs.org/docs/#api/en/lights/HemisphereLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  1552. * [AmbientLight2](https://threepipe.org/docs/classes/AmbientLight2.html) - Extends three.js [AmbientLight](https://threejs.org/docs/#api/en/lights/AmbientLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  1553. * [RectAreaLight2](https://threepipe.org/docs/classes/RectAreaLight2.html) - Extends three.js [RectAreaLight](https://threejs.org/docs/#api/en/lights/RectAreaLight) and implements [ILight](https://threepipe.org/docs/interfaces/ILight.html).
  1554. # Threepipe Plugins
  1555. 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.
  1556. ## TonemapPlugin
  1557. [//]: # (todo: image)
  1558. [Example](https://threepipe.org/examples/#tonemap-plugin/) &mdash;
  1559. [Source Code](./src/plugins/postprocessing/TonemapPlugin.ts) &mdash;
  1560. [API Reference](https://threepipe.org/docs/classes/TonemapPlugin.html)
  1561. TonemapPlugin adds a post-processing material extension to the ScreenPass in render manager
  1562. that applies tonemapping to the color. The tonemapping operator can be changed
  1563. by setting the `toneMapping` property of the plugin. The default tonemapping operator is `ACESFilmicToneMapping`.
  1564. Other Tonemapping properties can be like `exposure`, `contrast` and `saturation`
  1565. TonemapPlugin is added by default in ThreeViewer unless `tonemap` is set to `false` in the options.
  1566. ## DropzonePlugin
  1567. [//]: # (todo: image)
  1568. [Example](https://threepipe.org/examples/#dropzone-plugin/) &mdash;
  1569. [Source Code](./src/plugins/interaction/DropzonePlugin.ts) &mdash;
  1570. [API Reference](https://threepipe.org/docs/classes/DropzonePlugin.html)
  1571. DropzonePlugin adds support for drag and drop of local files to automatically import, process and load them into the viewer.
  1572. DropzonePlugin can be added by default in ThreeViewer
  1573. by setting the `dropzone` property to `true` or an object of `DropzonePluginOptions` in the options.
  1574. ```typescript
  1575. import {DropzonePlugin, ThreeViewer} from 'threepipe'
  1576. const viewer = new ThreeViewer({
  1577. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  1578. dropzone: true, // just set to true to enable drag drop functionatility in the viewer
  1579. })
  1580. ```
  1581. To set custom options,
  1582. pass an object of [DropzonePluginOptions](https://threepipe.org/docs/interfaces/DropzonePluginOptions.html) type to the `dropzone` property.
  1583. ```typescript
  1584. import {DropzonePlugin, ThreeViewer} from 'threepipe'
  1585. const viewer = new ThreeViewer({
  1586. canvas: document.getElementById('mcanvas') as HTMLCanvasElement,
  1587. dropzone: { // this can also be set to true and configured by getting a reference to the DropzonePlugin
  1588. allowedExtensions: ['gltf', 'glb', 'hdr', 'png', 'jpg', 'json', 'fbx', 'obj', 'bin', 'exr'], // only allow these file types. If undefined, all files are allowed.
  1589. addOptions: {
  1590. disposeSceneObjects: true, // auto dispose of old scene objects
  1591. autoSetEnvironment: true, // when hdr is dropped
  1592. autoSetBackground: true, // when any image is dropped
  1593. autoCenter: true, // auto center the object
  1594. autoScale: true, // auto scale according to radius
  1595. autoScaleRadius: 2,
  1596. license: 'Imported from dropzone', // Any license to set on imported objects
  1597. importConfig: true, // import config from file
  1598. },
  1599. // check more options in the DropzonePluginOptions interface
  1600. },
  1601. })
  1602. ```
  1603. ## ProgressivePlugin
  1604. [//]: # (todo: image)
  1605. [Example](https://threepipe.org/examples/#progressive-plugin/) &mdash;
  1606. [Source Code](./src/plugins/pipeline/ProgressivePlugin.ts) &mdash;
  1607. [API Reference](https://threepipe.org/docs/classes/ProgressivePlugin.html)
  1608. Progressive Plugin adds a post-render pass to blend the last frame with the current frame.
  1609. 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. The helper function `convergedPromise` returns a new promise that can be used to wait for the progressive rendering to converge.
  1610. ## SSAAPlugin
  1611. [//]: # (todo: image)
  1612. [Example](https://threepipe.org/examples/#ssaa-plugin/) &mdash;
  1613. [Source Code](./src/plugins/pipeline/SSAAPlugin.ts) &mdash;
  1614. [API Reference](https://threepipe.org/docs/classes/SSAAPlugin.html)
  1615. SSAA Plugin adds support for [Super Sampling Anti-Aliasing](https://en.wikipedia.org/wiki/Supersampling) to the viewer. Simply add the plugin to the viewer to use it.
  1616. It jitters the camera view offset over multiple frames, which are then blended by the [ProgressivePlugin](#progressiveplugin) to create a higher quality image. This is useful for reducing aliasing artifacts in the scene.
  1617. By default, the pipeline only renders once per request animation frame. So we don't get any anti-aliasing while moving. For that, either use the TAA(Temporal Anti-aliasing) plugin or for the case of simple scenes - render multiple times per frame which can be done by setting `plugin.rendersPerFrame` or `viewer.rendersPerFrame`. Check out the [example](https://threepipe.org/examples/#ssaa-plugin/) to see the effect on frame rate.
  1618. ```typescript
  1619. const ssaa = viewer.addPluginSync(new SSAAPlugin())
  1620. ssaa.enabled = true // toggle jittering(if you want to set custom view offset)
  1621. ssaa.rendersPerFrame = 4 // render 4 times per frame (max 32 is useful)
  1622. ```
  1623. ## DepthBufferPlugin
  1624. [//]: # (todo: image)
  1625. [Example](https://threepipe.org/examples/#depth-buffer-plugin/) &mdash;
  1626. [Source Code](./src/plugins/pipeline/DepthBufferPlugin.ts) &mdash;
  1627. [API Reference](https://threepipe.org/docs/classes/DepthBufferPlugin.html)
  1628. 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.
  1629. ```typescript
  1630. import {ThreeViewer, DepthBufferPlugin} from 'threepipe'
  1631. const viewer = new ThreeViewer({...})
  1632. const depthPlugin = viewer.addPluginSync(new DepthBufferPlugin(HalfFloatType))
  1633. const depthTarget = depthPlugin.target;
  1634. // Use the depth target by accesing `depthTarget.texture`.
  1635. ```
  1636. 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.
  1637. ## NormalBufferPlugin
  1638. [//]: # (todo: image)
  1639. [Example](https://threepipe.org/examples/#normal-buffer-plugin/) &mdash;
  1640. [Source Code](./src/plugins/pipeline/NormalBufferPlugin.ts) &mdash;
  1641. [API Reference](https://threepipe.org/docs/classes/NormalBufferPlugin.html)
  1642. 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.
  1643. Note: Use [`GBufferPlugin`](#GBufferPlugin) if using both `DepthBufferPlugin` and `NormalBufferPlugin` to render both depth and normal buffers in a single pass.
  1644. ```typescript
  1645. import {ThreeViewer, NormalBufferPlugin} from 'threepipe'
  1646. const viewer = new ThreeViewer({...})
  1647. const normalPlugin = viewer.addPluginSync(new NormalBufferPlugin())
  1648. const normalTarget = normalPlugin.target;
  1649. // Use the normal target by accessing `normalTarget.texture`.
  1650. ```
  1651. ## GBufferPlugin
  1652. [//]: # (todo: image)
  1653. [Example](https://threepipe.org/examples/#gbuffer-plugin/) &mdash;
  1654. [Source Code](./src/plugins/pipeline/GBufferPlugin.ts) &mdash;
  1655. [API Reference](https://threepipe.org/docs/classes/GBufferPlugin.html)
  1656. GBuffer Plugin adds a pre-render pass to the render manager and renders depth+normals to a target and some customizable flags to another. The multiple render target and textures can be accessed by other plugins throughout the rendering pipeline to create effects like SSAO, SSR, etc.
  1657. ```typescript
  1658. import {ThreeViewer, GBufferPlugin} from 'threepipe'
  1659. const viewer = new ThreeViewer({...})
  1660. const gBufferPlugin = viewer.addPluginSync(new GBufferPlugin())
  1661. const gBuffer = gBufferPlugin.target;
  1662. const normalDepth = gBufferPlugin.normalDepthTexture;
  1663. const gBufferFlags = gBufferPlugin.flagsTexture;
  1664. ```
  1665. ## SSAOPlugin
  1666. [//]: # (todo: image)
  1667. [Example](https://threepipe.org/examples/#ssao-plugin/) &mdash;
  1668. [Source Code](./src/plugins/pipeline/SSAOPlugin.ts) &mdash;
  1669. [API Reference](https://threepipe.org/docs/classes/SSAOPlugin.html)
  1670. SSAO Plugin adds support for [Screen Space Ambient Occlusion](https://en.wikipedia.org/wiki/Screen_space_ambient_occlusion) to the viewer. Simply add the plugin to the viewer to use it.
  1671. This is done by adding a pre-render pass to the render manager which renders SSAO to a custom render target. SSAOPlugin depends on [GBufferPlugin](#gbufferplugin), and is automatically added if not already.
  1672. This render target is then used by all PhysicalMaterial(s) in the scene during the main RenderPass to get the AO data. SSAO can also be disabled from the UI of the material.
  1673. Note: Use with [ProgressivePlugin](#progressiveplugin) and `TemporalAAPlugin` for best results.
  1674. ```typescript
  1675. import {ThreeViewer, SSAOPlugin} from 'threepipe'
  1676. const viewer = new ThreeViewer({...})
  1677. const ssaoPlugin = viewer.addPluginSync(new SSAOPlugin())
  1678. // get the buffer.
  1679. console.log(ssaoPlugin.target);
  1680. // disable ssao for a material in the scene
  1681. material.userData.ssaoDisabled = true
  1682. ```
  1683. > In the target/buffer - The ssao data is in the `r` channel to remain compatible with ORM. `gba` contains the depth in vec3(xyz) format.
  1684. > Note that its `ssaoDisabled`, so setting it to `true` will disable the effect.
  1685. ## CanvasSnapshotPlugin
  1686. [//]: # (todo: image)
  1687. [Example](https://threepipe.org/examples/#canvas-snapshot-plugin/) &mdash;
  1688. [Source Code](./src/plugins/export/CanvasSnapshotPlugin.ts) &mdash;
  1689. [API Reference](https://threepipe.org/docs/classes/CanvasSnapshotPlugin.html)
  1690. Canvas Snapshot Plugin adds support for taking snapshots of the canvas and exporting them as images and data urls. It includes options to take snapshot of a region, mime type, quality render scale and scaling the output image. Check out the interface [CanvasSnapshotOptions](https://threepipe.org/docs/interfaces/CanvasSnapshotOptions.html) for more details.
  1691. ```typescript
  1692. import {ThreeViewer, CanvasSnapshotPlugin} from 'threepipe'
  1693. const viewer = new ThreeViewer({...})
  1694. const snapshotPlugin = viewer.addPluginSync(new CanvasSnapshotPlugin())
  1695. // download a snapshot.
  1696. await snapshotPlugin.downloadSnapshot('image.webp', { // all parameters are optional
  1697. scale: 1, // scale the final image
  1698. timeout: 0, // wait before taking the snapshot, in ms
  1699. quality: 0.9, // quality of the image (0-1) only for jpeg and webp
  1700. displayPixelRatio: 2, // render scale
  1701. mimeType: 'image/webp', // mime type of the image
  1702. waitForProgressive: true, // wait for progressive rendering to finish (ProgressivePlugin). true by default
  1703. rect: { // region to take snapshot. eg. crop center of the canvas
  1704. height: viewer.canvas.clientHeight / 2,
  1705. width: viewer.canvas.clientWidth / 2,
  1706. x: viewer.canvas.clientWidth / 4,
  1707. y: viewer.canvas.clientHeight / 4,
  1708. },
  1709. })
  1710. // get data url (string)
  1711. const dataUrl = await snapshotPlugin.getDataUrl({ // all parameters are optional
  1712. displayPixelRatio: 2, // render scale
  1713. mimeType: 'image/webp', // mime type of the image
  1714. })
  1715. // get File
  1716. const file = await snapshotPlugin.getFile('file.jpeg', { // all parameters are optional
  1717. mimeType: 'image/jpeg', // mime type of the image
  1718. })
  1719. ```
  1720. ## PickingPlugin
  1721. [//]: # (todo: image)
  1722. [Example](https://threepipe.org/examples/#picking-plugin/) &mdash;
  1723. [Source Code](./src/plugins/interaction/PickingPlugin.ts) &mdash;
  1724. [API Reference](https://threepipe.org/docs/classes/PickingPlugin.html)
  1725. Picking Plugin adds support for selecting and hovering over objects in the viewer with user interactions and selection widgets.
  1726. When the plugin is added to the viewer, it starts listening to the mouse move and click events over the canvas.
  1727. When an object is clicked, it is selected,
  1728. and if a UI plugin is added, the uiconfig for the selected object is populated in the interface.
  1729. The events `selectedObjectChanged`, `hoverObjectChanged`, and `hitObject` can be listened to on the plugin.
  1730. Picking plugin internally uses [ObjectPicker](https://threepipe.org/docs/classes/ObjectPicker.html),
  1731. check out the documentation or source code for more information.
  1732. ```typescript
  1733. import {ThreeViewer, PickingPlugin} from 'threepipe'
  1734. const viewer = new ThreeViewer({...})
  1735. const pickingPlugin = viewer.addPluginSync(new PickingPlugin())
  1736. // Hovering events are also supported, but since its computationally expensive for large scenes it is disabled by default.
  1737. pickingPlugin.hoverEnabled = true
  1738. pickingPlugin.addEventListener('hitObject', (e)=>{
  1739. // This is fired when the user clicks on the canvas.
  1740. // The selected object hasn't been changed yet, and we have the option to change it or disable selection at this point.
  1741. // e.intersects.selectedObject contains the object that the user clicked on.
  1742. console.log('Hit: ', e.intersects.selectedObject)
  1743. // It can be changed here
  1744. // e.intersects.selectedObject = e.intersects.selectedObject.parent // select the parent
  1745. // e.intersects.selectedObject = null // unselect
  1746. // Check other properties on the event like intersects, mouse position, normal etc.
  1747. console.log(e)
  1748. })
  1749. pickingPlugin.addEventListener('selectedObjectChanged', (e)=>{
  1750. // This is fired when the selected object is changed.
  1751. // e.object contains the new selected object. It can be null if nothing is selected.
  1752. console.log('Selected: ', e.object)
  1753. })
  1754. // Objects can be programmatically selected and unselected
  1755. // to select
  1756. pickingPlugin.setSelectedObject(object)
  1757. // get the selected object
  1758. console.log(pickingPlugin.getSelectedObject())
  1759. // to unselect
  1760. pickingPlugin.setSelectedObject(null)
  1761. // Select object with camera animation to the object
  1762. pickingPlugin.setSelectedObject(object, true)
  1763. pickingPlugin.addEventListener('hoverObjectChanged', (e)=>{
  1764. // This is fired when the hovered object is changed.
  1765. // e.object contains the new hovered object.
  1766. console.log('Hovering: ', e.object)
  1767. })
  1768. ```
  1769. ## FullScreenPlugin
  1770. [//]: # (todo: image)
  1771. [Example](https://threepipe.org/examples/#fullscreen-plugin/) &mdash;
  1772. [Source Code](./src/plugins/interaction/FullScreenPlugin.ts) &mdash;
  1773. [API Reference](https://threepipe.org/docs/classes/FullScreenPlugin.html)
  1774. A simple plugin that provides functions to enter, exit and toggle full screen mode and check if the viewer is in full screen mode. Either the canvas or the whole container can be set to full screen.
  1775. ```typescript
  1776. import {ThreeViewer, FullScreenPlugin} from 'threepipe'
  1777. const viewer = new ThreeViewer({...})
  1778. const fullscreen = viewer.addPluginSync(new FullScreenPlugin())
  1779. // enter full screen
  1780. await fullscreen.enter(viewer.container) // viewer.canvas is used if no element is passed
  1781. // exit full screen
  1782. await fullscreen.exit()
  1783. // toggle
  1784. await fullscreen.toggle(viewer.container)
  1785. // check if full screen
  1786. console.log(fullScreenPlugin.isFullScreen())
  1787. ```
  1788. ## AssetExporterPlugin
  1789. [//]: # (todo: image)
  1790. [Example](https://threepipe.org/examples/#asset-exporter-plugin/) &mdash;
  1791. [Source Code](./src/plugins/export/AssetExporterPlugin.ts) &mdash;
  1792. [API Reference](https://threepipe.org/docs/classes/AssetExporterPlugin.html)
  1793. Asset Exporter Plugin provides options and methods to export the scene, object GLB or Viewer Config.
  1794. All the functionality is available in the viewer(and `AssetExporter`) directly, this plugin only provides a ui-config and maintains state of the options which is saved as plugin configuration along with glb/vjson file
  1795. ```typescript
  1796. import {ThreeViewer, AssetExporterPlugin} from 'threepipe'
  1797. const viewer = new ThreeViewer({...})
  1798. const assetExporter = viewer.addPluginSync(new AssetExporterPlugin())
  1799. // check the existing options
  1800. console.log(assetExporter.exportOptions)
  1801. // enable/disable viewer config/json embedding in glb
  1802. assetExporter.viewerConfig = true
  1803. // set encryption
  1804. assetExporter.encrypt = true
  1805. assetExporter.encryptKey = 'superstrongpassword' // comment this to get prompted for a key during export.
  1806. // export scene as blob
  1807. const blob = assetExporter.exportScene()
  1808. // or export and download directly
  1809. assetExporter.downloadSceneGlb()
  1810. // export a specific object
  1811. const object = viewer.scene.getObjectByName('objectName')
  1812. const blob2 = assetExporter.exportObject(object, true) // true to also download
  1813. ```
  1814. Note: when downloading the model through the plugin, it uses viewer.export, which downloads the files by default, but uploads it to remote destinations when overloaded using `FileTransferPlugin`.
  1815. ## LoadingScreenPlugin
  1816. [//]: # (todo: image)
  1817. [Example](https://threepipe.org/examples/#loading-screen-plugin/) &mdash;
  1818. [Source Code](./src/plugins/interaction/LoadingScreenPlugin.ts) &mdash;
  1819. [API Reference](https://threepipe.org/docs/classes/LoadingScreenPlugin.html)
  1820. Loading Screen Plugin adds configurable overlay with a logo, loading text, spinner and the list of loading items. It also provides options to minimize and maximize the loading popup when there is no objects in the scene.
  1821. The overlay is automatically added to the viewer container and shown when any files are loading. Behaviour can be configured to change how its shown and hidden, and can even be triggered programmatically.
  1822. ```typescript
  1823. import {ThreeViewer, LoadingScreenPlugin} from 'threepipe'
  1824. const viewer = new ThreeViewer({...})
  1825. const loadingScreen = viewer.addPluginSync(new LoadingScreenPlugin())
  1826. loadingScreen.loadingTextHeader = 'Loading Helmet 3D Model'
  1827. loadingScreen.errorTextHeader = 'Error Loading Helmet 3D Model'
  1828. loadingScreen.showFileNames = true
  1829. loadingScreen.showProcessStates = true
  1830. loadingScreen.showProgress = true
  1831. loadingScreen.backgroundOpacity = 0.4 // 0-1
  1832. loadingScreen.backgroundBlur = 28 // px
  1833. ```
  1834. See also the base class [AAssetManagerProcessStatePlugin](https://threepipe.org/docs/classes/AAssetManagerProcessStatePlugin.html) to write a custom loading plugin.
  1835. ## InteractionPromptPlugin
  1836. [//]: # (todo: image)
  1837. [Example](https://threepipe.org/examples/#interaction-prompt-plugin/) &mdash;
  1838. [Source Code](./src/plugins/interaction/InteractionPromptPlugin.ts) &mdash;
  1839. [API Reference](https://threepipe.org/docs/classes/InteractionPromptPlugin.html)
  1840. Interaction Prompt Plugin adds a hand pointer icon over the canvas that moves to prompt the user to interact with the 3d scene. To use, simply add the plugin to the viewer.
  1841. The default pointer icon from [google/model-viewer](https://github.com/google/model-viewer) and can be configured with the `pointerIcon` property.
  1842. The pointer is automatically shown when some object is in the scene and the camera is not moving.
  1843. The animation starts after a delay and stops on user interaction. It then restarts after a delay after the user stops interacting
  1844. The plugin provides several options and functions to configure the automatic behaviour or trigger the animation manually.
  1845. ```typescript
  1846. import {ThreeViewer, InteractionPromptPlugin} from 'threepipe'
  1847. const viewer = new ThreeViewer({...})
  1848. const interactionPrompt = viewer.addPluginSync(new InteractionPromptPlugin())
  1849. // change duration
  1850. interactionPrompt.animationDuration = 3000
  1851. // change animation distance in pixels
  1852. interactionPrompt.animationDistance = 100
  1853. // disable auto start when the camera stops
  1854. interactionPrompt.autoStart = false
  1855. interactionPrompt.autoStop = false
  1856. // manually start and stop
  1857. interactionPrompt.startAnimation()
  1858. // ...
  1859. interactionPrompt.stopAnimation()
  1860. ```
  1861. Note - The pointer is automatically shown/hidden when animation is started/stopped.
  1862. ## TransformControlsPlugin
  1863. [//]: # (todo: image)
  1864. [Example](https://threepipe.org/examples/#transform-controls-plugin/) &mdash;
  1865. [Source Code](./src/plugins/interaction/TransformControlsPlugin.ts) &mdash;
  1866. [API Reference](https://threepipe.org/docs/classes/TransformControlsPlugin.html)
  1867. Transform Controls Plugin adds support for moving, rotating and scaling objects in the viewer with interactive widgets.
  1868. Under the hood, TransformControlsPlugin uses [TransformControls2](https://threepipe.org/docs/classes/TransformControls2) to provide the interactive controls, it is a extended version of three.js [TransformControls](https://threejs.org/docs/#examples/en/controls/TransformControls).
  1869. When the plugin is added to the viewer, it interfaces with the [PickingPlugin](#pickingplugin) and shows the control gizmos when an object is selected and hides them when the object is unselected.
  1870. If the `PickingPlugin` is not added to the viewer before the `TransformControlsPlugin`, it is added automatically with the plugin.
  1871. ```typescript
  1872. import {ThreeViewer, TransformControlsPlugin} from 'threepipe'
  1873. const viewer = new ThreeViewer({...})
  1874. const transfromControlsPlugin = viewer.addPluginSync(new TransformControlsPlugin())
  1875. // Get the underlying transform controls
  1876. console.log(transfromControlsPlugin.transformControls)
  1877. ```
  1878. ## ContactShadowGroundPlugin
  1879. [//]: # (todo: image)
  1880. [Example](https://threepipe.org/examples/#contact-shadow-ground-plugin/) &mdash;
  1881. [Source Code](./src/plugins/extras/ContactShadowGroundPlugin.ts) &mdash;
  1882. [API Reference](https://threepipe.org/docs/classes/ContactShadowGroundPlugin.html)
  1883. Contact Shadow Ground Plugin adds a ground plane with three.js contact shadows to the viewer scene.
  1884. The plane is added to the scene root at runtime and not saved with scene export. Instead the plugin settings are saved with the scene.
  1885. It inherits from the base class [BaseGroundPlugin](https://threepipe.org/docs/classes/BaseGroundPlugin.html) which provides generic ground plane functionality. Check the source code for more details. With the property `autoAdjustTransform`, the ground plane is automatically adjusted based on the bounding box of the scene.
  1886. ```typescript
  1887. import {ThreeViewer, ContactShadowGroundPlugin} from 'threepipe'
  1888. const viewer = new ThreeViewer({...})
  1889. viewer.addPluginSync(new ContactShadowGroundPlugin())
  1890. ```
  1891. ## GLTFAnimationPlugin
  1892. [//]: # (todo: image)
  1893. [Example](https://threepipe.org/examples/#gltf-animation-plugin/) &mdash;
  1894. [Source Code](./src/plugins/animation/GLTFAnimationPlugin.ts) &mdash;
  1895. [API Reference](https://threepipe.org/docs/classes/GLTFAnimationPlugin.html)
  1896. Manages playback of GLTF animations.
  1897. The GLTF animations can be created in any 3d software that supports GLTF export like Blender.
  1898. If animations from multiple files are loaded, they will be merged in a single root object and played together.
  1899. 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.
  1900. 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.
  1901. 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
  1902. ## PopmotionPlugin
  1903. [//]: # (todo: image)
  1904. [Example](https://threepipe.org/examples/#popmotion-plugin/) &mdash;
  1905. [Source Code](./src/plugins/animation/PopmotionPlugin.ts) &mdash;
  1906. [API Reference](https://threepipe.org/docs/classes/PopmotionPlugin.html)
  1907. Provides animation/tweening capabilities to the viewer using the [popmotion.io](https://popmotion.io/) library.
  1908. Overrides the driver in popmotion to sync with the viewer and provide ways to store and stop animations.
  1909. ```typescript
  1910. import {PopmotionPlugin, ThreeViewer} from 'threepipe'
  1911. const viewer = new ThreeViewer({...})
  1912. const cube = viewer.scene.getObjectByName('cube');
  1913. const popmotion = viewer.addPluginSync(new PopmotionPlugin())
  1914. // Move the object cube 1 unit up.
  1915. const anim = popmotion.animateTarget(cube, 'position', {
  1916. to: cube.position.clone().add(new Vector3(0,1,0)),
  1917. duration: 500, // ms
  1918. onComplete: () => isMovedUp = true,
  1919. onStop: () => throw(new Error('Animation stopped')),
  1920. })
  1921. // Alternatively, set the property directly in onUpdate.
  1922. const anim1 = popmotion.animate({
  1923. from: cube.position.y,
  1924. to: cube.position.y + 1,
  1925. duration: 500, // ms
  1926. onUpdate: (v) => {
  1927. cube.position.setY(v)
  1928. cube.setDirty()
  1929. },
  1930. onComplete: () => isMovedUp = true,
  1931. onStop: () => throw(new Error('Animation stopped')),
  1932. onEnd: () => console.log('Animation ended'), // This runs after both onComplete and onStop
  1933. })
  1934. // await for animation. This promise will reject only if an exception is thrown in onStop or onComplete. onStop rejects if throwOnStop is true
  1935. await anim.promise.catch((e)=>{
  1936. console.log(e, 'animation stopped before completion')
  1937. });
  1938. // or stop the animation
  1939. // anim.stop()
  1940. // Animate the color
  1941. await popmotion.animateAsync({ // Also await for the animation.
  1942. from: '#' + cube.material.color.getHexString(),
  1943. to: '#' + new Color().setHSL(Math.random(), 1, 0.5).getHexString(),
  1944. duration: 1000, // 1s
  1945. onUpdate: (v) => {
  1946. cube.material.color.set(v)
  1947. cube.material.setDirty()
  1948. },
  1949. })
  1950. ```
  1951. Note: The animation is started when the animate or animateAsync function is called.
  1952. ## CameraViewPlugin
  1953. [//]: # (todo: image)
  1954. [Example](https://threepipe.org/examples/#camera-view-plugin/) &mdash;
  1955. [Source Code](./src/plugins/animation/CameraViewPlugin.ts) &mdash;
  1956. [API Reference](https://threepipe.org/docs/classes/CameraViewPlugin.html)
  1957. CameraViewPlugin adds support to save and load camera views, which can then be animated to.
  1958. It uses PopmotionPlugin internally to animate any camera to a saved view or to loop through all the saved views.
  1959. It also provides a UI to manage the views.
  1960. ```typescript
  1961. import {CameraViewPlugin, ThreeViewer, CameraView, Vector3, Quaternion, EasingFunctions, timeout} from 'threepipe'
  1962. const viewer = new ThreeViewer({...})
  1963. const cameraViewPlugin = viewer.addPluginSync(new CameraViewPlugin())
  1964. const intialView = cameraViewPlugin.getView()
  1965. // or = viewer.scene.mainCamera.getView()
  1966. // create a new view
  1967. const view = new CameraView(
  1968. 'My View', // name
  1969. new Vector3(0, 0, 10), // position
  1970. new Vector3(0, 0, 0), // target
  1971. new Quaternion(0, 0, 0, 1), // quaternion rotation
  1972. 1 // zoom
  1973. )
  1974. // or clone a view
  1975. const view2 = intialView.clone()
  1976. view2.position.add(new Vector3(0, 5, 0)) // move up 5 units
  1977. // animate the main camera to a view
  1978. await cameraViewPlugin.animateToView(
  1979. view,
  1980. 2000, // in ms, = 2sec
  1981. EasingFunctions.easeInOut,
  1982. ).catch(()=>console.log('Animation stopped'))
  1983. // stop any/all animations
  1984. cameraViewPlugin.stopAllAnimations()
  1985. // add views to the plugin
  1986. cameraViewPlugin.addView(view)
  1987. cameraViewPlugin.addView(view2)
  1988. cameraViewPlugin.addView(intialView)
  1989. cameraViewPlugin.addCurrentView() // adds the current view of the main camera
  1990. // loop through all the views once
  1991. cameraViewPlugin.animDuration = 2000 // default duration
  1992. cameraViewPlugin.animEase = EasingFunctions.easeInOutSine // default easing
  1993. await cameraViewPlugin.animateAllViews()
  1994. // loop through all the views forever
  1995. cameraViewPlugin.viewLooping = true
  1996. await timeout(10000) // wait for some time
  1997. // stop looping
  1998. cameraViewPlugin.viewLooping = false
  1999. ```
  2000. ## RenderTargetPreviewPlugin
  2001. [//]: # (todo: image)
  2002. [Example](https://threepipe.org/examples/#render-target-preview/) &mdash;
  2003. [Source Code](./src/plugins/ui/RenderTargetPreviewPlugin.ts) &mdash;
  2004. [API Reference](https://threepipe.org/docs/classes/RenderTargetPreviewPlugin.html)
  2005. RenderTargetPreviewPlugin is a useful development and debugging plugin that renders any registered render-target to the screen in small collapsable panels.
  2006. ```typescript
  2007. import {ThreeViewer, RenderTargetPreviewPlugin, NormalBufferPlugin} from 'threepipe'
  2008. const viewer = new ThreeViewer({...})
  2009. const normalPlugin = viewer.addPluginSync(new NormalBufferPlugin(HalfFloatType))
  2010. const previewPlugin = viewer.addPluginSync(new RenderTargetPreviewPlugin())
  2011. // Show the normal buffer in a panel
  2012. previewPlugin.addTarget(()=>normalPlugin.target, 'normal', false, false)
  2013. ```
  2014. ## GeometryUVPreviewPlugin
  2015. [//]: # (todo: image)
  2016. [Example](https://threepipe.org/examples/#geometry-uv-preview/) &mdash;
  2017. [Source Code](./src/plugins/ui/GeometryUVPreviewPlugin.ts) &mdash;
  2018. [API Reference](https://threepipe.org/docs/classes/GeometryUVPreviewPlugin.html)
  2019. GeometryUVPreviewPlugin is a useful development and debugging plugin
  2020. that adds a panel to the viewer to show the UVs of a geometry.
  2021. ```typescript
  2022. import {ThreeViewer, GeometryUVPreviewPlugin, SphereGeometry} from 'threepipe'
  2023. const viewer = new ThreeViewer({...})
  2024. const previewPlugin = viewer.addPluginSync(new GeometryUVPreviewPlugin())
  2025. const geometry = new SphereGeometry(1, 32, 32)
  2026. // Show the normal buffer in a panel
  2027. previewPlugin.addGeometry(geometry, 'sphere')
  2028. ```
  2029. ## FrameFadePlugin
  2030. [//]: # (todo: image)
  2031. [Example](https://threepipe.org/examples/#frame-fade-plugin/) &mdash;
  2032. [Source Code](./src/plugins/pipeline/FrameFadePlugin.ts) &mdash;
  2033. [API Reference](https://threepipe.org/docs/classes/FrameFadePlugin.html)
  2034. 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.
  2035. ```typescript
  2036. import {ThreeViewer, FrameFadePlugin} from 'threepipe'
  2037. const viewer = new ThreeViewer({...})
  2038. const fadePlugin = viewer.addPluginSync(new FrameFadePlugin())
  2039. // Make some changes in the scene (any visual change that needs to be faded)
  2040. // Start transition and wait for it to finish
  2041. await fadePlugin.startTransition(400) // duration in ms
  2042. ```
  2043. 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.
  2044. 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.
  2045. ## VignettePlugin
  2046. [//]: # (todo: image)
  2047. [Example](https://threepipe.org/examples/#vignette-plugin/) &mdash;
  2048. [Source Code](./src/plugins/postprocessing/VignettePlugin.ts) &mdash;
  2049. [API Reference](https://threepipe.org/docs/classes/VignettePlugin.html)
  2050. VignettePlugin adds a post-processing material extension to the ScreenPass in render manager
  2051. that applies a vignette effect to the final render. The parameters `power` and `color` can be changed to customize the effect.
  2052. ```typescript
  2053. import {ThreeViewer, VignettePlugin} from 'threepipe'
  2054. const viewer = new ThreeViewer({...})
  2055. const vignettePlugin = viewer.addPluginSync(VignettePlugin)
  2056. // Change the vignette color
  2057. vignettePlugin.power = 1
  2058. vignettePlugin.color = new Color(0.5, 0, 0)
  2059. // or
  2060. // vignettePlugin.color.set('#ff0000'); vignettePlugin.setDirty() // Call setDirty to tell the plugin that color has changed
  2061. ```
  2062. ## ChromaticAberrationPlugin
  2063. [//]: # (todo: image)
  2064. [Example](https://threepipe.org/examples/#chromatic-aberration-plugin/) &mdash;
  2065. [Source Code](./src/plugins/postprocessing/ChromaticAberrationPlugin.ts) &mdash;
  2066. [API Reference](https://threepipe.org/docs/classes/ChromaticAberrationPlugin.html)
  2067. ChromaticAberrationPlugin adds a post-processing material extension to the ScreenPass in render manager
  2068. that applies a chromatic-aberration effect to the final render. The parameter `intensity` can be changed to customize the effect.
  2069. ```typescript
  2070. import {ThreeViewer, ChromaticAberrationPlugin} from 'threepipe'
  2071. const viewer = new ThreeViewer({...})
  2072. const chromaticAberrationPlugin = viewer.addPluginSync(ChromaticAberrationPlugin)
  2073. // Change the chromaticAberration color
  2074. chromaticAberrationPlugin.intensity = 0.5
  2075. ```
  2076. ## FilmicGrainPlugin
  2077. [//]: # (todo: image)
  2078. [Example](https://threepipe.org/examples/#filmic-grain-plugin/) &mdash;
  2079. [Source Code](./src/plugins/postprocessing/FilmicGrainPlugin.ts) &mdash;
  2080. [API Reference](https://threepipe.org/docs/classes/FilmicGrainPlugin.html)
  2081. FilmicGrainPlugin adds a post-processing material extension to the ScreenPass in render manager
  2082. that applies a filmic-grain effect to the final render. The parameters `power` and `color` can be changed to customize the effect.
  2083. ```typescript
  2084. import {ThreeViewer, FilmicGrainPlugin} from 'threepipe'
  2085. const viewer = new ThreeViewer({...})
  2086. const filmicGrainPlugin = viewer.addPluginSync(FilmicGrainPlugin)
  2087. // Change the filmicGrain color
  2088. filmicGrainPlugin.intensity = 10
  2089. filmicGrainPlugin.multiply = false
  2090. ```
  2091. ## NoiseBumpMaterialPlugin
  2092. [//]: # (todo: image)
  2093. [Example](https://threepipe.org/examples/#noise-bump-material-plugin/) &mdash;
  2094. [Source Code](./src/plugins/material/NoiseBumpMaterialPlugin.ts) &mdash;
  2095. [API Reference](https://threepipe.org/docs/classes/NoiseBumpMaterialPlugin.html)
  2096. 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.
  2097. It uses voronoise function from blender along with several additions to generate the noise for the generation.
  2098. It also adds a UI to the material to edit the settings.
  2099. It uses `WEBGI_materials_noise_bump` glTF extension to save the settings in glTF/glb files.
  2100. ```typescript
  2101. import {ThreeViewer, NoiseBumpMaterialPlugin} from 'threepipe'
  2102. const viewer = new ThreeViewer({...})
  2103. const noiseBump = viewer.addPluginSync(NoiseBumpMaterialPlugin)
  2104. // Add noise bump to a material
  2105. NoiseBumpMaterialPlugin.AddNoiseBumpMaterial(material, {
  2106. flakeScale: 300,
  2107. })
  2108. // Change properties with code or use the UI
  2109. material.userData._noiseBumpMat!.bumpNoiseParams = [1, 1]
  2110. material.setDirty()
  2111. // Disable
  2112. material.userData._noiseBumpMat!.hasBump = false
  2113. material.setDirty()
  2114. ```
  2115. ## CustomBumpMapPlugin
  2116. [//]: # (todo: image)
  2117. [Example](https://threepipe.org/examples/#custom-bump-map-plugin/) &mdash;
  2118. [Source Code](./src/plugins/material/CustomBumpMapPlugin.ts) &mdash;
  2119. [API Reference](https://threepipe.org/docs/classes/CustomBumpMapPlugin.html)
  2120. CustomBumpMapPlugin adds a material extension to PhysicalMaterial to support custom bump maps.
  2121. 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.
  2122. This plugin also has support for bicubic filtering of the custom bump map and is enabled by default.
  2123. It also adds a UI to the material to edit the settings.
  2124. It uses `WEBGI_materials_custom_bump_map` glTF extension to save the settings in glTF/glb files.
  2125. ```typescript
  2126. import {ThreeViewer, CustomBumpMapPlugin} from 'threepipe'
  2127. const viewer = new ThreeViewer({...})
  2128. const customBump = viewer.addPluginSync(CustomBumpMapPlugin)
  2129. // Add noise bump to a material
  2130. customBump.enableCustomBump(material, bumpMap, 0.2)
  2131. // Change properties with code or use the UI
  2132. material.userData._customBumpMat = texture
  2133. material.setDirty()
  2134. // Disable
  2135. material.userData._hasCustomBump = false
  2136. // or
  2137. material.userData._customBumpMat = null
  2138. material.setDirty()
  2139. ```
  2140. ## ClearcoatTintPlugin
  2141. [//]: # (todo: image)
  2142. [Example](https://threepipe.org/examples/#clearcoat-tint-plugin/) &mdash;
  2143. [Source Code](./src/plugins/material/ClearcoatTintPlugin.ts) &mdash;
  2144. [API Reference](https://threepipe.org/docs/classes/ClearcoatTintPlugin.html)
  2145. ClearcoatTintPlugin adds a material extension to PhysicalMaterial which adds tint and thickness to the built-in clearcoat properties.
  2146. It also adds a UI to the material to edit the settings.
  2147. It uses `WEBGI_materials_clearcoat_tint` glTF extension to save the settings in glTF/glb files.
  2148. ```typescript
  2149. import {ThreeViewer, ClearcoatTintPlugin} from 'threepipe'
  2150. const viewer = new ThreeViewer({...})
  2151. const clearcoatTint = viewer.addPluginSync(ClearcoatTintPlugin)
  2152. material.clearcoat = 1
  2153. // add initial properties
  2154. ClearcoatTintPlugin.AddClearcoatTint(material, {
  2155. tintColor: '#ff0000',
  2156. thickness: 1,
  2157. })
  2158. // Change properties with code or use the UI
  2159. material.userData._clearcoatTint!.tintColor = '#ff0000'
  2160. material.setDirty()
  2161. // Disable
  2162. material.userData._clearcoatTint.enableTint = false
  2163. material.setDirty()
  2164. ```
  2165. ## FragmentClippingExtensionPlugin
  2166. [//]: # (todo: image)
  2167. [Example](https://threepipe.org/examples/#fragment-clipping-extension-plugin/) &mdash;
  2168. [Source Code](./src/plugins/material/FragmentClippingExtensionPlugin.ts) &mdash;
  2169. [API Reference](https://threepipe.org/docs/classes/FragmentClippingExtensionPlugin.html)
  2170. FragmentClippingExtensionPlugin adds a material extension to PhysicalMaterial to add support for fragment clipping.
  2171. Fragment clipping allows to clip fragments of the material in screen space or world space based on a circle, rectangle, plane, sphere, etc.
  2172. It uses fixed SDFs with params defined by the user for clipping.
  2173. It also adds a UI to the material to edit the settings.
  2174. It uses `WEBGI_materials_fragment_clipping_extension` glTF extension to save the settings in glTF/glb files.
  2175. ```typescript
  2176. import {ThreeViewer, FragmentClippingExtensionPlugin} from 'threepipe'
  2177. const viewer = new ThreeViewer({...})
  2178. const fragmentClipping = viewer.addPluginSync(FragmentClippingExtensionPlugin)
  2179. // add initial properties
  2180. FragmentClippingExtensionPlugin.AddFragmentClipping(material, {
  2181. clipPosition: new Vector4(0.5, 0.5, 0, 0),
  2182. clipParams: new Vector4(0.1, 0.05, 0, 1),
  2183. })
  2184. // Change properties with code or use the UI
  2185. material.userData._fragmentClipping!.clipPosition.set(0, 0, 0, 0)
  2186. material.setDirty()
  2187. // Disable
  2188. material.userData._clearcoatTint.clipEnabled = false
  2189. material.setDirty()
  2190. ```
  2191. ## ParallaxMappingPlugin
  2192. [//]: # (todo: image)
  2193. [Example](https://threepipe.org/examples/#parallax-mapping-plugin/) &mdash;
  2194. [Source Code](./src/plugins/material/ParallaxMappingPlugin.ts) &mdash;
  2195. [API Reference](https://threepipe.org/docs/classes/ParallaxMappingPlugin.html)
  2196. `ParallaxMappingPlugin` adds a material extension to PhysicalMaterial to add support for [parallax relief mapping](https://en.wikipedia.org/wiki/Relief_mapping_(computer_graphics)). The idea is to walk along a ray that has entered the bumpmap's volume, finding the intersection point of the ray with the bumpmap. [Steep parallax mapping](https://en.wikipedia.org/wiki/Parallax_mapping) and [parallax occlusion mapping](https://en.wikipedia.org/wiki/Parallax_occlusion_mapping) are other common names for these techniques.
  2197. To use the plugin, add the plugin to the viewer and use the `bumpMap` in `PhysicalMaterial` normally. The max height is determined by the `bumpScale` in the material. This is assumed to be in world scale.
  2198. ```typescript
  2199. import {ThreeViewer, ParallaxMappingPlugin} from 'threepipe'
  2200. const viewer = new ThreeViewer({...})
  2201. const parallaxMapping = viewer.addPluginSync(ParallaxMappingPlugin)
  2202. // load or create an object
  2203. // set the bump map
  2204. object.material.bumpMap = await viewer.load<ITexture>(bumps[0]) || null
  2205. // set the bump scale
  2206. object.material.bumpScale = 0.1
  2207. // setDirty to notify the viewer to update.
  2208. object.material.setDirty()
  2209. ```
  2210. ### References and related links:
  2211. - WebGL implementation by Rabbid76 - [github.com/Rabbid76/graphics-snippets](https://github.com/Rabbid76/graphics-snippets/blob/master/html/technique/parallax_005_parallax_relief_mapping_derivative_tbn.html)
  2212. - Lesson on Parallax Occlusion Mapping in GLSL - [http://sunandblackcat.com/tipFullView.php?topicid=28](https://web.archive.org/web/20190128023901/http://sunandblackcat.com/tipFullView.php?topicid=28)
  2213. - Learn OpenGL - https://learnopengl.com/Advanced-Lighting/Parallax-Mapping
  2214. ## HDRiGroundPlugin
  2215. [//]: # (todo: image)
  2216. [Example](https://threepipe.org/examples/#hdri-ground-plugin/) &mdash;
  2217. [Source Code](./src/plugins/extras/HDRiGroundPlugin.ts) &mdash;
  2218. [API Reference](https://threepipe.org/docs/classes/HDRiGroundPlugin.html)
  2219. 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.
  2220. The world radius, tripod height, and origin position(center offset) can be set in the plugin.
  2221. The plugin is disabled by default when added. Set `.enabled` to enable it or pass `true` in the constructor.
  2222. 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.
  2223. ```typescript
  2224. import {ThreeViewer, HDRiGrounPlugin} from 'threepipe'
  2225. const viewer = new ThreeViewer({...})
  2226. const hdriGround = viewer.addPluginSync(new HDRiGrounPlugin())
  2227. // Load an hdr environment map
  2228. await viewer.setEnvironmentMap('https://threejs.org/examples/textures/equirectangular/venice_sunset_1k.hdr')
  2229. // set background to environment
  2230. viewer.scene.background = 'environment'
  2231. // or
  2232. // viewer.scene.background = viewer.scene.environemnt
  2233. // enable the plugin
  2234. hdriGround.enabled = true
  2235. ```
  2236. Check the [example](https://threepipe.org/examples/#hdri-ground-plugin/) for a demo.
  2237. ## VirtualCamerasPlugin
  2238. [//]: # (todo: image)
  2239. [Example](https://threepipe.org/examples/#virtual-cameras-plugin/) &mdash;
  2240. [Source Code](./src/plugins/rendering/VirtualCamerasPlugin.ts) &mdash;
  2241. [API Reference](https://threepipe.org/docs/classes/VirtualCamerasPlugin.html)
  2242. 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.
  2243. 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.
  2244. ```typescript
  2245. import {ThreeViewer, VirtualCamerasPlugin} from 'threepipe'
  2246. const viewer = new ThreeViewer({...})
  2247. const virtualCameras = viewer.addPluginSync(new VirtualCamerasPlugin())
  2248. const camera = new PerspectiveCamera2('orbit', viewer.canvas, false, 45, 1)
  2249. camera.name = name
  2250. camera.position.set(0, 5, 0)
  2251. camera.target.set(0, 0.25, 0)
  2252. camera.userData.autoLookAtTarget = true // automatically look at the target (in setDirty)
  2253. camera.setDirty()
  2254. camera.addEventListener('update', ()=>{
  2255. viewer.setDirty() // if the camera is not added to the scene it wont update automatically when camera.setDirty is called(like from the UI)
  2256. })
  2257. const vCam = virtualCameras.addCamera(camera)
  2258. console.log(vCam.target) // target is a WebGLRenderTarget/IRenderTarget
  2259. ```
  2260. Check the [virtual camera](https://threepipe.org/examples/#virtual-camera/) example for using the texture in the scene.
  2261. ## EditorViewWidgetPlugin
  2262. [//]: # (todo: image)
  2263. [Example](https://threepipe.org/examples/#editor-view-widget-plugin/) &mdash;
  2264. [Source Code](./src/plugins/interaction/EditorViewWidgetPlugin.ts) &mdash;
  2265. [API Reference](https://threepipe.org/docs/classes/EditorViewWidgetPlugin.html)
  2266. EditorViewWidgetPlugin adds a ViewHelper in the parent of the viewer canvas to show the current camera view and allow the user to change the camera view to one of the primary world axes.
  2267. Simply add the plugin to the viewer to see the widget.
  2268. ```typescript
  2269. import {ThreeViewer, EditorViewWidgetPlugin} from 'threepipe'
  2270. const viewer = new ThreeViewer({...})
  2271. const plugin = viewer.addPluginSync(new EditorViewWidgetPlugin())
  2272. // to hide the widget
  2273. plugin.enabled = false
  2274. ```
  2275. ## Object3DWidgetsPlugin
  2276. [//]: # (todo: image)
  2277. [Example](https://threepipe.org/examples/#object3d-widgets-plugin/) &mdash;
  2278. [Source Code](./src/plugins/extras/Object3DWidgetsPlugin.ts) &mdash;
  2279. [API Reference](https://threepipe.org/docs/classes/Object3DWidgetsPlugin.html)
  2280. Object3DWidgetsPlugin adds support for light and camera helpers/gizmos in the viewer.
  2281. A helper is automatically created when any supported light or camera is added to the scene.
  2282. Simply add the plugin to the viewer to see the widget.
  2283. Support for additional types of helpers can be added dynamically or by other plugins by pushing a helper constructor to the `Object3DWidgetsPlugin.helpers` array, and calling `Object3DWidgetsPlugin.refresh()`.
  2284. The helper class prototype should implement the `IObject3DHelper` interface. Check `DirectionalLightHelper2` for an example.
  2285. ```typescript
  2286. import {ThreeViewer, Object3DWidgetsPlugin, Object3DGeneratorPlugin} from 'threepipe'
  2287. const viewer = new ThreeViewer({...})
  2288. // Add the plugin to add support
  2289. const plugin = viewer.addPluginSync(new Object3DWidgetsPlugin())
  2290. // Add some lights or cameras to the scene. (This can be done before adding the plugin as well)
  2291. // Using Object3DGeneratorPlugin to create a camera and add it to the scene.
  2292. const generator = viewer.getOrAddPluginSync(Object3DGeneratorPlugin)
  2293. generator.generate('camera-perspective', {
  2294. position: new Vector3(5, 5, 0),
  2295. name: 'My Camera'
  2296. })
  2297. // to hide the widgets
  2298. plugin.enabled = false
  2299. // to add support for a custom helper
  2300. plugin.helpers.push(MyCustomHelper)
  2301. plugin.refresh()
  2302. ```
  2303. ## Object3DGeneratorPlugin
  2304. [//]: # (todo: image)
  2305. [Example](https://threepipe.org/examples/#object3d-generator-plugin/) &mdash;
  2306. [Source Code](./src/plugins/extras/Object3DGeneratorPlugin.ts) &mdash;
  2307. [API Reference](https://threepipe.org/docs/classes/Object3DGeneratorPlugin.html)
  2308. Object3DGeneratorPlugin adds support for creating different types of lights and camera objects in the viewer.
  2309. Call the `generate` method with any type to generate a type of object(like lights, cameras, mesh etc).
  2310. Support for the following types of generators is included in the plugin:
  2311. * camera-perspective - Creates instance of `PerspectiveCamera2`
  2312. * light-directional - Creates instance of `DirectionalLight2`
  2313. * light-ambient - Creates instance of `AmbientLight2`
  2314. * light-point - Creates instance of `PointLight2`
  2315. * light-spot - Creates instance of `SpotLight2`
  2316. * light-hemisphere - Creates instance of `HemisphereLight2`
  2317. * light-rect-area - Creates instance of `RectAreaLight2`
  2318. Additional types of generators can be added dynamically or by other plugins by adding a custom generator function to the `Object3DGeneratorPlugin.generators` object. This is done by [GeometryGeneratorPlugin](#threepipeplugin-geometry-generator) to add various type of primitive objects like plane, sphere, etc
  2319. A custom generator can take in any kind object as parameters and should return an `IObject3D`.
  2320. Sample Usage
  2321. ```typescript
  2322. import {ThreeViewer, Object3DWidgetsPlugin, Object3DGeneratorPlugin, Mesh2} from 'threepipe'
  2323. const viewer = new ThreeViewer({...})
  2324. const generator = viewer.addPluginSync(Object3DGeneratorPlugin)
  2325. generator.generate('camera-perspective', {
  2326. position: new Vector3(5, 5, 0),
  2327. name: 'My Camera'
  2328. })
  2329. const light = generator.generate('light-spot', {
  2330. position: new Vector3(5, 0, 0),
  2331. })
  2332. // to add support for a custom helper
  2333. plugin.generators['custom-object'] = (params)=>{
  2334. const object = new Mesh2(new PlaneGeometry(1,1), new PhysicalMaterial())
  2335. object.name = params.name ?? 'Custom Mesh'
  2336. if(params.position) object.position.copy(params.position)
  2337. return object
  2338. }
  2339. const obj = generator.generate('custom-object', {
  2340. position: new Vector3(5, 0, 0),
  2341. })
  2342. // Add Object3DWidgetsPlugin to see the added lights and cameras.
  2343. viewer.addPluginSync(new Object3DWidgetsPlugin())
  2344. ```
  2345. Check the [example](https://threepipe.org/examples/#object3d-generator-plugin/) for the UI.
  2346. ## DeviceOrientationControlsPlugin
  2347. [//]: # (todo: image)
  2348. [Example](https://threepipe.org/examples/#device-orientation-controls-plugin/) &mdash;
  2349. [Source Code](./src/plugins/interaction/DeviceOrientationControlsPlugin.ts) &mdash;
  2350. [API Reference](https://threepipe.org/docs/classes/DeviceOrientationControlsPlugin.html)
  2351. DeviceOrientationControlsPlugin enables controlling the main camera rotation in the scene with device orientation. This only works on devices which have a gyroscope(but can also be emulated in devtools in chrome).
  2352. After the plugin is added, it adds support for setting `deviceOrientation` as the key in `scene.mainCamera.controlMode`.
  2353. When the controls is started (for the first time), the current camera rotation is and the device orientation is saved and used as reference. To reset the saved device orientation, call `resetView` in the controls.
  2354. Sample Usage
  2355. ```typescript
  2356. import {ThreeViewer, DeviceOrientationControlsPlugin, Mesh2} from 'threepipe'
  2357. const viewer = new ThreeViewer({...})
  2358. viewer.addPluginSync(DeviceOrientationControlsPlugin)
  2359. // after some user action
  2360. viewer.scene.mainCamera.controlsMode = 'deviceOrientation'
  2361. // to reset the saved device orientation
  2362. viewer.scene.mainCamera.controls.resetView()
  2363. // switch back to default orbit controls
  2364. viewer.scene.mainCamera.controlsMode = 'orbit'
  2365. ```
  2366. ## PointerLockControlsPlugin
  2367. [//]: # (todo: image)
  2368. [Example](https://threepipe.org/examples/#pointer-lock-controls-plugin/) &mdash;
  2369. [Source Code](./src/plugins/interaction/PointerLockControlsPlugin.ts) &mdash;
  2370. [API Reference](https://threepipe.org/docs/classes/PointerLockControlsPlugin.html)
  2371. PointerLockControlsPlugin adds support for using PointerLockControls from three.js. It works similar to controls in first person shooter, captures the mouse pointer and uses it to look around with the camera.
  2372. After the plugin is added, it adds support for setting `pointerLock` as the key in `scene.mainCamera.controlMode`.
  2373. Sample Usage
  2374. ```typescript
  2375. import {ThreeViewer, PointerLockControlsPlugin, Mesh2} from 'threepipe'
  2376. const viewer = new ThreeViewer({...})
  2377. viewer.addPluginSync(PointerLockControlsPlugin)
  2378. // after some user action
  2379. viewer.scene.mainCamera.controlsMode = 'pointerLock'
  2380. // listen to lock/unlock events
  2381. viewer.scene.mainCamera.controls?.addEventListener('lock', ()=> console.log('pointer locked'))
  2382. viewer.scene.mainCamera.controls?.addEventListener('unlock', ()=> console.log('pointer unlocked'))
  2383. // switch back to default orbit controls
  2384. viewer.scene.mainCamera.controlsMode = 'orbit'
  2385. ```
  2386. ## ThreeFirstPersonControlsPlugin
  2387. [//]: # (todo: image)
  2388. [Example](https://threepipe.org/examples/#three-first-person-controls-plugin/) &mdash;
  2389. [Source Code](./src/plugins/interaction/ThreeFirstPersonControlsPlugin.ts) &mdash;
  2390. [API Reference](https://threepipe.org/docs/classes/ThreeFirstPersonControlsPlugin.html)
  2391. ThreeFirstPersonControlsPlugin adds support for using FirstPersonControls from three.js. It works similar to idle look around in first person games, it does not captures the mouse pointer.
  2392. After the plugin is added, it adds support for setting `threeFirstPerson` as the key in `scene.mainCamera.controlMode`.
  2393. Sample Usage
  2394. ```typescript
  2395. import {ThreeViewer, ThreeFirstPersonControlsPlugin, Mesh2} from 'threepipe'
  2396. const viewer = new ThreeViewer({...})
  2397. viewer.addPluginSync(ThreeFirstPersonControlsPlugin)
  2398. // after some user action
  2399. viewer.scene.mainCamera.controlsMode = 'threeFirstPerson'
  2400. // switch back to default orbit controls
  2401. viewer.scene.mainCamera.controlsMode = 'orbit'
  2402. ```
  2403. ## GLTFKHRMaterialVariantsPlugin
  2404. [//]: # (todo: image)
  2405. [Example](https://threepipe.org/examples/#gltf-khr-material-variants-plugin/) &mdash;
  2406. [Source Code](./src/plugins/extras/GLTFKHRMaterialVariantsPlugin.ts) &mdash;
  2407. [API Reference](https://threepipe.org/docs/classes/GLTFKHRMaterialVariantsPlugin.html)
  2408. GLTFKHRMaterialVariantsPlugin adds support for importing and exporting glTF models with the `KHR_materials_variants` extension to load the model with different material variants/combinations. It also provides API and UI to change the current material variant.
  2409. The plugin automatically adds support for the extension when added to the viewer.
  2410. The materials are stored in `object.userData._variantMaterials` and are automatically loaded and saved when using the `GLTFLoader`.
  2411. Sample Usage
  2412. ```typescript
  2413. import {ThreeViewer, GLTFKHRMaterialVariantsPlugin, Mesh2} from 'threepipe'
  2414. const viewer = new ThreeViewer({...})
  2415. const variantsPlugin = viewer.addPluginSync(GLTFKHRMaterialVariantsPlugin)
  2416. // load some model
  2417. await viewer.load(model_url)
  2418. // list of all variants in the model (names and objects)
  2419. console.log(variantsPlugin.variants)
  2420. // change the selected variant
  2421. variantsPlugin.selectedVariant = 'beach'
  2422. ```
  2423. ### Links
  2424. - https://www.khronos.org/blog/blender-gltf-i-o-support-for-gltf-pbr-material-extensions
  2425. - https://www.khronos.org/blog/streamlining-3d-commerce-with-material-variant-support-in-gltf-assets
  2426. - https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_variants/README.md
  2427. ## Rhino3dmLoadPlugin
  2428. [Example](https://threepipe.org/examples/#rhino3dm-load/) &mdash;
  2429. [Source Code](./src/plugins/import/Rhino3dmLoadPlugin.ts) &mdash;
  2430. [API Reference](https://threepipe.org/docs/classes/Rhino3dmLoadPlugin.html)
  2431. 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.
  2432. It also adds some helpful options to process the model after load.
  2433. ```typescript
  2434. import {Rhino3dmLoadPlugin} from 'threepipe'
  2435. const rhino3dmPlugin = viewer.addPluginSync(new Rhino3dmLoadPlugin())
  2436. rhino3dmPlugin.importMaterials = true // import materials source from 3dm file
  2437. rhino3dmPlugin.forceLayerMaterials = true // force material source to be layer in 3dm file.
  2438. rhino3dmPlugin.hideLineMesh = true // hide all lines and points in the model.
  2439. rhino3dmPlugin.replaceWithInstancedMesh = true // replace meshes with the same parent, geometry and material with a single instance mesh.
  2440. const mesh = await viewer.load('file.3dm')
  2441. ```
  2442. ## PLYLoadPlugin
  2443. [Example](https://threepipe.org/examples/#ply-load/) &mdash;
  2444. [Source Code](./src/plugins/import/PLYLoadPlugin.ts) &mdash;
  2445. [API Reference](https://threepipe.org/docs/classes/PLYLoadPlugin.html)
  2446. Adds support for loading .ply ([Polygon file format](https://en.wikipedia.org/wiki/PLY_(file_format))) files.
  2447. ```typescript
  2448. import {PLYLoadPlugin} from 'threepipe'
  2449. viewer.addPluginSync(new PLYLoadPlugin())
  2450. const mesh = await viewer.load('file.ply')
  2451. ```
  2452. ## USDZLoadPlugin
  2453. [Example](https://threepipe.org/examples/#usdz-load/) &mdash;
  2454. [Source Code](./src/plugins/import/USDZLoadPlugin.ts) &mdash;
  2455. [API Reference](https://threepipe.org/docs/classes/USDZLoadPlugin.html)
  2456. Adds support for loading .usdz and .usda ([Universal Scene Description](https://graphics.pixar.com/usd/docs/index.html)) files.
  2457. ```typescript
  2458. import {USDZLoadPlugin} from 'threepipe'
  2459. viewer.addPluginSync(new USDZLoadPlugin())
  2460. const mesh = await viewer.load('file.usdz')
  2461. const mesh2 = await viewer.load('file.usda')
  2462. ```
  2463. ## STLLoadPlugin
  2464. [Example](https://threepipe.org/examples/#stl-load/) &mdash;
  2465. [Source Code](./src/plugins/import/STLLoadPlugin.ts) &mdash;
  2466. [API Reference](https://threepipe.org/docs/classes/STLLoadPlugin.html)
  2467. Adds support for loading .stl ([Stereolithography](https://en.wikipedia.org/wiki/STL_(file_format))) files.
  2468. ```typescript
  2469. import {STLLoadPlugin} from 'threepipe'
  2470. viewer.addPluginSync(new STLLoadPlugin())
  2471. const mesh = await viewer.load('file.stl')
  2472. ```
  2473. ## KTX2LoadPlugin
  2474. [Example](https://threepipe.org/examples/#ktx2-load/) &mdash;
  2475. [Source Code](./src/plugins/import/KTX2LoadPlugin.ts) &mdash;
  2476. [API Reference](https://threepipe.org/docs/classes/KTX2LoadPlugin.html)
  2477. Adds support for loading .ktx2 ([Khronos Texture](https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/) files with asset manager and embedded in glTF files.
  2478. 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.
  2479. ```typescript
  2480. import {KTX2LoadPlugin} from 'threepipe'
  2481. viewer.addPluginSync(new KTX2LoadPlugin())
  2482. const texture = await viewer.load('file.ktx2')
  2483. ```
  2484. ## KTXLoadPlugin
  2485. [Example](https://threepipe.org/examples/#ktx-load/) &mdash;
  2486. [Source Code](./src/plugins/import/KTXLoadPlugin.ts) &mdash;
  2487. [API Reference](https://threepipe.org/docs/classes/KTXLoadPlugin.html)
  2488. Adds support for loading .ktx ([Khronos Texture](https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/) files.
  2489. 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.
  2490. ```typescript
  2491. import {KTXLoadPlugin} from 'threepipe'
  2492. viewer.addPluginSync(new KTXLoadPlugin())
  2493. const texture = await viewer.load('file.ktx')
  2494. ```
  2495. ## GLTFMeshOptDecodePlugin
  2496. [Example](https://threepipe.org/examples/#gltf-meshopt-compression/) &mdash;
  2497. [Source Code](./src/plugins/import/GLTFMeshOptDecodePlugin.ts) &mdash;
  2498. [API Reference](https://threepipe.org/docs/classes/GLTFMeshOptDecodePlugin.html)
  2499. Loads the MeshOpt Decoder module from [meshoptimizer](https://github.com/zeux/meshoptimizer) library at runtime from a customisable cdn url.
  2500. The loaded module is set in `window.MeshoptDecoder` and then used by `GLTFLoader2` to decode files using [EXT_meshopt_compression](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_meshopt_compression/README.md) extension
  2501. ```typescript
  2502. import {GLTFMeshOptDecodePlugin} from 'threepipe'
  2503. const plugin = viewer.addPluginSync(new GLTFMeshOptDecodePlugin())
  2504. // await plugin.initialize() // optional, this happens when loading a gltf file with extension anyway
  2505. const texture = await viewer.load('file.glb')
  2506. ```
  2507. ## SimplifyModifierPlugin
  2508. [Example](https://threepipe.org/examples/#simplify-modifier-plugin/) &mdash;
  2509. [Source Code](./src/plugins/extras/SimplifyModifierPlugin.ts) &mdash;
  2510. [API Reference](https://threepipe.org/docs/classes/SimplifyModifierPlugin.html)
  2511. Boilerplate for implementing a plugin for simplifying geometries.
  2512. This is a base class and cannot be used directly.
  2513. A sample to use it:
  2514. ```typescript
  2515. class SimplifyModifierPluginImpl extends SimplifyModifierPlugin {
  2516. protected _simplify(geometry: IGeometry, count: number) {
  2517. return new SimplifyModifier().modify(geometry, count) as IGeometry
  2518. }
  2519. }
  2520. const plugin = viewer.addPluginSync(new SimplifyModifierPluginImpl())
  2521. const root = await viewer.load('file.glb')
  2522. plugin.simplifyAll(root, {factor: 0.75})
  2523. ```
  2524. Check the [example](https://threepipe.org/examples/#simplify-modifier-plugin/) for full implementation.
  2525. ## MeshOptSimplifyModifierPlugin
  2526. [Example](https://threepipe.org/examples/#meshopt-simplify-modifier-plugin/) &mdash;
  2527. [Source Code](./src/plugins/extras/MeshOptSimplifyModifierPlugin.ts) &mdash;
  2528. [API Reference](https://threepipe.org/docs/classes/MeshOptSimplifyModifierPlugin.html)
  2529. Simplify modifier using [meshoptimizer](https://github.com/zeux/meshoptimizer) library. It Loads the library at runtime from a customisable CDN URL.
  2530. Note: It does not guarantee that the geometry will be simplified to the exact target count.
  2531. ```typescript
  2532. const simplifyModifier = viewer.addPluginSync(new MeshOptSimplifyModifierPlugin())
  2533. const root = await viewer.load('file.glb')
  2534. simplifyModifier.simplifyAll(root, {factor: 0.75})
  2535. ```
  2536. # @threepipe Packages
  2537. Additional plugins can be found in the [plugins](plugins/) directory.
  2538. These add support for integrating with other libraries, adding new features, and other functionality with different licenses.
  2539. ## @threepipe/plugin-tweakpane
  2540. [Tweakpane](https://tweakpane.github.io/docs/) UI plugin for ThreePipe
  2541. [//]: # (todo: image)
  2542. [Example](https://threepipe.org/examples/#tweakpane-ui-plugin/) &mdash;
  2543. [Source Code](./plugins/tweakpane/src/TweakpaneUiPlugin.ts) &mdash;
  2544. [API Reference](https://threepipe.org/plugins/tweakpane/docs/classes/TweakpaneUiPlugin.html)
  2545. NPM: `npm install @threepipe/plugin-tweakpane`
  2546. CDN: https://threepipe.org/plugins/tweakpane/dist/index.mjs
  2547. TweakpaneUiPlugin adds support for using [uiconfig-tweakpane](https://github.com/repalash/uiconfig-tweakpane)
  2548. to create a configuration UI in applications using the [Tweakpane](https://tweakpane.github.io/docs/) library.
  2549. The plugin takes the [uiconfig](https://github.com/repalash/uiconfig.js)
  2550. that's defined in the viewer and all the objects to automatically render a UI in the browser.
  2551. ```typescript
  2552. import {IObject3D, ThreeViewer, TonemapPlugin} from 'threepipe'
  2553. import {TweakpaneUiPlugin} from '@threepipe/plugin-tweakpane'
  2554. const viewer = new ThreeViewer({...})
  2555. // Add the plugin
  2556. const plugin = viewer.addPluginSync(new TweakpaneUiPlugin(true)) // true to show expanded the UI by default
  2557. // Add the UI for the viewer
  2558. plugin.appendChild(viewer.uiConfig)
  2559. // Add UI for some plugins
  2560. plugin.setupPlugins(TonemapPlugin, DropzonePlugin)
  2561. ```
  2562. ## @threepipe/plugin-blueprintjs
  2563. [Blueprint.js](https://blueprintjs.com/) UI plugin for ThreePipe
  2564. [//]: # (todo: image)
  2565. [Example](https://threepipe.org/examples/#blueprintjs-ui-plugin/) &mdash;
  2566. [Source Code](./plugins/blueprintjs/src/BlueprintJsUiPlugin.ts) &mdash;
  2567. [API Reference](https://threepipe.org/plugins/blueprintjs/docs/classes/BlueprintJsUiPlugin.html)
  2568. NPM: `npm install @threepipe/plugin-blueprintjs`
  2569. CDN: https://threepipe.org/plugins/blueprintjs/dist/index.mjs
  2570. BlueprintJsUiPlugin adds support for using [uiconfig-blueprint](https://github.com/repalash/uiconfig-blueprint)
  2571. to create a configuration UI in applications using the [BlueprintJs](https://blueprintjs.com/) library.
  2572. The plugin takes the [uiconfig](https://github.com/repalash/uiconfig.js)
  2573. that's defined in the viewer and all the objects to automatically render a UI in the browser.
  2574. ```typescript
  2575. import {IObject3D, ThreeViewer, TonemapPlugin} from 'threepipe'
  2576. import {BlueprintJsUiPlugin} from '@threepipe/plugin-blueprintjs'
  2577. const viewer = new ThreeViewer({...})
  2578. // Add the plugin
  2579. const plugin = viewer.addPluginSync(new BlueprintJsUiPlugin(true)) // true to show expanded the UI by default
  2580. // Add the UI for the viewer
  2581. plugin.appendChild(viewer.uiConfig)
  2582. // Add UI for some plugins
  2583. plugin.setupPlugins(TonemapPlugin, DropzonePlugin)
  2584. ```
  2585. ## @threepipe/plugin-tweakpane-editor
  2586. Tweakpane Editor Plugin for ThreePipe
  2587. [//]: # (todo: image)
  2588. [Example](https://threepipe.org/examples/#tweakpane-editor/) &mdash;
  2589. [Source Code](./plugins/tweakpane-editor/src/TweakpaneEditorPlugin.ts) &mdash;
  2590. [API Reference](https://threepipe.org/plugins/tweakpane-editor/docs/classes/TweakpaneEditorPlugin.html)
  2591. NPM: `npm install @threepipe/plugin-tweakpane-editor`
  2592. CDN: https://threepipe.org/plugins/tweakpane-editor/dist/index.mjs
  2593. TweakpaneEditorPlugin uses TweakpaneUiPlugin to create an editor for editing viewer,
  2594. plugins, model and material configurations in the browser.
  2595. ```typescript
  2596. import {IObject3D, ThreeViewer, TonemapPlugin} from 'threepipe'
  2597. import {TweakpaneEditorPlugin} from '@threepipe/plugin-tweakpane-editor'
  2598. const viewer = new ThreeViewer({...})
  2599. viewer.addPluginSync(new TweakpaneUiPlugin(true))
  2600. const editor = viewer.addPluginSync(new TweakpaneEditorPlugin())
  2601. // Add some plugins to the viewer
  2602. await viewer.addPlugins([
  2603. new ViewerUiConfigPlugin(),
  2604. // new SceneUiConfigPlugin(), // this is already in ViewerUiPlugin
  2605. new DepthBufferPlugin(HalfFloatType, true, true),
  2606. new NormalBufferPlugin(HalfFloatType, false),
  2607. new RenderTargetPreviewPlugin(false),
  2608. ])
  2609. // Load the plugin UI in the editor and tweakpane ui with categories.
  2610. editor.loadPlugins({
  2611. ['Viewer']: [ViewerUiConfigPlugin, SceneUiConfigPlugin, DropzonePlugin, FullScreenPlugin],
  2612. ['GBuffer']: [DepthBufferPlugin, NormalBufferPlugin],
  2613. ['Post-processing']: [TonemapPlugin],
  2614. ['Debug']: [RenderTargetPreviewPlugin],
  2615. })
  2616. ```
  2617. ## @threepipe/plugin-configurator
  2618. Configurator Plugin implementations with basic UI for Threepipe.
  2619. Includes Material Configurator and Switch Node Configurator Plugins.
  2620. NPM: `npm install @threepipe/plugin-configurator`
  2621. CDN: https://threepipe.org/plugins/dist/configurator/index.mjs
  2622. ### MaterialConfiguratorPlugin
  2623. [//]: # (todo: image)
  2624. [Example](https://threepipe.org/examples/#material-configurator-plugin/) &mdash;
  2625. [Source Code](./plugins/configurator/src/MaterialConfiguratorPlugin.ts) &mdash;
  2626. [API Reference](https://threepipe.org/plugins/configurator/docs/classes/MaterialConfiguratorPlugin.html)
  2627. MaterialConfiguratorPlugin adds a UI to configure and switch between different material variations.
  2628. The variations of materials are mapped to material names or uuids in the scene.
  2629. These variations can be applied to the materials in the scene. (This copies the properties to the same material instances instead of assigning new materials)
  2630. The plugin interfaces with the picking plugin and also provides uiConfig to show and edit the variations.
  2631. This functionality is inherited from [MaterialConfiguratorBasePlugin](https://threepipe.org/docs/classes/MaterialConfiguratorBasePlugin.html).
  2632. Additionally, this plugin adds a simple Grid UI in the DOM over the viewer canvas to show various material variations and allow the user to apply them.
  2633. The UI can also be used in the editor to edit the variations and apply them.
  2634. To use, simply add the plugin in the viewer and configure using the created UI and UI Config. Note that `PickingPlugin` is required to be added before this to allow configurator.
  2635. To create a custom configurator UI, use the `MaterialConfiguratorBasePlugin` directly and call the function `applyVariation`, `getPreview` and `addVariation` to apply and add variations respectively.
  2636. [//]: # (TODO Add Example for custom UI)
  2637. ### SwitchNodePlugin
  2638. [//]: # (todo: image)
  2639. [Example](https://threepipe.org/examples/#switch-node-plugin/) &mdash;
  2640. [Source Code](./plugins/configurator/src/SwitchNodePlugin.ts) &mdash;
  2641. [API Reference](https://threepipe.org/plugins/configurator/docs/classes/SwitchNodePlugin.html)
  2642. SwitchNodePlugin adds a UI to configure and switch between different different object variations within a switch node object.
  2643. This plugin allows you to configure object variations with object names in a file and apply them in the scene.
  2644. Each SwitchNode is a parent object with multiple direct children. Only one child is visible at a time.
  2645. This works by toggling the `visible` property of the children of a parent object.
  2646. The plugin interfaces with the picking plugin and also provides uiConfig to show and edit the variations.
  2647. It also provides a function to create snapshot previews of individual variations. This creates a limited render of the object with the selected child visible.
  2648. To get a proper render, its better to render it offline and set the image as a preview.
  2649. This functionality is inherited from [SwitchNodeBasePlugin](https://threepipe.org/docs/classes/SwitchNodeBasePlugin.html).
  2650. Additionally, this plugin adds a simple Grid UI in the DOM over the viewer canvas to show various material variations and allow the user to apply them.
  2651. The UI can also be used in the editor to edit the variations and apply them.
  2652. To use, simply add the plugin in the viewer and configure using the created UI and UI Config. Note that `PickingPlugin` is required to be added before this to allow configurator.
  2653. To create a custom configurator UI, use the `SwitchNodeBasePlugin` directly and call the function `selectNode`, `getPreview` and `addNode` to apply and add variations respectively.
  2654. [//]: # (TODO Add Example for custom UI)
  2655. ## @threepipe/plugin-network
  2656. Network/Cloud related plugin implementations for Threepipe.
  2657. Includes `AWSClientPlugin` and `TransfrSharePlugin`.
  2658. NPM: `npm install @threepipe/plugin-network`
  2659. CDN: https://threepipe.org/plugins/dist/network/index.mjs
  2660. ### TransfrSharePlugin
  2661. [//]: # (todo: image)
  2662. [Example](https://threepipe.org/examples/#transfr-share-plugin/) &mdash;
  2663. [Source Code](./plugins/network/src/TransfrSharePlugin.ts) &mdash;
  2664. [API Reference](https://threepipe.org/plugins/network/docs/classes/TransfrSharePlugin.html)
  2665. TransfrSharePlugin provides functionality to export and upload the scene or an object as glb and provide link to share/preview/edit the files.
  2666. It uses the options from the `AssetExporterPlugin` to export the scene or object, and can be configured using it's ui.
  2667. Uses the free service [transfr.one](https://transfr.one/) by default which deletes the files after a certain time, but the url can be changed to a custom backend or a self-hosted version of transfr.
  2668. Note: since the uploaded files are publicly accessible by anyone by default, it is recommended to encrypt the file using the exporter options or use a secure backend.
  2669. ```typescript
  2670. import {ThreeViewer} from 'threepipe'
  2671. import {TransfrSharePlugin} from '@threepipe/plugin-network'
  2672. const viewer = new ThreeViewer({...})
  2673. // Add the plugin
  2674. const sharePlugin = viewer.addPluginSync(new TransfrSharePlugin())
  2675. // when sharing, this query param is set to the model link
  2676. sharePlugin.queryParam = 'm' // this is the default
  2677. // used when clicking/calling Share page link
  2678. sharePlugin.pageUrl = window.location.href // this is the default
  2679. // used when clicking/calling Share viewer link
  2680. sharePlugin.baseUrls.viewer = 'https://threepipe.org/examples/model-viewer/index.html'
  2681. // used when clicking/calling Share editor link
  2682. sharePlugin.baseUrls.editor = 'https://threepipe.org/examples/tweakpane-editor/index.html'
  2683. // set to a custom server
  2684. // sharePlugin.serverUrl = 'https://example.com/'
  2685. // upload and get the link of the 3d model
  2686. const link = await sharePlugin.getLink()
  2687. // or upload and get the share link with a base page. And also copy to clipboard and shows a alert prompt(using viewer.dialog)
  2688. const link2 = await sharePlugin.shareLink('https://example.com/custom_viewer')
  2689. // or get the editor link directly
  2690. const link3 = await sharePlugin.shareEditorLink()
  2691. // to encrypt
  2692. const assetExporterPlugin = viewer.getPlugin(AssetExporterPlugin) // this is a dependency, so automatically added
  2693. assetExporterPlugin.encrypt = true
  2694. // assetExporterPlugin.encryptKey = 'password' // user will be prompted for password when exporting if this is commented
  2695. await sharePlugin.shareViewerLink()
  2696. ```
  2697. ### AWSClientPlugin
  2698. [//]: # (todo: image)
  2699. [Example](https://threepipe.org/examples/#aws-client-plugin/) &mdash;
  2700. [Source Code](./plugins/network/src/AWSClientPlugin.ts) &mdash;
  2701. [API Reference](https://threepipe.org/plugins/network/docs/classes/AWSClientPlugin.html)
  2702. Provides `fetch` function that performs a fetch request with AWS v4 signing.
  2703. This is useful for connecting to AWS services like S3 directly from the client.
  2704. It also interfaces with the `FileTransferPlugin` to directly upload file when exported with the viewer or the plugin.
  2705. Note: Make sure to use keys with limited privileges and correct CORS settings.
  2706. All the keys will be stored in plain text if `serializeSettings` is set to true
  2707. ```typescript
  2708. import {ThreeViewer} from 'threepipe'
  2709. import {AWSClientPlugin} from '@threepipe/plugin-network'
  2710. const viewer = new ThreeViewer({...})
  2711. const awsPlugin = viewer.addPluginSync(new AWSClientPlugin())
  2712. // set parameters and export. This can all be done from the UI also.
  2713. awsPlugin.accessKeyId = '00000000000000000000'
  2714. awsPlugin.accessKeySecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  2715. awsPlugin.endpointURL = 'https://s3.amazonaws.com/bucket/'
  2716. awsPlugin.pathPrefix = 'some/path/'
  2717. // or load a json file with the parameters
  2718. // the json file can be creating by entering the data in the UI and clicking the download preset json option.
  2719. await viewer.load('file.json')
  2720. // this will export the scene as glb
  2721. const blob = await viewer.exportScene()
  2722. // for a plugin config
  2723. // blob = await viewer.export(viewer.getPlugin(GroundPlugin))
  2724. // for a material
  2725. // blob = await viewer.export(object.material)
  2726. // for an object/mesh
  2727. // blob = await viewer.export(object, {exportExt: 'glb'})
  2728. // upload to s3. needs the parameters to be correct
  2729. await viewer.exportBlob(blob, 'filename.glb')
  2730. ```
  2731. Note: CORS should be enabled for the S3 bucket on the domain where the viewer is hosted. This requirement can be bypassed during development by setting `AWSClientPlugin.USE_PROXY = true`. A free proxy is already set by default and can be changed by setting `AWSClientPlugin.PROXY_URL`.
  2732. ## @threepipe/plugins-extra-importers
  2733. Exports several plugins to add support for various file types.
  2734. [Example](https://threepipe.org/examples/#extra-importer-plugins/) &mdash;
  2735. [Source Code](./plugins/extra-importers/src/index.ts) &mdash;
  2736. [API Reference](https://threepipe.org/plugins/extra-importers/docs)
  2737. NPM: `npm install @threepipe/plugins-extra-importers`
  2738. CDN: https://threepipe.org/plugins/extra-importers/dist/index.mjs
  2739. This package exports several plugins to add support for several file types using the following plugins
  2740. - [TDSLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/TDSLoadPlugin.html) - Load 3DS Max (.3ds) files
  2741. - [ThreeMFLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/ThreeMFLoadPlugin.html) - Load 3MF (.3mf) files
  2742. - [ColladaLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/ColladaLoadPlugin.html) - Load Collada (.dae) files
  2743. - [AMFLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/AMFLoadPlugin.html) - Load AMF (.amf) files
  2744. - [BVHLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/BVHLoadPlugin.html) - Load BVH (.bvh) files
  2745. - [VOXLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/VOXLoadPlugin.html) - Load MagicaVoxel (.vox) files
  2746. - [GCodeLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/GCodeLoadPlugin.html) - Load GCode (.gcode) files
  2747. - [MDDLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/MDDLoadPlugin.html) - Load MDD (.mdd) files
  2748. - [PCDLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/PCDLoadPlugin.html) - Load Point cloud data (.pcd) files
  2749. - [TiltLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/TiltLoadPlugin.html) - Load Tilt Brush (.tilt) files
  2750. - [VRMLLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/VRMLLoadPlugin.html) - Load VRML (.wrl) files
  2751. - [MPDLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/MPDLoadPlugin.html) - Load LDraw (.mpd) files
  2752. - [VTKLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/VTKLoadPlugin.html) - Load VTK (.vtk) files
  2753. - [XYZLoadPlugin](https://threepipe.org/plugins/extra-importers/docs/classes/XYZLoadPlugin.html) - Load XYZ (.xyz) files
  2754. To add all the plugins at once use `extraImporters`. This adds support for loading all the above file types.
  2755. ```typescript
  2756. import {ThreeViewer} from 'threepipe'
  2757. import {extraImporters} from '@threepipe/plugins-extra-importers'
  2758. const viewer = new ThreeViewer({...})
  2759. viewer.addPluginsSync(extraImporters)
  2760. // Now load any file as is.
  2761. const model = await viewer.load<IObject3D>('file.3mf')
  2762. // To load the file as a data url, use the correct mimetype
  2763. const model1 = await viewer.load<IObject3D>('data:model/3mf;base64,...')
  2764. ```
  2765. Remove the `<IObject3D>` if using javascript and not typescript.
  2766. ## @threepipe/plugin-blend-importer
  2767. Exports [BlendImporterPlugin](https://threepipe.org/plugins/blend-importer/docs/classes/BlendLoadPlugin.html) which adds support for loading .blend files.
  2768. It uses [js.blend](https://github.com/acweathersby/js.blend) for parsing blend file structure.
  2769. Note: This is still a WIP.
  2770. Currently working: `Mesh`, `BufferGeometry` and basic `PointLight`.
  2771. To be added: `PhysicalMaterial`, `UnlitMaterial` (similar to blender-gltf-io plugin)
  2772. [Example](https://threepipe.org/examples/#blend-load/) &mdash;
  2773. [Source Code](./plugins/blend-importer/src/index.ts) &mdash;
  2774. [API Reference](https://threepipe.org/plugins/blend-importer/docs)
  2775. NPM: `npm install @threepipe/plugin-blend-importer`
  2776. ```typescript
  2777. import {ThreeViewer} from 'threepipe'
  2778. import {BlendLoadPlugin} from '@threepipe/plugin-blend-importer'
  2779. const viewer = new ThreeViewer({...})
  2780. viewer.addPluginSync(BlendLoadPlugin)
  2781. // Now load any .blend file.
  2782. const model = await viewer.load<IObject3D>('path/to/file.blend')
  2783. // To load the file as a data url, use the correct mimetype
  2784. const model1 = await viewer.load<IObject3D>('data:application/x-blender;base64,...')
  2785. ```
  2786. [//]: # ( TODO: The plugin should parse and references to other assets and find them relative to the .blend file or the current location.)
  2787. ## @threepipe/plugin-geometry-generator
  2788. Exports [GeometryGeneratorPlugin](https://threepipe.org/plugins/geometry-generator/docs/classes/BlendLoadPlugin.html) with several Geometry generators to create parametric and updatable geometries like plane, circle, sphere, box, torus, cylinder, cone etc.
  2789. [Example](https://threepipe.org/examples/#geometry-generator-plugin/) &mdash;
  2790. [Source Code](./plugins/geometry-generator/src/index.ts) &mdash;
  2791. [API Reference](https://threepipe.org/plugins/geometry-generator/docs)
  2792. NPM: `npm install @threepipe/plugin-geometry-generator`
  2793. The generated geometries/meshes include the parameters in the userData and can be re-generated by changing the parameters from the UI or the plugin API.
  2794. Includes the following generator which inherit from [AGeometryGenerator](https://threepipe.org/plugins/geometry-generator/docs/classes/AGeometryGenerator.html):
  2795. - **plane**: [PlaneGeometryGenerator](https://threepipe.org/plugins/geometry-generator/docs/classes/PlaneGeometryGenerator),
  2796. - **sphere**: [SphereGeometryGenerator](https://threepipe.org/plugins/geometry-generator/docs/classes/SphereGeometryGenerator),
  2797. - **box**: [BoxGeometryGenerator](https://threepipe.org/plugins/geometry-generator/docs/classes/BoxGeometryGenerator),
  2798. - **circle**: [CircleGeometryGenerator](https://threepipe.org/plugins/geometry-generator/docs/classes/CircleGeometryGenerator),
  2799. - **torus**: [TorusGeometryGenerator](https://threepipe.org/plugins/geometry-generator/docs/classes/TorusGeometryGenerator),
  2800. - **cylinder**: [CylinderGeometryGenerator](https://threepipe.org/plugins/geometry-generator/docs/classes/CylinderGeometryGenerator),
  2801. Sample Usage:
  2802. ```typescript
  2803. import {ThreeViewer, UnlitMaterial} from 'threepipe'
  2804. import {GeometryGeneratorPlugin} from '@threepipe/plugin-geometry-generator'
  2805. const viewer = new ThreeViewer({...})
  2806. const generator = viewer.addPluginSync(GeometryGeneratorPlugin)
  2807. const sphere = generator.generateObject('sphere', {radius: 3})
  2808. viewer.scene.addObject(sphere)
  2809. // to update the geometry
  2810. generator.updateGeometry(sphere.geometry, {radius: 4, widthSegments: 100})
  2811. // to add a custom generator
  2812. generator.generators.custom = new CustomGenerator('custom') // Extend from AGeometryGenerator or implement GeometryGenerator interface
  2813. // refresh the ui so the new generator is available to select.
  2814. generator.uiConfig.uiRefresh?.()
  2815. // change the material type for all objects
  2816. generator.defaultMaterialClass = UnlitMaterial // by default its PhysicalMaterial
  2817. viewer.scene.addObject(generator.generateObject('box', {width: 2, height: 2, depth: 2}))
  2818. ```
  2819. ## @threepipe/plugin-gaussian-splatting
  2820. Exports [GaussianSplattingPlugin](https://threepipe.org/plugins/gaussian-splatting/docs/classes/GaussianSplattingPlugin.html) which adds support for loading .blend files.
  2821. It uses [`three-gaussian-splat`](./plugins/gaussian-splatting/src/three-gaussian-splat), a rewrite of [@zappar/three-guassian-splat](https://github.com/zappar-xr/three-gaussian-splat) (and [gsplat.js](https://github.com/huggingface/gsplat.js) and [antimatter15/splat](https://github.com/antimatter15/splat)) for loading splat files and rendering gaussian splats.
  2822. [Example](https://threepipe.org/examples/#splat-load/) &mdash;
  2823. [Source Code](./plugins/gaussian-splatting/src/index.ts) &mdash;
  2824. [API Reference](https://threepipe.org/plugins/gaussian-splatting/docs)
  2825. NPM: `npm install @threepipe/plugin-gaussian-splatting`
  2826. Note: This is still a WIP.
  2827. Currently working:
  2828. * Importing .splat files (just array buffer of gaussian splat attributes)
  2829. * ThreeGaussianSplatPlugin (Same as GaussianSplattingPlugin), add importer and update events to the viewer
  2830. * GaussianSplatMaterialExtension for adding gaussian splat functionality to any material like Unlit, Physical
  2831. * GaussianSplatMesh a subclass of Mesh2 for holding the gaussian splat geometry and a material with gaussian splat extension. also handles basic raycast in the splat geometry. (assuming simple points)
  2832. * GaussianSplatGeometry holds the geometry data and and the sort worker. Computes correct bounding box and sphere.
  2833. * SplatLoader for loading splat files and creating the geometry and material.
  2834. * GaussianSplatMaterialUnlit, GaussianSplatMaterialRaw
  2835. * GaussianSplatMaterialPhysical, working but normals are hardcoded to 0,1,0
  2836. TBD:
  2837. * Exporting/embedding splat files into glb
  2838. * Rendering to depth/gbuffer
  2839. * Estimate normals/read from file
  2840. * Lighting in GaussianSplatMaterialPhysical
  2841. ```typescript
  2842. import {ThreeViewer} from 'threepipe'
  2843. import {GaussianSplattingPlugin} from '@threepipe/plugin-gaussian-splatting'
  2844. const viewer = new ThreeViewer({...})
  2845. viewer.addPluginSync(GaussianSplattingPlugin)
  2846. // Now load any .splat file.
  2847. const model = await viewer.load<GaussianSplatMesh>('path/to/file.splat')
  2848. ```
  2849. ## @threepipe/plugin-svg-renderer
  2850. Exports [ThreeSVGRendererPlugin](https://threepipe.org/plugins/svg-renderer/docs/classes/ThreeSVGRendererPlugin.html) and [BasicSVGRendererPlugin](https://threepipe.org/plugins/svg-renderer/docs/classes/BasicSVGRendererPlugin.html) which provide support for rendering the 3d scene as [SVG(Scalable Vector Graphics)](https://developer.mozilla.org/en-US/docs/Web/SVG). The generated SVG is compatible with browser rendering and other software like figma, illustrator etc.
  2851. [Example](https://threepipe.org/examples/#three-svg-renderer/) &mdash;
  2852. [Source Code](./plugins/svg-renderer/src/index.ts) &mdash;
  2853. [API Reference](https://threepipe.org/plugins/svg-renderer/docs) &mdash;
  2854. [GPLV3 License](./plugins/svg-renderer/LICENSE)
  2855. NPM: `npm install @threepipe/plugin-svg-renderer`
  2856. Note: This is still a WIP. API might change slightly
  2857. `ThreeSVGRendererPlugin` uses [`three-svg-renderer`](./plugins/svg-renderer/src/three-svg-renderer), which is a modified version of [three-svg-renderer](https://www.npmjs.com/package/three-svg-renderer) (GPLV3 Licenced).
  2858. The plugin renderers meshes in the viewer scene to svg objects by computing polygons and contours of the geometry in view space. Check [LokiResearch/three-svg-renderer](https://github.com/LokiResearch/three-svg-renderer?tab=readme-ov-file#references) for more details.
  2859. In the modified version that is used here, support for some types of geometries is added and a rendered image in screen-space is used to create raster fill images for paths along with some other small changes. Check out the [Example](https://threepipe.org/examples/#three-svg-renderer/) for demo. See also [svg-geometry-playground example](https://threepipe.org/examples/#svg-geometry-playground/) for usage with other plugins `PickingPlugin`, `TransformControlsPlugin` and `GeometryGeneratorPlugin`.
  2860. Note that this does not support all the features of three.js and may not work with all types of materials and geometries. Check the examples for a list of sample models that do and don't work.
  2861. `BasicSVGRendererPlugin` is a sample plugin using [SVGRenderer](https://threejs.org/docs/index.html?q=svg#examples/en/renderers/SVGRenderer) from three.js addons. This renders all triangles in the scene to separate svg paths. Check the three.js docs for more details. Check out the [Example](https://threepipe.org/examples/#basic-svg-renderer/) for demo.
  2862. ```typescript
  2863. import {ThreeViewer} from 'threepipe'
  2864. import {ThreeSVGRendererPlugin} from '@threepipe/plugin-svg-renderer'
  2865. const viewer = new ThreeViewer({
  2866. ...,
  2867. rgbm: false, // this is required
  2868. })
  2869. const svgRender = viewer.addPluginSync(ThreeSVGRendererPlugin)
  2870. svgRender.autoRender = true // automatically render when camera or any object changes.
  2871. svgRender.autoMakeSvgObjects = true // automatically create SVG objects for all meshes in the scene.
  2872. // svgRender.makeSVGObject(object) // manually create SVG object for an object. (if autoMakeSvgObjects is false)
  2873. // Now load or generate any 3d model. Make sure its not very big. And the meshes are optimized.
  2874. const model = await viewer.load<IOBject3D>('path/to/file.glb')
  2875. // clear the background of the viewer
  2876. viewer.scene.backgroundColor = null
  2877. viewer.scene.background = null
  2878. // disable damping to get better experience.
  2879. viewer.scene.mainCamera.controls!.enableDamping = false
  2880. // hide the canvas to see the underlying svg node.
  2881. // note: do not set the display to none or remove the canvas as OrbitControls and other plugins might still be tracking the canvas.
  2882. viewer.canvas.style.opacity = '0'
  2883. // 3d pipeline can also be disabled like this if `drawImageFills` is `false` to get better performance. Do this only after loading the model.
  2884. // await viewer.doOnce('postFrame') // wait for the first frame to be rendered (for autoScale etc)
  2885. // viewer.renderManager.autoBuildPipeline = false
  2886. // viewer.renderManager.pipeline = [] // this will disable main viewer rendering
  2887. ```