WebGPUBackend.js 29 KB

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