Renderer.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. import Animation from './Animation.js';
  2. import RenderObjects from './RenderObjects.js';
  3. import Attributes from './Attributes.js';
  4. import Geometries from './Geometries.js';
  5. import Info from './Info.js';
  6. import Pipelines from './Pipelines.js';
  7. import Bindings from './Bindings.js';
  8. import RenderLists from './RenderLists.js';
  9. import RenderContexts from './RenderContexts.js';
  10. import Textures from './Textures.js';
  11. import Background from './Background.js';
  12. import Nodes from './nodes/Nodes.js';
  13. import { Scene, Frustum, Matrix4, Vector2, Vector3, Vector4, Color, DoubleSide, BackSide, FrontSide, SRGBColorSpace, NoToneMapping } from 'three';
  14. const _scene = new Scene();
  15. const _drawingBufferSize = new Vector2();
  16. const _screen = new Vector4();
  17. const _frustum = new Frustum();
  18. const _projScreenMatrix = new Matrix4();
  19. const _vector3 = new Vector3();
  20. class Renderer {
  21. constructor( backend ) {
  22. this.isRenderer = true;
  23. // public
  24. this.domElement = backend.getDomElement();
  25. this.backend = backend;
  26. this.autoClear = true;
  27. this.autoClearColor = true;
  28. this.autoClearDepth = true;
  29. this.autoClearStencil = true;
  30. this.outputColorSpace = SRGBColorSpace;
  31. this.toneMapping = NoToneMapping;
  32. this.toneMappingExposure = 1.0;
  33. this.sortObjects = true;
  34. this.depth = true;
  35. this.stencil = true;
  36. // internals
  37. this._pixelRatio = 1;
  38. this._width = this.domElement.width;
  39. this._height = this.domElement.height;
  40. this._viewport = new Vector4( 0, 0, this._width, this._height );
  41. this._scissor = new Vector4( 0, 0, this._width, this._height );
  42. this._scissorTest = false;
  43. this._info = null;
  44. this._properties = null;
  45. this._attributes = null;
  46. this._geometries = null;
  47. this._nodes = null;
  48. this._bindings = null;
  49. this._objects = null;
  50. this._pipelines = null;
  51. this._renderLists = null;
  52. this._renderContexts = null;
  53. this._textures = null;
  54. this._background = null;
  55. this._animation = new Animation();
  56. this._currentRenderContext = null;
  57. this._lastRenderContext = null;
  58. this._opaqueSort = null;
  59. this._transparentSort = null;
  60. this._clearAlpha = 1;
  61. this._clearColor = new Color( 0x000000 );
  62. this._clearDepth = 1;
  63. this._clearStencil = 0;
  64. this._renderTarget = null;
  65. this._currentActiveCubeFace = 0;
  66. this._initialized = false;
  67. this._initPromise = null;
  68. // backwards compatibility
  69. this.shadowMap = {
  70. enabled: false,
  71. type: null
  72. };
  73. this.xr = {
  74. enabled: false
  75. };
  76. }
  77. async init() {
  78. if ( this._initialized ) {
  79. throw new Error( 'Renderer: Backend has already been initialized.' );
  80. }
  81. if ( this._initPromise !== null ) {
  82. return this._initPromise;
  83. }
  84. this._initPromise = new Promise( async ( resolve, reject ) => {
  85. const backend = this.backend;
  86. try {
  87. await backend.init( this );
  88. } catch ( error ) {
  89. reject( error );
  90. return;
  91. }
  92. this._info = new Info();
  93. this._nodes = new Nodes( this, backend );
  94. this._attributes = new Attributes( backend );
  95. this._background = new Background( this, this._nodes );
  96. this._geometries = new Geometries( this._attributes, this._info );
  97. this._textures = new Textures( backend, this._info );
  98. this._pipelines = new Pipelines( backend, this._nodes );
  99. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this._info );
  100. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this._info );
  101. this._renderLists = new RenderLists();
  102. this._renderContexts = new RenderContexts();
  103. //
  104. this._animation.setNodes( this._nodes );
  105. this._animation.start();
  106. this._initialized = true;
  107. resolve();
  108. } );
  109. return this._initPromise;
  110. }
  111. get coordinateSystem() {
  112. return this.backend.coordinateSystem;
  113. }
  114. async compile( /*scene, camera*/ ) {
  115. console.warn( 'THREE.Renderer: .compile() is not implemented yet.' );
  116. }
  117. async render( scene, camera ) {
  118. if ( this._initialized === false ) await this.init();
  119. // preserve render tree
  120. const nodeFrame = this._nodes.nodeFrame;
  121. const previousRenderId = nodeFrame.renderId;
  122. const previousRenderState = this._currentRenderContext;
  123. //
  124. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  125. const renderTarget = this._renderTarget;
  126. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  127. const activeCubeFace = this._activeCubeFace;
  128. this._currentRenderContext = renderContext;
  129. nodeFrame.renderId ++;
  130. //
  131. const coordinateSystem = this.coordinateSystem;
  132. if ( camera.coordinateSystem !== coordinateSystem ) {
  133. camera.coordinateSystem = coordinateSystem;
  134. camera.updateProjectionMatrix();
  135. }
  136. //
  137. if ( this._animation.isAnimating === false ) nodeFrame.update();
  138. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  139. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  140. if ( this._info.autoReset === true ) this._info.reset();
  141. this._info.render.frame ++;
  142. //
  143. let viewport = this._viewport;
  144. let scissor = this._scissor;
  145. let pixelRatio = this._pixelRatio;
  146. if ( renderTarget !== null ) {
  147. viewport = renderTarget.viewport;
  148. scissor = renderTarget.scissor;
  149. pixelRatio = 1;
  150. }
  151. this.getDrawingBufferSize( _drawingBufferSize );
  152. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  153. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  154. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  155. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  156. renderContext.viewportValue.minDepth = minDepth;
  157. renderContext.viewportValue.maxDepth = maxDepth;
  158. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  159. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  160. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  161. renderContext.depth = this.depth;
  162. renderContext.stencil = this.stencil;
  163. //
  164. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  165. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  166. const renderList = this._renderLists.get( scene, camera );
  167. renderList.init();
  168. this._projectObject( scene, camera, 0, renderList );
  169. renderList.finish();
  170. if ( this.sortObjects === true ) {
  171. renderList.sort( this._opaqueSort, this._transparentSort );
  172. }
  173. //
  174. if ( renderTarget !== null ) {
  175. this._textures.updateRenderTarget( renderTarget );
  176. const renderTargetData = this._textures.get( renderTarget );
  177. renderContext.texture = renderTargetData.texture;
  178. renderContext.depthTexture = renderTargetData.depthTexture;
  179. } else {
  180. renderContext.texture = null;
  181. renderContext.depthTexture = null;
  182. }
  183. renderContext.activeCubeFace = activeCubeFace;
  184. //
  185. this._nodes.updateScene( sceneRef );
  186. //
  187. this._background.update( sceneRef, renderList, renderContext );
  188. //
  189. this.backend.beginRender( renderContext );
  190. // process render lists
  191. const opaqueObjects = renderList.opaque;
  192. const transparentObjects = renderList.transparent;
  193. const lightsNode = renderList.lightsNode;
  194. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  195. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  196. // finish render pass
  197. this.backend.finishRender( renderContext );
  198. // restore render tree
  199. nodeFrame.renderId = previousRenderId;
  200. this._currentRenderContext = previousRenderState;
  201. this._lastRenderContext = renderContext;
  202. }
  203. setAnimationLoop( callback ) {
  204. if ( this._initialized === false ) this.init();
  205. const animation = this._animation;
  206. animation.setAnimationLoop( callback );
  207. ( callback === null ) ? animation.stop() : animation.start();
  208. }
  209. getArrayBuffer( attribute ) { // @deprecated, r155
  210. console.warn( 'THREE.Renderer: getArrayBuffer() is deprecated. Use getArrayBufferAsync() instead.' );
  211. return this.getArrayBufferAsync( attribute );
  212. }
  213. async getArrayBufferAsync( attribute ) {
  214. return await this.backend.getArrayBufferAsync( attribute );
  215. }
  216. getContext() {
  217. return this._context;
  218. }
  219. getPixelRatio() {
  220. return this._pixelRatio;
  221. }
  222. getDrawingBufferSize( target ) {
  223. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  224. }
  225. getSize( target ) {
  226. return target.set( this._width, this._height );
  227. }
  228. setPixelRatio( value = 1 ) {
  229. this._pixelRatio = value;
  230. this.setSize( this._width, this._height, false );
  231. }
  232. setDrawingBufferSize( width, height, pixelRatio ) {
  233. this._width = width;
  234. this._height = height;
  235. this._pixelRatio = pixelRatio;
  236. this.domElement.width = Math.floor( width * pixelRatio );
  237. this.domElement.height = Math.floor( height * pixelRatio );
  238. this.setViewport( 0, 0, width, height );
  239. if ( this._initialized ) this.backend.updateSize();
  240. }
  241. setSize( width, height, updateStyle = true ) {
  242. this._width = width;
  243. this._height = height;
  244. this.domElement.width = Math.floor( width * this._pixelRatio );
  245. this.domElement.height = Math.floor( height * this._pixelRatio );
  246. if ( updateStyle === true ) {
  247. this.domElement.style.width = width + 'px';
  248. this.domElement.style.height = height + 'px';
  249. }
  250. this.setViewport( 0, 0, width, height );
  251. if ( this._initialized ) this.backend.updateSize();
  252. }
  253. setOpaqueSort( method ) {
  254. this._opaqueSort = method;
  255. }
  256. setTransparentSort( method ) {
  257. this._transparentSort = method;
  258. }
  259. getScissor( target ) {
  260. const scissor = this._scissor;
  261. target.x = scissor.x;
  262. target.y = scissor.y;
  263. target.width = scissor.width;
  264. target.height = scissor.height;
  265. return target;
  266. }
  267. setScissor( x, y, width, height ) {
  268. const scissor = this._scissor;
  269. if ( x.isVector4 ) {
  270. scissor.copy( x );
  271. } else {
  272. scissor.set( x, y, width, height );
  273. }
  274. }
  275. getScissorTest() {
  276. return this._scissorTest;
  277. }
  278. setScissorTest( boolean ) {
  279. this._scissorTest = boolean;
  280. }
  281. getViewport( target ) {
  282. return target.copy( this._viewport );
  283. }
  284. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  285. const viewport = this._viewport;
  286. if ( x.isVector4 ) {
  287. viewport.copy( x );
  288. } else {
  289. viewport.set( x, y, width, height );
  290. }
  291. viewport.minDepth = minDepth;
  292. viewport.maxDepth = maxDepth;
  293. }
  294. getClearColor( target ) {
  295. return target.copy( this._clearColor );
  296. }
  297. setClearColor( color, alpha = 1 ) {
  298. this._clearColor.set( color );
  299. this._clearAlpha = alpha;
  300. }
  301. getClearAlpha() {
  302. return this._clearAlpha;
  303. }
  304. setClearAlpha( alpha ) {
  305. this._clearAlpha = alpha;
  306. }
  307. getClearDepth() {
  308. return this._clearDepth;
  309. }
  310. setClearDepth( depth ) {
  311. this._clearDepth = depth;
  312. }
  313. getClearStencil() {
  314. return this._clearStencil;
  315. }
  316. setClearStencil( stencil ) {
  317. this._clearStencil = stencil;
  318. }
  319. clear( color = true, depth = true, stencil = true ) {
  320. const renderContext = this._currentRenderContext || this._lastRenderContext;
  321. if ( renderContext ) this.backend.clear( renderContext, color, depth, stencil );
  322. }
  323. clearColor() {
  324. this.clear( true, false, false );
  325. }
  326. clearDepth() {
  327. this.clear( false, true, false );
  328. }
  329. clearStencil() {
  330. this.clear( false, false, true );
  331. }
  332. dispose() {
  333. this._objects.dispose();
  334. this._properties.dispose();
  335. this._pipelines.dispose();
  336. this._nodes.dispose();
  337. this._bindings.dispose();
  338. this._info.dispose();
  339. this._renderLists.dispose();
  340. this._renderContexts.dispose();
  341. this._textures.dispose();
  342. this.setRenderTarget( null );
  343. this.setAnimationLoop( null );
  344. }
  345. setRenderTarget( renderTarget, activeCubeFace = 0 ) {
  346. this._renderTarget = renderTarget;
  347. this._activeCubeFace = activeCubeFace;
  348. }
  349. async compute( computeNodes ) {
  350. if ( this._initialized === false ) await this.init();
  351. const backend = this.backend;
  352. const pipelines = this._pipelines;
  353. const bindings = this._bindings;
  354. const nodes = this._nodes;
  355. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  356. backend.beginCompute( computeNodes );
  357. for ( const computeNode of computeList ) {
  358. // onInit
  359. if ( pipelines.has( computeNode ) === false ) {
  360. const dispose = () => {
  361. computeNode.removeEventListener( 'dispose', dispose );
  362. pipelines.delete( computeNode );
  363. bindings.delete( computeNode );
  364. nodes.delete( computeNode );
  365. };
  366. computeNode.addEventListener( 'dispose', dispose );
  367. //
  368. computeNode.onInit( { renderer: this } );
  369. }
  370. nodes.updateForCompute( computeNode );
  371. bindings.updateForCompute( computeNode );
  372. const computePipeline = pipelines.getForCompute( computeNode );
  373. const computeBindings = bindings.getForCompute( computeNode );
  374. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  375. }
  376. backend.finishCompute( computeNodes );
  377. }
  378. getRenderTarget() {
  379. return this._renderTarget;
  380. }
  381. hasFeature( name ) {
  382. return this.backend.hasFeature( name );
  383. }
  384. copyFramebufferToTexture( framebufferTexture ) {
  385. const renderContext = this._currentRenderContext || this._lastRenderContext;
  386. this._textures.updateTexture( framebufferTexture );
  387. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext );
  388. }
  389. readRenderTargetPixelsAsync( renderTarget, x, y, width, height ) {
  390. return this.backend.copyTextureToBuffer( renderTarget.texture, x, y, width, height );
  391. }
  392. _projectObject( object, camera, groupOrder, renderList ) {
  393. if ( object.visible === false ) return;
  394. const visible = object.layers.test( camera.layers );
  395. if ( visible ) {
  396. if ( object.isGroup ) {
  397. groupOrder = object.renderOrder;
  398. } else if ( object.isLOD ) {
  399. if ( object.autoUpdate === true ) object.update( camera );
  400. } else if ( object.isLight ) {
  401. renderList.pushLight( object );
  402. } else if ( object.isSprite ) {
  403. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  404. if ( this.sortObjects === true ) {
  405. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  406. }
  407. const geometry = object.geometry;
  408. const material = object.material;
  409. if ( material.visible ) {
  410. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  411. }
  412. }
  413. } else if ( object.isLineLoop ) {
  414. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  415. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  416. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  417. const geometry = object.geometry;
  418. const material = object.material;
  419. if ( this.sortObjects === true ) {
  420. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  421. _vector3
  422. .copy( geometry.boundingSphere.center )
  423. .applyMatrix4( object.matrixWorld )
  424. .applyMatrix4( _projScreenMatrix );
  425. }
  426. if ( Array.isArray( material ) ) {
  427. const groups = geometry.groups;
  428. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  429. const group = groups[ i ];
  430. const groupMaterial = material[ group.materialIndex ];
  431. if ( groupMaterial && groupMaterial.visible ) {
  432. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  433. }
  434. }
  435. } else if ( material.visible ) {
  436. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  437. }
  438. }
  439. }
  440. }
  441. const children = object.children;
  442. for ( let i = 0, l = children.length; i < l; i ++ ) {
  443. this._projectObject( children[ i ], camera, groupOrder, renderList );
  444. }
  445. }
  446. _renderObjects( renderList, camera, scene, lightsNode ) {
  447. // process renderable objects
  448. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  449. const renderItem = renderList[ i ];
  450. // @TODO: Add support for multiple materials per object. This will require to extract
  451. // the material from the renderItem object and pass it with its group data to _renderObject().
  452. const { object, geometry, material, group } = renderItem;
  453. if ( camera.isArrayCamera ) {
  454. const cameras = camera.cameras;
  455. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  456. const camera2 = cameras[ j ];
  457. if ( object.layers.test( camera2.layers ) ) {
  458. const vp = camera2.viewport;
  459. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  460. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  461. const viewportValue = this._currentRenderContext.viewportValue;
  462. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  463. viewportValue.minDepth = minDepth;
  464. viewportValue.maxDepth = maxDepth;
  465. this.backend.updateViewport( this._currentRenderContext );
  466. this._renderObject( object, scene, camera2, geometry, material, group, lightsNode );
  467. }
  468. }
  469. } else {
  470. this._renderObject( object, scene, camera, geometry, material, group, lightsNode );
  471. }
  472. }
  473. }
  474. _getRenderObject( object, material, scene, camera, lightsNode, passId ) {
  475. return this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  476. }
  477. _renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  478. material = scene.overrideMaterial !== null ? scene.overrideMaterial : material;
  479. //
  480. object.onBeforeRender( this, scene, camera, geometry, material, group );
  481. //
  482. const renderObject = this._getRenderObject( object, material, scene, camera, lightsNode );
  483. this._nodes.updateBefore( renderObject );
  484. //
  485. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  486. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  487. //
  488. material.onBeforeRender( this, scene, camera, geometry, material, group );
  489. //
  490. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  491. material.side = BackSide;
  492. this._renderObjectDirect( this._getRenderObject( object, material, scene, camera, lightsNode, 'backSide' ) ); // create backSide pass id
  493. material.side = FrontSide;
  494. this._renderObjectDirect( renderObject ); // use default pass id
  495. material.side = DoubleSide;
  496. } else {
  497. this._renderObjectDirect( renderObject );
  498. }
  499. //
  500. object.onAfterRender( this, scene, camera, geometry, material, group );
  501. }
  502. _renderObjectDirect( renderObject ) {
  503. this._nodes.updateForRender( renderObject );
  504. this._geometries.updateForRender( renderObject );
  505. this._bindings.updateForRender( renderObject );
  506. //
  507. this.backend.draw( renderObject, this._info );
  508. }
  509. }
  510. export default Renderer;