WebGLRenderer.js 93 KB

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