WebGLRenderer.js 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781
  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. DisplayP3ColorSpace,
  22. LinearDisplayP3ColorSpace
  23. } from '../constants.js';
  24. import { Color } from '../math/Color.js';
  25. import { Frustum } from '../math/Frustum.js';
  26. import { Matrix4 } from '../math/Matrix4.js';
  27. import { Vector3 } from '../math/Vector3.js';
  28. import { Vector4 } from '../math/Vector4.js';
  29. import { WebGLAnimation } from './webgl/WebGLAnimation.js';
  30. import { WebGLAttributes } from './webgl/WebGLAttributes.js';
  31. import { WebGLBackground } from './webgl/WebGLBackground.js';
  32. import { WebGLBindingStates } from './webgl/WebGLBindingStates.js';
  33. import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer.js';
  34. import { WebGLCapabilities } from './webgl/WebGLCapabilities.js';
  35. import { WebGLClipping } from './webgl/WebGLClipping.js';
  36. import { WebGLCubeMaps } from './webgl/WebGLCubeMaps.js';
  37. import { WebGLCubeUVMaps } from './webgl/WebGLCubeUVMaps.js';
  38. import { WebGLExtensions } from './webgl/WebGLExtensions.js';
  39. import { WebGLGeometries } from './webgl/WebGLGeometries.js';
  40. import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer.js';
  41. import { WebGLInfo } from './webgl/WebGLInfo.js';
  42. import { WebGLMorphtargets } from './webgl/WebGLMorphtargets.js';
  43. import { WebGLObjects } from './webgl/WebGLObjects.js';
  44. import { WebGLPrograms } from './webgl/WebGLPrograms.js';
  45. import { WebGLProperties } from './webgl/WebGLProperties.js';
  46. import { WebGLRenderLists } from './webgl/WebGLRenderLists.js';
  47. import { WebGLRenderStates } from './webgl/WebGLRenderStates.js';
  48. import { WebGLRenderTarget } from './WebGLRenderTarget.js';
  49. import { WebGLShadowMap } from './webgl/WebGLShadowMap.js';
  50. import { WebGLState } from './webgl/WebGLState.js';
  51. import { WebGLTextures } from './webgl/WebGLTextures.js';
  52. import { WebGLUniforms } from './webgl/WebGLUniforms.js';
  53. import { WebGLUtils } from './webgl/WebGLUtils.js';
  54. import { WebXRManager } from './webxr/WebXRManager.js';
  55. import { WebGLMaterials } from './webgl/WebGLMaterials.js';
  56. import { WebGLUniformsGroups } from './webgl/WebGLUniformsGroups.js';
  57. import { createCanvasElement, probeAsync } from '../utils.js';
  58. import { ColorManagement } from '../math/ColorManagement.js';
  59. class WebGLRenderer {
  60. constructor( parameters = {} ) {
  61. const {
  62. canvas = createCanvasElement(),
  63. context = null,
  64. depth = true,
  65. stencil = false,
  66. alpha = false,
  67. antialias = false,
  68. premultipliedAlpha = true,
  69. preserveDrawingBuffer = false,
  70. powerPreference = 'default',
  71. failIfMajorPerformanceCaveat = false,
  72. } = parameters;
  73. this.isWebGLRenderer = true;
  74. let _alpha;
  75. if ( context !== null ) {
  76. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  77. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  78. }
  79. _alpha = context.getContextAttributes().alpha;
  80. } else {
  81. _alpha = alpha;
  82. }
  83. const uintClearColor = new Uint32Array( 4 );
  84. const intClearColor = new Int32Array( 4 );
  85. let currentRenderList = null;
  86. let currentRenderState = null;
  87. // render() can be called from within a callback triggered by another render.
  88. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  89. const renderListStack = [];
  90. const renderStateStack = [];
  91. // public properties
  92. this.domElement = canvas;
  93. // Debug configuration container
  94. this.debug = {
  95. /**
  96. * Enables error checking and reporting when shader programs are being compiled
  97. * @type {boolean}
  98. */
  99. checkShaderErrors: true,
  100. /**
  101. * Callback for custom error reporting.
  102. * @type {?Function}
  103. */
  104. onShaderError: null
  105. };
  106. // clearing
  107. this.autoClear = true;
  108. this.autoClearColor = true;
  109. this.autoClearDepth = true;
  110. this.autoClearStencil = true;
  111. // scene graph
  112. this.sortObjects = true;
  113. // user-defined clipping
  114. this.clippingPlanes = [];
  115. this.localClippingEnabled = false;
  116. // physically based shading
  117. this._outputColorSpace = SRGBColorSpace;
  118. // physical lights
  119. this._useLegacyLights = false;
  120. // tone mapping
  121. this.toneMapping = NoToneMapping;
  122. this.toneMappingExposure = 1.0;
  123. // internal properties
  124. const _this = this;
  125. let _isContextLost = false;
  126. // internal state cache
  127. let _currentActiveCubeFace = 0;
  128. let _currentActiveMipmapLevel = 0;
  129. let _currentRenderTarget = null;
  130. let _currentMaterialId = - 1;
  131. let _currentCamera = null;
  132. const _currentViewport = new Vector4();
  133. const _currentScissor = new Vector4();
  134. let _currentScissorTest = null;
  135. const _currentClearColor = new Color( 0x000000 );
  136. let _currentClearAlpha = 0;
  137. //
  138. let _width = canvas.width;
  139. let _height = canvas.height;
  140. let _pixelRatio = 1;
  141. let _opaqueSort = null;
  142. let _transparentSort = null;
  143. const _viewport = new Vector4( 0, 0, _width, _height );
  144. const _scissor = new Vector4( 0, 0, _width, _height );
  145. let _scissorTest = false;
  146. // frustum
  147. const _frustum = new Frustum();
  148. // clipping
  149. let _clippingEnabled = false;
  150. let _localClippingEnabled = false;
  151. // camera matrices cache
  152. const _projScreenMatrix = new Matrix4();
  153. const _vector3 = new Vector3();
  154. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  155. function getTargetPixelRatio() {
  156. return _currentRenderTarget === null ? _pixelRatio : 1;
  157. }
  158. // initialize
  159. let _gl = context;
  160. function getContext( contextName, contextAttributes ) {
  161. return canvas.getContext( contextName, contextAttributes );
  162. }
  163. try {
  164. const contextAttributes = {
  165. alpha: true,
  166. depth,
  167. stencil,
  168. antialias,
  169. premultipliedAlpha,
  170. preserveDrawingBuffer,
  171. powerPreference,
  172. failIfMajorPerformanceCaveat,
  173. };
  174. // OffscreenCanvas does not have setAttribute, see #22811
  175. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  176. // event listeners must be registered before WebGL context is created, see #12753
  177. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  178. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  179. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  180. if ( _gl === null ) {
  181. const contextName = 'webgl2';
  182. _gl = getContext( contextName, contextAttributes );
  183. if ( _gl === null ) {
  184. if ( getContext( contextName ) ) {
  185. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  186. } else {
  187. throw new Error( 'Error creating WebGL context.' );
  188. }
  189. }
  190. }
  191. } catch ( error ) {
  192. console.error( 'THREE.WebGLRenderer: ' + error.message );
  193. throw error;
  194. }
  195. let extensions, capabilities, state, info;
  196. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  197. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  198. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  199. let utils, bindingStates, uniformsGroups;
  200. function initGLContext() {
  201. extensions = new WebGLExtensions( _gl );
  202. extensions.init();
  203. utils = new WebGLUtils( _gl, extensions );
  204. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  205. state = new WebGLState( _gl );
  206. info = new WebGLInfo( _gl );
  207. properties = new WebGLProperties();
  208. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  209. cubemaps = new WebGLCubeMaps( _this );
  210. cubeuvmaps = new WebGLCubeUVMaps( _this );
  211. attributes = new WebGLAttributes( _gl );
  212. bindingStates = new WebGLBindingStates( _gl, attributes );
  213. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  214. objects = new WebGLObjects( _gl, geometries, attributes, info );
  215. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  216. clipping = new WebGLClipping( properties );
  217. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  218. materials = new WebGLMaterials( _this, properties );
  219. renderLists = new WebGLRenderLists();
  220. renderStates = new WebGLRenderStates( extensions );
  221. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  222. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  223. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  224. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  225. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  226. info.programs = programCache.programs;
  227. _this.capabilities = capabilities;
  228. _this.extensions = extensions;
  229. _this.properties = properties;
  230. _this.renderLists = renderLists;
  231. _this.shadowMap = shadowMap;
  232. _this.state = state;
  233. _this.info = info;
  234. }
  235. initGLContext();
  236. // xr
  237. const xr = new WebXRManager( _this, _gl );
  238. this.xr = xr;
  239. // API
  240. this.getContext = function () {
  241. return _gl;
  242. };
  243. this.getContextAttributes = function () {
  244. return _gl.getContextAttributes();
  245. };
  246. this.forceContextLoss = function () {
  247. const extension = extensions.get( 'WEBGL_lose_context' );
  248. if ( extension ) extension.loseContext();
  249. };
  250. this.forceContextRestore = function () {
  251. const extension = extensions.get( 'WEBGL_lose_context' );
  252. if ( extension ) extension.restoreContext();
  253. };
  254. this.getPixelRatio = function () {
  255. return _pixelRatio;
  256. };
  257. this.setPixelRatio = function ( value ) {
  258. if ( value === undefined ) return;
  259. _pixelRatio = value;
  260. this.setSize( _width, _height, false );
  261. };
  262. this.getSize = function ( target ) {
  263. return target.set( _width, _height );
  264. };
  265. this.setSize = function ( width, height, updateStyle = true ) {
  266. if ( xr.isPresenting ) {
  267. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  268. return;
  269. }
  270. _width = width;
  271. _height = height;
  272. canvas.width = Math.floor( width * _pixelRatio );
  273. canvas.height = Math.floor( height * _pixelRatio );
  274. if ( updateStyle === true ) {
  275. canvas.style.width = width + 'px';
  276. canvas.style.height = height + 'px';
  277. }
  278. this.setViewport( 0, 0, width, height );
  279. };
  280. this.getDrawingBufferSize = function ( target ) {
  281. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  282. };
  283. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  284. _width = width;
  285. _height = height;
  286. _pixelRatio = pixelRatio;
  287. canvas.width = Math.floor( width * pixelRatio );
  288. canvas.height = Math.floor( height * pixelRatio );
  289. this.setViewport( 0, 0, width, height );
  290. };
  291. this.getCurrentViewport = function ( target ) {
  292. return target.copy( _currentViewport );
  293. };
  294. this.getViewport = function ( target ) {
  295. return target.copy( _viewport );
  296. };
  297. this.setViewport = function ( x, y, width, height ) {
  298. if ( x.isVector4 ) {
  299. _viewport.set( x.x, x.y, x.z, x.w );
  300. } else {
  301. _viewport.set( x, y, width, height );
  302. }
  303. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  304. };
  305. this.getScissor = function ( target ) {
  306. return target.copy( _scissor );
  307. };
  308. this.setScissor = function ( x, y, width, height ) {
  309. if ( x.isVector4 ) {
  310. _scissor.set( x.x, x.y, x.z, x.w );
  311. } else {
  312. _scissor.set( x, y, width, height );
  313. }
  314. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  315. };
  316. this.getScissorTest = function () {
  317. return _scissorTest;
  318. };
  319. this.setScissorTest = function ( boolean ) {
  320. state.setScissorTest( _scissorTest = boolean );
  321. };
  322. this.setOpaqueSort = function ( method ) {
  323. _opaqueSort = method;
  324. };
  325. this.setTransparentSort = function ( method ) {
  326. _transparentSort = method;
  327. };
  328. // Clearing
  329. this.getClearColor = function ( target ) {
  330. return target.copy( background.getClearColor() );
  331. };
  332. this.setClearColor = function () {
  333. background.setClearColor.apply( background, arguments );
  334. };
  335. this.getClearAlpha = function () {
  336. return background.getClearAlpha();
  337. };
  338. this.setClearAlpha = function () {
  339. background.setClearAlpha.apply( background, arguments );
  340. };
  341. this.clear = function ( color = true, depth = true, stencil = true ) {
  342. let bits = 0;
  343. if ( color ) {
  344. // check if we're trying to clear an integer target
  345. let isIntegerFormat = false;
  346. if ( _currentRenderTarget !== null ) {
  347. const targetFormat = _currentRenderTarget.texture.format;
  348. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  349. targetFormat === RGIntegerFormat ||
  350. targetFormat === RedIntegerFormat;
  351. }
  352. // use the appropriate clear functions to clear the target if it's a signed
  353. // or unsigned integer target
  354. if ( isIntegerFormat ) {
  355. const targetType = _currentRenderTarget.texture.type;
  356. const isUnsignedType = targetType === UnsignedByteType ||
  357. targetType === UnsignedIntType ||
  358. targetType === UnsignedShortType ||
  359. targetType === UnsignedInt248Type ||
  360. targetType === UnsignedShort4444Type ||
  361. targetType === UnsignedShort5551Type;
  362. const clearColor = background.getClearColor();
  363. const a = background.getClearAlpha();
  364. const r = clearColor.r;
  365. const g = clearColor.g;
  366. const b = clearColor.b;
  367. if ( isUnsignedType ) {
  368. uintClearColor[ 0 ] = r;
  369. uintClearColor[ 1 ] = g;
  370. uintClearColor[ 2 ] = b;
  371. uintClearColor[ 3 ] = a;
  372. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  373. } else {
  374. intClearColor[ 0 ] = r;
  375. intClearColor[ 1 ] = g;
  376. intClearColor[ 2 ] = b;
  377. intClearColor[ 3 ] = a;
  378. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  379. }
  380. } else {
  381. bits |= _gl.COLOR_BUFFER_BIT;
  382. }
  383. }
  384. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  385. if ( stencil ) {
  386. bits |= _gl.STENCIL_BUFFER_BIT;
  387. this.state.buffers.stencil.setMask( 0xffffffff );
  388. }
  389. _gl.clear( bits );
  390. };
  391. this.clearColor = function () {
  392. this.clear( true, false, false );
  393. };
  394. this.clearDepth = function () {
  395. this.clear( false, true, false );
  396. };
  397. this.clearStencil = function () {
  398. this.clear( false, false, true );
  399. };
  400. //
  401. this.dispose = function () {
  402. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  403. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  404. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  405. renderLists.dispose();
  406. renderStates.dispose();
  407. properties.dispose();
  408. cubemaps.dispose();
  409. cubeuvmaps.dispose();
  410. objects.dispose();
  411. bindingStates.dispose();
  412. uniformsGroups.dispose();
  413. programCache.dispose();
  414. xr.dispose();
  415. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  416. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  417. animation.stop();
  418. };
  419. // Events
  420. function onContextLost( event ) {
  421. event.preventDefault();
  422. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  423. _isContextLost = true;
  424. }
  425. function onContextRestore( /* event */ ) {
  426. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  427. _isContextLost = false;
  428. const infoAutoReset = info.autoReset;
  429. const shadowMapEnabled = shadowMap.enabled;
  430. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  431. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  432. const shadowMapType = shadowMap.type;
  433. initGLContext();
  434. info.autoReset = infoAutoReset;
  435. shadowMap.enabled = shadowMapEnabled;
  436. shadowMap.autoUpdate = shadowMapAutoUpdate;
  437. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  438. shadowMap.type = shadowMapType;
  439. }
  440. function onContextCreationError( event ) {
  441. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  442. }
  443. function onMaterialDispose( event ) {
  444. const material = event.target;
  445. material.removeEventListener( 'dispose', onMaterialDispose );
  446. deallocateMaterial( material );
  447. }
  448. // Buffer deallocation
  449. function deallocateMaterial( material ) {
  450. releaseMaterialProgramReferences( material );
  451. properties.remove( material );
  452. }
  453. function releaseMaterialProgramReferences( material ) {
  454. const programs = properties.get( material ).programs;
  455. if ( programs !== undefined ) {
  456. programs.forEach( function ( program ) {
  457. programCache.releaseProgram( program );
  458. } );
  459. if ( material.isShaderMaterial ) {
  460. programCache.releaseShaderCache( material );
  461. }
  462. }
  463. }
  464. // Buffer rendering
  465. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  466. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  467. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  468. const program = setProgram( camera, scene, geometry, material, object );
  469. state.setMaterial( material, frontFaceCW );
  470. //
  471. let index = geometry.index;
  472. let rangeFactor = 1;
  473. if ( material.wireframe === true ) {
  474. index = geometries.getWireframeAttribute( geometry );
  475. if ( index === undefined ) return;
  476. rangeFactor = 2;
  477. }
  478. //
  479. const drawRange = geometry.drawRange;
  480. const position = geometry.attributes.position;
  481. let drawStart = drawRange.start * rangeFactor;
  482. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  483. if ( group !== null ) {
  484. drawStart = Math.max( drawStart, group.start * rangeFactor );
  485. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  486. }
  487. if ( index !== null ) {
  488. drawStart = Math.max( drawStart, 0 );
  489. drawEnd = Math.min( drawEnd, index.count );
  490. } else if ( position !== undefined && position !== null ) {
  491. drawStart = Math.max( drawStart, 0 );
  492. drawEnd = Math.min( drawEnd, position.count );
  493. }
  494. const drawCount = drawEnd - drawStart;
  495. if ( drawCount < 0 || drawCount === Infinity ) return;
  496. //
  497. bindingStates.setup( object, material, program, geometry, index );
  498. let attribute;
  499. let renderer = bufferRenderer;
  500. if ( index !== null ) {
  501. attribute = attributes.get( index );
  502. renderer = indexedBufferRenderer;
  503. renderer.setIndex( attribute );
  504. }
  505. //
  506. if ( object.isMesh ) {
  507. if ( material.wireframe === true ) {
  508. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  509. renderer.setMode( _gl.LINES );
  510. } else {
  511. renderer.setMode( _gl.TRIANGLES );
  512. }
  513. } else if ( object.isLine ) {
  514. let lineWidth = material.linewidth;
  515. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  516. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  517. if ( object.isLineSegments ) {
  518. renderer.setMode( _gl.LINES );
  519. } else if ( object.isLineLoop ) {
  520. renderer.setMode( _gl.LINE_LOOP );
  521. } else {
  522. renderer.setMode( _gl.LINE_STRIP );
  523. }
  524. } else if ( object.isPoints ) {
  525. renderer.setMode( _gl.POINTS );
  526. } else if ( object.isSprite ) {
  527. renderer.setMode( _gl.TRIANGLES );
  528. }
  529. if ( object.isBatchedMesh ) {
  530. if ( object._multiDrawInstances !== null ) {
  531. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  532. } else {
  533. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  534. }
  535. } else if ( object.isInstancedMesh ) {
  536. renderer.renderInstances( drawStart, drawCount, object.count );
  537. } else if ( geometry.isInstancedBufferGeometry ) {
  538. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  539. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  540. renderer.renderInstances( drawStart, drawCount, instanceCount );
  541. } else {
  542. renderer.render( drawStart, drawCount );
  543. }
  544. };
  545. // Compile
  546. function prepareMaterial( material, scene, object ) {
  547. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  548. material.side = BackSide;
  549. material.needsUpdate = true;
  550. getProgram( material, scene, object );
  551. material.side = FrontSide;
  552. material.needsUpdate = true;
  553. getProgram( material, scene, object );
  554. material.side = DoubleSide;
  555. } else {
  556. getProgram( material, scene, object );
  557. }
  558. }
  559. this.compile = function ( scene, camera, targetScene = null ) {
  560. if ( targetScene === null ) targetScene = scene;
  561. currentRenderState = renderStates.get( targetScene );
  562. currentRenderState.init( camera );
  563. renderStateStack.push( currentRenderState );
  564. // gather lights from both the target scene and the new object that will be added to the scene.
  565. targetScene.traverseVisible( function ( object ) {
  566. if ( object.isLight && object.layers.test( camera.layers ) ) {
  567. currentRenderState.pushLight( object );
  568. if ( object.castShadow ) {
  569. currentRenderState.pushShadow( object );
  570. }
  571. }
  572. } );
  573. if ( scene !== targetScene ) {
  574. scene.traverseVisible( function ( object ) {
  575. if ( object.isLight && object.layers.test( camera.layers ) ) {
  576. currentRenderState.pushLight( object );
  577. if ( object.castShadow ) {
  578. currentRenderState.pushShadow( object );
  579. }
  580. }
  581. } );
  582. }
  583. currentRenderState.setupLights( _this._useLegacyLights );
  584. // Only initialize materials in the new scene, not the targetScene.
  585. const materials = new Set();
  586. scene.traverse( function ( object ) {
  587. const material = object.material;
  588. if ( material ) {
  589. if ( Array.isArray( material ) ) {
  590. for ( let i = 0; i < material.length; i ++ ) {
  591. const material2 = material[ i ];
  592. prepareMaterial( material2, targetScene, object );
  593. materials.add( material2 );
  594. }
  595. } else {
  596. prepareMaterial( material, targetScene, object );
  597. materials.add( material );
  598. }
  599. }
  600. } );
  601. renderStateStack.pop();
  602. currentRenderState = null;
  603. return materials;
  604. };
  605. // compileAsync
  606. this.compileAsync = function ( scene, camera, targetScene = null ) {
  607. const materials = this.compile( scene, camera, targetScene );
  608. // Wait for all the materials in the new object to indicate that they're
  609. // ready to be used before resolving the promise.
  610. return new Promise( ( resolve ) => {
  611. function checkMaterialsReady() {
  612. materials.forEach( function ( material ) {
  613. const materialProperties = properties.get( material );
  614. const program = materialProperties.currentProgram;
  615. if ( program.isReady() ) {
  616. // remove any programs that report they're ready to use from the list
  617. materials.delete( material );
  618. }
  619. } );
  620. // once the list of compiling materials is empty, call the callback
  621. if ( materials.size === 0 ) {
  622. resolve( scene );
  623. return;
  624. }
  625. // if some materials are still not ready, wait a bit and check again
  626. setTimeout( checkMaterialsReady, 10 );
  627. }
  628. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  629. // If we can check the compilation status of the materials without
  630. // blocking then do so right away.
  631. checkMaterialsReady();
  632. } else {
  633. // Otherwise start by waiting a bit to give the materials we just
  634. // initialized a chance to finish.
  635. setTimeout( checkMaterialsReady, 10 );
  636. }
  637. } );
  638. };
  639. // Animation Loop
  640. let onAnimationFrameCallback = null;
  641. function onAnimationFrame( time ) {
  642. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  643. }
  644. function onXRSessionStart() {
  645. animation.stop();
  646. }
  647. function onXRSessionEnd() {
  648. animation.start();
  649. }
  650. const animation = new WebGLAnimation();
  651. animation.setAnimationLoop( onAnimationFrame );
  652. if ( typeof self !== 'undefined' ) animation.setContext( self );
  653. this.setAnimationLoop = function ( callback ) {
  654. onAnimationFrameCallback = callback;
  655. xr.setAnimationLoop( callback );
  656. ( callback === null ) ? animation.stop() : animation.start();
  657. };
  658. xr.addEventListener( 'sessionstart', onXRSessionStart );
  659. xr.addEventListener( 'sessionend', onXRSessionEnd );
  660. // Rendering
  661. this.render = function ( scene, camera ) {
  662. if ( camera !== undefined && camera.isCamera !== true ) {
  663. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  664. return;
  665. }
  666. if ( _isContextLost === true ) return;
  667. // update scene graph
  668. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  669. // update camera matrices and frustum
  670. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  671. if ( xr.enabled === true && xr.isPresenting === true ) {
  672. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  673. camera = xr.getCamera(); // use XR camera for rendering
  674. }
  675. //
  676. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  677. currentRenderState = renderStates.get( scene, renderStateStack.length );
  678. currentRenderState.init( camera );
  679. renderStateStack.push( currentRenderState );
  680. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  681. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  682. _localClippingEnabled = this.localClippingEnabled;
  683. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  684. currentRenderList = renderLists.get( scene, renderListStack.length );
  685. currentRenderList.init();
  686. renderListStack.push( currentRenderList );
  687. projectObject( scene, camera, 0, _this.sortObjects );
  688. currentRenderList.finish();
  689. if ( _this.sortObjects === true ) {
  690. currentRenderList.sort( _opaqueSort, _transparentSort );
  691. }
  692. const renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  693. if ( renderBackground ) {
  694. background.addToRenderList( currentRenderList, scene );
  695. }
  696. //
  697. this.info.render.frame ++;
  698. if ( _clippingEnabled === true ) clipping.beginShadows();
  699. const shadowsArray = currentRenderState.state.shadowsArray;
  700. shadowMap.render( shadowsArray, scene, camera );
  701. if ( _clippingEnabled === true ) clipping.endShadows();
  702. //
  703. if ( this.info.autoReset === true ) this.info.reset();
  704. // render scene
  705. const opaqueObjects = currentRenderList.opaque;
  706. const transmissiveObjects = currentRenderList.transmissive;
  707. currentRenderState.setupLights( _this._useLegacyLights );
  708. if ( camera.isArrayCamera ) {
  709. const cameras = camera.cameras;
  710. if ( transmissiveObjects.length > 0 ) {
  711. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  712. const camera2 = cameras[ i ];
  713. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  714. }
  715. }
  716. if ( renderBackground ) background.render( scene );
  717. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  718. const camera2 = cameras[ i ];
  719. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  720. }
  721. } else {
  722. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  723. if ( renderBackground ) background.render( scene );
  724. renderScene( currentRenderList, scene, camera );
  725. }
  726. //
  727. if ( _currentRenderTarget !== null ) {
  728. // resolve multisample renderbuffers to a single-sample texture if necessary
  729. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  730. // Generate mipmap if we're using any kind of mipmap filtering
  731. textures.updateRenderTargetMipmap( _currentRenderTarget );
  732. }
  733. //
  734. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  735. // _gl.finish();
  736. bindingStates.resetDefaultState();
  737. _currentMaterialId = - 1;
  738. _currentCamera = null;
  739. renderStateStack.pop();
  740. if ( renderStateStack.length > 0 ) {
  741. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  742. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  743. } else {
  744. currentRenderState = null;
  745. }
  746. renderListStack.pop();
  747. if ( renderListStack.length > 0 ) {
  748. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  749. } else {
  750. currentRenderList = null;
  751. }
  752. };
  753. function projectObject( object, camera, groupOrder, sortObjects ) {
  754. if ( object.visible === false ) return;
  755. const visible = object.layers.test( camera.layers );
  756. if ( visible ) {
  757. if ( object.isGroup ) {
  758. groupOrder = object.renderOrder;
  759. } else if ( object.isLOD ) {
  760. if ( object.autoUpdate === true ) object.update( camera );
  761. } else if ( object.isLight ) {
  762. currentRenderState.pushLight( object );
  763. if ( object.castShadow ) {
  764. currentRenderState.pushShadow( object );
  765. }
  766. } else if ( object.isSprite ) {
  767. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  768. if ( sortObjects ) {
  769. _vector3.setFromMatrixPosition( object.matrixWorld )
  770. .applyMatrix4( _projScreenMatrix );
  771. }
  772. const geometry = objects.update( object );
  773. const material = object.material;
  774. if ( material.visible ) {
  775. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  776. }
  777. }
  778. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  779. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  780. const geometry = objects.update( object );
  781. const material = object.material;
  782. if ( sortObjects ) {
  783. if ( object.boundingSphere !== undefined ) {
  784. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  785. _vector3.copy( object.boundingSphere.center );
  786. } else {
  787. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  788. _vector3.copy( geometry.boundingSphere.center );
  789. }
  790. _vector3
  791. .applyMatrix4( object.matrixWorld )
  792. .applyMatrix4( _projScreenMatrix );
  793. }
  794. if ( Array.isArray( material ) ) {
  795. const groups = geometry.groups;
  796. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  797. const group = groups[ i ];
  798. const groupMaterial = material[ group.materialIndex ];
  799. if ( groupMaterial && groupMaterial.visible ) {
  800. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  801. }
  802. }
  803. } else if ( material.visible ) {
  804. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  805. }
  806. }
  807. }
  808. }
  809. const children = object.children;
  810. for ( let i = 0, l = children.length; i < l; i ++ ) {
  811. projectObject( children[ i ], camera, groupOrder, sortObjects );
  812. }
  813. }
  814. function renderScene( currentRenderList, scene, camera, viewport ) {
  815. const opaqueObjects = currentRenderList.opaque;
  816. const transmissiveObjects = currentRenderList.transmissive;
  817. const transparentObjects = currentRenderList.transparent;
  818. currentRenderState.setupLightsView( camera );
  819. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  820. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  821. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  822. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  823. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  824. // Ensure depth buffer writing is enabled so it can be cleared on next render
  825. state.buffers.depth.setTest( true );
  826. state.buffers.depth.setMask( true );
  827. state.buffers.color.setMask( true );
  828. state.setPolygonOffset( false );
  829. }
  830. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  831. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  832. if ( overrideMaterial !== null ) {
  833. return;
  834. }
  835. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  836. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  837. generateMipmaps: true,
  838. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  839. minFilter: LinearMipmapLinearFilter,
  840. samples: 4,
  841. stencilBuffer: stencil,
  842. resolveDepthBuffer: false,
  843. resolveStencilBuffer: false
  844. } );
  845. // debug
  846. /*
  847. const geometry = new PlaneGeometry();
  848. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  849. const mesh = new Mesh( geometry, material );
  850. scene.add( mesh );
  851. */
  852. }
  853. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  854. const activeViewport = camera.viewport || _currentViewport;
  855. transmissionRenderTarget.setSize( activeViewport.z, activeViewport.w );
  856. //
  857. const currentRenderTarget = _this.getRenderTarget();
  858. _this.setRenderTarget( transmissionRenderTarget );
  859. _this.getClearColor( _currentClearColor );
  860. _currentClearAlpha = _this.getClearAlpha();
  861. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  862. _this.clear();
  863. // Turn off the features which can affect the frag color for opaque objects pass.
  864. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  865. const currentToneMapping = _this.toneMapping;
  866. _this.toneMapping = NoToneMapping;
  867. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  868. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  869. const currentCameraViewport = camera.viewport;
  870. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  871. currentRenderState.setupLightsView( camera );
  872. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  873. renderObjects( opaqueObjects, scene, camera );
  874. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  875. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  876. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  877. let renderTargetNeedsUpdate = false;
  878. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  879. const renderItem = transmissiveObjects[ i ];
  880. const object = renderItem.object;
  881. const geometry = renderItem.geometry;
  882. const material = renderItem.material;
  883. const group = renderItem.group;
  884. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  885. const currentSide = material.side;
  886. material.side = BackSide;
  887. material.needsUpdate = true;
  888. renderObject( object, scene, camera, geometry, material, group );
  889. material.side = currentSide;
  890. material.needsUpdate = true;
  891. renderTargetNeedsUpdate = true;
  892. }
  893. }
  894. if ( renderTargetNeedsUpdate === true ) {
  895. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  896. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  897. }
  898. }
  899. _this.setRenderTarget( currentRenderTarget );
  900. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  901. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  902. _this.toneMapping = currentToneMapping;
  903. }
  904. function renderObjects( renderList, scene, camera ) {
  905. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  906. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  907. const renderItem = renderList[ i ];
  908. const object = renderItem.object;
  909. const geometry = renderItem.geometry;
  910. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  911. const group = renderItem.group;
  912. if ( object.layers.test( camera.layers ) ) {
  913. renderObject( object, scene, camera, geometry, material, group );
  914. }
  915. }
  916. }
  917. function renderObject( object, scene, camera, geometry, material, group ) {
  918. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  919. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  920. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  921. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  922. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  923. material.side = BackSide;
  924. material.needsUpdate = true;
  925. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  926. material.side = FrontSide;
  927. material.needsUpdate = true;
  928. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  929. material.side = DoubleSide;
  930. } else {
  931. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  932. }
  933. object.onAfterRender( _this, scene, camera, geometry, material, group );
  934. }
  935. function getProgram( material, scene, object ) {
  936. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  937. const materialProperties = properties.get( material );
  938. const lights = currentRenderState.state.lights;
  939. const shadowsArray = currentRenderState.state.shadowsArray;
  940. const lightsStateVersion = lights.state.version;
  941. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  942. const programCacheKey = programCache.getProgramCacheKey( parameters );
  943. let programs = materialProperties.programs;
  944. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  945. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  946. materialProperties.fog = scene.fog;
  947. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  948. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  949. if ( programs === undefined ) {
  950. // new material
  951. material.addEventListener( 'dispose', onMaterialDispose );
  952. programs = new Map();
  953. materialProperties.programs = programs;
  954. }
  955. let program = programs.get( programCacheKey );
  956. if ( program !== undefined ) {
  957. // early out if program and light state is identical
  958. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  959. updateCommonMaterialProperties( material, parameters );
  960. return program;
  961. }
  962. } else {
  963. parameters.uniforms = programCache.getUniforms( material );
  964. material.onBuild( object, parameters, _this );
  965. material.onBeforeCompile( parameters, _this );
  966. program = programCache.acquireProgram( parameters, programCacheKey );
  967. programs.set( programCacheKey, program );
  968. materialProperties.uniforms = parameters.uniforms;
  969. }
  970. const uniforms = materialProperties.uniforms;
  971. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  972. uniforms.clippingPlanes = clipping.uniform;
  973. }
  974. updateCommonMaterialProperties( material, parameters );
  975. // store the light setup it was created for
  976. materialProperties.needsLights = materialNeedsLights( material );
  977. materialProperties.lightsStateVersion = lightsStateVersion;
  978. if ( materialProperties.needsLights ) {
  979. // wire up the material to this renderer's lighting state
  980. uniforms.ambientLightColor.value = lights.state.ambient;
  981. uniforms.lightProbe.value = lights.state.probe;
  982. uniforms.directionalLights.value = lights.state.directional;
  983. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  984. uniforms.spotLights.value = lights.state.spot;
  985. uniforms.spotLightShadows.value = lights.state.spotShadow;
  986. uniforms.rectAreaLights.value = lights.state.rectArea;
  987. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  988. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  989. uniforms.pointLights.value = lights.state.point;
  990. uniforms.pointLightShadows.value = lights.state.pointShadow;
  991. uniforms.hemisphereLights.value = lights.state.hemi;
  992. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  993. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  994. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  995. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  996. uniforms.spotLightMap.value = lights.state.spotLightMap;
  997. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  998. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  999. // TODO (abelnation): add area lights shadow info to uniforms
  1000. }
  1001. materialProperties.currentProgram = program;
  1002. materialProperties.uniformsList = null;
  1003. return program;
  1004. }
  1005. function getUniformList( materialProperties ) {
  1006. if ( materialProperties.uniformsList === null ) {
  1007. const progUniforms = materialProperties.currentProgram.getUniforms();
  1008. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  1009. }
  1010. return materialProperties.uniformsList;
  1011. }
  1012. function updateCommonMaterialProperties( material, parameters ) {
  1013. const materialProperties = properties.get( material );
  1014. materialProperties.outputColorSpace = parameters.outputColorSpace;
  1015. materialProperties.batching = parameters.batching;
  1016. materialProperties.instancing = parameters.instancing;
  1017. materialProperties.instancingColor = parameters.instancingColor;
  1018. materialProperties.instancingMorph = parameters.instancingMorph;
  1019. materialProperties.skinning = parameters.skinning;
  1020. materialProperties.morphTargets = parameters.morphTargets;
  1021. materialProperties.morphNormals = parameters.morphNormals;
  1022. materialProperties.morphColors = parameters.morphColors;
  1023. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  1024. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  1025. materialProperties.numIntersection = parameters.numClipIntersection;
  1026. materialProperties.vertexAlphas = parameters.vertexAlphas;
  1027. materialProperties.vertexTangents = parameters.vertexTangents;
  1028. materialProperties.toneMapping = parameters.toneMapping;
  1029. }
  1030. function setProgram( camera, scene, geometry, material, object ) {
  1031. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  1032. textures.resetTextureUnits();
  1033. const fog = scene.fog;
  1034. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  1035. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  1036. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  1037. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  1038. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  1039. const morphTargets = !! geometry.morphAttributes.position;
  1040. const morphNormals = !! geometry.morphAttributes.normal;
  1041. const morphColors = !! geometry.morphAttributes.color;
  1042. let toneMapping = NoToneMapping;
  1043. if ( material.toneMapped ) {
  1044. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  1045. toneMapping = _this.toneMapping;
  1046. }
  1047. }
  1048. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  1049. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  1050. const materialProperties = properties.get( material );
  1051. const lights = currentRenderState.state.lights;
  1052. if ( _clippingEnabled === true ) {
  1053. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  1054. const useCache =
  1055. camera === _currentCamera &&
  1056. material.id === _currentMaterialId;
  1057. // we might want to call this function with some ClippingGroup
  1058. // object instead of the material, once it becomes feasible
  1059. // (#8465, #8379)
  1060. clipping.setState( material, camera, useCache );
  1061. }
  1062. }
  1063. //
  1064. let needsProgramChange = false;
  1065. if ( material.version === materialProperties.__version ) {
  1066. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  1067. needsProgramChange = true;
  1068. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  1069. needsProgramChange = true;
  1070. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  1071. needsProgramChange = true;
  1072. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  1073. needsProgramChange = true;
  1074. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  1075. needsProgramChange = true;
  1076. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  1077. needsProgramChange = true;
  1078. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  1079. needsProgramChange = true;
  1080. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  1081. needsProgramChange = true;
  1082. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  1083. needsProgramChange = true;
  1084. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  1085. needsProgramChange = true;
  1086. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  1087. needsProgramChange = true;
  1088. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  1089. needsProgramChange = true;
  1090. } else if ( materialProperties.envMap !== envMap ) {
  1091. needsProgramChange = true;
  1092. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  1093. needsProgramChange = true;
  1094. } else if ( materialProperties.numClippingPlanes !== undefined &&
  1095. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  1096. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  1097. needsProgramChange = true;
  1098. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  1099. needsProgramChange = true;
  1100. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  1101. needsProgramChange = true;
  1102. } else if ( materialProperties.morphTargets !== morphTargets ) {
  1103. needsProgramChange = true;
  1104. } else if ( materialProperties.morphNormals !== morphNormals ) {
  1105. needsProgramChange = true;
  1106. } else if ( materialProperties.morphColors !== morphColors ) {
  1107. needsProgramChange = true;
  1108. } else if ( materialProperties.toneMapping !== toneMapping ) {
  1109. needsProgramChange = true;
  1110. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  1111. needsProgramChange = true;
  1112. }
  1113. } else {
  1114. needsProgramChange = true;
  1115. materialProperties.__version = material.version;
  1116. }
  1117. //
  1118. let program = materialProperties.currentProgram;
  1119. if ( needsProgramChange === true ) {
  1120. program = getProgram( material, scene, object );
  1121. }
  1122. let refreshProgram = false;
  1123. let refreshMaterial = false;
  1124. let refreshLights = false;
  1125. const p_uniforms = program.getUniforms(),
  1126. m_uniforms = materialProperties.uniforms;
  1127. if ( state.useProgram( program.program ) ) {
  1128. refreshProgram = true;
  1129. refreshMaterial = true;
  1130. refreshLights = true;
  1131. }
  1132. if ( material.id !== _currentMaterialId ) {
  1133. _currentMaterialId = material.id;
  1134. refreshMaterial = true;
  1135. }
  1136. if ( refreshProgram || _currentCamera !== camera ) {
  1137. // common camera uniforms
  1138. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  1139. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1140. const uCamPos = p_uniforms.map.cameraPosition;
  1141. if ( uCamPos !== undefined ) {
  1142. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1143. }
  1144. if ( capabilities.logarithmicDepthBuffer ) {
  1145. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1146. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1147. }
  1148. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  1149. if ( material.isMeshPhongMaterial ||
  1150. material.isMeshToonMaterial ||
  1151. material.isMeshLambertMaterial ||
  1152. material.isMeshBasicMaterial ||
  1153. material.isMeshStandardMaterial ||
  1154. material.isShaderMaterial ) {
  1155. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  1156. }
  1157. if ( _currentCamera !== camera ) {
  1158. _currentCamera = camera;
  1159. // lighting uniforms depend on the camera so enforce an update
  1160. // now, in case this material supports lights - or later, when
  1161. // the next material that does gets activated:
  1162. refreshMaterial = true; // set to true on material change
  1163. refreshLights = true; // remains set until update done
  1164. }
  1165. }
  1166. // skinning and morph target uniforms must be set even if material didn't change
  1167. // auto-setting of texture unit for bone and morph texture must go before other textures
  1168. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  1169. if ( object.isSkinnedMesh ) {
  1170. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1171. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1172. const skeleton = object.skeleton;
  1173. if ( skeleton ) {
  1174. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  1175. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  1176. }
  1177. }
  1178. if ( object.isBatchedMesh ) {
  1179. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  1180. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  1181. }
  1182. const morphAttributes = geometry.morphAttributes;
  1183. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  1184. morphtargets.update( object, geometry, program );
  1185. }
  1186. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  1187. materialProperties.receiveShadow = object.receiveShadow;
  1188. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  1189. }
  1190. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  1191. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  1192. m_uniforms.envMap.value = envMap;
  1193. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  1194. }
  1195. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  1196. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  1197. }
  1198. if ( refreshMaterial ) {
  1199. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  1200. if ( materialProperties.needsLights ) {
  1201. // the current material requires lighting info
  1202. // note: all lighting uniforms are always set correctly
  1203. // they simply reference the renderer's state for their
  1204. // values
  1205. //
  1206. // use the current material's .needsUpdate flags to set
  1207. // the GL state when required
  1208. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1209. }
  1210. // refresh uniforms common to several materials
  1211. if ( fog && material.fog === true ) {
  1212. materials.refreshFogUniforms( m_uniforms, fog );
  1213. }
  1214. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  1215. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  1216. }
  1217. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  1218. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  1219. material.uniformsNeedUpdate = false;
  1220. }
  1221. if ( material.isSpriteMaterial ) {
  1222. p_uniforms.setValue( _gl, 'center', object.center );
  1223. }
  1224. // common matrices
  1225. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1226. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1227. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1228. // UBOs
  1229. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  1230. const groups = material.uniformsGroups;
  1231. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  1232. const group = groups[ i ];
  1233. uniformsGroups.update( group, program );
  1234. uniformsGroups.bind( group, program );
  1235. }
  1236. }
  1237. return program;
  1238. }
  1239. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1240. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1241. uniforms.ambientLightColor.needsUpdate = value;
  1242. uniforms.lightProbe.needsUpdate = value;
  1243. uniforms.directionalLights.needsUpdate = value;
  1244. uniforms.directionalLightShadows.needsUpdate = value;
  1245. uniforms.pointLights.needsUpdate = value;
  1246. uniforms.pointLightShadows.needsUpdate = value;
  1247. uniforms.spotLights.needsUpdate = value;
  1248. uniforms.spotLightShadows.needsUpdate = value;
  1249. uniforms.rectAreaLights.needsUpdate = value;
  1250. uniforms.hemisphereLights.needsUpdate = value;
  1251. }
  1252. function materialNeedsLights( material ) {
  1253. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  1254. material.isMeshStandardMaterial || material.isShadowMaterial ||
  1255. ( material.isShaderMaterial && material.lights === true );
  1256. }
  1257. this.getActiveCubeFace = function () {
  1258. return _currentActiveCubeFace;
  1259. };
  1260. this.getActiveMipmapLevel = function () {
  1261. return _currentActiveMipmapLevel;
  1262. };
  1263. this.getRenderTarget = function () {
  1264. return _currentRenderTarget;
  1265. };
  1266. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  1267. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  1268. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  1269. const renderTargetProperties = properties.get( renderTarget );
  1270. renderTargetProperties.__hasExternalTextures = true;
  1271. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  1272. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  1273. // The multisample_render_to_texture extension doesn't work properly if there
  1274. // are midframe flushes and an external depth buffer. Disable use of the extension.
  1275. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  1276. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  1277. renderTargetProperties.__useRenderToTexture = false;
  1278. }
  1279. }
  1280. };
  1281. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  1282. const renderTargetProperties = properties.get( renderTarget );
  1283. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  1284. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  1285. };
  1286. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  1287. _currentRenderTarget = renderTarget;
  1288. _currentActiveCubeFace = activeCubeFace;
  1289. _currentActiveMipmapLevel = activeMipmapLevel;
  1290. let useDefaultFramebuffer = true;
  1291. let framebuffer = null;
  1292. let isCube = false;
  1293. let isRenderTarget3D = false;
  1294. if ( renderTarget ) {
  1295. const renderTargetProperties = properties.get( renderTarget );
  1296. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  1297. // We need to make sure to rebind the framebuffer.
  1298. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1299. useDefaultFramebuffer = false;
  1300. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  1301. textures.setupRenderTarget( renderTarget );
  1302. } else if ( renderTargetProperties.__hasExternalTextures ) {
  1303. // Color and depth texture must be rebound in order for the swapchain to update.
  1304. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  1305. }
  1306. const texture = renderTarget.texture;
  1307. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  1308. isRenderTarget3D = true;
  1309. }
  1310. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1311. if ( renderTarget.isWebGLCubeRenderTarget ) {
  1312. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  1313. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  1314. } else {
  1315. framebuffer = __webglFramebuffer[ activeCubeFace ];
  1316. }
  1317. isCube = true;
  1318. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  1319. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  1320. } else {
  1321. if ( Array.isArray( __webglFramebuffer ) ) {
  1322. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  1323. } else {
  1324. framebuffer = __webglFramebuffer;
  1325. }
  1326. }
  1327. _currentViewport.copy( renderTarget.viewport );
  1328. _currentScissor.copy( renderTarget.scissor );
  1329. _currentScissorTest = renderTarget.scissorTest;
  1330. } else {
  1331. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  1332. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  1333. _currentScissorTest = _scissorTest;
  1334. }
  1335. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1336. if ( framebufferBound && useDefaultFramebuffer ) {
  1337. state.drawBuffers( renderTarget, framebuffer );
  1338. }
  1339. state.viewport( _currentViewport );
  1340. state.scissor( _currentScissor );
  1341. state.setScissorTest( _currentScissorTest );
  1342. if ( isCube ) {
  1343. const textureProperties = properties.get( renderTarget.texture );
  1344. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  1345. } else if ( isRenderTarget3D ) {
  1346. const textureProperties = properties.get( renderTarget.texture );
  1347. const layer = activeCubeFace || 0;
  1348. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  1349. }
  1350. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  1351. };
  1352. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1353. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1354. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1355. return;
  1356. }
  1357. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1358. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  1359. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1360. }
  1361. if ( framebuffer ) {
  1362. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1363. try {
  1364. const texture = renderTarget.texture;
  1365. const textureFormat = texture.format;
  1366. const textureType = texture.type;
  1367. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  1368. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1369. return;
  1370. }
  1371. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  1372. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1373. return;
  1374. }
  1375. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1376. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1377. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  1378. }
  1379. } finally {
  1380. // restore framebuffer of current render target if necessary
  1381. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  1382. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1383. }
  1384. }
  1385. };
  1386. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1387. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1388. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1389. }
  1390. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1391. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  1392. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1393. }
  1394. if ( framebuffer ) {
  1395. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1396. try {
  1397. const texture = renderTarget.texture;
  1398. const textureFormat = texture.format;
  1399. const textureType = texture.type;
  1400. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  1401. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  1402. }
  1403. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  1404. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1405. }
  1406. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1407. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1408. const glBuffer = _gl.createBuffer();
  1409. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  1410. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  1411. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  1412. _gl.flush();
  1413. // check if the commands have finished every 8 ms
  1414. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  1415. await probeAsync( _gl, sync, 4 );
  1416. try {
  1417. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  1418. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  1419. } finally {
  1420. _gl.deleteBuffer( glBuffer );
  1421. _gl.deleteSync( sync );
  1422. }
  1423. return buffer;
  1424. }
  1425. } finally {
  1426. // restore framebuffer of current render target if necessary
  1427. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  1428. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1429. }
  1430. }
  1431. };
  1432. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  1433. // support previous signature with position first
  1434. if ( texture.isTexture !== true ) {
  1435. // @deprecated, r165
  1436. console.warn( 'WebGLRenderer: copyFramebufferToTexture function signature has changed.' );
  1437. position = arguments[ 0 ] || null;
  1438. texture = arguments[ 1 ];
  1439. }
  1440. const levelScale = Math.pow( 2, - level );
  1441. const width = Math.floor( texture.image.width * levelScale );
  1442. const height = Math.floor( texture.image.height * levelScale );
  1443. const x = position !== null ? position.x : 0;
  1444. const y = position !== null ? position.y : 0;
  1445. textures.setTexture2D( texture, 0 );
  1446. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  1447. state.unbindTexture();
  1448. };
  1449. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  1450. // support previous signature with dstPosition first
  1451. if ( srcTexture.isTexture !== true ) {
  1452. // @deprecated, r165
  1453. console.warn( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  1454. dstPosition = arguments[ 0 ] || null;
  1455. srcTexture = arguments[ 1 ];
  1456. dstTexture = arguments[ 2 ];
  1457. level = arguments[ 3 ] || 0;
  1458. srcRegion = null;
  1459. }
  1460. let width, height, minX, minY;
  1461. let dstX, dstY;
  1462. if ( srcRegion !== null ) {
  1463. width = srcRegion.max.x - srcRegion.min.x;
  1464. height = srcRegion.max.y - srcRegion.min.y;
  1465. minX = srcRegion.min.x;
  1466. minY = srcRegion.min.y;
  1467. } else {
  1468. width = srcTexture.image.width;
  1469. height = srcTexture.image.height;
  1470. minX = 0;
  1471. minY = 0;
  1472. }
  1473. if ( dstPosition !== null ) {
  1474. dstX = dstPosition.x;
  1475. dstY = dstPosition.y;
  1476. } else {
  1477. dstX = 0;
  1478. dstY = 0;
  1479. }
  1480. const glFormat = utils.convert( dstTexture.format );
  1481. const glType = utils.convert( dstTexture.type );
  1482. textures.setTexture2D( dstTexture, 0 );
  1483. // As another texture upload may have changed pixelStorei
  1484. // parameters, make sure they are correct for the dstTexture
  1485. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  1486. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  1487. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  1488. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  1489. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  1490. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  1491. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  1492. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  1493. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  1494. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  1495. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  1496. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  1497. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  1498. if ( srcTexture.isDataTexture ) {
  1499. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  1500. } else {
  1501. if ( srcTexture.isCompressedTexture ) {
  1502. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  1503. } else {
  1504. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, glFormat, glType, image );
  1505. }
  1506. }
  1507. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  1508. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  1509. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  1510. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  1511. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  1512. // Generate mipmaps only when copying level 0
  1513. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1514. state.unbindTexture();
  1515. };
  1516. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  1517. // support previous signature with source box first
  1518. if ( srcTexture.isTexture !== true ) {
  1519. // @deprecated, r165
  1520. console.warn( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  1521. srcRegion = arguments[ 0 ] || null;
  1522. dstPosition = arguments[ 1 ] || null;
  1523. srcTexture = arguments[ 2 ];
  1524. dstTexture = arguments[ 3 ];
  1525. level = arguments[ 4 ] || 0;
  1526. }
  1527. let width, height, depth, minX, minY, minZ;
  1528. let dstX, dstY, dstZ;
  1529. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  1530. if ( srcRegion !== null ) {
  1531. width = srcRegion.max.x - srcRegion.min.x;
  1532. height = srcRegion.max.y - srcRegion.min.y;
  1533. depth = srcRegion.max.z - srcRegion.min.z;
  1534. minX = srcRegion.min.x;
  1535. minY = srcRegion.min.y;
  1536. minZ = srcRegion.min.z;
  1537. } else {
  1538. width = image.width;
  1539. height = image.height;
  1540. depth = image.depth;
  1541. minX = 0;
  1542. minY = 0;
  1543. minZ = 0;
  1544. }
  1545. if ( dstPosition !== null ) {
  1546. dstX = dstPosition.x;
  1547. dstY = dstPosition.y;
  1548. dstZ = dstPosition.z;
  1549. } else {
  1550. dstX = 0;
  1551. dstY = 0;
  1552. dstZ = 0;
  1553. }
  1554. const glFormat = utils.convert( dstTexture.format );
  1555. const glType = utils.convert( dstTexture.type );
  1556. let glTarget;
  1557. if ( dstTexture.isData3DTexture ) {
  1558. textures.setTexture3D( dstTexture, 0 );
  1559. glTarget = _gl.TEXTURE_3D;
  1560. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  1561. textures.setTexture2DArray( dstTexture, 0 );
  1562. glTarget = _gl.TEXTURE_2D_ARRAY;
  1563. } else {
  1564. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  1565. return;
  1566. }
  1567. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  1568. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  1569. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  1570. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  1571. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  1572. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  1573. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  1574. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  1575. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  1576. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  1577. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  1578. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  1579. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  1580. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  1581. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  1582. } else {
  1583. if ( dstTexture.isCompressedArrayTexture ) {
  1584. _gl.compressedTexSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  1585. } else {
  1586. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  1587. }
  1588. }
  1589. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  1590. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  1591. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  1592. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  1593. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  1594. // Generate mipmaps only when copying level 0
  1595. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  1596. state.unbindTexture();
  1597. };
  1598. this.initRenderTarget = function ( target ) {
  1599. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  1600. textures.setupRenderTarget( target );
  1601. }
  1602. };
  1603. this.initTexture = function ( texture ) {
  1604. if ( texture.isCubeTexture ) {
  1605. textures.setTextureCube( texture, 0 );
  1606. } else if ( texture.isData3DTexture ) {
  1607. textures.setTexture3D( texture, 0 );
  1608. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  1609. textures.setTexture2DArray( texture, 0 );
  1610. } else {
  1611. textures.setTexture2D( texture, 0 );
  1612. }
  1613. state.unbindTexture();
  1614. };
  1615. this.resetState = function () {
  1616. _currentActiveCubeFace = 0;
  1617. _currentActiveMipmapLevel = 0;
  1618. _currentRenderTarget = null;
  1619. state.reset();
  1620. bindingStates.reset();
  1621. };
  1622. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  1623. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  1624. }
  1625. }
  1626. get coordinateSystem() {
  1627. return WebGLCoordinateSystem;
  1628. }
  1629. get outputColorSpace() {
  1630. return this._outputColorSpace;
  1631. }
  1632. set outputColorSpace( colorSpace ) {
  1633. this._outputColorSpace = colorSpace;
  1634. const gl = this.getContext();
  1635. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  1636. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  1637. }
  1638. get useLegacyLights() { // @deprecated, r155
  1639. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  1640. return this._useLegacyLights;
  1641. }
  1642. set useLegacyLights( value ) { // @deprecated, r155
  1643. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  1644. this._useLegacyLights = value;
  1645. }
  1646. }
  1647. export { WebGLRenderer };
粤ICP备19079148号