webgpuEngine.ts 171 KB

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