WebGLRenderer.js 62 KB

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