WebGLRenderer.js 59 KB

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