webgpuEngine.ts 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485
  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. this._mainColorAttachments[0].loadValue = backBuffer ? color : WebGPUConstants.GPULoadOp_load;
  432. this._mainDepthAttachment.depthLoadValue = depth ? this._clearDepthValue : WebGPUConstants.GPULoadOp_load;
  433. this._mainDepthAttachment.stencilLoadValue = stencil ? this._clearStencilValue : WebGPUConstants.GPULoadOp_load;
  434. // TODO WEBGPU. Where to store GPUOpStore ???
  435. // TODO WEBGPU. Should be main or rtt with a frame buffer like object.
  436. this._startMainRenderPass();
  437. }
  438. //------------------------------------------------------------------------------
  439. // WebGPU Buffers
  440. //------------------------------------------------------------------------------
  441. private _createBuffer(view: ArrayBufferView, flags: GPUBufferUsageFlags): DataBuffer {
  442. const padding = view.byteLength % 4;
  443. const verticesBufferDescriptor = {
  444. size: view.byteLength + padding,
  445. usage: flags
  446. };
  447. const buffer = this._device.createBuffer(verticesBufferDescriptor);
  448. const dataBuffer = new WebGPUDataBuffer(buffer);
  449. dataBuffer.references = 1;
  450. dataBuffer.capacity = view.byteLength;
  451. this._setSubData(dataBuffer, 0, view);
  452. return dataBuffer;
  453. }
  454. private _setSubData(dataBuffer: WebGPUDataBuffer, dstByteOffset: number, src: ArrayBufferView, srcByteOffset = 0, byteLength = 0): void {
  455. const buffer = dataBuffer.underlyingResource as GPUBuffer;
  456. byteLength = byteLength || src.byteLength;
  457. byteLength = Math.min(byteLength, dataBuffer.capacity - dstByteOffset);
  458. // After Migration to Canary
  459. // This would do from PR #261
  460. let chunkStart = src.byteOffset + srcByteOffset;
  461. let chunkEnd = chunkStart + byteLength;
  462. // 4 bytes alignments for upload
  463. const padding = byteLength % 4;
  464. if (padding !== 0) {
  465. const tempView = new Uint8Array(src.buffer.slice(chunkStart, chunkEnd));
  466. src = new Uint8Array(byteLength + padding);
  467. tempView.forEach((element, index) => {
  468. (src as Uint8Array)[index] = element;
  469. });
  470. srcByteOffset = 0;
  471. chunkStart = 0;
  472. chunkEnd = byteLength + padding;
  473. byteLength = byteLength + padding;
  474. }
  475. // Chunk
  476. const maxChunk = 1024 * 1024 * 15;
  477. let offset = 0;
  478. while ((chunkEnd - (chunkStart + offset)) > maxChunk) {
  479. // TODO WEBGPU.
  480. // Deprecated soon to be removed... replace by mappedBuffers
  481. buffer.setSubData(dstByteOffset + offset, src, srcByteOffset + offset, maxChunk);
  482. offset += maxChunk;
  483. }
  484. // TODO WEBGPU.
  485. // Deprecated soon to be removed... replace by mappedBuffers
  486. buffer.setSubData(dstByteOffset + offset, src, srcByteOffset + offset, byteLength - offset);
  487. }
  488. //------------------------------------------------------------------------------
  489. // Vertex/Index Buffers
  490. //------------------------------------------------------------------------------
  491. public createVertexBuffer(data: DataArray): DataBuffer {
  492. let view: ArrayBufferView;
  493. if (data instanceof Array) {
  494. view = new Float32Array(data);
  495. }
  496. else if (data instanceof ArrayBuffer) {
  497. view = new Uint8Array(data);
  498. }
  499. else {
  500. view = data;
  501. }
  502. const dataBuffer = this._createBuffer(view, WebGPUConstants.GPUBufferUsage_VERTEX | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  503. return dataBuffer;
  504. }
  505. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  506. // TODO WEBGPU.
  507. return this.createVertexBuffer(data);
  508. }
  509. public updateDynamicVertexBuffer(vertexBuffer: DataBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  510. const dataBuffer = vertexBuffer as WebGPUDataBuffer;
  511. if (byteOffset === undefined) {
  512. byteOffset = 0;
  513. }
  514. let view: ArrayBufferView;
  515. if (byteLength === undefined) {
  516. if (data instanceof Array) {
  517. view = new Float32Array(data);
  518. }
  519. else if (data instanceof ArrayBuffer) {
  520. view = new Uint8Array(data);
  521. }
  522. else {
  523. view = data;
  524. }
  525. byteLength = view.byteLength;
  526. } else {
  527. if (data instanceof Array) {
  528. view = new Float32Array(data);
  529. }
  530. else if (data instanceof ArrayBuffer) {
  531. view = new Uint8Array(data);
  532. }
  533. else {
  534. view = data;
  535. }
  536. }
  537. this._setSubData(dataBuffer, byteOffset, view, 0, byteLength);
  538. }
  539. public createIndexBuffer(data: IndicesArray): DataBuffer {
  540. let is32Bits = true;
  541. let view: ArrayBufferView;
  542. if (data instanceof Uint32Array || data instanceof Int32Array) {
  543. view = data;
  544. }
  545. else if (data instanceof Uint16Array) {
  546. view = data;
  547. is32Bits = false;
  548. }
  549. else {
  550. if (data.length > 65535) {
  551. view = new Uint32Array(data);
  552. }
  553. else {
  554. view = new Uint16Array(data);
  555. is32Bits = false;
  556. }
  557. }
  558. const dataBuffer = this._createBuffer(view, WebGPUConstants.GPUBufferUsage_INDEX | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  559. dataBuffer.is32Bits = is32Bits;
  560. return dataBuffer;
  561. }
  562. public updateDynamicIndexBuffer(indexBuffer: DataBuffer, indices: IndicesArray, offset: number = 0): void {
  563. const gpuBuffer = indexBuffer as WebGPUDataBuffer;
  564. // TODO WEBGPU. Manage buffer morphing from small int to bigint.
  565. var view: ArrayBufferView;
  566. if (indices instanceof Uint16Array) {
  567. if (indexBuffer.is32Bits) {
  568. view = Uint32Array.from(indices);
  569. }
  570. else {
  571. view = indices;
  572. }
  573. }
  574. else if (indices instanceof Uint32Array) {
  575. if (indexBuffer.is32Bits) {
  576. view = indices;
  577. }
  578. else {
  579. view = Uint16Array.from(indices);
  580. }
  581. }
  582. else {
  583. if (indexBuffer.is32Bits) {
  584. view = new Uint32Array(indices);
  585. }
  586. else {
  587. view = new Uint16Array(indices);
  588. }
  589. }
  590. // TODO WEBGPU. check if offset is in bytes ???
  591. this._setSubData(gpuBuffer, offset, view);
  592. }
  593. public bindBuffersDirectly(vertexBuffer: DataBuffer, indexBuffer: DataBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  594. throw "Not implemented on WebGPU so far.";
  595. }
  596. public updateAndBindInstancesBuffer(instancesBuffer: DataBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  597. throw "Not implemented on WebGPU so far.";
  598. }
  599. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<DataBuffer>, effect: Effect): void {
  600. this._currentIndexBuffer = indexBuffer;
  601. this._currentVertexBuffers = vertexBuffers;
  602. }
  603. /** @hidden */
  604. public _releaseBuffer(buffer: DataBuffer): boolean {
  605. buffer.references--;
  606. if (buffer.references === 0) {
  607. (buffer.underlyingResource as GPUBuffer).destroy();
  608. return true;
  609. }
  610. return false;
  611. }
  612. //------------------------------------------------------------------------------
  613. // UBO
  614. //------------------------------------------------------------------------------
  615. public createUniformBuffer(elements: FloatArray): DataBuffer {
  616. let view: Float32Array;
  617. if (elements instanceof Array) {
  618. view = new Float32Array(elements);
  619. }
  620. else {
  621. view = elements;
  622. }
  623. const dataBuffer = this._createBuffer(view, WebGPUConstants.GPUBufferUsage_UNIFORM | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  624. return dataBuffer;
  625. }
  626. public createDynamicUniformBuffer(elements: FloatArray): DataBuffer {
  627. // TODO WEBGPU. Implement dynamic buffers.
  628. return this.createUniformBuffer(elements);
  629. }
  630. public updateUniformBuffer(uniformBuffer: DataBuffer, elements: FloatArray, offset?: number, count?: number): void {
  631. if (offset === undefined) {
  632. offset = 0;
  633. }
  634. const dataBuffer = uniformBuffer as WebGPUDataBuffer;
  635. let view: Float32Array;
  636. if (count === undefined) {
  637. if (elements instanceof Float32Array) {
  638. view = elements;
  639. } else {
  640. view = new Float32Array(elements);
  641. }
  642. count = view.byteLength;
  643. } else {
  644. if (elements instanceof Float32Array) {
  645. view = elements;
  646. } else {
  647. view = new Float32Array(elements);
  648. }
  649. }
  650. // TODO WEBGPU. Check count and offset are in bytes.
  651. this._setSubData(dataBuffer, offset, view, 0, count);
  652. }
  653. public bindUniformBufferBase(buffer: DataBuffer, location: number, name: string): void {
  654. this._uniformsBuffers[name] = buffer as WebGPUDataBuffer;
  655. }
  656. //------------------------------------------------------------------------------
  657. // Effects
  658. //------------------------------------------------------------------------------
  659. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  660. onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
  661. const vertex = baseName.vertexElement || baseName.vertex || baseName;
  662. const fragment = baseName.fragmentElement || baseName.fragment || baseName;
  663. const name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  664. const shader = this._compiledShaders[name];
  665. if (shader) {
  666. return new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, shader.sources);
  667. }
  668. else {
  669. return new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name);
  670. }
  671. }
  672. private _compileRawShaderToSpirV(source: string, type: string): Uint32Array {
  673. const Shaderc = this._shaderc;
  674. const compiler = new Shaderc.Compiler();
  675. const opts = new Shaderc.CompileOptions();
  676. const result = compiler.CompileGlslToSpv(source,
  677. type === "fragment" ? Shaderc.shader_kind.fragment :
  678. type === "vertex" ? Shaderc.shader_kind.vertex :
  679. type === "compute" ? Shaderc.shader_kind.compute : null,
  680. "tempCompilation.glsl", "main", opts);
  681. const error = result.GetErrorMessage();
  682. if (error) {
  683. Logger.Error(error);
  684. throw new Error("Something went wrong while compile the shader.");
  685. }
  686. return result.GetBinary().slice();
  687. }
  688. private _compileShaderToSpirV(source: string, type: string, defines: Nullable<string>, shaderVersion: string): Uint32Array {
  689. return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  690. }
  691. private _createPipelineStageDescriptor(vertexShader: Uint32Array, fragmentShader: Uint32Array): GPURenderPipelineStageDescriptor {
  692. return {
  693. vertexStage: {
  694. module: this._device.createShaderModule({
  695. code: vertexShader,
  696. }),
  697. entryPoint: "main",
  698. },
  699. fragmentStage: {
  700. module: this._device.createShaderModule({
  701. code: fragmentShader,
  702. }),
  703. entryPoint: "main"
  704. }
  705. };
  706. }
  707. private _compileRawPipelineStageDescriptor(vertexCode: string, fragmentCode: string): GPURenderPipelineStageDescriptor {
  708. var vertexShader = this._compileRawShaderToSpirV(vertexCode, "vertex");
  709. var fragmentShader = this._compileRawShaderToSpirV(fragmentCode, "fragment");
  710. return this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  711. }
  712. private _compilePipelineStageDescriptor(vertexCode: string, fragmentCode: string, defines: Nullable<string>): GPURenderPipelineStageDescriptor {
  713. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  714. var shaderVersion = "#version 450\n";
  715. var vertexShader = this._compileShaderToSpirV(vertexCode, "vertex", defines, shaderVersion);
  716. var fragmentShader = this._compileShaderToSpirV(fragmentCode, "fragment", defines, shaderVersion);
  717. let program = this._createPipelineStageDescriptor(vertexShader, fragmentShader);
  718. this.onAfterShaderCompilationObservable.notifyObservers(this);
  719. return program;
  720. }
  721. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  722. throw "Not available on WebGPU";
  723. }
  724. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  725. throw "Not available on WebGPU";
  726. }
  727. public createPipelineContext(shaderProcessingContext: Nullable<ShaderProcessingContext>): IPipelineContext {
  728. var pipelineContext = new WebGPUPipelineContext(shaderProcessingContext! as WebGPUShaderProcessingContext, this);
  729. pipelineContext.engine = this;
  730. return pipelineContext;
  731. }
  732. /** @hidden */
  733. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean,
  734. rebuildRebind: any,
  735. defines: Nullable<string>,
  736. transformFeedbackVaryings: Nullable<string[]>,
  737. key: string) {
  738. const webGpuContext = pipelineContext as WebGPUPipelineContext;
  739. // TODO WEBGPU. Check if caches could be reuse from piepline ???
  740. const shader = this._compiledShaders[key];
  741. if (shader) {
  742. webGpuContext.stages = shader.stages;
  743. webGpuContext.availableAttributes = shader.availableAttributes;
  744. webGpuContext.availableUBOs = shader.availableUBOs;
  745. webGpuContext.availableSamplers = shader.availableSamplers;
  746. webGpuContext.orderedAttributes = shader.orderedAttributes;
  747. webGpuContext.orderedUBOsAndSamplers = shader.orderedUBOsAndSamplers;
  748. webGpuContext.leftOverUniforms = shader.leftOverUniforms;
  749. webGpuContext.leftOverUniformsByName = shader.leftOverUniformsByName;
  750. webGpuContext.sources = shader.sources;
  751. }
  752. else {
  753. if (createAsRaw) {
  754. webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode);
  755. }
  756. else {
  757. webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines);
  758. }
  759. this._compiledShaders[key] = {
  760. stages: webGpuContext.stages,
  761. availableAttributes: webGpuContext.availableAttributes,
  762. availableUBOs: webGpuContext.availableUBOs,
  763. availableSamplers: webGpuContext.availableSamplers,
  764. orderedAttributes: webGpuContext.orderedAttributes,
  765. orderedUBOsAndSamplers: webGpuContext.orderedUBOsAndSamplers,
  766. leftOverUniforms: webGpuContext.leftOverUniforms,
  767. leftOverUniformsByName: webGpuContext.leftOverUniformsByName,
  768. sources: {
  769. fragment: fragmentSourceCode,
  770. vertex: vertexSourceCode
  771. }
  772. };
  773. }
  774. }
  775. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  776. const results = new Array(attributesNames.length);
  777. const gpuPipelineContext = (pipelineContext as WebGPUPipelineContext);
  778. // TODO WEBGPU.
  779. // Hard coded for WebGPU until an introspection lib is available.
  780. // Should be done at processing time, not need to double the work in here.
  781. for (let i = 0; i < attributesNames.length; i++) {
  782. const attributeName = attributesNames[i];
  783. const attributeLocation = gpuPipelineContext.availableAttributes[attributeName];
  784. if (attributeLocation === undefined) {
  785. continue;
  786. }
  787. results[i] = attributeLocation;
  788. }
  789. return results;
  790. }
  791. public enableEffect(effect: Effect): void {
  792. this._currentEffect = effect;
  793. if (effect.onBind) {
  794. effect.onBind(effect);
  795. }
  796. if (effect._onBindObservable) {
  797. effect._onBindObservable.notifyObservers(effect);
  798. }
  799. }
  800. public _releaseEffect(effect: Effect): void {
  801. // Effect gets garbage collected without explicit destroy in WebGPU.
  802. }
  803. /**
  804. * 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
  805. */
  806. public releaseEffects() {
  807. // Effect gets garbage collected without explicit destroy in WebGPU.
  808. }
  809. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  810. const webgpuPipelineContext = pipelineContext as WebGPUPipelineContext;
  811. if (webgpuPipelineContext) {
  812. // TODO WEBGPU. Spector like cleanup.
  813. // TODO WEBGPU. Any pipeline required cleanup.
  814. }
  815. }
  816. //------------------------------------------------------------------------------
  817. // Textures
  818. //------------------------------------------------------------------------------
  819. // TODO WEBGPU. SHOULD not be possible to return gl unwrapped from Engine.
  820. /** @hidden */
  821. public _createTexture(): WebGLTexture {
  822. return { };
  823. }
  824. /** @hidden */
  825. public _releaseTexture(texture: InternalTexture): void {
  826. // TODO WEBGPU. check if it is all to release.
  827. if (texture._webGPUTexture) {
  828. texture._webGPUTexture.destroy();
  829. }
  830. }
  831. private _uploadMipMapsFromWebglTexture(mipMaps: number, webglEngineTexture: InternalTexture, gpuTexture: GPUTexture, width: number, height: number, face: number) {
  832. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, width, height, face);
  833. let faceWidth = width;
  834. let faceHeight = height;
  835. for (let mip = 1; mip <= mipMaps; mip++) {
  836. faceWidth = Math.max(Math.floor(faceWidth / 2), 1);
  837. faceHeight = Math.max(Math.floor(faceHeight / 2), 1);
  838. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, faceWidth, faceHeight, face, mip);
  839. }
  840. }
  841. private _uploadFromWebglTexture(webglEngineTexture: InternalTexture, gpuTexture: GPUTexture, width: number, height: number, face: number, mip: number = 0): void {
  842. let pixels = this._decodeEngine._readTexturePixels(webglEngineTexture, width, height, face, mip);
  843. if (pixels instanceof Float32Array) {
  844. const newPixels = new Uint8ClampedArray(pixels.length);
  845. pixels.forEach((value, index) => newPixels[index] = value * 255);
  846. pixels = newPixels;
  847. }
  848. const textureView: GPUTextureCopyView = {
  849. texture: gpuTexture,
  850. origin: {
  851. x: 0,
  852. y: 0,
  853. z: 0
  854. },
  855. mipLevel: mip,
  856. arrayLayer: Math.max(face, 0),
  857. };
  858. const textureExtent = {
  859. width,
  860. height,
  861. depth: 1
  862. };
  863. const commandEncoder = this._device.createCommandEncoder({});
  864. const rowPitch = Math.ceil(width * 4 / 256) * 256;
  865. let dataBuffer: DataBuffer;
  866. if (rowPitch == width * 4) {
  867. dataBuffer = this._createBuffer(pixels, WebGPUConstants.GPUBufferUsage_TRANSFER_SRC | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  868. const bufferView: GPUBufferCopyView = {
  869. buffer: dataBuffer.underlyingResource,
  870. rowPitch: rowPitch,
  871. imageHeight: height,
  872. offset: 0,
  873. };
  874. commandEncoder.copyBufferToTexture(bufferView, textureView, textureExtent);
  875. } else {
  876. const alignedPixels = new Uint8Array(rowPitch * height);
  877. let pixelsIndex = 0;
  878. for (let y = 0; y < height; ++y) {
  879. for (let x = 0; x < width; ++x) {
  880. let i = x * 4 + y * rowPitch;
  881. alignedPixels[i] = (pixels as any)[pixelsIndex];
  882. alignedPixels[i + 1] = (pixels as any)[pixelsIndex + 1];
  883. alignedPixels[i + 2] = (pixels as any)[pixelsIndex + 2];
  884. alignedPixels[i + 3] = (pixels as any)[pixelsIndex + 3];
  885. pixelsIndex += 4;
  886. }
  887. }
  888. dataBuffer = this._createBuffer(alignedPixels, WebGPUConstants.GPUBufferUsage_TRANSFER_SRC | WebGPUConstants.GPUBufferUsage_TRANSFER_DST);
  889. const bufferView: GPUBufferCopyView = {
  890. buffer: dataBuffer.underlyingResource,
  891. rowPitch: rowPitch,
  892. imageHeight: height,
  893. offset: 0,
  894. };
  895. commandEncoder.copyBufferToTexture(bufferView, textureView, textureExtent);
  896. }
  897. this._device.getQueue().submit([commandEncoder.finish()]);
  898. this._releaseBuffer(dataBuffer);
  899. }
  900. private _getSamplerFilterDescriptor(internalTexture: InternalTexture): {
  901. magFilter: GPUFilterMode,
  902. minFilter: GPUFilterMode,
  903. mipmapFilter: GPUFilterMode
  904. } {
  905. let magFilter: GPUFilterMode, minFilter: GPUFilterMode, mipmapFilter: GPUFilterMode;
  906. switch (internalTexture.samplingMode) {
  907. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  908. magFilter = WebGPUConstants.GPUFilterMode_linear;
  909. minFilter = WebGPUConstants.GPUFilterMode_linear;
  910. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  911. break;
  912. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  913. magFilter = WebGPUConstants.GPUFilterMode_linear;
  914. minFilter = WebGPUConstants.GPUFilterMode_linear;
  915. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  916. break;
  917. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  918. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  919. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  920. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  921. break;
  922. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  923. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  924. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  925. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  926. break;
  927. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  928. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  929. minFilter = WebGPUConstants.GPUFilterMode_linear;
  930. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  931. break;
  932. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  933. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  934. minFilter = WebGPUConstants.GPUFilterMode_linear;
  935. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  936. break;
  937. case Engine.TEXTURE_NEAREST_LINEAR:
  938. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  939. minFilter = WebGPUConstants.GPUFilterMode_linear;
  940. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  941. break;
  942. case Engine.TEXTURE_NEAREST_NEAREST:
  943. magFilter = WebGPUConstants.GPUFilterMode_nearest;
  944. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  945. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  946. break;
  947. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  948. magFilter = WebGPUConstants.GPUFilterMode_linear;
  949. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  950. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  951. break;
  952. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  953. magFilter = WebGPUConstants.GPUFilterMode_linear;
  954. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  955. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  956. break;
  957. case Engine.TEXTURE_LINEAR_LINEAR:
  958. magFilter = WebGPUConstants.GPUFilterMode_linear;
  959. minFilter = WebGPUConstants.GPUFilterMode_linear;
  960. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  961. break;
  962. case Engine.TEXTURE_LINEAR_NEAREST:
  963. magFilter = WebGPUConstants.GPUFilterMode_linear;
  964. minFilter = WebGPUConstants.GPUFilterMode_nearest;
  965. mipmapFilter = WebGPUConstants.GPUFilterMode_nearest;
  966. break;
  967. default:
  968. magFilter = WebGPUConstants.GPUFilterMode_linear;
  969. minFilter = WebGPUConstants.GPUFilterMode_linear;
  970. mipmapFilter = WebGPUConstants.GPUFilterMode_linear;
  971. break;
  972. }
  973. return {
  974. magFilter,
  975. minFilter,
  976. mipmapFilter
  977. };
  978. }
  979. private _getWrappingMode(mode: number): GPUAddressMode {
  980. switch (mode) {
  981. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  982. return WebGPUConstants.GPUAddressMode_repeat;
  983. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  984. return WebGPUConstants.GPUAddressMode_clampToEdge;
  985. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  986. return WebGPUConstants.GPUAddressMode_mirrorRepeat;
  987. }
  988. return WebGPUConstants.GPUAddressMode_repeat;
  989. }
  990. private _getSamplerWrappingDescriptor(internalTexture: InternalTexture): {
  991. addressModeU: GPUAddressMode,
  992. addressModeV: GPUAddressMode,
  993. addressModeW: GPUAddressMode
  994. } {
  995. return {
  996. addressModeU: this._getWrappingMode(internalTexture._cachedWrapU!),
  997. addressModeV: this._getWrappingMode(internalTexture._cachedWrapV!),
  998. addressModeW: this._getWrappingMode(internalTexture._cachedWrapR!),
  999. };
  1000. }
  1001. private _getSamplerDescriptor(internalTexture: InternalTexture): GPUSamplerDescriptor {
  1002. return {
  1003. ...this._getSamplerFilterDescriptor(internalTexture),
  1004. ...this._getSamplerWrappingDescriptor(internalTexture),
  1005. };
  1006. }
  1007. 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 {
  1008. const texture = new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  1009. const url = String(urlArg);
  1010. // TODO WEBGPU. Find a better way.
  1011. // TODO WEBGPU. this._options.textureSize
  1012. texture.url = url;
  1013. texture.generateMipMaps = !noMipmap;
  1014. texture.samplingMode = samplingMode;
  1015. texture.invertY = invertY;
  1016. if (format) {
  1017. texture.format = format;
  1018. }
  1019. let webglEngineTexture: InternalTexture;
  1020. const onLoadInternal = () => {
  1021. texture.isReady = webglEngineTexture.isReady;
  1022. const width = webglEngineTexture.width;
  1023. const height = webglEngineTexture.height;
  1024. texture.width = width;
  1025. texture.height = height;
  1026. texture.baseWidth = width;
  1027. texture.baseHeight = height;
  1028. texture._isRGBD = webglEngineTexture._isRGBD;
  1029. texture._sphericalPolynomial = webglEngineTexture._sphericalPolynomial;
  1030. let mipMaps = Scalar.Log2(Math.max(width, height));
  1031. mipMaps = Math.round(mipMaps);
  1032. const textureExtent = {
  1033. width,
  1034. height,
  1035. depth: 1
  1036. };
  1037. const textureDescriptor: GPUTextureDescriptor = {
  1038. dimension: WebGPUConstants.GPUTextureDimension_2d,
  1039. format: WebGPUConstants.GPUTextureFormat_rgba8unorm,
  1040. arrayLayerCount: 1,
  1041. mipLevelCount: noMipmap ? 1 : mipMaps + 1,
  1042. sampleCount: 1,
  1043. size: textureExtent,
  1044. usage: WebGPUConstants.GPUTextureUsage_COPY_DST | WebGPUConstants.GPUTextureUsage_SAMPLED
  1045. };
  1046. const gpuTexture = this._device.createTexture(textureDescriptor);
  1047. texture._webGPUTexture = gpuTexture;
  1048. if (noMipmap) {
  1049. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, width, height, -1);
  1050. }
  1051. else {
  1052. this._uploadMipMapsFromWebglTexture(mipMaps, webglEngineTexture, gpuTexture, width, height, -1);
  1053. }
  1054. texture._webGPUTextureView = gpuTexture.createDefaultView();
  1055. webglEngineTexture.dispose();
  1056. texture.onLoadedObservable.notifyObservers(texture);
  1057. texture.onLoadedObservable.clear();
  1058. if (onLoad) {
  1059. onLoad();
  1060. }
  1061. };
  1062. webglEngineTexture = this._decodeEngine.createTexture(urlArg, noMipmap, invertY, scene, samplingMode,
  1063. onLoadInternal, onError, buffer, fallBack, format);
  1064. this._internalTexturesCache.push(texture);
  1065. return texture;
  1066. }
  1067. 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 {
  1068. var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  1069. texture.isCube = true;
  1070. texture.url = rootUrl;
  1071. texture.generateMipMaps = !noMipmap;
  1072. // TODO WEBGPU. Cube Texture Sampling Mode.
  1073. texture.samplingMode = noMipmap ? Constants.TEXTURE_BILINEAR_SAMPLINGMODE : Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1074. texture._lodGenerationScale = lodScale;
  1075. texture._lodGenerationOffset = lodOffset;
  1076. if (!this._doNotHandleContextLost) {
  1077. texture._extension = forcedExtension;
  1078. texture._files = files;
  1079. }
  1080. let webglEngineTexture: InternalTexture;
  1081. const onLoadInternal = () => {
  1082. texture.isReady = webglEngineTexture.isReady;
  1083. const width = webglEngineTexture.width;
  1084. const height = webglEngineTexture.height;
  1085. const depth = 1;
  1086. texture.width = width;
  1087. texture.height = height;
  1088. texture.baseWidth = width;
  1089. texture.baseHeight = height;
  1090. texture.depth = depth;
  1091. texture.baseDepth = depth;
  1092. texture._isRGBD = webglEngineTexture._isRGBD;
  1093. texture._sphericalPolynomial = webglEngineTexture._sphericalPolynomial;
  1094. let mipMaps = Scalar.Log2(width);
  1095. mipMaps = Math.round(mipMaps);
  1096. const textureExtent = {
  1097. width,
  1098. height,
  1099. depth,
  1100. };
  1101. const textureDescriptor: GPUTextureDescriptor = {
  1102. dimension: WebGPUConstants.GPUTextureDimension_2d,
  1103. format: WebGPUConstants.GPUTextureFormat_rgba8unorm,
  1104. arrayLayerCount: 6,
  1105. mipLevelCount: noMipmap ? 1 : mipMaps + 1,
  1106. sampleCount: 1,
  1107. size: textureExtent,
  1108. usage: WebGPUConstants.GPUTextureUsage_COPY_DST | WebGPUConstants.GPUTextureUsage_SAMPLED
  1109. };
  1110. const gpuTexture = this._device.createTexture(textureDescriptor);
  1111. texture._webGPUTexture = gpuTexture;
  1112. const faces = [0, 1, 2, 3, 4, 5];
  1113. for (let face of faces) {
  1114. if (noMipmap) {
  1115. this._uploadFromWebglTexture(webglEngineTexture, gpuTexture, width, height, face);
  1116. }
  1117. else {
  1118. this._uploadMipMapsFromWebglTexture(mipMaps, webglEngineTexture, gpuTexture, width, height, face);
  1119. }
  1120. }
  1121. texture._webGPUTextureView = gpuTexture.createView({
  1122. arrayLayerCount: 6,
  1123. dimension: WebGPUConstants.GPUTextureViewDimension_cube,
  1124. format: WebGPUConstants.GPUTextureFormat_rgba8unorm,
  1125. mipLevelCount: noMipmap ? 1 : mipMaps + 1,
  1126. baseArrayLayer: 0,
  1127. baseMipLevel: 0,
  1128. aspect: WebGPUConstants.GPUTextureAspect_all
  1129. } as any);
  1130. webglEngineTexture.dispose();
  1131. onLoad && onLoad();
  1132. };
  1133. webglEngineTexture = this._decodeEngine.createCubeTexture(rootUrl, scene, files, noMipmap, onLoadInternal, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, excludeLoaders);
  1134. this._internalTexturesCache.push(texture);
  1135. return texture;
  1136. }
  1137. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  1138. texture.samplingMode = samplingMode;
  1139. }
  1140. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  1141. // TODO WEBGPU.
  1142. throw "Unimplemented updateDynamicTexture on WebGPU so far";
  1143. }
  1144. public setTexture(channel: number, _: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>, name: string): void {
  1145. if (this._currentEffect) {
  1146. const pipeline = this._currentEffect._pipelineContext as WebGPUPipelineContext;
  1147. if (!texture) {
  1148. pipeline.samplers[name] = null;
  1149. return;
  1150. }
  1151. const internalTexture = texture!.getInternalTexture();
  1152. if (internalTexture) {
  1153. internalTexture._cachedWrapU = texture.wrapU;
  1154. internalTexture._cachedWrapV = texture.wrapV;
  1155. internalTexture._cachedWrapR = texture.wrapR;
  1156. }
  1157. if (pipeline.samplers[name]) {
  1158. pipeline.samplers[name]!.texture = internalTexture!;
  1159. }
  1160. else {
  1161. // TODO WEBGPU. GC + 121 mapping samplers <-> availableSamplers
  1162. const availableSampler = pipeline.availableSamplers[name];
  1163. if (availableSampler) {
  1164. pipeline.samplers[name] = {
  1165. setIndex: availableSampler.setIndex,
  1166. textureBinding: availableSampler.bindingIndex,
  1167. samplerBinding: availableSampler.bindingIndex + 1,
  1168. texture: internalTexture!
  1169. };
  1170. }
  1171. }
  1172. }
  1173. }
  1174. public bindSamplers(effect: Effect): void { }
  1175. public _bindTextureDirectly(target: number, texture: InternalTexture): boolean {
  1176. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  1177. this._boundTexturesCache[this._activeChannel] = texture;
  1178. return true;
  1179. }
  1180. return false;
  1181. }
  1182. /** @hidden */
  1183. public _bindTexture(channel: number, texture: InternalTexture): void {
  1184. if (channel < 0) {
  1185. return;
  1186. }
  1187. this._bindTextureDirectly(0, texture);
  1188. }
  1189. /** @hidden */
  1190. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  1191. }
  1192. /** @hidden */
  1193. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1194. }
  1195. /** @hidden */
  1196. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  1197. }
  1198. /** @hidden */
  1199. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  1200. }
  1201. //------------------------------------------------------------------------------
  1202. // Render Target Textures
  1203. //------------------------------------------------------------------------------
  1204. public createRenderTargetTexture(size: any, options: boolean | RenderTargetCreationOptions): InternalTexture {
  1205. let fullOptions = new RenderTargetCreationOptions();
  1206. if (options !== undefined && typeof options === "object") {
  1207. fullOptions.generateMipMaps = options.generateMipMaps;
  1208. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  1209. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  1210. fullOptions.type = options.type === undefined ? Constants.TEXTURETYPE_UNSIGNED_INT : options.type;
  1211. fullOptions.samplingMode = options.samplingMode === undefined ? Constants.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  1212. } else {
  1213. fullOptions.generateMipMaps = <boolean>options;
  1214. fullOptions.generateDepthBuffer = true;
  1215. fullOptions.generateStencilBuffer = false;
  1216. fullOptions.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  1217. fullOptions.samplingMode = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE;
  1218. }
  1219. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  1220. var width = size.width || size;
  1221. var height = size.height || size;
  1222. texture._depthStencilBuffer = {};
  1223. texture._framebuffer = {};
  1224. texture.baseWidth = width;
  1225. texture.baseHeight = height;
  1226. texture.width = width;
  1227. texture.height = height;
  1228. texture.isReady = true;
  1229. texture.samples = 1;
  1230. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  1231. texture.samplingMode = fullOptions.samplingMode;
  1232. texture.type = fullOptions.type;
  1233. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  1234. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  1235. this._internalTexturesCache.push(texture);
  1236. return texture;
  1237. }
  1238. //------------------------------------------------------------------------------
  1239. // Render Commands
  1240. //------------------------------------------------------------------------------
  1241. /**
  1242. * Begin a new frame
  1243. */
  1244. public beginFrame(): void {
  1245. super.beginFrame();
  1246. this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);
  1247. this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);
  1248. }
  1249. private _freezeCommands: boolean = false;
  1250. private _frozenCommands: Nullable<GPUCommandBuffer[]> = null;
  1251. public _shouldOnlyUpdateCameras(): boolean {
  1252. return this._frozenCommands !== null;
  1253. }
  1254. /**
  1255. * End the current frame
  1256. */
  1257. public endFrame(): void {
  1258. this._endRenderPass();
  1259. if (this._freezeCommands && this._frozenCommands) {
  1260. this._commandBuffers[0] = this._frozenCommands[0];
  1261. this._commandBuffers[1] = this._frozenCommands[1];
  1262. }
  1263. else {
  1264. this._commandBuffers[0] = this._uploadEncoder.finish();
  1265. this._commandBuffers[1] = this._renderEncoder.finish();
  1266. }
  1267. if (this._freezeCommands && !this._frozenCommands) {
  1268. this._frozenCommands = [ ];
  1269. this._frozenCommands[0] = this._commandBuffers[0];
  1270. this._frozenCommands[1] = this._commandBuffers[1];
  1271. }
  1272. this._device.getQueue().submit(this._commandBuffers);
  1273. super.endFrame();
  1274. }
  1275. /**
  1276. * Freezes the current list of commands to speed up rendering of sub sequent frames.
  1277. */
  1278. public freezeCommands(): void {
  1279. this._freezeCommands = true;
  1280. this._frozenCommands = null;
  1281. }
  1282. /**
  1283. * Freezes the current list of commands to speed up rendering of sub sequent frames.
  1284. */
  1285. public unFreezeCommands(): void {
  1286. this._freezeCommands = false;
  1287. this._frozenCommands = null;
  1288. }
  1289. //------------------------------------------------------------------------------
  1290. // Render Pass
  1291. //------------------------------------------------------------------------------
  1292. private _startMainRenderPass(): void {
  1293. if (this._currentRenderPass) {
  1294. this._endRenderPass();
  1295. }
  1296. // Resolve in case of MSAA
  1297. if (this._options.antialiasing) {
  1298. this._mainColorAttachments[0].resolveTarget = this._swapChain.getCurrentTexture().createDefaultView();
  1299. }
  1300. else {
  1301. this._mainColorAttachments[0].attachment = this._swapChain.getCurrentTexture().createDefaultView();
  1302. }
  1303. this._currentRenderPass = this._renderEncoder.beginRenderPass({
  1304. colorAttachments: this._mainColorAttachments,
  1305. depthStencilAttachment: this._mainDepthAttachment
  1306. });
  1307. }
  1308. private _endRenderPass(): void {
  1309. if (this._currentRenderPass) {
  1310. this._currentRenderPass.endPass();
  1311. this._currentRenderPass = null;
  1312. }
  1313. }
  1314. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1315. if (this._currentRenderTarget) {
  1316. this.unBindFramebuffer(this._currentRenderTarget);
  1317. }
  1318. this._currentRenderTarget = texture;
  1319. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  1320. if (this._cachedViewport && !forceFullscreenViewport) {
  1321. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1322. }
  1323. }
  1324. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1325. this._currentRenderTarget = null;
  1326. if (onBeforeUnbind) {
  1327. if (texture._MSAAFramebuffer) {
  1328. this._currentFramebuffer = texture._framebuffer;
  1329. }
  1330. onBeforeUnbind();
  1331. }
  1332. this._currentFramebuffer = null;
  1333. }
  1334. //------------------------------------------------------------------------------
  1335. // Render
  1336. //------------------------------------------------------------------------------
  1337. private _getTopology(fillMode: number): GPUPrimitiveTopology {
  1338. switch (fillMode) {
  1339. // Triangle views
  1340. case Constants.MATERIAL_TriangleFillMode:
  1341. return WebGPUConstants.GPUPrimitiveTopology_triangleList;
  1342. case Constants.MATERIAL_PointFillMode:
  1343. return WebGPUConstants.GPUPrimitiveTopology_pointList;
  1344. case Constants.MATERIAL_WireFrameFillMode:
  1345. return WebGPUConstants.GPUPrimitiveTopology_lineList;
  1346. // Draw modes
  1347. case Constants.MATERIAL_PointListDrawMode:
  1348. return WebGPUConstants.GPUPrimitiveTopology_pointList;
  1349. case Constants.MATERIAL_LineListDrawMode:
  1350. return WebGPUConstants.GPUPrimitiveTopology_lineList;
  1351. case Constants.MATERIAL_LineLoopDrawMode:
  1352. // return this._gl.LINE_LOOP;
  1353. // TODO WEBGPU. Line Loop Mode
  1354. throw "LineLoop is an unsupported fillmode in WebGPU";
  1355. case Constants.MATERIAL_LineStripDrawMode:
  1356. return WebGPUConstants.GPUPrimitiveTopology_lineStrip;
  1357. case Constants.MATERIAL_TriangleStripDrawMode:
  1358. return WebGPUConstants.GPUPrimitiveTopology_triangleStrip;
  1359. case Constants.MATERIAL_TriangleFanDrawMode:
  1360. // return this._gl.TRIANGLE_FAN;
  1361. // TODO WEBGPU. Triangle Fan Mode
  1362. throw "TriangleFan is an unsupported fillmode in WebGPU";
  1363. default:
  1364. return WebGPUConstants.GPUPrimitiveTopology_triangleList;
  1365. }
  1366. }
  1367. private _getCompareFunction(compareFunction: Nullable<number>): GPUCompareFunction {
  1368. switch (compareFunction) {
  1369. case Constants.ALWAYS:
  1370. return WebGPUConstants.GPUCompareFunction_always;
  1371. case Constants.EQUAL:
  1372. return WebGPUConstants.GPUCompareFunction_equal;
  1373. case Constants.GREATER:
  1374. return WebGPUConstants.GPUCompareFunction_greater;
  1375. case Constants.GEQUAL:
  1376. return WebGPUConstants.GPUCompareFunction_greaterEqual;
  1377. case Constants.LESS:
  1378. return WebGPUConstants.GPUCompareFunction_less;
  1379. case Constants.LEQUAL:
  1380. return WebGPUConstants.GPUCompareFunction_lessEqual;
  1381. case Constants.NEVER:
  1382. return WebGPUConstants.GPUCompareFunction_never;
  1383. case Constants.NOTEQUAL:
  1384. return WebGPUConstants.GPUCompareFunction_notEqual;
  1385. default:
  1386. return WebGPUConstants.GPUCompareFunction_less;
  1387. }
  1388. }
  1389. private _getOpFunction(operation: Nullable<number>, defaultOp: GPUStencilOperation): GPUStencilOperation {
  1390. switch (operation) {
  1391. case Constants.KEEP:
  1392. return WebGPUConstants.GPUStencilOperation_keep;
  1393. case Constants.ZERO:
  1394. return WebGPUConstants.GPUStencilOperation_zero;
  1395. case Constants.REPLACE:
  1396. return WebGPUConstants.GPUStencilOperation_replace;
  1397. case Constants.INVERT:
  1398. return WebGPUConstants.GPUStencilOperation_invert;
  1399. case Constants.INCR:
  1400. return WebGPUConstants.GPUStencilOperation_incrementClamp;
  1401. case Constants.DECR:
  1402. return WebGPUConstants.GPUStencilOperation_decrementClamp;
  1403. case Constants.INCR_WRAP:
  1404. return WebGPUConstants.GPUStencilOperation_incrementWrap;
  1405. case Constants.DECR_WRAP:
  1406. return WebGPUConstants.GPUStencilOperation_decrementWrap;
  1407. default:
  1408. return defaultOp;
  1409. }
  1410. }
  1411. private _getDepthStencilStateDescriptor(): GPUDepthStencilStateDescriptor {
  1412. // TODO WEBGPU. Depth State according to the cached state.
  1413. // And the current render pass attachment setup.
  1414. const stencilFrontBack: GPUStencilStateFaceDescriptor = {
  1415. compare: this._getCompareFunction(this._stencilState.stencilFunc),
  1416. depthFailOp: this._getOpFunction(this._stencilState.stencilOpDepthFail, WebGPUConstants.GPUStencilOperation_keep),
  1417. failOp: this._getOpFunction(this._stencilState.stencilOpStencilFail, WebGPUConstants.GPUStencilOperation_keep),
  1418. passOp: this._getOpFunction(this._stencilState.stencilOpStencilDepthPass, WebGPUConstants.GPUStencilOperation_replace)
  1419. };
  1420. return {
  1421. depthWriteEnabled: this.getDepthWrite(),
  1422. depthCompare: this._getCompareFunction(this.getDepthFunction()),
  1423. format: WebGPUConstants.GPUTextureFormat_depth24plusStencil8,
  1424. stencilFront: stencilFrontBack,
  1425. stencilBack: stencilFrontBack,
  1426. stencilReadMask: this._stencilState.stencilFuncMask,
  1427. stencilWriteMask: this._stencilState.stencilMask,
  1428. };
  1429. }
  1430. /**
  1431. * Set various states to the webGL context
  1432. * @param culling defines backface culling state
  1433. * @param zOffset defines the value to apply to zOffset (0 by default)
  1434. * @param force defines if states must be applied even if cache is up to date
  1435. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  1436. */
  1437. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1438. // Culling
  1439. if (this._depthCullingState.cull !== culling || force) {
  1440. this._depthCullingState.cull = culling;
  1441. }
  1442. // Cull face
  1443. // var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  1444. var cullFace = this.cullBackFaces ? 1 : 2;
  1445. if (this._depthCullingState.cullFace !== cullFace || force) {
  1446. this._depthCullingState.cullFace = cullFace;
  1447. }
  1448. // Z offset
  1449. this.setZOffset(zOffset);
  1450. // Front face
  1451. // var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  1452. var frontFace = reverseSide ? 1 : 2;
  1453. if (this._depthCullingState.frontFace !== frontFace || force) {
  1454. this._depthCullingState.frontFace = frontFace;
  1455. }
  1456. }
  1457. private _getFrontFace(): GPUFrontFace {
  1458. switch (this._depthCullingState.frontFace) {
  1459. case 1:
  1460. return WebGPUConstants.GPUFrontFace_cw;
  1461. default:
  1462. return WebGPUConstants.GPUFrontFace_ccw;
  1463. }
  1464. }
  1465. private _getCullMode(): GPUCullMode {
  1466. if (this._depthCullingState.cull === false) {
  1467. return WebGPUConstants.GPUCullMode_none;
  1468. }
  1469. if (this._depthCullingState.cullFace === 2) {
  1470. return WebGPUConstants.GPUCullMode_front;
  1471. }
  1472. else {
  1473. return WebGPUConstants.GPUCullMode_back;
  1474. }
  1475. }
  1476. private _getRasterizationStateDescriptor(): GPURasterizationStateDescriptor {
  1477. // TODO WEBGPU. Cull State according to the cached state.
  1478. // And the current render pass attachment setup.
  1479. return {
  1480. frontFace: this._getFrontFace(),
  1481. cullMode: this._getCullMode(),
  1482. depthBias: this._depthCullingState.zOffset,
  1483. // depthBiasClamp: 0,
  1484. // depthBiasSlopeScale: 0,
  1485. };
  1486. }
  1487. private _getWriteMask(): number {
  1488. if (this.__colorWrite) {
  1489. return WebGPUConstants.GPUColorWriteBits_ALL;
  1490. }
  1491. return WebGPUConstants.GPUColorWriteBits_NONE;
  1492. }
  1493. /**
  1494. * Sets the current alpha mode
  1495. * @param mode defines the mode to use (one of the Engine.ALPHA_XXX)
  1496. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  1497. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  1498. */
  1499. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  1500. if (this._alphaMode === mode) {
  1501. return;
  1502. }
  1503. switch (mode) {
  1504. case Engine.ALPHA_DISABLE:
  1505. this._alphaState.alphaBlend = false;
  1506. break;
  1507. case Engine.ALPHA_PREMULTIPLIED:
  1508. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1509. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 1);
  1510. this._alphaState.alphaBlend = true;
  1511. break;
  1512. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  1513. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  1514. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0303, 1, 0x0303);
  1515. this._alphaState.alphaBlend = true;
  1516. break;
  1517. case Engine.ALPHA_COMBINE:
  1518. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1519. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0303, 1, 1);
  1520. this._alphaState.alphaBlend = true;
  1521. break;
  1522. case Engine.ALPHA_ONEONE:
  1523. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1524. this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1);
  1525. this._alphaState.alphaBlend = true;
  1526. break;
  1527. case Engine.ALPHA_ADD:
  1528. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1529. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 1, 0, 1);
  1530. this._alphaState.alphaBlend = true;
  1531. break;
  1532. case Engine.ALPHA_SUBTRACT:
  1533. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1534. this._alphaState.setAlphaBlendFunctionParameters(0, 0x0301, 1, 1);
  1535. this._alphaState.alphaBlend = true;
  1536. break;
  1537. case Engine.ALPHA_MULTIPLY:
  1538. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1539. this._alphaState.setAlphaBlendFunctionParameters(0x0306, 0, 1, 1);
  1540. this._alphaState.alphaBlend = true;
  1541. break;
  1542. case Engine.ALPHA_MAXIMIZED:
  1543. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1544. this._alphaState.setAlphaBlendFunctionParameters(0x0302, 0x0301, 1, 1);
  1545. this._alphaState.alphaBlend = true;
  1546. break;
  1547. case Engine.ALPHA_INTERPOLATE:
  1548. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  1549. this._alphaState.setAlphaBlendFunctionParameters(0x8001, 0x8002, 0x8003, 0x8004);
  1550. this._alphaState.alphaBlend = true;
  1551. break;
  1552. case Engine.ALPHA_SCREENMODE:
  1553. // this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  1554. this._alphaState.setAlphaBlendFunctionParameters(1, 0x0301, 1, 0x0303);
  1555. this._alphaState.alphaBlend = true;
  1556. break;
  1557. }
  1558. if (!noDepthWriteChange) {
  1559. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1560. }
  1561. this._alphaMode = mode;
  1562. }
  1563. private _getAphaBlendOperation(operation: Nullable<number>): GPUBlendOperation {
  1564. switch (operation) {
  1565. case 0x8006:
  1566. return WebGPUConstants.GPUBlendOperation_add;
  1567. case 0x800A:
  1568. return WebGPUConstants.GPUBlendOperation_substract;
  1569. case 0x800B:
  1570. return WebGPUConstants.GPUBlendOperation_reverseSubtract;
  1571. default:
  1572. return WebGPUConstants.GPUBlendOperation_add;
  1573. }
  1574. }
  1575. private _getAphaBlendFactor(factor: Nullable<number>): GPUBlendFactor {
  1576. switch (factor) {
  1577. case 0:
  1578. return WebGPUConstants.GPUBlendFactor_zero;
  1579. case 1:
  1580. return WebGPUConstants.GPUBlendFactor_one;
  1581. case 0x0300:
  1582. return WebGPUConstants.GPUBlendFactor_srcColor;
  1583. case 0x0301:
  1584. return WebGPUConstants.GPUBlendFactor_oneMinusSrcColor;
  1585. case 0x0302:
  1586. return WebGPUConstants.GPUBlendFactor_srcAlpha;
  1587. case 0x0303:
  1588. return WebGPUConstants.GPUBlendFactor_oneMinusSrcAlpha;
  1589. case 0x0304:
  1590. return WebGPUConstants.GPUBlendFactor_dstAlpha;
  1591. case 0x0305:
  1592. return WebGPUConstants.GPUBlendFactor_oneMinusDstAlpha;
  1593. case 0x0306:
  1594. return WebGPUConstants.GPUBlendFactor_dstColor;
  1595. case 0x0307:
  1596. return WebGPUConstants.GPUBlendFactor_oneMinusDstColor;
  1597. case 0x0308:
  1598. return WebGPUConstants.GPUBlendFactor_srcAlphaSaturated;
  1599. case 0x8001:
  1600. return WebGPUConstants.GPUBlendFactor_blendColor;
  1601. case 0x8002:
  1602. return WebGPUConstants.GPUBlendFactor_oneMinusBlendColor;
  1603. case 0x8003:
  1604. return WebGPUConstants.GPUBlendFactor_blendColor;
  1605. case 0x8004:
  1606. return WebGPUConstants.GPUBlendFactor_oneMinusBlendColor;
  1607. default:
  1608. return WebGPUConstants.GPUBlendFactor_one;
  1609. }
  1610. }
  1611. private _getAphaBlendState(): GPUBlendDescriptor {
  1612. if (!this._alphaState.alphaBlend) {
  1613. return { };
  1614. }
  1615. return {
  1616. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[2]),
  1617. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[3]),
  1618. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[1]),
  1619. };
  1620. }
  1621. private _getColorBlendState(): GPUBlendDescriptor {
  1622. if (!this._alphaState.alphaBlend) {
  1623. return { };
  1624. }
  1625. return {
  1626. srcFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[0]),
  1627. dstFactor: this._getAphaBlendFactor(this._alphaState._blendFunctionParameters[1]),
  1628. operation: this._getAphaBlendOperation(this._alphaState._blendEquationParameters[0]),
  1629. };
  1630. }
  1631. private _getColorStateDescriptors(): GPUColorStateDescriptor[] {
  1632. // TODO WEBGPU. Manage Multi render target.
  1633. return [{
  1634. format: this._options.swapChainFormat!,
  1635. alphaBlend: this._getAphaBlendState(),
  1636. colorBlend: this._getColorBlendState(),
  1637. writeMask: this._getWriteMask(),
  1638. }];
  1639. }
  1640. private _getStages(): GPURenderPipelineStageDescriptor {
  1641. const gpuPipeline = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1642. return gpuPipeline.stages!;
  1643. }
  1644. private _getVertexInputDescriptorFormat(kind: string, type: number, normalized: boolean): GPUVertexFormat {
  1645. switch (kind) {
  1646. case VertexBuffer.UVKind:
  1647. case VertexBuffer.UV2Kind:
  1648. case VertexBuffer.UV3Kind:
  1649. case VertexBuffer.UV4Kind:
  1650. case VertexBuffer.UV5Kind:
  1651. case VertexBuffer.UV6Kind:
  1652. switch (type) {
  1653. case VertexBuffer.BYTE:
  1654. return normalized ? WebGPUConstants.GPUVertexFormat_char2norm : WebGPUConstants.GPUVertexFormat_char2;
  1655. case VertexBuffer.UNSIGNED_BYTE:
  1656. return normalized ? WebGPUConstants.GPUVertexFormat_uchar2norm : WebGPUConstants.GPUVertexFormat_uchar2;
  1657. case VertexBuffer.SHORT:
  1658. return normalized ? WebGPUConstants.GPUVertexFormat_short2norm : WebGPUConstants.GPUVertexFormat_short2;
  1659. case VertexBuffer.UNSIGNED_SHORT:
  1660. return normalized ? WebGPUConstants.GPUVertexFormat_ushort2norm : WebGPUConstants.GPUVertexFormat_ushort2;
  1661. case VertexBuffer.INT:
  1662. return WebGPUConstants.GPUVertexFormat_int2;
  1663. case VertexBuffer.UNSIGNED_INT:
  1664. return WebGPUConstants.GPUVertexFormat_uint2;
  1665. case VertexBuffer.FLOAT:
  1666. return WebGPUConstants.GPUVertexFormat_float2;
  1667. }
  1668. case VertexBuffer.NormalKind:
  1669. case VertexBuffer.PositionKind:
  1670. switch (type) {
  1671. case VertexBuffer.INT:
  1672. return WebGPUConstants.GPUVertexFormat_int3;
  1673. case VertexBuffer.UNSIGNED_INT:
  1674. return WebGPUConstants.GPUVertexFormat_uint3;
  1675. case VertexBuffer.FLOAT:
  1676. return WebGPUConstants.GPUVertexFormat_float3;
  1677. default:
  1678. throw "Unsupported vertex type " + type + "(https://github.com/gpuweb/gpuweb/issues/231)";
  1679. }
  1680. case VertexBuffer.ColorKind:
  1681. case VertexBuffer.MatricesIndicesKind:
  1682. case VertexBuffer.MatricesIndicesExtraKind:
  1683. case VertexBuffer.MatricesWeightsKind:
  1684. case VertexBuffer.MatricesWeightsExtraKind:
  1685. case VertexBuffer.TangentKind:
  1686. case "world0":
  1687. case "world1":
  1688. case "world2":
  1689. case "world3":
  1690. switch (type) {
  1691. case VertexBuffer.BYTE:
  1692. return normalized ? WebGPUConstants.GPUVertexFormat_char4norm : WebGPUConstants.GPUVertexFormat_char4;
  1693. case VertexBuffer.UNSIGNED_BYTE:
  1694. return normalized ? WebGPUConstants.GPUVertexFormat_uchar4norm : WebGPUConstants.GPUVertexFormat_uchar4;
  1695. case VertexBuffer.SHORT:
  1696. return normalized ? WebGPUConstants.GPUVertexFormat_short4norm : WebGPUConstants.GPUVertexFormat_short4;
  1697. case VertexBuffer.UNSIGNED_SHORT:
  1698. return normalized ? WebGPUConstants.GPUVertexFormat_ushort4norm : WebGPUConstants.GPUVertexFormat_ushort4;
  1699. case VertexBuffer.INT:
  1700. return WebGPUConstants.GPUVertexFormat_int4;
  1701. case VertexBuffer.UNSIGNED_INT:
  1702. return WebGPUConstants.GPUVertexFormat_uint4;
  1703. case VertexBuffer.FLOAT:
  1704. return WebGPUConstants.GPUVertexFormat_float4;
  1705. }
  1706. }
  1707. // MorphTargets
  1708. if (kind.indexOf("position") === 0 ||
  1709. kind.indexOf("normal") === 0 ||
  1710. kind.indexOf("tangent") === 0) {
  1711. switch (type) {
  1712. case VertexBuffer.INT:
  1713. return WebGPUConstants.GPUVertexFormat_int3;
  1714. case VertexBuffer.UNSIGNED_INT:
  1715. return WebGPUConstants.GPUVertexFormat_uint3;
  1716. case VertexBuffer.FLOAT:
  1717. return WebGPUConstants.GPUVertexFormat_float3;
  1718. default:
  1719. throw "Unsupported vertex type " + type + "(https://github.com/gpuweb/gpuweb/issues/231)";
  1720. }
  1721. }
  1722. if (kind.indexOf("uv_") === 0) {
  1723. switch (type) {
  1724. case VertexBuffer.BYTE:
  1725. return normalized ? WebGPUConstants.GPUVertexFormat_char2norm : WebGPUConstants.GPUVertexFormat_char2;
  1726. case VertexBuffer.UNSIGNED_BYTE:
  1727. return normalized ? WebGPUConstants.GPUVertexFormat_uchar2norm : WebGPUConstants.GPUVertexFormat_uchar2;
  1728. case VertexBuffer.SHORT:
  1729. return normalized ? WebGPUConstants.GPUVertexFormat_short2norm : WebGPUConstants.GPUVertexFormat_short2;
  1730. case VertexBuffer.UNSIGNED_SHORT:
  1731. return normalized ? WebGPUConstants.GPUVertexFormat_ushort2norm : WebGPUConstants.GPUVertexFormat_ushort2;
  1732. case VertexBuffer.INT:
  1733. return WebGPUConstants.GPUVertexFormat_int2;
  1734. case VertexBuffer.UNSIGNED_INT:
  1735. return WebGPUConstants.GPUVertexFormat_uint2;
  1736. case VertexBuffer.FLOAT:
  1737. return WebGPUConstants.GPUVertexFormat_float2;
  1738. }
  1739. }
  1740. // TODO WEBGPU. Manages Custom Attributes.
  1741. throw new Error("Invalid kind '" + kind + "'");
  1742. }
  1743. private _getVertexInputDescriptor(): GPUVertexInputDescriptor {
  1744. const descriptors: GPUVertexBufferDescriptor[] = [];
  1745. const effect = this._currentEffect!;
  1746. const attributes = effect.getAttributesNames();
  1747. for (var index = 0; index < attributes.length; index++) {
  1748. const location = effect.getAttributeLocation(index);
  1749. if (location >= 0) {
  1750. const vertexBuffer = this._currentVertexBuffers![attributes[index]];
  1751. if (!vertexBuffer) {
  1752. continue;
  1753. }
  1754. const positionAttributeDescriptor: GPUVertexAttributeDescriptor = {
  1755. shaderLocation: location,
  1756. offset: 0, // not available in WebGL
  1757. format: this._getVertexInputDescriptorFormat(vertexBuffer.getKind(), vertexBuffer.type, vertexBuffer.normalized),
  1758. };
  1759. // TODO WEBGPU. Factorize the one with the same underlying buffer.
  1760. // manage interleaved and instances.
  1761. const vertexBufferDescriptor: GPUVertexBufferDescriptor = {
  1762. stride: vertexBuffer.byteStride,
  1763. stepMode: vertexBuffer.getIsInstanced() ? WebGPUConstants.GPUInputStepMode_instance : WebGPUConstants.GPUInputStepMode_vertex,
  1764. attributeSet: [positionAttributeDescriptor]
  1765. };
  1766. descriptors.push(vertexBufferDescriptor);
  1767. }
  1768. }
  1769. if (!this._currentIndexBuffer) {
  1770. return {
  1771. indexFormat: WebGPUConstants.GPUIndexFormat_uint32,
  1772. vertexBuffers: descriptors
  1773. };
  1774. }
  1775. const inputStateDescriptor: GPUVertexInputDescriptor = {
  1776. indexFormat: this._currentIndexBuffer!.is32Bits ? WebGPUConstants.GPUIndexFormat_uint32 : WebGPUConstants.GPUIndexFormat_uint16,
  1777. vertexBuffers: descriptors
  1778. };
  1779. return inputStateDescriptor;
  1780. }
  1781. private _getPipelineLayout(): GPUPipelineLayout {
  1782. const bindGroupLayouts: GPUBindGroupLayout[] = [];
  1783. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1784. for (let i = 0; i < webgpuPipelineContext.orderedUBOsAndSamplers.length; i++) {
  1785. const setDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i];
  1786. if (setDefinition === undefined) {
  1787. continue;
  1788. }
  1789. const bindings: GPUBindGroupLayoutBinding[] = [];
  1790. for (let j = 0; j < setDefinition.length; j++) {
  1791. const bindingDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i][j];
  1792. if (bindingDefinition === undefined) {
  1793. continue;
  1794. }
  1795. // TODO WEBGPU. Authorize shared samplers and Vertex Textures.
  1796. if (bindingDefinition.isSampler) {
  1797. bindings.push({
  1798. binding: j,
  1799. visibility: WebGPUConstants.GPUShaderStageBit_FRAGMENT,
  1800. type: WebGPUConstants.GPUBindingType_sampledTexture,
  1801. }, {
  1802. // TODO WEBGPU. No Magic + 1.
  1803. binding: j + 1,
  1804. visibility: WebGPUConstants.GPUShaderStageBit_FRAGMENT,
  1805. type: WebGPUConstants.GPUBindingType_sampler
  1806. });
  1807. }
  1808. else {
  1809. bindings.push({
  1810. binding: j,
  1811. visibility: WebGPUConstants.GPUShaderStageBit_VERTEX | WebGPUConstants.GPUShaderStageBit_FRAGMENT,
  1812. type: WebGPUConstants.GPUBindingType_uniformBuffer,
  1813. });
  1814. }
  1815. }
  1816. if (bindings.length > 0) {
  1817. const uniformsBindGroupLayout = this._device.createBindGroupLayout({
  1818. bindings,
  1819. });
  1820. bindGroupLayouts[i] = uniformsBindGroupLayout;
  1821. }
  1822. }
  1823. webgpuPipelineContext.bindGroupLayouts = bindGroupLayouts;
  1824. return this._device.createPipelineLayout({ bindGroupLayouts });
  1825. }
  1826. private _getRenderPipeline(fillMode: number): GPURenderPipeline {
  1827. // This is wrong to cache this way but workarounds the need of cache in the simple demo context.
  1828. const gpuPipeline = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1829. if (gpuPipeline.renderPipeline) {
  1830. return gpuPipeline.renderPipeline;
  1831. }
  1832. // Unsupported at the moment but needs to be extracted from the MSAA param.
  1833. const topology = this._getTopology(fillMode);
  1834. const rasterizationStateDescriptor = this._getRasterizationStateDescriptor();
  1835. const depthStateDescriptor = this._getDepthStencilStateDescriptor();
  1836. const colorStateDescriptors = this._getColorStateDescriptors();
  1837. const stages = this._getStages();
  1838. const inputStateDescriptor = this._getVertexInputDescriptor();
  1839. const pipelineLayout = this._getPipelineLayout();
  1840. gpuPipeline.renderPipeline = this._device.createRenderPipeline({
  1841. sampleCount: this._mainPassSampleCount,
  1842. primitiveTopology: topology,
  1843. rasterizationState: rasterizationStateDescriptor,
  1844. depthStencilState: depthStateDescriptor,
  1845. colorStates: colorStateDescriptors,
  1846. ...stages,
  1847. vertexInput: inputStateDescriptor,
  1848. layout: pipelineLayout,
  1849. });
  1850. return gpuPipeline.renderPipeline;
  1851. }
  1852. private _getVertexInputsToRender(): IWebGPUPipelineContextVertexInputsCache {
  1853. const effect = this._currentEffect!;
  1854. const gpuContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1855. let vertexInputs = gpuContext.vertexInputs;
  1856. if (vertexInputs) {
  1857. return vertexInputs;
  1858. }
  1859. vertexInputs = {
  1860. indexBuffer: null,
  1861. indexOffset: 0,
  1862. vertexStartSlot: 0,
  1863. vertexBuffers: [],
  1864. vertexOffsets: [],
  1865. };
  1866. gpuContext.vertexInputs = vertexInputs;
  1867. if (this._currentIndexBuffer) {
  1868. // TODO WEBGPU. Check if cache would be worth it.
  1869. vertexInputs.indexBuffer = this._currentIndexBuffer.underlyingResource;
  1870. vertexInputs.indexOffset = 0;
  1871. }
  1872. else {
  1873. vertexInputs.indexBuffer = null;
  1874. }
  1875. const attributes = effect.getAttributesNames();
  1876. for (var index = 0; index < attributes.length; index++) {
  1877. const order = effect.getAttributeLocation(index);
  1878. if (order >= 0) {
  1879. const vertexBuffer = this._currentVertexBuffers![attributes[index]];
  1880. if (!vertexBuffer) {
  1881. continue;
  1882. }
  1883. var buffer = vertexBuffer.getBuffer();
  1884. if (buffer) {
  1885. vertexInputs.vertexBuffers.push(buffer.underlyingResource);
  1886. vertexInputs.vertexOffsets.push(vertexBuffer.byteOffset);
  1887. }
  1888. }
  1889. }
  1890. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  1891. return vertexInputs;
  1892. }
  1893. private _getBindGroupsToRender(): GPUBindGroup[] {
  1894. const webgpuPipelineContext = this._currentEffect!._pipelineContext as WebGPUPipelineContext;
  1895. let bindGroups = webgpuPipelineContext.bindGroups;
  1896. if (bindGroups) {
  1897. if (webgpuPipelineContext.uniformBuffer) {
  1898. webgpuPipelineContext.uniformBuffer.update();
  1899. }
  1900. return bindGroups;
  1901. }
  1902. if (webgpuPipelineContext.uniformBuffer) {
  1903. this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer()!, 0, "LeftOver");
  1904. webgpuPipelineContext.uniformBuffer.update();
  1905. }
  1906. bindGroups = [];
  1907. webgpuPipelineContext.bindGroups = bindGroups;
  1908. const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts;
  1909. for (let i = 0; i < webgpuPipelineContext.orderedUBOsAndSamplers.length; i++) {
  1910. const setDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i];
  1911. if (setDefinition === undefined) {
  1912. continue;
  1913. }
  1914. const bindings: GPUBindGroupBinding[] = [];
  1915. for (let j = 0; j < setDefinition.length; j++) {
  1916. const bindingDefinition = webgpuPipelineContext.orderedUBOsAndSamplers[i][j];
  1917. if (bindingDefinition === undefined) {
  1918. continue;
  1919. }
  1920. // TODO WEBGPU. Authorize shared samplers and Vertex Textures.
  1921. if (bindingDefinition.isSampler) {
  1922. const bindingInfo = webgpuPipelineContext.samplers[bindingDefinition.name];
  1923. if (bindingInfo) {
  1924. if (!bindingInfo.texture._webGPUSampler) {
  1925. const samplerDescriptor: GPUSamplerDescriptor = this._getSamplerDescriptor(bindingInfo.texture!);
  1926. const gpuSampler = this._device.createSampler(samplerDescriptor);
  1927. bindingInfo.texture._webGPUSampler = gpuSampler;
  1928. }
  1929. bindings.push({
  1930. binding: bindingInfo.textureBinding,
  1931. resource: bindingInfo.texture._webGPUTextureView!,
  1932. }, {
  1933. binding: bindingInfo.samplerBinding,
  1934. resource: bindingInfo.texture._webGPUSampler!,
  1935. });
  1936. }
  1937. else {
  1938. Logger.Error("Sampler has not been bound: " + bindingDefinition.name);
  1939. }
  1940. }
  1941. else {
  1942. const dataBuffer = this._uniformsBuffers[bindingDefinition.name];
  1943. if (dataBuffer) {
  1944. const webgpuBuffer = dataBuffer.underlyingResource as GPUBuffer;
  1945. bindings.push({
  1946. binding: j,
  1947. resource: {
  1948. buffer: webgpuBuffer,
  1949. offset: 0,
  1950. size: dataBuffer.capacity,
  1951. },
  1952. });
  1953. }
  1954. else {
  1955. Logger.Error("UBO has not been bound: " + bindingDefinition.name);
  1956. }
  1957. }
  1958. }
  1959. const groupLayout = bindGroupLayouts[i];
  1960. if (groupLayout) {
  1961. bindGroups[i] = this._device.createBindGroup({
  1962. layout: groupLayout,
  1963. bindings,
  1964. });
  1965. }
  1966. }
  1967. return bindGroups;
  1968. }
  1969. private _bindVertexInputs(vertexInputs: IWebGPUPipelineContextVertexInputsCache): void {
  1970. const renderPass = this._currentRenderPass!;
  1971. if (vertexInputs.indexBuffer) {
  1972. // TODO WEBGPU. Check if cache would be worth it.
  1973. renderPass.setIndexBuffer(vertexInputs.indexBuffer, vertexInputs.indexOffset);
  1974. }
  1975. // TODO WEBGPU. Optimize buffer reusability and types as more are now allowed.
  1976. this._currentRenderPass!.setVertexBuffers(vertexInputs.vertexStartSlot, vertexInputs.vertexBuffers, vertexInputs.vertexOffsets);
  1977. }
  1978. private _setRenderBindGroups(bindGroups: GPUBindGroup[]): void {
  1979. // TODO WEBGPU. Only set groups if changes happened.
  1980. const renderPass = this._currentRenderPass!;
  1981. for (let i = 0; i < bindGroups.length; i++) {
  1982. renderPass.setBindGroup(i, bindGroups[i]);
  1983. }
  1984. }
  1985. private _setRenderPipeline(fillMode: number): void {
  1986. // TODO WEBGPU. Add dynamicity to the data.
  1987. const pipeline = this._getRenderPipeline(fillMode);
  1988. this._currentRenderPass!.setPipeline(pipeline);
  1989. const vertexInputs = this._getVertexInputsToRender();
  1990. this._bindVertexInputs(vertexInputs);
  1991. const bindGroups = this._getBindGroupsToRender();
  1992. this._setRenderBindGroups(bindGroups);
  1993. if (this._alphaState.alphaBlend && this._alphaState._isBlendConstantsDirty) {
  1994. this._currentRenderPass!.setBlendColor(this._alphaState._blendConstants as any);
  1995. }
  1996. }
  1997. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount: number = 1): void {
  1998. this._setRenderPipeline(fillMode);
  1999. this._currentRenderPass!.drawIndexed(indexCount, instancesCount, indexStart, 0, 0);
  2000. }
  2001. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount: number = 1): void {
  2002. this._currentIndexBuffer = null;
  2003. this._setRenderPipeline(fillMode);
  2004. this._currentRenderPass!.draw(verticesCount, instancesCount, verticesStart, 0);
  2005. }
  2006. /**
  2007. * Force a specific size of the canvas
  2008. * @param width defines the new canvas' width
  2009. * @param height defines the new canvas' height
  2010. */
  2011. public setSize(width: number, height: number): void {
  2012. super.setSize(width, height);
  2013. // TODO WEBGPU. Disposeold attachements.
  2014. this._initializeMainAttachments();
  2015. }
  2016. //------------------------------------------------------------------------------
  2017. // Dispose
  2018. //------------------------------------------------------------------------------
  2019. /**
  2020. * Dispose and release all associated resources
  2021. */
  2022. public dispose(): void {
  2023. this._decodeEngine.dispose();
  2024. this._compiledShaders = { };
  2025. if (this._mainTexture) {
  2026. this._mainTexture.destroy();
  2027. }
  2028. if (this._depthTexture) {
  2029. this._depthTexture.destroy();
  2030. }
  2031. super.dispose();
  2032. }
  2033. //------------------------------------------------------------------------------
  2034. // Misc
  2035. //------------------------------------------------------------------------------
  2036. public getRenderWidth(useScreen = false): number {
  2037. if (!useScreen && this._currentRenderTarget) {
  2038. return this._currentRenderTarget.width;
  2039. }
  2040. return this._canvas.width;
  2041. }
  2042. public getRenderHeight(useScreen = false): number {
  2043. if (!useScreen && this._currentRenderTarget) {
  2044. return this._currentRenderTarget.height;
  2045. }
  2046. return this._canvas.height;
  2047. }
  2048. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  2049. return this._canvas;
  2050. }
  2051. //------------------------------------------------------------------------------
  2052. // Errors
  2053. //------------------------------------------------------------------------------
  2054. public getError(): number {
  2055. // TODO WEBGPU. from the webgpu errors.
  2056. return 0;
  2057. }
  2058. //------------------------------------------------------------------------------
  2059. // Unused WebGPU
  2060. //------------------------------------------------------------------------------
  2061. public areAllEffectsReady(): boolean {
  2062. // TODO WEBGPU.
  2063. // No parallel shader compilation.
  2064. return true;
  2065. }
  2066. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  2067. // TODO WEBGPU.
  2068. // No parallel shader compilation.
  2069. // No Async, so direct launch
  2070. action();
  2071. }
  2072. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  2073. // TODO WEBGPU.
  2074. // No parallel shader compilation.
  2075. return true;
  2076. }
  2077. public _getUnpackAlignement(): number {
  2078. return 1;
  2079. }
  2080. public _unpackFlipY(value: boolean) { }
  2081. // TODO WEBGPU. All of this should go once engine split with baseEngine.
  2082. public applyStates() {
  2083. // TODO WEBGPU. Apply States dynamically.
  2084. // This is done at the pipeline creation level for the moment...
  2085. }
  2086. /** @hidden */
  2087. public _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  2088. throw "_getSamplingParameters is not available in WebGPU";
  2089. }
  2090. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  2091. }
  2092. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2093. return [];
  2094. }
  2095. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  2096. }
  2097. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  2098. }
  2099. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  2100. }
  2101. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  2102. }
  2103. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  2104. }
  2105. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  2106. }
  2107. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  2108. }
  2109. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  2110. }
  2111. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  2112. }
  2113. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  2114. }
  2115. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  2116. }
  2117. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  2118. }
  2119. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  2120. }
  2121. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  2122. }
  2123. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  2124. }
  2125. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  2126. }
  2127. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  2128. }
  2129. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  2130. }
  2131. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  2132. }
  2133. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  2134. }
  2135. }