2
0

WebGPUBackend.js 23 KB

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