WebGLRenderer.js 65 KB

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