1
0

WebGLRenderer.js 69 KB

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