WebGPUBackend.js 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903
  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. groupGPU.currentPipeline = null;
  1053. _commandEncoderDescriptor.reset();
  1054. _computePassDescriptor.reset();
  1055. }
  1056. /**
  1057. * Executes a compute command for the given compute node.
  1058. *
  1059. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  1060. * @param {Node} computeNode - The compute node.
  1061. * @param {Array<BindGroup>} bindings - The bindings.
  1062. * @param {ComputePipeline} pipeline - The compute pipeline.
  1063. * @param {number|Array<number>|IndirectStorageBufferAttribute} [dispatchSize=null]
  1064. * - A single number representing count, or
  1065. * - An array [x, y, z] representing dispatch size, or
  1066. * - A IndirectStorageBufferAttribute for indirect dispatch size.
  1067. */
  1068. compute( computeGroup, computeNode, bindings, pipeline, dispatchSize = null ) {
  1069. const computeNodeData = this.get( computeNode );
  1070. const groupGPU = this.get( computeGroup );
  1071. const { passEncoderGPU } = groupGPU;
  1072. // pipeline
  1073. const pipelineGPU = this.get( pipeline ).pipeline;
  1074. if ( groupGPU.currentPipeline !== pipelineGPU ) {
  1075. passEncoderGPU.setPipeline( pipelineGPU );
  1076. groupGPU.currentPipeline = pipelineGPU;
  1077. }
  1078. // bind groups
  1079. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  1080. const bindGroup = bindings[ i ];
  1081. const bindingsData = this.get( bindGroup );
  1082. passEncoderGPU.setBindGroup( i, bindingsData.group );
  1083. }
  1084. if ( dispatchSize === null ) {
  1085. dispatchSize = computeNode.dispatchSize || computeNode.count;
  1086. }
  1087. // When the dispatchSize is set with a StorageBuffer from the GPU.
  1088. if ( dispatchSize && dispatchSize.isIndirectStorageBufferAttribute ) {
  1089. const dispatchBuffer = this.get( dispatchSize ).buffer;
  1090. passEncoderGPU.dispatchWorkgroupsIndirect( dispatchBuffer, 0 );
  1091. return;
  1092. }
  1093. if ( typeof dispatchSize === 'number' ) {
  1094. // If a single number is given, we calculate the dispatch size based on the workgroup size
  1095. const count = dispatchSize;
  1096. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  1097. // cache dispatch size to avoid recalculating it every time
  1098. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  1099. computeNodeData.count = count;
  1100. const workgroupSize = computeNode.workgroupSize;
  1101. let size = workgroupSize[ 0 ];
  1102. for ( let i = 1; i < workgroupSize.length; i ++ )
  1103. size *= workgroupSize[ i ];
  1104. const dispatchCount = Math.ceil( count / size );
  1105. //
  1106. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  1107. dispatchSize = [ dispatchCount, 1, 1 ];
  1108. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  1109. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  1110. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  1111. }
  1112. computeNodeData.dispatchSize = dispatchSize;
  1113. }
  1114. dispatchSize = computeNodeData.dispatchSize;
  1115. }
  1116. //
  1117. passEncoderGPU.dispatchWorkgroups(
  1118. dispatchSize[ 0 ],
  1119. dispatchSize[ 1 ] || 1,
  1120. dispatchSize[ 2 ] || 1
  1121. );
  1122. }
  1123. /**
  1124. * This method is executed at the end of a compute call and
  1125. * finalizes work after compute tasks.
  1126. *
  1127. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  1128. */
  1129. finishCompute( computeGroup ) {
  1130. const groupData = this.get( computeGroup );
  1131. groupData.passEncoderGPU.end();
  1132. submit( this.device, groupData.cmdEncoderGPU.finish() );
  1133. }
  1134. /**
  1135. * Internal draw function that performs the draw with the given pass encoder.
  1136. *
  1137. * @private
  1138. * @param {RenderObject} renderObject - The render object.
  1139. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  1140. * @param {Object} renderContextData - The render context data object, holding current pass state and occlusion query tracking.
  1141. * @param {GPURenderPipeline} pipelineGPU - The GPU render pipeline.
  1142. * @param {Array<BindGroup>} bindings - The bind groups.
  1143. * @param {Array<BufferAttribute>} vertexBuffers - The vertex buffers.
  1144. * @param {{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} drawParams - The draw parameters.
  1145. * @param {GPURenderPassEncoder|GPURenderBundleEncoder} passEncoderGPU - The GPU pass encoder used for recording draw commands.
  1146. * @param {Object} currentSets - Tracking object for currently set pipeline, attributes, bind groups, and index state.
  1147. */
  1148. _draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, passEncoderGPU, currentSets ) {
  1149. const { object, material, context } = renderObject;
  1150. const index = renderObject.getIndex();
  1151. const hasIndex = ( index !== null );
  1152. // pipeline
  1153. if ( currentSets.pipeline !== pipelineGPU ) {
  1154. passEncoderGPU.setPipeline( pipelineGPU );
  1155. currentSets.pipeline = pipelineGPU;
  1156. }
  1157. // bind groups
  1158. const currentBindingGroups = currentSets.bindingGroups;
  1159. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  1160. const bindGroup = bindings[ i ];
  1161. if ( currentBindingGroups[ i ] !== bindGroup.id ) {
  1162. const bindingsData = this.get( bindGroup );
  1163. passEncoderGPU.setBindGroup( i, bindingsData.group );
  1164. currentBindingGroups[ i ] = bindGroup.id;
  1165. }
  1166. }
  1167. // attributes
  1168. // index
  1169. if ( hasIndex === true ) {
  1170. if ( currentSets.index !== index ) {
  1171. const buffer = this.get( index ).buffer;
  1172. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  1173. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  1174. currentSets.index = index;
  1175. }
  1176. }
  1177. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  1178. const vertexBuffer = vertexBuffers[ i ];
  1179. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  1180. const buffer = this.get( vertexBuffer ).buffer;
  1181. passEncoderGPU.setVertexBuffer( i, buffer );
  1182. currentSets.attributes[ i ] = vertexBuffer;
  1183. }
  1184. }
  1185. // stencil
  1186. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  1187. passEncoderGPU.setStencilReference( material.stencilRef );
  1188. renderContextData.currentStencilRef = material.stencilRef;
  1189. }
  1190. if ( object.isBatchedMesh === true ) {
  1191. const starts = object._multiDrawStarts;
  1192. const counts = object._multiDrawCounts;
  1193. const drawCount = object._multiDrawCount;
  1194. let bytesPerElement = ( hasIndex === true ) ? index.array.BYTES_PER_ELEMENT : 1;
  1195. if ( material.wireframe ) {
  1196. bytesPerElement = object.geometry.attributes.position.count > 65535 ? 4 : 2;
  1197. }
  1198. for ( let i = 0; i < drawCount; i ++ ) {
  1199. if ( hasIndex === true ) {
  1200. passEncoderGPU.drawIndexed( counts[ i ], 1, starts[ i ] / bytesPerElement, 0, i );
  1201. } else {
  1202. passEncoderGPU.draw( counts[ i ], 1, starts[ i ], i );
  1203. }
  1204. info.update( object, counts[ i ], 1 );
  1205. }
  1206. } else if ( hasIndex === true ) {
  1207. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  1208. const indirect = renderObject.getIndirect();
  1209. if ( indirect !== null ) {
  1210. const buffer = this.get( indirect ).buffer;
  1211. const indirectOffset = renderObject.getIndirectOffset();
  1212. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  1213. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  1214. passEncoderGPU.drawIndexedIndirect( buffer, indirectOffsets[ i ] );
  1215. }
  1216. } else {
  1217. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  1218. }
  1219. info.update( object, indexCount, instanceCount );
  1220. } else {
  1221. const { vertexCount, instanceCount, firstVertex } = drawParams;
  1222. const indirect = renderObject.getIndirect();
  1223. if ( indirect !== null ) {
  1224. const buffer = this.get( indirect ).buffer;
  1225. const indirectOffset = renderObject.getIndirectOffset();
  1226. const indirectOffsets = Array.isArray( indirectOffset ) ? indirectOffset : [ indirectOffset ];
  1227. for ( let i = 0; i < indirectOffsets.length; i ++ ) {
  1228. passEncoderGPU.drawIndirect( buffer, indirectOffsets[ i ] );
  1229. }
  1230. } else {
  1231. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  1232. }
  1233. info.update( object, vertexCount, instanceCount );
  1234. }
  1235. }
  1236. // render object
  1237. /**
  1238. * Executes a draw command for the given render object.
  1239. *
  1240. * @param {RenderObject} renderObject - The render object to draw.
  1241. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  1242. */
  1243. draw( renderObject, info ) {
  1244. const { object, context, pipeline } = renderObject;
  1245. const renderContextData = this.get( context );
  1246. const pipelineData = this.get( pipeline );
  1247. const pipelineGPU = pipelineData.pipeline;
  1248. // Skip if pipeline has error
  1249. if ( pipelineData.error === true ) return;
  1250. const drawParams = renderObject.getDrawParameters();
  1251. if ( drawParams === null ) return;
  1252. const bindings = renderObject.getBindings();
  1253. // vertex buffers
  1254. const vertexBuffers = renderObject.getVertexBuffers();
  1255. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  1256. const cameraData = this.get( renderObject.camera );
  1257. const cameras = renderObject.camera.cameras;
  1258. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  1259. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  1260. const bindingsData = this.get( cameraIndex );
  1261. const indexesGPU = [];
  1262. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  1263. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  1264. data[ 0 ] = i;
  1265. const { layoutGPU } = bindingsData.layout;
  1266. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, layoutGPU );
  1267. indexesGPU.push( bindGroupIndex );
  1268. }
  1269. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  1270. }
  1271. const pixelRatio = this.renderer.getPixelRatio();
  1272. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  1273. const subCamera = cameras[ i ];
  1274. if ( object.layers.test( subCamera.layers ) ) {
  1275. const vp = subCamera.viewport;
  1276. let pass = renderContextData.currentPass;
  1277. let sets = renderContextData.currentSets;
  1278. const isBundleEncoder = renderContextData.bundleEncoders !== undefined;
  1279. if ( isBundleEncoder ) {
  1280. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  1281. const bundleSets = renderContextData.bundleSets[ i ];
  1282. pass = bundleEncoder;
  1283. sets = bundleSets;
  1284. }
  1285. // GPURenderBundleEncoder does not support setViewport, only GPURenderPassEncoder does
  1286. if ( vp && ! isBundleEncoder ) {
  1287. pass.setViewport(
  1288. Math.floor( vp.x * pixelRatio ),
  1289. Math.floor( vp.y * pixelRatio ),
  1290. Math.floor( vp.width * pixelRatio ),
  1291. Math.floor( vp.height * pixelRatio ),
  1292. context.viewportValue.minDepth,
  1293. context.viewportValue.maxDepth
  1294. );
  1295. }
  1296. // Set camera index binding for this layer
  1297. if ( cameraIndex && cameraData.indexesGPU ) {
  1298. const indexPos = bindings.indexOf( cameraIndex );
  1299. pass.setBindGroup( indexPos, cameraData.indexesGPU[ i ] );
  1300. sets.bindingGroups[ indexPos ] = cameraIndex.id;
  1301. }
  1302. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, pass, sets );
  1303. }
  1304. }
  1305. } else {
  1306. // Regular single camera rendering
  1307. if ( renderContextData.currentPass ) {
  1308. // Handle occlusion queries
  1309. if ( renderContextData.occlusionQuerySet !== undefined ) {
  1310. const lastObject = renderContextData.lastOcclusionObject;
  1311. if ( lastObject !== object ) {
  1312. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  1313. renderContextData.currentPass.endOcclusionQuery();
  1314. renderContextData.occlusionQueryIndex ++;
  1315. }
  1316. if ( object.occlusionTest === true ) {
  1317. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  1318. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  1319. }
  1320. renderContextData.lastOcclusionObject = object;
  1321. }
  1322. }
  1323. this._draw( renderObject, info, renderContextData, pipelineGPU, bindings, vertexBuffers, drawParams, renderContextData.currentPass, renderContextData.currentSets );
  1324. }
  1325. }
  1326. }
  1327. // cache key
  1328. /**
  1329. * Returns `true` if the render pipeline requires an update.
  1330. *
  1331. * @param {RenderObject} renderObject - The render object.
  1332. * @return {boolean} Whether the render pipeline requires an update or not.
  1333. */
  1334. needsRenderUpdate( renderObject ) {
  1335. const data = this.get( renderObject );
  1336. const { object, material } = renderObject;
  1337. const utils = this.utils;
  1338. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  1339. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  1340. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  1341. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  1342. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  1343. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinantAffine() < 0 );
  1344. let needsUpdate = false;
  1345. if ( data.material !== material || data.materialVersion !== material.version ||
  1346. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  1347. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  1348. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  1349. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  1350. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  1351. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  1352. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  1353. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  1354. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  1355. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  1356. data.primitiveTopology !== primitiveTopology ||
  1357. data.frontFaceCW !== frontFaceCW ||
  1358. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  1359. ) {
  1360. data.material = material; data.materialVersion = material.version;
  1361. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  1362. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  1363. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  1364. data.colorWrite = material.colorWrite;
  1365. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  1366. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  1367. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  1368. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  1369. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  1370. data.sampleCount = sampleCount;
  1371. data.colorSpace = colorSpace;
  1372. data.colorFormat = colorFormat;
  1373. data.depthStencilFormat = depthStencilFormat;
  1374. data.primitiveTopology = primitiveTopology;
  1375. data.frontFaceCW = frontFaceCW;
  1376. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  1377. needsUpdate = true;
  1378. }
  1379. return needsUpdate;
  1380. }
  1381. /**
  1382. * Returns a cache key that is used to identify render pipelines.
  1383. *
  1384. * @param {RenderObject} renderObject - The render object.
  1385. * @return {string} The cache key.
  1386. */
  1387. getRenderCacheKey( renderObject ) {
  1388. const { object, material } = renderObject;
  1389. const utils = this.utils;
  1390. const renderContext = renderObject.context;
  1391. // meshes with negative scale have a different frontFace render pipeline
  1392. // descriptor value so the following must be honored in the cache key
  1393. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinantAffine() < 0 );
  1394. return [
  1395. material.transparent, material.blending, material.premultipliedAlpha,
  1396. material.blendSrc, material.blendDst, material.blendEquation,
  1397. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  1398. material.colorWrite,
  1399. material.depthWrite, material.depthTest, material.depthFunc,
  1400. material.stencilWrite, material.stencilFunc,
  1401. material.stencilFail, material.stencilZFail, material.stencilZPass,
  1402. material.stencilFuncMask, material.stencilWriteMask,
  1403. material.side,
  1404. frontFaceCW,
  1405. utils.getSampleCountRenderContext( renderContext ),
  1406. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  1407. utils.getPrimitiveTopology( object, material ),
  1408. renderObject.getGeometryCacheKey(),
  1409. renderObject.clippingContextCacheKey
  1410. ].join();
  1411. }
  1412. // textures
  1413. /**
  1414. * Updates a GPU sampler for the given texture.
  1415. *
  1416. * @param {Texture} texture - The texture to update the sampler for.
  1417. * @param {TextureNode} textureNode - The texture node to update the sampler with.
  1418. * @return {string} The current sampler key.
  1419. */
  1420. updateSampler( texture, textureNode ) {
  1421. return this.textureUtils.updateSampler( texture, textureNode );
  1422. }
  1423. /**
  1424. * Creates a default texture for the given texture that can be used
  1425. * as a placeholder until the actual texture is ready for usage.
  1426. *
  1427. * @param {Texture} texture - The texture to create a default texture for.
  1428. * @return {boolean} Whether the sampler has been updated or not.
  1429. */
  1430. createDefaultTexture( texture ) {
  1431. return this.textureUtils.createDefaultTexture( texture );
  1432. }
  1433. /**
  1434. * Defines a texture on the GPU for the given texture object.
  1435. *
  1436. * @param {Texture} texture - The texture.
  1437. * @param {Object} [options={}] - Optional configuration parameter.
  1438. */
  1439. createTexture( texture, options ) {
  1440. this.textureUtils.createTexture( texture, options );
  1441. }
  1442. /**
  1443. * Uploads the updated texture data to the GPU.
  1444. *
  1445. * @param {Texture} texture - The texture.
  1446. * @param {Object} [options={}] - Optional configuration parameter.
  1447. */
  1448. updateTexture( texture, options ) {
  1449. this.textureUtils.updateTexture( texture, options );
  1450. }
  1451. /**
  1452. * Generates mipmaps for the given texture.
  1453. *
  1454. * @param {Texture} texture - The texture.
  1455. */
  1456. generateMipmaps( texture ) {
  1457. this.textureUtils.generateMipmaps( texture );
  1458. }
  1459. /**
  1460. * Destroys the GPU data for the given texture object.
  1461. *
  1462. * @param {Texture} texture - The texture.
  1463. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  1464. */
  1465. destroyTexture( texture, isDefaultTexture = false ) {
  1466. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  1467. }
  1468. /**
  1469. * Returns texture data as a typed array.
  1470. *
  1471. * @async
  1472. * @param {Texture} texture - The texture to copy.
  1473. * @param {number} x - The x coordinate of the copy origin.
  1474. * @param {number} y - The y coordinate of the copy origin.
  1475. * @param {number} width - The width of the copy.
  1476. * @param {number} height - The height of the copy.
  1477. * @param {number} faceIndex - The face index.
  1478. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  1479. */
  1480. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  1481. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  1482. }
  1483. /**
  1484. * Inits a time stamp query for the given render context.
  1485. *
  1486. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  1487. * @param {number} uid - Unique id for the context (e.g. render context id).
  1488. * @param {Object} descriptor - The query descriptor.
  1489. */
  1490. initTimestampQuery( type, uid, descriptor ) {
  1491. if ( ! this.trackTimestamp ) return;
  1492. if ( ! this.timestampQueryPool[ type ] ) {
  1493. // TODO: Variable maxQueries?
  1494. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  1495. }
  1496. const timestampQueryPool = this.timestampQueryPool[ type ];
  1497. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  1498. _renderPassTimestampWrites.querySet = timestampQueryPool.querySet;
  1499. _renderPassTimestampWrites.beginningOfPassWriteIndex = baseOffset;
  1500. _renderPassTimestampWrites.endOfPassWriteIndex = baseOffset + 1;
  1501. descriptor.timestampWrites = _renderPassTimestampWrites;
  1502. }
  1503. // node builder
  1504. /**
  1505. * Returns a node builder for the given render object.
  1506. *
  1507. * @param {RenderObject} object - The render object.
  1508. * @param {Renderer} renderer - The renderer.
  1509. * @return {WGSLNodeBuilder} The node builder.
  1510. */
  1511. createNodeBuilder( object, renderer ) {
  1512. return new WGSLNodeBuilder( object, renderer );
  1513. }
  1514. // program
  1515. /**
  1516. * Creates a shader program from the given programmable stage.
  1517. *
  1518. * @param {ProgrammableStage} program - The programmable stage.
  1519. */
  1520. createProgram( program ) {
  1521. const programGPU = this.get( program );
  1522. _shaderModuleDescriptor.label = program.stage + ( program.name !== '' ? `_${ program.name }` : '' );
  1523. _shaderModuleDescriptor.code = program.code;
  1524. programGPU.module = {
  1525. module: this.device.createShaderModule( _shaderModuleDescriptor ),
  1526. entryPoint: 'main'
  1527. };
  1528. _shaderModuleDescriptor.reset();
  1529. }
  1530. /**
  1531. * Destroys the shader program of the given programmable stage.
  1532. *
  1533. * @param {ProgrammableStage} program - The programmable stage.
  1534. */
  1535. destroyProgram( program ) {
  1536. this.delete( program );
  1537. }
  1538. // pipelines
  1539. /**
  1540. * Creates a render pipeline for the given render object.
  1541. *
  1542. * @param {RenderObject} renderObject - The render object.
  1543. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  1544. */
  1545. createRenderPipeline( renderObject, promises ) {
  1546. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  1547. }
  1548. /**
  1549. * Creates a compute pipeline for the given compute node.
  1550. *
  1551. * @param {ComputePipeline} computePipeline - The compute pipeline.
  1552. * @param {Array<BindGroup>} bindings - The bindings.
  1553. */
  1554. createComputePipeline( computePipeline, bindings ) {
  1555. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  1556. }
  1557. /**
  1558. * Prepares the state for encoding render bundles.
  1559. *
  1560. * @param {RenderContext} renderContext - The render context.
  1561. */
  1562. beginBundle( renderContext ) {
  1563. const renderContextData = this.get( renderContext );
  1564. renderContextData._currentPass = renderContextData.currentPass;
  1565. renderContextData._currentSets = renderContextData.currentSets;
  1566. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  1567. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  1568. }
  1569. /**
  1570. * After processing render bundles this method finalizes related work.
  1571. *
  1572. * @param {RenderContext} renderContext - The render context.
  1573. * @param {RenderBundle} bundle - The render bundle.
  1574. */
  1575. finishBundle( renderContext, bundle ) {
  1576. const renderContextData = this.get( renderContext );
  1577. const bundleEncoder = renderContextData.currentPass;
  1578. const bundleGPU = bundleEncoder.finish();
  1579. this.get( bundle ).bundleGPU = bundleGPU;
  1580. // restore render pass state
  1581. renderContextData.currentSets = renderContextData._currentSets;
  1582. renderContextData.currentPass = renderContextData._currentPass;
  1583. }
  1584. /**
  1585. * Adds a render bundle to the render context data.
  1586. *
  1587. * @param {RenderContext} renderContext - The render context.
  1588. * @param {RenderBundle} bundle - The render bundle to add.
  1589. */
  1590. addBundle( renderContext, bundle ) {
  1591. const renderContextData = this.get( renderContext );
  1592. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  1593. }
  1594. // bindings
  1595. /**
  1596. * Creates a uniform buffer.
  1597. *
  1598. * @param {Buffer} uniformBuffer - The uniform buffer.
  1599. */
  1600. createUniformBuffer( uniformBuffer ) {
  1601. const uniformBufferData = this.get( uniformBuffer );
  1602. if ( uniformBufferData.buffer === undefined ) {
  1603. const byteLength = uniformBuffer.byteLength;
  1604. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  1605. const visibilities = [];
  1606. if ( uniformBuffer.visibility & GPUShaderStage.VERTEX ) {
  1607. visibilities.push( 'vertex' );
  1608. }
  1609. if ( uniformBuffer.visibility & GPUShaderStage.FRAGMENT ) {
  1610. visibilities.push( 'fragment' );
  1611. }
  1612. if ( uniformBuffer.visibility & GPUShaderStage.COMPUTE ) {
  1613. visibilities.push( 'compute' );
  1614. }
  1615. const bufferVisibility = `(${visibilities.join( ',' )})`;
  1616. _bufferDescriptor.label = `bindingBuffer${uniformBuffer.id}_${uniformBuffer.name}_${bufferVisibility}`;
  1617. _bufferDescriptor.size = byteLength;
  1618. _bufferDescriptor.usage = usage;
  1619. const bufferGPU = this.device.createBuffer( _bufferDescriptor );
  1620. _bufferDescriptor.reset();
  1621. uniformBufferData.buffer = bufferGPU;
  1622. }
  1623. }
  1624. /**
  1625. * Destroys the GPU data for the given uniform buffer.
  1626. *
  1627. * @param {Buffer} uniformBuffer - The uniform buffer.
  1628. */
  1629. destroyUniformBuffer( uniformBuffer ) {
  1630. const uniformBufferData = this.get( uniformBuffer );
  1631. uniformBufferData.buffer.destroy();
  1632. this.delete( uniformBuffer );
  1633. }
  1634. /**
  1635. * Creates bindings from the given bind group definition.
  1636. *
  1637. * @param {BindGroup} bindGroup - The bind group.
  1638. * @param {Array<BindGroup>} bindings - Array of bind groups.
  1639. * @param {number} cacheIndex - The cache index.
  1640. * @param {number} version - The version.
  1641. */
  1642. createBindings( bindGroup, bindings, cacheIndex, version ) {
  1643. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  1644. }
  1645. /**
  1646. * Updates the given bind group definition.
  1647. *
  1648. * @param {BindGroup} bindGroup - The bind group.
  1649. * @param {Array<BindGroup>} bindings - Array of bind groups.
  1650. * @param {number} cacheIndex - The cache index.
  1651. * @param {number} version - The version.
  1652. */
  1653. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  1654. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  1655. }
  1656. /**
  1657. * Updates a buffer binding.
  1658. *
  1659. * @param {Buffer} binding - The buffer binding to update.
  1660. */
  1661. updateBinding( binding ) {
  1662. this.bindingUtils.updateBinding( binding );
  1663. }
  1664. /**
  1665. * Delete data associated with the current bind group.
  1666. *
  1667. * @param {BindGroup} bindGroup - The bind group.
  1668. */
  1669. deleteBindGroupData( bindGroup ) {
  1670. this.bindingUtils.deleteBindGroupData( bindGroup );
  1671. }
  1672. // attributes
  1673. /**
  1674. * Creates the buffer of an indexed shader attribute.
  1675. *
  1676. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  1677. */
  1678. createIndexAttribute( attribute ) {
  1679. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  1680. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  1681. usage |= GPUBufferUsage.STORAGE;
  1682. }
  1683. this.attributeUtils.createAttribute( attribute, usage );
  1684. }
  1685. /**
  1686. * Creates the GPU buffer of a shader attribute.
  1687. *
  1688. * @param {BufferAttribute} attribute - The buffer attribute.
  1689. */
  1690. createAttribute( attribute ) {
  1691. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1692. }
  1693. /**
  1694. * Creates the GPU buffer of a storage attribute.
  1695. *
  1696. * @param {BufferAttribute} attribute - The buffer attribute.
  1697. */
  1698. createStorageAttribute( attribute ) {
  1699. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1700. }
  1701. /**
  1702. * Creates the GPU buffer of an indirect storage attribute.
  1703. *
  1704. * @param {BufferAttribute} attribute - The buffer attribute.
  1705. */
  1706. createIndirectStorageAttribute( attribute ) {
  1707. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1708. }
  1709. /**
  1710. * Updates the GPU buffer of a shader attribute.
  1711. *
  1712. * @param {BufferAttribute} attribute - The buffer attribute to update.
  1713. */
  1714. updateAttribute( attribute ) {
  1715. this.attributeUtils.updateAttribute( attribute );
  1716. }
  1717. /**
  1718. * Destroys the GPU buffer of a shader attribute.
  1719. *
  1720. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  1721. */
  1722. destroyAttribute( attribute ) {
  1723. this.attributeUtils.destroyAttribute( attribute );
  1724. }
  1725. // canvas
  1726. /**
  1727. * Triggers an update of the default render pass descriptor.
  1728. */
  1729. updateSize() {
  1730. this.delete( this.renderer.getCanvasTarget() );
  1731. }
  1732. // utils public
  1733. /**
  1734. * Checks if the given feature is supported by the backend.
  1735. *
  1736. * @param {string} name - The feature's name.
  1737. * @return {boolean} Whether the feature is supported or not.
  1738. */
  1739. hasFeature( name ) {
  1740. if ( GPUFeatureMap[ name ] !== undefined ) name = GPUFeatureMap[ name ];
  1741. return this.device.features.has( name );
  1742. }
  1743. /**
  1744. * Copies data of the given source texture to the given destination texture.
  1745. *
  1746. * @param {Texture} srcTexture - The source texture.
  1747. * @param {Texture} dstTexture - The destination texture.
  1748. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  1749. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  1750. * @param {number} [srcLevel=0] - The mipmap level to copy.
  1751. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  1752. */
  1753. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  1754. let dstX = 0;
  1755. let dstY = 0;
  1756. let dstZ = 0;
  1757. let srcX = 0;
  1758. let srcY = 0;
  1759. let srcZ = 0;
  1760. let srcWidth = srcTexture.image.width;
  1761. let srcHeight = srcTexture.image.height;
  1762. let srcDepth = 1;
  1763. if ( srcRegion !== null ) {
  1764. if ( srcRegion.isBox3 === true ) {
  1765. srcX = srcRegion.min.x;
  1766. srcY = srcRegion.min.y;
  1767. srcZ = srcRegion.min.z;
  1768. srcWidth = srcRegion.max.x - srcRegion.min.x;
  1769. srcHeight = srcRegion.max.y - srcRegion.min.y;
  1770. srcDepth = srcRegion.max.z - srcRegion.min.z;
  1771. } else {
  1772. // Assume it's a Box2
  1773. srcX = srcRegion.min.x;
  1774. srcY = srcRegion.min.y;
  1775. srcWidth = srcRegion.max.x - srcRegion.min.x;
  1776. srcHeight = srcRegion.max.y - srcRegion.min.y;
  1777. srcDepth = 1;
  1778. }
  1779. }
  1780. if ( dstPosition !== null ) {
  1781. dstX = dstPosition.x;
  1782. dstY = dstPosition.y;
  1783. dstZ = dstPosition.z || 0;
  1784. }
  1785. _commandEncoderDescriptor.label = 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id;
  1786. const encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  1787. _commandEncoderDescriptor.reset();
  1788. const sourceGPU = this.get( srcTexture ).texture;
  1789. const destinationGPU = this.get( dstTexture ).texture;
  1790. _texelCopyTextureInfoSrc.texture = sourceGPU;
  1791. _texelCopyTextureInfoSrc.mipLevel = srcLevel;
  1792. _texelCopyTextureInfoSrc.origin.x = srcX;
  1793. _texelCopyTextureInfoSrc.origin.y = srcY;
  1794. _texelCopyTextureInfoSrc.origin.z = srcZ;
  1795. _texelCopyTextureInfoDst.texture = destinationGPU;
  1796. _texelCopyTextureInfoDst.mipLevel = dstLevel;
  1797. _texelCopyTextureInfoDst.origin.x = dstX;
  1798. _texelCopyTextureInfoDst.origin.y = dstY;
  1799. _texelCopyTextureInfoDst.origin.z = dstZ;
  1800. _extent3D.width = srcWidth;
  1801. _extent3D.height = srcHeight;
  1802. _extent3D.depthOrArrayLayers = srcDepth;
  1803. encoder.copyTextureToTexture(
  1804. _texelCopyTextureInfoSrc,
  1805. _texelCopyTextureInfoDst,
  1806. _extent3D
  1807. );
  1808. _texelCopyTextureInfoSrc.reset();
  1809. _texelCopyTextureInfoDst.reset();
  1810. _extent3D.reset();
  1811. submit( this.device, encoder.finish() );
  1812. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  1813. this.textureUtils.generateMipmaps( dstTexture );
  1814. }
  1815. }
  1816. /**
  1817. * Copies the current bound framebuffer to the given texture.
  1818. *
  1819. * @param {Texture} texture - The destination texture.
  1820. * @param {RenderContext} renderContext - The render context.
  1821. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  1822. */
  1823. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  1824. const renderContextData = this.get( renderContext );
  1825. let sourceGPU = null;
  1826. if ( renderContext.renderTarget ) {
  1827. if ( texture.isDepthTexture ) {
  1828. sourceGPU = this.get( renderContext.depthTexture ).texture;
  1829. } else {
  1830. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  1831. }
  1832. } else {
  1833. if ( texture.isDepthTexture ) {
  1834. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  1835. } else {
  1836. sourceGPU = this.context.getCurrentTexture();
  1837. }
  1838. }
  1839. const destinationGPU = this.get( texture ).texture;
  1840. if ( sourceGPU.format !== destinationGPU.format ) {
  1841. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  1842. return;
  1843. }
  1844. let encoder;
  1845. if ( renderContextData.currentPass ) {
  1846. renderContextData.currentPass.end();
  1847. encoder = renderContextData.encoder;
  1848. } else {
  1849. _commandEncoderDescriptor.label = 'copyFramebufferToTexture_' + texture.id;
  1850. encoder = this.device.createCommandEncoder( _commandEncoderDescriptor );
  1851. _commandEncoderDescriptor.reset();
  1852. }
  1853. _texelCopyTextureInfoSrc.texture = sourceGPU;
  1854. _texelCopyTextureInfoSrc.origin.x = rectangle.x;
  1855. _texelCopyTextureInfoSrc.origin.y = rectangle.y;
  1856. _texelCopyTextureInfoDst.texture = destinationGPU;
  1857. _extent3D.width = rectangle.z;
  1858. _extent3D.height = rectangle.w;
  1859. encoder.copyTextureToTexture(
  1860. _texelCopyTextureInfoSrc,
  1861. _texelCopyTextureInfoDst,
  1862. _extent3D
  1863. );
  1864. _texelCopyTextureInfoSrc.reset();
  1865. _texelCopyTextureInfoDst.reset();
  1866. _extent3D.reset();
  1867. // mipmaps must be genereated with the same encoder otherwise the copied texture data
  1868. // might be out-of-sync, see #31768
  1869. if ( texture.generateMipmaps ) {
  1870. this.textureUtils.generateMipmaps( texture, encoder );
  1871. }
  1872. if ( renderContextData.currentPass ) {
  1873. const { descriptor } = renderContextData;
  1874. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  1875. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  1876. }
  1877. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  1878. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  1879. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  1880. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  1881. if ( renderContext.viewport ) {
  1882. this.updateViewport( renderContext );
  1883. }
  1884. if ( renderContext.scissor ) {
  1885. this.updateScissor( renderContext );
  1886. }
  1887. } else {
  1888. submit( this.device, encoder.finish() );
  1889. }
  1890. }
  1891. /**
  1892. * Checks if the given compatibility is supported by the backend.
  1893. *
  1894. * @param {string} name - The compatibility name.
  1895. * @return {boolean} Whether the compatibility is supported or not.
  1896. */
  1897. hasCompatibility( name ) {
  1898. if ( this._compatibility[ name ] !== undefined ) {
  1899. return this._compatibility[ name ];
  1900. }
  1901. return super.hasCompatibility( name );
  1902. }
  1903. dispose() {
  1904. this.bindingUtils.dispose();
  1905. this.textureUtils.dispose();
  1906. if ( this.occludedResolveCache ) {
  1907. for ( const buffer of this.occludedResolveCache.values() ) {
  1908. buffer.destroy();
  1909. }
  1910. this.occludedResolveCache.clear();
  1911. }
  1912. if ( this.timestampQueryPool ) {
  1913. for ( const queryPool of Object.values( this.timestampQueryPool ) ) {
  1914. if ( queryPool !== null ) queryPool.dispose();
  1915. }
  1916. }
  1917. if ( this.parameters.device === undefined && this.device !== null ) {
  1918. this.device.destroy();
  1919. }
  1920. }
  1921. }
  1922. export default WebGPUBackend;
粤ICP备19079148号