WebGLRenderer.js 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922
  1. import { REVISION, MaxEquation, MinEquation, RGB_ETC1_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT5_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT1_Format, RGB_S3TC_DXT1_Format, SrcAlphaSaturateFactor, OneMinusDstColorFactor, DstColorFactor, OneMinusDstAlphaFactor, DstAlphaFactor, OneMinusSrcAlphaFactor, SrcAlphaFactor, OneMinusSrcColorFactor, SrcColorFactor, OneFactor, ZeroFactor, ReverseSubtractEquation, SubtractEquation, AddEquation, DepthFormat, DepthStencilFormat, LuminanceAlphaFormat, LuminanceFormat, RGBAFormat, RGBFormat, AlphaFormat, HalfFloatType, FloatType, UnsignedIntType, IntType, UnsignedShortType, ShortType, ByteType, UnsignedInt248Type, UnsignedShort565Type, UnsignedShort5551Type, UnsignedShort4444Type, UnsignedByteType, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestFilter, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, FrontFaceDirectionCW, NoBlending, BackSide, DoubleSide, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, NoColors, FlatShading, LinearToneMapping } from '../constants';
  2. import { Matrix4 } from '../math/Matrix4';
  3. import { WebGLUniforms } from './webgl/WebGLUniforms';
  4. import { UniformsUtils } from './shaders/UniformsUtils';
  5. import { ShaderLib } from './shaders/ShaderLib';
  6. import { LensFlarePlugin } from './webgl/plugins/LensFlarePlugin';
  7. import { SpritePlugin } from './webgl/plugins/SpritePlugin';
  8. import { WebGLShadowMap } from './webgl/WebGLShadowMap';
  9. import { ShaderMaterial } from '../materials/ShaderMaterial';
  10. import { Mesh } from '../objects/Mesh';
  11. import { BoxBufferGeometry } from '../geometries/BoxGeometry';
  12. import { PlaneBufferGeometry } from '../geometries/PlaneGeometry';
  13. import { MeshBasicMaterial } from '../materials/MeshBasicMaterial';
  14. import { PerspectiveCamera } from '../cameras/PerspectiveCamera';
  15. import { OrthographicCamera } from '../cameras/OrthographicCamera';
  16. import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer';
  17. import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer';
  18. import { WebGLLights } from './webgl/WebGLLights';
  19. import { WebGLPrograms } from './webgl/WebGLPrograms';
  20. import { WebGLObjects } from './webgl/WebGLObjects';
  21. import { WebGLTextures } from './webgl/WebGLTextures';
  22. import { WebGLProperties } from './webgl/WebGLProperties';
  23. import { WebGLState } from './webgl/WebGLState';
  24. import { WebGLCapabilities } from './webgl/WebGLCapabilities';
  25. import { BufferGeometry } from '../core/BufferGeometry';
  26. import { WebGLExtensions } from './webgl/WebGLExtensions';
  27. import { Vector3 } from '../math/Vector3';
  28. import { Sphere } from '../math/Sphere';
  29. import { WebGLClipping } from './webgl/WebGLClipping';
  30. import { Frustum } from '../math/Frustum';
  31. import { Vector4 } from '../math/Vector4';
  32. import { Color } from '../math/Color';
  33. /**
  34. * @author supereggbert / http://www.paulbrunt.co.uk/
  35. * @author mrdoob / http://mrdoob.com/
  36. * @author alteredq / http://alteredqualia.com/
  37. * @author szimek / https://github.com/szimek/
  38. * @author tschw
  39. */
  40. function WebGLRenderer( parameters ) {
  41. console.log( 'THREE.WebGLRenderer', REVISION );
  42. parameters = parameters || {};
  43. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  44. _context = parameters.context !== undefined ? parameters.context : null,
  45. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  46. _depth = parameters.depth !== undefined ? parameters.depth : true,
  47. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  48. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  49. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  50. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  51. var lights = [];
  52. var opaqueObjects = [];
  53. var opaqueObjectsLastIndex = - 1;
  54. var transparentObjects = [];
  55. var transparentObjectsLastIndex = - 1;
  56. var morphInfluences = new Float32Array( 8 );
  57. var sprites = [];
  58. var lensFlares = [];
  59. // public properties
  60. this.domElement = _canvas;
  61. this.context = null;
  62. // clearing
  63. this.autoClear = true;
  64. this.autoClearColor = true;
  65. this.autoClearDepth = true;
  66. this.autoClearStencil = true;
  67. // scene graph
  68. this.sortObjects = true;
  69. // user-defined clipping
  70. this.clippingPlanes = [];
  71. this.localClippingEnabled = false;
  72. // physically based shading
  73. this.gammaFactor = 2.0; // for backwards compatibility
  74. this.gammaInput = false;
  75. this.gammaOutput = false;
  76. // physical lights
  77. this.physicallyCorrectLights = false;
  78. // tone mapping
  79. this.toneMapping = LinearToneMapping;
  80. this.toneMappingExposure = 1.0;
  81. this.toneMappingWhitePoint = 1.0;
  82. // morphs
  83. this.maxMorphTargets = 8;
  84. this.maxMorphNormals = 4;
  85. // internal properties
  86. var _this = this,
  87. // internal state cache
  88. _currentProgram = null,
  89. _currentRenderTarget = null,
  90. _currentFramebuffer = null,
  91. _currentMaterialId = - 1,
  92. _currentGeometryProgram = '',
  93. _currentCamera = null,
  94. _currentScissor = new Vector4(),
  95. _currentScissorTest = null,
  96. _currentViewport = new Vector4(),
  97. //
  98. _usedTextureUnits = 0,
  99. //
  100. _clearColor = new Color( 0x000000 ),
  101. _clearAlpha = 0,
  102. _width = _canvas.width,
  103. _height = _canvas.height,
  104. _pixelRatio = 1,
  105. _scissor = new Vector4( 0, 0, _width, _height ),
  106. _scissorTest = false,
  107. _viewport = new Vector4( 0, 0, _width, _height ),
  108. // frustum
  109. _frustum = new Frustum(),
  110. // clipping
  111. _clipping = new WebGLClipping(),
  112. _clippingEnabled = false,
  113. _localClippingEnabled = false,
  114. _sphere = new Sphere(),
  115. // camera matrices cache
  116. _projScreenMatrix = new Matrix4(),
  117. _vector3 = new Vector3(),
  118. _matrix4 = new Matrix4(),
  119. _matrix42 = new Matrix4(),
  120. // light arrays cache
  121. _lights = {
  122. hash: '',
  123. ambient: [ 0, 0, 0 ],
  124. directional: [],
  125. directionalShadowMap: [],
  126. directionalShadowMatrix: [],
  127. spot: [],
  128. spotShadowMap: [],
  129. spotShadowMatrix: [],
  130. rectArea: [],
  131. point: [],
  132. pointShadowMap: [],
  133. pointShadowMatrix: [],
  134. hemi: [],
  135. shadows: []
  136. },
  137. // info
  138. _infoRender = {
  139. calls: 0,
  140. vertices: 0,
  141. faces: 0,
  142. points: 0
  143. };
  144. this.info = {
  145. render: _infoRender,
  146. memory: {
  147. geometries: 0,
  148. textures: 0
  149. },
  150. programs: null
  151. };
  152. // initialize
  153. var _gl;
  154. try {
  155. var attributes = {
  156. alpha: _alpha,
  157. depth: _depth,
  158. stencil: _stencil,
  159. antialias: _antialias,
  160. premultipliedAlpha: _premultipliedAlpha,
  161. preserveDrawingBuffer: _preserveDrawingBuffer
  162. };
  163. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  164. if ( _gl === null ) {
  165. if ( _canvas.getContext( 'webgl' ) !== null ) {
  166. throw 'Error creating WebGL context with your selected attributes.';
  167. } else {
  168. throw 'Error creating WebGL context.';
  169. }
  170. }
  171. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  172. if ( _gl.getShaderPrecisionFormat === undefined ) {
  173. _gl.getShaderPrecisionFormat = function () {
  174. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  175. };
  176. }
  177. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  178. } catch ( error ) {
  179. console.error( 'THREE.WebGLRenderer: ' + error );
  180. }
  181. var extensions = new WebGLExtensions( _gl );
  182. extensions.get( 'WEBGL_depth_texture' );
  183. extensions.get( 'OES_texture_float' );
  184. extensions.get( 'OES_texture_float_linear' );
  185. extensions.get( 'OES_texture_half_float' );
  186. extensions.get( 'OES_texture_half_float_linear' );
  187. extensions.get( 'OES_standard_derivatives' );
  188. extensions.get( 'ANGLE_instanced_arrays' );
  189. if ( extensions.get( 'OES_element_index_uint' ) ) {
  190. BufferGeometry.MaxIndex = 4294967296;
  191. }
  192. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  193. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  194. var properties = new WebGLProperties();
  195. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  196. var objects = new WebGLObjects( _gl, properties, this.info );
  197. var programCache = new WebGLPrograms( this, capabilities );
  198. var lightCache = new WebGLLights();
  199. this.info.programs = programCache.programs;
  200. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  201. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  202. //
  203. var backgroundPlaneCamera, backgroundPlaneMesh;
  204. var backgroundBoxCamera, backgroundBoxMesh;
  205. //
  206. function getTargetPixelRatio() {
  207. return _currentRenderTarget === null ? _pixelRatio : 1;
  208. }
  209. function setDefaultGLState() {
  210. state.init();
  211. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  212. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  213. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  214. }
  215. function resetGLState() {
  216. _currentProgram = null;
  217. _currentCamera = null;
  218. _currentGeometryProgram = '';
  219. _currentMaterialId = - 1;
  220. state.reset();
  221. }
  222. setDefaultGLState();
  223. this.context = _gl;
  224. this.capabilities = capabilities;
  225. this.extensions = extensions;
  226. this.properties = properties;
  227. this.state = state;
  228. // shadow map
  229. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  230. this.shadowMap = shadowMap;
  231. // Plugins
  232. var spritePlugin = new SpritePlugin( this, sprites );
  233. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  234. // API
  235. this.getContext = function () {
  236. return _gl;
  237. };
  238. this.getContextAttributes = function () {
  239. return _gl.getContextAttributes();
  240. };
  241. this.forceContextLoss = function () {
  242. extensions.get( 'WEBGL_lose_context' ).loseContext();
  243. };
  244. this.getMaxAnisotropy = function () {
  245. return capabilities.getMaxAnisotropy();
  246. };
  247. this.getPrecision = function () {
  248. return capabilities.precision;
  249. };
  250. this.getPixelRatio = function () {
  251. return _pixelRatio;
  252. };
  253. this.setPixelRatio = function ( value ) {
  254. if ( value === undefined ) return;
  255. _pixelRatio = value;
  256. this.setSize( _viewport.z, _viewport.w, false );
  257. };
  258. this.getSize = function () {
  259. return {
  260. width: _width,
  261. height: _height
  262. };
  263. };
  264. this.setSize = function ( width, height, updateStyle ) {
  265. _width = width;
  266. _height = height;
  267. _canvas.width = width * _pixelRatio;
  268. _canvas.height = height * _pixelRatio;
  269. if ( updateStyle !== false ) {
  270. _canvas.style.width = width + 'px';
  271. _canvas.style.height = height + 'px';
  272. }
  273. this.setViewport( 0, 0, width, height );
  274. };
  275. this.setViewport = function ( x, y, width, height ) {
  276. state.viewport( _viewport.set( x, y, width, height ) );
  277. };
  278. this.setScissor = function ( x, y, width, height ) {
  279. state.scissor( _scissor.set( x, y, width, height ) );
  280. };
  281. this.setScissorTest = function ( boolean ) {
  282. state.setScissorTest( _scissorTest = boolean );
  283. };
  284. // Clearing
  285. this.getClearColor = function () {
  286. return _clearColor;
  287. };
  288. this.setClearColor = function ( color, alpha ) {
  289. _clearColor.set( color );
  290. _clearAlpha = alpha !== undefined ? alpha : 1;
  291. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  292. };
  293. this.getClearAlpha = function () {
  294. return _clearAlpha;
  295. };
  296. this.setClearAlpha = function ( alpha ) {
  297. _clearAlpha = alpha;
  298. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  299. };
  300. this.clear = function ( color, depth, stencil ) {
  301. var bits = 0;
  302. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  303. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  304. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  305. _gl.clear( bits );
  306. };
  307. this.clearColor = function () {
  308. this.clear( true, false, false );
  309. };
  310. this.clearDepth = function () {
  311. this.clear( false, true, false );
  312. };
  313. this.clearStencil = function () {
  314. this.clear( false, false, true );
  315. };
  316. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  317. this.setRenderTarget( renderTarget );
  318. this.clear( color, depth, stencil );
  319. };
  320. // Reset
  321. this.resetGLState = resetGLState;
  322. this.dispose = function() {
  323. transparentObjects = [];
  324. transparentObjectsLastIndex = -1;
  325. opaqueObjects = [];
  326. opaqueObjectsLastIndex = -1;
  327. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  328. };
  329. // Events
  330. function onContextLost( event ) {
  331. event.preventDefault();
  332. resetGLState();
  333. setDefaultGLState();
  334. properties.clear();
  335. }
  336. function onMaterialDispose( event ) {
  337. var material = event.target;
  338. material.removeEventListener( 'dispose', onMaterialDispose );
  339. deallocateMaterial( material );
  340. }
  341. // Buffer deallocation
  342. function deallocateMaterial( material ) {
  343. releaseMaterialProgramReference( material );
  344. properties.delete( material );
  345. }
  346. function releaseMaterialProgramReference( material ) {
  347. var programInfo = properties.get( material ).program;
  348. material.program = undefined;
  349. if ( programInfo !== undefined ) {
  350. programCache.releaseProgram( programInfo );
  351. }
  352. }
  353. // Buffer rendering
  354. this.renderBufferImmediate = function ( object, program, material ) {
  355. state.initAttributes();
  356. var buffers = properties.get( object );
  357. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  358. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  359. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  360. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  361. var attributes = program.getAttributes();
  362. if ( object.hasPositions ) {
  363. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  364. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  365. state.enableAttribute( attributes.position );
  366. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  367. }
  368. if ( object.hasNormals ) {
  369. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  370. if ( ! material.isMeshPhongMaterial &&
  371. ! material.isMeshStandardMaterial &&
  372. ! material.isMeshNormalMaterial &&
  373. material.shading === FlatShading ) {
  374. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  375. var array = object.normalArray;
  376. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  377. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  378. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  379. array[ i + 0 ] = nx;
  380. array[ i + 1 ] = ny;
  381. array[ i + 2 ] = nz;
  382. array[ i + 3 ] = nx;
  383. array[ i + 4 ] = ny;
  384. array[ i + 5 ] = nz;
  385. array[ i + 6 ] = nx;
  386. array[ i + 7 ] = ny;
  387. array[ i + 8 ] = nz;
  388. }
  389. }
  390. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  391. state.enableAttribute( attributes.normal );
  392. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  393. }
  394. if ( object.hasUvs && material.map ) {
  395. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  396. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  397. state.enableAttribute( attributes.uv );
  398. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  399. }
  400. if ( object.hasColors && material.vertexColors !== NoColors ) {
  401. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  402. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  403. state.enableAttribute( attributes.color );
  404. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  405. }
  406. state.disableUnusedAttributes();
  407. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  408. object.count = 0;
  409. };
  410. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  411. setMaterial( material );
  412. var program = setProgram( camera, fog, material, object );
  413. var updateBuffers = false;
  414. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  415. if ( geometryProgram !== _currentGeometryProgram ) {
  416. _currentGeometryProgram = geometryProgram;
  417. updateBuffers = true;
  418. }
  419. // morph targets
  420. var morphTargetInfluences = object.morphTargetInfluences;
  421. if ( morphTargetInfluences !== undefined ) {
  422. var activeInfluences = [];
  423. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  424. var influence = morphTargetInfluences[ i ];
  425. activeInfluences.push( [ influence, i ] );
  426. }
  427. activeInfluences.sort( absNumericalSort );
  428. if ( activeInfluences.length > 8 ) {
  429. activeInfluences.length = 8;
  430. }
  431. var morphAttributes = geometry.morphAttributes;
  432. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  433. var influence = activeInfluences[ i ];
  434. morphInfluences[ i ] = influence[ 0 ];
  435. if ( influence[ 0 ] !== 0 ) {
  436. var index = influence[ 1 ];
  437. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  438. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  439. } else {
  440. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  441. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  442. }
  443. }
  444. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  445. morphInfluences[ i ] = 0.0;
  446. }
  447. program.getUniforms().setValue(
  448. _gl, 'morphTargetInfluences', morphInfluences );
  449. updateBuffers = true;
  450. }
  451. //
  452. var index = geometry.index;
  453. var position = geometry.attributes.position;
  454. var rangeFactor = 1;
  455. if ( material.wireframe === true ) {
  456. index = objects.getWireframeAttribute( geometry );
  457. rangeFactor = 2;
  458. }
  459. var renderer;
  460. if ( index !== null ) {
  461. renderer = indexedBufferRenderer;
  462. renderer.setIndex( index );
  463. } else {
  464. renderer = bufferRenderer;
  465. }
  466. if ( updateBuffers ) {
  467. setupVertexAttributes( material, program, geometry );
  468. if ( index !== null ) {
  469. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  470. }
  471. }
  472. //
  473. var dataCount = 0;
  474. if ( index !== null ) {
  475. dataCount = index.count;
  476. } else if ( position !== undefined ) {
  477. dataCount = position.count;
  478. }
  479. var rangeStart = geometry.drawRange.start * rangeFactor;
  480. var rangeCount = geometry.drawRange.count * rangeFactor;
  481. var groupStart = group !== null ? group.start * rangeFactor : 0;
  482. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  483. var drawStart = Math.max( rangeStart, groupStart );
  484. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  485. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  486. if ( drawCount === 0 ) return;
  487. //
  488. if ( object.isMesh ) {
  489. if ( material.wireframe === true ) {
  490. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  491. renderer.setMode( _gl.LINES );
  492. } else {
  493. switch ( object.drawMode ) {
  494. case TrianglesDrawMode:
  495. renderer.setMode( _gl.TRIANGLES );
  496. break;
  497. case TriangleStripDrawMode:
  498. renderer.setMode( _gl.TRIANGLE_STRIP );
  499. break;
  500. case TriangleFanDrawMode:
  501. renderer.setMode( _gl.TRIANGLE_FAN );
  502. break;
  503. }
  504. }
  505. } else if ( object.isLine ) {
  506. var lineWidth = material.linewidth;
  507. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  508. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  509. if ( object.isLineSegments ) {
  510. renderer.setMode( _gl.LINES );
  511. } else if ( object.isLineLoop ) {
  512. renderer.setMode( _gl.LINE_LOOP );
  513. } else {
  514. renderer.setMode( _gl.LINE_STRIP );
  515. }
  516. } else if ( object.isPoints ) {
  517. renderer.setMode( _gl.POINTS );
  518. }
  519. if ( geometry && geometry.isInstancedBufferGeometry ) {
  520. if ( geometry.maxInstancedCount > 0 ) {
  521. renderer.renderInstances( geometry, drawStart, drawCount );
  522. }
  523. } else {
  524. renderer.render( drawStart, drawCount );
  525. }
  526. };
  527. function setupVertexAttributes( material, program, geometry, startIndex ) {
  528. var extension;
  529. if ( geometry && geometry.isInstancedBufferGeometry ) {
  530. extension = extensions.get( 'ANGLE_instanced_arrays' );
  531. if ( extension === null ) {
  532. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  533. return;
  534. }
  535. }
  536. if ( startIndex === undefined ) startIndex = 0;
  537. state.initAttributes();
  538. var geometryAttributes = geometry.attributes;
  539. var programAttributes = program.getAttributes();
  540. var materialDefaultAttributeValues = material.defaultAttributeValues;
  541. for ( var name in programAttributes ) {
  542. var programAttribute = programAttributes[ name ];
  543. if ( programAttribute >= 0 ) {
  544. var geometryAttribute = geometryAttributes[ name ];
  545. if ( geometryAttribute !== undefined ) {
  546. var normalized = geometryAttribute.normalized;
  547. var size = geometryAttribute.itemSize;
  548. var attributeProperties = objects.getAttributeProperties( geometryAttribute );
  549. var buffer = attributeProperties.__webglBuffer;
  550. var type = attributeProperties.type;
  551. var bytesPerElement = attributeProperties.bytesPerElement;
  552. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  553. var data = geometryAttribute.data;
  554. var stride = data.stride;
  555. var offset = geometryAttribute.offset;
  556. if ( data && data.isInstancedInterleavedBuffer ) {
  557. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  558. if ( geometry.maxInstancedCount === undefined ) {
  559. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  560. }
  561. } else {
  562. state.enableAttribute( programAttribute );
  563. }
  564. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  565. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  566. } else {
  567. if ( geometryAttribute.isInstancedBufferAttribute ) {
  568. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  569. if ( geometry.maxInstancedCount === undefined ) {
  570. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  571. }
  572. } else {
  573. state.enableAttribute( programAttribute );
  574. }
  575. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  576. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  577. }
  578. } else if ( materialDefaultAttributeValues !== undefined ) {
  579. var value = materialDefaultAttributeValues[ name ];
  580. if ( value !== undefined ) {
  581. switch ( value.length ) {
  582. case 2:
  583. _gl.vertexAttrib2fv( programAttribute, value );
  584. break;
  585. case 3:
  586. _gl.vertexAttrib3fv( programAttribute, value );
  587. break;
  588. case 4:
  589. _gl.vertexAttrib4fv( programAttribute, value );
  590. break;
  591. default:
  592. _gl.vertexAttrib1fv( programAttribute, value );
  593. }
  594. }
  595. }
  596. }
  597. }
  598. state.disableUnusedAttributes();
  599. }
  600. // Sorting
  601. function absNumericalSort( a, b ) {
  602. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  603. }
  604. function painterSortStable( a, b ) {
  605. if ( a.object.renderOrder !== b.object.renderOrder ) {
  606. return a.object.renderOrder - b.object.renderOrder;
  607. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  608. return a.material.program.id - b.material.program.id;
  609. } else if ( a.material.id !== b.material.id ) {
  610. return a.material.id - b.material.id;
  611. } else if ( a.z !== b.z ) {
  612. return a.z - b.z;
  613. } else {
  614. return a.id - b.id;
  615. }
  616. }
  617. function reversePainterSortStable( a, b ) {
  618. if ( a.object.renderOrder !== b.object.renderOrder ) {
  619. return a.object.renderOrder - b.object.renderOrder;
  620. } if ( a.z !== b.z ) {
  621. return b.z - a.z;
  622. } else {
  623. return a.id - b.id;
  624. }
  625. }
  626. // Rendering
  627. this.render = function ( scene, camera, renderTarget, forceClear ) {
  628. if ( camera !== undefined && camera.isCamera !== true ) {
  629. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  630. return;
  631. }
  632. // reset caching for this frame
  633. _currentGeometryProgram = '';
  634. _currentMaterialId = - 1;
  635. _currentCamera = null;
  636. // update scene graph
  637. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  638. // update camera matrices and frustum
  639. if ( camera.parent === null ) camera.updateMatrixWorld();
  640. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  641. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  642. _frustum.setFromMatrix( _projScreenMatrix );
  643. lights.length = 0;
  644. opaqueObjectsLastIndex = - 1;
  645. transparentObjectsLastIndex = - 1;
  646. sprites.length = 0;
  647. lensFlares.length = 0;
  648. _localClippingEnabled = this.localClippingEnabled;
  649. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  650. projectObject( scene, camera );
  651. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  652. transparentObjects.length = transparentObjectsLastIndex + 1;
  653. if ( _this.sortObjects === true ) {
  654. opaqueObjects.sort( painterSortStable );
  655. transparentObjects.sort( reversePainterSortStable );
  656. }
  657. //
  658. if ( _clippingEnabled ) _clipping.beginShadows();
  659. setupShadows( lights );
  660. shadowMap.render( scene, camera );
  661. setupLights( lights, camera );
  662. if ( _clippingEnabled ) _clipping.endShadows();
  663. //
  664. _infoRender.calls = 0;
  665. _infoRender.vertices = 0;
  666. _infoRender.faces = 0;
  667. _infoRender.points = 0;
  668. if ( renderTarget === undefined ) {
  669. renderTarget = null;
  670. }
  671. this.setRenderTarget( renderTarget );
  672. //
  673. var background = scene.background;
  674. if ( background === null ) {
  675. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  676. } else if ( background && background.isColor ) {
  677. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  678. forceClear = true;
  679. }
  680. if ( this.autoClear || forceClear ) {
  681. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  682. }
  683. if ( background && background.isCubeTexture ) {
  684. if ( backgroundBoxCamera === undefined ) {
  685. backgroundBoxCamera = new PerspectiveCamera();
  686. backgroundBoxMesh = new Mesh(
  687. new BoxBufferGeometry( 5, 5, 5 ),
  688. new ShaderMaterial( {
  689. uniforms: ShaderLib.cube.uniforms,
  690. vertexShader: ShaderLib.cube.vertexShader,
  691. fragmentShader: ShaderLib.cube.fragmentShader,
  692. side: BackSide,
  693. depthTest: false,
  694. depthWrite: false,
  695. fog: false
  696. } )
  697. );
  698. }
  699. backgroundBoxCamera.projectionMatrix.copy( camera.projectionMatrix );
  700. backgroundBoxCamera.matrixWorld.extractRotation( camera.matrixWorld );
  701. backgroundBoxCamera.matrixWorldInverse.getInverse( backgroundBoxCamera.matrixWorld );
  702. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  703. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundBoxCamera.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  704. objects.update( backgroundBoxMesh );
  705. _this.renderBufferDirect( backgroundBoxCamera, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  706. } else if ( background && background.isTexture ) {
  707. if ( backgroundPlaneCamera === undefined ) {
  708. backgroundPlaneCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  709. backgroundPlaneMesh = new Mesh(
  710. new PlaneBufferGeometry( 2, 2 ),
  711. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  712. );
  713. }
  714. backgroundPlaneMesh.material.map = background;
  715. objects.update( backgroundPlaneMesh );
  716. _this.renderBufferDirect( backgroundPlaneCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  717. }
  718. //
  719. if ( scene.overrideMaterial ) {
  720. var overrideMaterial = scene.overrideMaterial;
  721. renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  722. renderObjects( transparentObjects, scene, camera, overrideMaterial );
  723. } else {
  724. // opaque pass (front-to-back order)
  725. state.setBlending( NoBlending );
  726. renderObjects( opaqueObjects, scene, camera );
  727. // transparent pass (back-to-front order)
  728. renderObjects( transparentObjects, scene, camera );
  729. }
  730. // custom render plugins (post pass)
  731. spritePlugin.render( scene, camera );
  732. lensFlarePlugin.render( scene, camera, _currentViewport );
  733. // Generate mipmap if we're using any kind of mipmap filtering
  734. if ( renderTarget ) {
  735. textures.updateRenderTargetMipmap( renderTarget );
  736. }
  737. // Ensure depth buffer writing is enabled so it can be cleared on next render
  738. state.setDepthTest( true );
  739. state.setDepthWrite( true );
  740. state.setColorWrite( true );
  741. // _gl.finish();
  742. };
  743. function pushRenderItem( object, geometry, material, z, group ) {
  744. var array, index;
  745. // allocate the next position in the appropriate array
  746. if ( material.transparent ) {
  747. array = transparentObjects;
  748. index = ++ transparentObjectsLastIndex;
  749. } else {
  750. array = opaqueObjects;
  751. index = ++ opaqueObjectsLastIndex;
  752. }
  753. // recycle existing render item or grow the array
  754. var renderItem = array[ index ];
  755. if ( renderItem !== undefined ) {
  756. renderItem.id = object.id;
  757. renderItem.object = object;
  758. renderItem.geometry = geometry;
  759. renderItem.material = material;
  760. renderItem.z = _vector3.z;
  761. renderItem.group = group;
  762. } else {
  763. renderItem = {
  764. id: object.id,
  765. object: object,
  766. geometry: geometry,
  767. material: material,
  768. z: _vector3.z,
  769. group: group
  770. };
  771. // assert( index === array.length );
  772. array.push( renderItem );
  773. }
  774. }
  775. // TODO Duplicated code (Frustum)
  776. function isObjectViewable( object ) {
  777. var geometry = object.geometry;
  778. if ( geometry.boundingSphere === null )
  779. geometry.computeBoundingSphere();
  780. _sphere.copy( geometry.boundingSphere ).
  781. applyMatrix4( object.matrixWorld );
  782. return isSphereViewable( _sphere );
  783. }
  784. function isSpriteViewable( sprite ) {
  785. _sphere.center.set( 0, 0, 0 );
  786. _sphere.radius = 0.7071067811865476;
  787. _sphere.applyMatrix4( sprite.matrixWorld );
  788. return isSphereViewable( _sphere );
  789. }
  790. function isSphereViewable( sphere ) {
  791. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  792. var numPlanes = _clipping.numPlanes;
  793. if ( numPlanes === 0 ) return true;
  794. var planes = _this.clippingPlanes,
  795. center = sphere.center,
  796. negRad = - sphere.radius,
  797. i = 0;
  798. do {
  799. // out when deeper than radius in the negative halfspace
  800. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  801. } while ( ++ i !== numPlanes );
  802. return true;
  803. }
  804. function projectObject( object, camera ) {
  805. if ( object.visible === false ) return;
  806. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  807. if ( visible ) {
  808. if ( object.isLight ) {
  809. lights.push( object );
  810. } else if ( object.isSprite ) {
  811. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  812. sprites.push( object );
  813. }
  814. } else if ( object.isLensFlare ) {
  815. lensFlares.push( object );
  816. } else if ( object.isImmediateRenderObject ) {
  817. if ( _this.sortObjects === true ) {
  818. _vector3.setFromMatrixPosition( object.matrixWorld );
  819. _vector3.applyMatrix4( _projScreenMatrix );
  820. }
  821. pushRenderItem( object, null, object.material, _vector3.z, null );
  822. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  823. if ( object.isSkinnedMesh ) {
  824. object.skeleton.update();
  825. }
  826. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  827. var material = object.material;
  828. if ( material.visible === true ) {
  829. if ( _this.sortObjects === true ) {
  830. _vector3.setFromMatrixPosition( object.matrixWorld );
  831. _vector3.applyMatrix4( _projScreenMatrix );
  832. }
  833. var geometry = objects.update( object );
  834. if ( material.isMultiMaterial ) {
  835. var groups = geometry.groups;
  836. var materials = material.materials;
  837. // there must be at least one group if a MultiMaterial is used
  838. if ( groups.length === 0 ) {
  839. if ( geometry.index !== null ) {
  840. // indexed geometry
  841. geometry.addGroup( 0, geometry.index.count );
  842. } else {
  843. // non-indexed geometry
  844. geometry.addGroup( 0, geometry.attributes.position.count );
  845. }
  846. }
  847. // push a render item for each group of the geometry
  848. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  849. var group = groups[ i ];
  850. var groupMaterial = materials[ group.materialIndex ];
  851. if ( groupMaterial === undefined ) {
  852. console.warn( 'THREE.WebGLRenderer: MultiMaterial has insufficient amount of materials for geometry. %i material(s) expected but only %i provided.', groups.length, materials.length );
  853. } else {
  854. if ( groupMaterial.visible === true ) {
  855. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  856. }
  857. }
  858. }
  859. } else {
  860. pushRenderItem( object, geometry, material, _vector3.z, null );
  861. }
  862. }
  863. }
  864. }
  865. }
  866. var children = object.children;
  867. for ( var i = 0, l = children.length; i < l; i ++ ) {
  868. projectObject( children[ i ], camera );
  869. }
  870. }
  871. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  872. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  873. var renderItem = renderList[ i ];
  874. var object = renderItem.object;
  875. var geometry = renderItem.geometry;
  876. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  877. var group = renderItem.group;
  878. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  879. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  880. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  881. if ( object.isImmediateRenderObject ) {
  882. setMaterial( material );
  883. var program = setProgram( camera, scene.fog, material, object );
  884. _currentGeometryProgram = '';
  885. object.render( function ( object ) {
  886. _this.renderBufferImmediate( object, program, material );
  887. } );
  888. } else {
  889. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  890. }
  891. object.onAfterRender( _this, scene, camera, geometry, material, group );
  892. }
  893. }
  894. function initMaterial( material, fog, object ) {
  895. var materialProperties = properties.get( material );
  896. var parameters = programCache.getParameters(
  897. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  898. var code = programCache.getProgramCode( material, parameters );
  899. var program = materialProperties.program;
  900. var programChange = true;
  901. if ( program === undefined ) {
  902. // new material
  903. material.addEventListener( 'dispose', onMaterialDispose );
  904. } else if ( program.code !== code ) {
  905. // changed glsl or parameters
  906. releaseMaterialProgramReference( material );
  907. } else if ( parameters.shaderID !== undefined ) {
  908. // same glsl and uniform list
  909. return;
  910. } else {
  911. // only rebuild uniform list
  912. programChange = false;
  913. }
  914. if ( programChange ) {
  915. if ( parameters.shaderID ) {
  916. var shader = ShaderLib[ parameters.shaderID ];
  917. materialProperties.__webglShader = {
  918. name: material.type,
  919. uniforms: UniformsUtils.clone( shader.uniforms ),
  920. vertexShader: shader.vertexShader,
  921. fragmentShader: shader.fragmentShader
  922. };
  923. } else {
  924. materialProperties.__webglShader = {
  925. name: material.type,
  926. uniforms: material.uniforms,
  927. vertexShader: material.vertexShader,
  928. fragmentShader: material.fragmentShader
  929. };
  930. }
  931. material.__webglShader = materialProperties.__webglShader;
  932. program = programCache.acquireProgram( material, parameters, code );
  933. materialProperties.program = program;
  934. material.program = program;
  935. }
  936. var attributes = program.getAttributes();
  937. if ( material.morphTargets ) {
  938. material.numSupportedMorphTargets = 0;
  939. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  940. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  941. material.numSupportedMorphTargets ++;
  942. }
  943. }
  944. }
  945. if ( material.morphNormals ) {
  946. material.numSupportedMorphNormals = 0;
  947. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  948. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  949. material.numSupportedMorphNormals ++;
  950. }
  951. }
  952. }
  953. var uniforms = materialProperties.__webglShader.uniforms;
  954. if ( ! material.isShaderMaterial &&
  955. ! material.isRawShaderMaterial ||
  956. material.clipping === true ) {
  957. materialProperties.numClippingPlanes = _clipping.numPlanes;
  958. materialProperties.numIntersection = _clipping.numIntersection;
  959. uniforms.clippingPlanes = _clipping.uniform;
  960. }
  961. materialProperties.fog = fog;
  962. // store the light setup it was created for
  963. materialProperties.lightsHash = _lights.hash;
  964. if ( material.lights ) {
  965. // wire up the material to this renderer's lighting state
  966. uniforms.ambientLightColor.value = _lights.ambient;
  967. uniforms.directionalLights.value = _lights.directional;
  968. uniforms.spotLights.value = _lights.spot;
  969. uniforms.rectAreaLights.value = _lights.rectArea;
  970. uniforms.pointLights.value = _lights.point;
  971. uniforms.hemisphereLights.value = _lights.hemi;
  972. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  973. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  974. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  975. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  976. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  977. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  978. // TODO (abelnation): add area lights shadow info to uniforms
  979. }
  980. var progUniforms = materialProperties.program.getUniforms(),
  981. uniformsList =
  982. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  983. materialProperties.uniformsList = uniformsList;
  984. }
  985. function setMaterial( material ) {
  986. material.side === DoubleSide
  987. ? state.disable( _gl.CULL_FACE )
  988. : state.enable( _gl.CULL_FACE );
  989. state.setFlipSided( material.side === BackSide );
  990. material.transparent === true
  991. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  992. : state.setBlending( NoBlending );
  993. state.setDepthFunc( material.depthFunc );
  994. state.setDepthTest( material.depthTest );
  995. state.setDepthWrite( material.depthWrite );
  996. state.setColorWrite( material.colorWrite );
  997. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  998. }
  999. function setProgram( camera, fog, material, object ) {
  1000. _usedTextureUnits = 0;
  1001. var materialProperties = properties.get( material );
  1002. if ( _clippingEnabled ) {
  1003. if ( _localClippingEnabled || camera !== _currentCamera ) {
  1004. var useCache =
  1005. camera === _currentCamera &&
  1006. material.id === _currentMaterialId;
  1007. // we might want to call this function with some ClippingGroup
  1008. // object instead of the material, once it becomes feasible
  1009. // (#8465, #8379)
  1010. _clipping.setState(
  1011. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  1012. camera, materialProperties, useCache );
  1013. }
  1014. }
  1015. if ( material.needsUpdate === false ) {
  1016. if ( materialProperties.program === undefined ) {
  1017. material.needsUpdate = true;
  1018. } else if ( material.fog && materialProperties.fog !== fog ) {
  1019. material.needsUpdate = true;
  1020. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  1021. material.needsUpdate = true;
  1022. } else if ( materialProperties.numClippingPlanes !== undefined &&
  1023. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  1024. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  1025. material.needsUpdate = true;
  1026. }
  1027. }
  1028. if ( material.needsUpdate ) {
  1029. initMaterial( material, fog, object );
  1030. material.needsUpdate = false;
  1031. }
  1032. var refreshProgram = false;
  1033. var refreshMaterial = false;
  1034. var refreshLights = false;
  1035. var program = materialProperties.program,
  1036. p_uniforms = program.getUniforms(),
  1037. m_uniforms = materialProperties.__webglShader.uniforms;
  1038. if ( program.id !== _currentProgram ) {
  1039. _gl.useProgram( program.program );
  1040. _currentProgram = program.id;
  1041. refreshProgram = true;
  1042. refreshMaterial = true;
  1043. refreshLights = true;
  1044. }
  1045. if ( material.id !== _currentMaterialId ) {
  1046. _currentMaterialId = material.id;
  1047. refreshMaterial = true;
  1048. }
  1049. if ( refreshProgram || camera !== _currentCamera ) {
  1050. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  1051. if ( capabilities.logarithmicDepthBuffer ) {
  1052. p_uniforms.setValue( _gl, 'logDepthBufFC',
  1053. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  1054. }
  1055. if ( camera !== _currentCamera ) {
  1056. _currentCamera = camera;
  1057. // lighting uniforms depend on the camera so enforce an update
  1058. // now, in case this material supports lights - or later, when
  1059. // the next material that does gets activated:
  1060. refreshMaterial = true; // set to true on material change
  1061. refreshLights = true; // remains set until update done
  1062. }
  1063. // load material specific uniforms
  1064. // (shader material also gets them for the sake of genericity)
  1065. if ( material.isShaderMaterial ||
  1066. material.isMeshPhongMaterial ||
  1067. material.isMeshStandardMaterial ||
  1068. material.envMap ) {
  1069. var uCamPos = p_uniforms.map.cameraPosition;
  1070. if ( uCamPos !== undefined ) {
  1071. uCamPos.setValue( _gl,
  1072. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  1073. }
  1074. }
  1075. if ( material.isMeshPhongMaterial ||
  1076. material.isMeshLambertMaterial ||
  1077. material.isMeshBasicMaterial ||
  1078. material.isMeshStandardMaterial ||
  1079. material.isShaderMaterial ||
  1080. material.skinning ) {
  1081. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  1082. }
  1083. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  1084. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  1085. }
  1086. // skinning uniforms must be set even if material didn't change
  1087. // auto-setting of texture unit for bone texture must go before other textures
  1088. // not sure why, but otherwise weird things happen
  1089. if ( material.skinning ) {
  1090. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  1091. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  1092. var skeleton = object.skeleton;
  1093. if ( skeleton ) {
  1094. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  1095. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  1096. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  1097. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  1098. } else {
  1099. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  1100. }
  1101. }
  1102. }
  1103. if ( refreshMaterial ) {
  1104. if ( material.lights ) {
  1105. // the current material requires lighting info
  1106. // note: all lighting uniforms are always set correctly
  1107. // they simply reference the renderer's state for their
  1108. // values
  1109. //
  1110. // use the current material's .needsUpdate flags to set
  1111. // the GL state when required
  1112. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  1113. }
  1114. // refresh uniforms common to several materials
  1115. if ( fog && material.fog ) {
  1116. refreshUniformsFog( m_uniforms, fog );
  1117. }
  1118. if ( material.isMeshBasicMaterial ||
  1119. material.isMeshLambertMaterial ||
  1120. material.isMeshPhongMaterial ||
  1121. material.isMeshStandardMaterial ||
  1122. material.isMeshNormalMaterial ||
  1123. material.isMeshDepthMaterial ) {
  1124. refreshUniformsCommon( m_uniforms, material );
  1125. }
  1126. // refresh single material specific uniforms
  1127. if ( material.isLineBasicMaterial ) {
  1128. refreshUniformsLine( m_uniforms, material );
  1129. } else if ( material.isLineDashedMaterial ) {
  1130. refreshUniformsLine( m_uniforms, material );
  1131. refreshUniformsDash( m_uniforms, material );
  1132. } else if ( material.isPointsMaterial ) {
  1133. refreshUniformsPoints( m_uniforms, material );
  1134. } else if ( material.isMeshLambertMaterial ) {
  1135. refreshUniformsLambert( m_uniforms, material );
  1136. } else if ( material.isMeshToonMaterial ) {
  1137. refreshUniformsToon( m_uniforms, material );
  1138. } else if ( material.isMeshPhongMaterial ) {
  1139. refreshUniformsPhong( m_uniforms, material );
  1140. } else if ( material.isMeshPhysicalMaterial ) {
  1141. refreshUniformsPhysical( m_uniforms, material );
  1142. } else if ( material.isMeshStandardMaterial ) {
  1143. refreshUniformsStandard( m_uniforms, material );
  1144. } else if ( material.isMeshDepthMaterial ) {
  1145. if ( material.displacementMap ) {
  1146. m_uniforms.displacementMap.value = material.displacementMap;
  1147. m_uniforms.displacementScale.value = material.displacementScale;
  1148. m_uniforms.displacementBias.value = material.displacementBias;
  1149. }
  1150. } else if ( material.isMeshNormalMaterial ) {
  1151. refreshUniformsNormal( m_uniforms, material );
  1152. }
  1153. // RectAreaLight Texture
  1154. // TODO (mrdoob): Find a nicer implementation
  1155. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = THREE.UniformsLib.LTC_MAT_TEXTURE;
  1156. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = THREE.UniformsLib.LTC_MAG_TEXTURE;
  1157. WebGLUniforms.upload(
  1158. _gl, materialProperties.uniformsList, m_uniforms, _this );
  1159. }
  1160. // common matrices
  1161. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  1162. p_uniforms.set( _gl, object, 'normalMatrix' );
  1163. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  1164. return program;
  1165. }
  1166. // Uniforms (refresh uniforms objects)
  1167. function refreshUniformsCommon( uniforms, material ) {
  1168. uniforms.opacity.value = material.opacity;
  1169. uniforms.diffuse.value = material.color;
  1170. if ( material.emissive ) {
  1171. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  1172. }
  1173. uniforms.map.value = material.map;
  1174. uniforms.specularMap.value = material.specularMap;
  1175. uniforms.alphaMap.value = material.alphaMap;
  1176. if ( material.lightMap ) {
  1177. uniforms.lightMap.value = material.lightMap;
  1178. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  1179. }
  1180. if ( material.aoMap ) {
  1181. uniforms.aoMap.value = material.aoMap;
  1182. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  1183. }
  1184. // uv repeat and offset setting priorities
  1185. // 1. color map
  1186. // 2. specular map
  1187. // 3. normal map
  1188. // 4. bump map
  1189. // 5. alpha map
  1190. // 6. emissive map
  1191. var uvScaleMap;
  1192. if ( material.map ) {
  1193. uvScaleMap = material.map;
  1194. } else if ( material.specularMap ) {
  1195. uvScaleMap = material.specularMap;
  1196. } else if ( material.displacementMap ) {
  1197. uvScaleMap = material.displacementMap;
  1198. } else if ( material.normalMap ) {
  1199. uvScaleMap = material.normalMap;
  1200. } else if ( material.bumpMap ) {
  1201. uvScaleMap = material.bumpMap;
  1202. } else if ( material.roughnessMap ) {
  1203. uvScaleMap = material.roughnessMap;
  1204. } else if ( material.metalnessMap ) {
  1205. uvScaleMap = material.metalnessMap;
  1206. } else if ( material.alphaMap ) {
  1207. uvScaleMap = material.alphaMap;
  1208. } else if ( material.emissiveMap ) {
  1209. uvScaleMap = material.emissiveMap;
  1210. }
  1211. if ( uvScaleMap !== undefined ) {
  1212. // backwards compatibility
  1213. if ( uvScaleMap.isWebGLRenderTarget ) {
  1214. uvScaleMap = uvScaleMap.texture;
  1215. }
  1216. var offset = uvScaleMap.offset;
  1217. var repeat = uvScaleMap.repeat;
  1218. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1219. }
  1220. uniforms.envMap.value = material.envMap;
  1221. // don't flip CubeTexture envMaps, flip everything else:
  1222. // WebGLRenderTargetCube will be flipped for backwards compatibility
  1223. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  1224. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  1225. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  1226. uniforms.reflectivity.value = material.reflectivity;
  1227. uniforms.refractionRatio.value = material.refractionRatio;
  1228. }
  1229. function refreshUniformsLine( uniforms, material ) {
  1230. uniforms.diffuse.value = material.color;
  1231. uniforms.opacity.value = material.opacity;
  1232. }
  1233. function refreshUniformsDash( uniforms, material ) {
  1234. uniforms.dashSize.value = material.dashSize;
  1235. uniforms.totalSize.value = material.dashSize + material.gapSize;
  1236. uniforms.scale.value = material.scale;
  1237. }
  1238. function refreshUniformsPoints( uniforms, material ) {
  1239. uniforms.diffuse.value = material.color;
  1240. uniforms.opacity.value = material.opacity;
  1241. uniforms.size.value = material.size * _pixelRatio;
  1242. uniforms.scale.value = _height * 0.5;
  1243. uniforms.map.value = material.map;
  1244. if ( material.map !== null ) {
  1245. var offset = material.map.offset;
  1246. var repeat = material.map.repeat;
  1247. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  1248. }
  1249. }
  1250. function refreshUniformsFog( uniforms, fog ) {
  1251. uniforms.fogColor.value = fog.color;
  1252. if ( fog.isFog ) {
  1253. uniforms.fogNear.value = fog.near;
  1254. uniforms.fogFar.value = fog.far;
  1255. } else if ( fog.isFogExp2 ) {
  1256. uniforms.fogDensity.value = fog.density;
  1257. }
  1258. }
  1259. function refreshUniformsLambert( uniforms, material ) {
  1260. if ( material.emissiveMap ) {
  1261. uniforms.emissiveMap.value = material.emissiveMap;
  1262. }
  1263. }
  1264. function refreshUniformsPhong( uniforms, material ) {
  1265. uniforms.specular.value = material.specular;
  1266. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  1267. if ( material.emissiveMap ) {
  1268. uniforms.emissiveMap.value = material.emissiveMap;
  1269. }
  1270. if ( material.bumpMap ) {
  1271. uniforms.bumpMap.value = material.bumpMap;
  1272. uniforms.bumpScale.value = material.bumpScale;
  1273. }
  1274. if ( material.normalMap ) {
  1275. uniforms.normalMap.value = material.normalMap;
  1276. uniforms.normalScale.value.copy( material.normalScale );
  1277. }
  1278. if ( material.displacementMap ) {
  1279. uniforms.displacementMap.value = material.displacementMap;
  1280. uniforms.displacementScale.value = material.displacementScale;
  1281. uniforms.displacementBias.value = material.displacementBias;
  1282. }
  1283. }
  1284. function refreshUniformsToon( uniforms, material ) {
  1285. refreshUniformsPhong( uniforms, material );
  1286. if ( material.gradientMap ) {
  1287. uniforms.gradientMap.value = material.gradientMap;
  1288. }
  1289. }
  1290. function refreshUniformsStandard( uniforms, material ) {
  1291. uniforms.roughness.value = material.roughness;
  1292. uniforms.metalness.value = material.metalness;
  1293. if ( material.roughnessMap ) {
  1294. uniforms.roughnessMap.value = material.roughnessMap;
  1295. }
  1296. if ( material.metalnessMap ) {
  1297. uniforms.metalnessMap.value = material.metalnessMap;
  1298. }
  1299. if ( material.emissiveMap ) {
  1300. uniforms.emissiveMap.value = material.emissiveMap;
  1301. }
  1302. if ( material.bumpMap ) {
  1303. uniforms.bumpMap.value = material.bumpMap;
  1304. uniforms.bumpScale.value = material.bumpScale;
  1305. }
  1306. if ( material.normalMap ) {
  1307. uniforms.normalMap.value = material.normalMap;
  1308. uniforms.normalScale.value.copy( material.normalScale );
  1309. }
  1310. if ( material.displacementMap ) {
  1311. uniforms.displacementMap.value = material.displacementMap;
  1312. uniforms.displacementScale.value = material.displacementScale;
  1313. uniforms.displacementBias.value = material.displacementBias;
  1314. }
  1315. if ( material.envMap ) {
  1316. //uniforms.envMap.value = material.envMap; // part of uniforms common
  1317. uniforms.envMapIntensity.value = material.envMapIntensity;
  1318. }
  1319. }
  1320. function refreshUniformsPhysical( uniforms, material ) {
  1321. uniforms.clearCoat.value = material.clearCoat;
  1322. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  1323. refreshUniformsStandard( uniforms, material );
  1324. }
  1325. function refreshUniformsNormal( uniforms, material ) {
  1326. if ( material.bumpMap ) {
  1327. uniforms.bumpMap.value = material.bumpMap;
  1328. uniforms.bumpScale.value = material.bumpScale;
  1329. }
  1330. if ( material.normalMap ) {
  1331. uniforms.normalMap.value = material.normalMap;
  1332. uniforms.normalScale.value.copy( material.normalScale );
  1333. }
  1334. if ( material.displacementMap ) {
  1335. uniforms.displacementMap.value = material.displacementMap;
  1336. uniforms.displacementScale.value = material.displacementScale;
  1337. uniforms.displacementBias.value = material.displacementBias;
  1338. }
  1339. }
  1340. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  1341. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  1342. uniforms.ambientLightColor.needsUpdate = value;
  1343. uniforms.directionalLights.needsUpdate = value;
  1344. uniforms.pointLights.needsUpdate = value;
  1345. uniforms.spotLights.needsUpdate = value;
  1346. uniforms.rectAreaLights.needsUpdate = value;
  1347. uniforms.hemisphereLights.needsUpdate = value;
  1348. }
  1349. // Lighting
  1350. function setupShadows( lights ) {
  1351. var lightShadowsLength = 0;
  1352. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  1353. var light = lights[ i ];
  1354. if ( light.castShadow ) {
  1355. _lights.shadows[ lightShadowsLength ++ ] = light;
  1356. }
  1357. }
  1358. _lights.shadows.length = lightShadowsLength;
  1359. }
  1360. function setupLights( lights, camera ) {
  1361. var l, ll, light,
  1362. r = 0, g = 0, b = 0,
  1363. color,
  1364. intensity,
  1365. distance,
  1366. shadowMap,
  1367. viewMatrix = camera.matrixWorldInverse,
  1368. directionalLength = 0,
  1369. pointLength = 0,
  1370. spotLength = 0,
  1371. rectAreaLength = 0,
  1372. hemiLength = 0;
  1373. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  1374. light = lights[ l ];
  1375. color = light.color;
  1376. intensity = light.intensity;
  1377. distance = light.distance;
  1378. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  1379. if ( light.isAmbientLight ) {
  1380. r += color.r * intensity;
  1381. g += color.g * intensity;
  1382. b += color.b * intensity;
  1383. } else if ( light.isDirectionalLight ) {
  1384. var uniforms = lightCache.get( light );
  1385. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1386. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1387. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1388. uniforms.direction.sub( _vector3 );
  1389. uniforms.direction.transformDirection( viewMatrix );
  1390. uniforms.shadow = light.castShadow;
  1391. if ( light.castShadow ) {
  1392. uniforms.shadowBias = light.shadow.bias;
  1393. uniforms.shadowRadius = light.shadow.radius;
  1394. uniforms.shadowMapSize = light.shadow.mapSize;
  1395. }
  1396. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  1397. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  1398. _lights.directional[ directionalLength ++ ] = uniforms;
  1399. } else if ( light.isSpotLight ) {
  1400. var uniforms = lightCache.get( light );
  1401. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1402. uniforms.position.applyMatrix4( viewMatrix );
  1403. uniforms.color.copy( color ).multiplyScalar( intensity );
  1404. uniforms.distance = distance;
  1405. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1406. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  1407. uniforms.direction.sub( _vector3 );
  1408. uniforms.direction.transformDirection( viewMatrix );
  1409. uniforms.coneCos = Math.cos( light.angle );
  1410. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  1411. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1412. uniforms.shadow = light.castShadow;
  1413. if ( light.castShadow ) {
  1414. uniforms.shadowBias = light.shadow.bias;
  1415. uniforms.shadowRadius = light.shadow.radius;
  1416. uniforms.shadowMapSize = light.shadow.mapSize;
  1417. }
  1418. _lights.spotShadowMap[ spotLength ] = shadowMap;
  1419. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  1420. _lights.spot[ spotLength ++ ] = uniforms;
  1421. } else if ( light.isRectAreaLight ) {
  1422. var uniforms = lightCache.get( light );
  1423. // (a) intensity controls irradiance of entire light
  1424. uniforms.color
  1425. .copy( color )
  1426. .multiplyScalar( intensity / ( light.width * light.height ) );
  1427. // (b) intensity controls the radiance per light area
  1428. // uniforms.color.copy( color ).multiplyScalar( intensity );
  1429. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1430. uniforms.position.applyMatrix4( viewMatrix );
  1431. // extract local rotation of light to derive width/height half vectors
  1432. _matrix42.identity();
  1433. _matrix4.copy( light.matrixWorld );
  1434. _matrix4.premultiply( viewMatrix );
  1435. _matrix42.extractRotation( _matrix4 );
  1436. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  1437. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  1438. uniforms.halfWidth.applyMatrix4( _matrix42 );
  1439. uniforms.halfHeight.applyMatrix4( _matrix42 );
  1440. // TODO (abelnation): RectAreaLight distance?
  1441. // uniforms.distance = distance;
  1442. _lights.rectArea[ rectAreaLength ++ ] = uniforms;
  1443. } else if ( light.isPointLight ) {
  1444. var uniforms = lightCache.get( light );
  1445. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  1446. uniforms.position.applyMatrix4( viewMatrix );
  1447. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  1448. uniforms.distance = light.distance;
  1449. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  1450. uniforms.shadow = light.castShadow;
  1451. if ( light.castShadow ) {
  1452. uniforms.shadowBias = light.shadow.bias;
  1453. uniforms.shadowRadius = light.shadow.radius;
  1454. uniforms.shadowMapSize = light.shadow.mapSize;
  1455. }
  1456. _lights.pointShadowMap[ pointLength ] = shadowMap;
  1457. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  1458. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  1459. }
  1460. // for point lights we set the shadow matrix to be a translation-only matrix
  1461. // equal to inverse of the light's position
  1462. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  1463. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  1464. _lights.point[ pointLength ++ ] = uniforms;
  1465. } else if ( light.isHemisphereLight ) {
  1466. var uniforms = lightCache.get( light );
  1467. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  1468. uniforms.direction.transformDirection( viewMatrix );
  1469. uniforms.direction.normalize();
  1470. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  1471. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  1472. _lights.hemi[ hemiLength ++ ] = uniforms;
  1473. }
  1474. }
  1475. _lights.ambient[ 0 ] = r;
  1476. _lights.ambient[ 1 ] = g;
  1477. _lights.ambient[ 2 ] = b;
  1478. _lights.directional.length = directionalLength;
  1479. _lights.spot.length = spotLength;
  1480. _lights.rectArea.length = rectAreaLength;
  1481. _lights.point.length = pointLength;
  1482. _lights.hemi.length = hemiLength;
  1483. // TODO (sam-g-steel) why aren't we using join
  1484. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  1485. }
  1486. // GL state setting
  1487. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  1488. state.setCullFace( cullFace );
  1489. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  1490. };
  1491. // Textures
  1492. function allocTextureUnit() {
  1493. var textureUnit = _usedTextureUnits;
  1494. if ( textureUnit >= capabilities.maxTextures ) {
  1495. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  1496. }
  1497. _usedTextureUnits += 1;
  1498. return textureUnit;
  1499. }
  1500. this.allocTextureUnit = allocTextureUnit;
  1501. // this.setTexture2D = setTexture2D;
  1502. this.setTexture2D = ( function() {
  1503. var warned = false;
  1504. // backwards compatibility: peel texture.texture
  1505. return function setTexture2D( texture, slot ) {
  1506. if ( texture && texture.isWebGLRenderTarget ) {
  1507. if ( ! warned ) {
  1508. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  1509. warned = true;
  1510. }
  1511. texture = texture.texture;
  1512. }
  1513. textures.setTexture2D( texture, slot );
  1514. };
  1515. }() );
  1516. this.setTexture = ( function() {
  1517. var warned = false;
  1518. return function setTexture( texture, slot ) {
  1519. if ( ! warned ) {
  1520. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  1521. warned = true;
  1522. }
  1523. textures.setTexture2D( texture, slot );
  1524. };
  1525. }() );
  1526. this.setTextureCube = ( function() {
  1527. var warned = false;
  1528. return function setTextureCube( texture, slot ) {
  1529. // backwards compatibility: peel texture.texture
  1530. if ( texture && texture.isWebGLRenderTargetCube ) {
  1531. if ( ! warned ) {
  1532. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  1533. warned = true;
  1534. }
  1535. texture = texture.texture;
  1536. }
  1537. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  1538. // TODO: unify these code paths
  1539. if ( ( texture && texture.isCubeTexture ) ||
  1540. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  1541. // CompressedTexture can have Array in image :/
  1542. // this function alone should take care of cube textures
  1543. textures.setTextureCube( texture, slot );
  1544. } else {
  1545. // assumed: texture property of THREE.WebGLRenderTargetCube
  1546. textures.setTextureCubeDynamic( texture, slot );
  1547. }
  1548. };
  1549. }() );
  1550. this.getCurrentRenderTarget = function() {
  1551. return _currentRenderTarget;
  1552. };
  1553. this.setRenderTarget = function ( renderTarget ) {
  1554. _currentRenderTarget = renderTarget;
  1555. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  1556. textures.setupRenderTarget( renderTarget );
  1557. }
  1558. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  1559. var framebuffer;
  1560. if ( renderTarget ) {
  1561. var renderTargetProperties = properties.get( renderTarget );
  1562. if ( isCube ) {
  1563. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  1564. } else {
  1565. framebuffer = renderTargetProperties.__webglFramebuffer;
  1566. }
  1567. _currentScissor.copy( renderTarget.scissor );
  1568. _currentScissorTest = renderTarget.scissorTest;
  1569. _currentViewport.copy( renderTarget.viewport );
  1570. } else {
  1571. framebuffer = null;
  1572. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  1573. _currentScissorTest = _scissorTest;
  1574. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  1575. }
  1576. if ( _currentFramebuffer !== framebuffer ) {
  1577. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1578. _currentFramebuffer = framebuffer;
  1579. }
  1580. state.scissor( _currentScissor );
  1581. state.setScissorTest( _currentScissorTest );
  1582. state.viewport( _currentViewport );
  1583. if ( isCube ) {
  1584. var textureProperties = properties.get( renderTarget.texture );
  1585. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  1586. }
  1587. };
  1588. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  1589. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  1590. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  1591. return;
  1592. }
  1593. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  1594. if ( framebuffer ) {
  1595. var restore = false;
  1596. if ( framebuffer !== _currentFramebuffer ) {
  1597. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  1598. restore = true;
  1599. }
  1600. try {
  1601. var texture = renderTarget.texture;
  1602. var textureFormat = texture.format;
  1603. var textureType = texture.type;
  1604. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  1605. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  1606. return;
  1607. }
  1608. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  1609. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  1610. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  1611. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  1612. return;
  1613. }
  1614. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  1615. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  1616. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  1617. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  1618. }
  1619. } else {
  1620. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  1621. }
  1622. } finally {
  1623. if ( restore ) {
  1624. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  1625. }
  1626. }
  1627. }
  1628. };
  1629. // Map three.js constants to WebGL constants
  1630. function paramThreeToGL( p ) {
  1631. var extension;
  1632. if ( p === RepeatWrapping ) return _gl.REPEAT;
  1633. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  1634. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  1635. if ( p === NearestFilter ) return _gl.NEAREST;
  1636. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  1637. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  1638. if ( p === LinearFilter ) return _gl.LINEAR;
  1639. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  1640. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  1641. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  1642. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  1643. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  1644. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  1645. if ( p === ByteType ) return _gl.BYTE;
  1646. if ( p === ShortType ) return _gl.SHORT;
  1647. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  1648. if ( p === IntType ) return _gl.INT;
  1649. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  1650. if ( p === FloatType ) return _gl.FLOAT;
  1651. if ( p === HalfFloatType ) {
  1652. extension = extensions.get( 'OES_texture_half_float' );
  1653. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  1654. }
  1655. if ( p === AlphaFormat ) return _gl.ALPHA;
  1656. if ( p === RGBFormat ) return _gl.RGB;
  1657. if ( p === RGBAFormat ) return _gl.RGBA;
  1658. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  1659. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  1660. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  1661. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  1662. if ( p === AddEquation ) return _gl.FUNC_ADD;
  1663. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  1664. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  1665. if ( p === ZeroFactor ) return _gl.ZERO;
  1666. if ( p === OneFactor ) return _gl.ONE;
  1667. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  1668. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  1669. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  1670. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  1671. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  1672. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  1673. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  1674. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  1675. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  1676. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  1677. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  1678. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  1679. if ( extension !== null ) {
  1680. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  1681. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  1682. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  1683. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  1684. }
  1685. }
  1686. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  1687. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  1688. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  1689. if ( extension !== null ) {
  1690. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  1691. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  1692. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  1693. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  1694. }
  1695. }
  1696. if ( p === RGB_ETC1_Format ) {
  1697. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  1698. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  1699. }
  1700. if ( p === MinEquation || p === MaxEquation ) {
  1701. extension = extensions.get( 'EXT_blend_minmax' );
  1702. if ( extension !== null ) {
  1703. if ( p === MinEquation ) return extension.MIN_EXT;
  1704. if ( p === MaxEquation ) return extension.MAX_EXT;
  1705. }
  1706. }
  1707. if ( p === UnsignedInt248Type ) {
  1708. extension = extensions.get( 'WEBGL_depth_texture' );
  1709. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  1710. }
  1711. return 0;
  1712. }
  1713. }
  1714. export { WebGLRenderer };
粤ICP备19079148号