WebGPUBackend.js 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884
  1. // debugger tools
  2. // import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  3. import { GPUFeatureName, GPULoadOp, GPUStoreOp, GPUIndexFormat, GPUTextureViewDimension, GPUFeatureMap, GPUShaderStage } from './utils/WebGPUConstants.js';
  4. import WGSLNodeBuilder from './nodes/WGSLNodeBuilder.js';
  5. import Backend from '../common/Backend.js';
  6. import WebGPUUtils, { submit } from './utils/WebGPUUtils.js';
  7. import WebGPUAttributeUtils from './utils/WebGPUAttributeUtils.js';
  8. import WebGPUBindingUtils from './utils/WebGPUBindingUtils.js';
  9. import WebGPUCapabilities from './utils/WebGPUCapabilities.js';
  10. import WebGPUPipelineUtils from './utils/WebGPUPipelineUtils.js';
  11. import WebGPUTextureUtils from './utils/WebGPUTextureUtils.js';
  12. import { WebGPUCoordinateSystem, TimestampQuery, REVISION, HalfFloatType, Compatibility } from '../../constants.js';
  13. import WebGPUTimestampQueryPool from './utils/WebGPUTimestampQueryPool.js';
  14. import { error } from '../../utils.js';
  15. import GPUBufferDescriptor from './descriptors/GPUBufferDescriptor.js';
  16. import GPUCommandEncoderDescriptor from './descriptors/GPUCommandEncoderDescriptor.js';
  17. import GPUComputePassDescriptor from './descriptors/GPUComputePassDescriptor.js';
  18. import GPUQuerySetDescriptor from './descriptors/GPUQuerySetDescriptor.js';
  19. import GPUShaderModuleDescriptor from './descriptors/GPUShaderModuleDescriptor.js';
  20. import GPURenderPassColorAttachment from './descriptors/GPURenderPassColorAttachment.js';
  21. import GPURenderPassDepthStencilAttachment from './descriptors/GPURenderPassDepthStencilAttachment.js';
  22. import GPURenderPassDescriptor from './descriptors/GPURenderPassDescriptor.js';
  23. import GPURenderPassTimestampWrites from './descriptors/GPURenderPassTimestampWrites.js';
  24. import GPUTexelCopyTextureInfo from './descriptors/GPUTexelCopyTextureInfo.js';
  25. import GPUTextureViewDescriptor from './descriptors/GPUTextureViewDescriptor.js';
  26. import GPUExtent3D from './descriptors/GPUExtent3D.js';
  27. const _clearValue = { r: 0, g: 0, b: 0, a: 1 };
  28. const _bufferDescriptor = new GPUBufferDescriptor();
  29. const _commandEncoderDescriptor = new GPUCommandEncoderDescriptor();
  30. const _computePassDescriptor = new GPUComputePassDescriptor();
  31. const _querySetDescriptor = new GPUQuerySetDescriptor();
  32. const _shaderModuleDescriptor = new GPUShaderModuleDescriptor();
  33. const _renderPassTimestampWrites = new GPURenderPassTimestampWrites();
  34. const _texelCopyTextureInfoSrc = new GPUTexelCopyTextureInfo();
  35. const _texelCopyTextureInfoDst = new GPUTexelCopyTextureInfo();
  36. const _viewDescriptor = new GPUTextureViewDescriptor();
  37. const _extent3D = new GPUExtent3D();
  38. /**
  39. * A backend implementation targeting WebGPU.
  40. *
  41. * @private
  42. * @augments Backend
  43. */
  44. class WebGPUBackend extends Backend {
  45. /**
  46. * WebGPUBackend options.
  47. *
  48. * @typedef {Object} WebGPUBackend~Options
  49. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  50. * @property {boolean} [reversedDepthBuffer=false] - Whether reversed depth buffer is enabled or not.
  51. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  52. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  53. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  54. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  55. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  56. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  57. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  58. * @property {string} [powerPreference=undefined] - The power preference.
  59. * @property {Object} [requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  60. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  61. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  62. */
  63. /**
  64. * Constructs a new WebGPU backend.
  65. *
  66. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  67. */
  68. constructor( parameters = {} ) {
  69. super( parameters );
  70. /**
  71. * This flag can be used for type testing.
  72. *
  73. * @type {boolean}
  74. * @readonly
  75. * @default true
  76. */
  77. this.isWebGPUBackend = true;
  78. // some parameters require default values other than "undefined"
  79. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  80. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  81. /**
  82. * Indicates whether the backend is in WebGPU compatibility mode or not.
  83. * The backend must be initialized before the property can be evaluated.
  84. *
  85. * @type {?boolean}
  86. * @readonly
  87. * @default null
  88. */
  89. this.compatibilityMode = null;
  90. /**
  91. * A reference to the device.
  92. *
  93. * @type {?GPUDevice}
  94. * @default null
  95. */
  96. this.device = null;
  97. /**
  98. * A reference to the default render pass descriptor.
  99. *
  100. * @type {?Object}
  101. * @default null
  102. */
  103. this.defaultRenderPassdescriptor = null;
  104. /**
  105. * A reference to a backend module holding common utility functions.
  106. *
  107. * @type {WebGPUUtils}
  108. */
  109. this.utils = new WebGPUUtils( this );
  110. /**
  111. * A reference to a backend module holding shader attribute-related
  112. * utility functions.
  113. *
  114. * @type {WebGPUAttributeUtils}
  115. */
  116. this.attributeUtils = new WebGPUAttributeUtils( this );
  117. /**
  118. * A reference to a backend module holding shader binding-related
  119. * utility functions.
  120. *
  121. * @type {WebGPUBindingUtils}
  122. */
  123. this.bindingUtils = new WebGPUBindingUtils( this );
  124. /**
  125. * A reference to a backend module holding device capability related
  126. * utility functions.
  127. *
  128. * @type {WebGPUCapabilities}
  129. */
  130. this.capabilities = new WebGPUCapabilities( this );
  131. /**
  132. * A reference to a backend module holding shader pipeline-related
  133. * utility functions.
  134. *
  135. * @type {WebGPUPipelineUtils}
  136. */
  137. this.pipelineUtils = new WebGPUPipelineUtils( this );
  138. /**
  139. * A reference to a backend module holding shader texture-related
  140. * utility functions.
  141. *
  142. * @type {WebGPUTextureUtils}
  143. */
  144. this.textureUtils = new WebGPUTextureUtils( this );
  145. /**
  146. * A map that manages the resolve buffers for occlusion queries.
  147. *
  148. * @type {Map<number,GPUBuffer>}
  149. */
  150. this.occludedResolveCache = new Map();
  151. // compatibility checks
  152. const compatibilityTextureCompare = typeof navigator === 'undefined' ? true : /Android/.test( navigator.userAgent ) === false;
  153. /**
  154. * A map of compatibility checks.
  155. *
  156. * @type {Object}
  157. */
  158. this._compatibility = {
  159. [ Compatibility.TEXTURE_COMPARE ]: compatibilityTextureCompare
  160. };
  161. }
  162. /**
  163. * Initializes the backend so it is ready for usage.
  164. *
  165. * @async
  166. * @param {Renderer} renderer - The renderer.
  167. * @return {Promise} A Promise that resolves when the backend has been initialized.
  168. */
  169. async init( renderer ) {
  170. await super.init( renderer );
  171. //
  172. const parameters = this.parameters;
  173. // create the device if it is not passed with parameters
  174. let device;
  175. if ( parameters.device === undefined ) {
  176. const adapterOptions = {
  177. powerPreference: parameters.powerPreference,
  178. featureLevel: 'compatibility',
  179. xrCompatible: renderer.xr.enabled
  180. };
  181. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  182. if ( adapter === null ) {
  183. throw new Error( 'THREE.WebGPUBackend: Unable to create WebGPU adapter.' );
  184. }
  185. // feature support
  186. const features = Object.values( GPUFeatureName );
  187. const supportedFeatures = [];
  188. for ( const name of features ) {
  189. if ( adapter.features.has( name ) ) {
  190. supportedFeatures.push( name );
  191. }
  192. }
  193. const deviceDescriptor = {
  194. requiredFeatures: supportedFeatures,
  195. requiredLimits: parameters.requiredLimits
  196. };
  197. device = await adapter.requestDevice( deviceDescriptor );
  198. } else {
  199. device = parameters.device;
  200. }
  201. this.compatibilityMode = ! device.features.has( 'core-features-and-limits' );
  202. if ( this.compatibilityMode ) {
  203. renderer._samples = 0;
  204. }
  205. device.lost.then( ( info ) => {
  206. if ( info.reason === 'destroyed' ) return;
  207. const deviceLossInfo = {
  208. api: 'WebGPU',
  209. message: info.message || 'Unknown reason',
  210. reason: info.reason || null,
  211. originalEvent: info
  212. };
  213. renderer.onDeviceLost( deviceLossInfo );
  214. } );
  215. device.onuncapturederror = ( event ) => {
  216. const gpuError = event.error;
  217. const type = gpuError && gpuError.constructor ? gpuError.constructor.name : 'GPUError';
  218. const message = ( gpuError && gpuError.message ) || 'Unknown uncaptured GPU error';
  219. renderer.onError( {
  220. api: 'WebGPU',
  221. type,
  222. message,
  223. originalEvent: event
  224. } );
  225. };
  226. this.device = device;
  227. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  228. this.updateSize();
  229. }
  230. /**
  231. * Registers external GPU textures from `XRGPUBinding` for use in rendering.
  232. *
  233. * @param {RenderTarget} renderTarget - The render target to register the textures for.
  234. * @param {GPUTexture} colorTexture - The shared XR color GPUTexture.
  235. * @param {?Array<Object>} [viewDescriptors=null] - Optional view descriptors, one per XR view.
  236. */
  237. setXRRenderTargetTextures( renderTarget, colorTexture, viewDescriptors = null ) {
  238. this.set( renderTarget.texture, {
  239. texture: colorTexture,
  240. format: colorTexture.format,
  241. externalTexture: true,
  242. xrViewDescriptors: viewDescriptors,
  243. initialized: true
  244. } );
  245. }
  246. /**
  247. * A reference to the context.
  248. *
  249. * @type {?GPUCanvasContext}
  250. * @default null
  251. */
  252. get context() {
  253. const canvasTarget = this.renderer.getCanvasTarget();
  254. const canvasData = this.get( canvasTarget );
  255. let context = canvasData.context;
  256. if ( context === undefined ) {
  257. const parameters = this.parameters;
  258. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  259. context = parameters.context;
  260. } else {
  261. context = canvasTarget.domElement.getContext( 'webgpu' );
  262. }
  263. // OffscreenCanvas does not have setAttribute, see #22811
  264. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  265. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  266. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  267. context.configure( {
  268. device: this.device,
  269. format: this.utils.getPreferredCanvasFormat(),
  270. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  271. alphaMode: alphaMode,
  272. toneMapping: {
  273. mode: toneMappingMode
  274. }
  275. } );
  276. canvasData.context = context;
  277. }
  278. return context;
  279. }
  280. /**
  281. * The coordinate system of the backend.
  282. *
  283. * @type {number}
  284. * @readonly
  285. */
  286. get coordinateSystem() {
  287. return WebGPUCoordinateSystem;
  288. }
  289. /**
  290. * Whether the backend supports query timestamps or not.
  291. *
  292. * @type {boolean}
  293. * @readonly
  294. */
  295. get hasTimestamp() {
  296. return true;
  297. }
  298. /**
  299. * This method performs a readback operation by moving buffer data from
  300. * a storage buffer attribute from the GPU to the CPU. ReadbackBuffer can
  301. * be used to retain and reuse handles to the intermediate buffers and prevent
  302. * new allocation.
  303. *
  304. * @async
  305. * @param {BufferAttribute} attribute - The storage buffer attribute to read frm.
  306. * @param {number} count - The offset from which to start reading the
  307. * @param {number} offset - The storage buffer attribute.
  308. * @param {ReadbackBuffer|ArrayBuffer} target - The storage buffer attribute.
  309. * @return {Promise<ArrayBuffer|ReadbackBuffer>} A promise that resolves with the buffer data when the data are ready.
  310. */
  311. async getArrayBufferAsync( attribute, target = null, offset = 0, count = - 1 ) {
  312. return await this.attributeUtils.getArrayBufferAsync( attribute, target, offset, count );
  313. }
  314. /**
  315. * Returns the backend's rendering context.
  316. *
  317. * @return {GPUCanvasContext} The rendering context.
  318. */
  319. getContext() {
  320. return this.context;
  321. }
  322. /**
  323. * Returns the default render pass descriptor.
  324. *
  325. * In WebGPU, the default framebuffer must be configured
  326. * like custom framebuffers so the backend needs a render
  327. * pass descriptor even when rendering directly to screen.
  328. *
  329. * @private
  330. * @return {Object} The render pass descriptor.
  331. */
  332. _getDefaultRenderPassDescriptor() {
  333. const renderer = this.renderer;
  334. const canvasTarget = renderer.getCanvasTarget();
  335. const canvasData = this.get( canvasTarget );
  336. const samples = renderer.currentSamples;
  337. let descriptor = canvasData.descriptor;
  338. if ( descriptor === undefined || canvasData.samples !== samples ) {
  339. descriptor = new GPURenderPassDescriptor();
  340. descriptor.colorAttachments.push( new GPURenderPassColorAttachment() );
  341. if ( renderer.depth === true || renderer.stencil === true ) {
  342. const depthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  343. depthStencilAttachment.view = this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView();
  344. descriptor.depthStencilAttachment = depthStencilAttachment;
  345. }
  346. const colorAttachment = descriptor.colorAttachments[ 0 ];
  347. if ( samples > 0 ) {
  348. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  349. } else {
  350. colorAttachment.resolveTarget = undefined;
  351. }
  352. canvasData.descriptor = descriptor;
  353. canvasData.samples = samples;
  354. }
  355. const colorAttachment = descriptor.colorAttachments[ 0 ];
  356. if ( samples > 0 ) {
  357. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  358. } else {
  359. colorAttachment.view = this.context.getCurrentTexture().createView();
  360. }
  361. return descriptor;
  362. }
  363. /**
  364. * Returns whether the render target is a render target array with depth 2D array texture.
  365. *
  366. * @param {RenderContext} renderContext - The render context.
  367. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  368. *
  369. * @private
  370. */
  371. _isRenderCameraDepthArray( renderContext ) {
  372. const camera = renderContext.camera;
  373. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture === true && camera !== null && camera.isArrayCamera === true;
  374. }
  375. /**
  376. * Returns whether the current render context references external textures.
  377. *
  378. * External textures can change every frame, so their descriptors must not be cached.
  379. *
  380. * @private
  381. * @param {RenderContext} renderContext - The render context.
  382. * @return {boolean} Whether the render context uses external textures.
  383. */
  384. _hasExternalTexture( renderContext ) {
  385. const textures = renderContext.textures;
  386. if ( textures === null ) return false;
  387. for ( let i = 0; i < textures.length; i ++ ) {
  388. if ( this.get( textures[ i ] ).externalTexture === true ) return true;
  389. }
  390. return false;
  391. }
  392. /**
  393. * Creates attachment views for an external texture render target.
  394. *
  395. * @private
  396. * @param {RenderContext} renderContext - The render context.
  397. * @param {Object} textureData - The backend data for the texture.
  398. * @return {Array<Object>} The attachment view descriptors.
  399. */
  400. _createExternalTextureViews( renderContext, textureData ) {
  401. const textureViews = [];
  402. const camera = renderContext.camera;
  403. if ( textureData.xrViewDescriptors && camera !== null && camera.isArrayCamera === true ) {
  404. for ( let i = 0; i < textureData.xrViewDescriptors.length; i ++ ) {
  405. textureViews.push( {
  406. view: textureData.texture.createView( textureData.xrViewDescriptors[ i ] ),
  407. resolveTarget: undefined,
  408. depthSlice: undefined
  409. } );
  410. }
  411. } else {
  412. textureViews.push( {
  413. view: textureData.texture.createView( {
  414. dimension: GPUTextureViewDimension.TwoD,
  415. baseArrayLayer: renderContext.activeCubeFace,
  416. arrayLayerCount: 1
  417. } ),
  418. resolveTarget: undefined,
  419. depthSlice: undefined
  420. } );
  421. }
  422. return textureViews;
  423. }
  424. /**
  425. * Returns the render pass descriptor for the given render context.
  426. *
  427. * @private
  428. * @param {RenderContext} renderContext - The render context.
  429. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  430. * @return {Object} The render pass descriptor.
  431. */
  432. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  433. const renderTarget = renderContext.renderTarget;
  434. const renderTargetData = this.get( renderTarget );
  435. const hasExternalTexture = this._hasExternalTexture( renderContext );
  436. let descriptors = renderTargetData.descriptors;
  437. if ( descriptors === undefined ||
  438. renderTargetData.width !== renderTarget.width ||
  439. renderTargetData.height !== renderTarget.height ||
  440. renderTargetData.samples !== renderTarget.samples ||
  441. hasExternalTexture
  442. ) {
  443. descriptors = {};
  444. renderTargetData.descriptors = descriptors;
  445. }
  446. const cacheKey = renderContext.getCacheKey();
  447. let descriptorBase = descriptors[ cacheKey ];
  448. if ( descriptorBase === undefined || hasExternalTexture ) {
  449. const textures = renderContext.textures;
  450. const textureViews = [];
  451. let sliceIndex;
  452. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  453. for ( let i = 0; i < textures.length; i ++ ) {
  454. const textureData = this.get( textures[ i ] );
  455. if ( textureData.externalTexture === true ) {
  456. textureViews.push( ...this._createExternalTextureViews( renderContext, textureData ) );
  457. continue;
  458. }
  459. _viewDescriptor.label = `colorAttachment_${ i }`;
  460. _viewDescriptor.baseMipLevel = renderContext.activeMipmapLevel;
  461. _viewDescriptor.mipLevelCount = 1;
  462. _viewDescriptor.baseArrayLayer = renderContext.activeCubeFace;
  463. _viewDescriptor.arrayLayerCount = 1;
  464. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  465. if ( renderTarget.isRenderTarget3D ) {
  466. sliceIndex = renderContext.activeCubeFace;
  467. _viewDescriptor.baseArrayLayer = 0;
  468. _viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  469. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  470. if ( isRenderCameraDepthArray === true ) {
  471. const cameras = renderContext.camera.cameras;
  472. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  473. _viewDescriptor.baseArrayLayer = layer;
  474. _viewDescriptor.arrayLayerCount = 1;
  475. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  476. const textureView = textureData.texture.createView( _viewDescriptor );
  477. textureViews.push( {
  478. view: textureView,
  479. resolveTarget: undefined,
  480. depthSlice: undefined
  481. } );
  482. }
  483. } else {
  484. _viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  485. }
  486. }
  487. if ( isRenderCameraDepthArray !== true ) {
  488. const textureView = textureData.texture.createView( _viewDescriptor );
  489. let view, resolveTarget;
  490. if ( textureData.msaaTexture !== undefined ) {
  491. view = textureData.msaaTexture.createView();
  492. resolveTarget = textureView;
  493. } else {
  494. view = textureView;
  495. resolveTarget = undefined;
  496. }
  497. textureViews.push( {
  498. view,
  499. resolveTarget,
  500. depthSlice: sliceIndex
  501. } );
  502. }
  503. _viewDescriptor.reset();
  504. }
  505. const colorAttachments = [];
  506. for ( let i = 0; i < textureViews.length; i ++ ) {
  507. const viewInfo = textureViews[ i ];
  508. const attachment = new GPURenderPassColorAttachment();
  509. attachment.view = viewInfo.view;
  510. attachment.depthSlice = viewInfo.depthSlice;
  511. attachment.resolveTarget = viewInfo.resolveTarget;
  512. colorAttachments.push( attachment );
  513. }
  514. descriptorBase = {
  515. textureViews,
  516. colorAttachments,
  517. descriptor: new GPURenderPassDescriptor()
  518. };
  519. if ( renderContext.depth ) {
  520. const depthTextureData = this.get( renderContext.depthTexture );
  521. if ( renderContext.depthTexture.isArrayTexture || renderContext.depthTexture.isCubeTexture ) {
  522. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  523. _viewDescriptor.arrayLayerCount = 1;
  524. _viewDescriptor.baseArrayLayer = renderContext.activeCubeFace;
  525. }
  526. const depthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  527. depthStencilAttachment.view = depthTextureData.texture.createView( _viewDescriptor );
  528. descriptorBase.depthStencilAttachment = depthStencilAttachment;
  529. _viewDescriptor.reset();
  530. }
  531. descriptors[ cacheKey ] = descriptorBase;
  532. renderTargetData.width = renderTarget.width;
  533. renderTargetData.height = renderTarget.height;
  534. renderTargetData.samples = renderTarget.samples;
  535. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  536. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  537. }
  538. const descriptor = descriptorBase.descriptor;
  539. descriptor.reset();
  540. // Apply dynamic properties to cached attachments
  541. for ( let i = 0; i < descriptorBase.colorAttachments.length; i ++ ) {
  542. const attachment = descriptorBase.colorAttachments[ i ];
  543. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  544. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  545. clearValue = colorAttachmentsConfig.clearValue;
  546. }
  547. attachment.loadOp = colorAttachmentsConfig.loadOp || GPULoadOp.Load;
  548. attachment.storeOp = colorAttachmentsConfig.storeOp || GPUStoreOp.Store;
  549. attachment.clearValue = clearValue;
  550. descriptor.colorAttachments.push( attachment );
  551. }
  552. if ( descriptorBase.depthStencilAttachment ) {
  553. descriptor.depthStencilAttachment = descriptorBase.depthStencilAttachment;
  554. }
  555. return descriptor;
  556. }
  557. /**
  558. * This method is executed at the beginning of a render call and prepares
  559. * the WebGPU state for upcoming render calls
  560. *
  561. * @param {RenderContext} renderContext - The render context.
  562. */
  563. beginRender( renderContext ) {
  564. const renderContextData = this.get( renderContext );
  565. //
  566. const device = this.device;
  567. const occlusionQueryCount = renderContext.occlusionQueryCount;
  568. let occlusionQuerySet;
  569. if ( occlusionQueryCount > 0 ) {
  570. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  571. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  572. // Get a reference to the array of objects with queries. The renderContextData property
  573. // can be changed by another render pass before the buffer.mapAsyc() completes.
  574. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  575. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  576. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  577. //
  578. _querySetDescriptor.label = `occlusionQuerySet_${ renderContext.id }`;
  579. _querySetDescriptor.type = 'occlusion';
  580. _querySetDescriptor.count = occlusionQueryCount;
  581. occlusionQuerySet = device.createQuerySet( _querySetDescriptor );
  582. _querySetDescriptor.reset();
  583. renderContextData.occlusionQuerySet = occlusionQuerySet;
  584. renderContextData.occlusionQueryIndex = 0;
  585. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  586. renderContextData.lastOcclusionObject = null;
  587. }
  588. let descriptor;
  589. if ( renderContext.textures === null ) {
  590. descriptor = this._getDefaultRenderPassDescriptor();
  591. } else {
  592. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  593. }
  594. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  595. descriptor.occlusionQuerySet = occlusionQuerySet;
  596. const depthStencilAttachment = descriptor.depthStencilAttachment;
  597. if ( renderContext.textures !== null ) {
  598. const colorAttachments = descriptor.colorAttachments;
  599. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  600. const colorAttachment = colorAttachments[ i ];
  601. if ( renderContext.clearColor ) {
  602. if ( i === 0 ) {
  603. colorAttachment.clearValue = renderContext.clearColorValue;
  604. } else {
  605. _clearValue.r = 0;
  606. _clearValue.g = 0;
  607. _clearValue.b = 0;
  608. _clearValue.a = 1;
  609. colorAttachment.clearValue = _clearValue;
  610. }
  611. colorAttachment.loadOp = GPULoadOp.Clear;
  612. } else {
  613. colorAttachment.loadOp = GPULoadOp.Load;
  614. }
  615. colorAttachment.storeOp = GPUStoreOp.Store;
  616. }
  617. } else {
  618. const colorAttachment = descriptor.colorAttachments[ 0 ];
  619. if ( renderContext.clearColor ) {
  620. colorAttachment.clearValue = renderContext.clearColorValue;
  621. colorAttachment.loadOp = GPULoadOp.Clear;
  622. } else {
  623. colorAttachment.loadOp = GPULoadOp.Load;
  624. }
  625. colorAttachment.storeOp = GPUStoreOp.Store;
  626. }
  627. //
  628. if ( renderContext.depth ) {
  629. if ( renderContext.clearDepth ) {
  630. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  631. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  632. } else {
  633. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  634. }
  635. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  636. }
  637. if ( renderContext.stencil ) {
  638. if ( renderContext.clearStencil ) {
  639. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  640. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  641. } else {
  642. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  643. }
  644. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  645. }
  646. //
  647. _commandEncoderDescriptor.label = 'renderContext_' + renderContext.id;
  648. const encoder = device.createCommandEncoder( _commandEncoderDescriptor );
  649. _commandEncoderDescriptor.reset();
  650. // Layered render targets: prepare bundle encoders for each camera in the array camera.
  651. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  652. const cameras = renderContext.camera.cameras;
  653. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  654. this._createArrayCameraLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  655. } else {
  656. this._updateArrayCameraLayerDescriptors( renderContext, renderContextData, cameras );
  657. }
  658. // Create bundle encoders for each layer
  659. renderContextData.bundleEncoders = [];
  660. renderContextData.bundleSets = [];
  661. // Create separate bundle encoders for each camera in the array
  662. for ( let i = 0; i < cameras.length; i ++ ) {
  663. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  664. renderContext,
  665. 'renderBundleArrayCamera_' + i
  666. );
  667. // Initialize state tracking for this bundle
  668. const bundleSets = {
  669. attributes: {},
  670. bindingGroups: [],
  671. pipeline: null,
  672. index: null
  673. };
  674. renderContextData.bundleEncoders.push( bundleEncoder );
  675. renderContextData.bundleSets.push( bundleSets );
  676. }
  677. // We'll complete the bundles in finishRender
  678. renderContextData.currentPass = null;
  679. } else {
  680. const currentPass = encoder.beginRenderPass( descriptor );
  681. renderContextData.currentPass = currentPass;
  682. if ( renderContext.viewport ) {
  683. this.updateViewport( renderContext );
  684. }
  685. if ( renderContext.scissor ) {
  686. this.updateScissor( renderContext );
  687. }
  688. }
  689. //
  690. renderContextData.descriptor = descriptor;
  691. renderContextData.encoder = encoder;
  692. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  693. renderContextData.renderBundles = [];
  694. }
  695. /**
  696. * Creates render pass descriptors for each camera in an array camera.
  697. *
  698. * @param {RenderContext} renderContext - The render context.
  699. * @param {Object} renderContextData - The render context data.
  700. * @param {Object} descriptor - The render pass descriptor.
  701. * @param {ArrayCamera} cameras - The array camera.
  702. *
  703. * @private
  704. */
  705. _createArrayCameraLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  706. const depthStencilAttachment = descriptor.depthStencilAttachment;
  707. renderContextData.layerDescriptors = [];
  708. const depthTextureData = this.get( renderContext.depthTexture );
  709. if ( ! depthTextureData.viewCache ) {
  710. depthTextureData.viewCache = [];
  711. }
  712. for ( let i = 0; i < cameras.length; i ++ ) {
  713. const sourceAttachment = descriptor.colorAttachments[ 0 ];
  714. const layerColorAttachment = new GPURenderPassColorAttachment();
  715. layerColorAttachment.view = descriptor.colorAttachments[ i ].view;
  716. layerColorAttachment.depthSlice = sourceAttachment.depthSlice;
  717. layerColorAttachment.resolveTarget = sourceAttachment.resolveTarget;
  718. layerColorAttachment.loadOp = sourceAttachment.loadOp;
  719. layerColorAttachment.storeOp = sourceAttachment.storeOp;
  720. layerColorAttachment.clearValue = sourceAttachment.clearValue;
  721. const layerDescriptor = new GPURenderPassDescriptor();
  722. layerDescriptor.label = descriptor.label;
  723. layerDescriptor.occlusionQuerySet = descriptor.occlusionQuerySet;
  724. layerDescriptor.timestampWrites = descriptor.timestampWrites;
  725. layerDescriptor.colorAttachments.push( layerColorAttachment );
  726. if ( descriptor.depthStencilAttachment ) {
  727. const layerIndex = i;
  728. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  729. _viewDescriptor.dimension = GPUTextureViewDimension.TwoD;
  730. _viewDescriptor.baseArrayLayer = i;
  731. _viewDescriptor.arrayLayerCount = 1;
  732. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( _viewDescriptor );
  733. _viewDescriptor.reset();
  734. }
  735. const layerDepthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  736. layerDepthStencilAttachment.view = depthTextureData.viewCache[ layerIndex ];
  737. layerDepthStencilAttachment.depthLoadOp = depthStencilAttachment.depthLoadOp || GPULoadOp.Clear;
  738. layerDepthStencilAttachment.depthStoreOp = depthStencilAttachment.depthStoreOp || GPUStoreOp.Store;
  739. layerDepthStencilAttachment.depthClearValue = depthStencilAttachment.depthClearValue || 1.0;
  740. if ( renderContext.stencil ) {
  741. layerDepthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  742. layerDepthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  743. layerDepthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  744. }
  745. layerDescriptor.depthStencilAttachment = layerDepthStencilAttachment;
  746. } else {
  747. const layerDepthStencilAttachment = new GPURenderPassDepthStencilAttachment();
  748. layerDepthStencilAttachment.view = depthStencilAttachment.view;
  749. layerDepthStencilAttachment.depthLoadOp = depthStencilAttachment.depthLoadOp;
  750. layerDepthStencilAttachment.depthStoreOp = depthStencilAttachment.depthStoreOp;
  751. layerDepthStencilAttachment.depthClearValue = depthStencilAttachment.depthClearValue;
  752. layerDepthStencilAttachment.depthReadOnly = depthStencilAttachment.depthReadOnly;
  753. layerDepthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  754. layerDepthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  755. layerDepthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  756. layerDepthStencilAttachment.stencilReadOnly = depthStencilAttachment.stencilReadOnly;
  757. layerDescriptor.depthStencilAttachment = layerDepthStencilAttachment;
  758. }
  759. renderContextData.layerDescriptors.push( layerDescriptor );
  760. }
  761. }
  762. /**
  763. * Updates render pass descriptors for each camera in an array camera.
  764. *
  765. * @param {RenderContext} renderContext - The render context.
  766. * @param {Object} renderContextData - The render context data.
  767. * @param {ArrayCamera} cameras - The array camera.
  768. *
  769. */
  770. _updateArrayCameraLayerDescriptors( renderContext, renderContextData, cameras ) {
  771. for ( let i = 0; i < cameras.length; i ++ ) {
  772. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  773. if ( layerDescriptor.depthStencilAttachment ) {
  774. const depthAttachment = layerDescriptor.depthStencilAttachment;
  775. if ( renderContext.depth ) {
  776. if ( renderContext.clearDepth ) {
  777. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  778. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  779. } else {
  780. depthAttachment.depthLoadOp = GPULoadOp.Load;
  781. }
  782. }
  783. if ( renderContext.stencil ) {
  784. if ( renderContext.clearStencil ) {
  785. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  786. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  787. } else {
  788. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  789. }
  790. }
  791. }
  792. }
  793. }
  794. /**
  795. * This method is executed at the end of a render call and finalizes work
  796. * after draw calls.
  797. *
  798. * @param {RenderContext} renderContext - The render context.
  799. */
  800. finishRender( renderContext ) {
  801. const renderContextData = this.get( renderContext );
  802. const occlusionQueryCount = renderContext.occlusionQueryCount;
  803. if ( renderContextData.renderBundles.length > 0 ) {
  804. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  805. }
  806. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  807. renderContextData.currentPass.endOcclusionQuery();
  808. }
  809. // Layered render targets: execute the bundle for each layer.
  810. const encoder = renderContextData.encoder;
  811. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  812. const bundles = [];
  813. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  814. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  815. bundles.push( bundleEncoder.finish() );
  816. }
  817. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  818. if ( i < bundles.length ) {
  819. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  820. const renderPass = encoder.beginRenderPass( layerDescriptor );
  821. if ( renderContext.viewport ) {
  822. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  823. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  824. }
  825. if ( renderContext.scissor ) {
  826. const { x, y, width, height } = renderContext.scissorValue;
  827. renderPass.setScissorRect( x, y, width, height );
  828. }
  829. renderPass.executeBundles( [ bundles[ i ] ] );
  830. renderPass.end();
  831. }
  832. }
  833. } else if ( renderContextData.currentPass ) {
  834. renderContextData.currentPass.end();
  835. }
  836. if ( occlusionQueryCount > 0 ) {
  837. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  838. //
  839. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  840. if ( queryResolveBuffer === undefined ) {
  841. _bufferDescriptor.size = bufferSize;
  842. _bufferDescriptor.usage = GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC;
  843. queryResolveBuffer = this.device.createBuffer( _bufferDescriptor );
  844. _bufferDescriptor.reset();
  845. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  846. }
  847. //
  848. _bufferDescriptor.size = bufferSize;
  849. _bufferDescriptor.usage = GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ;
  850. const readBuffer = this.device.createBuffer( _bufferDescriptor );
  851. _bufferDescriptor.reset();
  852. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  853. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  854. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  855. renderContextData.occlusionQueryBuffer = readBuffer;
  856. //
  857. this.resolveOccludedAsync( renderContext );
  858. }
  859. submit( this.device, renderContextData.encoder.finish() );
  860. //
  861. if ( renderContext.textures !== null ) {
  862. const textures = renderContext.textures;
  863. for ( let i = 0; i < textures.length; i ++ ) {
  864. const texture = textures[ i ];
  865. if ( texture.generateMipmaps === true ) {
  866. this.textureUtils.generateMipmaps( texture );
  867. }
  868. }
  869. }
  870. }
  871. /**
  872. * Returns `true` if the given 3D object is fully occluded by other
  873. * 3D objects in the scene.
  874. *
  875. * @param {RenderContext} renderContext - The render context.
  876. * @param {Object3D} object - The 3D object to test.
  877. * @return {boolean} Whether the 3D object is fully occluded or not.
  878. */
  879. isOccluded( renderContext, object ) {
  880. const renderContextData = this.get( renderContext );
  881. return renderContextData.occluded && renderContextData.occluded.has( object );
  882. }
  883. /**
  884. * This method processes the result of occlusion queries and writes it
  885. * into render context data.
  886. *
  887. * @async
  888. * @param {RenderContext} renderContext - The render context.
  889. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  890. */
  891. async resolveOccludedAsync( renderContext ) {
  892. const renderContextData = this.get( renderContext );
  893. // handle occlusion query results
  894. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  895. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  896. const occluded = new WeakSet();
  897. renderContextData.currentOcclusionQueryObjects = null;
  898. renderContextData.currentOcclusionQueryBuffer = null;
  899. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  900. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  901. const results = new BigUint64Array( buffer );
  902. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  903. if ( results[ i ] === BigInt( 0 ) ) {
  904. occluded.add( currentOcclusionQueryObjects[ i ] );
  905. }
  906. }
  907. currentOcclusionQueryBuffer.destroy();
  908. renderContextData.occluded = occluded;
  909. }
  910. }
  911. /**
  912. * Updates the viewport with the values from the given render context.
  913. *
  914. * @param {RenderContext} renderContext - The render context.
  915. */
  916. updateViewport( renderContext ) {
  917. const { currentPass } = this.get( renderContext );
  918. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  919. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  920. }
  921. /**
  922. * Updates the scissor with the values from the given render context.
  923. *
  924. * @param {RenderContext} renderContext - The render context.
  925. */
  926. updateScissor( renderContext ) {
  927. const { currentPass } = this.get( renderContext );
  928. const { x, y, width, height } = renderContext.scissorValue;
  929. currentPass.setScissorRect( x, y, width, height );
  930. }
  931. /**
  932. * Returns the clear color and alpha into a single
  933. * color object.
  934. *
  935. * @return {Color4} The clear color.
  936. */
  937. getClearColor() {
  938. const clearColor = super.getClearColor();
  939. // only premultiply alpha when alphaMode is "premultiplied"
  940. if ( this.renderer.alpha === true ) {
  941. clearColor.r *= clearColor.a;
  942. clearColor.g *= clearColor.a;
  943. clearColor.b *= clearColor.a;
  944. }
  945. return clearColor;
  946. }
  947. /**
  948. * Performs a clear operation.
  949. *
  950. * @param {boolean} color - Whether the color buffer should be cleared or not.
  951. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  952. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  953. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  954. */
  955. clear( color, depth, stencil, renderTargetContext = null ) {
  956. const device = this.device;
  957. const renderer = this.renderer;
  958. let colorAttachments = [];
  959. let depthStencilAttachment;
  960. let supportsDepth;
  961. let supportsStencil;
  962. if ( color ) {
  963. const clearColor = this.getClearColor();
  964. _clearValue.r = clearColor.r;
  965. _clearValue.g = clearColor.g;
  966. _clearValue.b = clearColor.b;
  967. _clearValue.a = clearColor.a;
  968. }
  969. if ( renderTargetContext === null ) {
  970. supportsDepth = renderer.depth;
  971. supportsStencil = renderer.stencil;
  972. const descriptor = this._getDefaultRenderPassDescriptor();
  973. if ( color ) {
  974. colorAttachments = descriptor.colorAttachments;
  975. const colorAttachment = colorAttachments[ 0 ];
  976. colorAttachment.clearValue = _clearValue;
  977. colorAttachment.loadOp = GPULoadOp.Clear;
  978. colorAttachment.storeOp = GPUStoreOp.Store;
  979. }
  980. if ( supportsDepth || supportsStencil ) {
  981. depthStencilAttachment = descriptor.depthStencilAttachment;
  982. }
  983. } else {
  984. supportsDepth = renderTargetContext.depth;
  985. supportsStencil = renderTargetContext.stencil;
  986. const clearConfig = {
  987. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  988. clearValue: color ? _clearValue : undefined
  989. };
  990. if ( supportsDepth ) {
  991. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  992. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  993. clearConfig.depthStoreOp = GPUStoreOp.Store;
  994. }
  995. if ( supportsStencil ) {
  996. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  997. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  998. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  999. }
  1000. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  1001. colorAttachments = descriptor.colorAttachments;
  1002. depthStencilAttachment = descriptor.depthStencilAttachment;
  1003. }
  1004. if ( supportsDepth && depthStencilAttachment ) {
  1005. if ( depth ) {
  1006. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  1007. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  1008. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  1009. } else {
  1010. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  1011. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  1012. }
  1013. }
  1014. //
  1015. if ( supportsStencil && depthStencilAttachment ) {
  1016. if ( stencil ) {
  1017. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  1018. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  1019. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  1020. } else {
  1021. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  1022. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  1023. }
  1024. }
  1025. //
  1026. _commandEncoderDescriptor.label = 'clear';
  1027. const encoder = device.createCommandEncoder( _commandEncoderDescriptor );
  1028. _commandEncoderDescriptor.reset();
  1029. const currentPass = encoder.beginRenderPass( {
  1030. colorAttachments,
  1031. depthStencilAttachment
  1032. } );
  1033. currentPass.end();
  1034. submit( device, encoder.finish() );
  1035. }
  1036. // compute
  1037. /**
  1038. * This method is executed at the beginning of a compute call and
  1039. * prepares the state for upcoming compute tasks.
  1040. *
  1041. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  1042. */
  1043. beginCompute( computeGroup ) {
  1044. const groupGPU = this.get( computeGroup );
  1045. //
  1046. const label = 'computeGroup_' + computeGroup.id;
  1047. _computePassDescriptor.label = label;
  1048. _commandEncoderDescriptor.label = label;
  1049. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), _computePassDescriptor );
  1050. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( _commandEncoderDescriptor );
  1051. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( _computePassDescriptor );
  1052. _commandEncoderDescriptor.reset();
  1053. _computePassDescriptor.reset();
  1054. }
  1055. /**
  1056. * Executes a compute command for the given compute node.
  1057. *
  1058. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  1059. * @param {Node} computeNode - The compute node.
  1060. * @param {Array<BindGroup>} bindings - The bindings.
  1061. * @param {ComputePipeline} pipeline - The compute pipeline.
  1062. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  1063. * - A single number representing count, or
  1064. * - An array [x, y, z] representing dispatch size, or
  1065. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  1066. */
  1067. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  1068. const computeNodeData = this.get( computeNode );
  1069. const { passEncoderGPU } = this.get( computeGroup );
  1070. // pipeline
  1071. const pipelineGPU = this.get( pipeline ).pipeline;
  1072. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  1073. // bind groups
  1074. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  1075. const bindGroup = bindings[ i ];
  1076. const bindingsData = this.get( bindGroup );
  1077. passEncoderGPU.setBindGroup( i, bindingsData.group );
  1078. }
  1079. if ( dispatchSize === null ) {
  1080. dispatchSize = computeNode.dispatchSize || computeNode.count;
  1081. }
  1082. // When the dispatchSize is set with a StorageBuffer from the GPU.
  1083. if ( dispatchSize && dispatchSize.isIndirectStorageBufferAttribute ) {
  1084. const dispatchBuffer = this.get( dispatchSize ).buffer;
  1085. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  1086. return;
  1087. }
  1088. if ( typeof dispatchSize === 'number' ) {
  1089. // If a single number is given, we calculate the dispatch size based on the workgroup size
  1090. const count = dispatchSize;
  1091. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  1092. // cache dispatch size to avoid recalculating it every time
  1093. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  1094. computeNodeData.count = count;
  1095. const workgroupSize = computeNode.workgroupSize;
  1096. let size = workgroupSize[ 0 ];
  1097. for ( let i = 1; i < workgroupSize.length; i ++ )
  1098. size *= workgroupSize[ i ];
  1099. const dispatchCount = Math.ceil( count / size );
  1100. //
  1101. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  1102. dispatchSize = [ dispatchCount, 1, 1 ];
  1103. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  1104. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  1105. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  1106. }
  1107. computeNodeData.dispatchSize = dispatchSize;
  1108. }
  1109. dispatchSize = computeNodeData.dispatchSize;
  1110. }
  1111. //
  1112. passEncoderGPU.dispatchWorkgroups(
  1113. dispatchSize[ 0 ],
  1114. dispatchSize[ 1 ] || 1,
  1115. dispatchSize[ 2 ] || 1
  1116. );
  1117. }
  1118. /**
  1119. * This method is executed at the end of a compute call and
  1120. * finalizes work after compute tasks.
  1121. *
  1122. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  1123. */
  1124. finishCompute( computeGroup ) {
  1125. const groupData = this.get( computeGroup );
  1126. groupData.passEncoderGPU.end();
  1127. submit( this.device, groupData.cmdEncoderGPU.finish() );
  1128. }
  1129. /**
  1130. * Internal draw function that performs the draw with the given pass encoder.
  1131. *
  1132. * @private
  1133. * @param {RenderObject} renderObject - The render object.
  1134. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  1135. * @param {Object} renderContextData - The render context data object, holding current pass state and occlusion query tracking.
  1136. * @param {GPURenderPipeline} pipelineGPU - The GPU render pipeline.
  1137. * @param {Array<BindGroup>} bindings - The bind groups.
  1138. * @param {Array<BufferAttribute>} vertexBuffers - The vertex buffers.
  1139. * @param {{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} drawParams - The draw parameters.
  1140. * @param {GPURenderPassEncoder|GPURenderBundleEncoder} passEncoderGPU - The GPU pass encoder used for recording draw commands.
  1141. * @param {Object} currentSets - Tracking object for currently set pipeline, attributes, bind groups, and index state.
  1142. */
  1143. _draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, passEncoderGPU, currentSets ) {
  1144. const { object, material, context } = renderObject;
  1145. const index = renderObject.getIndex();
  1146. const hasIndex = ( index !== null );
  1147. // pipeline
  1148. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  1149. currentSets.pipeline = pipelineGPU;
  1150. // bind groups
  1151. const currentBindingGroups = currentSets.bindingGroups;
  1152. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  1153. const bindGroup = bindings[ i ];
  1154. const bindingsData = this.get( bindGroup );
  1155. if ( currentBindingGroups[ i ] !== bindGroup.id ) {
  1156. passEncoderGPU.setBindGroup( i, bindingsData.group );
  1157. currentBindingGroups[ i ] = bindGroup.id;
  1158. }
  1159. }
  1160. // attributes
  1161. // index
  1162. if ( hasIndex === true ) {
  1163. if ( currentSets.index !== index ) {
  1164. const buffer = this.get( index ).buffer;
  1165. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  1166. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  1167. currentSets.index = index;
  1168. }
  1169. }
  1170. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  1171. const vertexBuffer = vertexBuffers[ i ];
  1172. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  1173. const buffer = this.get( vertexBuffer ).buffer;
  1174. passEncoderGPU.setVertexBuffer( i, buffer );
  1175. currentSets.attributes[ i ] = vertexBuffer;
  1176. }
  1177. }
  1178. // stencil
  1179. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  1180. passEncoderGPU.setStencilReference( material.stencilRef );
  1181. renderContextData.currentStencilRef = material.stencilRef;
  1182. }
  1183. if ( object.isBatchedMesh === true ) {
  1184. const starts = object._multiDrawStarts;
  1185. const counts = object._multiDrawCounts;
  1186. const drawCount = object._multiDrawCount;
  1187. let bytesPerElement = ( hasIndex === true ) ? index.array.BYTES_PER_ELEMENT : 1;
  1188. if ( material.wireframe ) {
  1189. bytesPerElement = object.geometry.attributes.position.count > 65535 ? 4 : 2;
  1190. }
  1191. for ( let i = 0; i < drawCount; i ++ ) {
  1192. if ( hasIndex === true ) {
  1193. passEncoderGPU.drawIndexed( counts[ i ], 1, starts[ i ] / bytesPerElement, 0, i );
  1194. } else {
  1195. passEncoderGPU.draw( counts[ i ], 1, starts[ i ], i );
  1196. }
  1197. info.update( object, counts[ i ], 1 );
  1198. }
  1199. } else if ( hasIndex === true ) {
  1200. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  1201. const indirect = renderObject.getIndirect();
  1202. if ( indirect !== null ) {
  1203. const buffer = this.get( indirect ).buffer;
  1204. const indirectOffset = renderObject.getIndirectOffset();
  1205. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  1206. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  1207. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  1208. }
  1209. } else {
  1210. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  1211. }
  1212. info.update( object, indexCount, instanceCount );
  1213. } else {
  1214. const { vertexCount, instanceCount, firstVertex } = drawParams;
  1215. const indirect = renderObject.getIndirect();
  1216. if ( indirect !== null ) {
  1217. const buffer = this.get( indirect ).buffer;
  1218. const indirectOffset = renderObject.getIndirectOffset();
  1219. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  1220. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  1221. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  1222. }
  1223. } else {
  1224. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  1225. }
  1226. info.update( object, vertexCount, instanceCount );
  1227. }
  1228. }
  1229. // render object
  1230. /**
  1231. * Executes a draw command for the given render object.
  1232. *
  1233. * @param {RenderObject} renderObject - The render object to draw.
  1234. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  1235. */
  1236. draw( renderObject, info ) {
  1237. const { object, context, pipeline } = renderObject;
  1238. const renderContextData = this.get( context );
  1239. const pipelineData = this.get( pipeline );
  1240. const pipelineGPU = pipelineData.pipeline;
  1241. // Skip if pipeline has error
  1242. if ( pipelineData.error === true ) return;
  1243. const drawParams = renderObject.getDrawParameters();
  1244. if ( drawParams === null ) return;
  1245. const bindings = renderObject.getBindings();
  1246. // vertex buffers
  1247. const vertexBuffers = renderObject.getVertexBuffers();
  1248. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  1249. const cameraData = this.get( renderObject.camera );
  1250. const cameras = renderObject.camera.cameras;
  1251. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  1252. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  1253. const bindingsData = this.get( cameraIndex );
  1254. const indexesGPU = [];
  1255. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  1256. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  1257. data[ 0 ] = i;
  1258. const { layoutGPU } = bindingsData.layout;
  1259. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  1260. indexesGPU.push( bindGroupIndex );
  1261. }
  1262. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  1263. }
  1264. const pixelRatio = this.renderer.getPixelRatio();
  1265. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  1266. const subCamera = cameras[ i ];
  1267. if ( object.layers.test( subCamera.layers ) ) {
  1268. const vp = subCamera.viewport;
  1269. let pass = renderContextData.currentPass;
  1270. let sets = renderContextData.currentSets;
  1271. const isBundleEncoder = renderContextData.bundleEncoders !== undefined;
  1272. if ( isBundleEncoder ) {
  1273. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  1274. const bundleSets = renderContextData.bundleSets[ i ];
  1275. pass = bundleEncoder;
  1276. sets = bundleSets;
  1277. }
  1278. // GPURenderBundleEncoder does not support setViewport, only GPURenderPassEncoder does
  1279. if ( vp && ! isBundleEncoder ) {
  1280. pass.setViewport(
  1281. Math.floor( vp.x * pixelRatio ),
  1282. Math.floor( vp.y * pixelRatio ),
  1283. Math.floor( vp.width * pixelRatio ),
  1284. Math.floor( vp.height * pixelRatio ),
  1285. context.viewportValue.minDepth,
  1286. context.viewportValue.maxDepth
  1287. );
  1288. }
  1289. // Set camera index binding for this layer
  1290. if ( cameraIndex && cameraData.indexesGPU ) {
  1291. const indexPos = bindings.indexOf( cameraIndex );
  1292. pass.setBindGroup( indexPos, cameraData.indexesGPU[ i ] );
  1293. sets.bindingGroups[ indexPos ] = cameraIndex.id;
  1294. }
  1295. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, pass, sets );
  1296. }
  1297. }
  1298. } else {
  1299. // Regular single camera rendering
  1300. if ( renderContextData.currentPass ) {
  1301. // Handle occlusion queries
  1302. if ( renderContextData.occlusionQuerySet !== undefined ) {
  1303. const lastObject = renderContextData.lastOcclusionObject;
  1304. if ( lastObject !== object ) {
  1305. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  1306. renderContextData.currentPass.endOcclusionQuery();
  1307. renderContextData.occlusionQueryIndex ++;
  1308. }
  1309. if ( object.occlusionTest === true ) {
  1310. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  1311. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  1312. }
  1313. renderContextData.lastOcclusionObject = object;
  1314. }
  1315. }
  1316. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, renderContextData.currentPass, renderContextData.currentSets );
  1317. }
  1318. }
  1319. }
  1320. // cache key
  1321. /**
  1322. * Returns `true` if the render pipeline requires an update.
  1323. *
  1324. * @param {RenderObject} renderObject - The render object.
  1325. * @return {boolean} Whether the render pipeline requires an update or not.
  1326. */
  1327. needsRenderUpdate( renderObject ) {
  1328. const data = this.get( renderObject );
  1329. const { object, material } = renderObject;
  1330. const utils = this.utils;
  1331. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  1332. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  1333. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  1334. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  1335. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  1336. let needsUpdate = false;
  1337. if ( data.material !== material || data.materialVersion !== material.version ||
  1338. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  1339. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  1340. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  1341. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  1342. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  1343. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  1344. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  1345. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  1346. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  1347. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  1348. data.primitiveTopology !== primitiveTopology ||
  1349. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  1350. ) {
  1351. data.material = material; data.materialVersion = material.version;
  1352. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  1353. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  1354. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  1355. data.colorWrite = material.colorWrite;
  1356. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  1357. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  1358. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  1359. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  1360. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  1361. data.sampleCount = sampleCount;
  1362. data.colorSpace = colorSpace;
  1363. data.colorFormat = colorFormat;
  1364. data.depthStencilFormat = depthStencilFormat;
  1365. data.primitiveTopology = primitiveTopology;
  1366. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  1367. needsUpdate = true;
  1368. }
  1369. return needsUpdate;
  1370. }
  1371. /**
  1372. * Returns a cache key that is used to identify render pipelines.
  1373. *
  1374. * @param {RenderObject} renderObject - The render object.
  1375. * @return {string} The cache key.
  1376. */
  1377. getRenderCacheKey( renderObject ) {
  1378. const { object, material } = renderObject;
  1379. const utils = this.utils;
  1380. const renderContext = renderObject.context;
  1381. // meshes with negative scale have a different frontFace render pipeline
  1382. // descriptor value so the following must be honored in the cache key
  1383. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  1384. return [
  1385. material.transparent, material.blending, material.premultipliedAlpha,
  1386. material.blendSrc, material.blendDst, material.blendEquation,
  1387. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  1388. material.colorWrite,
  1389. material.depthWrite, material.depthTest, material.depthFunc,
  1390. material.stencilWrite, material.stencilFunc,
  1391. material.stencilFail, material.stencilZFail, material.stencilZPass,
  1392. material.stencilFuncMask, material.stencilWriteMask,
  1393. material.side,
  1394. frontFaceCW,
  1395. utils.getSampleCountRenderContext( renderContext ),
  1396. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  1397. utils.getPrimitiveTopology( object, material ),
  1398. renderObject.getGeometryCacheKey(),
  1399. renderObject.clippingContextCacheKey
  1400. ].join();
  1401. }
  1402. // textures
  1403. /**
  1404. * Updates a GPU sampler for the given texture.
  1405. *
  1406. * @param {Texture} texture - The texture to update the sampler for.
  1407. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  1408. * @return {string} The current sampler key.
  1409. */
  1410. updateSampler( texture, textureNode ) {
  1411. return this.textureUtils.updateSampler( texture, textureNode );
  1412. }
  1413. /**
  1414. * Creates a default texture for the given texture that can be used
  1415. * as a placeholder until the actual texture is ready for usage.
  1416. *
  1417. * @param {Texture} texture - The texture to create a default texture for.
  1418. * @return {boolean} Whether the sampler has been updated or not.
  1419. */
  1420. createDefaultTexture( texture ) {
  1421. return this.textureUtils.createDefaultTexture( texture );
  1422. }
  1423. /**
  1424. * Defines a texture on the GPU for the given texture object.
  1425. *
  1426. * @param {Texture} texture - The texture.
  1427. * @param {Object} [options={}] - Optional configuration parameter.
  1428. */
  1429. createTexture( texture, options ) {
  1430. this.textureUtils.createTexture( texture, options );
  1431. }
  1432. /**
  1433. * Uploads the updated texture data to the GPU.
  1434. *
  1435. * @param {Texture} texture - The texture.
  1436. * @param {Object} [options={}] - Optional configuration parameter.
  1437. */
  1438. updateTexture( texture, options ) {
  1439. this.textureUtils.updateTexture( texture, options );
  1440. }
  1441. /**
  1442. * Generates mipmaps for the given texture.
  1443. *
  1444. * @param {Texture} texture - The texture.
  1445. */
  1446. generateMipmaps( texture ) {
  1447. this.textureUtils.generateMipmaps( texture );
  1448. }
  1449. /**
  1450. * Destroys the GPU data for the given texture object.
  1451. *
  1452. * @param {Texture} texture - The texture.
  1453. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  1454. */
  1455. destroyTexture( texture, isDefaultTexture = false ) {
  1456. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  1457. }
  1458. /**
  1459. * Returns texture data as a typed array.
  1460. *
  1461. * @async
  1462. * @param {Texture} texture - The texture to copy.
  1463. * @param {number} x - The x coordinate of the copy origin.
  1464. * @param {number} y - The y coordinate of the copy origin.
  1465. * @param {number} width - The width of the copy.
  1466. * @param {number} height - The height of the copy.
  1467. * @param {number} faceIndex - The face index.
  1468. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  1469. */
  1470. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  1471. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  1472. }
  1473. /**
  1474. * Inits a time stamp query for the given render context.
  1475. *
  1476. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  1477. * @param {number} uid - Unique id for the context (e.g. render context id).
  1478. * @param {Object} descriptor - The query descriptor.
  1479. */
  1480. initTimestampQuery( type, uid, descriptor ) {
  1481. if ( ! this.trackTimestamp ) return;
  1482. if ( ! this.timestampQueryPool[ type ] ) {
  1483. // TODO: Variable maxQueries?
  1484. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  1485. }
  1486. const timestampQueryPool = this.timestampQueryPool[ type ];
  1487. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  1488. _renderPassTimestampWrites.querySet = timestampQueryPool.querySet;
  1489. _renderPassTimestampWrites.beginningOfPassWriteIndex = baseOffset;
  1490. _renderPassTimestampWrites.endOfPassWriteIndex = baseOffset + 1;
  1491. descriptor.timestampWrites = _renderPassTimestampWrites;
  1492. }
  1493. // node builder
  1494. /**
  1495. * Returns a node builder for the given render object.
  1496. *
  1497. * @param {RenderObject} object - The render object.
  1498. * @param {Renderer} renderer - The renderer.
  1499. * @return {WGSLNodeBuilder} The node builder.
  1500. */
  1501. createNodeBuilder( object, renderer ) {
  1502. return new WGSLNodeBuilder( object, renderer );
  1503. }
  1504. // program
  1505. /**
  1506. * Creates a shader program from the given programmable stage.
  1507. *
  1508. * @param {ProgrammableStage} program - The programmable stage.
  1509. */
  1510. createProgram( program ) {
  1511. const programGPU = this.get( program );
  1512. _shaderModuleDescriptor.label = program.stage + ( program.name !== '' ? `_${ program.name }` : '' );
  1513. _shaderModuleDescriptor.code = program.code;
  1514. programGPU.module = {
  1515. module: this.device.createShaderModule( _shaderModuleDescriptor ),
  1516. entryPoint: 'main'
  1517. };
  1518. _shaderModuleDescriptor.reset();
  1519. }
  1520. /**
  1521. * Destroys the shader program of the given programmable stage.
  1522. *
  1523. * @param {ProgrammableStage} program - The programmable stage.
  1524. */
  1525. destroyProgram( program ) {
  1526. this.delete( program );
  1527. }
  1528. // pipelines
  1529. /**
  1530. * Creates a render pipeline for the given render object.
  1531. *
  1532. * @param {RenderObject} renderObject - The render object.
  1533. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  1534. */
  1535. createRenderPipeline( renderObject, promises ) {
  1536. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  1537. }
  1538. /**
  1539. * Creates a compute pipeline for the given compute node.
  1540. *
  1541. * @param {ComputePipeline} computePipeline - The compute pipeline.
  1542. * @param {Array<BindGroup>} bindings - The bindings.
  1543. */
  1544. createComputePipeline( computePipeline, bindings ) {
  1545. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  1546. }
  1547. /**
  1548. * Prepares the state for encoding render bundles.
  1549. *
  1550. * @param {RenderContext} renderContext - The render context.
  1551. */
  1552. beginBundle( renderContext ) {
  1553. const renderContextData = this.get( renderContext );
  1554. renderContextData._currentPass = renderContextData.currentPass;
  1555. renderContextData._currentSets = renderContextData.currentSets;
  1556. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  1557. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  1558. }
  1559. /**
  1560. * After processing render bundles this method finalizes related work.
  1561. *
  1562. * @param {RenderContext} renderContext - The render context.
  1563. * @param {RenderBundle} bundle - The render bundle.
  1564. */
  1565. finishBundle( renderContext, bundle ) {
  1566. const renderContextData = this.get( renderContext );
  1567. const bundleEncoder = renderContextData.currentPass;
  1568. const bundleGPU = bundleEncoder.finish();
  1569. this.get( bundle ).bundleGPU = bundleGPU;
  1570. // restore render pass state
  1571. renderContextData.currentSets = renderContextData._currentSets;
  1572. renderContextData.currentPass = renderContextData._currentPass;
  1573. }
  1574. /**
  1575. * Adds a render bundle to the render context data.
  1576. *
  1577. * @param {RenderContext} renderContext - The render context.
  1578. * @param {RenderBundle} bundle - The render bundle to add.
  1579. */
  1580. addBundle( renderContext, bundle ) {
  1581. const renderContextData = this.get( renderContext );
  1582. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  1583. }
  1584. // bindings
  1585. /**
  1586. * Creates a uniform buffer.
  1587. *
  1588. * @param {Buffer} uniformBuffer - The uniform buffer.
  1589. */
  1590. createUniformBuffer( uniformBuffer ) {
  1591. const uniformBufferData = this.get( uniformBuffer );
  1592. if ( uniformBufferData.buffer === undefined ) {
  1593. const byteLength = uniformBuffer.byteLength;
  1594. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  1595. const visibilities = [];
  1596. if ( uniformBuffer.visibility & GPUShaderStage.VERTEX ) {
  1597. visibilities.push( 'vertex' );
  1598. }
  1599. if ( uniformBuffer.visibility & GPUShaderStage.FRAGMENT ) {
  1600. visibilities.push( 'fragment' );
  1601. }
  1602. if ( uniformBuffer.visibility & GPUShaderStage.COMPUTE ) {
  1603. visibilities.push( 'compute' );
  1604. }
  1605. const bufferVisibility = `(${visibilities.join( ',' )})`;
  1606. _bufferDescriptor.label = `bindingBuffer${uniformBuffer.id}_${uniformBuffer.name}_${bufferVisibility}`;
  1607. _bufferDescriptor.size = byteLength;
  1608. _bufferDescriptor.usage = usage;
  1609. const bufferGPU = this.device.createBuffer( _bufferDescriptor );
  1610. _bufferDescriptor.reset();
  1611. uniformBufferData.buffer = bufferGPU;
  1612. }
  1613. }
  1614. /**
  1615. * Destroys the GPU data for the given uniform buffer.
  1616. *
  1617. * @param {Buffer} uniformBuffer - The uniform buffer.
  1618. */
  1619. destroyUniformBuffer( uniformBuffer ) {
  1620. const uniformBufferData = this.get( uniformBuffer );
  1621. uniformBufferData.buffer.destroy();
  1622. this.delete( uniformBuffer );
  1623. }
  1624. /**
  1625. * Creates bindings from the given bind group definition.
  1626. *
  1627. * @param {BindGroup} bindGroup - The bind group.
  1628. * @param {Array<BindGroup>} bindings - Array of bind groups.
  1629. * @param {number} cacheIndex - The cache index.
  1630. * @param {number} version - The version.
  1631. */
  1632. createBindings( bindGroup, bindings, cacheIndex, version ) {
  1633. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  1634. }
  1635. /**
  1636. * Updates the given bind group definition.
  1637. *
  1638. * @param {BindGroup} bindGroup - The bind group.
  1639. * @param {Array<BindGroup>} bindings - Array of bind groups.
  1640. * @param {number} cacheIndex - The cache index.
  1641. * @param {number} version - The version.
  1642. */
  1643. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  1644. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  1645. }
  1646. /**
  1647. * Updates a buffer binding.
  1648. *
  1649. * @param {Buffer} binding - The buffer binding to update.
  1650. */
  1651. updateBinding( binding ) {
  1652. this.bindingUtils.updateBinding( binding );
  1653. }
  1654. /**
  1655. * Delete data associated with the current bind group.
  1656. *
  1657. * @param {BindGroup} bindGroup - The bind group.
  1658. */
  1659. deleteBindGroupData( bindGroup ) {
  1660. this.bindingUtils.deleteBindGroupData( bindGroup );
  1661. }
  1662. // attributes
  1663. /**
  1664. * Creates the buffer of an indexed shader attribute.
  1665. *
  1666. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  1667. */
  1668. createIndexAttribute( attribute ) {
  1669. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  1670. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  1671. usage |= GPUBufferUsage.STORAGE;
  1672. }
  1673. this.attributeUtils.createAttribute( attribute, usage );
  1674. }
  1675. /**
  1676. * Creates the GPU buffer of a shader attribute.
  1677. *
  1678. * @param {BufferAttribute} attribute - The buffer attribute.
  1679. */
  1680. createAttribute( attribute ) {
  1681. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1682. }
  1683. /**
  1684. * Creates the GPU buffer of a storage attribute.
  1685. *
  1686. * @param {BufferAttribute} attribute - The buffer attribute.
  1687. */
  1688. createStorageAttribute( attribute ) {
  1689. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1690. }
  1691. /**
  1692. * Creates the GPU buffer of an indirect storage attribute.
  1693. *
  1694. * @param {BufferAttribute} attribute - The buffer attribute.
  1695. */
  1696. createIndirectStorageAttribute( attribute ) {
  1697. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1698. }
  1699. /**
  1700. * Updates the GPU buffer of a shader attribute.
  1701. *
  1702. * @param {BufferAttribute} attribute - The buffer attribute to update.
  1703. */
  1704. updateAttribute( attribute ) {
  1705. this.attributeUtils.updateAttribute( attribute );
  1706. }
  1707. /**
  1708. * Destroys the GPU buffer of a shader attribute.
  1709. *
  1710. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  1711. */
  1712. destroyAttribute( attribute ) {
  1713. this.attributeUtils.destroyAttribute( attribute );
  1714. }
  1715. // canvas
  1716. /**
  1717. * Triggers an update of the default render pass descriptor.
  1718. */
  1719. updateSize() {
  1720. this.delete( this.renderer.getCanvasTarget() );
  1721. }
  1722. // utils public
  1723. /**
  1724. * Checks if the given feature is supported by the backend.
  1725. *
  1726. * @param {string} name - The feature's name.
  1727. * @return {boolean} Whether the feature is supported or not.
  1728. */
  1729. hasFeature( name ) {
  1730. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  1731. return this.device.features.has( name );
  1732. }
  1733. /**
  1734. * Copies data of the given source texture to the given destination texture.
  1735. *
  1736. * @param {Texture} srcTexture - The source texture.
  1737. * @param {Texture} dstTexture - The destination texture.
  1738. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  1739. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  1740. * @param {number} [srcLevel=0] - The mipmap level to copy.
  1741. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  1742. */
  1743. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  1744. let dstX = 0;
  1745. let dstY = 0;
  1746. let dstZ = 0;
  1747. let srcX = 0;
  1748. let srcY = 0;
  1749. let srcZ = 0;
  1750. let srcWidth = srcTexture.image.width;
  1751. let srcHeight = srcTexture.image.height;
  1752. let srcDepth = 1;
  1753. if ( srcRegion !== null ) {
  1754. if ( srcRegion.isBox3 === true ) {
  1755. srcX = srcRegion.min.x;
  1756. srcY = srcRegion.min.y;
  1757. srcZ = srcRegion.min.z;
  1758. srcWidth = srcRegion.max.x - srcRegion.min.x;
  1759. srcHeight = srcRegion.max.y - srcRegion.min.y;
  1760. srcDepth = srcRegion.max.z - srcRegion.min.z;
  1761. } else {
  1762. // Assume it's a Box2
  1763. srcX = srcRegion.min.x;
  1764. srcY = srcRegion.min.y;
  1765. srcWidth = srcRegion.max.x - srcRegion.min.x;
  1766. srcHeight = srcRegion.max.y - srcRegion.min.y;
  1767. srcDepth = 1;
  1768. }
  1769. }
  1770. if ( dstPosition !== null ) {
  1771. dstX = dstPosition.x;
  1772. dstY = dstPosition.y;
  1773. dstZ = dstPosition.z || 0;
  1774. }
  1775. _commandEncoderDescriptor.label = 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id;
  1776. const encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  1777. _commandEncoderDescriptor.reset();
  1778. const sourceGPU = this.get( srcTexture ).texture;
  1779. const destinationGPU = this.get( dstTexture ).texture;
  1780. _texelCopyTextureInfoSrc.texture = sourceGPU;
  1781. _texelCopyTextureInfoSrc.mipLevel = srcLevel;
  1782. _texelCopyTextureInfoSrc.origin.x = srcX;
  1783. _texelCopyTextureInfoSrc.origin.y = srcY;
  1784. _texelCopyTextureInfoSrc.origin.z = srcZ;
  1785. _texelCopyTextureInfoDst.texture = destinationGPU;
  1786. _texelCopyTextureInfoDst.mipLevel = dstLevel;
  1787. _texelCopyTextureInfoDst.origin.x = dstX;
  1788. _texelCopyTextureInfoDst.origin.y = dstY;
  1789. _texelCopyTextureInfoDst.origin.z = dstZ;
  1790. _extent3D.width = srcWidth;
  1791. _extent3D.height = srcHeight;
  1792. _extent3D.depthOrArrayLayers = srcDepth;
  1793. encoder.copyTextureToTexture(
  1794. _texelCopyTextureInfoSrc,
  1795. _texelCopyTextureInfoDst,
  1796. _extent3D
  1797. );
  1798. _texelCopyTextureInfoSrc.reset();
  1799. _texelCopyTextureInfoDst.reset();
  1800. _extent3D.reset();
  1801. submit( this.device, encoder.finish() );
  1802. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  1803. this.textureUtils.generateMipmaps( dstTexture );
  1804. }
  1805. }
  1806. /**
  1807. * Copies the current bound framebuffer to the given texture.
  1808. *
  1809. * @param {Texture} texture - The destination texture.
  1810. * @param {RenderContext} renderContext - The render context.
  1811. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  1812. */
  1813. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  1814. const renderContextData = this.get( renderContext );
  1815. let sourceGPU = null;
  1816. if ( renderContext.renderTarget ) {
  1817. if ( texture.isDepthTexture ) {
  1818. sourceGPU = this.get( renderContext.depthTexture ).texture;
  1819. } else {
  1820. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  1821. }
  1822. } else {
  1823. if ( texture.isDepthTexture ) {
  1824. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  1825. } else {
  1826. sourceGPU = this.context.getCurrentTexture();
  1827. }
  1828. }
  1829. const destinationGPU = this.get( texture ).texture;
  1830. if ( sourceGPU.format !== destinationGPU.format ) {
  1831. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  1832. return;
  1833. }
  1834. let encoder;
  1835. if ( renderContextData.currentPass ) {
  1836. renderContextData.currentPass.end();
  1837. encoder = renderContextData.encoder;
  1838. } else {
  1839. _commandEncoderDescriptor.label = 'copyFramebufferToTexture_' + texture.id;
  1840. encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  1841. _commandEncoderDescriptor.reset();
  1842. }
  1843. _texelCopyTextureInfoSrc.texture = sourceGPU;
  1844. _texelCopyTextureInfoSrc.origin.x = rectangle.x;
  1845. _texelCopyTextureInfoSrc.origin.y = rectangle.y;
  1846. _texelCopyTextureInfoDst.texture = destinationGPU;
  1847. _extent3D.width = rectangle.z;
  1848. _extent3D.height = rectangle.w;
  1849. encoder.copyTextureToTexture(
  1850. _texelCopyTextureInfoSrc,
  1851. _texelCopyTextureInfoDst,
  1852. _extent3D
  1853. );
  1854. _texelCopyTextureInfoSrc.reset();
  1855. _texelCopyTextureInfoDst.reset();
  1856. _extent3D.reset();
  1857. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  1858. // might be out-of-sync, see #31768
  1859. if ( texture.generateMipmaps ) {
  1860. this.textureUtils.generateMipmaps( texture, encoder );
  1861. }
  1862. if ( renderContextData.currentPass ) {
  1863. const { descriptor } = renderContextData;
  1864. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  1865. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  1866. }
  1867. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  1868. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  1869. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  1870. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  1871. if ( renderContext.viewport ) {
  1872. this.updateViewport( renderContext );
  1873. }
  1874. if ( renderContext.scissor ) {
  1875. this.updateScissor( renderContext );
  1876. }
  1877. } else {
  1878. submit( this.device, encoder.finish() );
  1879. }
  1880. }
  1881. /**
  1882. * Checks if the given compatibility is supported by the backend.
  1883. *
  1884. * @param {string} name - The compatibility name.
  1885. * @return {boolean} Whether the compatibility is supported or not.
  1886. */
  1887. hasCompatibility( name ) {
  1888. if ( this._compatibility[ name ] !== undefined ) {
  1889. return this._compatibility[ name ];
  1890. }
  1891. return super.hasCompatibility( name );
  1892. }
  1893. dispose() {
  1894. this.bindingUtils.dispose();
  1895. this.textureUtils.dispose();
  1896. if ( this.occludedResolveCache ) {
  1897. for ( const buffer of this.occludedResolveCache.values() ) {
  1898. buffer.destroy();
  1899. }
  1900. this.occludedResolveCache.clear();
  1901. }
  1902. if ( this.timestampQueryPool ) {
  1903. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  1904. if ( queryPool !== null ) queryPool.dispose();
  1905. }
  1906. }
  1907. if ( this.parameters.device === undefined && this.device !== null ) {
  1908. this.device.destroy();
  1909. }
  1910. }
  1911. }
  1912. export default WebGPUBackend;
粤ICP备19079148号