WebGLRenderer.js 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835
  1. import {
  2. RGBAFormat,
  3. HalfFloatType,
  4. FloatType,
  5. UnsignedByteType,
  6. LinearToneMapping,
  7. BackSide
  8. } from '../constants.js';
  9. import { _Math } from '../math/Math.js';
  10. import { DataTexture } from '../textures/DataTexture.js';
  11. import { Frustum } from '../math/Frustum.js';
  12. import { Matrix4 } from '../math/Matrix4.js';
  13. import { ShaderLib } from './shaders/ShaderLib.js';
  14. import { UniformsLib } from './shaders/UniformsLib.js';
  15. import { cloneUniforms } from './shaders/UniformsUtils.js';
  16. import { Vector2 } from '../math/Vector2.js';
  17. import { Vector3 } from '../math/Vector3.js';
  18. import { Vector4 } from '../math/Vector4.js';
  19. import { WebGLAnimation } from './webgl/WebGLAnimation.js';
  20. import { WebGLAttributes } from './webgl/WebGLAttributes.js';
  21. import { WebGLBackground } from './webgl/WebGLBackground.js';
  22. import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer.js';
  23. import { WebGLCapabilities } from './webgl/WebGLCapabilities.js';
  24. import { WebGLClipping } from './webgl/WebGLClipping.js';
  25. import { WebGLExtensions } from './webgl/WebGLExtensions.js';
  26. import { WebGLGeometries } from './webgl/WebGLGeometries.js';
  27. import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer.js';
  28. import { WebGLInfo } from './webgl/WebGLInfo.js';
  29. import { WebGLMorphtargets } from './webgl/WebGLMorphtargets.js';
  30. import { WebGLObjects } from './webgl/WebGLObjects.js';
  31. import { WebGLPrograms } from './webgl/WebGLPrograms.js';
  32. import { WebGLProperties } from './webgl/WebGLProperties.js';
  33. import { WebGLRenderLists } from './webgl/WebGLRenderLists.js';
  34. import { WebGLRenderStates } from './webgl/WebGLRenderStates.js';
  35. import { WebGLShadowMap } from './webgl/WebGLShadowMap.js';
  36. import { WebGLState } from './webgl/WebGLState.js';
  37. import { WebGLTextures } from './webgl/WebGLTextures.js';
  38. import { WebGLUniforms } from './webgl/WebGLUniforms.js';
  39. import { WebGLUtils } from './webgl/WebGLUtils.js';
  40. import { WebGLMultiview } from './webgl/WebGLMultiview.js';
  41. import { WebVRManager } from './webvr/WebVRManager.js';
  42. import { WebXRManager } from './webvr/WebXRManager.js';
  43. /**
  44. * @author supereggbert / http://www.paulbrunt.co.uk/
  45. * @author mrdoob / http://mrdoob.com/
  46. * @author alteredq / http://alteredqualia.com/
  47. * @author szimek / https://github.com/szimek/
  48. * @author tschw
  49. */
  50. function WebGLRenderer( parameters ) {
  51. parameters = parameters || {};
  52. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  53. _context = parameters.context !== undefined ? parameters.context : null,
  54. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  55. _depth = parameters.depth !== undefined ? parameters.depth : true,
  56. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  57. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  58. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  59. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  60. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  61. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  62. var currentRenderList = null;
  63. var currentRenderState = null;
  64. // public properties
  65. this.domElement = _canvas;
  66. // Debug configuration container
  67. this.debug = {
  68. /**
  69. * Enables error checking and reporting when shader programs are being compiled
  70. * @type {boolean}
  71. */
  72. checkShaderErrors: true
  73. };
  74. // clearing
  75. this.autoClear = true;
  76. this.autoClearColor = true;
  77. this.autoClearDepth = true;
  78. this.autoClearStencil = true;
  79. // scene graph
  80. this.sortObjects = true;
  81. // user-defined clipping
  82. this.clippingPlanes = [];
  83. this.localClippingEnabled = false;
  84. // physically based shading
  85. this.gammaFactor = 2.0; // for backwards compatibility
  86. this.gammaOutput = false;
  87. // physical lights
  88. this.physicallyCorrectLights = false;
  89. // tone mapping
  90. this.toneMapping = LinearToneMapping;
  91. this.toneMappingExposure = 1.0;
  92. this.toneMappingWhitePoint = 1.0;
  93. // morphs
  94. this.maxMorphTargets = 8;
  95. this.maxMorphNormals = 4;
  96. // internal properties
  97. var _this = this,
  98. _isContextLost = false,
  99. // internal state cache
  100. _framebuffer = null,
  101. _currentActiveCubeFace = 0,
  102. _currentActiveMipmapLevel = 0,
  103. _currentRenderTarget = null,
  104. _currentFramebuffer = null,
  105. _currentMaterialId = - 1,
  106. // geometry and program caching
  107. _currentGeometryProgram = {
  108. geometry: null,
  109. program: null,
  110. wireframe: false
  111. },
  112. _currentCamera = null,
  113. _currentArrayCamera = null,
  114. _currentViewport = new Vector4(),
  115. _currentScissor = new Vector4(),
  116. _currentScissorTest = null,
  117. //
  118. _width = _canvas.width,
  119. _height = _canvas.height,
  120. _pixelRatio = 1,
  121. _viewport = new Vector4( 0, 0, _width, _height ),
  122. _scissor = new Vector4( 0, 0, _width, _height ),
  123. _scissorTest = false,
  124. // frustum
  125. _frustum = new Frustum(),
  126. // clipping
  127. _clipping = new WebGLClipping(),
  128. _clippingEnabled = false,
  129. _localClippingEnabled = false,
  130. // camera matrices cache
  131. _projScreenMatrix = new Matrix4(),
  132. _vector3 = new Vector3();
  133. function getTargetPixelRatio() {
  134. return _currentRenderTarget === null ? _pixelRatio : 1;
  135. }
  136. // initialize
  137. var _gl;
  138. try {
  139. var contextAttributes = {
  140. alpha: _alpha,
  141. depth: _depth,
  142. stencil: _stencil,
  143. antialias: _antialias,
  144. premultipliedAlpha: _premultipliedAlpha,
  145. preserveDrawingBuffer: _preserveDrawingBuffer,
  146. powerPreference: _powerPreference,
  147. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat,
  148. xrCompatible: true
  149. };
  150. // event listeners must be registered before WebGL context is created, see #12753
  151. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  152. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  153. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  154. if ( _gl === null ) {
  155. if ( _canvas.getContext( 'webgl' ) !== null ) {
  156. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  157. } else {
  158. throw new Error( 'Error creating WebGL context.' );
  159. }
  160. }
  161. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  162. if ( _gl.getShaderPrecisionFormat === undefined ) {
  163. _gl.getShaderPrecisionFormat = function () {
  164. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  165. };
  166. }
  167. } catch ( error ) {
  168. console.error( 'THREE.WebGLRenderer: ' + error.message );
  169. throw error;
  170. }
  171. var extensions, capabilities, state, info;
  172. var properties, textures, attributes, geometries, objects;
  173. var programCache, renderLists, renderStates;
  174. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  175. var utils;
  176. function initGLContext() {
  177. extensions = new WebGLExtensions( _gl );
  178. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  179. if ( capabilities.isWebGL2 === false ) {
  180. extensions.get( 'WEBGL_depth_texture' );
  181. extensions.get( 'OES_texture_float' );
  182. extensions.get( 'OES_texture_half_float' );
  183. extensions.get( 'OES_texture_half_float_linear' );
  184. extensions.get( 'OES_standard_derivatives' );
  185. extensions.get( 'OES_element_index_uint' );
  186. extensions.get( 'ANGLE_instanced_arrays' );
  187. }
  188. extensions.get( 'OES_texture_float_linear' );
  189. utils = new WebGLUtils( _gl, extensions, capabilities );
  190. state = new WebGLState( _gl, extensions, capabilities );
  191. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  192. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  193. info = new WebGLInfo( _gl );
  194. properties = new WebGLProperties();
  195. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  196. attributes = new WebGLAttributes( _gl );
  197. geometries = new WebGLGeometries( _gl, attributes, info );
  198. objects = new WebGLObjects( _gl, geometries, attributes, info );
  199. morphtargets = new WebGLMorphtargets( _gl );
  200. programCache = new WebGLPrograms( _this, extensions, capabilities );
  201. renderLists = new WebGLRenderLists();
  202. renderStates = new WebGLRenderStates();
  203. background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );
  204. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  205. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  206. info.programs = programCache.programs;
  207. _this.capabilities = capabilities;
  208. _this.extensions = extensions;
  209. _this.properties = properties;
  210. _this.renderLists = renderLists;
  211. _this.state = state;
  212. _this.info = info;
  213. }
  214. initGLContext();
  215. // xr
  216. var xr = ( typeof navigator !== 'undefined' && 'xr' in navigator ) ? new WebXRManager( _this, _gl ) : new WebVRManager( _this );
  217. this.xr = xr;
  218. // Multiview
  219. var multiview = new WebGLMultiview( _this, _gl );
  220. // shadow map
  221. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  222. this.shadowMap = shadowMap;
  223. // API
  224. this.getContext = function () {
  225. return _gl;
  226. };
  227. this.getContextAttributes = function () {
  228. return _gl.getContextAttributes();
  229. };
  230. this.forceContextLoss = function () {
  231. var extension = extensions.get( 'WEBGL_lose_context' );
  232. if ( extension ) extension.loseContext();
  233. };
  234. this.forceContextRestore = function () {
  235. var extension = extensions.get( 'WEBGL_lose_context' );
  236. if ( extension ) extension.restoreContext();
  237. };
  238. this.getPixelRatio = function () {
  239. return _pixelRatio;
  240. };
  241. this.setPixelRatio = function ( value ) {
  242. if ( value === undefined ) return;
  243. _pixelRatio = value;
  244. this.setSize( _width, _height, false );
  245. };
  246. this.getSize = function ( target ) {
  247. if ( target === undefined ) {
  248. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  249. target = new Vector2();
  250. }
  251. return target.set( _width, _height );
  252. };
  253. this.setSize = function ( width, height, updateStyle ) {
  254. if ( xr.isPresenting() ) {
  255. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  256. return;
  257. }
  258. _width = width;
  259. _height = height;
  260. _canvas.width = Math.floor( width * _pixelRatio );
  261. _canvas.height = Math.floor( height * _pixelRatio );
  262. if ( updateStyle !== false ) {
  263. _canvas.style.width = width + 'px';
  264. _canvas.style.height = height + 'px';
  265. }
  266. this.setViewport( 0, 0, width, height );
  267. };
  268. this.getDrawingBufferSize = function ( target ) {
  269. if ( target === undefined ) {
  270. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  271. target = new Vector2();
  272. }
  273. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  274. };
  275. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  276. _width = width;
  277. _height = height;
  278. _pixelRatio = pixelRatio;
  279. _canvas.width = Math.floor( width * pixelRatio );
  280. _canvas.height = Math.floor( height * pixelRatio );
  281. this.setViewport( 0, 0, width, height );
  282. };
  283. this.getCurrentViewport = function ( target ) {
  284. if ( target === undefined ) {
  285. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  286. target = new Vector4();
  287. }
  288. return target.copy( _currentViewport );
  289. };
  290. this.getViewport = function ( target ) {
  291. return target.copy( _viewport );
  292. };
  293. this.setViewport = function ( x, y, width, height ) {
  294. if ( x.isVector4 ) {
  295. _viewport.set( x.x, x.y, x.z, x.w );
  296. } else {
  297. _viewport.set( x, y, width, height );
  298. }
  299. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  300. };
  301. this.getScissor = function ( target ) {
  302. return target.copy( _scissor );
  303. };
  304. this.setScissor = function ( x, y, width, height ) {
  305. if ( x.isVector4 ) {
  306. _scissor.set( x.x, x.y, x.z, x.w );
  307. } else {
  308. _scissor.set( x, y, width, height );
  309. }
  310. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  311. };
  312. this.getScissorTest = function () {
  313. return _scissorTest;
  314. };
  315. this.setScissorTest = function ( boolean ) {
  316. state.setScissorTest( _scissorTest = boolean );
  317. };
  318. // Clearing
  319. this.getClearColor = function () {
  320. return background.getClearColor();
  321. };
  322. this.setClearColor = function () {
  323. background.setClearColor.apply( background, arguments );
  324. };
  325. this.getClearAlpha = function () {
  326. return background.getClearAlpha();
  327. };
  328. this.setClearAlpha = function () {
  329. background.setClearAlpha.apply( background, arguments );
  330. };
  331. this.clear = function ( color, depth, stencil ) {
  332. var bits = 0;
  333. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  334. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  335. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  336. _gl.clear( bits );
  337. };
  338. this.clearColor = function () {
  339. this.clear( true, false, false );
  340. };
  341. this.clearDepth = function () {
  342. this.clear( false, true, false );
  343. };
  344. this.clearStencil = function () {
  345. this.clear( false, false, true );
  346. };
  347. //
  348. this.dispose = function () {
  349. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  350. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  351. renderLists.dispose();
  352. renderStates.dispose();
  353. properties.dispose();
  354. objects.dispose();
  355. xr.dispose();
  356. animation.stop();
  357. };
  358. // Events
  359. function onContextLost( event ) {
  360. event.preventDefault();
  361. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  362. _isContextLost = true;
  363. }
  364. function onContextRestore( /* event */ ) {
  365. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  366. _isContextLost = false;
  367. initGLContext();
  368. }
  369. function onMaterialDispose( event ) {
  370. var material = event.target;
  371. material.removeEventListener( 'dispose', onMaterialDispose );
  372. deallocateMaterial( material );
  373. }
  374. // Buffer deallocation
  375. function deallocateMaterial( material ) {
  376. releaseMaterialProgramReference( material );
  377. properties.remove( material );
  378. }
  379. function releaseMaterialProgramReference( material ) {
  380. var programInfo = properties.get( material ).program;
  381. material.program = undefined;
  382. if ( programInfo !== undefined ) {
  383. programCache.releaseProgram( programInfo );
  384. }
  385. }
  386. // Buffer rendering
  387. function renderObjectImmediate( object, program ) {
  388. object.render( function ( object ) {
  389. _this.renderBufferImmediate( object, program );
  390. } );
  391. }
  392. this.renderBufferImmediate = function ( object, program ) {
  393. state.initAttributes();
  394. var buffers = properties.get( object );
  395. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  396. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  397. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  398. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  399. var programAttributes = program.getAttributes();
  400. if ( object.hasPositions ) {
  401. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  402. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  403. state.enableAttribute( programAttributes.position );
  404. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  405. }
  406. if ( object.hasNormals ) {
  407. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  408. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  409. state.enableAttribute( programAttributes.normal );
  410. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  411. }
  412. if ( object.hasUvs ) {
  413. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  414. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  415. state.enableAttribute( programAttributes.uv );
  416. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  417. }
  418. if ( object.hasColors ) {
  419. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  420. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  421. state.enableAttribute( programAttributes.color );
  422. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  423. }
  424. state.disableUnusedAttributes();
  425. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  426. object.count = 0;
  427. };
  428. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  429. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  430. var program = setProgram( camera, fog, material, object );
  431. state.setMaterial( material, frontFaceCW );
  432. var updateBuffers = false;
  433. if ( _currentGeometryProgram.geometry !== geometry.id ||
  434. _currentGeometryProgram.program !== program.id ||
  435. _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) {
  436. _currentGeometryProgram.geometry = geometry.id;
  437. _currentGeometryProgram.program = program.id;
  438. _currentGeometryProgram.wireframe = material.wireframe === true;
  439. updateBuffers = true;
  440. }
  441. if ( material.morphTargets || material.morphNormals ) {
  442. morphtargets.update( object, geometry, material, program );
  443. updateBuffers = true;
  444. }
  445. //
  446. var index = geometry.index;
  447. var position = geometry.attributes.position;
  448. //
  449. if ( index !== null && index.count === 0 ) return;
  450. if ( position === undefined || position.count === 0 ) return;
  451. //
  452. var rangeFactor = 1;
  453. if ( material.wireframe === true ) {
  454. index = geometries.getWireframeAttribute( geometry );
  455. rangeFactor = 2;
  456. }
  457. var attribute;
  458. var renderer = bufferRenderer;
  459. if ( index !== null ) {
  460. attribute = attributes.get( index );
  461. renderer = indexedBufferRenderer;
  462. renderer.setIndex( attribute );
  463. }
  464. if ( updateBuffers ) {
  465. setupVertexAttributes( object, geometry, material, program );
  466. if ( index !== null ) {
  467. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  468. }
  469. }
  470. //
  471. var dataCount = ( index !== null ) ? index.count : position.count;
  472. var rangeStart = geometry.drawRange.start * rangeFactor;
  473. var rangeCount = geometry.drawRange.count * rangeFactor;
  474. var groupStart = group !== null ? group.start * rangeFactor : 0;
  475. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  476. var drawStart = Math.max( rangeStart, groupStart );
  477. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  478. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  479. if ( drawCount === 0 ) return;
  480. //
  481. if ( object.isMesh ) {
  482. if ( material.wireframe === true ) {
  483. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  484. renderer.setMode( _gl.LINES );
  485. } else {
  486. renderer.setMode( _gl.TRIANGLES );
  487. }
  488. } else if ( object.isLine ) {
  489. var lineWidth = material.linewidth;
  490. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  491. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  492. if ( object.isLineSegments ) {
  493. renderer.setMode( _gl.LINES );
  494. } else if ( object.isLineLoop ) {
  495. renderer.setMode( _gl.LINE_LOOP );
  496. } else {
  497. renderer.setMode( _gl.LINE_STRIP );
  498. }
  499. } else if ( object.isPoints ) {
  500. renderer.setMode( _gl.POINTS );
  501. } else if ( object.isSprite ) {
  502. renderer.setMode( _gl.TRIANGLES );
  503. }
  504. if ( object.isInstancedMesh ) {
  505. renderer.renderInstances( geometry, drawStart, drawCount, object.count );
  506. } else if ( geometry.isInstancedBufferGeometry ) {
  507. renderer.renderInstances( geometry, drawStart, drawCount, geometry.maxInstancedCount );
  508. } else {
  509. renderer.render( drawStart, drawCount );
  510. }
  511. };
  512. function setupVertexAttributes( object, geometry, material, program ) {
  513. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  514. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  515. }
  516. state.initAttributes();
  517. var geometryAttributes = geometry.attributes;
  518. var programAttributes = program.getAttributes();
  519. var materialDefaultAttributeValues = material.defaultAttributeValues;
  520. for ( var name in programAttributes ) {
  521. var programAttribute = programAttributes[ name ];
  522. if ( programAttribute >= 0 ) {
  523. var geometryAttribute = geometryAttributes[ name ];
  524. if ( geometryAttribute !== undefined ) {
  525. var normalized = geometryAttribute.normalized;
  526. var size = geometryAttribute.itemSize;
  527. var attribute = attributes.get( geometryAttribute );
  528. // TODO Attribute may not be available on context restore
  529. if ( attribute === undefined ) continue;
  530. var buffer = attribute.buffer;
  531. var type = attribute.type;
  532. var bytesPerElement = attribute.bytesPerElement;
  533. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  534. var data = geometryAttribute.data;
  535. var stride = data.stride;
  536. var offset = geometryAttribute.offset;
  537. if ( data && data.isInstancedInterleavedBuffer ) {
  538. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  539. if ( geometry.maxInstancedCount === undefined ) {
  540. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  541. }
  542. } else {
  543. state.enableAttribute( programAttribute );
  544. }
  545. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  546. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  547. } else {
  548. if ( geometryAttribute.isInstancedBufferAttribute ) {
  549. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  550. if ( geometry.maxInstancedCount === undefined ) {
  551. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  552. }
  553. } else {
  554. state.enableAttribute( programAttribute );
  555. }
  556. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  557. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  558. }
  559. } else if ( name === 'instanceMatrix' ) {
  560. var attribute = attributes.get( object.instanceMatrix );
  561. // TODO Attribute may not be available on context restore
  562. if ( attribute === undefined ) continue;
  563. var buffer = attribute.buffer;
  564. var type = attribute.type;
  565. state.enableAttributeAndDivisor( programAttribute + 0, 1 );
  566. state.enableAttributeAndDivisor( programAttribute + 1, 1 );
  567. state.enableAttributeAndDivisor( programAttribute + 2, 1 );
  568. state.enableAttributeAndDivisor( programAttribute + 3, 1 );
  569. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  570. _gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  571. _gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  572. _gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  573. _gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  574. } else if ( materialDefaultAttributeValues !== undefined ) {
  575. var value = materialDefaultAttributeValues[ name ];
  576. if ( value !== undefined ) {
  577. switch ( value.length ) {
  578. case 2:
  579. _gl.vertexAttrib2fv( programAttribute, value );
  580. break;
  581. case 3:
  582. _gl.vertexAttrib3fv( programAttribute, value );
  583. break;
  584. case 4:
  585. _gl.vertexAttrib4fv( programAttribute, value );
  586. break;
  587. default:
  588. _gl.vertexAttrib1fv( programAttribute, value );
  589. }
  590. }
  591. }
  592. }
  593. }
  594. state.disableUnusedAttributes();
  595. }
  596. // Compile
  597. this.compile = function ( scene, camera ) {
  598. currentRenderState = renderStates.get( scene, camera );
  599. currentRenderState.init();
  600. scene.traverse( function ( object ) {
  601. if ( object.isLight ) {
  602. currentRenderState.pushLight( object );
  603. if ( object.castShadow ) {
  604. currentRenderState.pushShadow( object );
  605. }
  606. }
  607. } );
  608. currentRenderState.setupLights( camera );
  609. scene.traverse( function ( object ) {
  610. if ( object.material ) {
  611. if ( Array.isArray( object.material ) ) {
  612. for ( var i = 0; i < object.material.length; i ++ ) {
  613. initMaterial( object.material[ i ], scene.fog, object );
  614. }
  615. } else {
  616. initMaterial( object.material, scene.fog, object );
  617. }
  618. }
  619. } );
  620. };
  621. // Animation Loop
  622. var onAnimationFrameCallback = null;
  623. function onAnimationFrame( time ) {
  624. if ( xr.isPresenting() ) return;
  625. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  626. }
  627. var animation = new WebGLAnimation();
  628. animation.setAnimationLoop( onAnimationFrame );
  629. if ( typeof window !== 'undefined' ) animation.setContext( window );
  630. this.setAnimationLoop = function ( callback ) {
  631. onAnimationFrameCallback = callback;
  632. xr.setAnimationLoop( callback );
  633. animation.start();
  634. };
  635. // Rendering
  636. this.render = function ( scene, camera ) {
  637. var renderTarget, forceClear;
  638. if ( arguments[ 2 ] !== undefined ) {
  639. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  640. renderTarget = arguments[ 2 ];
  641. }
  642. if ( arguments[ 3 ] !== undefined ) {
  643. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  644. forceClear = arguments[ 3 ];
  645. }
  646. if ( ! ( camera && camera.isCamera ) ) {
  647. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  648. return;
  649. }
  650. if ( _isContextLost ) return;
  651. // reset caching for this frame
  652. _currentGeometryProgram.geometry = null;
  653. _currentGeometryProgram.program = null;
  654. _currentGeometryProgram.wireframe = false;
  655. _currentMaterialId = - 1;
  656. _currentCamera = null;
  657. // update scene graph
  658. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  659. // update camera matrices and frustum
  660. if ( camera.parent === null ) camera.updateMatrixWorld();
  661. if ( xr.enabled && xr.isPresenting() ) {
  662. camera = xr.getCamera( camera );
  663. }
  664. //
  665. currentRenderState = renderStates.get( scene, camera );
  666. currentRenderState.init();
  667. scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  668. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  669. _frustum.setFromMatrix( _projScreenMatrix );
  670. _localClippingEnabled = this.localClippingEnabled;
  671. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  672. currentRenderList = renderLists.get( scene, camera );
  673. currentRenderList.init();
  674. projectObject( scene, camera, 0, _this.sortObjects );
  675. if ( _this.sortObjects === true ) {
  676. currentRenderList.sort();
  677. }
  678. //
  679. if ( _clippingEnabled ) _clipping.beginShadows();
  680. var shadowsArray = currentRenderState.state.shadowsArray;
  681. shadowMap.render( shadowsArray, scene, camera );
  682. currentRenderState.setupLights( camera );
  683. if ( _clippingEnabled ) _clipping.endShadows();
  684. //
  685. if ( this.info.autoReset ) this.info.reset();
  686. if ( renderTarget !== undefined ) {
  687. this.setRenderTarget( renderTarget );
  688. }
  689. if ( xr.enabled && multiview.isAvailable() ) {
  690. multiview.attachCamera( camera );
  691. }
  692. //
  693. background.render( currentRenderList, scene, camera, forceClear );
  694. // render scene
  695. var opaqueObjects = currentRenderList.opaque;
  696. var transparentObjects = currentRenderList.transparent;
  697. if ( scene.overrideMaterial ) {
  698. var overrideMaterial = scene.overrideMaterial;
  699. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  700. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  701. } else {
  702. // opaque pass (front-to-back order)
  703. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  704. // transparent pass (back-to-front order)
  705. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  706. }
  707. //
  708. scene.onAfterRender( _this, scene, camera );
  709. //
  710. if ( _currentRenderTarget !== null ) {
  711. // Generate mipmap if we're using any kind of mipmap filtering
  712. textures.updateRenderTargetMipmap( _currentRenderTarget );
  713. // resolve multisample renderbuffers to a single-sample texture if necessary
  714. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  715. }
  716. // Ensure depth buffer writing is enabled so it can be cleared on next render
  717. state.buffers.depth.setTest( true );
  718. state.buffers.depth.setMask( true );
  719. state.buffers.color.setMask( true );
  720. state.setPolygonOffset( false );
  721. if ( xr.enabled ) {
  722. if ( multiview.isAvailable() ) {
  723. multiview.detachCamera( camera );
  724. }
  725. xr.submitFrame();
  726. }
  727. // _gl.finish();
  728. currentRenderList = null;
  729. currentRenderState = null;
  730. };
  731. function projectObject( object, camera, groupOrder, sortObjects ) {
  732. if ( object.visible === false ) return;
  733. var visible = object.layers.test( camera.layers );
  734. if ( visible ) {
  735. if ( object.isGroup ) {
  736. groupOrder = object.renderOrder;
  737. } else if ( object.isLOD ) {
  738. if ( object.autoUpdate === true ) object.update( camera );
  739. } else if ( object.isLight ) {
  740. currentRenderState.pushLight( object );
  741. if ( object.castShadow ) {
  742. currentRenderState.pushShadow( object );
  743. }
  744. } else if ( object.isSprite ) {
  745. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  746. if ( sortObjects ) {
  747. _vector3.setFromMatrixPosition( object.matrixWorld )
  748. .applyMatrix4( _projScreenMatrix );
  749. }
  750. var geometry = objects.update( object );
  751. var material = object.material;
  752. if ( material.visible ) {
  753. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  754. }
  755. }
  756. } else if ( object.isImmediateRenderObject ) {
  757. if ( sortObjects ) {
  758. _vector3.setFromMatrixPosition( object.matrixWorld )
  759. .applyMatrix4( _projScreenMatrix );
  760. }
  761. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  762. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  763. if ( object.isSkinnedMesh ) {
  764. // update skeleton only once in a frame
  765. if ( object.skeleton.frame !== info.render.frame ) {
  766. object.skeleton.update();
  767. object.skeleton.frame = info.render.frame;
  768. }
  769. }
  770. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  771. if ( sortObjects ) {
  772. _vector3.setFromMatrixPosition( object.matrixWorld )
  773. .applyMatrix4( _projScreenMatrix );
  774. }
  775. var geometry = objects.update( object );
  776. var material = object.material;
  777. if ( Array.isArray( material ) ) {
  778. var groups = geometry.groups;
  779. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  780. var group = groups[ i ];
  781. var groupMaterial = material[ group.materialIndex ];
  782. if ( groupMaterial && groupMaterial.visible ) {
  783. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  784. }
  785. }
  786. } else if ( material.visible ) {
  787. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  788. }
  789. }
  790. }
  791. }
  792. var children = object.children;
  793. for ( var i = 0, l = children.length; i < l; i ++ ) {
  794. projectObject( children[ i ], camera, groupOrder, sortObjects );
  795. }
  796. }
  797. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  798. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  799. var renderItem = renderList[ i ];
  800. var object = renderItem.object;
  801. var geometry = renderItem.geometry;
  802. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  803. var group = renderItem.group;
  804. if ( camera.isArrayCamera ) {
  805. _currentArrayCamera = camera;
  806. if ( xr.enabled && multiview.isAvailable() ) {
  807. renderObject( object, scene, camera, geometry, material, group );
  808. } else {
  809. var cameras = camera.cameras;
  810. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  811. var camera2 = cameras[ j ];
  812. if ( object.layers.test( camera2.layers ) ) {
  813. state.viewport( _currentViewport.copy( camera2.viewport ) );
  814. currentRenderState.setupLights( camera2 );
  815. renderObject( object, scene, camera2, geometry, material, group );
  816. }
  817. }
  818. }
  819. } else {
  820. _currentArrayCamera = null;
  821. renderObject( object, scene, camera, geometry, material, group );
  822. }
  823. }
  824. }
  825. function renderObject( object, scene, camera, geometry, material, group ) {
  826. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  827. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  828. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  829. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  830. if ( object.isImmediateRenderObject ) {
  831. var program = setProgram( camera, scene.fog, material, object );
  832. state.setMaterial( material );
  833. _currentGeometryProgram.geometry = null;
  834. _currentGeometryProgram.program = null;
  835. _currentGeometryProgram.wireframe = false;
  836. renderObjectImmediate( object, program );
  837. } else {
  838. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  839. }
  840. object.onAfterRender( _this, scene, camera, geometry, material, group );
  841. currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );
  842. }
  843. function initMaterial( material, fog, object ) {
  844. var materialProperties = properties.get( material );
  845. var lights = currentRenderState.state.lights;
  846. var shadowsArray = currentRenderState.state.shadowsArray;
  847. var lightsStateVersion = lights.state.version;
  848. var parameters = programCache.getParameters(
  849. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  850. var programCacheKey = programCache.getProgramCacheKey( material, parameters );
  851. var program = materialProperties.program;
  852. var programChange = true;
  853. if ( program === undefined ) {
  854. // new material
  855. material.addEventListener( 'dispose', onMaterialDispose );
  856. } else if ( program.cacheKey !== programCacheKey ) {
  857. // changed glsl or parameters
  858. releaseMaterialProgramReference( material );
  859. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  860. materialProperties.lightsStateVersion = lightsStateVersion;
  861. programChange = false;
  862. } else if ( parameters.shaderID !== undefined ) {
  863. // same glsl and uniform list
  864. return;
  865. } else {
  866. // only rebuild uniform list
  867. programChange = false;
  868. }
  869. if ( programChange ) {
  870. if ( parameters.shaderID ) {
  871. var shader = ShaderLib[ parameters.shaderID ];
  872. materialProperties.shader = {
  873. name: material.type,
  874. uniforms: cloneUniforms( shader.uniforms ),
  875. vertexShader: shader.vertexShader,
  876. fragmentShader: shader.fragmentShader
  877. };
  878. } else {
  879. materialProperties.shader = {
  880. name: material.type,
  881. uniforms: material.uniforms,
  882. vertexShader: material.vertexShader,
  883. fragmentShader: material.fragmentShader
  884. };
  885. }
  886. material.onBeforeCompile( materialProperties.shader, _this );
  887. // Computing cache key again as onBeforeCompile may have changed the shaders
  888. programCacheKey = programCache.getProgramCacheKey( material, parameters );
  889. program = programCache.acquireProgram( material, materialProperties.shader, parameters, programCacheKey );
  890. materialProperties.program = program;
  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.shader.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 = 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, fog, material, object ) {
  945. textures.resetTextureUnits();
  946. var materialProperties = properties.get( material );
  947. var lights = currentRenderState.state.lights;
  948. if ( _clippingEnabled ) {
  949. if ( _localClippingEnabled || camera !== _currentCamera ) {
  950. var useCache =
  951. camera === _currentCamera &&
  952. material.id === _currentMaterialId;
  953. // we might want to call this function with some ClippingGroup
  954. // object instead of the material, once it becomes feasible
  955. // (#8465, #8379)
  956. _clipping.setState(
  957. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  958. camera, materialProperties, useCache );
  959. }
  960. }
  961. if ( material.version === materialProperties.__version ) {
  962. if ( materialProperties.program === undefined ) {
  963. material.needsUpdate = true;
  964. } else if ( material.fog && materialProperties.fog !== fog ) {
  965. material.needsUpdate = true;
  966. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  967. material.needsUpdate = true;
  968. } else if ( materialProperties.numClippingPlanes !== undefined &&
  969. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  970. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  971. material.needsUpdate = true;
  972. }
  973. }
  974. if ( material.version !== materialProperties.__version ) {
  975. initMaterial( material, fog, object );
  976. materialProperties.__version = material.version;
  977. }
  978. var refreshProgram = false;
  979. var refreshMaterial = false;
  980. var refreshLights = false;
  981. var program = materialProperties.program,
  982. p_uniforms = program.getUniforms(),
  983. m_uniforms = materialProperties.shader.uniforms;
  984. if ( state.useProgram( program.program ) ) {
  985. refreshProgram = true;
  986. refreshMaterial = true;
  987. refreshLights = true;
  988. }
  989. if ( material.id !== _currentMaterialId ) {
  990. _currentMaterialId = material.id;
  991. refreshMaterial = true;
  992. }
  993. if ( refreshProgram || _currentCamera !== camera ) {
  994. if ( program.numMultiviewViews > 0 ) {
  995. multiview.updateCameraProjectionMatricesUniform( camera, p_uniforms );
  996. } else {
  997. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  998. }
  999. if ( capabilities.logarithmicDepthBuffer ) {
  1000. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1001. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1002. }
  1003. if ( _currentCamera !== camera ) {
  1004. _currentCamera = camera;
  1005. // lighting uniforms depend on the camera so enforce an update
  1006. // now, in case this material supports lights - or later, when
  1007. // the next material that does gets activated:
  1008. refreshMaterial = true; // set to true on material change
  1009. refreshLights = true; // remains set until update done
  1010. }
  1011. // load material specific uniforms
  1012. // (shader material also gets them for the sake of genericity)
  1013. if ( material.isShaderMaterial ||
  1014. material.isMeshPhongMaterial ||
  1015. material.isMeshToonMaterial ||
  1016. material.isMeshStandardMaterial ||
  1017. material.envMap ) {
  1018. var uCamPos = p_uniforms.map.cameraPosition;
  1019. if ( uCamPos !== undefined ) {
  1020. uCamPos.setValue( _gl,
  1021. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1022. }
  1023. }
  1024. if ( material.isMeshPhongMaterial ||
  1025. material.isMeshToonMaterial ||
  1026. material.isMeshLambertMaterial ||
  1027. material.isMeshBasicMaterial ||
  1028. material.isMeshStandardMaterial ||
  1029. material.isShaderMaterial ) {
  1030. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  1031. }
  1032. if ( material.isMeshPhongMaterial ||
  1033. material.isMeshToonMaterial ||
  1034. material.isMeshLambertMaterial ||
  1035. material.isMeshBasicMaterial ||
  1036. material.isMeshStandardMaterial ||
  1037. material.isShaderMaterial ||
  1038. material.skinning ) {
  1039. if ( program.numMultiviewViews > 0 ) {
  1040. multiview.updateCameraViewMatricesUniform( camera, p_uniforms );
  1041. } else {
  1042. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1043. }
  1044. }
  1045. }
  1046. // skinning uniforms must be set even if material didn't change
  1047. // auto-setting of texture unit for bone texture must go before other textures
  1048. // not sure why, but otherwise weird things happen
  1049. if ( material.skinning ) {
  1050. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1051. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1052. var skeleton = object.skeleton;
  1053. if ( skeleton ) {
  1054. var bones = skeleton.bones;
  1055. if ( capabilities.floatVertexTextures ) {
  1056. if ( skeleton.boneTexture === undefined ) {
  1057. // layout (1 matrix = 4 pixels)
  1058. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  1059. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  1060. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  1061. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  1062. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  1063. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  1064. size = _Math.ceilPowerOfTwo( size );
  1065. size = Math.max( size, 4 );
  1066. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  1067. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  1068. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  1069. skeleton.boneMatrices = boneMatrices;
  1070. skeleton.boneTexture = boneTexture;
  1071. skeleton.boneTextureSize = size;
  1072. }
  1073. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  1074. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  1075. } else {
  1076. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  1077. }
  1078. }
  1079. }
  1080. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  1081. materialProperties.receiveShadow = object.receiveShadow;
  1082. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  1083. }
  1084. if ( refreshMaterial ) {
  1085. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  1086. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  1087. if ( materialProperties.needsLights ) {
  1088. // the current material requires lighting info
  1089. // note: all lighting uniforms are always set correctly
  1090. // they simply reference the renderer's state for their
  1091. // values
  1092. //
  1093. // use the current material's .needsUpdate flags to set
  1094. // the GL state when required
  1095. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1096. }
  1097. // refresh uniforms common to several materials
  1098. if ( fog && material.fog ) {
  1099. refreshUniformsFog( m_uniforms, fog );
  1100. }
  1101. if ( material.isMeshBasicMaterial ) {
  1102. refreshUniformsCommon( m_uniforms, material );
  1103. } else if ( material.isMeshLambertMaterial ) {
  1104. refreshUniformsCommon( m_uniforms, material );
  1105. refreshUniformsLambert( m_uniforms, material );
  1106. } else if ( material.isMeshToonMaterial ) {
  1107. refreshUniformsCommon( m_uniforms, material );
  1108. refreshUniformsToon( m_uniforms, material );
  1109. } else if ( material.isMeshPhongMaterial ) {
  1110. refreshUniformsCommon( m_uniforms, material );
  1111. refreshUniformsPhong( m_uniforms, material );
  1112. } else if ( material.isMeshStandardMaterial ) {
  1113. refreshUniformsCommon( m_uniforms, material );
  1114. if ( material.isMeshPhysicalMaterial ) {
  1115. refreshUniformsPhysical( m_uniforms, material );
  1116. } else {
  1117. refreshUniformsStandard( m_uniforms, material );
  1118. }
  1119. } else if ( material.isMeshMatcapMaterial ) {
  1120. refreshUniformsCommon( m_uniforms, material );
  1121. refreshUniformsMatcap( m_uniforms, material );
  1122. } else if ( material.isMeshDepthMaterial ) {
  1123. refreshUniformsCommon( m_uniforms, material );
  1124. refreshUniformsDepth( m_uniforms, material );
  1125. } else if ( material.isMeshDistanceMaterial ) {
  1126. refreshUniformsCommon( m_uniforms, material );
  1127. refreshUniformsDistance( m_uniforms, material );
  1128. } else if ( material.isMeshNormalMaterial ) {
  1129. refreshUniformsCommon( m_uniforms, material );
  1130. refreshUniformsNormal( m_uniforms, material );
  1131. } else if ( material.isLineBasicMaterial ) {
  1132. refreshUniformsLine( m_uniforms, material );
  1133. if ( material.isLineDashedMaterial ) {
  1134. refreshUniformsDash( m_uniforms, material );
  1135. }
  1136. } else if ( material.isPointsMaterial ) {
  1137. refreshUniformsPoints( m_uniforms, material );
  1138. } else if ( material.isSpriteMaterial ) {
  1139. refreshUniformsSprites( m_uniforms, material );
  1140. } else if ( material.isShadowMaterial ) {
  1141. m_uniforms.color.value.copy( material.color );
  1142. m_uniforms.opacity.value = material.opacity;
  1143. } else if ( material.envMap ) {
  1144. refreshUniformsCommon( m_uniforms, material );
  1145. }
  1146. // RectAreaLight Texture
  1147. // TODO (mrdoob): Find a nicer implementation
  1148. if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
  1149. if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;
  1150. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  1151. if ( material.isShaderMaterial ) {
  1152. material.uniformsNeedUpdate = false; // #15581
  1153. }
  1154. }
  1155. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  1156. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  1157. material.uniformsNeedUpdate = false;
  1158. }
  1159. if ( material.isSpriteMaterial ) {
  1160. p_uniforms.setValue( _gl, 'center', object.center );
  1161. }
  1162. // common matrices
  1163. if ( program.numMultiviewViews > 0 ) {
  1164. multiview.updateObjectMatricesUniforms( object, camera, p_uniforms );
  1165. } else {
  1166. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  1167. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  1168. }
  1169. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1170. return program;
  1171. }
  1172. // Uniforms (refresh uniforms objects)
  1173. function refreshUniformsCommon( uniforms, material ) {
  1174. uniforms.opacity.value = material.opacity;
  1175. if ( material.color ) {
  1176. uniforms.diffuse.value.copy( material.color );
  1177. }
  1178. if ( material.emissive ) {
  1179. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1180. }
  1181. if ( material.map ) {
  1182. uniforms.map.value = material.map;
  1183. }
  1184. if ( material.alphaMap ) {
  1185. uniforms.alphaMap.value = material.alphaMap;
  1186. }
  1187. if ( material.specularMap ) {
  1188. uniforms.specularMap.value = material.specularMap;
  1189. }
  1190. if ( material.envMap ) {
  1191. uniforms.envMap.value = material.envMap;
  1192. // don't flip CubeTexture envMaps, flip everything else:
  1193. // WebGLRenderTargetCube will be flipped for backwards compatibility
  1194. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  1195. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  1196. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  1197. uniforms.reflectivity.value = material.reflectivity;
  1198. uniforms.refractionRatio.value = material.refractionRatio;
  1199. uniforms.maxMipLevel.value = properties.get( material.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 ) {
  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 ) {
  1417. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1418. uniforms.envMapIntensity.value = material.envMapIntensity;
  1419. }
  1420. }
  1421. function refreshUniformsPhysical( uniforms, material ) {
  1422. refreshUniformsStandard( uniforms, material );
  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.isWebGLRenderTargetCube ) {
  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.isWebGLRenderTargetCube && 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. var width = srcTexture.image.width;
  1614. var height = srcTexture.image.height;
  1615. var glFormat = utils.convert( dstTexture.format );
  1616. var glType = utils.convert( dstTexture.type );
  1617. textures.setTexture2D( dstTexture, 0 );
  1618. if ( srcTexture.isDataTexture ) {
  1619. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  1620. } else {
  1621. _gl.texSubImage2D( _gl.TEXTURE_2D, level || 0, position.x, position.y, glFormat, glType, srcTexture.image );
  1622. }
  1623. state.unbindTexture();
  1624. };
  1625. this.initTexture = function ( texture ) {
  1626. textures.setTexture2D( texture, 0 );
  1627. state.unbindTexture();
  1628. };
  1629. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  1630. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  1631. }
  1632. }
  1633. export { WebGLRenderer };