WebGLRenderer.js 95 KB

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