webgpuEngine.ts 136 KB

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