WebGLRenderer.js 57 KB

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