WebGPUBackend.js 24 KB

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