renderer_webgpu.cpp 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931
  1. /*
  2. * Copyright 2011-2019 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "bgfx_p.h"
  6. //#define DAWN_ENABLE_BACKEND_D3D12
  7. #define DAWN_ENABLE_BACKEND_VULKAN
  8. #define BGFX_CONFIG_DEBUG_ANNOTATION 0
  9. #if BGFX_CONFIG_RENDERER_WEBGPU
  10. # include "renderer_webgpu.h"
  11. # include "renderer_vk.h"
  12. # include "renderer.h"
  13. # include "debug_renderdoc.h"
  14. # if !BX_PLATFORM_EMSCRIPTEN
  15. # ifdef DAWN_ENABLE_BACKEND_D3D12
  16. # include <dawn_native/D3D12Backend.h>
  17. # endif // !BX_PLATFORM_EMSCRIPTEN
  18. # ifdef DAWN_ENABLE_BACKEND_VULKAN
  19. # include <dawn_native/VulkanBackend.h>
  20. # endif // DAWN_ENABLE_BACKEND_VULKAN
  21. # include <dawn_native/DawnNative.h>
  22. # include <dawn/dawn_wsi.h>
  23. # include <dawn/dawn_proc.h>
  24. # else
  25. # include <emscripten/emscripten.h>
  26. # include <emscripten/html5.h>
  27. # endif // !BX_PLATFORM_EMSCRIPTEN
  28. namespace bgfx { namespace webgpu
  29. {
  30. // TODO (hugoam) cleanup
  31. template <class T>
  32. T defaultDescriptor() { return T(); }
  33. template <> wgpu::BlendDescriptor defaultDescriptor() { return { wgpu::BlendOperation::Add, wgpu::BlendFactor::One, wgpu::BlendFactor::Zero }; }
  34. template <> wgpu::ColorStateDescriptor defaultDescriptor() { return { NULL, wgpu::TextureFormat::RGBA8Unorm, defaultDescriptor<wgpu::BlendDescriptor>(), defaultDescriptor<wgpu::BlendDescriptor>(), wgpu::ColorWriteMask::All }; }
  35. template <> wgpu::StencilStateFaceDescriptor defaultDescriptor() { return { wgpu::CompareFunction::Always, wgpu::StencilOperation::Keep, wgpu::StencilOperation::Keep, wgpu::StencilOperation::Keep }; }
  36. template <> wgpu::VertexStateDescriptor defaultDescriptor() { return { NULL, wgpu::IndexFormat::Uint32, 0, NULL }; }
  37. template <> wgpu::VertexBufferLayoutDescriptor defaultDescriptor() { return { 0, wgpu::InputStepMode::Vertex, 0, NULL }; }
  38. template <> wgpu::VertexAttributeDescriptor defaultDescriptor() { return { wgpu::VertexFormat::Float, 0, 0 }; }
  39. template <> wgpu::RasterizationStateDescriptor defaultDescriptor() { return { NULL, wgpu::FrontFace::CCW, wgpu::CullMode::None, 0, 0.f, 0.f }; }
  40. template <> wgpu::ProgrammableStageDescriptor defaultDescriptor() { return { NULL, {}, "main" }; }
  41. template <> wgpu::DepthStencilStateDescriptor defaultDescriptor() { return { NULL, wgpu::TextureFormat::Depth24PlusStencil8, false, wgpu::CompareFunction::Always, defaultDescriptor<wgpu::StencilStateFaceDescriptor>(), defaultDescriptor<wgpu::StencilStateFaceDescriptor>(), 0xff, 0xff }; }
  42. template <> wgpu::PipelineLayoutDescriptor defaultDescriptor() { return { NULL, "", 0, NULL }; }
  43. template <> wgpu::TextureViewDescriptor defaultDescriptor() { return {}; }
  44. template <> wgpu::RenderPassColorAttachmentDescriptor defaultDescriptor() { return { {}, {}, wgpu::LoadOp::Clear, wgpu::StoreOp::Store, { 0.0f, 0.0f, 0.0f, 0.0f } }; }
  45. template <> wgpu::RenderPassDepthStencilAttachmentDescriptor defaultDescriptor() { return { {}, wgpu::LoadOp::Clear, wgpu::StoreOp::Store, 1.0f, wgpu::LoadOp::Clear, wgpu::StoreOp::Store, 0 }; }
  46. RenderPassDescriptor::RenderPassDescriptor()
  47. {
  48. depthStencilAttachment = defaultDescriptor<wgpu::RenderPassDepthStencilAttachmentDescriptor>();
  49. for(uint32_t i = 0; i < kMaxColorAttachments; ++i)
  50. {
  51. colorAttachments[i] = defaultDescriptor<wgpu::RenderPassColorAttachmentDescriptor>();
  52. }
  53. desc = defaultDescriptor<wgpu::RenderPassDescriptor>();
  54. //desc.colorAttachmentCount = colorAttachmentCount;
  55. desc.colorAttachments = colorAttachments;
  56. desc.colorAttachmentCount = 1; // TODO (hugoam) set it properly everywhere
  57. }
  58. VertexStateDescriptor::VertexStateDescriptor()
  59. {
  60. for(uint32_t i = 0; i < kMaxVertexInputs; ++i)
  61. {
  62. vertexBuffers[i] = defaultDescriptor<wgpu::VertexBufferLayoutDescriptor>();
  63. }
  64. for (uint32_t i = 0; i < kMaxVertexAttributes; ++i)
  65. {
  66. attributes[i] = defaultDescriptor<wgpu::VertexAttributeDescriptor>();
  67. }
  68. vertexBuffers[0].attributes = &attributes[0];
  69. //vertexBuffers[0].attributeCount = numAttributes;
  70. desc = defaultDescriptor<wgpu::VertexStateDescriptor>();
  71. desc.vertexBuffers = vertexBuffers;
  72. //desc.vertexBufferCount = numVertexBuffers;
  73. }
  74. RenderPipelineDescriptor::RenderPipelineDescriptor()
  75. {
  76. //vertexStage = defaultDescriptor<wgpu::ProgrammableStageDescriptor>();
  77. fragmentStage = defaultDescriptor<wgpu::ProgrammableStageDescriptor>();
  78. rasterizationState = defaultDescriptor<wgpu::RasterizationStateDescriptor>();
  79. depthStencilState = defaultDescriptor<wgpu::DepthStencilStateDescriptor>();
  80. for(uint32_t i = 0; i < kMaxColorAttachments; ++i)
  81. {
  82. colorStates[i] = defaultDescriptor<wgpu::ColorStateDescriptor>();
  83. }
  84. desc = defaultDescriptor<wgpu::RenderPipelineDescriptor>();
  85. desc.primitiveTopology = wgpu::PrimitiveTopology::TriangleList;
  86. desc.sampleCount = 1;
  87. desc.colorStateCount = 1;
  88. //wgpu::VertexStateDescriptor inputState = inputState.descriptor();
  89. desc.vertexStage = defaultDescriptor<wgpu::ProgrammableStageDescriptor>();
  90. desc.fragmentStage = &fragmentStage;
  91. //desc.vertexState = &inputState;
  92. desc.rasterizationState = &rasterizationState;
  93. desc.depthStencilState = NULL;
  94. desc.colorStates = colorStates;
  95. }
  96. // TODO (hugoam) cleanup (end)
  97. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  98. inline void setViewType(ViewId _view, const bx::StringView _str)
  99. {
  100. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION || BGFX_CONFIG_PROFILER) )
  101. {
  102. bx::memCopy(&s_viewName[_view][3], _str.getPtr(), _str.getLength() );
  103. }
  104. }
  105. struct PrimInfo
  106. {
  107. wgpu::PrimitiveTopology m_type;
  108. uint32_t m_min;
  109. uint32_t m_div;
  110. uint32_t m_sub;
  111. };
  112. static const PrimInfo s_primInfo[] =
  113. {
  114. { wgpu::PrimitiveTopology::TriangleList, 3, 3, 0 },
  115. { wgpu::PrimitiveTopology::TriangleStrip, 3, 1, 2 },
  116. { wgpu::PrimitiveTopology::LineList, 2, 2, 0 },
  117. { wgpu::PrimitiveTopology::LineStrip, 2, 1, 1 },
  118. { wgpu::PrimitiveTopology::PointList, 1, 1, 0 },
  119. };
  120. BX_STATIC_ASSERT(Topology::Count == BX_COUNTOF(s_primInfo) );
  121. static const wgpu::VertexFormat s_attribType[][4][2] =
  122. {
  123. { // Uint8
  124. { wgpu::VertexFormat::UChar2, wgpu::VertexFormat::UChar2Norm },
  125. { wgpu::VertexFormat::UChar2, wgpu::VertexFormat::UChar2Norm },
  126. { wgpu::VertexFormat::UChar4, wgpu::VertexFormat::UChar4Norm },
  127. { wgpu::VertexFormat::UChar4, wgpu::VertexFormat::UChar4Norm },
  128. },
  129. { // Uint10
  130. { wgpu::VertexFormat::UShort2, wgpu::VertexFormat::UShort2Norm },
  131. { wgpu::VertexFormat::UShort2, wgpu::VertexFormat::UShort2Norm },
  132. { wgpu::VertexFormat::UShort4, wgpu::VertexFormat::UShort4Norm },
  133. { wgpu::VertexFormat::UShort4, wgpu::VertexFormat::UShort4Norm },
  134. },
  135. { // Int16
  136. { wgpu::VertexFormat::Short2, wgpu::VertexFormat::Short2Norm },
  137. { wgpu::VertexFormat::Short2, wgpu::VertexFormat::Short2Norm },
  138. { wgpu::VertexFormat::Short4, wgpu::VertexFormat::Short4Norm },
  139. { wgpu::VertexFormat::Short4, wgpu::VertexFormat::Short4Norm },
  140. },
  141. { // Half
  142. { wgpu::VertexFormat::Half2, wgpu::VertexFormat::Half2 },
  143. { wgpu::VertexFormat::Half2, wgpu::VertexFormat::Half2 },
  144. { wgpu::VertexFormat::Half4, wgpu::VertexFormat::Half4 },
  145. { wgpu::VertexFormat::Half4, wgpu::VertexFormat::Half4 },
  146. },
  147. { // Float
  148. { wgpu::VertexFormat::Float, wgpu::VertexFormat::Float },
  149. { wgpu::VertexFormat::Float2, wgpu::VertexFormat::Float2 },
  150. { wgpu::VertexFormat::Float3, wgpu::VertexFormat::Float3 },
  151. { wgpu::VertexFormat::Float4, wgpu::VertexFormat::Float4 },
  152. },
  153. };
  154. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  155. static const wgpu::CullMode s_cullMode[] =
  156. {
  157. wgpu::CullMode::None,
  158. wgpu::CullMode::Front,
  159. wgpu::CullMode::Back,
  160. wgpu::CullMode::None,
  161. };
  162. static const wgpu::BlendFactor s_blendFactor[][2] =
  163. {
  164. { wgpu::BlendFactor(0), wgpu::BlendFactor(0) }, // ignored
  165. { wgpu::BlendFactor::Zero, wgpu::BlendFactor::Zero }, // ZERO
  166. { wgpu::BlendFactor::One, wgpu::BlendFactor::One }, // ONE
  167. { wgpu::BlendFactor::SrcColor, wgpu::BlendFactor::SrcAlpha }, // SRC_COLOR
  168. { wgpu::BlendFactor::OneMinusSrcColor, wgpu::BlendFactor::OneMinusSrcAlpha }, // INV_SRC_COLOR
  169. { wgpu::BlendFactor::SrcAlpha, wgpu::BlendFactor::SrcAlpha }, // SRC_ALPHA
  170. { wgpu::BlendFactor::OneMinusSrcAlpha, wgpu::BlendFactor::OneMinusSrcAlpha }, // INV_SRC_ALPHA
  171. { wgpu::BlendFactor::DstAlpha, wgpu::BlendFactor::DstAlpha }, // DST_ALPHA
  172. { wgpu::BlendFactor::OneMinusDstAlpha, wgpu::BlendFactor::OneMinusDstAlpha }, // INV_DST_ALPHA
  173. { wgpu::BlendFactor::DstColor, wgpu::BlendFactor::DstAlpha }, // DST_COLOR
  174. { wgpu::BlendFactor::OneMinusDstColor, wgpu::BlendFactor::OneMinusDstAlpha }, // INV_DST_COLOR
  175. { wgpu::BlendFactor::SrcAlphaSaturated, wgpu::BlendFactor::One }, // SRC_ALPHA_SAT
  176. { wgpu::BlendFactor::BlendColor, wgpu::BlendFactor::BlendColor }, // FACTOR
  177. { wgpu::BlendFactor::OneMinusBlendColor, wgpu::BlendFactor::OneMinusBlendColor }, // INV_FACTOR
  178. };
  179. static const wgpu::BlendOperation s_blendEquation[] =
  180. {
  181. wgpu::BlendOperation::Add,
  182. wgpu::BlendOperation::Subtract,
  183. wgpu::BlendOperation::ReverseSubtract,
  184. wgpu::BlendOperation::Min,
  185. wgpu::BlendOperation::Max,
  186. };
  187. static const wgpu::CompareFunction s_cmpFunc[] =
  188. {
  189. wgpu::CompareFunction::Always, // ignored
  190. wgpu::CompareFunction::Less,
  191. wgpu::CompareFunction::LessEqual,
  192. wgpu::CompareFunction::Equal,
  193. wgpu::CompareFunction::GreaterEqual,
  194. wgpu::CompareFunction::Greater,
  195. wgpu::CompareFunction::NotEqual,
  196. wgpu::CompareFunction::Never,
  197. wgpu::CompareFunction::Always,
  198. };
  199. static const wgpu::StencilOperation s_stencilOp[] =
  200. {
  201. wgpu::StencilOperation::Zero,
  202. wgpu::StencilOperation::Keep,
  203. wgpu::StencilOperation::Replace,
  204. wgpu::StencilOperation::IncrementWrap,
  205. wgpu::StencilOperation::IncrementClamp,
  206. wgpu::StencilOperation::DecrementWrap,
  207. wgpu::StencilOperation::DecrementClamp,
  208. wgpu::StencilOperation::Invert,
  209. };
  210. static const wgpu::AddressMode s_textureAddress[] =
  211. {
  212. wgpu::AddressMode::Repeat,
  213. wgpu::AddressMode::MirrorRepeat,
  214. wgpu::AddressMode::ClampToEdge,
  215. wgpu::AddressMode(0), // Border ? ClampToZero ?
  216. };
  217. static const wgpu::FilterMode s_textureFilterMinMag[] =
  218. {
  219. wgpu::FilterMode::Linear,
  220. wgpu::FilterMode::Nearest,
  221. wgpu::FilterMode::Linear,
  222. };
  223. static const wgpu::FilterMode s_textureFilterMip[] =
  224. {
  225. wgpu::FilterMode::Linear,
  226. wgpu::FilterMode::Nearest,
  227. };
  228. struct TextureFormatInfo
  229. {
  230. wgpu::TextureFormat m_fmt;
  231. wgpu::TextureFormat m_fmtSrgb;
  232. };
  233. static TextureFormatInfo s_textureFormat[] =
  234. {
  235. { wgpu::TextureFormat::BC1RGBAUnorm, wgpu::TextureFormat::BC1RGBAUnormSrgb }, // BC1
  236. { wgpu::TextureFormat::BC2RGBAUnorm, wgpu::TextureFormat::BC2RGBAUnormSrgb }, // BC2
  237. { wgpu::TextureFormat::BC3RGBAUnorm, wgpu::TextureFormat::BC3RGBAUnormSrgb }, // BC3
  238. { wgpu::TextureFormat::BC4RUnorm, wgpu::TextureFormat::Undefined }, // BC4 // BC4RSnorm ??
  239. { wgpu::TextureFormat::BC5RGUnorm, wgpu::TextureFormat::Undefined }, // BC5 // BC5RGSnorm ??
  240. { wgpu::TextureFormat::BC6HRGBUfloat, wgpu::TextureFormat::Undefined }, // BC6H // BC6HRGBSfloat ??
  241. { wgpu::TextureFormat::BC7RGBAUnorm, wgpu::TextureFormat::BC7RGBAUnormSrgb }, // BC7
  242. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ETC1
  243. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ETC2
  244. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ETC2A
  245. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ETC2A1
  246. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC12
  247. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC14
  248. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC12A
  249. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC14A
  250. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC22
  251. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // PTC24
  252. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ATC
  253. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ATCE
  254. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ATCI
  255. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC4x4
  256. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC5x5
  257. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC6x6
  258. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC8x5
  259. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC8x6
  260. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // ASTC10x5
  261. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // Unknown
  262. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // R1
  263. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // A8
  264. { wgpu::TextureFormat::R8Unorm, wgpu::TextureFormat::Undefined }, // R8
  265. { wgpu::TextureFormat::R8Sint, wgpu::TextureFormat::Undefined }, // R8I
  266. { wgpu::TextureFormat::R8Uint, wgpu::TextureFormat::Undefined }, // R8U
  267. { wgpu::TextureFormat::R8Snorm, wgpu::TextureFormat::Undefined }, // R8S
  268. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // R16
  269. { wgpu::TextureFormat::R16Sint, wgpu::TextureFormat::Undefined }, // R16I
  270. { wgpu::TextureFormat::R16Uint, wgpu::TextureFormat::Undefined }, // R16U
  271. { wgpu::TextureFormat::R16Float, wgpu::TextureFormat::Undefined }, // R16F
  272. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // R16S
  273. { wgpu::TextureFormat::R32Sint, wgpu::TextureFormat::Undefined }, // R32I
  274. { wgpu::TextureFormat::R32Uint, wgpu::TextureFormat::Undefined }, // R32U
  275. { wgpu::TextureFormat::R32Float, wgpu::TextureFormat::Undefined }, // R32F
  276. { wgpu::TextureFormat::RG8Unorm, wgpu::TextureFormat::Undefined }, // RG8
  277. { wgpu::TextureFormat::RG8Sint, wgpu::TextureFormat::Undefined }, // RG8I
  278. { wgpu::TextureFormat::RG8Uint, wgpu::TextureFormat::Undefined }, // RG8U
  279. { wgpu::TextureFormat::RG8Snorm, wgpu::TextureFormat::Undefined }, // RG8S
  280. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RG16
  281. { wgpu::TextureFormat::RG16Sint, wgpu::TextureFormat::Undefined }, // RG16I
  282. { wgpu::TextureFormat::RG16Uint, wgpu::TextureFormat::Undefined }, // RG16U
  283. { wgpu::TextureFormat::RG16Float, wgpu::TextureFormat::Undefined }, // RG16F
  284. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RG16S
  285. { wgpu::TextureFormat::RG32Sint, wgpu::TextureFormat::Undefined }, // RG32I
  286. { wgpu::TextureFormat::RG32Uint, wgpu::TextureFormat::Undefined }, // RG32U
  287. { wgpu::TextureFormat::RG32Float, wgpu::TextureFormat::Undefined }, // RG32F
  288. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB8
  289. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB8I
  290. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB8U
  291. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB8S
  292. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB9E5F
  293. { wgpu::TextureFormat::BGRA8Unorm, wgpu::TextureFormat::BGRA8UnormSrgb }, // BGRA8
  294. { wgpu::TextureFormat::RGBA8Unorm, wgpu::TextureFormat::RGBA8UnormSrgb }, // RGBA8
  295. { wgpu::TextureFormat::RGBA8Sint, wgpu::TextureFormat::Undefined }, // RGBA8I
  296. { wgpu::TextureFormat::RGBA8Uint, wgpu::TextureFormat::Undefined }, // RGBA8U
  297. { wgpu::TextureFormat::RGBA8Snorm, wgpu::TextureFormat::Undefined }, // RGBA8S
  298. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGBA16
  299. { wgpu::TextureFormat::RGBA16Sint, wgpu::TextureFormat::Undefined }, // RGBA16I
  300. { wgpu::TextureFormat::RGBA16Uint, wgpu::TextureFormat::Undefined }, // RGBA16U
  301. { wgpu::TextureFormat::RGBA16Float, wgpu::TextureFormat::Undefined }, // RGBA16F
  302. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGBA16S
  303. { wgpu::TextureFormat::RGBA32Sint, wgpu::TextureFormat::Undefined }, // RGBA32I
  304. { wgpu::TextureFormat::RGBA32Uint, wgpu::TextureFormat::Undefined }, // RGBA32U
  305. { wgpu::TextureFormat::RGBA32Float, wgpu::TextureFormat::Undefined }, // RGBA32F
  306. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // R5G6B5
  307. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGBA4
  308. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // RGB5A1
  309. { wgpu::TextureFormat::RGB10A2Unorm, wgpu::TextureFormat::Undefined }, // RGB10A2
  310. { wgpu::TextureFormat::RG11B10Float, wgpu::TextureFormat::Undefined }, // RG11B10F
  311. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // UnknownDepth
  312. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // D16
  313. { wgpu::TextureFormat::Depth24Plus, wgpu::TextureFormat::Undefined }, // D24
  314. { wgpu::TextureFormat::Depth24PlusStencil8, wgpu::TextureFormat::Undefined }, // D24S8
  315. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // D32
  316. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // D16F
  317. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // D24F
  318. { wgpu::TextureFormat::Depth32Float, wgpu::TextureFormat::Undefined }, // D32F
  319. { wgpu::TextureFormat::Undefined, wgpu::TextureFormat::Undefined }, // D0S8
  320. };
  321. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat));
  322. int32_t s_msaa[] =
  323. {
  324. 1,
  325. 2,
  326. 4,
  327. 8,
  328. 16,
  329. };
  330. struct RendererContextWgpu;
  331. static RendererContextWgpu* s_renderWgpu;
  332. static bool s_ignoreError = false;
  333. #if !BX_PLATFORM_EMSCRIPTEN
  334. DawnSwapChainImplementation(*createSwapChain)(wgpu::Device device, void* nwh);
  335. # if defined(DAWN_ENABLE_BACKEND_D3D12)
  336. DawnSwapChainImplementation CreateSwapChainD3D12(wgpu::Device device, void* nwh)
  337. {
  338. HWND win32Window = (HWND)nwh;
  339. return dawn_native::d3d12::CreateNativeSwapChainImpl(device.Get(), win32Window);
  340. }
  341. # endif // defined(DAWN_ENABLE_BACKEND_D3D12)
  342. # if defined(DAWN_ENABLE_BACKEND_VULKAN)
  343. DawnSwapChainImplementation CreateSwapChainVulkan(wgpu::Device device, void* nwh)
  344. {
  345. VkInstance instance = dawn_native::vulkan::GetInstance(device.Get());
  346. PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR = (PFN_vkCreateWin32SurfaceKHR)dawn_native::vulkan::GetInstanceProcAddr(device.Get(), "vkCreateWin32SurfaceKHR");
  347. VkSurfaceKHR surface;
  348. # if BX_PLATFORM_WINDOWS
  349. // Copied from renderer_vk.cpp -> needs refactor
  350. {
  351. VkWin32SurfaceCreateInfoKHR sci;
  352. sci.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
  353. sci.pNext = NULL;
  354. sci.flags = 0;
  355. sci.hinstance = (HINSTANCE)GetModuleHandle(NULL);
  356. sci.hwnd = (HWND)nwh;
  357. VkResult result = vkCreateWin32SurfaceKHR(instance, &sci, NULL, &surface);
  358. }
  359. # endif // BX_PLATFORM_WINDOWS
  360. return dawn_native::vulkan::CreateNativeSwapChainImpl(device.Get(), surface);
  361. }
  362. # endif // defined(DAWN_ENABLE_BACKEND_VULKAN)
  363. #endif // !BX_PLATFORM_EMSCRIPTEN
  364. struct RendererContextWgpu : public RendererContextI
  365. {
  366. RendererContextWgpu()
  367. : m_frameIndex(0)
  368. , m_numWindows(0)
  369. , m_rtMsaa(false)
  370. , m_capture(NULL)
  371. , m_captureSize(0)
  372. {
  373. bx::memSet(&m_windows, 0xff, sizeof(m_windows) );
  374. }
  375. ~RendererContextWgpu()
  376. {
  377. }
  378. bool init(const Init& _init)
  379. {
  380. BX_UNUSED(_init);
  381. BX_TRACE("Init.");
  382. if (_init.debug
  383. || _init.profile)
  384. {
  385. m_renderDocDll = loadRenderDoc();
  386. }
  387. setGraphicsDebuggerPresent(NULL != m_renderDocDll);
  388. m_fbh.idx = kInvalidHandle;
  389. bx::memSet(m_uniforms, 0, sizeof(m_uniforms) );
  390. bx::memSet(&m_resolution, 0, sizeof(m_resolution) );
  391. #if !BX_PLATFORM_EMSCRIPTEN
  392. // Default to D3D12, Metal, Vulkan, OpenGL in that order as D3D12 and Metal are the preferred on
  393. // their respective platforms, and Vulkan is preferred to OpenGL
  394. # if defined(DAWN_ENABLE_BACKEND_D3D12)
  395. static dawn_native::BackendType backendType = dawn_native::BackendType::D3D12;
  396. # elif defined(DAWN_ENABLE_BACKEND_METAL)
  397. static dawn_native::BackendType backendType = dawn_native::BackendType::Metal;
  398. # elif defined(DAWN_ENABLE_BACKEND_OPENGL)
  399. static dawn_native::BackendType backendType = dawn_native::BackendType::OpenGL;
  400. # elif defined(DAWN_ENABLE_BACKEND_VULKAN)
  401. static dawn_native::BackendType backendType = dawn_native::BackendType::Vulkan;
  402. # else
  403. # error "Unknown platform."
  404. # endif // defined(DAWN_ENABLE_BACKEND_*)
  405. if (BX_ENABLED(BGFX_CONFIG_DEBUG))
  406. {
  407. m_instance.EnableBackendValidation(true);
  408. }
  409. m_instance.DiscoverDefaultAdapters();
  410. dawn_native::Adapter backendAdapter;
  411. std::vector<dawn_native::Adapter> adapters = m_instance.GetAdapters();
  412. for (dawn_native::Adapter& adapter : adapters)
  413. {
  414. if (adapter.GetBackendType() == backendType)
  415. {
  416. backendAdapter = adapter;
  417. break;
  418. }
  419. }
  420. //BX_ASSERT(adapterIt != adapters.end());
  421. WGPUDevice backendDevice = backendAdapter.CreateDevice();
  422. DawnProcTable backendProcs = dawn_native::GetProcs();
  423. using CreateSwapChain = DawnSwapChainImplementation (*)(wgpu::Device device, void* nwh);
  424. # if defined(DAWN_ENABLE_BACKEND_D3D12)
  425. createSwapChain = CreateSwapChainD3D12;
  426. # elif defined(DAWN_ENABLE_BACKEND_METAL)
  427. createSwapChain = CreateSwapChainMetal;
  428. # elif defined(DAWN_ENABLE_BACKEND_NULL)
  429. createSwapChain = CreateSwapChainNull;
  430. # elif defined(DAWN_ENABLE_BACKEND_OPENGL)
  431. createSwapChain = CreateSwapChainOpenGL;
  432. # elif defined(DAWN_ENABLE_BACKEND_VULKAN)
  433. createSwapChain = CreateSwapChainVulkan;
  434. # endif // defined(DAWN_ENABLE_BACKEND_*)
  435. // Choose whether to use the backend procs and devices directly, or set up the wire.
  436. WGPUDevice cDevice = backendDevice;
  437. DawnProcTable procs = backendProcs;
  438. dawnProcSetProcs(&procs);
  439. m_device = wgpu::Device::Acquire(cDevice);
  440. #else
  441. m_device = wgpu::Device(emscripten_webgpu_get_device());
  442. #endif // !BX_PLATFORM_EMSCRIPTEN
  443. auto PrintDeviceError = [](WGPUErrorType errorType, const char* message, void*) {
  444. BX_UNUSED(errorType);
  445. if (s_ignoreError)
  446. {
  447. BX_TRACE("Device error: %s", message);
  448. }
  449. else
  450. {
  451. BX_CHECK(false, "Device error: %s", message);
  452. }
  453. s_ignoreError = false;
  454. };
  455. m_device.SetUncapturedErrorCallback(PrintDeviceError, NULL);
  456. if (!m_device)
  457. {
  458. BX_WARN(!m_device, "Unable to create WebGPU device.");
  459. return false;
  460. }
  461. bool success = m_mainFrameBuffer.create(
  462. 0
  463. , g_platformData.nwh
  464. , _init.resolution.width
  465. , _init.resolution.height
  466. , TextureFormat::Unknown
  467. , TextureFormat::UnknownDepth
  468. );
  469. m_numWindows = 1;
  470. if (!success)
  471. {
  472. return false;
  473. }
  474. m_queue = m_device.GetDefaultQueue();
  475. m_cmd.init(m_queue);
  476. //BGFX_FATAL(NULL != m_cmd.m_commandQueue, Fatal::UnableToInitialize, "Unable to create Metal device.");
  477. for (uint8_t ii = 0; ii < WEBGPU_MAX_FRAMES_IN_FLIGHT; ++ii)
  478. {
  479. BX_TRACE("Create scratch buffer %d", ii);
  480. m_scratchBuffers[ii].create(BGFX_CONFIG_MAX_DRAW_CALLS * 128);
  481. m_bindStateCache[ii].create(); // (1024);
  482. }
  483. for (uint8_t ii = 0; ii < WEBGPU_NUM_UNIFORM_BUFFERS; ++ii)
  484. {
  485. bool mapped = true; // ii == WEBGPU_NUM_UNIFORM_BUFFERS - 1;
  486. m_uniformBuffers[ii].create(BGFX_CONFIG_MAX_DRAW_CALLS * 128, mapped);
  487. }
  488. g_caps.supported |= (0
  489. | BGFX_CAPS_ALPHA_TO_COVERAGE
  490. | BGFX_CAPS_BLEND_INDEPENDENT
  491. | BGFX_CAPS_FRAGMENT_DEPTH
  492. | BGFX_CAPS_INDEX32
  493. | BGFX_CAPS_INSTANCING
  494. // | BGFX_CAPS_OCCLUSION_QUERY
  495. | BGFX_CAPS_SWAP_CHAIN
  496. | BGFX_CAPS_TEXTURE_2D_ARRAY
  497. // | BGFX_CAPS_TEXTURE_3D
  498. | BGFX_CAPS_TEXTURE_BLIT
  499. | BGFX_CAPS_TEXTURE_COMPARE_ALL
  500. | BGFX_CAPS_TEXTURE_COMPARE_LEQUAL
  501. | BGFX_CAPS_TEXTURE_READ_BACK
  502. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  503. | BGFX_CAPS_VERTEX_ATTRIB_UINT10
  504. | BGFX_CAPS_COMPUTE
  505. );
  506. g_caps.limits.maxTextureSize = 8192;
  507. g_caps.limits.maxFBAttachments = 4;
  508. g_caps.supported |= BGFX_CAPS_TEXTURE_CUBE_ARRAY;
  509. g_caps.supported |= BGFX_CAPS_DRAW_INDIRECT;
  510. g_caps.limits.maxTextureLayers = 2048;
  511. g_caps.limits.maxVertexStreams = BGFX_CONFIG_MAX_VERTEX_STREAMS;
  512. // Maximum number of entries in the buffer argument table, per graphics or compute function are 31.
  513. // It is decremented by 1 because 1 entry is used for uniforms.
  514. g_caps.limits.maxComputeBindings = bx::uint32_min(30, BGFX_MAX_COMPUTE_BINDINGS);
  515. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  516. {
  517. uint16_t support = 0;
  518. support |= wgpu::TextureFormat::Undefined != s_textureFormat[ii].m_fmt
  519. ? BGFX_CAPS_FORMAT_TEXTURE_2D
  520. | BGFX_CAPS_FORMAT_TEXTURE_3D
  521. | BGFX_CAPS_FORMAT_TEXTURE_CUBE
  522. | BGFX_CAPS_FORMAT_TEXTURE_VERTEX
  523. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  524. ;
  525. support |= wgpu::TextureFormat::Undefined != s_textureFormat[ii].m_fmtSrgb
  526. ? BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  527. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  528. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  529. | BGFX_CAPS_FORMAT_TEXTURE_VERTEX
  530. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  531. ;
  532. if (!bimg::isCompressed(bimg::TextureFormat::Enum(ii) ) )
  533. {
  534. support |= 0
  535. | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  536. // | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA
  537. ;
  538. }
  539. g_caps.formats[ii] = support;
  540. }
  541. g_caps.formats[TextureFormat::A8 ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  542. g_caps.formats[TextureFormat::RG32I ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  543. g_caps.formats[TextureFormat::RG32U ] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  544. g_caps.formats[TextureFormat::RGBA32I] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  545. g_caps.formats[TextureFormat::RGBA32U] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  546. g_caps.formats[TextureFormat::ETC2 ] =
  547. g_caps.formats[TextureFormat::ETC2A ] =
  548. g_caps.formats[TextureFormat::ETC2A1] =
  549. g_caps.formats[TextureFormat::PTC12 ] =
  550. g_caps.formats[TextureFormat::PTC14 ] =
  551. g_caps.formats[TextureFormat::PTC12A] =
  552. g_caps.formats[TextureFormat::PTC14A] =
  553. g_caps.formats[TextureFormat::R5G6B5] =
  554. g_caps.formats[TextureFormat::RGBA4 ] =
  555. g_caps.formats[TextureFormat::RGB5A1] = BGFX_CAPS_FORMAT_TEXTURE_NONE;
  556. g_caps.formats[TextureFormat::RGB9E5F] &= ~(BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA);
  557. // disable compressed formats
  558. for (uint32_t ii = 0; ii < TextureFormat::Unknown; ++ii)
  559. {
  560. s_textureFormat[ii].m_fmt = wgpu::TextureFormat::Undefined;
  561. }
  562. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  563. {
  564. if (BGFX_CAPS_FORMAT_TEXTURE_NONE == g_caps.formats[ii])
  565. {
  566. s_textureFormat[ii].m_fmt = wgpu::TextureFormat::Undefined;
  567. s_textureFormat[ii].m_fmtSrgb = wgpu::TextureFormat::Undefined;
  568. }
  569. }
  570. for (uint32_t ii = 1, last = 0; ii < BX_COUNTOF(s_msaa); ++ii)
  571. {
  572. // TODO (hugoam)
  573. //const int32_t sampleCount = 1; //1<<ii;
  574. //if (m_device.supportsTextureSampleCount(sampleCount) )
  575. //{
  576. // s_msaa[ii] = sampleCount;
  577. // last = ii;
  578. //}
  579. //else
  580. {
  581. s_msaa[ii] = s_msaa[last];
  582. }
  583. }
  584. // Init reserved part of view name.
  585. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  586. {
  587. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii);
  588. }
  589. m_gpuTimer.init();
  590. g_internalData.context = &m_device;
  591. return true;
  592. }
  593. void shutdown()
  594. {
  595. m_gpuTimer.shutdown();
  596. m_pipelineStateCache.invalidate();
  597. for (uint32_t ii = 0; ii < BX_COUNTOF(m_shaders); ++ii)
  598. {
  599. m_shaders[ii].destroy();
  600. }
  601. for (uint32_t ii = 0; ii < BX_COUNTOF(m_textures); ++ii)
  602. {
  603. m_textures[ii].destroy();
  604. }
  605. captureFinish();
  606. m_mainFrameBuffer.destroy();
  607. for (uint32_t ii = 0; ii < BX_COUNTOF(m_scratchBuffers); ++ii)
  608. {
  609. m_scratchBuffers[ii].destroy();
  610. }
  611. m_cmd.shutdown();
  612. }
  613. RendererType::Enum getRendererType() const override
  614. {
  615. return RendererType::WebGPU;
  616. }
  617. const char* getRendererName() const override
  618. {
  619. return BGFX_RENDERER_WEBGPU_NAME;
  620. }
  621. void createIndexBuffer(IndexBufferHandle _handle, const Memory* _mem, uint16_t _flags) override
  622. {
  623. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  624. }
  625. void destroyIndexBuffer(IndexBufferHandle _handle) override
  626. {
  627. m_indexBuffers[_handle.idx].destroy();
  628. }
  629. void createVertexLayout(VertexLayoutHandle _handle, const VertexLayout& _decl) override
  630. {
  631. VertexLayout& decl = m_vertexDecls[_handle.idx];
  632. bx::memCopy(&decl, &_decl, sizeof(VertexLayout) );
  633. dump(decl);
  634. }
  635. void destroyVertexLayout(VertexLayoutHandle /*_handle*/) override
  636. {
  637. }
  638. void createVertexBuffer(VertexBufferHandle _handle, const Memory* _mem, VertexLayoutHandle _declHandle, uint16_t _flags) override
  639. {
  640. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle, _flags);
  641. }
  642. void destroyVertexBuffer(VertexBufferHandle _handle) override
  643. {
  644. m_vertexBuffers[_handle.idx].destroy();
  645. }
  646. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) override
  647. {
  648. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  649. }
  650. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override
  651. {
  652. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  653. }
  654. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) override
  655. {
  656. m_indexBuffers[_handle.idx].destroy();
  657. }
  658. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) override
  659. {
  660. VertexLayoutHandle decl = BGFX_INVALID_HANDLE;
  661. m_vertexBuffers[_handle.idx].create(_size, NULL, decl, _flags);
  662. }
  663. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, const Memory* _mem) override
  664. {
  665. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  666. }
  667. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) override
  668. {
  669. m_vertexBuffers[_handle.idx].destroy();
  670. }
  671. void createShader(ShaderHandle _handle, const Memory* _mem) override
  672. {
  673. m_shaders[_handle.idx].create(_handle, _mem);
  674. }
  675. void destroyShader(ShaderHandle _handle) override
  676. {
  677. m_shaders[_handle.idx].destroy();
  678. }
  679. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) override
  680. {
  681. m_program[_handle.idx].create(&m_shaders[_vsh.idx], isValid(_fsh) ? &m_shaders[_fsh.idx] : NULL);
  682. }
  683. void destroyProgram(ProgramHandle _handle) override
  684. {
  685. m_program[_handle.idx].destroy();
  686. }
  687. void* createTexture(TextureHandle _handle, const Memory* _mem, uint64_t _flags, uint8_t _skip) override
  688. {
  689. m_textures[_handle.idx].create(_handle, _mem, _flags, _skip);
  690. return NULL;
  691. }
  692. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) override
  693. {
  694. }
  695. void updateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) override
  696. {
  697. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  698. }
  699. void updateTextureEnd() override
  700. {
  701. }
  702. void readback(ReadbackWgpu& readback, const TextureWgpu& texture, void* _data)
  703. {
  704. m_cmd.kick(false, true);
  705. m_cmd.beginRender();
  706. if (readback.m_mapped)
  707. return;
  708. BX_CHECK(readback.m_mip<texture.m_numMips,"Invalid mip: %d num mips:", readback.m_mip,texture.m_numMips);
  709. uint32_t srcWidth = bx::uint32_max(1, texture.m_width >> readback.m_mip);
  710. uint32_t srcHeight = bx::uint32_max(1, texture.m_height >> readback.m_mip);
  711. const uint32_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(texture.m_textureFormat));
  712. const uint32_t pitch = srcWidth * bpp / 8;
  713. const uint32_t dstpitch = bx::strideAlign(pitch, kMinBufferOffsetAlignment);
  714. // TODO move inside ReadbackWgpu::create
  715. if (!readback.m_buffer)
  716. {
  717. wgpu::BufferDescriptor desc;
  718. desc.size = dstpitch * srcHeight;
  719. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead;
  720. readback.m_buffer = m_device.CreateBuffer(&desc);
  721. }
  722. wgpu::TextureCopyView textureCopyView;
  723. textureCopyView.texture = texture.m_ptr;
  724. textureCopyView.origin = { 0, 0, 0 };
  725. wgpu::BufferCopyView bufferCopyView;
  726. bufferCopyView.buffer = readback.m_buffer;
  727. bufferCopyView.bytesPerRow = dstpitch;
  728. bufferCopyView.rowsPerImage = srcHeight;
  729. wgpu::Extent3D extent3D = { srcWidth, srcHeight, 1 };
  730. getBlitCommandEncoder().CopyTextureToBuffer(&textureCopyView, &bufferCopyView, &extent3D);
  731. auto finish = [](WGPUBufferMapAsyncStatus status, void const* data, uint64_t dataLength, void* userdata)
  732. {
  733. if(status == WGPUBufferMapAsyncStatus_Success)
  734. static_cast<ReadbackWgpu*>(userdata)->readback(data, dataLength);
  735. };
  736. m_cmd.finish();
  737. m_cmd.kick(true);
  738. readback.m_mapped = true;
  739. readback.m_data = _data;
  740. readback.m_size = pitch * srcHeight;
  741. readback.m_buffer.MapReadAsync(finish, &readback);
  742. }
  743. void readTexture(TextureHandle _handle, void* _data, uint8_t _mip) override
  744. {
  745. TextureWgpu& texture = m_textures[_handle.idx];
  746. readback(texture.m_readback, texture, _data);
  747. }
  748. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips, uint16_t _numLayers) override
  749. {
  750. TextureWgpu& texture = m_textures[_handle.idx];
  751. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  752. const Memory* mem = alloc(size);
  753. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  754. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  755. bx::write(&writer, magic);
  756. TextureCreate tc;
  757. tc.m_width = _width;
  758. tc.m_height = _height;
  759. tc.m_depth = 0;
  760. tc.m_numLayers = _numLayers;
  761. tc.m_numMips = _numMips;
  762. tc.m_format = TextureFormat::Enum(texture.m_requestedFormat);
  763. tc.m_cubeMap = false;
  764. tc.m_mem = NULL;
  765. bx::write(&writer, tc);
  766. texture.destroy();
  767. texture.create(_handle, mem, texture.m_flags, 0);
  768. release(mem);
  769. }
  770. void overrideInternal(TextureHandle _handle, uintptr_t _ptr) override
  771. {
  772. BX_UNUSED(_handle, _ptr);
  773. }
  774. uintptr_t getInternal(TextureHandle _handle) override
  775. {
  776. BX_UNUSED(_handle);
  777. return 0;
  778. }
  779. void destroyTexture(TextureHandle _handle) override
  780. {
  781. m_textures[_handle.idx].destroy();
  782. }
  783. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const Attachment* _attachment) override
  784. {
  785. m_frameBuffers[_handle.idx].create(_num, _attachment);
  786. }
  787. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat) override
  788. {
  789. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  790. {
  791. FrameBufferHandle handle = m_windows[ii];
  792. if (isValid(handle)
  793. && m_frameBuffers[handle.idx].m_nwh == _nwh)
  794. {
  795. destroyFrameBuffer(handle);
  796. }
  797. }
  798. uint16_t denseIdx = m_numWindows++;
  799. m_windows[denseIdx] = _handle;
  800. FrameBufferWgpu& fb = m_frameBuffers[_handle.idx];
  801. fb.create(denseIdx, _nwh, _width, _height, _format, _depthFormat);
  802. fb.m_swapChain->resize(m_frameBuffers[_handle.idx], _width, _height, 0);
  803. }
  804. void destroyFrameBuffer(FrameBufferHandle _handle) override
  805. {
  806. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  807. if (UINT16_MAX != denseIdx)
  808. {
  809. --m_numWindows;
  810. if (m_numWindows > 1)
  811. {
  812. FrameBufferHandle handle = m_windows[m_numWindows];
  813. m_windows[m_numWindows] = {kInvalidHandle};
  814. if (m_numWindows != denseIdx)
  815. {
  816. m_windows[denseIdx] = handle;
  817. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  818. }
  819. }
  820. }
  821. }
  822. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) override
  823. {
  824. if (NULL != m_uniforms[_handle.idx])
  825. {
  826. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  827. }
  828. uint32_t size = bx::alignUp(g_uniformTypeSize[_type]*_num, 16);
  829. void* data = BX_ALLOC(g_allocator, size);
  830. bx::memSet(data, 0, size);
  831. m_uniforms[_handle.idx] = data;
  832. m_uniformReg.add(_handle, _name);
  833. }
  834. void destroyUniform(UniformHandle _handle) override
  835. {
  836. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  837. m_uniforms[_handle.idx] = NULL;
  838. m_uniformReg.remove(_handle);
  839. }
  840. void requestScreenShotPre(const char* _filePath)
  841. {
  842. BX_UNUSED(_filePath);
  843. //m_saveScreenshot = true;
  844. }
  845. void requestScreenShot(FrameBufferHandle _handle, const char* _filePath) override
  846. {
  847. BX_UNUSED(_handle); BX_UNUSED(_filePath);
  848. }
  849. void updateViewName(ViewId _id, const char* _name) override
  850. {
  851. bx::strCopy(
  852. &s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  853. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  854. , _name
  855. );
  856. }
  857. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) override
  858. {
  859. bx::memCopy(m_uniforms[_loc], _data, _size);
  860. }
  861. void invalidateOcclusionQuery(OcclusionQueryHandle _handle) override
  862. {
  863. BX_UNUSED(_handle);
  864. }
  865. void setMarker(const char* _marker, uint16_t _len) override
  866. {
  867. BX_UNUSED(_len);
  868. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  869. {
  870. m_renderEncoder.InsertDebugMarker(_marker);
  871. }
  872. }
  873. virtual void setName(Handle _handle, const char* _name, uint16_t _len) override
  874. {
  875. BX_UNUSED(_handle); BX_UNUSED(_name); BX_UNUSED(_len);
  876. BX_UNUSED(_len);
  877. switch (_handle.type)
  878. {
  879. case Handle::IndexBuffer:
  880. m_indexBuffers[_handle.idx].m_label.clear();
  881. m_indexBuffers[_handle.idx].m_label.append(_name);
  882. break;
  883. case Handle::Shader:
  884. m_shaders[_handle.idx].m_label.clear();
  885. m_shaders[_handle.idx].m_label.append(_name);
  886. break;
  887. case Handle::Texture:
  888. m_textures[_handle.idx].m_label.clear();
  889. m_textures[_handle.idx].m_label.append(_name);
  890. break;
  891. case Handle::VertexBuffer:
  892. m_vertexBuffers[_handle.idx].m_label.clear();
  893. m_vertexBuffers[_handle.idx].m_label.append(_name);
  894. break;
  895. default:
  896. BX_CHECK(false, "Invalid handle type?! %d", _handle.type);
  897. break;
  898. }
  899. }
  900. void submitBlit(BlitState& _bs, uint16_t _view);
  901. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) override;
  902. void blitSetup(TextVideoMemBlitter& _blitter) override
  903. {
  904. BX_UNUSED(_blitter);
  905. }
  906. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) override
  907. {
  908. const uint32_t numVertices = _numIndices*4/6;
  909. if (0 < numVertices)
  910. {
  911. m_indexBuffers [_blitter.m_ib->handle.idx].update(
  912. 0
  913. , bx::strideAlign(_numIndices*2, 4)
  914. , _blitter.m_ib->data
  915. , true
  916. );
  917. m_vertexBuffers[_blitter.m_vb->handle.idx].update(
  918. 0
  919. , numVertices*_blitter.m_layout.m_stride
  920. , _blitter.m_vb->data
  921. , true
  922. );
  923. endEncoding();
  924. uint32_t width = m_resolution.width;
  925. uint32_t height = m_resolution.height;
  926. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  927. uint64_t state = 0
  928. | BGFX_STATE_WRITE_RGB
  929. | BGFX_STATE_WRITE_A
  930. | BGFX_STATE_DEPTH_TEST_ALWAYS
  931. ;
  932. PipelineStateWgpu* pso = getPipelineState(
  933. state
  934. , 0
  935. , 0
  936. , fbh
  937. , _blitter.m_vb->layoutHandle
  938. , false
  939. , _blitter.m_program
  940. , 0
  941. );
  942. RenderPassDescriptor renderPassDescriptor;
  943. wgpu::RenderPassColorAttachmentDescriptor& color = renderPassDescriptor.colorAttachments[0];
  944. setFrameBuffer(renderPassDescriptor, fbh);
  945. color.loadOp = wgpu::LoadOp::Load;
  946. color.storeOp = wgpu::StoreOp::Store;
  947. // NULL != renderPassDescriptor.colorAttachments[0].resolveTexture
  948. // ? wgpu::StoreOp::MultisampleResolve
  949. // : wgpu::StoreOp::Store
  950. //;
  951. wgpu::RenderPassEncoder rce = m_cmd.m_renderEncoder.BeginRenderPass(&renderPassDescriptor.desc);
  952. m_renderEncoder = rce;
  953. rce.SetViewport(0.0f, 0.0f, (float)width, (float)height, 0.0f, 1.0f);
  954. rce.SetScissorRect(0.0f, 0.0f, (float)width, (float)height);
  955. rce.SetPipeline(pso->m_rps);
  956. ProgramWgpu& program = m_program[_blitter.m_program.idx];
  957. ScratchBufferWgpu& scratchBuffer = m_scratchBuffers[0];
  958. BindStateCacheWgpu& bindStates = m_bindStateCache[0];
  959. float proj[16];
  960. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f, 0.0f, false);
  961. PredefinedUniform& predefined = program.m_predefined[0];
  962. uint8_t flags = predefined.m_type;
  963. setShaderUniform(flags, predefined.m_loc, proj, 4);
  964. BX_CHECK(program.m_vsh->m_size > 0, "Not supposed to happen");
  965. const uint32_t voffset = scratchBuffer.write(m_vsScratch, program.m_vsh->m_gpuSize);
  966. const uint32_t fsize = (NULL != program.m_fsh ? program.m_fsh->m_gpuSize : 0);
  967. BX_CHECK(fsize == 0, "Not supposed to happen");
  968. TextureWgpu& texture = m_textures[_blitter.m_texture.idx];
  969. BindingsWgpu b;
  970. BindStateWgpu& bindState = allocBindState(program, bindStates, b, scratchBuffer);
  971. wgpu::BindGroupEntry& textureEntry = b.m_entries[b.numEntries++];
  972. textureEntry.binding = program.m_textures[0].binding;
  973. textureEntry.textureView = texture.m_ptr.CreateView();
  974. wgpu::BindGroupEntry& samplerEntry = b.m_entries[b.numEntries++];
  975. samplerEntry.binding = program.m_samplers[0].binding;
  976. samplerEntry.sampler = 0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & state)
  977. ? getSamplerState(state)
  978. : texture.m_sampler;
  979. bindGroups(program, bindState, b);
  980. uint32_t numOffset = 1;
  981. uint32_t offsets[1] = { voffset };
  982. bindProgram(rce, program, bindState, numOffset, offsets);
  983. VertexBufferWgpu& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  984. rce.SetVertexBuffer(0, vb.m_ptr);
  985. rce.SetIndexBuffer(m_indexBuffers[_blitter.m_ib->handle.idx].m_ptr);
  986. rce.DrawIndexed(_numIndices, 1, 0, 0, 0);
  987. }
  988. }
  989. bool isDeviceRemoved() override
  990. {
  991. return false;
  992. }
  993. void flip() override
  994. {
  995. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  996. {
  997. FrameBufferWgpu& frameBuffer = ii == 0 ? m_mainFrameBuffer : m_frameBuffers[m_windows[ii].idx];
  998. if (NULL != frameBuffer.m_swapChain)
  999. //&& frameBuffer.m_swapChain->m_drawable)
  1000. {
  1001. SwapChainWgpu& swapChain = *frameBuffer.m_swapChain;
  1002. swapChain.flip();
  1003. }
  1004. }
  1005. m_cmd.m_stagingEncoder = NULL;
  1006. m_cmd.m_renderEncoder = NULL;
  1007. }
  1008. void updateResolution(const Resolution& _resolution)
  1009. {
  1010. m_resolution = _resolution;
  1011. return; // TODO (hugoam)
  1012. m_mainFrameBuffer.m_swapChain->m_maxAnisotropy = !!(_resolution.reset & BGFX_RESET_MAXANISOTROPY)
  1013. ? 16
  1014. : 1
  1015. ;
  1016. const uint32_t maskFlags = ~(0
  1017. | BGFX_RESET_MAXANISOTROPY
  1018. | BGFX_RESET_DEPTH_CLAMP
  1019. | BGFX_RESET_SUSPEND
  1020. );
  1021. if (m_resolution.width != _resolution.width
  1022. || m_resolution.height != _resolution.height
  1023. || (m_resolution.reset&maskFlags) != (_resolution.reset&maskFlags) )
  1024. {
  1025. wgpu::TextureFormat prevMetalLayerPixelFormat; // = m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat;
  1026. BX_UNUSED(prevMetalLayerPixelFormat);
  1027. m_resolution = _resolution;
  1028. m_resolution.reset &= ~BGFX_RESET_INTERNAL_FORCE;
  1029. m_mainFrameBuffer.m_swapChain->resize(m_mainFrameBuffer, _resolution.width, _resolution.height, _resolution.reset);
  1030. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  1031. {
  1032. m_frameBuffers[ii].postReset();
  1033. }
  1034. updateCapture();
  1035. m_textVideoMem.resize(false, _resolution.width, _resolution.height);
  1036. m_textVideoMem.clear();
  1037. //if (prevMetalLayerPixelFormat != m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat)
  1038. {
  1039. //MTL_RELEASE(m_screenshotBlitRenderPipelineState)
  1040. //reset(m_renderPipelineDescriptor);
  1041. //m_renderPipelineDescriptor.colorAttachments[0].pixelFormat = m_mainFrameBuffer.m_swapChain->m_metalLayer.pixelFormat;
  1042. //m_renderPipelineDescriptor.vertexFunction = m_screenshotBlitProgram.m_vsh->m_function;
  1043. //m_renderPipelineDescriptor.fragmentFunction = m_screenshotBlitProgram.m_fsh->m_function;
  1044. //m_screenshotBlitRenderPipelineState = m_device.newRenderPipelineStateWithDescriptor(m_renderPipelineDescriptor);
  1045. }
  1046. }
  1047. }
  1048. void invalidateCompute()
  1049. {
  1050. if (m_computeEncoder)
  1051. {
  1052. m_computeEncoder.EndPass();
  1053. m_computeEncoder = NULL;
  1054. }
  1055. }
  1056. void updateCapture()
  1057. {
  1058. }
  1059. void capture()
  1060. {
  1061. }
  1062. void captureFinish()
  1063. {
  1064. }
  1065. BindStateWgpu& allocBindState(const ProgramWgpu& program, BindStateCacheWgpu& bindStates, BindingsWgpu& bindings, ScratchBufferWgpu& scratchBuffer)
  1066. {
  1067. BindStateWgpu& bindState = bindStates.m_bindStates[bindStates.m_currentBindState];
  1068. bindStates.m_currentBindState++;
  1069. bindState.numOffset = program.m_numUniforms;
  1070. // first two bindings are always uniform buffer (vertex/fragment)
  1071. bindings.m_entries[0].binding = 0;
  1072. bindings.m_entries[0].offset = 0;
  1073. bindings.m_entries[0].size = program.m_vsh->m_gpuSize;
  1074. bindings.m_entries[0].buffer = scratchBuffer.m_buffer;
  1075. bindings.numEntries++;
  1076. if (NULL != program.m_fsh
  1077. && 0 < program.m_fsh->m_gpuSize)
  1078. {
  1079. bindings.m_entries[1].binding = 48;
  1080. bindings.m_entries[1].offset = 0;
  1081. bindings.m_entries[1].size = program.m_fsh->m_gpuSize;
  1082. bindings.m_entries[1].buffer = scratchBuffer.m_buffer;
  1083. bindings.numEntries++;
  1084. }
  1085. return bindState;
  1086. }
  1087. void bindGroups(const ProgramWgpu& program, BindStateWgpu& bindState, BindingsWgpu& bindings)
  1088. {
  1089. wgpu::BindGroupDescriptor bindGroupDesc;
  1090. bindGroupDesc.layout = program.m_bindGroupLayout;
  1091. bindGroupDesc.entryCount = bindings.numEntries;
  1092. bindGroupDesc.entries = bindings.m_entries;
  1093. bindState.m_bindGroup = m_device.CreateBindGroup(&bindGroupDesc);
  1094. }
  1095. template <class Encoder>
  1096. void bindProgram(Encoder& encoder, const ProgramWgpu& program, BindStateWgpu& bindState, uint32_t numOffset, uint32_t* offsets)
  1097. {
  1098. BX_CHECK(bindState.numOffset == numOffset, "We're obviously doing something wrong");
  1099. encoder.SetBindGroup(0, bindState.m_bindGroup, numOffset, offsets);
  1100. }
  1101. BindStateWgpu& allocAndFillBindState(const ProgramWgpu& program, BindStateCacheWgpu& bindStates, ScratchBufferWgpu& scratchBuffer, const RenderBind& renderBind)
  1102. {
  1103. BindingsWgpu b;
  1104. BindStateWgpu& bindState = allocBindState(program, bindStates, b, scratchBuffer);
  1105. for (uint8_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  1106. {
  1107. const Binding& bind = renderBind.m_bind[stage];
  1108. const BindInfo& bindInfo = program.m_bindInfo[stage];
  1109. bool isUsed = isValid(program.m_bindInfo[stage].m_uniform);
  1110. BX_CHECK(!isUsed || kInvalidHandle != bind.m_idx, "All expected bindings must be bound with WebGPU");
  1111. if (kInvalidHandle != bind.m_idx)
  1112. {
  1113. switch (bind.m_type)
  1114. {
  1115. case Binding::Image:
  1116. {
  1117. TextureWgpu& texture = m_textures[bind.m_idx];
  1118. wgpu::BindGroupEntry& entry = b.m_entries[b.numEntries++];
  1119. entry.binding = bindInfo.m_binding;
  1120. entry.textureView = texture.getTextureMipLevel(bind.m_mip);
  1121. }
  1122. break;
  1123. case Binding::Texture:
  1124. {
  1125. // apparently bgfx allows to set a texture to a stage that a program does not even use
  1126. if (isUsed)
  1127. {
  1128. TextureWgpu& texture = m_textures[bind.m_idx];
  1129. uint32_t flags = bind.m_samplerFlags;
  1130. wgpu::TextureViewDescriptor viewDesc = defaultDescriptor<wgpu::TextureViewDescriptor>();
  1131. viewDesc.dimension = program.m_textures[bindInfo.m_index].viewDimension;
  1132. wgpu::BindGroupEntry& textureEntry = b.m_entries[b.numEntries++];
  1133. textureEntry.binding = bindInfo.m_binding;
  1134. //textureEntry.textureView = texture.m_ptr.CreateView();
  1135. textureEntry.textureView = texture.m_ptr.CreateView(&viewDesc);
  1136. wgpu::BindGroupEntry& samplerEntry = b.m_entries[b.numEntries++];
  1137. samplerEntry.binding = bindInfo.m_binding + 16;
  1138. samplerEntry.sampler = 0 == (BGFX_SAMPLER_INTERNAL_DEFAULT & flags)
  1139. ? getSamplerState(flags)
  1140. : texture.m_sampler;
  1141. }
  1142. }
  1143. break;
  1144. case Binding::IndexBuffer:
  1145. case Binding::VertexBuffer:
  1146. {
  1147. const BufferWgpu& buffer = Binding::IndexBuffer == bind.m_type
  1148. ? m_indexBuffers[bind.m_idx]
  1149. : m_vertexBuffers[bind.m_idx]
  1150. ;
  1151. wgpu::BindGroupEntry& entry = b.m_entries[b.numEntries++];
  1152. entry.binding = bindInfo.m_binding;
  1153. entry.offset = 0;
  1154. entry.size = buffer.m_size;
  1155. entry.buffer = buffer.m_ptr;
  1156. }
  1157. break;
  1158. }
  1159. }
  1160. }
  1161. bindGroups(program, bindState, b);
  1162. return bindState;
  1163. };
  1164. void setShaderUniform(uint8_t _flags, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1165. {
  1166. if(_flags&BGFX_UNIFORM_FRAGMENTBIT)
  1167. {
  1168. bx::memCopy(&m_fsScratch[_regIndex], _val, _numRegs * 16);
  1169. }
  1170. else
  1171. {
  1172. bx::memCopy(&m_vsScratch[_regIndex], _val, _numRegs * 16);
  1173. }
  1174. }
  1175. void setShaderUniform4f(uint8_t _flags, uint32_t _loc, const void* _val, uint32_t _numRegs)
  1176. {
  1177. setShaderUniform(_flags, _loc, _val, _numRegs);
  1178. }
  1179. void setShaderUniform4x4f(uint8_t _flags, uint32_t _loc, const void* _val, uint32_t _numRegs)
  1180. {
  1181. setShaderUniform(_flags, _loc, _val, _numRegs);
  1182. }
  1183. void commitShaderConstants(ScratchBufferWgpu& _scratchBuffer, const ProgramWgpu& _program, uint32_t _vertexOffset, uint32_t _fragmentOffset)
  1184. {
  1185. const uint32_t size = _program.m_vsh->m_gpuSize;
  1186. if (0 != size)
  1187. _scratchBuffer.write(m_vsScratch, size);
  1188. if(NULL != _program.m_fsh)
  1189. {
  1190. const uint32_t size = _program.m_fsh->m_gpuSize;
  1191. if(0 != size)
  1192. _scratchBuffer.write(m_fsScratch, size);
  1193. }
  1194. }
  1195. void commit(UniformBuffer& _uniformBuffer)
  1196. {
  1197. _uniformBuffer.reset();
  1198. for (;;)
  1199. {
  1200. uint32_t opcode = _uniformBuffer.read();
  1201. if (UniformType::End == opcode)
  1202. {
  1203. break;
  1204. }
  1205. UniformType::Enum type;
  1206. uint16_t loc;
  1207. uint16_t num;
  1208. uint16_t copy;
  1209. UniformBuffer::decodeOpcode(opcode, type, loc, num, copy);
  1210. const char* data;
  1211. if (copy)
  1212. {
  1213. data = _uniformBuffer.read(g_uniformTypeSize[type]*num);
  1214. }
  1215. else
  1216. {
  1217. UniformHandle handle;
  1218. bx::memCopy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  1219. data = (const char*)m_uniforms[handle.idx];
  1220. }
  1221. switch ( (uint32_t)type)
  1222. {
  1223. case UniformType::Mat3:
  1224. case UniformType::Mat3|BGFX_UNIFORM_FRAGMENTBIT:
  1225. {
  1226. float* value = (float*)data;
  1227. for (uint32_t ii = 0, count = num/3; ii < count; ++ii, loc += 3*16, value += 9)
  1228. {
  1229. Matrix4 mtx;
  1230. mtx.un.val[ 0] = value[0];
  1231. mtx.un.val[ 1] = value[1];
  1232. mtx.un.val[ 2] = value[2];
  1233. mtx.un.val[ 3] = 0.0f;
  1234. mtx.un.val[ 4] = value[3];
  1235. mtx.un.val[ 5] = value[4];
  1236. mtx.un.val[ 6] = value[5];
  1237. mtx.un.val[ 7] = 0.0f;
  1238. mtx.un.val[ 8] = value[6];
  1239. mtx.un.val[ 9] = value[7];
  1240. mtx.un.val[10] = value[8];
  1241. mtx.un.val[11] = 0.0f;
  1242. setShaderUniform(uint8_t(type), loc, &mtx.un.val[0], 3);
  1243. }
  1244. }
  1245. break;
  1246. case UniformType::Sampler:
  1247. case UniformType::Sampler | BGFX_UNIFORM_FRAGMENTBIT:
  1248. case UniformType::Vec4:
  1249. case UniformType::Vec4 | BGFX_UNIFORM_FRAGMENTBIT:
  1250. case UniformType::Mat4:
  1251. case UniformType::Mat4 | BGFX_UNIFORM_FRAGMENTBIT:
  1252. {
  1253. setShaderUniform(uint8_t(type), loc, data, num);
  1254. }
  1255. break;
  1256. case UniformType::End:
  1257. break;
  1258. default:
  1259. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy);
  1260. break;
  1261. }
  1262. }
  1263. }
  1264. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, const float _palette[][4])
  1265. {
  1266. uint32_t width;
  1267. uint32_t height;
  1268. if (isValid(m_fbh) )
  1269. {
  1270. const FrameBufferWgpu& fb = m_frameBuffers[m_fbh.idx];
  1271. width = fb.m_width;
  1272. height = fb.m_height;
  1273. }
  1274. else
  1275. {
  1276. width = m_resolution.width;
  1277. height = m_resolution.height;
  1278. }
  1279. uint64_t state = 0;
  1280. state |= _clear.m_flags & BGFX_CLEAR_COLOR ? BGFX_STATE_WRITE_RGB|BGFX_STATE_WRITE_A : 0;
  1281. state |= _clear.m_flags & BGFX_CLEAR_DEPTH ? BGFX_STATE_DEPTH_TEST_ALWAYS|BGFX_STATE_WRITE_Z : 0;
  1282. state |= BGFX_STATE_PT_TRISTRIP;
  1283. uint64_t stencil = 0;
  1284. stencil |= _clear.m_flags & BGFX_CLEAR_STENCIL ? 0
  1285. | BGFX_STENCIL_TEST_ALWAYS
  1286. | BGFX_STENCIL_FUNC_REF(_clear.m_stencil)
  1287. | BGFX_STENCIL_FUNC_RMASK(0xff)
  1288. | BGFX_STENCIL_OP_FAIL_S_REPLACE
  1289. | BGFX_STENCIL_OP_FAIL_Z_REPLACE
  1290. | BGFX_STENCIL_OP_PASS_Z_REPLACE
  1291. : 0
  1292. ;
  1293. uint32_t numMrt = 1;
  1294. FrameBufferHandle fbh = m_fbh;
  1295. if (isValid(fbh) && m_frameBuffers[fbh.idx].m_swapChain == NULL)
  1296. {
  1297. const FrameBufferWgpu& fb = m_frameBuffers[fbh.idx];
  1298. numMrt = bx::uint32_max(1, fb.m_num);
  1299. }
  1300. wgpu::RenderPassEncoder rce = m_renderEncoder;
  1301. ProgramHandle programHandle = _clearQuad.m_program[numMrt-1];
  1302. const VertexLayout* decl = &_clearQuad.m_layout;
  1303. const PipelineStateWgpu* pso = getPipelineState(
  1304. state
  1305. , stencil
  1306. , 0
  1307. , fbh
  1308. , 1
  1309. , &decl
  1310. , false
  1311. , programHandle
  1312. , 0
  1313. );
  1314. rce.SetPipeline(pso->m_rps);
  1315. float mrtClearColor[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  1316. float mrtClearDepth[4] = { _clear.m_depth };
  1317. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  1318. {
  1319. for (uint32_t ii = 0; ii < numMrt; ++ii)
  1320. {
  1321. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[ii]);
  1322. bx::memCopy(mrtClearColor[ii], _palette[index], 16);
  1323. }
  1324. }
  1325. else
  1326. {
  1327. float rgba[4] =
  1328. {
  1329. _clear.m_index[0]*1.0f/255.0f,
  1330. _clear.m_index[1]*1.0f/255.0f,
  1331. _clear.m_index[2]*1.0f/255.0f,
  1332. _clear.m_index[3]*1.0f/255.0f,
  1333. };
  1334. for (uint32_t ii = 0; ii < numMrt; ++ii)
  1335. {
  1336. bx::memCopy( mrtClearColor[ii]
  1337. , rgba
  1338. , 16
  1339. );
  1340. }
  1341. }
  1342. ProgramWgpu& program = m_program[programHandle.idx];
  1343. ScratchBufferWgpu& scratchBuffer = m_scratchBuffers[0];
  1344. BindStateCacheWgpu& bindStates = m_bindStateCache[0];
  1345. BindingsWgpu b;
  1346. BindStateWgpu& bindState = allocBindState(program, bindStates, b, scratchBuffer);
  1347. const uint32_t voffset = scratchBuffer.write(mrtClearDepth, sizeof(mrtClearDepth), program.m_vsh->m_gpuSize);
  1348. const uint32_t foffset = scratchBuffer.write(mrtClearColor, sizeof(mrtClearColor), program.m_fsh->m_gpuSize);
  1349. uint32_t numOffset = 2;
  1350. uint32_t offsets[2] = { voffset, foffset };
  1351. bindGroups(program, bindState, b);
  1352. const VertexBufferWgpu& vb = m_vertexBuffers[_clearQuad.m_vb.idx];
  1353. bindProgram(rce, program, bindState, numOffset, offsets);
  1354. rce.SetViewport(_rect.m_x, _rect.m_y, _rect.m_width, _rect.m_height, 0.0f, 1.0f);
  1355. rce.SetScissorRect(_rect.m_x, _rect.m_y, _rect.m_width, _rect.m_height);
  1356. rce.SetVertexBuffer(0, vb.m_ptr);
  1357. rce.Draw(4, 1, 0, 0);
  1358. }
  1359. wgpu::TextureViewDescriptor attachmentView(const Attachment& _at, const TextureWgpu& _texture)
  1360. {
  1361. bool _resolve = bool(_texture.m_ptrMsaa);
  1362. BX_UNUSED(_resolve);
  1363. wgpu::TextureViewDescriptor desc;
  1364. if (1 < _texture.m_numSides)
  1365. {
  1366. desc.baseArrayLayer = _at.layer;
  1367. }
  1368. desc.baseMipLevel = _at.mip;
  1369. desc.arrayLayerCount = 1;
  1370. desc.mipLevelCount = 1;
  1371. if (_texture.m_type == TextureWgpu::Texture3D)
  1372. {
  1373. desc.dimension = wgpu::TextureViewDimension::e3D;
  1374. }
  1375. return desc;
  1376. }
  1377. void setFrameBuffer(RenderPassDescriptor& _renderPassDescriptor, FrameBufferHandle _fbh, bool _msaa = true)
  1378. {
  1379. if (!isValid(_fbh)
  1380. || m_frameBuffers[_fbh.idx].m_swapChain)
  1381. {
  1382. SwapChainWgpu* swapChain = !isValid(_fbh)
  1383. ? m_mainFrameBuffer.m_swapChain
  1384. : m_frameBuffers[_fbh.idx].m_swapChain
  1385. ;
  1386. _renderPassDescriptor.colorAttachments[0] = defaultDescriptor<wgpu::RenderPassColorAttachmentDescriptor>();
  1387. _renderPassDescriptor.desc.colorAttachmentCount = 1;
  1388. // Force 1 array layers for attachments
  1389. wgpu::TextureViewDescriptor desc;
  1390. desc.arrayLayerCount = 1;
  1391. if (swapChain->m_backBufferColorMsaa)
  1392. {
  1393. _renderPassDescriptor.colorAttachments[0].attachment = swapChain->m_backBufferColorMsaa.CreateView(&desc);
  1394. _renderPassDescriptor.colorAttachments[0].resolveTarget = swapChain->current();
  1395. }
  1396. else
  1397. {
  1398. _renderPassDescriptor.colorAttachments[0].attachment = swapChain->current();
  1399. }
  1400. _renderPassDescriptor.depthStencilAttachment = defaultDescriptor<wgpu::RenderPassDepthStencilAttachmentDescriptor>();
  1401. _renderPassDescriptor.depthStencilAttachment.attachment = swapChain->m_backBufferDepth.CreateView();
  1402. _renderPassDescriptor.desc.depthStencilAttachment = &_renderPassDescriptor.depthStencilAttachment;
  1403. }
  1404. else
  1405. {
  1406. FrameBufferWgpu& frameBuffer = m_frameBuffers[_fbh.idx];
  1407. _renderPassDescriptor.desc.colorAttachmentCount = frameBuffer.m_num;
  1408. for (uint32_t ii = 0; ii < frameBuffer.m_num; ++ii)
  1409. {
  1410. const TextureWgpu& texture = m_textures[frameBuffer.m_colorHandle[ii].idx];
  1411. const wgpu::TextureViewDescriptor desc = attachmentView(frameBuffer.m_colorAttachment[ii], texture);
  1412. _renderPassDescriptor.colorAttachments[ii] = defaultDescriptor<wgpu::RenderPassColorAttachmentDescriptor>();
  1413. _renderPassDescriptor.colorAttachments[ii].attachment = texture.m_ptrMsaa
  1414. ? texture.m_ptrMsaa.CreateView(&desc)
  1415. : texture.m_ptr.CreateView(&desc)
  1416. ;
  1417. _renderPassDescriptor.colorAttachments[ii].resolveTarget = texture.m_ptrMsaa
  1418. ? texture.m_ptr.CreateView(&desc)
  1419. : wgpu::TextureView()
  1420. ;
  1421. }
  1422. if (isValid(frameBuffer.m_depthHandle) )
  1423. {
  1424. const TextureWgpu& texture = m_textures[frameBuffer.m_depthHandle.idx];
  1425. const wgpu::TextureViewDescriptor desc = attachmentView(frameBuffer.m_depthAttachment, texture);
  1426. _renderPassDescriptor.depthStencilAttachment = defaultDescriptor<wgpu::RenderPassDepthStencilAttachmentDescriptor>();
  1427. _renderPassDescriptor.depthStencilAttachment.attachment = texture.m_ptrMsaa
  1428. ? texture.m_ptrMsaa.CreateView(&desc)
  1429. : texture.m_ptr.CreateView(&desc)
  1430. ;
  1431. _renderPassDescriptor.desc.depthStencilAttachment = &_renderPassDescriptor.depthStencilAttachment;
  1432. }
  1433. }
  1434. m_fbh = _fbh;
  1435. m_rtMsaa = _msaa;
  1436. }
  1437. void setDepthStencilState(wgpu::DepthStencilStateDescriptor& desc, uint64_t _state, uint64_t _stencil = 0)
  1438. {
  1439. const uint32_t fstencil = unpackStencil(0, _stencil);
  1440. const uint32_t func = (_state&BGFX_STATE_DEPTH_TEST_MASK) >> BGFX_STATE_DEPTH_TEST_SHIFT;
  1441. desc.depthWriteEnabled = !!(BGFX_STATE_WRITE_Z & _state);
  1442. desc.depthCompare = s_cmpFunc[func];
  1443. uint32_t bstencil = unpackStencil(1, _stencil);
  1444. const uint32_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != fstencil;
  1445. bstencil = frontAndBack ? bstencil : fstencil;
  1446. desc.stencilFront = defaultDescriptor<wgpu::StencilStateFaceDescriptor>();
  1447. desc.stencilBack = defaultDescriptor<wgpu::StencilStateFaceDescriptor>();
  1448. if (0 != _stencil)
  1449. {
  1450. // TODO (hugoam)
  1451. const uint32_t readMask = (fstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  1452. const uint32_t writeMask = 0xff;
  1453. desc.stencilReadMask = readMask;
  1454. desc.stencilWriteMask = writeMask;
  1455. desc.stencilFront.failOp = s_stencilOp[(fstencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT];
  1456. desc.stencilFront.depthFailOp = s_stencilOp[(fstencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT];
  1457. desc.stencilFront.passOp = s_stencilOp[(fstencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT];
  1458. desc.stencilFront.compare = s_cmpFunc[(fstencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT];
  1459. desc.stencilBack.failOp = s_stencilOp[(bstencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT];
  1460. desc.stencilBack.depthFailOp = s_stencilOp[(bstencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT];
  1461. desc.stencilBack.passOp = s_stencilOp[(bstencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT];
  1462. desc.stencilBack.compare = s_cmpFunc[(bstencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT];
  1463. }
  1464. }
  1465. RenderPassStateWgpu* getRenderPassState(bgfx::FrameBufferHandle fbh, bool clear, Clear clr)
  1466. {
  1467. bx::HashMurmur2A murmur;
  1468. murmur.begin();
  1469. murmur.add(fbh.idx);
  1470. murmur.add(clear);
  1471. murmur.add(&clr, sizeof(clr));
  1472. uint32_t hash = murmur.end();
  1473. RenderPassStateWgpu* rps = m_renderPassStateCache.find(hash);
  1474. if (NULL == rps)
  1475. {
  1476. rps = BX_NEW(g_allocator, RenderPassStateWgpu);
  1477. m_renderPassStateCache.add(hash, rps);
  1478. }
  1479. return rps;
  1480. }
  1481. PipelineStateWgpu* getPipelineState(
  1482. uint64_t _state
  1483. , uint64_t _stencil
  1484. , uint32_t _rgba
  1485. , FrameBufferHandle _fbh
  1486. , uint8_t _numStreams
  1487. , const VertexLayout** _vertexDecls
  1488. , bool _index32
  1489. , ProgramHandle _program
  1490. , uint8_t _numInstanceData
  1491. )
  1492. {
  1493. _state &= 0
  1494. | BGFX_STATE_WRITE_RGB
  1495. | BGFX_STATE_WRITE_A
  1496. | BGFX_STATE_WRITE_Z
  1497. | BGFX_STATE_DEPTH_TEST_MASK
  1498. | BGFX_STATE_BLEND_MASK
  1499. | BGFX_STATE_BLEND_EQUATION_MASK
  1500. | BGFX_STATE_BLEND_INDEPENDENT
  1501. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  1502. | BGFX_STATE_CULL_MASK
  1503. | BGFX_STATE_MSAA
  1504. | BGFX_STATE_LINEAA
  1505. | BGFX_STATE_CONSERVATIVE_RASTER
  1506. | BGFX_STATE_PT_MASK
  1507. ;
  1508. const bool independentBlendEnable = !!(BGFX_STATE_BLEND_INDEPENDENT & _state);
  1509. const ProgramWgpu& program = m_program[_program.idx];
  1510. bx::HashMurmur2A murmur;
  1511. murmur.begin();
  1512. murmur.add(_state);
  1513. murmur.add(_stencil);
  1514. murmur.add(independentBlendEnable ? _rgba : 0);
  1515. murmur.add(_numInstanceData);
  1516. FrameBufferWgpu& frameBuffer = !isValid(_fbh) ? m_mainFrameBuffer : m_frameBuffers[_fbh.idx];
  1517. murmur.add(frameBuffer.m_pixelFormatHash);
  1518. murmur.add(program.m_vsh->m_hash);
  1519. if (NULL != program.m_fsh)
  1520. {
  1521. murmur.add(program.m_fsh->m_hash);
  1522. }
  1523. for (uint8_t ii = 0; ii < _numStreams; ++ii)
  1524. {
  1525. murmur.add(_vertexDecls[ii]->m_hash);
  1526. }
  1527. uint32_t hash = murmur.end();
  1528. PipelineStateWgpu* pso = m_pipelineStateCache.find(hash);
  1529. if (NULL == pso)
  1530. {
  1531. pso = BX_NEW(g_allocator, PipelineStateWgpu);
  1532. //pd.alphaToCoverageEnabled = !!(BGFX_STATE_BLEND_ALPHA_TO_COVERAGE & _state);
  1533. RenderPipelineDescriptor& pd = pso->m_rpd;
  1534. uint32_t frameBufferAttachment = 1;
  1535. uint32_t sampleCount = 1;
  1536. if (!isValid(_fbh)
  1537. || s_renderWgpu->m_frameBuffers[_fbh.idx].m_swapChain)
  1538. {
  1539. SwapChainWgpu& swapChain = !isValid(_fbh)
  1540. ? *s_renderWgpu->m_mainFrameBuffer.m_swapChain
  1541. : *s_renderWgpu->m_frameBuffers[_fbh.idx].m_swapChain
  1542. ;
  1543. sampleCount = swapChain.m_backBufferColorMsaa
  1544. ? swapChain.m_sampleCount
  1545. : 1
  1546. ;
  1547. pd.colorStates[0].format = swapChain.m_colorFormat;
  1548. pd.depthStencilState.format = swapChain.m_depthFormat;
  1549. pd.desc.depthStencilState = &pd.depthStencilState;
  1550. }
  1551. else
  1552. {
  1553. frameBufferAttachment = frameBuffer.m_num;
  1554. for (uint32_t ii = 0; ii < frameBuffer.m_num; ++ii)
  1555. {
  1556. const TextureWgpu& texture = m_textures[frameBuffer.m_colorHandle[ii].idx];
  1557. sampleCount = texture.m_ptrMsaa
  1558. ? texture.m_sampleCount
  1559. : 1
  1560. ;
  1561. pd.colorStates[ii].format = s_textureFormat[texture.m_textureFormat].m_fmt;
  1562. }
  1563. pd.desc.colorStateCount = frameBuffer.m_num;
  1564. if (isValid(frameBuffer.m_depthHandle) )
  1565. {
  1566. const TextureWgpu& texture = m_textures[frameBuffer.m_depthHandle.idx];
  1567. pd.depthStencilState.format = s_textureFormat[texture.m_textureFormat].m_fmt;
  1568. pd.desc.depthStencilState = &pd.depthStencilState;
  1569. }
  1570. }
  1571. const uint32_t blend = uint32_t( (_state&BGFX_STATE_BLEND_MASK )>>BGFX_STATE_BLEND_SHIFT);
  1572. const uint32_t equation = uint32_t( (_state&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  1573. const uint32_t srcRGB = (blend )&0xf;
  1574. const uint32_t dstRGB = (blend>> 4)&0xf;
  1575. const uint32_t srcA = (blend>> 8)&0xf;
  1576. const uint32_t dstA = (blend>>12)&0xf;
  1577. const uint32_t equRGB = (equation )&0x7;
  1578. const uint32_t equA = (equation>>3)&0x7;
  1579. wgpu::ColorWriteMask writeMask = wgpu::ColorWriteMask::None;
  1580. writeMask |= (_state&BGFX_STATE_WRITE_R) ? wgpu::ColorWriteMask::Red : wgpu::ColorWriteMask::None;
  1581. writeMask |= (_state&BGFX_STATE_WRITE_G) ? wgpu::ColorWriteMask::Green : wgpu::ColorWriteMask::None;
  1582. writeMask |= (_state&BGFX_STATE_WRITE_B) ? wgpu::ColorWriteMask::Blue : wgpu::ColorWriteMask::None;
  1583. writeMask |= (_state&BGFX_STATE_WRITE_A) ? wgpu::ColorWriteMask::Alpha : wgpu::ColorWriteMask::None;
  1584. for (uint32_t ii = 0; ii < (independentBlendEnable ? 1 : frameBufferAttachment); ++ii)
  1585. {
  1586. wgpu::ColorStateDescriptor& drt = pd.colorStates[ii]; // = pd.colorAttachments[ii];
  1587. if(!(BGFX_STATE_BLEND_MASK & _state))
  1588. {
  1589. drt.colorBlend = defaultDescriptor<wgpu::BlendDescriptor>();
  1590. drt.alphaBlend = defaultDescriptor<wgpu::BlendDescriptor>();
  1591. }
  1592. else
  1593. {
  1594. drt.colorBlend.srcFactor = s_blendFactor[srcRGB][0];
  1595. drt.colorBlend.dstFactor = s_blendFactor[dstRGB][0];
  1596. drt.colorBlend.operation = s_blendEquation[equRGB];
  1597. drt.alphaBlend.srcFactor = s_blendFactor[srcA][1];
  1598. drt.alphaBlend.dstFactor = s_blendFactor[dstA][1];
  1599. drt.alphaBlend.operation = s_blendEquation[equA];
  1600. }
  1601. drt.writeMask = writeMask;
  1602. }
  1603. if (independentBlendEnable)
  1604. {
  1605. for (uint32_t ii = 1, rgba = _rgba; ii < frameBufferAttachment; ++ii, rgba >>= 11)
  1606. {
  1607. wgpu::ColorStateDescriptor drt = pd.colorStates[ii]; // = pd.colorAttachments[ii];
  1608. //drt.blendingEnabled = 0 != (rgba&0x7ff);
  1609. const uint32_t src = (rgba )&0xf;
  1610. const uint32_t dst = (rgba>>4)&0xf;
  1611. const uint32_t equationIndex = (rgba>>8)&0x7;
  1612. drt.colorBlend.srcFactor = s_blendFactor[src][0];
  1613. drt.colorBlend.dstFactor = s_blendFactor[dst][0];
  1614. drt.colorBlend.operation = s_blendEquation[equationIndex];
  1615. drt.alphaBlend.srcFactor = s_blendFactor[src][1];
  1616. drt.alphaBlend.dstFactor = s_blendFactor[dst][1];
  1617. drt.alphaBlend.operation = s_blendEquation[equationIndex];
  1618. drt.writeMask = writeMask;
  1619. }
  1620. }
  1621. pd.desc.vertexStage.module = program.m_vsh->m_module;
  1622. pd.fragmentStage.module = program.m_fsh != NULL ? program.m_fsh->m_module : wgpu::ShaderModule();
  1623. setDepthStencilState(pd.depthStencilState, _state, _stencil);
  1624. const uint64_t cull = _state & BGFX_STATE_CULL_MASK;
  1625. const uint8_t cullIndex = uint8_t(cull >> BGFX_STATE_CULL_SHIFT);
  1626. pd.rasterizationState.cullMode = s_cullMode[cullIndex];
  1627. pd.rasterizationState.frontFace = (_state & BGFX_STATE_FRONT_CCW) ? wgpu::FrontFace::CCW : wgpu::FrontFace::CW;
  1628. // pd.desc = m_renderPipelineDescriptor;
  1629. pd.desc.sampleCount = sampleCount;
  1630. wgpu::PipelineLayoutDescriptor layout = defaultDescriptor<wgpu::PipelineLayoutDescriptor>();
  1631. layout.bindGroupLayouts = &program.m_bindGroupLayout;
  1632. layout.bindGroupLayoutCount = 1;
  1633. BX_TRACE("Creating WebGPU render pipeline layout for program %s", program.m_vsh->name());
  1634. pd.desc.layout = m_device.CreatePipelineLayout(&layout);
  1635. // TODO (hugoam) this should be cached too ?
  1636. //uint32_t ref = (_state&BGFX_STATE_ALPHA_REF_MASK) >> BGFX_STATE_ALPHA_REF_SHIFT;
  1637. //viewState.m_alphaRef = ref / 255.0f;
  1638. const uint64_t primType = _state & BGFX_STATE_PT_MASK;
  1639. uint8_t primIndex = uint8_t(primType >> BGFX_STATE_PT_SHIFT);
  1640. PrimInfo prim = s_primInfo[primIndex];
  1641. pd.desc.primitiveTopology = prim.m_type;
  1642. VertexStateDescriptor input;
  1643. input.desc.vertexBufferCount = 0;
  1644. wgpu::VertexBufferLayoutDescriptor* inputBinding = input.vertexBuffers;
  1645. wgpu::VertexAttributeDescriptor* inputAttrib = input.attributes;
  1646. auto fillVertexDecl = [&](const ShaderWgpu* _vsh, const VertexLayout& _decl)
  1647. {
  1648. input.desc.vertexBufferCount += 1;
  1649. inputBinding->arrayStride = _decl.m_stride;
  1650. inputBinding->stepMode = wgpu::InputStepMode::Vertex;
  1651. inputBinding->attributes = inputAttrib;
  1652. uint32_t numAttribs = 0;
  1653. for(uint32_t attr = 0; attr < Attrib::Count; ++attr)
  1654. {
  1655. if(UINT16_MAX != _decl.m_attributes[attr])
  1656. {
  1657. if(UINT8_MAX == _vsh->m_attrRemap[attr])
  1658. continue;
  1659. inputAttrib->shaderLocation = _vsh->m_attrRemap[attr];
  1660. if(0 == _decl.m_attributes[attr])
  1661. {
  1662. inputAttrib->format = wgpu::VertexFormat::Float3;
  1663. inputAttrib->offset = 0;
  1664. }
  1665. else
  1666. {
  1667. uint8_t num;
  1668. AttribType::Enum type;
  1669. bool normalized;
  1670. bool asInt;
  1671. _decl.decode(Attrib::Enum(attr), num, type, normalized, asInt);
  1672. inputAttrib->format = s_attribType[type][num-1][normalized];
  1673. inputAttrib->offset = _decl.m_offset[attr];
  1674. }
  1675. ++inputAttrib;
  1676. ++numAttribs;
  1677. }
  1678. }
  1679. inputBinding->attributeCount = numAttribs;
  1680. inputBinding++;
  1681. return numAttribs;
  1682. };
  1683. //bool attrSet[Attrib::Count] = {};
  1684. uint16_t unsettedAttr[Attrib::Count];
  1685. bx::memCopy(unsettedAttr, program.m_vsh->m_attrMask, sizeof(uint16_t) * Attrib::Count);
  1686. uint8_t stream = 0;
  1687. for (; stream < _numStreams; ++stream)
  1688. {
  1689. VertexLayout layout;
  1690. bx::memCopy(&layout, _vertexDecls[stream], sizeof(VertexLayout));
  1691. const uint16_t* attrMask = program.m_vsh->m_attrMask;
  1692. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  1693. {
  1694. Attrib::Enum iiattr = Attrib::Enum(ii);
  1695. uint16_t mask = attrMask[ii];
  1696. uint16_t attr = (layout.m_attributes[ii] & mask);
  1697. if (attr == 0)
  1698. {
  1699. layout.m_attributes[ii] = UINT16_MAX;
  1700. }
  1701. if (unsettedAttr[ii] && attr != UINT16_MAX)
  1702. {
  1703. unsettedAttr[ii] = 0;
  1704. }
  1705. }
  1706. fillVertexDecl(program.m_vsh, layout);
  1707. }
  1708. for (uint32_t ii = 0; ii < Attrib::Count; ++ii)
  1709. {
  1710. Attrib::Enum iiattr = Attrib::Enum(ii);
  1711. if (0 < unsettedAttr[ii])
  1712. {
  1713. //uint32_t numAttribs = input.vertexBuffers[stream].attributeCount;
  1714. //uint32_t numAttribs = inputBinding->attributeCount;
  1715. //wgpu::VertexBufferLayoutDescriptor* inputAttrib = const_cast<VkVertexInputAttributeDescription*>(_vertexInputState.pVertexAttributeDescriptions + numAttribs);
  1716. inputAttrib->shaderLocation = program.m_vsh->m_attrRemap[ii];
  1717. //inputAttrib->binding = 0;
  1718. inputAttrib->format = wgpu::VertexFormat::Float3; // VK_FORMAT_R32G32B32_SFLOAT;
  1719. inputAttrib->offset = 0;
  1720. input.vertexBuffers[stream-1].attributeCount++;
  1721. ++inputAttrib;
  1722. }
  1723. }
  1724. // TODO (hugoam) WebGPU will crash whenever we are not supplying the correct number of attributes (which depends on the stride passed to bgfx::allocInstanceDataBuffer)
  1725. // so we need to know the number of live instance attributes in the shader and if they aren't all supplied:
  1726. // - fail the pipeline state creation
  1727. // - bind dummy attributes
  1728. if (0 < _numInstanceData)
  1729. {
  1730. uint32_t numBindings = input.desc.vertexBufferCount; // == stream+1 // .vertexBindingDescriptionCount;
  1731. uint32_t firstAttrib = input.vertexBuffers[stream-1].attributeCount;
  1732. uint32_t numAttribs = firstAttrib;
  1733. inputBinding->arrayStride = _numInstanceData * 16;
  1734. inputBinding->stepMode = wgpu::InputStepMode::Instance;
  1735. for (uint32_t inst = 0; inst < _numInstanceData; ++inst)
  1736. {
  1737. inputAttrib->shaderLocation = numAttribs;
  1738. inputAttrib->format = wgpu::VertexFormat::Float4;
  1739. inputAttrib->offset = inst * 16;
  1740. ++numAttribs;
  1741. ++inputAttrib;
  1742. }
  1743. input.desc.vertexBufferCount = numBindings + 1;
  1744. input.vertexBuffers[stream].attributeCount = numAttribs - firstAttrib;
  1745. input.vertexBuffers[stream].attributes = &input.attributes[firstAttrib];
  1746. }
  1747. input.desc.indexFormat = _index32 ? wgpu::IndexFormat::Uint32 : wgpu::IndexFormat::Uint16;
  1748. pd.desc.vertexState = &input.desc;
  1749. BX_TRACE("Creating WebGPU render pipeline state for program %s", program.m_vsh->name());
  1750. pso->m_rps = m_device.CreateRenderPipeline(&pd.desc);
  1751. m_pipelineStateCache.add(hash, pso);
  1752. }
  1753. return pso;
  1754. }
  1755. PipelineStateWgpu* getPipelineState(
  1756. uint64_t _state
  1757. , uint64_t _stencil
  1758. , uint32_t _rgba
  1759. , FrameBufferHandle _fbh
  1760. , VertexLayoutHandle _declHandle
  1761. , bool _index32
  1762. , ProgramHandle _program
  1763. , uint8_t _numInstanceData
  1764. )
  1765. {
  1766. const VertexLayout* decl = &m_vertexDecls[_declHandle.idx];
  1767. return getPipelineState(
  1768. _state
  1769. , _stencil
  1770. , _rgba
  1771. , _fbh
  1772. , 1
  1773. , &decl
  1774. , _index32
  1775. , _program
  1776. , _numInstanceData
  1777. );
  1778. }
  1779. PipelineStateWgpu* getComputePipelineState(ProgramHandle _program)
  1780. {
  1781. ProgramWgpu& program = m_program[_program.idx];
  1782. if (NULL == program.m_computePS)
  1783. {
  1784. PipelineStateWgpu* pso = BX_NEW(g_allocator, PipelineStateWgpu);
  1785. program.m_computePS = pso;
  1786. wgpu::PipelineLayoutDescriptor layout = defaultDescriptor<wgpu::PipelineLayoutDescriptor>();
  1787. layout.bindGroupLayouts = &program.m_bindGroupLayout;
  1788. layout.bindGroupLayoutCount = 1;
  1789. BX_TRACE("Creating WebGPU render pipeline layout for program %s", program.m_vsh->name());
  1790. pso->m_layout = m_device.CreatePipelineLayout(&layout);
  1791. wgpu::ComputePipelineDescriptor desc;
  1792. desc.layout = pso->m_layout;
  1793. desc.computeStage = { NULL, program.m_vsh->m_module, "main" };
  1794. BX_TRACE("Creating WebGPU render pipeline state for program %s", program.m_vsh->name());
  1795. pso->m_cps = m_device.CreateComputePipeline(&desc);
  1796. }
  1797. return program.m_computePS;
  1798. }
  1799. wgpu::Sampler getSamplerState(uint32_t _flags)
  1800. {
  1801. _flags &= BGFX_SAMPLER_BITS_MASK;
  1802. SamplerStateWgpu* sampler = m_samplerStateCache.find(_flags);
  1803. if (NULL == sampler)
  1804. {
  1805. sampler = BX_NEW(g_allocator, SamplerStateWgpu);
  1806. wgpu::SamplerDescriptor desc;
  1807. desc.addressModeU = s_textureAddress[(_flags&BGFX_SAMPLER_U_MASK)>>BGFX_SAMPLER_U_SHIFT];
  1808. desc.addressModeV = s_textureAddress[(_flags&BGFX_SAMPLER_V_MASK)>>BGFX_SAMPLER_V_SHIFT];
  1809. desc.addressModeW = s_textureAddress[(_flags&BGFX_SAMPLER_W_MASK)>>BGFX_SAMPLER_W_SHIFT];
  1810. desc.minFilter = s_textureFilterMinMag[(_flags&BGFX_SAMPLER_MIN_MASK)>>BGFX_SAMPLER_MIN_SHIFT];
  1811. desc.magFilter = s_textureFilterMinMag[(_flags&BGFX_SAMPLER_MAG_MASK)>>BGFX_SAMPLER_MAG_SHIFT];
  1812. desc.mipmapFilter = s_textureFilterMip[(_flags&BGFX_SAMPLER_MIP_MASK)>>BGFX_SAMPLER_MIP_SHIFT];
  1813. desc.lodMinClamp = 0;
  1814. desc.lodMaxClamp = bx::kFloatMax;
  1815. const uint32_t cmpFunc = (_flags&BGFX_SAMPLER_COMPARE_MASK)>>BGFX_SAMPLER_COMPARE_SHIFT;
  1816. desc.compare = 0 == cmpFunc
  1817. ? wgpu::CompareFunction::Undefined
  1818. : s_cmpFunc[cmpFunc]
  1819. ;
  1820. sampler->m_sampler = s_renderWgpu->m_device.CreateSampler(&desc);
  1821. m_samplerStateCache.add(_flags, sampler);
  1822. }
  1823. return sampler->m_sampler;
  1824. }
  1825. wgpu::CommandEncoder& getRenderEncoder()
  1826. {
  1827. if (!m_cmd.m_renderEncoder)
  1828. m_cmd.beginRender();
  1829. return m_cmd.m_renderEncoder;
  1830. }
  1831. wgpu::CommandEncoder& getStagingEncoder()
  1832. {
  1833. if (!m_cmd.m_stagingEncoder)
  1834. m_cmd.beginStaging();
  1835. return m_cmd.m_stagingEncoder;
  1836. }
  1837. wgpu::CommandEncoder& getBlitCommandEncoder()
  1838. {
  1839. if (m_renderEncoder || m_computeEncoder)
  1840. endEncoding();
  1841. return getRenderEncoder();
  1842. }
  1843. wgpu::RenderPassEncoder renderPass(bgfx::Frame* _render, bgfx::FrameBufferHandle fbh, bool clear, Clear clr, const char* name = NULL)
  1844. {
  1845. RenderPassStateWgpu* rps = s_renderWgpu->getRenderPassState(fbh, clear, clr);
  1846. RenderPassDescriptor& renderPassDescriptor = rps->m_rpd;
  1847. renderPassDescriptor.desc.label = name;
  1848. setFrameBuffer(renderPassDescriptor, fbh);
  1849. if(clear)
  1850. {
  1851. for(uint32_t ii = 0; ii < g_caps.limits.maxFBAttachments; ++ii)
  1852. {
  1853. wgpu::RenderPassColorAttachmentDescriptor& color = renderPassDescriptor.colorAttachments[ii];
  1854. if(0 != (BGFX_CLEAR_COLOR & clr.m_flags))
  1855. {
  1856. if(0 != (BGFX_CLEAR_COLOR_USE_PALETTE & clr.m_flags))
  1857. {
  1858. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE - 1, clr.m_index[ii]);
  1859. const float* rgba = _render->m_colorPalette[index];
  1860. const float rr = rgba[0];
  1861. const float gg = rgba[1];
  1862. const float bb = rgba[2];
  1863. const float aa = rgba[3];
  1864. color.clearColor = { rr, gg, bb, aa };
  1865. }
  1866. else
  1867. {
  1868. float rr = clr.m_index[0] * 1.0f / 255.0f;
  1869. float gg = clr.m_index[1] * 1.0f / 255.0f;
  1870. float bb = clr.m_index[2] * 1.0f / 255.0f;
  1871. float aa = clr.m_index[3] * 1.0f / 255.0f;
  1872. color.clearColor = { rr, gg, bb, aa };
  1873. }
  1874. color.loadOp = wgpu::LoadOp::Clear;
  1875. }
  1876. else
  1877. {
  1878. color.loadOp = wgpu::LoadOp::Load;
  1879. }
  1880. //desc.storeOp = desc.attachment.sampleCount > 1 ? wgpu::StoreOp::MultisampleResolve : wgpu::StoreOp::Store;
  1881. color.storeOp = wgpu::StoreOp::Store;
  1882. }
  1883. wgpu::RenderPassDepthStencilAttachmentDescriptor& depthStencil = renderPassDescriptor.depthStencilAttachment;
  1884. if(depthStencil.attachment)
  1885. {
  1886. depthStencil.clearDepth = clr.m_depth;
  1887. depthStencil.depthLoadOp = 0 != (BGFX_CLEAR_DEPTH & clr.m_flags)
  1888. ? wgpu::LoadOp::Clear
  1889. : wgpu::LoadOp::Load
  1890. ;
  1891. depthStencil.depthStoreOp = m_mainFrameBuffer.m_swapChain->m_backBufferColorMsaa
  1892. ? wgpu::StoreOp(0) //wgpu::StoreOp::DontCare
  1893. : wgpu::StoreOp::Store
  1894. ;
  1895. depthStencil.clearStencil = clr.m_stencil;
  1896. depthStencil.stencilLoadOp = 0 != (BGFX_CLEAR_STENCIL & clr.m_flags)
  1897. ? wgpu::LoadOp::Clear
  1898. : wgpu::LoadOp::Load
  1899. ;
  1900. depthStencil.stencilStoreOp = m_mainFrameBuffer.m_swapChain->m_backBufferColorMsaa
  1901. ? wgpu::StoreOp(0) //wgpu::StoreOp::DontCare
  1902. : wgpu::StoreOp::Store
  1903. ;
  1904. }
  1905. }
  1906. else
  1907. {
  1908. for(uint32_t ii = 0; ii < g_caps.limits.maxFBAttachments; ++ii)
  1909. {
  1910. wgpu::RenderPassColorAttachmentDescriptor& color = renderPassDescriptor.colorAttachments[ii];
  1911. if(color.attachment)
  1912. {
  1913. color.loadOp = wgpu::LoadOp::Load;
  1914. }
  1915. }
  1916. wgpu::RenderPassDepthStencilAttachmentDescriptor& depthStencil = renderPassDescriptor.depthStencilAttachment;
  1917. if(depthStencil.attachment)
  1918. {
  1919. depthStencil.depthLoadOp = wgpu::LoadOp::Load;
  1920. depthStencil.depthStoreOp = wgpu::StoreOp::Store;
  1921. depthStencil.stencilLoadOp = wgpu::LoadOp::Load;
  1922. depthStencil.stencilStoreOp = wgpu::StoreOp::Store;
  1923. }
  1924. }
  1925. wgpu::RenderPassEncoder rce = m_cmd.m_renderEncoder.BeginRenderPass(&renderPassDescriptor.desc);
  1926. m_renderEncoder = rce;
  1927. return rce;
  1928. }
  1929. void endEncoding()
  1930. {
  1931. if (m_renderEncoder)
  1932. {
  1933. m_renderEncoder.EndPass();
  1934. m_renderEncoder = NULL;
  1935. }
  1936. if (m_computeEncoder)
  1937. {
  1938. m_computeEncoder.EndPass();
  1939. m_computeEncoder = NULL;
  1940. }
  1941. }
  1942. void* m_renderDocDll;
  1943. #if !BX_PLATFORM_EMSCRIPTEN
  1944. dawn_native::Instance m_instance;
  1945. #endif
  1946. wgpu::Device m_device;
  1947. wgpu::Queue m_queue;
  1948. TimerQueryWgpu m_gpuTimer;
  1949. CommandQueueWgpu m_cmd;
  1950. StagingBufferWgpu m_uniformBuffers[WEBGPU_NUM_UNIFORM_BUFFERS];
  1951. ScratchBufferWgpu m_scratchBuffers[WEBGPU_MAX_FRAMES_IN_FLIGHT];
  1952. BindStateCacheWgpu m_bindStateCache[WEBGPU_MAX_FRAMES_IN_FLIGHT];
  1953. uint8_t m_frameIndex;
  1954. uint16_t m_numWindows;
  1955. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1956. IndexBufferWgpu m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  1957. VertexBufferWgpu m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  1958. ShaderWgpu m_shaders[BGFX_CONFIG_MAX_SHADERS];
  1959. ProgramWgpu m_program[BGFX_CONFIG_MAX_PROGRAMS];
  1960. TextureWgpu m_textures[BGFX_CONFIG_MAX_TEXTURES];
  1961. ReadbackWgpu m_readbacks[BGFX_CONFIG_MAX_TEXTURES];
  1962. FrameBufferWgpu m_mainFrameBuffer;
  1963. FrameBufferWgpu m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  1964. VertexLayout m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_LAYOUTS];
  1965. UniformRegistry m_uniformReg;
  1966. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  1967. //StateCacheT<BindStateWgpu*> m_bindStateCache;
  1968. StateCacheT<RenderPassStateWgpu*> m_renderPassStateCache;
  1969. StateCacheT<PipelineStateWgpu*> m_pipelineStateCache;
  1970. StateCacheT<SamplerStateWgpu*> m_samplerStateCache;
  1971. TextVideoMem m_textVideoMem;
  1972. uint8_t m_fsScratch[64 << 10];
  1973. uint8_t m_vsScratch[64 << 10];
  1974. FrameBufferHandle m_fbh;
  1975. bool m_rtMsaa;
  1976. Resolution m_resolution;
  1977. void* m_capture;
  1978. uint32_t m_captureSize;
  1979. wgpu::RenderPassEncoder m_renderEncoder;
  1980. wgpu::ComputePassEncoder m_computeEncoder;
  1981. };
  1982. RendererContextI* rendererCreate(const Init& _init)
  1983. {
  1984. s_renderWgpu = BX_NEW(g_allocator, RendererContextWgpu);
  1985. if (!s_renderWgpu->init(_init) )
  1986. {
  1987. BX_DELETE(g_allocator, s_renderWgpu);
  1988. s_renderWgpu = NULL;
  1989. }
  1990. return s_renderWgpu;
  1991. }
  1992. void rendererDestroy()
  1993. {
  1994. s_renderWgpu->shutdown();
  1995. BX_DELETE(g_allocator, s_renderWgpu);
  1996. s_renderWgpu = NULL;
  1997. }
  1998. void writeString(bx::WriterI* _writer, const char* _str)
  1999. {
  2000. bx::write(_writer, _str, (int32_t)bx::strLen(_str) );
  2001. }
  2002. void ShaderWgpu::create(ShaderHandle _handle, const Memory* _mem)
  2003. {
  2004. m_handle = _handle;
  2005. BX_TRACE("Creating shader %s", getName(_handle));
  2006. bx::MemoryReader reader(_mem->data, _mem->size);
  2007. uint32_t magic;
  2008. bx::read(&reader, magic);
  2009. wgpu::ShaderStage shaderStage;
  2010. if (isShaderType(magic, 'C'))
  2011. {
  2012. shaderStage = wgpu::ShaderStage::Compute;
  2013. }
  2014. else if (isShaderType(magic, 'F'))
  2015. {
  2016. shaderStage = wgpu::ShaderStage::Fragment;
  2017. }
  2018. else if (isShaderType(magic, 'G'))
  2019. {
  2020. //shaderStage = wgpu::ShaderStage::Geometry;
  2021. }
  2022. else if (isShaderType(magic, 'V'))
  2023. {
  2024. shaderStage = wgpu::ShaderStage::Vertex;
  2025. }
  2026. m_stage = shaderStage;
  2027. uint32_t hashIn;
  2028. bx::read(&reader, hashIn);
  2029. uint32_t hashOut;
  2030. if (isShaderVerLess(magic, 6) )
  2031. {
  2032. hashOut = hashIn;
  2033. }
  2034. else
  2035. {
  2036. bx::read(&reader, hashOut);
  2037. }
  2038. uint16_t count;
  2039. bx::read(&reader, count);
  2040. m_numPredefined = 0;
  2041. m_numUniforms = count;
  2042. BX_TRACE("%s Shader consts %d"
  2043. , getShaderTypeName(magic)
  2044. , count
  2045. );
  2046. const bool fragment = isShaderType(magic, 'F');
  2047. uint8_t fragmentBit = fragment ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  2048. BX_CHECK(!isShaderVerLess(magic, 7), "WebGPU backend supports only shader binary version >= 7");
  2049. if (0 < count)
  2050. {
  2051. for (uint32_t ii = 0; ii < count; ++ii)
  2052. {
  2053. uint8_t nameSize = 0;
  2054. bx::read(&reader, nameSize);
  2055. char name[256];
  2056. bx::read(&reader, &name, nameSize);
  2057. name[nameSize] = '\0';
  2058. uint8_t type = 0;
  2059. bx::read(&reader, type);
  2060. uint8_t num;
  2061. bx::read(&reader, num);
  2062. uint16_t regIndex;
  2063. bx::read(&reader, regIndex);
  2064. uint16_t regCount;
  2065. bx::read(&reader, regCount);
  2066. uint8_t texComponent;
  2067. bx::read(&reader, texComponent);
  2068. uint8_t texDimension;
  2069. bx::read(&reader, texDimension);
  2070. const char* kind = "invalid";
  2071. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  2072. if (PredefinedUniform::Count != predefined)
  2073. {
  2074. kind = "predefined";
  2075. m_predefined[m_numPredefined].m_loc = regIndex;
  2076. m_predefined[m_numPredefined].m_count = regCount;
  2077. m_predefined[m_numPredefined].m_type = uint8_t(predefined|fragmentBit);
  2078. m_numPredefined++;
  2079. }
  2080. else if (UniformType::End == (~BGFX_UNIFORM_MASK & type))
  2081. {
  2082. // regCount is used for descriptor type
  2083. const bool buffer = regCount == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  2084. const bool readonly = (type & BGFX_UNIFORM_READONLYBIT) != 0;
  2085. const uint8_t stage = regIndex - (buffer ? 16 : 32) - (fragment ? 48 : 0);
  2086. m_bindInfo[stage].m_index = m_numBuffers;
  2087. m_bindInfo[stage].m_binding = regIndex;
  2088. m_bindInfo[stage].m_uniform = { 0 };
  2089. m_buffers[m_numBuffers] = wgpu::BindGroupLayoutBinding();
  2090. m_buffers[m_numBuffers].binding = regIndex;
  2091. m_buffers[m_numBuffers].visibility = shaderStage;
  2092. if (buffer)
  2093. {
  2094. m_buffers[m_numBuffers].type = readonly
  2095. ? wgpu::BindingType::ReadonlyStorageBuffer
  2096. : wgpu::BindingType::StorageBuffer;
  2097. }
  2098. else
  2099. {
  2100. m_buffers[m_numBuffers].type = readonly
  2101. ? wgpu::BindingType::ReadonlyStorageTexture
  2102. : wgpu::BindingType::WriteonlyStorageTexture;
  2103. }
  2104. m_numBuffers++;
  2105. kind = "storage";
  2106. }
  2107. else if (UniformType::Sampler == (~BGFX_UNIFORM_MASK & type))
  2108. {
  2109. const UniformRegInfo* info = s_renderWgpu->m_uniformReg.find(name);
  2110. BX_CHECK(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  2111. const uint8_t stage = regIndex - 16 - (fragment ? 48 : 0);
  2112. m_bindInfo[stage].m_index = m_numSamplers;
  2113. m_bindInfo[stage].m_binding = regIndex;
  2114. m_bindInfo[stage].m_uniform = info->m_handle;
  2115. m_textures[m_numSamplers] = wgpu::BindGroupLayoutBinding();
  2116. m_textures[m_numSamplers].binding = regIndex;
  2117. m_textures[m_numSamplers].visibility = shaderStage;
  2118. m_textures[m_numSamplers].type = wgpu::BindingType::SampledTexture;
  2119. m_textures[m_numSamplers].viewDimension = wgpu::TextureViewDimension(texDimension);
  2120. m_textures[m_numSamplers].textureComponentType = wgpu::TextureComponentType(texComponent);
  2121. const bool comparisonSampler = (type & BGFX_UNIFORM_COMPAREBIT) != 0;
  2122. m_samplers[m_numSamplers] = wgpu::BindGroupLayoutBinding();
  2123. m_samplers[m_numSamplers].binding = regIndex + 16;
  2124. m_samplers[m_numSamplers].visibility = shaderStage;
  2125. m_samplers[m_numSamplers].type = comparisonSampler
  2126. ? wgpu::BindingType::ComparisonSampler
  2127. : wgpu::BindingType::Sampler;
  2128. m_numSamplers++;
  2129. kind = "sampler";
  2130. }
  2131. else
  2132. {
  2133. const UniformRegInfo* info = s_renderWgpu->m_uniformReg.find(name);
  2134. BX_CHECK(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  2135. if(NULL == m_constantBuffer)
  2136. {
  2137. m_constantBuffer = UniformBuffer::create(1024);
  2138. }
  2139. kind = "user";
  2140. m_constantBuffer->writeUniformHandle((UniformType::Enum)(type | fragmentBit), regIndex, info->m_handle, regCount);
  2141. }
  2142. BX_TRACE("\t%s: %s (%s), r.index %3d, r.count %2d"
  2143. , kind
  2144. , name
  2145. , getUniformTypeName(UniformType::Enum(type&~BGFX_UNIFORM_MASK) )
  2146. , regIndex
  2147. , regCount
  2148. );
  2149. BX_UNUSED(kind);
  2150. }
  2151. if (NULL != m_constantBuffer)
  2152. {
  2153. m_constantBuffer->finish();
  2154. }
  2155. }
  2156. uint32_t shaderSize;
  2157. bx::read(&reader, shaderSize);
  2158. BX_TRACE("Shader body is at %lld size %u remaining %lld", reader.getPos(), shaderSize, reader.remaining());
  2159. const uint32_t* code = (const uint32_t*)reader.getDataPtr();
  2160. bx::skip(&reader, shaderSize+1);
  2161. m_code = (uint32_t*)BX_ALLOC(g_allocator, shaderSize);
  2162. m_codeSize = shaderSize;
  2163. bx::memCopy(m_code, code, shaderSize);
  2164. // TODO (hugoam) delete this
  2165. BX_TRACE("First word %08" PRIx32, code[0]);
  2166. uint8_t numAttrs = 0;
  2167. bx::read(&reader, numAttrs);
  2168. m_numAttrs = numAttrs;
  2169. bx::memSet(m_attrMask, 0, sizeof(m_attrMask));
  2170. bx::memSet(m_attrRemap, UINT8_MAX, sizeof(m_attrRemap));
  2171. for(uint8_t ii = 0; ii < numAttrs; ++ii)
  2172. {
  2173. uint16_t id;
  2174. bx::read(&reader, id);
  2175. auto toString = [](Attrib::Enum attr)
  2176. {
  2177. if (attr == Attrib::Position) return "Position";
  2178. else if (attr == Attrib::Normal) return "Normal";
  2179. else if (attr == Attrib::Tangent) return "Tangent";
  2180. else if (attr == Attrib::Bitangent) return "Bitangent";
  2181. else if (attr == Attrib::Color0) return "Color0";
  2182. else if (attr == Attrib::Color1) return "Color1";
  2183. else if (attr == Attrib::Color2) return "Color2";
  2184. else if (attr == Attrib::Color3) return "Color3";
  2185. else if (attr == Attrib::Indices) return "Indices";
  2186. else if (attr == Attrib::Weight) return "Weight";
  2187. else if (attr == Attrib::TexCoord0) return "TexCoord0";
  2188. else if (attr == Attrib::TexCoord1) return "TexCoord1";
  2189. else if (attr == Attrib::TexCoord2) return "TexCoord2";
  2190. else if (attr == Attrib::TexCoord3) return "TexCoord3";
  2191. else if (attr == Attrib::TexCoord4) return "TexCoord4";
  2192. else if (attr == Attrib::TexCoord5) return "TexCoord5";
  2193. else if (attr == Attrib::TexCoord6) return "TexCoord6";
  2194. else if (attr == Attrib::TexCoord7) return "TexCoord7";
  2195. return "Invalid";
  2196. };
  2197. Attrib::Enum attr = idToAttrib(id);
  2198. if(Attrib::Count != attr)
  2199. {
  2200. m_attrMask[attr] = UINT16_MAX;
  2201. m_attrRemap[attr] = ii;
  2202. BX_TRACE("\tattrib: %s (%i) at index %i", toString(attr), attr, ii);
  2203. }
  2204. }
  2205. wgpu::ShaderModuleSPIRVDescriptor spirv;
  2206. spirv.code = m_code;
  2207. spirv.codeSize = shaderSize / 4;
  2208. wgpu::ShaderModuleDescriptor desc;
  2209. desc.label = getName(_handle);
  2210. desc.nextInChain = &spirv;
  2211. m_module = s_renderWgpu->m_device.CreateShaderModule(&desc);
  2212. BGFX_FATAL(m_module
  2213. , bgfx::Fatal::InvalidShader
  2214. , "Failed to create %s shader."
  2215. , getShaderTypeName(magic)
  2216. );
  2217. bx::HashMurmur2A murmur;
  2218. murmur.begin();
  2219. murmur.add(hashIn);
  2220. murmur.add(hashOut);
  2221. murmur.add(code, shaderSize);
  2222. murmur.add(numAttrs);
  2223. murmur.add(m_attrMask, numAttrs);
  2224. m_hash = murmur.end();
  2225. auto roundUp = [](auto value, auto multiple)
  2226. {
  2227. return ((value + multiple - 1) / multiple) * multiple;
  2228. };
  2229. bx::read(&reader, m_size);
  2230. const uint32_t align = kMinBufferOffsetAlignment;
  2231. m_gpuSize = bx::strideAlign(m_size, align);
  2232. BX_TRACE("shader size %d (used=%d) (prev=%d)", (int)m_size, (int)m_gpuSize, (int)bx::strideAlign(roundUp(m_size, 4), align));
  2233. }
  2234. void ProgramWgpu::create(const ShaderWgpu* _vsh, const ShaderWgpu* _fsh)
  2235. {
  2236. BX_CHECK(_vsh->m_module, "Vertex shader doesn't exist.");
  2237. m_vsh = _vsh;
  2238. m_fsh = _fsh;
  2239. m_gpuSize = _vsh->m_gpuSize + (_fsh ? _fsh->m_gpuSize : 0);
  2240. //BX_CHECK(NULL != _vsh->m_code, "Vertex shader doesn't exist.");
  2241. m_vsh = _vsh;
  2242. bx::memCopy(&m_predefined[0], _vsh->m_predefined, _vsh->m_numPredefined * sizeof(PredefinedUniform));
  2243. m_numPredefined = _vsh->m_numPredefined;
  2244. if(NULL != _fsh)
  2245. {
  2246. //BX_CHECK(NULL != _fsh->m_code, "Fragment shader doesn't exist.");
  2247. m_fsh = _fsh;
  2248. bx::memCopy(&m_predefined[m_numPredefined], _fsh->m_predefined, _fsh->m_numPredefined * sizeof(PredefinedUniform));
  2249. m_numPredefined += _fsh->m_numPredefined;
  2250. }
  2251. wgpu::BindGroupLayoutEntry bindings[2 + BGFX_CONFIG_MAX_TEXTURE_SAMPLERS * 3];
  2252. m_numUniforms = 0 + (_vsh->m_size > 0 ? 1 : 0) + (NULL != _fsh && _fsh->m_size > 0 ? 1 : 0);
  2253. uint8_t numBindings = 0;
  2254. // bind uniform buffer at slot 0
  2255. bindings[numBindings].binding = 0;
  2256. bindings[numBindings].visibility = _vsh->m_stage;
  2257. bindings[numBindings].type = wgpu::BindingType::UniformBuffer;
  2258. bindings[numBindings].hasDynamicOffset = true;
  2259. numBindings++;
  2260. if (m_numUniforms > 1)
  2261. {
  2262. bindings[numBindings].binding = 48;
  2263. bindings[numBindings].visibility = wgpu::ShaderStage::Fragment;
  2264. bindings[numBindings].type = wgpu::BindingType::UniformBuffer;
  2265. bindings[numBindings].hasDynamicOffset = true;
  2266. numBindings++;
  2267. }
  2268. uint8_t numSamplers = 0;
  2269. for (uint32_t ii = 0; ii < _vsh->m_numSamplers; ++ii)
  2270. {
  2271. m_textures[ii] = _vsh->m_textures[ii];
  2272. m_samplers[ii] = _vsh->m_samplers[ii];
  2273. bindings[numBindings++] = _vsh->m_textures[ii];
  2274. bindings[numBindings++] = _vsh->m_samplers[ii];
  2275. }
  2276. numSamplers += _vsh->m_numSamplers;
  2277. if (NULL != _fsh)
  2278. {
  2279. for (uint32_t ii = 0; ii < _fsh->m_numSamplers; ++ii)
  2280. {
  2281. m_textures[numSamplers + ii] = _fsh->m_textures[ii];
  2282. m_samplers[numSamplers + ii] = _fsh->m_samplers[ii];
  2283. bindings[numBindings++] = _fsh->m_textures[ii];
  2284. bindings[numBindings++] = _fsh->m_samplers[ii];
  2285. }
  2286. numSamplers += _fsh->m_numSamplers;
  2287. }
  2288. for (uint8_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  2289. {
  2290. if (isValid(m_vsh->m_bindInfo[stage].m_uniform))
  2291. {
  2292. m_bindInfo[stage] = m_vsh->m_bindInfo[stage];
  2293. }
  2294. else if (NULL != m_fsh && isValid(m_fsh->m_bindInfo[stage].m_uniform))
  2295. {
  2296. m_bindInfo[stage] = m_fsh->m_bindInfo[stage];
  2297. m_bindInfo[stage].m_index += _vsh->m_numSamplers;
  2298. }
  2299. }
  2300. m_numSamplers = numSamplers;
  2301. for (uint32_t ii = 0; ii < _vsh->m_numBuffers; ++ii)
  2302. {
  2303. m_buffers[ii] = _vsh->m_buffers[ii];
  2304. bindings[numBindings++] = _vsh->m_buffers[ii];
  2305. }
  2306. m_numBuffers = _vsh->m_numBuffers;
  2307. BX_CHECK(m_numUniforms + m_numSamplers * 2 + m_numBuffers == numBindings, "");
  2308. wgpu::BindGroupLayoutDescriptor bindGroupDesc;
  2309. bindGroupDesc.entryCount = numBindings;
  2310. bindGroupDesc.entries = bindings;
  2311. m_bindGroupLayout = s_renderWgpu->m_device.CreateBindGroupLayout(&bindGroupDesc);
  2312. bx::HashMurmur2A murmur;
  2313. murmur.begin();
  2314. murmur.add(m_numUniforms);
  2315. murmur.add(m_textures, sizeof(wgpu::BindGroupLayoutEntry) * numSamplers);
  2316. murmur.add(m_samplers, sizeof(wgpu::BindGroupLayoutEntry) * numSamplers);
  2317. murmur.add(m_buffers, sizeof(wgpu::BindGroupLayoutEntry) * m_numBuffers);
  2318. m_bindGroupLayoutHash = murmur.end();
  2319. }
  2320. void ProgramWgpu::destroy()
  2321. {
  2322. m_vsh = NULL;
  2323. m_fsh = NULL;
  2324. if ( NULL != m_computePS )
  2325. {
  2326. BX_DELETE(g_allocator, m_computePS);
  2327. m_computePS = NULL;
  2328. }
  2329. }
  2330. void BufferWgpu::create(uint32_t _size, void* _data, uint16_t _flags, uint16_t _stride, bool _vertex)
  2331. {
  2332. BX_UNUSED(_stride);
  2333. m_size = _size;
  2334. m_flags = _flags;
  2335. m_vertex = _vertex;
  2336. const uint32_t paddedSize = bx::strideAlign(_size, 4);
  2337. bool storage = m_flags & BGFX_BUFFER_COMPUTE_READ_WRITE;
  2338. bool indirect = m_flags & BGFX_BUFFER_DRAW_INDIRECT;
  2339. wgpu::BufferDescriptor desc;
  2340. desc.size = paddedSize;
  2341. desc.usage = _vertex ? wgpu::BufferUsage::Vertex : wgpu::BufferUsage::Index;
  2342. desc.usage |= (storage || indirect) ? wgpu::BufferUsage::Storage : wgpu::BufferUsage::None;
  2343. desc.usage |= indirect ? wgpu::BufferUsage::Indirect : wgpu::BufferUsage::None;
  2344. desc.usage |= NULL == _data ? wgpu::BufferUsage::CopyDst : wgpu::BufferUsage::None;
  2345. if(NULL != _data)
  2346. {
  2347. wgpu::CreateBufferMappedResult mapped = s_renderWgpu->m_device.CreateBufferMapped(&desc);
  2348. m_ptr = mapped.buffer;
  2349. bx::memCopy(mapped.data, _data, _size);
  2350. mapped.buffer.Unmap();
  2351. }
  2352. else
  2353. {
  2354. m_ptr = s_renderWgpu->m_device.CreateBuffer(&desc);
  2355. }
  2356. }
  2357. void BufferWgpu::update(uint32_t _offset, uint32_t _size, void* _data, bool _discard)
  2358. {
  2359. wgpu::CommandEncoder& bce = s_renderWgpu->getBlitCommandEncoder();
  2360. if (!m_vertex && !_discard)
  2361. {
  2362. if ( m_dynamic == NULL )
  2363. {
  2364. m_dynamic = (uint8_t*)BX_ALLOC(g_allocator, m_size);
  2365. }
  2366. bx::memCopy(m_dynamic + _offset, _data, _size);
  2367. uint32_t start = _offset & 4;
  2368. uint32_t end = bx::strideAlign(_offset + _size, 4);
  2369. wgpu::BufferDescriptor desc;
  2370. desc.size = end - start;
  2371. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::CopySrc;
  2372. wgpu::CreateBufferMappedResult mapped = s_renderWgpu->m_device.CreateBufferMapped(&desc);
  2373. wgpu::Buffer staging = mapped.buffer;
  2374. bx::memCopy(mapped.data, m_dynamic, end - start);
  2375. mapped.buffer.Unmap();
  2376. // TODO pad to 4 bytes
  2377. bce.CopyBufferToBuffer(staging, 0, m_ptr, start, end - start);
  2378. s_renderWgpu->m_cmd.release(staging);
  2379. }
  2380. else
  2381. {
  2382. wgpu::BufferDescriptor desc;
  2383. desc.size = _size;
  2384. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::CopySrc;
  2385. wgpu::CreateBufferMappedResult mapped = s_renderWgpu->m_device.CreateBufferMapped(&desc);
  2386. wgpu::Buffer staging = mapped.buffer;
  2387. bx::memCopy(mapped.data, _data, _size);
  2388. mapped.buffer.Unmap();
  2389. bce.CopyBufferToBuffer(staging, 0, m_ptr, _offset, _size);
  2390. s_renderWgpu->m_cmd.release(staging);
  2391. }
  2392. }
  2393. void VertexBufferWgpu::create(uint32_t _size, void* _data, VertexLayoutHandle _layoutHandle, uint16_t _flags)
  2394. {
  2395. m_layoutHandle = _layoutHandle;
  2396. uint16_t stride = isValid(_layoutHandle)
  2397. ? s_renderWgpu->m_vertexDecls[_layoutHandle.idx].m_stride
  2398. : 0
  2399. ;
  2400. BufferWgpu::create(_size, _data, _flags, stride, true);
  2401. }
  2402. void TextureWgpu::create(TextureHandle _handle, const Memory* _mem, uint64_t _flags, uint8_t _skip)
  2403. {
  2404. m_handle = _handle;
  2405. m_sampler = s_renderWgpu->getSamplerState(uint32_t(_flags) );
  2406. bimg::ImageContainer imageContainer;
  2407. if (bimg::imageParse(imageContainer, _mem->data, _mem->size) )
  2408. {
  2409. const bimg::ImageBlockInfo& blockInfo = getBlockInfo(bimg::TextureFormat::Enum(imageContainer.m_format) );
  2410. const uint8_t startLod = bx::min<uint8_t>(_skip, imageContainer.m_numMips-1);
  2411. bimg::TextureInfo ti;
  2412. bimg::imageGetSize(
  2413. &ti
  2414. , uint16_t(imageContainer.m_width >>startLod)
  2415. , uint16_t(imageContainer.m_height>>startLod)
  2416. , uint16_t(imageContainer.m_depth >>startLod)
  2417. , imageContainer.m_cubeMap
  2418. , 1 < imageContainer.m_numMips
  2419. , imageContainer.m_numLayers
  2420. , imageContainer.m_format
  2421. );
  2422. ti.numMips = bx::min<uint8_t>(imageContainer.m_numMips-startLod, ti.numMips);
  2423. m_flags = _flags;
  2424. m_width = ti.width;
  2425. m_height = ti.height;
  2426. m_depth = ti.depth;
  2427. m_numLayers = ti.numLayers;
  2428. m_numMips = ti.numMips;
  2429. m_numSides = ti.numLayers * (imageContainer.m_cubeMap ? 6 : 1);
  2430. m_requestedFormat = TextureFormat::Enum(imageContainer.m_format);
  2431. m_textureFormat = getViableTextureFormat(imageContainer);
  2432. if (m_requestedFormat == bgfx::TextureFormat::D16)
  2433. m_textureFormat = bgfx::TextureFormat::D32F;
  2434. const bool compressed = bimg::isCompressed(bimg::TextureFormat::Enum(imageContainer.m_format));
  2435. if (compressed)
  2436. m_textureFormat = bgfx::TextureFormat::BGRA8;
  2437. const bool convert = m_textureFormat != m_requestedFormat;
  2438. const uint8_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) );
  2439. wgpu::TextureDescriptor desc = defaultDescriptor<wgpu::TextureDescriptor>();
  2440. //desc.label = getName(_handle);
  2441. if (1 < ti.numLayers)
  2442. {
  2443. if (imageContainer.m_cubeMap)
  2444. {
  2445. m_type = TextureCube;
  2446. desc.dimension = wgpu::TextureDimension::e2D;
  2447. }
  2448. else
  2449. {
  2450. m_type = Texture2D;
  2451. desc.dimension = wgpu::TextureDimension::e2D;
  2452. }
  2453. }
  2454. else if (imageContainer.m_cubeMap)
  2455. {
  2456. m_type = TextureCube;
  2457. desc.dimension = wgpu::TextureDimension::e2D;
  2458. }
  2459. else if (1 < imageContainer.m_depth)
  2460. {
  2461. m_type = Texture3D;
  2462. desc.dimension = wgpu::TextureDimension::e3D;
  2463. }
  2464. else
  2465. {
  2466. m_type = Texture2D;
  2467. desc.dimension = wgpu::TextureDimension::e2D;
  2468. }
  2469. const uint16_t numSides = ti.numLayers * (imageContainer.m_cubeMap ? 6 : 1);
  2470. const uint32_t numSrd = numSides * ti.numMips;
  2471. const bool writeOnly = 0 != (_flags&BGFX_TEXTURE_RT_WRITE_ONLY);
  2472. const bool computeWrite = 0 != (_flags&BGFX_TEXTURE_COMPUTE_WRITE);
  2473. const bool renderTarget = 0 != (_flags&BGFX_TEXTURE_RT_MASK);
  2474. const bool srgb = 0 != (_flags&BGFX_TEXTURE_SRGB);
  2475. BX_TRACE("Texture %3d: %s (requested: %s), layers %d, %dx%d%s RT[%c], WO[%c], CW[%c], sRGB[%c]"
  2476. , this - s_renderWgpu->m_textures
  2477. , getName( (TextureFormat::Enum)m_textureFormat)
  2478. , getName( (TextureFormat::Enum)m_requestedFormat)
  2479. , ti.numLayers
  2480. , ti.width
  2481. , ti.height
  2482. , imageContainer.m_cubeMap ? "x6" : ""
  2483. , renderTarget ? 'x' : ' '
  2484. , writeOnly ? 'x' : ' '
  2485. , computeWrite ? 'x' : ' '
  2486. , srgb ? 'x' : ' '
  2487. );
  2488. const uint32_t msaaQuality = bx::uint32_satsub( (_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT, 1);
  2489. const int32_t sampleCount = s_msaa[msaaQuality];
  2490. wgpu::TextureFormat format = wgpu::TextureFormat::Undefined;
  2491. if (srgb)
  2492. {
  2493. format = s_textureFormat[m_textureFormat].m_fmtSrgb;
  2494. BX_WARN(format != wgpu::TextureFormat::Undefined
  2495. , "sRGB not supported for texture format %d"
  2496. , m_textureFormat
  2497. );
  2498. }
  2499. if (format == wgpu::TextureFormat::Undefined)
  2500. {
  2501. // not swizzled and not sRGB, or sRGB unsupported
  2502. format = s_textureFormat[m_textureFormat].m_fmt;
  2503. }
  2504. desc.format = format;
  2505. desc.size.width = m_width;
  2506. desc.size.height = m_height;
  2507. desc.size.depth = bx::uint32_max(1,imageContainer.m_depth);
  2508. desc.mipLevelCount = m_numMips;
  2509. desc.sampleCount = 1;
  2510. desc.arrayLayerCount = m_numSides;
  2511. desc.usage = wgpu::TextureUsage::Sampled;
  2512. desc.usage |= wgpu::TextureUsage::CopyDst;
  2513. desc.usage |= wgpu::TextureUsage::CopySrc;
  2514. if (computeWrite)
  2515. {
  2516. desc.usage |= wgpu::TextureUsage::Storage;
  2517. }
  2518. if (renderTarget)
  2519. {
  2520. desc.usage |= wgpu::TextureUsage::OutputAttachment;
  2521. }
  2522. m_ptr = s_renderWgpu->m_device.CreateTexture(&desc);
  2523. if (sampleCount > 1)
  2524. {
  2525. desc.sampleCount = sampleCount;
  2526. m_ptrMsaa = s_renderWgpu->m_device.CreateTexture(&desc);
  2527. }
  2528. // decode images
  2529. struct ImageInfo
  2530. {
  2531. uint8_t* data;
  2532. uint32_t width;
  2533. uint32_t height;
  2534. uint32_t depth;
  2535. uint32_t pitch;
  2536. uint32_t slice;
  2537. uint32_t size;
  2538. uint8_t mipLevel;
  2539. uint8_t layer;
  2540. };
  2541. ImageInfo* imageInfos = (ImageInfo*)BX_ALLOC(g_allocator, sizeof(ImageInfo) * numSrd);
  2542. bx::memSet(imageInfos, 0, sizeof(ImageInfo) * numSrd);
  2543. uint32_t alignment = 1; // tightly aligned buffer
  2544. uint32_t kk = 0;
  2545. for (uint8_t side = 0; side < numSides; ++side)
  2546. {
  2547. for (uint8_t lod = 0; lod < ti.numMips; ++lod)
  2548. {
  2549. bimg::ImageMip mip;
  2550. if (bimg::imageGetRawData(imageContainer, side, lod + startLod, _mem->data, _mem->size, mip))
  2551. {
  2552. if (convert)
  2553. {
  2554. const uint32_t pitch = bx::strideAlign(bx::max<uint32_t>(mip.m_width, 4) * bpp / 8, alignment);
  2555. const uint32_t slice = bx::strideAlign(bx::max<uint32_t>(mip.m_height, 4) * pitch, alignment);
  2556. const uint32_t size = slice * mip.m_depth;
  2557. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, size);
  2558. bimg::imageDecodeToBgra8(
  2559. g_allocator
  2560. , temp
  2561. , mip.m_data
  2562. , mip.m_width
  2563. , mip.m_height
  2564. , pitch
  2565. , mip.m_format
  2566. );
  2567. imageInfos[kk].data = temp;
  2568. imageInfos[kk].width = mip.m_width;
  2569. imageInfos[kk].height = mip.m_height;
  2570. imageInfos[kk].depth = mip.m_depth;
  2571. imageInfos[kk].pitch = pitch;
  2572. imageInfos[kk].slice = slice;
  2573. imageInfos[kk].size = size;
  2574. imageInfos[kk].mipLevel = lod;
  2575. imageInfos[kk].layer = side;
  2576. }
  2577. else if (compressed)
  2578. {
  2579. const uint32_t pitch = bx::strideAlign((mip.m_width / blockInfo.blockWidth) * mip.m_blockSize, alignment);
  2580. const uint32_t slice = bx::strideAlign((mip.m_height / blockInfo.blockHeight) * pitch, alignment);
  2581. const uint32_t size = slice * mip.m_depth;
  2582. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, size);
  2583. bimg::imageCopy(
  2584. temp
  2585. , mip.m_height / blockInfo.blockHeight
  2586. , (mip.m_width / blockInfo.blockWidth) * mip.m_blockSize
  2587. , mip.m_depth
  2588. , mip.m_data
  2589. , pitch
  2590. );
  2591. imageInfos[kk].data = temp;
  2592. imageInfos[kk].width = mip.m_width;
  2593. imageInfos[kk].height = mip.m_height;
  2594. imageInfos[kk].depth = mip.m_depth;
  2595. imageInfos[kk].pitch = pitch;
  2596. imageInfos[kk].slice = slice;
  2597. imageInfos[kk].size = size;
  2598. imageInfos[kk].mipLevel = lod;
  2599. imageInfos[kk].layer = side;
  2600. }
  2601. else
  2602. {
  2603. const uint32_t pitch = bx::strideAlign(mip.m_width * mip.m_bpp / 8, alignment);
  2604. const uint32_t slice = bx::strideAlign(mip.m_height * pitch, alignment);
  2605. const uint32_t size = slice * mip.m_depth;
  2606. uint8_t* temp = (uint8_t*)BX_ALLOC(g_allocator, size);
  2607. bimg::imageCopy(temp
  2608. , mip.m_height
  2609. , mip.m_width * mip.m_bpp / 8
  2610. , mip.m_depth
  2611. , mip.m_data
  2612. , pitch
  2613. );
  2614. imageInfos[kk].data = temp;
  2615. imageInfos[kk].width = mip.m_width;
  2616. imageInfos[kk].height = mip.m_height;
  2617. imageInfos[kk].depth = mip.m_depth;
  2618. imageInfos[kk].pitch = pitch;
  2619. imageInfos[kk].slice = slice;
  2620. imageInfos[kk].size = size;
  2621. imageInfos[kk].mipLevel = lod;
  2622. imageInfos[kk].layer = side;
  2623. }
  2624. }
  2625. ++kk;
  2626. }
  2627. }
  2628. uint32_t totalMemSize = 0;
  2629. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2630. {
  2631. const uint32_t dstpitch = bx::strideAlign(imageInfos[ii].pitch, kMinBufferOffsetAlignment);
  2632. totalMemSize += dstpitch * imageInfos[ii].height;
  2633. //totalMemSize += imageInfos[ii].size;
  2634. }
  2635. wgpu::Buffer stagingBuffer;
  2636. if (totalMemSize > 0)
  2637. {
  2638. wgpu::BufferDescriptor staginBufferDesc;
  2639. staginBufferDesc.size = totalMemSize;
  2640. staginBufferDesc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::CopySrc;
  2641. wgpu::CreateBufferMappedResult mapped = s_renderWgpu->m_device.CreateBufferMapped(&staginBufferDesc);
  2642. stagingBuffer = mapped.buffer;
  2643. uint64_t offset = 0;
  2644. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2645. {
  2646. const uint32_t dstpitch = bx::strideAlign(imageInfos[ii].pitch, kMinBufferOffsetAlignment);
  2647. const uint8_t* src = (uint8_t*)imageInfos[ii].data;
  2648. uint8_t* dst = (uint8_t*)mapped.data;
  2649. for (uint32_t yy = 0; yy < imageInfos[ii].height; ++yy, src += imageInfos[ii].pitch, offset += dstpitch)
  2650. {
  2651. bx::memCopy(dst + offset, src, imageInfos[ii].pitch);
  2652. }
  2653. //bx::memCopy(dst + offset, imageInfos[ii].data, imageInfos[ii].size);
  2654. //offset += imageInfos[ii].size;
  2655. }
  2656. mapped.buffer.Unmap();
  2657. }
  2658. wgpu::BufferCopyView* bufferCopyView = (wgpu::BufferCopyView*)BX_ALLOC(g_allocator, sizeof(wgpu::BufferCopyView) * numSrd);
  2659. wgpu::TextureCopyView* textureCopyView = (wgpu::TextureCopyView*)BX_ALLOC(g_allocator, sizeof(wgpu::TextureCopyView) * numSrd);
  2660. wgpu::Extent3D* textureCopySize = (wgpu::Extent3D*)BX_ALLOC(g_allocator, sizeof(wgpu::Extent3D) * numSrd);
  2661. uint64_t offset = 0;
  2662. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2663. {
  2664. const uint32_t dstpitch = bx::strideAlign(imageInfos[ii].pitch, kMinBufferOffsetAlignment);
  2665. uint32_t idealWidth = bx::max<uint32_t>(1, m_width >> imageInfos[ii].mipLevel);
  2666. uint32_t idealHeight = bx::max<uint32_t>(1, m_height >> imageInfos[ii].mipLevel);
  2667. BX_PLACEMENT_NEW(&bufferCopyView[ii], wgpu::BufferCopyView)();
  2668. BX_PLACEMENT_NEW(&textureCopyView[ii], wgpu::TextureCopyView)();
  2669. BX_PLACEMENT_NEW(&textureCopySize[ii], wgpu::Extent3D)();
  2670. bufferCopyView[ii].buffer = stagingBuffer;
  2671. bufferCopyView[ii].offset = offset;
  2672. bufferCopyView[ii].bytesPerRow = dstpitch; // assume that image data are tightly aligned
  2673. bufferCopyView[ii].rowsPerImage = 0; // assume that image data are tightly aligned
  2674. textureCopyView[ii].texture = m_ptr;
  2675. //textureCopyView[ii].imageSubresource.aspectMask = m_vkTextureAspect;
  2676. textureCopyView[ii].mipLevel = imageInfos[ii].mipLevel;
  2677. textureCopyView[ii].arrayLayer = imageInfos[ii].layer;
  2678. //textureCopyView[ii].layerCount = 1;
  2679. textureCopyView[ii].origin = { 0, 0, 0 };
  2680. textureCopySize[ii] = { idealWidth, idealHeight, imageInfos[ii].depth };
  2681. offset += dstpitch * imageInfos[ii].height;
  2682. //offset += imageInfos[ii].size;
  2683. }
  2684. if (stagingBuffer)
  2685. {
  2686. wgpu::CommandEncoder encoder = s_renderWgpu->getBlitCommandEncoder();
  2687. //wgpu::CommandEncoder encoder = s_renderWgpu->m_cmd.m_encoder;
  2688. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2689. {
  2690. encoder.CopyBufferToTexture(&bufferCopyView[ii], &textureCopyView[ii], &textureCopySize[ii]);
  2691. }
  2692. }
  2693. else
  2694. {
  2695. //VkCommandBuffer commandBuffer = s_renderVK->beginNewCommand();
  2696. //setImageMemoryBarrier(
  2697. // commandBuffer
  2698. // , (m_flags & BGFX_TEXTURE_COMPUTE_WRITE
  2699. // ? VK_IMAGE_LAYOUT_GENERAL
  2700. // : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
  2701. // )
  2702. //);
  2703. //s_renderVK->submitCommandAndWait(commandBuffer);
  2704. }
  2705. //vkFreeMemory(device, stagingDeviceMem, allocatorCb);
  2706. //vkDestroy(stagingBuffer);
  2707. BX_FREE(g_allocator, bufferCopyView);
  2708. BX_FREE(g_allocator, textureCopyView);
  2709. BX_FREE(g_allocator, textureCopySize);
  2710. for (uint32_t ii = 0; ii < numSrd; ++ii)
  2711. {
  2712. BX_FREE(g_allocator, imageInfos[ii].data);
  2713. }
  2714. BX_FREE(g_allocator, imageInfos);
  2715. }
  2716. }
  2717. void TextureWgpu::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  2718. {
  2719. BX_UNUSED(_side); BX_UNUSED(_mip); BX_UNUSED(_depth); BX_UNUSED(_z);
  2720. const uint32_t bpp = bimg::getBitsPerPixel(bimg::TextureFormat::Enum(m_textureFormat) );
  2721. const uint32_t rectpitch = _rect.m_width*bpp/8;
  2722. const uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  2723. const uint32_t slice = ( (m_type == Texture3D) ? 0 : _side + _z * (m_type == TextureCube ? 6 : 1) );
  2724. const uint16_t zz = (m_type == Texture3D) ? _z : 0 ;
  2725. const bool convert = m_textureFormat != m_requestedFormat;
  2726. uint8_t* data = _mem->data;
  2727. uint8_t* temp = NULL;
  2728. if (convert)
  2729. {
  2730. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*_rect.m_height);
  2731. bimg::imageDecodeToBgra8(
  2732. g_allocator
  2733. , temp
  2734. , data
  2735. , _rect.m_width
  2736. , _rect.m_height
  2737. , srcpitch
  2738. , bimg::TextureFormat::Enum(m_requestedFormat)
  2739. );
  2740. data = temp;
  2741. }
  2742. const uint32_t dstpitch = bx::strideAlign(rectpitch, kMinBufferOffsetAlignment);
  2743. wgpu::BufferDescriptor desc;
  2744. desc.size = dstpitch * _rect.m_height;
  2745. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::CopySrc;
  2746. wgpu::CreateBufferMappedResult mapped = s_renderWgpu->m_device.CreateBufferMapped(&desc);
  2747. wgpu::Buffer staging = mapped.buffer;
  2748. const uint8_t* src = (uint8_t*)data;
  2749. uint8_t* dst = (uint8_t*)mapped.data;
  2750. uint64_t offset = 0;
  2751. for (uint32_t yy = 0; yy < _rect.m_height; ++yy, src += srcpitch, offset += dstpitch)
  2752. {
  2753. const uint32_t size = bx::strideAlign(rectpitch, 4);
  2754. bx::memCopy(dst + offset, src, size);
  2755. }
  2756. mapped.buffer.Unmap();
  2757. wgpu::BufferCopyView srcView;
  2758. srcView.buffer = staging;
  2759. srcView.offset = 0;
  2760. srcView.bytesPerRow = dstpitch;
  2761. srcView.rowsPerImage = 0;
  2762. wgpu::TextureCopyView destView;
  2763. destView.texture = m_ptr;
  2764. destView.mipLevel = _mip;
  2765. destView.arrayLayer = _side;
  2766. destView.origin = { _rect.m_x, _rect.m_y, zz };
  2767. //destView.origin = { _rect.m_x, _rect.m_y, _z };
  2768. wgpu::Extent3D destExtent = { _rect.m_width, _rect.m_height, _depth };
  2769. //region.imageSubresource.aspectMask = m_vkTextureAspect;
  2770. wgpu::CommandEncoder encoder = s_renderWgpu->getBlitCommandEncoder();
  2771. //wgpu::CommandEncoder encoder = s_renderWgpu->m_cmd.m_encoder;
  2772. encoder.CopyBufferToTexture(&srcView, &destView, &destExtent);
  2773. //wgpu::CommandBuffer copy = encoder.Finish();
  2774. //wgpu::Queue queue = s_renderWgpu->m_queue;
  2775. //queue.Submit(1, &copy);
  2776. //staging.Destroy();
  2777. if (NULL != temp)
  2778. {
  2779. BX_FREE(g_allocator, temp);
  2780. }
  2781. }
  2782. void BindStateWgpu::clear()
  2783. {
  2784. m_bindGroup = NULL;
  2785. }
  2786. void StagingBufferWgpu::create(uint32_t _size, bool mapped)
  2787. {
  2788. wgpu::BufferDescriptor desc;
  2789. desc.size = BGFX_CONFIG_MAX_DRAW_CALLS * 128;
  2790. desc.usage = wgpu::BufferUsage::MapWrite | wgpu::BufferUsage::CopySrc;
  2791. if (mapped)
  2792. {
  2793. wgpu::CreateBufferMappedResult mapped = s_renderWgpu->m_device.CreateBufferMapped(&desc);
  2794. m_buffer = mapped.buffer;
  2795. m_data = mapped.data;
  2796. m_size = mapped.dataLength;
  2797. }
  2798. else
  2799. {
  2800. m_buffer = s_renderWgpu->m_device.CreateBuffer(&desc);
  2801. map();
  2802. }
  2803. }
  2804. void StagingBufferWgpu::map()
  2805. {
  2806. auto ready = [](WGPUBufferMapAsyncStatus status, void* data, uint64_t dataLength, void* userdata)
  2807. {
  2808. if (status == WGPUBufferMapAsyncStatus_Success)
  2809. static_cast<StagingBufferWgpu*>(userdata)->mapped(data, dataLength);
  2810. };
  2811. m_buffer.MapWriteAsync(ready, this);
  2812. }
  2813. void StagingBufferWgpu::unmap()
  2814. {
  2815. m_data = NULL;
  2816. m_size = 0;
  2817. m_buffer.Unmap();
  2818. }
  2819. void StagingBufferWgpu::destroy()
  2820. {
  2821. m_buffer = NULL;
  2822. }
  2823. void StagingBufferWgpu::mapped(void* _data, uint64_t _size)
  2824. {
  2825. m_data = _data;
  2826. m_size = _size;
  2827. }
  2828. void ScratchBufferWgpu::create(uint32_t _size)
  2829. {
  2830. m_offset = 0;
  2831. m_size = _size;
  2832. wgpu::BufferDescriptor desc;
  2833. desc.size = BGFX_CONFIG_MAX_DRAW_CALLS * 128;
  2834. desc.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::Uniform;
  2835. m_buffer = s_renderWgpu->m_device.CreateBuffer(&desc);
  2836. }
  2837. void ScratchBufferWgpu::destroy()
  2838. {
  2839. }
  2840. void ScratchBufferWgpu::begin()
  2841. {
  2842. for (uint8_t ii = 0; ii < WEBGPU_NUM_UNIFORM_BUFFERS; ++ii)
  2843. {
  2844. if (NULL != s_renderWgpu->m_uniformBuffers[ii].m_data)
  2845. {
  2846. m_staging = &s_renderWgpu->m_uniformBuffers[ii];
  2847. break;
  2848. }
  2849. }
  2850. BX_CHECK(NULL != m_staging, "No available mapped uniform buffer");
  2851. }
  2852. uint32_t ScratchBufferWgpu::write(void* data, uint64_t _size, uint64_t _offset)
  2853. {
  2854. BX_CHECK(nullptr != m_staging, "Cannot write uniforms outside of begin()/submit() calls");
  2855. BX_CHECK(m_size > m_offset + _offset, "Out-of-bounds scratch buffer write");
  2856. uint32_t offset = m_offset;
  2857. bx::memCopy((void*)((uint8_t*)m_staging->m_data + offset), data, _size);
  2858. m_offset += _offset;
  2859. return offset;
  2860. }
  2861. uint32_t ScratchBufferWgpu::write(void* data, uint64_t _size)
  2862. {
  2863. BX_CHECK(nullptr != m_staging, "Cannot write uniforms outside of begin()/submit() calls");
  2864. BX_CHECK(m_size > m_offset + _size, "Out-of-bounds scratch buffer write");
  2865. uint32_t offset = m_offset;
  2866. bx::memCopy((void*)((uint8_t*)m_staging->m_data + offset), data, _size);
  2867. m_offset += _size;
  2868. return offset;
  2869. }
  2870. void ScratchBufferWgpu::submit()
  2871. {
  2872. m_staging->unmap();
  2873. if (m_offset != 0)
  2874. {
  2875. wgpu::CommandEncoder& bce = s_renderWgpu->getStagingEncoder();
  2876. bce.CopyBufferToBuffer(m_staging->m_buffer, 0, m_buffer, 0, m_offset);
  2877. }
  2878. }
  2879. void ScratchBufferWgpu::release()
  2880. {
  2881. m_staging->map();
  2882. m_staging = NULL;
  2883. m_offset = 0;
  2884. }
  2885. void BindStateCacheWgpu::create() //(uint32_t _maxBindGroups)
  2886. {
  2887. //m_maxBindStates = 1024; // _maxBindStates;
  2888. m_currentBindState = 0;
  2889. }
  2890. void BindStateCacheWgpu::destroy()
  2891. {
  2892. reset();
  2893. }
  2894. void BindStateCacheWgpu::reset()
  2895. {
  2896. for (size_t i = 0; i < m_currentBindState; ++i)
  2897. {
  2898. m_bindStates[i] = {};
  2899. }
  2900. m_currentBindState = 0;
  2901. }
  2902. wgpu::TextureView TextureWgpu::getTextureMipLevel(int _mip)
  2903. {
  2904. if (_mip >= 0
  2905. && _mip < m_numMips
  2906. && m_ptr)
  2907. {
  2908. if (!m_ptrMips[_mip])
  2909. {
  2910. wgpu::TextureViewDescriptor desc;
  2911. desc.baseMipLevel = _mip;
  2912. desc.mipLevelCount = 1;
  2913. desc.format = s_textureFormat[m_textureFormat].m_fmt;
  2914. if (TextureCube == m_type)
  2915. {
  2916. //desc.dimension = MTLTextureType2DArray;
  2917. desc.baseArrayLayer = 0;
  2918. desc.arrayLayerCount = m_numLayers * 6;
  2919. }
  2920. else
  2921. {
  2922. desc.baseArrayLayer = 0;
  2923. desc.arrayLayerCount = m_numLayers;
  2924. }
  2925. m_ptrMips[_mip] = m_ptr.CreateView(&desc);
  2926. }
  2927. return m_ptrMips[_mip];
  2928. }
  2929. return wgpu::TextureView();
  2930. }
  2931. void SwapChainWgpu::init(wgpu::Device _device, void* _nwh, uint32_t _width, uint32_t _height)
  2932. {
  2933. BX_UNUSED(_nwh);
  2934. wgpu::SwapChainDescriptor desc;
  2935. desc.usage = wgpu::TextureUsage::OutputAttachment;
  2936. desc.width = _width;
  2937. desc.height = _height;
  2938. #if !BX_PLATFORM_EMSCRIPTEN
  2939. m_impl = createSwapChain(_device, _nwh);
  2940. desc.presentMode = wgpu::PresentMode::Immediate;
  2941. desc.format = wgpu::TextureFormat::RGBA8Unorm;
  2942. desc.implementation = reinterpret_cast<uint64_t>(&m_impl);
  2943. m_swapChain = _device.CreateSwapChain(nullptr, &desc);
  2944. #else
  2945. wgpu::SurfaceDescriptorFromHTMLCanvasId canvasDesc{};
  2946. canvasDesc.id = "canvas";
  2947. wgpu::SurfaceDescriptor surfDesc{};
  2948. surfDesc.nextInChain = &canvasDesc;
  2949. wgpu::Surface surface = wgpu::Instance().CreateSurface(&surfDesc);
  2950. desc.presentMode = wgpu::PresentMode::Fifo;
  2951. desc.format = wgpu::TextureFormat::BGRA8Unorm;
  2952. m_swapChain = _device.CreateSwapChain(surface, &desc);
  2953. #endif
  2954. m_colorFormat = desc.format;
  2955. m_depthFormat = wgpu::TextureFormat::Depth24PlusStencil8;
  2956. }
  2957. void SwapChainWgpu::resize(FrameBufferWgpu& _frameBuffer, uint32_t _width, uint32_t _height, uint32_t _flags)
  2958. {
  2959. BX_TRACE("SwapChainWgpu::resize");
  2960. const int32_t sampleCount = s_msaa[(_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT];
  2961. wgpu::TextureFormat format = (_flags & BGFX_RESET_SRGB_BACKBUFFER)
  2962. #ifdef DAWN_ENABLE_BACKEND_VULKAN
  2963. ? wgpu::TextureFormat::BGRA8UnormSrgb
  2964. : wgpu::TextureFormat::BGRA8Unorm
  2965. #else
  2966. ? wgpu::TextureFormat::RGBA8UnormSrgb
  2967. : wgpu::TextureFormat::RGBA8Unorm
  2968. #endif
  2969. ;
  2970. #if !BX_PLATFORM_EMSCRIPTEN
  2971. m_swapChain.Configure(format, wgpu::TextureUsage::OutputAttachment, _width, _height);
  2972. #endif
  2973. m_colorFormat = format;
  2974. m_depthFormat = wgpu::TextureFormat::Depth24PlusStencil8;
  2975. bx::HashMurmur2A murmur;
  2976. murmur.begin();
  2977. murmur.add(1);
  2978. murmur.add((uint32_t)m_colorFormat);
  2979. murmur.add((uint32_t)m_depthFormat);
  2980. murmur.add((uint32_t)sampleCount);
  2981. _frameBuffer.m_pixelFormatHash = murmur.end();
  2982. wgpu::TextureDescriptor desc;
  2983. desc.dimension = wgpu::TextureDimension::e2D;
  2984. desc.size.width = _width;
  2985. desc.size.height = _height;
  2986. desc.size.depth = 1;
  2987. desc.mipLevelCount = 1;
  2988. desc.sampleCount = sampleCount;
  2989. desc.arrayLayerCount = 1;
  2990. desc.usage = wgpu::TextureUsage::OutputAttachment;
  2991. if (m_backBufferDepth)
  2992. {
  2993. m_backBufferDepth.Destroy();
  2994. }
  2995. desc.format = wgpu::TextureFormat::Depth24PlusStencil8;
  2996. m_backBufferDepth = s_renderWgpu->m_device.CreateTexture(&desc);
  2997. if (sampleCount > 1)
  2998. {
  2999. if (m_backBufferColorMsaa)
  3000. {
  3001. m_backBufferColorMsaa.Destroy();
  3002. }
  3003. desc.format = m_colorFormat;
  3004. desc.sampleCount = sampleCount;
  3005. m_backBufferColorMsaa = s_renderWgpu->m_device.CreateTexture(&desc);
  3006. }
  3007. }
  3008. void SwapChainWgpu::flip()
  3009. {
  3010. m_drawable = m_swapChain.GetCurrentTextureView();
  3011. }
  3012. wgpu::TextureView SwapChainWgpu::current()
  3013. {
  3014. if (!m_drawable)
  3015. m_drawable = m_swapChain.GetCurrentTextureView();
  3016. return m_drawable;
  3017. }
  3018. void FrameBufferWgpu::create(uint8_t _num, const Attachment* _attachment)
  3019. {
  3020. m_swapChain = NULL;
  3021. m_denseIdx = UINT16_MAX;
  3022. m_num = 0;
  3023. m_width = 0;
  3024. m_height = 0;
  3025. for (uint32_t ii = 0; ii < _num; ++ii)
  3026. {
  3027. const Attachment& at = _attachment[ii];
  3028. TextureHandle handle = at.handle;
  3029. if (isValid(handle) )
  3030. {
  3031. const TextureWgpu& texture = s_renderWgpu->m_textures[handle.idx];
  3032. if (0 == m_width)
  3033. {
  3034. m_width = texture.m_width;
  3035. m_height = texture.m_height;
  3036. }
  3037. if (bimg::isDepth(bimg::TextureFormat::Enum(texture.m_textureFormat) ) )
  3038. {
  3039. m_depthHandle = handle;
  3040. m_depthAttachment = at;
  3041. }
  3042. else
  3043. {
  3044. m_colorHandle[m_num] = handle;
  3045. m_colorAttachment[m_num] = at;
  3046. m_num++;
  3047. }
  3048. }
  3049. }
  3050. bx::HashMurmur2A murmur;
  3051. murmur.begin();
  3052. murmur.add(m_num);
  3053. for (uint32_t ii = 0; ii < m_num; ++ii)
  3054. {
  3055. const TextureWgpu& texture = s_renderWgpu->m_textures[m_colorHandle[ii].idx];
  3056. murmur.add(uint32_t(s_textureFormat[texture.m_textureFormat].m_fmt) );
  3057. }
  3058. if (!isValid(m_depthHandle) )
  3059. {
  3060. murmur.add(uint32_t(wgpu::TextureFormat::Undefined) );
  3061. }
  3062. else
  3063. {
  3064. const TextureWgpu& depthTexture = s_renderWgpu->m_textures[m_depthHandle.idx];
  3065. murmur.add(uint32_t(s_textureFormat[depthTexture.m_textureFormat].m_fmt) );
  3066. }
  3067. murmur.add(1); // SampleCount
  3068. m_pixelFormatHash = murmur.end();
  3069. }
  3070. bool FrameBufferWgpu::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat)
  3071. {
  3072. BX_UNUSED(_format, _depthFormat);
  3073. m_swapChain = BX_NEW(g_allocator, SwapChainWgpu);
  3074. m_num = 0;
  3075. m_width = _width;
  3076. m_height = _height;
  3077. m_nwh = _nwh;
  3078. m_denseIdx = _denseIdx;
  3079. m_swapChain->init(s_renderWgpu->m_device, _nwh, _width, _height);
  3080. m_swapChain->resize(*this, _width, _height, 0);
  3081. return m_swapChain->m_swapChain != NULL;
  3082. }
  3083. void FrameBufferWgpu::postReset()
  3084. {
  3085. }
  3086. uint16_t FrameBufferWgpu::destroy()
  3087. {
  3088. if (NULL != m_swapChain)
  3089. {
  3090. BX_DELETE(g_allocator, m_swapChain);
  3091. m_swapChain = NULL;
  3092. }
  3093. m_num = 0;
  3094. m_nwh = NULL;
  3095. m_depthHandle.idx = kInvalidHandle;
  3096. uint16_t denseIdx = m_denseIdx;
  3097. m_denseIdx = UINT16_MAX;
  3098. return denseIdx;
  3099. }
  3100. void CommandQueueWgpu::init(wgpu::Queue _queue)
  3101. {
  3102. m_queue = _queue;
  3103. #if BGFX_CONFIG_MULTITHREADED
  3104. //m_framesSemaphore.post(WEBGPU_MAX_FRAMES_IN_FLIGHT);
  3105. #endif
  3106. }
  3107. void CommandQueueWgpu::shutdown()
  3108. {
  3109. finish(true);
  3110. }
  3111. void CommandQueueWgpu::beginRender()
  3112. {
  3113. m_renderEncoder = s_renderWgpu->m_device.CreateCommandEncoder();
  3114. }
  3115. void CommandQueueWgpu::beginStaging()
  3116. {
  3117. m_stagingEncoder = s_renderWgpu->m_device.CreateCommandEncoder();
  3118. }
  3119. inline void commandBufferFinishedCallback(void* _data)
  3120. {
  3121. #if BGFX_CONFIG_MULTITHREADED
  3122. CommandQueueWgpu* queue = (CommandQueueWgpu*)_data;
  3123. if (queue)
  3124. {
  3125. //queue->m_framesSemaphore.post();
  3126. }
  3127. #else
  3128. BX_UNUSED(_data);
  3129. #endif
  3130. }
  3131. void CommandQueueWgpu::kick(bool _endFrame, bool _waitForFinish)
  3132. {
  3133. if (m_renderEncoder)
  3134. {
  3135. if (_endFrame)
  3136. {
  3137. m_releaseWriteIndex = (m_releaseWriteIndex + 1) % WEBGPU_MAX_FRAMES_IN_FLIGHT;
  3138. //m_encoder.addCompletedHandler(commandBufferFinishedCallback, this);
  3139. }
  3140. if (m_stagingEncoder)
  3141. {
  3142. wgpu::CommandBuffer commands = m_stagingEncoder.Finish();
  3143. m_queue.Submit(1, &commands);
  3144. }
  3145. wgpu::CommandBuffer commands = m_renderEncoder.Finish();
  3146. m_queue.Submit(1, &commands);
  3147. if (_waitForFinish)
  3148. {
  3149. #if BGFX_CONFIG_MULTITHREADED
  3150. //m_framesSemaphore.post();
  3151. #endif
  3152. }
  3153. m_stagingEncoder = NULL;
  3154. m_renderEncoder = NULL;
  3155. }
  3156. }
  3157. void CommandQueueWgpu::finish(bool _finishAll)
  3158. {
  3159. if (_finishAll)
  3160. {
  3161. uint32_t count = m_renderEncoder
  3162. ? 2
  3163. : 3
  3164. ;
  3165. for (uint32_t ii = 0; ii < count; ++ii)
  3166. {
  3167. consume();
  3168. }
  3169. #if BGFX_CONFIG_MULTITHREADED
  3170. //m_framesSemaphore.post(count);
  3171. #endif
  3172. }
  3173. else
  3174. {
  3175. consume();
  3176. }
  3177. }
  3178. void CommandQueueWgpu::release(wgpu::Buffer _buffer)
  3179. {
  3180. m_release[m_releaseWriteIndex].push_back(_buffer);
  3181. }
  3182. void CommandQueueWgpu::consume()
  3183. {
  3184. #if BGFX_CONFIG_MULTITHREADED
  3185. //m_framesSemaphore.wait();
  3186. #endif
  3187. m_releaseReadIndex = (m_releaseReadIndex + 1) % WEBGPU_MAX_FRAMES_IN_FLIGHT;
  3188. for (wgpu::Buffer& buffer : m_release[m_releaseReadIndex])
  3189. {
  3190. buffer.Destroy();
  3191. }
  3192. m_release[m_releaseReadIndex].clear();
  3193. }
  3194. void TimerQueryWgpu::init()
  3195. {
  3196. m_frequency = bx::getHPFrequency();
  3197. }
  3198. void TimerQueryWgpu::shutdown()
  3199. {
  3200. }
  3201. uint32_t TimerQueryWgpu::begin(uint32_t _resultIdx)
  3202. {
  3203. BX_UNUSED(_resultIdx);
  3204. return 0;
  3205. }
  3206. void TimerQueryWgpu::end(uint32_t _idx)
  3207. {
  3208. BX_UNUSED(_idx);
  3209. }
  3210. #if 0
  3211. static void setTimestamp(void* _data)
  3212. {
  3213. *( (int64_t*)_data) = bx::getHPCounter();
  3214. }
  3215. #endif
  3216. void TimerQueryWgpu::addHandlers(wgpu::CommandBuffer& _commandBuffer)
  3217. {
  3218. BX_UNUSED(_commandBuffer);
  3219. while (0 == m_control.reserve(1) )
  3220. {
  3221. m_control.consume(1);
  3222. }
  3223. //uint32_t offset = m_control.m_current;
  3224. //_commandBuffer.addScheduledHandler(setTimestamp, &m_result[offset].m_begin);
  3225. //_commandBuffer.addCompletedHandler(setTimestamp, &m_result[offset].m_end);
  3226. m_control.commit(1);
  3227. }
  3228. bool TimerQueryWgpu::get()
  3229. {
  3230. if (0 != m_control.available() )
  3231. {
  3232. uint32_t offset = m_control.m_read;
  3233. m_begin = m_result[offset].m_begin;
  3234. m_end = m_result[offset].m_end;
  3235. m_elapsed = m_end - m_begin;
  3236. m_control.consume(1);
  3237. return true;
  3238. }
  3239. return false;
  3240. }
  3241. void RendererContextWgpu::submitBlit(BlitState& _bs, uint16_t _view)
  3242. {
  3243. if (!_bs.hasItem(_view) )
  3244. {
  3245. return;
  3246. }
  3247. endEncoding();
  3248. wgpu::CommandEncoder& bce = getBlitCommandEncoder();
  3249. while (_bs.hasItem(_view) )
  3250. {
  3251. const BlitItem& blit = _bs.advance();
  3252. const TextureWgpu& src = m_textures[blit.m_src.idx];
  3253. const TextureWgpu& dst = m_textures[blit.m_dst.idx];
  3254. uint32_t srcWidth = bx::uint32_min(src.m_width, blit.m_srcX + blit.m_width) - blit.m_srcX;
  3255. uint32_t srcHeight = bx::uint32_min(src.m_height, blit.m_srcY + blit.m_height) - blit.m_srcY;
  3256. uint32_t srcDepth = bx::uint32_min(src.m_depth, blit.m_srcZ + blit.m_depth) - blit.m_srcZ;
  3257. uint32_t dstWidth = bx::uint32_min(dst.m_width, blit.m_dstX + blit.m_width) - blit.m_dstX;
  3258. uint32_t dstHeight = bx::uint32_min(dst.m_height, blit.m_dstY + blit.m_height) - blit.m_dstY;
  3259. uint32_t dstDepth = bx::uint32_min(dst.m_depth, blit.m_dstZ + blit.m_depth) - blit.m_dstZ;
  3260. uint32_t width = bx::uint32_min(srcWidth, dstWidth);
  3261. uint32_t height = bx::uint32_min(srcHeight, dstHeight);
  3262. uint32_t depth = bx::uint32_min(srcDepth, dstDepth);
  3263. bool readBack = !!(dst.m_flags & BGFX_TEXTURE_READ_BACK);
  3264. wgpu::TextureCopyView srcView;
  3265. srcView.texture = src.m_ptr;
  3266. srcView.origin = { blit.m_srcX, blit.m_srcY, 0 };
  3267. srcView.mipLevel = blit.m_srcMip;
  3268. srcView.arrayLayer = blit.m_srcZ;
  3269. wgpu::TextureCopyView dstView;
  3270. dstView.texture = dst.m_ptr;
  3271. dstView.origin = { blit.m_dstX, blit.m_dstY, 0 };
  3272. dstView.mipLevel = blit.m_dstMip;
  3273. dstView.arrayLayer = blit.m_dstZ;
  3274. if (depth == 0)
  3275. {
  3276. wgpu::Extent3D copyExtent = { width, height, 1 };
  3277. bce.CopyTextureToTexture(&srcView, &dstView, &copyExtent);
  3278. }
  3279. else
  3280. {
  3281. wgpu::Extent3D copyExtent = { width, height, depth };
  3282. bce.CopyTextureToTexture(&srcView, &dstView, &copyExtent);
  3283. }
  3284. if (readBack)
  3285. {
  3286. //bce..synchronizeTexture(dst.m_ptr, 0, blit.m_dstMip);
  3287. }
  3288. }
  3289. //if (bce)
  3290. //{
  3291. // bce.endEncoding();
  3292. // bce = 0;
  3293. //}
  3294. }
  3295. void RendererContextWgpu::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  3296. {
  3297. if(_render->m_capture)
  3298. {
  3299. renderDocTriggerCapture();
  3300. }
  3301. m_cmd.finish(false);
  3302. if (!m_cmd.m_renderEncoder)
  3303. {
  3304. m_cmd.beginRender();
  3305. }
  3306. BGFX_WEBGPU_PROFILER_BEGIN_LITERAL("rendererSubmit", kColorFrame);
  3307. int64_t timeBegin = bx::getHPCounter();
  3308. int64_t captureElapsed = 0;
  3309. //m_gpuTimer.addHandlers(m_encoder);
  3310. updateResolution(_render->m_resolution);
  3311. m_frameIndex = 0; // (m_frameIndex + 1) % WEBGPU_MAX_FRAMES_IN_FLIGHT;
  3312. ScratchBufferWgpu& scratchBuffer = m_scratchBuffers[m_frameIndex];
  3313. scratchBuffer.begin();
  3314. BindStateCacheWgpu& bindStates = m_bindStateCache[m_frameIndex];
  3315. bindStates.reset();
  3316. if (0 < _render->m_iboffset)
  3317. {
  3318. BGFX_PROFILER_SCOPE("bgfx/Update transient index buffer", kColorResource);
  3319. TransientIndexBuffer* ib = _render->m_transientIb;
  3320. m_indexBuffers[ib->handle.idx].update(0, bx::strideAlign(_render->m_iboffset,4), ib->data, true);
  3321. }
  3322. if (0 < _render->m_vboffset)
  3323. {
  3324. BGFX_PROFILER_SCOPE("bgfx/Update transient vertex buffer", kColorResource);
  3325. TransientVertexBuffer* vb = _render->m_transientVb;
  3326. m_vertexBuffers[vb->handle.idx].update(0, bx::strideAlign(_render->m_vboffset,4), vb->data, true);
  3327. }
  3328. _render->sort();
  3329. RenderDraw currentState;
  3330. currentState.clear();
  3331. currentState.m_stateFlags = BGFX_STATE_NONE;
  3332. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  3333. RenderBind currentBind;
  3334. currentBind.clear();
  3335. static ViewState viewState;
  3336. viewState.reset(_render);
  3337. uint32_t blendFactor = 0;
  3338. //bool wireframe = !!(_render->m_debug&BGFX_DEBUG_WIREFRAME);
  3339. ProgramHandle currentProgram = BGFX_INVALID_HANDLE;
  3340. uint32_t currentBindHash = 0;
  3341. uint32_t currentBindLayoutHash = 0;
  3342. BindStateWgpu* previousBindState = NULL;
  3343. SortKey key;
  3344. uint16_t view = UINT16_MAX;
  3345. FrameBufferHandle fbh = { BGFX_CONFIG_MAX_FRAME_BUFFERS };
  3346. BlitState bs(_render);
  3347. const uint64_t primType = 0;
  3348. uint8_t primIndex = uint8_t(primType >> BGFX_STATE_PT_SHIFT);
  3349. PrimInfo prim = s_primInfo[primIndex];
  3350. const uint32_t maxComputeBindings = g_caps.limits.maxComputeBindings;
  3351. // TODO store this
  3352. static wgpu::RenderPassEncoder rce;
  3353. PipelineStateWgpu* currentPso = NULL;
  3354. bool wasCompute = false;
  3355. bool viewHasScissor = false;
  3356. Rect viewScissorRect;
  3357. viewScissorRect.clear();
  3358. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  3359. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  3360. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  3361. uint32_t statsNumDrawIndirect[BX_COUNTOF(s_primInfo)] = {};
  3362. uint32_t statsNumIndices = 0;
  3363. uint32_t statsKeyType[2] = {};
  3364. Profiler<TimerQueryWgpu> profiler(
  3365. _render
  3366. , m_gpuTimer
  3367. , s_viewName
  3368. );
  3369. if (0 == (_render->m_debug & BGFX_DEBUG_IFH))
  3370. {
  3371. viewState.m_rect = _render->m_view[0].m_rect;
  3372. int32_t numItems = _render->m_numRenderItems;
  3373. for (int32_t item = 0; item < numItems;)
  3374. {
  3375. const uint64_t encodedKey = _render->m_sortKeys[item];
  3376. const bool isCompute = key.decode(encodedKey, _render->m_viewRemap);
  3377. statsKeyType[isCompute]++;
  3378. const bool viewChanged = 0
  3379. || key.m_view != view
  3380. || item == numItems
  3381. ;
  3382. const uint32_t itemIdx = _render->m_sortValues[item];
  3383. const RenderItem& renderItem = _render->m_renderItem[itemIdx];
  3384. const RenderBind& renderBind = _render->m_renderItemBind[itemIdx];
  3385. ++item;
  3386. if (viewChanged
  3387. || (!isCompute && wasCompute))
  3388. {
  3389. view = key.m_view;
  3390. currentProgram = BGFX_INVALID_HANDLE;
  3391. if (item > 1)
  3392. {
  3393. profiler.end();
  3394. }
  3395. BGFX_WEBGPU_PROFILER_END();
  3396. setViewType(view, " ");
  3397. BGFX_WEBGPU_PROFILER_BEGIN(view, kColorView);
  3398. profiler.begin(view);
  3399. viewState.m_rect = _render->m_view[view].m_rect;
  3400. submitBlit(bs, view);
  3401. if (!isCompute)
  3402. {
  3403. const Rect& scissorRect = _render->m_view[view].m_scissor;
  3404. viewHasScissor = !scissorRect.isZero();
  3405. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  3406. Clear& clr = _render->m_view[view].m_clear;
  3407. Rect viewRect = viewState.m_rect;
  3408. bool clearWithRenderPass = false;
  3409. if (!m_renderEncoder
  3410. || fbh.idx != _render->m_view[view].m_fbh.idx)
  3411. {
  3412. endEncoding();
  3413. fbh = _render->m_view[view].m_fbh;
  3414. uint32_t width = m_resolution.width;
  3415. uint32_t height = m_resolution.height;
  3416. if (isValid(fbh))
  3417. {
  3418. FrameBufferWgpu& frameBuffer = m_frameBuffers[fbh.idx];
  3419. width = frameBuffer.m_width;
  3420. height = frameBuffer.m_height;
  3421. }
  3422. clearWithRenderPass = true
  3423. && 0 == viewRect.m_x
  3424. && 0 == viewRect.m_y
  3425. && width == viewRect.m_width
  3426. && height == viewRect.m_height
  3427. ;
  3428. rce = renderPass(_render, fbh, clearWithRenderPass, clr, s_viewName[view]);
  3429. }
  3430. else if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3431. {
  3432. rce.PopDebugGroup();
  3433. }
  3434. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3435. {
  3436. rce.PushDebugGroup(s_viewName[view]);
  3437. }
  3438. //rce.setTriangleFillMode(wireframe ? MTLTriangleFillModeLines : MTLTriangleFillModeFill);
  3439. const Rect& rect = viewState.m_rect;
  3440. rce.SetViewport(rect.m_x, rect.m_y, rect.m_width, rect.m_height, 0.0f, 1.0f);
  3441. rce.SetScissorRect(rect.m_x, rect.m_y, rect.m_width, rect.m_height);
  3442. if (BGFX_CLEAR_NONE != (clr.m_flags & BGFX_CLEAR_MASK)
  3443. && !clearWithRenderPass)
  3444. {
  3445. clearQuad(_clearQuad, viewState.m_rect, clr, _render->m_colorPalette);
  3446. }
  3447. }
  3448. }
  3449. if (isCompute)
  3450. {
  3451. if (!wasCompute)
  3452. {
  3453. wasCompute = true;
  3454. endEncoding();
  3455. rce = NULL;
  3456. setViewType(view, "C");
  3457. BGFX_WEBGPU_PROFILER_END();
  3458. BGFX_WEBGPU_PROFILER_BEGIN(view, kColorCompute);
  3459. m_computeEncoder = m_cmd.m_renderEncoder.BeginComputePass();
  3460. }
  3461. else if (viewChanged)
  3462. {
  3463. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3464. {
  3465. m_computeEncoder.PopDebugGroup();
  3466. }
  3467. endEncoding();
  3468. m_computeEncoder = m_cmd.m_renderEncoder.BeginComputePass();
  3469. }
  3470. if (viewChanged)
  3471. {
  3472. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3473. {
  3474. s_viewName[view][3] = L'C';
  3475. m_computeEncoder.PushDebugGroup(s_viewName[view]);
  3476. s_viewName[view][3] = L' ';
  3477. }
  3478. }
  3479. const RenderCompute& compute = renderItem.compute;
  3480. bool programChanged = false;
  3481. bool constantsChanged = compute.m_uniformBegin < compute.m_uniformEnd;
  3482. rendererUpdateUniforms(this, _render->m_uniformBuffer[compute.m_uniformIdx], compute.m_uniformBegin, compute.m_uniformEnd);
  3483. if (key.m_program.idx != currentProgram.idx)
  3484. {
  3485. currentProgram = key.m_program;
  3486. currentPso = getComputePipelineState(currentProgram);
  3487. if (NULL == currentPso)
  3488. {
  3489. currentProgram = BGFX_INVALID_HANDLE;
  3490. continue;
  3491. }
  3492. m_computeEncoder.SetPipeline(currentPso->m_cps);
  3493. programChanged =
  3494. constantsChanged = true;
  3495. }
  3496. if (!isValid(currentProgram)
  3497. || NULL == currentPso)
  3498. BX_WARN(false, "Invalid program / No PSO");
  3499. const ProgramWgpu& program = m_program[currentProgram.idx];
  3500. if (constantsChanged)
  3501. {
  3502. UniformBuffer* vcb = program.m_vsh->m_constantBuffer;
  3503. if (NULL != vcb)
  3504. {
  3505. commit(*vcb);
  3506. }
  3507. }
  3508. viewState.setPredefined<4>(this, view, program, _render, compute);
  3509. uint32_t numOffset = 1;
  3510. uint32_t offsets[2] = { scratchBuffer.m_offset, 0 };
  3511. if (program.m_vsh->m_size > 0)
  3512. {
  3513. scratchBuffer.write(m_vsScratch, program.m_vsh->m_gpuSize);
  3514. }
  3515. BindStateWgpu& bindState = allocAndFillBindState(program, bindStates, scratchBuffer, renderBind);
  3516. bindProgram(m_computeEncoder, program, bindState, numOffset, offsets);
  3517. if (isValid(compute.m_indirectBuffer))
  3518. {
  3519. const VertexBufferWgpu& vb = m_vertexBuffers[compute.m_indirectBuffer.idx];
  3520. uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect
  3521. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  3522. : compute.m_numIndirect
  3523. ;
  3524. uint32_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  3525. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  3526. {
  3527. m_computeEncoder.DispatchIndirect(
  3528. vb.m_ptr
  3529. , args
  3530. );
  3531. args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  3532. }
  3533. }
  3534. else
  3535. {
  3536. m_computeEncoder.Dispatch(compute.m_numX, compute.m_numY, compute.m_numZ);
  3537. }
  3538. continue;
  3539. }
  3540. bool resetState = viewChanged || wasCompute;
  3541. if (wasCompute)
  3542. {
  3543. wasCompute = false;
  3544. currentProgram = BGFX_INVALID_HANDLE;
  3545. setViewType(view, " ");
  3546. BGFX_WEBGPU_PROFILER_END();
  3547. BGFX_WEBGPU_PROFILER_BEGIN(view, kColorDraw);
  3548. }
  3549. const RenderDraw& draw = renderItem.draw;
  3550. // TODO (hugoam)
  3551. //const bool depthWrite = !!(BGFX_STATE_WRITE_Z & draw.m_stateFlags);
  3552. const uint64_t newFlags = draw.m_stateFlags;
  3553. uint64_t changedFlags = currentState.m_stateFlags ^ draw.m_stateFlags;
  3554. currentState.m_stateFlags = newFlags;
  3555. const uint64_t newStencil = draw.m_stencil;
  3556. uint64_t changedStencil = (currentState.m_stencil ^ draw.m_stencil) & BGFX_STENCIL_FUNC_REF_MASK;
  3557. currentState.m_stencil = newStencil;
  3558. if (resetState)
  3559. {
  3560. wasCompute = false;
  3561. currentState.clear();
  3562. currentState.m_scissor = !draw.m_scissor;
  3563. changedFlags = BGFX_STATE_MASK;
  3564. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  3565. currentState.m_stateFlags = newFlags;
  3566. currentState.m_stencil = newStencil;
  3567. currentBind.clear();
  3568. currentProgram = BGFX_INVALID_HANDLE;
  3569. const uint64_t pt = newFlags & BGFX_STATE_PT_MASK;
  3570. primIndex = uint8_t(pt >> BGFX_STATE_PT_SHIFT);
  3571. }
  3572. if (prim.m_type != s_primInfo[primIndex].m_type)
  3573. {
  3574. prim = s_primInfo[primIndex];
  3575. }
  3576. uint16_t scissor = draw.m_scissor;
  3577. if (currentState.m_scissor != scissor)
  3578. {
  3579. currentState.m_scissor = scissor;
  3580. if (UINT16_MAX == scissor)
  3581. {
  3582. if (viewHasScissor)
  3583. {
  3584. const auto& r = viewScissorRect;
  3585. rce.SetScissorRect(r.m_x, r.m_y, r.m_width, r.m_height);
  3586. }
  3587. else
  3588. { // can't disable: set to view rect
  3589. const auto& r = viewState.m_rect;
  3590. rce.SetScissorRect(r.m_x, r.m_y, r.m_width, r.m_height);
  3591. }
  3592. }
  3593. else
  3594. {
  3595. Rect scissorRect;
  3596. scissorRect.setIntersect(viewScissorRect, _render->m_frameCache.m_rectCache.m_cache[scissor]);
  3597. const auto& r = scissorRect;
  3598. if (r.m_width == 0 || r.m_height == 0)
  3599. {
  3600. continue;
  3601. }
  3602. rce.SetScissorRect(r.m_x, r.m_y, r.m_width, r.m_height);
  3603. }
  3604. }
  3605. if (0 != changedStencil)
  3606. {
  3607. const uint32_t fstencil = unpackStencil(0, draw.m_stencil);
  3608. const uint32_t ref = (fstencil & BGFX_STENCIL_FUNC_REF_MASK) >> BGFX_STENCIL_FUNC_REF_SHIFT;
  3609. rce.SetStencilReference(ref);
  3610. }
  3611. if ((0 | BGFX_STATE_PT_MASK) & changedFlags)
  3612. {
  3613. const uint64_t pt = newFlags & BGFX_STATE_PT_MASK;
  3614. primIndex = uint8_t(pt >> BGFX_STATE_PT_SHIFT);
  3615. if (prim.m_type != s_primInfo[primIndex].m_type)
  3616. {
  3617. prim = s_primInfo[primIndex];
  3618. }
  3619. }
  3620. if (blendFactor != draw.m_rgba
  3621. && !(newFlags & BGFX_STATE_BLEND_INDEPENDENT))
  3622. {
  3623. const uint32_t rgba = draw.m_rgba;
  3624. float rr = ((rgba >> 24)) / 255.0f;
  3625. float gg = ((rgba >> 16) & 0xff) / 255.0f;
  3626. float bb = ((rgba >> 8) & 0xff) / 255.0f;
  3627. float aa = ((rgba) & 0xff) / 255.0f;
  3628. wgpu::Color color = { rr, gg, bb, aa };
  3629. rce.SetBlendColor(&color);
  3630. blendFactor = draw.m_rgba;
  3631. }
  3632. bool programChanged = false;
  3633. bool constantsChanged = draw.m_uniformBegin < draw.m_uniformEnd;
  3634. rendererUpdateUniforms(this, _render->m_uniformBuffer[draw.m_uniformIdx], draw.m_uniformBegin, draw.m_uniformEnd);
  3635. bool vertexStreamChanged = hasVertexStreamChanged(currentState, draw);
  3636. if (key.m_program.idx != currentProgram.idx
  3637. || vertexStreamChanged
  3638. || (0
  3639. | BGFX_STATE_BLEND_MASK
  3640. | BGFX_STATE_BLEND_EQUATION_MASK
  3641. | BGFX_STATE_WRITE_RGB
  3642. | BGFX_STATE_WRITE_A
  3643. | BGFX_STATE_BLEND_INDEPENDENT
  3644. | BGFX_STATE_MSAA
  3645. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  3646. ) & changedFlags
  3647. || ((blendFactor != draw.m_rgba) && !!(newFlags & BGFX_STATE_BLEND_INDEPENDENT)))
  3648. {
  3649. currentProgram = key.m_program;
  3650. currentState.m_streamMask = draw.m_streamMask;
  3651. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  3652. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  3653. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  3654. const VertexLayout* decls[BGFX_CONFIG_MAX_VERTEX_STREAMS];
  3655. uint32_t numVertices = draw.m_numVertices;
  3656. uint8_t numStreams = 0;
  3657. for (uint32_t idx = 0, streamMask = draw.m_streamMask
  3658. ; 0 != streamMask
  3659. ; streamMask >>= 1, idx += 1, ++numStreams
  3660. )
  3661. {
  3662. const uint32_t ntz = bx::uint32_cnttz(streamMask);
  3663. streamMask >>= ntz;
  3664. idx += ntz;
  3665. currentState.m_stream[idx].m_layoutHandle = draw.m_stream[idx].m_layoutHandle;
  3666. currentState.m_stream[idx].m_handle = draw.m_stream[idx].m_handle;
  3667. currentState.m_stream[idx].m_startVertex = draw.m_stream[idx].m_startVertex;
  3668. const uint16_t handle = draw.m_stream[idx].m_handle.idx;
  3669. const VertexBufferWgpu& vb = m_vertexBuffers[handle];
  3670. const uint16_t decl = isValid(draw.m_stream[idx].m_layoutHandle)
  3671. ? draw.m_stream[idx].m_layoutHandle.idx
  3672. : vb.m_layoutHandle.idx;
  3673. const VertexLayout& vertexDecl = m_vertexDecls[decl];
  3674. const uint32_t stride = vertexDecl.m_stride;
  3675. decls[numStreams] = &vertexDecl;
  3676. numVertices = bx::uint32_min(UINT32_MAX == draw.m_numVertices
  3677. ? vb.m_size / stride
  3678. : draw.m_numVertices
  3679. , numVertices
  3680. );
  3681. const uint32_t offset = draw.m_stream[idx].m_startVertex * stride;
  3682. rce.SetVertexBuffer(idx, vb.m_ptr, offset);
  3683. }
  3684. bool index32 = false;
  3685. if (isValid(draw.m_indexBuffer))
  3686. {
  3687. const IndexBufferWgpu& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  3688. index32 = 0 != (ib.m_flags & BGFX_BUFFER_INDEX32);
  3689. }
  3690. currentState.m_numVertices = numVertices;
  3691. if (!isValid(currentProgram))
  3692. {
  3693. continue;
  3694. }
  3695. else
  3696. {
  3697. currentPso = NULL;
  3698. if (0 < numStreams)
  3699. {
  3700. currentPso = getPipelineState(
  3701. newFlags
  3702. , newStencil
  3703. , draw.m_rgba
  3704. , fbh
  3705. , numStreams
  3706. , decls
  3707. , index32
  3708. , currentProgram
  3709. , uint8_t(draw.m_instanceDataStride / 16)
  3710. );
  3711. }
  3712. if (NULL == currentPso)
  3713. {
  3714. currentProgram = BGFX_INVALID_HANDLE;
  3715. continue;
  3716. }
  3717. rce.SetPipeline(currentPso->m_rps);
  3718. }
  3719. if (isValid(draw.m_instanceDataBuffer))
  3720. {
  3721. const VertexBufferWgpu& inst = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  3722. rce.SetVertexBuffer(numStreams/*+1*/, inst.m_ptr, draw.m_instanceDataOffset);
  3723. }
  3724. programChanged =
  3725. constantsChanged = true;
  3726. }
  3727. if (isValid(currentProgram))
  3728. {
  3729. const ProgramWgpu& program = m_program[currentProgram.idx];
  3730. if (constantsChanged)
  3731. {
  3732. UniformBuffer* vcb = program.m_vsh->m_constantBuffer;
  3733. if (NULL != vcb)
  3734. {
  3735. commit(*vcb);
  3736. }
  3737. }
  3738. if (constantsChanged)
  3739. {
  3740. UniformBuffer* fcb = program.m_fsh->m_constantBuffer;
  3741. if (NULL != fcb)
  3742. {
  3743. commit(*fcb);
  3744. }
  3745. }
  3746. viewState.setPredefined<4>(this, view, program, _render, draw);
  3747. bool hasPredefined = 0 < program.m_numPredefined;
  3748. uint32_t numOffset = 0;
  3749. uint32_t offsets[2] = { 0, 0 };
  3750. if (constantsChanged
  3751. || hasPredefined)
  3752. {
  3753. //viewState.setPredefined<4>(this, view, program, _render, draw, programChanged || viewChanged);
  3754. //commitShaderConstants(scratchBuffer, program, voffset, foffset);
  3755. const uint32_t vsize = program.m_vsh->m_gpuSize;
  3756. const uint32_t fsize = (NULL != program.m_fsh ? program.m_fsh->m_gpuSize : 0);
  3757. if (program.m_vsh->m_size > 0)
  3758. {
  3759. offsets[numOffset++] = scratchBuffer.write(m_vsScratch, vsize);
  3760. }
  3761. if (fsize > 0)
  3762. {
  3763. offsets[numOffset++] = scratchBuffer.write(m_fsScratch, fsize);
  3764. }
  3765. }
  3766. uint32_t bindHash = bx::hash<bx::HashMurmur2A>(renderBind.m_bind, sizeof(renderBind.m_bind));
  3767. if (currentBindHash != bindHash
  3768. || currentBindLayoutHash != program.m_bindGroupLayoutHash)
  3769. {
  3770. currentBindHash = bindHash;
  3771. currentBindLayoutHash = program.m_bindGroupLayoutHash;
  3772. previousBindState = &bindStates.m_bindStates[bindStates.m_currentBindState];
  3773. allocAndFillBindState(program, bindStates, scratchBuffer, renderBind);
  3774. }
  3775. BindStateWgpu& bindState = bindStates.m_bindStates[bindStates.m_currentBindState-1];
  3776. bindProgram(rce, program, bindState, numOffset, offsets);
  3777. }
  3778. if (0 != currentState.m_streamMask)
  3779. {
  3780. uint32_t numVertices = draw.m_numVertices;
  3781. if (UINT32_MAX == numVertices)
  3782. {
  3783. const VertexBufferWgpu& vb = m_vertexBuffers[currentState.m_stream[0].m_handle.idx];
  3784. uint16_t decl = !isValid(vb.m_layoutHandle) ? draw.m_stream[0].m_layoutHandle.idx : vb.m_layoutHandle.idx;
  3785. const VertexLayout& vertexDecl = m_vertexDecls[decl];
  3786. numVertices = vb.m_size/vertexDecl.m_stride;
  3787. }
  3788. uint32_t numIndices = 0;
  3789. uint32_t numPrimsSubmitted = 0;
  3790. uint32_t numInstances = 0;
  3791. uint32_t numPrimsRendered = 0;
  3792. uint32_t numDrawIndirect = 0;
  3793. if (isValid(draw.m_indirectBuffer) )
  3794. {
  3795. const VertexBufferWgpu& vb = m_vertexBuffers[draw.m_indirectBuffer.idx];
  3796. if (isValid(draw.m_indexBuffer) )
  3797. {
  3798. const IndexBufferWgpu& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  3799. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  3800. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  3801. : draw.m_numIndirect
  3802. ;
  3803. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  3804. {
  3805. rce.SetIndexBuffer(ib.m_ptr, 0);
  3806. rce.DrawIndexedIndirect(vb.m_ptr, (draw.m_startIndirect + ii)* BGFX_CONFIG_DRAW_INDIRECT_STRIDE);
  3807. }
  3808. }
  3809. else
  3810. {
  3811. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  3812. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  3813. : draw.m_numIndirect
  3814. ;
  3815. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  3816. {
  3817. rce.DrawIndirect(vb.m_ptr, (draw.m_startIndirect + ii)* BGFX_CONFIG_DRAW_INDIRECT_STRIDE);
  3818. }
  3819. }
  3820. }
  3821. else
  3822. {
  3823. if (isValid(draw.m_indexBuffer) )
  3824. {
  3825. const IndexBufferWgpu& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  3826. const uint32_t indexSize = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32) ? 2 : 4;
  3827. if (UINT32_MAX == draw.m_numIndices)
  3828. {
  3829. numIndices = ib.m_size/indexSize;
  3830. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3831. numInstances = draw.m_numInstances;
  3832. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3833. rce.SetIndexBuffer(ib.m_ptr, 0);
  3834. rce.DrawIndexed(numIndices, draw.m_numInstances, 0, 0, 0);
  3835. }
  3836. else if (prim.m_min <= draw.m_numIndices)
  3837. {
  3838. numIndices = draw.m_numIndices;
  3839. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  3840. numInstances = draw.m_numInstances;
  3841. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3842. rce.SetIndexBuffer(ib.m_ptr, 0);
  3843. rce.DrawIndexed(numIndices, numInstances, draw.m_startIndex, 0, 0);
  3844. }
  3845. }
  3846. else
  3847. {
  3848. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  3849. numInstances = draw.m_numInstances;
  3850. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  3851. rce.Draw(numVertices, draw.m_numInstances, 0, 0);
  3852. }
  3853. }
  3854. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  3855. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  3856. statsNumInstances[primIndex] += numInstances;
  3857. statsNumDrawIndirect[primIndex] += numDrawIndirect;
  3858. statsNumIndices += numIndices;
  3859. }
  3860. }
  3861. if (wasCompute)
  3862. {
  3863. invalidateCompute();
  3864. setViewType(view, "C");
  3865. BGFX_WEBGPU_PROFILER_END();
  3866. BGFX_WEBGPU_PROFILER_BEGIN(view, kColorCompute);
  3867. }
  3868. submitBlit(bs, BGFX_CONFIG_MAX_VIEWS);
  3869. if (0 < _render->m_numRenderItems)
  3870. {
  3871. captureElapsed = -bx::getHPCounter();
  3872. capture();
  3873. rce = m_renderEncoder;
  3874. captureElapsed += bx::getHPCounter();
  3875. profiler.end();
  3876. }
  3877. }
  3878. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  3879. {
  3880. if (0 < _render->m_numRenderItems)
  3881. {
  3882. rce.PopDebugGroup();
  3883. }
  3884. }
  3885. BGFX_WEBGPU_PROFILER_END();
  3886. int64_t timeEnd = bx::getHPCounter();
  3887. int64_t frameTime = timeEnd - timeBegin;
  3888. static int64_t min = frameTime;
  3889. static int64_t max = frameTime;
  3890. min = bx::min<int64_t>(min, frameTime);
  3891. max = bx::max<int64_t>(max, frameTime);
  3892. static uint32_t maxGpuLatency = 0;
  3893. static double maxGpuElapsed = 0.0f;
  3894. double elapsedGpuMs = 0.0;
  3895. do
  3896. {
  3897. double toGpuMs = 1000.0 / double(m_gpuTimer.m_frequency);
  3898. elapsedGpuMs = m_gpuTimer.m_elapsed * toGpuMs;
  3899. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  3900. }
  3901. while (m_gpuTimer.get() );
  3902. maxGpuLatency = bx::uint32_imax(maxGpuLatency, m_gpuTimer.m_control.available()-1);
  3903. const int64_t timerFreq = bx::getHPFrequency();
  3904. Stats& perfStats = _render->m_perfStats;
  3905. perfStats.cpuTimeBegin = timeBegin;
  3906. perfStats.cpuTimeEnd = timeEnd;
  3907. perfStats.cpuTimerFreq = timerFreq;
  3908. perfStats.gpuTimeBegin = m_gpuTimer.m_begin;
  3909. perfStats.gpuTimeEnd = m_gpuTimer.m_end;
  3910. perfStats.gpuTimerFreq = m_gpuTimer.m_frequency;
  3911. perfStats.numDraw = statsKeyType[0];
  3912. perfStats.numCompute = statsKeyType[1];
  3913. perfStats.numBlit = _render->m_numBlitItems;
  3914. perfStats.maxGpuLatency = maxGpuLatency;
  3915. bx::memCopy(perfStats.numPrims, statsNumPrimsRendered, sizeof(perfStats.numPrims) );
  3916. perfStats.gpuMemoryMax = -INT64_MAX;
  3917. perfStats.gpuMemoryUsed = -INT64_MAX;
  3918. //rce.setTriangleFillMode(MTLTriangleFillModeFill);
  3919. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  3920. {
  3921. rce = renderPass(_render, BGFX_INVALID_HANDLE, false, Clear());
  3922. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3923. {
  3924. rce.PushDebugGroup("debugstats");
  3925. }
  3926. TextVideoMem& tvm = m_textVideoMem;
  3927. static int64_t next = timeEnd;
  3928. if (timeEnd >= next)
  3929. {
  3930. next = timeEnd + timerFreq;
  3931. double freq = double(timerFreq);
  3932. double toMs = 1000.0/freq;
  3933. tvm.clear();
  3934. uint16_t pos = 0;
  3935. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x8c : 0x8f
  3936. , " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  3937. , getRendererName()
  3938. );
  3939. pos = 10;
  3940. tvm.printf(10, pos++, 0x8b, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  3941. , double(frameTime)*toMs
  3942. , double(min)*toMs
  3943. , double(max)*toMs
  3944. , freq/frameTime
  3945. );
  3946. const uint32_t msaa = (m_resolution.reset&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  3947. tvm.printf(10, pos++, 0x8b, " Reset flags: [%c] vsync, [%c] MSAAx%d, [%c] MaxAnisotropy "
  3948. , !!(m_resolution.reset&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  3949. , 0 != msaa ? '\xfe' : ' '
  3950. , 1<<msaa
  3951. , !!(m_resolution.reset&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  3952. );
  3953. double elapsedCpuMs = double(frameTime)*toMs;
  3954. tvm.printf(10, pos++, 0x8b, " Submitted: %4d (draw %4d, compute %4d) / CPU %3.4f [ms] %c GPU %3.4f [ms] (latency %d)"
  3955. , _render->m_numRenderItems
  3956. , statsKeyType[0]
  3957. , statsKeyType[1]
  3958. , elapsedCpuMs
  3959. , elapsedCpuMs > maxGpuElapsed ? '>' : '<'
  3960. , maxGpuElapsed
  3961. , maxGpuLatency
  3962. );
  3963. maxGpuLatency = 0;
  3964. maxGpuElapsed = 0.0;
  3965. for (uint32_t ii = 0; ii < Topology::Count; ++ii)
  3966. {
  3967. tvm.printf(10, pos++, 0x8b, " %10s: %7d (#inst: %5d), submitted: %7d"
  3968. , getName(Topology::Enum(ii) )
  3969. , statsNumPrimsRendered[ii]
  3970. , statsNumInstances[ii]
  3971. , statsNumPrimsSubmitted[ii]
  3972. );
  3973. }
  3974. tvm.printf(10, pos++, 0x8b, " Indices: %7d ", statsNumIndices);
  3975. // tvm.printf(10, pos++, 0x8b, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax);
  3976. tvm.printf(10, pos++, 0x8b, " DVB size: %7d ", _render->m_vboffset);
  3977. tvm.printf(10, pos++, 0x8b, " DIB size: %7d ", _render->m_iboffset);
  3978. pos++;
  3979. double captureMs = double(captureElapsed)*toMs;
  3980. tvm.printf(10, pos++, 0x8b, " Capture: %3.4f [ms]", captureMs);
  3981. uint8_t attr[2] = { 0x8c, 0x8a };
  3982. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  3983. tvm.printf(10, pos++, attr[attrIndex &1], " Submit wait: %3.4f [ms]", _render->m_waitSubmit*toMs);
  3984. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %3.4f [ms]", _render->m_waitRender*toMs);
  3985. min = frameTime;
  3986. max = frameTime;
  3987. }
  3988. blit(this, _textVideoMemBlitter, tvm);
  3989. rce = m_renderEncoder;
  3990. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3991. {
  3992. rce.PopDebugGroup();
  3993. }
  3994. }
  3995. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  3996. {
  3997. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  3998. {
  3999. rce.PushDebugGroup("debugtext");
  4000. }
  4001. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  4002. rce = m_renderEncoder;
  4003. if (BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION))
  4004. {
  4005. rce.PopDebugGroup();
  4006. }
  4007. }
  4008. endEncoding();
  4009. scratchBuffer.submit();
  4010. m_cmd.kick(true);
  4011. scratchBuffer.release();
  4012. #if !BX_PLATFORM_EMSCRIPTEN
  4013. for (uint32_t ii = 0, num = m_numWindows; ii < num; ++ii)
  4014. {
  4015. FrameBufferWgpu& frameBuffer = ii == 0 ? m_mainFrameBuffer : m_frameBuffers[m_windows[ii].idx];
  4016. if (NULL != frameBuffer.m_swapChain
  4017. && frameBuffer.m_swapChain->m_drawable)
  4018. {
  4019. SwapChainWgpu& swapChain = *frameBuffer.m_swapChain;
  4020. swapChain.m_swapChain.Present();
  4021. }
  4022. }
  4023. #endif
  4024. }
  4025. } /* namespace webgpu */ } // namespace bgfx
  4026. #else
  4027. namespace bgfx { namespace webgpu
  4028. {
  4029. RendererContextI* rendererCreate(const Init& _init)
  4030. {
  4031. BX_UNUSED(_init);
  4032. return NULL;
  4033. }
  4034. void rendererDestroy()
  4035. {
  4036. }
  4037. } /* namespace webgpu */ } // namespace bgfx
  4038. #endif // BGFX_CONFIG_RENDERER_WEBGPU