WebGLRenderer.js 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847
  1. /**
  2. * @author supereggbert / http://www.paulbrunt.co.uk/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author alteredq / http://alteredqualia.com/
  5. * @author szimek / https://github.com/szimek/
  6. * @author tschw
  7. */
  8. import {
  9. RGBAFormat,
  10. HalfFloatType,
  11. FloatType,
  12. UnsignedByteType,
  13. LinearEncoding,
  14. LinearToneMapping,
  15. BackSide
  16. } from '../constants.js';
  17. import { MathUtils } from '../math/MathUtils.js';
  18. import { DataTexture } from '../textures/DataTexture.js';
  19. import { Frustum } from '../math/Frustum.js';
  20. import { Matrix4 } from '../math/Matrix4.js';
  21. import { UniformsLib } from './shaders/UniformsLib.js';
  22. import { Vector2 } from '../math/Vector2.js';
  23. import { Vector3 } from '../math/Vector3.js';
  24. import { Vector4 } from '../math/Vector4.js';
  25. import { Scene } from '../scenes/Scene.js';
  26. import { WebGLAnimation } from './webgl/WebGLAnimation.js';
  27. import { WebGLAttributes } from './webgl/WebGLAttributes.js';
  28. import { WebGLBackground } from './webgl/WebGLBackground.js';
  29. import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer.js';
  30. import { WebGLCapabilities } from './webgl/WebGLCapabilities.js';
  31. import { WebGLClipping } from './webgl/WebGLClipping.js';
  32. import { WebGLExtensions } from './webgl/WebGLExtensions.js';
  33. import { WebGLGeometries } from './webgl/WebGLGeometries.js';
  34. import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer.js';
  35. import { WebGLInfo } from './webgl/WebGLInfo.js';
  36. import { WebGLMorphtargets } from './webgl/WebGLMorphtargets.js';
  37. import { WebGLObjects } from './webgl/WebGLObjects.js';
  38. import { WebGLPrograms } from './webgl/WebGLPrograms.js';
  39. import { WebGLProperties } from './webgl/WebGLProperties.js';
  40. import { WebGLRenderLists } from './webgl/WebGLRenderLists.js';
  41. import { WebGLRenderStates } from './webgl/WebGLRenderStates.js';
  42. import { WebGLShadowMap } from './webgl/WebGLShadowMap.js';
  43. import { WebGLState } from './webgl/WebGLState.js';
  44. import { WebGLTextures } from './webgl/WebGLTextures.js';
  45. import { WebGLUniforms } from './webgl/WebGLUniforms.js';
  46. import { WebGLUtils } from './webgl/WebGLUtils.js';
  47. import { WebGLMultiview } from './webgl/WebGLMultiview.js';
  48. import { WebXRManager } from './webxr/WebXRManager.js';
  49. function WebGLRenderer( parameters ) {
  50. parameters = parameters || {};
  51. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  52. _context = parameters.context !== undefined ? parameters.context : null,
  53. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  54. _depth = parameters.depth !== undefined ? parameters.depth : true,
  55. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  56. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  57. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  58. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  59. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  60. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  61. var currentRenderList = null;
  62. var currentRenderState = null;
  63. // public properties
  64. this.domElement = _canvas;
  65. // Debug configuration container
  66. this.debug = {
  67. /**
  68. * Enables error checking and reporting when shader programs are being compiled
  69. * @type {boolean}
  70. */
  71. checkShaderErrors: true
  72. };
  73. // clearing
  74. this.autoClear = true;
  75. this.autoClearColor = true;
  76. this.autoClearDepth = true;
  77. this.autoClearStencil = true;
  78. // scene graph
  79. this.sortObjects = true;
  80. // user-defined clipping
  81. this.clippingPlanes = [];
  82. this.localClippingEnabled = false;
  83. // physically based shading
  84. this.gammaFactor = 2.0; // for backwards compatibility
  85. this.outputEncoding = LinearEncoding;
  86. // physical lights
  87. this.physicallyCorrectLights = false;
  88. // tone mapping
  89. this.toneMapping = LinearToneMapping;
  90. this.toneMappingExposure = 1.0;
  91. this.toneMappingWhitePoint = 1.0;
  92. // morphs
  93. this.maxMorphTargets = 8;
  94. this.maxMorphNormals = 4;
  95. // internal properties
  96. var _this = this,
  97. _isContextLost = false,
  98. // internal state cache
  99. _framebuffer = null,
  100. _currentActiveCubeFace = 0,
  101. _currentActiveMipmapLevel = 0,
  102. _currentRenderTarget = null,
  103. _currentFramebuffer = null,
  104. _currentMaterialId = - 1,
  105. // geometry and program caching
  106. _currentGeometryProgram = {
  107. geometry: null,
  108. program: null,
  109. wireframe: false
  110. },
  111. _currentCamera = null,
  112. _currentArrayCamera = null,
  113. _currentViewport = new Vector4(),
  114. _currentScissor = new Vector4(),
  115. _currentScissorTest = null,
  116. //
  117. _width = _canvas.width,
  118. _height = _canvas.height,
  119. _pixelRatio = 1,
  120. _opaqueSort = null,
  121. _transparentSort = null,
  122. _viewport = new Vector4( 0, 0, _width, _height ),
  123. _scissor = new Vector4( 0, 0, _width, _height ),
  124. _scissorTest = false,
  125. // frustum
  126. _frustum = new Frustum(),
  127. // clipping
  128. _clipping = new WebGLClipping(),
  129. _clippingEnabled = false,
  130. _localClippingEnabled = false,
  131. // camera matrices cache
  132. _projScreenMatrix = new Matrix4(),
  133. _vector3 = new Vector3();
  134. function getTargetPixelRatio() {
  135. return _currentRenderTarget === null ? _pixelRatio : 1;
  136. }
  137. // initialize
  138. var _gl;
  139. try {
  140. var contextAttributes = {
  141. alpha: _alpha,
  142. depth: _depth,
  143. stencil: _stencil,
  144. antialias: _antialias,
  145. premultipliedAlpha: _premultipliedAlpha,
  146. preserveDrawingBuffer: _preserveDrawingBuffer,
  147. powerPreference: _powerPreference,
  148. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  149. xrCompatible: true
  150. };
  151. // event listeners must be registered before WebGL context is created, see #12753
  152. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  153. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  154. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  155. if ( _gl === null ) {
  156. if ( _canvas.getContext( 'webgl' ) !== null ) {
  157. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  158. } else {
  159. throw new Error( 'Error creating WebGL context.' );
  160. }
  161. }
  162. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  163. if ( _gl.getShaderPrecisionFormat === undefined ) {
  164. _gl.getShaderPrecisionFormat = function () {
  165. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  166. };
  167. }
  168. } catch ( error ) {
  169. console.error( 'THREE.WebGLRenderer: ' + error.message );
  170. throw error;
  171. }
  172. var extensions, capabilities, state, info;
  173. var properties, textures, attributes, geometries, objects;
  174. var programCache, renderLists, renderStates;
  175. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  176. var utils;
  177. function initGLContext() {
  178. extensions = new WebGLExtensions( _gl );
  179. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  180. if ( capabilities.isWebGL2 === false ) {
  181. extensions.get( 'WEBGL_depth_texture' );
  182. extensions.get( 'OES_texture_float' );
  183. extensions.get( 'OES_texture_half_float' );
  184. extensions.get( 'OES_texture_half_float_linear' );
  185. extensions.get( 'OES_standard_derivatives' );
  186. extensions.get( 'OES_element_index_uint' );
  187. extensions.get( 'ANGLE_instanced_arrays' );
  188. }
  189. extensions.get( 'OES_texture_float_linear' );
  190. utils = new WebGLUtils( _gl, extensions, capabilities );
  191. state = new WebGLState( _gl, extensions, capabilities );
  192. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  193. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  194. info = new WebGLInfo( _gl );
  195. properties = new WebGLProperties();
  196. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  197. attributes = new WebGLAttributes( _gl, capabilities );
  198. geometries = new WebGLGeometries( _gl, attributes, info );
  199. objects = new WebGLObjects( _gl, geometries, attributes, info );
  200. morphtargets = new WebGLMorphtargets( _gl );
  201. programCache = new WebGLPrograms( _this, extensions, capabilities );
  202. renderLists = new WebGLRenderLists();
  203. renderStates = new WebGLRenderStates();
  204. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  205. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  206. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  207. info.programs = programCache.programs;
  208. _this.capabilities = capabilities;
  209. _this.extensions = extensions;
  210. _this.properties = properties;
  211. _this.renderLists = renderLists;
  212. _this.state = state;
  213. _this.info = info;
  214. }
  215. initGLContext();
  216. // xr
  217. var xr = new WebXRManager( _this, _gl );
  218. this.xr = xr;
  219. // Multiview
  220. var multiview = new WebGLMultiview( _this, _gl );
  221. // shadow map
  222. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  223. this.shadowMap = shadowMap;
  224. // API
  225. this.getContext = function () {
  226. return _gl;
  227. };
  228. this.getContextAttributes = function () {
  229. return _gl.getContextAttributes();
  230. };
  231. this.forceContextLoss = function () {
  232. var extension = extensions.get( 'WEBGL_lose_context' );
  233. if ( extension ) extension.loseContext();
  234. };
  235. this.forceContextRestore = function () {
  236. var extension = extensions.get( 'WEBGL_lose_context' );
  237. if ( extension ) extension.restoreContext();
  238. };
  239. this.getPixelRatio = function () {
  240. return _pixelRatio;
  241. };
  242. this.setPixelRatio = function ( value ) {
  243. if ( value === undefined ) return;
  244. _pixelRatio = value;
  245. this.setSize( _width, _height, false );
  246. };
  247. this.getSize = function ( target ) {
  248. if ( target === undefined ) {
  249. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  250. target = new Vector2();
  251. }
  252. return target.set( _width, _height );
  253. };
  254. this.setSize = function ( width, height, updateStyle ) {
  255. if ( xr.isPresenting ) {
  256. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  257. return;
  258. }
  259. _width = width;
  260. _height = height;
  261. _canvas.width = Math.floor( width * _pixelRatio );
  262. _canvas.height = Math.floor( height * _pixelRatio );
  263. if ( updateStyle !== false ) {
  264. _canvas.style.width = width + 'px';
  265. _canvas.style.height = height + 'px';
  266. }
  267. this.setViewport( 0, 0, width, height );
  268. };
  269. this.getDrawingBufferSize = function ( target ) {
  270. if ( target === undefined ) {
  271. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  272. target = new Vector2();
  273. }
  274. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  275. };
  276. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  277. _width = width;
  278. _height = height;
  279. _pixelRatio = pixelRatio;
  280. _canvas.width = Math.floor( width * pixelRatio );
  281. _canvas.height = Math.floor( height * pixelRatio );
  282. this.setViewport( 0, 0, width, height );
  283. };
  284. this.getCurrentViewport = function ( target ) {
  285. if ( target === undefined ) {
  286. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  287. target = new Vector4();
  288. }
  289. return target.copy( _currentViewport );
  290. };
  291. this.getViewport = function ( target ) {
  292. return target.copy( _viewport );
  293. };
  294. this.setViewport = function ( x, y, width, height ) {
  295. if ( x.isVector4 ) {
  296. _viewport.set( x.x, x.y, x.z, x.w );
  297. } else {
  298. _viewport.set( x, y, width, height );
  299. }
  300. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  301. };
  302. this.getScissor = function ( target ) {
  303. return target.copy( _scissor );
  304. };
  305. this.setScissor = function ( x, y, width, height ) {
  306. if ( x.isVector4 ) {
  307. _scissor.set( x.x, x.y, x.z, x.w );
  308. } else {
  309. _scissor.set( x, y, width, height );
  310. }
  311. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  312. };
  313. this.getScissorTest = function () {
  314. return _scissorTest;
  315. };
  316. this.setScissorTest = function ( boolean ) {
  317. state.setScissorTest( _scissorTest = boolean );
  318. };
  319. this.setOpaqueSort = function ( method ) {
  320. _opaqueSort = method;
  321. };
  322. this.setTransparentSort = function ( method ) {
  323. _transparentSort = method;
  324. };
  325. // Clearing
  326. this.getClearColor = function () {
  327. return background.getClearColor();
  328. };
  329. this.setClearColor = function () {
  330. background.setClearColor.apply( background, arguments );
  331. };
  332. this.getClearAlpha = function () {
  333. return background.getClearAlpha();
  334. };
  335. this.setClearAlpha = function () {
  336. background.setClearAlpha.apply( background, arguments );
  337. };
  338. this.clear = function ( color, depth, stencil ) {
  339. var bits = 0;
  340. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  341. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  342. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  343. _gl.clear( bits );
  344. };
  345. this.clearColor = function () {
  346. this.clear( true, false, false );
  347. };
  348. this.clearDepth = function () {
  349. this.clear( false, true, false );
  350. };
  351. this.clearStencil = function () {
  352. this.clear( false, false, true );
  353. };
  354. //
  355. this.dispose = function () {
  356. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  357. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  358. renderLists.dispose();
  359. renderStates.dispose();
  360. properties.dispose();
  361. objects.dispose();
  362. xr.dispose();
  363. animation.stop();
  364. };
  365. // Events
  366. function onContextLost( event ) {
  367. event.preventDefault();
  368. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  369. _isContextLost = true;
  370. }
  371. function onContextRestore( /* event */ ) {
  372. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  373. _isContextLost = false;
  374. initGLContext();
  375. }
  376. function onMaterialDispose( event ) {
  377. var material = event.target;
  378. material.removeEventListener( 'dispose', onMaterialDispose );
  379. deallocateMaterial( material );
  380. }
  381. // Buffer deallocation
  382. function deallocateMaterial( material ) {
  383. releaseMaterialProgramReference( material );
  384. properties.remove( material );
  385. }
  386. function releaseMaterialProgramReference( material ) {
  387. var programInfo = properties.get( material ).program;
  388. material.program = undefined;
  389. if ( programInfo !== undefined ) {
  390. programCache.releaseProgram( programInfo );
  391. }
  392. }
  393. // Buffer rendering
  394. function renderObjectImmediate( object, program ) {
  395. object.render( function ( object ) {
  396. _this.renderBufferImmediate( object, program );
  397. } );
  398. }
  399. this.renderBufferImmediate = function ( object, program ) {
  400. state.initAttributes();
  401. var buffers = properties.get( object );
  402. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  403. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  404. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  405. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  406. var programAttributes = program.getAttributes();
  407. if ( object.hasPositions ) {
  408. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  409. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  410. state.enableAttribute( programAttributes.position );
  411. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  412. }
  413. if ( object.hasNormals ) {
  414. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  415. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  416. state.enableAttribute( programAttributes.normal );
  417. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  418. }
  419. if ( object.hasUvs ) {
  420. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  421. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  422. state.enableAttribute( programAttributes.uv );
  423. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  424. }
  425. if ( object.hasColors ) {
  426. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  427. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  428. state.enableAttribute( programAttributes.color );
  429. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  430. }
  431. state.disableUnusedAttributes();
  432. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  433. object.count = 0;
  434. };
  435. var tempScene = new Scene();
  436. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  437. if ( scene === null ) scene = tempScene; // renderBufferDirect second parameter used to be fog (could be null)
  438. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  439. var program = setProgram( camera, scene, material, object );
  440. state.setMaterial( material, frontFaceCW );
  441. var updateBuffers = false;
  442. if ( _currentGeometryProgram.geometry !== geometry.id ||
  443. _currentGeometryProgram.program !== program.id ||
  444. _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
  445. _currentGeometryProgram.geometry = geometry.id;
  446. _currentGeometryProgram.program = program.id;
  447. _currentGeometryProgram.wireframe = material.wireframe === true;
  448. updateBuffers = true;
  449. }
  450. if ( material.morphTargets || material.morphNormals ) {
  451. morphtargets.update( object, geometry, material, program );
  452. updateBuffers = true;
  453. }
  454. //
  455. var index = geometry.index;
  456. var position = geometry.attributes.position;
  457. //
  458. if ( index === null ) {
  459. if ( position === undefined || position.count === 0 ) return;
  460. } else if ( index.count === 0 ) {
  461. return;
  462. }
  463. //
  464. var rangeFactor = 1;
  465. if ( material.wireframe === true ) {
  466. index = geometries.getWireframeAttribute( geometry );
  467. rangeFactor = 2;
  468. }
  469. var attribute;
  470. var renderer = bufferRenderer;
  471. if ( index !== null ) {
  472. attribute = attributes.get( index );
  473. renderer = indexedBufferRenderer;
  474. renderer.setIndex( attribute );
  475. }
  476. if ( updateBuffers ) {
  477. setupVertexAttributes( object, geometry, material, program );
  478. if ( index !== null ) {
  479. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  480. }
  481. }
  482. //
  483. var dataCount = ( index !== null ) ? index.count : position.count;
  484. var rangeStart = geometry.drawRange.start * rangeFactor;
  485. var rangeCount = geometry.drawRange.count * rangeFactor;
  486. var groupStart = group !== null ? group.start * rangeFactor : 0;
  487. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  488. var drawStart = Math.max( rangeStart, groupStart );
  489. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  490. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  491. if ( drawCount === 0 ) return;
  492. //
  493. if ( object.isMesh ) {
  494. if ( material.wireframe === true ) {
  495. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  496. renderer.setMode( _gl.LINES );
  497. } else {
  498. renderer.setMode( _gl.TRIANGLES );
  499. }
  500. } else if ( object.isLine ) {
  501. var lineWidth = material.linewidth;
  502. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  503. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  504. if ( object.isLineSegments ) {
  505. renderer.setMode( _gl.LINES );
  506. } else if ( object.isLineLoop ) {
  507. renderer.setMode( _gl.LINE_LOOP );
  508. } else {
  509. renderer.setMode( _gl.LINE_STRIP );
  510. }
  511. } else if ( object.isPoints ) {
  512. renderer.setMode( _gl.POINTS );
  513. } else if ( object.isSprite ) {
  514. renderer.setMode( _gl.TRIANGLES );
  515. }
  516. if ( object.isInstancedMesh ) {
  517. renderer.renderInstances( geometry, drawStart, drawCount, object.count );
  518. } else if ( geometry.isInstancedBufferGeometry ) {
  519. renderer.renderInstances( geometry, drawStart, drawCount, geometry.maxInstancedCount );
  520. } else {
  521. renderer.render( drawStart, drawCount );
  522. }
  523. };
  524. function setupVertexAttributes( object, geometry, material, program ) {
  525. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  526. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  527. }
  528. state.initAttributes();
  529. var geometryAttributes = geometry.attributes;
  530. var programAttributes = program.getAttributes();
  531. var materialDefaultAttributeValues = material.defaultAttributeValues;
  532. for ( var name in programAttributes ) {
  533. var programAttribute = programAttributes[ name ];
  534. if ( programAttribute >= 0 ) {
  535. var geometryAttribute = geometryAttributes[ name ];
  536. if ( geometryAttribute !== undefined ) {
  537. var normalized = geometryAttribute.normalized;
  538. var size = geometryAttribute.itemSize;
  539. var attribute = attributes.get( geometryAttribute );
  540. // TODO Attribute may not be available on context restore
  541. if ( attribute === undefined ) continue;
  542. var buffer = attribute.buffer;
  543. var type = attribute.type;
  544. var bytesPerElement = attribute.bytesPerElement;
  545. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  546. var data = geometryAttribute.data;
  547. var stride = data.stride;
  548. var offset = geometryAttribute.offset;
  549. if ( data && data.isInstancedInterleavedBuffer ) {
  550. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  551. if ( geometry.maxInstancedCount === undefined ) {
  552. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  553. }
  554. } else {
  555. state.enableAttribute( programAttribute );
  556. }
  557. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  558. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  559. } else {
  560. if ( geometryAttribute.isInstancedBufferAttribute ) {
  561. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  562. if ( geometry.maxInstancedCount === undefined ) {
  563. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  564. }
  565. } else {
  566. state.enableAttribute( programAttribute );
  567. }
  568. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  569. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  570. }
  571. } else if ( name === 'instanceMatrix' ) {
  572. var attribute = attributes.get( object.instanceMatrix );
  573. // TODO Attribute may not be available on context restore
  574. if ( attribute === undefined ) continue;
  575. var buffer = attribute.buffer;
  576. var type = attribute.type;
  577. state.enableAttributeAndDivisor( programAttribute + 0, 1 );
  578. state.enableAttributeAndDivisor( programAttribute + 1, 1 );
  579. state.enableAttributeAndDivisor( programAttribute + 2, 1 );
  580. state.enableAttributeAndDivisor( programAttribute + 3, 1 );
  581. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  582. _gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  583. _gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  584. _gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  585. _gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  586. } else if ( materialDefaultAttributeValues !== undefined ) {
  587. var value = materialDefaultAttributeValues[ name ];
  588. if ( value !== undefined ) {
  589. switch ( value.length ) {
  590. case 2:
  591. _gl.vertexAttrib2fv( programAttribute, value );
  592. break;
  593. case 3:
  594. _gl.vertexAttrib3fv( programAttribute, value );
  595. break;
  596. case 4:
  597. _gl.vertexAttrib4fv( programAttribute, value );
  598. break;
  599. default:
  600. _gl.vertexAttrib1fv( programAttribute, value );
  601. }
  602. }
  603. }
  604. }
  605. }
  606. state.disableUnusedAttributes();
  607. }
  608. // Compile
  609. this.compile = function ( scene, camera ) {
  610. currentRenderState = renderStates.get( scene, camera );
  611. currentRenderState.init();
  612. scene.traverse( function ( object ) {
  613. if ( object.isLight ) {
  614. currentRenderState.pushLight( object );
  615. if ( object.castShadow ) {
  616. currentRenderState.pushShadow( object );
  617. }
  618. }
  619. } );
  620. currentRenderState.setupLights( camera );
  621. var compiled = {};
  622. scene.traverse( function ( object ) {
  623. if ( object.material ) {
  624. if ( Array.isArray( object.material ) ) {
  625. for ( var i = 0; i < object.material.length; i ++ ) {
  626. if ( object.material[ i ].uuid in compiled === false ) {
  627. initMaterial( object.material[ i ], scene, object );
  628. compiled[ object.material[ i ].uuid ] = true;
  629. }
  630. }
  631. } else if ( object.material.uuid in compiled === false ) {
  632. initMaterial( object.material, scene, object );
  633. compiled[ object.material.uuid ] = true;
  634. }
  635. }
  636. } );
  637. };
  638. // Animation Loop
  639. var onAnimationFrameCallback = null;
  640. function onAnimationFrame( time ) {
  641. if ( xr.isPresenting ) return;
  642. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  643. }
  644. var animation = new WebGLAnimation();
  645. animation.setAnimationLoop( onAnimationFrame );
  646. if ( typeof window !== 'undefined' ) animation.setContext( window );
  647. this.setAnimationLoop = function ( callback ) {
  648. onAnimationFrameCallback = callback;
  649. xr.setAnimationLoop( callback );
  650. animation.start();
  651. };
  652. // Rendering
  653. this.render = function ( scene, camera ) {
  654. var renderTarget, forceClear;
  655. if ( arguments[ 2 ] !== undefined ) {
  656. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  657. renderTarget = arguments[ 2 ];
  658. }
  659. if ( arguments[ 3 ] !== undefined ) {
  660. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  661. forceClear = arguments[ 3 ];
  662. }
  663. if ( ! ( camera && camera.isCamera ) ) {
  664. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  665. return;
  666. }
  667. if ( _isContextLost ) return;
  668. // reset caching for this frame
  669. _currentGeometryProgram.geometry = null;
  670. _currentGeometryProgram.program = null;
  671. _currentGeometryProgram.wireframe = false;
  672. _currentMaterialId = - 1;
  673. _currentCamera = null;
  674. // update scene graph
  675. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  676. // update camera matrices and frustum
  677. if ( camera.parent === null ) camera.updateMatrixWorld();
  678. if ( xr.enabled && xr.isPresenting ) {
  679. camera = xr.getCamera( camera );
  680. }
  681. //
  682. currentRenderState = renderStates.get( scene, camera );
  683. currentRenderState.init();
  684. scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  685. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  686. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  687. _localClippingEnabled = this.localClippingEnabled;
  688. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  689. currentRenderList = renderLists.get( scene, camera );
  690. currentRenderList.init();
  691. projectObject( scene, camera, 0, _this.sortObjects );
  692. currentRenderList.finish();
  693. if ( _this.sortObjects === true ) {
  694. currentRenderList.sort( _opaqueSort, _transparentSort );
  695. }
  696. //
  697. if ( _clippingEnabled ) _clipping.beginShadows();
  698. var shadowsArray = currentRenderState.state.shadowsArray;
  699. shadowMap.render( shadowsArray, scene, camera );
  700. currentRenderState.setupLights( camera );
  701. if ( _clippingEnabled ) _clipping.endShadows();
  702. //
  703. if ( this.info.autoReset ) this.info.reset();
  704. if ( renderTarget !== undefined ) {
  705. this.setRenderTarget( renderTarget );
  706. }
  707. if ( xr.enabled && multiview.isAvailable() ) {
  708. multiview.attachCamera( camera );
  709. }
  710. //
  711. background.render( currentRenderList, scene, camera, forceClear );
  712. // render scene
  713. var opaqueObjects = currentRenderList.opaque;
  714. var transparentObjects = currentRenderList.transparent;
  715. if ( scene.overrideMaterial ) {
  716. var overrideMaterial = scene.overrideMaterial;
  717. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  718. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  719. } else {
  720. // opaque pass (front-to-back order)
  721. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  722. // transparent pass (back-to-front order)
  723. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  724. }
  725. //
  726. scene.onAfterRender( _this, scene, camera );
  727. //
  728. if ( _currentRenderTarget !== null ) {
  729. // Generate mipmap if we're using any kind of mipmap filtering
  730. textures.updateRenderTargetMipmap( _currentRenderTarget );
  731. // resolve multisample renderbuffers to a single-sample texture if necessary
  732. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  733. }
  734. // Ensure depth buffer writing is enabled so it can be cleared on next render
  735. state.buffers.depth.setTest( true );
  736. state.buffers.depth.setMask( true );
  737. state.buffers.color.setMask( true );
  738. state.setPolygonOffset( false );
  739. if ( xr.enabled ) {
  740. if ( multiview.isAvailable() ) {
  741. multiview.detachCamera( camera );
  742. }
  743. }
  744. // _gl.finish();
  745. currentRenderList = null;
  746. currentRenderState = null;
  747. };
  748. function projectObject( object, camera, groupOrder, sortObjects ) {
  749. if ( object.visible === false ) return;
  750. var visible = object.layers.test( camera.layers );
  751. if ( visible ) {
  752. if ( object.isGroup ) {
  753. groupOrder = object.renderOrder;
  754. } else if ( object.isLOD ) {
  755. if ( object.autoUpdate === true ) object.update( camera );
  756. } else if ( object.isLight ) {
  757. currentRenderState.pushLight( object );
  758. if ( object.castShadow ) {
  759. currentRenderState.pushShadow( object );
  760. }
  761. } else if ( object.isSprite ) {
  762. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  763. if ( sortObjects ) {
  764. _vector3.setFromMatrixPosition( object.matrixWorld )
  765. .applyMatrix4( _projScreenMatrix );
  766. }
  767. var geometry = objects.update( object );
  768. var material = object.material;
  769. if ( material.visible ) {
  770. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  771. }
  772. }
  773. } else if ( object.isImmediateRenderObject ) {
  774. if ( sortObjects ) {
  775. _vector3.setFromMatrixPosition( object.matrixWorld )
  776. .applyMatrix4( _projScreenMatrix );
  777. }
  778. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  779. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  780. if ( object.isSkinnedMesh ) {
  781. // update skeleton only once in a frame
  782. if ( object.skeleton.frame !== info.render.frame ) {
  783. object.skeleton.update();
  784. object.skeleton.frame = info.render.frame;
  785. }
  786. }
  787. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  788. if ( sortObjects ) {
  789. _vector3.setFromMatrixPosition( object.matrixWorld )
  790. .applyMatrix4( _projScreenMatrix );
  791. }
  792. var geometry = objects.update( object );
  793. var material = object.material;
  794. if ( Array.isArray( material ) ) {
  795. var groups = geometry.groups;
  796. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  797. var group = groups[ i ];
  798. var 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. var children = object.children;
  810. for ( var i = 0, l = children.length; i < l; i ++ ) {
  811. projectObject( children[ i ], camera, groupOrder, sortObjects );
  812. }
  813. }
  814. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  815. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  816. var renderItem = renderList[ i ];
  817. var object = renderItem.object;
  818. var geometry = renderItem.geometry;
  819. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  820. var group = renderItem.group;
  821. if ( camera.isArrayCamera ) {
  822. _currentArrayCamera = camera;
  823. if ( xr.enabled && multiview.isAvailable() ) {
  824. renderObject( object, scene, camera, geometry, material, group );
  825. } else {
  826. var cameras = camera.cameras;
  827. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  828. var camera2 = cameras[ j ];
  829. if ( object.layers.test( camera2.layers ) ) {
  830. state.viewport( _currentViewport.copy( camera2.viewport ) );
  831. currentRenderState.setupLights( camera2 );
  832. renderObject( object, scene, camera2, geometry, material, group );
  833. }
  834. }
  835. }
  836. } else {
  837. _currentArrayCamera = null;
  838. renderObject( object, scene, camera, geometry, material, group );
  839. }
  840. }
  841. }
  842. function renderObject( object, scene, camera, geometry, material, group ) {
  843. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  844. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  845. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  846. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  847. if ( object.isImmediateRenderObject ) {
  848. var program = setProgram( camera, scene, material, object );
  849. state.setMaterial( material );
  850. _currentGeometryProgram.geometry = null;
  851. _currentGeometryProgram.program = null;
  852. _currentGeometryProgram.wireframe = false;
  853. renderObjectImmediate( object, program );
  854. } else {
  855. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  856. }
  857. object.onAfterRender( _this, scene, camera, geometry, material, group );
  858. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  859. }
  860. function initMaterial( material, scene, object ) {
  861. var materialProperties = properties.get( material );
  862. var lights = currentRenderState.state.lights;
  863. var shadowsArray = currentRenderState.state.shadowsArray;
  864. var lightsStateVersion = lights.state.version;
  865. var parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object );
  866. var programCacheKey = programCache.getProgramCacheKey( parameters );
  867. var program = materialProperties.program;
  868. var programChange = true;
  869. if ( program === undefined ) {
  870. // new material
  871. material.addEventListener( 'dispose', onMaterialDispose );
  872. } else if ( program.cacheKey !== programCacheKey ) {
  873. // changed glsl or parameters
  874. releaseMaterialProgramReference( material );
  875. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  876. materialProperties.lightsStateVersion = lightsStateVersion;
  877. programChange = false;
  878. } else if ( parameters.shaderID !== undefined ) {
  879. // same glsl and uniform list
  880. return;
  881. } else {
  882. // only rebuild uniform list
  883. programChange = false;
  884. }
  885. if ( programChange ) {
  886. program = programCache.acquireProgram( parameters, programCacheKey );
  887. materialProperties.program = program;
  888. materialProperties.uniforms = parameters.uniforms;
  889. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  890. materialProperties.outputEncoding = _this.outputEncoding;
  891. material.program = program;
  892. }
  893. var programAttributes = program.getAttributes();
  894. if ( material.morphTargets ) {
  895. material.numSupportedMorphTargets = 0;
  896. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  897. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  898. material.numSupportedMorphTargets ++;
  899. }
  900. }
  901. }
  902. if ( material.morphNormals ) {
  903. material.numSupportedMorphNormals = 0;
  904. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  905. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  906. material.numSupportedMorphNormals ++;
  907. }
  908. }
  909. }
  910. var uniforms = materialProperties.uniforms;
  911. if ( ! material.isShaderMaterial &&
  912. ! material.isRawShaderMaterial ||
  913. material.clipping === true ) {
  914. materialProperties.numClippingPlanes = _clipping.numPlanes;
  915. materialProperties.numIntersection = _clipping.numIntersection;
  916. uniforms.clippingPlanes = _clipping.uniform;
  917. }
  918. materialProperties.fog = scene.fog;
  919. // store the light setup it was created for
  920. materialProperties.needsLights = materialNeedsLights( material );
  921. materialProperties.lightsStateVersion = lightsStateVersion;
  922. if ( materialProperties.needsLights ) {
  923. // wire up the material to this renderer's lighting state
  924. uniforms.ambientLightColor.value = lights.state.ambient;
  925. uniforms.lightProbe.value = lights.state.probe;
  926. uniforms.directionalLights.value = lights.state.directional;
  927. uniforms.spotLights.value = lights.state.spot;
  928. uniforms.rectAreaLights.value = lights.state.rectArea;
  929. uniforms.pointLights.value = lights.state.point;
  930. uniforms.hemisphereLights.value = lights.state.hemi;
  931. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  932. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  933. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  934. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  935. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  936. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  937. // TODO (abelnation): add area lights shadow info to uniforms
  938. }
  939. var progUniforms = materialProperties.program.getUniforms(),
  940. uniformsList =
  941. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  942. materialProperties.uniformsList = uniformsList;
  943. }
  944. function setProgram( camera, scene, material, object ) {
  945. textures.resetTextureUnits();
  946. var fog = scene.fog;
  947. var environment = material.isMeshStandardMaterial ? scene.environment : null;
  948. var materialProperties = properties.get( material );
  949. var lights = currentRenderState.state.lights;
  950. if ( _clippingEnabled ) {
  951. if ( _localClippingEnabled || camera !== _currentCamera ) {
  952. var useCache =
  953. camera === _currentCamera &&
  954. material.id === _currentMaterialId;
  955. // we might want to call this function with some ClippingGroup
  956. // object instead of the material, once it becomes feasible
  957. // (#8465, #8379)
  958. _clipping.setState(
  959. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  960. camera, materialProperties, useCache );
  961. }
  962. }
  963. if ( material.version === materialProperties.__version ) {
  964. if ( materialProperties.program === undefined ) {
  965. initMaterial( material, scene, object );
  966. } else if ( material.fog && materialProperties.fog !== fog ) {
  967. initMaterial( material, scene, object );
  968. } else if ( materialProperties.environment !== environment ) {
  969. initMaterial( material, scene, object );
  970. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  971. initMaterial( material, scene, object );
  972. } else if ( materialProperties.numClippingPlanes !== undefined &&
  973. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  974. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  975. initMaterial( material, scene, object );
  976. } else if ( materialProperties.outputEncoding !== _this.outputEncoding ) {
  977. initMaterial( material, scene, object );
  978. }
  979. } else {
  980. initMaterial( material, scene, object );
  981. materialProperties.__version = material.version;
  982. }
  983. var refreshProgram = false;
  984. var refreshMaterial = false;
  985. var refreshLights = false;
  986. var program = materialProperties.program,
  987. p_uniforms = program.getUniforms(),
  988. m_uniforms = materialProperties.uniforms;
  989. if ( state.useProgram( program.program ) ) {
  990. refreshProgram = true;
  991. refreshMaterial = true;
  992. refreshLights = true;
  993. }
  994. if ( material.id !== _currentMaterialId ) {
  995. _currentMaterialId = material.id;
  996. refreshMaterial = true;
  997. }
  998. if ( refreshProgram || _currentCamera !== camera ) {
  999. if ( program.numMultiviewViews > 0 ) {
  1000. multiview.updateCameraProjectionMatricesUniform( camera, p_uniforms );
  1001. } else {
  1002. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  1003. }
  1004. if ( capabilities.logarithmicDepthBuffer ) {
  1005. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1006. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1007. }
  1008. if ( _currentCamera !== camera ) {
  1009. _currentCamera = camera;
  1010. // lighting uniforms depend on the camera so enforce an update
  1011. // now, in case this material supports lights - or later, when
  1012. // the next material that does gets activated:
  1013. refreshMaterial = true; // set to true on material change
  1014. refreshLights = true; // remains set until update done
  1015. }
  1016. // load material specific uniforms
  1017. // (shader material also gets them for the sake of genericity)
  1018. if ( material.isShaderMaterial ||
  1019. material.isMeshPhongMaterial ||
  1020. material.isMeshToonMaterial ||
  1021. material.isMeshStandardMaterial ||
  1022. material.envMap ) {
  1023. var uCamPos = p_uniforms.map.cameraPosition;
  1024. if ( uCamPos !== undefined ) {
  1025. uCamPos.setValue( _gl,
  1026. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1027. }
  1028. }
  1029. if ( material.isMeshPhongMaterial ||
  1030. material.isMeshToonMaterial ||
  1031. material.isMeshLambertMaterial ||
  1032. material.isMeshBasicMaterial ||
  1033. material.isMeshStandardMaterial ||
  1034. material.isShaderMaterial ) {
  1035. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  1036. }
  1037. if ( material.isMeshPhongMaterial ||
  1038. material.isMeshToonMaterial ||
  1039. material.isMeshLambertMaterial ||
  1040. material.isMeshBasicMaterial ||
  1041. material.isMeshStandardMaterial ||
  1042. material.isShaderMaterial ||
  1043. material.skinning ) {
  1044. if ( program.numMultiviewViews > 0 ) {
  1045. multiview.updateCameraViewMatricesUniform( camera, p_uniforms );
  1046. } else {
  1047. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1048. }
  1049. }
  1050. }
  1051. // skinning uniforms must be set even if material didn't change
  1052. // auto-setting of texture unit for bone texture must go before other textures
  1053. // not sure why, but otherwise weird things happen
  1054. if ( material.skinning ) {
  1055. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1056. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1057. var skeleton = object.skeleton;
  1058. if ( skeleton ) {
  1059. var bones = skeleton.bones;
  1060. if ( capabilities.floatVertexTextures ) {
  1061. if ( skeleton.boneTexture === undefined ) {
  1062. // layout (1 matrix = 4 pixels)
  1063. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  1064. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  1065. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  1066. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  1067. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  1068. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  1069. size = MathUtils.ceilPowerOfTwo( size );
  1070. size = Math.max( size, 4 );
  1071. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  1072. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  1073. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  1074. skeleton.boneMatrices = boneMatrices;
  1075. skeleton.boneTexture = boneTexture;
  1076. skeleton.boneTextureSize = size;
  1077. }
  1078. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  1079. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  1080. } else {
  1081. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  1082. }
  1083. }
  1084. }
  1085. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  1086. materialProperties.receiveShadow = object.receiveShadow;
  1087. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  1088. }
  1089. if ( refreshMaterial ) {
  1090. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  1091. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  1092. if ( materialProperties.needsLights ) {
  1093. // the current material requires lighting info
  1094. // note: all lighting uniforms are always set correctly
  1095. // they simply reference the renderer's state for their
  1096. // values
  1097. //
  1098. // use the current material's .needsUpdate flags to set
  1099. // the GL state when required
  1100. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1101. }
  1102. // refresh uniforms common to several materials
  1103. if ( fog && material.fog ) {
  1104. refreshUniformsFog( m_uniforms, fog );
  1105. }
  1106. if ( material.isMeshBasicMaterial ) {
  1107. refreshUniformsCommon( m_uniforms, material );
  1108. } else if ( material.isMeshLambertMaterial ) {
  1109. refreshUniformsCommon( m_uniforms, material );
  1110. refreshUniformsLambert( m_uniforms, material );
  1111. } else if ( material.isMeshToonMaterial ) {
  1112. refreshUniformsCommon( m_uniforms, material );
  1113. refreshUniformsToon( m_uniforms, material );
  1114. } else if ( material.isMeshPhongMaterial ) {
  1115. refreshUniformsCommon( m_uniforms, material );
  1116. refreshUniformsPhong( m_uniforms, material );
  1117. } else if ( material.isMeshStandardMaterial ) {
  1118. refreshUniformsCommon( m_uniforms, material, environment );
  1119. if ( material.isMeshPhysicalMaterial ) {
  1120. refreshUniformsPhysical( m_uniforms, material, environment );
  1121. } else {
  1122. refreshUniformsStandard( m_uniforms, material, environment );
  1123. }
  1124. } else if ( material.isMeshMatcapMaterial ) {
  1125. refreshUniformsCommon( m_uniforms, material );
  1126. refreshUniformsMatcap( m_uniforms, material );
  1127. } else if ( material.isMeshDepthMaterial ) {
  1128. refreshUniformsCommon( m_uniforms, material );
  1129. refreshUniformsDepth( m_uniforms, material );
  1130. } else if ( material.isMeshDistanceMaterial ) {
  1131. refreshUniformsCommon( m_uniforms, material );
  1132. refreshUniformsDistance( m_uniforms, material );
  1133. } else if ( material.isMeshNormalMaterial ) {
  1134. refreshUniformsCommon( m_uniforms, material );
  1135. refreshUniformsNormal( m_uniforms, material );
  1136. } else if ( material.isLineBasicMaterial ) {
  1137. refreshUniformsLine( m_uniforms, material );
  1138. if ( material.isLineDashedMaterial ) {
  1139. refreshUniformsDash( m_uniforms, material );
  1140. }
  1141. } else if ( material.isPointsMaterial ) {
  1142. refreshUniformsPoints( m_uniforms, material );
  1143. } else if ( material.isSpriteMaterial ) {
  1144. refreshUniformsSprites( m_uniforms, material );
  1145. } else if ( material.isShadowMaterial ) {
  1146. m_uniforms.color.value.copy( material.color );
  1147. m_uniforms.opacity.value = material.opacity;
  1148. }
  1149. // RectAreaLight Texture
  1150. // TODO (mrdoob): Find a nicer implementation
  1151. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  1152. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  1153. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  1154. if ( material.isShaderMaterial ) {
  1155. material.uniformsNeedUpdate = false; // #15581
  1156. }
  1157. }
  1158. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  1159. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  1160. material.uniformsNeedUpdate = false;
  1161. }
  1162. if ( material.isSpriteMaterial ) {
  1163. p_uniforms.setValue( _gl, 'center', object.center );
  1164. }
  1165. // common matrices
  1166. if ( program.numMultiviewViews > 0 ) {
  1167. multiview.updateObjectMatricesUniforms( object, camera, p_uniforms );
  1168. } else {
  1169. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1170. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1171. }
  1172. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1173. return program;
  1174. }
  1175. // Uniforms (refresh uniforms objects)
  1176. function refreshUniformsCommon( uniforms, material, environment ) {
  1177. uniforms.opacity.value = material.opacity;
  1178. if ( material.color ) {
  1179. uniforms.diffuse.value.copy( material.color );
  1180. }
  1181. if ( material.emissive ) {
  1182. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1183. }
  1184. if ( material.map ) {
  1185. uniforms.map.value = material.map;
  1186. }
  1187. if ( material.alphaMap ) {
  1188. uniforms.alphaMap.value = material.alphaMap;
  1189. }
  1190. if ( material.specularMap ) {
  1191. uniforms.specularMap.value = material.specularMap;
  1192. }
  1193. var envMap = material.envMap || environment;
  1194. if ( envMap ) {
  1195. uniforms.envMap.value = envMap;
  1196. uniforms.flipEnvMap.value = envMap.isCubeTexture ? - 1 : 1;
  1197. uniforms.reflectivity.value = material.reflectivity;
  1198. uniforms.refractionRatio.value = material.refractionRatio;
  1199. uniforms.maxMipLevel.value = properties.get( envMap ).__maxMipLevel;
  1200. }
  1201. if ( material.lightMap ) {
  1202. uniforms.lightMap.value = material.lightMap;
  1203. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1204. }
  1205. if ( material.aoMap ) {
  1206. uniforms.aoMap.value = material.aoMap;
  1207. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1208. }
  1209. // uv repeat and offset setting priorities
  1210. // 1. color map
  1211. // 2. specular map
  1212. // 3. normal map
  1213. // 4. bump map
  1214. // 5. alpha map
  1215. // 6. emissive map
  1216. var uvScaleMap;
  1217. if ( material.map ) {
  1218. uvScaleMap = material.map;
  1219. } else if ( material.specularMap ) {
  1220. uvScaleMap = material.specularMap;
  1221. } else if ( material.displacementMap ) {
  1222. uvScaleMap = material.displacementMap;
  1223. } else if ( material.normalMap ) {
  1224. uvScaleMap = material.normalMap;
  1225. } else if ( material.bumpMap ) {
  1226. uvScaleMap = material.bumpMap;
  1227. } else if ( material.roughnessMap ) {
  1228. uvScaleMap = material.roughnessMap;
  1229. } else if ( material.metalnessMap ) {
  1230. uvScaleMap = material.metalnessMap;
  1231. } else if ( material.alphaMap ) {
  1232. uvScaleMap = material.alphaMap;
  1233. } else if ( material.emissiveMap ) {
  1234. uvScaleMap = material.emissiveMap;
  1235. }
  1236. if ( uvScaleMap !== undefined ) {
  1237. // backwards compatibility
  1238. if ( uvScaleMap.isWebGLRenderTarget ) {
  1239. uvScaleMap = uvScaleMap.texture;
  1240. }
  1241. if ( uvScaleMap.matrixAutoUpdate === true ) {
  1242. uvScaleMap.updateMatrix();
  1243. }
  1244. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  1245. }
  1246. // uv repeat and offset setting priorities for uv2
  1247. // 1. ao map
  1248. // 2. light map
  1249. var uv2ScaleMap;
  1250. if ( material.aoMap ) {
  1251. uv2ScaleMap = material.aoMap;
  1252. } else if ( material.lightMap ) {
  1253. uv2ScaleMap = material.lightMap;
  1254. }
  1255. if ( uv2ScaleMap !== undefined ) {
  1256. // backwards compatibility
  1257. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  1258. uv2ScaleMap = uv2ScaleMap.texture;
  1259. }
  1260. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  1261. uv2ScaleMap.updateMatrix();
  1262. }
  1263. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  1264. }
  1265. }
  1266. function refreshUniformsLine( uniforms, material ) {
  1267. uniforms.diffuse.value.copy( material.color );
  1268. uniforms.opacity.value = material.opacity;
  1269. }
  1270. function refreshUniformsDash( uniforms, material ) {
  1271. uniforms.dashSize.value = material.dashSize;
  1272. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1273. uniforms.scale.value = material.scale;
  1274. }
  1275. function refreshUniformsPoints( uniforms, material ) {
  1276. uniforms.diffuse.value.copy( material.color );
  1277. uniforms.opacity.value = material.opacity;
  1278. uniforms.size.value = material.size * _pixelRatio;
  1279. uniforms.scale.value = _height * 0.5;
  1280. if ( material.map ) {
  1281. uniforms.map.value = material.map;
  1282. }
  1283. if ( material.alphaMap ) {
  1284. uniforms.alphaMap.value = material.alphaMap;
  1285. }
  1286. // uv repeat and offset setting priorities
  1287. // 1. color map
  1288. // 2. alpha map
  1289. var uvScaleMap;
  1290. if ( material.map ) {
  1291. uvScaleMap = material.map;
  1292. } else if ( material.alphaMap ) {
  1293. uvScaleMap = material.alphaMap;
  1294. }
  1295. if ( uvScaleMap !== undefined ) {
  1296. if ( uvScaleMap.matrixAutoUpdate === true ) {
  1297. uvScaleMap.updateMatrix();
  1298. }
  1299. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  1300. }
  1301. }
  1302. function refreshUniformsSprites( uniforms, material ) {
  1303. uniforms.diffuse.value.copy( material.color );
  1304. uniforms.opacity.value = material.opacity;
  1305. uniforms.rotation.value = material.rotation;
  1306. if ( material.map ) {
  1307. uniforms.map.value = material.map;
  1308. }
  1309. if ( material.alphaMap ) {
  1310. uniforms.alphaMap.value = material.alphaMap;
  1311. }
  1312. // uv repeat and offset setting priorities
  1313. // 1. color map
  1314. // 2. alpha map
  1315. var uvScaleMap;
  1316. if ( material.map ) {
  1317. uvScaleMap = material.map;
  1318. } else if ( material.alphaMap ) {
  1319. uvScaleMap = material.alphaMap;
  1320. }
  1321. if ( uvScaleMap !== undefined ) {
  1322. if ( uvScaleMap.matrixAutoUpdate === true ) {
  1323. uvScaleMap.updateMatrix();
  1324. }
  1325. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  1326. }
  1327. }
  1328. function refreshUniformsFog( uniforms, fog ) {
  1329. uniforms.fogColor.value.copy( fog.color );
  1330. if ( fog.isFog ) {
  1331. uniforms.fogNear.value = fog.near;
  1332. uniforms.fogFar.value = fog.far;
  1333. } else if ( fog.isFogExp2 ) {
  1334. uniforms.fogDensity.value = fog.density;
  1335. }
  1336. }
  1337. function refreshUniformsLambert( uniforms, material ) {
  1338. if ( material.emissiveMap ) {
  1339. uniforms.emissiveMap.value = material.emissiveMap;
  1340. }
  1341. }
  1342. function refreshUniformsPhong( uniforms, material ) {
  1343. uniforms.specular.value.copy( material.specular );
  1344. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1345. if ( material.emissiveMap ) {
  1346. uniforms.emissiveMap.value = material.emissiveMap;
  1347. }
  1348. if ( material.bumpMap ) {
  1349. uniforms.bumpMap.value = material.bumpMap;
  1350. uniforms.bumpScale.value = material.bumpScale;
  1351. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1352. }
  1353. if ( material.normalMap ) {
  1354. uniforms.normalMap.value = material.normalMap;
  1355. uniforms.normalScale.value.copy( material.normalScale );
  1356. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1357. }
  1358. if ( material.displacementMap ) {
  1359. uniforms.displacementMap.value = material.displacementMap;
  1360. uniforms.displacementScale.value = material.displacementScale;
  1361. uniforms.displacementBias.value = material.displacementBias;
  1362. }
  1363. }
  1364. function refreshUniformsToon( uniforms, material ) {
  1365. uniforms.specular.value.copy( material.specular );
  1366. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1367. if ( material.gradientMap ) {
  1368. uniforms.gradientMap.value = material.gradientMap;
  1369. }
  1370. if ( material.emissiveMap ) {
  1371. uniforms.emissiveMap.value = material.emissiveMap;
  1372. }
  1373. if ( material.bumpMap ) {
  1374. uniforms.bumpMap.value = material.bumpMap;
  1375. uniforms.bumpScale.value = material.bumpScale;
  1376. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1377. }
  1378. if ( material.normalMap ) {
  1379. uniforms.normalMap.value = material.normalMap;
  1380. uniforms.normalScale.value.copy( material.normalScale );
  1381. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1382. }
  1383. if ( material.displacementMap ) {
  1384. uniforms.displacementMap.value = material.displacementMap;
  1385. uniforms.displacementScale.value = material.displacementScale;
  1386. uniforms.displacementBias.value = material.displacementBias;
  1387. }
  1388. }
  1389. function refreshUniformsStandard( uniforms, material, environment ) {
  1390. uniforms.roughness.value = material.roughness;
  1391. uniforms.metalness.value = material.metalness;
  1392. if ( material.roughnessMap ) {
  1393. uniforms.roughnessMap.value = material.roughnessMap;
  1394. }
  1395. if ( material.metalnessMap ) {
  1396. uniforms.metalnessMap.value = material.metalnessMap;
  1397. }
  1398. if ( material.emissiveMap ) {
  1399. uniforms.emissiveMap.value = material.emissiveMap;
  1400. }
  1401. if ( material.bumpMap ) {
  1402. uniforms.bumpMap.value = material.bumpMap;
  1403. uniforms.bumpScale.value = material.bumpScale;
  1404. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1405. }
  1406. if ( material.normalMap ) {
  1407. uniforms.normalMap.value = material.normalMap;
  1408. uniforms.normalScale.value.copy( material.normalScale );
  1409. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1410. }
  1411. if ( material.displacementMap ) {
  1412. uniforms.displacementMap.value = material.displacementMap;
  1413. uniforms.displacementScale.value = material.displacementScale;
  1414. uniforms.displacementBias.value = material.displacementBias;
  1415. }
  1416. if ( material.envMap || environment ) {
  1417. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1418. uniforms.envMapIntensity.value = material.envMapIntensity;
  1419. }
  1420. }
  1421. function refreshUniformsPhysical( uniforms, material, environment ) {
  1422. refreshUniformsStandard( uniforms, material, environment );
  1423. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  1424. uniforms.clearcoat.value = material.clearcoat;
  1425. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  1426. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  1427. if ( material.clearcoatNormalMap ) {
  1428. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  1429. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  1430. if ( material.side === BackSide ) {
  1431. uniforms.clearcoatNormalScale.value.negate();
  1432. }
  1433. }
  1434. uniforms.transparency.value = material.transparency;
  1435. }
  1436. function refreshUniformsMatcap( uniforms, material ) {
  1437. if ( material.matcap ) {
  1438. uniforms.matcap.value = material.matcap;
  1439. }
  1440. if ( material.bumpMap ) {
  1441. uniforms.bumpMap.value = material.bumpMap;
  1442. uniforms.bumpScale.value = material.bumpScale;
  1443. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1444. }
  1445. if ( material.normalMap ) {
  1446. uniforms.normalMap.value = material.normalMap;
  1447. uniforms.normalScale.value.copy( material.normalScale );
  1448. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1449. }
  1450. if ( material.displacementMap ) {
  1451. uniforms.displacementMap.value = material.displacementMap;
  1452. uniforms.displacementScale.value = material.displacementScale;
  1453. uniforms.displacementBias.value = material.displacementBias;
  1454. }
  1455. }
  1456. function refreshUniformsDepth( uniforms, material ) {
  1457. if ( material.displacementMap ) {
  1458. uniforms.displacementMap.value = material.displacementMap;
  1459. uniforms.displacementScale.value = material.displacementScale;
  1460. uniforms.displacementBias.value = material.displacementBias;
  1461. }
  1462. }
  1463. function refreshUniformsDistance( uniforms, material ) {
  1464. if ( material.displacementMap ) {
  1465. uniforms.displacementMap.value = material.displacementMap;
  1466. uniforms.displacementScale.value = material.displacementScale;
  1467. uniforms.displacementBias.value = material.displacementBias;
  1468. }
  1469. uniforms.referencePosition.value.copy( material.referencePosition );
  1470. uniforms.nearDistance.value = material.nearDistance;
  1471. uniforms.farDistance.value = material.farDistance;
  1472. }
  1473. function refreshUniformsNormal( uniforms, material ) {
  1474. if ( material.bumpMap ) {
  1475. uniforms.bumpMap.value = material.bumpMap;
  1476. uniforms.bumpScale.value = material.bumpScale;
  1477. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  1478. }
  1479. if ( material.normalMap ) {
  1480. uniforms.normalMap.value = material.normalMap;
  1481. uniforms.normalScale.value.copy( material.normalScale );
  1482. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  1483. }
  1484. if ( material.displacementMap ) {
  1485. uniforms.displacementMap.value = material.displacementMap;
  1486. uniforms.displacementScale.value = material.displacementScale;
  1487. uniforms.displacementBias.value = material.displacementBias;
  1488. }
  1489. }
  1490. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1491. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1492. uniforms.ambientLightColor.needsUpdate = value;
  1493. uniforms.lightProbe.needsUpdate = value;
  1494. uniforms.directionalLights.needsUpdate = value;
  1495. uniforms.pointLights.needsUpdate = value;
  1496. uniforms.spotLights.needsUpdate = value;
  1497. uniforms.rectAreaLights.needsUpdate = value;
  1498. uniforms.hemisphereLights.needsUpdate = value;
  1499. }
  1500. function materialNeedsLights( material ) {
  1501. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  1502. material.isMeshStandardMaterial || material.isShadowMaterial ||
  1503. ( material.isShaderMaterial && material.lights === true );
  1504. }
  1505. //
  1506. this.setFramebuffer = function ( value ) {
  1507. if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( _gl.FRAMEBUFFER, value );
  1508. _framebuffer = value;
  1509. };
  1510. this.getActiveCubeFace = function () {
  1511. return _currentActiveCubeFace;
  1512. };
  1513. this.getActiveMipmapLevel = function () {
  1514. return _currentActiveMipmapLevel;
  1515. };
  1516. this.getRenderTarget = function () {
  1517. return _currentRenderTarget;
  1518. };
  1519. this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) {
  1520. _currentRenderTarget = renderTarget;
  1521. _currentActiveCubeFace = activeCubeFace;
  1522. _currentActiveMipmapLevel = activeMipmapLevel;
  1523. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1524. textures.setupRenderTarget( renderTarget );
  1525. }
  1526. var framebuffer = _framebuffer;
  1527. var isCube = false;
  1528. if ( renderTarget ) {
  1529. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1530. if ( renderTarget.isWebGLCubeRenderTarget ) {
  1531. framebuffer = __webglFramebuffer[ activeCubeFace || 0 ];
  1532. isCube = true;
  1533. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  1534. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  1535. } else {
  1536. framebuffer = __webglFramebuffer;
  1537. }
  1538. _currentViewport.copy( renderTarget.viewport );
  1539. _currentScissor.copy( renderTarget.scissor );
  1540. _currentScissorTest = renderTarget.scissorTest;
  1541. } else {
  1542. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  1543. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  1544. _currentScissorTest = _scissorTest;
  1545. }
  1546. if ( _currentFramebuffer !== framebuffer ) {
  1547. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1548. _currentFramebuffer = framebuffer;
  1549. }
  1550. state.viewport( _currentViewport );
  1551. state.scissor( _currentScissor );
  1552. state.setScissorTest( _currentScissorTest );
  1553. if ( isCube ) {
  1554. var textureProperties = properties.get( renderTarget.texture );
  1555. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 );
  1556. }
  1557. };
  1558. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  1559. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  1560. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1561. return;
  1562. }
  1563. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1564. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  1565. framebuffer = framebuffer[ activeCubeFaceIndex ];
  1566. }
  1567. if ( framebuffer ) {
  1568. var restore = false;
  1569. if ( framebuffer !== _currentFramebuffer ) {
  1570. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1571. restore = true;
  1572. }
  1573. try {
  1574. var texture = renderTarget.texture;
  1575. var textureFormat = texture.format;
  1576. var textureType = texture.type;
  1577. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1578. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1579. return;
  1580. }
  1581. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  1582. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  1583. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  1584. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1585. return;
  1586. }
  1587. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  1588. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1589. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1590. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  1591. }
  1592. } else {
  1593. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  1594. }
  1595. } finally {
  1596. if ( restore ) {
  1597. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  1598. }
  1599. }
  1600. }
  1601. };
  1602. this.copyFramebufferToTexture = function ( position, texture, level ) {
  1603. if ( level === undefined ) level = 0;
  1604. var levelScale = Math.pow( 2, - level );
  1605. var width = Math.floor( texture.image.width * levelScale );
  1606. var height = Math.floor( texture.image.height * levelScale );
  1607. var glFormat = utils.convert( texture.format );
  1608. textures.setTexture2D( texture, 0 );
  1609. _gl.copyTexImage2D( _gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0 );
  1610. state.unbindTexture();
  1611. };
  1612. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {
  1613. level = level || 0;
  1614. var width = srcTexture.image.width;
  1615. var height = srcTexture.image.height;
  1616. var glFormat = utils.convert( dstTexture.format );
  1617. var glType = utils.convert( dstTexture.type );
  1618. textures.setTexture2D( dstTexture, 0 );
  1619. if ( srcTexture.isDataTexture ) {
  1620. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  1621. } else {
  1622. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  1623. }
  1624. if ( level == 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1625. state.unbindTexture();
  1626. };
  1627. this.initTexture = function ( texture ) {
  1628. textures.setTexture2D( texture, 0 );
  1629. state.unbindTexture();
  1630. };
  1631. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  1632. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  1633. }
  1634. }
  1635. export { WebGLRenderer };