WebGLRenderer.js 67 KB

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