WebGPUBackend.js 27 KB

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