WebGLRenderer.js 68 KB

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