WebGLRenderer.js 61 KB

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