WebGLRenderer.js 92 KB

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