WebGPUBackend.js 36 KB

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