WebGPUBackend.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  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 ( hasIndex === true ) {
  532. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  533. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  534. info.update( object, indexCount, instanceCount );
  535. } else {
  536. const positionAttribute = geometry.attributes.position;
  537. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  538. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  539. info.update( object, vertexCount, instanceCount );
  540. }
  541. if ( this.renderer._currentRenderBundle ) {
  542. const renderBundle = passEncoderGPU.finish();
  543. renderObjectData.lastPipelineGPU = pipelineGPU;
  544. renderObjectData.renderBundle = renderBundle;
  545. renderObjectData.bundleEncoder = passEncoderGPU;
  546. }
  547. }
  548. // cache key
  549. needsRenderUpdate( renderObject ) {
  550. const data = this.get( renderObject );
  551. const { object, material } = renderObject;
  552. const utils = this.utils;
  553. const sampleCount = utils.getSampleCount( renderObject.context );
  554. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  555. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  556. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  557. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  558. let needsUpdate = false;
  559. if ( data.material !== material || data.materialVersion !== material.version ||
  560. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  561. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  562. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  563. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  564. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  565. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  566. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  567. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  568. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  569. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  570. data.primitiveTopology !== primitiveTopology ||
  571. data.clippingContextVersion !== renderObject.clippingContextVersion
  572. ) {
  573. data.material = material; data.materialVersion = material.version;
  574. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  575. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  576. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  577. data.colorWrite = material.colorWrite;
  578. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  579. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  580. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  581. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  582. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  583. data.sampleCount = sampleCount;
  584. data.colorSpace = colorSpace;
  585. data.colorFormat = colorFormat;
  586. data.depthStencilFormat = depthStencilFormat;
  587. data.primitiveTopology = primitiveTopology;
  588. data.clippingContextVersion = renderObject.clippingContextVersion;
  589. needsUpdate = true;
  590. }
  591. return needsUpdate;
  592. }
  593. getRenderCacheKey( renderObject ) {
  594. const { object, material } = renderObject;
  595. const utils = this.utils;
  596. const renderContext = renderObject.context;
  597. return [
  598. material.transparent, material.blending, material.premultipliedAlpha,
  599. material.blendSrc, material.blendDst, material.blendEquation,
  600. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  601. material.colorWrite,
  602. material.depthWrite, material.depthTest, material.depthFunc,
  603. material.stencilWrite, material.stencilFunc,
  604. material.stencilFail, material.stencilZFail, material.stencilZPass,
  605. material.stencilFuncMask, material.stencilWriteMask,
  606. material.side,
  607. utils.getSampleCount( renderContext ),
  608. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  609. utils.getPrimitiveTopology( object, material ),
  610. renderObject.clippingContextVersion
  611. ].join();
  612. }
  613. // textures
  614. createSampler( texture ) {
  615. this.textureUtils.createSampler( texture );
  616. }
  617. destroySampler( texture ) {
  618. this.textureUtils.destroySampler( texture );
  619. }
  620. createDefaultTexture( texture ) {
  621. this.textureUtils.createDefaultTexture( texture );
  622. }
  623. createTexture( texture, options ) {
  624. this.textureUtils.createTexture( texture, options );
  625. }
  626. updateTexture( texture, options ) {
  627. this.textureUtils.updateTexture( texture, options );
  628. }
  629. generateMipmaps( texture ) {
  630. this.textureUtils.generateMipmaps( texture );
  631. }
  632. destroyTexture( texture ) {
  633. this.textureUtils.destroyTexture( texture );
  634. }
  635. copyTextureToBuffer( texture, x, y, width, height ) {
  636. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  637. }
  638. initTimestampQuery( renderContext, descriptor ) {
  639. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  640. const renderContextData = this.get( renderContext );
  641. if ( ! renderContextData.timeStampQuerySet ) {
  642. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  643. // beginning and one for the end of compute pass execution.
  644. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  645. const timestampWrites = {
  646. querySet: timeStampQuerySet,
  647. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  648. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  649. };
  650. Object.assign( descriptor, {
  651. timestampWrites,
  652. } );
  653. renderContextData.timeStampQuerySet = timeStampQuerySet;
  654. }
  655. }
  656. // timestamp utils
  657. prepareTimestampBuffer( renderContext, encoder ) {
  658. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  659. const renderContextData = this.get( renderContext );
  660. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  661. const resolveBuffer = this.device.createBuffer( {
  662. size,
  663. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  664. } );
  665. const resultBuffer = this.device.createBuffer( {
  666. size,
  667. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  668. } );
  669. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  670. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  671. renderContextData.currentTimestampQueryBuffer = resultBuffer;
  672. }
  673. async resolveTimestampAsync(renderContext, type = 'render') {
  674. if (!this.hasFeature(GPUFeatureName.TimestampQuery) || !this.trackTimestamp) return;
  675. const renderContextData = this.get(renderContext);
  676. const { currentTimestampQueryBuffer } = renderContextData;
  677. if (currentTimestampQueryBuffer === undefined) return;
  678. const buffer = currentTimestampQueryBuffer;
  679. try {
  680. await buffer.mapAsync(GPUMapMode.READ);
  681. const times = new BigUint64Array(buffer.getMappedRange());
  682. const duration = Number(times[1] - times[0]) / 1000000;
  683. this.renderer.info.updateTimestamp(type, duration);
  684. } catch (error) {
  685. console.error(`Error mapping buffer: ${error}`);
  686. // Optionally handle the error, e.g., re-queue the buffer or skip it
  687. } finally {
  688. buffer.unmap();
  689. }
  690. }
  691. // node builder
  692. createNodeBuilder( object, renderer ) {
  693. return new WGSLNodeBuilder( object, renderer );
  694. }
  695. // program
  696. createProgram( program ) {
  697. const programGPU = this.get( program );
  698. programGPU.module = {
  699. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  700. entryPoint: 'main'
  701. };
  702. }
  703. destroyProgram( program ) {
  704. this.delete( program );
  705. }
  706. // pipelines
  707. createRenderPipeline( renderObject, promises ) {
  708. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  709. }
  710. createComputePipeline( computePipeline, bindings ) {
  711. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  712. }
  713. createBundleEncoder( renderContext, renderObject ) {
  714. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  715. }
  716. // bindings
  717. createBindings( bindGroup ) {
  718. this.bindingUtils.createBindings( bindGroup );
  719. }
  720. updateBindings( bindGroup ) {
  721. this.bindingUtils.createBindings( bindGroup );
  722. }
  723. updateBinding( binding ) {
  724. this.bindingUtils.updateBinding( binding );
  725. }
  726. // attributes
  727. createIndexAttribute( attribute ) {
  728. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  729. }
  730. createAttribute( attribute ) {
  731. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  732. }
  733. createStorageAttribute( attribute ) {
  734. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  735. }
  736. updateAttribute( attribute ) {
  737. this.attributeUtils.updateAttribute( attribute );
  738. }
  739. destroyAttribute( attribute ) {
  740. this.attributeUtils.destroyAttribute( attribute );
  741. }
  742. // canvas
  743. updateSize() {
  744. this.colorBuffer = this.textureUtils.getColorBuffer();
  745. this.defaultRenderPassdescriptor = null;
  746. }
  747. // utils public
  748. getMaxAnisotropy() {
  749. return 16;
  750. }
  751. hasFeature( name ) {
  752. return this.device.features.has( name );
  753. }
  754. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  755. let dstX = 0;
  756. let dstY = 0;
  757. if ( dstPosition !== null ) {
  758. dstX = dstPosition.x;
  759. dstY = dstPosition.y;
  760. }
  761. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  762. const sourceGPU = this.get( srcTexture ).texture;
  763. const destinationGPU = this.get( dstTexture ).texture;
  764. encoder.copyTextureToTexture(
  765. {
  766. texture: sourceGPU,
  767. mipLevel: level,
  768. origin: { x: 0, y: 0, z: 0 }
  769. },
  770. {
  771. texture: destinationGPU,
  772. mipLevel: level,
  773. origin: { x: dstX, y: dstY, z: 0 }
  774. },
  775. [
  776. srcTexture.image.width,
  777. srcTexture.image.height
  778. ]
  779. );
  780. this.device.queue.submit( [ encoder.finish() ] );
  781. }
  782. copyFramebufferToTexture( texture, renderContext ) {
  783. const renderContextData = this.get( renderContext );
  784. const { encoder, descriptor } = renderContextData;
  785. let sourceGPU = null;
  786. if ( renderContext.renderTarget ) {
  787. if ( texture.isDepthTexture ) {
  788. sourceGPU = this.get( renderContext.depthTexture ).texture;
  789. } else {
  790. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  791. }
  792. } else {
  793. if ( texture.isDepthTexture ) {
  794. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  795. } else {
  796. sourceGPU = this.context.getCurrentTexture();
  797. }
  798. }
  799. const destinationGPU = this.get( texture ).texture;
  800. if ( sourceGPU.format !== destinationGPU.format ) {
  801. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  802. return;
  803. }
  804. renderContextData.currentPass.end();
  805. encoder.copyTextureToTexture(
  806. {
  807. texture: sourceGPU,
  808. origin: { x: 0, y: 0, z: 0 }
  809. },
  810. {
  811. texture: destinationGPU
  812. },
  813. [
  814. texture.image.width,
  815. texture.image.height
  816. ]
  817. );
  818. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  819. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  820. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  821. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  822. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  823. renderContextData.currentSets = { attributes: {} };
  824. }
  825. }
  826. export default WebGPUBackend;