WebGLRenderer.js 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598
  1. /**
  2. * @author supereggbert / http://www.paulbrunt.co.uk/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author alteredq / http://alteredqualia.com/
  5. * @author szimek / https://github.com/szimek/
  6. */
  7. THREE.WebGLRenderer = function ( parameters ) {
  8. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9. parameters = parameters || {};
  10. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11. _context = parameters.context !== undefined ? parameters.context : null,
  12. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  13. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  17. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  18. var lights = [];
  19. var opaqueObjects = [];
  20. var opaqueObjectsLastIndex = - 1;
  21. var transparentObjects = [];
  22. var transparentObjectsLastIndex = - 1;
  23. var morphInfluences = new Float32Array( 8 );
  24. var sprites = [];
  25. var lensFlares = [];
  26. // public properties
  27. this.domElement = _canvas;
  28. this.context = null;
  29. // clearing
  30. this.autoClear = true;
  31. this.autoClearColor = true;
  32. this.autoClearDepth = true;
  33. this.autoClearStencil = true;
  34. // scene graph
  35. this.sortObjects = true;
  36. // physically based shading
  37. this.gammaFactor = 2.0; // for backwards compatibility
  38. this.gammaInput = false;
  39. this.gammaOutput = false;
  40. // physical lights
  41. this.physicallyCorrectLights = false;
  42. // tone mapping
  43. this.toneMapping = THREE.LinearToneMapping;
  44. this.toneMappingExposure = 1.0;
  45. this.toneMappingWhitePoint = 1.0;
  46. // morphs
  47. this.maxMorphTargets = 8;
  48. this.maxMorphNormals = 4;
  49. // flags
  50. this.autoScaleCubemaps = true;
  51. // internal properties
  52. var _this = this,
  53. // internal state cache
  54. _currentProgram = null,
  55. _currentRenderTarget = null,
  56. _currentFramebuffer = null,
  57. _currentMaterialId = - 1,
  58. _currentGeometryProgram = '',
  59. _currentCamera = null,
  60. _currentScissor = new THREE.Vector4(),
  61. _currentScissorTest = null,
  62. _currentViewport = new THREE.Vector4(),
  63. //
  64. _usedTextureUnits = 0,
  65. //
  66. _clearColor = new THREE.Color( 0x000000 ),
  67. _clearAlpha = 0,
  68. _width = _canvas.width,
  69. _height = _canvas.height,
  70. _pixelRatio = 1,
  71. _scissor = new THREE.Vector4( 0, 0, _width, _height ),
  72. _scissorTest = false,
  73. _viewport = new THREE.Vector4( 0, 0, _width, _height ),
  74. // frustum
  75. _frustum = new THREE.Frustum(),
  76. // camera matrices cache
  77. _projScreenMatrix = new THREE.Matrix4(),
  78. _vector3 = new THREE.Vector3(),
  79. // light arrays cache
  80. _lights = {
  81. hash: '',
  82. ambient: [ 0, 0, 0 ],
  83. directional: [],
  84. directionalShadowMap: [],
  85. directionalShadowMatrix: [],
  86. spot: [],
  87. spotShadowMap: [],
  88. spotShadowMatrix: [],
  89. point: [],
  90. pointShadowMap: [],
  91. pointShadowMatrix: [],
  92. hemi: [],
  93. shadows: [],
  94. shadowsPointLight: 0
  95. },
  96. // info
  97. _infoMemory = {
  98. geometries: 0,
  99. textures: 0
  100. },
  101. _infoRender = {
  102. calls: 0,
  103. vertices: 0,
  104. faces: 0,
  105. points: 0
  106. };
  107. this.info = {
  108. render: _infoRender,
  109. memory: _infoMemory,
  110. programs: null
  111. };
  112. // initialize
  113. var _gl;
  114. try {
  115. var attributes = {
  116. alpha: _alpha,
  117. depth: _depth,
  118. stencil: _stencil,
  119. antialias: _antialias,
  120. premultipliedAlpha: _premultipliedAlpha,
  121. preserveDrawingBuffer: _preserveDrawingBuffer
  122. };
  123. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  124. if ( _gl === null ) {
  125. if ( _canvas.getContext( 'webgl' ) !== null ) {
  126. throw 'Error creating WebGL context with your selected attributes.';
  127. } else {
  128. throw 'Error creating WebGL context.';
  129. }
  130. }
  131. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  132. if ( _gl.getShaderPrecisionFormat === undefined ) {
  133. _gl.getShaderPrecisionFormat = function () {
  134. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  135. };
  136. }
  137. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  138. } catch ( error ) {
  139. console.error( 'THREE.WebGLRenderer: ' + error );
  140. }
  141. var extensions = new THREE.WebGLExtensions( _gl );
  142. extensions.get( 'OES_texture_float' );
  143. extensions.get( 'OES_texture_float_linear' );
  144. extensions.get( 'OES_texture_half_float' );
  145. extensions.get( 'OES_texture_half_float_linear' );
  146. extensions.get( 'OES_standard_derivatives' );
  147. extensions.get( 'ANGLE_instanced_arrays' );
  148. if ( extensions.get( 'OES_element_index_uint' ) ) {
  149. THREE.BufferGeometry.MaxIndex = 4294967296;
  150. }
  151. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  152. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  153. var properties = new THREE.WebGLProperties();
  154. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  155. var programCache = new THREE.WebGLPrograms( this, capabilities );
  156. var lightCache = new THREE.WebGLLights();
  157. this.info.programs = programCache.programs;
  158. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  159. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  160. //
  161. function getTargetPixelRatio() {
  162. return _currentRenderTarget === null ? _pixelRatio : 1;
  163. }
  164. function glClearColor( r, g, b, a ) {
  165. if ( _premultipliedAlpha === true ) {
  166. r *= a; g *= a; b *= a;
  167. }
  168. state.clearColor( r, g, b, a );
  169. }
  170. function setDefaultGLState() {
  171. state.init();
  172. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  173. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  174. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  175. }
  176. function resetGLState() {
  177. _currentProgram = null;
  178. _currentCamera = null;
  179. _currentGeometryProgram = '';
  180. _currentMaterialId = - 1;
  181. state.reset();
  182. }
  183. setDefaultGLState();
  184. this.context = _gl;
  185. this.capabilities = capabilities;
  186. this.extensions = extensions;
  187. this.properties = properties;
  188. this.state = state;
  189. // shadow map
  190. var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
  191. this.shadowMap = shadowMap;
  192. // Plugins
  193. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  194. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  195. // API
  196. this.getContext = function () {
  197. return _gl;
  198. };
  199. this.getContextAttributes = function () {
  200. return _gl.getContextAttributes();
  201. };
  202. this.forceContextLoss = function () {
  203. extensions.get( 'WEBGL_lose_context' ).loseContext();
  204. };
  205. this.getMaxAnisotropy = ( function () {
  206. var value;
  207. return function getMaxAnisotropy() {
  208. if ( value !== undefined ) return value;
  209. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  210. if ( extension !== null ) {
  211. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  212. } else {
  213. value = 0;
  214. }
  215. return value;
  216. };
  217. } )();
  218. this.getPrecision = function () {
  219. return capabilities.precision;
  220. };
  221. this.getPixelRatio = function () {
  222. return _pixelRatio;
  223. };
  224. this.setPixelRatio = function ( value ) {
  225. if ( value === undefined ) return;
  226. _pixelRatio = value;
  227. this.setSize( _viewport.z, _viewport.w, false );
  228. };
  229. this.getSize = function () {
  230. return {
  231. width: _width,
  232. height: _height
  233. };
  234. };
  235. this.setSize = function ( width, height, updateStyle ) {
  236. _width = width;
  237. _height = height;
  238. _canvas.width = width * _pixelRatio;
  239. _canvas.height = height * _pixelRatio;
  240. if ( updateStyle !== false ) {
  241. _canvas.style.width = width + 'px';
  242. _canvas.style.height = height + 'px';
  243. }
  244. this.setViewport( 0, 0, width, height );
  245. };
  246. this.setViewport = function ( x, y, width, height ) {
  247. state.viewport( _viewport.set( x, y, width, height ) );
  248. };
  249. this.setScissor = function ( x, y, width, height ) {
  250. state.scissor( _scissor.set( x, y, width, height ) );
  251. };
  252. this.setScissorTest = function ( boolean ) {
  253. state.setScissorTest( _scissorTest = boolean );
  254. };
  255. // Clearing
  256. this.getClearColor = function () {
  257. return _clearColor;
  258. };
  259. this.setClearColor = function ( color, alpha ) {
  260. _clearColor.set( color );
  261. _clearAlpha = alpha !== undefined ? alpha : 1;
  262. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  263. };
  264. this.getClearAlpha = function () {
  265. return _clearAlpha;
  266. };
  267. this.setClearAlpha = function ( alpha ) {
  268. _clearAlpha = alpha;
  269. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  270. };
  271. this.clear = function ( color, depth, stencil ) {
  272. var bits = 0;
  273. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  274. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  275. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  276. _gl.clear( bits );
  277. };
  278. this.clearColor = function () {
  279. this.clear( true, false, false );
  280. };
  281. this.clearDepth = function () {
  282. this.clear( false, true, false );
  283. };
  284. this.clearStencil = function () {
  285. this.clear( false, false, true );
  286. };
  287. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  288. this.setRenderTarget( renderTarget );
  289. this.clear( color, depth, stencil );
  290. };
  291. // Reset
  292. this.resetGLState = resetGLState;
  293. this.dispose = function() {
  294. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  295. };
  296. // Events
  297. function onContextLost( event ) {
  298. event.preventDefault();
  299. resetGLState();
  300. setDefaultGLState();
  301. properties.clear();
  302. }
  303. function onTextureDispose( event ) {
  304. var texture = event.target;
  305. texture.removeEventListener( 'dispose', onTextureDispose );
  306. deallocateTexture( texture );
  307. _infoMemory.textures --;
  308. }
  309. function onRenderTargetDispose( event ) {
  310. var renderTarget = event.target;
  311. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  312. deallocateRenderTarget( renderTarget );
  313. _infoMemory.textures --;
  314. }
  315. function onMaterialDispose( event ) {
  316. var material = event.target;
  317. material.removeEventListener( 'dispose', onMaterialDispose );
  318. deallocateMaterial( material );
  319. }
  320. // Buffer deallocation
  321. function deallocateTexture( texture ) {
  322. var textureProperties = properties.get( texture );
  323. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  324. // cube texture
  325. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  326. } else {
  327. // 2D texture
  328. if ( textureProperties.__webglInit === undefined ) return;
  329. _gl.deleteTexture( textureProperties.__webglTexture );
  330. }
  331. // remove all webgl properties
  332. properties.delete( texture );
  333. }
  334. function deallocateRenderTarget( renderTarget ) {
  335. var renderTargetProperties = properties.get( renderTarget );
  336. var textureProperties = properties.get( renderTarget.texture );
  337. if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
  338. _gl.deleteTexture( textureProperties.__webglTexture );
  339. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  340. for ( var i = 0; i < 6; i ++ ) {
  341. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  342. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  343. }
  344. } else {
  345. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  346. _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  347. }
  348. properties.delete( renderTarget.texture );
  349. properties.delete( renderTarget );
  350. }
  351. function deallocateMaterial( material ) {
  352. releaseMaterialProgramReference( material );
  353. properties.delete( material );
  354. }
  355. function releaseMaterialProgramReference( material ) {
  356. var programInfo = properties.get( material ).program;
  357. material.program = undefined;
  358. if ( programInfo !== undefined ) {
  359. programCache.releaseProgram( programInfo );
  360. }
  361. }
  362. // Buffer rendering
  363. this.renderBufferImmediate = function ( object, program, material ) {
  364. state.initAttributes();
  365. var buffers = properties.get( object );
  366. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  367. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  368. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  369. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  370. var attributes = program.getAttributes();
  371. if ( object.hasPositions ) {
  372. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  373. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  374. state.enableAttribute( attributes.position );
  375. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  376. }
  377. if ( object.hasNormals ) {
  378. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  379. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.shading === THREE.FlatShading ) {
  380. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  381. var array = object.normalArray;
  382. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  383. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  384. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  385. array[ i + 0 ] = nx;
  386. array[ i + 1 ] = ny;
  387. array[ i + 2 ] = nz;
  388. array[ i + 3 ] = nx;
  389. array[ i + 4 ] = ny;
  390. array[ i + 5 ] = nz;
  391. array[ i + 6 ] = nx;
  392. array[ i + 7 ] = ny;
  393. array[ i + 8 ] = nz;
  394. }
  395. }
  396. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  397. state.enableAttribute( attributes.normal );
  398. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  399. }
  400. if ( object.hasUvs && material.map ) {
  401. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  402. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  403. state.enableAttribute( attributes.uv );
  404. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  405. }
  406. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  407. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  408. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  409. state.enableAttribute( attributes.color );
  410. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  411. }
  412. state.disableUnusedAttributes();
  413. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  414. object.count = 0;
  415. };
  416. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  417. setMaterial( material );
  418. var program = setProgram( camera, fog, material, object );
  419. var updateBuffers = false;
  420. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  421. if ( geometryProgram !== _currentGeometryProgram ) {
  422. _currentGeometryProgram = geometryProgram;
  423. updateBuffers = true;
  424. }
  425. // morph targets
  426. var morphTargetInfluences = object.morphTargetInfluences;
  427. if ( morphTargetInfluences !== undefined ) {
  428. var activeInfluences = [];
  429. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  430. var influence = morphTargetInfluences[ i ];
  431. activeInfluences.push( [ influence, i ] );
  432. }
  433. activeInfluences.sort( absNumericalSort );
  434. if ( activeInfluences.length > 8 ) {
  435. activeInfluences.length = 8;
  436. }
  437. var morphAttributes = geometry.morphAttributes;
  438. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  439. var influence = activeInfluences[ i ];
  440. morphInfluences[ i ] = influence[ 0 ];
  441. if ( influence[ 0 ] !== 0 ) {
  442. var index = influence[ 1 ];
  443. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  444. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  445. } else {
  446. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  447. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  448. }
  449. }
  450. var uniforms = program.getUniforms();
  451. if ( uniforms.morphTargetInfluences !== null ) {
  452. _gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  453. }
  454. updateBuffers = true;
  455. }
  456. //
  457. var index = geometry.index;
  458. var position = geometry.attributes.position;
  459. if ( material.wireframe === true ) {
  460. index = objects.getWireframeAttribute( geometry );
  461. }
  462. var renderer;
  463. if ( index !== null ) {
  464. renderer = indexedBufferRenderer;
  465. renderer.setIndex( index );
  466. } else {
  467. renderer = bufferRenderer;
  468. }
  469. if ( updateBuffers ) {
  470. setupVertexAttributes( material, program, geometry );
  471. if ( index !== null ) {
  472. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  473. }
  474. }
  475. //
  476. var dataStart = 0;
  477. var dataCount = Infinity;
  478. if ( index !== null ) {
  479. dataCount = index.count;
  480. } else if ( position !== undefined ) {
  481. dataCount = position.count;
  482. }
  483. var rangeStart = geometry.drawRange.start;
  484. var rangeCount = geometry.drawRange.count;
  485. var groupStart = group !== null ? group.start : 0;
  486. var groupCount = group !== null ? group.count : Infinity;
  487. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  488. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  489. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  490. //
  491. if ( object instanceof THREE.Mesh ) {
  492. if ( material.wireframe === true ) {
  493. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  494. renderer.setMode( _gl.LINES );
  495. } else {
  496. switch ( object.drawMode ) {
  497. case THREE.TrianglesDrawMode:
  498. renderer.setMode( _gl.TRIANGLES );
  499. break;
  500. case THREE.TriangleStripDrawMode:
  501. renderer.setMode( _gl.TRIANGLE_STRIP );
  502. break;
  503. case THREE.TriangleFanDrawMode:
  504. renderer.setMode( _gl.TRIANGLE_FAN );
  505. break;
  506. }
  507. }
  508. } else if ( object instanceof THREE.Line ) {
  509. var lineWidth = material.linewidth;
  510. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  511. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  512. if ( object instanceof THREE.LineSegments ) {
  513. renderer.setMode( _gl.LINES );
  514. } else {
  515. renderer.setMode( _gl.LINE_STRIP );
  516. }
  517. } else if ( object instanceof THREE.Points ) {
  518. renderer.setMode( _gl.POINTS );
  519. }
  520. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  521. if ( geometry.maxInstancedCount > 0 ) {
  522. renderer.renderInstances( geometry, drawStart, drawCount );
  523. }
  524. } else {
  525. renderer.render( drawStart, drawCount );
  526. }
  527. };
  528. function setupVertexAttributes( material, program, geometry, startIndex ) {
  529. var extension;
  530. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  531. extension = extensions.get( 'ANGLE_instanced_arrays' );
  532. if ( extension === null ) {
  533. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  534. return;
  535. }
  536. }
  537. if ( startIndex === undefined ) startIndex = 0;
  538. state.initAttributes();
  539. var geometryAttributes = geometry.attributes;
  540. var programAttributes = program.getAttributes();
  541. var materialDefaultAttributeValues = material.defaultAttributeValues;
  542. for ( var name in programAttributes ) {
  543. var programAttribute = programAttributes[ name ];
  544. if ( programAttribute >= 0 ) {
  545. var geometryAttribute = geometryAttributes[ name ];
  546. if ( geometryAttribute !== undefined ) {
  547. var size = geometryAttribute.itemSize;
  548. var buffer = objects.getAttributeBuffer( geometryAttribute );
  549. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  550. var data = geometryAttribute.data;
  551. var stride = data.stride;
  552. var offset = geometryAttribute.offset;
  553. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  554. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  555. if ( geometry.maxInstancedCount === undefined ) {
  556. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  557. }
  558. } else {
  559. state.enableAttribute( programAttribute );
  560. }
  561. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  562. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  563. } else {
  564. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  565. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  566. if ( geometry.maxInstancedCount === undefined ) {
  567. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  568. }
  569. } else {
  570. state.enableAttribute( programAttribute );
  571. }
  572. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  573. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  574. }
  575. } else if ( materialDefaultAttributeValues !== undefined ) {
  576. var value = materialDefaultAttributeValues[ name ];
  577. if ( value !== undefined ) {
  578. switch ( value.length ) {
  579. case 2:
  580. _gl.vertexAttrib2fv( programAttribute, value );
  581. break;
  582. case 3:
  583. _gl.vertexAttrib3fv( programAttribute, value );
  584. break;
  585. case 4:
  586. _gl.vertexAttrib4fv( programAttribute, value );
  587. break;
  588. default:
  589. _gl.vertexAttrib1fv( programAttribute, value );
  590. }
  591. }
  592. }
  593. }
  594. }
  595. state.disableUnusedAttributes();
  596. }
  597. // Sorting
  598. function absNumericalSort( a, b ) {
  599. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  600. }
  601. function painterSortStable ( a, b ) {
  602. if ( a.object.renderOrder !== b.object.renderOrder ) {
  603. return a.object.renderOrder - b.object.renderOrder;
  604. } else if ( a.material.id !== b.material.id ) {
  605. return a.material.id - b.material.id;
  606. } else if ( a.z !== b.z ) {
  607. return a.z - b.z;
  608. } else {
  609. return a.id - b.id;
  610. }
  611. }
  612. function reversePainterSortStable ( a, b ) {
  613. if ( a.object.renderOrder !== b.object.renderOrder ) {
  614. return a.object.renderOrder - b.object.renderOrder;
  615. } if ( a.z !== b.z ) {
  616. return b.z - a.z;
  617. } else {
  618. return a.id - b.id;
  619. }
  620. }
  621. // Rendering
  622. this.render = function ( scene, camera, renderTarget, forceClear ) {
  623. if ( camera instanceof THREE.Camera === false ) {
  624. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  625. return;
  626. }
  627. var fog = scene.fog;
  628. // reset caching for this frame
  629. _currentGeometryProgram = '';
  630. _currentMaterialId = - 1;
  631. _currentCamera = null;
  632. // update scene graph
  633. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  634. // update camera matrices and frustum
  635. if ( camera.parent === null ) camera.updateMatrixWorld();
  636. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  637. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  638. _frustum.setFromMatrix( _projScreenMatrix );
  639. lights.length = 0;
  640. opaqueObjectsLastIndex = - 1;
  641. transparentObjectsLastIndex = - 1;
  642. sprites.length = 0;
  643. lensFlares.length = 0;
  644. projectObject( scene, camera );
  645. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  646. transparentObjects.length = transparentObjectsLastIndex + 1;
  647. if ( _this.sortObjects === true ) {
  648. opaqueObjects.sort( painterSortStable );
  649. transparentObjects.sort( reversePainterSortStable );
  650. }
  651. setupLights( lights, camera );
  652. //
  653. shadowMap.render( scene, camera );
  654. //
  655. _infoRender.calls = 0;
  656. _infoRender.vertices = 0;
  657. _infoRender.faces = 0;
  658. _infoRender.points = 0;
  659. if ( renderTarget === undefined ) {
  660. renderTarget = null;
  661. }
  662. this.setRenderTarget( renderTarget );
  663. if ( this.autoClear || forceClear ) {
  664. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  665. }
  666. //
  667. if ( scene.overrideMaterial ) {
  668. var overrideMaterial = scene.overrideMaterial;
  669. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  670. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  671. } else {
  672. // opaque pass (front-to-back order)
  673. state.setBlending( THREE.NoBlending );
  674. renderObjects( opaqueObjects, camera, fog );
  675. // transparent pass (back-to-front order)
  676. renderObjects( transparentObjects, camera, fog );
  677. }
  678. // custom render plugins (post pass)
  679. spritePlugin.render( scene, camera );
  680. lensFlarePlugin.render( scene, camera, _currentViewport );
  681. // Generate mipmap if we're using any kind of mipmap filtering
  682. if ( renderTarget ) {
  683. var texture = renderTarget.texture;
  684. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  685. texture.minFilter !== THREE.NearestFilter &&
  686. texture.minFilter !== THREE.LinearFilter ) {
  687. updateRenderTargetMipmap( renderTarget );
  688. }
  689. }
  690. // Ensure depth buffer writing is enabled so it can be cleared on next render
  691. state.setDepthTest( true );
  692. state.setDepthWrite( true );
  693. state.setColorWrite( true );
  694. // _gl.finish();
  695. };
  696. function pushRenderItem( object, geometry, material, z, group ) {
  697. var array, index;
  698. // allocate the next position in the appropriate array
  699. if ( material.transparent ) {
  700. array = transparentObjects;
  701. index = ++ transparentObjectsLastIndex;
  702. } else {
  703. array = opaqueObjects;
  704. index = ++ opaqueObjectsLastIndex;
  705. }
  706. // recycle existing render item or grow the array
  707. var renderItem = array[ index ];
  708. if ( renderItem !== undefined ) {
  709. renderItem.id = object.id;
  710. renderItem.object = object;
  711. renderItem.geometry = geometry;
  712. renderItem.material = material;
  713. renderItem.z = _vector3.z;
  714. renderItem.group = group;
  715. } else {
  716. renderItem = {
  717. id: object.id,
  718. object: object,
  719. geometry: geometry,
  720. material: material,
  721. z: _vector3.z,
  722. group: group
  723. };
  724. // assert( index === array.length );
  725. array.push( renderItem );
  726. }
  727. }
  728. function projectObject( object, camera ) {
  729. if ( object.visible === false ) return;
  730. if ( object.layers.test( camera.layers ) ) {
  731. if ( object instanceof THREE.Light ) {
  732. lights.push( object );
  733. } else if ( object instanceof THREE.Sprite ) {
  734. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  735. sprites.push( object );
  736. }
  737. } else if ( object instanceof THREE.LensFlare ) {
  738. lensFlares.push( object );
  739. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  740. if ( _this.sortObjects === true ) {
  741. _vector3.setFromMatrixPosition( object.matrixWorld );
  742. _vector3.applyProjection( _projScreenMatrix );
  743. }
  744. pushRenderItem( object, null, object.material, _vector3.z, null );
  745. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  746. if ( object instanceof THREE.SkinnedMesh ) {
  747. object.skeleton.update();
  748. }
  749. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  750. var material = object.material;
  751. if ( material.visible === true ) {
  752. if ( _this.sortObjects === true ) {
  753. _vector3.setFromMatrixPosition( object.matrixWorld );
  754. _vector3.applyProjection( _projScreenMatrix );
  755. }
  756. var geometry = objects.update( object );
  757. if ( material instanceof THREE.MultiMaterial ) {
  758. var groups = geometry.groups;
  759. var materials = material.materials;
  760. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  761. var group = groups[ i ];
  762. var groupMaterial = materials[ group.materialIndex ];
  763. if ( groupMaterial.visible === true ) {
  764. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  765. }
  766. }
  767. } else {
  768. pushRenderItem( object, geometry, material, _vector3.z, null );
  769. }
  770. }
  771. }
  772. }
  773. }
  774. var children = object.children;
  775. for ( var i = 0, l = children.length; i < l; i ++ ) {
  776. projectObject( children[ i ], camera );
  777. }
  778. }
  779. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  780. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  781. var renderItem = renderList[ i ];
  782. var object = renderItem.object;
  783. var geometry = renderItem.geometry;
  784. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  785. var group = renderItem.group;
  786. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  787. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  788. if ( object instanceof THREE.ImmediateRenderObject ) {
  789. setMaterial( material );
  790. var program = setProgram( camera, fog, material, object );
  791. _currentGeometryProgram = '';
  792. object.render( function ( object ) {
  793. _this.renderBufferImmediate( object, program, material );
  794. } );
  795. } else {
  796. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  797. }
  798. }
  799. }
  800. function initMaterial( material, fog, object ) {
  801. var materialProperties = properties.get( material );
  802. var parameters = programCache.getParameters( material, _lights, fog, object );
  803. var code = programCache.getProgramCode( material, parameters );
  804. var program = materialProperties.program;
  805. var programChange = true;
  806. if ( program === undefined ) {
  807. // new material
  808. material.addEventListener( 'dispose', onMaterialDispose );
  809. } else if ( program.code !== code ) {
  810. // changed glsl or parameters
  811. releaseMaterialProgramReference( material );
  812. } else if ( parameters.shaderID !== undefined ) {
  813. // same glsl and uniform list
  814. return;
  815. } else {
  816. // only rebuild uniform list
  817. programChange = false;
  818. }
  819. if ( programChange ) {
  820. if ( parameters.shaderID ) {
  821. var shader = THREE.ShaderLib[ parameters.shaderID ];
  822. materialProperties.__webglShader = {
  823. name: material.type,
  824. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  825. vertexShader: shader.vertexShader,
  826. fragmentShader: shader.fragmentShader
  827. };
  828. } else {
  829. materialProperties.__webglShader = {
  830. name: material.type,
  831. uniforms: material.uniforms,
  832. vertexShader: material.vertexShader,
  833. fragmentShader: material.fragmentShader
  834. };
  835. }
  836. material.__webglShader = materialProperties.__webglShader;
  837. program = programCache.acquireProgram( material, parameters, code );
  838. materialProperties.program = program;
  839. material.program = program;
  840. }
  841. var attributes = program.getAttributes();
  842. if ( material.morphTargets ) {
  843. material.numSupportedMorphTargets = 0;
  844. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  845. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  846. material.numSupportedMorphTargets ++;
  847. }
  848. }
  849. }
  850. if ( material.morphNormals ) {
  851. material.numSupportedMorphNormals = 0;
  852. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  853. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  854. material.numSupportedMorphNormals ++;
  855. }
  856. }
  857. }
  858. materialProperties.uniformsList = [];
  859. var uniforms = materialProperties.__webglShader.uniforms,
  860. uniformLocations = materialProperties.program.getUniforms();
  861. for ( var u in uniforms ) {
  862. var location = uniformLocations[ u ];
  863. if ( location ) {
  864. materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
  865. }
  866. }
  867. if ( material instanceof THREE.MeshPhongMaterial ||
  868. material instanceof THREE.MeshLambertMaterial ||
  869. material instanceof THREE.MeshStandardMaterial ||
  870. material.lights ) {
  871. // store the light setup it was created for
  872. materialProperties.lightsHash = _lights.hash;
  873. // wire up the material to this renderer's lighting state
  874. uniforms.ambientLightColor.value = _lights.ambient;
  875. uniforms.directionalLights.value = _lights.directional;
  876. uniforms.spotLights.value = _lights.spot;
  877. uniforms.pointLights.value = _lights.point;
  878. uniforms.hemisphereLights.value = _lights.hemi;
  879. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  880. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  881. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  882. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  883. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  884. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  885. }
  886. // detect dynamic uniforms
  887. materialProperties.hasDynamicUniforms = false;
  888. for ( var j = 0, jl = materialProperties.uniformsList.length; j < jl; j ++ ) {
  889. var uniform = materialProperties.uniformsList[ j ][ 0 ];
  890. if ( uniform.dynamic === true ) {
  891. materialProperties.hasDynamicUniforms = true;
  892. break;
  893. }
  894. }
  895. }
  896. function setMaterial( material ) {
  897. setMaterialFaces( material );
  898. if ( material.transparent === true ) {
  899. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  900. } else {
  901. state.setBlending( THREE.NoBlending );
  902. }
  903. state.setDepthFunc( material.depthFunc );
  904. state.setDepthTest( material.depthTest );
  905. state.setDepthWrite( material.depthWrite );
  906. state.setColorWrite( material.colorWrite );
  907. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  908. }
  909. function setMaterialFaces( material ) {
  910. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  911. state.setFlipSided( material.side === THREE.BackSide );
  912. }
  913. function setProgram( camera, fog, material, object ) {
  914. _usedTextureUnits = 0;
  915. var materialProperties = properties.get( material );
  916. if ( materialProperties.program === undefined ) {
  917. material.needsUpdate = true;
  918. }
  919. if ( materialProperties.lightsHash !== undefined &&
  920. materialProperties.lightsHash !== _lights.hash ) {
  921. material.needsUpdate = true;
  922. }
  923. if ( material.needsUpdate ) {
  924. initMaterial( material, fog, object );
  925. material.needsUpdate = false;
  926. }
  927. var refreshProgram = false;
  928. var refreshMaterial = false;
  929. var refreshLights = false;
  930. var program = materialProperties.program,
  931. p_uniforms = program.getUniforms(),
  932. m_uniforms = materialProperties.__webglShader.uniforms;
  933. if ( program.id !== _currentProgram ) {
  934. _gl.useProgram( program.program );
  935. _currentProgram = program.id;
  936. refreshProgram = true;
  937. refreshMaterial = true;
  938. refreshLights = true;
  939. }
  940. if ( material.id !== _currentMaterialId ) {
  941. _currentMaterialId = material.id;
  942. refreshMaterial = true;
  943. }
  944. if ( refreshProgram || camera !== _currentCamera ) {
  945. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  946. if ( capabilities.logarithmicDepthBuffer ) {
  947. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  948. }
  949. if ( camera !== _currentCamera ) {
  950. _currentCamera = camera;
  951. // lighting uniforms depend on the camera so enforce an update
  952. // now, in case this material supports lights - or later, when
  953. // the next material that does gets activated:
  954. refreshMaterial = true; // set to true on material change
  955. refreshLights = true; // remains set until update done
  956. }
  957. // load material specific uniforms
  958. // (shader material also gets them for the sake of genericity)
  959. if ( material instanceof THREE.ShaderMaterial ||
  960. material instanceof THREE.MeshPhongMaterial ||
  961. material instanceof THREE.MeshStandardMaterial ||
  962. material.envMap ) {
  963. if ( p_uniforms.cameraPosition !== undefined ) {
  964. _vector3.setFromMatrixPosition( camera.matrixWorld );
  965. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  966. }
  967. }
  968. if ( material instanceof THREE.MeshPhongMaterial ||
  969. material instanceof THREE.MeshLambertMaterial ||
  970. material instanceof THREE.MeshBasicMaterial ||
  971. material instanceof THREE.MeshStandardMaterial ||
  972. material instanceof THREE.ShaderMaterial ||
  973. material.skinning ) {
  974. if ( p_uniforms.viewMatrix !== undefined ) {
  975. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  976. }
  977. }
  978. if ( p_uniforms.toneMappingExposure !== undefined ) {
  979. _gl.uniform1f( p_uniforms.toneMappingExposure, _this.toneMappingExposure );
  980. }
  981. if ( p_uniforms.toneMappingWhitePoint !== undefined ) {
  982. _gl.uniform1f( p_uniforms.toneMappingWhitePoint, _this.toneMappingWhitePoint );
  983. }
  984. }
  985. // skinning uniforms must be set even if material didn't change
  986. // auto-setting of texture unit for bone texture must go before other textures
  987. // not sure why, but otherwise weird things happen
  988. if ( material.skinning ) {
  989. if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
  990. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  991. }
  992. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
  993. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  994. }
  995. if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  996. if ( p_uniforms.boneTexture !== undefined ) {
  997. var textureUnit = getTextureUnit();
  998. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  999. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  1000. }
  1001. if ( p_uniforms.boneTextureWidth !== undefined ) {
  1002. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  1003. }
  1004. if ( p_uniforms.boneTextureHeight !== undefined ) {
  1005. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  1006. }
  1007. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  1008. if ( p_uniforms.boneGlobalMatrices !== undefined ) {
  1009. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  1010. }
  1011. }
  1012. }
  1013. if ( refreshMaterial ) {
  1014. if ( material instanceof THREE.MeshPhongMaterial ||
  1015. material instanceof THREE.MeshLambertMaterial ||
  1016. material instanceof THREE.MeshStandardMaterial ||
  1017. material.lights ) {
  1018. // the current material requires lighting info
  1019. // note: all lighting uniforms are always set correctly
  1020. // they simply reference the renderer's state for their
  1021. // values
  1022. //
  1023. // use the current material's .needsUpdate flags to set
  1024. // the GL state when required
  1025. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1026. }
  1027. // refresh uniforms common to several materials
  1028. if ( fog && material.fog ) {
  1029. refreshUniformsFog( m_uniforms, fog );
  1030. }
  1031. if ( material instanceof THREE.MeshBasicMaterial ||
  1032. material instanceof THREE.MeshLambertMaterial ||
  1033. material instanceof THREE.MeshPhongMaterial ||
  1034. material instanceof THREE.MeshStandardMaterial ) {
  1035. refreshUniformsCommon( m_uniforms, material );
  1036. }
  1037. // refresh single material specific uniforms
  1038. if ( material instanceof THREE.LineBasicMaterial ) {
  1039. refreshUniformsLine( m_uniforms, material );
  1040. } else if ( material instanceof THREE.LineDashedMaterial ) {
  1041. refreshUniformsLine( m_uniforms, material );
  1042. refreshUniformsDash( m_uniforms, material );
  1043. } else if ( material instanceof THREE.PointsMaterial ) {
  1044. refreshUniformsPoints( m_uniforms, material );
  1045. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  1046. refreshUniformsLambert( m_uniforms, material );
  1047. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  1048. refreshUniformsPhong( m_uniforms, material );
  1049. } else if ( material instanceof THREE.MeshStandardMaterial ) {
  1050. refreshUniformsStandard( m_uniforms, material );
  1051. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  1052. m_uniforms.mNear.value = camera.near;
  1053. m_uniforms.mFar.value = camera.far;
  1054. m_uniforms.opacity.value = material.opacity;
  1055. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  1056. m_uniforms.opacity.value = material.opacity;
  1057. }
  1058. // load common uniforms
  1059. loadUniformsGeneric( materialProperties.uniformsList );
  1060. }
  1061. loadUniformsMatrices( p_uniforms, object );
  1062. if ( p_uniforms.modelMatrix !== undefined ) {
  1063. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  1064. }
  1065. if ( materialProperties.hasDynamicUniforms === true ) {
  1066. updateDynamicUniforms( materialProperties.uniformsList, object, camera );
  1067. }
  1068. return program;
  1069. }
  1070. function updateDynamicUniforms ( uniforms, object, camera ) {
  1071. var dynamicUniforms = [];
  1072. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  1073. var uniform = uniforms[ j ][ 0 ];
  1074. var onUpdateCallback = uniform.onUpdateCallback;
  1075. if ( onUpdateCallback !== undefined ) {
  1076. onUpdateCallback.bind( uniform )( object, camera );
  1077. dynamicUniforms.push( uniforms[ j ] );
  1078. }
  1079. }
  1080. loadUniformsGeneric( dynamicUniforms );
  1081. }
  1082. // Uniforms (refresh uniforms objects)
  1083. function refreshUniformsCommon ( uniforms, material ) {
  1084. uniforms.opacity.value = material.opacity;
  1085. uniforms.diffuse.value = material.color;
  1086. if ( material.emissive ) {
  1087. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1088. }
  1089. uniforms.map.value = material.map;
  1090. uniforms.specularMap.value = material.specularMap;
  1091. uniforms.alphaMap.value = material.alphaMap;
  1092. if ( material.aoMap ) {
  1093. uniforms.aoMap.value = material.aoMap;
  1094. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1095. }
  1096. // uv repeat and offset setting priorities
  1097. // 1. color map
  1098. // 2. specular map
  1099. // 3. normal map
  1100. // 4. bump map
  1101. // 5. alpha map
  1102. // 6. emissive map
  1103. var uvScaleMap;
  1104. if ( material.map ) {
  1105. uvScaleMap = material.map;
  1106. } else if ( material.specularMap ) {
  1107. uvScaleMap = material.specularMap;
  1108. } else if ( material.displacementMap ) {
  1109. uvScaleMap = material.displacementMap;
  1110. } else if ( material.normalMap ) {
  1111. uvScaleMap = material.normalMap;
  1112. } else if ( material.bumpMap ) {
  1113. uvScaleMap = material.bumpMap;
  1114. } else if ( material.roughnessMap ) {
  1115. uvScaleMap = material.roughnessMap;
  1116. } else if ( material.metalnessMap ) {
  1117. uvScaleMap = material.metalnessMap;
  1118. } else if ( material.alphaMap ) {
  1119. uvScaleMap = material.alphaMap;
  1120. } else if ( material.emissiveMap ) {
  1121. uvScaleMap = material.emissiveMap;
  1122. }
  1123. if ( uvScaleMap !== undefined ) {
  1124. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {
  1125. uvScaleMap = uvScaleMap.texture;
  1126. }
  1127. var offset = uvScaleMap.offset;
  1128. var repeat = uvScaleMap.repeat;
  1129. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1130. }
  1131. uniforms.envMap.value = material.envMap;
  1132. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  1133. uniforms.reflectivity.value = material.reflectivity;
  1134. uniforms.refractionRatio.value = material.refractionRatio;
  1135. }
  1136. function refreshUniformsLine ( uniforms, material ) {
  1137. uniforms.diffuse.value = material.color;
  1138. uniforms.opacity.value = material.opacity;
  1139. }
  1140. function refreshUniformsDash ( uniforms, material ) {
  1141. uniforms.dashSize.value = material.dashSize;
  1142. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1143. uniforms.scale.value = material.scale;
  1144. }
  1145. function refreshUniformsPoints ( uniforms, material ) {
  1146. uniforms.diffuse.value = material.color;
  1147. uniforms.opacity.value = material.opacity;
  1148. uniforms.size.value = material.size * _pixelRatio;
  1149. uniforms.scale.value = _canvas.clientHeight / 2.0; // TODO: Cache this.
  1150. uniforms.map.value = material.map;
  1151. if ( material.map !== null ) {
  1152. var offset = material.map.offset;
  1153. var repeat = material.map.repeat;
  1154. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1155. }
  1156. }
  1157. function refreshUniformsFog ( uniforms, fog ) {
  1158. uniforms.fogColor.value = fog.color;
  1159. if ( fog instanceof THREE.Fog ) {
  1160. uniforms.fogNear.value = fog.near;
  1161. uniforms.fogFar.value = fog.far;
  1162. } else if ( fog instanceof THREE.FogExp2 ) {
  1163. uniforms.fogDensity.value = fog.density;
  1164. }
  1165. }
  1166. function refreshUniformsLambert ( uniforms, material ) {
  1167. if ( material.lightMap ) {
  1168. uniforms.lightMap.value = material.lightMap;
  1169. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1170. }
  1171. if ( material.emissiveMap ) {
  1172. uniforms.emissiveMap.value = material.emissiveMap;
  1173. }
  1174. }
  1175. function refreshUniformsPhong ( uniforms, material ) {
  1176. uniforms.specular.value = material.specular;
  1177. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1178. if ( material.lightMap ) {
  1179. uniforms.lightMap.value = material.lightMap;
  1180. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1181. }
  1182. if ( material.emissiveMap ) {
  1183. uniforms.emissiveMap.value = material.emissiveMap;
  1184. }
  1185. if ( material.bumpMap ) {
  1186. uniforms.bumpMap.value = material.bumpMap;
  1187. uniforms.bumpScale.value = material.bumpScale;
  1188. }
  1189. if ( material.normalMap ) {
  1190. uniforms.normalMap.value = material.normalMap;
  1191. uniforms.normalScale.value.copy( material.normalScale );
  1192. }
  1193. if ( material.displacementMap ) {
  1194. uniforms.displacementMap.value = material.displacementMap;
  1195. uniforms.displacementScale.value = material.displacementScale;
  1196. uniforms.displacementBias.value = material.displacementBias;
  1197. }
  1198. }
  1199. function refreshUniformsStandard ( uniforms, material ) {
  1200. uniforms.roughness.value = material.roughness;
  1201. uniforms.metalness.value = material.metalness;
  1202. if ( material.roughnessMap ) {
  1203. uniforms.roughnessMap.value = material.roughnessMap;
  1204. }
  1205. if ( material.metalnessMap ) {
  1206. uniforms.metalnessMap.value = material.metalnessMap;
  1207. }
  1208. if ( material.lightMap ) {
  1209. uniforms.lightMap.value = material.lightMap;
  1210. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1211. }
  1212. if ( material.emissiveMap ) {
  1213. uniforms.emissiveMap.value = material.emissiveMap;
  1214. }
  1215. if ( material.bumpMap ) {
  1216. uniforms.bumpMap.value = material.bumpMap;
  1217. uniforms.bumpScale.value = material.bumpScale;
  1218. }
  1219. if ( material.normalMap ) {
  1220. uniforms.normalMap.value = material.normalMap;
  1221. uniforms.normalScale.value.copy( material.normalScale );
  1222. }
  1223. if ( material.displacementMap ) {
  1224. uniforms.displacementMap.value = material.displacementMap;
  1225. uniforms.displacementScale.value = material.displacementScale;
  1226. uniforms.displacementBias.value = material.displacementBias;
  1227. }
  1228. if ( material.envMap ) {
  1229. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1230. uniforms.envMapIntensity.value = material.envMapIntensity;
  1231. }
  1232. }
  1233. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1234. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  1235. uniforms.ambientLightColor.needsUpdate = value;
  1236. uniforms.directionalLights.needsUpdate = value;
  1237. uniforms.pointLights.needsUpdate = value;
  1238. uniforms.spotLights.needsUpdate = value;
  1239. uniforms.hemisphereLights.needsUpdate = value;
  1240. }
  1241. // Uniforms (load to GPU)
  1242. function loadUniformsMatrices ( uniforms, object ) {
  1243. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
  1244. if ( uniforms.normalMatrix ) {
  1245. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
  1246. }
  1247. }
  1248. function getTextureUnit() {
  1249. var textureUnit = _usedTextureUnits;
  1250. if ( textureUnit >= capabilities.maxTextures ) {
  1251. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  1252. }
  1253. _usedTextureUnits += 1;
  1254. return textureUnit;
  1255. }
  1256. function loadUniform( uniform, type, location, value ) {
  1257. var texture, textureUnit;
  1258. if ( type === '1i' ) {
  1259. _gl.uniform1i( location, value );
  1260. } else if ( type === '1f' ) {
  1261. _gl.uniform1f( location, value );
  1262. } else if ( type === '2f' ) {
  1263. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  1264. } else if ( type === '3f' ) {
  1265. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  1266. } else if ( type === '4f' ) {
  1267. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  1268. } else if ( type === '1iv' ) {
  1269. _gl.uniform1iv( location, value );
  1270. } else if ( type === '3iv' ) {
  1271. _gl.uniform3iv( location, value );
  1272. } else if ( type === '1fv' ) {
  1273. _gl.uniform1fv( location, value );
  1274. } else if ( type === '2fv' ) {
  1275. _gl.uniform2fv( location, value );
  1276. } else if ( type === '3fv' ) {
  1277. _gl.uniform3fv( location, value );
  1278. } else if ( type === '4fv' ) {
  1279. _gl.uniform4fv( location, value );
  1280. } else if ( type === 'Matrix2fv' ) {
  1281. _gl.uniformMatrix2fv( location, false, value );
  1282. } else if ( type === 'Matrix3fv' ) {
  1283. _gl.uniformMatrix3fv( location, false, value );
  1284. } else if ( type === 'Matrix4fv' ) {
  1285. _gl.uniformMatrix4fv( location, false, value );
  1286. //
  1287. } else if ( type === 'i' ) {
  1288. // single integer
  1289. _gl.uniform1i( location, value );
  1290. } else if ( type === 'f' ) {
  1291. // single float
  1292. _gl.uniform1f( location, value );
  1293. } else if ( type === 'v2' ) {
  1294. // single THREE.Vector2
  1295. _gl.uniform2f( location, value.x, value.y );
  1296. } else if ( type === 'v3' ) {
  1297. // single THREE.Vector3
  1298. _gl.uniform3f( location, value.x, value.y, value.z );
  1299. } else if ( type === 'v4' ) {
  1300. // single THREE.Vector4
  1301. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  1302. } else if ( type === 'c' ) {
  1303. // single THREE.Color
  1304. _gl.uniform3f( location, value.r, value.g, value.b );
  1305. } else if ( type === 's' ) {
  1306. // TODO: Optimize this
  1307. var properties = uniform.properties;
  1308. for ( var name in properties ) {
  1309. var property = properties[ name ];
  1310. var locationProperty = location[ name ];
  1311. var valueProperty = value[ name ];
  1312. loadUniform( property, property.type, locationProperty, valueProperty );
  1313. }
  1314. } else if ( type === 'sa' ) {
  1315. // TODO: Optimize this
  1316. var properties = uniform.properties;
  1317. for ( var i = 0, l = value.length; i < l; i ++ ) {
  1318. for ( var name in properties ) {
  1319. var property = properties[ name ];
  1320. var locationProperty = location[ i ][ name ];
  1321. var valueProperty = value[ i ][ name ];
  1322. loadUniform( property, property.type, locationProperty, valueProperty );
  1323. }
  1324. }
  1325. } else if ( type === 'iv1' ) {
  1326. // flat array of integers (JS or typed array)
  1327. _gl.uniform1iv( location, value );
  1328. } else if ( type === 'iv' ) {
  1329. // flat array of integers with 3 x N size (JS or typed array)
  1330. _gl.uniform3iv( location, value );
  1331. } else if ( type === 'fv1' ) {
  1332. // flat array of floats (JS or typed array)
  1333. _gl.uniform1fv( location, value );
  1334. } else if ( type === 'fv' ) {
  1335. // flat array of floats with 3 x N size (JS or typed array)
  1336. _gl.uniform3fv( location, value );
  1337. } else if ( type === 'v2v' ) {
  1338. // array of THREE.Vector2
  1339. if ( uniform._array === undefined ) {
  1340. uniform._array = new Float32Array( 2 * value.length );
  1341. }
  1342. for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
  1343. uniform._array[ i2 + 0 ] = value[ i ].x;
  1344. uniform._array[ i2 + 1 ] = value[ i ].y;
  1345. }
  1346. _gl.uniform2fv( location, uniform._array );
  1347. } else if ( type === 'v3v' ) {
  1348. // array of THREE.Vector3
  1349. if ( uniform._array === undefined ) {
  1350. uniform._array = new Float32Array( 3 * value.length );
  1351. }
  1352. for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
  1353. uniform._array[ i3 + 0 ] = value[ i ].x;
  1354. uniform._array[ i3 + 1 ] = value[ i ].y;
  1355. uniform._array[ i3 + 2 ] = value[ i ].z;
  1356. }
  1357. _gl.uniform3fv( location, uniform._array );
  1358. } else if ( type === 'v4v' ) {
  1359. // array of THREE.Vector4
  1360. if ( uniform._array === undefined ) {
  1361. uniform._array = new Float32Array( 4 * value.length );
  1362. }
  1363. for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
  1364. uniform._array[ i4 + 0 ] = value[ i ].x;
  1365. uniform._array[ i4 + 1 ] = value[ i ].y;
  1366. uniform._array[ i4 + 2 ] = value[ i ].z;
  1367. uniform._array[ i4 + 3 ] = value[ i ].w;
  1368. }
  1369. _gl.uniform4fv( location, uniform._array );
  1370. } else if ( type === 'm2' ) {
  1371. // single THREE.Matrix2
  1372. _gl.uniformMatrix2fv( location, false, value.elements );
  1373. } else if ( type === 'm3' ) {
  1374. // single THREE.Matrix3
  1375. _gl.uniformMatrix3fv( location, false, value.elements );
  1376. } else if ( type === 'm3v' ) {
  1377. // array of THREE.Matrix3
  1378. if ( uniform._array === undefined ) {
  1379. uniform._array = new Float32Array( 9 * value.length );
  1380. }
  1381. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1382. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  1383. }
  1384. _gl.uniformMatrix3fv( location, false, uniform._array );
  1385. } else if ( type === 'm4' ) {
  1386. // single THREE.Matrix4
  1387. _gl.uniformMatrix4fv( location, false, value.elements );
  1388. } else if ( type === 'm4v' ) {
  1389. // array of THREE.Matrix4
  1390. if ( uniform._array === undefined ) {
  1391. uniform._array = new Float32Array( 16 * value.length );
  1392. }
  1393. for ( var i = 0, il = value.length; i < il; i ++ ) {
  1394. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  1395. }
  1396. _gl.uniformMatrix4fv( location, false, uniform._array );
  1397. } else if ( type === 't' ) {
  1398. // single THREE.Texture (2d or cube)
  1399. texture = value;
  1400. textureUnit = getTextureUnit();
  1401. _gl.uniform1i( location, textureUnit );
  1402. if ( ! texture ) return;
  1403. if ( texture instanceof THREE.CubeTexture ||
  1404. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  1405. // CompressedTexture can have Array in image :/
  1406. setCubeTexture( texture, textureUnit );
  1407. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  1408. setCubeTextureDynamic( texture.texture, textureUnit );
  1409. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  1410. _this.setTexture( texture.texture, textureUnit );
  1411. } else {
  1412. _this.setTexture( texture, textureUnit );
  1413. }
  1414. } else if ( type === 'tv' ) {
  1415. // array of THREE.Texture (2d or cube)
  1416. if ( uniform._array === undefined ) {
  1417. uniform._array = [];
  1418. }
  1419. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  1420. uniform._array[ i ] = getTextureUnit();
  1421. }
  1422. _gl.uniform1iv( location, uniform._array );
  1423. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  1424. texture = uniform.value[ i ];
  1425. textureUnit = uniform._array[ i ];
  1426. if ( ! texture ) continue;
  1427. if ( texture instanceof THREE.CubeTexture ||
  1428. ( texture.image instanceof Array && texture.image.length === 6 ) ) {
  1429. // CompressedTexture can have Array in image :/
  1430. setCubeTexture( texture, textureUnit );
  1431. } else if ( texture instanceof THREE.WebGLRenderTarget ) {
  1432. _this.setTexture( texture.texture, textureUnit );
  1433. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  1434. setCubeTextureDynamic( texture.texture, textureUnit );
  1435. } else {
  1436. _this.setTexture( texture, textureUnit );
  1437. }
  1438. }
  1439. } else {
  1440. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  1441. }
  1442. }
  1443. function loadUniformsGeneric( uniforms ) {
  1444. for ( var i = 0, l = uniforms.length; i < l; i ++ ) {
  1445. var uniform = uniforms[ i ][ 0 ];
  1446. // needsUpdate property is not added to all uniforms.
  1447. if ( uniform.needsUpdate === false ) continue;
  1448. var type = uniform.type;
  1449. var location = uniforms[ i ][ 1 ];
  1450. var value = uniform.value;
  1451. loadUniform( uniform, type, location, value );
  1452. }
  1453. }
  1454. function setupLights ( lights, camera ) {
  1455. var l, ll, light,
  1456. r = 0, g = 0, b = 0,
  1457. color,
  1458. intensity,
  1459. distance,
  1460. viewMatrix = camera.matrixWorldInverse,
  1461. directionalLength = 0,
  1462. pointLength = 0,
  1463. spotLength = 0,
  1464. hemiLength = 0,
  1465. shadowsLength = 0;
  1466. _lights.shadowsPointLight = 0;
  1467. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  1468. light = lights[ l ];
  1469. color = light.color;
  1470. intensity = light.intensity;
  1471. distance = light.distance;
  1472. if ( light instanceof THREE.AmbientLight ) {
  1473. r += color.r * intensity;
  1474. g += color.g * intensity;
  1475. b += color.b * intensity;
  1476. } else if ( light instanceof THREE.DirectionalLight ) {
  1477. var uniforms = lightCache.get( light );
  1478. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1479. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1480. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1481. uniforms.direction.sub( _vector3 );
  1482. uniforms.direction.transformDirection( viewMatrix );
  1483. uniforms.shadow = light.castShadow;
  1484. if ( light.castShadow ) {
  1485. uniforms.shadowBias = light.shadow.bias;
  1486. uniforms.shadowRadius = light.shadow.radius;
  1487. uniforms.shadowMapSize = light.shadow.mapSize;
  1488. _lights.shadows[ shadowsLength ++ ] = light;
  1489. }
  1490. _lights.directionalShadowMap[ directionalLength ] = light.shadow.map;
  1491. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  1492. _lights.directional[ directionalLength ++ ] = uniforms;
  1493. } else if ( light instanceof THREE.SpotLight ) {
  1494. var uniforms = lightCache.get( light );
  1495. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1496. uniforms.position.applyMatrix4( viewMatrix );
  1497. uniforms.color.copy( color ).multiplyScalar( intensity );
  1498. uniforms.distance = distance;
  1499. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1500. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1501. uniforms.direction.sub( _vector3 );
  1502. uniforms.direction.transformDirection( viewMatrix );
  1503. uniforms.coneCos = Math.cos( light.angle );
  1504. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  1505. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1506. uniforms.shadow = light.castShadow;
  1507. if ( light.castShadow ) {
  1508. uniforms.shadowBias = light.shadow.bias;
  1509. uniforms.shadowRadius = light.shadow.radius;
  1510. uniforms.shadowMapSize = light.shadow.mapSize;
  1511. _lights.shadows[ shadowsLength ++ ] = light;
  1512. }
  1513. _lights.spotShadowMap[ spotLength ] = light.shadow.map;
  1514. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  1515. _lights.spot[ spotLength ++ ] = uniforms;
  1516. } else if ( light instanceof THREE.PointLight ) {
  1517. var uniforms = lightCache.get( light );
  1518. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1519. uniforms.position.applyMatrix4( viewMatrix );
  1520. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1521. uniforms.distance = light.distance;
  1522. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1523. uniforms.shadow = light.castShadow;
  1524. if ( light.castShadow ) {
  1525. uniforms.shadowBias = light.shadow.bias;
  1526. uniforms.shadowRadius = light.shadow.radius;
  1527. uniforms.shadowMapSize = light.shadow.mapSize;
  1528. _lights.shadows[ shadowsLength ++ ] = light;
  1529. }
  1530. _lights.pointShadowMap[ pointLength ] = light.shadow.map;
  1531. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  1532. _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4();
  1533. }
  1534. // for point lights we set the shadow matrix to be a translation-only matrix
  1535. // equal to inverse of the light's position
  1536. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  1537. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  1538. _lights.point[ pointLength ++ ] = uniforms;
  1539. } else if ( light instanceof THREE.HemisphereLight ) {
  1540. var uniforms = lightCache.get( light );
  1541. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1542. uniforms.direction.transformDirection( viewMatrix );
  1543. uniforms.direction.normalize();
  1544. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  1545. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  1546. _lights.hemi[ hemiLength ++ ] = uniforms;
  1547. }
  1548. }
  1549. _lights.ambient[ 0 ] = r;
  1550. _lights.ambient[ 1 ] = g;
  1551. _lights.ambient[ 2 ] = b;
  1552. _lights.directional.length = directionalLength;
  1553. _lights.spot.length = spotLength;
  1554. _lights.point.length = pointLength;
  1555. _lights.hemi.length = hemiLength;
  1556. _lights.shadows.length = shadowsLength;
  1557. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + shadowsLength;
  1558. }
  1559. // GL state setting
  1560. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  1561. if ( cullFace === THREE.CullFaceNone ) {
  1562. state.disable( _gl.CULL_FACE );
  1563. } else {
  1564. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  1565. _gl.frontFace( _gl.CW );
  1566. } else {
  1567. _gl.frontFace( _gl.CCW );
  1568. }
  1569. if ( cullFace === THREE.CullFaceBack ) {
  1570. _gl.cullFace( _gl.BACK );
  1571. } else if ( cullFace === THREE.CullFaceFront ) {
  1572. _gl.cullFace( _gl.FRONT );
  1573. } else {
  1574. _gl.cullFace( _gl.FRONT_AND_BACK );
  1575. }
  1576. state.enable( _gl.CULL_FACE );
  1577. }
  1578. };
  1579. // Textures
  1580. function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) {
  1581. var extension;
  1582. if ( isPowerOfTwoImage ) {
  1583. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  1584. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  1585. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  1586. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  1587. } else {
  1588. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  1589. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  1590. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  1591. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  1592. }
  1593. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  1594. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  1595. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  1596. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  1597. }
  1598. }
  1599. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  1600. if ( extension ) {
  1601. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  1602. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  1603. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  1604. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  1605. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  1606. }
  1607. }
  1608. }
  1609. function uploadTexture( textureProperties, texture, slot ) {
  1610. if ( textureProperties.__webglInit === undefined ) {
  1611. textureProperties.__webglInit = true;
  1612. texture.addEventListener( 'dispose', onTextureDispose );
  1613. textureProperties.__webglTexture = _gl.createTexture();
  1614. _infoMemory.textures ++;
  1615. }
  1616. state.activeTexture( _gl.TEXTURE0 + slot );
  1617. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  1618. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  1619. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  1620. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  1621. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  1622. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  1623. image = makePowerOfTwo( image );
  1624. }
  1625. var isPowerOfTwoImage = isPowerOfTwo( image ),
  1626. glFormat = paramThreeToGL( texture.format ),
  1627. glType = paramThreeToGL( texture.type );
  1628. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  1629. var mipmap, mipmaps = texture.mipmaps;
  1630. if ( texture instanceof THREE.DataTexture ) {
  1631. // use manually created mipmaps if available
  1632. // if there are no manual mipmaps
  1633. // set 0 level mipmap and then use GL to generate other mipmap levels
  1634. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  1635. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1636. mipmap = mipmaps[ i ];
  1637. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1638. }
  1639. texture.generateMipmaps = false;
  1640. } else {
  1641. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  1642. }
  1643. } else if ( texture instanceof THREE.CompressedTexture ) {
  1644. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1645. mipmap = mipmaps[ i ];
  1646. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  1647. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  1648. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  1649. } else {
  1650. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  1651. }
  1652. } else {
  1653. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1654. }
  1655. }
  1656. } else {
  1657. // regular Texture (image, video, canvas)
  1658. // use manually created mipmaps if available
  1659. // if there are no manual mipmaps
  1660. // set 0 level mipmap and then use GL to generate other mipmap levels
  1661. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  1662. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  1663. mipmap = mipmaps[ i ];
  1664. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  1665. }
  1666. texture.generateMipmaps = false;
  1667. } else {
  1668. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  1669. }
  1670. }
  1671. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1672. textureProperties.__version = texture.version;
  1673. if ( texture.onUpdate ) texture.onUpdate( texture );
  1674. }
  1675. this.setTexture = function ( texture, slot ) {
  1676. var textureProperties = properties.get( texture );
  1677. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  1678. var image = texture.image;
  1679. if ( image === undefined ) {
  1680. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  1681. return;
  1682. }
  1683. if ( image.complete === false ) {
  1684. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  1685. return;
  1686. }
  1687. uploadTexture( textureProperties, texture, slot );
  1688. return;
  1689. }
  1690. state.activeTexture( _gl.TEXTURE0 + slot );
  1691. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  1692. };
  1693. function clampToMaxSize ( image, maxSize ) {
  1694. if ( image.width > maxSize || image.height > maxSize ) {
  1695. // Warning: Scaling through the canvas will only work with images that use
  1696. // premultiplied alpha.
  1697. var scale = maxSize / Math.max( image.width, image.height );
  1698. var canvas = document.createElement( 'canvas' );
  1699. canvas.width = Math.floor( image.width * scale );
  1700. canvas.height = Math.floor( image.height * scale );
  1701. var context = canvas.getContext( '2d' );
  1702. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  1703. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  1704. return canvas;
  1705. }
  1706. return image;
  1707. }
  1708. function isPowerOfTwo( image ) {
  1709. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  1710. }
  1711. function textureNeedsPowerOfTwo( texture ) {
  1712. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  1713. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  1714. return false;
  1715. }
  1716. function makePowerOfTwo( image ) {
  1717. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  1718. var canvas = document.createElement( 'canvas' );
  1719. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  1720. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  1721. var context = canvas.getContext( '2d' );
  1722. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  1723. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  1724. return canvas;
  1725. }
  1726. return image;
  1727. }
  1728. function setCubeTexture ( texture, slot ) {
  1729. var textureProperties = properties.get( texture );
  1730. if ( texture.image.length === 6 ) {
  1731. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  1732. if ( ! textureProperties.__image__webglTextureCube ) {
  1733. texture.addEventListener( 'dispose', onTextureDispose );
  1734. textureProperties.__image__webglTextureCube = _gl.createTexture();
  1735. _infoMemory.textures ++;
  1736. }
  1737. state.activeTexture( _gl.TEXTURE0 + slot );
  1738. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  1739. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  1740. var isCompressed = texture instanceof THREE.CompressedTexture;
  1741. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  1742. var cubeImage = [];
  1743. for ( var i = 0; i < 6; i ++ ) {
  1744. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  1745. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  1746. } else {
  1747. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  1748. }
  1749. }
  1750. var image = cubeImage[ 0 ],
  1751. isPowerOfTwoImage = isPowerOfTwo( image ),
  1752. glFormat = paramThreeToGL( texture.format ),
  1753. glType = paramThreeToGL( texture.type );
  1754. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  1755. for ( var i = 0; i < 6; i ++ ) {
  1756. if ( ! isCompressed ) {
  1757. if ( isDataTexture ) {
  1758. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  1759. } else {
  1760. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  1761. }
  1762. } else {
  1763. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  1764. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  1765. mipmap = mipmaps[ j ];
  1766. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  1767. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  1768. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  1769. } else {
  1770. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  1771. }
  1772. } else {
  1773. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  1774. }
  1775. }
  1776. }
  1777. }
  1778. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  1779. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  1780. }
  1781. textureProperties.__version = texture.version;
  1782. if ( texture.onUpdate ) texture.onUpdate( texture );
  1783. } else {
  1784. state.activeTexture( _gl.TEXTURE0 + slot );
  1785. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  1786. }
  1787. }
  1788. }
  1789. function setCubeTextureDynamic ( texture, slot ) {
  1790. state.activeTexture( _gl.TEXTURE0 + slot );
  1791. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  1792. }
  1793. // Render targets
  1794. // Setup storage for target texture and bind it to correct framebuffer
  1795. function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
  1796. var glFormat = paramThreeToGL( renderTarget.texture.format );
  1797. var glType = paramThreeToGL( renderTarget.texture.type );
  1798. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  1799. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1800. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  1801. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1802. }
  1803. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  1804. function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
  1805. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  1806. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  1807. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  1808. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  1809. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  1810. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  1811. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  1812. } else {
  1813. // FIXME: We don't support !depth !stencil
  1814. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  1815. }
  1816. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  1817. }
  1818. // Setup GL resources for a non-texture depth buffer
  1819. function setupDepthRenderbuffer( renderTarget ) {
  1820. var renderTargetProperties = properties.get( renderTarget );
  1821. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  1822. if ( isCube ) {
  1823. renderTargetProperties.__webglDepthbuffer = [];
  1824. for ( var i = 0; i < 6; i ++ ) {
  1825. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  1826. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  1827. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  1828. }
  1829. } else {
  1830. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  1831. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  1832. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  1833. }
  1834. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  1835. }
  1836. // Set up GL resources for the render target
  1837. function setupRenderTarget( renderTarget ) {
  1838. var renderTargetProperties = properties.get( renderTarget );
  1839. var textureProperties = properties.get( renderTarget.texture );
  1840. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  1841. textureProperties.__webglTexture = _gl.createTexture();
  1842. _infoMemory.textures ++;
  1843. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  1844. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
  1845. // Setup framebuffer
  1846. if ( isCube ) {
  1847. renderTargetProperties.__webglFramebuffer = [];
  1848. for ( var i = 0; i < 6; i ++ ) {
  1849. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  1850. }
  1851. } else {
  1852. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  1853. }
  1854. // Setup color buffer
  1855. if ( isCube ) {
  1856. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  1857. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  1858. for ( var i = 0; i < 6; i ++ ) {
  1859. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  1860. }
  1861. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  1862. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  1863. } else {
  1864. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  1865. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  1866. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  1867. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  1868. state.bindTexture( _gl.TEXTURE_2D, null );
  1869. }
  1870. // Setup depth and stencil buffers
  1871. if ( renderTarget.depthBuffer ) {
  1872. setupDepthRenderbuffer( renderTarget );
  1873. }
  1874. }
  1875. this.getCurrentRenderTarget = function() {
  1876. return _currentRenderTarget;
  1877. }
  1878. this.setRenderTarget = function ( renderTarget ) {
  1879. _currentRenderTarget = renderTarget;
  1880. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1881. setupRenderTarget( renderTarget );
  1882. }
  1883. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  1884. var framebuffer;
  1885. if ( renderTarget ) {
  1886. var renderTargetProperties = properties.get( renderTarget );
  1887. if ( isCube ) {
  1888. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  1889. } else {
  1890. framebuffer = renderTargetProperties.__webglFramebuffer;
  1891. }
  1892. _currentScissor.copy( renderTarget.scissor );
  1893. _currentScissorTest = renderTarget.scissorTest;
  1894. _currentViewport.copy( renderTarget.viewport );
  1895. } else {
  1896. framebuffer = null;
  1897. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  1898. _currentScissorTest = _scissorTest;
  1899. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  1900. }
  1901. if ( _currentFramebuffer !== framebuffer ) {
  1902. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1903. _currentFramebuffer = framebuffer;
  1904. }
  1905. state.scissor( _currentScissor );
  1906. state.setScissorTest( _currentScissorTest );
  1907. state.viewport( _currentViewport );
  1908. if ( isCube ) {
  1909. var textureProperties = properties.get( renderTarget.texture );
  1910. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, 0 );
  1911. }
  1912. };
  1913. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  1914. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  1915. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1916. return;
  1917. }
  1918. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1919. if ( framebuffer ) {
  1920. var restore = false;
  1921. if ( framebuffer !== _currentFramebuffer ) {
  1922. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1923. restore = true;
  1924. }
  1925. try {
  1926. var texture = renderTarget.texture;
  1927. if ( texture.format !== THREE.RGBAFormat
  1928. && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1929. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1930. return;
  1931. }
  1932. if ( texture.type !== THREE.UnsignedByteType
  1933. && paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
  1934. && ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
  1935. && ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  1936. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1937. return;
  1938. }
  1939. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  1940. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  1941. } else {
  1942. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  1943. }
  1944. } finally {
  1945. if ( restore ) {
  1946. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  1947. }
  1948. }
  1949. }
  1950. };
  1951. function updateRenderTargetMipmap( renderTarget ) {
  1952. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  1953. var texture = properties.get( renderTarget.texture ).__webglTexture;
  1954. state.bindTexture( target, texture );
  1955. _gl.generateMipmap( target );
  1956. state.bindTexture( target, null );
  1957. }
  1958. // Fallback filters for non-power-of-2 textures
  1959. function filterFallback ( f ) {
  1960. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  1961. return _gl.NEAREST;
  1962. }
  1963. return _gl.LINEAR;
  1964. }
  1965. // Map three.js constants to WebGL constants
  1966. function paramThreeToGL ( p ) {
  1967. var extension;
  1968. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  1969. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  1970. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  1971. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  1972. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  1973. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  1974. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  1975. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  1976. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  1977. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  1978. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  1979. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  1980. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  1981. if ( p === THREE.ByteType ) return _gl.BYTE;
  1982. if ( p === THREE.ShortType ) return _gl.SHORT;
  1983. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  1984. if ( p === THREE.IntType ) return _gl.INT;
  1985. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  1986. if ( p === THREE.FloatType ) return _gl.FLOAT;
  1987. extension = extensions.get( 'OES_texture_half_float' );
  1988. if ( extension !== null ) {
  1989. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  1990. }
  1991. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  1992. if ( p === THREE.RGBFormat ) return _gl.RGB;
  1993. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  1994. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  1995. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  1996. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  1997. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  1998. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  1999. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  2000. if ( p === THREE.OneFactor ) return _gl.ONE;
  2001. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  2002. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  2003. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  2004. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  2005. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  2006. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  2007. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  2008. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  2009. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  2010. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  2011. if ( extension !== null ) {
  2012. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  2013. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  2014. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  2015. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  2016. }
  2017. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  2018. if ( extension !== null ) {
  2019. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  2020. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  2021. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  2022. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  2023. }
  2024. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  2025. if ( extension !== null ) {
  2026. if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  2027. }
  2028. extension = extensions.get( 'EXT_blend_minmax' );
  2029. if ( extension !== null ) {
  2030. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  2031. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  2032. }
  2033. return 0;
  2034. }
  2035. };