webgpuEngine.ts 169 KB

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