webgpuEngine.ts 167 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796
  1. import { Logger } from "../Misc/logger";
  2. import { Nullable, DataArray, IndicesArray, FloatArray, Immutable } from "../types";
  3. import { Color4 } from "../Maths/math";
  4. import { Engine } from "../Engines/engine";
  5. import { InstancingAttributeInfo } from "../Engines/instancingAttributeInfo";
  6. import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
  7. import { InternalTexture, InternalTextureSource } from "../Materials/Textures/internalTexture";
  8. import { IEffectCreationOptions, Effect } from "../Materials/effect";
  9. import { EffectFallbacks } from "../Materials/effectFallbacks";
  10. import { _TimeToken } from "../Instrumentation/timeToken";
  11. import { Constants } from "./constants";
  12. import * as WebGPUConstants from './WebGPU/webgpuConstants';
  13. import { VertexBuffer } from "../Meshes/buffer";
  14. import { WebGPUPipelineContext, IWebGPUPipelineContextVertexInputsCache, IWebGPURenderPipelineStageDescriptor } from './WebGPU/webgpuPipelineContext';
  15. import { IPipelineContext } from './IPipelineContext';
  16. import { DataBuffer } from '../Meshes/dataBuffer';
  17. import { WebGPUDataBuffer } from '../Meshes/WebGPU/webgpuDataBuffer';
  18. import { BaseTexture } from "../Materials/Textures/baseTexture";
  19. import { IShaderProcessor } from "./Processors/iShaderProcessor";
  20. import { WebGPUShaderProcessor } from "./WebGPU/webgpuShaderProcessors";
  21. import { ShaderProcessingContext } from "./Processors/shaderProcessingOptions";
  22. import { WebGPUShaderProcessingContext } from "./WebGPU/webgpuShaderProcessingContext";
  23. import { Tools } from "../Misc/tools";
  24. import { WebGPUTextureHelper } from './WebGPU/webgpuTextureHelper';
  25. import { ISceneLike, ThinEngine } from './thinEngine';
  26. import { Scene } from '../scene';
  27. import { WebGPUBufferManager } from './WebGPU/webgpuBufferManager';
  28. import { DepthTextureCreationOptions } from './depthTextureCreationOptions';
  29. import { HardwareTextureWrapper } from '../Materials/Textures/hardwareTextureWrapper';
  30. import { WebGPUHardwareTexture } from './WebGPU/webgpuHardwareTexture';
  31. import { IColor4Like } from '../Maths/math.like';
  32. import { IWebRequest } from '../Misc/interfaces/iWebRequest';
  33. import { UniformBuffer } from '../Materials/uniformBuffer';
  34. declare type VideoTexture = import("../Materials/Textures/videoTexture").VideoTexture;
  35. declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
  36. // TODO WEBGPU remove when not needed anymore
  37. function assert(condition: any, msg?: string): asserts condition {
  38. if (!condition) {
  39. throw new Error(msg);
  40. }
  41. }
  42. const dbgShowShaderCode = false;
  43. const dbgSanityChecks = true;
  44. const dbgGenerateLogs = true;
  45. const dbgVerboseLogsForFirstFrames = true;
  46. const dbgVerboseLogsNumFrames = 10;
  47. const dbgShowWarningsNotImplemented = true;
  48. export const dbgShowDebugInliningProcess = false;
  49. /**
  50. * Options to load the associated Glslang library
  51. */
  52. export interface GlslangOptions {
  53. /**
  54. * Defines an existing instance of Glslang (usefull in modules who do not access the global instance).
  55. */
  56. glslang?: any;
  57. /**
  58. * Defines the URL of the glslang JS File.
  59. */
  60. jsPath?: string;
  61. /**
  62. * Defines the URL of the glslang WASM File.
  63. */
  64. wasmPath?: string;
  65. }
  66. /**
  67. * Options to create the WebGPU engine
  68. */
  69. export interface WebGPUEngineOptions extends GPURequestAdapterOptions {
  70. /**
  71. * If delta time between frames should be constant
  72. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  73. */
  74. deterministicLockstep?: boolean;
  75. /**
  76. * Maximum about of steps between frames (Default: 4)
  77. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  78. */
  79. lockstepMaxSteps?: number;
  80. /**
  81. * Defines the seconds between each deterministic lock step
  82. */
  83. timeStep?: number;
  84. /**
  85. * Defines that engine should ignore modifying touch action attribute and style
  86. * If not handle, you might need to set it up on your side for expected touch devices behavior.
  87. */
  88. doNotHandleTouchAction?: boolean;
  89. /**
  90. * Defines if webaudio should be initialized as well
  91. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  92. */
  93. audioEngine?: boolean;
  94. /**
  95. * Defines the category of adapter to use.
  96. * Is it the discrete or integrated device.
  97. */
  98. powerPreference?: GPUPowerPreference;
  99. /**
  100. * Defines the device descriptor used to create a device.
  101. */
  102. deviceDescriptor?: GPUDeviceDescriptor;
  103. /**
  104. * Defines the requested Swap Chain Format.
  105. */
  106. swapChainFormat?: GPUTextureFormat;
  107. /**
  108. * Defines wether MSAA is enabled on the canvas.
  109. */
  110. antialiasing?: boolean;
  111. /**
  112. * Defines wether the stencil buffer should be enabled.
  113. */
  114. stencil?: boolean;
  115. }
  116. /**
  117. * The web GPU engine class provides support for WebGPU version of babylon.js.
  118. */
  119. export class WebGPUEngine extends Engine {
  120. // Default glslang options.
  121. private static readonly _glslangDefaultOptions: GlslangOptions = {
  122. jsPath: "https://preview.babylonjs.com/glslang/glslang.js",
  123. wasmPath: "https://preview.babylonjs.com/glslang/glslang.wasm"
  124. };
  125. // Page Life cycle and constants
  126. private readonly _uploadEncoderDescriptor = { label: "upload" };
  127. private readonly _renderEncoderDescriptor = { label: "render" };
  128. private readonly _renderTargetEncoderDescriptor = { label: "renderTarget" };
  129. private readonly _clearDepthValue = 1;
  130. private readonly _clearReverseDepthValue = 0;
  131. private readonly _clearStencilValue = 0;
  132. private readonly _defaultSampleCount = 4; // Only supported value for now.
  133. // Engine Life Cycle
  134. private _canvas: HTMLCanvasElement;
  135. private _options: WebGPUEngineOptions;
  136. private _glslang: any = null;
  137. private _adapter: GPUAdapter;
  138. private _adapterSupportedExtensions: GPUExtensionName[];
  139. private _device: GPUDevice;
  140. private _deviceEnabledExtensions: GPUExtensionName[];
  141. private _context: GPUCanvasContext;
  142. private _swapChain: GPUSwapChain;
  143. private _swapChainTexture: GPUTexture;
  144. private _mainPassSampleCount: number;
  145. private _textureHelper: WebGPUTextureHelper;
  146. private _bufferManager: WebGPUBufferManager;
  147. private _deferredReleaseTextures: Array<[InternalTexture, Nullable<HardwareTextureWrapper>, Nullable<BaseTexture>, Nullable<InternalTexture>]> = [];
  148. private _counters: {
  149. numPipelineDescriptorCreation: number;
  150. numBindGroupsCreation: number;
  151. } = {
  152. numPipelineDescriptorCreation: 0,
  153. numBindGroupsCreation: 0,
  154. };
  155. // Some of the internal state might change during the render pass.
  156. // This happens mainly during clear for the state
  157. // And when the frame starts to swap the target texture from the swap chain
  158. private _mainTexture: GPUTexture;
  159. private _depthTexture: GPUTexture;
  160. private _mainColorAttachments: GPURenderPassColorAttachmentDescriptor[];
  161. private _mainTextureExtends: GPUExtent3D;
  162. private _mainDepthAttachment: GPURenderPassDepthStencilAttachmentDescriptor;
  163. private _depthTextureFormat: GPUTextureFormat | undefined;
  164. private _colorFormat: GPUTextureFormat;
  165. // Frame Life Cycle (recreated each frame)
  166. private _uploadEncoder: GPUCommandEncoder;
  167. private _renderEncoder: GPUCommandEncoder;
  168. private _renderTargetEncoder: GPUCommandEncoder;
  169. private _commandBuffers: GPUCommandBuffer[] = [null as any, null as any, null as any];
  170. // Frame Buffer Life Cycle (recreated for each render target pass)
  171. private _currentRenderPass: Nullable<GPURenderPassEncoder> = null;
  172. private _mainRenderPass: Nullable<GPURenderPassEncoder> = null;
  173. private _currentRenderTargetColorAttachmentViewDescriptor: GPUTextureViewDescriptor;
  174. private _currentRenderTargetDepthAttachmentViewDescriptor: GPUTextureViewDescriptor;
  175. // DrawCall Life Cycle
  176. // Effect is on the parent class
  177. // protected _currentEffect: Nullable<Effect> = null;
  178. private _currentVertexBuffers: Nullable<{ [key: string]: Nullable<VertexBuffer> }> = null;
  179. private _currentIndexBuffer: Nullable<DataBuffer> = null;
  180. private __colorWrite = true;
  181. private _uniformsBuffers: { [name: string]: WebGPUDataBuffer } = {};
  182. // Caches
  183. private _compiledShaders: { [key: string]: {
  184. stages: IWebGPURenderPipelineStageDescriptor,
  185. availableAttributes: { [key: string]: number },
  186. availableUBOs: { [key: string]: { setIndex: number, bindingIndex: number} },
  187. availableSamplers: { [key: string]: { setIndex: number, bindingIndex: number} },
  188. orderedAttributes: string[],
  189. orderedUBOsAndSamplers: { name: string, isSampler: boolean }[][],
  190. leftOverUniforms: { name: string, type: string, length: number }[],
  191. leftOverUniformsByName: { [name: string]: string },
  192. sources: {
  193. vertex: string,
  194. fragment: string,
  195. rawVertex: string,
  196. rawFragment: string,
  197. }
  198. } } = {};
  199. /**
  200. * Gets a boolean indicating that the engine supports uniform buffers
  201. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  202. */
  203. public get supportsUniformBuffers(): boolean {
  204. return true;
  205. }
  206. /** Gets the supported extensions by the WebGPU adapter */
  207. public get supportedExtensions(): Immutable<GPUExtensionName[]> {
  208. return this._adapterSupportedExtensions;
  209. }
  210. /** Gets the currently enabled extensions on the WebGPU device */
  211. public get enabledExtensions(): Immutable<GPUExtensionName[]> {
  212. return this._deviceEnabledExtensions;
  213. }
  214. /**
  215. * Create a new instance of the gpu engine.
  216. * @param canvas Defines the canvas to use to display the result
  217. * @param options Defines the options passed to the engine to create the GPU context dependencies
  218. */
  219. public constructor(canvas: HTMLCanvasElement, options: WebGPUEngineOptions = {}) {
  220. super(null);
  221. ThinEngine.Features.forceBitmapOverHTMLImageElement = true;
  222. ThinEngine.Features.supportRenderAndCopyToLodForFloatTextures = true;
  223. ThinEngine.Features.framebuffersHaveYTopToBottom = true;
  224. ThinEngine.Features.supportDepthStencilTexture = true;
  225. ThinEngine.Features.supportShadowSamplers = true;
  226. ThinEngine.Features.uniformBufferHardCheckMatrix = true;
  227. ThinEngine.Features.allowTexturePrefiltering = true;
  228. ThinEngine.Features.trackUbosInFrame = true;
  229. ThinEngine.Features._collectUbosUpdatedInFrame = true;
  230. options.deviceDescriptor = options.deviceDescriptor || { };
  231. options.swapChainFormat = options.swapChainFormat || WebGPUConstants.TextureFormat.BGRA8Unorm;
  232. options.antialiasing = false; //options.antialiasing === undefined ? true : options.antialiasing;
  233. options.stencil = options.stencil ?? true;
  234. Logger.Log(`Babylon.js v${Engine.Version} - WebGPU engine`);
  235. if (!navigator.gpu) {
  236. Logger.Error("WebGPU is not supported by your browser.");
  237. return;
  238. }
  239. this._isWebGPU = true;
  240. this._shaderPlatformName = "WEBGPU";
  241. if (options.deterministicLockstep === undefined) {
  242. options.deterministicLockstep = false;
  243. }
  244. if (options.lockstepMaxSteps === undefined) {
  245. options.lockstepMaxSteps = 4;
  246. }
  247. if (options.audioEngine === undefined) {
  248. options.audioEngine = true;
  249. }
  250. this._deterministicLockstep = options.deterministicLockstep;
  251. this._lockstepMaxSteps = options.lockstepMaxSteps;
  252. this._timeStep = options.timeStep || 1 / 60;
  253. this._doNotHandleContextLost = true;
  254. this._canvas = canvas;
  255. this._options = options;
  256. this.premultipliedAlpha = false;
  257. this._hardwareScalingLevel = 1;
  258. this._mainPassSampleCount = options.antialiasing ? this._defaultSampleCount : 1;
  259. this._isStencilEnable = options.stencil;
  260. this._depthCullingState.depthTest = true;
  261. this._depthCullingState.depthFunc = Constants.LEQUAL;
  262. this._depthCullingState.depthMask = true;
  263. this._sharedInit(canvas, !!options.doNotHandleTouchAction, options.audioEngine);
  264. // TODO. WEBGPU. Use real way to do it.
  265. this._canvas.style.transform = "scaleY(-1)";
  266. }
  267. //------------------------------------------------------------------------------
  268. // Initialization
  269. //------------------------------------------------------------------------------
  270. /**
  271. * Initializes the WebGPU context and dependencies.
  272. * @param glslangOptions Defines the GLSLang compiler options if necessary
  273. * @returns a promise notifying the readiness of the engine.
  274. */
  275. public initAsync(glslangOptions?: GlslangOptions): Promise<void> {
  276. return this._initGlslang(glslangOptions)
  277. .then((glslang: any) => {
  278. this._glslang = glslang;
  279. return navigator.gpu!.requestAdapter(this._options);
  280. })
  281. .then((adapter: GPUAdapter | null) => {
  282. this._adapter = adapter!;
  283. this._adapterSupportedExtensions = this._adapter.extensions.slice(0);
  284. const deviceDescriptor = this._options.deviceDescriptor;
  285. if (deviceDescriptor?.extensions) {
  286. const requestedExtensions = deviceDescriptor.extensions;
  287. const validExtensions = [];
  288. const iterator = requestedExtensions[Symbol.iterator]();
  289. while (true) {
  290. const { done, value : extension } = iterator.next();
  291. if (done) {
  292. break;
  293. }
  294. if (this._adapterSupportedExtensions.indexOf(extension) >= 0) {
  295. validExtensions.push(extension);
  296. }
  297. }
  298. deviceDescriptor.extensions = validExtensions;
  299. }
  300. return this._adapter.requestDevice(this._options.deviceDescriptor);
  301. })
  302. .then((device: GPUDevice | null) => {
  303. this._device = device!;
  304. this._deviceEnabledExtensions = this._device.extensions.slice(0);
  305. })
  306. .then(() => {
  307. this._bufferManager = new WebGPUBufferManager(this._device);
  308. this._textureHelper = new WebGPUTextureHelper(this._device, this._glslang, this._bufferManager);
  309. if (dbgVerboseLogsForFirstFrames) {
  310. if ((this as any)._count === undefined) {
  311. (this as any)._count = 0;
  312. console.log("%c frame #" + (this as any)._count + " - begin", "background: #ffff00");
  313. }
  314. }
  315. this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
  316. this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
  317. this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor);
  318. this._initializeLimits();
  319. this._initializeContextAndSwapChain();
  320. this._initializeMainAttachments();
  321. this.resize();
  322. })
  323. .catch((e: any) => {
  324. Logger.Error("Can not create WebGPU Device and/or context.");
  325. Logger.Error(e);
  326. });
  327. }
  328. private _initGlslang(glslangOptions?: GlslangOptions): Promise<any> {
  329. glslangOptions = glslangOptions || { };
  330. glslangOptions = {
  331. ...WebGPUEngine._glslangDefaultOptions,
  332. ...glslangOptions
  333. };
  334. if (glslangOptions.glslang) {
  335. return Promise.resolve(glslangOptions.glslang);
  336. }
  337. if ((window as any).glslang) {
  338. return (window as any).glslang(glslangOptions!.wasmPath);
  339. }
  340. if (glslangOptions.jsPath && glslangOptions.wasmPath) {
  341. return Tools.LoadScriptAsync(glslangOptions.jsPath)
  342. .then(() => {
  343. return (window as any).glslang(glslangOptions!.wasmPath);
  344. });
  345. }
  346. return Promise.reject("gslang is not available.");
  347. }
  348. private _initializeLimits(): void {
  349. // Init caps
  350. // TODO WEBGPU Real Capability check once limits will be working.
  351. this._caps = {
  352. maxTexturesImageUnits: 16,
  353. maxVertexTextureImageUnits: 16,
  354. maxCombinedTexturesImageUnits: 32,
  355. maxTextureSize: 2048,
  356. maxCubemapTextureSize: 2048,
  357. maxRenderTextureSize: 2048,
  358. maxVertexAttribs: 16,
  359. maxVaryingVectors: 16,
  360. maxFragmentUniformVectors: 1024,
  361. maxVertexUniformVectors: 1024,
  362. standardDerivatives: true,
  363. astc: null,
  364. s3tc: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.ExtensionName.TextureCompressionBC) >= 0 ? true : undefined) as any,
  365. pvrtc: null,
  366. etc1: null,
  367. etc2: null,
  368. bptc: this._deviceEnabledExtensions.indexOf(WebGPUConstants.ExtensionName.TextureCompressionBC) >= 0 ? true : undefined,
  369. maxAnisotropy: 0, // TODO: Retrieve this smartly. Currently set to D3D11 maximum allowable value.
  370. uintIndices: true,
  371. fragmentDepthSupported: true,
  372. highPrecisionShaderSupported: true,
  373. colorBufferFloat: true,
  374. textureFloat: true,
  375. textureFloatLinearFiltering: true,
  376. textureFloatRender: true,
  377. textureHalfFloat: true,
  378. textureHalfFloatLinearFiltering: true,
  379. textureHalfFloatRender: true,
  380. textureLOD: true,
  381. drawBuffersExtension: true,
  382. depthTextureExtension: true,
  383. vertexArrayObject: false,
  384. instancedArrays: true,
  385. canUseTimestampForTimerQuery: false,
  386. blendMinMax: true,
  387. maxMSAASamples: 8 // TODO WEBGPU what is the right value?
  388. };
  389. this._caps.parallelShaderCompile = null as any;
  390. }
  391. private _initializeContextAndSwapChain(): void {
  392. this._context = this._canvas.getContext('gpupresent') as unknown as GPUCanvasContext;
  393. this._swapChain = this._context.configureSwapChain({
  394. device: this._device,
  395. format: this._options.swapChainFormat!,
  396. usage: WebGPUConstants.TextureUsage.OutputAttachment | WebGPUConstants.TextureUsage.CopySrc,
  397. });
  398. this._colorFormat = this._options.swapChainFormat!;
  399. if (dbgGenerateLogs) {
  400. this._context.getSwapChainPreferredFormat(this._device).then((format) => {
  401. console.log("Swap chain preferred format:", format);
  402. });
  403. }
  404. }
  405. // Set default values as WebGL with depth and stencil attachment for the broadest Compat.
  406. private _initializeMainAttachments(): void {
  407. this._mainTextureExtends = {
  408. width: this.getRenderWidth(),
  409. height: this.getRenderHeight(),
  410. depth: 1
  411. };
  412. if (this._options.antialiasing) {
  413. const mainTextureDescriptor: GPUTextureDescriptor = {
  414. size: this._mainTextureExtends,
  415. mipLevelCount: 1,
  416. sampleCount: this._mainPassSampleCount,
  417. dimension: WebGPUConstants.TextureDimension.E2d,
  418. format: WebGPUConstants.TextureFormat.BGRA8Unorm,
  419. usage: WebGPUConstants.TextureUsage.OutputAttachment,
  420. };
  421. if (this._mainTexture) {
  422. this._mainTexture.destroy();
  423. }
  424. this._mainTexture = this._device.createTexture(mainTextureDescriptor);
  425. this._mainColorAttachments = [{
  426. attachment: this._mainTexture.createView(),
  427. loadValue: new Color4(0, 0, 0, 1),
  428. storeOp: WebGPUConstants.StoreOp.Clear // Better than "Store" as we don't need to reuse the content of the multisampled texture
  429. }];
  430. }
  431. else {
  432. this._mainColorAttachments = [{
  433. attachment: undefined as any,
  434. loadValue: new Color4(0, 0, 0, 1),
  435. storeOp: WebGPUConstants.StoreOp.Store
  436. }];
  437. }
  438. this._depthTextureFormat = this._getMainDepthTextureFormat();
  439. const depthTextureDescriptor: GPUTextureDescriptor = {
  440. size: this._mainTextureExtends,
  441. mipLevelCount: 1,
  442. sampleCount: this._mainPassSampleCount,
  443. dimension: WebGPUConstants.TextureDimension.E2d,
  444. format: this._depthTextureFormat,
  445. usage: WebGPUConstants.TextureUsage.OutputAttachment
  446. };
  447. if (this._depthTexture) {
  448. this._depthTexture.destroy();
  449. }
  450. this._depthTexture = this._device.createTexture(depthTextureDescriptor);
  451. this._mainDepthAttachment = {
  452. attachment: this._depthTexture.createView(),
  453. depthLoadValue: this._clearDepthValue,
  454. depthStoreOp: WebGPUConstants.StoreOp.Store,
  455. stencilLoadValue: this._clearStencilValue,
  456. stencilStoreOp: WebGPUConstants.StoreOp.Store,
  457. };
  458. if (this._mainRenderPass !== null) {
  459. this._endMainRenderPass();
  460. }
  461. }
  462. /**
  463. * Gets a shader processor implementation fitting with the current engine type.
  464. * @returns The shader processor implementation.
  465. */
  466. protected _getShaderProcessor(): Nullable<IShaderProcessor> {
  467. return new WebGPUShaderProcessor();
  468. }
  469. /** @hidden */
  470. public _getShaderProcessingContext(): Nullable<ShaderProcessingContext> {
  471. return new WebGPUShaderProcessingContext();
  472. }
  473. //------------------------------------------------------------------------------
  474. // Static Pipeline WebGPU States
  475. //------------------------------------------------------------------------------
  476. public wipeCaches(bruteForce?: boolean): void {
  477. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  478. return;
  479. }
  480. this.resetTextureCache();
  481. //this._currentEffect = null; // can't reset _currentEffect, else some crashes can occur (for eg in ProceduralTexture which calls bindFrameBuffer (which calls wipeCaches) after having called enableEffect and before drawing into the texture)
  482. this._currentIndexBuffer = null;
  483. this._currentVertexBuffers = null;
  484. if (bruteForce) {
  485. this._currentProgram = null;
  486. this._stencilState.reset();
  487. this._depthCullingState.reset();
  488. this._depthCullingState.depthFunc = Constants.LEQUAL;
  489. this._alphaState.reset();
  490. this._alphaMode = Constants.ALPHA_ADD;
  491. this._alphaEquation = Constants.ALPHA_DISABLE;
  492. this.__colorWrite = true;
  493. }
  494. this._cachedVertexBuffers = null;
  495. this._cachedIndexBuffer = null;
  496. this._cachedEffectForVertexBuffers = null;
  497. }
  498. public setColorWrite(enable: boolean): void {
  499. this.__colorWrite = enable;
  500. }
  501. public getColorWrite(): boolean {
  502. return this.__colorWrite;
  503. }
  504. //------------------------------------------------------------------------------
  505. // Dynamic WebGPU States
  506. //------------------------------------------------------------------------------
  507. private _viewportsCurrent: Array<{ x: number, y: number, w: number, h: number }> = [{ x: 0, y: 0, w: 0, h: 0 }, { x: 0, y: 0, w: 0, h: 0 }];
  508. private _resetCurrentViewport(index: number) {
  509. this._viewportsCurrent[index].x = 0;
  510. this._viewportsCurrent[index].y = 0;
  511. this._viewportsCurrent[index].w = 0;
  512. this._viewportsCurrent[index].h = 0;
  513. }
  514. private _applyViewport(renderPass: GPURenderPassEncoder): void {
  515. const index = renderPass === this._mainRenderPass ? 0 : 1;
  516. const x = this._viewportCached.x,
  517. y = this._viewportCached.y,
  518. w = this._viewportCached.z,
  519. h = this._viewportCached.w;
  520. if (this._viewportsCurrent[index].x !== x || this._viewportsCurrent[index].y !== y ||
  521. this._viewportsCurrent[index].w !== w || this._viewportsCurrent[index].h !== h)
  522. {
  523. this._viewportsCurrent[index].x = x;
  524. this._viewportsCurrent[index].y = y;
  525. this._viewportsCurrent[index].w = w;
  526. this._viewportsCurrent[index].h = h;
  527. renderPass.setViewport(x, y, w, h, 0, 1);
  528. if (dbgVerboseLogsForFirstFrames) {
  529. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  530. console.log("frame #" + (this as any)._count + " - _viewport applied - (", x, y, w, h, ") current pass is main pass=" + (renderPass === this._mainRenderPass));
  531. }
  532. }
  533. }
  534. }
  535. /** @hidden */
  536. public _viewport(x: number, y: number, width: number, height: number): void {
  537. this._viewportCached.x = x;
  538. this._viewportCached.y = y;
  539. this._viewportCached.z = width;
  540. this._viewportCached.w = height;
  541. }
  542. public enableScissor(x: number, y: number, width: number, height: number): void {
  543. const renderPass = this._getCurrentRenderPass();
  544. renderPass.setScissorRect(x, y, width, height);
  545. }
  546. public disableScissor() {
  547. const renderPass = this._getCurrentRenderPass();
  548. renderPass.setScissorRect(0, 0, this.getRenderWidth(), this.getRenderHeight());
  549. }
  550. public clear(color: Nullable<IColor4Like>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  551. // Some PGs are using color3...
  552. if (color && color.a === undefined) {
  553. color.a = 1;
  554. }
  555. // We need to recreate the render pass so that the new parameters for clear color / depth / stencil are taken into account
  556. if (this._currentRenderTarget) {
  557. if (this._currentRenderPass) {
  558. this._endRenderTargetRenderPass();
  559. }
  560. this._startRenderTargetRenderPass(this._currentRenderTarget!, backBuffer ? color : null, depth, stencil);
  561. } else {
  562. if (this.useReverseDepthBuffer) {
  563. this._depthCullingState.depthFunc = Constants.GREATER;
  564. }
  565. this._mainColorAttachments[0].loadValue = backBuffer && color ? color : WebGPUConstants.LoadOp.Load;
  566. this._mainDepthAttachment.depthLoadValue = depth ? (this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue) : WebGPUConstants.LoadOp.Load;
  567. this._mainDepthAttachment.stencilLoadValue = stencil ? this._clearStencilValue : WebGPUConstants.LoadOp.Load;
  568. if (this._mainRenderPass) {
  569. this._endMainRenderPass();
  570. }
  571. this._startMainRenderPass();
  572. }
  573. }
  574. //------------------------------------------------------------------------------
  575. // Vertex/Index Buffers
  576. //------------------------------------------------------------------------------
  577. public createVertexBuffer(data: DataArray): DataBuffer {
  578. let view: ArrayBufferView;
  579. if (data instanceof Array) {
  580. view = new Float32Array(data);
  581. }
  582. else if (data instanceof ArrayBuffer) {
  583. view = new Uint8Array(data);
  584. }
  585. else {
  586. view = data;
  587. }
  588. const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Vertex | WebGPUConstants.BufferUsage.CopyDst);
  589. return dataBuffer;
  590. }
  591. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  592. return this.createVertexBuffer(data);
  593. }
  594. public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  595. const dataBuffer = vertexBuffer as WebGPUDataBuffer;
  596. if (byteOffset === undefined) {
  597. byteOffset = 0;
  598. }
  599. let view: ArrayBufferView;
  600. if (byteLength === undefined) {
  601. if (data instanceof Array) {
  602. view = new Float32Array(data);
  603. }
  604. else if (data instanceof ArrayBuffer) {
  605. view = new Uint8Array(data);
  606. }
  607. else {
  608. view = data;
  609. }
  610. byteLength = view.byteLength;
  611. } else {
  612. if (data instanceof Array) {
  613. view = new Float32Array(data);
  614. }
  615. else if (data instanceof ArrayBuffer) {
  616. view = new Uint8Array(data);
  617. }
  618. else {
  619. view = data;
  620. }
  621. }
  622. this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength);
  623. }
  624. public createIndexBuffer(data: IndicesArray): DataBuffer {
  625. let is32Bits = true;
  626. let view: ArrayBufferView;
  627. if (data instanceof Uint32Array || data instanceof Int32Array) {
  628. view = data;
  629. }
  630. else if (data instanceof Uint16Array) {
  631. view = data;
  632. is32Bits = false;
  633. }
  634. else {
  635. if (data.length > 65535) {
  636. view = new Uint32Array(data);
  637. }
  638. else {
  639. view = new Uint16Array(data);
  640. is32Bits = false;
  641. }
  642. }
  643. const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Index | WebGPUConstants.BufferUsage.CopyDst);
  644. dataBuffer.is32Bits = is32Bits;
  645. return dataBuffer;
  646. }
  647. public updateDynamicIndexBuffer(indexBuffer: DataBuffer, indices: IndicesArray, offset: number = 0): void {
  648. const gpuBuffer = indexBuffer as WebGPUDataBuffer;
  649. var view: ArrayBufferView;
  650. if (indices instanceof Uint16Array) {
  651. if (indexBuffer.is32Bits) {
  652. view = Uint32Array.from(indices);
  653. }
  654. else {
  655. view = indices;
  656. }
  657. }
  658. else if (indices instanceof Uint32Array) {
  659. if (indexBuffer.is32Bits) {
  660. view = indices;
  661. }
  662. else {
  663. view = Uint16Array.from(indices);
  664. }
  665. }
  666. else {
  667. if (indexBuffer.is32Bits) {
  668. view = new Uint32Array(indices);
  669. }
  670. else {
  671. view = new Uint16Array(indices);
  672. }
  673. }
  674. this._bufferManager.setSubData(gpuBuffer, offset, view);
  675. }
  676. public bindBuffersDirectly(vertexBuffer: DataBuffer, indexBuffer: DataBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  677. throw "Not implemented on WebGPU so far.";
  678. }
  679. public updateAndBindInstancesBuffer(instancesBuffer: DataBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  680. throw "Not implemented on WebGPU so far.";
  681. }
  682. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<DataBuffer>, effect: Effect): void {
  683. this._currentIndexBuffer = indexBuffer;
  684. this._currentVertexBuffers = vertexBuffers;
  685. }
  686. /** @hidden */
  687. public _releaseBuffer(buffer: DataBuffer): boolean {
  688. return this._bufferManager.releaseBuffer(buffer);
  689. }
  690. //------------------------------------------------------------------------------
  691. // UBO
  692. //------------------------------------------------------------------------------
  693. public createUniformBuffer(elements: FloatArray): DataBuffer {
  694. let view: Float32Array;
  695. if (elements instanceof Array) {
  696. view = new Float32Array(elements);
  697. }
  698. else {
  699. view = elements;
  700. }
  701. const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst);
  702. return dataBuffer;
  703. }
  704. public createDynamicUniformBuffer(elements: FloatArray): DataBuffer {
  705. return this.createUniformBuffer(elements);
  706. }
  707. public updateUniformBuffer(uniformBuffer: DataBuffer, elements: FloatArray, offset?: number, count?: number): void {
  708. if (offset === undefined) {
  709. offset = 0;
  710. }
  711. const dataBuffer = uniformBuffer as WebGPUDataBuffer;
  712. let view: Float32Array;
  713. if (count === undefined) {
  714. if (elements instanceof Float32Array) {
  715. view = elements;
  716. } else {
  717. view = new Float32Array(elements);
  718. }
  719. count = view.byteLength;
  720. } else {
  721. if (elements instanceof Float32Array) {
  722. view = elements;
  723. } else {
  724. view = new Float32Array(elements);
  725. }
  726. }
  727. this._bufferManager.setSubData(dataBuffer, offset, view, 0, count);
  728. }
  729. public bindUniformBufferBase(buffer: DataBuffer, location: number, name: string): void {
  730. this._uniformsBuffers[name] = buffer as WebGPUDataBuffer;
  731. }
  732. //------------------------------------------------------------------------------
  733. // Effects
  734. //------------------------------------------------------------------------------
  735. public createEffect(baseName: any, attributesNamesOrOptions: string[] | IEffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  736. onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
  737. const vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName.vertexSource || baseName;
  738. const fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName.fragmentSource || baseName;
  739. const name = vertex + "+" + fragment + "@" + (defines ? defines : (<IEffectCreationOptions>attributesNamesOrOptions).defines);
  740. /*const shader = this._compiledShaders[name];
  741. if (shader) {
  742. return new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, shader.sources);
  743. }
  744. else {
  745. return new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name);
  746. }*/
  747. if (this._compiledEffects[name]) {
  748. var compiledEffect = <Effect>this._compiledEffects[name];
  749. if (onCompiled && compiledEffect.isReady()) {
  750. onCompiled(compiledEffect);
  751. }
  752. return compiledEffect;
  753. }
  754. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name);
  755. this._compiledEffects[name] = effect;
  756. return effect;
  757. }
  758. private _compileRawShaderToSpirV(source: string, type: string): Uint32Array {
  759. return this._glslang.compileGLSL(source, type);
  760. }
  761. private _compileShaderToSpirV(source: string, type: string, defines: Nullable<string>, shaderVersion: string): Uint32Array {
  762. return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  763. }
  764. private _createPipelineStageDescriptor(vertexShader: Uint32Array, fragmentShader: Uint32Array): IWebGPURenderPipelineStageDescriptor {
  765. return {
  766. vertexStage: {
  767. module: this._device.createShaderModule({
  768. code: vertexShader,
  769. }),
  770. entryPoint: "main",
  771. },
  772. fragmentStage: {
  773. module: this._device.createShaderModule({
  774. code: fragmentShader,
  775. }),
  776. entryPoint: "main"
  777. }
  778. };
  779. }
  780. private _compileRawPipelineStageDescriptor(vertexCode: string, fragmentCode: string): IWebGPURenderPipelineStageDescriptor {
  781. var vertexShader = this._compileRawShaderToSpirV(vertexCode, "vertex");
  782. var fragmentShader = this._compileRawShaderToSpirV(fragmentCode, "fragment");
  783. return this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  784. }
  785. private _compilePipelineStageDescriptor(vertexCode: string, fragmentCode: string, defines: Nullable<string>): IWebGPURenderPipelineStageDescriptor {
  786. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  787. var shaderVersion = "#version 450\n";
  788. var vertexShader = this._compileShaderToSpirV(vertexCode, "vertex", defines, shaderVersion);
  789. var fragmentShader = this._compileShaderToSpirV(fragmentCode, "fragment", defines, shaderVersion);
  790. let program = this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  791. this.onAfterShaderCompilationObservable.notifyObservers(this);
  792. return program;
  793. }
  794. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  795. throw "Not available on WebGPU";
  796. }
  797. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  798. throw "Not available on WebGPU";
  799. }
  800. public createPipelineContext(shaderProcessingContext: Nullable<ShaderProcessingContext>): IPipelineContext {
  801. var pipelineContext = new WebGPUPipelineContext(shaderProcessingContext! as WebGPUShaderProcessingContext, this);
  802. pipelineContext.engine = this;
  803. return pipelineContext;
  804. }
  805. /** @hidden */
  806. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean, rawVertexSourceCode: string, rawFragmentSourceCode: string,
  807. rebuildRebind: any,
  808. defines: Nullable<string>,
  809. transformFeedbackVaryings: Nullable<string[]>,
  810. key: string) {
  811. const webGpuContext = pipelineContext as WebGPUPipelineContext;
  812. // TODO WEBGPU. Check if caches could be reuse from piepline ???
  813. const shader = this._compiledShaders[key];
  814. if (shader) {
  815. webGpuContext.stages = shader.stages;
  816. webGpuContext.availableAttributes = shader.availableAttributes;
  817. webGpuContext.availableUBOs = shader.availableUBOs;
  818. webGpuContext.availableSamplers = shader.availableSamplers;
  819. webGpuContext.orderedAttributes = shader.orderedAttributes;
  820. webGpuContext.orderedUBOsAndSamplers = shader.orderedUBOsAndSamplers;
  821. webGpuContext.leftOverUniforms = shader.leftOverUniforms;
  822. webGpuContext.leftOverUniformsByName = shader.leftOverUniformsByName;
  823. webGpuContext.sources = shader.sources;
  824. }
  825. else {
  826. if (dbgShowShaderCode) {
  827. console.log(defines);
  828. console.log(vertexSourceCode);
  829. console.log(fragmentSourceCode);
  830. }
  831. webGpuContext.sources = {
  832. fragment: fragmentSourceCode,
  833. vertex: vertexSourceCode,
  834. rawVertex: rawVertexSourceCode,
  835. rawFragment: rawFragmentSourceCode,
  836. };
  837. if (createAsRaw) {
  838. webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode);
  839. }
  840. else {
  841. webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines);
  842. }
  843. this._compiledShaders[key] = {
  844. stages: webGpuContext.stages,
  845. availableAttributes: webGpuContext.availableAttributes,
  846. availableUBOs: webGpuContext.availableUBOs,
  847. availableSamplers: webGpuContext.availableSamplers,
  848. orderedAttributes: webGpuContext.orderedAttributes,
  849. orderedUBOsAndSamplers: webGpuContext.orderedUBOsAndSamplers,
  850. leftOverUniforms: webGpuContext.leftOverUniforms,
  851. leftOverUniformsByName: webGpuContext.leftOverUniformsByName,
  852. sources: webGpuContext.sources
  853. };
  854. }
  855. }
  856. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  857. const results = new Array(attributesNames.length);
  858. const gpuPipelineContext = (pipelineContext as WebGPUPipelineContext);
  859. // TODO WEBGPU. Hard coded for WebGPU until an introspection lib is available.
  860. // Should be done at processing time, not need to double the work in here.
  861. for (let i = 0; i < attributesNames.length; i++) {
  862. const attributeName = attributesNames[i];
  863. const attributeLocation = gpuPipelineContext.availableAttributes[attributeName];
  864. if (attributeLocation === undefined) {
  865. continue;
  866. }
  867. results[i] = attributeLocation;
  868. }
  869. return results;
  870. }
  871. public enableEffect(effect: Nullable<Effect>): void {
  872. if (!effect || effect === this._currentEffect) {
  873. return;
  874. }
  875. this._currentEffect = effect;
  876. if (effect.onBind) {
  877. effect.onBind(effect);
  878. }
  879. if (effect._onBindObservable) {
  880. effect._onBindObservable.notifyObservers(effect);
  881. }
  882. }
  883. public _releaseEffect(effect: Effect): void {
  884. // Effect gets garbage collected without explicit destroy in WebGPU.
  885. }
  886. /**
  887. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  888. */
  889. public releaseEffects() {
  890. // Effect gets garbage collected without explicit destroy in WebGPU.
  891. }
  892. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  893. const webgpuPipelineContext = pipelineContext as WebGPUPipelineContext;
  894. if (webgpuPipelineContext) {
  895. pipelineContext.dispose();
  896. }
  897. }
  898. //------------------------------------------------------------------------------
  899. // Textures
  900. //------------------------------------------------------------------------------
  901. public get needPOTTextures(): boolean {
  902. return false;
  903. }
  904. private _getMainDepthTextureFormat(): GPUTextureFormat {
  905. return this.isStencilEnable ? WebGPUConstants.TextureFormat.Depth24PlusStencil8 : WebGPUConstants.TextureFormat.Depth32Float;
  906. }
  907. /** @hidden */
  908. public _createHardwareTexture(): HardwareTextureWrapper {
  909. return new WebGPUHardwareTexture();
  910. }
  911. /** @hidden */
  912. public _releaseTexture(texture: InternalTexture): void {
  913. const hardwareTexture = texture._hardwareTexture;
  914. const irradianceTexture = texture._irradianceTexture;
  915. const depthStencilTexture = texture._depthStencilTexture;
  916. const index = this._internalTexturesCache.indexOf(texture);
  917. if (index !== -1) {
  918. this._internalTexturesCache.splice(index, 1);
  919. }
  920. // We can't destroy the objects just now because they could be used in the current frame - we delay the destroying after the end of the frame
  921. this._deferredReleaseTextures.push([texture, hardwareTexture, irradianceTexture, depthStencilTexture]);
  922. }
  923. private _getSamplerFilterDescriptor(internalTexture: InternalTexture): {
  924. magFilter: GPUFilterMode,
  925. minFilter: GPUFilterMode,
  926. mipmapFilter: GPUFilterMode
  927. } {
  928. let magFilter: GPUFilterMode, minFilter: GPUFilterMode, mipmapFilter: GPUFilterMode;
  929. switch (internalTexture.samplingMode) {
  930. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  931. magFilter = WebGPUConstants.FilterMode.Linear;
  932. minFilter = WebGPUConstants.FilterMode.Linear;
  933. mipmapFilter = WebGPUConstants.FilterMode.Nearest;
  934. break;
  935. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  936. magFilter = WebGPUConstants.FilterMode.Linear;
  937. minFilter = WebGPUConstants.FilterMode.Linear;
  938. mipmapFilter = WebGPUConstants.FilterMode.Linear;
  939. break;
  940. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  941. magFilter = WebGPUConstants.FilterMode.Nearest;
  942. minFilter = WebGPUConstants.FilterMode.Nearest;
  943. mipmapFilter = WebGPUConstants.FilterMode.Linear;
  944. break;
  945. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  946. magFilter = WebGPUConstants.FilterMode.Nearest;
  947. minFilter = WebGPUConstants.FilterMode.Nearest;
  948. mipmapFilter = WebGPUConstants.FilterMode.Nearest;
  949. break;
  950. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  951. magFilter = WebGPUConstants.FilterMode.Nearest;
  952. minFilter = WebGPUConstants.FilterMode.Linear;
  953. mipmapFilter = WebGPUConstants.FilterMode.Nearest;
  954. break;
  955. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  956. magFilter = WebGPUConstants.FilterMode.Nearest;
  957. minFilter = WebGPUConstants.FilterMode.Linear;
  958. mipmapFilter = WebGPUConstants.FilterMode.Linear;
  959. break;
  960. case Engine.TEXTURE_NEAREST_LINEAR:
  961. magFilter = WebGPUConstants.FilterMode.Nearest;
  962. minFilter = WebGPUConstants.FilterMode.Linear;
  963. mipmapFilter = WebGPUConstants.FilterMode.Nearest;
  964. break;
  965. case Engine.TEXTURE_NEAREST_NEAREST:
  966. magFilter = WebGPUConstants.FilterMode.Nearest;
  967. minFilter = WebGPUConstants.FilterMode.Nearest;
  968. mipmapFilter = WebGPUConstants.FilterMode.Nearest;
  969. break;
  970. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  971. magFilter = WebGPUConstants.FilterMode.Linear;
  972. minFilter = WebGPUConstants.FilterMode.Nearest;
  973. mipmapFilter = WebGPUConstants.FilterMode.Nearest;
  974. break;
  975. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  976. magFilter = WebGPUConstants.FilterMode.Linear;
  977. minFilter = WebGPUConstants.FilterMode.Nearest;
  978. mipmapFilter = WebGPUConstants.FilterMode.Linear;
  979. break;
  980. case Engine.TEXTURE_LINEAR_LINEAR:
  981. magFilter = WebGPUConstants.FilterMode.Linear;
  982. minFilter = WebGPUConstants.FilterMode.Linear;
  983. mipmapFilter = WebGPUConstants.FilterMode.Nearest;
  984. break;
  985. case Engine.TEXTURE_LINEAR_NEAREST:
  986. magFilter = WebGPUConstants.FilterMode.Linear;
  987. minFilter = WebGPUConstants.FilterMode.Nearest;
  988. mipmapFilter = WebGPUConstants.FilterMode.Nearest;
  989. break;
  990. default:
  991. magFilter = WebGPUConstants.FilterMode.Linear;
  992. minFilter = WebGPUConstants.FilterMode.Linear;
  993. mipmapFilter = WebGPUConstants.FilterMode.Linear;
  994. break;
  995. }
  996. return {
  997. magFilter,
  998. minFilter,
  999. mipmapFilter
  1000. };
  1001. }
  1002. /** @hidden */
  1003. public _getWebGPUInternalFormat(format: number): GPUTextureFormat {
  1004. let internalFormat = WebGPUConstants.TextureFormat.RGBA8Unorm;
  1005. switch (format) {
  1006. case Constants.TEXTUREFORMAT_ALPHA:
  1007. throw "TEXTUREFORMAT_ALPHA format not supported in WebGPU";
  1008. case Constants.TEXTUREFORMAT_LUMINANCE:
  1009. throw "TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";
  1010. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1011. throw "TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";
  1012. case Constants.TEXTUREFORMAT_RED:
  1013. internalFormat = WebGPUConstants.TextureFormat.R8Snorm;
  1014. case Constants.TEXTUREFORMAT_RG:
  1015. internalFormat = WebGPUConstants.TextureFormat.RG8Snorm;
  1016. case Constants.TEXTUREFORMAT_RGB:
  1017. throw "RGB format not supported in WebGPU";
  1018. case Constants.TEXTUREFORMAT_RGBA:
  1019. internalFormat = WebGPUConstants.TextureFormat.RGBA8Unorm;
  1020. }
  1021. return internalFormat;
  1022. }
  1023. /** @hidden */
  1024. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  1025. return Constants.TEXTUREFORMAT_RGBA;
  1026. }
  1027. private _getWebGPUTextureFormat(type: number, format: number): GPUTextureFormat {
  1028. switch (format) {
  1029. case Constants.TEXTUREFORMAT_DEPTH24_STENCIL8:
  1030. return WebGPUConstants.TextureFormat.Depth24PlusStencil8;
  1031. case Constants.TEXTUREFORMAT_DEPTH32_FLOAT:
  1032. return WebGPUConstants.TextureFormat.Depth32Float;
  1033. case Constants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:
  1034. return WebGPUConstants.TextureFormat.BC7RGBAUnorm;
  1035. case Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT:
  1036. return WebGPUConstants.TextureFormat.BC6HRGBUFloat;
  1037. case Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT:
  1038. return WebGPUConstants.TextureFormat.BC6HRGBSFloat;
  1039. case Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5:
  1040. return WebGPUConstants.TextureFormat.BC3RGBAUnorm;
  1041. case Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3:
  1042. return WebGPUConstants.TextureFormat.BC2RGBAUnorm;
  1043. case Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:
  1044. return WebGPUConstants.TextureFormat.BC1RGBAUNorm;
  1045. }
  1046. switch (type) {
  1047. case Constants.TEXTURETYPE_BYTE:
  1048. switch (format) {
  1049. case Constants.TEXTUREFORMAT_RED:
  1050. return WebGPUConstants.TextureFormat.R8Snorm;
  1051. case Constants.TEXTUREFORMAT_RG:
  1052. return WebGPUConstants.TextureFormat.RG8Snorm;
  1053. case Constants.TEXTUREFORMAT_RGB:
  1054. throw "RGB format not supported in WebGPU";
  1055. case Constants.TEXTUREFORMAT_RED_INTEGER:
  1056. return WebGPUConstants.TextureFormat.R8Sint;
  1057. case Constants.TEXTUREFORMAT_RG_INTEGER:
  1058. return WebGPUConstants.TextureFormat.RG8Sint;
  1059. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  1060. throw "RGB_INTEGER format not supported in WebGPU";
  1061. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  1062. return WebGPUConstants.TextureFormat.RGBA8Sint;
  1063. default:
  1064. return WebGPUConstants.TextureFormat.RGBA8Snorm;
  1065. }
  1066. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  1067. switch (format) {
  1068. case Constants.TEXTUREFORMAT_RED:
  1069. return WebGPUConstants.TextureFormat.R8Unorm;
  1070. case Constants.TEXTUREFORMAT_RG:
  1071. return WebGPUConstants.TextureFormat.RG8Unorm;
  1072. case Constants.TEXTUREFORMAT_RGB:
  1073. throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
  1074. case Constants.TEXTUREFORMAT_RGBA:
  1075. return WebGPUConstants.TextureFormat.RGBA8Unorm;
  1076. case Constants.TEXTUREFORMAT_BGRA:
  1077. return WebGPUConstants.TextureFormat.BGRA8Unorm;
  1078. case Constants.TEXTUREFORMAT_RED_INTEGER:
  1079. return WebGPUConstants.TextureFormat.R8Uint;
  1080. case Constants.TEXTUREFORMAT_RG_INTEGER:
  1081. return WebGPUConstants.TextureFormat.RG8Uint;
  1082. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  1083. throw "RGB_INTEGER format not supported in WebGPU";
  1084. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  1085. return WebGPUConstants.TextureFormat.RGBA8Uint;
  1086. case Constants.TEXTUREFORMAT_ALPHA:
  1087. throw "TEXTUREFORMAT_ALPHA format not supported in WebGPU";
  1088. case Constants.TEXTUREFORMAT_LUMINANCE:
  1089. throw "TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";
  1090. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  1091. throw "TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";
  1092. default:
  1093. return WebGPUConstants.TextureFormat.RGBA8Unorm;
  1094. }
  1095. case Constants.TEXTURETYPE_SHORT:
  1096. switch (format) {
  1097. case Constants.TEXTUREFORMAT_RED_INTEGER:
  1098. return WebGPUConstants.TextureFormat.R16Sint;
  1099. case Constants.TEXTUREFORMAT_RG_INTEGER:
  1100. return WebGPUConstants.TextureFormat.RG16Sint;
  1101. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  1102. throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
  1103. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  1104. return WebGPUConstants.TextureFormat.RGBA16Sint;
  1105. default:
  1106. return WebGPUConstants.TextureFormat.RGBA16Sint;
  1107. }
  1108. case Constants.TEXTURETYPE_UNSIGNED_SHORT:
  1109. switch (format) {
  1110. case Constants.TEXTUREFORMAT_RED_INTEGER:
  1111. return WebGPUConstants.TextureFormat.R16Uint;
  1112. case Constants.TEXTUREFORMAT_RG_INTEGER:
  1113. return WebGPUConstants.TextureFormat.RG16Uint;
  1114. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  1115. throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
  1116. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  1117. return WebGPUConstants.TextureFormat.RGBA16Uint;
  1118. default:
  1119. return WebGPUConstants.TextureFormat.RGBA16Uint;
  1120. }
  1121. case Constants.TEXTURETYPE_INT:
  1122. switch (format) {
  1123. case Constants.TEXTUREFORMAT_RED_INTEGER:
  1124. return WebGPUConstants.TextureFormat.R32Sint;
  1125. case Constants.TEXTUREFORMAT_RG_INTEGER:
  1126. return WebGPUConstants.TextureFormat.RG32Sint;
  1127. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  1128. throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
  1129. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  1130. return WebGPUConstants.TextureFormat.RGBA32Sint;
  1131. default:
  1132. return WebGPUConstants.TextureFormat.RGBA32Sint;
  1133. }
  1134. case Constants.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  1135. switch (format) {
  1136. case Constants.TEXTUREFORMAT_RED_INTEGER:
  1137. return WebGPUConstants.TextureFormat.R32Uint;
  1138. case Constants.TEXTUREFORMAT_RG_INTEGER:
  1139. return WebGPUConstants.TextureFormat.RG32Uint;
  1140. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  1141. throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";
  1142. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  1143. return WebGPUConstants.TextureFormat.RGBA32Uint;
  1144. default:
  1145. return WebGPUConstants.TextureFormat.RGBA32Uint;
  1146. }
  1147. case Constants.TEXTURETYPE_FLOAT:
  1148. switch (format) {
  1149. case Constants.TEXTUREFORMAT_RED:
  1150. return WebGPUConstants.TextureFormat.R32Float; // By default. Other possibility is R16Float.
  1151. case Constants.TEXTUREFORMAT_RG:
  1152. return WebGPUConstants.TextureFormat.RG32Float; // By default. Other possibility is RG16Float.
  1153. case Constants.TEXTUREFORMAT_RGB:
  1154. throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
  1155. case Constants.TEXTUREFORMAT_RGBA:
  1156. return WebGPUConstants.TextureFormat.RGBA32Float; // By default. Other possibility is RGBA16Float.
  1157. default:
  1158. return WebGPUConstants.TextureFormat.RGBA32Float;
  1159. }
  1160. case Constants.TEXTURETYPE_HALF_FLOAT:
  1161. switch (format) {
  1162. case Constants.TEXTUREFORMAT_RED:
  1163. return WebGPUConstants.TextureFormat.R16Float;
  1164. case Constants.TEXTUREFORMAT_RG:
  1165. return WebGPUConstants.TextureFormat.RG16Float;
  1166. case Constants.TEXTUREFORMAT_RGB:
  1167. throw "TEXTUREFORMAT_RGB format not supported in WebGPU";
  1168. case Constants.TEXTUREFORMAT_RGBA:
  1169. return WebGPUConstants.TextureFormat.RGBA16Float;
  1170. default:
  1171. return WebGPUConstants.TextureFormat.RGBA16Float;
  1172. }
  1173. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  1174. throw "TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";
  1175. case Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  1176. throw "TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV format not supported in WebGPU";
  1177. case Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  1178. throw "TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV format not supported in WebGPU";
  1179. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  1180. throw "TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";
  1181. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  1182. throw "TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";
  1183. case Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  1184. switch (format) {
  1185. case Constants.TEXTUREFORMAT_RGBA:
  1186. return WebGPUConstants.TextureFormat.RGB10A2Unorm;
  1187. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  1188. throw "TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV";
  1189. default:
  1190. return WebGPUConstants.TextureFormat.RGB10A2Unorm;
  1191. }
  1192. }
  1193. return WebGPUConstants.TextureFormat.RGBA8Unorm;
  1194. }
  1195. private _getWrappingMode(mode: number): GPUAddressMode {
  1196. switch (mode) {
  1197. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  1198. return WebGPUConstants.AddressMode.Repeat;
  1199. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  1200. return WebGPUConstants.AddressMode.ClampToEdge;
  1201. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  1202. return WebGPUConstants.AddressMode.MirrorRepeat;
  1203. }
  1204. return WebGPUConstants.AddressMode.Repeat;
  1205. }
  1206. private _getSamplerWrappingDescriptor(internalTexture: InternalTexture): {
  1207. addressModeU: GPUAddressMode,
  1208. addressModeV: GPUAddressMode,
  1209. addressModeW: GPUAddressMode
  1210. } {
  1211. return {
  1212. addressModeU: this._getWrappingMode(internalTexture._cachedWrapU!),
  1213. addressModeV: this._getWrappingMode(internalTexture._cachedWrapV!),
  1214. addressModeW: this._getWrappingMode(internalTexture._cachedWrapR!),
  1215. };
  1216. }
  1217. private _getSamplerDescriptor(internalTexture: InternalTexture): GPUSamplerDescriptor {
  1218. return {
  1219. ...this._getSamplerFilterDescriptor(internalTexture),
  1220. ...this._getSamplerWrappingDescriptor(internalTexture),
  1221. compare: internalTexture._comparisonFunction ? this._getCompareFunction(internalTexture._comparisonFunction) : undefined,
  1222. };
  1223. }
  1224. public createTexture(url: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<ISceneLike>, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  1225. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  1226. buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob | ImageBitmap> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  1227. forcedExtension: Nullable<string> = null, mimeType?: string): InternalTexture {
  1228. // TODO WEBGPU. this._options.textureSize
  1229. return this._createTextureBase(
  1230. url, noMipmap, invertY, scene, samplingMode, onLoad, onError,
  1231. (texture: InternalTexture, extension: string, scene: Nullable<ISceneLike>, img: HTMLImageElement | ImageBitmap | { width: number, height: number }, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  1232. processFunction: (width: number, height: number, img: HTMLImageElement | ImageBitmap | { width: number, height: number }, extension: string, texture: InternalTexture, continuationCallback: () => void) => boolean, samplingMode: number) => {
  1233. const imageBitmap = img as (ImageBitmap | { width: number, height: number}); // we will never get an HTMLImageElement in WebGPU
  1234. texture.baseWidth = imageBitmap.width;
  1235. texture.baseHeight = imageBitmap.height;
  1236. texture.width = imageBitmap.width;
  1237. texture.height = imageBitmap.height;
  1238. texture.format = format ?? -1;
  1239. processFunction(texture.width, texture.height, imageBitmap, extension, texture, () => {});
  1240. if (!texture._hardwareTexture?.underlyingResource) { // the texture could have been created before reaching this point so don't recreate it if already existing
  1241. const gpuTextureWrapper = this._createGPUTextureForInternalTexture(texture, imageBitmap.width, imageBitmap.height);
  1242. if (this._textureHelper.isImageBitmap(imageBitmap)) {
  1243. this._textureHelper.updateTexture(imageBitmap, gpuTextureWrapper.underlyingResource!, imageBitmap.width, imageBitmap.height, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0, this._uploadEncoder);
  1244. if (!noMipmap && !isCompressed) {
  1245. this._generateMipmaps(texture);
  1246. }
  1247. }
  1248. } else if (!noMipmap && !isCompressed) {
  1249. this._generateMipmaps(texture);
  1250. }
  1251. if (scene) {
  1252. scene._removePendingData(texture);
  1253. }
  1254. texture.isReady = true;
  1255. texture.onLoadedObservable.notifyObservers(texture);
  1256. texture.onLoadedObservable.clear();
  1257. },
  1258. () => false,
  1259. buffer, fallback, format, forcedExtension, mimeType
  1260. );
  1261. }
  1262. /** @hidden */
  1263. public _setCubeMapTextureParams(texture: InternalTexture, loadMipmap: boolean) {
  1264. texture.samplingMode = loadMipmap ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  1265. texture._cachedWrapU = Constants.TEXTURE_CLAMP_ADDRESSMODE;
  1266. texture._cachedWrapV = Constants.TEXTURE_CLAMP_ADDRESSMODE;
  1267. }
  1268. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null,
  1269. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null, createPolynomials: boolean = false, lodScale: number = 0, lodOffset: number = 0, fallback: Nullable<InternalTexture> = null): InternalTexture {
  1270. return this.createCubeTextureBase(
  1271. rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback,
  1272. null,
  1273. (texture: InternalTexture, imgs: HTMLImageElement[] | ImageBitmap[]) => {
  1274. const imageBitmaps = imgs as ImageBitmap[]; // we will always get an ImageBitmap array in WebGPU
  1275. const width = imageBitmaps[0].width;
  1276. const height = width;
  1277. this._setCubeMapTextureParams(texture, !noMipmap);
  1278. texture.format = format ?? -1;
  1279. const gpuTextureWrapper = this._createGPUTextureForInternalTexture(texture, width, height);
  1280. this._textureHelper.updateCubeTextures(imageBitmaps, gpuTextureWrapper.underlyingResource!, width, height, gpuTextureWrapper.format, false, false, 0, 0, this._uploadEncoder);
  1281. if (!noMipmap) {
  1282. this._generateMipmaps(texture);
  1283. }
  1284. texture.isReady = true;
  1285. texture.onLoadedObservable.notifyObservers(texture);
  1286. texture.onLoadedObservable.clear();
  1287. if (onLoad) {
  1288. onLoad();
  1289. }
  1290. }
  1291. );
  1292. }
  1293. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  1294. compression: Nullable<string> = null, type: number = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture
  1295. {
  1296. const texture = new InternalTexture(this, InternalTextureSource.Raw);
  1297. texture.baseWidth = width;
  1298. texture.baseHeight = height;
  1299. texture.width = width;
  1300. texture.height = height;
  1301. texture.format = format;
  1302. texture.generateMipMaps = generateMipMaps;
  1303. texture.samplingMode = samplingMode;
  1304. texture.invertY = invertY;
  1305. texture._compression = compression;
  1306. texture.type = type;
  1307. if (!this._doNotHandleContextLost) {
  1308. texture._bufferView = data;
  1309. }
  1310. this._createGPUTextureForInternalTexture(texture, width, height);
  1311. this.updateRawTexture(texture, data, format, invertY, compression, type);
  1312. this._internalTexturesCache.push(texture);
  1313. return texture;
  1314. }
  1315. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  1316. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  1317. compression: Nullable<string> = null): InternalTexture
  1318. {
  1319. const texture = new InternalTexture(this, InternalTextureSource.CubeRaw);
  1320. texture.isCube = true;
  1321. texture.format = format === Constants.TEXTUREFORMAT_RGB ? Constants.TEXTUREFORMAT_RGBA : format;
  1322. texture.type = type;
  1323. texture.generateMipMaps = generateMipMaps;
  1324. texture.width = size;
  1325. texture.height = size;
  1326. if (!this._doNotHandleContextLost) {
  1327. texture._bufferViewArray = data;
  1328. }
  1329. this._createGPUTextureForInternalTexture(texture);
  1330. if (data) {
  1331. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  1332. }
  1333. return texture;
  1334. }
  1335. public createRawCubeTextureFromUrl(url: string, scene: Nullable<Scene>, size: number, format: number, type: number, noMipmap: boolean,
  1336. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  1337. mipmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  1338. onLoad: Nullable<() => void> = null,
  1339. onError: Nullable<(message?: string, exception?: any) => void> = null,
  1340. samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  1341. invertY: boolean = false): InternalTexture
  1342. {
  1343. const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null);
  1344. scene?._addPendingData(texture);
  1345. texture.url = url;
  1346. this._internalTexturesCache.push(texture);
  1347. const onerror = (request?: IWebRequest, exception?: any) => {
  1348. scene?._removePendingData(texture);
  1349. if (onError && request) {
  1350. onError(request.status + " " + request.statusText, exception);
  1351. }
  1352. };
  1353. const internalCallback = (data: any) => {
  1354. const width = texture.width;
  1355. const faceDataArrays = callback(data);
  1356. if (!faceDataArrays) {
  1357. return;
  1358. }
  1359. const faces = [0, 2, 4, 1, 3, 5];
  1360. if (mipmapGenerator) {
  1361. const needConversion = format === Constants.TEXTUREFORMAT_RGB;
  1362. const mipData = mipmapGenerator(faceDataArrays);
  1363. const gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1364. const faces = [0, 1, 2, 3, 4, 5];
  1365. for (let level = 0; level < mipData.length; level++) {
  1366. const mipSize = width >> level;
  1367. const allFaces = [];
  1368. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  1369. let mipFaceData = mipData[level][faces[faceIndex]];
  1370. if (needConversion) {
  1371. mipFaceData = _convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  1372. }
  1373. allFaces.push(new Uint8Array(mipFaceData.buffer, mipFaceData.byteOffset, mipFaceData.byteLength));
  1374. }
  1375. this._textureHelper.updateCubeTextures(allFaces, gpuTextureWrapper.underlyingResource!, mipSize, mipSize, gpuTextureWrapper.format, invertY, false, 0, 0, this._uploadEncoder);
  1376. }
  1377. }
  1378. else {
  1379. const allFaces = [];
  1380. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  1381. allFaces.push(faceDataArrays[faces[faceIndex]]);
  1382. }
  1383. this.updateRawCubeTexture(texture, allFaces, format, type, invertY);
  1384. }
  1385. texture.isReady = true;
  1386. scene?._removePendingData(texture);
  1387. if (onLoad) {
  1388. onLoad();
  1389. }
  1390. };
  1391. this._loadFile(url, (data) => {
  1392. internalCallback(data);
  1393. }, undefined, scene?.offlineProvider, true, onerror);
  1394. return texture;
  1395. }
  1396. public createRawTexture2DArray(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  1397. compression: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture
  1398. {
  1399. var source = InternalTextureSource.Raw2DArray;
  1400. var texture = new InternalTexture(this, source);
  1401. if (dbgShowWarningsNotImplemented) {
  1402. console.warn("createRawTexture2DArray not implemented yet in WebGPU");
  1403. }
  1404. return texture;
  1405. }
  1406. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  1407. compression: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture
  1408. {
  1409. var source = InternalTextureSource.Raw2DArray;
  1410. var texture = new InternalTexture(this, source);
  1411. if (dbgShowWarningsNotImplemented) {
  1412. console.warn("createRawTexture3D not implemented yet in WebGPU");
  1413. }
  1414. return texture;
  1415. }
  1416. public generateMipMapsForCubemap(texture: InternalTexture, unbind = true) {
  1417. if (texture.generateMipMaps) {
  1418. let gpuTexture = texture._hardwareTexture?.underlyingResource;
  1419. if (!gpuTexture) {
  1420. this._createGPUTextureForInternalTexture(texture);
  1421. }
  1422. this._generateMipmaps(texture);
  1423. }
  1424. }
  1425. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture, generateMipMaps: boolean = false): void {
  1426. if (generateMipMaps) {
  1427. texture.generateMipMaps = true;
  1428. this._generateMipmaps(texture);
  1429. }
  1430. texture.samplingMode = samplingMode;
  1431. }
  1432. public updateTextureWrappingMode(texture: InternalTexture, wrapU: Nullable<number>, wrapV: Nullable<number> = null, wrapR: Nullable<number> = null): void {
  1433. if (wrapU !== null) {
  1434. texture._cachedWrapU = wrapU;
  1435. }
  1436. if (wrapV !== null) {
  1437. texture._cachedWrapV = wrapV;
  1438. }
  1439. if ((texture.is2DArray || texture.is3D) && (wrapR !== null)) {
  1440. texture._cachedWrapR = wrapR;
  1441. }
  1442. }
  1443. private _setInternalTexture(name: string, internalTexture: Nullable<InternalTexture>): void {
  1444. if (this._currentEffect) {
  1445. const webgpuPipelineContext = this._currentEffect._pipelineContext as WebGPUPipelineContext;
  1446. if (webgpuPipelineContext.samplers[name]) {
  1447. if (webgpuPipelineContext.samplers[name]!.texture !== internalTexture) {
  1448. webgpuPipelineContext.bindGroups = null as any; // the bind groups need to be rebuilt (at least the bind group owning this texture, but it's easier to just have them all rebuilt)
  1449. }
  1450. webgpuPipelineContext.samplers[name]!.texture = internalTexture!;
  1451. }
  1452. else {
  1453. // TODO WEBGPU. 121 mapping samplers <-> availableSamplers
  1454. const availableSampler = webgpuPipelineContext.availableSamplers[name];
  1455. if (availableSampler) {
  1456. webgpuPipelineContext.samplers[name] = {
  1457. setIndex: availableSampler.setIndex,
  1458. textureBinding: availableSampler.bindingIndex,
  1459. samplerBinding: availableSampler.bindingIndex + 1,
  1460. texture: internalTexture!
  1461. };
  1462. }
  1463. }
  1464. }
  1465. }
  1466. public setTexture(channel: number, _: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>, name: string): void {
  1467. this._setTexture(channel, texture, false, false, name);
  1468. }
  1469. protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false, name = ""): boolean {
  1470. if (this._currentEffect) {
  1471. const webgpuPipelineContext = this._currentEffect._pipelineContext as WebGPUPipelineContext;
  1472. if (!texture) {
  1473. if (webgpuPipelineContext.samplers[name] && webgpuPipelineContext.samplers[name]!.texture) {
  1474. webgpuPipelineContext.bindGroups = null as any; // the bind groups need to be rebuilt (at least the bind group owning this texture, but it's easier to just have them all rebuilt)
  1475. }
  1476. webgpuPipelineContext.samplers[name] = null;
  1477. return false;
  1478. }
  1479. // Video
  1480. if ((<VideoTexture>texture).video) {
  1481. this._activeChannel = channel;
  1482. (<VideoTexture>texture).update();
  1483. } else if (texture.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  1484. texture.delayLoad();
  1485. return false;
  1486. }
  1487. let internalTexture: Nullable<InternalTexture> = null;
  1488. if (depthStencilTexture) {
  1489. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  1490. }
  1491. else if (texture.isReady()) {
  1492. internalTexture = <InternalTexture>texture.getInternalTexture();
  1493. }
  1494. else if (texture.isCube) {
  1495. internalTexture = this.emptyCubeTexture;
  1496. if (dbgGenerateLogs) {
  1497. console.log("Using a temporary empty cube texture. internalTexture.uniqueId=", texture.uniqueId, texture);
  1498. }
  1499. }
  1500. else if (texture.is3D) {
  1501. internalTexture = this.emptyTexture3D;
  1502. if (dbgGenerateLogs) {
  1503. console.log("Using a temporary empty 3D texture. internalTexture.uniqueId=", texture.uniqueId, texture);
  1504. }
  1505. }
  1506. else if (texture.is2DArray) {
  1507. internalTexture = this.emptyTexture2DArray;
  1508. if (dbgGenerateLogs) {
  1509. console.log("Using a temporary empty 2D array texture. internalTexture.uniqueId=", texture.uniqueId, texture);
  1510. }
  1511. }
  1512. else {
  1513. internalTexture = this.emptyTexture;
  1514. if (dbgGenerateLogs) {
  1515. console.log("Using a temporary empty texture. internalTexture.uniqueId=", texture.uniqueId, texture);
  1516. }
  1517. }
  1518. if (internalTexture && !internalTexture.isMultiview) {
  1519. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  1520. if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  1521. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  1522. const textureWrapMode = (texture.coordinatesMode !== Constants.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Constants.TEXTURE_SKYBOX_MODE) ? Constants.TEXTURE_WRAP_ADDRESSMODE : Constants.TEXTURE_CLAMP_ADDRESSMODE;
  1523. texture.wrapU = textureWrapMode;
  1524. texture.wrapV = textureWrapMode;
  1525. }
  1526. this._setAnisotropicLevel(0, internalTexture, texture.anisotropicFilteringLevel);
  1527. }
  1528. if (internalTexture) {
  1529. internalTexture._cachedWrapU = texture.wrapU;
  1530. internalTexture._cachedWrapV = texture.wrapV;
  1531. internalTexture._cachedWrapR = texture.wrapR;
  1532. }
  1533. if (dbgSanityChecks && internalTexture && (internalTexture as any)._released) {
  1534. console.error("using a released texture in engine.setTexture!", internalTexture);
  1535. debugger;
  1536. }
  1537. this._setInternalTexture(name, internalTexture);
  1538. } else {
  1539. if (dbgVerboseLogsForFirstFrames) {
  1540. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  1541. console.log("frame #" + (this as any)._count + " - _setTexture called with a null _currentEffect! texture=", texture);
  1542. }
  1543. }
  1544. }
  1545. return true;
  1546. }
  1547. /** @hidden */
  1548. public _setAnisotropicLevel(target: number, internalTexture: InternalTexture, anisotropicFilteringLevel: number) {
  1549. if (internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  1550. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  1551. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR) {
  1552. anisotropicFilteringLevel = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  1553. }
  1554. if (internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) {
  1555. //this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy), internalTexture);
  1556. internalTexture._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel;
  1557. if (dbgShowWarningsNotImplemented) {
  1558. console.warn("_setAnisotropicLevel not implemented yet");
  1559. }
  1560. }
  1561. }
  1562. public bindSamplers(effect: Effect): void { }
  1563. public _bindTextureDirectly(target: number, texture: InternalTexture, forTextureDataUpdate = false, force = false): boolean {
  1564. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  1565. this._boundTexturesCache[this._activeChannel] = texture;
  1566. return true;
  1567. }
  1568. return false;
  1569. }
  1570. /** @hidden */
  1571. public _bindTexture(channel: number, texture: InternalTexture, name: string): void {
  1572. if (channel === undefined) {
  1573. return;
  1574. }
  1575. if (texture) {
  1576. texture._associatedChannel = channel;
  1577. }
  1578. this._activeChannel = channel;
  1579. this._setInternalTexture(name, texture);
  1580. }
  1581. private _createGPUTextureForInternalTexture(texture: InternalTexture, width?: number, height?: number): WebGPUHardwareTexture {
  1582. if (!texture._hardwareTexture) {
  1583. texture._hardwareTexture = this._createHardwareTexture();
  1584. }
  1585. if (width === undefined) {
  1586. width = texture.width;
  1587. }
  1588. if (height === undefined) {
  1589. height = texture.height;
  1590. }
  1591. const gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1592. gpuTextureWrapper.format = this._getWebGPUTextureFormat(texture.type, texture.format);
  1593. const textureUsages =
  1594. texture._source === InternalTextureSource.RenderTarget ? WebGPUConstants.TextureUsage.Sampled | WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.OutputAttachment :
  1595. texture._source === InternalTextureSource.Depth ? WebGPUConstants.TextureUsage.Sampled | WebGPUConstants.TextureUsage.OutputAttachment : -1;
  1596. const generateMipMaps = texture._source === InternalTextureSource.RenderTarget ? false : texture.generateMipMaps;
  1597. if (texture.isCube) {
  1598. const gpuTexture = this._textureHelper.createCubeTexture({ width, height }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, gpuTextureWrapper.format, texture.samples || 1, this._uploadEncoder, textureUsages);
  1599. gpuTextureWrapper.set(gpuTexture);
  1600. gpuTextureWrapper.createView({
  1601. dimension: WebGPUConstants.TextureViewDimension.Cube,
  1602. mipLevelCount: generateMipMaps ? WebGPUTextureHelper.computeNumMipmapLevels(width!, height!) : 1,
  1603. baseArrayLayer: 0,
  1604. baseMipLevel: 0,
  1605. aspect: WebGPUConstants.TextureAspect.All
  1606. });
  1607. } else {
  1608. const gpuTexture = this._textureHelper.createTexture({ width, height }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, gpuTextureWrapper.format, texture.samples || 1, this._uploadEncoder, textureUsages);
  1609. gpuTextureWrapper.set(gpuTexture);
  1610. gpuTextureWrapper.createView({
  1611. dimension: WebGPUConstants.TextureViewDimension.E2d,
  1612. mipLevelCount: generateMipMaps ? WebGPUTextureHelper.computeNumMipmapLevels(width!, height!) : 1,
  1613. baseArrayLayer: 0,
  1614. baseMipLevel: 0,
  1615. aspect: WebGPUConstants.TextureAspect.All
  1616. });
  1617. }
  1618. texture.width = texture.baseWidth = width;
  1619. texture.height = texture.baseHeight = height;
  1620. return gpuTextureWrapper;
  1621. }
  1622. private _generateMipmaps(texture: InternalTexture) {
  1623. const gpuTexture = texture._hardwareTexture?.underlyingResource;
  1624. if (!gpuTexture) {
  1625. return;
  1626. }
  1627. const format = (texture._hardwareTexture as WebGPUHardwareTexture).format;
  1628. const mipmapCount = WebGPUTextureHelper.computeNumMipmapLevels(texture.width, texture.height);
  1629. if (dbgVerboseLogsForFirstFrames) {
  1630. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  1631. console.log("frame #" + (this as any)._count + " - generate mipmaps called - width=", texture.width, "height=", texture.height, "isCube=", texture.isCube);
  1632. }
  1633. }
  1634. if (texture.isCube) {
  1635. this._textureHelper.generateCubeMipmaps(gpuTexture, format, mipmapCount, this._uploadEncoder);
  1636. } else {
  1637. this._textureHelper.generateMipmaps(gpuTexture, format, mipmapCount, 0, this._uploadEncoder);
  1638. }
  1639. }
  1640. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement | OffscreenCanvas, invertY: boolean, premulAlpha: boolean = false, format?: number, forceBindTexture?: boolean): void {
  1641. if (!texture) {
  1642. return;
  1643. }
  1644. const width = canvas.width, height = canvas.height;
  1645. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1646. if (!texture._hardwareTexture?.underlyingResource) {
  1647. gpuTextureWrapper = this._createGPUTextureForInternalTexture(texture, width, height);
  1648. }
  1649. if (dbgSanityChecks && (texture as any)._released) {
  1650. console.error("Using a released texture in updateDynamicTexture!", texture, gpuTextureWrapper);
  1651. }
  1652. createImageBitmap(canvas).then((bitmap) => {
  1653. this._textureHelper.updateTexture(bitmap, gpuTextureWrapper.underlyingResource!, width, height, gpuTextureWrapper.format, 0, 0, invertY, premulAlpha, 0, 0, this._uploadEncoder);
  1654. if (texture.generateMipMaps) {
  1655. this._generateMipmaps(texture);
  1656. }
  1657. texture.isReady = true;
  1658. });
  1659. }
  1660. public updateTextureData(texture: InternalTexture, imageData: ArrayBufferView, xOffset: number, yOffset: number, width: number, height: number, faceIndex: number = 0, lod: number = 0): void {
  1661. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1662. if (!texture._hardwareTexture?.underlyingResource) {
  1663. gpuTextureWrapper = this._createGPUTextureForInternalTexture(texture);
  1664. }
  1665. const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);
  1666. this._textureHelper.updateTexture(data, gpuTextureWrapper.underlyingResource!, width, height, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, xOffset, yOffset, this._uploadEncoder);
  1667. }
  1668. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  1669. if (!texture || texture._isDisabled) {
  1670. return;
  1671. }
  1672. if (this._videoTextureSupported === undefined) {
  1673. this._videoTextureSupported = true;
  1674. }
  1675. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1676. if (!texture._hardwareTexture?.underlyingResource) {
  1677. gpuTextureWrapper = this._createGPUTextureForInternalTexture(texture);
  1678. }
  1679. createImageBitmap(video).then((bitmap) => {
  1680. this._textureHelper.updateTexture(bitmap, gpuTextureWrapper.underlyingResource!, texture.width, texture.height, gpuTextureWrapper.format, 0, 0, !invertY, false, 0, 0, this._uploadEncoder);
  1681. if (texture.generateMipMaps) {
  1682. this._generateMipmaps(texture);
  1683. }
  1684. texture.isReady = true;
  1685. }).catch((msg) => {
  1686. // Sometimes createImageBitmap(video) fails with "Failed to execute 'createImageBitmap' on 'Window': The provided element's player has no current data."
  1687. // Just keep going on
  1688. texture.isReady = true;
  1689. });
  1690. }
  1691. /** @hidden */
  1692. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  1693. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1694. if (!texture._hardwareTexture?.underlyingResource) {
  1695. texture.format = internalFormat;
  1696. gpuTextureWrapper = this._createGPUTextureForInternalTexture(texture, width, height);
  1697. }
  1698. const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);
  1699. this._textureHelper.updateTexture(data, gpuTextureWrapper.underlyingResource!, width, height, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0, this._uploadEncoder);
  1700. }
  1701. /** @hidden */
  1702. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0, babylonInternalFormat?: number, useTextureWidthAndHeight = false): void {
  1703. // TODO WEBPU babylonInternalFormat not handled.
  1704. // Note that it is used only by BasisTools.LoadTextureFromTranscodeResult when transcoding could not be done, and in that case the texture format used (TEXTURETYPE_UNSIGNED_SHORT_5_6_5) is not compatible with WebGPU...
  1705. const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);
  1706. const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);
  1707. const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  1708. const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  1709. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1710. if (!texture._hardwareTexture?.underlyingResource) {
  1711. gpuTextureWrapper = this._createGPUTextureForInternalTexture(texture, width, height);
  1712. }
  1713. const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);
  1714. this._textureHelper.updateTexture(data, gpuTextureWrapper.underlyingResource!, width, height, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0, this._uploadEncoder);
  1715. }
  1716. /** @hidden */
  1717. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1718. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  1719. }
  1720. /** @hidden */
  1721. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement | ImageBitmap, faceIndex: number = 0, lod: number = 0) {
  1722. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1723. if (!texture._hardwareTexture?.underlyingResource) {
  1724. gpuTextureWrapper = this._createGPUTextureForInternalTexture(texture);
  1725. }
  1726. const bitmap = image as ImageBitmap; // in WebGPU we will always get an ImageBitmap, not an HTMLImageElement
  1727. const width = Math.ceil(texture.width / (1 << lod));
  1728. const height = Math.ceil(texture.height / (1 << lod));
  1729. this._textureHelper.updateTexture(bitmap, gpuTextureWrapper.underlyingResource!, width, height, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0, this._uploadEncoder);
  1730. }
  1731. public updateRawTexture(texture: Nullable<InternalTexture>, bufferView: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type: number = Constants.TEXTURETYPE_UNSIGNED_INT): void {
  1732. if (!texture) {
  1733. return;
  1734. }
  1735. if (!this._doNotHandleContextLost) {
  1736. texture._bufferView = bufferView;
  1737. texture.invertY = invertY;
  1738. texture._compression = compression;
  1739. }
  1740. if (bufferView) {
  1741. const gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1742. const needConversion = format === Constants.TEXTUREFORMAT_RGB;
  1743. if (needConversion) {
  1744. bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, type);
  1745. }
  1746. const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
  1747. this._textureHelper.updateTexture(data, gpuTextureWrapper.underlyingResource!, texture.width, texture.height, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0, this._uploadEncoder);
  1748. if (texture.generateMipMaps) {
  1749. this._generateMipmaps(texture);
  1750. }
  1751. }
  1752. texture.isReady = true;
  1753. }
  1754. public updateRawCubeTexture(texture: InternalTexture, bufferView: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level: number = 0): void {
  1755. texture._bufferViewArray = bufferView;
  1756. texture.invertY = invertY;
  1757. texture._compression = compression;
  1758. const gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1759. const needConversion = format === Constants.TEXTUREFORMAT_RGB;
  1760. const data = [];
  1761. for (let i = 0; i < bufferView.length; ++i) {
  1762. let faceData = bufferView[i];
  1763. if (needConversion) {
  1764. faceData = _convertRGBtoRGBATextureData(bufferView[i], texture.width, texture.height, type);
  1765. }
  1766. data.push(new Uint8Array(faceData.buffer, faceData.byteOffset, faceData.byteLength));
  1767. }
  1768. this._textureHelper.updateCubeTextures(data, gpuTextureWrapper.underlyingResource!, texture.width, texture.height, gpuTextureWrapper.format, invertY, false, 0, 0, this._uploadEncoder);
  1769. if (texture.generateMipMaps) {
  1770. this._generateMipmaps(texture);
  1771. }
  1772. texture.isReady = true;
  1773. }
  1774. public updateRawTexture2DArray(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT): void {
  1775. if (dbgShowWarningsNotImplemented) {
  1776. console.warn("updateRawTexture2DArray not implemented yet in WebGPU");
  1777. }
  1778. }
  1779. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, textureType: number = Constants.TEXTURETYPE_UNSIGNED_INT): void {
  1780. if (dbgShowWarningsNotImplemented) {
  1781. console.warn("updateRawTexture2DArray not implemented yet in WebGPU");
  1782. }
  1783. }
  1784. public readPixels(x: number, y: number, width: number, height: number, hasAlpha = true): Promise<ArrayBufferView> {
  1785. return this._textureHelper.readPixels(this._swapChainTexture, x, y, width, height, this._options.swapChainFormat!);
  1786. }
  1787. /** @hidden */
  1788. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1, level = 0, buffer: Nullable<ArrayBufferView> = null): Promise<ArrayBufferView> {
  1789. let gpuTextureWrapper = texture._hardwareTexture as WebGPUHardwareTexture;
  1790. return this._textureHelper.readPixels(gpuTextureWrapper.underlyingResource!, 0, 0, width, height, gpuTextureWrapper.format, faceIndex, level, buffer);
  1791. }
  1792. //------------------------------------------------------------------------------
  1793. // Render Target Textures
  1794. //------------------------------------------------------------------------------
  1795. public createRenderTargetTexture(size: any, options: boolean | RenderTargetCreationOptions): InternalTexture {
  1796. let fullOptions = new RenderTargetCreationOptions();
  1797. if (options !== undefined && typeof options === "object") {
  1798. fullOptions.generateMipMaps = options.generateMipMaps;
  1799. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1800. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  1801. fullOptions.type = options.type === undefined ? Constants.TEXTURETYPE_UNSIGNED_INT : options.type;
  1802. fullOptions.samplingMode = options.samplingMode === undefined ? Constants.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  1803. fullOptions.format = options.format === undefined ? Constants.TEXTUREFORMAT_RGBA : options.format;
  1804. fullOptions.samples = options.samples ?? this._mainPassSampleCount;
  1805. } else {
  1806. fullOptions.generateMipMaps = <boolean>options;
  1807. fullOptions.generateDepthBuffer = true;
  1808. fullOptions.generateStencilBuffer = false;
  1809. fullOptions.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  1810. fullOptions.samplingMode = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1811. fullOptions.format = Constants.TEXTUREFORMAT_RGBA;
  1812. fullOptions.samples = this._mainPassSampleCount;
  1813. }
  1814. const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);
  1815. const width = size.width || size;
  1816. const height = size.height || size;
  1817. const layers = size.layers || 0;
  1818. texture._depthStencilBuffer = {};
  1819. texture._framebuffer = {};
  1820. texture.baseWidth = width;
  1821. texture.baseHeight = height;
  1822. texture.width = width;
  1823. texture.height = height;
  1824. texture.depth = layers;
  1825. texture.isReady = true;
  1826. texture.samples = fullOptions.samples;
  1827. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  1828. texture.samplingMode = fullOptions.samplingMode;
  1829. texture.type = fullOptions.type;
  1830. texture.format = fullOptions.format;
  1831. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  1832. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  1833. this._internalTexturesCache.push(texture);
  1834. if (texture._generateDepthBuffer || texture._generateStencilBuffer) {
  1835. texture._depthStencilTexture = this.createDepthStencilTexture({ width, height, layers }, {
  1836. bilinearFiltering:
  1837. fullOptions.samplingMode === undefined ||
  1838. fullOptions.samplingMode === Constants.TEXTURE_BILINEAR_SAMPLINGMODE || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR ||
  1839. fullOptions.samplingMode === Constants.TEXTURE_TRILINEAR_SAMPLINGMODE || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR ||
  1840. fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST || fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR ||
  1841. fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST,
  1842. comparisonFunction: 0,
  1843. generateStencil: texture._generateStencilBuffer,
  1844. isCube: texture.isCube,
  1845. samples: texture.samples,
  1846. });
  1847. }
  1848. if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) {
  1849. texture.generateMipMaps = true;
  1850. }
  1851. this._createGPUTextureForInternalTexture(texture);
  1852. if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) {
  1853. texture.generateMipMaps = false;
  1854. }
  1855. return texture;
  1856. }
  1857. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  1858. let fullOptions = {
  1859. generateMipMaps: true,
  1860. generateDepthBuffer: true,
  1861. generateStencilBuffer: false,
  1862. type: Constants.TEXTURETYPE_UNSIGNED_INT,
  1863. samplingMode: Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  1864. format: Constants.TEXTUREFORMAT_RGBA,
  1865. samples: this._mainPassSampleCount,
  1866. ...options
  1867. };
  1868. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  1869. const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);
  1870. texture.width = size;
  1871. texture.height = size;
  1872. texture.depth = 0;
  1873. texture.isReady = true;
  1874. texture.isCube = true;
  1875. texture.samples = fullOptions.samples;
  1876. texture.generateMipMaps = fullOptions.generateMipMaps;
  1877. texture.samplingMode = fullOptions.samplingMode;
  1878. texture.type = fullOptions.type;
  1879. texture.format = fullOptions.format;
  1880. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  1881. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  1882. this._internalTexturesCache.push(texture);
  1883. if (texture._generateDepthBuffer || texture._generateStencilBuffer) {
  1884. texture._depthStencilTexture = this.createDepthStencilTexture({ width: texture.width, height: texture.height, layers: texture.depth }, {
  1885. bilinearFiltering:
  1886. fullOptions.samplingMode === undefined ||
  1887. fullOptions.samplingMode === Constants.TEXTURE_BILINEAR_SAMPLINGMODE || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR ||
  1888. fullOptions.samplingMode === Constants.TEXTURE_TRILINEAR_SAMPLINGMODE || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR ||
  1889. fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST || fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR ||
  1890. fullOptions.samplingMode === Constants.TEXTURE_NEAREST_LINEAR || fullOptions.samplingMode === Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST,
  1891. comparisonFunction: 0,
  1892. generateStencil: texture._generateStencilBuffer,
  1893. isCube: texture.isCube,
  1894. samples: texture.samples,
  1895. });
  1896. }
  1897. if (options && options.createMipMaps && !fullOptions.generateMipMaps) {
  1898. texture.generateMipMaps = true;
  1899. }
  1900. this._createGPUTextureForInternalTexture(texture);
  1901. if (options && options.createMipMaps && !fullOptions.generateMipMaps) {
  1902. texture.generateMipMaps = false;
  1903. }
  1904. return texture;
  1905. }
  1906. /** @hidden */
  1907. public _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number, layers?: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number, samples = 1): void {
  1908. const width = (<{ width: number, height: number, layers?: number }>size).width || <number>size;
  1909. const height = (<{ width: number, height: number, layers?: number }>size).height || <number>size;
  1910. const layers = (<{ width: number, height: number, layers?: number }>size).layers || 0;
  1911. internalTexture.baseWidth = width;
  1912. internalTexture.baseHeight = height;
  1913. internalTexture.width = width;
  1914. internalTexture.height = height;
  1915. internalTexture.is2DArray = layers > 0;
  1916. internalTexture.depth = layers;
  1917. internalTexture.isReady = true;
  1918. internalTexture.samples = samples;
  1919. internalTexture.generateMipMaps = false;
  1920. internalTexture._generateDepthBuffer = true;
  1921. internalTexture._generateStencilBuffer = generateStencil;
  1922. internalTexture.samplingMode = bilinearFiltering ? Constants.TEXTURE_BILINEAR_SAMPLINGMODE : Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  1923. internalTexture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  1924. internalTexture._comparisonFunction = comparisonFunction;
  1925. }
  1926. /** @hidden */
  1927. public _createDepthStencilTexture(size: number | { width: number, height: number, layers?: number }, options: DepthTextureCreationOptions): InternalTexture {
  1928. const internalTexture = new InternalTexture(this, InternalTextureSource.Depth);
  1929. const internalOptions = {
  1930. bilinearFiltering: false,
  1931. comparisonFunction: 0,
  1932. generateStencil: false,
  1933. samples: this._mainPassSampleCount,
  1934. ...options
  1935. };
  1936. internalTexture.format = internalOptions.generateStencil ? Constants.TEXTUREFORMAT_DEPTH24_STENCIL8 : Constants.TEXTUREFORMAT_DEPTH32_FLOAT;
  1937. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);
  1938. this._createGPUTextureForInternalTexture(internalTexture);
  1939. return internalTexture;
  1940. }
  1941. /** @hidden */
  1942. public _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions): InternalTexture {
  1943. const internalTexture = new InternalTexture(this, InternalTextureSource.Depth);
  1944. internalTexture.isCube = true;
  1945. const internalOptions = {
  1946. bilinearFiltering: false,
  1947. comparisonFunction: 0,
  1948. generateStencil: false,
  1949. samples: this._mainPassSampleCount,
  1950. ...options
  1951. };
  1952. internalTexture.format = internalOptions.generateStencil ? Constants.TEXTUREFORMAT_DEPTH24_STENCIL8 : Constants.TEXTUREFORMAT_DEPTH32_FLOAT;
  1953. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);
  1954. this._createGPUTextureForInternalTexture(internalTexture);
  1955. return internalTexture;
  1956. }
  1957. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  1958. // samples is used at creation time in WebGPU, you can't change it afterwards
  1959. return samples;
  1960. }
  1961. //------------------------------------------------------------------------------
  1962. // Render Commands
  1963. //------------------------------------------------------------------------------
  1964. /**
  1965. * Begin a new frame
  1966. */
  1967. public beginFrame(): void {
  1968. super.beginFrame();
  1969. }
  1970. /**
  1971. * End the current frame
  1972. */
  1973. public endFrame() {
  1974. this._endMainRenderPass();
  1975. this.flushFramebuffer();
  1976. if (dbgVerboseLogsForFirstFrames) {
  1977. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  1978. console.log("frame #" + (this as any)._count + " - counters - numPipelineDescriptorCreation=", this._counters.numPipelineDescriptorCreation, ", numBindGroupsCreation=", this._counters.numBindGroupsCreation);
  1979. }
  1980. }
  1981. for (let i = 0; i < this._deferredReleaseTextures.length; ++i) {
  1982. const [texture, hardwareTexture, irradianceTexture, depthStencilTexture] = this._deferredReleaseTextures[i];
  1983. hardwareTexture?.release();
  1984. irradianceTexture?.dispose();
  1985. depthStencilTexture?.dispose();
  1986. // TODO WEBGPU remove debug code
  1987. if ((texture as any)._swapped) {
  1988. delete (texture as any)._swapped;
  1989. } else {
  1990. (texture as any)._released = true;
  1991. }
  1992. }
  1993. this._deferredReleaseTextures.length = 0;
  1994. this._bufferManager.destroyDeferredBuffers();
  1995. if (ThinEngine.Features._collectUbosUpdatedInFrame) {
  1996. if (dbgVerboseLogsForFirstFrames) {
  1997. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  1998. const list: Array<string> = [];
  1999. for (const name in UniformBuffer._updatedUbosInFrame) {
  2000. list.push(name + ":" + UniformBuffer._updatedUbosInFrame[name]);
  2001. }
  2002. console.log("frame #" + (this as any)._count + " - updated ubos -", list.join(", "));
  2003. }
  2004. }
  2005. UniformBuffer._updatedUbosInFrame = {};
  2006. }
  2007. this._counters.numPipelineDescriptorCreation = 0;
  2008. this._counters.numBindGroupsCreation = 0;
  2009. super.endFrame();
  2010. if (dbgVerboseLogsForFirstFrames) {
  2011. if ((this as any)._count < dbgVerboseLogsNumFrames) {
  2012. console.log("%c frame #" + (this as any)._count + " - end", "background: #ffff00");
  2013. }
  2014. if ((this as any)._count < dbgVerboseLogsNumFrames) {
  2015. (this as any)._count++;
  2016. if ((this as any)._count !== dbgVerboseLogsNumFrames) {
  2017. console.log("%c frame #" + (this as any)._count + " - begin", "background: #ffff00");
  2018. }
  2019. }
  2020. }
  2021. }
  2022. //------------------------------------------------------------------------------
  2023. // Render Pass
  2024. //------------------------------------------------------------------------------
  2025. private _startRenderTargetRenderPass(internalTexture: InternalTexture, clearColor: Nullable<IColor4Like>, clearDepth: boolean, clearStencil: boolean = false) {
  2026. const gpuTexture = (internalTexture._hardwareTexture as WebGPUHardwareTexture).underlyingResource!;
  2027. const depthStencilTexture = internalTexture._depthStencilTexture;
  2028. const gpuDepthStencilTexture = depthStencilTexture?._hardwareTexture?.underlyingResource as Nullable<GPUTexture>;
  2029. const colorTextureView = gpuTexture.createView(this._currentRenderTargetColorAttachmentViewDescriptor);
  2030. const depthTextureView = gpuDepthStencilTexture?.createView(this._currentRenderTargetDepthAttachmentViewDescriptor);
  2031. this._renderTargetEncoder.pushDebugGroup("start render target rendering");
  2032. const renderPassDescriptor = {
  2033. colorAttachments: [{
  2034. attachment: colorTextureView,
  2035. loadValue: clearColor !== null ? clearColor : WebGPUConstants.LoadOp.Load,
  2036. storeOp: WebGPUConstants.StoreOp.Store
  2037. }],
  2038. depthStencilAttachment: depthStencilTexture && gpuDepthStencilTexture ? {
  2039. attachment: depthTextureView!,
  2040. depthLoadValue: clearDepth && depthStencilTexture._generateDepthBuffer ? this._clearDepthValue : WebGPUConstants.LoadOp.Load,
  2041. depthStoreOp: WebGPUConstants.StoreOp.Store,
  2042. stencilLoadValue: clearStencil && depthStencilTexture._generateStencilBuffer ? this._clearStencilValue : WebGPUConstants.LoadOp.Load,
  2043. stencilStoreOp: WebGPUConstants.StoreOp.Store,
  2044. } : undefined
  2045. };
  2046. const renderPass = this._renderTargetEncoder.beginRenderPass(renderPassDescriptor);
  2047. if (dbgVerboseLogsForFirstFrames) {
  2048. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  2049. console.log("frame #" + (this as any)._count + " - render target begin pass - internalTexture.uniqueId=", internalTexture.uniqueId, renderPassDescriptor);
  2050. }
  2051. }
  2052. this._currentRenderPass = renderPass;
  2053. this._resetCurrentViewport(1);
  2054. }
  2055. private _endRenderTargetRenderPass() {
  2056. if (this._currentRenderPass) {
  2057. this._currentRenderPass.endPass();
  2058. if (dbgVerboseLogsForFirstFrames) {
  2059. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  2060. console.log("frame #" + (this as any)._count + " - render target end pass - internalTexture.uniqueId=", this._currentRenderTarget?.uniqueId);
  2061. }
  2062. }
  2063. this._renderTargetEncoder.popDebugGroup();
  2064. this._resetCurrentViewport(1);
  2065. }
  2066. }
  2067. private _getCurrentRenderPass(): GPURenderPassEncoder {
  2068. if (this._currentRenderTarget && !this._currentRenderPass) {
  2069. this._startRenderTargetRenderPass(this._currentRenderTarget, null, false, false);
  2070. } else if (!this._currentRenderPass) {
  2071. this._startMainRenderPass();
  2072. }
  2073. return this._currentRenderPass!;
  2074. }
  2075. private _startMainRenderPass(): void {
  2076. if (this._mainRenderPass) {
  2077. this._endMainRenderPass();
  2078. }
  2079. this._swapChainTexture = this._swapChain.getCurrentTexture();
  2080. // Resolve in case of MSAA
  2081. if (this._options.antialiasing) {
  2082. this._mainColorAttachments[0].resolveTarget = this._swapChainTexture.createView();
  2083. }
  2084. else {
  2085. this._mainColorAttachments[0].attachment = this._swapChainTexture.createView();
  2086. }
  2087. if (dbgVerboseLogsForFirstFrames) {
  2088. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  2089. console.log("frame #" + (this as any)._count + " - main begin pass - texture width=" + (this._mainTextureExtends as any).width, " height=" + (this._mainTextureExtends as any).height, this._mainColorAttachments, this._mainDepthAttachment);
  2090. }
  2091. }
  2092. this._renderEncoder.pushDebugGroup("start main rendering");
  2093. this._currentRenderPass = this._renderEncoder.beginRenderPass({
  2094. colorAttachments: this._mainColorAttachments,
  2095. depthStencilAttachment: this._mainDepthAttachment
  2096. });
  2097. this._mainRenderPass = this._currentRenderPass;
  2098. this._resetCurrentViewport(0);
  2099. }
  2100. private _endMainRenderPass(): void {
  2101. if (this._mainRenderPass !== null) {
  2102. this._mainRenderPass.endPass();
  2103. if (dbgVerboseLogsForFirstFrames) {
  2104. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  2105. console.log("frame #" + (this as any)._count + " - main end pass");
  2106. }
  2107. }
  2108. this._renderEncoder.popDebugGroup();
  2109. this._resetCurrentViewport(0);
  2110. if (this._mainRenderPass === this._currentRenderPass) {
  2111. this._currentRenderPass = null;
  2112. }
  2113. this._mainRenderPass = null;
  2114. }
  2115. }
  2116. public bindFramebuffer(texture: InternalTexture, faceIndex: number = 0, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, lodLevel = 0, layer = 0): void {
  2117. const hardwareTexture = texture._hardwareTexture as Nullable<WebGPUHardwareTexture>;
  2118. const gpuTexture = hardwareTexture?.underlyingResource as Nullable<GPUTexture>;
  2119. if (!hardwareTexture || !gpuTexture) {
  2120. if (dbgSanityChecks) {
  2121. console.error("bindFramebuffer: Trying to bind a texture that does not have a hardware texture or that has a webgpu texture empty!", texture, hardwareTexture, gpuTexture);
  2122. }
  2123. return;
  2124. }
  2125. if (this._currentRenderTarget) {
  2126. this.unBindFramebuffer(this._currentRenderTarget);
  2127. }
  2128. this._currentRenderTarget = texture;
  2129. this._setDepthTextureFormat(this._currentRenderTarget._depthStencilTexture ? this._getWebGPUTextureFormat(-1, this._currentRenderTarget._depthStencilTexture.format) : undefined);
  2130. this._setColorFormat(this._getWebGPUTextureFormat(this._currentRenderTarget.type, this._currentRenderTarget.format));
  2131. // TODO WEBGPU handle array layer
  2132. this._currentRenderTargetColorAttachmentViewDescriptor = {
  2133. format: this._colorFormat,
  2134. dimension: WebGPUConstants.TextureViewDimension.E2d,
  2135. mipLevelCount: 1,
  2136. baseArrayLayer: faceIndex,
  2137. baseMipLevel: lodLevel,
  2138. arrayLayerCount: 1,
  2139. aspect: WebGPUConstants.TextureAspect.All
  2140. };
  2141. this._currentRenderTargetDepthAttachmentViewDescriptor = {
  2142. format: this._depthTextureFormat,
  2143. dimension: WebGPUConstants.TextureViewDimension.E2d,
  2144. mipLevelCount: 1,
  2145. baseArrayLayer: 0,
  2146. baseMipLevel: 0,
  2147. arrayLayerCount: 1,
  2148. aspect: WebGPUConstants.TextureAspect.All
  2149. };
  2150. if (dbgVerboseLogsForFirstFrames) {
  2151. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  2152. console.log("frame #" + (this as any)._count + " - bindFramebuffer called - face=", faceIndex, "lodLevel=", lodLevel, this._currentRenderTargetColorAttachmentViewDescriptor, this._currentRenderTargetDepthAttachmentViewDescriptor);
  2153. }
  2154. }
  2155. this._currentRenderPass = null; // lazy creation of the render pass, hoping the render pass will be created by a call to clear()...
  2156. if (this._cachedViewport && !forceFullscreenViewport) {
  2157. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  2158. } else {
  2159. if (!requiredWidth) {
  2160. requiredWidth = texture.width;
  2161. if (lodLevel) {
  2162. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  2163. }
  2164. }
  2165. if (!requiredHeight) {
  2166. requiredHeight = texture.height;
  2167. if (lodLevel) {
  2168. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  2169. }
  2170. }
  2171. this._viewport(0, 0, requiredWidth, requiredHeight);
  2172. }
  2173. this.wipeCaches();
  2174. }
  2175. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  2176. // TODO WEBGPU remove the assert debugging code
  2177. assert(this._currentRenderTarget === null || (this._currentRenderTarget !== null && texture === this._currentRenderTarget), "unBindFramebuffer - the texture we wan't to unbind is not the same than the currentRenderTarget! texture=" + texture + ", this._currentRenderTarget=" + this._currentRenderTarget);
  2178. if (this._currentRenderPass && this._currentRenderPass !== this._mainRenderPass) {
  2179. this._endRenderTargetRenderPass();
  2180. }
  2181. this._currentRenderTarget = null;
  2182. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2183. this._generateMipmaps(texture);
  2184. }
  2185. if (onBeforeUnbind) {
  2186. onBeforeUnbind();
  2187. }
  2188. this._currentRenderPass = this._mainRenderPass;
  2189. this._setDepthTextureFormat(this._getMainDepthTextureFormat());
  2190. this._setColorFormat(this._options.swapChainFormat!);
  2191. }
  2192. public flushFramebuffer(): void {
  2193. this._commandBuffers[0] = this._uploadEncoder.finish();
  2194. this._commandBuffers[1] = this._renderTargetEncoder.finish();
  2195. this._commandBuffers[2] = this._renderEncoder.finish();
  2196. this._device.defaultQueue.submit(this._commandBuffers);
  2197. this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
  2198. this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
  2199. this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor);
  2200. }
  2201. public restoreDefaultFramebuffer(): void {
  2202. if (this._currentRenderTarget) {
  2203. this.unBindFramebuffer(this._currentRenderTarget);
  2204. } else {
  2205. this._currentRenderPass = this._mainRenderPass;
  2206. this._setDepthTextureFormat(this._getMainDepthTextureFormat());
  2207. this._setColorFormat(this._options.swapChainFormat!);
  2208. }
  2209. if (this._currentRenderPass) {
  2210. if (this._cachedViewport) {
  2211. this.setViewport(this._cachedViewport);
  2212. }
  2213. }
  2214. this.wipeCaches();
  2215. }
  2216. /** @hidden */
  2217. public _releaseFramebufferObjects(texture: InternalTexture): void {
  2218. }
  2219. //------------------------------------------------------------------------------
  2220. // Render
  2221. //------------------------------------------------------------------------------
  2222. public setZOffset(value: number): void {
  2223. if (value !== this._depthCullingState.zOffset) {
  2224. this._depthCullingState.zOffset = value;
  2225. }
  2226. }
  2227. private _setColorFormat(format: GPUTextureFormat): void {
  2228. if (this._colorFormat === format) {
  2229. return;
  2230. }
  2231. this._colorFormat = format;
  2232. }
  2233. private _setDepthTextureFormat(format: GPUTextureFormat | undefined): void {
  2234. if (this._depthTextureFormat === format) {
  2235. return;
  2236. }
  2237. this._depthTextureFormat = format;
  2238. }
  2239. public setDepthBuffer(enable: boolean): void {
  2240. if (this._depthCullingState.depthTest !== enable) {
  2241. this._depthCullingState.depthTest = enable;
  2242. }
  2243. }
  2244. public setDepthWrite(enable: boolean): void {
  2245. if (this._depthCullingState.depthMask !== enable) {
  2246. this._depthCullingState.depthMask = enable;
  2247. }
  2248. }
  2249. public setStencilBuffer(enable: boolean): void {
  2250. if (this._stencilState.stencilTest !== enable) {
  2251. this._stencilState.stencilTest = enable;
  2252. }
  2253. }
  2254. public setStencilMask(mask: number): void {
  2255. if (this._stencilState.stencilMask !== mask) {
  2256. this._stencilState.stencilMask = mask;
  2257. }
  2258. }
  2259. public setStencilFunction(stencilFunc: number) {
  2260. if (this._stencilState.stencilFunc !== stencilFunc) {
  2261. this._stencilState.stencilFunc = stencilFunc;
  2262. }
  2263. }
  2264. public setStencilFunctionReference(reference: number) {
  2265. if (this._stencilState.stencilFuncRef !== reference) {
  2266. this._stencilState.stencilFuncRef = reference;
  2267. }
  2268. }
  2269. public setStencilFunctionMask(mask: number) {
  2270. if (this._stencilState.stencilFuncMask !== mask) {
  2271. this._stencilState.stencilFuncMask = mask;
  2272. }
  2273. }
  2274. public setStencilOperationFail(operation: number): void {
  2275. if (this._stencilState.stencilOpStencilFail !== operation) {
  2276. this._stencilState.stencilOpStencilFail = operation;
  2277. }
  2278. }
  2279. public setStencilOperationDepthFail(operation: number): void {
  2280. if (this._stencilState.stencilOpDepthFail !== operation) {
  2281. this._stencilState.stencilOpDepthFail = operation;
  2282. }
  2283. }
  2284. public setStencilOperationPass(operation: number): void {
  2285. if (this._stencilState.stencilOpStencilDepthPass !== operation) {
  2286. this._stencilState.stencilOpStencilDepthPass = operation;
  2287. }
  2288. }
  2289. public setDitheringState(value: boolean): void {
  2290. // Does not exist in WebGPU
  2291. }
  2292. public setRasterizerState(value: boolean): void {
  2293. // Does not exist in WebGPU
  2294. }
  2295. public setDepthFunction(depthFunc: number) {
  2296. if (this._depthCullingState.depthFunc !== depthFunc) {
  2297. this._depthCullingState.depthFunc = depthFunc;
  2298. }
  2299. }
  2300. public setDepthFunctionToGreater(): void {
  2301. if (this._depthCullingState.depthFunc !== Constants.GREATER) {
  2302. this._depthCullingState.depthFunc = Constants.GREATER;
  2303. }
  2304. }
  2305. public setDepthFunctionToGreaterOrEqual(): void {
  2306. if (this._depthCullingState.depthFunc !== Constants.GEQUAL) {
  2307. this._depthCullingState.depthFunc = Constants.GEQUAL;
  2308. }
  2309. }
  2310. public setDepthFunctionToLess(): void {
  2311. if (this._depthCullingState.depthFunc !== Constants.LESS) {
  2312. this._depthCullingState.depthFunc = Constants.LESS;
  2313. }
  2314. }
  2315. public setDepthFunctionToLessOrEqual(): void {
  2316. if (this._depthCullingState.depthFunc !== Constants.LEQUAL) {
  2317. this._depthCullingState.depthFunc = Constants.LEQUAL;
  2318. }
  2319. }
  2320. private _indexFormatInRenderPass(topology: GPUPrimitiveTopology): boolean {
  2321. return topology === WebGPUConstants.PrimitiveTopology.PointList ||
  2322. topology === WebGPUConstants.PrimitiveTopology.LineList ||
  2323. topology === WebGPUConstants.PrimitiveTopology.TriangleList;
  2324. }
  2325. private _getTopology(fillMode: number): GPUPrimitiveTopology {
  2326. switch (fillMode) {
  2327. // Triangle views
  2328. case Constants.MATERIAL_TriangleFillMode:
  2329. return WebGPUConstants.PrimitiveTopology.TriangleList;
  2330. case Constants.MATERIAL_PointFillMode:
  2331. return WebGPUConstants.PrimitiveTopology.PointList;
  2332. case Constants.MATERIAL_WireFrameFillMode:
  2333. return WebGPUConstants.PrimitiveTopology.LineList;
  2334. // Draw modes
  2335. case Constants.MATERIAL_PointListDrawMode:
  2336. return WebGPUConstants.PrimitiveTopology.PointList;
  2337. case Constants.MATERIAL_LineListDrawMode:
  2338. return WebGPUConstants.PrimitiveTopology.LineList;
  2339. case Constants.MATERIAL_LineLoopDrawMode:
  2340. // return this._gl.LINE_LOOP;
  2341. // TODO WEBGPU. Line Loop Mode Fallback at buffer load time.
  2342. throw "LineLoop is an unsupported fillmode in WebGPU";
  2343. case Constants.MATERIAL_LineStripDrawMode:
  2344. return WebGPUConstants.PrimitiveTopology.LineStrip;
  2345. case Constants.MATERIAL_TriangleStripDrawMode:
  2346. return WebGPUConstants.PrimitiveTopology.TriangleStrip;
  2347. case Constants.MATERIAL_TriangleFanDrawMode:
  2348. // return this._gl.TRIANGLE_FAN;
  2349. // TODO WEBGPU. Triangle Fan Mode Fallback at buffer load time.
  2350. throw "TriangleFan is an unsupported fillmode in WebGPU";
  2351. default:
  2352. return WebGPUConstants.PrimitiveTopology.TriangleList;
  2353. }
  2354. }
  2355. private _getCompareFunction(compareFunction: Nullable<number>): GPUCompareFunction {
  2356. switch (compareFunction) {
  2357. case Constants.ALWAYS:
  2358. return WebGPUConstants.CompareFunction.Always;
  2359. case Constants.EQUAL:
  2360. return WebGPUConstants.CompareFunction.Equal;
  2361. case Constants.GREATER:
  2362. return WebGPUConstants.CompareFunction.Greater;
  2363. case Constants.GEQUAL:
  2364. return WebGPUConstants.CompareFunction.GreaterEqual;
  2365. case Constants.LESS:
  2366. return WebGPUConstants.CompareFunction.Less;
  2367. case Constants.LEQUAL:
  2368. return WebGPUConstants.CompareFunction.LessEqual;
  2369. case Constants.NEVER:
  2370. return WebGPUConstants.CompareFunction.Never;
  2371. case Constants.NOTEQUAL:
  2372. return WebGPUConstants.CompareFunction.NotEqual;
  2373. default:
  2374. return WebGPUConstants.CompareFunction.Less;
  2375. }
  2376. }
  2377. private _getOpFunction(operation: Nullable<number>, defaultOp: GPUStencilOperation): GPUStencilOperation {
  2378. switch (operation) {
  2379. case Constants.KEEP:
  2380. return WebGPUConstants.StencilOperation.Keep;
  2381. case Constants.ZERO:
  2382. return WebGPUConstants.StencilOperation.Zero;
  2383. case Constants.REPLACE:
  2384. return WebGPUConstants.StencilOperation.Replace;
  2385. case Constants.INVERT:
  2386. return WebGPUConstants.StencilOperation.Invert;
  2387. case Constants.INCR:
  2388. return WebGPUConstants.StencilOperation.IncrementClamp;
  2389. case Constants.DECR:
  2390. return WebGPUConstants.StencilOperation.DecrementClamp;
  2391. case Constants.INCR_WRAP:
  2392. return WebGPUConstants.StencilOperation.IncrementWrap;
  2393. case Constants.DECR_WRAP:
  2394. return WebGPUConstants.StencilOperation.DecrementWrap;
  2395. default:
  2396. return defaultOp;
  2397. }
  2398. }
  2399. private _getDepthStencilStateDescriptor(): GPUDepthStencilStateDescriptor | undefined {
  2400. if (this._depthTextureFormat === undefined) {
  2401. return undefined;
  2402. }
  2403. const stencilFrontBack: GPUStencilStateFaceDescriptor = {
  2404. compare: this._getCompareFunction(this._stencilState.stencilFunc),
  2405. depthFailOp: this._getOpFunction(this._stencilState.stencilOpDepthFail, WebGPUConstants.StencilOperation.Keep),
  2406. failOp: this._getOpFunction(this._stencilState.stencilOpStencilFail, WebGPUConstants.StencilOperation.Keep),
  2407. passOp: this._getOpFunction(this._stencilState.stencilOpStencilDepthPass, WebGPUConstants.StencilOperation.Replace)
  2408. };
  2409. return {
  2410. depthWriteEnabled: this.getDepthWrite(),
  2411. depthCompare: this.getDepthBuffer() ? this._getCompareFunction(this.getDepthFunction()) : WebGPUConstants.CompareFunction.Always,
  2412. format: this._depthTextureFormat,
  2413. stencilFront: stencilFrontBack,
  2414. stencilBack: stencilFrontBack,
  2415. stencilReadMask: this._stencilState.stencilFuncMask,
  2416. stencilWriteMask: this._stencilState.stencilMask,
  2417. };
  2418. }
  2419. /**
  2420. * Set various states to the webGL context
  2421. * @param culling defines backface culling state
  2422. * @param zOffset defines the value to apply to zOffset (0 by default)
  2423. * @param force defines if states must be applied even if cache is up to date
  2424. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  2425. */
  2426. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  2427. // Culling
  2428. if (this._depthCullingState.cull !== culling || force) {
  2429. this._depthCullingState.cull = culling;
  2430. }
  2431. // Cull face
  2432. // var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  2433. var cullFace = this.cullBackFaces ? 1 : 2;
  2434. if (this._depthCullingState.cullFace !== cullFace || force) {
  2435. this._depthCullingState.cullFace = cullFace;
  2436. }
  2437. // Z offset
  2438. this.setZOffset(zOffset);
  2439. // Front face
  2440. // var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  2441. var frontFace = reverseSide ? 1 : 2;
  2442. if (this._depthCullingState.frontFace !== frontFace || force) {
  2443. this._depthCullingState.frontFace = frontFace;
  2444. }
  2445. }
  2446. private _getFrontFace(): GPUFrontFace {
  2447. switch (this._depthCullingState.frontFace) {
  2448. case 1:
  2449. return WebGPUConstants.FrontFace.CCW;
  2450. default:
  2451. return WebGPUConstants.FrontFace.CW;
  2452. }
  2453. }
  2454. private _getCullMode(): GPUCullMode {
  2455. if (this._depthCullingState.cull === false) {
  2456. return WebGPUConstants.CullMode.None;
  2457. }
  2458. if (this._depthCullingState.cullFace === 2) {
  2459. return WebGPUConstants.CullMode.Front;
  2460. }
  2461. else {
  2462. return WebGPUConstants.CullMode.Back;
  2463. }
  2464. }
  2465. private _getRasterizationStateDescriptor(): GPURasterizationStateDescriptor {
  2466. return {
  2467. frontFace: this._getFrontFace(),
  2468. cullMode: this._getCullMode(),
  2469. depthBias: 0,
  2470. depthBiasClamp: 0,
  2471. depthBiasSlopeScale: this._depthCullingState.zOffset,
  2472. };
  2473. }
  2474. private _getWriteMask(): number {
  2475. if (this.__colorWrite) {
  2476. return WebGPUConstants.ColorWrite.All;
  2477. }
  2478. return 0;
  2479. }
  2480. /**
  2481. * Sets the current alpha mode
  2482. * @param mode defines the mode to use (one of the Engine.ALPHA_XXX)
  2483. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  2484. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  2485. */
  2486. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  2487. if (this._alphaMode === mode) {
  2488. return;
  2489. }
  2490. switch (mode) {
  2491. case Engine.ALPHA_DISABLE:
  2492. this._alphaState.alphaBlend = false;
  2493. break;
  2494. case Engine.ALPHA_PREMULTIPLIED:
  2495. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2496. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 1);
  2497. this._alphaState.alphaBlend = true;
  2498. break;
  2499. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  2500. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2501. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 0x0303);
  2502. this._alphaState.alphaBlend = true;
  2503. break;
  2504. case Engine.ALPHA_COMBINE:
  2505. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2506. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0303, 1, 1);
  2507. this._alphaState.alphaBlend = true;
  2508. break;
  2509. case Engine.ALPHA_ONEONE:
  2510. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2511. this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1);
  2512. this._alphaState.alphaBlend = true;
  2513. break;
  2514. case Engine.ALPHA_ADD:
  2515. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2516. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 1, 0, 1);
  2517. this._alphaState.alphaBlend = true;
  2518. break;
  2519. case Engine.ALPHA_SUBTRACT:
  2520. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2521. this._alphaState.setAlphaBlendFunctionParameters(0, 0x0301, 1, 1);
  2522. this._alphaState.alphaBlend = true;
  2523. break;
  2524. case Engine.ALPHA_MULTIPLY:
  2525. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  2526. this._alphaState.setAlphaBlendFunctionParameters(0x0306, 0, 1, 1);
  2527. this._alphaState.alphaBlend = true;
  2528. break;
  2529. case Engine.ALPHA_MAXIMIZED:
  2530. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2531. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0301, 1, 1);
  2532. this._alphaState.alphaBlend = true;
  2533. break;
  2534. case Engine.ALPHA_INTERPOLATE:
  2535. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  2536. this._alphaState.setAlphaBlendFunctionParameters(0x8001, 0x8002, 0x8003, 0x8004);
  2537. this._alphaState.alphaBlend = true;
  2538. break;
  2539. case Engine.ALPHA_SCREENMODE:
  2540. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2541. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0301, 1, 0x0303);
  2542. this._alphaState.alphaBlend = true;
  2543. break;
  2544. }
  2545. if (!noDepthWriteChange) {
  2546. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  2547. }
  2548. this._alphaMode = mode;
  2549. }
  2550. private _getAphaBlendOperation(operation: Nullable<number>): GPUBlendOperation {
  2551. switch (operation) {
  2552. case 0x8006:
  2553. return WebGPUConstants.BlendOperation.Add;
  2554. case 0x800A:
  2555. return WebGPUConstants.BlendOperation.Subtract;
  2556. case 0x800B:
  2557. return WebGPUConstants.BlendOperation.ReverseSubtract;
  2558. default:
  2559. return WebGPUConstants.BlendOperation.Add;
  2560. }
  2561. }
  2562. private _getAphaBlendFactor(factor: Nullable<number>): GPUBlendFactor {
  2563. switch (factor) {
  2564. case 0:
  2565. return WebGPUConstants.BlendFactor.Zero;
  2566. case 1:
  2567. return WebGPUConstants.BlendFactor.One;
  2568. case 0x0300:
  2569. return WebGPUConstants.BlendFactor.SrcColor;
  2570. case 0x0301:
  2571. return WebGPUConstants.BlendFactor.OneMinusSrcColor;
  2572. case 0x0302:
  2573. return WebGPUConstants.BlendFactor.SrcAlpha;
  2574. case 0x0303:
  2575. return WebGPUConstants.BlendFactor.OneMinusSrcAlpha;
  2576. case 0x0304:
  2577. return WebGPUConstants.BlendFactor.DstAlpha;
  2578. case 0x0305:
  2579. return WebGPUConstants.BlendFactor.OneMinusDstAlpha;
  2580. case 0x0306:
  2581. return WebGPUConstants.BlendFactor.DstColor;
  2582. case 0x0307:
  2583. return WebGPUConstants.BlendFactor.OneMinusDstColor;
  2584. case 0x0308:
  2585. return WebGPUConstants.BlendFactor.SrcAlphaSaturated;
  2586. case 0x8001:
  2587. return WebGPUConstants.BlendFactor.BlendColor;
  2588. case 0x8002:
  2589. return WebGPUConstants.BlendFactor.OneMinusBlendColor;
  2590. case 0x8003:
  2591. return WebGPUConstants.BlendFactor.BlendColor;
  2592. case 0x8004:
  2593. return WebGPUConstants.BlendFactor.OneMinusBlendColor;
  2594. default:
  2595. return WebGPUConstants.BlendFactor.One;
  2596. }
  2597. }
  2598. private _getAphaBlendState(): GPUBlendDescriptor {
  2599. if (!this._alphaState.alphaBlend) {
  2600. return { };
  2601. }
  2602. return {
  2603. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[2]),
  2604. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[3]),
  2605. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[1]),
  2606. };
  2607. }
  2608. private _getColorBlendState(): GPUBlendDescriptor {
  2609. if (!this._alphaState.alphaBlend) {
  2610. return { };
  2611. }
  2612. return {
  2613. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[0]),
  2614. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[1]),
  2615. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[0]),
  2616. };
  2617. }
  2618. private _getColorStateDescriptors(): GPUColorStateDescriptor[] {
  2619. return [{
  2620. format: this._colorFormat,
  2621. alphaBlend: this._getAphaBlendState(),
  2622. colorBlend: this._getColorBlendState(),
  2623. writeMask: this._getWriteMask(),
  2624. }];
  2625. }
  2626. private _getStages(): IWebGPURenderPipelineStageDescriptor {
  2627. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  2628. return webgpuPipelineContext.stages!;
  2629. }
  2630. private _getVertexInputDescriptorFormat(vertexBuffer: VertexBuffer): GPUVertexFormat {
  2631. const kind = vertexBuffer.getKind();
  2632. const type = vertexBuffer.type;
  2633. const normalized = vertexBuffer.normalized;
  2634. const size = vertexBuffer.getSize();
  2635. switch (type) {
  2636. case VertexBuffer.BYTE:
  2637. switch (size) {
  2638. case 2:
  2639. return normalized ? WebGPUConstants.VertexFormat.Char2Norm : WebGPUConstants.VertexFormat.Char2;
  2640. case 4:
  2641. return normalized ? WebGPUConstants.VertexFormat.Char4Norm : WebGPUConstants.VertexFormat.Char4;
  2642. }
  2643. case VertexBuffer.UNSIGNED_BYTE:
  2644. switch (size) {
  2645. case 2:
  2646. return normalized ? WebGPUConstants.VertexFormat.Uchar2Norm : WebGPUConstants.VertexFormat.Uchar2;
  2647. case 4:
  2648. return normalized ? WebGPUConstants.VertexFormat.Uchar4Norm : WebGPUConstants.VertexFormat.Uchar4;
  2649. }
  2650. case VertexBuffer.SHORT:
  2651. switch (size) {
  2652. case 2:
  2653. return normalized ? WebGPUConstants.VertexFormat.Short2Norm : WebGPUConstants.VertexFormat.Short2;
  2654. case 4:
  2655. return normalized ? WebGPUConstants.VertexFormat.Short4Norm : WebGPUConstants.VertexFormat.Short4;
  2656. }
  2657. case VertexBuffer.UNSIGNED_SHORT:
  2658. switch (size) {
  2659. case 2:
  2660. return normalized ? WebGPUConstants.VertexFormat.Ushort2Norm : WebGPUConstants.VertexFormat.Ushort2;
  2661. case 4:
  2662. return normalized ? WebGPUConstants.VertexFormat.Ushort4Norm : WebGPUConstants.VertexFormat.Ushort4;
  2663. }
  2664. case VertexBuffer.INT:
  2665. switch (size) {
  2666. case 1:
  2667. return WebGPUConstants.VertexFormat.Int;
  2668. case 2:
  2669. return WebGPUConstants.VertexFormat.Int2;
  2670. case 3:
  2671. return WebGPUConstants.VertexFormat.Int3;
  2672. case 4:
  2673. return WebGPUConstants.VertexFormat.Int4;
  2674. }
  2675. case VertexBuffer.UNSIGNED_INT:
  2676. switch (size) {
  2677. case 1:
  2678. return WebGPUConstants.VertexFormat.Uint;
  2679. case 2:
  2680. return WebGPUConstants.VertexFormat.Uint2;
  2681. case 3:
  2682. return WebGPUConstants.VertexFormat.Uint3;
  2683. case 4:
  2684. return WebGPUConstants.VertexFormat.Uint4;
  2685. }
  2686. case VertexBuffer.FLOAT:
  2687. switch (size) {
  2688. case 1:
  2689. return WebGPUConstants.VertexFormat.Float;
  2690. case 2:
  2691. return WebGPUConstants.VertexFormat.Float2;
  2692. case 3:
  2693. return WebGPUConstants.VertexFormat.Float3;
  2694. case 4:
  2695. return WebGPUConstants.VertexFormat.Float4;
  2696. }
  2697. }
  2698. throw new Error("Invalid Format '" + kind + "'");
  2699. }
  2700. private _getVertexInputDescriptor(topology: GPUPrimitiveTopology): GPUVertexStateDescriptor {
  2701. const descriptors: GPUVertexBufferLayoutDescriptor[] = [];
  2702. const effect = this._currentEffect!;
  2703. const attributes = effect.getAttributesNames();
  2704. for (var index = 0; index < attributes.length; index++) {
  2705. const location = effect.getAttributeLocation(index);
  2706. if (location >= 0) {
  2707. const vertexBuffer = this._currentVertexBuffers![attributes[index]];
  2708. if (!vertexBuffer) {
  2709. continue;
  2710. }
  2711. const positionAttributeDescriptor: GPUVertexAttributeDescriptor = {
  2712. shaderLocation: location,
  2713. offset: 0, // not available in WebGL
  2714. format: this._getVertexInputDescriptorFormat(vertexBuffer),
  2715. };
  2716. // TODO WEBGPU. Factorize the one with the same underlying buffer.
  2717. const vertexBufferDescriptor: GPUVertexBufferLayoutDescriptor = {
  2718. arrayStride: vertexBuffer.byteStride,
  2719. stepMode: vertexBuffer.getIsInstanced() ? WebGPUConstants.InputStepMode.Instance : WebGPUConstants.InputStepMode.Vertex,
  2720. attributes: [positionAttributeDescriptor]
  2721. };
  2722. descriptors.push(vertexBufferDescriptor);
  2723. }
  2724. }
  2725. if (!this._currentIndexBuffer) {
  2726. return {
  2727. indexFormat: !this._indexFormatInRenderPass(topology) ? WebGPUConstants.IndexFormat.Uint32 : undefined,
  2728. vertexBuffers: descriptors
  2729. };
  2730. }
  2731. const inputStateDescriptor: GPUVertexStateDescriptor = {
  2732. vertexBuffers: descriptors
  2733. };
  2734. if (!this._indexFormatInRenderPass(topology)) {
  2735. inputStateDescriptor.indexFormat = this._currentIndexBuffer!.is32Bits ? WebGPUConstants.IndexFormat.Uint32 : WebGPUConstants.IndexFormat.Uint16;
  2736. }
  2737. return inputStateDescriptor;
  2738. }
  2739. private _getPipelineLayout(): GPUPipelineLayout {
  2740. const bindGroupLayouts: GPUBindGroupLayout[] = [];
  2741. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  2742. for (let i = 0; i < webgpuPipelineContext.orderedUBOsAndSamplers.length; i++) {
  2743. const setDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i];
  2744. if (setDefinition === undefined) {
  2745. const entries: GPUBindGroupLayoutEntry[] = [];
  2746. const uniformsBindGroupLayout = this._device.createBindGroupLayout({
  2747. entries,
  2748. });
  2749. bindGroupLayouts[i] = uniformsBindGroupLayout;
  2750. continue;
  2751. }
  2752. const entries: GPUBindGroupLayoutEntry[] = [];
  2753. for (let j = 0; j < setDefinition.length; j++) {
  2754. const bindingDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i][j];
  2755. if (bindingDefinition === undefined) {
  2756. continue;
  2757. }
  2758. // TODO WEBGPU. Optimize shared samplers visibility for vertex/framgent.
  2759. if (bindingDefinition.isSampler) {
  2760. entries.push({
  2761. binding: j,
  2762. visibility: WebGPUConstants.ShaderStage.Vertex | WebGPUConstants.ShaderStage.Fragment,
  2763. type: WebGPUConstants.BindingType.SampledTexture,
  2764. viewDimension: bindingDefinition.textureDimension,
  2765. // TODO WEBGPU. Handle texture component type properly.
  2766. // textureComponentType?: GPUTextureComponentType,
  2767. // multisampled?: boolean;
  2768. // hasDynamicOffset?: boolean;
  2769. // storageTextureFormat?: GPUTextureFormat;
  2770. // minBufferBindingSize?: number;
  2771. }, {
  2772. // TODO WEBGPU. No Magic + 1 (coming from current 1 texture 1 sampler startegy).
  2773. binding: j + 1,
  2774. visibility: WebGPUConstants.ShaderStage.Vertex | WebGPUConstants.ShaderStage.Fragment,
  2775. type: bindingDefinition.isComparisonSampler ? WebGPUConstants.BindingType.ComparisonSampler : WebGPUConstants.BindingType.Sampler
  2776. });
  2777. }
  2778. else {
  2779. entries.push({
  2780. binding: j,
  2781. visibility: WebGPUConstants.ShaderStage.Vertex | WebGPUConstants.ShaderStage.Fragment,
  2782. type: WebGPUConstants.BindingType.UniformBuffer,
  2783. });
  2784. }
  2785. }
  2786. if (entries.length > 0) {
  2787. const uniformsBindGroupLayout = this._device.createBindGroupLayout({
  2788. entries,
  2789. });
  2790. bindGroupLayouts[i] = uniformsBindGroupLayout;
  2791. }
  2792. }
  2793. webgpuPipelineContext.bindGroupLayouts = bindGroupLayouts;
  2794. return this._device.createPipelineLayout({ bindGroupLayouts });
  2795. }
  2796. private _getRenderPipeline(topology: GPUPrimitiveTopology): GPURenderPipeline {
  2797. // This is wrong to cache this way but workarounds the need of cache in the simple demo context.
  2798. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  2799. /*if (webgpuPipelineContext.renderPipeline) {
  2800. return webgpuPipelineContext.renderPipeline;
  2801. }*/
  2802. this._counters.numPipelineDescriptorCreation++;
  2803. // Unsupported at the moment but needs to be extracted from the MSAA param.
  2804. const rasterizationStateDescriptor = this._getRasterizationStateDescriptor();
  2805. const depthStateDescriptor = this._getDepthStencilStateDescriptor();
  2806. const colorStateDescriptors = this._getColorStateDescriptors();
  2807. const stages = this._getStages();
  2808. const inputStateDescriptor = this._getVertexInputDescriptor(topology);
  2809. const pipelineLayout = this._getPipelineLayout();
  2810. webgpuPipelineContext.renderPipeline = this._device.createRenderPipeline({
  2811. sampleCount: this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount,
  2812. primitiveTopology: topology,
  2813. rasterizationState: rasterizationStateDescriptor,
  2814. depthStencilState: depthStateDescriptor,
  2815. colorStates: colorStateDescriptors,
  2816. ...stages,
  2817. vertexState: inputStateDescriptor,
  2818. layout: pipelineLayout,
  2819. });
  2820. return webgpuPipelineContext.renderPipeline;
  2821. }
  2822. private _getVertexInputsToRender(): IWebGPUPipelineContextVertexInputsCache {
  2823. const effect = this._currentEffect!;
  2824. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  2825. let vertexInputs = webgpuPipelineContext.vertexInputs;
  2826. /*!!if (vertexInputs) {
  2827. return vertexInputs;
  2828. }*/
  2829. vertexInputs = {
  2830. indexBuffer: null,
  2831. indexOffset: 0,
  2832. vertexStartSlot: 0,
  2833. vertexBuffers: [],
  2834. vertexOffsets: [],
  2835. };
  2836. webgpuPipelineContext.vertexInputs = vertexInputs;
  2837. if (this._currentIndexBuffer) {
  2838. // TODO WEBGPU. Check if cache would be worth it.
  2839. vertexInputs.indexBuffer = this._currentIndexBuffer.underlyingResource;
  2840. vertexInputs.indexOffset = 0;
  2841. }
  2842. else {
  2843. vertexInputs.indexBuffer = null;
  2844. }
  2845. const attributes = effect.getAttributesNames();
  2846. for (var index = 0; index < attributes.length; index++) {
  2847. const order = effect.getAttributeLocation(index);
  2848. if (order >= 0) {
  2849. const vertexBuffer = this._currentVertexBuffers![attributes[index]];
  2850. if (!vertexBuffer) {
  2851. continue;
  2852. }
  2853. var buffer = vertexBuffer.getBuffer();
  2854. if (buffer) {
  2855. vertexInputs.vertexBuffers.push(buffer.underlyingResource);
  2856. vertexInputs.vertexOffsets.push(vertexBuffer.byteOffset);
  2857. }
  2858. }
  2859. }
  2860. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  2861. return vertexInputs;
  2862. }
  2863. private _getBindGroupsToRender(): GPUBindGroup[] {
  2864. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  2865. let bindGroups = webgpuPipelineContext.bindGroups;
  2866. /*if (bindGroups) {
  2867. if (webgpuPipelineContext.uniformBuffer) {
  2868. webgpuPipelineContext.uniformBuffer.update();
  2869. }
  2870. return bindGroups;
  2871. }*/
  2872. this._counters.numBindGroupsCreation++;
  2873. if (webgpuPipelineContext.uniformBuffer) {
  2874. this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer()!, 0, "LeftOver");
  2875. webgpuPipelineContext.uniformBuffer.update();
  2876. }
  2877. bindGroups = [];
  2878. webgpuPipelineContext.bindGroups = bindGroups;
  2879. const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts;
  2880. for (let i = 0; i < webgpuPipelineContext.orderedUBOsAndSamplers.length; i++) {
  2881. const setDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i];
  2882. if (setDefinition === undefined) {
  2883. let groupLayout: GPUBindGroupLayout;
  2884. if (bindGroupLayouts && bindGroupLayouts[i]) {
  2885. groupLayout = bindGroupLayouts[i];
  2886. }
  2887. else {
  2888. groupLayout = webgpuPipelineContext.renderPipeline.getBindGroupLayout(i);
  2889. }
  2890. bindGroups[i] = this._device.createBindGroup({
  2891. layout: groupLayout,
  2892. entries: [],
  2893. });
  2894. continue;
  2895. }
  2896. const entries: GPUBindGroupEntry[] = [];
  2897. for (let j = 0; j < setDefinition.length; j++) {
  2898. const bindingDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i][j];
  2899. if (bindingDefinition === undefined) {
  2900. continue;
  2901. }
  2902. // TODO WEBGPU. Authorize shared samplers and Vertex Textures.
  2903. if (bindingDefinition.isSampler) {
  2904. const bindingInfo = webgpuPipelineContext.samplers[bindingDefinition.name];
  2905. if (bindingInfo) {
  2906. if (dbgSanityChecks && bindingInfo.texture === null) {
  2907. console.error("Trying to bind a null texture! bindingDefinition=", bindingDefinition, " | bindingInfo=", bindingInfo);
  2908. debugger;
  2909. }
  2910. const hardwareTexture = bindingInfo.texture._hardwareTexture as WebGPUHardwareTexture;
  2911. if (!hardwareTexture.sampler) {
  2912. const samplerDescriptor: GPUSamplerDescriptor = this._getSamplerDescriptor(bindingInfo.texture!);
  2913. const gpuSampler = this._device.createSampler(samplerDescriptor);
  2914. hardwareTexture.sampler = gpuSampler;
  2915. }
  2916. if (dbgSanityChecks && !hardwareTexture.view) {
  2917. console.error("Trying to bind a null gpu texture! bindingDefinition=", bindingDefinition, " | bindingInfo=", bindingInfo, " | isReady=", bindingInfo.texture.isReady);
  2918. debugger;
  2919. }
  2920. // TODO WEBGPU remove this code
  2921. if ((bindingInfo.texture as any)._released) {
  2922. console.error("Trying to bind a released texture!", bindingInfo.texture, bindingInfo);
  2923. debugger;
  2924. }
  2925. entries.push({
  2926. binding: bindingInfo.textureBinding,
  2927. resource: hardwareTexture.view!,
  2928. }, {
  2929. binding: bindingInfo.samplerBinding,
  2930. resource: hardwareTexture.sampler!,
  2931. });
  2932. }
  2933. else {
  2934. Logger.Error("Sampler has not been bound: " + bindingDefinition.name);
  2935. }
  2936. }
  2937. else {
  2938. const dataBuffer = this._uniformsBuffers[bindingDefinition.name];
  2939. if (dataBuffer) {
  2940. const webgpuBuffer = dataBuffer.underlyingResource as GPUBuffer;
  2941. entries.push({
  2942. binding: j,
  2943. resource: {
  2944. buffer: webgpuBuffer,
  2945. offset: 0,
  2946. size: dataBuffer.capacity,
  2947. },
  2948. });
  2949. }
  2950. else {
  2951. Logger.Error("UBO has not been bound: " + bindingDefinition.name);
  2952. }
  2953. }
  2954. }
  2955. if (entries.length > 0) {
  2956. let groupLayout: GPUBindGroupLayout;
  2957. if (bindGroupLayouts && bindGroupLayouts[i]) {
  2958. groupLayout = bindGroupLayouts[i];
  2959. }
  2960. else {
  2961. groupLayout = webgpuPipelineContext.renderPipeline.getBindGroupLayout(i);
  2962. }
  2963. bindGroups[i] = this._device.createBindGroup({
  2964. layout: groupLayout,
  2965. entries,
  2966. });
  2967. }
  2968. }
  2969. return bindGroups;
  2970. }
  2971. private _bindVertexInputs(vertexInputs: IWebGPUPipelineContextVertexInputsCache, setIndexFormat: boolean): void {
  2972. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  2973. if (vertexInputs.indexBuffer) {
  2974. // TODO WEBGPU. Check if cache would be worth it.
  2975. if (setIndexFormat) {
  2976. renderPass.setIndexBuffer(vertexInputs.indexBuffer, this._currentIndexBuffer!.is32Bits ? WebGPUConstants.IndexFormat.Uint32 : WebGPUConstants.IndexFormat.Uint16, vertexInputs.indexOffset);
  2977. } else {
  2978. renderPass.setIndexBuffer(vertexInputs.indexBuffer, vertexInputs.indexOffset);
  2979. }
  2980. }
  2981. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  2982. for (let i = 0; i < vertexInputs.vertexBuffers.length; i++) {
  2983. const buf = vertexInputs.vertexBuffers[i];
  2984. if (buf) {
  2985. renderPass.setVertexBuffer(vertexInputs.vertexStartSlot + i, buf, vertexInputs.vertexOffsets[i]);
  2986. }
  2987. }
  2988. }
  2989. private _setRenderBindGroups(bindGroups: GPUBindGroup[]): void {
  2990. // TODO WEBGPU. Only set groups if changes happened.
  2991. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  2992. for (let i = 0; i < bindGroups.length; i++) {
  2993. renderPass.setBindGroup(i, bindGroups[i]);
  2994. }
  2995. }
  2996. private _setRenderPipeline(fillMode: number): void {
  2997. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  2998. const topology = this._getTopology(fillMode);
  2999. const setIndexFormatInRenderPass = this._indexFormatInRenderPass(topology);
  3000. const pipeline = this._getRenderPipeline(topology);
  3001. renderPass.setPipeline(pipeline);
  3002. const vertexInputs = this._getVertexInputsToRender();
  3003. this._bindVertexInputs(vertexInputs, setIndexFormatInRenderPass);
  3004. const bindGroups = this._getBindGroupsToRender();
  3005. this._setRenderBindGroups(bindGroups);
  3006. if (this._stencilState.stencilTest) {
  3007. this._getCurrentRenderPass().setStencilReference(this._stencilState.stencilFuncRef);
  3008. }
  3009. // TODO WebGPU add back the dirty mechanism, but we need to distinguish between the main render pass and the RTT pass (if any)
  3010. if (this._alphaState.alphaBlend /* && this._alphaState._isBlendConstantsDirty*/ && renderPass !== this._bundleEncoder) {
  3011. // TODO WebGPU. should use renderPass.
  3012. this._getCurrentRenderPass().setBlendColor(this._alphaState._blendConstants as any);
  3013. }
  3014. if (renderPass !== this._bundleEncoder) {
  3015. this._applyViewport(renderPass as GPURenderPassEncoder);
  3016. }
  3017. }
  3018. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount: number = 1): void {
  3019. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  3020. this._setRenderPipeline(fillMode);
  3021. renderPass.drawIndexed(indexCount, instancesCount || 1, indexStart, 0, 0);
  3022. }
  3023. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount: number = 1): void {
  3024. const renderPass = this._bundleEncoder || this._getCurrentRenderPass();
  3025. this._currentIndexBuffer = null;
  3026. this._setRenderPipeline(fillMode);
  3027. renderPass.draw(verticesCount, instancesCount || 1, verticesStart, 0);
  3028. }
  3029. /**
  3030. * Force a specific size of the canvas
  3031. * @param width defines the new canvas' width
  3032. * @param height defines the new canvas' height
  3033. * @returns true if the size was changed
  3034. */
  3035. public setSize(width: number, height: number): boolean {
  3036. if (!super.setSize(width, height)) {
  3037. return false;
  3038. }
  3039. if (dbgVerboseLogsForFirstFrames) {
  3040. if (!(this as any)._count || (this as any)._count < dbgVerboseLogsNumFrames) {
  3041. console.log("frame #" + (this as any)._count + " - setSize called -", width, height);
  3042. }
  3043. }
  3044. this._initializeMainAttachments();
  3045. return true;
  3046. }
  3047. public applyStates() {
  3048. }
  3049. //------------------------------------------------------------------------------
  3050. // Render Bundle
  3051. //------------------------------------------------------------------------------
  3052. private _bundleEncoder: Nullable<GPURenderBundleEncoder>;
  3053. /**
  3054. * Start recording all the gpu calls into a bundle.
  3055. */
  3056. public startRecordBundle(): void {
  3057. // TODO. WebGPU. options should be dynamic.
  3058. this._bundleEncoder = this._device.createRenderBundleEncoder({
  3059. colorFormats: [ WebGPUConstants.TextureFormat.BGRA8Unorm ],
  3060. depthStencilFormat: WebGPUConstants.TextureFormat.Depth24PlusStencil8,
  3061. sampleCount: this._mainPassSampleCount,
  3062. });
  3063. }
  3064. /**
  3065. * Stops recording the bundle.
  3066. * @returns the recorded bundle
  3067. */
  3068. public stopRecordBundle(): GPURenderBundle {
  3069. const bundle = this._bundleEncoder!.finish();
  3070. this._bundleEncoder = null;
  3071. return bundle;
  3072. }
  3073. /**
  3074. * Execute the previously recorded bundle.
  3075. * @param bundles defines the bundle to replay
  3076. */
  3077. public executeBundles(bundles: GPURenderBundle[]): void {
  3078. const renderPass = this._getCurrentRenderPass();
  3079. renderPass.executeBundles(bundles);
  3080. }
  3081. //------------------------------------------------------------------------------
  3082. // Dispose
  3083. //------------------------------------------------------------------------------
  3084. /**
  3085. * Dispose and release all associated resources
  3086. */
  3087. public dispose(): void {
  3088. this._compiledShaders = { };
  3089. if (this._mainTexture) {
  3090. this._mainTexture.destroy();
  3091. }
  3092. if (this._depthTexture) {
  3093. this._depthTexture.destroy();
  3094. }
  3095. super.dispose();
  3096. }
  3097. //------------------------------------------------------------------------------
  3098. // Misc
  3099. //------------------------------------------------------------------------------
  3100. public getRenderWidth(useScreen = false): number {
  3101. if (!useScreen && this._currentRenderTarget) {
  3102. return this._currentRenderTarget.width;
  3103. }
  3104. return this._canvas.width;
  3105. }
  3106. public getRenderHeight(useScreen = false): number {
  3107. if (!useScreen && this._currentRenderTarget) {
  3108. return this._currentRenderTarget.height;
  3109. }
  3110. return this._canvas.height;
  3111. }
  3112. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  3113. return this._canvas;
  3114. }
  3115. //------------------------------------------------------------------------------
  3116. // Errors
  3117. //------------------------------------------------------------------------------
  3118. public getError(): number {
  3119. // TODO WEBGPU. from the webgpu errors.
  3120. return 0;
  3121. }
  3122. //------------------------------------------------------------------------------
  3123. // Unused WebGPU
  3124. //------------------------------------------------------------------------------
  3125. public areAllEffectsReady(): boolean {
  3126. // No parallel shader compilation.
  3127. return true;
  3128. }
  3129. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  3130. // No parallel shader compilation.
  3131. // No Async, so direct launch
  3132. action();
  3133. }
  3134. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  3135. // No parallel shader compilation.
  3136. return true;
  3137. }
  3138. public _getUnpackAlignement(): number {
  3139. return 1;
  3140. }
  3141. public _unpackFlipY(value: boolean) { }
  3142. // TODO WEBGPU. All of the below should go once engine split with baseEngine.
  3143. /** @hidden */
  3144. public _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  3145. throw "_getSamplingParameters is not available in WebGPU";
  3146. }
  3147. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  3148. }
  3149. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  3150. return [];
  3151. }
  3152. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  3153. return false;
  3154. }
  3155. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  3156. return false;
  3157. }
  3158. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  3159. return false;
  3160. }
  3161. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): boolean {
  3162. return false;
  3163. }
  3164. public setArray(uniform: WebGLUniformLocation, array: number[]): boolean {
  3165. return false;
  3166. }
  3167. public setArray2(uniform: WebGLUniformLocation, array: number[]): boolean {
  3168. return false;
  3169. }
  3170. public setArray3(uniform: WebGLUniformLocation, array: number[]): boolean {
  3171. return false;
  3172. }
  3173. public setArray4(uniform: WebGLUniformLocation, array: number[]): boolean {
  3174. return false;
  3175. }
  3176. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): boolean {
  3177. return false;
  3178. }
  3179. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): boolean {
  3180. return false;
  3181. }
  3182. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): boolean {
  3183. return false;
  3184. }
  3185. public setFloat(uniform: WebGLUniformLocation, value: number): boolean {
  3186. return false;
  3187. }
  3188. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): boolean {
  3189. return false;
  3190. }
  3191. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): boolean {
  3192. return false;
  3193. }
  3194. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): boolean {
  3195. return false;
  3196. }
  3197. }
  3198. /** @hidden */
  3199. function _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  3200. // Create new RGBA data container.
  3201. var rgbaData: any;
  3202. if (textureType === Constants.TEXTURETYPE_FLOAT) {
  3203. rgbaData = new Float32Array(width * height * 4);
  3204. }
  3205. else {
  3206. rgbaData = new Uint32Array(width * height * 4);
  3207. }
  3208. // Convert each pixel.
  3209. for (let x = 0; x < width; x++) {
  3210. for (let y = 0; y < height; y++) {
  3211. let index = (y * width + x) * 3;
  3212. let newIndex = (y * width + x) * 4;
  3213. // Map Old Value to new value.
  3214. rgbaData[newIndex + 0] = rgbData[index + 0];
  3215. rgbaData[newIndex + 1] = rgbData[index + 1];
  3216. rgbaData[newIndex + 2] = rgbData[index + 2];
  3217. // Add fully opaque alpha channel.
  3218. rgbaData[newIndex + 3] = 1;
  3219. }
  3220. }
  3221. return rgbaData;
  3222. }