WebGLRenderer.js 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488
  1. import {
  2. REVISION,
  3. BackSide,
  4. FrontSide,
  5. DoubleSide,
  6. HalfFloatType,
  7. UnsignedByteType,
  8. NoToneMapping,
  9. LinearMipmapLinearFilter,
  10. SRGBColorSpace,
  11. LinearSRGBColorSpace,
  12. RGBAIntegerFormat,
  13. RGIntegerFormat,
  14. RedIntegerFormat,
  15. UnsignedIntType,
  16. UnsignedShortType,
  17. UnsignedInt248Type,
  18. UnsignedShort4444Type,
  19. UnsignedShort5551Type,
  20. WebGLCoordinateSystem
  21. } from '../constants.js';
  22. import { Color } from '../math/Color.js';
  23. import { Frustum } from '../math/Frustum.js';
  24. import { Matrix4 } from '../math/Matrix4.js';
  25. import { Vector3 } from '../math/Vector3.js';
  26. import { Vector4 } from '../math/Vector4.js';
  27. import { WebGLAnimation } from './webgl/WebGLAnimation.js';
  28. import { WebGLAttributes } from './webgl/WebGLAttributes.js';
  29. import { WebGLBackground } from './webgl/WebGLBackground.js';
  30. import { WebGLBindingStates } from './webgl/WebGLBindingStates.js';
  31. import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer.js';
  32. import { WebGLCapabilities } from './webgl/WebGLCapabilities.js';
  33. import { WebGLClipping } from './webgl/WebGLClipping.js';
  34. import { WebGLCubeMaps } from './webgl/WebGLCubeMaps.js';
  35. import { WebGLCubeUVMaps } from './webgl/WebGLCubeUVMaps.js';
  36. import { WebGLExtensions } from './webgl/WebGLExtensions.js';
  37. import { WebGLGeometries } from './webgl/WebGLGeometries.js';
  38. import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer.js';
  39. import { WebGLInfo } from './webgl/WebGLInfo.js';
  40. import { WebGLMorphtargets } from './webgl/WebGLMorphtargets.js';
  41. import { WebGLObjects } from './webgl/WebGLObjects.js';
  42. import { WebGLPrograms } from './webgl/WebGLPrograms.js';
  43. import { WebGLProperties } from './webgl/WebGLProperties.js';
  44. import { WebGLRenderLists } from './webgl/WebGLRenderLists.js';
  45. import { WebGLRenderStates } from './webgl/WebGLRenderStates.js';
  46. import { WebGLRenderTarget } from './WebGLRenderTarget.js';
  47. import { WebGLShadowMap } from './webgl/WebGLShadowMap.js';
  48. import { WebGLState } from './webgl/WebGLState.js';
  49. import { WebGLTextures } from './webgl/WebGLTextures.js';
  50. import { WebGLUniforms } from './webgl/WebGLUniforms.js';
  51. import { WebGLUtils } from './webgl/WebGLUtils.js';
  52. import { WebXRManager } from './webxr/WebXRManager.js';
  53. import { WebGLMaterials } from './webgl/WebGLMaterials.js';
  54. import { WebGLUniformsGroups } from './webgl/WebGLUniformsGroups.js';
  55. import { createCanvasElement, probeAsync, toNormalizedProjectionMatrix, toReversedProjectionMatrix, warnOnce } from '../utils.js';
  56. import { ColorManagement } from '../math/ColorManagement.js';
  57. /**
  58. * This renderer uses WebGL 2 to display scenes.
  59. *
  60. * WebGL 1 is not supported since `r163`.
  61. */
  62. class WebGLRenderer {
  63. /**
  64. * Constructs a new WebGL renderer.
  65. *
  66. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  67. */
  68. constructor( parameters = {} ) {
  69. const {
  70. canvas = createCanvasElement(),
  71. context = null,
  72. depth = true,
  73. stencil = false,
  74. alpha = false,
  75. antialias = false,
  76. premultipliedAlpha = true,
  77. preserveDrawingBuffer = false,
  78. powerPreference = 'default',
  79. failIfMajorPerformanceCaveat = false,
  80. reverseDepthBuffer = false,
  81. } = parameters;
  82. /**
  83. * This flag can be used for type testing.
  84. *
  85. * @type {boolean}
  86. * @readonly
  87. * @default true
  88. */
  89. this.isWebGLRenderer = true;
  90. let _alpha;
  91. if ( context !== null ) {
  92. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  93. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  94. }
  95. _alpha = context.getContextAttributes().alpha;
  96. } else {
  97. _alpha = alpha;
  98. }
  99. const uintClearColor = new Uint32Array( 4 );
  100. const intClearColor = new Int32Array( 4 );
  101. let currentRenderList = null;
  102. let currentRenderState = null;
  103. // render() can be called from within a callback triggered by another render.
  104. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  105. const renderListStack = [];
  106. const renderStateStack = [];
  107. // public properties
  108. /**
  109. * A canvas where the renderer draws its output.This is automatically created by the renderer
  110. * in the constructor (if not provided already); you just need to add it to your page like so:
  111. * ```js
  112. * document.body.appendChild( renderer.domElement );
  113. * ```
  114. *
  115. * @type {DOMElement}
  116. */
  117. this.domElement = canvas;
  118. /**
  119. * A object with debug configuration settings.
  120. *
  121. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  122. * checked for errors during compilation and linkage process. It may be useful to disable
  123. * this check in production for performance gain. It is strongly recommended to keep these
  124. * checks enabled during development. If the shader does not compile and link - it will not
  125. * work and associated material will not render.
  126. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  127. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  128. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  129. * Assigning a custom function disables the default error reporting.
  130. *
  131. * @type {Object}
  132. */
  133. this.debug = {
  134. /**
  135. * Enables error checking and reporting when shader programs are being compiled.
  136. * @type {boolean}
  137. */
  138. checkShaderErrors: true,
  139. /**
  140. * Callback for custom error reporting.
  141. * @type {?Function}
  142. */
  143. onShaderError: null
  144. };
  145. // clearing
  146. /**
  147. * Whether the renderer should automatically clear its output before rendering a frame or not.
  148. *
  149. * @type {boolean}
  150. * @default true
  151. */
  152. this.autoClear = true;
  153. /**
  154. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  155. * the color buffer or not.
  156. *
  157. * @type {boolean}
  158. * @default true
  159. */
  160. this.autoClearColor = true;
  161. /**
  162. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  163. * the depth buffer or not.
  164. *
  165. * @type {boolean}
  166. * @default true
  167. */
  168. this.autoClearDepth = true;
  169. /**
  170. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  171. * the stencil buffer or not.
  172. *
  173. * @type {boolean}
  174. * @default true
  175. */
  176. this.autoClearStencil = true;
  177. // scene graph
  178. /**
  179. * Whether the renderer should sort objects or not.
  180. *
  181. * Note: Sorting is used to attempt to properly render objects that have some
  182. * degree of transparency. By definition, sorting objects may not work in all
  183. * cases. Depending on the needs of application, it may be necessary to turn
  184. * off sorting and use other methods to deal with transparency rendering e.g.
  185. * manually determining each object's rendering order.
  186. *
  187. * @type {boolean}
  188. * @default true
  189. */
  190. this.sortObjects = true;
  191. // user-defined clipping
  192. /**
  193. * User-defined clipping planes specified in world space. These planes apply globally.
  194. * Points in space whose dot product with the plane is negative are cut away.
  195. *
  196. * @type {Array<Plane>}
  197. */
  198. this.clippingPlanes = [];
  199. /**
  200. * Whether the renderer respects object-level clipping planes or not.
  201. *
  202. * @type {boolean}
  203. * @default false
  204. */
  205. this.localClippingEnabled = false;
  206. // tone mapping
  207. /**
  208. * The tone mapping technique of the renderer.
  209. *
  210. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  211. * @default NoToneMapping
  212. */
  213. this.toneMapping = NoToneMapping;
  214. /**
  215. * Exposure level of tone mapping.
  216. *
  217. * @type {number}
  218. * @default 1
  219. */
  220. this.toneMappingExposure = 1.0;
  221. // transmission
  222. /**
  223. * The normalized resolution scale for the transmission render target, measured in percentage
  224. * of viewport dimensions. Lowering this value can result in significant performance improvements
  225. * when using {@link MeshPhysicalMaterial#transmission}.
  226. *
  227. * @type {number}
  228. * @default 1
  229. */
  230. this.transmissionResolutionScale = 1.0;
  231. // internal properties
  232. const _this = this;
  233. let _isContextLost = false;
  234. // internal state cache
  235. this._outputColorSpace = SRGBColorSpace;
  236. let _currentActiveCubeFace = 0;
  237. let _currentActiveMipmapLevel = 0;
  238. let _currentRenderTarget = null;
  239. let _currentMaterialId = - 1;
  240. let _currentCamera = null;
  241. const _currentViewport = new Vector4();
  242. const _currentScissor = new Vector4();
  243. let _currentScissorTest = null;
  244. const _currentClearColor = new Color( 0x000000 );
  245. let _currentClearAlpha = 0;
  246. //
  247. let _width = canvas.width;
  248. let _height = canvas.height;
  249. let _pixelRatio = 1;
  250. let _opaqueSort = null;
  251. let _transparentSort = null;
  252. const _viewport = new Vector4( 0, 0, _width, _height );
  253. const _scissor = new Vector4( 0, 0, _width, _height );
  254. let _scissorTest = false;
  255. // frustum
  256. const _frustum = new Frustum();
  257. // clipping
  258. let _clippingEnabled = false;
  259. let _localClippingEnabled = false;
  260. // camera matrices cache
  261. const _currentProjectionMatrix = new Matrix4();
  262. const _projScreenMatrix = new Matrix4();
  263. const _vector3 = new Vector3();
  264. const _vector4 = new Vector4();
  265. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  266. let _renderBackground = false;
  267. function getTargetPixelRatio() {
  268. return _currentRenderTarget === null ? _pixelRatio : 1;
  269. }
  270. // initialize
  271. let _gl = context;
  272. function getContext( contextName, contextAttributes ) {
  273. return canvas.getContext( contextName, contextAttributes );
  274. }
  275. try {
  276. const contextAttributes = {
  277. alpha: true,
  278. depth,
  279. stencil,
  280. antialias,
  281. premultipliedAlpha,
  282. preserveDrawingBuffer,
  283. powerPreference,
  284. failIfMajorPerformanceCaveat,
  285. };
  286. // OffscreenCanvas does not have setAttribute, see #22811
  287. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  288. // event listeners must be registered before WebGL context is created, see #12753
  289. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  290. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  291. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  292. if ( _gl === null ) {
  293. const contextName = 'webgl2';
  294. _gl = getContext( contextName, contextAttributes );
  295. if ( _gl === null ) {
  296. if ( getContext( contextName ) ) {
  297. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  298. } else {
  299. throw new Error( 'Error creating WebGL context.' );
  300. }
  301. }
  302. }
  303. } catch ( error ) {
  304. console.error( 'THREE.WebGLRenderer: ' + error.message );
  305. throw error;
  306. }
  307. let extensions, capabilities, state, info;
  308. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  309. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  310. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  311. let utils, bindingStates, uniformsGroups;
  312. function initGLContext() {
  313. extensions = new WebGLExtensions( _gl );
  314. extensions.init();
  315. utils = new WebGLUtils( _gl, extensions );
  316. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  317. state = new WebGLState( _gl, extensions );
  318. if ( capabilities.reverseDepthBuffer && reverseDepthBuffer ) {
  319. state.buffers.depth.setReversed( true );
  320. }
  321. info = new WebGLInfo( _gl );
  322. properties = new WebGLProperties();
  323. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  324. cubemaps = new WebGLCubeMaps( _this );
  325. cubeuvmaps = new WebGLCubeUVMaps( _this );
  326. attributes = new WebGLAttributes( _gl );
  327. bindingStates = new WebGLBindingStates( _gl, attributes );
  328. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  329. objects = new WebGLObjects( _gl, geometries, attributes, info );
  330. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  331. clipping = new WebGLClipping( properties );
  332. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  333. materials = new WebGLMaterials( _this, properties );
  334. renderLists = new WebGLRenderLists();
  335. renderStates = new WebGLRenderStates( extensions );
  336. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  337. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  338. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  339. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  340. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  341. info.programs = programCache.programs;
  342. /**
  343. * Holds details about the capabilities of the current rendering context.
  344. *
  345. * @name WebGLRenderer#capabilities
  346. * @type {WebGLRenderer~Capabilities}
  347. */
  348. _this.capabilities = capabilities;
  349. /**
  350. * Provides methods for retrieving and testing WebGL extensions.
  351. *
  352. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  353. * and return the extension object if available.
  354. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  355. *
  356. * @name WebGLRenderer#extensions
  357. * @type {Object}
  358. */
  359. _this.extensions = extensions;
  360. /**
  361. * Used to track properties of other objects like native WebGL objects.
  362. *
  363. * @name WebGLRenderer#properties
  364. * @type {Object}
  365. */
  366. _this.properties = properties;
  367. /**
  368. * Manages the render lists of the renderer.
  369. *
  370. * @name WebGLRenderer#renderLists
  371. * @type {Object}
  372. */
  373. _this.renderLists = renderLists;
  374. /**
  375. * Interface for managing shadows.
  376. *
  377. * @name WebGLRenderer#shadowMap
  378. * @type {WebGLRenderer~ShadowMap}
  379. */
  380. _this.shadowMap = shadowMap;
  381. /**
  382. * Interface for managing the WebGL state.
  383. *
  384. * @name WebGLRenderer#state
  385. * @type {Object}
  386. */
  387. _this.state = state;
  388. /**
  389. * Holds a series of statistical information about the GPU memory
  390. * and the rendering process. Useful for debugging and monitoring.
  391. *
  392. * By default these data are reset at each render call but when having
  393. * multiple render passes per frame (e.g. when using post processing) it can
  394. * be preferred to reset with a custom pattern. First, set `autoReset` to
  395. * `false`.
  396. * ```js
  397. * renderer.info.autoReset = false;
  398. * ```
  399. * Call `reset()` whenever you have finished to render a single frame.
  400. * ```js
  401. * renderer.info.reset();
  402. * ```
  403. *
  404. * @name WebGLRenderer#info
  405. * @type {WebGLRenderer~Info}
  406. */
  407. _this.info = info;
  408. }
  409. initGLContext();
  410. // xr
  411. const xr = new WebXRManager( _this, _gl );
  412. /**
  413. * A reference to the XR manager.
  414. *
  415. * @type {WebXRManager}
  416. */
  417. this.xr = xr;
  418. /**
  419. * Returns the rendering context.
  420. *
  421. * @return {WebGL2RenderingContext} The rendering context.
  422. */
  423. this.getContext = function () {
  424. return _gl;
  425. };
  426. /**
  427. * Returns the rendering context attributes.
  428. *
  429. * @return {WebGLContextAttributes} The rendering context attributes.
  430. */
  431. this.getContextAttributes = function () {
  432. return _gl.getContextAttributes();
  433. };
  434. /**
  435. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  436. */
  437. this.forceContextLoss = function () {
  438. const extension = extensions.get( 'WEBGL_lose_context' );
  439. if ( extension ) extension.loseContext();
  440. };
  441. /**
  442. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  443. */
  444. this.forceContextRestore = function () {
  445. const extension = extensions.get( 'WEBGL_lose_context' );
  446. if ( extension ) extension.restoreContext();
  447. };
  448. /**
  449. * Returns the pixel ratio.
  450. *
  451. * @return {number} The pixel ratio.
  452. */
  453. this.getPixelRatio = function () {
  454. return _pixelRatio;
  455. };
  456. /**
  457. * Sets the given pixel ratio and resizes the canvas if necessary.
  458. *
  459. * @param {number} value - The pixel ratio.
  460. */
  461. this.setPixelRatio = function ( value ) {
  462. if ( value === undefined ) return;
  463. _pixelRatio = value;
  464. this.setSize( _width, _height, false );
  465. };
  466. /**
  467. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  468. *
  469. * @param {Vector2} target - The method writes the result in this target object.
  470. * @return {Vector2} The renderer's size in logical pixels.
  471. */
  472. this.getSize = function ( target ) {
  473. return target.set( _width, _height );
  474. };
  475. /**
  476. * Resizes the output canvas to (width, height) with device pixel ratio taken
  477. * into account, and also sets the viewport to fit that size, starting in (0,
  478. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  479. *
  480. * @param {number} width - The width in logical pixels.
  481. * @param {number} height - The height in logical pixels.
  482. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  483. */
  484. this.setSize = function ( width, height, updateStyle = true ) {
  485. if ( xr.isPresenting ) {
  486. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  487. return;
  488. }
  489. _width = width;
  490. _height = height;
  491. canvas.width = Math.floor( width * _pixelRatio );
  492. canvas.height = Math.floor( height * _pixelRatio );
  493. if ( updateStyle === true ) {
  494. canvas.style.width = width + 'px';
  495. canvas.style.height = height + 'px';
  496. }
  497. this.setViewport( 0, 0, width, height );
  498. };
  499. /**
  500. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  501. *
  502. * @param {Vector2} target - The method writes the result in this target object.
  503. * @return {Vector2} The drawing buffer size.
  504. */
  505. this.getDrawingBufferSize = function ( target ) {
  506. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  507. };
  508. /**
  509. * This method allows to define the drawing buffer size by specifying
  510. * width, height and pixel ratio all at once. The size of the drawing
  511. * buffer is computed with this formula:
  512. * ```js
  513. * size.x = width * pixelRatio;
  514. * size.y = height * pixelRatio;
  515. * ```
  516. *
  517. * @param {number} width - The width in logical pixels.
  518. * @param {number} height - The height in logical pixels.
  519. * @param {number} pixelRatio - The pixel ratio.
  520. */
  521. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  522. _width = width;
  523. _height = height;
  524. _pixelRatio = pixelRatio;
  525. canvas.width = Math.floor( width * pixelRatio );
  526. canvas.height = Math.floor( height * pixelRatio );
  527. this.setViewport( 0, 0, width, height );
  528. };
  529. /**
  530. * Returns the current viewport definition.
  531. *
  532. * @param {Vector2} target - The method writes the result in this target object.
  533. * @return {Vector2} The current viewport definition.
  534. */
  535. this.getCurrentViewport = function ( target ) {
  536. return target.copy( _currentViewport );
  537. };
  538. /**
  539. * Returns the viewport definition.
  540. *
  541. * @param {Vector4} target - The method writes the result in this target object.
  542. * @return {Vector4} The viewport definition.
  543. */
  544. this.getViewport = function ( target ) {
  545. return target.copy( _viewport );
  546. };
  547. /**
  548. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  549. *
  550. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  551. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  552. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  553. * @param {number} width - The width of the viewport in logical pixel unit.
  554. * @param {number} height - The height of the viewport in logical pixel unit.
  555. */
  556. this.setViewport = function ( x, y, width, height ) {
  557. if ( x.isVector4 ) {
  558. _viewport.set( x.x, x.y, x.z, x.w );
  559. } else {
  560. _viewport.set( x, y, width, height );
  561. }
  562. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  563. };
  564. /**
  565. * Returns the scissor region.
  566. *
  567. * @param {Vector4} target - The method writes the result in this target object.
  568. * @return {Vector4} The scissor region.
  569. */
  570. this.getScissor = function ( target ) {
  571. return target.copy( _scissor );
  572. };
  573. /**
  574. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  575. *
  576. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  577. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  578. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  579. * @param {number} width - The width of the scissor region in logical pixel unit.
  580. * @param {number} height - The height of the scissor region in logical pixel unit.
  581. */
  582. this.setScissor = function ( x, y, width, height ) {
  583. if ( x.isVector4 ) {
  584. _scissor.set( x.x, x.y, x.z, x.w );
  585. } else {
  586. _scissor.set( x, y, width, height );
  587. }
  588. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  589. };
  590. /**
  591. * Returns `true` if the scissor test is enabled.
  592. *
  593. * @return {boolean} Whether the scissor test is enabled or not.
  594. */
  595. this.getScissorTest = function () {
  596. return _scissorTest;
  597. };
  598. /**
  599. * Enable or disable the scissor test. When this is enabled, only the pixels
  600. * within the defined scissor area will be affected by further renderer
  601. * actions.
  602. *
  603. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  604. */
  605. this.setScissorTest = function ( boolean ) {
  606. state.setScissorTest( _scissorTest = boolean );
  607. };
  608. /**
  609. * Sets a custom opaque sort function for the render lists. Pass `null`
  610. * to use the default `painterSortStable` function.
  611. *
  612. * @param {?Function} method - The opaque sort function.
  613. */
  614. this.setOpaqueSort = function ( method ) {
  615. _opaqueSort = method;
  616. };
  617. /**
  618. * Sets a custom transparent sort function for the render lists. Pass `null`
  619. * to use the default `reversePainterSortStable` function.
  620. *
  621. * @param {?Function} method - The opaque sort function.
  622. */
  623. this.setTransparentSort = function ( method ) {
  624. _transparentSort = method;
  625. };
  626. // Clearing
  627. /**
  628. * Returns the clear color.
  629. *
  630. * @param {Color} target - The method writes the result in this target object.
  631. * @return {Color} The clear color.
  632. */
  633. this.getClearColor = function ( target ) {
  634. return target.copy( background.getClearColor() );
  635. };
  636. /**
  637. * Sets the clear color and alpha.
  638. *
  639. * @param {Color} color - The clear color.
  640. * @param {number} [alpha=1] - The clear alpha.
  641. */
  642. this.setClearColor = function () {
  643. background.setClearColor( ...arguments );
  644. };
  645. /**
  646. * Returns the clear alpha. Ranges within `[0,1]`.
  647. *
  648. * @return {number} The clear alpha.
  649. */
  650. this.getClearAlpha = function () {
  651. return background.getClearAlpha();
  652. };
  653. /**
  654. * Sets the clear alpha.
  655. *
  656. * @param {number} alpha - The clear alpha.
  657. */
  658. this.setClearAlpha = function () {
  659. background.setClearAlpha( ...arguments );
  660. };
  661. /**
  662. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  663. * This method initializes the buffers to the current clear color values.
  664. *
  665. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  666. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  667. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  668. */
  669. this.clear = function ( color = true, depth = true, stencil = true ) {
  670. let bits = 0;
  671. if ( color ) {
  672. // check if we're trying to clear an integer target
  673. let isIntegerFormat = false;
  674. if ( _currentRenderTarget !== null ) {
  675. const targetFormat = _currentRenderTarget.texture.format;
  676. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  677. targetFormat === RGIntegerFormat ||
  678. targetFormat === RedIntegerFormat;
  679. }
  680. // use the appropriate clear functions to clear the target if it's a signed
  681. // or unsigned integer target
  682. if ( isIntegerFormat ) {
  683. const targetType = _currentRenderTarget.texture.type;
  684. const isUnsignedType = targetType === UnsignedByteType ||
  685. targetType === UnsignedIntType ||
  686. targetType === UnsignedShortType ||
  687. targetType === UnsignedInt248Type ||
  688. targetType === UnsignedShort4444Type ||
  689. targetType === UnsignedShort5551Type;
  690. const clearColor = background.getClearColor();
  691. const a = background.getClearAlpha();
  692. const r = clearColor.r;
  693. const g = clearColor.g;
  694. const b = clearColor.b;
  695. if ( isUnsignedType ) {
  696. uintClearColor[ 0 ] = r;
  697. uintClearColor[ 1 ] = g;
  698. uintClearColor[ 2 ] = b;
  699. uintClearColor[ 3 ] = a;
  700. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  701. } else {
  702. intClearColor[ 0 ] = r;
  703. intClearColor[ 1 ] = g;
  704. intClearColor[ 2 ] = b;
  705. intClearColor[ 3 ] = a;
  706. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  707. }
  708. } else {
  709. bits |= _gl.COLOR_BUFFER_BIT;
  710. }
  711. }
  712. if ( depth ) {
  713. bits |= _gl.DEPTH_BUFFER_BIT;
  714. }
  715. if ( stencil ) {
  716. bits |= _gl.STENCIL_BUFFER_BIT;
  717. this.state.buffers.stencil.setMask( 0xffffffff );
  718. }
  719. _gl.clear( bits );
  720. };
  721. /**
  722. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  723. */
  724. this.clearColor = function () {
  725. this.clear( true, false, false );
  726. };
  727. /**
  728. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  729. */
  730. this.clearDepth = function () {
  731. this.clear( false, true, false );
  732. };
  733. /**
  734. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  735. */
  736. this.clearStencil = function () {
  737. this.clear( false, false, true );
  738. };
  739. /**
  740. * Frees the GPU-related resources allocated by this instance. Call this
  741. * method whenever this instance is no longer used in your app.
  742. */
  743. this.dispose = function () {
  744. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  745. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  746. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  747. background.dispose();
  748. renderLists.dispose();
  749. renderStates.dispose();
  750. properties.dispose();
  751. cubemaps.dispose();
  752. cubeuvmaps.dispose();
  753. objects.dispose();
  754. bindingStates.dispose();
  755. uniformsGroups.dispose();
  756. programCache.dispose();
  757. xr.dispose();
  758. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  759. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  760. animation.stop();
  761. };
  762. // Events
  763. function onContextLost( event ) {
  764. event.preventDefault();
  765. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  766. _isContextLost = true;
  767. }
  768. function onContextRestore( /* event */ ) {
  769. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  770. _isContextLost = false;
  771. const infoAutoReset = info.autoReset;
  772. const shadowMapEnabled = shadowMap.enabled;
  773. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  774. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  775. const shadowMapType = shadowMap.type;
  776. initGLContext();
  777. info.autoReset = infoAutoReset;
  778. shadowMap.enabled = shadowMapEnabled;
  779. shadowMap.autoUpdate = shadowMapAutoUpdate;
  780. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  781. shadowMap.type = shadowMapType;
  782. }
  783. function onContextCreationError( event ) {
  784. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  785. }
  786. function onMaterialDispose( event ) {
  787. const material = event.target;
  788. material.removeEventListener( 'dispose', onMaterialDispose );
  789. deallocateMaterial( material );
  790. }
  791. // Buffer deallocation
  792. function deallocateMaterial( material ) {
  793. releaseMaterialProgramReferences( material );
  794. properties.remove( material );
  795. }
  796. function releaseMaterialProgramReferences( material ) {
  797. const programs = properties.get( material ).programs;
  798. if ( programs !== undefined ) {
  799. programs.forEach( function ( program ) {
  800. programCache.releaseProgram( program );
  801. } );
  802. if ( material.isShaderMaterial ) {
  803. programCache.releaseShaderCache( material );
  804. }
  805. }
  806. }
  807. // Buffer rendering
  808. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  809. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  810. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  811. const program = setProgram( camera, scene, geometry, material, object );
  812. state.setMaterial( material, frontFaceCW );
  813. //
  814. let index = geometry.index;
  815. let rangeFactor = 1;
  816. if ( material.wireframe === true ) {
  817. index = geometries.getWireframeAttribute( geometry );
  818. if ( index === undefined ) return;
  819. rangeFactor = 2;
  820. }
  821. //
  822. const drawRange = geometry.drawRange;
  823. const position = geometry.attributes.position;
  824. let drawStart = drawRange.start * rangeFactor;
  825. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  826. if ( group !== null ) {
  827. drawStart = Math.max( drawStart, group.start * rangeFactor );
  828. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  829. }
  830. if ( index !== null ) {
  831. drawStart = Math.max( drawStart, 0 );
  832. drawEnd = Math.min( drawEnd, index.count );
  833. } else if ( position !== undefined && position !== null ) {
  834. drawStart = Math.max( drawStart, 0 );
  835. drawEnd = Math.min( drawEnd, position.count );
  836. }
  837. const drawCount = drawEnd - drawStart;
  838. if ( drawCount < 0 || drawCount === Infinity ) return;
  839. //
  840. bindingStates.setup( object, material, program, geometry, index );
  841. let attribute;
  842. let renderer = bufferRenderer;
  843. if ( index !== null ) {
  844. attribute = attributes.get( index );
  845. renderer = indexedBufferRenderer;
  846. renderer.setIndex( attribute );
  847. }
  848. //
  849. if ( object.isMesh ) {
  850. if ( material.wireframe === true ) {
  851. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  852. renderer.setMode( _gl.LINES );
  853. } else {
  854. renderer.setMode( _gl.TRIANGLES );
  855. }
  856. } else if ( object.isLine ) {
  857. let lineWidth = material.linewidth;
  858. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  859. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  860. if ( object.isLineSegments ) {
  861. renderer.setMode( _gl.LINES );
  862. } else if ( object.isLineLoop ) {
  863. renderer.setMode( _gl.LINE_LOOP );
  864. } else {
  865. renderer.setMode( _gl.LINE_STRIP );
  866. }
  867. } else if ( object.isPoints ) {
  868. renderer.setMode( _gl.POINTS );
  869. } else if ( object.isSprite ) {
  870. renderer.setMode( _gl.TRIANGLES );
  871. }
  872. if ( object.isBatchedMesh ) {
  873. if ( object._multiDrawInstances !== null ) {
  874. // @deprecated, r174
  875. warnOnce( 'THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  876. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  877. } else {
  878. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  879. const starts = object._multiDrawStarts;
  880. const counts = object._multiDrawCounts;
  881. const drawCount = object._multiDrawCount;
  882. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  883. const uniforms = properties.get( material ).currentProgram.getUniforms();
  884. for ( let i = 0; i < drawCount; i ++ ) {
  885. uniforms.setValue( _gl, '_gl_DrawID', i );
  886. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  887. }
  888. } else {
  889. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  890. }
  891. }
  892. } else if ( object.isInstancedMesh ) {
  893. renderer.renderInstances( drawStart, drawCount, object.count );
  894. } else if ( geometry.isInstancedBufferGeometry ) {
  895. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  896. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  897. renderer.renderInstances( drawStart, drawCount, instanceCount );
  898. } else {
  899. renderer.render( drawStart, drawCount );
  900. }
  901. };
  902. // Compile
  903. function prepareMaterial( material, scene, object ) {
  904. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  905. material.side = BackSide;
  906. material.needsUpdate = true;
  907. getProgram( material, scene, object );
  908. material.side = FrontSide;
  909. material.needsUpdate = true;
  910. getProgram( material, scene, object );
  911. material.side = DoubleSide;
  912. } else {
  913. getProgram( material, scene, object );
  914. }
  915. }
  916. /**
  917. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  918. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  919. * optional parameter for applying the target scene.
  920. *
  921. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  922. *
  923. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  924. * @param {Camera} camera - The camera.
  925. * @param {?Scene} [targetScene=null] - The target scene.
  926. * @return {?Set} The precompiled materials.
  927. */
  928. this.compile = function ( scene, camera, targetScene = null ) {
  929. if ( targetScene === null ) targetScene = scene;
  930. currentRenderState = renderStates.get( targetScene );
  931. currentRenderState.init( camera );
  932. renderStateStack.push( currentRenderState );
  933. // gather lights from both the target scene and the new object that will be added to the scene.
  934. targetScene.traverseVisible( function ( object ) {
  935. if ( object.isLight && object.layers.test( camera.layers ) ) {
  936. currentRenderState.pushLight( object );
  937. if ( object.castShadow ) {
  938. currentRenderState.pushShadow( object );
  939. }
  940. }
  941. } );
  942. if ( scene !== targetScene ) {
  943. scene.traverseVisible( function ( object ) {
  944. if ( object.isLight && object.layers.test( camera.layers ) ) {
  945. currentRenderState.pushLight( object );
  946. if ( object.castShadow ) {
  947. currentRenderState.pushShadow( object );
  948. }
  949. }
  950. } );
  951. }
  952. currentRenderState.setupLights();
  953. // Only initialize materials in the new scene, not the targetScene.
  954. const materials = new Set();
  955. scene.traverse( function ( object ) {
  956. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  957. return;
  958. }
  959. const material = object.material;
  960. if ( material ) {
  961. if ( Array.isArray( material ) ) {
  962. for ( let i = 0; i < material.length; i ++ ) {
  963. const material2 = material[ i ];
  964. prepareMaterial( material2, targetScene, object );
  965. materials.add( material2 );
  966. }
  967. } else {
  968. prepareMaterial( material, targetScene, object );
  969. materials.add( material );
  970. }
  971. }
  972. } );
  973. currentRenderState = renderStateStack.pop();
  974. return materials;
  975. };
  976. // compileAsync
  977. /**
  978. * Asynchronous version of {@link WebGLRenderer#compile}.
  979. *
  980. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  981. * it is recommended to use this version of `compile()` whenever possible.
  982. *
  983. * @async
  984. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  985. * @param {Camera} camera - The camera.
  986. * @param {?Scene} [targetScene=null] - The target scene.
  987. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  988. */
  989. this.compileAsync = function ( scene, camera, targetScene = null ) {
  990. const materials = this.compile( scene, camera, targetScene );
  991. // Wait for all the materials in the new object to indicate that they're
  992. // ready to be used before resolving the promise.
  993. return new Promise( ( resolve ) => {
  994. function checkMaterialsReady() {
  995. materials.forEach( function ( material ) {
  996. const materialProperties = properties.get( material );
  997. const program = materialProperties.currentProgram;
  998. if ( program.isReady() ) {
  999. // remove any programs that report they're ready to use from the list
  1000. materials.delete( material );
  1001. }
  1002. } );
  1003. // once the list of compiling materials is empty, call the callback
  1004. if ( materials.size === 0 ) {
  1005. resolve( scene );
  1006. return;
  1007. }
  1008. // if some materials are still not ready, wait a bit and check again
  1009. setTimeout( checkMaterialsReady, 10 );
  1010. }
  1011. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  1012. // If we can check the compilation status of the materials without
  1013. // blocking then do so right away.
  1014. checkMaterialsReady();
  1015. } else {
  1016. // Otherwise start by waiting a bit to give the materials we just
  1017. // initialized a chance to finish.
  1018. setTimeout( checkMaterialsReady, 10 );
  1019. }
  1020. } );
  1021. };
  1022. // Animation Loop
  1023. let onAnimationFrameCallback = null;
  1024. function onAnimationFrame( time ) {
  1025. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  1026. }
  1027. function onXRSessionStart() {
  1028. animation.stop();
  1029. }
  1030. function onXRSessionEnd() {
  1031. animation.start();
  1032. }
  1033. const animation = new WebGLAnimation();
  1034. animation.setAnimationLoop( onAnimationFrame );
  1035. if ( typeof self !== 'undefined' ) animation.setContext( self );
  1036. this.setAnimationLoop = function ( callback ) {
  1037. onAnimationFrameCallback = callback;
  1038. xr.setAnimationLoop( callback );
  1039. ( callback === null ) ? animation.stop() : animation.start();
  1040. };
  1041. xr.addEventListener( 'sessionstart', onXRSessionStart );
  1042. xr.addEventListener( 'sessionend', onXRSessionEnd );
  1043. // Rendering
  1044. /**
  1045. * Renders the given scene (or other type of 3D object) using the given camera.
  1046. *
  1047. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  1048. * or to the canvas as usual.
  1049. *
  1050. * By default render buffers are cleared before rendering but you can prevent
  1051. * this by setting the property `autoClear` to `false`. If you want to prevent
  1052. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  1053. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  1054. *
  1055. * @param {Object3D} scene - The scene to render.
  1056. * @param {Camera} camera - The camera.
  1057. */
  1058. this.render = function ( scene, camera ) {
  1059. if ( camera !== undefined && camera.isCamera !== true ) {
  1060. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  1061. return;
  1062. }
  1063. if ( _isContextLost === true ) return;
  1064. // update scene graph
  1065. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  1066. // update camera matrices and frustum
  1067. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  1068. if ( xr.enabled === true && xr.isPresenting === true ) {
  1069. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  1070. camera = xr.getCamera(); // use XR camera for rendering
  1071. }
  1072. //
  1073. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  1074. currentRenderState = renderStates.get( scene, renderStateStack.length );
  1075. currentRenderState.init( camera );
  1076. renderStateStack.push( currentRenderState );
  1077. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  1078. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  1079. _localClippingEnabled = this.localClippingEnabled;
  1080. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  1081. currentRenderList = renderLists.get( scene, renderListStack.length );
  1082. currentRenderList.init();
  1083. renderListStack.push( currentRenderList );
  1084. if ( xr.enabled === true && xr.isPresenting === true ) {
  1085. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  1086. if ( depthSensingMesh !== null ) {
  1087. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  1088. }
  1089. }
  1090. projectObject( scene, camera, 0, _this.sortObjects );
  1091. currentRenderList.finish();
  1092. if ( _this.sortObjects === true ) {
  1093. currentRenderList.sort( _opaqueSort, _transparentSort );
  1094. }
  1095. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  1096. if ( _renderBackground ) {
  1097. background.addToRenderList( currentRenderList, scene );
  1098. }
  1099. //
  1100. this.info.render.frame ++;
  1101. if ( _clippingEnabled === true ) clipping.beginShadows();
  1102. const shadowsArray = currentRenderState.state.shadowsArray;
  1103. shadowMap.render( shadowsArray, scene, camera );
  1104. if ( _clippingEnabled === true ) clipping.endShadows();
  1105. //
  1106. if ( this.info.autoReset === true ) this.info.reset();
  1107. // render scene
  1108. const opaqueObjects = currentRenderList.opaque;
  1109. const transmissiveObjects = currentRenderList.transmissive;
  1110. currentRenderState.setupLights();
  1111. if ( camera.isArrayCamera ) {
  1112. const cameras = camera.cameras;
  1113. if ( transmissiveObjects.length > 0 ) {
  1114. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  1115. const camera2 = cameras[ i ];
  1116. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  1117. }
  1118. }
  1119. if ( _renderBackground ) background.render( scene );
  1120. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  1121. const camera2 = cameras[ i ];
  1122. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  1123. }
  1124. } else {
  1125. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  1126. if ( _renderBackground ) background.render( scene );
  1127. renderScene( currentRenderList, scene, camera );
  1128. }
  1129. //
  1130. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  1131. // resolve multisample renderbuffers to a single-sample texture if necessary
  1132. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  1133. // Generate mipmap if we're using any kind of mipmap filtering
  1134. textures.updateRenderTargetMipmap( _currentRenderTarget );
  1135. }
  1136. //
  1137. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  1138. // _gl.finish();
  1139. bindingStates.resetDefaultState();
  1140. _currentMaterialId = - 1;
  1141. _currentCamera = null;
  1142. renderStateStack.pop();
  1143. if ( renderStateStack.length > 0 ) {
  1144. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  1145. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  1146. } else {
  1147. currentRenderState = null;
  1148. }
  1149. renderListStack.pop();
  1150. if ( renderListStack.length > 0 ) {
  1151. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  1152. } else {
  1153. currentRenderList = null;
  1154. }
  1155. };
  1156. function projectObject( object, camera, groupOrder, sortObjects ) {
  1157. if ( object.visible === false ) return;
  1158. const visible = object.layers.test( camera.layers );
  1159. if ( visible ) {
  1160. if ( object.isGroup ) {
  1161. groupOrder = object.renderOrder;
  1162. } else if ( object.isLOD ) {
  1163. if ( object.autoUpdate === true ) object.update( camera );
  1164. } else if ( object.isLight ) {
  1165. currentRenderState.pushLight( object );
  1166. if ( object.castShadow ) {
  1167. currentRenderState.pushShadow( object );
  1168. }
  1169. } else if ( object.isSprite ) {
  1170. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  1171. if ( sortObjects ) {
  1172. _vector4.setFromMatrixPosition( object.matrixWorld )
  1173. .applyMatrix4( _projScreenMatrix );
  1174. }
  1175. const geometry = objects.update( object );
  1176. const material = object.material;
  1177. if ( material.visible ) {
  1178. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  1179. }
  1180. }
  1181. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  1182. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  1183. const geometry = objects.update( object );
  1184. const material = object.material;
  1185. if ( sortObjects ) {
  1186. if ( object.boundingSphere !== undefined ) {
  1187. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  1188. _vector4.copy( object.boundingSphere.center );
  1189. } else {
  1190. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  1191. _vector4.copy( geometry.boundingSphere.center );
  1192. }
  1193. _vector4
  1194. .applyMatrix4( object.matrixWorld )
  1195. .applyMatrix4( _projScreenMatrix );
  1196. }
  1197. if ( Array.isArray( material ) ) {
  1198. const groups = geometry.groups;
  1199. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  1200. const group = groups[ i ];
  1201. const groupMaterial = material[ group.materialIndex ];
  1202. if ( groupMaterial && groupMaterial.visible ) {
  1203. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  1204. }
  1205. }
  1206. } else if ( material.visible ) {
  1207. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  1208. }
  1209. }
  1210. }
  1211. }
  1212. const children = object.children;
  1213. for ( let i = 0, l = children.length; i < l; i ++ ) {
  1214. projectObject( children[ i ], camera, groupOrder, sortObjects );
  1215. }
  1216. }
  1217. function renderScene( currentRenderList, scene, camera, viewport ) {
  1218. const opaqueObjects = currentRenderList.opaque;
  1219. const transmissiveObjects = currentRenderList.transmissive;
  1220. const transparentObjects = currentRenderList.transparent;
  1221. currentRenderState.setupLightsView( camera );
  1222. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  1223. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  1224. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  1225. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  1226. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  1227. // Ensure depth buffer writing is enabled so it can be cleared on next render
  1228. state.buffers.depth.setTest( true );
  1229. state.buffers.depth.setMask( true );
  1230. state.buffers.color.setMask( true );
  1231. state.setPolygonOffset( false );
  1232. }
  1233. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  1234. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  1235. if ( overrideMaterial !== null ) {
  1236. return;
  1237. }
  1238. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  1239. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  1240. generateMipmaps: true,
  1241. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  1242. minFilter: LinearMipmapLinearFilter,
  1243. samples: 4,
  1244. stencilBuffer: stencil,
  1245. resolveDepthBuffer: false,
  1246. resolveStencilBuffer: false,
  1247. colorSpace: ColorManagement.workingColorSpace,
  1248. } );
  1249. // debug
  1250. /*
  1251. const geometry = new PlaneGeometry();
  1252. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  1253. const mesh = new Mesh( geometry, material );
  1254. scene.add( mesh );
  1255. */
  1256. }
  1257. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  1258. const activeViewport = camera.viewport || _currentViewport;
  1259. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  1260. //
  1261. const currentRenderTarget = _this.getRenderTarget();
  1262. _this.setRenderTarget( transmissionRenderTarget );
  1263. _this.getClearColor( _currentClearColor );
  1264. _currentClearAlpha = _this.getClearAlpha();
  1265. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  1266. _this.clear();
  1267. if ( _renderBackground ) background.render( scene );
  1268. // Turn off the features which can affect the frag color for opaque objects pass.
  1269. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  1270. const currentToneMapping = _this.toneMapping;
  1271. _this.toneMapping = NoToneMapping;
  1272. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  1273. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  1274. const currentCameraViewport = camera.viewport;
  1275. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  1276. currentRenderState.setupLightsView( camera );
  1277. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  1278. renderObjects( opaqueObjects, scene, camera );
  1279. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  1280. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  1281. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  1282. let renderTargetNeedsUpdate = false;
  1283. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  1284. const renderItem = transmissiveObjects[ i ];
  1285. const object = renderItem.object;
  1286. const geometry = renderItem.geometry;
  1287. const material = renderItem.material;
  1288. const group = renderItem.group;
  1289. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  1290. const currentSide = material.side;
  1291. material.side = BackSide;
  1292. material.needsUpdate = true;
  1293. renderObject( object, scene, camera, geometry, material, group );
  1294. material.side = currentSide;
  1295. material.needsUpdate = true;
  1296. renderTargetNeedsUpdate = true;
  1297. }
  1298. }
  1299. if ( renderTargetNeedsUpdate === true ) {
  1300. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  1301. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  1302. }
  1303. }
  1304. _this.setRenderTarget( currentRenderTarget );
  1305. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  1306. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  1307. _this.toneMapping = currentToneMapping;
  1308. }
  1309. function renderObjects( renderList, scene, camera ) {
  1310. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  1311. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  1312. const renderItem = renderList[ i ];
  1313. const object = renderItem.object;
  1314. const geometry = renderItem.geometry;
  1315. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  1316. const group = renderItem.group;
  1317. if ( object.layers.test( camera.layers ) ) {
  1318. renderObject( object, scene, camera, geometry, material, group );
  1319. }
  1320. }
  1321. }
  1322. function renderObject( object, scene, camera, geometry, material, group ) {
  1323. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  1324. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  1325. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  1326. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  1327. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  1328. material.side = BackSide;
  1329. material.needsUpdate = true;
  1330. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  1331. material.side = FrontSide;
  1332. material.needsUpdate = true;
  1333. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  1334. material.side = DoubleSide;
  1335. } else {
  1336. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  1337. }
  1338. object.onAfterRender( _this, scene, camera, geometry, material, group );
  1339. }
  1340. function getProgram( material, scene, object ) {
  1341. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  1342. const materialProperties = properties.get( material );
  1343. const lights = currentRenderState.state.lights;
  1344. const shadowsArray = currentRenderState.state.shadowsArray;
  1345. const lightsStateVersion = lights.state.version;
  1346. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  1347. const programCacheKey = programCache.getProgramCacheKey( parameters );
  1348. let programs = materialProperties.programs;
  1349. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  1350. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  1351. materialProperties.fog = scene.fog;
  1352. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  1353. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  1354. if ( programs === undefined ) {
  1355. // new material
  1356. material.addEventListener( 'dispose', onMaterialDispose );
  1357. programs = new Map();
  1358. materialProperties.programs = programs;
  1359. }
  1360. let program = programs.get( programCacheKey );
  1361. if ( program !== undefined ) {
  1362. // early out if program and light state is identical
  1363. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  1364. updateCommonMaterialProperties( material, parameters );
  1365. return program;
  1366. }
  1367. } else {
  1368. parameters.uniforms = programCache.getUniforms( material );
  1369. material.onBeforeCompile( parameters, _this );
  1370. program = programCache.acquireProgram( parameters, programCacheKey );
  1371. programs.set( programCacheKey, program );
  1372. materialProperties.uniforms = parameters.uniforms;
  1373. }
  1374. const uniforms = materialProperties.uniforms;
  1375. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  1376. uniforms.clippingPlanes = clipping.uniform;
  1377. }
  1378. updateCommonMaterialProperties( material, parameters );
  1379. // store the light setup it was created for
  1380. materialProperties.needsLights = materialNeedsLights( material );
  1381. materialProperties.lightsStateVersion = lightsStateVersion;
  1382. if ( materialProperties.needsLights ) {
  1383. // wire up the material to this renderer's lighting state
  1384. uniforms.ambientLightColor.value = lights.state.ambient;
  1385. uniforms.lightProbe.value = lights.state.probe;
  1386. uniforms.directionalLights.value = lights.state.directional;
  1387. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  1388. uniforms.spotLights.value = lights.state.spot;
  1389. uniforms.spotLightShadows.value = lights.state.spotShadow;
  1390. uniforms.rectAreaLights.value = lights.state.rectArea;
  1391. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  1392. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  1393. uniforms.pointLights.value = lights.state.point;
  1394. uniforms.pointLightShadows.value = lights.state.pointShadow;
  1395. uniforms.hemisphereLights.value = lights.state.hemi;
  1396. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  1397. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  1398. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  1399. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  1400. uniforms.spotLightMap.value = lights.state.spotLightMap;
  1401. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  1402. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  1403. // TODO (abelnation): add area lights shadow info to uniforms
  1404. }
  1405. materialProperties.currentProgram = program;
  1406. materialProperties.uniformsList = null;
  1407. return program;
  1408. }
  1409. function getUniformList( materialProperties ) {
  1410. if ( materialProperties.uniformsList === null ) {
  1411. const progUniforms = materialProperties.currentProgram.getUniforms();
  1412. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  1413. }
  1414. return materialProperties.uniformsList;
  1415. }
  1416. function updateCommonMaterialProperties( material, parameters ) {
  1417. const materialProperties = properties.get( material );
  1418. materialProperties.outputColorSpace = parameters.outputColorSpace;
  1419. materialProperties.batching = parameters.batching;
  1420. materialProperties.batchingColor = parameters.batchingColor;
  1421. materialProperties.instancing = parameters.instancing;
  1422. materialProperties.instancingColor = parameters.instancingColor;
  1423. materialProperties.instancingMorph = parameters.instancingMorph;
  1424. materialProperties.skinning = parameters.skinning;
  1425. materialProperties.morphTargets = parameters.morphTargets;
  1426. materialProperties.morphNormals = parameters.morphNormals;
  1427. materialProperties.morphColors = parameters.morphColors;
  1428. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  1429. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  1430. materialProperties.numIntersection = parameters.numClipIntersection;
  1431. materialProperties.vertexAlphas = parameters.vertexAlphas;
  1432. materialProperties.vertexTangents = parameters.vertexTangents;
  1433. materialProperties.toneMapping = parameters.toneMapping;
  1434. }
  1435. function setProgram( camera, scene, geometry, material, object ) {
  1436. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  1437. textures.resetTextureUnits();
  1438. const fog = scene.fog;
  1439. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  1440. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  1441. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  1442. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  1443. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  1444. const morphTargets = !! geometry.morphAttributes.position;
  1445. const morphNormals = !! geometry.morphAttributes.normal;
  1446. const morphColors = !! geometry.morphAttributes.color;
  1447. let toneMapping = NoToneMapping;
  1448. if ( material.toneMapped ) {
  1449. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  1450. toneMapping = _this.toneMapping;
  1451. }
  1452. }
  1453. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  1454. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  1455. const materialProperties = properties.get( material );
  1456. const lights = currentRenderState.state.lights;
  1457. if ( _clippingEnabled === true ) {
  1458. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  1459. const useCache =
  1460. camera === _currentCamera &&
  1461. material.id === _currentMaterialId;
  1462. // we might want to call this function with some ClippingGroup
  1463. // object instead of the material, once it becomes feasible
  1464. // (#8465, #8379)
  1465. clipping.setState( material, camera, useCache );
  1466. }
  1467. }
  1468. //
  1469. let needsProgramChange = false;
  1470. if ( material.version === materialProperties.__version ) {
  1471. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  1472. needsProgramChange = true;
  1473. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  1474. needsProgramChange = true;
  1475. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  1476. needsProgramChange = true;
  1477. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  1478. needsProgramChange = true;
  1479. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  1480. needsProgramChange = true;
  1481. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  1482. needsProgramChange = true;
  1483. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  1484. needsProgramChange = true;
  1485. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  1486. needsProgramChange = true;
  1487. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  1488. needsProgramChange = true;
  1489. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  1490. needsProgramChange = true;
  1491. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  1492. needsProgramChange = true;
  1493. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  1494. needsProgramChange = true;
  1495. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  1496. needsProgramChange = true;
  1497. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  1498. needsProgramChange = true;
  1499. } else if ( materialProperties.envMap !== envMap ) {
  1500. needsProgramChange = true;
  1501. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  1502. needsProgramChange = true;
  1503. } else if ( materialProperties.numClippingPlanes !== undefined &&
  1504. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  1505. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  1506. needsProgramChange = true;
  1507. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  1508. needsProgramChange = true;
  1509. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  1510. needsProgramChange = true;
  1511. } else if ( materialProperties.morphTargets !== morphTargets ) {
  1512. needsProgramChange = true;
  1513. } else if ( materialProperties.morphNormals !== morphNormals ) {
  1514. needsProgramChange = true;
  1515. } else if ( materialProperties.morphColors !== morphColors ) {
  1516. needsProgramChange = true;
  1517. } else if ( materialProperties.toneMapping !== toneMapping ) {
  1518. needsProgramChange = true;
  1519. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  1520. needsProgramChange = true;
  1521. }
  1522. } else {
  1523. needsProgramChange = true;
  1524. materialProperties.__version = material.version;
  1525. }
  1526. //
  1527. let program = materialProperties.currentProgram;
  1528. if ( needsProgramChange === true ) {
  1529. program = getProgram( material, scene, object );
  1530. }
  1531. let refreshProgram = false;
  1532. let refreshMaterial = false;
  1533. let refreshLights = false;
  1534. const p_uniforms = program.getUniforms(),
  1535. m_uniforms = materialProperties.uniforms;
  1536. if ( state.useProgram( program.program ) ) {
  1537. refreshProgram = true;
  1538. refreshMaterial = true;
  1539. refreshLights = true;
  1540. }
  1541. if ( material.id !== _currentMaterialId ) {
  1542. _currentMaterialId = material.id;
  1543. refreshMaterial = true;
  1544. }
  1545. if ( refreshProgram || _currentCamera !== camera ) {
  1546. // common camera uniforms
  1547. const reverseDepthBuffer = state.buffers.depth.getReversed();
  1548. if ( reverseDepthBuffer ) {
  1549. _currentProjectionMatrix.copy( camera.projectionMatrix );
  1550. toNormalizedProjectionMatrix( _currentProjectionMatrix );
  1551. toReversedProjectionMatrix( _currentProjectionMatrix );
  1552. p_uniforms.setValue( _gl, 'projectionMatrix', _currentProjectionMatrix );
  1553. } else {
  1554. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  1555. }
  1556. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1557. const uCamPos = p_uniforms.map.cameraPosition;
  1558. if ( uCamPos !== undefined ) {
  1559. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1560. }
  1561. if ( capabilities.logarithmicDepthBuffer ) {
  1562. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1563. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1564. }
  1565. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  1566. if ( material.isMeshPhongMaterial ||
  1567. material.isMeshToonMaterial ||
  1568. material.isMeshLambertMaterial ||
  1569. material.isMeshBasicMaterial ||
  1570. material.isMeshStandardMaterial ||
  1571. material.isShaderMaterial ) {
  1572. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  1573. }
  1574. if ( _currentCamera !== camera ) {
  1575. _currentCamera = camera;
  1576. // lighting uniforms depend on the camera so enforce an update
  1577. // now, in case this material supports lights - or later, when
  1578. // the next material that does gets activated:
  1579. refreshMaterial = true; // set to true on material change
  1580. refreshLights = true; // remains set until update done
  1581. }
  1582. }
  1583. // skinning and morph target uniforms must be set even if material didn't change
  1584. // auto-setting of texture unit for bone and morph texture must go before other textures
  1585. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  1586. if ( object.isSkinnedMesh ) {
  1587. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1588. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1589. const skeleton = object.skeleton;
  1590. if ( skeleton ) {
  1591. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  1592. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  1593. }
  1594. }
  1595. if ( object.isBatchedMesh ) {
  1596. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  1597. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  1598. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  1599. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  1600. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  1601. if ( object._colorsTexture !== null ) {
  1602. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  1603. }
  1604. }
  1605. const morphAttributes = geometry.morphAttributes;
  1606. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  1607. morphtargets.update( object, geometry, program );
  1608. }
  1609. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  1610. materialProperties.receiveShadow = object.receiveShadow;
  1611. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  1612. }
  1613. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  1614. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  1615. m_uniforms.envMap.value = envMap;
  1616. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  1617. }
  1618. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  1619. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  1620. }
  1621. if ( refreshMaterial ) {
  1622. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  1623. if ( materialProperties.needsLights ) {
  1624. // the current material requires lighting info
  1625. // note: all lighting uniforms are always set correctly
  1626. // they simply reference the renderer's state for their
  1627. // values
  1628. //
  1629. // use the current material's .needsUpdate flags to set
  1630. // the GL state when required
  1631. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1632. }
  1633. // refresh uniforms common to several materials
  1634. if ( fog && material.fog === true ) {
  1635. materials.refreshFogUniforms( m_uniforms, fog );
  1636. }
  1637. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  1638. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  1639. }
  1640. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  1641. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  1642. material.uniformsNeedUpdate = false;
  1643. }
  1644. if ( material.isSpriteMaterial ) {
  1645. p_uniforms.setValue( _gl, 'center', object.center );
  1646. }
  1647. // common matrices
  1648. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1649. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1650. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1651. // UBOs
  1652. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  1653. const groups = material.uniformsGroups;
  1654. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  1655. const group = groups[ i ];
  1656. uniformsGroups.update( group, program );
  1657. uniformsGroups.bind( group, program );
  1658. }
  1659. }
  1660. return program;
  1661. }
  1662. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1663. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1664. uniforms.ambientLightColor.needsUpdate = value;
  1665. uniforms.lightProbe.needsUpdate = value;
  1666. uniforms.directionalLights.needsUpdate = value;
  1667. uniforms.directionalLightShadows.needsUpdate = value;
  1668. uniforms.pointLights.needsUpdate = value;
  1669. uniforms.pointLightShadows.needsUpdate = value;
  1670. uniforms.spotLights.needsUpdate = value;
  1671. uniforms.spotLightShadows.needsUpdate = value;
  1672. uniforms.rectAreaLights.needsUpdate = value;
  1673. uniforms.hemisphereLights.needsUpdate = value;
  1674. }
  1675. function materialNeedsLights( material ) {
  1676. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  1677. material.isMeshStandardMaterial || material.isShadowMaterial ||
  1678. ( material.isShaderMaterial && material.lights === true );
  1679. }
  1680. /**
  1681. * Returns the active cube face.
  1682. *
  1683. * @return {number} The active cube face.
  1684. */
  1685. this.getActiveCubeFace = function () {
  1686. return _currentActiveCubeFace;
  1687. };
  1688. /**
  1689. * Returns the active mipmap level.
  1690. *
  1691. * @return {number} The active mipmap level.
  1692. */
  1693. this.getActiveMipmapLevel = function () {
  1694. return _currentActiveMipmapLevel;
  1695. };
  1696. /**
  1697. * Returns the active render target.
  1698. *
  1699. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  1700. * is currently set.
  1701. */
  1702. this.getRenderTarget = function () {
  1703. return _currentRenderTarget;
  1704. };
  1705. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  1706. const renderTargetProperties = properties.get( renderTarget );
  1707. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  1708. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  1709. // The multisample_render_to_texture extension doesn't work properly if there
  1710. // are midframe flushes and an external depth buffer. Disable use of the extension.
  1711. renderTargetProperties.__useRenderToTexture = false;
  1712. }
  1713. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  1714. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  1715. renderTargetProperties.__hasExternalTextures = true;
  1716. };
  1717. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  1718. const renderTargetProperties = properties.get( renderTarget );
  1719. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  1720. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  1721. };
  1722. const _scratchFrameBuffer = _gl.createFramebuffer();
  1723. /**
  1724. * Sets the active rendertarget.
  1725. *
  1726. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  1727. * the canvas is set as the active render target instead.
  1728. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  1729. * Indicates the z layer to render in to when using 3D or array render targets.
  1730. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  1731. */
  1732. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  1733. _currentRenderTarget = renderTarget;
  1734. _currentActiveCubeFace = activeCubeFace;
  1735. _currentActiveMipmapLevel = activeMipmapLevel;
  1736. let useDefaultFramebuffer = true;
  1737. let framebuffer = null;
  1738. let isCube = false;
  1739. let isRenderTarget3D = false;
  1740. if ( renderTarget ) {
  1741. const renderTargetProperties = properties.get( renderTarget );
  1742. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  1743. // We need to make sure to rebind the framebuffer.
  1744. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1745. useDefaultFramebuffer = false;
  1746. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  1747. textures.setupRenderTarget( renderTarget );
  1748. } else if ( renderTargetProperties.__hasExternalTextures ) {
  1749. // Color and depth texture must be rebound in order for the swapchain to update.
  1750. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  1751. } else if ( renderTarget.depthBuffer ) {
  1752. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  1753. const depthTexture = renderTarget.depthTexture;
  1754. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  1755. // check if the depth texture is compatible
  1756. if (
  1757. depthTexture !== null &&
  1758. properties.has( depthTexture ) &&
  1759. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  1760. ) {
  1761. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  1762. }
  1763. // Swap the depth buffer to the currently attached one
  1764. textures.setupDepthRenderbuffer( renderTarget );
  1765. }
  1766. }
  1767. const texture = renderTarget.texture;
  1768. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  1769. isRenderTarget3D = true;
  1770. }
  1771. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1772. if ( renderTarget.isWebGLCubeRenderTarget ) {
  1773. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  1774. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  1775. } else {
  1776. framebuffer = __webglFramebuffer[ activeCubeFace ];
  1777. }
  1778. isCube = true;
  1779. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  1780. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  1781. } else {
  1782. if ( Array.isArray( __webglFramebuffer ) ) {
  1783. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  1784. } else {
  1785. framebuffer = __webglFramebuffer;
  1786. }
  1787. }
  1788. _currentViewport.copy( renderTarget.viewport );
  1789. _currentScissor.copy( renderTarget.scissor );
  1790. _currentScissorTest = renderTarget.scissorTest;
  1791. } else {
  1792. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  1793. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  1794. _currentScissorTest = _scissorTest;
  1795. }
  1796. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  1797. // being bound that are different sizes.
  1798. if ( activeMipmapLevel !== 0 ) {
  1799. framebuffer = _scratchFrameBuffer;
  1800. }
  1801. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1802. if ( framebufferBound && useDefaultFramebuffer ) {
  1803. state.drawBuffers( renderTarget, framebuffer );
  1804. }
  1805. state.viewport( _currentViewport );
  1806. state.scissor( _currentScissor );
  1807. state.setScissorTest( _currentScissorTest );
  1808. if ( isCube ) {
  1809. const textureProperties = properties.get( renderTarget.texture );
  1810. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  1811. } else if ( isRenderTarget3D ) {
  1812. const textureProperties = properties.get( renderTarget.texture );
  1813. const layer = activeCubeFace;
  1814. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer );
  1815. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  1816. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  1817. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  1818. const textureProperties = properties.get( renderTarget.texture );
  1819. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  1820. }
  1821. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  1822. };
  1823. /**
  1824. * Reads the pixel data from the given render target into the given buffer.
  1825. *
  1826. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  1827. * @param {number} x - The `x` coordinate of the copy region's origin.
  1828. * @param {number} y - The `y` coordinate of the copy region's origin.
  1829. * @param {number} width - The width of the copy region.
  1830. * @param {number} height - The height of the copy region.
  1831. * @param {TypedArray} buffer - The result buffer.
  1832. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  1833. */
  1834. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1835. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1836. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1837. return;
  1838. }
  1839. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1840. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  1841. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1842. }
  1843. if ( framebuffer ) {
  1844. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1845. try {
  1846. const texture = renderTarget.texture;
  1847. const textureFormat = texture.format;
  1848. const textureType = texture.type;
  1849. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  1850. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1851. return;
  1852. }
  1853. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  1854. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1855. return;
  1856. }
  1857. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1858. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1859. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  1860. }
  1861. } finally {
  1862. // restore framebuffer of current render target if necessary
  1863. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  1864. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1865. }
  1866. }
  1867. };
  1868. /**
  1869. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  1870. *
  1871. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  1872. *
  1873. * @async
  1874. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  1875. * @param {number} x - The `x` coordinate of the copy region's origin.
  1876. * @param {number} y - The `y` coordinate of the copy region's origin.
  1877. * @param {number} width - The width of the copy region.
  1878. * @param {number} height - The height of the copy region.
  1879. * @param {TypedArray} buffer - The result buffer.
  1880. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  1881. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  1882. */
  1883. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1884. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1885. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1886. }
  1887. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1888. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  1889. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1890. }
  1891. if ( framebuffer ) {
  1892. const texture = renderTarget.texture;
  1893. const textureFormat = texture.format;
  1894. const textureType = texture.type;
  1895. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  1896. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  1897. }
  1898. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  1899. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1900. }
  1901. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1902. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1903. // set the active frame buffer to the one we want to read
  1904. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1905. const glBuffer = _gl.createBuffer();
  1906. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  1907. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  1908. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  1909. // reset the frame buffer to the currently set buffer before waiting
  1910. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  1911. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  1912. // check if the commands have finished every 8 ms
  1913. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  1914. _gl.flush();
  1915. await probeAsync( _gl, sync, 4 );
  1916. // read the data and delete the buffer
  1917. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  1918. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  1919. _gl.deleteBuffer( glBuffer );
  1920. _gl.deleteSync( sync );
  1921. return buffer;
  1922. } else {
  1923. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  1924. }
  1925. }
  1926. };
  1927. /**
  1928. * Copies pixels from the current bound framebuffer into the given texture.
  1929. *
  1930. * @param {FramebufferTexture} texture - The texture.
  1931. * @param {Vector2} position - The start position of the copy operation.
  1932. * @param {number} [level=0] - The mip level. The default represents the base mip.
  1933. */
  1934. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  1935. const levelScale = Math.pow( 2, - level );
  1936. const width = Math.floor( texture.image.width * levelScale );
  1937. const height = Math.floor( texture.image.height * levelScale );
  1938. const x = position !== null ? position.x : 0;
  1939. const y = position !== null ? position.y : 0;
  1940. textures.setTexture2D( texture, 0 );
  1941. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  1942. state.unbindTexture();
  1943. };
  1944. const _srcFramebuffer = _gl.createFramebuffer();
  1945. const _dstFramebuffer = _gl.createFramebuffer();
  1946. /**
  1947. * Copies data of the given source texture into a destination texture.
  1948. *
  1949. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  1950. * {@link WebGLRenderer#initRenderTarget}.
  1951. *
  1952. * @param {Texture} srcTexture - The source texture.
  1953. * @param {Texture} dstTexture - The destination texture.
  1954. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  1955. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  1956. * @param {number} srcLevel - The source mipmap level to copy.
  1957. * @param {number} dstLevel - The destination mipmap level.
  1958. */
  1959. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  1960. // support the previous signature with just a single dst mipmap level
  1961. if ( dstLevel === null ) {
  1962. if ( srcLevel !== 0 ) {
  1963. // @deprecated, r171
  1964. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  1965. dstLevel = srcLevel;
  1966. srcLevel = 0;
  1967. } else {
  1968. dstLevel = 0;
  1969. }
  1970. }
  1971. // gather the necessary dimensions to copy
  1972. let width, height, depth, minX, minY, minZ;
  1973. let dstX, dstY, dstZ;
  1974. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  1975. if ( srcRegion !== null ) {
  1976. width = srcRegion.max.x - srcRegion.min.x;
  1977. height = srcRegion.max.y - srcRegion.min.y;
  1978. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  1979. minX = srcRegion.min.x;
  1980. minY = srcRegion.min.y;
  1981. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  1982. } else {
  1983. const levelScale = Math.pow( 2, - srcLevel );
  1984. width = Math.floor( image.width * levelScale );
  1985. height = Math.floor( image.height * levelScale );
  1986. if ( srcTexture.isDataArrayTexture ) {
  1987. depth = image.depth;
  1988. } else if ( srcTexture.isData3DTexture ) {
  1989. depth = Math.floor( image.depth * levelScale );
  1990. } else {
  1991. depth = 1;
  1992. }
  1993. minX = 0;
  1994. minY = 0;
  1995. minZ = 0;
  1996. }
  1997. if ( dstPosition !== null ) {
  1998. dstX = dstPosition.x;
  1999. dstY = dstPosition.y;
  2000. dstZ = dstPosition.z;
  2001. } else {
  2002. dstX = 0;
  2003. dstY = 0;
  2004. dstZ = 0;
  2005. }
  2006. // Set up the destination target
  2007. const glFormat = utils.convert( dstTexture.format );
  2008. const glType = utils.convert( dstTexture.type );
  2009. let glTarget;
  2010. if ( dstTexture.isData3DTexture ) {
  2011. textures.setTexture3D( dstTexture, 0 );
  2012. glTarget = _gl.TEXTURE_3D;
  2013. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  2014. textures.setTexture2DArray( dstTexture, 0 );
  2015. glTarget = _gl.TEXTURE_2D_ARRAY;
  2016. } else {
  2017. textures.setTexture2D( dstTexture, 0 );
  2018. glTarget = _gl.TEXTURE_2D;
  2019. }
  2020. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  2021. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  2022. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  2023. // used for copying data from cpu
  2024. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  2025. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  2026. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  2027. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  2028. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  2029. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  2030. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  2031. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  2032. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  2033. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  2034. // set up the src texture
  2035. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  2036. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  2037. if ( srcTexture.isDepthTexture ) {
  2038. const srcTextureProperties = properties.get( srcTexture );
  2039. const dstTextureProperties = properties.get( dstTexture );
  2040. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  2041. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  2042. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  2043. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  2044. for ( let i = 0; i < depth; i ++ ) {
  2045. // if the source or destination are a 3d target then a layer needs to be bound
  2046. if ( isSrc3D ) {
  2047. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  2048. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  2049. }
  2050. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  2051. }
  2052. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  2053. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  2054. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  2055. // get the appropriate frame buffers
  2056. const srcTextureProperties = properties.get( srcTexture );
  2057. const dstTextureProperties = properties.get( dstTexture );
  2058. // bind the frame buffer targets
  2059. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  2060. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  2061. for ( let i = 0; i < depth; i ++ ) {
  2062. // assign the correct layers and mip maps to the frame buffers
  2063. if ( isSrc3D ) {
  2064. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  2065. } else {
  2066. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  2067. }
  2068. if ( isDst3D ) {
  2069. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  2070. } else {
  2071. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  2072. }
  2073. // copy the data using the fastest function that can achieve the copy
  2074. if ( srcLevel !== 0 ) {
  2075. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  2076. } else if ( isDst3D ) {
  2077. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  2078. } else {
  2079. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  2080. }
  2081. }
  2082. // unbind read, draw buffers
  2083. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  2084. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  2085. } else {
  2086. if ( isDst3D ) {
  2087. // copy data into the 3d texture
  2088. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  2089. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  2090. } else if ( dstTexture.isCompressedArrayTexture ) {
  2091. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  2092. } else {
  2093. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  2094. }
  2095. } else {
  2096. // copy data into the 2d texture
  2097. if ( srcTexture.isDataTexture ) {
  2098. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  2099. } else if ( srcTexture.isCompressedTexture ) {
  2100. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  2101. } else {
  2102. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  2103. }
  2104. }
  2105. }
  2106. // reset values
  2107. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  2108. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  2109. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  2110. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  2111. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  2112. // Generate mipmaps only when copying level 0
  2113. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  2114. _gl.generateMipmap( glTarget );
  2115. }
  2116. state.unbindTexture();
  2117. };
  2118. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  2119. // @deprecated, r170
  2120. warnOnce( 'WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.' );
  2121. return this.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  2122. };
  2123. /**
  2124. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  2125. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  2126. * rendered to.
  2127. *
  2128. * @param {WebGLRenderTarget} target - The render target.
  2129. */
  2130. this.initRenderTarget = function ( target ) {
  2131. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  2132. textures.setupRenderTarget( target );
  2133. }
  2134. };
  2135. /**
  2136. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  2137. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  2138. *
  2139. * @param {Texture} texture - The texture.
  2140. */
  2141. this.initTexture = function ( texture ) {
  2142. if ( texture.isCubeTexture ) {
  2143. textures.setTextureCube( texture, 0 );
  2144. } else if ( texture.isData3DTexture ) {
  2145. textures.setTexture3D( texture, 0 );
  2146. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  2147. textures.setTexture2DArray( texture, 0 );
  2148. } else {
  2149. textures.setTexture2D( texture, 0 );
  2150. }
  2151. state.unbindTexture();
  2152. };
  2153. /**
  2154. * Can be used to reset the internal WebGL state. This method is mostly
  2155. * relevant for applications which share a single WebGL context across
  2156. * multiple WebGL libraries.
  2157. */
  2158. this.resetState = function () {
  2159. _currentActiveCubeFace = 0;
  2160. _currentActiveMipmapLevel = 0;
  2161. _currentRenderTarget = null;
  2162. state.reset();
  2163. bindingStates.reset();
  2164. };
  2165. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  2166. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  2167. }
  2168. }
  2169. /**
  2170. * Defines the coordinate system of the renderer.
  2171. *
  2172. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  2173. *
  2174. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  2175. * @default WebGLCoordinateSystem
  2176. * @readonly
  2177. */
  2178. get coordinateSystem() {
  2179. return WebGLCoordinateSystem;
  2180. }
  2181. /**
  2182. * Defines the output color space of the renderer.
  2183. *
  2184. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  2185. * @default SRGBColorSpace
  2186. */
  2187. get outputColorSpace() {
  2188. return this._outputColorSpace;
  2189. }
  2190. set outputColorSpace( colorSpace ) {
  2191. this._outputColorSpace = colorSpace;
  2192. const gl = this.getContext();
  2193. gl.drawingBufferColorspace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  2194. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  2195. }
  2196. }
  2197. // JSDoc
  2198. /**
  2199. * WebGLRenderer options.
  2200. *
  2201. * @typedef {Object} WebGLRenderer~Options
  2202. * @property {DOMElement} [canvas=null] - A canvas element where the renderer draws its output. If not passed in here, a new canvas element will be created by the renderer.
  2203. * @property {WebGL2RenderingContext} [context=null] - Can be used to attach an existing rendering context to this renderer.
  2204. * @property {('highp'|'mediump'|'lowp')} [precision='highp'] - The default shader precision. Uses `highp` if supported by the device.
  2205. * @property {boolean} [alpha=false] - Controls the default clear alpha value. When set to`true`, the value is `0`. Otherwise it's `1`.
  2206. * @property {boolean} [premultipliedAlpha=true] Whether the renderer will assume colors have premultiplied alpha or not.
  2207. * @property {boolean} [antialias=false] Whether to use the default MSAA or not.
  2208. * @property {boolean} [stencil=false] Whether the drawing buffer has a stencil buffer of at least 8 bits or not.
  2209. * @property {boolean} [preserveDrawingBuffer=false] Whether to preserve the buffer until manually cleared or overwritten.
  2210. * @property {('default'|'low-power'|'high-performance')} [powerPreference='default'] Provides a hint to the user agent indicating what configuration of GPU is suitable for this WebGL context.
  2211. * @property {boolean} [failIfMajorPerformanceCaveat=false] Whether the renderer creation will fail upon low performance is detected.
  2212. * @property {boolean} [depth=true] Whether the drawing buffer has a depth buffer of at least 16 bits.
  2213. * @property {boolean} [logarithmicDepthBuffer=false] Whether to use a logarithmic depth buffer. It may be necessary to use this if dealing with huge differences in scale in a single scene.
  2214. * Note that this setting uses `gl_FragDepth` if available which disables the Early Fragment Test optimization and can cause a decrease in performance.
  2215. * @property {boolean} [reverseDepthBuffer=false] Whether to use a reverse depth buffer. Requires the `EXT_clip_control` extension.
  2216. * This is a more faster and accurate version than logarithmic depth buffer.
  2217. **/
  2218. /**
  2219. * WebGLRenderer Capabilities.
  2220. *
  2221. * @typedef {Object} WebGLRenderer~Capabilities
  2222. * @property {Function} getMaxAnisotropy - Returns the maximum available anisotropy.
  2223. * @property {Function} getMaxPrecision - Returns the maximum available precision for vertex and fragment shaders.
  2224. * @property {boolean} logarithmicDepthBuffer - `true` if `logarithmicDepthBuffer` was set to `true` in the constructor.
  2225. * @property {number} maxAttributes - The number of shader attributes that can be used by the vertex shader.
  2226. * @property {number} maxCubemapSize - Maximum height * width of cube map textures that a shader can use.
  2227. * @property {number} maxFragmentUniforms - The number of uniforms that can be used by a fragment shader.
  2228. * @property {number} maxSamples - Maximum number of samples in context of Multisample anti-aliasing (MSAA).
  2229. * @property {number} maxTextures - The maximum number of textures that can be used by a shader.
  2230. * @property {number} maxTextureSize - Maximum height * width of a texture that a shader use.
  2231. * @property {number} maxVaryings - The number of varying vectors that can used by shaders.
  2232. * @property {number} maxVertexTextures - The number of textures that can be used in a vertex shader.
  2233. * @property {number} maxVertexUniforms - The maximum number of uniforms that can be used in a vertex shader.
  2234. * @property {string} precision - The shader precision currently being used by the renderer.
  2235. * @property {boolean} reverseDepthBuffer - `true` if `reverseDepthBuffer` was set to `true` in the constructor
  2236. * and the rendering context supports `EXT_clip_control`.
  2237. * @property {boolean} vertexTextures - `true` if vertex textures can be used.
  2238. **/
  2239. /**
  2240. * WebGLRenderer Info Memory
  2241. *
  2242. * @typedef {Object} WebGLRenderer~InfoMemory
  2243. * @property {number} geometries - The number of active geometries.
  2244. * @property {number} textures - The number of active textures.
  2245. **/
  2246. /**
  2247. * WebGLRenderer Info Render
  2248. *
  2249. * @typedef {Object} WebGLRenderer~InfoRender
  2250. * @property {number} frame - The frame ID.
  2251. * @property {number} calls - The number of draw calls per frame.
  2252. * @property {number} triangles - The number of rendered triangles primitives per frame.
  2253. * @property {number} points - The number of rendered points primitives per frame.
  2254. * @property {number} lines - The number of rendered lines primitives per frame.
  2255. **/
  2256. /**
  2257. * WebGLRenderer Info
  2258. *
  2259. * @typedef {Object} WebGLRenderer~Info
  2260. * @property {boolean} [autoReset=true] - Whether to automatically reset the info by the renderer or not.
  2261. * @property {WebGLRenderer~InfoMemory} memory - Information about allocated objects.
  2262. * @property {WebGLRenderer~InfoRender} render - Information about rendered objects.
  2263. * @property {?Array<WebGLProgram>} programs - An array `WebGLProgram`s used for rendering.
  2264. * @property {Function} reset - Resets the info object for the next frame.
  2265. **/
  2266. /**
  2267. * WebGLRenderer Shadow Map.
  2268. *
  2269. * @typedef {Object} WebGLRenderer~ShadowMap
  2270. * @property {boolean} [enabled=false] - If set to `true`, use shadow maps in the scene.
  2271. * @property {boolean} [autoUpdate=true] - Enables automatic updates to the shadows in the scene.
  2272. * If you do not require dynamic lighting / shadows, you may set this to `false`.
  2273. * @property {boolean} [needsUpdate=false] - When set to `true`, shadow maps in the scene
  2274. * will be updated in the next `render` call.
  2275. * @property {(BasicShadowMap|PCFShadowMap|PCFSoftShadowMap|VSMShadowMap)} [type=PCFShadowMap] - Defines the shadow map type.
  2276. **/
  2277. export { WebGLRenderer };
粤ICP备19079148号