WebGLRenderer.js 66 KB

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