WebGPUBackend.js 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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. needsUpdate( renderObject ) {
  423. const renderObjectGPU = 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 ( renderObjectGPU.sampleCount !== sampleCount || renderObjectGPU.colorSpace !== colorSpace ||
  433. renderObjectGPU.colorFormat !== colorFormat || renderObjectGPU.depthStencilFormat !== depthStencilFormat ||
  434. renderObjectGPU.primitiveTopology !== primitiveTopology ) {
  435. renderObjectGPU.sampleCount = sampleCount;
  436. renderObjectGPU.colorSpace = colorSpace;
  437. renderObjectGPU.colorFormat = colorFormat;
  438. renderObjectGPU.depthStencilFormat = depthStencilFormat;
  439. renderObjectGPU.primitiveTopology = primitiveTopology;
  440. needsUpdate = true;
  441. }
  442. return needsUpdate;
  443. }
  444. getCacheKey( renderObject ) {
  445. const { object, material } = renderObject;
  446. const utils = this.utils;
  447. const renderContext = renderObject.context;
  448. return [
  449. utils.getSampleCount( renderContext ),
  450. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  451. utils.getPrimitiveTopology( object, material )
  452. ].join();
  453. }
  454. // textures
  455. createSampler( texture ) {
  456. this.textureUtils.createSampler( texture );
  457. }
  458. destroySampler( texture ) {
  459. this.textureUtils.destroySampler( texture );
  460. }
  461. createDefaultTexture( texture ) {
  462. this.textureUtils.createDefaultTexture( texture );
  463. }
  464. createTexture( texture, options ) {
  465. this.textureUtils.createTexture( texture, options );
  466. }
  467. updateTexture( texture, options ) {
  468. this.textureUtils.updateTexture( texture, options );
  469. }
  470. generateMipmaps( texture ) {
  471. this.textureUtils.generateMipmaps( texture );
  472. }
  473. destroyTexture( texture ) {
  474. this.textureUtils.destroyTexture( texture );
  475. }
  476. copyTextureToBuffer( texture, x, y, width, height ) {
  477. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  478. }
  479. // node builder
  480. createNodeBuilder( object, renderer, scene = null ) {
  481. return new WGSLNodeBuilder( object, renderer, scene );
  482. }
  483. // program
  484. createProgram( program ) {
  485. const programGPU = this.get( program );
  486. programGPU.module = {
  487. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  488. entryPoint: 'main'
  489. };
  490. }
  491. destroyProgram( program ) {
  492. this.delete( program );
  493. }
  494. // pipelines
  495. createRenderPipeline( renderObject ) {
  496. this.pipelineUtils.createRenderPipeline( renderObject );
  497. }
  498. createComputePipeline( computePipeline, bindings ) {
  499. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  500. }
  501. // bindings
  502. createBindings( bindings ) {
  503. this.bindingUtils.createBindings( bindings );
  504. }
  505. updateBindings( bindings ) {
  506. this.bindingUtils.createBindings( bindings );
  507. }
  508. updateBinding( binding ) {
  509. this.bindingUtils.updateBinding( binding );
  510. }
  511. // attributes
  512. createIndexAttribute( attribute ) {
  513. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  514. }
  515. createAttribute( attribute ) {
  516. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  517. }
  518. createStorageAttribute( attribute ) {
  519. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  520. }
  521. updateAttribute( attribute ) {
  522. this.attributeUtils.updateAttribute( attribute );
  523. }
  524. destroyAttribute( attribute ) {
  525. this.attributeUtils.destroyAttribute( attribute );
  526. }
  527. // canvas
  528. updateSize() {
  529. this._configureContext();
  530. this._setupColorBuffer();
  531. }
  532. // utils public
  533. hasFeature( name ) {
  534. const adapter = this.adapter || _staticAdapter;
  535. //
  536. const features = Object.values( GPUFeatureName );
  537. if ( features.includes( name ) === false ) {
  538. throw new Error( 'THREE.WebGPURenderer: Unknown WebGPU GPU feature: ' + name );
  539. }
  540. //
  541. return adapter.features.has( name );
  542. }
  543. copyFramebufferToTexture( texture, renderContext ) {
  544. const renderContextData = this.get( renderContext );
  545. const { encoder, descriptor } = renderContextData;
  546. let sourceGPU = null;
  547. if ( texture.isFramebufferTexture ) {
  548. sourceGPU = this.context.getCurrentTexture();
  549. } else if ( texture.isDepthTexture ) {
  550. sourceGPU = this._getDepthBufferGPU( renderContext );
  551. }
  552. const destinationGPU = this.get( texture ).texture;
  553. renderContextData.currentPass.end();
  554. encoder.copyTextureToTexture(
  555. {
  556. texture: sourceGPU,
  557. origin: { x: 0, y: 0, z: 0 }
  558. },
  559. {
  560. texture: destinationGPU
  561. },
  562. [
  563. texture.image.width,
  564. texture.image.height
  565. ]
  566. );
  567. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  568. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  569. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  570. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  571. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  572. renderContextData.currentSets = { attributes: {} };
  573. }
  574. // utils
  575. _getDepthBufferGPU( renderContext ) {
  576. const { width, height } = this.getDrawingBufferSize();
  577. const depthTexture = this.defaultDepthTexture;
  578. const depthTextureGPU = this.get( depthTexture ).texture;
  579. let format, type;
  580. if ( renderContext.stencil ) {
  581. format = DepthStencilFormat;
  582. type = UnsignedInt248Type;
  583. } else if ( renderContext.depth ) {
  584. format = DepthFormat;
  585. type = UnsignedIntType;
  586. }
  587. if ( depthTextureGPU !== undefined ) {
  588. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  589. return depthTextureGPU;
  590. }
  591. this.textureUtils.destroyTexture( depthTexture );
  592. }
  593. depthTexture.name = 'depthBuffer';
  594. depthTexture.format = format;
  595. depthTexture.type = type;
  596. depthTexture.image.width = width;
  597. depthTexture.image.height = height;
  598. this.textureUtils.createTexture( depthTexture, { sampleCount: this.parameters.sampleCount, width, height } );
  599. return this.get( depthTexture ).texture;
  600. }
  601. _configureContext() {
  602. this.context.configure( {
  603. device: this.device,
  604. format: GPUTextureFormat.BGRA8Unorm,
  605. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  606. alphaMode: 'premultiplied'
  607. } );
  608. }
  609. _setupColorBuffer() {
  610. if ( this.colorBuffer ) this.colorBuffer.destroy();
  611. const { width, height } = this.getDrawingBufferSize();
  612. //const format = navigator.gpu.getPreferredCanvasFormat(); // @TODO: Move to WebGPUUtils
  613. this.colorBuffer = this.device.createTexture( {
  614. label: 'colorBuffer',
  615. size: {
  616. width: width,
  617. height: height,
  618. depthOrArrayLayers: 1
  619. },
  620. sampleCount: this.parameters.sampleCount,
  621. format: GPUTextureFormat.BGRA8Unorm,
  622. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  623. } );
  624. }
  625. }
  626. export default WebGPUBackend;