WebGLRenderer.js 69 KB

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