WebGPURenderer.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. import { GPUIndexFormat, GPUTextureFormat, GPUFeatureName } from './constants.js';
  2. import WebGPUAnimation from './WebGPUAnimation.js';
  3. import WebGPURenderObjects from './WebGPURenderObjects.js';
  4. import WebGPUAttributes from './WebGPUAttributes.js';
  5. import WebGPUGeometries from './WebGPUGeometries.js';
  6. import WebGPUInfo from './WebGPUInfo.js';
  7. import WebGPUProperties from './WebGPUProperties.js';
  8. import WebGPURenderPipelines from './WebGPURenderPipelines.js';
  9. import WebGPUComputePipelines from './WebGPUComputePipelines.js';
  10. import WebGPUBindings from './WebGPUBindings.js';
  11. import WebGPURenderLists from './WebGPURenderLists.js';
  12. import WebGPURenderStates from './WebGPURenderStates.js';
  13. import WebGPUTextures from './WebGPUTextures.js';
  14. import WebGPUBackground from './WebGPUBackground.js';
  15. import WebGPUNodes from './nodes/WebGPUNodes.js';
  16. import WebGPUUtils from './WebGPUUtils.js';
  17. import { Frustum, Matrix4, Vector3, Color, SRGBColorSpace, NoToneMapping, DepthFormat } from 'three';
  18. console.info( 'THREE.WebGPURenderer: Modified Matrix4.makePerspective() and Matrix4.makeOrtographic() to work with WebGPU, see https://github.com/mrdoob/three.js/issues/20276.' );
  19. Matrix4.prototype.makePerspective = function ( left, right, top, bottom, near, far ) {
  20. const te = this.elements;
  21. const x = 2 * near / ( right - left );
  22. const y = 2 * near / ( top - bottom );
  23. const a = ( right + left ) / ( right - left );
  24. const b = ( top + bottom ) / ( top - bottom );
  25. const c = - far / ( far - near );
  26. const d = - far * near / ( far - near );
  27. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  28. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  29. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  30. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  31. return this;
  32. };
  33. Matrix4.prototype.makeOrthographic = function ( left, right, top, bottom, near, far ) {
  34. const te = this.elements;
  35. const w = 1.0 / ( right - left );
  36. const h = 1.0 / ( top - bottom );
  37. const p = 1.0 / ( far - near );
  38. const x = ( right + left ) * w;
  39. const y = ( top + bottom ) * h;
  40. const z = near * p;
  41. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  42. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  43. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 1 * p; te[ 14 ] = - z;
  44. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  45. return this;
  46. };
  47. Frustum.prototype.setFromProjectionMatrix = function ( m ) {
  48. const planes = this.planes;
  49. const me = m.elements;
  50. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  51. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  52. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  53. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  54. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  55. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  56. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  57. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  58. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  59. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  60. return this;
  61. };
  62. const _frustum = new Frustum();
  63. const _projScreenMatrix = new Matrix4();
  64. const _vector3 = new Vector3();
  65. class WebGPURenderer {
  66. constructor( parameters = {} ) {
  67. this.isWebGPURenderer = true;
  68. // public
  69. this.domElement = ( parameters.canvas !== undefined ) ? parameters.canvas : this._createCanvasElement();
  70. this.autoClear = true;
  71. this.autoClearColor = true;
  72. this.autoClearDepth = true;
  73. this.autoClearStencil = true;
  74. this.outputColorSpace = SRGBColorSpace;
  75. this.toneMapping = NoToneMapping;
  76. this.toneMappingExposure = 1.0;
  77. this.sortObjects = true;
  78. // internals
  79. this._parameters = Object.assign( {}, parameters );
  80. this._pixelRatio = 1;
  81. this._width = this.domElement.width;
  82. this._height = this.domElement.height;
  83. this._viewport = null;
  84. this._scissor = null;
  85. this._adapter = null;
  86. this._device = null;
  87. this._context = null;
  88. this._colorBuffer = null;
  89. this._depthBuffer = null;
  90. this._info = null;
  91. this._properties = null;
  92. this._attributes = null;
  93. this._geometries = null;
  94. this._nodes = null;
  95. this._bindings = null;
  96. this._objects = null;
  97. this._renderPipelines = null;
  98. this._computePipelines = null;
  99. this._renderLists = null;
  100. this._renderStates = null;
  101. this._textures = null;
  102. this._background = null;
  103. this._animation = new WebGPUAnimation();
  104. this._currentRenderState = null;
  105. this._currentRenderList = null;
  106. this._opaqueSort = null;
  107. this._transparentSort = null;
  108. this._clearAlpha = 1;
  109. this._clearColor = new Color( 0x000000 );
  110. this._clearDepth = 1;
  111. this._clearStencil = 0;
  112. this._renderTarget = null;
  113. this._initialized = false;
  114. // some parameters require default values other than "undefined"
  115. this._parameters.antialias = ( parameters.antialias === true );
  116. if ( this._parameters.antialias === true ) {
  117. this._parameters.sampleCount = ( parameters.sampleCount === undefined ) ? 4 : parameters.sampleCount;
  118. } else {
  119. this._parameters.sampleCount = 1;
  120. }
  121. this._parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  122. // backwards compatibility
  123. this.shadow = {
  124. shadowMap: {}
  125. };
  126. }
  127. async init() {
  128. if ( this._initialized === true ) {
  129. throw new Error( 'WebGPURenderer: Device has already been initialized.' );
  130. }
  131. const parameters = this._parameters;
  132. const adapterOptions = {
  133. powerPreference: parameters.powerPreference
  134. };
  135. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  136. if ( adapter === null ) {
  137. throw new Error( 'WebGPURenderer: Unable to create WebGPU adapter.' );
  138. }
  139. // feature support
  140. const features = Object.values( GPUFeatureName );
  141. const supportedFeatures = [];
  142. for ( const name of features ) {
  143. if ( adapter.features.has( name ) ) {
  144. supportedFeatures.push( name );
  145. }
  146. }
  147. const deviceDescriptor = {
  148. requiredFeatures: supportedFeatures,
  149. requiredLimits: parameters.requiredLimits
  150. };
  151. const device = await adapter.requestDevice( deviceDescriptor );
  152. const context = ( parameters.context !== undefined ) ? parameters.context : this.domElement.getContext( 'webgpu' );
  153. context.configure( {
  154. device,
  155. format: GPUTextureFormat.BGRA8Unorm, // this is the only valid context format right now (r121)
  156. alphaMode: 'premultiplied'
  157. } );
  158. this._adapter = adapter;
  159. this._device = device;
  160. this._context = context;
  161. this._info = new WebGPUInfo();
  162. this._properties = new WebGPUProperties();
  163. this._attributes = new WebGPUAttributes( device );
  164. this._geometries = new WebGPUGeometries( this._attributes, this._properties, this._info );
  165. this._textures = new WebGPUTextures( device, this._properties, this._info );
  166. this._utils = new WebGPUUtils( this );
  167. this._nodes = new WebGPUNodes( this, this._properties );
  168. this._objects = new WebGPURenderObjects( this, this._nodes, this._geometries, this._info );
  169. this._computePipelines = new WebGPUComputePipelines( device, this._nodes );
  170. this._renderPipelines = new WebGPURenderPipelines( device, this._nodes, this._utils );
  171. this._bindings = this._renderPipelines.bindings = new WebGPUBindings( device, this._info, this._properties, this._textures, this._renderPipelines, this._computePipelines, this._attributes, this._nodes );
  172. this._renderLists = new WebGPURenderLists();
  173. this._renderStates = new WebGPURenderStates();
  174. this._background = new WebGPUBackground( this, this._properties );
  175. //
  176. this._setupColorBuffer();
  177. this._setupDepthBuffer();
  178. this._animation.setNodes( this._nodes );
  179. this._animation.start();
  180. this._initialized = true;
  181. }
  182. async render( scene, camera ) {
  183. if ( this._initialized === false ) await this.init();
  184. //
  185. const nodeFrame = this._nodes.nodeFrame;
  186. const previousRenderId = nodeFrame.renderId;
  187. nodeFrame.renderId ++;
  188. if ( this._animation.isAnimating === false ) nodeFrame.update();
  189. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  190. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  191. if ( this._info.autoReset === true ) this._info.reset();
  192. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  193. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  194. this._currentRenderList = this._renderLists.get( scene, camera );
  195. this._currentRenderList.init();
  196. this._currentRenderState = this._renderStates.get( scene, camera );
  197. this._currentRenderState.init();
  198. this._projectObject( scene, camera, 0 );
  199. this._currentRenderList.finish();
  200. if ( this.sortObjects === true ) {
  201. this._currentRenderList.sort( this._opaqueSort, this._transparentSort );
  202. }
  203. // prepare render pass descriptor
  204. const renderPassDescriptor = {
  205. colorAttachments: [ {
  206. view: null
  207. } ],
  208. depthStencilAttachment: {
  209. view: null
  210. }
  211. };
  212. const renderAttachments = {
  213. depth: true,
  214. stencil: true
  215. };
  216. const colorAttachment = renderPassDescriptor.colorAttachments[ 0 ];
  217. const depthStencilAttachment = renderPassDescriptor.depthStencilAttachment;
  218. const renderTarget = this._renderTarget;
  219. if ( renderTarget !== null ) {
  220. this._textures.initRenderTarget( renderTarget );
  221. // @TODO: Support RenderTarget with antialiasing.
  222. const renderTargetProperties = this._properties.get( renderTarget );
  223. colorAttachment.view = renderTargetProperties.colorTextureGPU.createView();
  224. depthStencilAttachment.view = renderTargetProperties.depthTextureGPU.createView();
  225. renderAttachments.stencil = renderTarget.depthTexture ? renderTarget.depthTexture.format !== DepthFormat : true;
  226. } else {
  227. if ( this._parameters.antialias === true ) {
  228. colorAttachment.view = this._colorBuffer.createView();
  229. colorAttachment.resolveTarget = this._context.getCurrentTexture().createView();
  230. } else {
  231. colorAttachment.view = this._context.getCurrentTexture().createView();
  232. colorAttachment.resolveTarget = undefined;
  233. }
  234. depthStencilAttachment.view = this._depthBuffer.createView();
  235. }
  236. //
  237. this._nodes.updateEnvironment( scene );
  238. this._nodes.updateFog( scene );
  239. this._nodes.updateBackground( scene );
  240. this._nodes.updateToneMapping();
  241. //
  242. this._background.update( this._currentRenderList, scene, renderPassDescriptor, renderAttachments );
  243. // start render pass
  244. const device = this._device;
  245. const cmdEncoder = device.createCommandEncoder( {} );
  246. const passEncoder = cmdEncoder.beginRenderPass( renderPassDescriptor );
  247. // global rasterization settings for all renderable objects
  248. const vp = this._viewport;
  249. if ( vp !== null ) {
  250. const width = Math.floor( vp.width * this._pixelRatio );
  251. const height = Math.floor( vp.height * this._pixelRatio );
  252. passEncoder.setViewport( vp.x, vp.y, width, height, vp.minDepth, vp.maxDepth );
  253. }
  254. const sc = this._scissor;
  255. if ( sc !== null ) {
  256. const width = Math.floor( sc.width * this._pixelRatio );
  257. const height = Math.floor( sc.height * this._pixelRatio );
  258. passEncoder.setScissorRect( sc.x, sc.y, width, height );
  259. }
  260. // lights node
  261. const lightsNode = this._currentRenderState.getLightsNode();
  262. // process render lists
  263. const opaqueObjects = this._currentRenderList.opaque;
  264. const transparentObjects = this._currentRenderList.transparent;
  265. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, scene, lightsNode, passEncoder );
  266. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, scene, lightsNode, passEncoder );
  267. // finish render pass
  268. passEncoder.end();
  269. device.queue.submit( [ cmdEncoder.finish() ] );
  270. nodeFrame.renderId = previousRenderId;
  271. }
  272. setAnimationLoop( callback ) {
  273. if ( this._initialized === false ) this.init();
  274. const animation = this._animation;
  275. animation.setAnimationLoop( callback );
  276. ( callback === null ) ? animation.stop() : animation.start();
  277. }
  278. async getArrayBuffer( attribute ) {
  279. return await this._attributes.getArrayBuffer( attribute );
  280. }
  281. getContext() {
  282. return this._context;
  283. }
  284. getPixelRatio() {
  285. return this._pixelRatio;
  286. }
  287. getDrawingBufferSize( target ) {
  288. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  289. }
  290. getSize( target ) {
  291. return target.set( this._width, this._height );
  292. }
  293. setPixelRatio( value = 1 ) {
  294. this._pixelRatio = value;
  295. this.setSize( this._width, this._height, false );
  296. }
  297. setDrawingBufferSize( width, height, pixelRatio ) {
  298. this._width = width;
  299. this._height = height;
  300. this._pixelRatio = pixelRatio;
  301. this.domElement.width = Math.floor( width * pixelRatio );
  302. this.domElement.height = Math.floor( height * pixelRatio );
  303. this._configureContext();
  304. this._setupColorBuffer();
  305. this._setupDepthBuffer();
  306. }
  307. setSize( width, height, updateStyle = true ) {
  308. this._width = width;
  309. this._height = height;
  310. this.domElement.width = Math.floor( width * this._pixelRatio );
  311. this.domElement.height = Math.floor( height * this._pixelRatio );
  312. if ( updateStyle === true ) {
  313. this.domElement.style.width = width + 'px';
  314. this.domElement.style.height = height + 'px';
  315. }
  316. this._configureContext();
  317. this._setupColorBuffer();
  318. this._setupDepthBuffer();
  319. }
  320. setOpaqueSort( method ) {
  321. this._opaqueSort = method;
  322. }
  323. setTransparentSort( method ) {
  324. this._transparentSort = method;
  325. }
  326. getScissor( target ) {
  327. const scissor = this._scissor;
  328. target.x = scissor.x;
  329. target.y = scissor.y;
  330. target.width = scissor.width;
  331. target.height = scissor.height;
  332. return target;
  333. }
  334. setScissor( x, y, width, height ) {
  335. if ( x === null ) {
  336. this._scissor = null;
  337. } else {
  338. this._scissor = {
  339. x: x,
  340. y: y,
  341. width: width,
  342. height: height
  343. };
  344. }
  345. }
  346. getViewport( target ) {
  347. const viewport = this._viewport;
  348. target.x = viewport.x;
  349. target.y = viewport.y;
  350. target.width = viewport.width;
  351. target.height = viewport.height;
  352. target.minDepth = viewport.minDepth;
  353. target.maxDepth = viewport.maxDepth;
  354. return target;
  355. }
  356. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  357. if ( x === null ) {
  358. this._viewport = null;
  359. } else {
  360. this._viewport = {
  361. x: x,
  362. y: y,
  363. width: width,
  364. height: height,
  365. minDepth: minDepth,
  366. maxDepth: maxDepth
  367. };
  368. }
  369. }
  370. getClearColor( target ) {
  371. return target.copy( this._clearColor );
  372. }
  373. setClearColor( color, alpha = 1 ) {
  374. this._clearColor.set( color );
  375. this._clearAlpha = alpha;
  376. }
  377. getClearAlpha() {
  378. return this._clearAlpha;
  379. }
  380. setClearAlpha( alpha ) {
  381. this._clearAlpha = alpha;
  382. }
  383. getClearDepth() {
  384. return this._clearDepth;
  385. }
  386. setClearDepth( depth ) {
  387. this._clearDepth = depth;
  388. }
  389. getClearStencil() {
  390. return this._clearStencil;
  391. }
  392. setClearStencil( stencil ) {
  393. this._clearStencil = stencil;
  394. }
  395. clear() {
  396. if ( this._background ) this._background.clear();
  397. }
  398. dispose() {
  399. this._objects.dispose();
  400. this._properties.dispose();
  401. this._renderPipelines.dispose();
  402. this._computePipelines.dispose();
  403. this._nodes.dispose();
  404. this._bindings.dispose();
  405. this._info.dispose();
  406. this._renderLists.dispose();
  407. this._renderStates.dispose();
  408. this._textures.dispose();
  409. this.setRenderTarget( null );
  410. this.setAnimationLoop( null );
  411. }
  412. setRenderTarget( renderTarget ) {
  413. this._renderTarget = renderTarget;
  414. }
  415. async compute( ...computeNodes ) {
  416. if ( this._initialized === false ) await this.init();
  417. const device = this._device;
  418. const computePipelines = this._computePipelines;
  419. const cmdEncoder = device.createCommandEncoder( {} );
  420. const passEncoder = cmdEncoder.beginComputePass();
  421. for ( const computeNode of computeNodes ) {
  422. // onInit
  423. if ( computePipelines.has( computeNode ) === false ) {
  424. computeNode.onInit( { renderer: this } );
  425. }
  426. // pipeline
  427. const pipeline = computePipelines.get( computeNode );
  428. passEncoder.setPipeline( pipeline );
  429. // node
  430. //this._nodes.update( computeNode );
  431. // bind group
  432. const bindGroup = this._bindings.getForCompute( computeNode ).group;
  433. this._bindings.update( computeNode );
  434. passEncoder.setBindGroup( 0, bindGroup );
  435. passEncoder.dispatchWorkgroups( computeNode.dispatchCount );
  436. }
  437. passEncoder.end();
  438. device.queue.submit( [ cmdEncoder.finish() ] );
  439. }
  440. getRenderTarget() {
  441. return this._renderTarget;
  442. }
  443. hasFeature( name ) {
  444. if ( this._initialized === false ) {
  445. throw new Error( 'THREE.WebGPURenderer: Renderer must be initialized before testing features.' );
  446. }
  447. //
  448. const features = Object.values( GPUFeatureName );
  449. if ( features.includes( name ) === false ) {
  450. throw new Error( 'THREE.WebGPURenderer: Unknown WebGPU GPU feature: ' + name );
  451. }
  452. //
  453. return this._adapter.features.has( name );
  454. }
  455. _projectObject( object, camera, groupOrder ) {
  456. const currentRenderList = this._currentRenderList;
  457. const currentRenderState = this._currentRenderState;
  458. if ( object.visible === false ) return;
  459. const visible = object.layers.test( camera.layers );
  460. if ( visible ) {
  461. if ( object.isGroup ) {
  462. groupOrder = object.renderOrder;
  463. } else if ( object.isLOD ) {
  464. if ( object.autoUpdate === true ) object.update( camera );
  465. } else if ( object.isLight ) {
  466. currentRenderState.pushLight( object );
  467. if ( object.castShadow ) {
  468. //currentRenderState.pushShadow( object );
  469. }
  470. } else if ( object.isSprite ) {
  471. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  472. if ( this.sortObjects === true ) {
  473. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  474. }
  475. const geometry = object.geometry;
  476. const material = object.material;
  477. if ( material.visible ) {
  478. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  479. }
  480. }
  481. } else if ( object.isLineLoop ) {
  482. console.error( 'THREE.WebGPURenderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  483. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  484. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  485. if ( this.sortObjects === true ) {
  486. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  487. }
  488. const geometry = object.geometry;
  489. const material = object.material;
  490. if ( Array.isArray( material ) ) {
  491. const groups = geometry.groups;
  492. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  493. const group = groups[ i ];
  494. const groupMaterial = material[ group.materialIndex ];
  495. if ( groupMaterial && groupMaterial.visible ) {
  496. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  497. }
  498. }
  499. } else if ( material.visible ) {
  500. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  501. }
  502. }
  503. }
  504. }
  505. const children = object.children;
  506. for ( let i = 0, l = children.length; i < l; i ++ ) {
  507. this._projectObject( children[ i ], camera, groupOrder );
  508. }
  509. }
  510. _renderObjects( renderList, camera, scene, lightsNode, passEncoder ) {
  511. // process renderable objects
  512. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  513. const renderItem = renderList[ i ];
  514. // @TODO: Add support for multiple materials per object. This will require to extract
  515. // the material from the renderItem object and pass it with its group data to _renderObject().
  516. const { object, geometry, material, group } = renderItem;
  517. if ( camera.isArrayCamera ) {
  518. const cameras = camera.cameras;
  519. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  520. const camera2 = cameras[ j ];
  521. if ( object.layers.test( camera2.layers ) ) {
  522. const vp = camera2.viewport;
  523. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  524. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  525. passEncoder.setViewport( vp.x, vp.y, vp.width, vp.height, minDepth, maxDepth );
  526. this._renderObject( object, scene, camera2, geometry, material, group, lightsNode, passEncoder );
  527. }
  528. }
  529. } else {
  530. this._renderObject( object, scene, camera, geometry, material, group, lightsNode, passEncoder );
  531. }
  532. }
  533. }
  534. _renderObject( object, scene, camera, geometry, material, group, lightsNode, passEncoder ) {
  535. const info = this._info;
  536. material = scene.overrideMaterial !== null ? scene.overrideMaterial : material;
  537. //
  538. object.onBeforeRender( this, scene, camera, geometry, material, group );
  539. //
  540. const renderObject = this._getRenderObject( object, material, scene, camera, lightsNode );
  541. //
  542. this._nodes.updateBefore( renderObject );
  543. //
  544. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  545. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  546. // updates
  547. this._nodes.update( renderObject );
  548. this._geometries.update( renderObject );
  549. this._bindings.update( renderObject );
  550. // pipeline
  551. const renderPipeline = this._renderPipelines.get( renderObject );
  552. passEncoder.setPipeline( renderPipeline.pipeline );
  553. // bind group
  554. const bindGroup = this._bindings.get( renderObject ).group;
  555. passEncoder.setBindGroup( 0, bindGroup );
  556. // index
  557. const index = this._geometries.getIndex( renderObject );
  558. const hasIndex = ( index !== null );
  559. if ( hasIndex === true ) {
  560. this._setupIndexBuffer( index, passEncoder );
  561. }
  562. // vertex buffers
  563. this._setupVertexBuffers( geometry.attributes, passEncoder, renderPipeline );
  564. // draw
  565. const drawRange = geometry.drawRange;
  566. const firstVertex = drawRange.start;
  567. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.isInstancedMesh ? object.count : 1 );
  568. if ( hasIndex === true ) {
  569. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  570. passEncoder.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  571. info.update( object, indexCount, instanceCount );
  572. } else {
  573. const positionAttribute = geometry.attributes.position;
  574. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  575. passEncoder.draw( vertexCount, instanceCount, firstVertex, 0 );
  576. info.update( object, vertexCount, instanceCount );
  577. }
  578. }
  579. _getRenderObject( object, material, scene, camera, lightsNode ) {
  580. const renderObject = this._objects.get( object, material, scene, camera, lightsNode );
  581. const renderObjectProperties = this._properties.get( renderObject );
  582. if ( renderObjectProperties.initialized !== true ) {
  583. renderObjectProperties.initialized = true;
  584. const dispose = () => {
  585. this._renderPipelines.remove( renderObject );
  586. this._nodes.remove( renderObject );
  587. this._properties.remove( renderObject );
  588. this._objects.remove( object, material, scene, camera, lightsNode );
  589. renderObject.material.removeEventListener( 'dispose', dispose );
  590. };
  591. renderObject.material.addEventListener( 'dispose', dispose );
  592. }
  593. const cacheKey = renderObject.getCacheKey();
  594. if ( renderObjectProperties.cacheKey !== cacheKey ) {
  595. renderObjectProperties.cacheKey = cacheKey;
  596. this._renderPipelines.remove( renderObject );
  597. this._nodes.remove( renderObject );
  598. }
  599. return renderObject;
  600. }
  601. _setupIndexBuffer( index, encoder ) {
  602. const buffer = this._attributes.get( index ).buffer;
  603. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  604. encoder.setIndexBuffer( buffer, indexFormat );
  605. }
  606. _setupVertexBuffers( geometryAttributes, encoder, renderPipeline ) {
  607. const shaderAttributes = renderPipeline.shaderAttributes;
  608. for ( const shaderAttribute of shaderAttributes ) {
  609. const name = shaderAttribute.name;
  610. const slot = shaderAttribute.slot;
  611. const attribute = geometryAttributes[ name ];
  612. if ( attribute !== undefined ) {
  613. const buffer = this._attributes.get( attribute ).buffer;
  614. encoder.setVertexBuffer( slot, buffer );
  615. }
  616. }
  617. }
  618. _setupColorBuffer() {
  619. const device = this._device;
  620. if ( device ) {
  621. if ( this._colorBuffer ) this._colorBuffer.destroy();
  622. this._colorBuffer = this._device.createTexture( {
  623. label: 'colorBuffer',
  624. size: {
  625. width: Math.floor( this._width * this._pixelRatio ),
  626. height: Math.floor( this._height * this._pixelRatio ),
  627. depthOrArrayLayers: 1
  628. },
  629. sampleCount: this._parameters.sampleCount,
  630. format: GPUTextureFormat.BGRA8Unorm,
  631. usage: GPUTextureUsage.RENDER_ATTACHMENT
  632. } );
  633. }
  634. }
  635. _setupDepthBuffer() {
  636. const device = this._device;
  637. if ( device ) {
  638. if ( this._depthBuffer ) this._depthBuffer.destroy();
  639. this._depthBuffer = this._device.createTexture( {
  640. label: 'depthBuffer',
  641. size: {
  642. width: Math.floor( this._width * this._pixelRatio ),
  643. height: Math.floor( this._height * this._pixelRatio ),
  644. depthOrArrayLayers: 1
  645. },
  646. sampleCount: this._parameters.sampleCount,
  647. format: GPUTextureFormat.Depth24PlusStencil8,
  648. usage: GPUTextureUsage.RENDER_ATTACHMENT
  649. } );
  650. }
  651. }
  652. _configureContext() {
  653. const device = this._device;
  654. if ( device ) {
  655. this._context.configure( {
  656. device: device,
  657. format: GPUTextureFormat.BGRA8Unorm,
  658. usage: GPUTextureUsage.RENDER_ATTACHMENT,
  659. alphaMode: 'premultiplied'
  660. } );
  661. }
  662. }
  663. _createCanvasElement() {
  664. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  665. canvas.style.display = 'block';
  666. return canvas;
  667. }
  668. }
  669. export default WebGPURenderer;