WebGLRenderer2.js 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360
  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. * @author gero3 / https://github.com/gero3/
  7. */
  8. THREE.WebGLRenderer = THREE.WebGLRenderer2 = function ( parameters ) {
  9. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10. parameters = parameters || {};
  11. var info = {
  12. memory: {
  13. programs: 0,
  14. geometries: 0,
  15. textures: 0
  16. },
  17. render: {
  18. calls: 0,
  19. vertices: 0,
  20. faces: 0,
  21. points: 0
  22. }
  23. };
  24. var renderer = new THREE.WebGLRenderer2.LowLevelRenderer(parameters);
  25. var meshRenderer = new THREE.WebGLRenderer2.MeshRenderer(renderer, info);
  26. var particleRenderer = new THREE.WebGLRenderer2.ParticleRenderer(renderer, info);
  27. var lineRenderer = new THREE.WebGLRenderer2.LineRenderer(renderer, info);
  28. var ribbonRenderer = new THREE.WebGLRenderer2.RibbonRenderer(renderer, info);
  29. var shaderBuilder = new THREE.WebGLRenderer2.ShaderBuilder(renderer, info);
  30. // clearing
  31. this.autoClear = true;
  32. this.autoClearColor = true;
  33. this.autoClearDepth = true;
  34. this.autoClearStencil = true;
  35. // scene graph
  36. this.sortObjects = true;
  37. this.autoUpdateObjects = true;
  38. this.autoUpdateScene = true;
  39. // physically based shading
  40. this.gammaInput = false;
  41. this.gammaOutput = false;
  42. this.physicallyBasedShading = false;
  43. // shadow map
  44. this.shadowMapEnabled = false;
  45. this.shadowMapAutoUpdate = true;
  46. this.shadowMapType = THREE.PCFShadowMap;
  47. this.shadowMapCullFace = THREE.CullFaceFront;
  48. this.shadowMapDebug = false;
  49. this.shadowMapCascade = false;
  50. // morphs
  51. this.maxMorphTargets = 8;
  52. this.maxMorphNormals = 4;
  53. // flags
  54. this.autoScaleCubemaps = true;
  55. // custom render plugins
  56. this.renderPluginsPre = [];
  57. this.renderPluginsPost = [];
  58. // info
  59. this.info = info;
  60. // internal properties
  61. var _this = this,
  62. // internal state cache
  63. _currentProgram = null,
  64. _currentFramebuffer = null,
  65. _currentMaterialId = -1,
  66. _currentGeometryGroupHash = null,
  67. _currentCamera = null,
  68. _geometryGroupCounter = 0,
  69. _usedTextureUnits = 0,
  70. // GL state
  71. _viewportX = 0,
  72. _viewportY = 0,
  73. _viewportWidth = 0,
  74. _viewportHeight = 0,
  75. _currentWidth = 0,
  76. _currentHeight = 0,
  77. _enabledAttributes = {},
  78. // frustum
  79. _frustum = new THREE.Frustum(),
  80. // camera matrices cache
  81. _projScreenMatrix = new THREE.Matrix4(),
  82. _projScreenMatrixPS = 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: [] },
  91. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [] },
  92. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  93. };
  94. // initialize
  95. this.context = renderer.getContext();
  96. this.domElement = renderer.getDomElement();
  97. this.getPrecision = renderer.getPrecision;
  98. // low level API
  99. this.getPrecision = renderer.getPrecision;
  100. this.getContext = renderer.getContext;
  101. this.supportsVertexTextures = renderer.supportsVertexTextures;
  102. this.supportsFloatTextures = renderer.supportsFloatTextures;
  103. this.supportsStandardDerivatives = renderer.supportsStandardDerivatives;
  104. this.supportsCompressedTextureS3TC = renderer.supportsCompressedTextureS3TC;
  105. this.getMaxAnisotropy = renderer.getMaxAnisotropy;
  106. this.setSize = renderer.setSize;
  107. this.setViewport = renderer.setViewport;
  108. this.setScissor = renderer.setScissor;
  109. this.enableScissorTest = renderer.enableScissorTest;
  110. this.setDepthWrite = renderer.setDepthWrite;
  111. this.setDepthTest = renderer.setDepthTest;
  112. this.setRenderTarget = renderer.setRenderTarget;
  113. this.setBlending = renderer.setBlending;
  114. this.setTexture = renderer.setTexture;
  115. this.setMaterialFaces = renderer.setMaterialFaces;
  116. this.setFaceCulling = renderer.setFaceCulling;
  117. // Clearing
  118. this.setClearColorHex = renderer.setClearColorHex;
  119. this.setClearColor = renderer.setClearColor;
  120. this.getClearColor = renderer.getClearColor;
  121. this.getClearAlpha = renderer.getClearAlpha;
  122. this.clear = renderer.clear;
  123. this.clearTarget = renderer.clearTarget;
  124. // Plugins
  125. this.addPostPlugin = function ( plugin ) {
  126. plugin.init( this );
  127. this.renderPluginsPost.push( plugin );
  128. };
  129. this.addPrePlugin = function ( plugin ) {
  130. plugin.init( this );
  131. this.renderPluginsPre.push( plugin );
  132. };
  133. // Rendering
  134. this.updateShadowMap = function ( scene, camera ) {
  135. _currentProgram = null;
  136. _currentGeometryGroupHash = -1;
  137. _currentMaterialId = -1;
  138. _lightsNeedUpdate = true;
  139. renderer.resetState();
  140. this.shadowMapPlugin.update( scene, camera );
  141. };
  142. // Events
  143. var onGeometryDispose = function ( event ) {
  144. var geometry = event.target;
  145. geometry.removeEventListener( 'dispose', onGeometryDispose );
  146. deallocateGeometry( geometry );
  147. _this.info.memory.geometries --;
  148. };
  149. var onTextureDispose = function ( event ) {
  150. var texture = event.target;
  151. texture.removeEventListener( 'dispose', onTextureDispose );
  152. deallocateTexture( texture );
  153. _this.info.memory.textures --;
  154. };
  155. var onRenderTargetDispose = function ( event ) {
  156. var renderTarget = event.target;
  157. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  158. deallocateRenderTarget( renderTarget );
  159. _this.info.memory.textures --;
  160. };
  161. var onMaterialDispose = function ( event ) {
  162. var material = event.target;
  163. material.removeEventListener( 'dispose', onMaterialDispose );
  164. deallocateMaterial( material );
  165. };
  166. // Buffer deallocation
  167. var deallocateGeometry = function ( geometry ) {
  168. var m,ml;
  169. geometry.__webglInit = undefined;
  170. if ( geometry.__webglVertexBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglVertexBuffer );
  171. if ( geometry.__webglNormalBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglNormalBuffer );
  172. if ( geometry.__webglTangentBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglTangentBuffer );
  173. if ( geometry.__webglColorBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglColorBuffer );
  174. if ( geometry.__webglUVBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglUVBuffer );
  175. if ( geometry.__webglUV2Buffer !== undefined ) renderer.deleteBuffer( geometry.__webglUV2Buffer );
  176. if ( geometry.__webglSkinIndicesBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  177. if ( geometry.__webglSkinWeightsBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  178. if ( geometry.__webglFaceBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglFaceBuffer );
  179. if ( geometry.__webglLineBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglLineBuffer );
  180. if ( geometry.__webglLineDistanceBuffer !== undefined ) renderer.deleteBuffer( geometry.__webglLineDistanceBuffer );
  181. // geometry groups
  182. if ( geometry.geometryGroups !== undefined ) {
  183. for ( var g in geometry.geometryGroups ) {
  184. var geometryGroup = geometry.geometryGroups[ g ];
  185. if ( geometryGroup.numMorphTargets !== undefined ) {
  186. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  187. renderer.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  188. }
  189. }
  190. if ( geometryGroup.numMorphNormals !== undefined ) {
  191. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  192. renderer.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  193. }
  194. }
  195. deleteCustomAttributesBuffers( geometryGroup );
  196. }
  197. }
  198. deleteCustomAttributesBuffers( geometry );
  199. };
  200. var deallocateTexture = function ( texture ) {
  201. if ( texture.image && texture.image.__webglTextureCube ) {
  202. // cube texture
  203. renderer.deleteTexture( texture.image.__webglTextureCube );
  204. } else {
  205. // 2D texture
  206. if ( ! texture.__webglInit ) return;
  207. texture.__webglInit = false;
  208. renderer.deleteTexture( texture.__webglTexture );
  209. }
  210. };
  211. var deallocateRenderTarget = function ( renderTarget ) {
  212. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  213. renderer.deleteTexture( renderTarget.__webglTexture );
  214. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  215. for ( var i = 0; i < 6; i ++ ) {
  216. renderer.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  217. renderer.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  218. }
  219. } else {
  220. renderer.deleteFramebuffer( renderTarget.__webglFramebuffer );
  221. renderer.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  222. }
  223. };
  224. var deallocateMaterial = function ( material ) {
  225. var program = material.program;
  226. if ( program === undefined ) return;
  227. material.program = undefined;
  228. // only deallocate GL program if this was the last use of shared program
  229. // assumed there is only single copy of any program in the _programs list
  230. // (that's how it's constructed)
  231. shaderBuilder.removeProgram(program)
  232. };
  233. function deleteCustomAttributesBuffers( geometry ) {
  234. if ( geometry.__webglCustomAttributesList ) {
  235. for ( var id in geometry.__webglCustomAttributesList ) {
  236. renderer.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  237. }
  238. }
  239. };
  240. // Buffer initialization
  241. function initCustomAttributes ( geometry, object ) {
  242. var nvertices = geometry.vertices.length;
  243. var material = object.material;
  244. if ( material.attributes ) {
  245. if ( geometry.__webglCustomAttributesList === undefined ) {
  246. geometry.__webglCustomAttributesList = [];
  247. }
  248. for ( var a in material.attributes ) {
  249. var attribute = material.attributes[ a ];
  250. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  251. attribute.__webglInitialized = true;
  252. var size = 1; // "f" and "i"
  253. if ( attribute.type === "v2" ) size = 2;
  254. else if ( attribute.type === "v3" ) size = 3;
  255. else if ( attribute.type === "v4" ) size = 4;
  256. else if ( attribute.type === "c" ) size = 3;
  257. attribute.size = size;
  258. attribute.array = new Float32Array( nvertices * size );
  259. attribute.buffer = renderer.createBuffer();
  260. attribute.buffer.belongsToAttribute = a;
  261. attribute.needsUpdate = true;
  262. }
  263. geometry.__webglCustomAttributesList.push( attribute );
  264. }
  265. }
  266. };
  267. function getBufferMaterial( object, geometryGroup ) {
  268. return object.material instanceof THREE.MeshFaceMaterial
  269. ? object.material.materials[ geometryGroup.materialIndex ]
  270. : object.material;
  271. };
  272. //
  273. function initDirectBuffers( geometry ) {
  274. var a, attribute;
  275. for ( a in geometry.attributes ) {
  276. attribute = geometry.attributes[ a ];
  277. attribute.buffer = renderer.createBuffer();
  278. if ( a === "index" ) {
  279. renderer.setStaticIndexBuffer(attribute.buffer,attribute.array);
  280. } else {
  281. renderer.setStaticArrayBuffer(attribute.buffer,attribute.array);
  282. }
  283. }
  284. };
  285. // Buffer setting
  286. function setDirectBuffers ( geometry, dispose ) {
  287. var attributes = geometry.attributes;
  288. var index = attributes[ "index" ];
  289. var position = attributes[ "position" ];
  290. var normal = attributes[ "normal" ];
  291. var uv = attributes[ "uv" ];
  292. var color = attributes[ "color" ];
  293. var tangent = attributes[ "tangent" ];
  294. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  295. renderer.setDynamicIndexBuffer( index.buffer, index.array);
  296. }
  297. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  298. renderer.setDynamicArrayBuffer( position.buffer, position.array);
  299. }
  300. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  301. renderer.setDynamicArrayBuffer( normal.buffer, normal.array);
  302. }
  303. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  304. renderer.setDynamicArrayBuffer( uv.buffer, uv.array);
  305. }
  306. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  307. renderer.setDynamicArrayBuffer( color.buffer, color.array);
  308. }
  309. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  310. renderer.setDynamicArrayBuffer( tangent.buffer, tangent.array);
  311. }
  312. if ( dispose ) {
  313. for ( var i in geometry.attributes ) {
  314. delete geometry.attributes[ i ].array;
  315. }
  316. }
  317. };
  318. // Buffer rendering
  319. this.renderBufferImmediate = function ( object, program, material ) {
  320. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = renderer.createBuffer();
  321. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = renderer.createBuffer();
  322. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = renderer.createBuffer();
  323. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = renderer.createBuffer();
  324. if ( object.hasPositions ) {
  325. renderer.setDynamicArrayBuffer( object.__webglVertexBuffer, object.positionArray);
  326. renderer.setFloatAttribute(program.attributes.position, object.__webglVertexBuffer, 3, 0);
  327. }
  328. if ( object.hasNormals ) {
  329. if ( material.shading === THREE.FlatShading ) {
  330. var nx, ny, nz,
  331. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  332. normalArray,
  333. i, il = object.count * 3;
  334. for( i = 0; i < il; i += 9 ) {
  335. normalArray = object.normalArray;
  336. nax = normalArray[ i ];
  337. nay = normalArray[ i + 1 ];
  338. naz = normalArray[ i + 2 ];
  339. nbx = normalArray[ i + 3 ];
  340. nby = normalArray[ i + 4 ];
  341. nbz = normalArray[ i + 5 ];
  342. ncx = normalArray[ i + 6 ];
  343. ncy = normalArray[ i + 7 ];
  344. ncz = normalArray[ i + 8 ];
  345. nx = ( nax + nbx + ncx ) / 3;
  346. ny = ( nay + nby + ncy ) / 3;
  347. nz = ( naz + nbz + ncz ) / 3;
  348. normalArray[ i ] = nx;
  349. normalArray[ i + 1 ] = ny;
  350. normalArray[ i + 2 ] = nz;
  351. normalArray[ i + 3 ] = nx;
  352. normalArray[ i + 4 ] = ny;
  353. normalArray[ i + 5 ] = nz;
  354. normalArray[ i + 6 ] = nx;
  355. normalArray[ i + 7 ] = ny;
  356. normalArray[ i + 8 ] = nz;
  357. }
  358. }
  359. renderer.setDynamicArrayBuffer( object.__webglNormalBuffer, object.normalArray);
  360. renderer.setFloatAttribute(program.attributes.normal, object.__webglNormalBuffer, 3, 0);
  361. }
  362. if ( object.hasUvs && material.map ) {
  363. renderer.setDynamicArrayBuffer( object.__webglUvBuffer, object.uvArray);
  364. renderer.setFloatAttribute(program.attributes.uv, object.__webglUvBuffer, 2, 0);
  365. }
  366. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  367. renderer.setDynamicArrayBuffer( object.__webglColorBuffer, object.colorArray);
  368. renderer.setFloatAttribute(program.attributes.color, object.__webglColorBuffer, 3, 0);
  369. }
  370. renderer.drawTriangles(object.count );
  371. object.count = 0;
  372. };
  373. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  374. if ( material.visible === false ) return;
  375. var program, attributes, linewidth, primitives, a, attribute;
  376. program = setProgram( camera, lights, fog, material, object );
  377. attributes = program.attributes;
  378. var updateBuffers = false,
  379. wireframeBit = material.wireframe ? 1 : 0,
  380. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  381. if ( geometryHash !== _currentGeometryGroupHash ) {
  382. _currentGeometryGroupHash = geometryHash;
  383. updateBuffers = true;
  384. }
  385. if ( updateBuffers ) {
  386. renderer.disableAttributes();
  387. }
  388. // render mesh
  389. if ( object instanceof THREE.Mesh ) {
  390. var index = geometry.attributes[ "index" ];
  391. // indexed triangles
  392. if ( index ) {
  393. var offsets = geometry.offsets;
  394. // if there is more than 1 chunk
  395. // must set attribute pointers to use new offsets for each chunk
  396. // even if geometry and materials didn't change
  397. if ( offsets.length > 1 ) updateBuffers = true;
  398. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  399. var startIndex = offsets[ i ].index;
  400. if ( updateBuffers ) {
  401. // vertices
  402. var position = geometry.attributes[ "position" ];
  403. var positionSize = position.itemSize;
  404. renderer.setFloatAttribute(attributes.position , position.buffer, positionSize, startIndex * positionSize * 4);
  405. // normals
  406. var normal = geometry.attributes[ "normal" ];
  407. if ( attributes.normal >= 0 && normal ) {
  408. var normalSize = normal.itemSize;
  409. renderer.setFloatAttribute(attributes.normal , normal.buffer, normalSize, startIndex * normalSize * 4);
  410. }
  411. // uvs
  412. var uv = geometry.attributes[ "uv" ];
  413. if ( attributes.uv >= 0 && uv ) {
  414. var uvSize = uv.itemSize;
  415. renderer.setFloatAttribute(attributes.uv , uv.buffer, uvSize, startIndex * uvSize * 4);
  416. }
  417. // colors
  418. var color = geometry.attributes[ "color" ];
  419. if ( attributes.color >= 0 && color ) {
  420. var colorSize = color.itemSize;
  421. renderer.setFloatAttribute(attributes.color , color.buffer, colorSize, startIndex * colorSize * 4);
  422. }
  423. // tangents
  424. var tangent = geometry.attributes[ "tangent" ];
  425. if ( attributes.tangent >= 0 && tangent ) {
  426. var tangentSize = tangent.itemSize;
  427. renderer.setFloatAttribute(attributes.tangent , tangent.buffer, tangentSize, startIndex * tangentSize * 4);
  428. }
  429. }
  430. // render indexed triangles
  431. renderer.drawTriangleElements(index.buffer, offsets[ i ].count, offsets[ i ].start * 2);
  432. _this.info.render.calls ++;
  433. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  434. _this.info.render.faces += offsets[ i ].count / 3;
  435. }
  436. // non-indexed triangles
  437. } else {
  438. if ( updateBuffers ) {
  439. // vertices
  440. var position = geometry.attributes[ "position" ];
  441. var positionSize = position.itemSize;
  442. renderer.setFloatAttribute(attributes.position , position.buffer, positionSize, 0);
  443. // normals
  444. var normal = geometry.attributes[ "normal" ];
  445. if ( attributes.normal >= 0 && normal ) {
  446. var normalSize = normal.itemSize;
  447. renderer.setFloatAttribute(attributes.normal , normal.buffer, normalSize, 0);
  448. }
  449. // uvs
  450. var uv = geometry.attributes[ "uv" ];
  451. if ( attributes.uv >= 0 && uv ) {
  452. var uvSize = uv.itemSize;
  453. renderer.setFloatAttribute(attributes.uv , uv.buffer, uvSize, 0);
  454. }
  455. // colors
  456. var color = geometry.attributes[ "color" ];
  457. if ( attributes.color >= 0 && color ) {
  458. var colorSize = color.itemSize;
  459. renderer.setFloatAttribute(attributes.color , color.buffer, colorSize, 0);
  460. }
  461. // tangents
  462. var tangent = geometry.attributes[ "tangent" ];
  463. if ( attributes.tangent >= 0 && tangent ) {
  464. var tangentSize = tangent.itemSize;
  465. renderer.setFloatAttribute(attributes.tangent , tangent.buffer, tangentSize, 0);
  466. }
  467. }
  468. // render non-indexed triangles
  469. renderer.drawTriangles( position.numItems / 3)
  470. _this.info.render.calls ++;
  471. _this.info.render.vertices += position.numItems / 3;
  472. _this.info.render.faces += position.numItems / 3 / 3;
  473. }
  474. // render particles
  475. } else if ( object instanceof THREE.ParticleSystem ) {
  476. if ( updateBuffers ) {
  477. // vertices
  478. var position = geometry.attributes[ "position" ];
  479. var positionSize = position.itemSize;
  480. renderer.setFloatAttribute(attributes.position , position.buffer, positionSize, 0);
  481. // colors
  482. var color = geometry.attributes[ "color" ];
  483. if ( attributes.color >= 0 && color ) {
  484. var colorSize = color.itemSize;
  485. renderer.setFloatAttribute(attributes.color , color.buffer, colorSize, 0);
  486. }
  487. // render particles
  488. renderer.drawPoints(position.numItems / 3);
  489. _this.info.render.calls ++;
  490. _this.info.render.points += position.numItems / 3;
  491. }
  492. } else if ( object instanceof THREE.Line ) {
  493. if ( updateBuffers ) {
  494. // vertices
  495. var position = geometry.attributes[ "position" ];
  496. var positionSize = position.itemSize;
  497. renderer.setFloatAttribute(attributes.position , position.buffer, positionSize, 0);
  498. // colors
  499. var color = geometry.attributes[ "color" ];
  500. if ( attributes.color >= 0 && color ) {
  501. var colorSize = color.itemSize;
  502. renderer.setFloatAttribute(attributes.color , color.buffer, colorSize, 0);
  503. }
  504. // render lines
  505. renderer.drawLineStrip(position.numItems / 3);
  506. _this.info.render.calls ++;
  507. _this.info.render.points += position.numItems;
  508. }
  509. }
  510. };
  511. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  512. if ( material.visible === false ) return;
  513. var program, attributes, linewidth, primitives, a, attribute, i, il;
  514. program = setProgram( camera, lights, fog, material, object );
  515. attributes = program.attributes;
  516. var updateBuffers = false,
  517. wireframeBit = material.wireframe ? 1 : 0,
  518. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  519. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  520. _currentGeometryGroupHash = geometryGroupHash;
  521. updateBuffers = true;
  522. }
  523. if ( updateBuffers ) {
  524. renderer.disableAttributes();
  525. }
  526. // vertices
  527. if ( !material.morphTargets && attributes.position >= 0 ) {
  528. if ( updateBuffers ) {
  529. renderer.setFloatAttribute(attributes.position , geometryGroup.__webglVertexBuffer, 3, 0);
  530. }
  531. } else {
  532. if ( object.morphTargetBase ) {
  533. setupMorphTargets( material, geometryGroup, object );
  534. }
  535. }
  536. if ( updateBuffers ) {
  537. // custom attributes
  538. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  539. if ( geometryGroup.__webglCustomAttributesList ) {
  540. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  541. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  542. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  543. renderer.setFloatAttribute(attributes[ attribute.buffer.belongsToAttribute ] , attribute.buffer, attribute.size, 0);
  544. }
  545. }
  546. }
  547. // colors
  548. if ( attributes.color >= 0 ) {
  549. renderer.setFloatAttribute(attributes.color , geometryGroup.__webglColorBuffer,3, 0);
  550. }
  551. // normals
  552. if ( attributes.normal >= 0 ) {
  553. renderer.setFloatAttribute(attributes.normal, geometryGroup.__webglNormalBuffer, 3, 0);
  554. }
  555. // tangents
  556. if ( attributes.tangent >= 0 ) {
  557. renderer.setFloatAttribute(attributes.tangent, geometryGroup.__webglTangentBuffer, 4, 0);
  558. }
  559. // uvs
  560. if ( attributes.uv >= 0 ) {
  561. renderer.setFloatAttribute(attributes.uv, geometryGroup.__webglUVBuffer, 2, 0);
  562. }
  563. if ( attributes.uv2 >= 0 ) {
  564. renderer.setFloatAttribute(attributes.uv2, geometryGroup.__webglUV2Buffer, 2, 0);
  565. }
  566. if ( material.skinning &&
  567. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  568. renderer.setFloatAttribute(attributes.skinIndex, geometryGroup.__webglSkinIndicesBuffer, 4, 0);
  569. renderer.setFloatAttribute(attributes.skinWeight, geometryGroup.__webglSkinWeightsBuffer, 4, 0);
  570. }
  571. // line distances
  572. if ( attributes.lineDistance >= 0 ) {
  573. renderer.setFloatAttribute(attributes.lineDistance, geometryGroup.__webglLineDistanceBuffer, 1, 0);
  574. }
  575. }
  576. // render mesh
  577. if ( object instanceof THREE.Mesh ) {
  578. // wireframe
  579. if ( material.wireframe ) {
  580. renderer.setLineWidth( material.wireframeLinewidth );
  581. renderer.drawLineElements(geometryGroup.__webglLineBuffer,geometryGroup.__webglLineCount,0);
  582. // triangles
  583. } else {
  584. renderer.drawTriangleElements( geometryGroup.__webglFaceBuffer, geometryGroup.__webglFaceCount, 0);
  585. }
  586. _this.info.render.calls ++;
  587. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  588. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  589. // render lines
  590. } else if ( object instanceof THREE.Line ) {
  591. renderer.setLineWidth( material.linewidth );
  592. if (object.type === THREE.LineStrip) {
  593. renderer.drawLineStrip(geometryGroup.__webglLineCount);
  594. } else {
  595. renderer.drawLines(geometryGroup.__webglLineCount);
  596. }
  597. _this.info.render.calls ++;
  598. // render particles
  599. } else if ( object instanceof THREE.ParticleSystem ) {
  600. renderer.drawPoints(geometryGroup.__webglParticleCount);
  601. _this.info.render.calls ++;
  602. _this.info.render.points += geometryGroup.__webglParticleCount;
  603. // render ribbon
  604. } else if ( object instanceof THREE.Ribbon ) {
  605. renderer.drawTriangleStrip(geometryGroup.__webglVertexCount);
  606. _this.info.render.calls ++;
  607. }
  608. };
  609. function setupMorphTargets ( material, geometryGroup, object ) {
  610. // set base
  611. var attributes = material.program.attributes;
  612. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  613. renderer.setFloatAttribute(attributes.position, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ], 3, 0);
  614. } else if ( attributes.position >= 0 ) {
  615. renderer.setFloatAttribute(attributes.position, geometryGroup.__webglVertexBuffer, 3, 0);
  616. }
  617. if ( object.morphTargetForcedOrder.length ) {
  618. // set forced order
  619. var m = 0;
  620. var order = object.morphTargetForcedOrder;
  621. var influences = object.morphTargetInfluences;
  622. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  623. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  624. renderer.setFloatAttribute(attributes[ "morphTarget" + m ], geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ], 3, 0);
  625. }
  626. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  627. renderer.setFloatAttribute(attributes[ "morphNormal" + m ], geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ], 3, 0);
  628. }
  629. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  630. m ++;
  631. }
  632. } else {
  633. // find the most influencing
  634. var influence, activeInfluenceIndices = [];
  635. var influences = object.morphTargetInfluences;
  636. var i, il = influences.length;
  637. for ( i = 0; i < il; i ++ ) {
  638. influence = influences[ i ];
  639. if ( influence > 0 ) {
  640. activeInfluenceIndices.push( [ influence, i ] );
  641. }
  642. }
  643. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  644. activeInfluenceIndices.sort( numericalSort );
  645. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  646. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  647. activeInfluenceIndices.sort( numericalSort );
  648. } else if ( activeInfluenceIndices.length === 0 ) {
  649. activeInfluenceIndices.push( [ 0, 0 ] );
  650. };
  651. var influenceIndex, m = 0;
  652. while ( m < material.numSupportedMorphTargets ) {
  653. if ( activeInfluenceIndices[ m ] ) {
  654. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  655. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  656. renderer.setFloatAttribute(attributes[ "morphTarget" + m ], geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ], 3, 0);
  657. }
  658. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  659. renderer.setFloatAttribute(attributes[ "morphNormal" + m ], geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ], 3, 0);
  660. }
  661. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  662. } else {
  663. /*
  664. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  665. if ( material.morphNormals ) {
  666. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  667. }
  668. */
  669. object.__webglMorphTargetInfluences[ m ] = 0;
  670. }
  671. m ++;
  672. }
  673. }
  674. // load updated influences uniform
  675. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  676. renderer.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  677. }
  678. };
  679. // Sorting
  680. function painterSortStable ( a, b ) {
  681. if ( a.z !== b.z ) {
  682. return b.z - a.z;
  683. } else {
  684. return b.id - a.id;
  685. }
  686. };
  687. function numericalSort ( a, b ) {
  688. return b[ 0 ] - a[ 0 ];
  689. };
  690. // Rendering
  691. this.render = function ( scene, camera, renderTarget, forceClear ) {
  692. if ( camera instanceof THREE.Camera === false ) {
  693. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  694. return;
  695. }
  696. var i, il,
  697. webglObject, object,
  698. renderList,
  699. lights = scene.__lights,
  700. fog = scene.fog;
  701. // reset caching for this frame
  702. _currentMaterialId = -1;
  703. _lightsNeedUpdate = true;
  704. // update scene graph
  705. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  706. // update camera matrices and frustum
  707. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  708. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  709. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  710. _frustum.setFromMatrix( _projScreenMatrix );
  711. // update WebGL objects
  712. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  713. // custom render plugins (pre pass)
  714. renderPlugins( this.renderPluginsPre, scene, camera );
  715. //
  716. _this.info.render.calls = 0;
  717. _this.info.render.vertices = 0;
  718. _this.info.render.faces = 0;
  719. _this.info.render.points = 0;
  720. renderer.setRenderTarget( renderTarget );
  721. if ( this.autoClear || forceClear ) {
  722. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  723. }
  724. // set matrices for regular objects (frustum culled)
  725. renderList = scene.__webglObjects;
  726. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  727. webglObject = renderList[ i ];
  728. object = webglObject.object;
  729. webglObject.render = false;
  730. if ( object.visible ) {
  731. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  732. setupMatrices( object, camera );
  733. unrollBufferMaterial( webglObject );
  734. webglObject.render = true;
  735. if ( this.sortObjects === true ) {
  736. if ( object.renderDepth !== null ) {
  737. webglObject.z = object.renderDepth;
  738. } else {
  739. _vector3.copy( object.matrixWorld.getPosition() );
  740. _vector3.projectPoint(_projScreenMatrix);
  741. webglObject.z = _vector3.z;
  742. }
  743. webglObject.id = object.id;
  744. }
  745. }
  746. }
  747. }
  748. if ( this.sortObjects ) {
  749. renderList.sort( painterSortStable );
  750. }
  751. // set matrices for immediate objects
  752. renderList = scene.__webglObjectsImmediate;
  753. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  754. webglObject = renderList[ i ];
  755. object = webglObject.object;
  756. if ( object.visible ) {
  757. setupMatrices( object, camera );
  758. unrollImmediateBufferMaterial( webglObject );
  759. }
  760. }
  761. if ( scene.overrideMaterial ) {
  762. var material = scene.overrideMaterial;
  763. renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  764. renderer.setDepthTest( material.depthTest );
  765. renderer.setDepthWrite( material.depthWrite );
  766. renderer.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  767. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  768. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  769. } else {
  770. var material = null;
  771. // opaque pass (front-to-back order)
  772. renderer.setBlending( THREE.NoBlending );
  773. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  774. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  775. // transparent pass (back-to-front order)
  776. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  777. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  778. }
  779. // custom render plugins (post pass)
  780. renderPlugins( this.renderPluginsPost, scene, camera );
  781. // Generate mipmap if we're using any kind of mipmap filtering
  782. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  783. renderer.updateRenderTargetMipmap( renderTarget );
  784. }
  785. // Ensure depth buffer writing is enabled so it can be cleared on next render
  786. renderer.setDepthTest( true );
  787. renderer.setDepthWrite( true );
  788. // _gl.finish();
  789. };
  790. function renderPlugins( plugins, scene, camera ) {
  791. if ( ! plugins.length ) return;
  792. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  793. // reset state for plugin (to start from clean slate)
  794. _currentProgram = null;
  795. _currentCamera = null;
  796. _currentGeometryGroupHash = -1;
  797. _currentMaterialId = -1;
  798. _lightsNeedUpdate = true;
  799. renderer.resetState();
  800. plugins[ i ].render( scene, camera, renderer.getCurrentWidth(), renderer.getCurrentWidth() );
  801. // reset state after plugin (anything could have changed)
  802. _currentProgram = null;
  803. _currentCamera = null;
  804. _currentGeometryGroupHash = -1;
  805. _currentMaterialId = -1;
  806. _lightsNeedUpdate = true;
  807. renderer.resetState();
  808. }
  809. };
  810. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  811. var webglObject, object, buffer, material, start, end, delta;
  812. if ( reverse ) {
  813. start = renderList.length - 1;
  814. end = -1;
  815. delta = -1;
  816. } else {
  817. start = 0;
  818. end = renderList.length;
  819. delta = 1;
  820. }
  821. for ( var i = start; i !== end; i += delta ) {
  822. webglObject = renderList[ i ];
  823. if ( webglObject.render ) {
  824. object = webglObject.object;
  825. buffer = webglObject.buffer;
  826. if ( overrideMaterial ) {
  827. material = overrideMaterial;
  828. } else {
  829. material = webglObject[ materialType ];
  830. if ( ! material ) continue;
  831. if ( useBlending ) renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  832. renderer.setDepthTest( material.depthTest );
  833. renderer.setDepthWrite( material.depthWrite );
  834. renderer.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  835. }
  836. renderer.setMaterialFaces( material );
  837. if ( buffer instanceof THREE.BufferGeometry ) {
  838. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  839. } else {
  840. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  841. }
  842. }
  843. }
  844. };
  845. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  846. var webglObject, object, material, program;
  847. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  848. webglObject = renderList[ i ];
  849. object = webglObject.object;
  850. if ( object.visible ) {
  851. if ( overrideMaterial ) {
  852. material = overrideMaterial;
  853. } else {
  854. material = webglObject[ materialType ];
  855. if ( ! material ) continue;
  856. if ( useBlending ) renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  857. renderer.setDepthTest( material.depthTest );
  858. renderer.setDepthWrite( material.depthWrite );
  859. renderer.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  860. }
  861. _this.renderImmediateObject( camera, lights, fog, material, object );
  862. }
  863. }
  864. };
  865. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  866. var program = setProgram( camera, lights, fog, material, object );
  867. _currentGeometryGroupHash = -1;
  868. renderer.setMaterialFaces( material );
  869. if ( object.immediateRenderCallback ) {
  870. object.immediateRenderCallback( program, renderer.getContext(), _frustum );
  871. } else {
  872. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  873. }
  874. };
  875. function unrollImmediateBufferMaterial ( globject ) {
  876. var object = globject.object,
  877. material = object.material;
  878. if ( material.transparent ) {
  879. globject.transparent = material;
  880. globject.opaque = null;
  881. } else {
  882. globject.opaque = material;
  883. globject.transparent = null;
  884. }
  885. };
  886. function unrollBufferMaterial ( globject ) {
  887. var object = globject.object,
  888. buffer = globject.buffer,
  889. material, materialIndex, meshMaterial;
  890. meshMaterial = object.material;
  891. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  892. materialIndex = buffer.materialIndex;
  893. material = meshMaterial.materials[ materialIndex ];
  894. if ( material.transparent ) {
  895. globject.transparent = material;
  896. globject.opaque = null;
  897. } else {
  898. globject.opaque = material;
  899. globject.transparent = null;
  900. }
  901. } else {
  902. material = meshMaterial;
  903. if ( material ) {
  904. if ( material.transparent ) {
  905. globject.transparent = material;
  906. globject.opaque = null;
  907. } else {
  908. globject.opaque = material;
  909. globject.transparent = null;
  910. }
  911. }
  912. }
  913. };
  914. // Geometry splitting
  915. function sortFacesByMaterial ( geometry, material ) {
  916. var f, fl, face, materialIndex, vertices,
  917. groupHash, hash_map = {};
  918. var numMorphTargets = geometry.morphTargets.length;
  919. var numMorphNormals = geometry.morphNormals.length;
  920. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  921. geometry.geometryGroups = {};
  922. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  923. face = geometry.faces[ f ];
  924. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  925. if ( hash_map[ materialIndex ] === undefined ) {
  926. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  927. }
  928. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  929. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  930. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  931. }
  932. vertices = face instanceof THREE.Face3 ? 3 : 4;
  933. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  934. hash_map[ materialIndex ].counter += 1;
  935. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  936. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  937. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  938. }
  939. }
  940. if ( face instanceof THREE.Face3 ) {
  941. geometry.geometryGroups[ groupHash ].faces3.push( f );
  942. } else {
  943. geometry.geometryGroups[ groupHash ].faces4.push( f );
  944. }
  945. geometry.geometryGroups[ groupHash ].vertices += vertices;
  946. }
  947. geometry.geometryGroupsList = [];
  948. for ( var g in geometry.geometryGroups ) {
  949. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  950. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  951. }
  952. };
  953. // Objects refresh
  954. this.initWebGLObjects = function ( scene ) {
  955. if ( !scene.__webglObjects ) {
  956. scene.__webglObjects = [];
  957. scene.__webglObjectsImmediate = [];
  958. scene.__webglSprites = [];
  959. scene.__webglFlares = [];
  960. }
  961. while ( scene.__objectsAdded.length ) {
  962. addObject( scene.__objectsAdded[ 0 ], scene );
  963. scene.__objectsAdded.splice( 0, 1 );
  964. }
  965. while ( scene.__objectsRemoved.length ) {
  966. removeObject( scene.__objectsRemoved[ 0 ], scene );
  967. scene.__objectsRemoved.splice( 0, 1 );
  968. }
  969. // update must be called after objects adding / removal
  970. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  971. updateObject( scene.__webglObjects[ o ].object );
  972. }
  973. };
  974. // Objects adding
  975. function addObject ( object, scene ) {
  976. var g, geometry, material, geometryGroup;
  977. if ( ! object.__webglInit ) {
  978. object.__webglInit = true;
  979. object._modelViewMatrix = new THREE.Matrix4();
  980. object._normalMatrix = new THREE.Matrix3();
  981. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  982. object.geometry.__webglInit = true;
  983. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  984. }
  985. if ( object instanceof THREE.Mesh ) {
  986. geometry = object.geometry;
  987. material = object.material;
  988. if ( geometry instanceof THREE.Geometry ) {
  989. if ( geometry.geometryGroups === undefined ) {
  990. sortFacesByMaterial( geometry, material );
  991. }
  992. // create separate VBOs per geometry chunk
  993. for ( g in geometry.geometryGroups ) {
  994. geometryGroup = geometry.geometryGroups[ g ];
  995. // initialise VBO on the first access
  996. if ( ! geometryGroup.__webglVertexBuffer ) {
  997. meshRenderer.createBuffers( geometryGroup );
  998. meshRenderer.initBuffers( geometryGroup, object );
  999. geometry.verticesNeedUpdate = true;
  1000. geometry.morphTargetsNeedUpdate = true;
  1001. geometry.elementsNeedUpdate = true;
  1002. geometry.uvsNeedUpdate = true;
  1003. geometry.normalsNeedUpdate = true;
  1004. geometry.tangentsNeedUpdate = true;
  1005. geometry.colorsNeedUpdate = true;
  1006. }
  1007. }
  1008. } else if ( geometry instanceof THREE.BufferGeometry ) {
  1009. initDirectBuffers( geometry );
  1010. }
  1011. } else if ( object instanceof THREE.Ribbon ) {
  1012. geometry = object.geometry;
  1013. if ( ! geometry.__webglVertexBuffer ) {
  1014. ribbonRenderer.createBuffers( geometry );
  1015. ribbonRenderer.initBuffers( geometry, object );
  1016. geometry.verticesNeedUpdate = true;
  1017. geometry.colorsNeedUpdate = true;
  1018. geometry.normalsNeedUpdate = true;
  1019. }
  1020. } else if ( object instanceof THREE.Line ) {
  1021. geometry = object.geometry;
  1022. if ( ! geometry.__webglVertexBuffer ) {
  1023. if ( geometry instanceof THREE.Geometry ) {
  1024. lineRenderer.createBuffers( geometry );
  1025. lineRenderer.initBuffers( geometry, object );
  1026. geometry.verticesNeedUpdate = true;
  1027. geometry.colorsNeedUpdate = true;
  1028. geometry.lineDistancesNeedUpdate = true;
  1029. } else if ( geometry instanceof THREE.BufferGeometry ) {
  1030. initDirectBuffers( geometry );
  1031. }
  1032. }
  1033. } else if ( object instanceof THREE.ParticleSystem ) {
  1034. geometry = object.geometry;
  1035. if ( ! geometry.__webglVertexBuffer ) {
  1036. if ( geometry instanceof THREE.Geometry ) {
  1037. particleRenderer.createBuffers( geometry );
  1038. particleRenderer.initBuffers( geometry, object );
  1039. geometry.verticesNeedUpdate = true;
  1040. geometry.colorsNeedUpdate = true;
  1041. } else if ( geometry instanceof THREE.BufferGeometry ) {
  1042. initDirectBuffers( geometry );
  1043. }
  1044. }
  1045. }
  1046. }
  1047. if ( ! object.__webglActive ) {
  1048. if ( object instanceof THREE.Mesh ) {
  1049. geometry = object.geometry;
  1050. if ( geometry instanceof THREE.BufferGeometry ) {
  1051. addBuffer( scene.__webglObjects, geometry, object );
  1052. } else if ( geometry instanceof THREE.Geometry ) {
  1053. for ( g in geometry.geometryGroups ) {
  1054. geometryGroup = geometry.geometryGroups[ g ];
  1055. addBuffer( scene.__webglObjects, geometryGroup, object );
  1056. }
  1057. }
  1058. } else if ( object instanceof THREE.Ribbon ||
  1059. object instanceof THREE.Line ||
  1060. object instanceof THREE.ParticleSystem ) {
  1061. geometry = object.geometry;
  1062. addBuffer( scene.__webglObjects, geometry, object );
  1063. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  1064. addBufferImmediate( scene.__webglObjectsImmediate, object );
  1065. } else if ( object instanceof THREE.Sprite ) {
  1066. scene.__webglSprites.push( object );
  1067. } else if ( object instanceof THREE.LensFlare ) {
  1068. scene.__webglFlares.push( object );
  1069. }
  1070. object.__webglActive = true;
  1071. }
  1072. };
  1073. function addBuffer ( objlist, buffer, object ) {
  1074. objlist.push(
  1075. {
  1076. buffer: buffer,
  1077. object: object,
  1078. opaque: null,
  1079. transparent: null
  1080. }
  1081. );
  1082. };
  1083. function addBufferImmediate ( objlist, object ) {
  1084. objlist.push(
  1085. {
  1086. object: object,
  1087. opaque: null,
  1088. transparent: null
  1089. }
  1090. );
  1091. };
  1092. // Objects updates
  1093. function updateObject ( object ) {
  1094. var geometry = object.geometry,
  1095. geometryGroup, customAttributesDirty, material;
  1096. if ( object instanceof THREE.Mesh ) {
  1097. if ( geometry instanceof THREE.BufferGeometry ) {
  1098. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  1099. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  1100. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  1101. setDirectBuffers( geometry, !geometry.dynamic );
  1102. }
  1103. geometry.verticesNeedUpdate = false;
  1104. geometry.elementsNeedUpdate = false;
  1105. geometry.uvsNeedUpdate = false;
  1106. geometry.normalsNeedUpdate = false;
  1107. geometry.colorsNeedUpdate = false;
  1108. geometry.tangentsNeedUpdate = false;
  1109. } else {
  1110. // check all geometry groups
  1111. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  1112. geometryGroup = geometry.geometryGroupsList[ i ];
  1113. material = getBufferMaterial( object, geometryGroup );
  1114. if ( geometry.buffersNeedUpdate ) {
  1115. meshRenderer.initBuffers( geometryGroup, object );
  1116. }
  1117. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  1118. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  1119. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  1120. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  1121. meshRenderer.setBuffers( geometryGroup, object, !geometry.dynamic, material );
  1122. }
  1123. }
  1124. geometry.verticesNeedUpdate = false;
  1125. geometry.morphTargetsNeedUpdate = false;
  1126. geometry.elementsNeedUpdate = false;
  1127. geometry.uvsNeedUpdate = false;
  1128. geometry.normalsNeedUpdate = false;
  1129. geometry.colorsNeedUpdate = false;
  1130. geometry.tangentsNeedUpdate = false;
  1131. geometry.buffersNeedUpdate = false;
  1132. material.attributes && clearCustomAttributes( material );
  1133. }
  1134. } else if ( object instanceof THREE.Ribbon ) {
  1135. material = getBufferMaterial( object, geometry );
  1136. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  1137. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  1138. ribbonRenderer.setBuffers( geometry);
  1139. }
  1140. geometry.verticesNeedUpdate = false;
  1141. geometry.colorsNeedUpdate = false;
  1142. geometry.normalsNeedUpdate = false;
  1143. material.attributes && clearCustomAttributes( material );
  1144. } else if ( object instanceof THREE.Line ) {
  1145. if ( geometry instanceof THREE.BufferGeometry ) {
  1146. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  1147. setDirectBuffers( geometry, !geometry.dynamic );
  1148. }
  1149. geometry.verticesNeedUpdate = false;
  1150. geometry.colorsNeedUpdate = false;
  1151. } else {
  1152. material = getBufferMaterial( object, geometry );
  1153. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  1154. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  1155. lineRenderer.setBuffers( geometry);
  1156. }
  1157. geometry.verticesNeedUpdate = false;
  1158. geometry.colorsNeedUpdate = false;
  1159. geometry.lineDistancesNeedUpdate = false;
  1160. material.attributes && clearCustomAttributes( material );
  1161. }
  1162. } else if ( object instanceof THREE.ParticleSystem ) {
  1163. if ( geometry instanceof THREE.BufferGeometry ) {
  1164. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  1165. setDirectBuffers( geometry, !geometry.dynamic );
  1166. }
  1167. geometry.verticesNeedUpdate = false;
  1168. geometry.colorsNeedUpdate = false;
  1169. } else {
  1170. material = getBufferMaterial( object, geometry );
  1171. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  1172. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  1173. particleRenderer.setBuffers( geometry, object, _projScreenMatrix);
  1174. }
  1175. geometry.verticesNeedUpdate = false;
  1176. geometry.colorsNeedUpdate = false;
  1177. material.attributes && clearCustomAttributes( material );
  1178. }
  1179. }
  1180. };
  1181. // Objects updates - custom attributes check
  1182. function areCustomAttributesDirty ( material ) {
  1183. for ( var a in material.attributes ) {
  1184. if ( material.attributes[ a ].needsUpdate ) return true;
  1185. }
  1186. return false;
  1187. };
  1188. function clearCustomAttributes ( material ) {
  1189. for ( var a in material.attributes ) {
  1190. material.attributes[ a ].needsUpdate = false;
  1191. }
  1192. };
  1193. // Objects removal
  1194. function removeObject ( object, scene ) {
  1195. if ( object instanceof THREE.Mesh ||
  1196. object instanceof THREE.ParticleSystem ||
  1197. object instanceof THREE.Ribbon ||
  1198. object instanceof THREE.Line ) {
  1199. removeInstances( scene.__webglObjects, object );
  1200. } else if ( object instanceof THREE.Sprite ) {
  1201. removeInstancesDirect( scene.__webglSprites, object );
  1202. } else if ( object instanceof THREE.LensFlare ) {
  1203. removeInstancesDirect( scene.__webglFlares, object );
  1204. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  1205. removeInstances( scene.__webglObjectsImmediate, object );
  1206. }
  1207. object.__webglActive = false;
  1208. };
  1209. function removeInstances ( objlist, object ) {
  1210. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  1211. if ( objlist[ o ].object === object ) {
  1212. objlist.splice( o, 1 );
  1213. }
  1214. }
  1215. };
  1216. function removeInstancesDirect ( objlist, object ) {
  1217. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  1218. if ( objlist[ o ] === object ) {
  1219. objlist.splice( o, 1 );
  1220. }
  1221. }
  1222. };
  1223. // Materials
  1224. this.initMaterial = function ( material, lights, fog, object ) {
  1225. material.addEventListener( 'dispose', onMaterialDispose );
  1226. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  1227. if ( material instanceof THREE.MeshDepthMaterial ) {
  1228. shaderID = 'depth';
  1229. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  1230. shaderID = 'normal';
  1231. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  1232. shaderID = 'basic';
  1233. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  1234. shaderID = 'lambert';
  1235. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  1236. shaderID = 'phong';
  1237. } else if ( material instanceof THREE.LineBasicMaterial ) {
  1238. shaderID = 'basic';
  1239. } else if ( material instanceof THREE.LineDashedMaterial ) {
  1240. shaderID = 'dashed';
  1241. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  1242. shaderID = 'particle_basic';
  1243. }
  1244. if ( shaderID ) {
  1245. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  1246. }
  1247. // heuristics to create shader parameters according to lights in the scene
  1248. // (not to blow over maxLights budget)
  1249. maxLightCount = allocateLights( lights );
  1250. maxShadows = allocateShadows( lights );
  1251. maxBones = allocateBones( object );
  1252. parameters = {
  1253. map: !!material.map,
  1254. envMap: !!material.envMap,
  1255. lightMap: !!material.lightMap,
  1256. bumpMap: !!material.bumpMap,
  1257. normalMap: !!material.normalMap,
  1258. specularMap: !!material.specularMap,
  1259. vertexColors: material.vertexColors,
  1260. fog: fog,
  1261. useFog: material.fog,
  1262. fogExp: fog instanceof THREE.FogExp2,
  1263. sizeAttenuation: material.sizeAttenuation,
  1264. skinning: material.skinning,
  1265. maxBones: maxBones,
  1266. useVertexTexture: renderer.supportsBoneTextures && object && object.useVertexTexture,
  1267. boneTextureWidth: object && object.boneTextureWidth,
  1268. boneTextureHeight: object && object.boneTextureHeight,
  1269. morphTargets: material.morphTargets,
  1270. morphNormals: material.morphNormals,
  1271. maxMorphTargets: this.maxMorphTargets,
  1272. maxMorphNormals: this.maxMorphNormals,
  1273. maxDirLights: maxLightCount.directional,
  1274. maxPointLights: maxLightCount.point,
  1275. maxSpotLights: maxLightCount.spot,
  1276. maxHemiLights: maxLightCount.hemi,
  1277. maxShadows: maxShadows,
  1278. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  1279. shadowMapType: this.shadowMapType,
  1280. shadowMapDebug: this.shadowMapDebug,
  1281. shadowMapCascade: this.shadowMapCascade,
  1282. alphaTest: material.alphaTest,
  1283. metal: material.metal,
  1284. perPixel: material.perPixel,
  1285. wrapAround: material.wrapAround,
  1286. doubleSided: material.side === THREE.DoubleSide,
  1287. flipSided: material.side === THREE.BackSide,
  1288. gammaInput : this.gammaInput,
  1289. gammaOutput : this.gammaOutput ,
  1290. physicallyBasedShading : this.physicallyBasedShading
  1291. };
  1292. material.program = shaderBuilder.buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  1293. var attributes = material.program.attributes;
  1294. if ( material.morphTargets ) {
  1295. material.numSupportedMorphTargets = 0;
  1296. var id, base = "morphTarget";
  1297. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  1298. id = base + i;
  1299. if ( attributes[ id ] >= 0 ) {
  1300. material.numSupportedMorphTargets ++;
  1301. }
  1302. }
  1303. }
  1304. if ( material.morphNormals ) {
  1305. material.numSupportedMorphNormals = 0;
  1306. var id, base = "morphNormal";
  1307. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  1308. id = base + i;
  1309. if ( attributes[ id ] >= 0 ) {
  1310. material.numSupportedMorphNormals ++;
  1311. }
  1312. }
  1313. }
  1314. material.uniformsList = [];
  1315. for ( u in material.uniforms ) {
  1316. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  1317. }
  1318. };
  1319. function setMaterialShaders( material, shaders ) {
  1320. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  1321. material.vertexShader = shaders.vertexShader;
  1322. material.fragmentShader = shaders.fragmentShader;
  1323. };
  1324. function setProgram( camera, lights, fog, material, object ) {
  1325. _usedTextureUnits = 0;
  1326. if ( material.needsUpdate ) {
  1327. if ( material.program ) deallocateMaterial( material );
  1328. _this.initMaterial( material, lights, fog, object );
  1329. material.needsUpdate = false;
  1330. }
  1331. if ( material.morphTargets ) {
  1332. if ( ! object.__webglMorphTargetInfluences ) {
  1333. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  1334. }
  1335. }
  1336. var refreshMaterial = false;
  1337. var program = material.program,
  1338. p_uniforms = program.uniforms,
  1339. m_uniforms = material.uniforms;
  1340. if ( program !== _currentProgram ) {
  1341. renderer.useProgram( program );
  1342. _currentProgram = program;
  1343. refreshMaterial = true;
  1344. }
  1345. if ( material.id !== _currentMaterialId ) {
  1346. _currentMaterialId = material.id;
  1347. refreshMaterial = true;
  1348. }
  1349. if ( refreshMaterial || camera !== _currentCamera ) {
  1350. renderer.uniformMatrix4fv( p_uniforms.projectionMatrix, camera.projectionMatrix.elements );
  1351. if ( camera !== _currentCamera ) _currentCamera = camera;
  1352. }
  1353. // skinning uniforms must be set even if material didn't change
  1354. // auto-setting of texture unit for bone texture must go before other textures
  1355. // not sure why, but otherwise weird things happen
  1356. if ( material.skinning ) {
  1357. if ( renderer.supportsBoneTextures && object.useVertexTexture ) {
  1358. if ( p_uniforms.boneTexture !== null ) {
  1359. var textureUnit = getTextureUnit();
  1360. renderer.uniform1i( p_uniforms.boneTexture, textureUnit );
  1361. renderer.setTexture( object.boneTexture, textureUnit );
  1362. }
  1363. } else {
  1364. if ( p_uniforms.boneGlobalMatrices !== null ) {
  1365. renderer.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, object.boneMatrices );
  1366. }
  1367. }
  1368. }
  1369. if ( refreshMaterial ) {
  1370. // refresh uniforms common to several materials
  1371. if ( fog && material.fog ) {
  1372. refreshUniformsFog( m_uniforms, fog );
  1373. }
  1374. if ( material instanceof THREE.MeshPhongMaterial ||
  1375. material instanceof THREE.MeshLambertMaterial ||
  1376. material.lights ) {
  1377. if ( _lightsNeedUpdate ) {
  1378. setupLights( program, lights );
  1379. _lightsNeedUpdate = false;
  1380. }
  1381. refreshUniformsLights( m_uniforms, _lights );
  1382. }
  1383. if ( material instanceof THREE.MeshBasicMaterial ||
  1384. material instanceof THREE.MeshLambertMaterial ||
  1385. material instanceof THREE.MeshPhongMaterial ) {
  1386. refreshUniformsCommon( m_uniforms, material );
  1387. }
  1388. // refresh single material specific uniforms
  1389. if ( material instanceof THREE.LineBasicMaterial ) {
  1390. refreshUniformsLine( m_uniforms, material );
  1391. } else if ( material instanceof THREE.LineDashedMaterial ) {
  1392. refreshUniformsLine( m_uniforms, material );
  1393. refreshUniformsDash( m_uniforms, material );
  1394. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  1395. refreshUniformsParticle( m_uniforms, material );
  1396. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  1397. refreshUniformsPhong( m_uniforms, material );
  1398. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  1399. refreshUniformsLambert( m_uniforms, material );
  1400. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  1401. m_uniforms.mNear.value = camera.near;
  1402. m_uniforms.mFar.value = camera.far;
  1403. m_uniforms.opacity.value = material.opacity;
  1404. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  1405. m_uniforms.opacity.value = material.opacity;
  1406. }
  1407. if ( object.receiveShadow && ! material._shadowPass ) {
  1408. refreshUniformsShadow( m_uniforms, lights );
  1409. }
  1410. // load common uniforms
  1411. loadUniformsGeneric( program, material.uniformsList );
  1412. // load material specific uniforms
  1413. // (shader material also gets them for the sake of genericity)
  1414. if ( material instanceof THREE.ShaderMaterial ||
  1415. material instanceof THREE.MeshPhongMaterial ||
  1416. material.envMap ) {
  1417. if ( p_uniforms.cameraPosition !== null ) {
  1418. var position = camera.matrixWorld.getPosition();
  1419. renderer.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  1420. }
  1421. }
  1422. if ( material instanceof THREE.MeshPhongMaterial ||
  1423. material instanceof THREE.MeshLambertMaterial ||
  1424. material instanceof THREE.ShaderMaterial ||
  1425. material.skinning ) {
  1426. if ( p_uniforms.viewMatrix !== null ) {
  1427. renderer.uniformMatrix4fv( p_uniforms.viewMatrix, camera.matrixWorldInverse.elements );
  1428. }
  1429. }
  1430. }
  1431. loadUniformsMatrices( p_uniforms, object );
  1432. if ( p_uniforms.modelMatrix !== null ) {
  1433. renderer.uniformMatrix4fv( p_uniforms.modelMatrix, object.matrixWorld.elements );
  1434. }
  1435. return program;
  1436. };
  1437. // Uniforms (refresh uniforms objects)
  1438. function refreshUniformsCommon ( uniforms, material ) {
  1439. uniforms.opacity.value = material.opacity;
  1440. if ( _this.gammaInput ) {
  1441. uniforms.diffuse.value.copyGammaToLinear( material.color );
  1442. } else {
  1443. uniforms.diffuse.value = material.color;
  1444. }
  1445. uniforms.map.value = material.map;
  1446. uniforms.lightMap.value = material.lightMap;
  1447. uniforms.specularMap.value = material.specularMap;
  1448. if ( material.bumpMap ) {
  1449. uniforms.bumpMap.value = material.bumpMap;
  1450. uniforms.bumpScale.value = material.bumpScale;
  1451. }
  1452. if ( material.normalMap ) {
  1453. uniforms.normalMap.value = material.normalMap;
  1454. uniforms.normalScale.value.copy( material.normalScale );
  1455. }
  1456. // uv repeat and offset setting priorities
  1457. // 1. color map
  1458. // 2. specular map
  1459. // 3. normal map
  1460. // 4. bump map
  1461. var uvScaleMap;
  1462. if ( material.map ) {
  1463. uvScaleMap = material.map;
  1464. } else if ( material.specularMap ) {
  1465. uvScaleMap = material.specularMap;
  1466. } else if ( material.normalMap ) {
  1467. uvScaleMap = material.normalMap;
  1468. } else if ( material.bumpMap ) {
  1469. uvScaleMap = material.bumpMap;
  1470. }
  1471. if ( uvScaleMap !== undefined ) {
  1472. var offset = uvScaleMap.offset;
  1473. var repeat = uvScaleMap.repeat;
  1474. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1475. }
  1476. uniforms.envMap.value = material.envMap;
  1477. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  1478. if ( _this.gammaInput ) {
  1479. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  1480. uniforms.reflectivity.value = material.reflectivity;
  1481. } else {
  1482. uniforms.reflectivity.value = material.reflectivity;
  1483. }
  1484. uniforms.refractionRatio.value = material.refractionRatio;
  1485. uniforms.combine.value = material.combine;
  1486. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  1487. };
  1488. function refreshUniformsLine ( uniforms, material ) {
  1489. uniforms.diffuse.value = material.color;
  1490. uniforms.opacity.value = material.opacity;
  1491. };
  1492. function refreshUniformsDash ( uniforms, material ) {
  1493. uniforms.dashSize.value = material.dashSize;
  1494. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1495. uniforms.scale.value = material.scale;
  1496. };
  1497. function refreshUniformsParticle ( uniforms, material ) {
  1498. uniforms.psColor.value = material.color;
  1499. uniforms.opacity.value = material.opacity;
  1500. uniforms.size.value = material.size;
  1501. uniforms.scale.value = renderer.getDomElement().height / 2.0; // TODO: Cache this.
  1502. uniforms.map.value = material.map;
  1503. };
  1504. function refreshUniformsFog ( uniforms, fog ) {
  1505. uniforms.fogColor.value = fog.color;
  1506. if ( fog instanceof THREE.Fog ) {
  1507. uniforms.fogNear.value = fog.near;
  1508. uniforms.fogFar.value = fog.far;
  1509. } else if ( fog instanceof THREE.FogExp2 ) {
  1510. uniforms.fogDensity.value = fog.density;
  1511. }
  1512. };
  1513. function refreshUniformsPhong ( uniforms, material ) {
  1514. uniforms.shininess.value = material.shininess;
  1515. if ( _this.gammaInput ) {
  1516. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  1517. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  1518. uniforms.specular.value.copyGammaToLinear( material.specular );
  1519. } else {
  1520. uniforms.ambient.value = material.ambient;
  1521. uniforms.emissive.value = material.emissive;
  1522. uniforms.specular.value = material.specular;
  1523. }
  1524. if ( material.wrapAround ) {
  1525. uniforms.wrapRGB.value.copy( material.wrapRGB );
  1526. }
  1527. };
  1528. function refreshUniformsLambert ( uniforms, material ) {
  1529. if ( _this.gammaInput ) {
  1530. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  1531. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  1532. } else {
  1533. uniforms.ambient.value = material.ambient;
  1534. uniforms.emissive.value = material.emissive;
  1535. }
  1536. if ( material.wrapAround ) {
  1537. uniforms.wrapRGB.value.copy( material.wrapRGB );
  1538. }
  1539. };
  1540. function refreshUniformsLights ( uniforms, lights ) {
  1541. uniforms.ambientLightColor.value = lights.ambient;
  1542. uniforms.directionalLightColor.value = lights.directional.colors;
  1543. uniforms.directionalLightDirection.value = lights.directional.positions;
  1544. uniforms.pointLightColor.value = lights.point.colors;
  1545. uniforms.pointLightPosition.value = lights.point.positions;
  1546. uniforms.pointLightDistance.value = lights.point.distances;
  1547. uniforms.spotLightColor.value = lights.spot.colors;
  1548. uniforms.spotLightPosition.value = lights.spot.positions;
  1549. uniforms.spotLightDistance.value = lights.spot.distances;
  1550. uniforms.spotLightDirection.value = lights.spot.directions;
  1551. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  1552. uniforms.spotLightExponent.value = lights.spot.exponents;
  1553. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  1554. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  1555. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  1556. };
  1557. function refreshUniformsShadow ( uniforms, lights ) {
  1558. if ( uniforms.shadowMatrix ) {
  1559. var j = 0;
  1560. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  1561. var light = lights[ i ];
  1562. if ( ! light.castShadow ) continue;
  1563. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  1564. uniforms.shadowMap.value[ j ] = light.shadowMap;
  1565. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  1566. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  1567. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  1568. uniforms.shadowBias.value[ j ] = light.shadowBias;
  1569. j ++;
  1570. }
  1571. }
  1572. }
  1573. };
  1574. // Uniforms (load to GPU)
  1575. function loadUniformsMatrices ( uniforms, object ) {
  1576. renderer.uniformMatrix4fv( uniforms.modelViewMatrix, object._modelViewMatrix.elements );
  1577. if ( uniforms.normalMatrix ) {
  1578. renderer.uniformMatrix3fv( uniforms.normalMatrix, object._normalMatrix.elements );
  1579. }
  1580. };
  1581. function getTextureUnit() {
  1582. var textureUnit = _usedTextureUnits;
  1583. if ( textureUnit >= renderer.maxTextures ) {
  1584. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + renderer.maxTextures );
  1585. }
  1586. _usedTextureUnits += 1;
  1587. return textureUnit;
  1588. };
  1589. function loadUniformsGeneric ( program, uniforms ) {
  1590. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  1591. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  1592. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  1593. if ( !location ) continue;
  1594. uniform = uniforms[ j ][ 0 ];
  1595. type = uniform.type;
  1596. value = uniform.value;
  1597. if ( type === "i" ) { // single integer
  1598. renderer.uniform1i( location, value );
  1599. } else if ( type === "f" ) { // single float
  1600. renderer.uniform1f( location, value );
  1601. } else if ( type === "v2" ) { // single THREE.Vector2
  1602. renderer.uniform2f( location, value.x, value.y );
  1603. } else if ( type === "v3" ) { // single THREE.Vector3
  1604. renderer.uniform3f( location, value.x, value.y, value.z );
  1605. } else if ( type === "v4" ) { // single THREE.Vector4
  1606. renderer.uniform4f( location, value.x, value.y, value.z, value.w );
  1607. } else if ( type === "c" ) { // single THREE.Color
  1608. renderer.uniform3f( location, value.r, value.g, value.b );
  1609. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  1610. renderer.uniform1iv( location, value );
  1611. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  1612. renderer.uniform3iv( location, value );
  1613. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  1614. renderer.uniform1fv( location, value );
  1615. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  1616. renderer.uniform3fv( location, value );
  1617. } else if ( type === "v2v" ) { // array of THREE.Vector2
  1618. if ( uniform._array === undefined ) {
  1619. uniform._array = new Float32Array( 2 * value.length );
  1620. }
  1621. for ( i = 0, il = value.length; i < il; i ++ ) {
  1622. offset = i * 2;
  1623. uniform._array[ offset ] = value[ i ].x;
  1624. uniform._array[ offset + 1 ] = value[ i ].y;
  1625. }
  1626. renderer.uniform2fv( location, uniform._array );
  1627. } else if ( type === "v3v" ) { // array of THREE.Vector3
  1628. if ( uniform._array === undefined ) {
  1629. uniform._array = new Float32Array( 3 * value.length );
  1630. }
  1631. for ( i = 0, il = value.length; i < il; i ++ ) {
  1632. offset = i * 3;
  1633. uniform._array[ offset ] = value[ i ].x;
  1634. uniform._array[ offset + 1 ] = value[ i ].y;
  1635. uniform._array[ offset + 2 ] = value[ i ].z;
  1636. }
  1637. renderer.uniform3fv( location, uniform._array );
  1638. } else if ( type === "v4v" ) { // array of THREE.Vector4
  1639. if ( uniform._array === undefined ) {
  1640. uniform._array = new Float32Array( 4 * value.length );
  1641. }
  1642. for ( i = 0, il = value.length; i < il; i ++ ) {
  1643. offset = i * 4;
  1644. uniform._array[ offset ] = value[ i ].x;
  1645. uniform._array[ offset + 1 ] = value[ i ].y;
  1646. uniform._array[ offset + 2 ] = value[ i ].z;
  1647. uniform._array[ offset + 3 ] = value[ i ].w;
  1648. }
  1649. renderer.uniform4fv( location, uniform._array );
  1650. } else if ( type === "m4") { // single THREE.Matrix4
  1651. if ( uniform._array === undefined ) {
  1652. uniform._array = new Float32Array( 16 );
  1653. }
  1654. value.flattenToArray( uniform._array );
  1655. renderer.uniformMatrix4fv( location, uniform._array );
  1656. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  1657. if ( uniform._array === undefined ) {
  1658. uniform._array = new Float32Array( 16 * value.length );
  1659. }
  1660. for ( i = 0, il = value.length; i < il; i ++ ) {
  1661. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  1662. }
  1663. renderer.uniformMatrix4fv( location, uniform._array );
  1664. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  1665. texture = value;
  1666. textureUnit = getTextureUnit();
  1667. renderer.uniform1i( location, textureUnit );
  1668. if ( !texture ) continue;
  1669. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  1670. renderer.setCubeTexture( texture, textureUnit );
  1671. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  1672. renderer.setCubeTextureDynamic( texture, textureUnit );
  1673. } else {
  1674. renderer.setTexture( texture, textureUnit );
  1675. }
  1676. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  1677. if ( uniform._array === undefined ) {
  1678. uniform._array = [];
  1679. }
  1680. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  1681. uniform._array[ i ] = getTextureUnit();
  1682. }
  1683. renderer.uniform1iv( location, uniform._array );
  1684. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  1685. texture = uniform.value[ i ];
  1686. textureUnit = uniform._array[ i ];
  1687. if ( !texture ) continue;
  1688. renderer.setTexture( texture, textureUnit );
  1689. }
  1690. }
  1691. }
  1692. };
  1693. function setupMatrices ( object, camera ) {
  1694. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  1695. object._normalMatrix.getInverse( object._modelViewMatrix );
  1696. object._normalMatrix.transpose();
  1697. };
  1698. //
  1699. function setColorGamma( array, offset, color, intensitySq ) {
  1700. array[ offset ] = color.r * color.r * intensitySq;
  1701. array[ offset + 1 ] = color.g * color.g * intensitySq;
  1702. array[ offset + 2 ] = color.b * color.b * intensitySq;
  1703. };
  1704. function setColorLinear( array, offset, color, intensity ) {
  1705. array[ offset ] = color.r * intensity;
  1706. array[ offset + 1 ] = color.g * intensity;
  1707. array[ offset + 2 ] = color.b * intensity;
  1708. };
  1709. function setupLights ( program, lights ) {
  1710. var l, ll, light, n,
  1711. r = 0, g = 0, b = 0,
  1712. color, skyColor, groundColor,
  1713. intensity, intensitySq,
  1714. position,
  1715. distance,
  1716. zlights = _lights,
  1717. dirColors = zlights.directional.colors,
  1718. dirPositions = zlights.directional.positions,
  1719. pointColors = zlights.point.colors,
  1720. pointPositions = zlights.point.positions,
  1721. pointDistances = zlights.point.distances,
  1722. spotColors = zlights.spot.colors,
  1723. spotPositions = zlights.spot.positions,
  1724. spotDistances = zlights.spot.distances,
  1725. spotDirections = zlights.spot.directions,
  1726. spotAnglesCos = zlights.spot.anglesCos,
  1727. spotExponents = zlights.spot.exponents,
  1728. hemiSkyColors = zlights.hemi.skyColors,
  1729. hemiGroundColors = zlights.hemi.groundColors,
  1730. hemiPositions = zlights.hemi.positions,
  1731. dirLength = 0,
  1732. pointLength = 0,
  1733. spotLength = 0,
  1734. hemiLength = 0,
  1735. dirCount = 0,
  1736. pointCount = 0,
  1737. spotCount = 0,
  1738. hemiCount = 0,
  1739. dirOffset = 0,
  1740. pointOffset = 0,
  1741. spotOffset = 0,
  1742. hemiOffset = 0;
  1743. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  1744. light = lights[ l ];
  1745. if ( light.onlyShadow ) continue;
  1746. color = light.color;
  1747. intensity = light.intensity;
  1748. distance = light.distance;
  1749. if ( light instanceof THREE.AmbientLight ) {
  1750. if ( ! light.visible ) continue;
  1751. if ( _this.gammaInput ) {
  1752. r += color.r * color.r;
  1753. g += color.g * color.g;
  1754. b += color.b * color.b;
  1755. } else {
  1756. r += color.r;
  1757. g += color.g;
  1758. b += color.b;
  1759. }
  1760. } else if ( light instanceof THREE.DirectionalLight ) {
  1761. dirCount += 1;
  1762. if ( ! light.visible ) continue;
  1763. _direction.copy( light.matrixWorld.getPosition() );
  1764. _direction.sub( light.target.matrixWorld.getPosition() );
  1765. _direction.normalize();
  1766. // skip lights with undefined direction
  1767. // these create troubles in OpenGL (making pixel black)
  1768. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  1769. dirOffset = dirLength * 3;
  1770. dirPositions[ dirOffset ] = _direction.x;
  1771. dirPositions[ dirOffset + 1 ] = _direction.y;
  1772. dirPositions[ dirOffset + 2 ] = _direction.z;
  1773. if ( _this.gammaInput ) {
  1774. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  1775. } else {
  1776. setColorLinear( dirColors, dirOffset, color, intensity );
  1777. }
  1778. dirLength += 1;
  1779. } else if ( light instanceof THREE.PointLight ) {
  1780. pointCount += 1;
  1781. if ( ! light.visible ) continue;
  1782. pointOffset = pointLength * 3;
  1783. if ( _this.gammaInput ) {
  1784. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  1785. } else {
  1786. setColorLinear( pointColors, pointOffset, color, intensity );
  1787. }
  1788. position = light.matrixWorld.getPosition();
  1789. pointPositions[ pointOffset ] = position.x;
  1790. pointPositions[ pointOffset + 1 ] = position.y;
  1791. pointPositions[ pointOffset + 2 ] = position.z;
  1792. pointDistances[ pointLength ] = distance;
  1793. pointLength += 1;
  1794. } else if ( light instanceof THREE.SpotLight ) {
  1795. spotCount += 1;
  1796. if ( ! light.visible ) continue;
  1797. spotOffset = spotLength * 3;
  1798. if ( _this.gammaInput ) {
  1799. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  1800. } else {
  1801. setColorLinear( spotColors, spotOffset, color, intensity );
  1802. }
  1803. position = light.matrixWorld.getPosition();
  1804. spotPositions[ spotOffset ] = position.x;
  1805. spotPositions[ spotOffset + 1 ] = position.y;
  1806. spotPositions[ spotOffset + 2 ] = position.z;
  1807. spotDistances[ spotLength ] = distance;
  1808. _direction.copy( position );
  1809. _direction.sub( light.target.matrixWorld.getPosition() );
  1810. _direction.normalize();
  1811. spotDirections[ spotOffset ] = _direction.x;
  1812. spotDirections[ spotOffset + 1 ] = _direction.y;
  1813. spotDirections[ spotOffset + 2 ] = _direction.z;
  1814. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  1815. spotExponents[ spotLength ] = light.exponent;
  1816. spotLength += 1;
  1817. } else if ( light instanceof THREE.HemisphereLight ) {
  1818. hemiCount += 1;
  1819. if ( ! light.visible ) continue;
  1820. _direction.copy( light.matrixWorld.getPosition() );
  1821. _direction.normalize();
  1822. // skip lights with undefined direction
  1823. // these create troubles in OpenGL (making pixel black)
  1824. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  1825. hemiOffset = hemiLength * 3;
  1826. hemiPositions[ hemiOffset ] = _direction.x;
  1827. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  1828. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  1829. skyColor = light.color;
  1830. groundColor = light.groundColor;
  1831. if ( _this.gammaInput ) {
  1832. intensitySq = intensity * intensity;
  1833. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  1834. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  1835. } else {
  1836. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  1837. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  1838. }
  1839. hemiLength += 1;
  1840. }
  1841. }
  1842. // null eventual remains from removed lights
  1843. // (this is to avoid if in shader)
  1844. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  1845. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  1846. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  1847. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  1848. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  1849. zlights.directional.length = dirLength;
  1850. zlights.point.length = pointLength;
  1851. zlights.spot.length = spotLength;
  1852. zlights.hemi.length = hemiLength;
  1853. zlights.ambient[ 0 ] = r;
  1854. zlights.ambient[ 1 ] = g;
  1855. zlights.ambient[ 2 ] = b;
  1856. };
  1857. // Allocations
  1858. function allocateBones ( object ) {
  1859. if ( renderer.supportsBoneTextures && object && object.useVertexTexture ) {
  1860. return 1024;
  1861. } else {
  1862. // default for when object is not specified
  1863. // ( for example when prebuilding shader
  1864. // to be used with multiple objects )
  1865. //
  1866. // - leave some extra space for other uniforms
  1867. // - limit here is ANGLE's 254 max uniform vectors
  1868. // (up to 54 should be safe)
  1869. var nVertexUniforms = renderer.maxVertexUniformVectors
  1870. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  1871. var maxBones = nVertexMatrices;
  1872. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  1873. maxBones = Math.min( object.bones.length, maxBones );
  1874. if ( maxBones < object.bones.length ) {
  1875. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  1876. }
  1877. }
  1878. return maxBones;
  1879. }
  1880. };
  1881. function allocateLights ( lights ) {
  1882. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  1883. dirLights = pointLights = spotLights = hemiLights = 0;
  1884. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  1885. light = lights[ l ];
  1886. if ( light.onlyShadow ) continue;
  1887. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  1888. if ( light instanceof THREE.PointLight ) pointLights ++;
  1889. if ( light instanceof THREE.SpotLight ) spotLights ++;
  1890. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  1891. }
  1892. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  1893. };
  1894. function allocateShadows ( lights ) {
  1895. var l, ll, light, maxShadows = 0;
  1896. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  1897. light = lights[ l ];
  1898. if ( ! light.castShadow ) continue;
  1899. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  1900. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  1901. }
  1902. return maxShadows;
  1903. };
  1904. // default plugins (order is important)
  1905. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  1906. this.addPrePlugin( this.shadowMapPlugin );
  1907. this.addPostPlugin( new THREE.SpritePlugin() );
  1908. this.addPostPlugin( new THREE.LensFlarePlugin() );
  1909. };