WebGPUBackend.js 34 KB

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