WebGLRenderer.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824
  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 && 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 && 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, 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. uniforms.clippingPlanes = _clipping.uniform;
  955. }
  956. materialProperties.fog = fog;
  957. // store the light setup it was created for
  958. materialProperties.lightsHash = _lights.hash;
  959. if ( material.lights ) {
  960. // wire up the material to this renderer's lighting state
  961. uniforms.ambientLightColor.value = _lights.ambient;
  962. uniforms.directionalLights.value = _lights.directional;
  963. uniforms.spotLights.value = _lights.spot;
  964. uniforms.pointLights.value = _lights.point;
  965. uniforms.hemisphereLights.value = _lights.hemi;
  966. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  967. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  968. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  969. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  970. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  971. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  972. }
  973. var progUniforms = materialProperties.program.getUniforms(),
  974. uniformsList =
  975. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  976. materialProperties.uniformsList = uniformsList;
  977. }
  978. function setMaterial( material ) {
  979. material.side === DoubleSide
  980. ? state.disable( _gl.CULL_FACE )
  981. : state.enable( _gl.CULL_FACE );
  982. state.setFlipSided( material.side === BackSide );
  983. material.transparent === true
  984. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  985. : state.setBlending( NoBlending );
  986. state.setDepthFunc( material.depthFunc );
  987. state.setDepthTest( material.depthTest );
  988. state.setDepthWrite( material.depthWrite );
  989. state.setColorWrite( material.colorWrite );
  990. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  991. }
  992. function setProgram( camera, fog, material, object ) {
  993. _usedTextureUnits = 0;
  994. var materialProperties = properties.get( material );
  995. if ( _clippingEnabled ) {
  996. if ( _localClippingEnabled || camera !== _currentCamera ) {
  997. var useCache =
  998. camera === _currentCamera &&
  999. material.id === _currentMaterialId;
  1000. // we might want to call this function with some ClippingGroup
  1001. // object instead of the material, once it becomes feasible
  1002. // (#8465, #8379)
  1003. _clipping.setState(
  1004. material.clippingPlanes, material.clipShadows,
  1005. camera, materialProperties, useCache );
  1006. }
  1007. }
  1008. if ( material.needsUpdate === false ) {
  1009. if ( materialProperties.program === undefined ) {
  1010. material.needsUpdate = true;
  1011. } else if ( material.fog && materialProperties.fog !== fog ) {
  1012. material.needsUpdate = true;
  1013. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  1014. material.needsUpdate = true;
  1015. } else if ( materialProperties.numClippingPlanes !== undefined &&
  1016. materialProperties.numClippingPlanes !== _clipping.numPlanes ) {
  1017. material.needsUpdate = true;
  1018. }
  1019. }
  1020. if ( material.needsUpdate ) {
  1021. initMaterial( material, fog, object );
  1022. material.needsUpdate = false;
  1023. }
  1024. var refreshProgram = false;
  1025. var refreshMaterial = false;
  1026. var refreshLights = false;
  1027. var program = materialProperties.program,
  1028. p_uniforms = program.getUniforms(),
  1029. m_uniforms = materialProperties.__webglShader.uniforms;
  1030. if ( program.id !== _currentProgram ) {
  1031. _gl.useProgram( program.program );
  1032. _currentProgram = program.id;
  1033. refreshProgram = true;
  1034. refreshMaterial = true;
  1035. refreshLights = true;
  1036. }
  1037. if ( material.id !== _currentMaterialId ) {
  1038. _currentMaterialId = material.id;
  1039. refreshMaterial = true;
  1040. }
  1041. if ( refreshProgram || camera !== _currentCamera ) {
  1042. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  1043. if ( capabilities.logarithmicDepthBuffer ) {
  1044. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1045. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1046. }
  1047. if ( camera !== _currentCamera ) {
  1048. _currentCamera = camera;
  1049. // lighting uniforms depend on the camera so enforce an update
  1050. // now, in case this material supports lights - or later, when
  1051. // the next material that does gets activated:
  1052. refreshMaterial = true; // set to true on material change
  1053. refreshLights = true; // remains set until update done
  1054. }
  1055. // load material specific uniforms
  1056. // (shader material also gets them for the sake of genericity)
  1057. if ( material.isShaderMaterial ||
  1058. material.isMeshPhongMaterial ||
  1059. material.isMeshStandardMaterial ||
  1060. material.envMap ) {
  1061. var uCamPos = p_uniforms.map.cameraPosition;
  1062. if ( uCamPos !== undefined ) {
  1063. uCamPos.setValue( _gl,
  1064. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1065. }
  1066. }
  1067. if ( material.isMeshPhongMaterial ||
  1068. material.isMeshLambertMaterial ||
  1069. material.isMeshBasicMaterial ||
  1070. material.isMeshStandardMaterial ||
  1071. material.isShaderMaterial ||
  1072. material.skinning ) {
  1073. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1074. }
  1075. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  1076. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  1077. }
  1078. // skinning uniforms must be set even if material didn't change
  1079. // auto-setting of texture unit for bone texture must go before other textures
  1080. // not sure why, but otherwise weird things happen
  1081. if ( material.skinning ) {
  1082. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1083. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1084. var skeleton = object.skeleton;
  1085. if ( skeleton ) {
  1086. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  1087. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  1088. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  1089. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  1090. } else {
  1091. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  1092. }
  1093. }
  1094. }
  1095. if ( refreshMaterial ) {
  1096. if ( material.lights ) {
  1097. // the current material requires lighting info
  1098. // note: all lighting uniforms are always set correctly
  1099. // they simply reference the renderer's state for their
  1100. // values
  1101. //
  1102. // use the current material's .needsUpdate flags to set
  1103. // the GL state when required
  1104. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1105. }
  1106. // refresh uniforms common to several materials
  1107. if ( fog && material.fog ) {
  1108. refreshUniformsFog( m_uniforms, fog );
  1109. }
  1110. if ( material.isMeshBasicMaterial ||
  1111. material.isMeshLambertMaterial ||
  1112. material.isMeshPhongMaterial ||
  1113. material.isMeshStandardMaterial ||
  1114. material.isMeshDepthMaterial ) {
  1115. refreshUniformsCommon( m_uniforms, material );
  1116. }
  1117. // refresh single material specific uniforms
  1118. if ( material.isLineBasicMaterial ) {
  1119. refreshUniformsLine( m_uniforms, material );
  1120. } else if ( material.isLineDashedMaterial ) {
  1121. refreshUniformsLine( m_uniforms, material );
  1122. refreshUniformsDash( m_uniforms, material );
  1123. } else if ( material.isPointsMaterial ) {
  1124. refreshUniformsPoints( m_uniforms, material );
  1125. } else if ( material.isMeshLambertMaterial ) {
  1126. refreshUniformsLambert( m_uniforms, material );
  1127. } else if ( material.isMeshPhongMaterial ) {
  1128. refreshUniformsPhong( m_uniforms, material );
  1129. } else if ( material.isMeshPhysicalMaterial ) {
  1130. refreshUniformsPhysical( m_uniforms, material );
  1131. } else if ( material.isMeshStandardMaterial ) {
  1132. refreshUniformsStandard( m_uniforms, material );
  1133. } else if ( material.isMeshDepthMaterial ) {
  1134. if ( material.displacementMap ) {
  1135. m_uniforms.displacementMap.value = material.displacementMap;
  1136. m_uniforms.displacementScale.value = material.displacementScale;
  1137. m_uniforms.displacementBias.value = material.displacementBias;
  1138. }
  1139. } else if ( material.isMeshNormalMaterial ) {
  1140. m_uniforms.opacity.value = material.opacity;
  1141. }
  1142. WebGLUniforms.upload(
  1143. _gl, materialProperties.uniformsList, m_uniforms, _this );
  1144. }
  1145. // common matrices
  1146. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  1147. p_uniforms.set( _gl, object, 'normalMatrix' );
  1148. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1149. return program;
  1150. }
  1151. // Uniforms (refresh uniforms objects)
  1152. function refreshUniformsCommon( uniforms, material ) {
  1153. uniforms.opacity.value = material.opacity;
  1154. uniforms.diffuse.value = material.color;
  1155. if ( material.emissive ) {
  1156. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1157. }
  1158. uniforms.map.value = material.map;
  1159. uniforms.specularMap.value = material.specularMap;
  1160. uniforms.alphaMap.value = material.alphaMap;
  1161. if ( material.aoMap ) {
  1162. uniforms.aoMap.value = material.aoMap;
  1163. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1164. }
  1165. // uv repeat and offset setting priorities
  1166. // 1. color map
  1167. // 2. specular map
  1168. // 3. normal map
  1169. // 4. bump map
  1170. // 5. alpha map
  1171. // 6. emissive map
  1172. var uvScaleMap;
  1173. if ( material.map ) {
  1174. uvScaleMap = material.map;
  1175. } else if ( material.specularMap ) {
  1176. uvScaleMap = material.specularMap;
  1177. } else if ( material.displacementMap ) {
  1178. uvScaleMap = material.displacementMap;
  1179. } else if ( material.normalMap ) {
  1180. uvScaleMap = material.normalMap;
  1181. } else if ( material.bumpMap ) {
  1182. uvScaleMap = material.bumpMap;
  1183. } else if ( material.roughnessMap ) {
  1184. uvScaleMap = material.roughnessMap;
  1185. } else if ( material.metalnessMap ) {
  1186. uvScaleMap = material.metalnessMap;
  1187. } else if ( material.alphaMap ) {
  1188. uvScaleMap = material.alphaMap;
  1189. } else if ( material.emissiveMap ) {
  1190. uvScaleMap = material.emissiveMap;
  1191. }
  1192. if ( uvScaleMap !== undefined ) {
  1193. // backwards compatibility
  1194. if ( uvScaleMap.isWebGLRenderTarget ) {
  1195. uvScaleMap = uvScaleMap.texture;
  1196. }
  1197. var offset = uvScaleMap.offset;
  1198. var repeat = uvScaleMap.repeat;
  1199. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1200. }
  1201. uniforms.envMap.value = material.envMap;
  1202. // don't flip CubeTexture envMaps, flip everything else:
  1203. // WebGLRenderTargetCube will be flipped for backwards compatibility
  1204. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  1205. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  1206. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  1207. uniforms.reflectivity.value = material.reflectivity;
  1208. uniforms.refractionRatio.value = material.refractionRatio;
  1209. }
  1210. function refreshUniformsLine( uniforms, material ) {
  1211. uniforms.diffuse.value = material.color;
  1212. uniforms.opacity.value = material.opacity;
  1213. }
  1214. function refreshUniformsDash( uniforms, material ) {
  1215. uniforms.dashSize.value = material.dashSize;
  1216. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1217. uniforms.scale.value = material.scale;
  1218. }
  1219. function refreshUniformsPoints( uniforms, material ) {
  1220. uniforms.diffuse.value = material.color;
  1221. uniforms.opacity.value = material.opacity;
  1222. uniforms.size.value = material.size * _pixelRatio;
  1223. uniforms.scale.value = _height * 0.5;
  1224. uniforms.map.value = material.map;
  1225. if ( material.map !== null ) {
  1226. var offset = material.map.offset;
  1227. var repeat = material.map.repeat;
  1228. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1229. }
  1230. }
  1231. function refreshUniformsFog( uniforms, fog ) {
  1232. uniforms.fogColor.value = fog.color;
  1233. if ( fog.isFog ) {
  1234. uniforms.fogNear.value = fog.near;
  1235. uniforms.fogFar.value = fog.far;
  1236. } else if ( fog.isFogExp2 ) {
  1237. uniforms.fogDensity.value = fog.density;
  1238. }
  1239. }
  1240. function refreshUniformsLambert( uniforms, material ) {
  1241. if ( material.lightMap ) {
  1242. uniforms.lightMap.value = material.lightMap;
  1243. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1244. }
  1245. if ( material.emissiveMap ) {
  1246. uniforms.emissiveMap.value = material.emissiveMap;
  1247. }
  1248. }
  1249. function refreshUniformsPhong( uniforms, material ) {
  1250. uniforms.specular.value = material.specular;
  1251. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1252. if ( material.lightMap ) {
  1253. uniforms.lightMap.value = material.lightMap;
  1254. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1255. }
  1256. if ( material.emissiveMap ) {
  1257. uniforms.emissiveMap.value = material.emissiveMap;
  1258. }
  1259. if ( material.bumpMap ) {
  1260. uniforms.bumpMap.value = material.bumpMap;
  1261. uniforms.bumpScale.value = material.bumpScale;
  1262. }
  1263. if ( material.normalMap ) {
  1264. uniforms.normalMap.value = material.normalMap;
  1265. uniforms.normalScale.value.copy( material.normalScale );
  1266. }
  1267. if ( material.displacementMap ) {
  1268. uniforms.displacementMap.value = material.displacementMap;
  1269. uniforms.displacementScale.value = material.displacementScale;
  1270. uniforms.displacementBias.value = material.displacementBias;
  1271. }
  1272. }
  1273. function refreshUniformsStandard( uniforms, material ) {
  1274. uniforms.roughness.value = material.roughness;
  1275. uniforms.metalness.value = material.metalness;
  1276. if ( material.roughnessMap ) {
  1277. uniforms.roughnessMap.value = material.roughnessMap;
  1278. }
  1279. if ( material.metalnessMap ) {
  1280. uniforms.metalnessMap.value = material.metalnessMap;
  1281. }
  1282. if ( material.lightMap ) {
  1283. uniforms.lightMap.value = material.lightMap;
  1284. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1285. }
  1286. if ( material.emissiveMap ) {
  1287. uniforms.emissiveMap.value = material.emissiveMap;
  1288. }
  1289. if ( material.bumpMap ) {
  1290. uniforms.bumpMap.value = material.bumpMap;
  1291. uniforms.bumpScale.value = material.bumpScale;
  1292. }
  1293. if ( material.normalMap ) {
  1294. uniforms.normalMap.value = material.normalMap;
  1295. uniforms.normalScale.value.copy( material.normalScale );
  1296. }
  1297. if ( material.displacementMap ) {
  1298. uniforms.displacementMap.value = material.displacementMap;
  1299. uniforms.displacementScale.value = material.displacementScale;
  1300. uniforms.displacementBias.value = material.displacementBias;
  1301. }
  1302. if ( material.envMap ) {
  1303. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1304. uniforms.envMapIntensity.value = material.envMapIntensity;
  1305. }
  1306. }
  1307. function refreshUniformsPhysical( uniforms, material ) {
  1308. uniforms.clearCoat.value = material.clearCoat;
  1309. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  1310. refreshUniformsStandard( uniforms, material );
  1311. }
  1312. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1313. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1314. uniforms.ambientLightColor.needsUpdate = value;
  1315. uniforms.directionalLights.needsUpdate = value;
  1316. uniforms.pointLights.needsUpdate = value;
  1317. uniforms.spotLights.needsUpdate = value;
  1318. uniforms.hemisphereLights.needsUpdate = value;
  1319. }
  1320. // Lighting
  1321. function setupShadows( lights ) {
  1322. var lightShadowsLength = 0;
  1323. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  1324. var light = lights[ i ];
  1325. if ( light.castShadow ) {
  1326. _lights.shadows[ lightShadowsLength ++ ] = light;
  1327. }
  1328. }
  1329. _lights.shadows.length = lightShadowsLength;
  1330. }
  1331. function setupLights( lights, camera ) {
  1332. var l, ll, light,
  1333. r = 0, g = 0, b = 0,
  1334. color,
  1335. intensity,
  1336. distance,
  1337. shadowMap,
  1338. viewMatrix = camera.matrixWorldInverse,
  1339. directionalLength = 0,
  1340. pointLength = 0,
  1341. spotLength = 0,
  1342. hemiLength = 0;
  1343. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  1344. light = lights[ l ];
  1345. color = light.color;
  1346. intensity = light.intensity;
  1347. distance = light.distance;
  1348. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  1349. if ( light.isAmbientLight ) {
  1350. r += color.r * intensity;
  1351. g += color.g * intensity;
  1352. b += color.b * intensity;
  1353. } else if ( light.isDirectionalLight ) {
  1354. var uniforms = lightCache.get( light );
  1355. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1356. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1357. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1358. uniforms.direction.sub( _vector3 );
  1359. uniforms.direction.transformDirection( viewMatrix );
  1360. uniforms.shadow = light.castShadow;
  1361. if ( light.castShadow ) {
  1362. uniforms.shadowBias = light.shadow.bias;
  1363. uniforms.shadowRadius = light.shadow.radius;
  1364. uniforms.shadowMapSize = light.shadow.mapSize;
  1365. }
  1366. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  1367. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  1368. _lights.directional[ directionalLength ++ ] = uniforms;
  1369. } else if ( light.isSpotLight ) {
  1370. var uniforms = lightCache.get( light );
  1371. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1372. uniforms.position.applyMatrix4( viewMatrix );
  1373. uniforms.color.copy( color ).multiplyScalar( intensity );
  1374. uniforms.distance = distance;
  1375. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1376. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1377. uniforms.direction.sub( _vector3 );
  1378. uniforms.direction.transformDirection( viewMatrix );
  1379. uniforms.coneCos = Math.cos( light.angle );
  1380. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  1381. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1382. uniforms.shadow = light.castShadow;
  1383. if ( light.castShadow ) {
  1384. uniforms.shadowBias = light.shadow.bias;
  1385. uniforms.shadowRadius = light.shadow.radius;
  1386. uniforms.shadowMapSize = light.shadow.mapSize;
  1387. }
  1388. _lights.spotShadowMap[ spotLength ] = shadowMap;
  1389. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  1390. _lights.spot[ spotLength ++ ] = uniforms;
  1391. } else if ( light.isPointLight ) {
  1392. var uniforms = lightCache.get( light );
  1393. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1394. uniforms.position.applyMatrix4( viewMatrix );
  1395. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1396. uniforms.distance = light.distance;
  1397. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1398. uniforms.shadow = light.castShadow;
  1399. if ( light.castShadow ) {
  1400. uniforms.shadowBias = light.shadow.bias;
  1401. uniforms.shadowRadius = light.shadow.radius;
  1402. uniforms.shadowMapSize = light.shadow.mapSize;
  1403. }
  1404. _lights.pointShadowMap[ pointLength ] = shadowMap;
  1405. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  1406. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  1407. }
  1408. // for point lights we set the shadow matrix to be a translation-only matrix
  1409. // equal to inverse of the light's position
  1410. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  1411. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  1412. _lights.point[ pointLength ++ ] = uniforms;
  1413. } else if ( light.isHemisphereLight ) {
  1414. var uniforms = lightCache.get( light );
  1415. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1416. uniforms.direction.transformDirection( viewMatrix );
  1417. uniforms.direction.normalize();
  1418. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  1419. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  1420. _lights.hemi[ hemiLength ++ ] = uniforms;
  1421. }
  1422. }
  1423. _lights.ambient[ 0 ] = r;
  1424. _lights.ambient[ 1 ] = g;
  1425. _lights.ambient[ 2 ] = b;
  1426. _lights.directional.length = directionalLength;
  1427. _lights.spot.length = spotLength;
  1428. _lights.point.length = pointLength;
  1429. _lights.hemi.length = hemiLength;
  1430. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
  1431. }
  1432. // GL state setting
  1433. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  1434. state.setCullFace( cullFace );
  1435. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  1436. };
  1437. // Textures
  1438. function allocTextureUnit() {
  1439. var textureUnit = _usedTextureUnits;
  1440. if ( textureUnit >= capabilities.maxTextures ) {
  1441. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  1442. }
  1443. _usedTextureUnits += 1;
  1444. return textureUnit;
  1445. }
  1446. this.allocTextureUnit = allocTextureUnit;
  1447. // this.setTexture2D = setTexture2D;
  1448. this.setTexture2D = ( function() {
  1449. var warned = false;
  1450. // backwards compatibility: peel texture.texture
  1451. return function setTexture2D( texture, slot ) {
  1452. if ( texture && texture.isWebGLRenderTarget ) {
  1453. if ( ! warned ) {
  1454. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  1455. warned = true;
  1456. }
  1457. texture = texture.texture;
  1458. }
  1459. textures.setTexture2D( texture, slot );
  1460. };
  1461. }() );
  1462. this.setTexture = ( function() {
  1463. var warned = false;
  1464. return function setTexture( texture, slot ) {
  1465. if ( ! warned ) {
  1466. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  1467. warned = true;
  1468. }
  1469. textures.setTexture2D( texture, slot );
  1470. };
  1471. }() );
  1472. this.setTextureCube = ( function() {
  1473. var warned = false;
  1474. return function setTextureCube( texture, slot ) {
  1475. // backwards compatibility: peel texture.texture
  1476. if ( texture && texture.isWebGLRenderTargetCube ) {
  1477. if ( ! warned ) {
  1478. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  1479. warned = true;
  1480. }
  1481. texture = texture.texture;
  1482. }
  1483. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  1484. // TODO: unify these code paths
  1485. if ( ( texture && texture.isCubeTexture ) ||
  1486. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  1487. // CompressedTexture can have Array in image :/
  1488. // this function alone should take care of cube textures
  1489. textures.setTextureCube( texture, slot );
  1490. } else {
  1491. // assumed: texture property of THREE.WebGLRenderTargetCube
  1492. textures.setTextureCubeDynamic( texture, slot );
  1493. }
  1494. };
  1495. }() );
  1496. this.getCurrentRenderTarget = function() {
  1497. return _currentRenderTarget;
  1498. };
  1499. this.setRenderTarget = function ( renderTarget ) {
  1500. _currentRenderTarget = renderTarget;
  1501. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1502. textures.setupRenderTarget( renderTarget );
  1503. }
  1504. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  1505. var framebuffer;
  1506. if ( renderTarget ) {
  1507. var renderTargetProperties = properties.get( renderTarget );
  1508. if ( isCube ) {
  1509. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  1510. } else {
  1511. framebuffer = renderTargetProperties.__webglFramebuffer;
  1512. }
  1513. _currentScissor.copy( renderTarget.scissor );
  1514. _currentScissorTest = renderTarget.scissorTest;
  1515. _currentViewport.copy( renderTarget.viewport );
  1516. } else {
  1517. framebuffer = null;
  1518. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  1519. _currentScissorTest = _scissorTest;
  1520. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  1521. }
  1522. if ( _currentFramebuffer !== framebuffer ) {
  1523. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1524. _currentFramebuffer = framebuffer;
  1525. }
  1526. state.scissor( _currentScissor );
  1527. state.setScissorTest( _currentScissorTest );
  1528. state.viewport( _currentViewport );
  1529. if ( isCube ) {
  1530. var textureProperties = properties.get( renderTarget.texture );
  1531. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  1532. }
  1533. };
  1534. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  1535. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  1536. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1537. return;
  1538. }
  1539. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1540. if ( framebuffer ) {
  1541. var restore = false;
  1542. if ( framebuffer !== _currentFramebuffer ) {
  1543. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1544. restore = true;
  1545. }
  1546. try {
  1547. var texture = renderTarget.texture;
  1548. var textureFormat = texture.format;
  1549. var textureType = texture.type;
  1550. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1551. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1552. return;
  1553. }
  1554. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  1555. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  1556. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  1557. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1558. return;
  1559. }
  1560. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  1561. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1562. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1563. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  1564. }
  1565. } else {
  1566. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  1567. }
  1568. } finally {
  1569. if ( restore ) {
  1570. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  1571. }
  1572. }
  1573. }
  1574. };
  1575. // Map three.js constants to WebGL constants
  1576. function paramThreeToGL( p ) {
  1577. var extension;
  1578. if ( p === RepeatWrapping ) return _gl.REPEAT;
  1579. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  1580. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  1581. if ( p === NearestFilter ) return _gl.NEAREST;
  1582. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  1583. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  1584. if ( p === LinearFilter ) return _gl.LINEAR;
  1585. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  1586. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  1587. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  1588. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  1589. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  1590. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  1591. if ( p === ByteType ) return _gl.BYTE;
  1592. if ( p === ShortType ) return _gl.SHORT;
  1593. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  1594. if ( p === IntType ) return _gl.INT;
  1595. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  1596. if ( p === FloatType ) return _gl.FLOAT;
  1597. extension = extensions.get( 'OES_texture_half_float' );
  1598. if ( extension !== null ) {
  1599. if ( p === HalfFloatType ) return extension.HALF_FLOAT_OES;
  1600. }
  1601. if ( p === AlphaFormat ) return _gl.ALPHA;
  1602. if ( p === RGBFormat ) return _gl.RGB;
  1603. if ( p === RGBAFormat ) return _gl.RGBA;
  1604. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  1605. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  1606. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  1607. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  1608. if ( p === AddEquation ) return _gl.FUNC_ADD;
  1609. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  1610. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  1611. if ( p === ZeroFactor ) return _gl.ZERO;
  1612. if ( p === OneFactor ) return _gl.ONE;
  1613. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  1614. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  1615. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  1616. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  1617. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  1618. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  1619. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  1620. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  1621. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  1622. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  1623. if ( extension !== null ) {
  1624. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  1625. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  1626. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  1627. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  1628. }
  1629. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  1630. if ( extension !== null ) {
  1631. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  1632. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  1633. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  1634. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  1635. }
  1636. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  1637. if ( extension !== null ) {
  1638. if ( p === RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  1639. }
  1640. extension = extensions.get( 'EXT_blend_minmax' );
  1641. if ( extension !== null ) {
  1642. if ( p === MinEquation ) return extension.MIN_EXT;
  1643. if ( p === MaxEquation ) return extension.MAX_EXT;
  1644. }
  1645. extension = extensions.get( 'WEBGL_depth_texture' );
  1646. if ( extension !== null ){
  1647. if ( p === UnsignedInt248Type ) return extension.UNSIGNED_INT_24_8_WEBGL;
  1648. }
  1649. return 0;
  1650. }
  1651. }
  1652. export { WebGLRenderer };