WebGPUBackend.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. /*// debugger tools
  2. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  3. //*/
  4. import { GPUFeatureName, GPUTextureFormat, GPULoadOp, GPUStoreOp, GPUIndexFormat, GPUTextureViewDimension } from './utils/WebGPUConstants.js';
  5. import WGSLNodeBuilder from './nodes/WGSLNodeBuilder.js';
  6. import Backend from '../common/Backend.js';
  7. import { DepthFormat, WebGPUCoordinateSystem } from 'three';
  8. import WebGPUUtils from './utils/WebGPUUtils.js';
  9. import WebGPUAttributeUtils from './utils/WebGPUAttributeUtils.js';
  10. import WebGPUBindingUtils from './utils/WebGPUBindingUtils.js';
  11. import WebGPUPipelineUtils from './utils/WebGPUPipelineUtils.js';
  12. import WebGPUTextureUtils from './utils/WebGPUTextureUtils.js';
  13. // statics
  14. let _staticAdapter = null;
  15. if ( navigator.gpu !== undefined ) {
  16. _staticAdapter = await navigator.gpu.requestAdapter();
  17. }
  18. //
  19. class WebGPUBackend extends Backend {
  20. constructor( parameters = {} ) {
  21. super( parameters );
  22. this.isWebGPUBackend = true;
  23. // some parameters require default values other than "undefined"
  24. this.parameters.antialias = ( parameters.antialias === true );
  25. if ( this.parameters.antialias === true ) {
  26. this.parameters.sampleCount = ( parameters.sampleCount === undefined ) ? 4 : parameters.sampleCount;
  27. } else {
  28. this.parameters.sampleCount = 1;
  29. }
  30. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  31. this.adapter = null;
  32. this.device = null;
  33. this.context = null;
  34. this.colorBuffer = null;
  35. this.utils = new WebGPUUtils( this );
  36. this.attributeUtils = new WebGPUAttributeUtils( this );
  37. this.bindingUtils = new WebGPUBindingUtils( this );
  38. this.pipelineUtils = new WebGPUPipelineUtils( this );
  39. this.textureUtils = new WebGPUTextureUtils( this );
  40. this.occludedResolveCache = new Map();
  41. }
  42. async init( renderer ) {
  43. await super.init( renderer );
  44. //
  45. const parameters = this.parameters;
  46. const adapterOptions = {
  47. powerPreference: parameters.powerPreference
  48. };
  49. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  50. if ( adapter === null ) {
  51. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  52. }
  53. // feature support
  54. const features = Object.values( GPUFeatureName );
  55. const supportedFeatures = [];
  56. for ( const name of features ) {
  57. if ( adapter.features.has( name ) ) {
  58. supportedFeatures.push( name );
  59. }
  60. }
  61. const deviceDescriptor = {
  62. requiredFeatures: supportedFeatures,
  63. requiredLimits: parameters.requiredLimits
  64. };
  65. const device = await adapter.requestDevice( deviceDescriptor );
  66. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  67. this.adapter = adapter;
  68. this.device = device;
  69. this.context = context;
  70. this.context.configure( {
  71. device: this.device,
  72. format: GPUTextureFormat.BGRA8Unorm,
  73. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  74. alphaMode: 'premultiplied'
  75. } );
  76. this.updateSize();
  77. }
  78. get coordinateSystem() {
  79. return WebGPUCoordinateSystem;
  80. }
  81. async getArrayBufferAsync( attribute ) {
  82. return await this.attributeUtils.getArrayBufferAsync( attribute );
  83. }
  84. beginRender( renderContext ) {
  85. const renderContextData = this.get( renderContext );
  86. const device = this.device;
  87. const occlusionQueryCount = renderContext.occlusionQueryCount;
  88. let occlusionQuerySet;
  89. if ( occlusionQueryCount > 0 ) {
  90. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  91. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  92. // Get a reference to the array of objects with queries. The renderContextData property
  93. // can be changed by another render pass before the buffer.mapAsyc() completes.
  94. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  95. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  96. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  97. //
  98. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  99. renderContextData.occlusionQuerySet = occlusionQuerySet;
  100. renderContextData.occlusionQueryIndex = 0;
  101. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  102. renderContextData.lastOcclusionObject = null;
  103. }
  104. const descriptor = {
  105. colorAttachments: [ {
  106. view: null
  107. } ],
  108. depthStencilAttachment: {
  109. view: null
  110. },
  111. occlusionQuerySet
  112. };
  113. const colorAttachment = descriptor.colorAttachments[ 0 ];
  114. const depthStencilAttachment = descriptor.depthStencilAttachment;
  115. const antialias = this.parameters.antialias;
  116. if ( renderContext.textures !== null ) {
  117. const textures = renderContext.textures;
  118. descriptor.colorAttachments = [];
  119. const colorAttachments = descriptor.colorAttachments;
  120. for ( let i = 0; i < textures.length; i ++ ) {
  121. const textureData = this.get( textures[ i ] );
  122. const textureView = textureData.texture.createView( {
  123. baseMipLevel: renderContext.activeMipmapLevel,
  124. mipLevelCount: 1,
  125. baseArrayLayer: renderContext.activeCubeFace,
  126. dimension: GPUTextureViewDimension.TwoD
  127. } );
  128. let view, resolveTarget;
  129. if ( textureData.msaaTexture !== undefined ) {
  130. view = textureData.msaaTexture.createView();
  131. resolveTarget = textureView;
  132. } else {
  133. view = textureView;
  134. resolveTarget = undefined;
  135. }
  136. colorAttachments.push( {
  137. view,
  138. resolveTarget,
  139. loadOp: GPULoadOp.Load,
  140. storeOp: GPUStoreOp.Store
  141. } );
  142. }
  143. const depthTextureData = this.get( renderContext.depthTexture );
  144. depthStencilAttachment.view = depthTextureData.texture.createView();
  145. if ( renderContext.stencil && renderContext.depthTexture.format === DepthFormat ) {
  146. renderContext.stencil = false;
  147. }
  148. } else {
  149. if ( antialias === true ) {
  150. colorAttachment.view = this.colorBuffer.createView();
  151. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  152. } else {
  153. colorAttachment.view = this.context.getCurrentTexture().createView();
  154. colorAttachment.resolveTarget = undefined;
  155. }
  156. depthStencilAttachment.view = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil ).createView();
  157. }
  158. if ( renderContext.textures !== null ) {
  159. const colorAttachments = descriptor.colorAttachments;
  160. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  161. const colorAttachment = colorAttachments[ i ];
  162. if ( renderContext.clearColor ) {
  163. colorAttachment.clearValue = renderContext.clearColorValue;
  164. colorAttachment.loadOp = GPULoadOp.Clear;
  165. colorAttachment.storeOp = GPUStoreOp.Store;
  166. } else {
  167. colorAttachment.loadOp = GPULoadOp.Load;
  168. colorAttachment.storeOp = GPUStoreOp.Store;
  169. }
  170. }
  171. } else {
  172. if ( renderContext.clearColor ) {
  173. colorAttachment.clearValue = renderContext.clearColorValue;
  174. colorAttachment.loadOp = GPULoadOp.Clear;
  175. colorAttachment.storeOp = GPUStoreOp.Store;
  176. } else {
  177. colorAttachment.loadOp = GPULoadOp.Load;
  178. colorAttachment.storeOp = GPUStoreOp.Store;
  179. }
  180. }
  181. //
  182. if ( renderContext.depth ) {
  183. if ( renderContext.clearDepth ) {
  184. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  185. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  186. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  187. } else {
  188. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  189. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  190. }
  191. }
  192. if ( renderContext.stencil ) {
  193. if ( renderContext.clearStencil ) {
  194. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  195. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  196. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  197. } else {
  198. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  199. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  200. }
  201. }
  202. //
  203. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  204. const currentPass = encoder.beginRenderPass( descriptor );
  205. //
  206. renderContextData.descriptor = descriptor;
  207. renderContextData.encoder = encoder;
  208. renderContextData.currentPass = currentPass;
  209. renderContextData.currentSets = { attributes: {} };
  210. //
  211. if ( renderContext.viewport ) {
  212. this.updateViewport( renderContext );
  213. }
  214. if ( renderContext.scissor ) {
  215. const { x, y, width, height } = renderContext.scissorValue;
  216. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  217. }
  218. }
  219. finishRender( renderContext ) {
  220. const renderContextData = this.get( renderContext );
  221. const occlusionQueryCount = renderContext.occlusionQueryCount;
  222. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  223. renderContextData.currentPass.endOcclusionQuery();
  224. }
  225. renderContextData.currentPass.end();
  226. if ( occlusionQueryCount > 0 ) {
  227. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  228. //
  229. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  230. if ( queryResolveBuffer === undefined ) {
  231. queryResolveBuffer = this.device.createBuffer(
  232. {
  233. size: bufferSize,
  234. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  235. }
  236. );
  237. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  238. }
  239. //
  240. const readBuffer = this.device.createBuffer(
  241. {
  242. size: bufferSize,
  243. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  244. }
  245. );
  246. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  247. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  248. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  249. renderContextData.occlusionQueryBuffer = readBuffer;
  250. //
  251. this.resolveOccludedAsync( renderContext );
  252. }
  253. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  254. //
  255. if ( renderContext.textures !== null ) {
  256. const textures = renderContext.textures;
  257. for ( let i = 0; i < textures.length; i ++ ) {
  258. const texture = textures[ i ];
  259. if ( texture.generateMipmaps === true ) {
  260. this.textureUtils.generateMipmaps( texture );
  261. }
  262. }
  263. }
  264. }
  265. isOccluded( renderContext, object ) {
  266. const renderContextData = this.get( renderContext );
  267. return renderContextData.occluded && renderContextData.occluded.has( object );
  268. }
  269. async resolveOccludedAsync( renderContext ) {
  270. const renderContextData = this.get( renderContext );
  271. // handle occlusion query results
  272. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  273. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  274. const occluded = new WeakSet();
  275. renderContextData.currentOcclusionQueryObjects = null;
  276. renderContextData.currentOcclusionQueryBuffer = null;
  277. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  278. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  279. const results = new BigUint64Array( buffer );
  280. for ( let i = 0; i < currentOcclusionQueryObjects.length; i++ ) {
  281. if ( results[ i ] !== 0n ) {
  282. occluded.add( currentOcclusionQueryObjects[ i ] );
  283. }
  284. }
  285. currentOcclusionQueryBuffer.destroy();
  286. renderContextData.occluded = occluded;
  287. }
  288. }
  289. updateViewport( renderContext ) {
  290. const { currentPass } = this.get( renderContext );
  291. let { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  292. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  293. }
  294. clear( color, depth, stencil, renderTargetData = null ) {
  295. const device = this.device;
  296. const renderer = this.renderer;
  297. const colorAttachments = [];
  298. let depthStencilAttachment;
  299. let clearValue;
  300. let supportsDepth;
  301. let supportsStencil;
  302. if ( color ) {
  303. const clearColor = this.getClearColor();
  304. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  305. }
  306. if ( renderTargetData === null ) {
  307. supportsDepth = renderer.depth;
  308. supportsStencil = renderer.stencil;
  309. depth = depth && supportsDepth;
  310. stencil = stencil && supportsStencil;
  311. if ( color ) {
  312. const antialias = this.parameters.antialias;
  313. const colorAttachment = {};
  314. if ( antialias === true ) {
  315. colorAttachment.view = this.colorBuffer.createView();
  316. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  317. } else {
  318. colorAttachment.view = this.context.getCurrentTexture().createView();
  319. }
  320. colorAttachment.clearValue = clearValue;
  321. colorAttachment.loadOp = GPULoadOp.Clear;
  322. colorAttachment.storeOp = GPUStoreOp.Store;
  323. colorAttachments.push( colorAttachment );
  324. }
  325. if ( depth || stencil ) {
  326. depthStencilAttachment = {
  327. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  328. };
  329. }
  330. } else {
  331. supportsDepth = renderTargetData.depth;
  332. supportsStencil = renderTargetData.stencil;
  333. depth = depth && supportsDepth;
  334. stencil = stencil && supportsStencil;
  335. if ( color ) {
  336. for ( const texture of renderTargetData.textures ) {
  337. const textureData = this.get( texture );
  338. const textureView = textureData.texture.createView();
  339. let view, resolveTarget;
  340. if ( textureData.msaaTexture !== undefined ) {
  341. view = textureData.msaaTexture.createView();
  342. resolveTarget = textureView;
  343. } else {
  344. view = textureView;
  345. resolveTarget = undefined;
  346. }
  347. colorAttachments.push( {
  348. view,
  349. resolveTarget,
  350. clearValue,
  351. loadOp: GPULoadOp.Clear,
  352. storeOp: GPUStoreOp.Store
  353. } );
  354. }
  355. }
  356. if ( depth || stencil ) {
  357. const depthTextureData = this.get( renderTargetData.depthTexture );
  358. depthStencilAttachment = {
  359. view: depthTextureData.texture.createView()
  360. };
  361. }
  362. }
  363. //
  364. if ( depthStencilAttachment !== undefined ) {
  365. if ( depth ) {
  366. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  367. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  368. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  369. } else {
  370. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  371. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  372. }
  373. //
  374. if ( stencil ) {
  375. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  376. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  377. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  378. } else {
  379. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  380. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  381. }
  382. }
  383. //
  384. const encoder = device.createCommandEncoder( {} );
  385. const currentPass = encoder.beginRenderPass( {
  386. colorAttachments,
  387. depthStencilAttachment
  388. } );
  389. currentPass.end();
  390. device.queue.submit( [ encoder.finish() ] );
  391. }
  392. // compute
  393. beginCompute( computeGroup ) {
  394. const groupGPU = this.get( computeGroup );
  395. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( {} );
  396. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass();
  397. }
  398. compute( computeGroup, computeNode, bindings, pipeline ) {
  399. const { passEncoderGPU } = this.get( computeGroup );
  400. // pipeline
  401. const pipelineGPU = this.get( pipeline ).pipeline;
  402. passEncoderGPU.setPipeline( pipelineGPU );
  403. // bind group
  404. const bindGroupGPU = this.get( bindings ).group;
  405. passEncoderGPU.setBindGroup( 0, bindGroupGPU );
  406. passEncoderGPU.dispatchWorkgroups( computeNode.dispatchCount );
  407. }
  408. finishCompute( computeGroup ) {
  409. const groupData = this.get( computeGroup );
  410. groupData.passEncoderGPU.end();
  411. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  412. }
  413. // render object
  414. draw( renderObject, info ) {
  415. const { object, geometry, context, pipeline } = renderObject;
  416. const bindingsData = this.get( renderObject.getBindings() );
  417. const contextData = this.get( context );
  418. const pipelineGPU = this.get( pipeline ).pipeline;
  419. const currentSets = contextData.currentSets;
  420. // pipeline
  421. const passEncoderGPU = contextData.currentPass;
  422. if ( currentSets.pipeline !== pipelineGPU ) {
  423. passEncoderGPU.setPipeline( pipelineGPU );
  424. currentSets.pipeline = pipelineGPU;
  425. }
  426. // bind group
  427. const bindGroupGPU = bindingsData.group;
  428. passEncoderGPU.setBindGroup( 0, bindGroupGPU );
  429. // attributes
  430. const index = renderObject.getIndex();
  431. const hasIndex = ( index !== null );
  432. // index
  433. if ( hasIndex === true ) {
  434. if ( currentSets.index !== index ) {
  435. const buffer = this.get( index ).buffer;
  436. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  437. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  438. currentSets.index = index;
  439. }
  440. }
  441. // vertex buffers
  442. const vertexBuffers = renderObject.getVertexBuffers();
  443. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  444. const vertexBuffer = vertexBuffers[ i ];
  445. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  446. const buffer = this.get( vertexBuffer ).buffer;
  447. passEncoderGPU.setVertexBuffer( i, buffer );
  448. currentSets.attributes[ i ] = vertexBuffer;
  449. }
  450. }
  451. // occlusion queries - handle multiple consecutive draw calls for an object
  452. if ( contextData.occlusionQuerySet !== undefined ) {
  453. const lastObject = contextData.lastOcclusionObject;
  454. if ( lastObject !== object ) {
  455. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  456. passEncoderGPU.endOcclusionQuery();
  457. contextData.occlusionQueryIndex ++;
  458. }
  459. if ( object.occlusionTest === true ) {
  460. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  461. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  462. }
  463. contextData.lastOcclusionObject = object;
  464. }
  465. }
  466. // draw
  467. const drawRange = geometry.drawRange;
  468. const firstVertex = drawRange.start;
  469. const instanceCount = this.getInstanceCount( renderObject );
  470. if ( instanceCount === 0 ) return;
  471. if ( hasIndex === true ) {
  472. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  473. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  474. info.update( object, indexCount, instanceCount );
  475. } else {
  476. const positionAttribute = geometry.attributes.position;
  477. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  478. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  479. info.update( object, vertexCount, instanceCount );
  480. }
  481. }
  482. // cache key
  483. needsRenderUpdate( renderObject ) {
  484. const data = this.get( renderObject );
  485. const { object, material } = renderObject;
  486. const utils = this.utils;
  487. const sampleCount = utils.getSampleCount( renderObject.context );
  488. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  489. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  490. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  491. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  492. let needsUpdate = false;
  493. if ( data.material !== material || data.materialVersion !== material.version ||
  494. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  495. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  496. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  497. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  498. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  499. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  500. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  501. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  502. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  503. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  504. data.primitiveTopology !== primitiveTopology
  505. ) {
  506. data.material = material; data.materialVersion = material.version;
  507. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  508. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  509. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  510. data.colorWrite = material.colorWrite;
  511. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  512. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  513. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  514. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  515. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  516. data.sampleCount = sampleCount;
  517. data.colorSpace = colorSpace;
  518. data.colorFormat = colorFormat;
  519. data.depthStencilFormat = depthStencilFormat;
  520. data.primitiveTopology = primitiveTopology;
  521. needsUpdate = true;
  522. }
  523. return needsUpdate;
  524. }
  525. getRenderCacheKey( renderObject ) {
  526. const { object, material } = renderObject;
  527. const utils = this.utils;
  528. const renderContext = renderObject.context;
  529. return [
  530. material.transparent, material.blending, material.premultipliedAlpha,
  531. material.blendSrc, material.blendDst, material.blendEquation,
  532. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  533. material.colorWrite,
  534. material.depthWrite, material.depthTest, material.depthFunc,
  535. material.stencilWrite, material.stencilFunc,
  536. material.stencilFail, material.stencilZFail, material.stencilZPass,
  537. material.stencilFuncMask, material.stencilWriteMask,
  538. material.side,
  539. utils.getSampleCount( renderContext ),
  540. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  541. utils.getPrimitiveTopology( object, material )
  542. ].join();
  543. }
  544. // textures
  545. createSampler( texture ) {
  546. this.textureUtils.createSampler( texture );
  547. }
  548. destroySampler( texture ) {
  549. this.textureUtils.destroySampler( texture );
  550. }
  551. createDefaultTexture( texture ) {
  552. this.textureUtils.createDefaultTexture( texture );
  553. }
  554. createTexture( texture, options ) {
  555. this.textureUtils.createTexture( texture, options );
  556. }
  557. updateTexture( texture, options ) {
  558. this.textureUtils.updateTexture( texture, options );
  559. }
  560. generateMipmaps( texture ) {
  561. this.textureUtils.generateMipmaps( texture );
  562. }
  563. destroyTexture( texture ) {
  564. this.textureUtils.destroyTexture( texture );
  565. }
  566. copyTextureToBuffer( texture, x, y, width, height ) {
  567. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  568. }
  569. // node builder
  570. createNodeBuilder( object, renderer, scene = null ) {
  571. return new WGSLNodeBuilder( object, renderer, scene );
  572. }
  573. // program
  574. createProgram( program ) {
  575. const programGPU = this.get( program );
  576. programGPU.module = {
  577. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  578. entryPoint: 'main'
  579. };
  580. }
  581. destroyProgram( program ) {
  582. this.delete( program );
  583. }
  584. // pipelines
  585. createRenderPipeline( renderObject ) {
  586. this.pipelineUtils.createRenderPipeline( renderObject );
  587. }
  588. createComputePipeline( computePipeline, bindings ) {
  589. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  590. }
  591. // bindings
  592. createBindings( bindings ) {
  593. this.bindingUtils.createBindings( bindings );
  594. }
  595. updateBindings( bindings ) {
  596. this.bindingUtils.createBindings( bindings );
  597. }
  598. updateBinding( binding ) {
  599. this.bindingUtils.updateBinding( binding );
  600. }
  601. // attributes
  602. createIndexAttribute( attribute ) {
  603. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  604. }
  605. createAttribute( attribute ) {
  606. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  607. }
  608. createStorageAttribute( attribute ) {
  609. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  610. }
  611. updateAttribute( attribute ) {
  612. this.attributeUtils.updateAttribute( attribute );
  613. }
  614. destroyAttribute( attribute ) {
  615. this.attributeUtils.destroyAttribute( attribute );
  616. }
  617. // canvas
  618. updateSize() {
  619. this.colorBuffer = this.textureUtils.getColorBuffer();
  620. }
  621. // utils public
  622. getMaxAnisotropy() {
  623. return 16;
  624. }
  625. hasFeature( name ) {
  626. const adapter = this.adapter || _staticAdapter;
  627. //
  628. const features = Object.values( GPUFeatureName );
  629. if ( features.includes( name ) === false ) {
  630. throw new Error( 'THREE.WebGPURenderer: Unknown WebGPU GPU feature: ' + name );
  631. }
  632. //
  633. return adapter.features.has( name );
  634. }
  635. copyFramebufferToTexture( texture, renderContext ) {
  636. const renderContextData = this.get( renderContext );
  637. const { encoder, descriptor } = renderContextData;
  638. let sourceGPU = null;
  639. if ( texture.isFramebufferTexture ) {
  640. sourceGPU = this.context.getCurrentTexture();
  641. } else if ( texture.isDepthTexture ) {
  642. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  643. }
  644. const destinationGPU = this.get( texture ).texture;
  645. renderContextData.currentPass.end();
  646. encoder.copyTextureToTexture(
  647. {
  648. texture: sourceGPU,
  649. origin: { x: 0, y: 0, z: 0 }
  650. },
  651. {
  652. texture: destinationGPU
  653. },
  654. [
  655. texture.image.width,
  656. texture.image.height
  657. ]
  658. );
  659. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  660. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  661. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  662. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  663. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  664. renderContextData.currentSets = { attributes: {} };
  665. }
  666. }
  667. export default WebGPUBackend;