WebGLRenderer.js 92 KB

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