webgpuEngine.ts 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472
  1. import { Logger } from "../Misc/logger";
  2. import { Nullable, DataArray, IndicesArray, FloatArray } from "../types";
  3. import { Scene } from "../scene";
  4. import { Color4 } from "../Maths/math";
  5. import { Scalar } from "../Maths/math.scalar";
  6. import { Engine, EngineCapabilities, InstancingAttributeInfo } from "../Engines/engine";
  7. import { RenderTargetCreationOptions } from "../Materials/Textures/renderTargetCreationOptions";
  8. import { InternalTexture } from "../Materials/Textures/internalTexture";
  9. import { EffectCreationOptions, EffectFallbacks, Effect } from "../Materials/effect";
  10. import { _TimeToken } from "../Instrumentation/timeToken";
  11. import { _DepthCullingState, _StencilState, _AlphaState } from "../States/index";
  12. import { Constants } from "./constants";
  13. import { WebGPUConstants } from "./WebGPU/webgpuConstants";
  14. import { VertexBuffer } from "../Meshes/buffer";
  15. import { WebGPUPipelineContext, IWebGPUPipelineContextVertexInputsCache } from './WebGPU/webgpuPipelineContext';
  16. import { IPipelineContext } from './IPipelineContext';
  17. import { DataBuffer } from '../Meshes/dataBuffer';
  18. import { WebGPUDataBuffer } from '../Meshes/WebGPU/webgpuDataBuffer';
  19. import { IInternalTextureLoader } from "../Materials/Textures/internalTextureLoader";
  20. import { BaseTexture } from "../Materials/Textures/baseTexture";
  21. import { IShaderProcessor } from "./Processors/iShaderProcessor";
  22. import { WebGPUShaderProcessor } from "./WebGPU/webgpuShaderProcessors";
  23. import { ShaderProcessingContext } from "./Processors/shaderProcessingOptions";
  24. import { WebGPUShaderProcessingContext } from "./WebGPU/webgpuShaderProcessingContext";
  25. import { Tools } from "../Misc/tools";
  26. /**
  27. * Options to load the associated Shaderc library
  28. */
  29. export interface ShadercOptions {
  30. /**
  31. * Defines an existing instance of shaderC (usefull in modules who do not access the global instance).
  32. */
  33. shaderc?: any;
  34. /**
  35. * Defines the URL of the shaderc JS File.
  36. */
  37. jsPath?: string;
  38. /**
  39. * Defines the URL of the shaderc WASM File.
  40. */
  41. wasmPath?: string;
  42. }
  43. /**
  44. * Options to create the WebGPU engine
  45. */
  46. export interface WebGPUEngineOptions extends GPURequestAdapterOptions {
  47. /**
  48. * If delta time between frames should be constant
  49. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  50. */
  51. deterministicLockstep?: boolean;
  52. /**
  53. * Maximum about of steps between frames (Default: 4)
  54. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  55. */
  56. lockstepMaxSteps?: number;
  57. /**
  58. * Defines that engine should ignore modifying touch action attribute and style
  59. * If not handle, you might need to set it up on your side for expected touch devices behavior.
  60. */
  61. doNotHandleTouchAction?: boolean;
  62. /**
  63. * Defines if webaudio should be initialized as well
  64. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  65. */
  66. audioEngine?: boolean;
  67. /**
  68. * Defines the category of adapter to use.
  69. * Is it the discrete or integrated device.
  70. */
  71. powerPreference?: GPUPowerPreference;
  72. /**
  73. * Defines the device descriptor used to create a device.
  74. */
  75. deviceDescriptor?: GPUDeviceDescriptor;
  76. /**
  77. * Defines the requested Swap Chain Format.
  78. */
  79. swapChainFormat?: GPUTextureFormat;
  80. /**
  81. * Defines wether MSAA is enabled on the canvas.
  82. */
  83. antialiasing?: boolean;
  84. }
  85. /**
  86. * The web GPU engine class provides support for WebGPU version of babylon.js.
  87. */
  88. export class WebGPUEngine extends Engine {
  89. // Default shaderc options.
  90. private static readonly _shadercDefaultOptions: ShadercOptions = {
  91. jsPath: "https://preview.babylonjs.com/shaderc/shaderc.js",
  92. wasmPath: "https://preview.babylonjs.com/shaderc/shaderc.wasm"
  93. };
  94. // Page Life cycle and constants
  95. private readonly _uploadEncoderDescriptor = { label: "upload" };
  96. private readonly _renderEncoderDescriptor = { label: "render" };
  97. private readonly _clearDepthValue = 1;
  98. private readonly _clearStencilValue = 0;
  99. private readonly _defaultSampleCount = 4; // Only supported value for now.
  100. // Engine Life Cycle
  101. private _canvas: HTMLCanvasElement;
  102. private _options: WebGPUEngineOptions;
  103. private _shaderc: any = null;
  104. private _adapter: GPUAdapter;
  105. private _device: GPUDevice;
  106. private _context: GPUCanvasContext;
  107. private _swapChain: GPUSwapChain;
  108. private _mainPassSampleCount: number;
  109. // Some of the internal state might change during the render pass.
  110. // This happens mainly during clear for the state
  111. // And when the frame starts to swap the target texture from the swap chain
  112. private _mainTexture: GPUTexture;
  113. private _depthTexture: GPUTexture;
  114. private _mainColorAttachments: GPURenderPassColorAttachmentDescriptor[];
  115. private _mainTextureExtends: GPUExtent3D;
  116. private _mainDepthAttachment: GPURenderPassDepthStencilAttachmentDescriptor;
  117. // Frame Life Cycle (recreated each frame)
  118. private _uploadEncoder: GPUCommandEncoder;
  119. private _renderEncoder: GPUCommandEncoder;
  120. private _commandBuffers: GPUCommandBuffer[] = [null as any, null as any];
  121. // Frame Buffer Life Cycle (recreated for each render target pass)
  122. private _currentRenderPass: Nullable<GPURenderPassEncoder> = null;
  123. // DrawCall Life Cycle
  124. // Effect is on the parent class
  125. // protected _currentEffect: Nullable<Effect> = null;
  126. private _currentVertexBuffers: Nullable<{ [key: string]: Nullable<VertexBuffer> }> = null;
  127. private _currentIndexBuffer: Nullable<DataBuffer> = null;
  128. private __colorWrite = true;
  129. private _uniformsBuffers: { [name: string]: WebGPUDataBuffer } = {};
  130. // Caches
  131. private _compiledShaders: { [key: string]: {
  132. stages: GPURenderPipelineStageDescriptor,
  133. availableAttributes: { [key: string]: number },
  134. availableUBOs: { [key: string]: { setIndex: number, bindingIndex: number} },
  135. availableSamplers: { [key: string]: { setIndex: number, bindingIndex: number} },
  136. orderedAttributes: string[],
  137. orderedUBOsAndSamplers: { name: string, isSampler: boolean }[][],
  138. leftOverUniforms: { name: string, type: string, length: number }[],
  139. leftOverUniformsByName: { [name: string]: string },
  140. sources: {
  141. vertex: string
  142. fragment: string,
  143. }
  144. } } = {};
  145. // TODO WEBGPU. Texture Management. Temporary...
  146. private _decodeCanvas = document.createElement("canvas");
  147. private _decodeEngine = new Engine(this._decodeCanvas, false, {
  148. alpha: true,
  149. premultipliedAlpha: false,
  150. }, false);
  151. /**
  152. * Gets a boolean indicating that the engine supports uniform buffers
  153. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  154. */
  155. public get supportsUniformBuffers(): boolean {
  156. return true;
  157. }
  158. /**
  159. * Create a new instance of the gpu engine.
  160. * @param canvas Defines the canvas to use to display the result
  161. * @param options Defines the options passed to the engine to create the GPU context dependencies
  162. */
  163. public constructor(canvas: HTMLCanvasElement, options: WebGPUEngineOptions = {}) {
  164. super(null);
  165. options.deviceDescriptor = options.deviceDescriptor || { };
  166. options.swapChainFormat = options.swapChainFormat || WebGPUConstants.GPUTextureFormat_bgra8unorm;
  167. options.antialiasing = options.antialiasing === undefined ? true : options.antialiasing;
  168. this._decodeEngine.getCaps().textureFloat = false;
  169. this._decodeEngine.getCaps().textureFloatRender = false;
  170. this._decodeEngine.getCaps().textureHalfFloat = false;
  171. this._decodeEngine.getCaps().textureHalfFloatRender = false;
  172. Logger.Log(`Babylon.js v${Engine.Version} - WebGPU engine`);
  173. if (!navigator.gpu) {
  174. // TODO WEBGPU Fall back to webgl.
  175. Logger.Error("WebGPU is not supported by your browser.");
  176. return;
  177. }
  178. this._isWebGPU = true;
  179. this._shaderPlatformName = "WEBGPU";
  180. if (options.deterministicLockstep === undefined) {
  181. options.deterministicLockstep = false;
  182. }
  183. if (options.lockstepMaxSteps === undefined) {
  184. options.lockstepMaxSteps = 4;
  185. }
  186. if (options.audioEngine === undefined) {
  187. options.audioEngine = true;
  188. }
  189. this._deterministicLockstep = options.deterministicLockstep;
  190. this._lockstepMaxSteps = options.lockstepMaxSteps;
  191. this._doNotHandleContextLost = true;
  192. this._canvas = canvas;
  193. this._options = options;
  194. this._hardwareScalingLevel = 1;
  195. this._mainPassSampleCount = options.antialiasing ? this._defaultSampleCount : 1;
  196. this._sharedInit(canvas, !!options.doNotHandleTouchAction, options.audioEngine);
  197. }
  198. //------------------------------------------------------------------------------
  199. // Initialization
  200. //------------------------------------------------------------------------------
  201. /**
  202. * Initializes the WebGPU context and dependencies.
  203. * @param shadercOptions Defines the ShaderC compiler options if necessary
  204. * @returns a promise notifying the readiness of the engine.
  205. */
  206. public initAsync(shadercOptions?: ShadercOptions): Promise<void> {
  207. return this._initShaderc(shadercOptions)
  208. .then((shaderc: any) => {
  209. this._shaderc = shaderc;
  210. return navigator.gpu!.requestAdapter(this._options);
  211. })
  212. .then((adapter: GPUAdapter) => {
  213. this._adapter = adapter;
  214. return this._adapter.requestDevice(this._options.deviceDescriptor);
  215. })
  216. .then((device: GPUDevice) => this._device = device)
  217. .then(() => {
  218. this._initializeLimits();
  219. this._initializeContextAndSwapChain();
  220. // this._initializeMainAttachments();
  221. // Initialization is in the resize :-)
  222. this.resize();
  223. })
  224. .catch((e: any) => {
  225. Logger.Error("Can not create WebGPU Device and/or context.");
  226. Logger.Error(e);
  227. });
  228. }
  229. private _initShaderc(shadercOptions?: ShadercOptions): Promise<any> {
  230. shadercOptions = shadercOptions || { };
  231. shadercOptions = {
  232. ...WebGPUEngine._shadercDefaultOptions,
  233. ...shadercOptions
  234. };
  235. if (shadercOptions.shaderc) {
  236. return Promise.resolve(shadercOptions.shaderc);
  237. }
  238. const wasmOptions = {
  239. wasmBinaryFile: shadercOptions!.wasmPath
  240. };
  241. if ((window as any).Shaderc) {
  242. return (window as any).Shaderc(wasmOptions);
  243. }
  244. if (shadercOptions.jsPath && shadercOptions.wasmPath) {
  245. return Tools.LoadScriptAsync(shadercOptions.jsPath)
  246. .then(() => {
  247. return (window as any).Shaderc(wasmOptions);
  248. });
  249. }
  250. return Promise.reject("shaderc is not available.");
  251. }
  252. private _initializeLimits(): void {
  253. // Init caps
  254. // TODO WEBGPU Real Capability check once limits will be working.
  255. this._caps = new EngineCapabilities();
  256. this._caps.maxTexturesImageUnits = 16;
  257. this._caps.maxVertexTextureImageUnits = 16;
  258. this._caps.maxTextureSize = 2048;
  259. this._caps.maxCubemapTextureSize = 2048;
  260. this._caps.maxRenderTextureSize = 2048;
  261. this._caps.maxVertexAttribs = 16;
  262. this._caps.maxVaryingVectors = 16;
  263. this._caps.maxFragmentUniformVectors = 1024;
  264. this._caps.maxVertexUniformVectors = 1024;
  265. // Extensions
  266. this._caps.standardDerivatives = true;
  267. this._caps.astc = null;
  268. this._caps.s3tc = null;
  269. this._caps.pvrtc = null;
  270. this._caps.etc1 = null;
  271. this._caps.etc2 = null;
  272. this._caps.textureAnisotropicFilterExtension = null;
  273. this._caps.maxAnisotropy = 0;
  274. this._caps.uintIndices = true;
  275. this._caps.fragmentDepthSupported = false;
  276. this._caps.highPrecisionShaderSupported = true;
  277. this._caps.colorBufferFloat = true;
  278. this._caps.textureFloat = false;
  279. this._caps.textureFloatLinearFiltering = false;
  280. this._caps.textureFloatRender = false;
  281. this._caps.textureHalfFloat = false;
  282. this._caps.textureHalfFloatLinearFiltering = false;
  283. this._caps.textureHalfFloatRender = false;
  284. this._caps.textureLOD = true;
  285. this._caps.drawBuffersExtension = true;
  286. this._caps.depthTextureExtension = true;
  287. // TODO WEBGPU. No need here but could be use to create descriptors ???
  288. this._caps.vertexArrayObject = false;
  289. this._caps.instancedArrays = true;
  290. // TODO WEBGPU. Unused for now.
  291. // this._caps.parallelShaderCompile = null;
  292. }
  293. private _initializeContextAndSwapChain(): void {
  294. this._context = this._canvas.getContext('gpupresent') as unknown as GPUCanvasContext;
  295. this._swapChain = this._context.configureSwapChain({
  296. device: this._device,
  297. format: this._options.swapChainFormat!,
  298. usage: WebGPUConstants.GPUTextureUsage_OUTPUT_ATTACHMENT | WebGPUConstants.GPUTextureUsage_COPY_SRC,
  299. });
  300. }
  301. // Set default values as WebGL with depth and stencil attachment for the broadest Compat.
  302. private _initializeMainAttachments(): void {
  303. this._mainTextureExtends = {
  304. width: this.getRenderWidth(),
  305. height: this.getRenderHeight(),
  306. depth: 1
  307. };
  308. if (this._options.antialiasing) {
  309. const mainTextureDescriptor = {
  310. size: this._mainTextureExtends,
  311. arrayLayerCount: 1,
  312. mipLevelCount: 1,
  313. sampleCount: this._mainPassSampleCount,
  314. dimension: WebGPUConstants.GPUTextureDimension_2d,
  315. format: WebGPUConstants.GPUTextureFormat_bgra8unorm,
  316. usage: WebGPUConstants.GPUTextureUsage_OUTPUT_ATTACHMENT,
  317. };
  318. if (this._mainTexture) {
  319. this._mainTexture.destroy();
  320. }
  321. this._mainTexture = this._device.createTexture(mainTextureDescriptor);
  322. this._mainColorAttachments = [{
  323. attachment: this._mainTexture.createDefaultView(),
  324. loadValue: new Color4(0, 0, 0, 1),
  325. storeOp: WebGPUConstants.GPUStoreOp_store
  326. }];
  327. }
  328. else {
  329. this._mainColorAttachments = [{
  330. attachment: this._swapChain.getCurrentTexture().createDefaultView(),
  331. loadValue: new Color4(0, 0, 0, 1),
  332. storeOp: WebGPUConstants.GPUStoreOp_store
  333. }];
  334. }
  335. const depthTextureDescriptor = {
  336. size: this._mainTextureExtends,
  337. arrayLayerCount: 1,
  338. mipLevelCount: 1,
  339. sampleCount: this._mainPassSampleCount,
  340. dimension: WebGPUConstants.GPUTextureDimension_2d,
  341. format: WebGPUConstants.GPUTextureFormat_depth24plusStencil8,
  342. usage: WebGPUConstants.GPUTextureUsage_OUTPUT_ATTACHMENT
  343. };
  344. if (this._depthTexture) {
  345. this._depthTexture.destroy();
  346. }
  347. this._depthTexture = this._device.createTexture(depthTextureDescriptor);
  348. this._mainDepthAttachment = {
  349. attachment: this._depthTexture.createDefaultView(),
  350. depthLoadValue: this._clearDepthValue,
  351. depthStoreOp: WebGPUConstants.GPUStoreOp_store,
  352. stencilLoadValue: this._clearStencilValue,
  353. stencilStoreOp: WebGPUConstants.GPUStoreOp_store,
  354. };
  355. }
  356. /**
  357. * Gets a shader processor implementation fitting with the current engine type.
  358. * @returns The shader processor implementation.
  359. */
  360. protected _getShaderProcessor(): Nullable<IShaderProcessor> {
  361. return new WebGPUShaderProcessor();
  362. }
  363. /** @hidden */
  364. public _getShaderProcessingContext(): Nullable<ShaderProcessingContext> {
  365. return new WebGPUShaderProcessingContext();
  366. }
  367. //------------------------------------------------------------------------------
  368. // Static Pipeline WebGPU States
  369. //------------------------------------------------------------------------------
  370. public wipeCaches(bruteForce?: boolean): void {
  371. if (this.preventCacheWipeBetweenFrames) {
  372. return;
  373. }
  374. this.resetTextureCache();
  375. this._currentEffect = null;
  376. this._currentIndexBuffer = null;
  377. this._currentVertexBuffers = null;
  378. if (bruteForce) {
  379. this._currentProgram = null;
  380. this._stencilState.reset();
  381. this._depthCullingState.reset();
  382. this._alphaState.reset();
  383. }
  384. this._cachedVertexBuffers = null;
  385. this._cachedIndexBuffer = null;
  386. this._cachedEffectForVertexBuffers = null;
  387. }
  388. public setColorWrite(enable: boolean): void {
  389. this.__colorWrite = enable;
  390. }
  391. public getColorWrite(): boolean {
  392. return this.__colorWrite;
  393. }
  394. //------------------------------------------------------------------------------
  395. // Dynamic WebGPU States
  396. //------------------------------------------------------------------------------
  397. public _viewport(x: number, y: number, width: number, height: number): void {
  398. // TODO WEBGPU. Cache.
  399. // if (x !== this._viewportCached.x ||
  400. // y !== this._viewportCached.y ||
  401. // width !== this._viewportCached.z ||
  402. // height !== this._viewportCached.w) {
  403. // this._viewportCached.x = x;
  404. // this._viewportCached.y = y;
  405. // this._viewportCached.z = width;
  406. // this._viewportCached.w = height;
  407. // this._gl.viewport(x, y, width, height);
  408. // }
  409. if (!this._currentRenderPass) {
  410. this._startMainRenderPass();
  411. }
  412. // TODO WEBGPU. Viewport.
  413. // Use 0 1 like the default webgl values.
  414. // this._currentRenderPass!.setViewport(x, y, width, height, 0, 1);
  415. }
  416. public enableScissor(x: number, y: number, width: number, height: number): void {
  417. if (!this._currentRenderPass) {
  418. this._startMainRenderPass();
  419. }
  420. // TODO WEBGPU. Scissor.
  421. //this._currentRenderPass!.setScissorRect(x, y, width, height);
  422. }
  423. public disableScissor() {
  424. if (!this._currentRenderPass) {
  425. this._startMainRenderPass();
  426. }
  427. // TODO WEBGPU. Scissor.
  428. //this._currentRenderPass!.setScissorRect(0, 0, this.getRenderWidth(), this.getRenderHeight());
  429. }
  430. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  431. // Some PGs are using color3...
  432. if (color.a === undefined) {
  433. color.a = 1;
  434. }
  435. this._mainColorAttachments[0].loadValue = backBuffer ? color : WebGPUConstants.GPULoadOp_load;
  436. this._mainDepthAttachment.depthLoadValue = depth ? this._clearDepthValue : WebGPUConstants.GPULoadOp_load;
  437. this._mainDepthAttachment.stencilLoadValue = stencil ? this._clearStencilValue : WebGPUConstants.GPULoadOp_load;
  438. // TODO WEBGPU. Where to store GPUOpStore ???
  439. // TODO WEBGPU. Should be main or rtt with a frame buffer like object.
  440. this._startMainRenderPass();
  441. }
  442. //------------------------------------------------------------------------------
  443. // WebGPU Buffers
  444. //------------------------------------------------------------------------------
  445. private _createBuffer(view: ArrayBufferView, flags: GPUBufferUsageFlags): DataBuffer {
  446. const padding = view.byteLength % 4;
  447. const verticesBufferDescriptor = {
  448. size: view.byteLength + padding,
  449. usage: flags
  450. };
  451. const buffer = this._device.createBuffer(verticesBufferDescriptor);
  452. const dataBuffer = new WebGPUDataBuffer(buffer);
  453. dataBuffer.references = 1;
  454. dataBuffer.capacity = view.byteLength;
  455. this._setSubData(dataBuffer, 0, view);
  456. return dataBuffer;
  457. }
  458. private _setSubData(dataBuffer: WebGPUDataBuffer, dstByteOffset: number, src: ArrayBufferView, srcByteOffset = 0, byteLength = 0): void {
  459. const buffer = dataBuffer.underlyingResource as GPUBuffer;
  460. byteLength = byteLength || src.byteLength;
  461. byteLength = Math.min(byteLength, dataBuffer.capacity - dstByteOffset);
  462. // After Migration to Canary
  463. // This would do from PR #261
  464. let chunkStart = src.byteOffset + srcByteOffset;
  465. let chunkEnd = chunkStart + byteLength;
  466. // 4 bytes alignments for upload
  467. const padding = byteLength % 4;
  468. if (padding !== 0) {
  469. const tempView = new Uint8Array(src.buffer.slice(chunkStart, chunkEnd));
  470. src = new Uint8Array(byteLength + padding);
  471. tempView.forEach((element, index) => {
  472. (src as Uint8Array)[index] = element;
  473. });
  474. srcByteOffset = 0;
  475. chunkStart = 0;
  476. chunkEnd = byteLength + padding;
  477. byteLength = byteLength + padding;
  478. }
  479. // Chunk
  480. const maxChunk = 1024 * 1024 * 15;
  481. let offset = 0;
  482. while ((chunkEnd - (chunkStart + offset)) > maxChunk) {
  483. // TODO WEBGPU.
  484. // Deprecated soon to be removed... replace by mappedBuffers
  485. buffer.setSubData(dstByteOffset + offset, src, srcByteOffset + offset, maxChunk);
  486. offset += maxChunk;
  487. }
  488. // TODO WEBGPU.
  489. // Deprecated soon to be removed... replace by mappedBuffers
  490. buffer.setSubData(dstByteOffset + offset, src, srcByteOffset + offset, byteLength - offset);
  491. }
  492. //------------------------------------------------------------------------------
  493. // Vertex/Index Buffers
  494. //------------------------------------------------------------------------------
  495. public createVertexBuffer(data: DataArray): DataBuffer {
  496. let view: ArrayBufferView;
  497. if (data instanceof Array) {
  498. view = new Float32Array(data);
  499. }
  500. else if (data instanceof ArrayBuffer) {
  501. view = new Uint8Array(data);
  502. }
  503. else {
  504. view = data;
  505. }
  506. const dataBuffer = this._createBuffer(view, WebGPUConstants.GPUBufferUsage_VERTEX | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  507. return dataBuffer;
  508. }
  509. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  510. // TODO WEBGPU.
  511. return this.createVertexBuffer(data);
  512. }
  513. public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  514. const dataBuffer = vertexBuffer as WebGPUDataBuffer;
  515. if (byteOffset === undefined) {
  516. byteOffset = 0;
  517. }
  518. let view: ArrayBufferView;
  519. if (byteLength === undefined) {
  520. if (data instanceof Array) {
  521. view = new Float32Array(data);
  522. }
  523. else if (data instanceof ArrayBuffer) {
  524. view = new Uint8Array(data);
  525. }
  526. else {
  527. view = data;
  528. }
  529. byteLength = view.byteLength;
  530. } else {
  531. if (data instanceof Array) {
  532. view = new Float32Array(data);
  533. }
  534. else if (data instanceof ArrayBuffer) {
  535. view = new Uint8Array(data);
  536. }
  537. else {
  538. view = data;
  539. }
  540. }
  541. this._setSubData(dataBuffer, byteOffset, view, 0, byteLength);
  542. }
  543. public createIndexBuffer(data: IndicesArray): DataBuffer {
  544. let is32Bits = true;
  545. let view: ArrayBufferView;
  546. if (data instanceof Uint32Array || data instanceof Int32Array) {
  547. view = data;
  548. }
  549. else if (data instanceof Uint16Array) {
  550. view = data;
  551. is32Bits = false;
  552. }
  553. else {
  554. if (data.length > 65535) {
  555. view = new Uint32Array(data);
  556. }
  557. else {
  558. view = new Uint16Array(data);
  559. is32Bits = false;
  560. }
  561. }
  562. const dataBuffer = this._createBuffer(view, WebGPUConstants.GPUBufferUsage_INDEX | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  563. dataBuffer.is32Bits = is32Bits;
  564. return dataBuffer;
  565. }
  566. public updateDynamicIndexBuffer(indexBuffer: DataBuffer, indices: IndicesArray, offset: number = 0): void {
  567. const gpuBuffer = indexBuffer as WebGPUDataBuffer;
  568. // TODO WEBGPU. Manage buffer morphing from small int to bigint.
  569. var view: ArrayBufferView;
  570. if (indices instanceof Uint16Array) {
  571. if (indexBuffer.is32Bits) {
  572. view = Uint32Array.from(indices);
  573. }
  574. else {
  575. view = indices;
  576. }
  577. }
  578. else if (indices instanceof Uint32Array) {
  579. if (indexBuffer.is32Bits) {
  580. view = indices;
  581. }
  582. else {
  583. view = Uint16Array.from(indices);
  584. }
  585. }
  586. else {
  587. if (indexBuffer.is32Bits) {
  588. view = new Uint32Array(indices);
  589. }
  590. else {
  591. view = new Uint16Array(indices);
  592. }
  593. }
  594. // TODO WEBGPU. check if offset is in bytes ???
  595. this._setSubData(gpuBuffer, offset, view);
  596. }
  597. public bindBuffersDirectly(vertexBuffer: DataBuffer, indexBuffer: DataBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  598. throw "Not implemented on WebGPU so far.";
  599. }
  600. public updateAndBindInstancesBuffer(instancesBuffer: DataBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  601. throw "Not implemented on WebGPU so far.";
  602. }
  603. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<DataBuffer>, effect: Effect): void {
  604. this._currentIndexBuffer = indexBuffer;
  605. this._currentVertexBuffers = vertexBuffers;
  606. }
  607. /** @hidden */
  608. public _releaseBuffer(buffer: DataBuffer): boolean {
  609. buffer.references--;
  610. if (buffer.references === 0) {
  611. (buffer.underlyingResource as GPUBuffer).destroy();
  612. return true;
  613. }
  614. return false;
  615. }
  616. //------------------------------------------------------------------------------
  617. // UBO
  618. //------------------------------------------------------------------------------
  619. public createUniformBuffer(elements: FloatArray): DataBuffer {
  620. let view: Float32Array;
  621. if (elements instanceof Array) {
  622. view = new Float32Array(elements);
  623. }
  624. else {
  625. view = elements;
  626. }
  627. const dataBuffer = this._createBuffer(view, WebGPUConstants.GPUBufferUsage_UNIFORM | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  628. return dataBuffer;
  629. }
  630. public createDynamicUniformBuffer(elements: FloatArray): DataBuffer {
  631. // TODO WEBGPU. Implement dynamic buffers.
  632. return this.createUniformBuffer(elements);
  633. }
  634. public updateUniformBuffer(uniformBuffer: DataBuffer, elements: FloatArray, offset?: number, count?: number): void {
  635. if (offset === undefined) {
  636. offset = 0;
  637. }
  638. const dataBuffer = uniformBuffer as WebGPUDataBuffer;
  639. let view: Float32Array;
  640. if (count === undefined) {
  641. if (elements instanceof Float32Array) {
  642. view = elements;
  643. } else {
  644. view = new Float32Array(elements);
  645. }
  646. count = view.byteLength;
  647. } else {
  648. if (elements instanceof Float32Array) {
  649. view = elements;
  650. } else {
  651. view = new Float32Array(elements);
  652. }
  653. }
  654. // TODO WEBGPU. Check count and offset are in bytes.
  655. this._setSubData(dataBuffer, offset, view, 0, count);
  656. }
  657. public bindUniformBufferBase(buffer: DataBuffer, location: number, name: string): void {
  658. this._uniformsBuffers[name] = buffer as WebGPUDataBuffer;
  659. }
  660. //------------------------------------------------------------------------------
  661. // Effects
  662. //------------------------------------------------------------------------------
  663. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  664. onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
  665. const vertex = baseName.vertexElement || baseName.vertex || baseName;
  666. const fragment = baseName.fragmentElement || baseName.fragment || baseName;
  667. const name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  668. const shader = this._compiledShaders[name];
  669. if (shader) {
  670. return new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, shader.sources);
  671. }
  672. else {
  673. return new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name);
  674. }
  675. }
  676. private _compileRawShaderToSpirV(source: string, type: string): Uint32Array {
  677. const Shaderc = this._shaderc;
  678. const compiler = new Shaderc.Compiler();
  679. const opts = new Shaderc.CompileOptions();
  680. const result = compiler.CompileGlslToSpv(source,
  681. type === "fragment" ? Shaderc.shader_kind.fragment :
  682. type === "vertex" ? Shaderc.shader_kind.vertex :
  683. type === "compute" ? Shaderc.shader_kind.compute : null,
  684. "tempCompilation.glsl", "main", opts);
  685. const error = result.GetErrorMessage();
  686. if (error) {
  687. Logger.Error(error);
  688. throw new Error("Something went wrong while compile the shader.");
  689. }
  690. return result.GetBinary().slice();
  691. }
  692. private _compileShaderToSpirV(source: string, type: string, defines: Nullable<string>, shaderVersion: string): Uint32Array {
  693. return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  694. }
  695. private _createPipelineStageDescriptor(vertexShader: Uint32Array, fragmentShader: Uint32Array): GPURenderPipelineStageDescriptor {
  696. return {
  697. vertexStage: {
  698. module: this._device.createShaderModule({
  699. code: vertexShader,
  700. }),
  701. entryPoint: "main",
  702. },
  703. fragmentStage: {
  704. module: this._device.createShaderModule({
  705. code: fragmentShader,
  706. }),
  707. entryPoint: "main"
  708. }
  709. };
  710. }
  711. private _compileRawPipelineStageDescriptor(vertexCode: string, fragmentCode: string): GPURenderPipelineStageDescriptor {
  712. var vertexShader = this._compileRawShaderToSpirV(vertexCode, "vertex");
  713. var fragmentShader = this._compileRawShaderToSpirV(fragmentCode, "fragment");
  714. return this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  715. }
  716. private _compilePipelineStageDescriptor(vertexCode: string, fragmentCode: string, defines: Nullable<string>): GPURenderPipelineStageDescriptor {
  717. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  718. var shaderVersion = "#version 450\n";
  719. var vertexShader = this._compileShaderToSpirV(vertexCode, "vertex", defines, shaderVersion);
  720. var fragmentShader = this._compileShaderToSpirV(fragmentCode, "fragment", defines, shaderVersion);
  721. let program = this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  722. this.onAfterShaderCompilationObservable.notifyObservers(this);
  723. return program;
  724. }
  725. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  726. throw "Not available on WebGPU";
  727. }
  728. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  729. throw "Not available on WebGPU";
  730. }
  731. public createPipelineContext(shaderProcessingContext: Nullable<ShaderProcessingContext>): IPipelineContext {
  732. var pipelineContext = new WebGPUPipelineContext(shaderProcessingContext! as WebGPUShaderProcessingContext, this);
  733. pipelineContext.engine = this;
  734. return pipelineContext;
  735. }
  736. /** @hidden */
  737. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean,
  738. rebuildRebind: any,
  739. defines: Nullable<string>,
  740. transformFeedbackVaryings: Nullable<string[]>,
  741. key: string) {
  742. const webGpuContext = pipelineContext as WebGPUPipelineContext;
  743. // TODO WEBGPU. Check if caches could be reuse from piepline ???
  744. const shader = this._compiledShaders[key];
  745. if (shader) {
  746. webGpuContext.stages = shader.stages;
  747. webGpuContext.availableAttributes = shader.availableAttributes;
  748. webGpuContext.availableUBOs = shader.availableUBOs;
  749. webGpuContext.availableSamplers = shader.availableSamplers;
  750. webGpuContext.orderedAttributes = shader.orderedAttributes;
  751. webGpuContext.orderedUBOsAndSamplers = shader.orderedUBOsAndSamplers;
  752. webGpuContext.leftOverUniforms = shader.leftOverUniforms;
  753. webGpuContext.leftOverUniformsByName = shader.leftOverUniformsByName;
  754. webGpuContext.sources = shader.sources;
  755. }
  756. else {
  757. if (createAsRaw) {
  758. webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode);
  759. }
  760. else {
  761. webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines);
  762. }
  763. this._compiledShaders[key] = {
  764. stages: webGpuContext.stages,
  765. availableAttributes: webGpuContext.availableAttributes,
  766. availableUBOs: webGpuContext.availableUBOs,
  767. availableSamplers: webGpuContext.availableSamplers,
  768. orderedAttributes: webGpuContext.orderedAttributes,
  769. orderedUBOsAndSamplers: webGpuContext.orderedUBOsAndSamplers,
  770. leftOverUniforms: webGpuContext.leftOverUniforms,
  771. leftOverUniformsByName: webGpuContext.leftOverUniformsByName,
  772. sources: {
  773. fragment: fragmentSourceCode,
  774. vertex: vertexSourceCode
  775. }
  776. };
  777. }
  778. }
  779. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  780. const results = new Array(attributesNames.length);
  781. const gpuPipelineContext = (pipelineContext as WebGPUPipelineContext);
  782. // TODO WEBGPU.
  783. // Hard coded for WebGPU until an introspection lib is available.
  784. // Should be done at processing time, not need to double the work in here.
  785. for (let i = 0; i < attributesNames.length; i++) {
  786. const attributeName = attributesNames[i];
  787. const attributeLocation = gpuPipelineContext.availableAttributes[attributeName];
  788. if (attributeLocation === undefined) {
  789. continue;
  790. }
  791. results[i] = attributeLocation;
  792. }
  793. return results;
  794. }
  795. public enableEffect(effect: Effect): void {
  796. this._currentEffect = effect;
  797. if (effect.onBind) {
  798. effect.onBind(effect);
  799. }
  800. if (effect._onBindObservable) {
  801. effect._onBindObservable.notifyObservers(effect);
  802. }
  803. }
  804. public _releaseEffect(effect: Effect): void {
  805. // Effect gets garbage collected without explicit destroy in WebGPU.
  806. }
  807. /**
  808. * 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
  809. */
  810. public releaseEffects() {
  811. // Effect gets garbage collected without explicit destroy in WebGPU.
  812. }
  813. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  814. const webgpuPipelineContext = pipelineContext as WebGPUPipelineContext;
  815. if (webgpuPipelineContext) {
  816. // TODO WEBGPU. Spector like cleanup.
  817. // TODO WEBGPU. Any pipeline required cleanup.
  818. }
  819. }
  820. //------------------------------------------------------------------------------
  821. // Textures
  822. //------------------------------------------------------------------------------
  823. // TODO WEBGPU. SHOULD not be possible to return gl unwrapped from Engine.
  824. /** @hidden */
  825. public _createTexture(): WebGLTexture {
  826. return { };
  827. }
  828. /** @hidden */
  829. public _releaseTexture(texture: InternalTexture): void {
  830. // TODO WEBGPU. check if it is all to release.
  831. if (texture._webGPUTexture) {
  832. texture._webGPUTexture.destroy();
  833. }
  834. }
  835. private _uploadMipMapsFromWebglTexture(mipMaps: number, webglEngineTexture: InternalTexture, gpuTexture: GPUTexture, width: number, height: number, face: number) {
  836. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, width, height, face);
  837. let faceWidth = width;
  838. let faceHeight = height;
  839. for (let mip = 1; mip <= mipMaps; mip++) {
  840. faceWidth = Math.max(Math.floor(faceWidth / 2), 1);
  841. faceHeight = Math.max(Math.floor(faceHeight / 2), 1);
  842. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, faceWidth, faceHeight, face, mip);
  843. }
  844. }
  845. private _uploadFromWebglTexture(webglEngineTexture: InternalTexture, gpuTexture: GPUTexture, width: number, height: number, face: number, mip: number = 0): void {
  846. let pixels = this._decodeEngine._readTexturePixels(webglEngineTexture, width, height, face, mip);
  847. if (pixels instanceof Float32Array) {
  848. const newPixels = new Uint8ClampedArray(pixels.length);
  849. pixels.forEach((value, index) => newPixels[index] = value * 255);
  850. pixels = newPixels;
  851. }
  852. const textureView: GPUTextureCopyView = {
  853. texture: gpuTexture,
  854. origin: {
  855. x: 0,
  856. y: 0,
  857. z: 0
  858. },
  859. mipLevel: mip,
  860. arrayLayer: Math.max(face, 0),
  861. };
  862. const textureExtent = {
  863. width,
  864. height,
  865. depth: 1
  866. };
  867. const commandEncoder = this._device.createCommandEncoder({});
  868. const rowPitch = Math.ceil(width * 4 / 256) * 256;
  869. let dataBuffer: DataBuffer;
  870. if (rowPitch == width * 4) {
  871. dataBuffer = this._createBuffer(pixels, WebGPUConstants.GPUBufferUsage_TRANSFER_SRC | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  872. const bufferView: GPUBufferCopyView = {
  873. buffer: dataBuffer.underlyingResource,
  874. rowPitch: rowPitch,
  875. imageHeight: height,
  876. offset: 0,
  877. };
  878. commandEncoder.copyBufferToTexture(bufferView, textureView, textureExtent);
  879. } else {
  880. const alignedPixels = new Uint8Array(rowPitch * height);
  881. let pixelsIndex = 0;
  882. for (let y = 0; y < height; ++y) {
  883. for (let x = 0; x < width; ++x) {
  884. let i = x * 4 + y * rowPitch;
  885. alignedPixels[i] = (pixels as any)[pixelsIndex];
  886. alignedPixels[i + 1] = (pixels as any)[pixelsIndex + 1];
  887. alignedPixels[i + 2] = (pixels as any)[pixelsIndex + 2];
  888. alignedPixels[i + 3] = (pixels as any)[pixelsIndex + 3];
  889. pixelsIndex += 4;
  890. }
  891. }
  892. dataBuffer = this._createBuffer(alignedPixels, WebGPUConstants.GPUBufferUsage_TRANSFER_SRC | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  893. const bufferView: GPUBufferCopyView = {
  894. buffer: dataBuffer.underlyingResource,
  895. rowPitch: rowPitch,
  896. imageHeight: height,
  897. offset: 0,
  898. };
  899. commandEncoder.copyBufferToTexture(bufferView, textureView, textureExtent);
  900. }
  901. this._device.getQueue().submit([commandEncoder.finish()]);
  902. this._releaseBuffer(dataBuffer);
  903. }
  904. private _getSamplerFilterDescriptor(internalTexture: InternalTexture): {
  905. magFilter: GPUFilterMode,
  906. minFilter: GPUFilterMode,
  907. mipmapFilter: GPUFilterMode
  908. } {
  909. let magFilter: GPUFilterMode, minFilter: GPUFilterMode, mipmapFilter: GPUFilterMode;
  910. switch (internalTexture.samplingMode) {
  911. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  912. magFilter = WebGPUConstants.GPUFilterMode_linear;
  913. minFilter = WebGPUConstants.GPUFilterMode_linear;
  914. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  915. break;
  916. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  917. magFilter = WebGPUConstants.GPUFilterMode_linear;
  918. minFilter = WebGPUConstants.GPUFilterMode_linear;
  919. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  920. break;
  921. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  922. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  923. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  924. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  925. break;
  926. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  927. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  928. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  929. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  930. break;
  931. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  932. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  933. minFilter = WebGPUConstants.GPUFilterMode_linear;
  934. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  935. break;
  936. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  937. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  938. minFilter = WebGPUConstants.GPUFilterMode_linear;
  939. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  940. break;
  941. case Engine.TEXTURE_NEAREST_LINEAR:
  942. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  943. minFilter = WebGPUConstants.GPUFilterMode_linear;
  944. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  945. break;
  946. case Engine.TEXTURE_NEAREST_NEAREST:
  947. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  948. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  949. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  950. break;
  951. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  952. magFilter = WebGPUConstants.GPUFilterMode_linear;
  953. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  954. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  955. break;
  956. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  957. magFilter = WebGPUConstants.GPUFilterMode_linear;
  958. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  959. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  960. break;
  961. case Engine.TEXTURE_LINEAR_LINEAR:
  962. magFilter = WebGPUConstants.GPUFilterMode_linear;
  963. minFilter = WebGPUConstants.GPUFilterMode_linear;
  964. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  965. break;
  966. case Engine.TEXTURE_LINEAR_NEAREST:
  967. magFilter = WebGPUConstants.GPUFilterMode_linear;
  968. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  969. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  970. break;
  971. default:
  972. magFilter = WebGPUConstants.GPUFilterMode_linear;
  973. minFilter = WebGPUConstants.GPUFilterMode_linear;
  974. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  975. break;
  976. }
  977. return {
  978. magFilter,
  979. minFilter,
  980. mipmapFilter
  981. };
  982. }
  983. private _getWrappingMode(mode: number): GPUAddressMode {
  984. switch (mode) {
  985. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  986. return WebGPUConstants.GPUAddressMode_repeat;
  987. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  988. return WebGPUConstants.GPUAddressMode_clampToEdge;
  989. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  990. return WebGPUConstants.GPUAddressMode_mirrorRepeat;
  991. }
  992. return WebGPUConstants.GPUAddressMode_repeat;
  993. }
  994. private _getSamplerWrappingDescriptor(internalTexture: InternalTexture): {
  995. addressModeU: GPUAddressMode,
  996. addressModeV: GPUAddressMode,
  997. addressModeW: GPUAddressMode
  998. } {
  999. return {
  1000. addressModeU: this._getWrappingMode(internalTexture._cachedWrapU!),
  1001. addressModeV: this._getWrappingMode(internalTexture._cachedWrapV!),
  1002. addressModeW: this._getWrappingMode(internalTexture._cachedWrapR!),
  1003. };
  1004. }
  1005. private _getSamplerDescriptor(internalTexture: InternalTexture): GPUSamplerDescriptor {
  1006. return {
  1007. ...this._getSamplerFilterDescriptor(internalTexture),
  1008. ...this._getSamplerWrappingDescriptor(internalTexture),
  1009. };
  1010. }
  1011. public createTexture(urlArg: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE, onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null, buffer: Nullable<ArrayBuffer | HTMLImageElement> = null, fallBack?: InternalTexture, format?: number): InternalTexture {
  1012. const texture = new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  1013. const url = String(urlArg);
  1014. // TODO WEBGPU. Find a better way.
  1015. // TODO WEBGPU. this._options.textureSize
  1016. texture.url = url;
  1017. texture.generateMipMaps = !noMipmap;
  1018. texture.samplingMode = samplingMode;
  1019. texture.invertY = invertY;
  1020. if (format) {
  1021. texture.format = format;
  1022. }
  1023. let webglEngineTexture: InternalTexture;
  1024. const onLoadInternal = () => {
  1025. texture.isReady = webglEngineTexture.isReady;
  1026. const width = webglEngineTexture.width;
  1027. const height = webglEngineTexture.height;
  1028. texture.width = width;
  1029. texture.height = height;
  1030. texture.baseWidth = width;
  1031. texture.baseHeight = height;
  1032. texture._isRGBD = webglEngineTexture._isRGBD;
  1033. texture._sphericalPolynomial = webglEngineTexture._sphericalPolynomial;
  1034. let mipMaps = Scalar.Log2(Math.max(width, height));
  1035. mipMaps = Math.floor(mipMaps);
  1036. const textureExtent = {
  1037. width,
  1038. height,
  1039. depth: 1
  1040. };
  1041. const textureDescriptor: GPUTextureDescriptor = {
  1042. dimension: WebGPUConstants.GPUTextureDimension_2d,
  1043. format: WebGPUConstants.GPUTextureFormat_rgba8unorm,
  1044. arrayLayerCount: 1,
  1045. mipLevelCount: noMipmap ? 1 : mipMaps + 1,
  1046. sampleCount: 1,
  1047. size: textureExtent,
  1048. usage: WebGPUConstants.GPUTextureUsage_COPY_DST | WebGPUConstants.GPUTextureUsage_SAMPLED
  1049. };
  1050. const gpuTexture = this._device.createTexture(textureDescriptor);
  1051. texture._webGPUTexture = gpuTexture;
  1052. if (noMipmap) {
  1053. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, width, height, -1);
  1054. }
  1055. else {
  1056. this._uploadMipMapsFromWebglTexture(mipMaps, webglEngineTexture, gpuTexture, width, height, -1);
  1057. }
  1058. texture._webGPUTextureView = gpuTexture.createDefaultView();
  1059. webglEngineTexture.dispose();
  1060. texture.onLoadedObservable.notifyObservers(texture);
  1061. texture.onLoadedObservable.clear();
  1062. if (onLoad) {
  1063. onLoad();
  1064. }
  1065. };
  1066. webglEngineTexture = this._decodeEngine.createTexture(urlArg, noMipmap, invertY, scene, samplingMode,
  1067. onLoadInternal, onError, buffer, fallBack, format);
  1068. this._internalTexturesCache.push(texture);
  1069. return texture;
  1070. }
  1071. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, 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, excludeLoaders: Array<IInternalTextureLoader> = []): InternalTexture {
  1072. var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  1073. texture.isCube = true;
  1074. texture.url = rootUrl;
  1075. texture.generateMipMaps = !noMipmap;
  1076. // TODO WEBGPU. Cube Texture Sampling Mode.
  1077. texture.samplingMode = noMipmap ? Constants.TEXTURE_BILINEAR_SAMPLINGMODE : Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1078. texture._lodGenerationScale = lodScale;
  1079. texture._lodGenerationOffset = lodOffset;
  1080. if (!this._doNotHandleContextLost) {
  1081. texture._extension = forcedExtension;
  1082. texture._files = files;
  1083. }
  1084. let webglEngineTexture: InternalTexture;
  1085. const onLoadInternal = () => {
  1086. texture.isReady = webglEngineTexture.isReady;
  1087. const width = webglEngineTexture.width;
  1088. const height = webglEngineTexture.height;
  1089. const depth = 1;
  1090. texture.width = width;
  1091. texture.height = height;
  1092. texture.baseWidth = width;
  1093. texture.baseHeight = height;
  1094. texture.depth = depth;
  1095. texture.baseDepth = depth;
  1096. texture._isRGBD = webglEngineTexture._isRGBD;
  1097. texture._sphericalPolynomial = webglEngineTexture._sphericalPolynomial;
  1098. let mipMaps = Scalar.Log2(width);
  1099. mipMaps = Math.round(mipMaps);
  1100. const textureExtent = {
  1101. width,
  1102. height,
  1103. depth,
  1104. };
  1105. const textureDescriptor: GPUTextureDescriptor = {
  1106. dimension: WebGPUConstants.GPUTextureDimension_2d,
  1107. format: WebGPUConstants.GPUTextureFormat_rgba8unorm,
  1108. arrayLayerCount: 6,
  1109. mipLevelCount: noMipmap ? 1 : mipMaps + 1,
  1110. sampleCount: 1,
  1111. size: textureExtent,
  1112. usage: WebGPUConstants.GPUTextureUsage_COPY_DST | WebGPUConstants.GPUTextureUsage_SAMPLED
  1113. };
  1114. const gpuTexture = this._device.createTexture(textureDescriptor);
  1115. texture._webGPUTexture = gpuTexture;
  1116. const faces = [0, 1, 2, 3, 4, 5];
  1117. for (let face of faces) {
  1118. if (noMipmap) {
  1119. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, width, height, face);
  1120. }
  1121. else {
  1122. this._uploadMipMapsFromWebglTexture(mipMaps, webglEngineTexture, gpuTexture, width, height, face);
  1123. }
  1124. }
  1125. texture._webGPUTextureView = gpuTexture.createView({
  1126. arrayLayerCount: 6,
  1127. dimension: WebGPUConstants.GPUTextureViewDimension_cube,
  1128. format: WebGPUConstants.GPUTextureFormat_rgba8unorm,
  1129. mipLevelCount: noMipmap ? 1 : mipMaps + 1,
  1130. baseArrayLayer: 0,
  1131. baseMipLevel: 0,
  1132. aspect: WebGPUConstants.GPUTextureAspect_all
  1133. } as any);
  1134. webglEngineTexture.dispose();
  1135. onLoad && onLoad();
  1136. };
  1137. webglEngineTexture = this._decodeEngine.createCubeTexture(rootUrl, scene, files, noMipmap, onLoadInternal, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, excludeLoaders);
  1138. this._internalTexturesCache.push(texture);
  1139. return texture;
  1140. }
  1141. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  1142. texture.samplingMode = samplingMode;
  1143. }
  1144. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  1145. // TODO WEBGPU.
  1146. throw "Unimplemented updateDynamicTexture on WebGPU so far";
  1147. }
  1148. public setTexture(channel: number, _: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>, name: string): void {
  1149. if (this._currentEffect) {
  1150. const pipeline = this._currentEffect._pipelineContext as WebGPUPipelineContext;
  1151. if (!texture) {
  1152. pipeline.samplers[name] = null;
  1153. return;
  1154. }
  1155. const internalTexture = texture!.getInternalTexture();
  1156. if (internalTexture) {
  1157. internalTexture._cachedWrapU = texture.wrapU;
  1158. internalTexture._cachedWrapV = texture.wrapV;
  1159. internalTexture._cachedWrapR = texture.wrapR;
  1160. }
  1161. if (pipeline.samplers[name]) {
  1162. pipeline.samplers[name]!.texture = internalTexture!;
  1163. }
  1164. else {
  1165. // TODO WEBGPU. GC + 121 mapping samplers <-> availableSamplers
  1166. const availableSampler = pipeline.availableSamplers[name];
  1167. if (availableSampler) {
  1168. pipeline.samplers[name] = {
  1169. setIndex: availableSampler.setIndex,
  1170. textureBinding: availableSampler.bindingIndex,
  1171. samplerBinding: availableSampler.bindingIndex + 1,
  1172. texture: internalTexture!
  1173. };
  1174. }
  1175. }
  1176. }
  1177. }
  1178. public bindSamplers(effect: Effect): void { }
  1179. public _bindTextureDirectly(target: number, texture: InternalTexture): boolean {
  1180. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  1181. this._boundTexturesCache[this._activeChannel] = texture;
  1182. return true;
  1183. }
  1184. return false;
  1185. }
  1186. /** @hidden */
  1187. public _bindTexture(channel: number, texture: InternalTexture): void {
  1188. if (channel < 0) {
  1189. return;
  1190. }
  1191. this._bindTextureDirectly(0, texture);
  1192. }
  1193. /** @hidden */
  1194. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  1195. }
  1196. /** @hidden */
  1197. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1198. }
  1199. /** @hidden */
  1200. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1201. }
  1202. /** @hidden */
  1203. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  1204. }
  1205. //------------------------------------------------------------------------------
  1206. // Render Target Textures
  1207. //------------------------------------------------------------------------------
  1208. public createRenderTargetTexture(size: any, options: boolean | RenderTargetCreationOptions): InternalTexture {
  1209. let fullOptions = new RenderTargetCreationOptions();
  1210. if (options !== undefined && typeof options === "object") {
  1211. fullOptions.generateMipMaps = options.generateMipMaps;
  1212. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1213. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  1214. fullOptions.type = options.type === undefined ? Constants.TEXTURETYPE_UNSIGNED_INT : options.type;
  1215. fullOptions.samplingMode = options.samplingMode === undefined ? Constants.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  1216. } else {
  1217. fullOptions.generateMipMaps = <boolean>options;
  1218. fullOptions.generateDepthBuffer = true;
  1219. fullOptions.generateStencilBuffer = false;
  1220. fullOptions.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  1221. fullOptions.samplingMode = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1222. }
  1223. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  1224. var width = size.width || size;
  1225. var height = size.height || size;
  1226. texture._depthStencilBuffer = {};
  1227. texture._framebuffer = {};
  1228. texture.baseWidth = width;
  1229. texture.baseHeight = height;
  1230. texture.width = width;
  1231. texture.height = height;
  1232. texture.isReady = true;
  1233. texture.samples = 1;
  1234. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  1235. texture.samplingMode = fullOptions.samplingMode;
  1236. texture.type = fullOptions.type;
  1237. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  1238. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  1239. this._internalTexturesCache.push(texture);
  1240. return texture;
  1241. }
  1242. //------------------------------------------------------------------------------
  1243. // Render Commands
  1244. //------------------------------------------------------------------------------
  1245. /**
  1246. * Begin a new frame
  1247. */
  1248. public beginFrame(): void {
  1249. super.beginFrame();
  1250. this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
  1251. this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
  1252. }
  1253. private _freezeCommands: boolean = false;
  1254. private _frozenCommands: Nullable<GPUCommandBuffer[]> = null;
  1255. public _shouldOnlyUpdateCameras(): boolean {
  1256. return this._frozenCommands !== null;
  1257. }
  1258. /**
  1259. * End the current frame
  1260. */
  1261. public endFrame(): void {
  1262. this._endRenderPass();
  1263. if (this._freezeCommands && this._frozenCommands) {
  1264. this._commandBuffers[0] = this._frozenCommands[0];
  1265. this._commandBuffers[1] = this._frozenCommands[1];
  1266. }
  1267. else {
  1268. this._commandBuffers[0] = this._uploadEncoder.finish();
  1269. this._commandBuffers[1] = this._renderEncoder.finish();
  1270. }
  1271. if (this._freezeCommands && !this._frozenCommands) {
  1272. this._frozenCommands = [ ];
  1273. this._frozenCommands[0] = this._commandBuffers[0];
  1274. this._frozenCommands[1] = this._commandBuffers[1];
  1275. }
  1276. this._device.getQueue().submit(this._commandBuffers);
  1277. super.endFrame();
  1278. }
  1279. /**
  1280. * Freezes the current list of commands to speed up rendering of sub sequent frames.
  1281. */
  1282. public freezeCommands(): void {
  1283. this._freezeCommands = true;
  1284. this._frozenCommands = null;
  1285. }
  1286. /**
  1287. * Freezes the current list of commands to speed up rendering of sub sequent frames.
  1288. */
  1289. public unFreezeCommands(): void {
  1290. this._freezeCommands = false;
  1291. this._frozenCommands = null;
  1292. }
  1293. //------------------------------------------------------------------------------
  1294. // Render Pass
  1295. //------------------------------------------------------------------------------
  1296. private _startMainRenderPass(): void {
  1297. if (this._currentRenderPass) {
  1298. this._endRenderPass();
  1299. }
  1300. // Resolve in case of MSAA
  1301. if (this._options.antialiasing) {
  1302. this._mainColorAttachments[0].resolveTarget = this._swapChain.getCurrentTexture().createDefaultView();
  1303. }
  1304. else {
  1305. this._mainColorAttachments[0].attachment = this._swapChain.getCurrentTexture().createDefaultView();
  1306. }
  1307. this._currentRenderPass = this._renderEncoder.beginRenderPass({
  1308. colorAttachments: this._mainColorAttachments,
  1309. depthStencilAttachment: this._mainDepthAttachment
  1310. });
  1311. }
  1312. private _endRenderPass(): void {
  1313. if (this._currentRenderPass) {
  1314. this._currentRenderPass.endPass();
  1315. this._currentRenderPass = null;
  1316. }
  1317. }
  1318. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1319. if (this._currentRenderTarget) {
  1320. this.unBindFramebuffer(this._currentRenderTarget);
  1321. }
  1322. this._currentRenderTarget = texture;
  1323. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  1324. if (this._cachedViewport && !forceFullscreenViewport) {
  1325. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1326. }
  1327. }
  1328. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1329. this._currentRenderTarget = null;
  1330. if (onBeforeUnbind) {
  1331. if (texture._MSAAFramebuffer) {
  1332. this._currentFramebuffer = texture._framebuffer;
  1333. }
  1334. onBeforeUnbind();
  1335. }
  1336. this._currentFramebuffer = null;
  1337. }
  1338. //------------------------------------------------------------------------------
  1339. // Render
  1340. //------------------------------------------------------------------------------
  1341. private _getTopology(fillMode: number): GPUPrimitiveTopology {
  1342. switch (fillMode) {
  1343. // Triangle views
  1344. case Constants.MATERIAL_TriangleFillMode:
  1345. return WebGPUConstants.GPUPrimitiveTopology_triangleList;
  1346. case Constants.MATERIAL_PointFillMode:
  1347. return WebGPUConstants.GPUPrimitiveTopology_pointList;
  1348. case Constants.MATERIAL_WireFrameFillMode:
  1349. return WebGPUConstants.GPUPrimitiveTopology_lineList;
  1350. // Draw modes
  1351. case Constants.MATERIAL_PointListDrawMode:
  1352. return WebGPUConstants.GPUPrimitiveTopology_pointList;
  1353. case Constants.MATERIAL_LineListDrawMode:
  1354. return WebGPUConstants.GPUPrimitiveTopology_lineList;
  1355. case Constants.MATERIAL_LineLoopDrawMode:
  1356. // return this._gl.LINE_LOOP;
  1357. // TODO WEBGPU. Line Loop Mode
  1358. throw "LineLoop is an unsupported fillmode in WebGPU";
  1359. case Constants.MATERIAL_LineStripDrawMode:
  1360. return WebGPUConstants.GPUPrimitiveTopology_lineStrip;
  1361. case Constants.MATERIAL_TriangleStripDrawMode:
  1362. return WebGPUConstants.GPUPrimitiveTopology_triangleStrip;
  1363. case Constants.MATERIAL_TriangleFanDrawMode:
  1364. // return this._gl.TRIANGLE_FAN;
  1365. // TODO WEBGPU. Triangle Fan Mode
  1366. throw "TriangleFan is an unsupported fillmode in WebGPU";
  1367. default:
  1368. return WebGPUConstants.GPUPrimitiveTopology_triangleList;
  1369. }
  1370. }
  1371. private _getCompareFunction(compareFunction: Nullable<number>): GPUCompareFunction {
  1372. switch (compareFunction) {
  1373. case Constants.ALWAYS:
  1374. return WebGPUConstants.GPUCompareFunction_always;
  1375. case Constants.EQUAL:
  1376. return WebGPUConstants.GPUCompareFunction_equal;
  1377. case Constants.GREATER:
  1378. return WebGPUConstants.GPUCompareFunction_greater;
  1379. case Constants.GEQUAL:
  1380. return WebGPUConstants.GPUCompareFunction_greaterEqual;
  1381. case Constants.LESS:
  1382. return WebGPUConstants.GPUCompareFunction_less;
  1383. case Constants.LEQUAL:
  1384. return WebGPUConstants.GPUCompareFunction_lessEqual;
  1385. case Constants.NEVER:
  1386. return WebGPUConstants.GPUCompareFunction_never;
  1387. case Constants.NOTEQUAL:
  1388. return WebGPUConstants.GPUCompareFunction_notEqual;
  1389. default:
  1390. return WebGPUConstants.GPUCompareFunction_less;
  1391. }
  1392. }
  1393. private _getOpFunction(operation: Nullable<number>, defaultOp: GPUStencilOperation): GPUStencilOperation {
  1394. switch (operation) {
  1395. case Constants.KEEP:
  1396. return WebGPUConstants.GPUStencilOperation_keep;
  1397. case Constants.ZERO:
  1398. return WebGPUConstants.GPUStencilOperation_zero;
  1399. case Constants.REPLACE:
  1400. return WebGPUConstants.GPUStencilOperation_replace;
  1401. case Constants.INVERT:
  1402. return WebGPUConstants.GPUStencilOperation_invert;
  1403. case Constants.INCR:
  1404. return WebGPUConstants.GPUStencilOperation_incrementClamp;
  1405. case Constants.DECR:
  1406. return WebGPUConstants.GPUStencilOperation_decrementClamp;
  1407. case Constants.INCR_WRAP:
  1408. return WebGPUConstants.GPUStencilOperation_incrementWrap;
  1409. case Constants.DECR_WRAP:
  1410. return WebGPUConstants.GPUStencilOperation_decrementWrap;
  1411. default:
  1412. return defaultOp;
  1413. }
  1414. }
  1415. private _getDepthStencilStateDescriptor(): GPUDepthStencilStateDescriptor {
  1416. // TODO WEBGPU. Depth State according to the cached state.
  1417. // And the current render pass attachment setup.
  1418. const stencilFrontBack: GPUStencilStateFaceDescriptor = {
  1419. compare: this._getCompareFunction(this._stencilState.stencilFunc),
  1420. depthFailOp: this._getOpFunction(this._stencilState.stencilOpDepthFail, WebGPUConstants.GPUStencilOperation_keep),
  1421. failOp: this._getOpFunction(this._stencilState.stencilOpStencilFail, WebGPUConstants.GPUStencilOperation_keep),
  1422. passOp: this._getOpFunction(this._stencilState.stencilOpStencilDepthPass, WebGPUConstants.GPUStencilOperation_replace)
  1423. };
  1424. return {
  1425. depthWriteEnabled: this.getDepthWrite(),
  1426. depthCompare: this._getCompareFunction(this.getDepthFunction()),
  1427. format: WebGPUConstants.GPUTextureFormat_depth24plusStencil8,
  1428. stencilFront: stencilFrontBack,
  1429. stencilBack: stencilFrontBack,
  1430. stencilReadMask: this._stencilState.stencilFuncMask,
  1431. stencilWriteMask: this._stencilState.stencilMask,
  1432. };
  1433. }
  1434. /**
  1435. * Set various states to the webGL context
  1436. * @param culling defines backface culling state
  1437. * @param zOffset defines the value to apply to zOffset (0 by default)
  1438. * @param force defines if states must be applied even if cache is up to date
  1439. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  1440. */
  1441. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1442. // Culling
  1443. if (this._depthCullingState.cull !== culling || force) {
  1444. this._depthCullingState.cull = culling;
  1445. }
  1446. // Cull face
  1447. // var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  1448. var cullFace = this.cullBackFaces ? 1 : 2;
  1449. if (this._depthCullingState.cullFace !== cullFace || force) {
  1450. this._depthCullingState.cullFace = cullFace;
  1451. }
  1452. // Z offset
  1453. this.setZOffset(zOffset);
  1454. // Front face
  1455. // var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  1456. var frontFace = reverseSide ? 1 : 2;
  1457. if (this._depthCullingState.frontFace !== frontFace || force) {
  1458. this._depthCullingState.frontFace = frontFace;
  1459. }
  1460. }
  1461. private _getFrontFace(): GPUFrontFace {
  1462. switch (this._depthCullingState.frontFace) {
  1463. case 1:
  1464. return WebGPUConstants.GPUFrontFace_cw;
  1465. default:
  1466. return WebGPUConstants.GPUFrontFace_ccw;
  1467. }
  1468. }
  1469. private _getCullMode(): GPUCullMode {
  1470. if (this._depthCullingState.cull === false) {
  1471. return WebGPUConstants.GPUCullMode_none;
  1472. }
  1473. if (this._depthCullingState.cullFace === 2) {
  1474. return WebGPUConstants.GPUCullMode_front;
  1475. }
  1476. else {
  1477. return WebGPUConstants.GPUCullMode_back;
  1478. }
  1479. }
  1480. private _getRasterizationStateDescriptor(): GPURasterizationStateDescriptor {
  1481. // TODO WEBGPU. Cull State according to the cached state.
  1482. // And the current render pass attachment setup.
  1483. return {
  1484. frontFace: this._getFrontFace(),
  1485. cullMode: this._getCullMode(),
  1486. depthBias: this._depthCullingState.zOffset,
  1487. // depthBiasClamp: 0,
  1488. // depthBiasSlopeScale: 0,
  1489. };
  1490. }
  1491. private _getWriteMask(): number {
  1492. if (this.__colorWrite) {
  1493. return WebGPUConstants.GPUColorWriteBits_ALL;
  1494. }
  1495. return WebGPUConstants.GPUColorWriteBits_NONE;
  1496. }
  1497. /**
  1498. * Sets the current alpha mode
  1499. * @param mode defines the mode to use (one of the Engine.ALPHA_XXX)
  1500. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  1501. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  1502. */
  1503. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  1504. if (this._alphaMode === mode) {
  1505. return;
  1506. }
  1507. switch (mode) {
  1508. case Engine.ALPHA_DISABLE:
  1509. this._alphaState.alphaBlend = false;
  1510. break;
  1511. case Engine.ALPHA_PREMULTIPLIED:
  1512. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1513. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 1);
  1514. this._alphaState.alphaBlend = true;
  1515. break;
  1516. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  1517. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  1518. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 0x0303);
  1519. this._alphaState.alphaBlend = true;
  1520. break;
  1521. case Engine.ALPHA_COMBINE:
  1522. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1523. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0303, 1, 1);
  1524. this._alphaState.alphaBlend = true;
  1525. break;
  1526. case Engine.ALPHA_ONEONE:
  1527. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1528. this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1);
  1529. this._alphaState.alphaBlend = true;
  1530. break;
  1531. case Engine.ALPHA_ADD:
  1532. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1533. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 1, 0, 1);
  1534. this._alphaState.alphaBlend = true;
  1535. break;
  1536. case Engine.ALPHA_SUBTRACT:
  1537. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1538. this._alphaState.setAlphaBlendFunctionParameters(0, 0x0301, 1, 1);
  1539. this._alphaState.alphaBlend = true;
  1540. break;
  1541. case Engine.ALPHA_MULTIPLY:
  1542. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1543. this._alphaState.setAlphaBlendFunctionParameters(0x0306, 0, 1, 1);
  1544. this._alphaState.alphaBlend = true;
  1545. break;
  1546. case Engine.ALPHA_MAXIMIZED:
  1547. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1548. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0301, 1, 1);
  1549. this._alphaState.alphaBlend = true;
  1550. break;
  1551. case Engine.ALPHA_INTERPOLATE:
  1552. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  1553. this._alphaState.setAlphaBlendFunctionParameters(0x8001, 0x8002, 0x8003, 0x8004);
  1554. this._alphaState.alphaBlend = true;
  1555. break;
  1556. case Engine.ALPHA_SCREENMODE:
  1557. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  1558. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0301, 1, 0x0303);
  1559. this._alphaState.alphaBlend = true;
  1560. break;
  1561. }
  1562. if (!noDepthWriteChange) {
  1563. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1564. }
  1565. this._alphaMode = mode;
  1566. }
  1567. private _getAphaBlendOperation(operation: Nullable<number>): GPUBlendOperation {
  1568. switch (operation) {
  1569. case 0x8006:
  1570. return WebGPUConstants.GPUBlendOperation_add;
  1571. case 0x800A:
  1572. return WebGPUConstants.GPUBlendOperation_substract;
  1573. case 0x800B:
  1574. return WebGPUConstants.GPUBlendOperation_reverseSubtract;
  1575. default:
  1576. return WebGPUConstants.GPUBlendOperation_add;
  1577. }
  1578. }
  1579. private _getAphaBlendFactor(factor: Nullable<number>): GPUBlendFactor {
  1580. switch (factor) {
  1581. case 0:
  1582. return WebGPUConstants.GPUBlendFactor_zero;
  1583. case 1:
  1584. return WebGPUConstants.GPUBlendFactor_one;
  1585. case 0x0300:
  1586. return WebGPUConstants.GPUBlendFactor_srcColor;
  1587. case 0x0301:
  1588. return WebGPUConstants.GPUBlendFactor_oneMinusSrcColor;
  1589. case 0x0302:
  1590. return WebGPUConstants.GPUBlendFactor_srcAlpha;
  1591. case 0x0303:
  1592. return WebGPUConstants.GPUBlendFactor_oneMinusSrcAlpha;
  1593. case 0x0304:
  1594. return WebGPUConstants.GPUBlendFactor_dstAlpha;
  1595. case 0x0305:
  1596. return WebGPUConstants.GPUBlendFactor_oneMinusDstAlpha;
  1597. case 0x0306:
  1598. return WebGPUConstants.GPUBlendFactor_dstColor;
  1599. case 0x0307:
  1600. return WebGPUConstants.GPUBlendFactor_oneMinusDstColor;
  1601. case 0x0308:
  1602. return WebGPUConstants.GPUBlendFactor_srcAlphaSaturated;
  1603. case 0x8001:
  1604. return WebGPUConstants.GPUBlendFactor_blendColor;
  1605. case 0x8002:
  1606. return WebGPUConstants.GPUBlendFactor_oneMinusBlendColor;
  1607. case 0x8003:
  1608. return WebGPUConstants.GPUBlendFactor_blendColor;
  1609. case 0x8004:
  1610. return WebGPUConstants.GPUBlendFactor_oneMinusBlendColor;
  1611. default:
  1612. return WebGPUConstants.GPUBlendFactor_one;
  1613. }
  1614. }
  1615. private _getAphaBlendState(): GPUBlendDescriptor {
  1616. if (!this._alphaState.alphaBlend) {
  1617. return { };
  1618. }
  1619. return {
  1620. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[2]),
  1621. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[3]),
  1622. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[1]),
  1623. };
  1624. }
  1625. private _getColorBlendState(): GPUBlendDescriptor {
  1626. if (!this._alphaState.alphaBlend) {
  1627. return { };
  1628. }
  1629. return {
  1630. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[0]),
  1631. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[1]),
  1632. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[0]),
  1633. };
  1634. }
  1635. private _getColorStateDescriptors(): GPUColorStateDescriptor[] {
  1636. // TODO WEBGPU. Manage Multi render target.
  1637. return [{
  1638. format: this._options.swapChainFormat!,
  1639. alphaBlend: this._getAphaBlendState(),
  1640. colorBlend: this._getColorBlendState(),
  1641. writeMask: this._getWriteMask(),
  1642. }];
  1643. }
  1644. private _getStages(): GPURenderPipelineStageDescriptor {
  1645. const gpuPipeline = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1646. return gpuPipeline.stages!;
  1647. }
  1648. private _getVertexInputDescriptorFormat(vertexBuffer: VertexBuffer): GPUVertexFormat {
  1649. const kind = vertexBuffer.getKind();
  1650. const type = vertexBuffer.type;
  1651. const normalized = vertexBuffer.normalized;
  1652. const size = vertexBuffer.getSize();
  1653. switch (type) {
  1654. case VertexBuffer.BYTE:
  1655. switch (size) {
  1656. case 2:
  1657. return normalized ? WebGPUConstants.GPUVertexFormat_char2norm : WebGPUConstants.GPUVertexFormat_char2;
  1658. case 4:
  1659. return normalized ? WebGPUConstants.GPUVertexFormat_char4norm : WebGPUConstants.GPUVertexFormat_char4;
  1660. }
  1661. case VertexBuffer.UNSIGNED_BYTE:
  1662. switch (size) {
  1663. case 2:
  1664. return normalized ? WebGPUConstants.GPUVertexFormat_uchar2norm : WebGPUConstants.GPUVertexFormat_uchar2;
  1665. case 4:
  1666. return normalized ? WebGPUConstants.GPUVertexFormat_uchar4norm : WebGPUConstants.GPUVertexFormat_uchar4;
  1667. }
  1668. case VertexBuffer.SHORT:
  1669. switch (size) {
  1670. case 2:
  1671. return normalized ? WebGPUConstants.GPUVertexFormat_short2norm : WebGPUConstants.GPUVertexFormat_short2;
  1672. case 4:
  1673. return normalized ? WebGPUConstants.GPUVertexFormat_short4norm : WebGPUConstants.GPUVertexFormat_short4;
  1674. }
  1675. case VertexBuffer.UNSIGNED_SHORT:
  1676. switch (size) {
  1677. case 2:
  1678. return normalized ? WebGPUConstants.GPUVertexFormat_ushort2norm : WebGPUConstants.GPUVertexFormat_ushort2;
  1679. case 4:
  1680. return normalized ? WebGPUConstants.GPUVertexFormat_ushort4norm : WebGPUConstants.GPUVertexFormat_ushort4;
  1681. }
  1682. case VertexBuffer.INT:
  1683. switch (size) {
  1684. case 1:
  1685. return WebGPUConstants.GPUVertexFormat_int;
  1686. case 2:
  1687. return WebGPUConstants.GPUVertexFormat_int2;
  1688. case 3:
  1689. return WebGPUConstants.GPUVertexFormat_int3;
  1690. case 4:
  1691. return WebGPUConstants.GPUVertexFormat_int4;
  1692. }
  1693. case VertexBuffer.UNSIGNED_INT:
  1694. switch (size) {
  1695. case 1:
  1696. return WebGPUConstants.GPUVertexFormat_uint;
  1697. case 2:
  1698. return WebGPUConstants.GPUVertexFormat_uint2;
  1699. case 3:
  1700. return WebGPUConstants.GPUVertexFormat_uint3;
  1701. case 4:
  1702. return WebGPUConstants.GPUVertexFormat_uint4;
  1703. }
  1704. case VertexBuffer.FLOAT:
  1705. switch (size) {
  1706. case 1:
  1707. return WebGPUConstants.GPUVertexFormat_float;
  1708. case 2:
  1709. return WebGPUConstants.GPUVertexFormat_float2;
  1710. case 3:
  1711. return WebGPUConstants.GPUVertexFormat_float3;
  1712. case 4:
  1713. return WebGPUConstants.GPUVertexFormat_float4;
  1714. }
  1715. }
  1716. throw new Error("Invalid Format '" + kind + "'");
  1717. }
  1718. private _getVertexInputDescriptor(): GPUVertexInputDescriptor {
  1719. const descriptors: GPUVertexBufferDescriptor[] = [];
  1720. const effect = this._currentEffect!;
  1721. const attributes = effect.getAttributesNames();
  1722. for (var index = 0; index < attributes.length; index++) {
  1723. const location = effect.getAttributeLocation(index);
  1724. if (location >= 0) {
  1725. const vertexBuffer = this._currentVertexBuffers![attributes[index]];
  1726. if (!vertexBuffer) {
  1727. continue;
  1728. }
  1729. const positionAttributeDescriptor: GPUVertexAttributeDescriptor = {
  1730. shaderLocation: location,
  1731. offset: 0, // not available in WebGL
  1732. format: this._getVertexInputDescriptorFormat(vertexBuffer),
  1733. };
  1734. // TODO WEBGPU. Factorize the one with the same underlying buffer.
  1735. // manage interleaved and instances.
  1736. const vertexBufferDescriptor: GPUVertexBufferDescriptor = {
  1737. stride: vertexBuffer.byteStride,
  1738. stepMode: vertexBuffer.getIsInstanced() ? WebGPUConstants.GPUInputStepMode_instance : WebGPUConstants.GPUInputStepMode_vertex,
  1739. attributeSet: [positionAttributeDescriptor]
  1740. };
  1741. descriptors.push(vertexBufferDescriptor);
  1742. }
  1743. }
  1744. if (!this._currentIndexBuffer) {
  1745. return {
  1746. indexFormat: WebGPUConstants.GPUIndexFormat_uint32,
  1747. vertexBuffers: descriptors
  1748. };
  1749. }
  1750. const inputStateDescriptor: GPUVertexInputDescriptor = {
  1751. indexFormat: this._currentIndexBuffer!.is32Bits ? WebGPUConstants.GPUIndexFormat_uint32 : WebGPUConstants.GPUIndexFormat_uint16,
  1752. vertexBuffers: descriptors
  1753. };
  1754. return inputStateDescriptor;
  1755. }
  1756. private _getPipelineLayout(): GPUPipelineLayout {
  1757. const bindGroupLayouts: GPUBindGroupLayout[] = [];
  1758. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1759. for (let i = 0; i < webgpuPipelineContext.orderedUBOsAndSamplers.length; i++) {
  1760. const setDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i];
  1761. if (setDefinition === undefined) {
  1762. const bindings: GPUBindGroupLayoutBinding[] = [];
  1763. const uniformsBindGroupLayout = this._device.createBindGroupLayout({
  1764. bindings,
  1765. });
  1766. bindGroupLayouts[i] = uniformsBindGroupLayout;
  1767. continue;
  1768. }
  1769. const bindings: GPUBindGroupLayoutBinding[] = [];
  1770. for (let j = 0; j < setDefinition.length; j++) {
  1771. const bindingDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i][j];
  1772. if (bindingDefinition === undefined) {
  1773. continue;
  1774. }
  1775. // TODO WEBGPU. Optimize shared samplers visibility for vertex/framgent.
  1776. if (bindingDefinition.isSampler) {
  1777. bindings.push({
  1778. binding: j,
  1779. visibility: WebGPUConstants.GPUShaderStageBit_VERTEX | WebGPUConstants.GPUShaderStageBit_FRAGMENT,
  1780. type: WebGPUConstants.GPUBindingType_sampledTexture,
  1781. }, {
  1782. // TODO WEBGPU. No Magic + 1.
  1783. binding: j + 1,
  1784. visibility: WebGPUConstants.GPUShaderStageBit_VERTEX | WebGPUConstants.GPUShaderStageBit_FRAGMENT,
  1785. type: WebGPUConstants.GPUBindingType_sampler
  1786. });
  1787. }
  1788. else {
  1789. bindings.push({
  1790. binding: j,
  1791. visibility: WebGPUConstants.GPUShaderStageBit_VERTEX | WebGPUConstants.GPUShaderStageBit_FRAGMENT,
  1792. type: WebGPUConstants.GPUBindingType_uniformBuffer,
  1793. });
  1794. }
  1795. }
  1796. if (bindings.length > 0) {
  1797. const uniformsBindGroupLayout = this._device.createBindGroupLayout({
  1798. bindings,
  1799. });
  1800. bindGroupLayouts[i] = uniformsBindGroupLayout;
  1801. }
  1802. }
  1803. webgpuPipelineContext.bindGroupLayouts = bindGroupLayouts;
  1804. return this._device.createPipelineLayout({ bindGroupLayouts });
  1805. }
  1806. private _getRenderPipeline(fillMode: number): GPURenderPipeline {
  1807. // This is wrong to cache this way but workarounds the need of cache in the simple demo context.
  1808. const gpuPipeline = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1809. if (gpuPipeline.renderPipeline) {
  1810. return gpuPipeline.renderPipeline;
  1811. }
  1812. // Unsupported at the moment but needs to be extracted from the MSAA param.
  1813. const topology = this._getTopology(fillMode);
  1814. const rasterizationStateDescriptor = this._getRasterizationStateDescriptor();
  1815. const depthStateDescriptor = this._getDepthStencilStateDescriptor();
  1816. const colorStateDescriptors = this._getColorStateDescriptors();
  1817. const stages = this._getStages();
  1818. const inputStateDescriptor = this._getVertexInputDescriptor();
  1819. const pipelineLayout = this._getPipelineLayout();
  1820. gpuPipeline.renderPipeline = this._device.createRenderPipeline({
  1821. sampleCount: this._mainPassSampleCount,
  1822. primitiveTopology: topology,
  1823. rasterizationState: rasterizationStateDescriptor,
  1824. depthStencilState: depthStateDescriptor,
  1825. colorStates: colorStateDescriptors,
  1826. ...stages,
  1827. vertexInput: inputStateDescriptor,
  1828. layout: pipelineLayout,
  1829. });
  1830. return gpuPipeline.renderPipeline;
  1831. }
  1832. private _getVertexInputsToRender(): IWebGPUPipelineContextVertexInputsCache {
  1833. const effect = this._currentEffect!;
  1834. const gpuContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1835. let vertexInputs = gpuContext.vertexInputs;
  1836. if (vertexInputs) {
  1837. return vertexInputs;
  1838. }
  1839. vertexInputs = {
  1840. indexBuffer: null,
  1841. indexOffset: 0,
  1842. vertexStartSlot: 0,
  1843. vertexBuffers: [],
  1844. vertexOffsets: [],
  1845. };
  1846. gpuContext.vertexInputs = vertexInputs;
  1847. if (this._currentIndexBuffer) {
  1848. // TODO WEBGPU. Check if cache would be worth it.
  1849. vertexInputs.indexBuffer = this._currentIndexBuffer.underlyingResource;
  1850. vertexInputs.indexOffset = 0;
  1851. }
  1852. else {
  1853. vertexInputs.indexBuffer = null;
  1854. }
  1855. const attributes = effect.getAttributesNames();
  1856. for (var index = 0; index < attributes.length; index++) {
  1857. const order = effect.getAttributeLocation(index);
  1858. if (order >= 0) {
  1859. const vertexBuffer = this._currentVertexBuffers![attributes[index]];
  1860. if (!vertexBuffer) {
  1861. continue;
  1862. }
  1863. var buffer = vertexBuffer.getBuffer();
  1864. if (buffer) {
  1865. vertexInputs.vertexBuffers.push(buffer.underlyingResource);
  1866. vertexInputs.vertexOffsets.push(vertexBuffer.byteOffset);
  1867. }
  1868. }
  1869. }
  1870. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  1871. return vertexInputs;
  1872. }
  1873. private _getBindGroupsToRender(): GPUBindGroup[] {
  1874. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1875. let bindGroups = webgpuPipelineContext.bindGroups;
  1876. if (bindGroups) {
  1877. if (webgpuPipelineContext.uniformBuffer) {
  1878. webgpuPipelineContext.uniformBuffer.update();
  1879. }
  1880. return bindGroups;
  1881. }
  1882. if (webgpuPipelineContext.uniformBuffer) {
  1883. this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer()!, 0, "LeftOver");
  1884. webgpuPipelineContext.uniformBuffer.update();
  1885. }
  1886. bindGroups = [];
  1887. webgpuPipelineContext.bindGroups = bindGroups;
  1888. const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts;
  1889. for (let i = 0; i < webgpuPipelineContext.orderedUBOsAndSamplers.length; i++) {
  1890. const setDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i];
  1891. if (setDefinition === undefined) {
  1892. const groupLayout = bindGroupLayouts[i];
  1893. if (groupLayout) {
  1894. bindGroups[i] = this._device.createBindGroup({
  1895. layout: groupLayout,
  1896. bindings: [],
  1897. });
  1898. }
  1899. continue;
  1900. }
  1901. const bindings: GPUBindGroupBinding[] = [];
  1902. for (let j = 0; j < setDefinition.length; j++) {
  1903. const bindingDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i][j];
  1904. if (bindingDefinition === undefined) {
  1905. continue;
  1906. }
  1907. // TODO WEBGPU. Authorize shared samplers and Vertex Textures.
  1908. if (bindingDefinition.isSampler) {
  1909. const bindingInfo = webgpuPipelineContext.samplers[bindingDefinition.name];
  1910. if (bindingInfo) {
  1911. if (!bindingInfo.texture._webGPUSampler) {
  1912. const samplerDescriptor: GPUSamplerDescriptor = this._getSamplerDescriptor(bindingInfo.texture!);
  1913. const gpuSampler = this._device.createSampler(samplerDescriptor);
  1914. bindingInfo.texture._webGPUSampler = gpuSampler;
  1915. }
  1916. bindings.push({
  1917. binding: bindingInfo.textureBinding,
  1918. resource: bindingInfo.texture._webGPUTextureView!,
  1919. }, {
  1920. binding: bindingInfo.samplerBinding,
  1921. resource: bindingInfo.texture._webGPUSampler!,
  1922. });
  1923. }
  1924. else {
  1925. Logger.Error("Sampler has not been bound: " + bindingDefinition.name);
  1926. }
  1927. }
  1928. else {
  1929. const dataBuffer = this._uniformsBuffers[bindingDefinition.name];
  1930. if (dataBuffer) {
  1931. const webgpuBuffer = dataBuffer.underlyingResource as GPUBuffer;
  1932. bindings.push({
  1933. binding: j,
  1934. resource: {
  1935. buffer: webgpuBuffer,
  1936. offset: 0,
  1937. size: dataBuffer.capacity,
  1938. },
  1939. });
  1940. }
  1941. else {
  1942. Logger.Error("UBO has not been bound: " + bindingDefinition.name);
  1943. }
  1944. }
  1945. }
  1946. const groupLayout = bindGroupLayouts[i];
  1947. if (groupLayout) {
  1948. bindGroups[i] = this._device.createBindGroup({
  1949. layout: groupLayout,
  1950. bindings,
  1951. });
  1952. }
  1953. }
  1954. return bindGroups;
  1955. }
  1956. private _bindVertexInputs(vertexInputs: IWebGPUPipelineContextVertexInputsCache): void {
  1957. const renderPass = this._currentRenderPass!;
  1958. if (vertexInputs.indexBuffer) {
  1959. // TODO WEBGPU. Check if cache would be worth it.
  1960. renderPass.setIndexBuffer(vertexInputs.indexBuffer, vertexInputs.indexOffset);
  1961. }
  1962. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  1963. this._currentRenderPass!.setVertexBuffers(vertexInputs.vertexStartSlot, vertexInputs.vertexBuffers, vertexInputs.vertexOffsets);
  1964. }
  1965. private _setRenderBindGroups(bindGroups: GPUBindGroup[]): void {
  1966. // TODO WEBGPU. Only set groups if changes happened.
  1967. const renderPass = this._currentRenderPass!;
  1968. for (let i = 0; i < bindGroups.length; i++) {
  1969. renderPass.setBindGroup(i, bindGroups[i]);
  1970. }
  1971. }
  1972. private _setRenderPipeline(fillMode: number): void {
  1973. // TODO WEBGPU. Add dynamicity to the data.
  1974. const pipeline = this._getRenderPipeline(fillMode);
  1975. this._currentRenderPass!.setPipeline(pipeline);
  1976. const vertexInputs = this._getVertexInputsToRender();
  1977. this._bindVertexInputs(vertexInputs);
  1978. const bindGroups = this._getBindGroupsToRender();
  1979. this._setRenderBindGroups(bindGroups);
  1980. if (this._alphaState.alphaBlend && this._alphaState._isBlendConstantsDirty) {
  1981. this._currentRenderPass!.setBlendColor(this._alphaState._blendConstants as any);
  1982. }
  1983. }
  1984. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount: number = 1): void {
  1985. this._setRenderPipeline(fillMode);
  1986. this._currentRenderPass!.drawIndexed(indexCount, instancesCount, indexStart, 0, 0);
  1987. }
  1988. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount: number = 1): void {
  1989. this._currentIndexBuffer = null;
  1990. this._setRenderPipeline(fillMode);
  1991. this._currentRenderPass!.draw(verticesCount, instancesCount, verticesStart, 0);
  1992. }
  1993. /**
  1994. * Force a specific size of the canvas
  1995. * @param width defines the new canvas' width
  1996. * @param height defines the new canvas' height
  1997. */
  1998. public setSize(width: number, height: number): void {
  1999. super.setSize(width, height);
  2000. // TODO WEBGPU. Disposeold attachements.
  2001. this._initializeMainAttachments();
  2002. }
  2003. //------------------------------------------------------------------------------
  2004. // Dispose
  2005. //------------------------------------------------------------------------------
  2006. /**
  2007. * Dispose and release all associated resources
  2008. */
  2009. public dispose(): void {
  2010. this._decodeEngine.dispose();
  2011. this._compiledShaders = { };
  2012. if (this._mainTexture) {
  2013. this._mainTexture.destroy();
  2014. }
  2015. if (this._depthTexture) {
  2016. this._depthTexture.destroy();
  2017. }
  2018. super.dispose();
  2019. }
  2020. //------------------------------------------------------------------------------
  2021. // Misc
  2022. //------------------------------------------------------------------------------
  2023. public getRenderWidth(useScreen = false): number {
  2024. if (!useScreen && this._currentRenderTarget) {
  2025. return this._currentRenderTarget.width;
  2026. }
  2027. return this._canvas.width;
  2028. }
  2029. public getRenderHeight(useScreen = false): number {
  2030. if (!useScreen && this._currentRenderTarget) {
  2031. return this._currentRenderTarget.height;
  2032. }
  2033. return this._canvas.height;
  2034. }
  2035. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  2036. return this._canvas;
  2037. }
  2038. //------------------------------------------------------------------------------
  2039. // Errors
  2040. //------------------------------------------------------------------------------
  2041. public getError(): number {
  2042. // TODO WEBGPU. from the webgpu errors.
  2043. return 0;
  2044. }
  2045. //------------------------------------------------------------------------------
  2046. // Unused WebGPU
  2047. //------------------------------------------------------------------------------
  2048. public areAllEffectsReady(): boolean {
  2049. // TODO WEBGPU.
  2050. // No parallel shader compilation.
  2051. return true;
  2052. }
  2053. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  2054. // TODO WEBGPU.
  2055. // No parallel shader compilation.
  2056. // No Async, so direct launch
  2057. action();
  2058. }
  2059. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  2060. // TODO WEBGPU.
  2061. // No parallel shader compilation.
  2062. return true;
  2063. }
  2064. public _getUnpackAlignement(): number {
  2065. return 1;
  2066. }
  2067. public _unpackFlipY(value: boolean) { }
  2068. // TODO WEBGPU. All of this should go once engine split with baseEngine.
  2069. public applyStates() {
  2070. // TODO WEBGPU. Apply States dynamically.
  2071. // This is done at the pipeline creation level for the moment...
  2072. }
  2073. /** @hidden */
  2074. public _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  2075. throw "_getSamplingParameters is not available in WebGPU";
  2076. }
  2077. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  2078. }
  2079. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2080. return [];
  2081. }
  2082. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  2083. }
  2084. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  2085. }
  2086. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  2087. }
  2088. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  2089. }
  2090. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  2091. }
  2092. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  2093. }
  2094. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  2095. }
  2096. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  2097. }
  2098. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  2099. }
  2100. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  2101. }
  2102. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  2103. }
  2104. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  2105. }
  2106. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  2107. }
  2108. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  2109. }
  2110. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  2111. }
  2112. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  2113. }
  2114. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  2115. }
  2116. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  2117. }
  2118. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  2119. }
  2120. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  2121. }
  2122. }