webgpuEngine.ts 166 KB

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