Renderer.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930
  1. import Animation from './Animation.js';
  2. import RenderObjects from './RenderObjects.js';
  3. import Attributes from './Attributes.js';
  4. import Geometries from './Geometries.js';
  5. import Info from './Info.js';
  6. import Pipelines from './Pipelines.js';
  7. import Bindings from './Bindings.js';
  8. import RenderLists from './RenderLists.js';
  9. import RenderContexts from './RenderContexts.js';
  10. import Textures from './Textures.js';
  11. import Background from './Background.js';
  12. import Nodes from './nodes/Nodes.js';
  13. import Color4 from './Color4.js';
  14. import ClippingContext from './ClippingContext.js';
  15. import QuadMesh from './QuadMesh.js';
  16. import RenderBundles from './RenderBundles.js';
  17. import NodeLibrary from './nodes/NodeLibrary.js';
  18. import Lighting from './Lighting.js';
  19. import XRManager from './XRManager.js';
  20. import NodeMaterial from '../../materials/nodes/NodeMaterial.js';
  21. import { Scene } from '../../scenes/Scene.js';
  22. import { Frustum } from '../../math/Frustum.js';
  23. import { Matrix4 } from '../../math/Matrix4.js';
  24. import { Vector2 } from '../../math/Vector2.js';
  25. import { Vector4 } from '../../math/Vector4.js';
  26. import { RenderTarget } from '../../core/RenderTarget.js';
  27. import { DoubleSide, BackSide, FrontSide, SRGBColorSpace, NoToneMapping, LinearFilter, LinearSRGBColorSpace, HalfFloatType, RGBAFormat, PCFShadowMap } from '../../constants.js';
  28. const _scene = /*@__PURE__*/ new Scene();
  29. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  30. const _screen = /*@__PURE__*/ new Vector4();
  31. const _frustum = /*@__PURE__*/ new Frustum();
  32. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33. const _vector4 = /*@__PURE__*/ new Vector4();
  34. /**
  35. * Base class for renderers.
  36. */
  37. class Renderer {
  38. /**
  39. * Constructs a new renderer.
  40. *
  41. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  42. * @param {Object} parameters - The configuration parameter.
  43. * @param {boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  44. * @param {boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  45. * @param {boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46. * @param {boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  47. * @param {boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48. * @param {number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  49. * to overwrite the default.
  50. * @param {?Function} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  51. * @param {number} [parameters.colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  52. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  53. */
  54. constructor( backend, parameters = {} ) {
  55. /**
  56. * This flag can be used for type testing.
  57. *
  58. * @type {boolean}
  59. * @readonly
  60. * @default true
  61. */
  62. this.isRenderer = true;
  63. //
  64. const {
  65. logarithmicDepthBuffer = false,
  66. alpha = true,
  67. depth = true,
  68. stencil = false,
  69. antialias = false,
  70. samples = 0,
  71. getFallback = null,
  72. colorBufferType = HalfFloatType
  73. } = parameters;
  74. /**
  75. * A reference to the canvas element the renderer is drawing to.
  76. * This value of this property will automatically be created by
  77. * the renderer.
  78. *
  79. * @type {HTMLCanvasElement|OffscreenCanvas}
  80. */
  81. this.domElement = backend.getDomElement();
  82. /**
  83. * A reference to the current backend.
  84. *
  85. * @type {Backend}
  86. */
  87. this.backend = backend;
  88. /**
  89. * The number of MSAA samples.
  90. *
  91. * @type {number}
  92. * @default 0
  93. */
  94. this.samples = samples || ( antialias === true ) ? 4 : 0;
  95. /**
  96. * Whether the renderer should automatically clear the current rendering target
  97. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  98. * or the current bound render target (custom framebuffer).
  99. *
  100. * @type {boolean}
  101. * @default true
  102. */
  103. this.autoClear = true;
  104. /**
  105. * When `autoClear` is set to `true`, this property defines whether the renderer
  106. * should clear the color buffer.
  107. *
  108. * @type {boolean}
  109. * @default true
  110. */
  111. this.autoClearColor = true;
  112. /**
  113. * When `autoClear` is set to `true`, this property defines whether the renderer
  114. * should clear the depth buffer.
  115. *
  116. * @type {boolean}
  117. * @default true
  118. */
  119. this.autoClearDepth = true;
  120. /**
  121. * When `autoClear` is set to `true`, this property defines whether the renderer
  122. * should clear the stencil buffer.
  123. *
  124. * @type {boolean}
  125. * @default true
  126. */
  127. this.autoClearStencil = true;
  128. /**
  129. * Whether the default framebuffer should be transparent or opaque.
  130. *
  131. * @type {boolean}
  132. * @default true
  133. */
  134. this.alpha = alpha;
  135. /**
  136. * Whether logarithmic depth buffer is enabled or not.
  137. *
  138. * @type {boolean}
  139. * @default false
  140. */
  141. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  142. /**
  143. * Defines the output color space of the renderer.
  144. *
  145. * @type {string}
  146. * @default SRGBColorSpace
  147. */
  148. this.outputColorSpace = SRGBColorSpace;
  149. /**
  150. * Defines the tone mapping of the renderer.
  151. *
  152. * @type {number}
  153. * @default NoToneMapping
  154. */
  155. this.toneMapping = NoToneMapping;
  156. /**
  157. * Defines the tone mapping exposure.
  158. *
  159. * @type {number}
  160. * @default 1
  161. */
  162. this.toneMappingExposure = 1.0;
  163. /**
  164. * Whether the renderer should sort its render lists or not.
  165. *
  166. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  167. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  168. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  169. * e.g. manually determining each object's rendering order.
  170. *
  171. * @type {boolean}
  172. * @default true
  173. */
  174. this.sortObjects = true;
  175. /**
  176. * Whether the default framebuffer should have a depth buffer or not.
  177. *
  178. * @type {boolean}
  179. * @default true
  180. */
  181. this.depth = depth;
  182. /**
  183. * Whether the default framebuffer should have a stencil buffer or not.
  184. *
  185. * @type {boolean}
  186. * @default false
  187. */
  188. this.stencil = stencil;
  189. /**
  190. * Holds a series of statistical information about the GPU memory
  191. * and the rendering process. Useful for debugging and monitoring.
  192. *
  193. * @type {Info}
  194. */
  195. this.info = new Info();
  196. this.nodes = {
  197. modelViewMatrix: null,
  198. modelNormalViewMatrix: null
  199. };
  200. /**
  201. * The node library defines how certain library objects like materials, lights
  202. * or tone mapping functions are mapped to node types. This is required since
  203. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  204. * be part of the scene graph, they are internally represented as nodes for
  205. * further processing.
  206. *
  207. * @type {NodeLibrary}
  208. */
  209. this.library = new NodeLibrary();
  210. /**
  211. * A map-like data structure for managing lights.
  212. *
  213. * @type {Lighting}
  214. */
  215. this.lighting = new Lighting();
  216. // internals
  217. /**
  218. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  219. *
  220. * @private
  221. * @type {Function}
  222. */
  223. this._getFallback = getFallback;
  224. /**
  225. * The renderer's pixel ration.
  226. *
  227. * @private
  228. * @type {number}
  229. * @default 1
  230. */
  231. this._pixelRatio = 1;
  232. /**
  233. * The width of the renderer's default framebuffer in logical pixel unit.
  234. *
  235. * @private
  236. * @type {number}
  237. */
  238. this._width = this.domElement.width;
  239. /**
  240. * The height of the renderer's default framebuffer in logical pixel unit.
  241. *
  242. * @private
  243. * @type {number}
  244. */
  245. this._height = this.domElement.height;
  246. /**
  247. * The viewport of the renderer in logical pixel unit.
  248. *
  249. * @private
  250. * @type {Vector4}
  251. */
  252. this._viewport = new Vector4( 0, 0, this._width, this._height );
  253. /**
  254. * The scissor rectangle of the renderer in logical pixel unit.
  255. *
  256. * @private
  257. * @type {Vector4}
  258. */
  259. this._scissor = new Vector4( 0, 0, this._width, this._height );
  260. /**
  261. * Whether the scissor test should be enabled or not.
  262. *
  263. * @private
  264. * @type {boolean}
  265. */
  266. this._scissorTest = false;
  267. /**
  268. * A reference to a renderer module for managing shader attributes.
  269. *
  270. * @private
  271. * @type {?Attributes}
  272. * @default null
  273. */
  274. this._attributes = null;
  275. /**
  276. * A reference to a renderer module for managing geometries.
  277. *
  278. * @private
  279. * @type {?Geometries}
  280. * @default null
  281. */
  282. this._geometries = null;
  283. /**
  284. * A reference to a renderer module for managing node related logic.
  285. *
  286. * @private
  287. * @type {?Nodes}
  288. * @default null
  289. */
  290. this._nodes = null;
  291. /**
  292. * A reference to a renderer module for managing the internal animation loop.
  293. *
  294. * @private
  295. * @type {?Animation}
  296. * @default null
  297. */
  298. this._animation = null;
  299. /**
  300. * A reference to a renderer module for managing shader program bindings.
  301. *
  302. * @private
  303. * @type {?Bindings}
  304. * @default null
  305. */
  306. this._bindings = null;
  307. /**
  308. * A reference to a renderer module for managing render objects.
  309. *
  310. * @private
  311. * @type {?RenderObjects}
  312. * @default null
  313. */
  314. this._objects = null;
  315. /**
  316. * A reference to a renderer module for managing render and compute pipelines.
  317. *
  318. * @private
  319. * @type {?Pipelines}
  320. * @default null
  321. */
  322. this._pipelines = null;
  323. /**
  324. * A reference to a renderer module for managing render bundles.
  325. *
  326. * @private
  327. * @type {?RenderBundles}
  328. * @default null
  329. */
  330. this._bundles = null;
  331. /**
  332. * A reference to a renderer module for managing render lists.
  333. *
  334. * @private
  335. * @type {?RenderLists}
  336. * @default null
  337. */
  338. this._renderLists = null;
  339. /**
  340. * A reference to a renderer module for managing render contexts.
  341. *
  342. * @private
  343. * @type {?RenderContexts}
  344. * @default null
  345. */
  346. this._renderContexts = null;
  347. /**
  348. * A reference to a renderer module for managing textures.
  349. *
  350. * @private
  351. * @type {?Textures}
  352. * @default null
  353. */
  354. this._textures = null;
  355. /**
  356. * A reference to a renderer module for backgrounds.
  357. *
  358. * @private
  359. * @type {?Background}
  360. * @default null
  361. */
  362. this._background = null;
  363. /**
  364. * This fullscreen quad is used for internal render passes
  365. * like the tone mapping and color space output pass.
  366. *
  367. * @private
  368. * @type {QuadMesh}
  369. */
  370. this._quad = new QuadMesh( new NodeMaterial() );
  371. this._quad.material.name = 'Renderer_output';
  372. /**
  373. * A reference to the current render context.
  374. *
  375. * @private
  376. * @type {?RenderContext}
  377. * @default null
  378. */
  379. this._currentRenderContext = null;
  380. /**
  381. * A custom sort function for the opaque render list.
  382. *
  383. * @private
  384. * @type {?Function}
  385. * @default null
  386. */
  387. this._opaqueSort = null;
  388. /**
  389. * A custom sort function for the transparent render list.
  390. *
  391. * @private
  392. * @type {?Function}
  393. * @default null
  394. */
  395. this._transparentSort = null;
  396. /**
  397. * The framebuffer target.
  398. *
  399. * @private
  400. * @type {?RenderTarget}
  401. * @default null
  402. */
  403. this._frameBufferTarget = null;
  404. const alphaClear = this.alpha === true ? 0 : 1;
  405. /**
  406. * The clear color value.
  407. *
  408. * @private
  409. * @type {Color4}
  410. */
  411. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  412. /**
  413. * The clear depth value.
  414. *
  415. * @private
  416. * @type {number}
  417. * @default 1
  418. */
  419. this._clearDepth = 1;
  420. /**
  421. * The clear stencil value.
  422. *
  423. * @private
  424. * @type {number}
  425. * @default 0
  426. */
  427. this._clearStencil = 0;
  428. /**
  429. * The current render target.
  430. *
  431. * @private
  432. * @type {?RenderTarget}
  433. * @default null
  434. */
  435. this._renderTarget = null;
  436. /**
  437. * The active cube face.
  438. *
  439. * @private
  440. * @type {number}
  441. * @default 0
  442. */
  443. this._activeCubeFace = 0;
  444. /**
  445. * The active mipmap level.
  446. *
  447. * @private
  448. * @type {number}
  449. * @default 0
  450. */
  451. this._activeMipmapLevel = 0;
  452. /**
  453. * The current output render target.
  454. *
  455. * @private
  456. * @type {?RenderTarget}
  457. * @default null
  458. */
  459. this._outputRenderTarget = null;
  460. /**
  461. * The MRT setting.
  462. *
  463. * @private
  464. * @type {?MRTNode}
  465. * @default null
  466. */
  467. this._mrt = null;
  468. /**
  469. * This function defines how a render object is going
  470. * to be rendered.
  471. *
  472. * @private
  473. * @type {?Function}
  474. * @default null
  475. */
  476. this._renderObjectFunction = null;
  477. /**
  478. * Used to keep track of the current render object function.
  479. *
  480. * @private
  481. * @type {?Function}
  482. * @default null
  483. */
  484. this._currentRenderObjectFunction = null;
  485. /**
  486. * Used to keep track of the current render bundle.
  487. *
  488. * @private
  489. * @type {?RenderBundle}
  490. * @default null
  491. */
  492. this._currentRenderBundle = null;
  493. /**
  494. * Next to `_renderObjectFunction()`, this function provides another hook
  495. * for influencing the render process of a render object. It is meant for internal
  496. * use and only relevant for `compileAsync()` right now. Instead of using
  497. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  498. * a different function might be used which performs no draw but just the node
  499. * and pipeline updates.
  500. *
  501. * @private
  502. * @type {?Function}
  503. * @default null
  504. */
  505. this._handleObjectFunction = this._renderObjectDirect;
  506. /**
  507. * Indicates whether the device has been lost or not. In WebGL terms, the device
  508. * lost is considered as a context lost. When this is set to `true`, rendering
  509. * isn't possible anymore.
  510. *
  511. * @private
  512. * @type {boolean}
  513. * @default false
  514. */
  515. this._isDeviceLost = false;
  516. /**
  517. * A callback function that defines what should happen when a device/context lost occurs.
  518. *
  519. * @type {Function}
  520. */
  521. this.onDeviceLost = this._onDeviceLost;
  522. /**
  523. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  524. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  525. * This will reduce rendering quality though.
  526. *
  527. * @private
  528. * @type {number}
  529. * @default HalfFloatType
  530. */
  531. this._colorBufferType = colorBufferType;
  532. /**
  533. * Whether the renderer has been initialized or not.
  534. *
  535. * @private
  536. * @type {boolean}
  537. * @default false
  538. */
  539. this._initialized = false;
  540. /**
  541. * A reference to the promise which initializes the renderer.
  542. *
  543. * @private
  544. * @type {?Promise}
  545. * @default null
  546. */
  547. this._initPromise = null;
  548. /**
  549. * An array of compilation promises which are used in `compileAsync()`.
  550. *
  551. * @private
  552. * @type {?Array<Promise>}
  553. * @default null
  554. */
  555. this._compilationPromises = null;
  556. /**
  557. * Whether the renderer should render transparent render objects or not.
  558. *
  559. * @type {boolean}
  560. * @default true
  561. */
  562. this.transparent = true;
  563. /**
  564. * Whether the renderer should render opaque render objects or not.
  565. *
  566. * @type {boolean}
  567. * @default true
  568. */
  569. this.opaque = true;
  570. /**
  571. * Shadow map configuration
  572. * @typedef {Object} ShadowMapConfig
  573. * @property {boolean} enabled - Whether to globally enable shadows or not.
  574. * @property {number} type - The shadow map type.
  575. */
  576. /**
  577. * The renderer's shadow configuration.
  578. *
  579. * @type {ShadowMapConfig}
  580. */
  581. this.shadowMap = {
  582. enabled: false,
  583. type: PCFShadowMap
  584. };
  585. /**
  586. * XR configuration.
  587. * @typedef {Object} XRConfig
  588. * @property {boolean} enabled - Whether to globally enable XR or not.
  589. */
  590. /**
  591. * The renderer's XR manager.
  592. *
  593. * @type {XRManager}
  594. */
  595. this.xr = new XRManager( this );
  596. /**
  597. * Debug configuration.
  598. * @typedef {Object} DebugConfig
  599. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  600. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  601. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  602. */
  603. /**
  604. * The renderer's debug configuration.
  605. *
  606. * @type {DebugConfig}
  607. */
  608. this.debug = {
  609. checkShaderErrors: true,
  610. onShaderError: null,
  611. getShaderAsync: async ( scene, camera, object ) => {
  612. await this.compileAsync( scene, camera );
  613. const renderList = this._renderLists.get( scene, camera );
  614. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  615. const material = scene.overrideMaterial || object.material;
  616. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  617. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  618. return { fragmentShader, vertexShader };
  619. }
  620. };
  621. }
  622. /**
  623. * Initializes the renderer so it is ready for usage.
  624. *
  625. * @async
  626. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  627. */
  628. async init() {
  629. if ( this._initialized ) {
  630. throw new Error( 'Renderer: Backend has already been initialized.' );
  631. }
  632. if ( this._initPromise !== null ) {
  633. return this._initPromise;
  634. }
  635. this._initPromise = new Promise( async ( resolve, reject ) => {
  636. let backend = this.backend;
  637. try {
  638. await backend.init( this );
  639. } catch ( error ) {
  640. if ( this._getFallback !== null ) {
  641. // try the fallback
  642. try {
  643. this.backend = backend = this._getFallback( error );
  644. await backend.init( this );
  645. } catch ( error ) {
  646. reject( error );
  647. return;
  648. }
  649. } else {
  650. reject( error );
  651. return;
  652. }
  653. }
  654. this._nodes = new Nodes( this, backend );
  655. this._animation = new Animation( this._nodes, this.info );
  656. this._attributes = new Attributes( backend );
  657. this._background = new Background( this, this._nodes );
  658. this._geometries = new Geometries( this._attributes, this.info );
  659. this._textures = new Textures( this, backend, this.info );
  660. this._pipelines = new Pipelines( backend, this._nodes );
  661. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  662. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  663. this._renderLists = new RenderLists( this.lighting );
  664. this._bundles = new RenderBundles();
  665. this._renderContexts = new RenderContexts();
  666. //
  667. this._animation.start();
  668. this._initialized = true;
  669. resolve();
  670. } );
  671. return this._initPromise;
  672. }
  673. /**
  674. * The coordinate system of the renderer. The value of this property
  675. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  676. * `THREE.WebGPUCoordinateSystem`.
  677. *
  678. * @readonly
  679. * @type {number}
  680. */
  681. get coordinateSystem() {
  682. return this.backend.coordinateSystem;
  683. }
  684. /**
  685. * Compiles all materials in the given scene. This can be useful to avoid a
  686. * phenomenon which is called "shader compilation stutter", which occurs when
  687. * rendering an object with a new shader for the first time.
  688. *
  689. * If you want to add a 3D object to an existing scene, use the third optional
  690. * parameter for applying the target scene. Note that the (target) scene's lighting
  691. * and environment must be configured before calling this method.
  692. *
  693. * @async
  694. * @param {Object3D} scene - The scene or 3D object to precompile.
  695. * @param {Camera} camera - The camera that is used to render the scene.
  696. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  697. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  698. */
  699. async compileAsync( scene, camera, targetScene = null ) {
  700. if ( this._isDeviceLost === true ) return;
  701. if ( this._initialized === false ) await this.init();
  702. // preserve render tree
  703. const nodeFrame = this._nodes.nodeFrame;
  704. const previousRenderId = nodeFrame.renderId;
  705. const previousRenderContext = this._currentRenderContext;
  706. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  707. const previousCompilationPromises = this._compilationPromises;
  708. //
  709. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  710. if ( targetScene === null ) targetScene = scene;
  711. const renderTarget = this._renderTarget;
  712. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  713. const activeMipmapLevel = this._activeMipmapLevel;
  714. const compilationPromises = [];
  715. this._currentRenderContext = renderContext;
  716. this._currentRenderObjectFunction = this.renderObject;
  717. this._handleObjectFunction = this._createObjectPipeline;
  718. this._compilationPromises = compilationPromises;
  719. nodeFrame.renderId ++;
  720. //
  721. nodeFrame.update();
  722. //
  723. renderContext.depth = this.depth;
  724. renderContext.stencil = this.stencil;
  725. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  726. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  727. //
  728. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  729. //
  730. const renderList = this._renderLists.get( scene, camera );
  731. renderList.begin();
  732. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  733. // include lights from target scene
  734. if ( targetScene !== scene ) {
  735. targetScene.traverseVisible( function ( object ) {
  736. if ( object.isLight && object.layers.test( camera.layers ) ) {
  737. renderList.pushLight( object );
  738. }
  739. } );
  740. }
  741. renderList.finish();
  742. //
  743. if ( renderTarget !== null ) {
  744. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  745. const renderTargetData = this._textures.get( renderTarget );
  746. renderContext.textures = renderTargetData.textures;
  747. renderContext.depthTexture = renderTargetData.depthTexture;
  748. } else {
  749. renderContext.textures = null;
  750. renderContext.depthTexture = null;
  751. }
  752. //
  753. this._background.update( sceneRef, renderList, renderContext );
  754. // process render lists
  755. const opaqueObjects = renderList.opaque;
  756. const transparentObjects = renderList.transparent;
  757. const transparentDoublePassObjects = renderList.transparentDoublePass;
  758. const lightsNode = renderList.lightsNode;
  759. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  760. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  761. // restore render tree
  762. nodeFrame.renderId = previousRenderId;
  763. this._currentRenderContext = previousRenderContext;
  764. this._currentRenderObjectFunction = previousRenderObjectFunction;
  765. this._compilationPromises = previousCompilationPromises;
  766. this._handleObjectFunction = this._renderObjectDirect;
  767. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  768. await Promise.all( compilationPromises );
  769. }
  770. /**
  771. * Renders the scene in an async fashion.
  772. *
  773. * @async
  774. * @param {Object3D} scene - The scene or 3D object to render.
  775. * @param {Camera} camera - The camera.
  776. * @return {Promise} A Promise that resolves when the render has been finished.
  777. */
  778. async renderAsync( scene, camera ) {
  779. if ( this._initialized === false ) await this.init();
  780. this._renderScene( scene, camera );
  781. }
  782. /**
  783. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  784. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  785. *
  786. * @async
  787. * @return {Promise} A Promise that resolves when synchronization has been finished.
  788. */
  789. async waitForGPU() {
  790. await this.backend.waitForGPU();
  791. }
  792. /**
  793. * Sets the given MRT configuration.
  794. *
  795. * @param {MRTNode} mrt - The MRT node to set.
  796. * @return {Renderer} A reference to this renderer.
  797. */
  798. setMRT( mrt ) {
  799. this._mrt = mrt;
  800. return this;
  801. }
  802. /**
  803. * Returns the MRT configuration.
  804. *
  805. * @return {MRTNode} The MRT configuration.
  806. */
  807. getMRT() {
  808. return this._mrt;
  809. }
  810. /**
  811. * Returns the color buffer type.
  812. *
  813. * @return {number} The color buffer type.
  814. */
  815. getColorBufferType() {
  816. return this._colorBufferType;
  817. }
  818. /**
  819. * Default implementation of the device lost callback.
  820. *
  821. * @private
  822. * @param {Object} info - Information about the context lost.
  823. */
  824. _onDeviceLost( info ) {
  825. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  826. if ( info.reason ) {
  827. errorMessage += `\nReason: ${info.reason}`;
  828. }
  829. console.error( errorMessage );
  830. this._isDeviceLost = true;
  831. }
  832. /**
  833. * Renders the given render bundle.
  834. *
  835. * @private
  836. * @param {Object} bundle - Render bundle data.
  837. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  838. * @param {LightsNode} lightsNode - The current lights node.
  839. */
  840. _renderBundle( bundle, sceneRef, lightsNode ) {
  841. const { bundleGroup, camera, renderList } = bundle;
  842. const renderContext = this._currentRenderContext;
  843. //
  844. const renderBundle = this._bundles.get( bundleGroup, camera );
  845. const renderBundleData = this.backend.get( renderBundle );
  846. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  847. //
  848. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  849. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  850. renderBundleData.renderContexts.add( renderContext );
  851. if ( renderBundleNeedsUpdate ) {
  852. this.backend.beginBundle( renderContext );
  853. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  854. renderBundleData.renderObjects = [];
  855. }
  856. this._currentRenderBundle = renderBundle;
  857. const opaqueObjects = renderList.opaque;
  858. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  859. this._currentRenderBundle = null;
  860. //
  861. this.backend.finishBundle( renderContext, renderBundle );
  862. renderBundleData.version = bundleGroup.version;
  863. } else {
  864. const { renderObjects } = renderBundleData;
  865. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  866. const renderObject = renderObjects[ i ];
  867. if ( this._nodes.needsRefresh( renderObject ) ) {
  868. this._nodes.updateBefore( renderObject );
  869. this._nodes.updateForRender( renderObject );
  870. this._bindings.updateForRender( renderObject );
  871. this._nodes.updateAfter( renderObject );
  872. }
  873. }
  874. }
  875. this.backend.addBundle( renderContext, renderBundle );
  876. }
  877. /**
  878. * Renders the scene or 3D object with the given camera. This method can only be called
  879. * if the renderer has been initialized.
  880. *
  881. * The target of the method is the default framebuffer (meaning the canvas)
  882. * or alternatively a render target when specified via `setRenderTarget()`.
  883. *
  884. * @param {Object3D} scene - The scene or 3D object to render.
  885. * @param {Camera} camera - The camera to render the scene with.
  886. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  887. * Only returned when the renderer has not been initialized.
  888. */
  889. render( scene, camera ) {
  890. if ( this._initialized === false ) {
  891. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  892. return this.renderAsync( scene, camera );
  893. }
  894. this._renderScene( scene, camera );
  895. }
  896. /**
  897. * Returns an internal render target which is used when computing the output tone mapping
  898. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  899. * pass and not inline to achieve more correct results.
  900. *
  901. * @private
  902. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  903. */
  904. _getFrameBufferTarget() {
  905. const { currentToneMapping, currentColorSpace } = this;
  906. const useToneMapping = currentToneMapping !== NoToneMapping;
  907. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  908. if ( useToneMapping === false && useColorSpace === false ) return null;
  909. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  910. const { depth, stencil } = this;
  911. let frameBufferTarget = this._frameBufferTarget;
  912. if ( frameBufferTarget === null ) {
  913. frameBufferTarget = new RenderTarget( width, height, {
  914. depthBuffer: depth,
  915. stencilBuffer: stencil,
  916. type: this._colorBufferType,
  917. format: RGBAFormat,
  918. colorSpace: LinearSRGBColorSpace,
  919. generateMipmaps: false,
  920. minFilter: LinearFilter,
  921. magFilter: LinearFilter,
  922. samples: this.samples
  923. } );
  924. frameBufferTarget.isPostProcessingRenderTarget = true;
  925. this._frameBufferTarget = frameBufferTarget;
  926. }
  927. frameBufferTarget.depthBuffer = depth;
  928. frameBufferTarget.stencilBuffer = stencil;
  929. frameBufferTarget.setSize( width, height );
  930. frameBufferTarget.viewport.copy( this._viewport );
  931. frameBufferTarget.scissor.copy( this._scissor );
  932. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  933. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  934. frameBufferTarget.scissorTest = this._scissorTest;
  935. return frameBufferTarget;
  936. }
  937. /**
  938. * Renders the scene or 3D object with the given camera.
  939. *
  940. * @private
  941. * @param {Object3D} scene - The scene or 3D object to render.
  942. * @param {Camera} camera - The camera to render the scene with.
  943. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  944. * @return {RenderContext} The current render context.
  945. */
  946. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  947. if ( this._isDeviceLost === true ) return;
  948. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  949. // preserve render tree
  950. const nodeFrame = this._nodes.nodeFrame;
  951. const previousRenderId = nodeFrame.renderId;
  952. const previousRenderContext = this._currentRenderContext;
  953. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  954. //
  955. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  956. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  957. const activeCubeFace = this._activeCubeFace;
  958. const activeMipmapLevel = this._activeMipmapLevel;
  959. //
  960. let renderTarget;
  961. if ( frameBufferTarget !== null ) {
  962. renderTarget = frameBufferTarget;
  963. this.setRenderTarget( renderTarget );
  964. } else {
  965. renderTarget = outputRenderTarget;
  966. }
  967. //
  968. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  969. this._currentRenderContext = renderContext;
  970. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  971. //
  972. this.info.calls ++;
  973. this.info.render.calls ++;
  974. this.info.render.frameCalls ++;
  975. nodeFrame.renderId = this.info.calls;
  976. //
  977. const coordinateSystem = this.coordinateSystem;
  978. const xr = this.xr;
  979. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  980. camera.coordinateSystem = coordinateSystem;
  981. camera.updateProjectionMatrix();
  982. if ( camera.isArrayCamera ) {
  983. for ( const subCamera of camera.cameras ) {
  984. subCamera.coordinateSystem = coordinateSystem;
  985. subCamera.updateProjectionMatrix();
  986. }
  987. }
  988. }
  989. //
  990. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  991. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  992. if ( xr.enabled === true && xr.isPresenting === true ) {
  993. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  994. camera = xr.getCamera(); // use XR camera for rendering
  995. }
  996. //
  997. let viewport = this._viewport;
  998. let scissor = this._scissor;
  999. let pixelRatio = this._pixelRatio;
  1000. if ( renderTarget !== null ) {
  1001. viewport = renderTarget.viewport;
  1002. scissor = renderTarget.scissor;
  1003. pixelRatio = 1;
  1004. }
  1005. this.getDrawingBufferSize( _drawingBufferSize );
  1006. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  1007. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  1008. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  1009. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  1010. renderContext.viewportValue.width >>= activeMipmapLevel;
  1011. renderContext.viewportValue.height >>= activeMipmapLevel;
  1012. renderContext.viewportValue.minDepth = minDepth;
  1013. renderContext.viewportValue.maxDepth = maxDepth;
  1014. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  1015. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  1016. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  1017. renderContext.scissorValue.width >>= activeMipmapLevel;
  1018. renderContext.scissorValue.height >>= activeMipmapLevel;
  1019. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  1020. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  1021. //
  1022. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  1023. //
  1024. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  1025. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  1026. const renderList = this._renderLists.get( scene, camera );
  1027. renderList.begin();
  1028. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  1029. renderList.finish();
  1030. if ( this.sortObjects === true ) {
  1031. renderList.sort( this._opaqueSort, this._transparentSort );
  1032. }
  1033. //
  1034. if ( renderTarget !== null ) {
  1035. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  1036. const renderTargetData = this._textures.get( renderTarget );
  1037. renderContext.textures = renderTargetData.textures;
  1038. renderContext.depthTexture = renderTargetData.depthTexture;
  1039. renderContext.width = renderTargetData.width;
  1040. renderContext.height = renderTargetData.height;
  1041. renderContext.renderTarget = renderTarget;
  1042. renderContext.depth = renderTarget.depthBuffer;
  1043. renderContext.stencil = renderTarget.stencilBuffer;
  1044. } else {
  1045. renderContext.textures = null;
  1046. renderContext.depthTexture = null;
  1047. renderContext.width = this.domElement.width;
  1048. renderContext.height = this.domElement.height;
  1049. renderContext.depth = this.depth;
  1050. renderContext.stencil = this.stencil;
  1051. }
  1052. renderContext.width >>= activeMipmapLevel;
  1053. renderContext.height >>= activeMipmapLevel;
  1054. renderContext.activeCubeFace = activeCubeFace;
  1055. renderContext.activeMipmapLevel = activeMipmapLevel;
  1056. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  1057. //
  1058. this._background.update( sceneRef, renderList, renderContext );
  1059. //
  1060. this.backend.beginRender( renderContext );
  1061. // process render lists
  1062. const {
  1063. bundles,
  1064. lightsNode,
  1065. transparentDoublePass: transparentDoublePassObjects,
  1066. transparent: transparentObjects,
  1067. opaque: opaqueObjects
  1068. } = renderList;
  1069. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  1070. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  1071. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  1072. // finish render pass
  1073. this.backend.finishRender( renderContext );
  1074. // restore render tree
  1075. nodeFrame.renderId = previousRenderId;
  1076. this._currentRenderContext = previousRenderContext;
  1077. this._currentRenderObjectFunction = previousRenderObjectFunction;
  1078. //
  1079. if ( frameBufferTarget !== null ) {
  1080. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  1081. this._renderOutput( renderTarget );
  1082. }
  1083. //
  1084. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  1085. //
  1086. return renderContext;
  1087. }
  1088. /**
  1089. * The output pass performs tone mapping and color space conversion.
  1090. *
  1091. * @private
  1092. * @param {RenderTarget} renderTarget - The current render target.
  1093. */
  1094. _renderOutput( renderTarget ) {
  1095. const quad = this._quad;
  1096. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  1097. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  1098. quad.material.needsUpdate = true;
  1099. }
  1100. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  1101. const currentAutoClear = this.autoClear;
  1102. const currentXR = this.xr.enabled;
  1103. this.autoClear = false;
  1104. this.xr.enabled = false;
  1105. this._renderScene( quad, quad.camera, false );
  1106. this.autoClear = currentAutoClear;
  1107. this.xr.enabled = currentXR;
  1108. }
  1109. /**
  1110. * Returns the maximum available anisotropy for texture filtering.
  1111. *
  1112. * @return {number} The maximum available anisotropy.
  1113. */
  1114. getMaxAnisotropy() {
  1115. return this.backend.getMaxAnisotropy();
  1116. }
  1117. /**
  1118. * Returns the active cube face.
  1119. *
  1120. * @return {number} The active cube face.
  1121. */
  1122. getActiveCubeFace() {
  1123. return this._activeCubeFace;
  1124. }
  1125. /**
  1126. * Returns the active mipmap level.
  1127. *
  1128. * @return {number} The active mipmap level.
  1129. */
  1130. getActiveMipmapLevel() {
  1131. return this._activeMipmapLevel;
  1132. }
  1133. /**
  1134. * Applications are advised to always define the animation loop
  1135. * with this method and not manually with `requestAnimationFrame()`
  1136. * for best compatibility.
  1137. *
  1138. * @async
  1139. * @param {Function} callback - The application's animation loop.
  1140. * @return {Promise} A Promise that resolves when the set has been executed.
  1141. */
  1142. async setAnimationLoop( callback ) {
  1143. if ( this._initialized === false ) await this.init();
  1144. this._animation.setAnimationLoop( callback );
  1145. }
  1146. /**
  1147. * Can be used to transfer buffer data from a storage buffer attribute
  1148. * from the GPU to the CPU in context of compute shaders.
  1149. *
  1150. * @async
  1151. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  1152. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  1153. */
  1154. async getArrayBufferAsync( attribute ) {
  1155. return await this.backend.getArrayBufferAsync( attribute );
  1156. }
  1157. /**
  1158. * Returns the rendering context.
  1159. *
  1160. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  1161. */
  1162. getContext() {
  1163. return this.backend.getContext();
  1164. }
  1165. /**
  1166. * Returns the pixel ratio.
  1167. *
  1168. * @return {number} The pixel ratio.
  1169. */
  1170. getPixelRatio() {
  1171. return this._pixelRatio;
  1172. }
  1173. /**
  1174. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  1175. *
  1176. * @param {Vector2} target - The method writes the result in this target object.
  1177. * @return {Vector2} The drawing buffer size.
  1178. */
  1179. getDrawingBufferSize( target ) {
  1180. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  1181. }
  1182. /**
  1183. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  1184. *
  1185. * @param {Vector2} target - The method writes the result in this target object.
  1186. * @return {Vector2} The drawing buffer size.
  1187. */
  1188. getSize( target ) {
  1189. return target.set( this._width, this._height );
  1190. }
  1191. /**
  1192. * Sets the given pixel ration and resizes the canvas if necessary.
  1193. *
  1194. * @param {number} [value=1] - The pixel ratio.
  1195. */
  1196. setPixelRatio( value = 1 ) {
  1197. if ( this._pixelRatio === value ) return;
  1198. this._pixelRatio = value;
  1199. this.setSize( this._width, this._height, false );
  1200. }
  1201. /**
  1202. * This method allows to define the drawing buffer size by specifying
  1203. * width, height and pixel ratio all at once. The size of the drawing
  1204. * buffer is computed with this formula:
  1205. * ````
  1206. * size.x = width * pixelRatio;
  1207. * size.y = height * pixelRatio;
  1208. *```
  1209. *
  1210. * @param {number} width - The width in logical pixels.
  1211. * @param {number} height - The height in logical pixels.
  1212. * @param {number} pixelRatio - The pixel ratio.
  1213. */
  1214. setDrawingBufferSize( width, height, pixelRatio ) {
  1215. this._width = width;
  1216. this._height = height;
  1217. this._pixelRatio = pixelRatio;
  1218. this.domElement.width = Math.floor( width * pixelRatio );
  1219. this.domElement.height = Math.floor( height * pixelRatio );
  1220. this.setViewport( 0, 0, width, height );
  1221. if ( this._initialized ) this.backend.updateSize();
  1222. }
  1223. /**
  1224. * Sets the size of the renderer.
  1225. *
  1226. * @param {number} width - The width in logical pixels.
  1227. * @param {number} height - The height in logical pixels.
  1228. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  1229. */
  1230. setSize( width, height, updateStyle = true ) {
  1231. this._width = width;
  1232. this._height = height;
  1233. this.domElement.width = Math.floor( width * this._pixelRatio );
  1234. this.domElement.height = Math.floor( height * this._pixelRatio );
  1235. if ( updateStyle === true ) {
  1236. this.domElement.style.width = width + 'px';
  1237. this.domElement.style.height = height + 'px';
  1238. }
  1239. this.setViewport( 0, 0, width, height );
  1240. if ( this._initialized ) this.backend.updateSize();
  1241. }
  1242. /**
  1243. * Defines a manual sort function for the opaque render list.
  1244. * Pass `null` to use the default sort.
  1245. *
  1246. * @param {Function} method - The sort function.
  1247. */
  1248. setOpaqueSort( method ) {
  1249. this._opaqueSort = method;
  1250. }
  1251. /**
  1252. * Defines a manual sort function for the transparent render list.
  1253. * Pass `null` to use the default sort.
  1254. *
  1255. * @param {Function} method - The sort function.
  1256. */
  1257. setTransparentSort( method ) {
  1258. this._transparentSort = method;
  1259. }
  1260. /**
  1261. * Returns the scissor rectangle.
  1262. *
  1263. * @param {Vector4} target - The method writes the result in this target object.
  1264. * @return {Vector4} The scissor rectangle.
  1265. */
  1266. getScissor( target ) {
  1267. const scissor = this._scissor;
  1268. target.x = scissor.x;
  1269. target.y = scissor.y;
  1270. target.width = scissor.width;
  1271. target.height = scissor.height;
  1272. return target;
  1273. }
  1274. /**
  1275. * Defines the scissor rectangle.
  1276. *
  1277. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  1278. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  1279. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  1280. * @param {number} width - The width of the scissor box in logical pixel unit.
  1281. * @param {number} height - The height of the scissor box in logical pixel unit.
  1282. */
  1283. setScissor( x, y, width, height ) {
  1284. const scissor = this._scissor;
  1285. if ( x.isVector4 ) {
  1286. scissor.copy( x );
  1287. } else {
  1288. scissor.set( x, y, width, height );
  1289. }
  1290. }
  1291. /**
  1292. * Returns the scissor test value.
  1293. *
  1294. * @return {boolean} Whether the scissor test should be enabled or not.
  1295. */
  1296. getScissorTest() {
  1297. return this._scissorTest;
  1298. }
  1299. /**
  1300. * Defines the scissor test.
  1301. *
  1302. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  1303. */
  1304. setScissorTest( boolean ) {
  1305. this._scissorTest = boolean;
  1306. this.backend.setScissorTest( boolean );
  1307. }
  1308. /**
  1309. * Returns the viewport definition.
  1310. *
  1311. * @param {Vector4} target - The method writes the result in this target object.
  1312. * @return {Vector4} The viewport definition.
  1313. */
  1314. getViewport( target ) {
  1315. return target.copy( this._viewport );
  1316. }
  1317. /**
  1318. * Defines the viewport.
  1319. *
  1320. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  1321. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  1322. * @param {number} width - The width of the viewport in logical pixel unit.
  1323. * @param {number} height - The height of the viewport in logical pixel unit.
  1324. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  1325. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  1326. */
  1327. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  1328. const viewport = this._viewport;
  1329. if ( x.isVector4 ) {
  1330. viewport.copy( x );
  1331. } else {
  1332. viewport.set( x, y, width, height );
  1333. }
  1334. viewport.minDepth = minDepth;
  1335. viewport.maxDepth = maxDepth;
  1336. }
  1337. /**
  1338. * Returns the clear color.
  1339. *
  1340. * @param {Color} target - The method writes the result in this target object.
  1341. * @return {Color} The clear color.
  1342. */
  1343. getClearColor( target ) {
  1344. return target.copy( this._clearColor );
  1345. }
  1346. /**
  1347. * Defines the clear color and optionally the clear alpha.
  1348. *
  1349. * @param {Color} color - The clear color.
  1350. * @param {number} [alpha=1] - The clear alpha.
  1351. */
  1352. setClearColor( color, alpha = 1 ) {
  1353. this._clearColor.set( color );
  1354. this._clearColor.a = alpha;
  1355. }
  1356. /**
  1357. * Returns the clear alpha.
  1358. *
  1359. * @return {number} The clear alpha.
  1360. */
  1361. getClearAlpha() {
  1362. return this._clearColor.a;
  1363. }
  1364. /**
  1365. * Defines the clear alpha.
  1366. *
  1367. * @param {number} alpha - The clear alpha.
  1368. */
  1369. setClearAlpha( alpha ) {
  1370. this._clearColor.a = alpha;
  1371. }
  1372. /**
  1373. * Returns the clear depth.
  1374. *
  1375. * @return {number} The clear depth.
  1376. */
  1377. getClearDepth() {
  1378. return this._clearDepth;
  1379. }
  1380. /**
  1381. * Defines the clear depth.
  1382. *
  1383. * @param {number} depth - The clear depth.
  1384. */
  1385. setClearDepth( depth ) {
  1386. this._clearDepth = depth;
  1387. }
  1388. /**
  1389. * Returns the clear stencil.
  1390. *
  1391. * @return {number} The clear stencil.
  1392. */
  1393. getClearStencil() {
  1394. return this._clearStencil;
  1395. }
  1396. /**
  1397. * Defines the clear stencil.
  1398. *
  1399. * @param {number} stencil - The clear stencil.
  1400. */
  1401. setClearStencil( stencil ) {
  1402. this._clearStencil = stencil;
  1403. }
  1404. /**
  1405. * This method performs an occlusion query for the given 3D object.
  1406. * It returns `true` if the given 3D object is fully occluded by other
  1407. * 3D objects in the scene.
  1408. *
  1409. * @param {Object3D} object - The 3D object to test.
  1410. * @return {boolean} Whether the 3D object is fully occluded or not.
  1411. */
  1412. isOccluded( object ) {
  1413. const renderContext = this._currentRenderContext;
  1414. return renderContext && this.backend.isOccluded( renderContext, object );
  1415. }
  1416. /**
  1417. * Performs a manual clear operation. This method ignores `autoClear` properties.
  1418. *
  1419. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  1420. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  1421. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  1422. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  1423. * Only returned when the renderer has not been initialized.
  1424. */
  1425. clear( color = true, depth = true, stencil = true ) {
  1426. if ( this._initialized === false ) {
  1427. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  1428. return this.clearAsync( color, depth, stencil );
  1429. }
  1430. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  1431. let renderContext = null;
  1432. if ( renderTarget !== null ) {
  1433. this._textures.updateRenderTarget( renderTarget );
  1434. const renderTargetData = this._textures.get( renderTarget );
  1435. renderContext = this._renderContexts.getForClear( renderTarget );
  1436. renderContext.textures = renderTargetData.textures;
  1437. renderContext.depthTexture = renderTargetData.depthTexture;
  1438. renderContext.width = renderTargetData.width;
  1439. renderContext.height = renderTargetData.height;
  1440. renderContext.renderTarget = renderTarget;
  1441. renderContext.depth = renderTarget.depthBuffer;
  1442. renderContext.stencil = renderTarget.stencilBuffer;
  1443. // #30329
  1444. renderContext.clearColorValue = this.backend.getClearColor();
  1445. }
  1446. this.backend.clear( color, depth, stencil, renderContext );
  1447. if ( renderTarget !== null && this._renderTarget === null ) {
  1448. this._renderOutput( renderTarget );
  1449. }
  1450. }
  1451. /**
  1452. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  1453. *
  1454. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  1455. * Only returned when the renderer has not been initialized.
  1456. */
  1457. clearColor() {
  1458. return this.clear( true, false, false );
  1459. }
  1460. /**
  1461. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  1462. *
  1463. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  1464. * Only returned when the renderer has not been initialized.
  1465. */
  1466. clearDepth() {
  1467. return this.clear( false, true, false );
  1468. }
  1469. /**
  1470. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  1471. *
  1472. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  1473. * Only returned when the renderer has not been initialized.
  1474. */
  1475. clearStencil() {
  1476. return this.clear( false, false, true );
  1477. }
  1478. /**
  1479. * Async version of {@link Renderer#clear}.
  1480. *
  1481. * @async
  1482. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  1483. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  1484. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  1485. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  1486. */
  1487. async clearAsync( color = true, depth = true, stencil = true ) {
  1488. if ( this._initialized === false ) await this.init();
  1489. this.clear( color, depth, stencil );
  1490. }
  1491. /**
  1492. * Async version of {@link Renderer#clearColor}.
  1493. *
  1494. * @async
  1495. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  1496. */
  1497. async clearColorAsync() {
  1498. this.clearAsync( true, false, false );
  1499. }
  1500. /**
  1501. * Async version of {@link Renderer#clearDepth}.
  1502. *
  1503. * @async
  1504. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  1505. */
  1506. async clearDepthAsync() {
  1507. this.clearAsync( false, true, false );
  1508. }
  1509. /**
  1510. * Async version of {@link Renderer#clearStencil}.
  1511. *
  1512. * @async
  1513. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  1514. */
  1515. async clearStencilAsync() {
  1516. this.clearAsync( false, false, true );
  1517. }
  1518. /**
  1519. * The current output tone mapping of the renderer. When a render target is set,
  1520. * the output tone mapping is always `NoToneMapping`.
  1521. *
  1522. * @type {number}
  1523. */
  1524. get currentToneMapping() {
  1525. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  1526. }
  1527. /**
  1528. * The current output color space of the renderer. When a render target is set,
  1529. * the output color space is always `LinearSRGBColorSpace`.
  1530. *
  1531. * @type {string}
  1532. */
  1533. get currentColorSpace() {
  1534. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  1535. }
  1536. /**
  1537. * Returns `true` if the rendering settings are set to screen output.
  1538. *
  1539. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  1540. */
  1541. get isOutputTarget() {
  1542. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  1543. }
  1544. /**
  1545. * Frees all internal resources of the renderer. Call this method if the renderer
  1546. * is no longer in use by your app.
  1547. */
  1548. dispose() {
  1549. this.info.dispose();
  1550. this.backend.dispose();
  1551. this._animation.dispose();
  1552. this._objects.dispose();
  1553. this._pipelines.dispose();
  1554. this._nodes.dispose();
  1555. this._bindings.dispose();
  1556. this._renderLists.dispose();
  1557. this._renderContexts.dispose();
  1558. this._textures.dispose();
  1559. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  1560. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  1561. if ( queryPool !== null ) queryPool.dispose();
  1562. } );
  1563. this.setRenderTarget( null );
  1564. this.setAnimationLoop( null );
  1565. }
  1566. /**
  1567. * Sets the given render target. Calling this method means the renderer does not
  1568. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  1569. * Use `null` as the first argument to reset the state.
  1570. *
  1571. * @param {?RenderTarget} renderTarget - The render target to set.
  1572. * @param {number} [activeCubeFace=0] - The active cube face.
  1573. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  1574. */
  1575. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  1576. this._renderTarget = renderTarget;
  1577. this._activeCubeFace = activeCubeFace;
  1578. this._activeMipmapLevel = activeMipmapLevel;
  1579. }
  1580. /**
  1581. * Returns the current render target.
  1582. *
  1583. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  1584. */
  1585. getRenderTarget() {
  1586. return this._renderTarget;
  1587. }
  1588. /**
  1589. * Sets the output render target for the renderer.
  1590. *
  1591. * @param {Object} renderTarget - The render target to set as the output target.
  1592. */
  1593. setOutputRenderTarget( renderTarget ) {
  1594. this._outputRenderTarget = renderTarget;
  1595. }
  1596. /**
  1597. * Returns the current output target.
  1598. *
  1599. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  1600. */
  1601. getOutputRenderTarget() {
  1602. return this._outputRenderTarget;
  1603. }
  1604. /**
  1605. * Callback for {@link Renderer#setRenderObjectFunction}.
  1606. *
  1607. * @callback renderObjectFunction
  1608. * @param {Object3D} object - The 3D object.
  1609. * @param {Scene} scene - The scene the 3D object belongs to.
  1610. * @param {Camera} camera - The camera the object should be rendered with.
  1611. * @param {BufferGeometry} geometry - The object's geometry.
  1612. * @param {Material} material - The object's material.
  1613. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  1614. * @param {LightsNode} lightsNode - The current lights node.
  1615. * @param {ClippingContext} clippingContext - The clipping context.
  1616. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  1617. */
  1618. /**
  1619. * Sets the given render object function. Calling this method overwrites the default implementation
  1620. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  1621. * if you want to modify the way objects are rendered. For example you can define things like "every
  1622. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  1623. * The custom function must always call `renderObject()` in its implementation.
  1624. *
  1625. * Use `null` as the first argument to reset the state.
  1626. *
  1627. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  1628. */
  1629. setRenderObjectFunction( renderObjectFunction ) {
  1630. this._renderObjectFunction = renderObjectFunction;
  1631. }
  1632. /**
  1633. * Returns the current render object function.
  1634. *
  1635. * @return {?Function} The current render object function. Returns `null` if no function is set.
  1636. */
  1637. getRenderObjectFunction() {
  1638. return this._renderObjectFunction;
  1639. }
  1640. /**
  1641. * Execute a single or an array of compute nodes. This method can only be called
  1642. * if the renderer has been initialized.
  1643. *
  1644. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  1645. * @return {?Promise} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  1646. */
  1647. compute( computeNodes ) {
  1648. if ( this._isDeviceLost === true ) return;
  1649. if ( this._initialized === false ) {
  1650. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  1651. return this.computeAsync( computeNodes );
  1652. }
  1653. //
  1654. const nodeFrame = this._nodes.nodeFrame;
  1655. const previousRenderId = nodeFrame.renderId;
  1656. //
  1657. this.info.calls ++;
  1658. this.info.compute.calls ++;
  1659. this.info.compute.frameCalls ++;
  1660. nodeFrame.renderId = this.info.calls;
  1661. //
  1662. const backend = this.backend;
  1663. const pipelines = this._pipelines;
  1664. const bindings = this._bindings;
  1665. const nodes = this._nodes;
  1666. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  1667. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  1668. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  1669. }
  1670. backend.beginCompute( computeNodes );
  1671. for ( const computeNode of computeList ) {
  1672. // onInit
  1673. if ( pipelines.has( computeNode ) === false ) {
  1674. const dispose = () => {
  1675. computeNode.removeEventListener( 'dispose', dispose );
  1676. pipelines.delete( computeNode );
  1677. bindings.delete( computeNode );
  1678. nodes.delete( computeNode );
  1679. };
  1680. computeNode.addEventListener( 'dispose', dispose );
  1681. //
  1682. const onInitFn = computeNode.onInitFunction;
  1683. if ( onInitFn !== null ) {
  1684. onInitFn.call( computeNode, { renderer: this } );
  1685. }
  1686. }
  1687. nodes.updateForCompute( computeNode );
  1688. bindings.updateForCompute( computeNode );
  1689. const computeBindings = bindings.getForCompute( computeNode );
  1690. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  1691. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  1692. }
  1693. backend.finishCompute( computeNodes );
  1694. //
  1695. nodeFrame.renderId = previousRenderId;
  1696. }
  1697. /**
  1698. * Execute a single or an array of compute nodes.
  1699. *
  1700. * @async
  1701. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  1702. * @return {Promise} A Promise that resolve when the compute has finished.
  1703. */
  1704. async computeAsync( computeNodes ) {
  1705. if ( this._initialized === false ) await this.init();
  1706. this.compute( computeNodes );
  1707. }
  1708. /**
  1709. * Checks if the given feature is supported by the selected backend.
  1710. *
  1711. * @async
  1712. * @param {string} name - The feature's name.
  1713. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  1714. */
  1715. async hasFeatureAsync( name ) {
  1716. if ( this._initialized === false ) await this.init();
  1717. return this.backend.hasFeature( name );
  1718. }
  1719. async resolveTimestampsAsync( type = 'render' ) {
  1720. if ( this._initialized === false ) await this.init();
  1721. return this.backend.resolveTimestampsAsync( type );
  1722. }
  1723. /**
  1724. * Checks if the given feature is supported by the selected backend. If the
  1725. * renderer has not been initialized, this method always returns `false`.
  1726. *
  1727. * @param {string} name - The feature's name.
  1728. * @return {boolean} Whether the feature is supported or not.
  1729. */
  1730. hasFeature( name ) {
  1731. if ( this._initialized === false ) {
  1732. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  1733. return false;
  1734. }
  1735. return this.backend.hasFeature( name );
  1736. }
  1737. /**
  1738. * Returns `true` when the renderer has been initialized.
  1739. *
  1740. * @return {boolean} Whether the renderer has been initialized or not.
  1741. */
  1742. hasInitialized() {
  1743. return this._initialized;
  1744. }
  1745. /**
  1746. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  1747. * (which can cause noticeable lags due to decode and GPU upload overhead).
  1748. *
  1749. * @async
  1750. * @param {Texture} texture - The texture.
  1751. * @return {Promise} A Promise that resolves when the texture has been initialized.
  1752. */
  1753. async initTextureAsync( texture ) {
  1754. if ( this._initialized === false ) await this.init();
  1755. this._textures.updateTexture( texture );
  1756. }
  1757. /**
  1758. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  1759. * (which can cause noticeable lags due to decode and GPU upload overhead).
  1760. *
  1761. * This method can only be used if the renderer has been initialized.
  1762. *
  1763. * @param {Texture} texture - The texture.
  1764. */
  1765. initTexture( texture ) {
  1766. if ( this._initialized === false ) {
  1767. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  1768. }
  1769. this._textures.updateTexture( texture );
  1770. }
  1771. /**
  1772. * Copies the current bound framebuffer into the given texture.
  1773. *
  1774. * @param {FramebufferTexture} framebufferTexture - The texture.
  1775. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  1776. */
  1777. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  1778. if ( rectangle !== null ) {
  1779. if ( rectangle.isVector2 ) {
  1780. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  1781. } else if ( rectangle.isVector4 ) {
  1782. rectangle = _vector4.copy( rectangle ).floor();
  1783. } else {
  1784. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  1785. return;
  1786. }
  1787. } else {
  1788. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  1789. }
  1790. //
  1791. let renderContext = this._currentRenderContext;
  1792. let renderTarget;
  1793. if ( renderContext !== null ) {
  1794. renderTarget = renderContext.renderTarget;
  1795. } else {
  1796. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  1797. if ( renderTarget !== null ) {
  1798. this._textures.updateRenderTarget( renderTarget );
  1799. renderContext = this._textures.get( renderTarget );
  1800. }
  1801. }
  1802. //
  1803. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  1804. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  1805. }
  1806. /**
  1807. * Copies data of source texture into a destination texture.
  1808. *
  1809. * @param {Texture} srcTexture - The source texture.
  1810. * @param {Texture} dstTexture - The destination texture.
  1811. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  1812. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  1813. * @param {number} level - The mipmap level to copy.
  1814. */
  1815. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  1816. this._textures.updateTexture( srcTexture );
  1817. this._textures.updateTexture( dstTexture );
  1818. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  1819. }
  1820. /**
  1821. * Reads pixel data from the given render target.
  1822. *
  1823. * @async
  1824. * @param {RenderTarget} renderTarget - The render target to read from.
  1825. * @param {number} x - The `x` coordinate of the copy region's origin.
  1826. * @param {number} y - The `y` coordinate of the copy region's origin.
  1827. * @param {number} width - The width of the copy region.
  1828. * @param {number} height - The height of the copy region.
  1829. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  1830. * @param {number} [faceIndex=0] - The active cube face index.
  1831. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  1832. */
  1833. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  1834. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  1835. }
  1836. /**
  1837. * Analyzes the given 3D object's hierarchy and builds render lists from the
  1838. * processed hierarchy.
  1839. *
  1840. * @param {Object3D} object - The 3D object to process (usually a scene).
  1841. * @param {Camera} camera - The camera the object is rendered with.
  1842. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  1843. * @param {RenderList} renderList - The current render list.
  1844. * @param {ClippingContext} clippingContext - The current clipping context.
  1845. */
  1846. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  1847. if ( object.visible === false ) return;
  1848. const visible = object.layers.test( camera.layers );
  1849. if ( visible ) {
  1850. if ( object.isGroup ) {
  1851. groupOrder = object.renderOrder;
  1852. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  1853. } else if ( object.isLOD ) {
  1854. if ( object.autoUpdate === true ) object.update( camera );
  1855. } else if ( object.isLight ) {
  1856. renderList.pushLight( object );
  1857. } else if ( object.isSprite ) {
  1858. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  1859. if ( this.sortObjects === true ) {
  1860. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  1861. }
  1862. const { geometry, material } = object;
  1863. if ( material.visible ) {
  1864. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  1865. }
  1866. }
  1867. } else if ( object.isLineLoop ) {
  1868. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  1869. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  1870. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  1871. const { geometry, material } = object;
  1872. if ( this.sortObjects === true ) {
  1873. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  1874. _vector4
  1875. .copy( geometry.boundingSphere.center )
  1876. .applyMatrix4( object.matrixWorld )
  1877. .applyMatrix4( _projScreenMatrix );
  1878. }
  1879. if ( Array.isArray( material ) ) {
  1880. const groups = geometry.groups;
  1881. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  1882. const group = groups[ i ];
  1883. const groupMaterial = material[ group.materialIndex ];
  1884. if ( groupMaterial && groupMaterial.visible ) {
  1885. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  1886. }
  1887. }
  1888. } else if ( material.visible ) {
  1889. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  1890. }
  1891. }
  1892. }
  1893. }
  1894. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  1895. const baseRenderList = renderList;
  1896. // replace render list
  1897. renderList = this._renderLists.get( object, camera );
  1898. renderList.begin();
  1899. baseRenderList.pushBundle( {
  1900. bundleGroup: object,
  1901. camera,
  1902. renderList,
  1903. } );
  1904. renderList.finish();
  1905. }
  1906. const children = object.children;
  1907. for ( let i = 0, l = children.length; i < l; i ++ ) {
  1908. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  1909. }
  1910. }
  1911. /**
  1912. * Renders the given render bundles.
  1913. *
  1914. * @private
  1915. * @param {Array<Object>} bundles - Array with render bundle data.
  1916. * @param {Scene} sceneRef - The scene the render bundles belong to.
  1917. * @param {LightsNode} lightsNode - The current lights node.
  1918. */
  1919. _renderBundles( bundles, sceneRef, lightsNode ) {
  1920. for ( const bundle of bundles ) {
  1921. this._renderBundle( bundle, sceneRef, lightsNode );
  1922. }
  1923. }
  1924. /**
  1925. * Renders the transparent objects from the given render lists.
  1926. *
  1927. * @private
  1928. * @param {Array<Object>} renderList - The transparent render list.
  1929. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  1930. * @param {Camera} camera - The camera the render list should be rendered with.
  1931. * @param {Scene} scene - The scene the render list belongs to.
  1932. * @param {LightsNode} lightsNode - The current lights node.
  1933. */
  1934. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  1935. if ( doublePassList.length > 0 ) {
  1936. // render back side
  1937. for ( const { material } of doublePassList ) {
  1938. material.side = BackSide;
  1939. }
  1940. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  1941. // render front side
  1942. for ( const { material } of doublePassList ) {
  1943. material.side = FrontSide;
  1944. }
  1945. this._renderObjects( renderList, camera, scene, lightsNode );
  1946. // restore
  1947. for ( const { material } of doublePassList ) {
  1948. material.side = DoubleSide;
  1949. }
  1950. } else {
  1951. this._renderObjects( renderList, camera, scene, lightsNode );
  1952. }
  1953. }
  1954. /**
  1955. * Renders the objects from the given render list.
  1956. *
  1957. * @private
  1958. * @param {Array<Object>} renderList - The render list.
  1959. * @param {Camera} camera - The camera the render list should be rendered with.
  1960. * @param {Scene} scene - The scene the render list belongs to.
  1961. * @param {LightsNode} lightsNode - The current lights node.
  1962. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  1963. */
  1964. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  1965. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  1966. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  1967. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  1968. }
  1969. }
  1970. /**
  1971. * This method represents the default render object function that manages the render lifecycle
  1972. * of the object.
  1973. *
  1974. * @param {Object3D} object - The 3D object.
  1975. * @param {Scene} scene - The scene the 3D object belongs to.
  1976. * @param {Camera} camera - The camera the object should be rendered with.
  1977. * @param {BufferGeometry} geometry - The object's geometry.
  1978. * @param {Material} material - The object's material.
  1979. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  1980. * @param {LightsNode} lightsNode - The current lights node.
  1981. * @param {ClippingContext} clippingContext - The clipping context.
  1982. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  1983. */
  1984. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  1985. let overridePositionNode;
  1986. let overrideColorNode;
  1987. let overrideDepthNode;
  1988. //
  1989. object.onBeforeRender( this, scene, camera, geometry, material, group );
  1990. //
  1991. if ( scene.overrideMaterial !== null ) {
  1992. const overrideMaterial = scene.overrideMaterial;
  1993. if ( material.positionNode && material.positionNode.isNode ) {
  1994. overridePositionNode = overrideMaterial.positionNode;
  1995. overrideMaterial.positionNode = material.positionNode;
  1996. }
  1997. overrideMaterial.alphaTest = material.alphaTest;
  1998. overrideMaterial.alphaMap = material.alphaMap;
  1999. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  2000. if ( overrideMaterial.isShadowPassMaterial ) {
  2001. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  2002. if ( material.depthNode && material.depthNode.isNode ) {
  2003. overrideDepthNode = overrideMaterial.depthNode;
  2004. overrideMaterial.depthNode = material.depthNode;
  2005. }
  2006. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  2007. overrideColorNode = overrideMaterial.colorNode;
  2008. overrideMaterial.colorNode = material.castShadowNode;
  2009. }
  2010. }
  2011. material = overrideMaterial;
  2012. }
  2013. //
  2014. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  2015. material.side = BackSide;
  2016. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  2017. material.side = FrontSide;
  2018. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  2019. material.side = DoubleSide;
  2020. } else {
  2021. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  2022. }
  2023. //
  2024. if ( overridePositionNode !== undefined ) {
  2025. scene.overrideMaterial.positionNode = overridePositionNode;
  2026. }
  2027. if ( overrideDepthNode !== undefined ) {
  2028. scene.overrideMaterial.depthNode = overrideDepthNode;
  2029. }
  2030. if ( overrideColorNode !== undefined ) {
  2031. scene.overrideMaterial.colorNode = overrideColorNode;
  2032. }
  2033. //
  2034. object.onAfterRender( this, scene, camera, geometry, material, group );
  2035. }
  2036. /**
  2037. * This method represents the default `_handleObjectFunction` implementation which creates
  2038. * a render object from the given data and performs the draw command with the selected backend.
  2039. *
  2040. * @private
  2041. * @param {Object3D} object - The 3D object.
  2042. * @param {Material} material - The object's material.
  2043. * @param {Scene} scene - The scene the 3D object belongs to.
  2044. * @param {Camera} camera - The camera the object should be rendered with.
  2045. * @param {LightsNode} lightsNode - The current lights node.
  2046. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  2047. * @param {ClippingContext} clippingContext - The clipping context.
  2048. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  2049. */
  2050. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  2051. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  2052. renderObject.drawRange = object.geometry.drawRange;
  2053. renderObject.group = group;
  2054. //
  2055. const needsRefresh = this._nodes.needsRefresh( renderObject );
  2056. if ( needsRefresh ) {
  2057. this._nodes.updateBefore( renderObject );
  2058. this._geometries.updateForRender( renderObject );
  2059. this._nodes.updateForRender( renderObject );
  2060. this._bindings.updateForRender( renderObject );
  2061. }
  2062. this._pipelines.updateForRender( renderObject );
  2063. //
  2064. if ( this._currentRenderBundle !== null ) {
  2065. const renderBundleData = this.backend.get( this._currentRenderBundle );
  2066. renderBundleData.renderObjects.push( renderObject );
  2067. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  2068. }
  2069. this.backend.draw( renderObject, this.info );
  2070. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  2071. }
  2072. /**
  2073. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  2074. * Used in `compileAsync()`.
  2075. *
  2076. * @private
  2077. * @param {Object3D} object - The 3D object.
  2078. * @param {Material} material - The object's material.
  2079. * @param {Scene} scene - The scene the 3D object belongs to.
  2080. * @param {Camera} camera - The camera the object should be rendered with.
  2081. * @param {LightsNode} lightsNode - The current lights node.
  2082. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  2083. * @param {ClippingContext} clippingContext - The clipping context.
  2084. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  2085. */
  2086. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  2087. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  2088. renderObject.drawRange = object.geometry.drawRange;
  2089. renderObject.group = group;
  2090. //
  2091. this._nodes.updateBefore( renderObject );
  2092. this._geometries.updateForRender( renderObject );
  2093. this._nodes.updateForRender( renderObject );
  2094. this._bindings.updateForRender( renderObject );
  2095. this._pipelines.getForRender( renderObject, this._compilationPromises );
  2096. this._nodes.updateAfter( renderObject );
  2097. }
  2098. /**
  2099. * Alias for `compileAsync()`.
  2100. *
  2101. * @method
  2102. * @param {Object3D} scene - The scene or 3D object to precompile.
  2103. * @param {Camera} camera - The camera that is used to render the scene.
  2104. * @param {Scene} targetScene - If the first argument is a 3D object, this parameter must represent the scene the 3D object is going to be added.
  2105. * @return {Promise} A Promise that resolves when the compile has been finished.
  2106. */
  2107. get compile() {
  2108. return this.compileAsync;
  2109. }
  2110. }
  2111. export default Renderer;
粤ICP备19079148号