WebGLRenderer.js 67 KB

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