WebGLRenderer.js 63 KB

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