WebGPUBackend.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. /*// debugger tools
  2. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  3. //*/
  4. import { WebGPUCoordinateSystem } from 'three';
  5. import { GPUFeatureName, GPUTextureFormat, GPULoadOp, GPUStoreOp, GPUIndexFormat, GPUTextureViewDimension } from './utils/WebGPUConstants.js';
  6. import WGSLNodeBuilder from './nodes/WGSLNodeBuilder.js';
  7. import Backend from '../common/Backend.js';
  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. //
  14. class WebGPUBackend extends Backend {
  15. constructor( parameters = {} ) {
  16. super( parameters );
  17. this.isWebGPUBackend = true;
  18. // some parameters require default values other than "undefined"
  19. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  20. this.parameters.antialias = ( parameters.antialias === true );
  21. if ( this.parameters.antialias === true ) {
  22. this.parameters.sampleCount = ( parameters.sampleCount === undefined ) ? 4 : parameters.sampleCount;
  23. } else {
  24. this.parameters.sampleCount = 1;
  25. }
  26. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  27. this.trackTimestamp = ( parameters.trackTimestamp === true );
  28. this.device = null;
  29. this.context = null;
  30. this.colorBuffer = null;
  31. this.defaultRenderPassdescriptor = null;
  32. this.utils = new WebGPUUtils( this );
  33. this.attributeUtils = new WebGPUAttributeUtils( this );
  34. this.bindingUtils = new WebGPUBindingUtils( this );
  35. this.pipelineUtils = new WebGPUPipelineUtils( this );
  36. this.textureUtils = new WebGPUTextureUtils( this );
  37. this.occludedResolveCache = new Map();
  38. }
  39. async init( renderer ) {
  40. await super.init( renderer );
  41. //
  42. const parameters = this.parameters;
  43. // create the device if it is not passed with parameters
  44. let device;
  45. if ( parameters.device === undefined ) {
  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. device = await adapter.requestDevice( deviceDescriptor );
  66. } else {
  67. device = parameters.device;
  68. }
  69. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  70. this.device = device;
  71. this.context = context;
  72. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  73. this.context.configure( {
  74. device: this.device,
  75. format: GPUTextureFormat.BGRA8Unorm,
  76. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  77. alphaMode: alphaMode
  78. } );
  79. this.updateSize();
  80. }
  81. get coordinateSystem() {
  82. return WebGPUCoordinateSystem;
  83. }
  84. async getArrayBufferAsync( attribute ) {
  85. return await this.attributeUtils.getArrayBufferAsync( attribute );
  86. }
  87. getContext() {
  88. return this.context;
  89. }
  90. _getDefaultRenderPassDescriptor() {
  91. let descriptor = this.defaultRenderPassdescriptor;
  92. const antialias = this.parameters.antialias;
  93. if ( descriptor === null ) {
  94. const renderer = this.renderer;
  95. descriptor = {
  96. colorAttachments: [ {
  97. view: null
  98. } ],
  99. depthStencilAttachment: {
  100. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  101. }
  102. };
  103. const colorAttachment = descriptor.colorAttachments[ 0 ];
  104. if ( antialias === true ) {
  105. colorAttachment.view = this.colorBuffer.createView();
  106. } else {
  107. colorAttachment.resolveTarget = undefined;
  108. }
  109. this.defaultRenderPassdescriptor = descriptor;
  110. }
  111. const colorAttachment = descriptor.colorAttachments[ 0 ];
  112. if ( antialias === true ) {
  113. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  114. } else {
  115. colorAttachment.view = this.context.getCurrentTexture().createView();
  116. }
  117. return descriptor;
  118. }
  119. _getRenderPassDescriptor( renderContext ) {
  120. const renderTarget = renderContext.renderTarget;
  121. const renderTargetData = this.get( renderTarget );
  122. let descriptors = renderTargetData.descriptors;
  123. if ( descriptors === undefined ) {
  124. descriptors = [];
  125. renderTargetData.descriptors = descriptors;
  126. }
  127. if ( renderTargetData.width !== renderTarget.width ||
  128. renderTargetData.height !== renderTarget.height ||
  129. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  130. renderTargetData.samples !== renderTarget.samples
  131. ) {
  132. descriptors.length = 0;
  133. }
  134. let descriptor = descriptors[ renderContext.activeCubeFace ];
  135. if ( descriptor === undefined ) {
  136. const textures = renderContext.textures;
  137. const colorAttachments = [];
  138. for ( let i = 0; i < textures.length; i ++ ) {
  139. const textureData = this.get( textures[ i ] );
  140. const textureView = textureData.texture.createView( {
  141. baseMipLevel: renderContext.activeMipmapLevel,
  142. mipLevelCount: 1,
  143. baseArrayLayer: renderContext.activeCubeFace,
  144. dimension: GPUTextureViewDimension.TwoD
  145. } );
  146. let view, resolveTarget;
  147. if ( textureData.msaaTexture !== undefined ) {
  148. view = textureData.msaaTexture.createView();
  149. resolveTarget = textureView;
  150. } else {
  151. view = textureView;
  152. resolveTarget = undefined;
  153. }
  154. colorAttachments.push( {
  155. view,
  156. resolveTarget,
  157. loadOp: GPULoadOp.Load,
  158. storeOp: GPUStoreOp.Store
  159. } );
  160. }
  161. const depthTextureData = this.get( renderContext.depthTexture );
  162. const depthStencilAttachment = {
  163. view: depthTextureData.texture.createView(),
  164. };
  165. descriptor = {
  166. colorAttachments,
  167. depthStencilAttachment
  168. };
  169. descriptors[ renderContext.activeCubeFace ] = descriptor;
  170. renderTargetData.width = renderTarget.width;
  171. renderTargetData.height = renderTarget.height;
  172. renderTargetData.samples = renderTarget.samples;
  173. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  174. }
  175. return descriptor;
  176. }
  177. beginRender( renderContext ) {
  178. const renderContextData = this.get( renderContext );
  179. const device = this.device;
  180. const occlusionQueryCount = renderContext.occlusionQueryCount;
  181. let occlusionQuerySet;
  182. if ( occlusionQueryCount > 0 ) {
  183. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  184. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  185. // Get a reference to the array of objects with queries. The renderContextData property
  186. // can be changed by another render pass before the buffer.mapAsyc() completes.
  187. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  188. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  189. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  190. //
  191. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  192. renderContextData.occlusionQuerySet = occlusionQuerySet;
  193. renderContextData.occlusionQueryIndex = 0;
  194. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  195. renderContextData.lastOcclusionObject = null;
  196. }
  197. let descriptor;
  198. if ( renderContext.textures === null ) {
  199. descriptor = this._getDefaultRenderPassDescriptor();
  200. } else {
  201. descriptor = this._getRenderPassDescriptor( renderContext );
  202. }
  203. this.initTimestampQuery( renderContext, descriptor );
  204. descriptor.occlusionQuerySet = occlusionQuerySet;
  205. const depthStencilAttachment = descriptor.depthStencilAttachment;
  206. if ( renderContext.textures !== null ) {
  207. const colorAttachments = descriptor.colorAttachments;
  208. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  209. const colorAttachment = colorAttachments[ i ];
  210. if ( renderContext.clearColor ) {
  211. colorAttachment.clearValue = renderContext.clearColorValue;
  212. colorAttachment.loadOp = GPULoadOp.Clear;
  213. colorAttachment.storeOp = GPUStoreOp.Store;
  214. } else {
  215. colorAttachment.loadOp = GPULoadOp.Load;
  216. colorAttachment.storeOp = GPUStoreOp.Store;
  217. }
  218. }
  219. } else {
  220. const colorAttachment = descriptor.colorAttachments[ 0 ];
  221. if ( renderContext.clearColor ) {
  222. colorAttachment.clearValue = renderContext.clearColorValue;
  223. colorAttachment.loadOp = GPULoadOp.Clear;
  224. colorAttachment.storeOp = GPUStoreOp.Store;
  225. } else {
  226. colorAttachment.loadOp = GPULoadOp.Load;
  227. colorAttachment.storeOp = GPUStoreOp.Store;
  228. }
  229. }
  230. //
  231. if ( renderContext.depth ) {
  232. if ( renderContext.clearDepth ) {
  233. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  234. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  235. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  236. } else {
  237. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  238. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  239. }
  240. }
  241. if ( renderContext.stencil ) {
  242. if ( renderContext.clearStencil ) {
  243. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  244. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  245. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  246. } else {
  247. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  248. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  249. }
  250. }
  251. //
  252. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  253. const currentPass = encoder.beginRenderPass( descriptor );
  254. //
  255. renderContextData.descriptor = descriptor;
  256. renderContextData.encoder = encoder;
  257. renderContextData.currentPass = currentPass;
  258. renderContextData.currentSets = { attributes: {} };
  259. //
  260. if ( renderContext.viewport ) {
  261. this.updateViewport( renderContext );
  262. }
  263. if ( renderContext.scissor ) {
  264. const { x, y, width, height } = renderContext.scissorValue;
  265. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  266. }
  267. }
  268. finishRender( renderContext ) {
  269. const renderContextData = this.get( renderContext );
  270. const occlusionQueryCount = renderContext.occlusionQueryCount;
  271. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  272. renderContextData.registerBundlesPhase = false;
  273. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  274. }
  275. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  276. renderContextData.currentPass.endOcclusionQuery();
  277. }
  278. renderContextData.currentPass.end();
  279. if ( occlusionQueryCount > 0 ) {
  280. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  281. //
  282. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  283. if ( queryResolveBuffer === undefined ) {
  284. queryResolveBuffer = this.device.createBuffer(
  285. {
  286. size: bufferSize,
  287. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  288. }
  289. );
  290. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  291. }
  292. //
  293. const readBuffer = this.device.createBuffer(
  294. {
  295. size: bufferSize,
  296. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  297. }
  298. );
  299. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  300. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  301. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  302. renderContextData.occlusionQueryBuffer = readBuffer;
  303. //
  304. this.resolveOccludedAsync( renderContext );
  305. }
  306. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  307. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  308. //
  309. if ( renderContext.textures !== null ) {
  310. const textures = renderContext.textures;
  311. for ( let i = 0; i < textures.length; i ++ ) {
  312. const texture = textures[ i ];
  313. if ( texture.generateMipmaps === true ) {
  314. this.textureUtils.generateMipmaps( texture );
  315. }
  316. }
  317. }
  318. }
  319. isOccluded( renderContext, object ) {
  320. const renderContextData = this.get( renderContext );
  321. return renderContextData.occluded && renderContextData.occluded.has( object );
  322. }
  323. async resolveOccludedAsync( renderContext ) {
  324. const renderContextData = this.get( renderContext );
  325. // handle occlusion query results
  326. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  327. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  328. const occluded = new WeakSet();
  329. renderContextData.currentOcclusionQueryObjects = null;
  330. renderContextData.currentOcclusionQueryBuffer = null;
  331. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  332. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  333. const results = new BigUint64Array( buffer );
  334. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  335. if ( results[ i ] !== 0n ) {
  336. occluded.add( currentOcclusionQueryObjects[ i ] );
  337. }
  338. }
  339. currentOcclusionQueryBuffer.destroy();
  340. renderContextData.occluded = occluded;
  341. }
  342. }
  343. updateViewport( renderContext ) {
  344. const { currentPass } = this.get( renderContext );
  345. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  346. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  347. }
  348. clear( color, depth, stencil, renderTargetData = null ) {
  349. const device = this.device;
  350. const renderer = this.renderer;
  351. let colorAttachments = [];
  352. let depthStencilAttachment;
  353. let clearValue;
  354. let supportsDepth;
  355. let supportsStencil;
  356. if ( color ) {
  357. const clearColor = this.getClearColor();
  358. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  359. }
  360. if ( renderTargetData === null ) {
  361. supportsDepth = renderer.depth;
  362. supportsStencil = renderer.stencil;
  363. const descriptor = this._getDefaultRenderPassDescriptor();
  364. if ( color ) {
  365. colorAttachments = descriptor.colorAttachments;
  366. const colorAttachment = colorAttachments[ 0 ];
  367. colorAttachment.clearValue = clearValue;
  368. colorAttachment.loadOp = GPULoadOp.Clear;
  369. colorAttachment.storeOp = GPUStoreOp.Store;
  370. }
  371. if ( supportsDepth || supportsStencil ) {
  372. depthStencilAttachment = descriptor.depthStencilAttachment;
  373. }
  374. } else {
  375. supportsDepth = renderTargetData.depth;
  376. supportsStencil = renderTargetData.stencil;
  377. if ( color ) {
  378. for ( const texture of renderTargetData.textures ) {
  379. const textureData = this.get( texture );
  380. const textureView = textureData.texture.createView();
  381. let view, resolveTarget;
  382. if ( textureData.msaaTexture !== undefined ) {
  383. view = textureData.msaaTexture.createView();
  384. resolveTarget = textureView;
  385. } else {
  386. view = textureView;
  387. resolveTarget = undefined;
  388. }
  389. colorAttachments.push( {
  390. view,
  391. resolveTarget,
  392. clearValue,
  393. loadOp: GPULoadOp.Clear,
  394. storeOp: GPUStoreOp.Store
  395. } );
  396. }
  397. }
  398. if ( supportsDepth || supportsStencil ) {
  399. const depthTextureData = this.get( renderTargetData.depthTexture );
  400. depthStencilAttachment = {
  401. view: depthTextureData.texture.createView()
  402. };
  403. }
  404. }
  405. //
  406. if ( supportsDepth ) {
  407. if ( depth ) {
  408. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  409. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  410. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  411. } else {
  412. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  413. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  414. }
  415. }
  416. //
  417. if ( supportsStencil ) {
  418. if ( stencil ) {
  419. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  420. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  421. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  422. } else {
  423. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  424. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  425. }
  426. }
  427. //
  428. const encoder = device.createCommandEncoder( {} );
  429. const currentPass = encoder.beginRenderPass( {
  430. colorAttachments,
  431. depthStencilAttachment
  432. } );
  433. currentPass.end();
  434. device.queue.submit( [ encoder.finish() ] );
  435. }
  436. // compute
  437. beginCompute( computeGroup ) {
  438. const groupGPU = this.get( computeGroup );
  439. const descriptor = {};
  440. this.initTimestampQuery( computeGroup, descriptor );
  441. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  442. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  443. }
  444. compute( computeGroup, computeNode, bindings, pipeline ) {
  445. const { passEncoderGPU } = this.get( computeGroup );
  446. // pipeline
  447. const pipelineGPU = this.get( pipeline ).pipeline;
  448. passEncoderGPU.setPipeline( pipelineGPU );
  449. // bind groups
  450. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  451. const bindGroup = bindings[ i ];
  452. const bindingsData = this.get( bindGroup );
  453. passEncoderGPU.setBindGroup( i, bindingsData.group );
  454. }
  455. passEncoderGPU.dispatchWorkgroups( computeNode.dispatchCount );
  456. }
  457. finishCompute( computeGroup ) {
  458. const groupData = this.get( computeGroup );
  459. groupData.passEncoderGPU.end();
  460. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  461. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  462. }
  463. // render object
  464. draw( renderObject, info ) {
  465. const { object, geometry, context, pipeline } = renderObject;
  466. const bindings = renderObject.getBindings();
  467. const contextData = this.get( context );
  468. const pipelineGPU = this.get( pipeline ).pipeline;
  469. const currentSets = contextData.currentSets;
  470. const renderObjectData = this.get( renderObject );
  471. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  472. const renderContextData = this.get( context );
  473. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  474. renderContextData.renderBundles.push( renderBundle );
  475. return;
  476. }
  477. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  478. // pipeline
  479. if ( currentSets.pipeline !== pipelineGPU ) {
  480. passEncoderGPU.setPipeline( pipelineGPU );
  481. currentSets.pipeline = pipelineGPU;
  482. }
  483. // bind groups
  484. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  485. const bindGroup = bindings[ i ];
  486. const bindingsData = this.get( bindGroup );
  487. passEncoderGPU.setBindGroup( i, bindingsData.group );
  488. }
  489. // attributes
  490. const index = renderObject.getIndex();
  491. const hasIndex = ( index !== null );
  492. // index
  493. if ( hasIndex === true ) {
  494. if ( currentSets.index !== index ) {
  495. const buffer = this.get( index ).buffer;
  496. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  497. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  498. currentSets.index = index;
  499. }
  500. }
  501. // vertex buffers
  502. const vertexBuffers = renderObject.getVertexBuffers();
  503. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  504. const vertexBuffer = vertexBuffers[ i ];
  505. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  506. const buffer = this.get( vertexBuffer ).buffer;
  507. passEncoderGPU.setVertexBuffer( i, buffer );
  508. currentSets.attributes[ i ] = vertexBuffer;
  509. }
  510. }
  511. // occlusion queries - handle multiple consecutive draw calls for an object
  512. if ( contextData.occlusionQuerySet !== undefined ) {
  513. const lastObject = contextData.lastOcclusionObject;
  514. if ( lastObject !== object ) {
  515. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  516. passEncoderGPU.endOcclusionQuery();
  517. contextData.occlusionQueryIndex ++;
  518. }
  519. if ( object.occlusionTest === true ) {
  520. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  521. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  522. }
  523. contextData.lastOcclusionObject = object;
  524. }
  525. }
  526. // draw
  527. const drawRange = renderObject.drawRange;
  528. const firstVertex = drawRange.start;
  529. const instanceCount = this.getInstanceCount( renderObject );
  530. if ( instanceCount === 0 ) return;
  531. if ( object.isBatchedMesh === true ) {
  532. const starts = object._multiDrawStarts;
  533. const counts = object._multiDrawCounts;
  534. const drawCount = object._multiDrawCount;
  535. const bytesPerElement = index.bytesPerElement || 1;
  536. for ( let i = 0; i < drawCount; i ++ ) {
  537. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, 1, starts[ i ] / 4, 0, i );
  538. }
  539. } else if ( hasIndex === true ) {
  540. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  541. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  542. info.update( object, indexCount, instanceCount );
  543. } else {
  544. const positionAttribute = geometry.attributes.position;
  545. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  546. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  547. info.update( object, vertexCount, instanceCount );
  548. }
  549. if ( this.renderer._currentRenderBundle ) {
  550. const renderBundle = passEncoderGPU.finish();
  551. renderObjectData.lastPipelineGPU = pipelineGPU;
  552. renderObjectData.renderBundle = renderBundle;
  553. renderObjectData.bundleEncoder = passEncoderGPU;
  554. }
  555. }
  556. // cache key
  557. needsRenderUpdate( renderObject ) {
  558. const data = this.get( renderObject );
  559. const { object, material } = renderObject;
  560. const utils = this.utils;
  561. const sampleCount = utils.getSampleCount( renderObject.context );
  562. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  563. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  564. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  565. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  566. let needsUpdate = false;
  567. if ( data.material !== material || data.materialVersion !== material.version ||
  568. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  569. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  570. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  571. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  572. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  573. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  574. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  575. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  576. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  577. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  578. data.primitiveTopology !== primitiveTopology ||
  579. data.clippingContextVersion !== renderObject.clippingContextVersion
  580. ) {
  581. data.material = material; data.materialVersion = material.version;
  582. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  583. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  584. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  585. data.colorWrite = material.colorWrite;
  586. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  587. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  588. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  589. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  590. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  591. data.sampleCount = sampleCount;
  592. data.colorSpace = colorSpace;
  593. data.colorFormat = colorFormat;
  594. data.depthStencilFormat = depthStencilFormat;
  595. data.primitiveTopology = primitiveTopology;
  596. data.clippingContextVersion = renderObject.clippingContextVersion;
  597. needsUpdate = true;
  598. }
  599. return needsUpdate;
  600. }
  601. getRenderCacheKey( renderObject ) {
  602. const { object, material } = renderObject;
  603. const utils = this.utils;
  604. const renderContext = renderObject.context;
  605. return [
  606. material.transparent, material.blending, material.premultipliedAlpha,
  607. material.blendSrc, material.blendDst, material.blendEquation,
  608. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  609. material.colorWrite,
  610. material.depthWrite, material.depthTest, material.depthFunc,
  611. material.stencilWrite, material.stencilFunc,
  612. material.stencilFail, material.stencilZFail, material.stencilZPass,
  613. material.stencilFuncMask, material.stencilWriteMask,
  614. material.side,
  615. utils.getSampleCount( renderContext ),
  616. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  617. utils.getPrimitiveTopology( object, material ),
  618. renderObject.clippingContextVersion
  619. ].join();
  620. }
  621. // textures
  622. createSampler( texture ) {
  623. this.textureUtils.createSampler( texture );
  624. }
  625. destroySampler( texture ) {
  626. this.textureUtils.destroySampler( texture );
  627. }
  628. createDefaultTexture( texture ) {
  629. this.textureUtils.createDefaultTexture( texture );
  630. }
  631. createTexture( texture, options ) {
  632. this.textureUtils.createTexture( texture, options );
  633. }
  634. updateTexture( texture, options ) {
  635. this.textureUtils.updateTexture( texture, options );
  636. }
  637. generateMipmaps( texture ) {
  638. this.textureUtils.generateMipmaps( texture );
  639. }
  640. destroyTexture( texture ) {
  641. this.textureUtils.destroyTexture( texture );
  642. }
  643. copyTextureToBuffer( texture, x, y, width, height ) {
  644. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  645. }
  646. initTimestampQuery( renderContext, descriptor ) {
  647. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  648. const renderContextData = this.get( renderContext );
  649. if ( ! renderContextData.timeStampQuerySet ) {
  650. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  651. // beginning and one for the end of compute pass execution.
  652. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  653. const timestampWrites = {
  654. querySet: timeStampQuerySet,
  655. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  656. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  657. };
  658. Object.assign( descriptor, {
  659. timestampWrites,
  660. } );
  661. renderContextData.timeStampQuerySet = timeStampQuerySet;
  662. }
  663. }
  664. // timestamp utils
  665. prepareTimestampBuffer( renderContext, encoder ) {
  666. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  667. const renderContextData = this.get( renderContext );
  668. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  669. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  670. renderContextData.currentTimestampQueryBuffers = {
  671. resolveBuffer: this.device.createBuffer({
  672. label: 'timestamp resolve buffer',
  673. size: size,
  674. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  675. }),
  676. resultBuffer: this.device.createBuffer({
  677. label: 'timestamp result buffer',
  678. size: size,
  679. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  680. }),
  681. isMappingPending: false,
  682. }
  683. }
  684. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers
  685. if ( isMappingPending === true ) return;
  686. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  687. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  688. }
  689. async resolveTimestampAsync( renderContext, type = 'render' ) {
  690. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  691. const renderContextData = this.get(renderContext);
  692. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  693. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  694. if ( isMappingPending === true ) return;
  695. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  696. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  697. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  698. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  699. this.renderer.info.updateTimestamp( type, duration );
  700. resultBuffer.unmap();
  701. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  702. })
  703. }
  704. // node builder
  705. createNodeBuilder( object, renderer ) {
  706. return new WGSLNodeBuilder( object, renderer );
  707. }
  708. // program
  709. createProgram( program ) {
  710. const programGPU = this.get( program );
  711. programGPU.module = {
  712. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  713. entryPoint: 'main'
  714. };
  715. }
  716. destroyProgram( program ) {
  717. this.delete( program );
  718. }
  719. // pipelines
  720. createRenderPipeline( renderObject, promises ) {
  721. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  722. }
  723. createComputePipeline( computePipeline, bindings ) {
  724. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  725. }
  726. createBundleEncoder( renderContext, renderObject ) {
  727. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  728. }
  729. // bindings
  730. createBindings( bindGroup ) {
  731. this.bindingUtils.createBindings( bindGroup );
  732. }
  733. updateBindings( bindGroup ) {
  734. this.bindingUtils.createBindings( bindGroup );
  735. }
  736. updateBinding( binding ) {
  737. this.bindingUtils.updateBinding( binding );
  738. }
  739. // attributes
  740. createIndexAttribute( attribute ) {
  741. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  742. }
  743. createAttribute( attribute ) {
  744. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  745. }
  746. createStorageAttribute( attribute ) {
  747. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  748. }
  749. updateAttribute( attribute ) {
  750. this.attributeUtils.updateAttribute( attribute );
  751. }
  752. destroyAttribute( attribute ) {
  753. this.attributeUtils.destroyAttribute( attribute );
  754. }
  755. // canvas
  756. updateSize() {
  757. this.colorBuffer = this.textureUtils.getColorBuffer();
  758. this.defaultRenderPassdescriptor = null;
  759. }
  760. // utils public
  761. getMaxAnisotropy() {
  762. return 16;
  763. }
  764. hasFeature( name ) {
  765. return this.device.features.has( name );
  766. }
  767. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  768. let dstX = 0;
  769. let dstY = 0;
  770. if ( dstPosition !== null ) {
  771. dstX = dstPosition.x;
  772. dstY = dstPosition.y;
  773. }
  774. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  775. const sourceGPU = this.get( srcTexture ).texture;
  776. const destinationGPU = this.get( dstTexture ).texture;
  777. encoder.copyTextureToTexture(
  778. {
  779. texture: sourceGPU,
  780. mipLevel: level,
  781. origin: { x: 0, y: 0, z: 0 }
  782. },
  783. {
  784. texture: destinationGPU,
  785. mipLevel: level,
  786. origin: { x: dstX, y: dstY, z: 0 }
  787. },
  788. [
  789. srcTexture.image.width,
  790. srcTexture.image.height
  791. ]
  792. );
  793. this.device.queue.submit( [ encoder.finish() ] );
  794. }
  795. copyFramebufferToTexture( texture, renderContext ) {
  796. const renderContextData = this.get( renderContext );
  797. const { encoder, descriptor } = renderContextData;
  798. let sourceGPU = null;
  799. if ( renderContext.renderTarget ) {
  800. if ( texture.isDepthTexture ) {
  801. sourceGPU = this.get( renderContext.depthTexture ).texture;
  802. } else {
  803. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  804. }
  805. } else {
  806. if ( texture.isDepthTexture ) {
  807. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  808. } else {
  809. sourceGPU = this.context.getCurrentTexture();
  810. }
  811. }
  812. const destinationGPU = this.get( texture ).texture;
  813. if ( sourceGPU.format !== destinationGPU.format ) {
  814. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  815. return;
  816. }
  817. renderContextData.currentPass.end();
  818. encoder.copyTextureToTexture(
  819. {
  820. texture: sourceGPU,
  821. origin: { x: 0, y: 0, z: 0 }
  822. },
  823. {
  824. texture: destinationGPU
  825. },
  826. [
  827. texture.image.width,
  828. texture.image.height
  829. ]
  830. );
  831. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  832. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  833. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  834. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  835. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  836. renderContextData.currentSets = { attributes: {} };
  837. }
  838. }
  839. export default WebGPUBackend;