WebGLRenderer.js 83 KB

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