bgfx.cpp 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898
  1. /*
  2. * Copyright 2011-2022 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include <bx/platform.h>
  6. #include "bgfx_p.h"
  7. #include <bgfx/embedded_shader.h>
  8. #include <bx/file.h>
  9. #include <bx/mutex.h>
  10. #include "topology.h"
  11. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS
  12. # include <objc/message.h>
  13. #elif BX_PLATFORM_WINDOWS
  14. # ifndef WIN32_LEAN_AND_MEAN
  15. # define WIN32_LEAN_AND_MEAN
  16. # endif // WIN32_LEAN_AND_MEAN
  17. # include <windows.h>
  18. #endif // BX_PLATFORM_OSX
  19. BX_ERROR_RESULT(BGFX_ERROR_TEXTURE_VALIDATION, BX_MAKEFOURCC('b', 'g', 0, 1) );
  20. BX_ERROR_RESULT(BGFX_ERROR_FRAME_BUFFER_VALIDATION, BX_MAKEFOURCC('b', 'g', 0, 2) );
  21. BX_ERROR_RESULT(BGFX_ERROR_IDENTIFIER_VALIDATION, BX_MAKEFOURCC('b', 'g', 0, 3) );
  22. namespace bgfx
  23. {
  24. #define BGFX_API_THREAD_MAGIC UINT32_C(0x78666762)
  25. #if BGFX_CONFIG_MULTITHREADED
  26. # define BGFX_CHECK_API_THREAD() \
  27. BX_ASSERT(NULL != s_ctx, "Library is not initialized yet."); \
  28. BX_ASSERT(BGFX_API_THREAD_MAGIC == s_threadIndex, "Must be called from main thread.")
  29. # define BGFX_CHECK_RENDER_THREAD() \
  30. BX_ASSERT( (NULL != s_ctx && s_ctx->m_singleThreaded) \
  31. || ~BGFX_API_THREAD_MAGIC == s_threadIndex \
  32. , "Must be called from render thread." \
  33. )
  34. #else
  35. # define BGFX_CHECK_API_THREAD()
  36. # define BGFX_CHECK_RENDER_THREAD()
  37. #endif // BGFX_CONFIG_MULTITHREADED
  38. #define BGFX_CHECK_CAPS(_caps, _msg) \
  39. BX_ASSERT(0 != (g_caps.supported & (_caps) ) \
  40. , _msg " Use bgfx::getCaps to check " #_caps " backend renderer capabilities." \
  41. );
  42. #if BGFX_CONFIG_USE_TINYSTL
  43. void* TinyStlAllocator::static_allocate(size_t _bytes)
  44. {
  45. return BX_ALLOC(g_allocator, _bytes);
  46. }
  47. void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
  48. {
  49. if (NULL != _ptr)
  50. {
  51. BX_FREE(g_allocator, _ptr);
  52. }
  53. }
  54. #endif // BGFX_CONFIG_USE_TINYSTL
  55. struct CallbackStub : public CallbackI
  56. {
  57. virtual ~CallbackStub()
  58. {
  59. }
  60. virtual void fatal(const char* _filePath, uint16_t _line, Fatal::Enum _code, const char* _str) override
  61. {
  62. bgfx::trace(_filePath, _line, "BGFX FATAL 0x%08x: %s\n", _code, _str);
  63. if (Fatal::DebugCheck == _code)
  64. {
  65. bx::debugBreak();
  66. }
  67. else
  68. {
  69. abort();
  70. }
  71. }
  72. virtual void traceVargs(const char* _filePath, uint16_t _line, const char* _format, va_list _argList) override
  73. {
  74. char temp[2048];
  75. char* out = temp;
  76. va_list argListCopy;
  77. va_copy(argListCopy, _argList);
  78. int32_t len = bx::snprintf(out, sizeof(temp), "%s (%d): ", _filePath, _line);
  79. int32_t total = len + bx::vsnprintf(out + len, sizeof(temp)-len, _format, argListCopy);
  80. va_end(argListCopy);
  81. if ( (int32_t)sizeof(temp) < total)
  82. {
  83. out = (char*)alloca(total+1);
  84. bx::memCopy(out, temp, len);
  85. bx::vsnprintf(out + len, total-len, _format, _argList);
  86. }
  87. out[total] = '\0';
  88. bx::debugOutput(out);
  89. }
  90. virtual void profilerBegin(const char* /*_name*/, uint32_t /*_abgr*/, const char* /*_filePath*/, uint16_t /*_line*/) override
  91. {
  92. }
  93. virtual void profilerBeginLiteral(const char* /*_name*/, uint32_t /*_abgr*/, const char* /*_filePath*/, uint16_t /*_line*/) override
  94. {
  95. }
  96. virtual void profilerEnd() override
  97. {
  98. }
  99. virtual uint32_t cacheReadSize(uint64_t /*_id*/) override
  100. {
  101. return 0;
  102. }
  103. virtual bool cacheRead(uint64_t /*_id*/, void* /*_data*/, uint32_t /*_size*/) override
  104. {
  105. return false;
  106. }
  107. virtual void cacheWrite(uint64_t /*_id*/, const void* /*_data*/, uint32_t /*_size*/) override
  108. {
  109. }
  110. virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t _size, bool _yflip) override
  111. {
  112. BX_UNUSED(_filePath, _width, _height, _pitch, _data, _size, _yflip);
  113. const int32_t len = bx::strLen(_filePath)+5;
  114. char* filePath = (char*)alloca(len);
  115. bx::strCopy(filePath, len, _filePath);
  116. bx::strCat(filePath, len, ".tga");
  117. bx::FileWriter writer;
  118. if (bx::open(&writer, filePath) )
  119. {
  120. bimg::imageWriteTga(&writer, _width, _height, _pitch, _data, false, _yflip);
  121. bx::close(&writer);
  122. }
  123. }
  124. virtual void captureBegin(uint32_t /*_width*/, uint32_t /*_height*/, uint32_t /*_pitch*/, TextureFormat::Enum /*_format*/, bool /*_yflip*/) override
  125. {
  126. BX_TRACE("Warning: using capture without callback (a.k.a. pointless).");
  127. }
  128. virtual void captureEnd() override
  129. {
  130. }
  131. virtual void captureFrame(const void* /*_data*/, uint32_t /*_size*/) override
  132. {
  133. }
  134. };
  135. #ifndef BGFX_CONFIG_MEMORY_TRACKING
  136. # define BGFX_CONFIG_MEMORY_TRACKING (BGFX_CONFIG_DEBUG && BX_CONFIG_SUPPORTS_THREADING)
  137. #endif // BGFX_CONFIG_MEMORY_TRACKING
  138. const size_t kNaturalAlignment = 8;
  139. class AllocatorStub : public bx::AllocatorI
  140. {
  141. public:
  142. AllocatorStub()
  143. #if BGFX_CONFIG_MEMORY_TRACKING
  144. : m_numBlocks(0)
  145. , m_maxBlocks(0)
  146. #endif // BGFX_CONFIG_MEMORY_TRACKING
  147. {
  148. }
  149. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line) override
  150. {
  151. if (0 == _size)
  152. {
  153. if (NULL != _ptr)
  154. {
  155. if (kNaturalAlignment >= _align)
  156. {
  157. #if BGFX_CONFIG_MEMORY_TRACKING
  158. {
  159. bx::MutexScope scope(m_mutex);
  160. BX_ASSERT(m_numBlocks > 0, "Number of blocks is 0. Possible alloc/free mismatch?");
  161. --m_numBlocks;
  162. }
  163. #endif // BGFX_CONFIG_MEMORY_TRACKING
  164. ::free(_ptr);
  165. }
  166. else
  167. {
  168. bx::alignedFree(this, _ptr, _align, _file, _line);
  169. }
  170. }
  171. return NULL;
  172. }
  173. else if (NULL == _ptr)
  174. {
  175. if (kNaturalAlignment >= _align)
  176. {
  177. #if BGFX_CONFIG_MEMORY_TRACKING
  178. {
  179. bx::MutexScope scope(m_mutex);
  180. ++m_numBlocks;
  181. m_maxBlocks = bx::max(m_maxBlocks, m_numBlocks);
  182. }
  183. #endif // BGFX_CONFIG_MEMORY_TRACKING
  184. return ::malloc(_size);
  185. }
  186. return bx::alignedAlloc(this, _size, _align, _file, _line);
  187. }
  188. if (kNaturalAlignment >= _align)
  189. {
  190. #if BGFX_CONFIG_MEMORY_TRACKING
  191. if (NULL == _ptr)
  192. {
  193. bx::MutexScope scope(m_mutex);
  194. ++m_numBlocks;
  195. m_maxBlocks = bx::max(m_maxBlocks, m_numBlocks);
  196. }
  197. #endif // BGFX_CONFIG_MEMORY_TRACKING
  198. return ::realloc(_ptr, _size);
  199. }
  200. return bx::alignedRealloc(this, _ptr, _size, _align, _file, _line);
  201. }
  202. void checkLeaks();
  203. protected:
  204. #if BGFX_CONFIG_MEMORY_TRACKING
  205. bx::Mutex m_mutex;
  206. uint32_t m_numBlocks;
  207. uint32_t m_maxBlocks;
  208. #endif // BGFX_CONFIG_MEMORY_TRACKING
  209. };
  210. static CallbackStub* s_callbackStub = NULL;
  211. static AllocatorStub* s_allocatorStub = NULL;
  212. static bool s_graphicsDebuggerPresent = false;
  213. CallbackI* g_callback = NULL;
  214. bx::AllocatorI* g_allocator = NULL;
  215. Caps g_caps;
  216. #if BGFX_CONFIG_MULTITHREADED && !defined(BX_THREAD_LOCAL)
  217. class ThreadData
  218. {
  219. BX_CLASS(ThreadData
  220. , NO_DEFAULT_CTOR
  221. , NO_COPY
  222. );
  223. public:
  224. ThreadData(uintptr_t _rhs)
  225. {
  226. union { uintptr_t ui; void* ptr; } cast = { _rhs };
  227. m_tls.set(cast.ptr);
  228. }
  229. operator uintptr_t() const
  230. {
  231. union { uintptr_t ui; void* ptr; } cast;
  232. cast.ptr = m_tls.get();
  233. return cast.ui;
  234. }
  235. uintptr_t operator=(uintptr_t _rhs)
  236. {
  237. union { uintptr_t ui; void* ptr; } cast = { _rhs };
  238. m_tls.set(cast.ptr);
  239. return _rhs;
  240. }
  241. bool operator==(uintptr_t _rhs) const
  242. {
  243. uintptr_t lhs = *this;
  244. return lhs == _rhs;
  245. }
  246. private:
  247. bx::TlsData m_tls;
  248. };
  249. static ThreadData s_threadIndex(0);
  250. #elif !BGFX_CONFIG_MULTITHREADED
  251. static uint32_t s_threadIndex(0);
  252. #else
  253. static BX_THREAD_LOCAL uint32_t s_threadIndex(0);
  254. #endif
  255. static Context* s_ctx = NULL;
  256. static bool s_renderFrameCalled = false;
  257. InternalData g_internalData;
  258. PlatformData g_platformData;
  259. bool g_platformDataChangedSinceReset = false;
  260. static Handle::TypeName s_typeName[] =
  261. {
  262. { "DIB", "DynamicIndexBuffer" },
  263. { "DVB", "DynamicVertexBuffer" },
  264. { "FB", "FrameBuffer" },
  265. { "IB", "IndexBuffer" },
  266. { "IndB", "IndirectBuffer" },
  267. { "OQ", "OcclusionQuery" },
  268. { "P", "Program" },
  269. { "S", "Shader" },
  270. { "T", "Texture" },
  271. { "U", "Uniform" },
  272. { "VB", "VertexBuffer" },
  273. { "VL", "VertexLayout" },
  274. { "?", "?" },
  275. };
  276. BX_STATIC_ASSERT(BX_COUNTOF(s_typeName) == Handle::Count+1, "");
  277. const Handle::TypeName& Handle::getTypeName(Handle::Enum _enum)
  278. {
  279. BX_ASSERT(_enum < Handle::Count, "Invalid Handle::Enum %d!", _enum);
  280. return s_typeName[bx::min(_enum, Handle::Count)];
  281. }
  282. void AllocatorStub::checkLeaks()
  283. {
  284. #if BGFX_CONFIG_MEMORY_TRACKING
  285. // BK - CallbackStub will be deleted after printing this info, so there is always one
  286. // leak if CallbackStub is used.
  287. BX_WARN(uint32_t(NULL != s_callbackStub ? 1 : 0) == m_numBlocks
  288. , "\n\n"
  289. "\n########################################################"
  290. "\n"
  291. "\nMEMORY LEAK: Number of leaked blocks %d (Max blocks: %d)"
  292. "\n"
  293. "\n########################################################"
  294. "\n\n"
  295. , m_numBlocks
  296. , m_maxBlocks
  297. );
  298. #endif // BGFX_CONFIG_MEMORY_TRACKING
  299. }
  300. void setPlatformData(const PlatformData& _data)
  301. {
  302. if (NULL != s_ctx)
  303. {
  304. BGFX_FATAL(true
  305. && g_platformData.ndt == _data.ndt
  306. && g_platformData.context == _data.context
  307. , Fatal::UnableToInitialize
  308. , "Only backbuffer pointer and native window handle can be changed after initialization!"
  309. );
  310. }
  311. bx::memCopy(&g_platformData, &_data, sizeof(PlatformData) );
  312. g_platformDataChangedSinceReset = true;
  313. }
  314. const InternalData* getInternalData()
  315. {
  316. return &g_internalData;
  317. }
  318. uintptr_t overrideInternal(TextureHandle _handle, uintptr_t _ptr)
  319. {
  320. BGFX_CHECK_RENDER_THREAD();
  321. RendererContextI* rci = s_ctx->m_renderCtx;
  322. if (0 == rci->getInternal(_handle) )
  323. {
  324. return 0;
  325. }
  326. rci->overrideInternal(_handle, _ptr);
  327. return rci->getInternal(_handle);
  328. }
  329. uintptr_t overrideInternal(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips, TextureFormat::Enum _format, uint64_t _flags)
  330. {
  331. BGFX_CHECK_RENDER_THREAD();
  332. RendererContextI* rci = s_ctx->m_renderCtx;
  333. if (0 == rci->getInternal(_handle) )
  334. {
  335. return 0;
  336. }
  337. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  338. Memory* mem = const_cast<Memory*>(alloc(size) );
  339. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  340. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  341. bx::write(&writer, magic, bx::ErrorAssert{});
  342. TextureCreate tc;
  343. tc.m_width = _width;
  344. tc.m_height = _height;
  345. tc.m_depth = 0;
  346. tc.m_numLayers = 1;
  347. tc.m_numMips = bx::max<uint8_t>(1, _numMips);
  348. tc.m_format = _format;
  349. tc.m_cubeMap = false;
  350. tc.m_mem = NULL;
  351. bx::write(&writer, tc, bx::ErrorAssert{});
  352. rci->destroyTexture(_handle);
  353. rci->createTexture(_handle, mem, _flags, 0);
  354. release(mem);
  355. return rci->getInternal(_handle);
  356. }
  357. void setGraphicsDebuggerPresent(bool _present)
  358. {
  359. BX_TRACE("Graphics debugger is %spresent.", _present ? "" : "not ");
  360. s_graphicsDebuggerPresent = _present;
  361. }
  362. bool isGraphicsDebuggerPresent()
  363. {
  364. return s_graphicsDebuggerPresent;
  365. }
  366. void fatal(const char* _filePath, uint16_t _line, Fatal::Enum _code, const char* _format, ...)
  367. {
  368. va_list argList;
  369. va_start(argList, _format);
  370. char temp[8192];
  371. char* out = temp;
  372. int32_t len = bx::vsnprintf(out, sizeof(temp), _format, argList);
  373. if ( (int32_t)sizeof(temp) < len)
  374. {
  375. out = (char*)alloca(len+1);
  376. len = bx::vsnprintf(out, len, _format, argList);
  377. }
  378. out[len] = '\0';
  379. if (BX_UNLIKELY(NULL == g_callback) )
  380. {
  381. bx::debugPrintf("%s(%d): BGFX FATAL 0x%08x: %s", _filePath, _line, _code, out);
  382. abort();
  383. }
  384. else
  385. {
  386. g_callback->fatal(_filePath, _line, _code, out);
  387. }
  388. va_end(argList);
  389. }
  390. void trace(const char* _filePath, uint16_t _line, const char* _format, ...)
  391. {
  392. va_list argList;
  393. va_start(argList, _format);
  394. if (BX_UNLIKELY(NULL == g_callback) )
  395. {
  396. bx::debugPrintfVargs(_format, argList);
  397. }
  398. else
  399. {
  400. g_callback->traceVargs(_filePath, _line, _format, argList);
  401. }
  402. va_end(argList);
  403. }
  404. #include "vs_debugfont.bin.h"
  405. #include "fs_debugfont.bin.h"
  406. #include "vs_clear.bin.h"
  407. #include "fs_clear0.bin.h"
  408. #include "fs_clear1.bin.h"
  409. #include "fs_clear2.bin.h"
  410. #include "fs_clear3.bin.h"
  411. #include "fs_clear4.bin.h"
  412. #include "fs_clear5.bin.h"
  413. #include "fs_clear6.bin.h"
  414. #include "fs_clear7.bin.h"
  415. static const EmbeddedShader s_embeddedShaders[] =
  416. {
  417. BGFX_EMBEDDED_SHADER(vs_debugfont),
  418. BGFX_EMBEDDED_SHADER(fs_debugfont),
  419. BGFX_EMBEDDED_SHADER(vs_clear),
  420. BGFX_EMBEDDED_SHADER(fs_clear0),
  421. BGFX_EMBEDDED_SHADER(fs_clear1),
  422. BGFX_EMBEDDED_SHADER(fs_clear2),
  423. BGFX_EMBEDDED_SHADER(fs_clear3),
  424. BGFX_EMBEDDED_SHADER(fs_clear4),
  425. BGFX_EMBEDDED_SHADER(fs_clear5),
  426. BGFX_EMBEDDED_SHADER(fs_clear6),
  427. BGFX_EMBEDDED_SHADER(fs_clear7),
  428. BGFX_EMBEDDED_SHADER_END()
  429. };
  430. ShaderHandle createEmbeddedShader(const EmbeddedShader* _es, RendererType::Enum _type, const char* _name)
  431. {
  432. for (const EmbeddedShader* es = _es; NULL != es->name; ++es)
  433. {
  434. if (0 == bx::strCmp(_name, es->name) )
  435. {
  436. for (const EmbeddedShader::Data* esd = es->data; RendererType::Count != esd->type; ++esd)
  437. {
  438. if (_type == esd->type
  439. && 1 < esd->size)
  440. {
  441. ShaderHandle handle = createShader(makeRef(esd->data, esd->size) );
  442. if (isValid(handle) )
  443. {
  444. setName(handle, _name);
  445. }
  446. return handle;
  447. }
  448. }
  449. }
  450. }
  451. ShaderHandle handle = BGFX_INVALID_HANDLE;
  452. return handle;
  453. }
  454. void dump(const VertexLayout& _layout)
  455. {
  456. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  457. {
  458. BX_TRACE("VertexLayout %08x (%08x), stride %d"
  459. , _layout.m_hash
  460. , bx::hash<bx::HashMurmur2A>(_layout.m_attributes)
  461. , _layout.m_stride
  462. );
  463. for (uint32_t attr = 0; attr < Attrib::Count; ++attr)
  464. {
  465. if (UINT16_MAX != _layout.m_attributes[attr])
  466. {
  467. uint8_t num;
  468. AttribType::Enum type;
  469. bool normalized;
  470. bool asInt;
  471. _layout.decode(Attrib::Enum(attr), num, type, normalized, asInt);
  472. BX_TRACE("\tattr %2d: %-20s num %d, type %d, norm [%c], asint [%c], offset %2d"
  473. , attr
  474. , getAttribName(Attrib::Enum(attr) )
  475. , num
  476. , type
  477. , normalized ? 'x' : ' '
  478. , asInt ? 'x' : ' '
  479. , _layout.m_offset[attr]
  480. );
  481. }
  482. }
  483. }
  484. }
  485. #include "charset.h"
  486. void charsetFillTexture(const uint8_t* _charset, uint8_t* _rgba, uint32_t _height, uint32_t _pitch, uint32_t _bpp)
  487. {
  488. for (uint32_t ii = 0; ii < 256; ++ii)
  489. {
  490. uint8_t* pix = &_rgba[ii*8*_bpp];
  491. for (uint32_t yy = 0; yy < _height; ++yy)
  492. {
  493. for (uint32_t xx = 0; xx < 8; ++xx)
  494. {
  495. uint8_t bit = 1<<(7-xx);
  496. bx::memSet(&pix[xx*_bpp], _charset[ii*_height+yy]&bit ? 255 : 0, _bpp);
  497. }
  498. pix += _pitch;
  499. }
  500. }
  501. }
  502. static uint8_t parseAttrTo(char*& _ptr, char _to, uint8_t _default)
  503. {
  504. const bx::StringView str = bx::strFind(_ptr, _to);
  505. if (!str.isEmpty()
  506. && 3 > str.getPtr()-_ptr)
  507. {
  508. char tmp[4];
  509. int32_t len = int32_t(str.getPtr()-_ptr);
  510. bx::strCopy(tmp, sizeof(tmp), _ptr, len);
  511. uint32_t attr;
  512. bx::fromString(&attr, tmp);
  513. _ptr += len+1;
  514. return uint8_t(attr);
  515. }
  516. return _default;
  517. }
  518. static uint8_t parseAttr(char*& _ptr, uint8_t _default)
  519. {
  520. char* ptr = _ptr;
  521. if (*ptr++ != '[')
  522. {
  523. return _default;
  524. }
  525. if (0 == bx::strCmp(ptr, "0m", 2) )
  526. {
  527. _ptr = ptr + 2;
  528. return _default;
  529. }
  530. uint8_t fg = parseAttrTo(ptr, ';', _default & 0xf);
  531. uint8_t bg = parseAttrTo(ptr, 'm', _default >> 4);
  532. uint8_t attr = (bg<<4) | fg;
  533. _ptr = ptr;
  534. return attr;
  535. }
  536. void TextVideoMem::printfVargs(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, va_list _argList)
  537. {
  538. if (_x < m_width && _y < m_height)
  539. {
  540. va_list argListCopy;
  541. va_copy(argListCopy, _argList);
  542. uint32_t num = bx::vsnprintf(NULL, 0, _format, argListCopy) + 1;
  543. char* temp = (char*)alloca(num);
  544. va_copy(argListCopy, _argList);
  545. num = bx::vsnprintf(temp, num, _format, argListCopy);
  546. uint8_t attr = _attr;
  547. MemSlot* mem = &m_mem[_y*m_width+_x];
  548. for (uint32_t ii = 0, xx = _x; ii < num && xx < m_width; ++ii)
  549. {
  550. char ch = temp[ii];
  551. if (BX_UNLIKELY(ch == '\x1b') )
  552. {
  553. char* ptr = &temp[ii+1];
  554. attr = parseAttr(ptr, _attr);
  555. ii += uint32_t(ptr - &temp[ii+1]);
  556. }
  557. else
  558. {
  559. mem->character = ch;
  560. mem->attribute = attr;
  561. ++mem;
  562. ++xx;
  563. }
  564. }
  565. }
  566. }
  567. static const uint32_t numCharsPerBatch = 1024;
  568. static const uint32_t numBatchVertices = numCharsPerBatch*4;
  569. static const uint32_t numBatchIndices = numCharsPerBatch*6;
  570. void TextVideoMemBlitter::init()
  571. {
  572. BGFX_CHECK_API_THREAD();
  573. m_layout
  574. .begin()
  575. .add(Attrib::Position, 3, AttribType::Float)
  576. .add(Attrib::Color0, 4, AttribType::Uint8, true)
  577. .add(Attrib::Color1, 4, AttribType::Uint8, true)
  578. .add(Attrib::TexCoord0, 2, AttribType::Float)
  579. .end();
  580. uint16_t width = 2048;
  581. uint16_t height = 24;
  582. uint8_t bpp = 1;
  583. uint32_t pitch = width*bpp;
  584. const Memory* mem;
  585. mem = alloc(pitch*height);
  586. uint8_t* rgba = mem->data;
  587. charsetFillTexture(vga8x8, rgba, 8, pitch, bpp);
  588. charsetFillTexture(vga8x16, &rgba[8*pitch], 16, pitch, bpp);
  589. m_texture = createTexture2D(width, height, false, 1, TextureFormat::R8
  590. , BGFX_SAMPLER_MIN_POINT
  591. | BGFX_SAMPLER_MAG_POINT
  592. | BGFX_SAMPLER_MIP_POINT
  593. | BGFX_SAMPLER_U_CLAMP
  594. | BGFX_SAMPLER_V_CLAMP
  595. , mem
  596. );
  597. ShaderHandle vsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, "vs_debugfont");
  598. ShaderHandle fsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, "fs_debugfont");
  599. BX_ASSERT(isValid(vsh) && isValid(fsh), "Failed to create embedded blit shaders");
  600. m_program = createProgram(vsh, fsh, true);
  601. m_vb = s_ctx->createTransientVertexBuffer(numBatchVertices*m_layout.m_stride, &m_layout);
  602. m_ib = s_ctx->createTransientIndexBuffer(numBatchIndices*2);
  603. }
  604. void TextVideoMemBlitter::shutdown()
  605. {
  606. BGFX_CHECK_API_THREAD();
  607. if (isValid(m_program) )
  608. {
  609. destroy(m_program);
  610. }
  611. destroy(m_texture);
  612. s_ctx->destroyTransientVertexBuffer(m_vb);
  613. s_ctx->destroyTransientIndexBuffer(m_ib);
  614. }
  615. static const uint32_t s_paletteSrgb[] =
  616. {
  617. 0x0, // Black
  618. 0xffa46534, // Blue
  619. 0xff069a4e, // Green
  620. 0xff9a9806, // Cyan
  621. 0xff0000cc, // Red
  622. 0xff7b5075, // Magenta
  623. 0xff00a0c4, // Brown
  624. 0xffcfd7d3, // Light Gray
  625. 0xff535755, // Dark Gray
  626. 0xffcf9f72, // Light Blue
  627. 0xff34e28a, // Light Green
  628. 0xffe2e234, // Light Cyan
  629. 0xff2929ef, // Light Red
  630. 0xffa87fad, // Light Magenta
  631. 0xff4fe9fc, // Yellow
  632. 0xffeceeee, // White
  633. };
  634. BX_STATIC_ASSERT(BX_COUNTOF(s_paletteSrgb) == 16);
  635. static const uint32_t s_paletteLinear[] =
  636. {
  637. 0x0, // Black
  638. 0xff5e2108, // Blue
  639. 0xff005213, // Green
  640. 0xff525000, // Cyan
  641. 0xff000099, // Red
  642. 0xff32142d, // Magenta
  643. 0xff00598c, // Brown
  644. 0xff9fada6, // Light Gray
  645. 0xff161817, // Dark Gray
  646. 0xff9f582a, // Light Blue
  647. 0xff08c140, // Light Green
  648. 0xffc1c108, // Light Cyan
  649. 0xff0505dc, // Light Red
  650. 0xff63366a, // Light Magenta
  651. 0xff13cff8, // Yellow
  652. 0xffd5dada // White
  653. };
  654. BX_STATIC_ASSERT(BX_COUNTOF(s_paletteLinear) == 16);
  655. void blit(RendererContextI* _renderCtx, TextVideoMemBlitter& _blitter, const TextVideoMem& _mem)
  656. {
  657. struct Vertex
  658. {
  659. float m_x;
  660. float m_y;
  661. float m_z;
  662. uint32_t m_fg;
  663. uint32_t m_bg;
  664. float m_u;
  665. float m_v;
  666. };
  667. uint32_t yy = 0;
  668. uint32_t xx = 0;
  669. const float texelWidth = 1.0f/2048.0f;
  670. const float texelWidthHalf = RendererType::Direct3D9 == g_caps.rendererType ? 0.0f : texelWidth*0.5f;
  671. const float texelHeight = 1.0f/24.0f;
  672. const float texelHeightHalf = RendererType::Direct3D9 == g_caps.rendererType ? texelHeight*0.5f : 0.0f;
  673. const float utop = (_mem.m_small ? 0.0f : 8.0f)*texelHeight + texelHeightHalf;
  674. const float ubottom = (_mem.m_small ? 8.0f : 24.0f)*texelHeight + texelHeightHalf;
  675. const float fontHeight = (_mem.m_small ? 8.0f : 16.0f);
  676. _renderCtx->blitSetup(_blitter);
  677. const uint32_t* palette = 0 != (s_ctx->m_init.resolution.reset & BGFX_RESET_SRGB_BACKBUFFER)
  678. ? s_paletteLinear
  679. : s_paletteSrgb
  680. ;
  681. for (;yy < _mem.m_height;)
  682. {
  683. Vertex* vertex = (Vertex*)_blitter.m_vb->data;
  684. uint16_t* indices = (uint16_t*)_blitter.m_ib->data;
  685. uint32_t startVertex = 0;
  686. uint32_t numIndices = 0;
  687. for (; yy < _mem.m_height && numIndices < numBatchIndices; ++yy)
  688. {
  689. xx = xx < _mem.m_width ? xx : 0;
  690. const TextVideoMem::MemSlot* line = &_mem.m_mem[yy*_mem.m_width+xx];
  691. for (; xx < _mem.m_width && numIndices < numBatchIndices; ++xx)
  692. {
  693. uint32_t ch = line->character;
  694. const uint8_t attr = line->attribute;
  695. if (ch > 0xff)
  696. {
  697. ch = 0;
  698. }
  699. if (0 != (ch|attr)
  700. && (' ' != ch || 0 != (attr&0xf0) ) )
  701. {
  702. const uint32_t fg = palette[attr&0xf];
  703. const uint32_t bg = palette[(attr>>4)&0xf];
  704. Vertex vert[4] =
  705. {
  706. { (xx )*8.0f, (yy )*fontHeight, 0.0f, fg, bg, (ch )*8.0f*texelWidth - texelWidthHalf, utop },
  707. { (xx+1)*8.0f, (yy )*fontHeight, 0.0f, fg, bg, (ch+1)*8.0f*texelWidth - texelWidthHalf, utop },
  708. { (xx+1)*8.0f, (yy+1)*fontHeight, 0.0f, fg, bg, (ch+1)*8.0f*texelWidth - texelWidthHalf, ubottom },
  709. { (xx )*8.0f, (yy+1)*fontHeight, 0.0f, fg, bg, (ch )*8.0f*texelWidth - texelWidthHalf, ubottom },
  710. };
  711. bx::memCopy(vertex, vert, sizeof(vert) );
  712. vertex += 4;
  713. indices[0] = uint16_t(startVertex+0);
  714. indices[1] = uint16_t(startVertex+1);
  715. indices[2] = uint16_t(startVertex+2);
  716. indices[3] = uint16_t(startVertex+2);
  717. indices[4] = uint16_t(startVertex+3);
  718. indices[5] = uint16_t(startVertex+0);
  719. startVertex += 4;
  720. indices += 6;
  721. numIndices += 6;
  722. }
  723. line++;
  724. }
  725. if (numIndices >= numBatchIndices)
  726. {
  727. break;
  728. }
  729. }
  730. _renderCtx->blitRender(_blitter, numIndices);
  731. }
  732. }
  733. void ClearQuad::init()
  734. {
  735. BGFX_CHECK_API_THREAD();
  736. if (RendererType::Noop != g_caps.rendererType)
  737. {
  738. m_layout
  739. .begin()
  740. .add(Attrib::Position, 2, AttribType::Float)
  741. .end();
  742. ShaderHandle vsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, "vs_clear");
  743. BX_ASSERT(isValid(vsh), "Failed to create clear quad embedded vertex shader \"vs_clear\"");
  744. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  745. {
  746. char name[32];
  747. bx::snprintf(name, BX_COUNTOF(name), "fs_clear%d", ii);
  748. ShaderHandle fsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, name);
  749. BX_ASSERT(isValid(fsh), "Failed to create clear quad embedded fragment shader \"%s\"", name);
  750. m_program[ii] = createProgram(vsh, fsh);
  751. BX_ASSERT(isValid(m_program[ii]), "Failed to create clear quad program.");
  752. destroy(fsh);
  753. }
  754. destroy(vsh);
  755. struct Vertex
  756. {
  757. float m_x;
  758. float m_y;
  759. };
  760. const uint16_t stride = m_layout.m_stride;
  761. const bgfx::Memory* mem = bgfx::alloc(4 * stride);
  762. Vertex* vertex = (Vertex*)mem->data;
  763. BX_ASSERT(stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", stride, sizeof(Vertex));
  764. vertex->m_x = -1.0f;
  765. vertex->m_y = -1.0f;
  766. vertex++;
  767. vertex->m_x = 1.0f;
  768. vertex->m_y = -1.0f;
  769. vertex++;
  770. vertex->m_x = -1.0f;
  771. vertex->m_y = 1.0f;
  772. vertex++;
  773. vertex->m_x = 1.0f;
  774. vertex->m_y = 1.0f;
  775. m_vb = s_ctx->createVertexBuffer(mem, m_layout, 0);
  776. }
  777. }
  778. void ClearQuad::shutdown()
  779. {
  780. BGFX_CHECK_API_THREAD();
  781. if (RendererType::Noop != g_caps.rendererType)
  782. {
  783. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  784. {
  785. if (isValid(m_program[ii]) )
  786. {
  787. destroy(m_program[ii]);
  788. m_program[ii].idx = kInvalidHandle;
  789. }
  790. }
  791. s_ctx->destroyVertexBuffer(m_vb);
  792. }
  793. }
  794. const char* s_uniformTypeName[] =
  795. {
  796. "sampler1",
  797. NULL,
  798. "vec4",
  799. "mat3",
  800. "mat4",
  801. };
  802. BX_STATIC_ASSERT(UniformType::Count == BX_COUNTOF(s_uniformTypeName) );
  803. const char* getUniformTypeName(UniformType::Enum _enum)
  804. {
  805. BX_ASSERT(_enum < UniformType::Count, "%d < UniformType::Count %d", _enum, UniformType::Count);
  806. return s_uniformTypeName[_enum];
  807. }
  808. UniformType::Enum nameToUniformTypeEnum(const char* _name)
  809. {
  810. for (uint32_t ii = 0; ii < UniformType::Count; ++ii)
  811. {
  812. if (NULL != s_uniformTypeName[ii]
  813. && 0 == bx::strCmp(_name, s_uniformTypeName[ii]) )
  814. {
  815. return UniformType::Enum(ii);
  816. }
  817. }
  818. return UniformType::Count;
  819. }
  820. static const char* s_predefinedName[PredefinedUniform::Count] =
  821. {
  822. "u_viewRect",
  823. "u_viewTexel",
  824. "u_view",
  825. "u_invView",
  826. "u_proj",
  827. "u_invProj",
  828. "u_viewProj",
  829. "u_invViewProj",
  830. "u_model",
  831. "u_modelView",
  832. "u_modelViewProj",
  833. "u_alphaRef4",
  834. };
  835. const char* getPredefinedUniformName(PredefinedUniform::Enum _enum)
  836. {
  837. return s_predefinedName[_enum];
  838. }
  839. PredefinedUniform::Enum nameToPredefinedUniformEnum(const bx::StringView& _name)
  840. {
  841. for (uint32_t ii = 0; ii < PredefinedUniform::Count; ++ii)
  842. {
  843. if (0 == bx::strCmp(_name, s_predefinedName[ii]) )
  844. {
  845. return PredefinedUniform::Enum(ii);
  846. }
  847. }
  848. return PredefinedUniform::Count;
  849. }
  850. void srtToMatrix4_x1(void* _dst, const void* _src)
  851. {
  852. Matrix4* mtx = reinterpret_cast< Matrix4*>(_dst);
  853. const Srt* srt = reinterpret_cast<const Srt*>(_src);
  854. const float rx = srt->rotate[0];
  855. const float ry = srt->rotate[1];
  856. const float rz = srt->rotate[2];
  857. const float rw = srt->rotate[3];
  858. const float xx2 = 2.0f * rx * rx;
  859. const float yy2 = 2.0f * ry * ry;
  860. const float zz2 = 2.0f * rz * rz;
  861. const float yx2 = 2.0f * ry * rx;
  862. const float yz2 = 2.0f * ry * rz;
  863. const float yw2 = 2.0f * ry * rw;
  864. const float wz2 = 2.0f * rw * rz;
  865. const float wx2 = 2.0f * rw * rx;
  866. const float xz2 = 2.0f * rx * rz;
  867. const float sx = srt->scale[0];
  868. const float sy = srt->scale[1];
  869. const float sz = srt->scale[2];
  870. mtx->un.val[ 0] = (1.0f - yy2 - zz2)*sx;
  871. mtx->un.val[ 1] = ( yx2 + wz2)*sx;
  872. mtx->un.val[ 2] = ( xz2 - yw2)*sx;
  873. mtx->un.val[ 3] = 0.0f;
  874. mtx->un.val[ 4] = ( yx2 - wz2)*sy;
  875. mtx->un.val[ 5] = (1.0f - xx2 - zz2)*sy;
  876. mtx->un.val[ 6] = ( yz2 + wx2)*sy;
  877. mtx->un.val[ 7] = 0.0f;
  878. mtx->un.val[ 8] = ( xz2 + yw2)*sz;
  879. mtx->un.val[ 9] = ( yz2 - wx2)*sz;
  880. mtx->un.val[10] = (1.0f - xx2 - yy2)*sz;
  881. mtx->un.val[11] = 0.0f;
  882. const float tx = srt->translate[0];
  883. const float ty = srt->translate[1];
  884. const float tz = srt->translate[2];
  885. mtx->un.val[12] = tx;
  886. mtx->un.val[13] = ty;
  887. mtx->un.val[14] = tz;
  888. mtx->un.val[15] = 1.0f;
  889. }
  890. void transpose(void* _dst, uint32_t _dstStride, const void* _src, uint32_t _srcStride = sizeof(bx::simd128_t) )
  891. {
  892. uint8_t* dst = reinterpret_cast< uint8_t *>(_dst);
  893. const uint8_t* src = reinterpret_cast<const uint8_t *>(_src);
  894. using namespace bx;
  895. const simd128_t r0 = simd_ld<simd128_t>(src);
  896. src += _srcStride;
  897. const simd128_t r1 = simd_ld<simd128_t>(src);
  898. src += _srcStride;
  899. const simd128_t r2 = simd_ld<simd128_t>(src);
  900. src += _srcStride;
  901. const simd128_t r3 = simd_ld<simd128_t>(src);
  902. const simd128_t aibj = simd_shuf_xAyB(r0, r2); // aibj
  903. const simd128_t emfn = simd_shuf_xAyB(r1, r3); // emfn
  904. const simd128_t ckdl = simd_shuf_zCwD(r0, r2); // ckdl
  905. const simd128_t gohp = simd_shuf_zCwD(r1, r3); // gohp
  906. const simd128_t aeim = simd_shuf_xAyB(aibj, emfn); // aeim
  907. const simd128_t bfjn = simd_shuf_zCwD(aibj, emfn); // bfjn
  908. const simd128_t cgko = simd_shuf_xAyB(ckdl, gohp); // cgko
  909. const simd128_t dhlp = simd_shuf_zCwD(ckdl, gohp); // dhlp
  910. simd_st(dst, aeim);
  911. dst += _dstStride;
  912. simd_st(dst, bfjn);
  913. dst += _dstStride;
  914. simd_st(dst, cgko);
  915. dst += _dstStride;
  916. simd_st(dst, dhlp);
  917. }
  918. void srtToMatrix4_x4_Ref(void* _dst, const void* _src)
  919. {
  920. uint8_t* dst = reinterpret_cast< uint8_t*>(_dst);
  921. const uint8_t* src = reinterpret_cast<const uint8_t*>(_src);
  922. srtToMatrix4_x1(dst + 0*sizeof(Matrix4), src + 0*sizeof(Srt) );
  923. srtToMatrix4_x1(dst + 1*sizeof(Matrix4), src + 1*sizeof(Srt) );
  924. srtToMatrix4_x1(dst + 2*sizeof(Matrix4), src + 2*sizeof(Srt) );
  925. srtToMatrix4_x1(dst + 3*sizeof(Matrix4), src + 3*sizeof(Srt) );
  926. }
  927. void srtToMatrix4_x4_Simd(void* _dst, const void* _src)
  928. {
  929. using namespace bx;
  930. simd128_t* dst = reinterpret_cast< simd128_t*>(_dst);
  931. const simd128_t* src = reinterpret_cast<const simd128_t*>(_src);
  932. simd128_t rotate[4];
  933. simd128_t translate[4];
  934. simd128_t scale[4];
  935. transpose(rotate, sizeof(simd128_t), src + 0, sizeof(Srt) );
  936. transpose(translate, sizeof(simd128_t), src + 1, sizeof(Srt) );
  937. transpose(scale, sizeof(simd128_t), src + 2, sizeof(Srt) );
  938. const simd128_t rx = simd_ld<simd128_t>(rotate + 0);
  939. const simd128_t ry = simd_ld<simd128_t>(rotate + 1);
  940. const simd128_t rz = simd_ld<simd128_t>(rotate + 2);
  941. const simd128_t rw = simd_ld<simd128_t>(rotate + 3);
  942. const simd128_t tx = simd_ld<simd128_t>(translate + 0);
  943. const simd128_t ty = simd_ld<simd128_t>(translate + 1);
  944. const simd128_t tz = simd_ld<simd128_t>(translate + 2);
  945. const simd128_t sx = simd_ld<simd128_t>(scale + 0);
  946. const simd128_t sy = simd_ld<simd128_t>(scale + 1);
  947. const simd128_t sz = simd_ld<simd128_t>(scale + 2);
  948. const simd128_t zero = simd_splat(0.0f);
  949. const simd128_t one = simd_splat(1.0f);
  950. const simd128_t two = simd_splat(2.0f);
  951. const simd128_t xx = simd_mul(rx, rx);
  952. const simd128_t xx2 = simd_mul(two, xx);
  953. const simd128_t yy = simd_mul(ry, ry);
  954. const simd128_t yy2 = simd_mul(two, yy);
  955. const simd128_t zz = simd_mul(rz, rz);
  956. const simd128_t zz2 = simd_mul(two, zz);
  957. const simd128_t yx = simd_mul(ry, rx);
  958. const simd128_t yx2 = simd_mul(two, yx);
  959. const simd128_t yz = simd_mul(ry, rz);
  960. const simd128_t yz2 = simd_mul(two, yz);
  961. const simd128_t yw = simd_mul(ry, rw);
  962. const simd128_t yw2 = simd_mul(two, yw);
  963. const simd128_t wz = simd_mul(rw, rz);
  964. const simd128_t wz2 = simd_mul(two, wz);
  965. const simd128_t wx = simd_mul(rw, rx);
  966. const simd128_t wx2 = simd_mul(two, wx);
  967. const simd128_t xz = simd_mul(rx, rz);
  968. const simd128_t xz2 = simd_mul(two, xz);
  969. const simd128_t t0x = simd_sub(one, yy2);
  970. const simd128_t r0x = simd_sub(t0x, zz2);
  971. const simd128_t r0y = simd_add(yx2, wz2);
  972. const simd128_t r0z = simd_sub(xz2, yw2);
  973. const simd128_t r1x = simd_sub(yx2, wz2);
  974. const simd128_t omxx2 = simd_sub(one, xx2);
  975. const simd128_t r1y = simd_sub(omxx2, zz2);
  976. const simd128_t r1z = simd_add(yz2, wx2);
  977. const simd128_t r2x = simd_add(xz2, yw2);
  978. const simd128_t r2y = simd_sub(yz2, wx2);
  979. const simd128_t r2z = simd_sub(omxx2, yy2);
  980. simd128_t tmp[4];
  981. tmp[0] = simd_mul(r0x, sx);
  982. tmp[1] = simd_mul(r0y, sx);
  983. tmp[2] = simd_mul(r0z, sx);
  984. tmp[3] = zero;
  985. transpose(dst + 0, sizeof(Matrix4), tmp);
  986. tmp[0] = simd_mul(r1x, sy);
  987. tmp[1] = simd_mul(r1y, sy);
  988. tmp[2] = simd_mul(r1z, sy);
  989. tmp[3] = zero;
  990. transpose(dst + 1, sizeof(Matrix4), tmp);
  991. tmp[0] = simd_mul(r2x, sz);
  992. tmp[1] = simd_mul(r2y, sz);
  993. tmp[2] = simd_mul(r2z, sz);
  994. tmp[3] = zero;
  995. transpose(dst + 2, sizeof(Matrix4), tmp);
  996. tmp[0] = tx;
  997. tmp[1] = ty;
  998. tmp[2] = tz;
  999. tmp[3] = one;
  1000. transpose(dst + 3, sizeof(Matrix4), tmp);
  1001. }
  1002. void srtToMatrix4(void* _dst, const void* _src, uint32_t _num)
  1003. {
  1004. uint8_t* dst = reinterpret_cast< uint8_t*>(_dst);
  1005. const uint8_t* src = reinterpret_cast<const uint8_t*>(_src);
  1006. if (!bx::isAligned(src, 16) )
  1007. {
  1008. for (uint32_t ii = 0, num = _num / 4; ii < num; ++ii)
  1009. {
  1010. srtToMatrix4_x4_Ref(dst, src);
  1011. src += 4*sizeof(Srt);
  1012. dst += 4*sizeof(Matrix4);
  1013. }
  1014. }
  1015. else
  1016. {
  1017. for (uint32_t ii = 0, num = _num / 4; ii < num; ++ii)
  1018. {
  1019. srtToMatrix4_x4_Simd(dst, src);
  1020. src += 4*sizeof(Srt);
  1021. dst += 4*sizeof(Matrix4);
  1022. }
  1023. }
  1024. for (uint32_t ii = 0, num = _num & 3; ii < num; ++ii)
  1025. {
  1026. srtToMatrix4_x1(dst, src);
  1027. src += sizeof(Srt);
  1028. dst += sizeof(Matrix4);
  1029. }
  1030. }
  1031. void EncoderImpl::submit(ViewId _id, ProgramHandle _program, OcclusionQueryHandle _occlusionQuery, uint32_t _depth, uint8_t _flags)
  1032. {
  1033. if (BX_ENABLED(BGFX_CONFIG_DEBUG_UNIFORM)
  1034. && (_flags & BGFX_DISCARD_STATE))
  1035. {
  1036. m_uniformSet.clear();
  1037. }
  1038. if (BX_ENABLED(BGFX_CONFIG_DEBUG_OCCLUSION)
  1039. && isValid(_occlusionQuery) )
  1040. {
  1041. BX_ASSERT(m_occlusionQuerySet.end() == m_occlusionQuerySet.find(_occlusionQuery.idx)
  1042. , "OcclusionQuery %d was already used for this frame."
  1043. , _occlusionQuery.idx
  1044. );
  1045. m_occlusionQuerySet.insert(_occlusionQuery.idx);
  1046. }
  1047. if (m_discard)
  1048. {
  1049. discard(_flags);
  1050. return;
  1051. }
  1052. if (0 == m_draw.m_numVertices
  1053. && 0 == m_draw.m_numIndices)
  1054. {
  1055. discard(_flags);
  1056. ++m_numDropped;
  1057. return;
  1058. }
  1059. const uint32_t renderItemIdx = bx::atomicFetchAndAddsat<uint32_t>(&m_frame->m_numRenderItems, 1, BGFX_CONFIG_MAX_DRAW_CALLS);
  1060. if (BGFX_CONFIG_MAX_DRAW_CALLS <= renderItemIdx)
  1061. {
  1062. discard(_flags);
  1063. ++m_numDropped;
  1064. return;
  1065. }
  1066. ++m_numSubmitted;
  1067. UniformBuffer* uniformBuffer = m_frame->m_uniformBuffer[m_uniformIdx];
  1068. m_uniformEnd = uniformBuffer->getPos();
  1069. m_key.m_program = isValid(_program)
  1070. ? _program
  1071. : ProgramHandle{0}
  1072. ;
  1073. m_key.m_view = _id;
  1074. SortKey::Enum type;
  1075. switch (s_ctx->m_view[_id].m_mode)
  1076. {
  1077. case ViewMode::Sequential: m_key.m_seq = s_ctx->getSeqIncr(_id); type = SortKey::SortSequence; break;
  1078. case ViewMode::DepthAscending: m_key.m_depth = _depth; type = SortKey::SortDepth; break;
  1079. case ViewMode::DepthDescending: m_key.m_depth = UINT32_MAX-_depth; type = SortKey::SortDepth; break;
  1080. default: m_key.m_depth = _depth; type = SortKey::SortProgram; break;
  1081. }
  1082. uint64_t key = m_key.encodeDraw(type);
  1083. m_frame->m_sortKeys[renderItemIdx] = key;
  1084. m_frame->m_sortValues[renderItemIdx] = RenderItemCount(renderItemIdx);
  1085. m_draw.m_uniformIdx = m_uniformIdx;
  1086. m_draw.m_uniformBegin = m_uniformBegin;
  1087. m_draw.m_uniformEnd = m_uniformEnd;
  1088. if (UINT8_MAX != m_draw.m_streamMask)
  1089. {
  1090. uint32_t numVertices = UINT32_MAX;
  1091. for (uint32_t idx = 0, streamMask = m_draw.m_streamMask
  1092. ; 0 != streamMask
  1093. ; streamMask >>= 1, idx += 1
  1094. )
  1095. {
  1096. const uint32_t ntz = bx::uint32_cnttz(streamMask);
  1097. streamMask >>= ntz;
  1098. idx += ntz;
  1099. numVertices = bx::min(numVertices, m_numVertices[idx]);
  1100. }
  1101. m_draw.m_numVertices = numVertices;
  1102. }
  1103. else
  1104. {
  1105. m_draw.m_numVertices = m_numVertices[0];
  1106. }
  1107. if (isValid(_occlusionQuery) )
  1108. {
  1109. m_draw.m_stateFlags |= BGFX_STATE_INTERNAL_OCCLUSION_QUERY;
  1110. m_draw.m_occlusionQuery = _occlusionQuery;
  1111. }
  1112. m_frame->m_renderItem[renderItemIdx].draw = m_draw;
  1113. m_frame->m_renderItemBind[renderItemIdx] = m_bind;
  1114. m_draw.clear(_flags);
  1115. m_bind.clear(_flags);
  1116. if (_flags & BGFX_DISCARD_STATE)
  1117. {
  1118. m_uniformBegin = m_uniformEnd;
  1119. }
  1120. }
  1121. void EncoderImpl::dispatch(ViewId _id, ProgramHandle _handle, uint32_t _numX, uint32_t _numY, uint32_t _numZ, uint8_t _flags)
  1122. {
  1123. if (BX_ENABLED(BGFX_CONFIG_DEBUG_UNIFORM) )
  1124. {
  1125. m_uniformSet.clear();
  1126. }
  1127. if (m_discard)
  1128. {
  1129. discard(_flags);
  1130. return;
  1131. }
  1132. const uint32_t renderItemIdx = bx::atomicFetchAndAddsat<uint32_t>(&m_frame->m_numRenderItems, 1, BGFX_CONFIG_MAX_DRAW_CALLS);
  1133. if (BGFX_CONFIG_MAX_DRAW_CALLS-1 <= renderItemIdx)
  1134. {
  1135. discard(_flags);
  1136. ++m_numDropped;
  1137. return;
  1138. }
  1139. ++m_numSubmitted;
  1140. UniformBuffer* uniformBuffer = m_frame->m_uniformBuffer[m_uniformIdx];
  1141. m_uniformEnd = uniformBuffer->getPos();
  1142. m_compute.m_startMatrix = m_draw.m_startMatrix;
  1143. m_compute.m_numMatrices = m_draw.m_numMatrices;
  1144. m_compute.m_numX = bx::max(_numX, 1u);
  1145. m_compute.m_numY = bx::max(_numY, 1u);
  1146. m_compute.m_numZ = bx::max(_numZ, 1u);
  1147. m_key.m_program = _handle;
  1148. m_key.m_depth = 0;
  1149. m_key.m_view = _id;
  1150. m_key.m_seq = s_ctx->getSeqIncr(_id);
  1151. uint64_t key = m_key.encodeCompute();
  1152. m_frame->m_sortKeys[renderItemIdx] = key;
  1153. m_frame->m_sortValues[renderItemIdx] = RenderItemCount(renderItemIdx);
  1154. m_compute.m_uniformIdx = m_uniformIdx;
  1155. m_compute.m_uniformBegin = m_uniformBegin;
  1156. m_compute.m_uniformEnd = m_uniformEnd;
  1157. m_frame->m_renderItem[renderItemIdx].compute = m_compute;
  1158. m_frame->m_renderItemBind[renderItemIdx] = m_bind;
  1159. m_compute.clear(_flags);
  1160. m_bind.clear(_flags);
  1161. m_uniformBegin = m_uniformEnd;
  1162. }
  1163. void EncoderImpl::blit(ViewId _id, TextureHandle _dst, uint8_t _dstMip, uint16_t _dstX, uint16_t _dstY, uint16_t _dstZ, TextureHandle _src, uint8_t _srcMip, uint16_t _srcX, uint16_t _srcY, uint16_t _srcZ, uint16_t _width, uint16_t _height, uint16_t _depth)
  1164. {
  1165. BX_WARN(m_frame->m_numBlitItems < BGFX_CONFIG_MAX_BLIT_ITEMS
  1166. , "Exceed number of available blit items per frame. BGFX_CONFIG_MAX_BLIT_ITEMS is %d. Skipping blit."
  1167. , BGFX_CONFIG_MAX_BLIT_ITEMS
  1168. );
  1169. if (m_frame->m_numBlitItems < BGFX_CONFIG_MAX_BLIT_ITEMS)
  1170. {
  1171. uint16_t item = m_frame->m_numBlitItems++;
  1172. BlitItem& bi = m_frame->m_blitItem[item];
  1173. bi.m_srcX = _srcX;
  1174. bi.m_srcY = _srcY;
  1175. bi.m_srcZ = _srcZ;
  1176. bi.m_dstX = _dstX;
  1177. bi.m_dstY = _dstY;
  1178. bi.m_dstZ = _dstZ;
  1179. bi.m_width = _width;
  1180. bi.m_height = _height;
  1181. bi.m_depth = _depth;
  1182. bi.m_srcMip = _srcMip;
  1183. bi.m_dstMip = _dstMip;
  1184. bi.m_src = _src;
  1185. bi.m_dst = _dst;
  1186. BlitKey key;
  1187. key.m_view = _id;
  1188. key.m_item = item;
  1189. m_frame->m_blitKeys[item] = key.encode();
  1190. }
  1191. }
  1192. void Frame::sort()
  1193. {
  1194. BGFX_PROFILER_SCOPE("bgfx/Sort", 0xff2040ff);
  1195. ViewId viewRemap[BGFX_CONFIG_MAX_VIEWS];
  1196. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1197. {
  1198. viewRemap[m_viewRemap[ii] ] = ViewId(ii);
  1199. View& view = m_view[ii];
  1200. Rect rect(0, 0, uint16_t(m_resolution.width), uint16_t(m_resolution.height) );
  1201. if (isValid(view.m_fbh) )
  1202. {
  1203. const FrameBufferRef& fbr = s_ctx->m_frameBufferRef[view.m_fbh.idx];
  1204. const BackbufferRatio::Enum bbRatio = fbr.m_window
  1205. ? BackbufferRatio::Count
  1206. : BackbufferRatio::Enum(s_ctx->m_textureRef[fbr.un.m_th[0].idx].m_bbRatio)
  1207. ;
  1208. if (BackbufferRatio::Count != bbRatio)
  1209. {
  1210. getTextureSizeFromRatio(bbRatio, rect.m_width, rect.m_height);
  1211. }
  1212. else
  1213. {
  1214. rect.m_width = fbr.m_width;
  1215. rect.m_height = fbr.m_height;
  1216. }
  1217. }
  1218. view.m_rect.intersect(rect);
  1219. if (!view.m_scissor.isZero() )
  1220. {
  1221. view.m_scissor.intersect(rect);
  1222. }
  1223. }
  1224. for (uint32_t ii = 0, num = m_numRenderItems; ii < num; ++ii)
  1225. {
  1226. m_sortKeys[ii] = SortKey::remapView(m_sortKeys[ii], viewRemap);
  1227. }
  1228. bx::radixSort(m_sortKeys, s_ctx->m_tempKeys, m_sortValues, s_ctx->m_tempValues, m_numRenderItems);
  1229. for (uint32_t ii = 0, num = m_numBlitItems; ii < num; ++ii)
  1230. {
  1231. m_blitKeys[ii] = BlitKey::remapView(m_blitKeys[ii], viewRemap);
  1232. }
  1233. bx::radixSort(m_blitKeys, (uint32_t*)&s_ctx->m_tempKeys, m_numBlitItems);
  1234. }
  1235. RenderFrame::Enum renderFrame(int32_t _msecs)
  1236. {
  1237. if (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) )
  1238. {
  1239. if (s_renderFrameCalled)
  1240. {
  1241. BGFX_CHECK_RENDER_THREAD();
  1242. }
  1243. if (NULL == s_ctx)
  1244. {
  1245. s_renderFrameCalled = true;
  1246. s_threadIndex = ~BGFX_API_THREAD_MAGIC;
  1247. return RenderFrame::NoContext;
  1248. }
  1249. int32_t msecs = -1 == _msecs
  1250. ? BGFX_CONFIG_API_SEMAPHORE_TIMEOUT
  1251. : _msecs
  1252. ;
  1253. RenderFrame::Enum result = s_ctx->renderFrame(msecs);
  1254. if (RenderFrame::Exiting == result)
  1255. {
  1256. Context* ctx = s_ctx;
  1257. ctx->apiSemWait();
  1258. s_ctx = NULL;
  1259. ctx->renderSemPost();
  1260. }
  1261. return result;
  1262. }
  1263. BX_ASSERT(false, "This call only makes sense if used with multi-threaded renderer.");
  1264. return RenderFrame::NoContext;
  1265. }
  1266. const uint32_t g_uniformTypeSize[UniformType::Count+1] =
  1267. {
  1268. sizeof(int32_t),
  1269. 0,
  1270. 4*sizeof(float),
  1271. 3*3*sizeof(float),
  1272. 4*4*sizeof(float),
  1273. 1,
  1274. };
  1275. void UniformBuffer::writeUniform(UniformType::Enum _type, uint16_t _loc, const void* _value, uint16_t _num)
  1276. {
  1277. uint32_t opcode = encodeOpcode(_type, _loc, _num, true);
  1278. write(opcode);
  1279. write(_value, g_uniformTypeSize[_type]*_num);
  1280. }
  1281. void UniformBuffer::writeUniformHandle(UniformType::Enum _type, uint16_t _loc, UniformHandle _handle, uint16_t _num)
  1282. {
  1283. uint32_t opcode = encodeOpcode(_type, _loc, _num, false);
  1284. write(opcode);
  1285. write(&_handle, sizeof(UniformHandle) );
  1286. }
  1287. void UniformBuffer::writeMarker(const char* _marker)
  1288. {
  1289. uint16_t num = (uint16_t)bx::strLen(_marker)+1;
  1290. uint32_t opcode = encodeOpcode(bgfx::UniformType::Count, 0, num, true);
  1291. write(opcode);
  1292. write(_marker, num);
  1293. }
  1294. struct CapsFlags
  1295. {
  1296. uint64_t m_flag;
  1297. const char* m_str;
  1298. };
  1299. static const CapsFlags s_capsFlags[] =
  1300. {
  1301. #define CAPS_FLAGS(_x) { _x, #_x }
  1302. CAPS_FLAGS(BGFX_CAPS_ALPHA_TO_COVERAGE),
  1303. CAPS_FLAGS(BGFX_CAPS_BLEND_INDEPENDENT),
  1304. CAPS_FLAGS(BGFX_CAPS_COMPUTE),
  1305. CAPS_FLAGS(BGFX_CAPS_CONSERVATIVE_RASTER),
  1306. CAPS_FLAGS(BGFX_CAPS_DRAW_INDIRECT),
  1307. CAPS_FLAGS(BGFX_CAPS_FRAGMENT_DEPTH),
  1308. CAPS_FLAGS(BGFX_CAPS_FRAGMENT_ORDERING),
  1309. CAPS_FLAGS(BGFX_CAPS_GRAPHICS_DEBUGGER),
  1310. CAPS_FLAGS(BGFX_CAPS_HDR10),
  1311. CAPS_FLAGS(BGFX_CAPS_HIDPI),
  1312. CAPS_FLAGS(BGFX_CAPS_IMAGE_RW),
  1313. CAPS_FLAGS(BGFX_CAPS_INDEX32),
  1314. CAPS_FLAGS(BGFX_CAPS_INSTANCING),
  1315. CAPS_FLAGS(BGFX_CAPS_OCCLUSION_QUERY),
  1316. CAPS_FLAGS(BGFX_CAPS_RENDERER_MULTITHREADED),
  1317. CAPS_FLAGS(BGFX_CAPS_SWAP_CHAIN),
  1318. CAPS_FLAGS(BGFX_CAPS_TEXTURE_2D_ARRAY),
  1319. CAPS_FLAGS(BGFX_CAPS_TEXTURE_3D),
  1320. CAPS_FLAGS(BGFX_CAPS_TEXTURE_BLIT),
  1321. CAPS_FLAGS(BGFX_CAPS_TRANSPARENT_BACKBUFFER),
  1322. CAPS_FLAGS(BGFX_CAPS_TEXTURE_COMPARE_ALL),
  1323. CAPS_FLAGS(BGFX_CAPS_TEXTURE_COMPARE_LEQUAL),
  1324. CAPS_FLAGS(BGFX_CAPS_TEXTURE_CUBE_ARRAY),
  1325. CAPS_FLAGS(BGFX_CAPS_TEXTURE_DIRECT_ACCESS),
  1326. CAPS_FLAGS(BGFX_CAPS_TEXTURE_READ_BACK),
  1327. CAPS_FLAGS(BGFX_CAPS_VERTEX_ATTRIB_HALF),
  1328. CAPS_FLAGS(BGFX_CAPS_VERTEX_ATTRIB_UINT10),
  1329. CAPS_FLAGS(BGFX_CAPS_VERTEX_ID),
  1330. CAPS_FLAGS(BGFX_CAPS_VIEWPORT_LAYER_ARRAY),
  1331. #undef CAPS_FLAGS
  1332. };
  1333. static void dumpCaps()
  1334. {
  1335. BX_TRACE("");
  1336. if (0 < g_caps.numGPUs)
  1337. {
  1338. BX_TRACE("Detected GPUs (%d):", g_caps.numGPUs);
  1339. BX_TRACE("\t +---------------- Index");
  1340. BX_TRACE("\t | +------------- Device ID");
  1341. BX_TRACE("\t | | +-------- Vendor ID");
  1342. for (uint32_t ii = 0; ii < g_caps.numGPUs; ++ii)
  1343. {
  1344. const Caps::GPU& gpu = g_caps.gpu[ii];
  1345. BX_UNUSED(gpu);
  1346. BX_TRACE("\t %d: %04x %04x"
  1347. , ii
  1348. , gpu.deviceId
  1349. , gpu.vendorId
  1350. );
  1351. }
  1352. BX_TRACE("");
  1353. }
  1354. BX_TRACE("GPU device, Device ID: %04x, Vendor ID: %04x", g_caps.deviceId, g_caps.vendorId);
  1355. BX_TRACE("");
  1356. RendererType::Enum renderers[RendererType::Count];
  1357. uint8_t num = getSupportedRenderers(BX_COUNTOF(renderers), renderers);
  1358. BX_TRACE("Supported renderer backends (%d):", num);
  1359. for (uint32_t ii = 0; ii < num; ++ii)
  1360. {
  1361. BX_TRACE("\t - %s", getRendererName(renderers[ii]) );
  1362. }
  1363. BX_TRACE("");
  1364. BX_TRACE("Sort key masks:");
  1365. BX_TRACE("\t View %016" PRIx64, kSortKeyViewMask);
  1366. BX_TRACE("\t Draw bit %016" PRIx64, kSortKeyDrawBit);
  1367. BX_TRACE("");
  1368. BX_TRACE("\tD Type %016" PRIx64, kSortKeyDrawTypeMask);
  1369. BX_TRACE("");
  1370. BX_TRACE("\tD0 Blend %016" PRIx64, kSortKeyDraw0BlendMask);
  1371. BX_TRACE("\tD0 Program %016" PRIx64, kSortKeyDraw0ProgramMask);
  1372. BX_TRACE("\tD0 Depth %016" PRIx64, kSortKeyDraw0DepthMask);
  1373. BX_TRACE("");
  1374. BX_TRACE("\tD1 Depth %016" PRIx64, kSortKeyDraw1DepthMask);
  1375. BX_TRACE("\tD1 Blend %016" PRIx64, kSortKeyDraw1BlendMask);
  1376. BX_TRACE("\tD1 Program %016" PRIx64, kSortKeyDraw1ProgramMask);
  1377. BX_TRACE("");
  1378. BX_TRACE("\tD2 Seq %016" PRIx64, kSortKeyDraw2SeqMask);
  1379. BX_TRACE("\tD2 Blend %016" PRIx64, kSortKeyDraw2BlendMask);
  1380. BX_TRACE("\tD2 Program %016" PRIx64, kSortKeyDraw2ProgramMask);
  1381. BX_TRACE("");
  1382. BX_TRACE("\t C Seq %016" PRIx64, kSortKeyComputeSeqMask);
  1383. BX_TRACE("\t C Program %016" PRIx64, kSortKeyComputeProgramMask);
  1384. BX_TRACE("");
  1385. BX_TRACE("Capabilities (renderer %s, vendor 0x%04x, device 0x%04x):"
  1386. , s_ctx->m_renderCtx->getRendererName()
  1387. , g_caps.vendorId
  1388. , g_caps.deviceId
  1389. );
  1390. for (uint32_t ii = 0; ii < BX_COUNTOF(s_capsFlags); ++ii)
  1391. {
  1392. BX_TRACE("\t[%c] %s"
  1393. , 0 != (g_caps.supported & s_capsFlags[ii].m_flag) ? 'x' : ' '
  1394. , s_capsFlags[ii].m_str
  1395. );
  1396. }
  1397. BX_UNUSED(s_capsFlags);
  1398. BX_TRACE("");
  1399. BX_TRACE("Limits:");
  1400. #define LIMITS(_x) BX_TRACE("\t%-24s%10d", #_x, g_caps.limits._x)
  1401. LIMITS(maxDrawCalls);
  1402. LIMITS(maxBlits);
  1403. LIMITS(maxTextureSize);
  1404. LIMITS(maxTextureLayers);
  1405. LIMITS(maxViews);
  1406. LIMITS(maxFrameBuffers);
  1407. LIMITS(maxFBAttachments);
  1408. LIMITS(maxPrograms);
  1409. LIMITS(maxShaders);
  1410. LIMITS(maxTextures);
  1411. LIMITS(maxTextureSamplers);
  1412. LIMITS(maxComputeBindings);
  1413. LIMITS(maxVertexLayouts);
  1414. LIMITS(maxVertexStreams);
  1415. LIMITS(maxIndexBuffers);
  1416. LIMITS(maxVertexBuffers);
  1417. LIMITS(maxDynamicIndexBuffers);
  1418. LIMITS(maxDynamicVertexBuffers);
  1419. LIMITS(maxUniforms);
  1420. LIMITS(maxOcclusionQueries);
  1421. LIMITS(maxEncoders);
  1422. LIMITS(minResourceCbSize);
  1423. LIMITS(transientVbSize);
  1424. LIMITS(transientIbSize);
  1425. #undef LIMITS
  1426. BX_TRACE("");
  1427. BX_TRACE("Supported texture formats:");
  1428. BX_TRACE("\t +---------------- 2D: x = supported / * = emulated");
  1429. BX_TRACE("\t |+--------------- 2D: sRGB format");
  1430. BX_TRACE("\t ||+-------------- 3D: x = supported / * = emulated");
  1431. BX_TRACE("\t |||+------------- 3D: sRGB format");
  1432. BX_TRACE("\t ||||+------------ Cube: x = supported / * = emulated");
  1433. BX_TRACE("\t |||||+----------- Cube: sRGB format");
  1434. BX_TRACE("\t ||||||+---------- vertex format");
  1435. BX_TRACE("\t |||||||+--------- image: i = read-write / r = read / w = write");
  1436. BX_TRACE("\t ||||||||+-------- framebuffer");
  1437. BX_TRACE("\t |||||||||+------- MSAA framebuffer");
  1438. BX_TRACE("\t ||||||||||+------ MSAA texture");
  1439. BX_TRACE("\t |||||||||||+----- Auto-generated mips");
  1440. BX_TRACE("\t |||||||||||| +-- name");
  1441. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1442. {
  1443. if (TextureFormat::Unknown != ii
  1444. && TextureFormat::UnknownDepth != ii)
  1445. {
  1446. uint32_t flags = g_caps.formats[ii];
  1447. BX_TRACE("\t[%c%c%c%c%c%c%c%c%c%c%c%c] %s"
  1448. , flags&BGFX_CAPS_FORMAT_TEXTURE_2D ? 'x' : flags&BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED ? '*' : ' '
  1449. , flags&BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB ? 'l' : ' '
  1450. , flags&BGFX_CAPS_FORMAT_TEXTURE_3D ? 'x' : flags&BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED ? '*' : ' '
  1451. , flags&BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB ? 'l' : ' '
  1452. , flags&BGFX_CAPS_FORMAT_TEXTURE_CUBE ? 'x' : flags&BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED ? '*' : ' '
  1453. , flags&BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB ? 'l' : ' '
  1454. , flags&BGFX_CAPS_FORMAT_TEXTURE_VERTEX ? 'v' : ' '
  1455. , (flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_READ) &&
  1456. (flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_WRITE) ? 'i' : flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_READ ? 'r' : flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_WRITE ? 'w' : ' '
  1457. , flags&BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER ? 'f' : ' '
  1458. , flags&BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA ? '+' : ' '
  1459. , flags&BGFX_CAPS_FORMAT_TEXTURE_MSAA ? 'm' : ' '
  1460. , flags&BGFX_CAPS_FORMAT_TEXTURE_MIP_AUTOGEN ? 'M' : ' '
  1461. , getName(TextureFormat::Enum(ii) )
  1462. );
  1463. BX_UNUSED(flags);
  1464. }
  1465. }
  1466. BX_TRACE("");
  1467. BX_TRACE("NDC depth [%d, 1], origin %s left."
  1468. , g_caps.homogeneousDepth ? -1 : 0
  1469. , g_caps.originBottomLeft ? "bottom" : "top"
  1470. );
  1471. BX_TRACE("");
  1472. }
  1473. void dump(const Resolution& _resolution)
  1474. {
  1475. const uint32_t reset = _resolution.reset;
  1476. const uint32_t msaa = (reset&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  1477. BX_UNUSED(reset, msaa);
  1478. BX_TRACE("Reset back-buffer swap chain:");
  1479. BX_TRACE("\t%dx%d, format: %s, numBackBuffers: %d, maxFrameLatency: %d"
  1480. , _resolution.width
  1481. , _resolution.height
  1482. , TextureFormat::Count == _resolution.format
  1483. ? "*default*"
  1484. : bimg::getName(bimg::TextureFormat::Enum(_resolution.format) )
  1485. , _resolution.numBackBuffers
  1486. , _resolution.maxFrameLatency
  1487. );
  1488. BX_TRACE("\t[%c] MSAAx%d", 0 != msaa ? 'x' : ' ', 1<<msaa);
  1489. BX_TRACE("\t[%c] Fullscreen", 0 != (reset & BGFX_RESET_FULLSCREEN) ? 'x' : ' ');
  1490. BX_TRACE("\t[%c] V-sync", 0 != (reset & BGFX_RESET_VSYNC) ? 'x' : ' ');
  1491. BX_TRACE("\t[%c] Max Anisotropy", 0 != (reset & BGFX_RESET_MAXANISOTROPY) ? 'x' : ' ');
  1492. BX_TRACE("\t[%c] Capture", 0 != (reset & BGFX_RESET_CAPTURE) ? 'x' : ' ');
  1493. BX_TRACE("\t[%c] Flush After Render", 0 != (reset & BGFX_RESET_FLUSH_AFTER_RENDER) ? 'x' : ' ');
  1494. BX_TRACE("\t[%c] Flip After Render", 0 != (reset & BGFX_RESET_FLIP_AFTER_RENDER) ? 'x' : ' ');
  1495. BX_TRACE("\t[%c] sRGB Back Buffer", 0 != (reset & BGFX_RESET_SRGB_BACKBUFFER) ? 'x' : ' ');
  1496. BX_TRACE("\t[%c] Transparent Back Buffer", 0 != (reset & BGFX_RESET_TRANSPARENT_BACKBUFFER) ? 'x' : ' ');
  1497. BX_TRACE("\t[%c] HDR10", 0 != (reset & BGFX_RESET_HDR10) ? 'x' : ' ');
  1498. BX_TRACE("\t[%c] Hi-DPI", 0 != (reset & BGFX_RESET_HIDPI) ? 'x' : ' ');
  1499. BX_TRACE("\t[%c] Depth Clamp", 0 != (reset & BGFX_RESET_DEPTH_CLAMP) ? 'x' : ' ');
  1500. BX_TRACE("\t[%c] Suspend", 0 != (reset & BGFX_RESET_SUSPEND) ? 'x' : ' ');
  1501. }
  1502. TextureFormat::Enum getViableTextureFormat(const bimg::ImageContainer& _imageContainer)
  1503. {
  1504. const uint32_t formatCaps = g_caps.formats[_imageContainer.m_format];
  1505. bool convert = 0 == formatCaps;
  1506. if (_imageContainer.m_cubeMap)
  1507. {
  1508. convert |= 0 == (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_CUBE)
  1509. && 0 != (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED)
  1510. ;
  1511. }
  1512. else if (_imageContainer.m_depth > 1)
  1513. {
  1514. convert |= 0 == (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_3D)
  1515. && 0 != (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED)
  1516. ;
  1517. }
  1518. else
  1519. {
  1520. convert |= 0 == (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_2D)
  1521. && 0 != (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED)
  1522. ;
  1523. }
  1524. if (convert)
  1525. {
  1526. return TextureFormat::BGRA8;
  1527. }
  1528. return TextureFormat::Enum(_imageContainer.m_format);
  1529. }
  1530. const char* getName(TextureFormat::Enum _fmt)
  1531. {
  1532. return bimg::getName(bimg::TextureFormat::Enum(_fmt));
  1533. }
  1534. const char* getName(UniformHandle _handle)
  1535. {
  1536. return s_ctx->m_uniformRef[_handle.idx].m_name.getPtr();
  1537. }
  1538. const char* getName(ShaderHandle _handle)
  1539. {
  1540. return s_ctx->m_shaderRef[_handle.idx].m_name.getPtr();
  1541. }
  1542. static const char* s_topologyName[] =
  1543. {
  1544. "Triangles",
  1545. "TriStrip",
  1546. "Lines",
  1547. "LineStrip",
  1548. "Points",
  1549. };
  1550. BX_STATIC_ASSERT(Topology::Count == BX_COUNTOF(s_topologyName) );
  1551. const char* getName(Topology::Enum _topology)
  1552. {
  1553. return s_topologyName[bx::min(_topology, Topology::PointList)];
  1554. }
  1555. const char* getShaderTypeName(uint32_t _magic)
  1556. {
  1557. if (isShaderType(_magic, 'C') )
  1558. {
  1559. return "Compute";
  1560. }
  1561. else if (isShaderType(_magic, 'F') )
  1562. {
  1563. return "Fragment";
  1564. }
  1565. else if (isShaderType(_magic, 'V') )
  1566. {
  1567. return "Vertex";
  1568. }
  1569. BX_ASSERT(false, "Invalid shader type!");
  1570. return NULL;
  1571. }
  1572. static TextureFormat::Enum s_emulatedFormats[] =
  1573. {
  1574. TextureFormat::BC1,
  1575. TextureFormat::BC2,
  1576. TextureFormat::BC3,
  1577. TextureFormat::BC4,
  1578. TextureFormat::BC5,
  1579. TextureFormat::ETC1,
  1580. TextureFormat::ETC2,
  1581. TextureFormat::ETC2A,
  1582. TextureFormat::ETC2A1,
  1583. TextureFormat::PTC12,
  1584. TextureFormat::PTC14,
  1585. TextureFormat::PTC12A,
  1586. TextureFormat::PTC14A,
  1587. TextureFormat::PTC22,
  1588. TextureFormat::PTC24,
  1589. TextureFormat::ATC,
  1590. TextureFormat::ATCE,
  1591. TextureFormat::ATCI,
  1592. TextureFormat::ASTC4x4,
  1593. TextureFormat::ASTC5x4,
  1594. TextureFormat::ASTC5x5,
  1595. TextureFormat::ASTC6x5,
  1596. TextureFormat::ASTC6x6,
  1597. TextureFormat::ASTC8x5,
  1598. TextureFormat::ASTC8x6,
  1599. TextureFormat::ASTC8x8,
  1600. TextureFormat::ASTC10x5,
  1601. TextureFormat::ASTC10x6,
  1602. TextureFormat::ASTC10x8,
  1603. TextureFormat::ASTC10x10,
  1604. TextureFormat::ASTC12x10,
  1605. TextureFormat::ASTC12x12,
  1606. TextureFormat::BGRA8, // GL doesn't support BGRA8 without extensions.
  1607. TextureFormat::RGBA8, // D3D9 doesn't support RGBA8
  1608. };
  1609. bool Context::init(const Init& _init)
  1610. {
  1611. BX_ASSERT(!m_rendererInitialized, "Already initialized?");
  1612. m_init = _init;
  1613. m_init.resolution.reset &= ~BGFX_RESET_INTERNAL_FORCE;
  1614. m_init.resolution.numBackBuffers = bx::clamp<uint8_t>(_init.resolution.numBackBuffers, 2, BGFX_CONFIG_MAX_BACK_BUFFERS);
  1615. m_init.resolution.maxFrameLatency = bx::min<uint8_t>(_init.resolution.maxFrameLatency, BGFX_CONFIG_MAX_FRAME_LATENCY);
  1616. dump(m_init.resolution);
  1617. if (true
  1618. && RendererType::Noop != m_init.type
  1619. && NULL == m_init.platformData.ndt
  1620. && NULL == m_init.platformData.nwh
  1621. && NULL == m_init.platformData.context
  1622. && NULL == m_init.platformData.backBuffer
  1623. && NULL == m_init.platformData.backBufferDS
  1624. )
  1625. {
  1626. BX_TRACE("bgfx platform data like window handle or backbuffer is not set, creating headless device.");
  1627. }
  1628. bx::memCopy(&g_platformData, &m_init.platformData, sizeof(PlatformData) );
  1629. m_exit = false;
  1630. m_flipped = true;
  1631. m_debug = BGFX_DEBUG_NONE;
  1632. m_frameTimeLast = bx::getHPCounter();
  1633. m_submit->create(_init.limits.minResourceCbSize);
  1634. #if BGFX_CONFIG_MULTITHREADED
  1635. m_render->create(_init.limits.minResourceCbSize);
  1636. if (s_renderFrameCalled)
  1637. {
  1638. // When bgfx::renderFrame is called before init render thread
  1639. // should not be created.
  1640. BX_TRACE("Application called bgfx::renderFrame directly, not creating render thread.");
  1641. m_singleThreaded = true
  1642. && ~BGFX_API_THREAD_MAGIC == s_threadIndex
  1643. ;
  1644. }
  1645. else
  1646. {
  1647. BX_TRACE("Creating rendering thread.");
  1648. m_thread.init(renderThread, this, 0, "bgfx - renderer backend thread");
  1649. m_singleThreaded = false;
  1650. }
  1651. #else
  1652. BX_TRACE("Multithreaded renderer is disabled.");
  1653. m_singleThreaded = true;
  1654. #endif // BGFX_CONFIG_MULTITHREADED
  1655. BX_TRACE("Running in %s-threaded mode", m_singleThreaded ? "single" : "multi");
  1656. s_threadIndex = BGFX_API_THREAD_MAGIC;
  1657. for (uint32_t ii = 0; ii < BX_COUNTOF(m_viewRemap); ++ii)
  1658. {
  1659. m_viewRemap[ii] = ViewId(ii);
  1660. }
  1661. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1662. {
  1663. resetView(ViewId(ii) );
  1664. }
  1665. for (uint32_t ii = 0; ii < BX_COUNTOF(m_clearColor); ++ii)
  1666. {
  1667. m_clearColor[ii][0] = 0.0f;
  1668. m_clearColor[ii][1] = 0.0f;
  1669. m_clearColor[ii][2] = 0.0f;
  1670. m_clearColor[ii][3] = 1.0f;
  1671. }
  1672. m_vertexLayoutRef.init();
  1673. CommandBuffer& cmdbuf = getCommandBuffer(CommandBuffer::RendererInit);
  1674. cmdbuf.write(_init);
  1675. frameNoRenderWait();
  1676. m_encoderHandle = bx::createHandleAlloc(g_allocator, _init.limits.maxEncoders);
  1677. m_encoder = (EncoderImpl*)BX_ALIGNED_ALLOC(g_allocator, sizeof(EncoderImpl)*_init.limits.maxEncoders, BX_ALIGNOF(EncoderImpl) );
  1678. m_encoderStats = (EncoderStats*)BX_ALLOC(g_allocator, sizeof(EncoderStats)*_init.limits.maxEncoders);
  1679. for (uint32_t ii = 0, num = _init.limits.maxEncoders; ii < num; ++ii)
  1680. {
  1681. BX_PLACEMENT_NEW(&m_encoder[ii], EncoderImpl);
  1682. }
  1683. uint16_t idx = m_encoderHandle->alloc();
  1684. BX_ASSERT(0 == idx, "Internal encoder handle is not 0 (idx %d).", idx); BX_UNUSED(idx);
  1685. m_encoder[0].begin(m_submit, 0);
  1686. m_encoder0 = BX_ENABLED(BGFX_CONFIG_ENCODER_API_ONLY)
  1687. ? NULL
  1688. : reinterpret_cast<Encoder*>(&m_encoder[0])
  1689. ;
  1690. // Make sure renderer init is called from render thread.
  1691. // g_caps is initialized and available after this point.
  1692. frame();
  1693. if (!m_rendererInitialized)
  1694. {
  1695. getCommandBuffer(CommandBuffer::RendererShutdownEnd);
  1696. frame();
  1697. frame();
  1698. m_vertexLayoutRef.shutdown(m_layoutHandle);
  1699. m_submit->destroy();
  1700. #if BGFX_CONFIG_MULTITHREADED
  1701. m_render->destroy();
  1702. #endif // BGFX_CONFIG_MULTITHREADED
  1703. return false;
  1704. }
  1705. for (uint32_t ii = 0; ii < BX_COUNTOF(s_emulatedFormats); ++ii)
  1706. {
  1707. const uint32_t fmt = s_emulatedFormats[ii];
  1708. g_caps.formats[fmt] |= 0 == (g_caps.formats[fmt] & BGFX_CAPS_FORMAT_TEXTURE_2D ) ? BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED : 0;
  1709. g_caps.formats[fmt] |= 0 == (g_caps.formats[fmt] & BGFX_CAPS_FORMAT_TEXTURE_3D ) ? BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED : 0;
  1710. g_caps.formats[fmt] |= 0 == (g_caps.formats[fmt] & BGFX_CAPS_FORMAT_TEXTURE_CUBE) ? BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED : 0;
  1711. }
  1712. for (uint32_t ii = 0; ii < TextureFormat::UnknownDepth; ++ii)
  1713. {
  1714. bool convertable = bimg::imageConvert(bimg::TextureFormat::BGRA8, bimg::TextureFormat::Enum(ii) );
  1715. g_caps.formats[ii] |= 0 == (g_caps.formats[ii] & BGFX_CAPS_FORMAT_TEXTURE_2D ) && convertable ? BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED : 0;
  1716. g_caps.formats[ii] |= 0 == (g_caps.formats[ii] & BGFX_CAPS_FORMAT_TEXTURE_3D ) && convertable ? BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED : 0;
  1717. g_caps.formats[ii] |= 0 == (g_caps.formats[ii] & BGFX_CAPS_FORMAT_TEXTURE_CUBE) && convertable ? BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED : 0;
  1718. }
  1719. g_caps.rendererType = m_renderCtx->getRendererType();
  1720. initAttribTypeSizeTable(g_caps.rendererType);
  1721. g_caps.supported &= _init.capabilities;
  1722. g_caps.supported |= 0
  1723. | (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) && !m_singleThreaded ? BGFX_CAPS_RENDERER_MULTITHREADED : 0)
  1724. | (isGraphicsDebuggerPresent() ? BGFX_CAPS_GRAPHICS_DEBUGGER : 0)
  1725. ;
  1726. dumpCaps();
  1727. m_textVideoMemBlitter.init();
  1728. m_clearQuad.init();
  1729. m_submit->m_transientVb = createTransientVertexBuffer(_init.limits.transientVbSize);
  1730. m_submit->m_transientIb = createTransientIndexBuffer(_init.limits.transientIbSize);
  1731. frame();
  1732. if (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) )
  1733. {
  1734. m_submit->m_transientVb = createTransientVertexBuffer(_init.limits.transientVbSize);
  1735. m_submit->m_transientIb = createTransientIndexBuffer(_init.limits.transientIbSize);
  1736. frame();
  1737. }
  1738. g_internalData.caps = getCaps();
  1739. return true;
  1740. }
  1741. void Context::shutdown()
  1742. {
  1743. getCommandBuffer(CommandBuffer::RendererShutdownBegin);
  1744. frame();
  1745. destroyTransientVertexBuffer(m_submit->m_transientVb);
  1746. destroyTransientIndexBuffer(m_submit->m_transientIb);
  1747. m_textVideoMemBlitter.shutdown();
  1748. m_clearQuad.shutdown();
  1749. frame();
  1750. if (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) )
  1751. {
  1752. destroyTransientVertexBuffer(m_submit->m_transientVb);
  1753. destroyTransientIndexBuffer(m_submit->m_transientIb);
  1754. frame();
  1755. }
  1756. frame(); // If any VertexLayouts needs to be destroyed.
  1757. getCommandBuffer(CommandBuffer::RendererShutdownEnd);
  1758. frame();
  1759. m_encoder[0].end(true);
  1760. m_encoderHandle->free(0);
  1761. bx::destroyHandleAlloc(g_allocator, m_encoderHandle);
  1762. m_encoderHandle = NULL;
  1763. for (uint32_t ii = 0, num = g_caps.limits.maxEncoders; ii < num; ++ii)
  1764. {
  1765. m_encoder[ii].~EncoderImpl();
  1766. }
  1767. BX_ALIGNED_FREE(g_allocator, m_encoder, BX_ALIGNOF(EncoderImpl) );
  1768. BX_FREE(g_allocator, m_encoderStats);
  1769. m_dynVertexBufferAllocator.compact();
  1770. m_dynIndexBufferAllocator.compact();
  1771. BX_ASSERT(
  1772. m_layoutHandle.getNumHandles() == m_vertexLayoutRef.m_vertexLayoutMap.getNumElements()
  1773. , "VertexLayoutRef mismatch, num handles %d, handles in hash map %d."
  1774. , m_layoutHandle.getNumHandles()
  1775. , m_vertexLayoutRef.m_vertexLayoutMap.getNumElements()
  1776. );
  1777. m_vertexLayoutRef.shutdown(m_layoutHandle);
  1778. #if BGFX_CONFIG_MULTITHREADED
  1779. // Render thread shutdown sequence.
  1780. renderSemWait(); // Wait for previous frame.
  1781. apiSemPost(); // OK to set context to NULL.
  1782. // s_ctx is NULL here.
  1783. renderSemWait(); // In RenderFrame::Exiting state.
  1784. if (m_thread.isRunning() )
  1785. {
  1786. m_thread.shutdown();
  1787. }
  1788. m_render->destroy();
  1789. #endif // BGFX_CONFIG_MULTITHREADED
  1790. bx::memSet(&g_internalData, 0, sizeof(InternalData) );
  1791. s_ctx = NULL;
  1792. m_submit->destroy();
  1793. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  1794. {
  1795. #define CHECK_HANDLE_LEAK(_name, _handleAlloc) \
  1796. BX_MACRO_BLOCK_BEGIN \
  1797. if (0 != _handleAlloc.getNumHandles() ) \
  1798. { \
  1799. BX_TRACE("LEAK: %s %d (max: %d)" \
  1800. , _name \
  1801. , _handleAlloc.getNumHandles() \
  1802. , _handleAlloc.getMaxHandles() \
  1803. ); \
  1804. for (uint16_t ii = 0, num = _handleAlloc.getNumHandles(); ii < num; ++ii) \
  1805. { \
  1806. BX_TRACE("\t%3d: %4d", ii, _handleAlloc.getHandleAt(ii) ); \
  1807. } \
  1808. } \
  1809. BX_MACRO_BLOCK_END
  1810. #define CHECK_HANDLE_LEAK_NAME(_name, _handleAlloc, _type, _ref) \
  1811. BX_MACRO_BLOCK_BEGIN \
  1812. if (0 != _handleAlloc.getNumHandles() ) \
  1813. { \
  1814. BX_TRACE("LEAK: %s %d (max: %d)" \
  1815. , _name \
  1816. , _handleAlloc.getNumHandles() \
  1817. , _handleAlloc.getMaxHandles() \
  1818. ); \
  1819. for (uint16_t ii = 0, num = _handleAlloc.getNumHandles(); ii < num; ++ii) \
  1820. { \
  1821. uint16_t idx = _handleAlloc.getHandleAt(ii); \
  1822. const _type& ref = _ref[idx]; BX_UNUSED(ref); \
  1823. BX_TRACE("\t%3d: %4d %s" \
  1824. , ii \
  1825. , idx \
  1826. , ref.m_name.getPtr() \
  1827. ); \
  1828. } \
  1829. } \
  1830. BX_MACRO_BLOCK_END
  1831. #define CHECK_HANDLE_LEAK_RC_NAME(_name, _handleAlloc, _type, _ref) \
  1832. BX_MACRO_BLOCK_BEGIN \
  1833. if (0 != _handleAlloc.getNumHandles() ) \
  1834. { \
  1835. BX_TRACE("LEAK: %s %d (max: %d)" \
  1836. , _name \
  1837. , _handleAlloc.getNumHandles() \
  1838. , _handleAlloc.getMaxHandles() \
  1839. ); \
  1840. for (uint16_t ii = 0, num = _handleAlloc.getNumHandles(); ii < num; ++ii) \
  1841. { \
  1842. uint16_t idx = _handleAlloc.getHandleAt(ii); \
  1843. const _type& ref = _ref[idx]; BX_UNUSED(ref); \
  1844. BX_TRACE("\t%3d: %4d %s (count %d)" \
  1845. , ii \
  1846. , idx \
  1847. , ref.m_name.getPtr() \
  1848. , ref.m_refCount \
  1849. ); \
  1850. } \
  1851. } \
  1852. BX_MACRO_BLOCK_END
  1853. CHECK_HANDLE_LEAK ("DynamicIndexBufferHandle", m_dynamicIndexBufferHandle );
  1854. CHECK_HANDLE_LEAK ("DynamicVertexBufferHandle", m_dynamicVertexBufferHandle );
  1855. CHECK_HANDLE_LEAK_NAME ("IndexBufferHandle", m_indexBufferHandle, IndexBuffer, m_indexBuffers );
  1856. CHECK_HANDLE_LEAK ("VertexLayoutHandle", m_layoutHandle );
  1857. CHECK_HANDLE_LEAK_NAME ("VertexBufferHandle", m_vertexBufferHandle, VertexBuffer, m_vertexBuffers );
  1858. CHECK_HANDLE_LEAK_RC_NAME("ShaderHandle", m_shaderHandle, ShaderRef, m_shaderRef );
  1859. CHECK_HANDLE_LEAK ("ProgramHandle", m_programHandle );
  1860. CHECK_HANDLE_LEAK_RC_NAME("TextureHandle", m_textureHandle, TextureRef, m_textureRef );
  1861. CHECK_HANDLE_LEAK_NAME ("FrameBufferHandle", m_frameBufferHandle, FrameBufferRef, m_frameBufferRef);
  1862. CHECK_HANDLE_LEAK_RC_NAME("UniformHandle", m_uniformHandle, UniformRef, m_uniformRef );
  1863. CHECK_HANDLE_LEAK ("OcclusionQueryHandle", m_occlusionQueryHandle );
  1864. #undef CHECK_HANDLE_LEAK
  1865. #undef CHECK_HANDLE_LEAK_NAME
  1866. }
  1867. }
  1868. void Context::freeDynamicBuffers()
  1869. {
  1870. for (uint16_t ii = 0, num = m_numFreeDynamicIndexBufferHandles; ii < num; ++ii)
  1871. {
  1872. destroyDynamicIndexBufferInternal(m_freeDynamicIndexBufferHandle[ii]);
  1873. }
  1874. m_numFreeDynamicIndexBufferHandles = 0;
  1875. for (uint16_t ii = 0, num = m_numFreeDynamicVertexBufferHandles; ii < num; ++ii)
  1876. {
  1877. destroyDynamicVertexBufferInternal(m_freeDynamicVertexBufferHandle[ii]);
  1878. }
  1879. m_numFreeDynamicVertexBufferHandles = 0;
  1880. for (uint16_t ii = 0, num = m_numFreeOcclusionQueryHandles; ii < num; ++ii)
  1881. {
  1882. m_occlusionQueryHandle.free(m_freeOcclusionQueryHandle[ii].idx);
  1883. }
  1884. m_numFreeOcclusionQueryHandles = 0;
  1885. }
  1886. void Context::freeAllHandles(Frame* _frame)
  1887. {
  1888. for (uint16_t ii = 0, num = _frame->m_freeIndexBuffer.getNumQueued(); ii < num; ++ii)
  1889. {
  1890. m_indexBufferHandle.free(_frame->m_freeIndexBuffer.get(ii).idx);
  1891. }
  1892. for (uint16_t ii = 0, num = _frame->m_freeVertexBuffer.getNumQueued(); ii < num; ++ii)
  1893. {
  1894. destroyVertexBufferInternal(_frame->m_freeVertexBuffer.get(ii));
  1895. }
  1896. for (uint16_t ii = 0, num = _frame->m_freeVertexLayout.getNumQueued(); ii < num; ++ii)
  1897. {
  1898. m_layoutHandle.free(_frame->m_freeVertexLayout.get(ii).idx);
  1899. }
  1900. for (uint16_t ii = 0, num = _frame->m_freeShader.getNumQueued(); ii < num; ++ii)
  1901. {
  1902. m_shaderHandle.free(_frame->m_freeShader.get(ii).idx);
  1903. }
  1904. for (uint16_t ii = 0, num = _frame->m_freeProgram.getNumQueued(); ii < num; ++ii)
  1905. {
  1906. m_programHandle.free(_frame->m_freeProgram.get(ii).idx);
  1907. }
  1908. for (uint16_t ii = 0, num = _frame->m_freeTexture.getNumQueued(); ii < num; ++ii)
  1909. {
  1910. m_textureHandle.free(_frame->m_freeTexture.get(ii).idx);
  1911. }
  1912. for (uint16_t ii = 0, num = _frame->m_freeFrameBuffer.getNumQueued(); ii < num; ++ii)
  1913. {
  1914. m_frameBufferHandle.free(_frame->m_freeFrameBuffer.get(ii).idx);
  1915. }
  1916. for (uint16_t ii = 0, num = _frame->m_freeUniform.getNumQueued(); ii < num; ++ii)
  1917. {
  1918. m_uniformHandle.free(_frame->m_freeUniform.get(ii).idx);
  1919. }
  1920. }
  1921. Encoder* Context::begin(bool _forThread)
  1922. {
  1923. EncoderImpl* encoder = &m_encoder[0];
  1924. #if BGFX_CONFIG_MULTITHREADED
  1925. if (_forThread || BGFX_API_THREAD_MAGIC != s_threadIndex)
  1926. {
  1927. bx::MutexScope scopeLock(m_encoderApiLock);
  1928. uint16_t idx = m_encoderHandle->alloc();
  1929. if (kInvalidHandle == idx)
  1930. {
  1931. return NULL;
  1932. }
  1933. encoder = &m_encoder[idx];
  1934. encoder->begin(m_submit, uint8_t(idx) );
  1935. }
  1936. #else
  1937. BX_UNUSED(_forThread);
  1938. #endif // BGFX_CONFIG_MULTITHREADED
  1939. return reinterpret_cast<Encoder*>(encoder);
  1940. }
  1941. void Context::end(Encoder* _encoder)
  1942. {
  1943. #if BGFX_CONFIG_MULTITHREADED
  1944. EncoderImpl* encoder = reinterpret_cast<EncoderImpl*>(_encoder);
  1945. if (encoder != &m_encoder[0])
  1946. {
  1947. encoder->end(true);
  1948. m_encoderEndSem.post();
  1949. }
  1950. #else
  1951. BX_UNUSED(_encoder);
  1952. #endif // BGFX_CONFIG_MULTITHREADED
  1953. }
  1954. uint32_t Context::frame(bool _capture)
  1955. {
  1956. m_encoder[0].end(true);
  1957. #if BGFX_CONFIG_MULTITHREADED
  1958. bx::MutexScope resourceApiScope(m_resourceApiLock);
  1959. encoderApiWait();
  1960. bx::MutexScope encoderApiScope(m_encoderApiLock);
  1961. #else
  1962. encoderApiWait();
  1963. #endif // BGFX_CONFIG_MULTITHREADED
  1964. m_submit->m_capture = _capture;
  1965. uint32_t frameNum = m_submit->m_frameNum;
  1966. BGFX_PROFILER_SCOPE("bgfx/API thread frame", 0xff2040ff);
  1967. // wait for render thread to finish
  1968. renderSemWait();
  1969. frameNoRenderWait();
  1970. m_encoder[0].begin(m_submit, 0);
  1971. return frameNum;
  1972. }
  1973. void Context::frameNoRenderWait()
  1974. {
  1975. swap();
  1976. // release render thread
  1977. apiSemPost();
  1978. }
  1979. void Context::swap()
  1980. {
  1981. freeDynamicBuffers();
  1982. m_submit->m_resolution = m_init.resolution;
  1983. m_init.resolution.reset &= ~BGFX_RESET_INTERNAL_FORCE;
  1984. m_submit->m_debug = m_debug;
  1985. m_submit->m_perfStats.numViews = 0;
  1986. bx::memCopy(m_submit->m_viewRemap, m_viewRemap, sizeof(m_viewRemap) );
  1987. bx::memCopy(m_submit->m_view, m_view, sizeof(m_view) );
  1988. if (m_colorPaletteDirty > 0)
  1989. {
  1990. --m_colorPaletteDirty;
  1991. bx::memCopy(m_submit->m_colorPalette, m_clearColor, sizeof(m_clearColor) );
  1992. }
  1993. freeAllHandles(m_submit);
  1994. m_submit->resetFreeHandles();
  1995. m_submit->finish();
  1996. bx::swap(m_render, m_submit);
  1997. bx::memCopy(m_render->m_occlusion, m_submit->m_occlusion, sizeof(m_submit->m_occlusion) );
  1998. if (!BX_ENABLED(BGFX_CONFIG_MULTITHREADED)
  1999. || m_singleThreaded)
  2000. {
  2001. renderFrame();
  2002. }
  2003. uint32_t nextFrameNum = m_render->m_frameNum + 1;
  2004. m_submit->start(nextFrameNum);
  2005. bx::memSet(m_seq, 0, sizeof(m_seq) );
  2006. m_submit->m_textVideoMem->resize(
  2007. m_render->m_textVideoMem->m_small
  2008. , m_init.resolution.width
  2009. , m_init.resolution.height
  2010. );
  2011. int64_t now = bx::getHPCounter();
  2012. m_submit->m_perfStats.cpuTimeFrame = now - m_frameTimeLast;
  2013. m_frameTimeLast = now;
  2014. }
  2015. ///
  2016. RendererContextI* rendererCreate(const Init& _init);
  2017. ///
  2018. void rendererDestroy(RendererContextI* _renderCtx);
  2019. void Context::flip()
  2020. {
  2021. if (m_rendererInitialized
  2022. && !m_flipped)
  2023. {
  2024. m_renderCtx->flip();
  2025. m_flipped = true;
  2026. if (m_renderCtx->isDeviceRemoved() )
  2027. {
  2028. // Something horribly went wrong, fallback to noop renderer.
  2029. rendererDestroy(m_renderCtx);
  2030. Init init;
  2031. init.type = RendererType::Noop;
  2032. m_renderCtx = rendererCreate(init);
  2033. g_caps.rendererType = RendererType::Noop;
  2034. }
  2035. }
  2036. }
  2037. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS
  2038. struct NSAutoreleasePoolScope
  2039. {
  2040. NSAutoreleasePoolScope()
  2041. {
  2042. id obj = class_createInstance(objc_getClass("NSAutoreleasePool"), 0);
  2043. typedef id(*objc_msgSend_init)(void*, SEL);
  2044. pool = ((objc_msgSend_init)objc_msgSend)(obj, sel_getUid("init") );
  2045. }
  2046. ~NSAutoreleasePoolScope()
  2047. {
  2048. typedef void(*objc_msgSend_release)(void*, SEL);
  2049. ((objc_msgSend_release)objc_msgSend)(pool, sel_getUid("release") );
  2050. }
  2051. id pool;
  2052. };
  2053. #endif // BX_PLATFORM_OSX
  2054. RenderFrame::Enum Context::renderFrame(int32_t _msecs)
  2055. {
  2056. BGFX_PROFILER_SCOPE("bgfx::renderFrame", 0xff2040ff);
  2057. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS
  2058. NSAutoreleasePoolScope pool;
  2059. #endif // BX_PLATFORM_OSX
  2060. if (!m_flipAfterRender)
  2061. {
  2062. BGFX_PROFILER_SCOPE("bgfx/flip", 0xff2040ff);
  2063. flip();
  2064. }
  2065. if (apiSemWait(_msecs) )
  2066. {
  2067. {
  2068. BGFX_PROFILER_SCOPE("bgfx/Exec commands pre", 0xff2040ff);
  2069. rendererExecCommands(m_render->m_cmdPre);
  2070. }
  2071. if (m_rendererInitialized)
  2072. {
  2073. {
  2074. BGFX_PROFILER_SCOPE("bgfx/Render submit", 0xff2040ff);
  2075. m_renderCtx->submit(m_render, m_clearQuad, m_textVideoMemBlitter);
  2076. m_flipped = false;
  2077. }
  2078. {
  2079. BGFX_PROFILER_SCOPE("bgfx/Screenshot", 0xff2040ff);
  2080. for (uint8_t ii = 0, num = m_render->m_numScreenShots; ii < num; ++ii)
  2081. {
  2082. const ScreenShot& screenShot = m_render->m_screenShot[ii];
  2083. m_renderCtx->requestScreenShot(screenShot.handle, screenShot.filePath.getCPtr() );
  2084. }
  2085. }
  2086. }
  2087. {
  2088. BGFX_PROFILER_SCOPE("bgfx/Exec commands post", 0xff2040ff);
  2089. rendererExecCommands(m_render->m_cmdPost);
  2090. }
  2091. renderSemPost();
  2092. if (m_flipAfterRender)
  2093. {
  2094. BGFX_PROFILER_SCOPE("bgfx/flip", 0xff2040ff);
  2095. flip();
  2096. }
  2097. }
  2098. else
  2099. {
  2100. return RenderFrame::Timeout;
  2101. }
  2102. return m_exit
  2103. ? RenderFrame::Exiting
  2104. : RenderFrame::Render
  2105. ;
  2106. }
  2107. void rendererUpdateUniforms(RendererContextI* _renderCtx, UniformBuffer* _uniformBuffer, uint32_t _begin, uint32_t _end)
  2108. {
  2109. _uniformBuffer->reset(_begin);
  2110. while (_uniformBuffer->getPos() < _end)
  2111. {
  2112. uint32_t opcode = _uniformBuffer->read();
  2113. if (UniformType::End == opcode)
  2114. {
  2115. break;
  2116. }
  2117. UniformType::Enum type;
  2118. uint16_t loc;
  2119. uint16_t num;
  2120. uint16_t copy;
  2121. UniformBuffer::decodeOpcode(opcode, type, loc, num, copy);
  2122. uint32_t size = g_uniformTypeSize[type]*num;
  2123. const char* data = _uniformBuffer->read(size);
  2124. if (UniformType::Count > type)
  2125. {
  2126. if (copy)
  2127. {
  2128. _renderCtx->updateUniform(loc, data, size);
  2129. }
  2130. else
  2131. {
  2132. _renderCtx->updateUniform(loc, *(const char**)(data), size);
  2133. }
  2134. }
  2135. else
  2136. {
  2137. _renderCtx->setMarker(data, uint16_t(size)-1);
  2138. }
  2139. }
  2140. }
  2141. void Context::flushTextureUpdateBatch(CommandBuffer& _cmdbuf)
  2142. {
  2143. if (m_textureUpdateBatch.sort() )
  2144. {
  2145. const uint32_t pos = _cmdbuf.m_pos;
  2146. uint32_t currentKey = UINT32_MAX;
  2147. for (uint32_t ii = 0, num = m_textureUpdateBatch.m_num; ii < num; ++ii)
  2148. {
  2149. _cmdbuf.m_pos = m_textureUpdateBatch.m_values[ii];
  2150. TextureHandle handle;
  2151. _cmdbuf.read(handle);
  2152. uint8_t side;
  2153. _cmdbuf.read(side);
  2154. uint8_t mip;
  2155. _cmdbuf.read(mip);
  2156. Rect rect;
  2157. _cmdbuf.read(rect);
  2158. uint16_t zz;
  2159. _cmdbuf.read(zz);
  2160. uint16_t depth;
  2161. _cmdbuf.read(depth);
  2162. uint16_t pitch;
  2163. _cmdbuf.read(pitch);
  2164. const Memory* mem;
  2165. _cmdbuf.read(mem);
  2166. uint32_t key = m_textureUpdateBatch.m_keys[ii];
  2167. if (key != currentKey)
  2168. {
  2169. if (currentKey != UINT32_MAX)
  2170. {
  2171. m_renderCtx->updateTextureEnd();
  2172. }
  2173. currentKey = key;
  2174. m_renderCtx->updateTextureBegin(handle, side, mip);
  2175. }
  2176. m_renderCtx->updateTexture(handle, side, mip, rect, zz, depth, pitch, mem);
  2177. release(mem);
  2178. }
  2179. if (currentKey != UINT32_MAX)
  2180. {
  2181. m_renderCtx->updateTextureEnd();
  2182. }
  2183. m_textureUpdateBatch.reset();
  2184. _cmdbuf.m_pos = pos;
  2185. }
  2186. }
  2187. typedef RendererContextI* (*RendererCreateFn)(const Init& _init);
  2188. typedef void (*RendererDestroyFn)();
  2189. #define BGFX_RENDERER_CONTEXT(_namespace) \
  2190. namespace _namespace \
  2191. { \
  2192. extern RendererContextI* rendererCreate(const Init& _init); \
  2193. extern void rendererDestroy(); \
  2194. }
  2195. BGFX_RENDERER_CONTEXT(noop);
  2196. BGFX_RENDERER_CONTEXT(agc);
  2197. BGFX_RENDERER_CONTEXT(d3d9);
  2198. BGFX_RENDERER_CONTEXT(d3d11);
  2199. BGFX_RENDERER_CONTEXT(d3d12);
  2200. BGFX_RENDERER_CONTEXT(gnm);
  2201. BGFX_RENDERER_CONTEXT(mtl);
  2202. BGFX_RENDERER_CONTEXT(nvn);
  2203. BGFX_RENDERER_CONTEXT(gl);
  2204. BGFX_RENDERER_CONTEXT(vk);
  2205. BGFX_RENDERER_CONTEXT(webgpu);
  2206. #undef BGFX_RENDERER_CONTEXT
  2207. struct RendererCreator
  2208. {
  2209. RendererCreateFn createFn;
  2210. RendererDestroyFn destroyFn;
  2211. const char* name;
  2212. bool supported;
  2213. };
  2214. static RendererCreator s_rendererCreator[] =
  2215. {
  2216. { noop::rendererCreate, noop::rendererDestroy, BGFX_RENDERER_NOOP_NAME, true }, // Noop
  2217. { agc::rendererCreate, agc::rendererDestroy, BGFX_RENDERER_AGC_NAME, !!BGFX_CONFIG_RENDERER_AGC }, // GNM
  2218. { d3d9::rendererCreate, d3d9::rendererDestroy, BGFX_RENDERER_DIRECT3D9_NAME, !!BGFX_CONFIG_RENDERER_DIRECT3D9 }, // Direct3D9
  2219. { d3d11::rendererCreate, d3d11::rendererDestroy, BGFX_RENDERER_DIRECT3D11_NAME, !!BGFX_CONFIG_RENDERER_DIRECT3D11 }, // Direct3D11
  2220. { d3d12::rendererCreate, d3d12::rendererDestroy, BGFX_RENDERER_DIRECT3D12_NAME, !!BGFX_CONFIG_RENDERER_DIRECT3D12 }, // Direct3D12
  2221. { gnm::rendererCreate, gnm::rendererDestroy, BGFX_RENDERER_GNM_NAME, !!BGFX_CONFIG_RENDERER_GNM }, // GNM
  2222. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS
  2223. { mtl::rendererCreate, mtl::rendererDestroy, BGFX_RENDERER_METAL_NAME, !!BGFX_CONFIG_RENDERER_METAL }, // Metal
  2224. #else
  2225. { noop::rendererCreate, noop::rendererDestroy, BGFX_RENDERER_NOOP_NAME, false }, // Noop
  2226. #endif // BX_PLATFORM_OSX || BX_PLATFORM_IOS
  2227. { nvn::rendererCreate, nvn::rendererDestroy, BGFX_RENDERER_NVN_NAME, !!BGFX_CONFIG_RENDERER_NVN }, // NVN
  2228. { gl::rendererCreate, gl::rendererDestroy, BGFX_RENDERER_OPENGL_NAME, !!BGFX_CONFIG_RENDERER_OPENGLES }, // OpenGLES
  2229. { gl::rendererCreate, gl::rendererDestroy, BGFX_RENDERER_OPENGL_NAME, !!BGFX_CONFIG_RENDERER_OPENGL }, // OpenGL
  2230. { vk::rendererCreate, vk::rendererDestroy, BGFX_RENDERER_VULKAN_NAME, !!BGFX_CONFIG_RENDERER_VULKAN }, // Vulkan
  2231. { webgpu::rendererCreate, webgpu::rendererDestroy, BGFX_RENDERER_WEBGPU_NAME, !!BGFX_CONFIG_RENDERER_WEBGPU }, // WebGPU
  2232. };
  2233. BX_STATIC_ASSERT(BX_COUNTOF(s_rendererCreator) == RendererType::Count);
  2234. bool windowsVersionIs(Condition::Enum _op, uint32_t _version)
  2235. {
  2236. #if BX_PLATFORM_WINDOWS
  2237. static const uint8_t s_condition[] =
  2238. {
  2239. VER_LESS_EQUAL,
  2240. VER_GREATER_EQUAL,
  2241. };
  2242. OSVERSIONINFOEXA ovi;
  2243. bx::memSet(&ovi, 0, sizeof(ovi) );
  2244. ovi.dwOSVersionInfoSize = sizeof(ovi);
  2245. // _WIN32_WINNT_WINBLUE 0x0603
  2246. // _WIN32_WINNT_WIN8 0x0602
  2247. // _WIN32_WINNT_WIN7 0x0601
  2248. // _WIN32_WINNT_VISTA 0x0600
  2249. ovi.dwMajorVersion = HIBYTE(_version);
  2250. ovi.dwMinorVersion = LOBYTE(_version);
  2251. DWORDLONG cond = 0;
  2252. VER_SET_CONDITION(cond, VER_MAJORVERSION, s_condition[_op]);
  2253. VER_SET_CONDITION(cond, VER_MINORVERSION, s_condition[_op]);
  2254. return !!VerifyVersionInfoA(&ovi, VER_MAJORVERSION | VER_MINORVERSION, cond);
  2255. #else
  2256. BX_UNUSED(_op, _version);
  2257. return false;
  2258. #endif // BX_PLATFORM_WINDOWS
  2259. }
  2260. RendererContextI* rendererCreate(const Init& _init)
  2261. {
  2262. int32_t scores[RendererType::Count];
  2263. uint32_t numScores = 0;
  2264. for (uint32_t ii = 0; ii < RendererType::Count; ++ii)
  2265. {
  2266. RendererType::Enum renderer = RendererType::Enum(ii);
  2267. if (s_rendererCreator[ii].supported)
  2268. {
  2269. int32_t score = 0;
  2270. if (_init.type == renderer)
  2271. {
  2272. score += 1000;
  2273. }
  2274. score += RendererType::Noop != renderer ? 1 : 0;
  2275. if (BX_ENABLED(BX_PLATFORM_WINDOWS) )
  2276. {
  2277. if (windowsVersionIs(Condition::GreaterEqual, 0x0602) )
  2278. {
  2279. score += RendererType::Direct3D11 == renderer ? 20 : 0;
  2280. score += RendererType::Direct3D12 == renderer ? 10 : 0;
  2281. }
  2282. else if (windowsVersionIs(Condition::GreaterEqual, 0x0601) )
  2283. {
  2284. score += RendererType::Direct3D11 == renderer ? 20 : 0;
  2285. score += RendererType::Direct3D9 == renderer ? 10 : 0;
  2286. score += RendererType::Direct3D12 == renderer ? -100 : 0;
  2287. }
  2288. else
  2289. {
  2290. score += RendererType::Direct3D12 == renderer ? -100 : 0;
  2291. }
  2292. }
  2293. else if (BX_ENABLED(BX_PLATFORM_LINUX) )
  2294. {
  2295. score += RendererType::Vulkan == renderer ? 50 : 0;
  2296. score += RendererType::OpenGL == renderer ? 40 : 0;
  2297. score += RendererType::OpenGLES == renderer ? 30 : 0;
  2298. score += RendererType::Direct3D12 == renderer ? 20 : 0;
  2299. score += RendererType::Direct3D11 == renderer ? 10 : 0;
  2300. score += RendererType::Direct3D9 == renderer ? 5 : 0;
  2301. }
  2302. else if (BX_ENABLED(BX_PLATFORM_OSX) )
  2303. {
  2304. score += RendererType::Metal == renderer ? 20 : 0;
  2305. score += RendererType::OpenGL == renderer ? 10 : 0;
  2306. }
  2307. else if (BX_ENABLED(BX_PLATFORM_IOS) )
  2308. {
  2309. score += RendererType::Metal == renderer ? 20 : 0;
  2310. score += RendererType::OpenGLES == renderer ? 10 : 0;
  2311. }
  2312. else if (BX_ENABLED(0
  2313. || BX_PLATFORM_ANDROID
  2314. || BX_PLATFORM_EMSCRIPTEN
  2315. || BX_PLATFORM_RPI
  2316. ) )
  2317. {
  2318. score += RendererType::OpenGLES == renderer ? 20 : 0;
  2319. }
  2320. else if (BX_ENABLED(BX_PLATFORM_PS4) )
  2321. {
  2322. score += RendererType::Gnm == renderer ? 20 : 0;
  2323. }
  2324. else if (BX_ENABLED(0
  2325. || BX_PLATFORM_XBOXONE
  2326. || BX_PLATFORM_WINRT
  2327. ) )
  2328. {
  2329. score += RendererType::Direct3D12 == renderer ? 20 : 0;
  2330. score += RendererType::Direct3D11 == renderer ? 10 : 0;
  2331. }
  2332. scores[numScores++] = (score<<8) | uint8_t(renderer);
  2333. }
  2334. }
  2335. bx::quickSort(scores, numScores, bx::compareDescending<int32_t>);
  2336. RendererContextI* renderCtx = NULL;
  2337. for (uint32_t ii = 0; ii < numScores; ++ii)
  2338. {
  2339. RendererType::Enum renderer = RendererType::Enum(scores[ii] & 0xff);
  2340. renderCtx = s_rendererCreator[renderer].createFn(_init);
  2341. if (NULL != renderCtx)
  2342. {
  2343. break;
  2344. }
  2345. s_rendererCreator[renderer].supported = false;
  2346. }
  2347. return renderCtx;
  2348. }
  2349. void rendererDestroy(RendererContextI* _renderCtx)
  2350. {
  2351. if (NULL != _renderCtx)
  2352. {
  2353. s_rendererCreator[_renderCtx->getRendererType()].destroyFn();
  2354. }
  2355. }
  2356. void Context::rendererExecCommands(CommandBuffer& _cmdbuf)
  2357. {
  2358. _cmdbuf.reset();
  2359. bool end = false;
  2360. if (NULL == m_renderCtx)
  2361. {
  2362. uint8_t command;
  2363. _cmdbuf.read(command);
  2364. switch (command)
  2365. {
  2366. case CommandBuffer::RendererShutdownEnd:
  2367. m_exit = true;
  2368. return;
  2369. case CommandBuffer::End:
  2370. return;
  2371. default:
  2372. {
  2373. BX_ASSERT(CommandBuffer::RendererInit == command
  2374. , "RendererInit must be the first command in command buffer before initialization. Unexpected command %d?"
  2375. , command
  2376. );
  2377. BX_ASSERT(!m_rendererInitialized, "This shouldn't happen! Bad synchronization?");
  2378. Init init;
  2379. _cmdbuf.read(init);
  2380. m_renderCtx = rendererCreate(init);
  2381. m_rendererInitialized = NULL != m_renderCtx;
  2382. if (!m_rendererInitialized)
  2383. {
  2384. _cmdbuf.read(command);
  2385. BX_ASSERT(CommandBuffer::End == command, "Unexpected command %d?"
  2386. , command
  2387. );
  2388. return;
  2389. }
  2390. }
  2391. break;
  2392. }
  2393. }
  2394. do
  2395. {
  2396. uint8_t command;
  2397. _cmdbuf.read(command);
  2398. switch (command)
  2399. {
  2400. case CommandBuffer::RendererShutdownBegin:
  2401. {
  2402. BX_ASSERT(m_rendererInitialized, "This shouldn't happen! Bad synchronization?");
  2403. m_rendererInitialized = false;
  2404. }
  2405. break;
  2406. case CommandBuffer::RendererShutdownEnd:
  2407. {
  2408. BX_ASSERT(!m_rendererInitialized && !m_exit, "This shouldn't happen! Bad synchronization?");
  2409. rendererDestroy(m_renderCtx);
  2410. m_renderCtx = NULL;
  2411. m_exit = true;
  2412. }
  2413. BX_FALLTHROUGH;
  2414. case CommandBuffer::End:
  2415. end = true;
  2416. break;
  2417. case CommandBuffer::CreateIndexBuffer:
  2418. {
  2419. BGFX_PROFILER_SCOPE("CreateIndexBuffer", 0xff2040ff);
  2420. IndexBufferHandle handle;
  2421. _cmdbuf.read(handle);
  2422. const Memory* mem;
  2423. _cmdbuf.read(mem);
  2424. uint16_t flags;
  2425. _cmdbuf.read(flags);
  2426. m_renderCtx->createIndexBuffer(handle, mem, flags);
  2427. release(mem);
  2428. }
  2429. break;
  2430. case CommandBuffer::DestroyIndexBuffer:
  2431. {
  2432. BGFX_PROFILER_SCOPE("DestroyIndexBuffer", 0xff2040ff);
  2433. IndexBufferHandle handle;
  2434. _cmdbuf.read(handle);
  2435. m_renderCtx->destroyIndexBuffer(handle);
  2436. }
  2437. break;
  2438. case CommandBuffer::CreateVertexLayout:
  2439. {
  2440. BGFX_PROFILER_SCOPE("CreateVertexLayout", 0xff2040ff);
  2441. VertexLayoutHandle handle;
  2442. _cmdbuf.read(handle);
  2443. VertexLayout layout;
  2444. _cmdbuf.read(layout);
  2445. m_renderCtx->createVertexLayout(handle, layout);
  2446. }
  2447. break;
  2448. case CommandBuffer::DestroyVertexLayout:
  2449. {
  2450. BGFX_PROFILER_SCOPE("DestroyVertexLayout", 0xff2040ff);
  2451. VertexLayoutHandle handle;
  2452. _cmdbuf.read(handle);
  2453. m_renderCtx->destroyVertexLayout(handle);
  2454. }
  2455. break;
  2456. case CommandBuffer::CreateVertexBuffer:
  2457. {
  2458. BGFX_PROFILER_SCOPE("CreateVertexBuffer", 0xff2040ff);
  2459. VertexBufferHandle handle;
  2460. _cmdbuf.read(handle);
  2461. const Memory* mem;
  2462. _cmdbuf.read(mem);
  2463. VertexLayoutHandle layoutHandle;
  2464. _cmdbuf.read(layoutHandle);
  2465. uint16_t flags;
  2466. _cmdbuf.read(flags);
  2467. m_renderCtx->createVertexBuffer(handle, mem, layoutHandle, flags);
  2468. release(mem);
  2469. }
  2470. break;
  2471. case CommandBuffer::DestroyVertexBuffer:
  2472. {
  2473. BGFX_PROFILER_SCOPE("DestroyVertexBuffer", 0xff2040ff);
  2474. VertexBufferHandle handle;
  2475. _cmdbuf.read(handle);
  2476. m_renderCtx->destroyVertexBuffer(handle);
  2477. }
  2478. break;
  2479. case CommandBuffer::CreateDynamicIndexBuffer:
  2480. {
  2481. BGFX_PROFILER_SCOPE("CreateDynamicIndexBuffer", 0xff2040ff);
  2482. IndexBufferHandle handle;
  2483. _cmdbuf.read(handle);
  2484. uint32_t size;
  2485. _cmdbuf.read(size);
  2486. uint16_t flags;
  2487. _cmdbuf.read(flags);
  2488. m_renderCtx->createDynamicIndexBuffer(handle, size, flags);
  2489. }
  2490. break;
  2491. case CommandBuffer::UpdateDynamicIndexBuffer:
  2492. {
  2493. BGFX_PROFILER_SCOPE("UpdateDynamicIndexBuffer", 0xff2040ff);
  2494. IndexBufferHandle handle;
  2495. _cmdbuf.read(handle);
  2496. uint32_t offset;
  2497. _cmdbuf.read(offset);
  2498. uint32_t size;
  2499. _cmdbuf.read(size);
  2500. const Memory* mem;
  2501. _cmdbuf.read(mem);
  2502. m_renderCtx->updateDynamicIndexBuffer(handle, offset, size, mem);
  2503. release(mem);
  2504. }
  2505. break;
  2506. case CommandBuffer::DestroyDynamicIndexBuffer:
  2507. {
  2508. BGFX_PROFILER_SCOPE("DestroyDynamicIndexBuffer", 0xff2040ff);
  2509. IndexBufferHandle handle;
  2510. _cmdbuf.read(handle);
  2511. m_renderCtx->destroyDynamicIndexBuffer(handle);
  2512. }
  2513. break;
  2514. case CommandBuffer::CreateDynamicVertexBuffer:
  2515. {
  2516. BGFX_PROFILER_SCOPE("CreateDynamicVertexBuffer", 0xff2040ff);
  2517. VertexBufferHandle handle;
  2518. _cmdbuf.read(handle);
  2519. uint32_t size;
  2520. _cmdbuf.read(size);
  2521. uint16_t flags;
  2522. _cmdbuf.read(flags);
  2523. m_renderCtx->createDynamicVertexBuffer(handle, size, flags);
  2524. }
  2525. break;
  2526. case CommandBuffer::UpdateDynamicVertexBuffer:
  2527. {
  2528. BGFX_PROFILER_SCOPE("UpdateDynamicVertexBuffer", 0xff2040ff);
  2529. VertexBufferHandle handle;
  2530. _cmdbuf.read(handle);
  2531. uint32_t offset;
  2532. _cmdbuf.read(offset);
  2533. uint32_t size;
  2534. _cmdbuf.read(size);
  2535. const Memory* mem;
  2536. _cmdbuf.read(mem);
  2537. m_renderCtx->updateDynamicVertexBuffer(handle, offset, size, mem);
  2538. release(mem);
  2539. }
  2540. break;
  2541. case CommandBuffer::DestroyDynamicVertexBuffer:
  2542. {
  2543. BGFX_PROFILER_SCOPE("DestroyDynamicVertexBuffer", 0xff2040ff);
  2544. VertexBufferHandle handle;
  2545. _cmdbuf.read(handle);
  2546. m_renderCtx->destroyDynamicVertexBuffer(handle);
  2547. }
  2548. break;
  2549. case CommandBuffer::CreateShader:
  2550. {
  2551. BGFX_PROFILER_SCOPE("CreateShader", 0xff2040ff);
  2552. ShaderHandle handle;
  2553. _cmdbuf.read(handle);
  2554. const Memory* mem;
  2555. _cmdbuf.read(mem);
  2556. m_renderCtx->createShader(handle, mem);
  2557. release(mem);
  2558. }
  2559. break;
  2560. case CommandBuffer::DestroyShader:
  2561. {
  2562. BGFX_PROFILER_SCOPE("DestroyShader", 0xff2040ff);
  2563. ShaderHandle handle;
  2564. _cmdbuf.read(handle);
  2565. m_renderCtx->destroyShader(handle);
  2566. }
  2567. break;
  2568. case CommandBuffer::CreateProgram:
  2569. {
  2570. BGFX_PROFILER_SCOPE("CreateProgram", 0xff2040ff);
  2571. ProgramHandle handle;
  2572. _cmdbuf.read(handle);
  2573. ShaderHandle vsh;
  2574. _cmdbuf.read(vsh);
  2575. ShaderHandle fsh;
  2576. _cmdbuf.read(fsh);
  2577. m_renderCtx->createProgram(handle, vsh, fsh);
  2578. }
  2579. break;
  2580. case CommandBuffer::DestroyProgram:
  2581. {
  2582. BGFX_PROFILER_SCOPE("DestroyProgram", 0xff2040ff);
  2583. ProgramHandle handle;
  2584. _cmdbuf.read(handle);
  2585. m_renderCtx->destroyProgram(handle);
  2586. }
  2587. break;
  2588. case CommandBuffer::CreateTexture:
  2589. {
  2590. BGFX_PROFILER_SCOPE("CreateTexture", 0xff2040ff);
  2591. TextureHandle handle;
  2592. _cmdbuf.read(handle);
  2593. const Memory* mem;
  2594. _cmdbuf.read(mem);
  2595. uint64_t flags;
  2596. _cmdbuf.read(flags);
  2597. uint8_t skip;
  2598. _cmdbuf.read(skip);
  2599. void* ptr = m_renderCtx->createTexture(handle, mem, flags, skip);
  2600. if (NULL != ptr)
  2601. {
  2602. setDirectAccessPtr(handle, ptr);
  2603. }
  2604. bx::MemoryReader reader(mem->data, mem->size);
  2605. bx::Error err;
  2606. uint32_t magic;
  2607. bx::read(&reader, magic, &err);
  2608. if (BGFX_CHUNK_MAGIC_TEX == magic)
  2609. {
  2610. TextureCreate tc;
  2611. bx::read(&reader, tc, &err);
  2612. if (NULL != tc.m_mem)
  2613. {
  2614. release(tc.m_mem);
  2615. }
  2616. }
  2617. release(mem);
  2618. }
  2619. break;
  2620. case CommandBuffer::UpdateTexture:
  2621. {
  2622. BGFX_PROFILER_SCOPE("UpdateTexture", 0xff2040ff);
  2623. if (m_textureUpdateBatch.isFull() )
  2624. {
  2625. flushTextureUpdateBatch(_cmdbuf);
  2626. }
  2627. uint32_t value = _cmdbuf.m_pos;
  2628. TextureHandle handle;
  2629. _cmdbuf.read(handle);
  2630. uint8_t side;
  2631. _cmdbuf.read(side);
  2632. uint8_t mip;
  2633. _cmdbuf.read(mip);
  2634. _cmdbuf.skip<Rect>();
  2635. _cmdbuf.skip<uint16_t>();
  2636. _cmdbuf.skip<uint16_t>();
  2637. _cmdbuf.skip<uint16_t>();
  2638. _cmdbuf.skip<Memory*>();
  2639. uint32_t key = (handle.idx<<16)
  2640. | (side<<8)
  2641. | mip
  2642. ;
  2643. m_textureUpdateBatch.add(key, value);
  2644. }
  2645. break;
  2646. case CommandBuffer::ReadTexture:
  2647. {
  2648. BGFX_PROFILER_SCOPE("ReadTexture", 0xff2040ff);
  2649. TextureHandle handle;
  2650. _cmdbuf.read(handle);
  2651. void* data;
  2652. _cmdbuf.read(data);
  2653. uint8_t mip;
  2654. _cmdbuf.read(mip);
  2655. m_renderCtx->readTexture(handle, data, mip);
  2656. }
  2657. break;
  2658. case CommandBuffer::ResizeTexture:
  2659. {
  2660. BGFX_PROFILER_SCOPE("ResizeTexture", 0xff2040ff);
  2661. TextureHandle handle;
  2662. _cmdbuf.read(handle);
  2663. uint16_t width;
  2664. _cmdbuf.read(width);
  2665. uint16_t height;
  2666. _cmdbuf.read(height);
  2667. uint8_t numMips;
  2668. _cmdbuf.read(numMips);
  2669. uint16_t numLayers;
  2670. _cmdbuf.read(numLayers);
  2671. m_renderCtx->resizeTexture(handle, width, height, numMips, numLayers);
  2672. }
  2673. break;
  2674. case CommandBuffer::DestroyTexture:
  2675. {
  2676. BGFX_PROFILER_SCOPE("DestroyTexture", 0xff2040ff);
  2677. TextureHandle handle;
  2678. _cmdbuf.read(handle);
  2679. m_renderCtx->destroyTexture(handle);
  2680. }
  2681. break;
  2682. case CommandBuffer::CreateFrameBuffer:
  2683. {
  2684. BGFX_PROFILER_SCOPE("CreateFrameBuffer", 0xff2040ff);
  2685. FrameBufferHandle handle;
  2686. _cmdbuf.read(handle);
  2687. bool window;
  2688. _cmdbuf.read(window);
  2689. if (window)
  2690. {
  2691. void* nwh;
  2692. _cmdbuf.read(nwh);
  2693. uint16_t width;
  2694. _cmdbuf.read(width);
  2695. uint16_t height;
  2696. _cmdbuf.read(height);
  2697. TextureFormat::Enum format;
  2698. _cmdbuf.read(format);
  2699. TextureFormat::Enum depthFormat;
  2700. _cmdbuf.read(depthFormat);
  2701. m_renderCtx->createFrameBuffer(handle, nwh, width, height, format, depthFormat);
  2702. }
  2703. else
  2704. {
  2705. uint8_t num;
  2706. _cmdbuf.read(num);
  2707. Attachment attachment[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  2708. _cmdbuf.read(attachment, sizeof(Attachment) * num);
  2709. m_renderCtx->createFrameBuffer(handle, num, attachment);
  2710. }
  2711. }
  2712. break;
  2713. case CommandBuffer::DestroyFrameBuffer:
  2714. {
  2715. BGFX_PROFILER_SCOPE("DestroyFrameBuffer", 0xff2040ff);
  2716. FrameBufferHandle handle;
  2717. _cmdbuf.read(handle);
  2718. m_renderCtx->destroyFrameBuffer(handle);
  2719. }
  2720. break;
  2721. case CommandBuffer::CreateUniform:
  2722. {
  2723. BGFX_PROFILER_SCOPE("CreateUniform", 0xff2040ff);
  2724. UniformHandle handle;
  2725. _cmdbuf.read(handle);
  2726. UniformType::Enum type;
  2727. _cmdbuf.read(type);
  2728. uint16_t num;
  2729. _cmdbuf.read(num);
  2730. uint8_t len;
  2731. _cmdbuf.read(len);
  2732. const char* name = (const char*)_cmdbuf.skip(len);
  2733. m_renderCtx->createUniform(handle, type, num, name);
  2734. }
  2735. break;
  2736. case CommandBuffer::DestroyUniform:
  2737. {
  2738. BGFX_PROFILER_SCOPE("DestroyUniform", 0xff2040ff);
  2739. UniformHandle handle;
  2740. _cmdbuf.read(handle);
  2741. m_renderCtx->destroyUniform(handle);
  2742. }
  2743. break;
  2744. case CommandBuffer::UpdateViewName:
  2745. {
  2746. BGFX_PROFILER_SCOPE("UpdateViewName", 0xff2040ff);
  2747. ViewId id;
  2748. _cmdbuf.read(id);
  2749. uint16_t len;
  2750. _cmdbuf.read(len);
  2751. const char* name = (const char*)_cmdbuf.skip(len);
  2752. m_renderCtx->updateViewName(id, name);
  2753. }
  2754. break;
  2755. case CommandBuffer::InvalidateOcclusionQuery:
  2756. {
  2757. BGFX_PROFILER_SCOPE("InvalidateOcclusionQuery", 0xff2040ff);
  2758. OcclusionQueryHandle handle;
  2759. _cmdbuf.read(handle);
  2760. m_renderCtx->invalidateOcclusionQuery(handle);
  2761. }
  2762. break;
  2763. case CommandBuffer::SetName:
  2764. {
  2765. BGFX_PROFILER_SCOPE("SetName", 0xff2040ff);
  2766. Handle handle;
  2767. _cmdbuf.read(handle);
  2768. uint16_t len;
  2769. _cmdbuf.read(len);
  2770. const char* name = (const char*)_cmdbuf.skip(len);
  2771. m_renderCtx->setName(handle, name, len-1);
  2772. }
  2773. break;
  2774. default:
  2775. BX_ASSERT(false, "Invalid command: %d", command);
  2776. break;
  2777. }
  2778. } while (!end);
  2779. flushTextureUpdateBatch(_cmdbuf);
  2780. }
  2781. uint32_t weldVertices(void* _output, const VertexLayout& _layout, const void* _data, uint32_t _num, bool _index32, float _epsilon)
  2782. {
  2783. return weldVertices(_output, _layout, _data, _num, _index32, _epsilon, g_allocator);
  2784. }
  2785. uint32_t topologyConvert(TopologyConvert::Enum _conversion, void* _dst, uint32_t _dstSize, const void* _indices, uint32_t _numIndices, bool _index32)
  2786. {
  2787. return topologyConvert(_conversion, _dst, _dstSize, _indices, _numIndices, _index32, g_allocator);
  2788. }
  2789. void topologySortTriList(TopologySort::Enum _sort, void* _dst, uint32_t _dstSize, const float _dir[3], const float _pos[3], const void* _vertices, uint32_t _stride, const void* _indices, uint32_t _numIndices, bool _index32)
  2790. {
  2791. topologySortTriList(_sort, _dst, _dstSize, _dir, _pos, _vertices, _stride, _indices, _numIndices, _index32, g_allocator);
  2792. }
  2793. uint8_t getSupportedRenderers(uint8_t _max, RendererType::Enum* _enum)
  2794. {
  2795. _enum = _max == 0 ? NULL : _enum;
  2796. uint8_t num = 0;
  2797. for (uint8_t ii = 0; ii < RendererType::Count; ++ii)
  2798. {
  2799. if ( (RendererType::Direct3D11 == ii || RendererType::Direct3D12 == ii)
  2800. && windowsVersionIs(Condition::LessEqual, 0x0502) )
  2801. {
  2802. continue;
  2803. }
  2804. if (NULL == _enum)
  2805. {
  2806. num++;
  2807. }
  2808. else
  2809. {
  2810. if (num < _max
  2811. && s_rendererCreator[ii].supported)
  2812. {
  2813. _enum[num++] = RendererType::Enum(ii);
  2814. }
  2815. }
  2816. }
  2817. return num;
  2818. }
  2819. const char* getRendererName(RendererType::Enum _type)
  2820. {
  2821. BX_ASSERT(_type < RendererType::Count, "Invalid renderer type %d.", _type);
  2822. return s_rendererCreator[_type].name;
  2823. }
  2824. PlatformData::PlatformData()
  2825. : ndt(NULL)
  2826. , nwh(NULL)
  2827. , context(NULL)
  2828. , backBuffer(NULL)
  2829. , backBufferDS(NULL)
  2830. {
  2831. }
  2832. Resolution::Resolution()
  2833. : format(TextureFormat::RGBA8)
  2834. , width(1280)
  2835. , height(720)
  2836. , reset(BGFX_RESET_NONE)
  2837. , numBackBuffers(2)
  2838. , maxFrameLatency(0)
  2839. {
  2840. }
  2841. Init::Limits::Limits()
  2842. : maxEncoders(BGFX_CONFIG_DEFAULT_MAX_ENCODERS)
  2843. , minResourceCbSize(BGFX_CONFIG_MIN_RESOURCE_COMMAND_BUFFER_SIZE)
  2844. , transientVbSize(BGFX_CONFIG_TRANSIENT_VERTEX_BUFFER_SIZE)
  2845. , transientIbSize(BGFX_CONFIG_TRANSIENT_INDEX_BUFFER_SIZE)
  2846. {
  2847. }
  2848. Init::Init()
  2849. : type(RendererType::Count)
  2850. , vendorId(BGFX_PCI_ID_NONE)
  2851. , deviceId(0)
  2852. , capabilities(UINT64_MAX)
  2853. , debug(BX_ENABLED(BGFX_CONFIG_DEBUG) )
  2854. , profile(BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  2855. , callback(NULL)
  2856. , allocator(NULL)
  2857. {
  2858. }
  2859. void Attachment::init(TextureHandle _handle, Access::Enum _access, uint16_t _layer, uint16_t _numLayers, uint16_t _mip, uint8_t _resolve)
  2860. {
  2861. access = _access;
  2862. handle = _handle;
  2863. mip = _mip;
  2864. layer = _layer;
  2865. numLayers = _numLayers;
  2866. resolve = _resolve;
  2867. }
  2868. bool init(const Init& _userInit)
  2869. {
  2870. if (NULL != s_ctx)
  2871. {
  2872. BX_TRACE("bgfx is already initialized.");
  2873. return false;
  2874. }
  2875. Init init = _userInit;
  2876. init.limits.maxEncoders = bx::clamp<uint16_t>(init.limits.maxEncoders, 1, (0 != BGFX_CONFIG_MULTITHREADED) ? 128 : 1);
  2877. init.limits.minResourceCbSize = bx::min<uint32_t>(init.limits.minResourceCbSize, BGFX_CONFIG_MIN_RESOURCE_COMMAND_BUFFER_SIZE);
  2878. struct ErrorState
  2879. {
  2880. enum Enum
  2881. {
  2882. Default,
  2883. ContextAllocated,
  2884. };
  2885. };
  2886. ErrorState::Enum errorState = ErrorState::Default;
  2887. if (NULL != init.allocator)
  2888. {
  2889. g_allocator = init.allocator;
  2890. }
  2891. else
  2892. {
  2893. bx::DefaultAllocator allocator;
  2894. g_allocator =
  2895. s_allocatorStub = BX_NEW(&allocator, AllocatorStub);
  2896. }
  2897. if (NULL != init.callback)
  2898. {
  2899. g_callback = init.callback;
  2900. }
  2901. else
  2902. {
  2903. g_callback =
  2904. s_callbackStub = BX_NEW(g_allocator, CallbackStub);
  2905. }
  2906. bx::memSet(&g_caps, 0, sizeof(g_caps) );
  2907. g_caps.limits.maxDrawCalls = BGFX_CONFIG_MAX_DRAW_CALLS;
  2908. g_caps.limits.maxBlits = BGFX_CONFIG_MAX_BLIT_ITEMS;
  2909. g_caps.limits.maxTextureSize = 0;
  2910. g_caps.limits.maxTextureLayers = 1;
  2911. g_caps.limits.maxViews = BGFX_CONFIG_MAX_VIEWS;
  2912. g_caps.limits.maxFrameBuffers = BGFX_CONFIG_MAX_FRAME_BUFFERS;
  2913. g_caps.limits.maxPrograms = BGFX_CONFIG_MAX_PROGRAMS;
  2914. g_caps.limits.maxShaders = BGFX_CONFIG_MAX_SHADERS;
  2915. g_caps.limits.maxTextures = BGFX_CONFIG_MAX_TEXTURES;
  2916. g_caps.limits.maxTextureSamplers = BGFX_CONFIG_MAX_TEXTURE_SAMPLERS;
  2917. g_caps.limits.maxComputeBindings = 0;
  2918. g_caps.limits.maxVertexLayouts = BGFX_CONFIG_MAX_VERTEX_LAYOUTS;
  2919. g_caps.limits.maxVertexStreams = 1;
  2920. g_caps.limits.maxIndexBuffers = BGFX_CONFIG_MAX_INDEX_BUFFERS;
  2921. g_caps.limits.maxVertexBuffers = BGFX_CONFIG_MAX_VERTEX_BUFFERS;
  2922. g_caps.limits.maxDynamicIndexBuffers = BGFX_CONFIG_MAX_DYNAMIC_INDEX_BUFFERS;
  2923. g_caps.limits.maxDynamicVertexBuffers = BGFX_CONFIG_MAX_DYNAMIC_VERTEX_BUFFERS;
  2924. g_caps.limits.maxUniforms = BGFX_CONFIG_MAX_UNIFORMS;
  2925. g_caps.limits.maxOcclusionQueries = BGFX_CONFIG_MAX_OCCLUSION_QUERIES;
  2926. g_caps.limits.maxFBAttachments = 1;
  2927. g_caps.limits.maxEncoders = init.limits.maxEncoders;
  2928. g_caps.limits.minResourceCbSize = init.limits.minResourceCbSize;
  2929. g_caps.limits.transientVbSize = init.limits.transientVbSize;
  2930. g_caps.limits.transientIbSize = init.limits.transientIbSize;
  2931. g_caps.vendorId = init.vendorId;
  2932. g_caps.deviceId = init.deviceId;
  2933. BX_TRACE("Init...");
  2934. // bgfx 1.104.7082
  2935. // ^ ^^^ ^^^^
  2936. // | | +--- Commit number (https://github.com/bkaradzic/bgfx / git rev-list --count HEAD)
  2937. // | +------- API version (from https://github.com/bkaradzic/bgfx/blob/master/scripts/bgfx.idl#L4)
  2938. // +--------- Major revision (always 1)
  2939. BX_TRACE("Version 1.%d.%d (commit: " BGFX_REV_SHA1 ")", BGFX_API_VERSION, BGFX_REV_NUMBER);
  2940. errorState = ErrorState::ContextAllocated;
  2941. s_ctx = BX_ALIGNED_NEW(g_allocator, Context, Context::kAlignment);
  2942. if (s_ctx->init(init) )
  2943. {
  2944. BX_TRACE("Init complete.");
  2945. return true;
  2946. }
  2947. BX_TRACE("Init failed.");
  2948. switch (errorState)
  2949. {
  2950. case ErrorState::ContextAllocated:
  2951. BX_ALIGNED_DELETE(g_allocator, s_ctx, Context::kAlignment);
  2952. s_ctx = NULL;
  2953. BX_FALLTHROUGH;
  2954. case ErrorState::Default:
  2955. if (NULL != s_callbackStub)
  2956. {
  2957. BX_DELETE(g_allocator, s_callbackStub);
  2958. s_callbackStub = NULL;
  2959. }
  2960. if (NULL != s_allocatorStub)
  2961. {
  2962. bx::DefaultAllocator allocator;
  2963. BX_DELETE(&allocator, s_allocatorStub);
  2964. s_allocatorStub = NULL;
  2965. }
  2966. s_threadIndex = 0;
  2967. g_callback = NULL;
  2968. g_allocator = NULL;
  2969. break;
  2970. }
  2971. return false;
  2972. }
  2973. void shutdown()
  2974. {
  2975. BX_TRACE("Shutdown...");
  2976. BGFX_CHECK_API_THREAD();
  2977. Context* ctx = s_ctx; // it's going to be NULLd inside shutdown.
  2978. ctx->shutdown();
  2979. BX_ASSERT(NULL == s_ctx, "bgfx is should be uninitialized here.");
  2980. BX_ALIGNED_DELETE(g_allocator, ctx, Context::kAlignment);
  2981. BX_TRACE("Shutdown complete.");
  2982. if (NULL != s_allocatorStub)
  2983. {
  2984. s_allocatorStub->checkLeaks();
  2985. }
  2986. if (NULL != s_callbackStub)
  2987. {
  2988. BX_DELETE(g_allocator, s_callbackStub);
  2989. s_callbackStub = NULL;
  2990. }
  2991. if (NULL != s_allocatorStub)
  2992. {
  2993. bx::DefaultAllocator allocator;
  2994. BX_DELETE(&allocator, s_allocatorStub);
  2995. s_allocatorStub = NULL;
  2996. }
  2997. s_threadIndex = 0;
  2998. g_callback = NULL;
  2999. g_allocator = NULL;
  3000. }
  3001. void reset(uint32_t _width, uint32_t _height, uint32_t _flags, TextureFormat::Enum _format)
  3002. {
  3003. BGFX_CHECK_API_THREAD();
  3004. BX_ASSERT(0 == (_flags&BGFX_RESET_RESERVED_MASK), "Do not set reset reserved flags!");
  3005. s_ctx->reset(_width, _height, _flags, _format);
  3006. }
  3007. Encoder* begin(bool _forThread)
  3008. {
  3009. return s_ctx->begin(_forThread);
  3010. }
  3011. #define BGFX_ENCODER(_func) reinterpret_cast<EncoderImpl*>(this)->_func
  3012. void Encoder::setMarker(const char* _marker)
  3013. {
  3014. BGFX_ENCODER(setMarker(_marker) );
  3015. }
  3016. void Encoder::setState(uint64_t _state, uint32_t _rgba)
  3017. {
  3018. BX_ASSERT(0 == (_state&BGFX_STATE_RESERVED_MASK), "Do not set state reserved flags!");
  3019. BGFX_ENCODER(setState(_state, _rgba) );
  3020. }
  3021. void Encoder::setCondition(OcclusionQueryHandle _handle, bool _visible)
  3022. {
  3023. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  3024. BGFX_ENCODER(setCondition(_handle, _visible) );
  3025. }
  3026. void Encoder::setStencil(uint32_t _fstencil, uint32_t _bstencil)
  3027. {
  3028. BGFX_ENCODER(setStencil(_fstencil, _bstencil) );
  3029. }
  3030. uint16_t Encoder::setScissor(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  3031. {
  3032. return BGFX_ENCODER(setScissor(_x, _y, _width, _height) );
  3033. }
  3034. void Encoder::setScissor(uint16_t _cache)
  3035. {
  3036. BGFX_ENCODER(setScissor(_cache) );
  3037. }
  3038. uint32_t Encoder::setTransform(const void* _mtx, uint16_t _num)
  3039. {
  3040. return BGFX_ENCODER(setTransform(_mtx, _num) );
  3041. }
  3042. uint32_t Encoder::allocTransform(Transform* _transform, uint16_t _num)
  3043. {
  3044. return BGFX_ENCODER(allocTransform(_transform, _num) );
  3045. }
  3046. void Encoder::setTransform(uint32_t _cache, uint16_t _num)
  3047. {
  3048. BGFX_ENCODER(setTransform(_cache, _num) );
  3049. }
  3050. void Encoder::setUniform(UniformHandle _handle, const void* _value, uint16_t _num)
  3051. {
  3052. BGFX_CHECK_HANDLE("setUniform", s_ctx->m_uniformHandle, _handle);
  3053. const UniformRef& uniform = s_ctx->m_uniformRef[_handle.idx];
  3054. BX_ASSERT(isValid(_handle) && 0 < uniform.m_refCount, "Setting invalid uniform (handle %3d)!", _handle.idx);
  3055. BX_ASSERT(_num == UINT16_MAX || uniform.m_num >= _num, "Truncated uniform update. %d (max: %d)", _num, uniform.m_num);
  3056. BGFX_ENCODER(setUniform(uniform.m_type, _handle, _value, UINT16_MAX != _num ? _num : uniform.m_num) );
  3057. }
  3058. void Encoder::setIndexBuffer(IndexBufferHandle _handle)
  3059. {
  3060. setIndexBuffer(_handle, 0, UINT32_MAX);
  3061. }
  3062. void Encoder::setIndexBuffer(IndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  3063. {
  3064. BGFX_CHECK_HANDLE("setIndexBuffer", s_ctx->m_indexBufferHandle, _handle);
  3065. const IndexBuffer& ib = s_ctx->m_indexBuffers[_handle.idx];
  3066. BGFX_ENCODER(setIndexBuffer(_handle, ib, _firstIndex, _numIndices) );
  3067. }
  3068. void Encoder::setIndexBuffer(DynamicIndexBufferHandle _handle)
  3069. {
  3070. setIndexBuffer(_handle, 0, UINT32_MAX);
  3071. }
  3072. void Encoder::setIndexBuffer(DynamicIndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  3073. {
  3074. BGFX_CHECK_HANDLE("setIndexBuffer", s_ctx->m_dynamicIndexBufferHandle, _handle);
  3075. const DynamicIndexBuffer& dib = s_ctx->m_dynamicIndexBuffers[_handle.idx];
  3076. BGFX_ENCODER(setIndexBuffer(dib, _firstIndex, _numIndices) );
  3077. }
  3078. void Encoder::setIndexBuffer(const TransientIndexBuffer* _tib)
  3079. {
  3080. setIndexBuffer(_tib, 0, UINT32_MAX);
  3081. }
  3082. void Encoder::setIndexBuffer(const TransientIndexBuffer* _tib, uint32_t _firstIndex, uint32_t _numIndices)
  3083. {
  3084. BX_ASSERT(NULL != _tib, "_tib can't be NULL");
  3085. BGFX_CHECK_HANDLE("setIndexBuffer", s_ctx->m_indexBufferHandle, _tib->handle);
  3086. BGFX_ENCODER(setIndexBuffer(_tib, _firstIndex, _numIndices) );
  3087. }
  3088. void Encoder::setVertexBuffer(
  3089. uint8_t _stream
  3090. , VertexBufferHandle _handle
  3091. , uint32_t _startVertex
  3092. , uint32_t _numVertices
  3093. , VertexLayoutHandle _layoutHandle
  3094. )
  3095. {
  3096. BGFX_CHECK_HANDLE("setVertexBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3097. BGFX_CHECK_HANDLE_INVALID_OK("setVertexBuffer", s_ctx->m_layoutHandle, _layoutHandle);
  3098. BGFX_ENCODER(setVertexBuffer(_stream, _handle, _startVertex, _numVertices, _layoutHandle) );
  3099. }
  3100. void Encoder::setVertexBuffer(uint8_t _stream, VertexBufferHandle _handle)
  3101. {
  3102. setVertexBuffer(_stream, _handle, 0, UINT32_MAX);
  3103. }
  3104. void Encoder::setVertexBuffer(
  3105. uint8_t _stream
  3106. , DynamicVertexBufferHandle _handle
  3107. , uint32_t _startVertex
  3108. , uint32_t _numVertices
  3109. , VertexLayoutHandle _layoutHandle
  3110. )
  3111. {
  3112. BGFX_CHECK_HANDLE("setVertexBuffer", s_ctx->m_dynamicVertexBufferHandle, _handle);
  3113. BGFX_CHECK_HANDLE_INVALID_OK("setVertexBuffer", s_ctx->m_layoutHandle, _layoutHandle);
  3114. const DynamicVertexBuffer& dvb = s_ctx->m_dynamicVertexBuffers[_handle.idx];
  3115. BGFX_ENCODER(setVertexBuffer(_stream, dvb, _startVertex, _numVertices, _layoutHandle) );
  3116. }
  3117. void Encoder::setVertexBuffer(uint8_t _stream, DynamicVertexBufferHandle _handle)
  3118. {
  3119. setVertexBuffer(_stream, _handle, 0, UINT32_MAX);
  3120. }
  3121. void Encoder::setVertexBuffer(
  3122. uint8_t _stream
  3123. , const TransientVertexBuffer* _tvb
  3124. , uint32_t _startVertex
  3125. , uint32_t _numVertices
  3126. , VertexLayoutHandle _layoutHandle
  3127. )
  3128. {
  3129. BX_ASSERT(NULL != _tvb, "_tvb can't be NULL");
  3130. BGFX_CHECK_HANDLE("setVertexBuffer", s_ctx->m_vertexBufferHandle, _tvb->handle);
  3131. BGFX_CHECK_HANDLE_INVALID_OK("setVertexBuffer", s_ctx->m_layoutHandle, _layoutHandle);
  3132. BGFX_ENCODER(setVertexBuffer(_stream, _tvb, _startVertex, _numVertices, _layoutHandle) );
  3133. }
  3134. void Encoder::setVertexBuffer(uint8_t _stream, const TransientVertexBuffer* _tvb)
  3135. {
  3136. setVertexBuffer(_stream, _tvb, 0, UINT32_MAX);
  3137. }
  3138. void Encoder::setVertexCount(uint32_t _numVertices)
  3139. {
  3140. BGFX_CHECK_CAPS(BGFX_CAPS_VERTEX_ID, "Auto generated vertices are not supported!");
  3141. BGFX_ENCODER(setVertexCount(_numVertices) );
  3142. }
  3143. void Encoder::setInstanceDataBuffer(const InstanceDataBuffer* _idb)
  3144. {
  3145. setInstanceDataBuffer(_idb, 0, UINT32_MAX);
  3146. }
  3147. void Encoder::setInstanceDataBuffer(const InstanceDataBuffer* _idb, uint32_t _start, uint32_t _num)
  3148. {
  3149. BX_ASSERT(NULL != _idb, "_idb can't be NULL");
  3150. BGFX_ENCODER(setInstanceDataBuffer(_idb, _start, _num) );
  3151. }
  3152. void Encoder::setInstanceDataBuffer(VertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  3153. {
  3154. BGFX_CHECK_HANDLE("setInstanceDataBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3155. const VertexBuffer& vb = s_ctx->m_vertexBuffers[_handle.idx];
  3156. BGFX_ENCODER(setInstanceDataBuffer(_handle, _startVertex, _num, vb.m_stride) );
  3157. }
  3158. void Encoder::setInstanceDataBuffer(DynamicVertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  3159. {
  3160. BGFX_CHECK_HANDLE("setInstanceDataBuffer", s_ctx->m_dynamicVertexBufferHandle, _handle);
  3161. const DynamicVertexBuffer& dvb = s_ctx->m_dynamicVertexBuffers[_handle.idx];
  3162. BGFX_ENCODER(setInstanceDataBuffer(dvb.m_handle
  3163. , dvb.m_startVertex + _startVertex
  3164. , _num
  3165. , dvb.m_stride
  3166. ) );
  3167. }
  3168. void Encoder::setInstanceCount(uint32_t _numInstances)
  3169. {
  3170. BGFX_CHECK_CAPS(BGFX_CAPS_VERTEX_ID, "Auto generated instances are not supported!");
  3171. BGFX_ENCODER(setInstanceCount(_numInstances) );
  3172. }
  3173. void Encoder::setTexture(uint8_t _stage, UniformHandle _sampler, TextureHandle _handle, uint32_t _flags)
  3174. {
  3175. BGFX_CHECK_HANDLE("setTexture/UniformHandle", s_ctx->m_uniformHandle, _sampler);
  3176. BGFX_CHECK_HANDLE_INVALID_OK("setTexture/TextureHandle", s_ctx->m_textureHandle, _handle);
  3177. BX_ASSERT(_stage < g_caps.limits.maxTextureSamplers, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxTextureSamplers);
  3178. if (isValid(_handle) )
  3179. {
  3180. const TextureRef& ref = s_ctx->m_textureRef[_handle.idx];
  3181. BX_ASSERT(!ref.isReadBack()
  3182. , "Can't sample from texture which was created with BGFX_TEXTURE_READ_BACK. This is CPU only texture."
  3183. );
  3184. BX_UNUSED(ref);
  3185. }
  3186. BGFX_ENCODER(setTexture(_stage, _sampler, _handle, _flags) );
  3187. }
  3188. void Encoder::touch(ViewId _id)
  3189. {
  3190. discard();
  3191. submit(_id, BGFX_INVALID_HANDLE);
  3192. }
  3193. void Encoder::submit(ViewId _id, ProgramHandle _program, uint32_t _depth, uint8_t _flags)
  3194. {
  3195. OcclusionQueryHandle handle = BGFX_INVALID_HANDLE;
  3196. submit(_id, _program, handle, _depth, _flags);
  3197. }
  3198. void Encoder::submit(ViewId _id, ProgramHandle _program, OcclusionQueryHandle _occlusionQuery, uint32_t _depth, uint8_t _flags)
  3199. {
  3200. BX_ASSERT(false
  3201. || !isValid(_occlusionQuery)
  3202. || 0 != (g_caps.supported & BGFX_CAPS_OCCLUSION_QUERY)
  3203. , "Occlusion query is not supported! Use bgfx::getCaps to check BGFX_CAPS_OCCLUSION_QUERY backend renderer capabilities."
  3204. );
  3205. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_programHandle, _program);
  3206. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_occlusionQueryHandle, _occlusionQuery);
  3207. BGFX_ENCODER(submit(_id, _program, _occlusionQuery, _depth, _flags) );
  3208. }
  3209. void Encoder::submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint16_t _start, uint16_t _num, uint32_t _depth, uint8_t _flags)
  3210. {
  3211. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_programHandle, _program);
  3212. BGFX_CHECK_HANDLE("submit", s_ctx->m_vertexBufferHandle, _indirectHandle);
  3213. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT, "Draw indirect is not supported!");
  3214. BGFX_ENCODER(submit(_id, _program, _indirectHandle, _start, _num, _depth, _flags) );
  3215. }
  3216. void Encoder::submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint16_t _start, IndexBufferHandle _numHandle, uint32_t _numIndex, uint16_t _numMax, uint32_t _depth, uint8_t _flags)
  3217. {
  3218. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_programHandle, _program);
  3219. BGFX_CHECK_HANDLE("submit", s_ctx->m_vertexBufferHandle, _indirectHandle);
  3220. BGFX_CHECK_HANDLE("submit", s_ctx->m_indexBufferHandle, _numHandle);
  3221. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT, "Draw indirect is not supported!");
  3222. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT_COUNT, "Draw indirect count is not supported!");
  3223. BGFX_ENCODER(submit(_id, _program, _indirectHandle, _start, _numHandle, _numIndex, _numMax, _depth, _flags) );
  3224. }
  3225. void Encoder::setBuffer(uint8_t _stage, IndexBufferHandle _handle, Access::Enum _access)
  3226. {
  3227. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3228. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_indexBufferHandle, _handle);
  3229. BGFX_ENCODER(setBuffer(_stage, _handle, _access) );
  3230. }
  3231. void Encoder::setBuffer(uint8_t _stage, VertexBufferHandle _handle, Access::Enum _access)
  3232. {
  3233. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3234. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3235. BGFX_ENCODER(setBuffer(_stage, _handle, _access) );
  3236. }
  3237. void Encoder::setBuffer(uint8_t _stage, DynamicIndexBufferHandle _handle, Access::Enum _access)
  3238. {
  3239. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3240. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_dynamicIndexBufferHandle, _handle);
  3241. const DynamicIndexBuffer& dib = s_ctx->m_dynamicIndexBuffers[_handle.idx];
  3242. BGFX_ENCODER(setBuffer(_stage, dib.m_handle, _access) );
  3243. }
  3244. void Encoder::setBuffer(uint8_t _stage, DynamicVertexBufferHandle _handle, Access::Enum _access)
  3245. {
  3246. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3247. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_dynamicVertexBufferHandle, _handle);
  3248. const DynamicVertexBuffer& dvb = s_ctx->m_dynamicVertexBuffers[_handle.idx];
  3249. BGFX_ENCODER(setBuffer(_stage, dvb.m_handle, _access) );
  3250. }
  3251. void Encoder::setBuffer(uint8_t _stage, IndirectBufferHandle _handle, Access::Enum _access)
  3252. {
  3253. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3254. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3255. VertexBufferHandle handle = { _handle.idx };
  3256. BGFX_ENCODER(setBuffer(_stage, handle, _access) );
  3257. }
  3258. void Encoder::setImage(uint8_t _stage, TextureHandle _handle, uint8_t _mip, Access::Enum _access, TextureFormat::Enum _format)
  3259. {
  3260. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3261. BGFX_CHECK_HANDLE_INVALID_OK("setImage/TextureHandle", s_ctx->m_textureHandle, _handle);
  3262. _format = TextureFormat::Count == _format
  3263. ? TextureFormat::Enum(s_ctx->m_textureRef[_handle.idx].m_format)
  3264. : _format
  3265. ;
  3266. BX_ASSERT(_format != TextureFormat::BGRA8
  3267. , "Can't use TextureFormat::BGRA8 with compute, use TextureFormat::RGBA8 instead."
  3268. );
  3269. if (isValid(_handle) )
  3270. {
  3271. const TextureRef& ref = s_ctx->m_textureRef[_handle.idx];
  3272. BX_ASSERT(!ref.isReadBack()
  3273. , "Can't texture (handle %d, '%S') which was created with BGFX_TEXTURE_READ_BACK with compute. This is CPU only texture."
  3274. , _handle.idx
  3275. , &ref.m_name
  3276. );
  3277. BX_UNUSED(ref);
  3278. }
  3279. BGFX_ENCODER(setImage(_stage, _handle, _mip, _access, _format) );
  3280. }
  3281. void Encoder::dispatch(ViewId _id, ProgramHandle _program, uint32_t _numX, uint32_t _numY, uint32_t _numZ, uint8_t _flags)
  3282. {
  3283. BGFX_CHECK_CAPS(BGFX_CAPS_COMPUTE, "Compute is not supported!");
  3284. BGFX_CHECK_HANDLE_INVALID_OK("dispatch", s_ctx->m_programHandle, _program);
  3285. BGFX_ENCODER(dispatch(_id, _program, _numX, _numY, _numZ, _flags) );
  3286. }
  3287. void Encoder::dispatch(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint16_t _start, uint16_t _num, uint8_t _flags)
  3288. {
  3289. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT, "Dispatch indirect is not supported!");
  3290. BGFX_CHECK_CAPS(BGFX_CAPS_COMPUTE, "Compute is not supported!");
  3291. BGFX_CHECK_HANDLE_INVALID_OK("dispatch", s_ctx->m_programHandle, _program);
  3292. BGFX_CHECK_HANDLE("dispatch", s_ctx->m_vertexBufferHandle, _indirectHandle);
  3293. BGFX_ENCODER(dispatch(_id, _program, _indirectHandle, _start, _num, _flags) );
  3294. }
  3295. void Encoder::discard(uint8_t _flags)
  3296. {
  3297. BGFX_ENCODER(discard(_flags) );
  3298. }
  3299. void Encoder::blit(ViewId _id, TextureHandle _dst, uint16_t _dstX, uint16_t _dstY, TextureHandle _src, uint16_t _srcX, uint16_t _srcY, uint16_t _width, uint16_t _height)
  3300. {
  3301. blit(_id, _dst, 0, _dstX, _dstY, 0, _src, 0, _srcX, _srcY, 0, _width, _height, 0);
  3302. }
  3303. void Encoder::blit(ViewId _id, TextureHandle _dst, uint8_t _dstMip, uint16_t _dstX, uint16_t _dstY, uint16_t _dstZ, TextureHandle _src, uint8_t _srcMip, uint16_t _srcX, uint16_t _srcY, uint16_t _srcZ, uint16_t _width, uint16_t _height, uint16_t _depth)
  3304. {
  3305. BGFX_CHECK_CAPS(BGFX_CAPS_TEXTURE_BLIT, "Texture blit is not supported!");
  3306. BGFX_CHECK_HANDLE("blit/src TextureHandle", s_ctx->m_textureHandle, _src);
  3307. BGFX_CHECK_HANDLE("blit/dst TextureHandle", s_ctx->m_textureHandle, _dst);
  3308. const TextureRef& src = s_ctx->m_textureRef[_src.idx];
  3309. const TextureRef& dst = s_ctx->m_textureRef[_dst.idx];
  3310. BX_ASSERT(dst.isBlitDst()
  3311. , "Blit destination texture (handle %d, '%S') is not created with `BGFX_TEXTURE_BLIT_DST` flag."
  3312. , _dst.idx
  3313. , &dst.m_name
  3314. );
  3315. BX_ASSERT(src.m_format == dst.m_format
  3316. , "Texture format must match (src %s, dst %s)."
  3317. , bimg::getName(bimg::TextureFormat::Enum(src.m_format) )
  3318. , bimg::getName(bimg::TextureFormat::Enum(dst.m_format) )
  3319. );
  3320. BX_ASSERT(_srcMip < src.m_numMips, "Invalid blit src mip (%d > %d)", _srcMip, src.m_numMips - 1);
  3321. BX_ASSERT(_dstMip < dst.m_numMips, "Invalid blit dst mip (%d > %d)", _dstMip, dst.m_numMips - 1);
  3322. uint32_t srcWidth = bx::max<uint32_t>(1, src.m_width >> _srcMip);
  3323. uint32_t srcHeight = bx::max<uint32_t>(1, src.m_height >> _srcMip);
  3324. uint32_t dstWidth = bx::max<uint32_t>(1, dst.m_width >> _dstMip);
  3325. uint32_t dstHeight = bx::max<uint32_t>(1, dst.m_height >> _dstMip);
  3326. uint32_t srcDepth = src.isCubeMap() ? 6 : bx::max<uint32_t>(1, src.m_depth >> _srcMip);
  3327. uint32_t dstDepth = dst.isCubeMap() ? 6 : bx::max<uint32_t>(1, dst.m_depth >> _dstMip);
  3328. BX_ASSERT(_srcX < srcWidth && _srcY < srcHeight && _srcZ < srcDepth
  3329. , "Blit src coordinates out of range (%d, %d, %d) >= (%d, %d, %d)"
  3330. , _srcX, _srcY, _srcZ
  3331. , srcWidth, srcHeight, srcDepth
  3332. );
  3333. BX_ASSERT(_dstX < dstWidth && _dstY < dstHeight && _dstZ < dstDepth
  3334. , "Blit dst coordinates out of range (%d, %d, %d) >= (%d, %d, %d)"
  3335. , _dstX, _dstY, _dstZ
  3336. , dstWidth, dstHeight, dstDepth
  3337. );
  3338. srcWidth = bx::min<uint32_t>(srcWidth, _srcX + _width ) - _srcX;
  3339. srcHeight = bx::min<uint32_t>(srcHeight, _srcY + _height) - _srcY;
  3340. srcDepth = bx::min<uint32_t>(srcDepth, _srcZ + _depth ) - _srcZ;
  3341. dstWidth = bx::min<uint32_t>(dstWidth, _dstX + _width ) - _dstX;
  3342. dstHeight = bx::min<uint32_t>(dstHeight, _dstY + _height) - _dstY;
  3343. dstDepth = bx::min<uint32_t>(dstDepth, _dstZ + _depth ) - _dstZ;
  3344. const uint16_t width = uint16_t(bx::min(srcWidth, dstWidth ) );
  3345. const uint16_t height = uint16_t(bx::min(srcHeight, dstHeight) );
  3346. const uint16_t depth = uint16_t(bx::min(srcDepth, dstDepth ) );
  3347. BGFX_ENCODER(blit(_id, _dst, _dstMip, _dstX, _dstY, _dstZ, _src, _srcMip, _srcX, _srcY, _srcZ, width, height, depth) );
  3348. }
  3349. #undef BGFX_ENCODER
  3350. void end(Encoder* _encoder)
  3351. {
  3352. s_ctx->end(_encoder);
  3353. }
  3354. uint32_t frame(bool _capture)
  3355. {
  3356. BGFX_CHECK_API_THREAD();
  3357. return s_ctx->frame(_capture);
  3358. }
  3359. const Caps* getCaps()
  3360. {
  3361. return &g_caps;
  3362. }
  3363. const Stats* getStats()
  3364. {
  3365. return s_ctx->getPerfStats();
  3366. }
  3367. RendererType::Enum getRendererType()
  3368. {
  3369. return g_caps.rendererType;
  3370. }
  3371. const Memory* alloc(uint32_t _size)
  3372. {
  3373. BX_ASSERT(0 < _size, "Invalid memory operation. _size is 0.");
  3374. Memory* mem = (Memory*)BX_ALLOC(g_allocator, sizeof(Memory) + _size);
  3375. mem->size = _size;
  3376. mem->data = (uint8_t*)mem + sizeof(Memory);
  3377. return mem;
  3378. }
  3379. const Memory* copy(const void* _data, uint32_t _size)
  3380. {
  3381. BX_ASSERT(0 < _size, "Invalid memory operation. _size is 0.");
  3382. const Memory* mem = alloc(_size);
  3383. bx::memCopy(mem->data, _data, _size);
  3384. return mem;
  3385. }
  3386. struct MemoryRef
  3387. {
  3388. Memory mem;
  3389. ReleaseFn releaseFn;
  3390. void* userData;
  3391. };
  3392. const Memory* makeRef(const void* _data, uint32_t _size, ReleaseFn _releaseFn, void* _userData)
  3393. {
  3394. MemoryRef* memRef = (MemoryRef*)BX_ALLOC(g_allocator, sizeof(MemoryRef) );
  3395. memRef->mem.size = _size;
  3396. memRef->mem.data = (uint8_t*)_data;
  3397. memRef->releaseFn = _releaseFn;
  3398. memRef->userData = _userData;
  3399. return &memRef->mem;
  3400. }
  3401. bool isMemoryRef(const Memory* _mem)
  3402. {
  3403. return _mem->data != (uint8_t*)_mem + sizeof(Memory);
  3404. }
  3405. void release(const Memory* _mem)
  3406. {
  3407. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3408. Memory* mem = const_cast<Memory*>(_mem);
  3409. if (isMemoryRef(mem) )
  3410. {
  3411. MemoryRef* memRef = reinterpret_cast<MemoryRef*>(mem);
  3412. if (NULL != memRef->releaseFn)
  3413. {
  3414. memRef->releaseFn(mem->data, memRef->userData);
  3415. }
  3416. }
  3417. BX_FREE(g_allocator, mem);
  3418. }
  3419. void setDebug(uint32_t _debug)
  3420. {
  3421. BGFX_CHECK_API_THREAD();
  3422. s_ctx->setDebug(_debug);
  3423. }
  3424. void dbgTextClear(uint8_t _attr, bool _small)
  3425. {
  3426. BGFX_CHECK_API_THREAD();
  3427. s_ctx->dbgTextClear(_attr, _small);
  3428. }
  3429. void dbgTextPrintfVargs(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, va_list _argList)
  3430. {
  3431. s_ctx->dbgTextPrintfVargs(_x, _y, _attr, _format, _argList);
  3432. }
  3433. void dbgTextPrintf(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, ...)
  3434. {
  3435. BGFX_CHECK_API_THREAD();
  3436. va_list argList;
  3437. va_start(argList, _format);
  3438. s_ctx->dbgTextPrintfVargs(_x, _y, _attr, _format, argList);
  3439. va_end(argList);
  3440. }
  3441. void dbgTextImage(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const void* _data, uint16_t _pitch)
  3442. {
  3443. BGFX_CHECK_API_THREAD();
  3444. s_ctx->dbgTextImage(_x, _y, _width, _height, _data, _pitch);
  3445. }
  3446. IndexBufferHandle createIndexBuffer(const Memory* _mem, uint16_t _flags)
  3447. {
  3448. BX_ASSERT(
  3449. 0 == (_flags & BGFX_BUFFER_INDEX32) || 0 != (g_caps.supported & BGFX_CAPS_INDEX32)
  3450. , "32-bit indices are not supported. Use bgfx::getCaps to check BGFX_CAPS_INDEX32 backend renderer capabilities."
  3451. );
  3452. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3453. return s_ctx->createIndexBuffer(_mem, _flags);
  3454. }
  3455. void setName(IndexBufferHandle _handle, const char* _name, int32_t _len)
  3456. {
  3457. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3458. }
  3459. void destroy(IndexBufferHandle _handle)
  3460. {
  3461. s_ctx->destroyIndexBuffer(_handle);
  3462. }
  3463. VertexLayoutHandle createVertexLayout(const VertexLayout& _layout)
  3464. {
  3465. return s_ctx->createVertexLayout(_layout);
  3466. }
  3467. void destroy(VertexLayoutHandle _handle)
  3468. {
  3469. s_ctx->destroyVertexLayout(_handle);
  3470. }
  3471. VertexBufferHandle createVertexBuffer(const Memory* _mem, const VertexLayout& _layout, uint16_t _flags)
  3472. {
  3473. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3474. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3475. return s_ctx->createVertexBuffer(_mem, _layout, _flags);
  3476. }
  3477. void setName(VertexBufferHandle _handle, const char* _name, int32_t _len)
  3478. {
  3479. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3480. }
  3481. void destroy(VertexBufferHandle _handle)
  3482. {
  3483. s_ctx->destroyVertexBuffer(_handle);
  3484. }
  3485. DynamicIndexBufferHandle createDynamicIndexBuffer(uint32_t _num, uint16_t _flags)
  3486. {
  3487. return s_ctx->createDynamicIndexBuffer(_num, _flags);
  3488. }
  3489. DynamicIndexBufferHandle createDynamicIndexBuffer(const Memory* _mem, uint16_t _flags)
  3490. {
  3491. BX_ASSERT(
  3492. 0 == (_flags & BGFX_BUFFER_INDEX32) || 0 != (g_caps.supported & BGFX_CAPS_INDEX32)
  3493. , "32-bit indices are not supported. Use bgfx::getCaps to check BGFX_CAPS_INDEX32 backend renderer capabilities."
  3494. );
  3495. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3496. return s_ctx->createDynamicIndexBuffer(_mem, _flags);
  3497. }
  3498. void update(DynamicIndexBufferHandle _handle, uint32_t _startIndex, const Memory* _mem)
  3499. {
  3500. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3501. s_ctx->update(_handle, _startIndex, _mem);
  3502. }
  3503. void destroy(DynamicIndexBufferHandle _handle)
  3504. {
  3505. s_ctx->destroyDynamicIndexBuffer(_handle);
  3506. }
  3507. DynamicVertexBufferHandle createDynamicVertexBuffer(uint32_t _num, const VertexLayout& _layout, uint16_t _flags)
  3508. {
  3509. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3510. return s_ctx->createDynamicVertexBuffer(_num, _layout, _flags);
  3511. }
  3512. DynamicVertexBufferHandle createDynamicVertexBuffer(const Memory* _mem, const VertexLayout& _layout, uint16_t _flags)
  3513. {
  3514. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3515. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3516. return s_ctx->createDynamicVertexBuffer(_mem, _layout, _flags);
  3517. }
  3518. void update(DynamicVertexBufferHandle _handle, uint32_t _startVertex, const Memory* _mem)
  3519. {
  3520. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3521. s_ctx->update(_handle, _startVertex, _mem);
  3522. }
  3523. void destroy(DynamicVertexBufferHandle _handle)
  3524. {
  3525. s_ctx->destroyDynamicVertexBuffer(_handle);
  3526. }
  3527. uint32_t getAvailTransientIndexBuffer(uint32_t _num, bool _index32)
  3528. {
  3529. BX_ASSERT(0 < _num, "Requesting 0 indices.");
  3530. return s_ctx->getAvailTransientIndexBuffer(_num, _index32);
  3531. }
  3532. uint32_t getAvailTransientVertexBuffer(uint32_t _num, const VertexLayout& _layout)
  3533. {
  3534. BX_ASSERT(0 < _num, "Requesting 0 vertices.");
  3535. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3536. return s_ctx->getAvailTransientVertexBuffer(_num, _layout.m_stride);
  3537. }
  3538. uint32_t getAvailInstanceDataBuffer(uint32_t _num, uint16_t _stride)
  3539. {
  3540. BX_ASSERT(0 < _num, "Requesting 0 instances.");
  3541. return s_ctx->getAvailTransientVertexBuffer(_num, _stride);
  3542. }
  3543. void allocTransientIndexBuffer(TransientIndexBuffer* _tib, uint32_t _num, bool _index32)
  3544. {
  3545. BX_ASSERT(NULL != _tib, "_tib can't be NULL");
  3546. BX_ASSERT(0 < _num, "Requesting 0 indices.");
  3547. BX_ASSERT(
  3548. !_index32 || 0 != (g_caps.supported & BGFX_CAPS_INDEX32)
  3549. , "32-bit indices are not supported. Use bgfx::getCaps to check BGFX_CAPS_INDEX32 backend renderer capabilities."
  3550. );
  3551. s_ctx->allocTransientIndexBuffer(_tib, _num, _index32);
  3552. const uint32_t indexSize = _tib->isIndex16 ? 2 : 4;
  3553. BX_ASSERT(_num == _tib->size/ indexSize
  3554. , "Failed to allocate transient index buffer (requested %d, available %d). "
  3555. "Use bgfx::getAvailTransient* functions to ensure availability."
  3556. , _num
  3557. , _tib->size/indexSize
  3558. );
  3559. BX_UNUSED(indexSize);
  3560. }
  3561. void allocTransientVertexBuffer(TransientVertexBuffer* _tvb, uint32_t _num, const VertexLayout& _layout)
  3562. {
  3563. BX_ASSERT(NULL != _tvb, "_tvb can't be NULL");
  3564. BX_ASSERT(0 < _num, "Requesting 0 vertices.");
  3565. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3566. VertexLayoutHandle layoutHandle;
  3567. {
  3568. BGFX_MUTEX_SCOPE(s_ctx->m_resourceApiLock);
  3569. layoutHandle = s_ctx->findOrCreateVertexLayout(_layout, true);
  3570. }
  3571. BX_ASSERT(isValid(layoutHandle), "Failed to allocate vertex layout handle (BGFX_CONFIG_MAX_VERTEX_LAYOUTS, max: %d).", BGFX_CONFIG_MAX_VERTEX_LAYOUTS);
  3572. s_ctx->allocTransientVertexBuffer(_tvb, _num, layoutHandle, _layout.m_stride);
  3573. BX_ASSERT(_num == _tvb->size / _layout.m_stride
  3574. , "Failed to allocate transient vertex buffer (requested %d, available %d). "
  3575. "Use bgfx::getAvailTransient* functions to ensure availability."
  3576. , _num
  3577. , _tvb->size / _layout.m_stride
  3578. );
  3579. }
  3580. bool allocTransientBuffers(bgfx::TransientVertexBuffer* _tvb, const bgfx::VertexLayout& _layout, uint32_t _numVertices, bgfx::TransientIndexBuffer* _tib, uint32_t _numIndices, bool _index32)
  3581. {
  3582. BGFX_MUTEX_SCOPE(s_ctx->m_resourceApiLock);
  3583. if (_numVertices == getAvailTransientVertexBuffer(_numVertices, _layout)
  3584. && _numIndices == getAvailTransientIndexBuffer(_numIndices, _index32) )
  3585. {
  3586. allocTransientVertexBuffer(_tvb, _numVertices, _layout);
  3587. allocTransientIndexBuffer(_tib, _numIndices, _index32);
  3588. return true;
  3589. }
  3590. return false;
  3591. }
  3592. void allocInstanceDataBuffer(InstanceDataBuffer* _idb, uint32_t _num, uint16_t _stride)
  3593. {
  3594. BGFX_CHECK_CAPS(BGFX_CAPS_INSTANCING, "Instancing is not supported!");
  3595. BX_ASSERT(bx::isAligned(_stride, 16), "Stride must be multiple of 16.");
  3596. BX_ASSERT(0 < _num, "Requesting 0 instanced data vertices.");
  3597. s_ctx->allocInstanceDataBuffer(_idb, _num, _stride);
  3598. BX_ASSERT(_num == _idb->size / _stride
  3599. , "Failed to allocate instance data buffer (requested %d, available %d). "
  3600. "Use bgfx::getAvailTransient* functions to ensure availability."
  3601. , _num
  3602. , _idb->size / _stride
  3603. );
  3604. }
  3605. IndirectBufferHandle createIndirectBuffer(uint32_t _num)
  3606. {
  3607. return s_ctx->createIndirectBuffer(_num);
  3608. }
  3609. void destroy(IndirectBufferHandle _handle)
  3610. {
  3611. s_ctx->destroyIndirectBuffer(_handle);
  3612. }
  3613. ShaderHandle createShader(const Memory* _mem)
  3614. {
  3615. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3616. return s_ctx->createShader(_mem);
  3617. }
  3618. uint16_t getShaderUniforms(ShaderHandle _handle, UniformHandle* _uniforms, uint16_t _max)
  3619. {
  3620. BX_WARN(NULL == _uniforms || 0 != _max
  3621. , "Passing uniforms array pointer, but array maximum capacity is set to 0."
  3622. );
  3623. uint16_t num = s_ctx->getShaderUniforms(_handle, _uniforms, _max);
  3624. BX_WARN(0 == _max || num <= _max
  3625. , "Shader has more uniforms that capacity of output array. Output is truncated (num %d, max %d)."
  3626. , num
  3627. , _max
  3628. );
  3629. return num;
  3630. }
  3631. void setName(ShaderHandle _handle, const char* _name, int32_t _len)
  3632. {
  3633. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3634. }
  3635. void destroy(ShaderHandle _handle)
  3636. {
  3637. s_ctx->destroyShader(_handle);
  3638. }
  3639. ProgramHandle createProgram(ShaderHandle _vsh, ShaderHandle _fsh, bool _destroyShaders)
  3640. {
  3641. if (!isValid(_fsh) )
  3642. {
  3643. return createProgram(_vsh, _destroyShaders);
  3644. }
  3645. return s_ctx->createProgram(_vsh, _fsh, _destroyShaders);
  3646. }
  3647. ProgramHandle createProgram(ShaderHandle _csh, bool _destroyShader)
  3648. {
  3649. return s_ctx->createProgram(_csh, _destroyShader);
  3650. }
  3651. void destroy(ProgramHandle _handle)
  3652. {
  3653. s_ctx->destroyProgram(_handle);
  3654. }
  3655. void isFrameBufferValid(uint8_t _num, const Attachment* _attachment, bx::Error* _err)
  3656. {
  3657. BX_ERROR_SCOPE(_err, "Frame buffer validation");
  3658. uint8_t color = 0;
  3659. uint8_t depth = 0;
  3660. const TextureRef& firstTexture = s_ctx->m_textureRef[_attachment[0].handle.idx];
  3661. const uint16_t firstAttachmentWidth = bx::max<uint16_t>(firstTexture.m_width >> _attachment[0].mip, 1);
  3662. const uint16_t firstAttachmentHeight = bx::max<uint16_t>(firstTexture.m_height >> _attachment[0].mip, 1);
  3663. for (uint32_t ii = 0; ii < _num; ++ii)
  3664. {
  3665. const Attachment& at = _attachment[ii];
  3666. const TextureHandle texHandle = at.handle;
  3667. const TextureRef& tr = s_ctx->m_textureRef[texHandle.idx];
  3668. BGFX_ERROR_CHECK(true
  3669. && isValid(texHandle)
  3670. && s_ctx->m_textureHandle.isValid(texHandle.idx)
  3671. , _err
  3672. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3673. , "Invalid texture attachment."
  3674. , "Attachment %d, texture handle %d."
  3675. , ii
  3676. , texHandle.idx
  3677. );
  3678. BGFX_ERROR_CHECK(true
  3679. && at.mip < tr.m_numMips
  3680. , _err
  3681. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3682. , "Invalid texture mip level."
  3683. , "Attachment %d, Mip %d, texture (handle %d) number of mips %d."
  3684. , ii
  3685. , at.mip
  3686. , texHandle.idx
  3687. , tr.m_numMips
  3688. );
  3689. {
  3690. const uint16_t numLayers = tr.is3D()
  3691. ? bx::max<uint16_t>(tr.m_depth >> at.mip, 1)
  3692. : tr.m_numLayers * (tr.isCubeMap() ? 6 : 1)
  3693. ;
  3694. BGFX_ERROR_CHECK(true
  3695. && (at.layer + at.numLayers) <= numLayers
  3696. , _err
  3697. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3698. , "Invalid texture layer range."
  3699. , "Attachment %d, Layer: %d, Num: %d, Max number of layers: %d."
  3700. , ii
  3701. , at.layer
  3702. , at.numLayers
  3703. , numLayers
  3704. );
  3705. }
  3706. BGFX_ERROR_CHECK(true
  3707. && _attachment[0].numLayers == at.numLayers
  3708. , _err
  3709. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3710. , "Mismatch in attachment layer count."
  3711. , "Attachment %d, Given: %d, Expected: %d."
  3712. , ii
  3713. , at.numLayers
  3714. , _attachment[0].numLayers
  3715. );
  3716. BGFX_ERROR_CHECK(true
  3717. && firstTexture.m_bbRatio == tr.m_bbRatio
  3718. , _err
  3719. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3720. , "Mismatch in texture back-buffer ratio."
  3721. , "Attachment %d, Given: %d, Expected: %d."
  3722. , ii
  3723. , tr.m_bbRatio
  3724. , firstTexture.m_bbRatio
  3725. );
  3726. BGFX_ERROR_CHECK(true
  3727. && firstTexture.m_numSamples == tr.m_numSamples
  3728. , _err
  3729. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3730. , "Mismatch in texture sample count."
  3731. , "Attachment %d, Given: %d, Expected: %d."
  3732. , ii
  3733. , tr.m_numSamples
  3734. , firstTexture.m_numSamples
  3735. );
  3736. if (BackbufferRatio::Count == firstTexture.m_bbRatio)
  3737. {
  3738. const uint16_t width = bx::max<uint16_t>(tr.m_width >> at.mip, 1);
  3739. const uint16_t height = bx::max<uint16_t>(tr.m_height >> at.mip, 1);
  3740. BGFX_ERROR_CHECK(true
  3741. && width == firstAttachmentWidth
  3742. && height == firstAttachmentHeight
  3743. , _err
  3744. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3745. , "Mismatch in texture size."
  3746. , "Attachment %d, Given: %dx%d, Expected: %dx%d."
  3747. , ii
  3748. , width
  3749. , height
  3750. , firstAttachmentWidth
  3751. , firstAttachmentHeight
  3752. );
  3753. }
  3754. if (bimg::isDepth(bimg::TextureFormat::Enum(tr.m_format) ) )
  3755. {
  3756. ++depth;
  3757. BGFX_ERROR_CHECK(
  3758. // if BGFX_TEXTURE_RT_MSAA_X2 or greater than BGFX_TEXTURE_RT_WRITE_ONLY is required
  3759. // if BGFX_TEXTURE_RT with no MSSA then WRITE_ONLY is not required.
  3760. (1 == ((tr.m_flags & BGFX_TEXTURE_RT_MSAA_MASK) >> BGFX_TEXTURE_RT_MSAA_SHIFT))
  3761. || (0 != (tr.m_flags & BGFX_TEXTURE_RT_WRITE_ONLY))
  3762. , _err
  3763. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3764. , "Frame buffer depth MSAA texture cannot be resolved. It must be created with `BGFX_TEXTURE_RT_WRITE_ONLY` flag."
  3765. , "Attachment %d, texture flags 0x%016" PRIx64 "."
  3766. , ii
  3767. , tr.m_flags
  3768. );
  3769. }
  3770. else
  3771. {
  3772. ++color;
  3773. }
  3774. BGFX_ERROR_CHECK(true
  3775. && 0 == (tr.m_flags & BGFX_TEXTURE_READ_BACK)
  3776. , _err
  3777. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3778. , "Frame buffer texture cannot be created with `BGFX_TEXTURE_READ_BACK`."
  3779. , "Attachment %d, texture flags 0x%016" PRIx64 "."
  3780. , ii
  3781. , tr.m_flags
  3782. );
  3783. BGFX_ERROR_CHECK(true
  3784. && 0 != (tr.m_flags & BGFX_TEXTURE_RT_MASK)
  3785. , _err
  3786. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3787. , "Frame buffer texture is not created with one of `BGFX_TEXTURE_RT*` flags."
  3788. , "Attachment %d, texture flags 0x%016" PRIx64 "."
  3789. , ii
  3790. , tr.m_flags
  3791. );
  3792. }
  3793. BGFX_ERROR_CHECK(true
  3794. && color <= g_caps.limits.maxFBAttachments
  3795. , _err
  3796. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3797. , "Too many frame buffer color attachments."
  3798. , "Num: %d, Max: %d."
  3799. , _num
  3800. , g_caps.limits.maxFBAttachments
  3801. );
  3802. BGFX_ERROR_CHECK(true
  3803. && depth <= 1
  3804. , _err
  3805. , BGFX_ERROR_FRAME_BUFFER_VALIDATION
  3806. , "There can be only one depth texture attachment."
  3807. , "Num depth attachments %d."
  3808. , depth
  3809. );
  3810. }
  3811. bool isFrameBufferValid(uint8_t _num, const Attachment* _attachment)
  3812. {
  3813. BGFX_MUTEX_SCOPE(s_ctx->m_resourceApiLock);
  3814. bx::Error err;
  3815. isFrameBufferValid(_num, _attachment, &err);
  3816. return err.isOk();
  3817. }
  3818. static void isTextureValid(uint16_t _width, uint16_t _height, uint16_t _depth, bool _cubeMap, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, bx::Error* _err)
  3819. {
  3820. BX_ERROR_SCOPE(_err, "Texture validation");
  3821. const bool is3DTexture = 1 < _depth;
  3822. BGFX_ERROR_CHECK(false
  3823. || !_cubeMap
  3824. || !is3DTexture
  3825. , _err
  3826. , BGFX_ERROR_TEXTURE_VALIDATION
  3827. , "Texture can't be 3D and cube map at the same time."
  3828. , ""
  3829. );
  3830. BGFX_ERROR_CHECK(false
  3831. || !is3DTexture
  3832. || 0 != (g_caps.supported & BGFX_CAPS_TEXTURE_3D)
  3833. , _err
  3834. , BGFX_ERROR_TEXTURE_VALIDATION
  3835. , "Texture3D is not supported! "
  3836. "Use bgfx::getCaps to check `BGFX_CAPS_TEXTURE_3D` backend renderer capabilities."
  3837. , ""
  3838. );
  3839. BGFX_ERROR_CHECK(false
  3840. || _width <= g_caps.limits.maxTextureSize
  3841. || _height <= g_caps.limits.maxTextureSize
  3842. , _err
  3843. , BGFX_ERROR_TEXTURE_VALIDATION
  3844. , "Requested texture width/height is above the `maxTextureSize` limit."
  3845. , "Texture width x height requested %d x %d (Max: %d)."
  3846. , _width
  3847. , _height
  3848. , g_caps.limits.maxTextureSize
  3849. );
  3850. BGFX_ERROR_CHECK(false
  3851. || 0 == (_flags & BGFX_TEXTURE_RT_MASK)
  3852. || 0 == (_flags & BGFX_TEXTURE_READ_BACK)
  3853. , _err
  3854. , BGFX_ERROR_TEXTURE_VALIDATION
  3855. , "Can't create render target with `BGFX_TEXTURE_READ_BACK` flag."
  3856. , ""
  3857. );
  3858. BGFX_ERROR_CHECK(false
  3859. || 0 == (_flags & BGFX_TEXTURE_COMPUTE_WRITE)
  3860. || 0 == (_flags & BGFX_TEXTURE_READ_BACK)
  3861. , _err
  3862. , BGFX_ERROR_TEXTURE_VALIDATION
  3863. , "Can't create compute texture with `BGFX_TEXTURE_READ_BACK` flag."
  3864. , ""
  3865. );
  3866. BGFX_ERROR_CHECK(false
  3867. || 1 >= _numLayers
  3868. || 0 != (g_caps.supported & BGFX_CAPS_TEXTURE_2D_ARRAY)
  3869. , _err
  3870. , BGFX_ERROR_TEXTURE_VALIDATION
  3871. , "Texture array is not supported! "
  3872. "Use bgfx::getCaps to check `BGFX_CAPS_TEXTURE_2D_ARRAY` backend renderer capabilities."
  3873. , ""
  3874. );
  3875. BGFX_ERROR_CHECK(false
  3876. || _numLayers <= g_caps.limits.maxTextureLayers
  3877. , _err
  3878. , BGFX_ERROR_TEXTURE_VALIDATION
  3879. , "Requested number of texture array layers is above the `maxTextureLayers` limit."
  3880. , "Number of texture array layers requested %d (Max: %d)."
  3881. , _numLayers
  3882. , g_caps.limits.maxTextureLayers
  3883. );
  3884. bool formatSupported;
  3885. if (0 != (_flags & (BGFX_TEXTURE_RT | BGFX_TEXTURE_RT_WRITE_ONLY)) )
  3886. {
  3887. formatSupported = 0 != (g_caps.formats[_format] & BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER);
  3888. }
  3889. else
  3890. {
  3891. formatSupported = 0 != (g_caps.formats[_format] & (0
  3892. | BGFX_CAPS_FORMAT_TEXTURE_2D
  3893. | BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED
  3894. | BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  3895. ) );
  3896. }
  3897. uint16_t srgbCaps = BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB;
  3898. if (_cubeMap)
  3899. {
  3900. formatSupported = 0 != (g_caps.formats[_format] & (0
  3901. | BGFX_CAPS_FORMAT_TEXTURE_CUBE
  3902. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED
  3903. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  3904. ) );
  3905. srgbCaps = BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB;
  3906. }
  3907. else if (is3DTexture)
  3908. {
  3909. formatSupported = 0 != (g_caps.formats[_format] & (0
  3910. | BGFX_CAPS_FORMAT_TEXTURE_3D
  3911. | BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED
  3912. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  3913. ) );
  3914. srgbCaps = BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB;
  3915. }
  3916. if (formatSupported
  3917. && 0 != (_flags & BGFX_TEXTURE_RT_MASK) )
  3918. {
  3919. formatSupported = 0 != (g_caps.formats[_format] & (0
  3920. | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  3921. ) );
  3922. }
  3923. BGFX_ERROR_CHECK(
  3924. formatSupported
  3925. , _err
  3926. , BGFX_ERROR_TEXTURE_VALIDATION
  3927. , "Texture format is not supported! "
  3928. "Use bgfx::isTextureValid to check support for texture format before creating it."
  3929. , "Texture format: %s."
  3930. , getName(_format)
  3931. );
  3932. BGFX_ERROR_CHECK(false
  3933. || 0 == (_flags & BGFX_TEXTURE_MSAA_SAMPLE)
  3934. || 0 != (g_caps.formats[_format] & BGFX_CAPS_FORMAT_TEXTURE_MSAA)
  3935. , _err
  3936. , BGFX_ERROR_TEXTURE_VALIDATION
  3937. , "MSAA sampling for this texture format is not supported."
  3938. , "Texture format: %s."
  3939. , getName(_format)
  3940. );
  3941. BGFX_ERROR_CHECK(false
  3942. || 0 == (_flags & BGFX_TEXTURE_SRGB)
  3943. || 0 != (g_caps.formats[_format] & srgbCaps & (0
  3944. | BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  3945. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  3946. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  3947. ) )
  3948. , _err
  3949. , BGFX_ERROR_TEXTURE_VALIDATION
  3950. , "sRGB sampling for this texture format is not supported."
  3951. , "Texture format: %s."
  3952. , getName(_format)
  3953. );
  3954. }
  3955. bool isTextureValid(uint16_t _depth, bool _cubeMap, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags)
  3956. {
  3957. bx::Error err;
  3958. isTextureValid(0, 0, _depth, _cubeMap, _numLayers, _format, _flags, &err);
  3959. return err.isOk();
  3960. }
  3961. void isIdentifierValid(const bx::StringView& _name, bx::Error* _err)
  3962. {
  3963. BX_ERROR_SCOPE(_err, "Uniform identifier validation");
  3964. BGFX_ERROR_CHECK(false
  3965. || !_name.isEmpty()
  3966. , _err
  3967. , BGFX_ERROR_IDENTIFIER_VALIDATION
  3968. , "Identifier can't be empty."
  3969. , ""
  3970. );
  3971. BGFX_ERROR_CHECK(false
  3972. || PredefinedUniform::Count == nameToPredefinedUniformEnum(_name)
  3973. , _err
  3974. , BGFX_ERROR_IDENTIFIER_VALIDATION
  3975. , "Identifier can't use predefined uniform name."
  3976. , ""
  3977. );
  3978. const char ch = *_name.getPtr();
  3979. BGFX_ERROR_CHECK(false
  3980. || bx::isAlpha(ch)
  3981. || '_' == ch
  3982. , _err
  3983. , BGFX_ERROR_IDENTIFIER_VALIDATION
  3984. , "The first character of an identifier should be either an alphabet character or an underscore."
  3985. , ""
  3986. );
  3987. bool result = true;
  3988. for (const char* ptr = _name.getPtr() + 1, *term = _name.getTerm()
  3989. ; ptr != term && result
  3990. ; ++ptr
  3991. )
  3992. {
  3993. result &= bx::isAlphaNum(*ptr) || '_' == *ptr;
  3994. }
  3995. BGFX_ERROR_CHECK(false
  3996. || result
  3997. , _err
  3998. , BGFX_ERROR_IDENTIFIER_VALIDATION
  3999. , "Identifier contains invalid characters. Identifier must be the alphabet character, number, or underscore."
  4000. , ""
  4001. );
  4002. }
  4003. void calcTextureSize(TextureInfo& _info, uint16_t _width, uint16_t _height, uint16_t _depth, bool _cubeMap, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format)
  4004. {
  4005. bimg::imageGetSize( (bimg::TextureInfo*)&_info, _width, _height, _depth, _cubeMap, _hasMips, _numLayers, bimg::TextureFormat::Enum(_format) );
  4006. }
  4007. TextureHandle createTexture(const Memory* _mem, uint64_t _flags, uint8_t _skip, TextureInfo* _info)
  4008. {
  4009. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  4010. return s_ctx->createTexture(_mem, _flags, _skip, _info, BackbufferRatio::Count, false);
  4011. }
  4012. void getTextureSizeFromRatio(BackbufferRatio::Enum _ratio, uint16_t& _width, uint16_t& _height)
  4013. {
  4014. switch (_ratio)
  4015. {
  4016. case BackbufferRatio::Half: _width /= 2; _height /= 2; break;
  4017. case BackbufferRatio::Quarter: _width /= 4; _height /= 4; break;
  4018. case BackbufferRatio::Eighth: _width /= 8; _height /= 8; break;
  4019. case BackbufferRatio::Sixteenth: _width /= 16; _height /= 16; break;
  4020. case BackbufferRatio::Double: _width *= 2; _height *= 2; break;
  4021. default:
  4022. break;
  4023. }
  4024. _width = bx::max<uint16_t>(1, _width);
  4025. _height = bx::max<uint16_t>(1, _height);
  4026. }
  4027. static TextureHandle createTexture2D(BackbufferRatio::Enum _ratio, uint16_t _width, uint16_t _height, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  4028. {
  4029. if (BackbufferRatio::Count != _ratio)
  4030. {
  4031. _width = uint16_t(s_ctx->m_init.resolution.width);
  4032. _height = uint16_t(s_ctx->m_init.resolution.height);
  4033. getTextureSizeFromRatio(_ratio, _width, _height);
  4034. }
  4035. bx::ErrorAssert err;
  4036. isTextureValid(_width, _height, 0, false, _numLayers, _format, _flags, &err);
  4037. if (!err.isOk() )
  4038. {
  4039. return BGFX_INVALID_HANDLE;
  4040. }
  4041. const uint8_t numMips = calcNumMips(_hasMips, _width, _height);
  4042. _numLayers = bx::max<uint16_t>(_numLayers, 1);
  4043. if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  4044. && NULL != _mem)
  4045. {
  4046. TextureInfo ti;
  4047. calcTextureSize(ti, _width, _height, 1, false, _hasMips, _numLayers, _format);
  4048. BX_ASSERT(ti.storageSize == _mem->size
  4049. , "createTexture2D: Texture storage size doesn't match passed memory size (storage size: %d, memory size: %d)"
  4050. , ti.storageSize
  4051. , _mem->size
  4052. );
  4053. }
  4054. uint32_t size = sizeof(uint32_t)+sizeof(TextureCreate);
  4055. const Memory* mem = alloc(size);
  4056. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  4057. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  4058. bx::write(&writer, magic, bx::ErrorAssert{});
  4059. TextureCreate tc;
  4060. tc.m_width = _width;
  4061. tc.m_height = _height;
  4062. tc.m_depth = 0;
  4063. tc.m_numLayers = _numLayers;
  4064. tc.m_numMips = numMips;
  4065. tc.m_format = _format;
  4066. tc.m_cubeMap = false;
  4067. tc.m_mem = _mem;
  4068. bx::write(&writer, tc, bx::ErrorAssert{});
  4069. return s_ctx->createTexture(mem, _flags, 0, NULL, _ratio, NULL != _mem);
  4070. }
  4071. TextureHandle createTexture2D(uint16_t _width, uint16_t _height, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  4072. {
  4073. BX_ASSERT(_width > 0 && _height > 0, "Invalid texture size (width %d, height %d).", _width, _height);
  4074. return createTexture2D(BackbufferRatio::Count, _width, _height, _hasMips, _numLayers, _format, _flags, _mem);
  4075. }
  4076. TextureHandle createTexture2D(BackbufferRatio::Enum _ratio, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags)
  4077. {
  4078. BX_ASSERT(_ratio < BackbufferRatio::Count, "Invalid back buffer ratio.");
  4079. return createTexture2D(_ratio, 0, 0, _hasMips, _numLayers, _format, _flags, NULL);
  4080. }
  4081. TextureHandle createTexture3D(uint16_t _width, uint16_t _height, uint16_t _depth, bool _hasMips, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  4082. {
  4083. bx::ErrorAssert err;
  4084. isTextureValid(_width, _height, _depth, false, 1, _format, _flags, &err);
  4085. if (!err.isOk() )
  4086. {
  4087. return BGFX_INVALID_HANDLE;
  4088. }
  4089. const uint8_t numMips = calcNumMips(_hasMips, _width, _height, _depth);
  4090. if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  4091. && NULL != _mem)
  4092. {
  4093. TextureInfo ti;
  4094. calcTextureSize(ti, _width, _height, _depth, false, _hasMips, 1, _format);
  4095. BX_ASSERT(ti.storageSize == _mem->size
  4096. , "createTexture3D: Texture storage size doesn't match passed memory size (storage size: %d, memory size: %d)"
  4097. , ti.storageSize
  4098. , _mem->size
  4099. );
  4100. }
  4101. uint32_t size = sizeof(uint32_t)+sizeof(TextureCreate);
  4102. const Memory* mem = alloc(size);
  4103. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  4104. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  4105. bx::write(&writer, magic, bx::ErrorAssert{});
  4106. TextureCreate tc;
  4107. tc.m_width = _width;
  4108. tc.m_height = _height;
  4109. tc.m_depth = _depth;
  4110. tc.m_numLayers = 1;
  4111. tc.m_numMips = numMips;
  4112. tc.m_format = _format;
  4113. tc.m_cubeMap = false;
  4114. tc.m_mem = _mem;
  4115. bx::write(&writer, tc, bx::ErrorAssert{});
  4116. return s_ctx->createTexture(mem, _flags, 0, NULL, BackbufferRatio::Count, NULL != _mem);
  4117. }
  4118. TextureHandle createTextureCube(uint16_t _size, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  4119. {
  4120. bx::ErrorAssert err;
  4121. isTextureValid(_size, _size, 0, true, _numLayers, _format, _flags, &err);
  4122. if (!err.isOk() )
  4123. {
  4124. return BGFX_INVALID_HANDLE;
  4125. }
  4126. const uint8_t numMips = calcNumMips(_hasMips, _size, _size);
  4127. _numLayers = bx::max<uint16_t>(_numLayers, 1);
  4128. if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  4129. && NULL != _mem)
  4130. {
  4131. TextureInfo ti;
  4132. calcTextureSize(ti, _size, _size, 1, true, _hasMips, _numLayers, _format);
  4133. BX_ASSERT(ti.storageSize == _mem->size
  4134. , "createTextureCube: Texture storage size doesn't match passed memory size (storage size: %d, memory size: %d)"
  4135. , ti.storageSize
  4136. , _mem->size
  4137. );
  4138. }
  4139. uint32_t size = sizeof(uint32_t)+sizeof(TextureCreate);
  4140. const Memory* mem = alloc(size);
  4141. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  4142. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  4143. bx::write(&writer, magic, bx::ErrorAssert{});
  4144. TextureCreate tc;
  4145. tc.m_width = _size;
  4146. tc.m_height = _size;
  4147. tc.m_depth = 0;
  4148. tc.m_numLayers = _numLayers;
  4149. tc.m_numMips = numMips;
  4150. tc.m_format = _format;
  4151. tc.m_cubeMap = true;
  4152. tc.m_mem = _mem;
  4153. bx::write(&writer, tc, bx::ErrorAssert{});
  4154. return s_ctx->createTexture(mem, _flags, 0, NULL, BackbufferRatio::Count, NULL != _mem);
  4155. }
  4156. void setName(TextureHandle _handle, const char* _name, int32_t _len)
  4157. {
  4158. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  4159. }
  4160. void* getDirectAccessPtr(TextureHandle _handle)
  4161. {
  4162. return s_ctx->getDirectAccessPtr(_handle);
  4163. }
  4164. void destroy(TextureHandle _handle)
  4165. {
  4166. s_ctx->destroyTexture(_handle);
  4167. }
  4168. void updateTexture2D(TextureHandle _handle, uint16_t _layer, uint8_t _mip, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const Memory* _mem, uint16_t _pitch)
  4169. {
  4170. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  4171. if (_width == 0
  4172. || _height == 0)
  4173. {
  4174. release(_mem);
  4175. }
  4176. else
  4177. {
  4178. s_ctx->updateTexture(_handle, 0, _mip, _x, _y, _layer, _width, _height, 1, _pitch, _mem);
  4179. }
  4180. }
  4181. void updateTexture3D(TextureHandle _handle, uint8_t _mip, uint16_t _x, uint16_t _y, uint16_t _z, uint16_t _width, uint16_t _height, uint16_t _depth, const Memory* _mem)
  4182. {
  4183. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  4184. BGFX_CHECK_CAPS(BGFX_CAPS_TEXTURE_3D, "Texture3D is not supported!");
  4185. if (0 == _width
  4186. || 0 == _height
  4187. || 0 == _depth)
  4188. {
  4189. release(_mem);
  4190. }
  4191. else
  4192. {
  4193. s_ctx->updateTexture(_handle, 0, _mip, _x, _y, _z, _width, _height, _depth, UINT16_MAX, _mem);
  4194. }
  4195. }
  4196. void updateTextureCube(TextureHandle _handle, uint16_t _layer, uint8_t _side, uint8_t _mip, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const Memory* _mem, uint16_t _pitch)
  4197. {
  4198. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  4199. BX_ASSERT(_side <= 5, "Invalid side %d.", _side);
  4200. if (0 == _width
  4201. || 0 == _height)
  4202. {
  4203. release(_mem);
  4204. }
  4205. else
  4206. {
  4207. s_ctx->updateTexture(_handle, _side, _mip, _x, _y, _layer, _width, _height, 1, _pitch, _mem);
  4208. }
  4209. }
  4210. uint32_t readTexture(TextureHandle _handle, void* _data, uint8_t _mip)
  4211. {
  4212. BX_ASSERT(NULL != _data, "_data can't be NULL");
  4213. BGFX_CHECK_CAPS(BGFX_CAPS_TEXTURE_READ_BACK, "Texture read-back is not supported!");
  4214. return s_ctx->readTexture(_handle, _data, _mip);
  4215. }
  4216. FrameBufferHandle createFrameBuffer(uint16_t _width, uint16_t _height, TextureFormat::Enum _format, uint64_t _textureFlags)
  4217. {
  4218. _textureFlags |= _textureFlags&BGFX_TEXTURE_RT_MSAA_MASK ? 0 : BGFX_TEXTURE_RT;
  4219. TextureHandle th = createTexture2D(_width, _height, false, 1, _format, _textureFlags);
  4220. return createFrameBuffer(1, &th, true);
  4221. }
  4222. FrameBufferHandle createFrameBuffer(BackbufferRatio::Enum _ratio, TextureFormat::Enum _format, uint64_t _textureFlags)
  4223. {
  4224. BX_ASSERT(_ratio < BackbufferRatio::Count, "Invalid back buffer ratio.");
  4225. _textureFlags |= _textureFlags&BGFX_TEXTURE_RT_MSAA_MASK ? 0 : BGFX_TEXTURE_RT;
  4226. TextureHandle th = createTexture2D(_ratio, false, 1, _format, _textureFlags);
  4227. return createFrameBuffer(1, &th, true);
  4228. }
  4229. FrameBufferHandle createFrameBuffer(uint8_t _num, const TextureHandle* _handles, bool _destroyTextures)
  4230. {
  4231. Attachment attachment[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  4232. for (uint8_t ii = 0; ii < _num; ++ii)
  4233. {
  4234. Attachment& at = attachment[ii];
  4235. at.init(_handles[ii], Access::Write, 0, 1, 0, BGFX_RESOLVE_AUTO_GEN_MIPS);
  4236. }
  4237. return createFrameBuffer(_num, attachment, _destroyTextures);
  4238. }
  4239. FrameBufferHandle createFrameBuffer(uint8_t _num, const Attachment* _attachment, bool _destroyTextures)
  4240. {
  4241. BX_ASSERT(_num != 0, "Number of frame buffer attachments can't be 0.");
  4242. BX_ASSERT(_num <= BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS
  4243. , "Number of frame buffer attachments is larger than allowed %d (max: %d)."
  4244. , _num
  4245. , BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS
  4246. );
  4247. BX_ASSERT(NULL != _attachment, "_attachment can't be NULL");
  4248. return s_ctx->createFrameBuffer(_num, _attachment, _destroyTextures);
  4249. }
  4250. FrameBufferHandle createFrameBuffer(void* _nwh, uint16_t _width, uint16_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat)
  4251. {
  4252. BGFX_CHECK_CAPS(BGFX_CAPS_SWAP_CHAIN, "Swap chain is not supported!");
  4253. BX_WARN(_width > 0 && _height > 0
  4254. , "Invalid frame buffer dimensions (width %d, height %d)."
  4255. , _width
  4256. , _height
  4257. );
  4258. BX_ASSERT(_format == TextureFormat::Count || bimg::isColor(bimg::TextureFormat::Enum(_format) )
  4259. , "Invalid texture format for color (%s)."
  4260. , bimg::getName(bimg::TextureFormat::Enum(_format) )
  4261. );
  4262. BX_ASSERT(_depthFormat == TextureFormat::Count || bimg::isDepth(bimg::TextureFormat::Enum(_depthFormat) )
  4263. , "Invalid texture format for depth (%s)."
  4264. , bimg::getName(bimg::TextureFormat::Enum(_depthFormat) )
  4265. );
  4266. return s_ctx->createFrameBuffer(
  4267. _nwh
  4268. , bx::max<uint16_t>(_width, 1)
  4269. , bx::max<uint16_t>(_height, 1)
  4270. , _format
  4271. , _depthFormat
  4272. );
  4273. }
  4274. void setName(FrameBufferHandle _handle, const char* _name, int32_t _len)
  4275. {
  4276. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  4277. }
  4278. TextureHandle getTexture(FrameBufferHandle _handle, uint8_t _attachment)
  4279. {
  4280. return s_ctx->getTexture(_handle, _attachment);
  4281. }
  4282. void destroy(FrameBufferHandle _handle)
  4283. {
  4284. s_ctx->destroyFrameBuffer(_handle);
  4285. }
  4286. UniformHandle createUniform(const char* _name, UniformType::Enum _type, uint16_t _num)
  4287. {
  4288. return s_ctx->createUniform(_name, _type, _num);
  4289. }
  4290. void getUniformInfo(UniformHandle _handle, UniformInfo& _info)
  4291. {
  4292. s_ctx->getUniformInfo(_handle, _info);
  4293. }
  4294. void destroy(UniformHandle _handle)
  4295. {
  4296. s_ctx->destroyUniform(_handle);
  4297. }
  4298. OcclusionQueryHandle createOcclusionQuery()
  4299. {
  4300. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  4301. return s_ctx->createOcclusionQuery();
  4302. }
  4303. OcclusionQueryResult::Enum getResult(OcclusionQueryHandle _handle, int32_t* _result)
  4304. {
  4305. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  4306. return s_ctx->getResult(_handle, _result);
  4307. }
  4308. void destroy(OcclusionQueryHandle _handle)
  4309. {
  4310. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  4311. s_ctx->destroyOcclusionQuery(_handle);
  4312. }
  4313. void setPaletteColor(uint8_t _index, uint32_t _rgba)
  4314. {
  4315. const uint8_t rr = uint8_t(_rgba>>24);
  4316. const uint8_t gg = uint8_t(_rgba>>16);
  4317. const uint8_t bb = uint8_t(_rgba>> 8);
  4318. const uint8_t aa = uint8_t(_rgba>> 0);
  4319. const float rgba[4] =
  4320. {
  4321. rr * 1.0f/255.0f,
  4322. gg * 1.0f/255.0f,
  4323. bb * 1.0f/255.0f,
  4324. aa * 1.0f/255.0f,
  4325. };
  4326. s_ctx->setPaletteColor(_index, rgba);
  4327. }
  4328. void setPaletteColor(uint8_t _index, float _r, float _g, float _b, float _a)
  4329. {
  4330. float rgba[4] = { _r, _g, _b, _a };
  4331. s_ctx->setPaletteColor(_index, rgba);
  4332. }
  4333. void setPaletteColor(uint8_t _index, const float _rgba[4])
  4334. {
  4335. s_ctx->setPaletteColor(_index, _rgba);
  4336. }
  4337. bool checkView(ViewId _id)
  4338. {
  4339. // workaround GCC 4.9 type-limit check.
  4340. const uint32_t id = _id;
  4341. return id < BGFX_CONFIG_MAX_VIEWS;
  4342. }
  4343. void setViewName(ViewId _id, const char* _name)
  4344. {
  4345. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4346. s_ctx->setViewName(_id, _name);
  4347. }
  4348. void setViewRect(ViewId _id, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  4349. {
  4350. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4351. s_ctx->setViewRect(_id, _x, _y, _width, _height);
  4352. }
  4353. void setViewRect(ViewId _id, uint16_t _x, uint16_t _y, BackbufferRatio::Enum _ratio)
  4354. {
  4355. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4356. uint16_t width = uint16_t(s_ctx->m_init.resolution.width);
  4357. uint16_t height = uint16_t(s_ctx->m_init.resolution.height);
  4358. getTextureSizeFromRatio(_ratio, width, height);
  4359. setViewRect(_id, _x, _y, width, height);
  4360. }
  4361. void setViewScissor(ViewId _id, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  4362. {
  4363. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4364. s_ctx->setViewScissor(_id, _x, _y, _width, _height);
  4365. }
  4366. void setViewClear(ViewId _id, uint16_t _flags, uint32_t _rgba, float _depth, uint8_t _stencil)
  4367. {
  4368. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4369. s_ctx->setViewClear(_id, _flags, _rgba, _depth, _stencil);
  4370. }
  4371. void setViewClear(ViewId _id, uint16_t _flags, float _depth, uint8_t _stencil, uint8_t _0, uint8_t _1, uint8_t _2, uint8_t _3, uint8_t _4, uint8_t _5, uint8_t _6, uint8_t _7)
  4372. {
  4373. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4374. s_ctx->setViewClear(_id, _flags, _depth, _stencil, _0, _1, _2, _3, _4, _5, _6, _7);
  4375. }
  4376. void setViewMode(ViewId _id, ViewMode::Enum _mode)
  4377. {
  4378. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4379. s_ctx->setViewMode(_id, _mode);
  4380. }
  4381. void setViewFrameBuffer(ViewId _id, FrameBufferHandle _handle)
  4382. {
  4383. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4384. s_ctx->setViewFrameBuffer(_id, _handle);
  4385. }
  4386. void setViewTransform(ViewId _id, const void* _view, const void* _proj)
  4387. {
  4388. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4389. s_ctx->setViewTransform(_id, _view, _proj);
  4390. }
  4391. void setViewOrder(ViewId _id, uint16_t _num, const ViewId* _order)
  4392. {
  4393. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4394. s_ctx->setViewOrder(_id, _num, _order);
  4395. }
  4396. void resetView(ViewId _id)
  4397. {
  4398. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4399. s_ctx->resetView(_id);
  4400. }
  4401. #define BGFX_CHECK_ENCODER0() \
  4402. BGFX_CHECK_API_THREAD(); \
  4403. BGFX_FATAL(NULL != s_ctx->m_encoder0, Fatal::DebugCheck \
  4404. , "bgfx is configured to allow only encoder API. See: `BGFX_CONFIG_ENCODER_API_ONLY`.")
  4405. void setMarker(const char* _marker)
  4406. {
  4407. BGFX_CHECK_ENCODER0();
  4408. s_ctx->m_encoder0->setMarker(_marker);
  4409. }
  4410. void setState(uint64_t _state, uint32_t _rgba)
  4411. {
  4412. BGFX_CHECK_ENCODER0();
  4413. s_ctx->m_encoder0->setState(_state, _rgba);
  4414. }
  4415. void setCondition(OcclusionQueryHandle _handle, bool _visible)
  4416. {
  4417. BGFX_CHECK_ENCODER0();
  4418. s_ctx->m_encoder0->setCondition(_handle, _visible);
  4419. }
  4420. void setStencil(uint32_t _fstencil, uint32_t _bstencil)
  4421. {
  4422. BGFX_CHECK_ENCODER0();
  4423. s_ctx->m_encoder0->setStencil(_fstencil, _bstencil);
  4424. }
  4425. uint16_t setScissor(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  4426. {
  4427. BGFX_CHECK_ENCODER0();
  4428. return s_ctx->m_encoder0->setScissor(_x, _y, _width, _height);
  4429. }
  4430. void setScissor(uint16_t _cache)
  4431. {
  4432. BGFX_CHECK_ENCODER0();
  4433. s_ctx->m_encoder0->setScissor(_cache);
  4434. }
  4435. uint32_t setTransform(const void* _mtx, uint16_t _num)
  4436. {
  4437. BGFX_CHECK_ENCODER0();
  4438. return s_ctx->m_encoder0->setTransform(_mtx, _num);
  4439. }
  4440. uint32_t allocTransform(Transform* _transform, uint16_t _num)
  4441. {
  4442. BGFX_CHECK_ENCODER0();
  4443. return s_ctx->m_encoder0->allocTransform(_transform, _num);
  4444. }
  4445. void setTransform(uint32_t _cache, uint16_t _num)
  4446. {
  4447. BGFX_CHECK_ENCODER0();
  4448. s_ctx->m_encoder0->setTransform(_cache, _num);
  4449. }
  4450. void setUniform(UniformHandle _handle, const void* _value, uint16_t _num)
  4451. {
  4452. BGFX_CHECK_ENCODER0();
  4453. s_ctx->m_encoder0->setUniform(_handle, _value, _num);
  4454. }
  4455. void setIndexBuffer(IndexBufferHandle _handle)
  4456. {
  4457. BGFX_CHECK_ENCODER0();
  4458. s_ctx->m_encoder0->setIndexBuffer(_handle);
  4459. }
  4460. void setIndexBuffer(IndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  4461. {
  4462. BGFX_CHECK_ENCODER0();
  4463. s_ctx->m_encoder0->setIndexBuffer(_handle, _firstIndex, _numIndices);
  4464. }
  4465. void setIndexBuffer(DynamicIndexBufferHandle _handle)
  4466. {
  4467. BGFX_CHECK_ENCODER0();
  4468. s_ctx->m_encoder0->setIndexBuffer(_handle);
  4469. }
  4470. void setIndexBuffer(DynamicIndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  4471. {
  4472. BGFX_CHECK_ENCODER0();
  4473. s_ctx->m_encoder0->setIndexBuffer(_handle, _firstIndex, _numIndices);
  4474. }
  4475. void setIndexBuffer(const TransientIndexBuffer* _tib)
  4476. {
  4477. BGFX_CHECK_ENCODER0();
  4478. s_ctx->m_encoder0->setIndexBuffer(_tib);
  4479. }
  4480. void setIndexBuffer(const TransientIndexBuffer* _tib, uint32_t _firstIndex, uint32_t _numIndices)
  4481. {
  4482. BGFX_CHECK_ENCODER0();
  4483. s_ctx->m_encoder0->setIndexBuffer(_tib, _firstIndex, _numIndices);
  4484. }
  4485. void setVertexBuffer(
  4486. uint8_t _stream
  4487. , VertexBufferHandle _handle
  4488. , uint32_t _startVertex
  4489. , uint32_t _numVertices
  4490. , VertexLayoutHandle _layoutHandle
  4491. )
  4492. {
  4493. BGFX_CHECK_ENCODER0();
  4494. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle, _startVertex, _numVertices, _layoutHandle);
  4495. }
  4496. void setVertexBuffer(uint8_t _stream, VertexBufferHandle _handle)
  4497. {
  4498. BGFX_CHECK_ENCODER0();
  4499. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle);
  4500. }
  4501. void setVertexBuffer(
  4502. uint8_t _stream
  4503. , DynamicVertexBufferHandle _handle
  4504. , uint32_t _startVertex
  4505. , uint32_t _numVertices
  4506. , VertexLayoutHandle _layoutHandle
  4507. )
  4508. {
  4509. BGFX_CHECK_ENCODER0();
  4510. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle, _startVertex, _numVertices, _layoutHandle);
  4511. }
  4512. void setVertexBuffer(uint8_t _stream, DynamicVertexBufferHandle _handle)
  4513. {
  4514. BGFX_CHECK_ENCODER0();
  4515. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle);
  4516. }
  4517. void setVertexBuffer(
  4518. uint8_t _stream
  4519. , const TransientVertexBuffer* _tvb
  4520. , uint32_t _startVertex
  4521. , uint32_t _numVertices
  4522. , VertexLayoutHandle _layoutHandle
  4523. )
  4524. {
  4525. BGFX_CHECK_ENCODER0();
  4526. s_ctx->m_encoder0->setVertexBuffer(_stream, _tvb, _startVertex, _numVertices, _layoutHandle);
  4527. }
  4528. void setVertexBuffer(uint8_t _stream, const TransientVertexBuffer* _tvb)
  4529. {
  4530. BGFX_CHECK_ENCODER0();
  4531. s_ctx->m_encoder0->setVertexBuffer(_stream, _tvb);
  4532. }
  4533. void setVertexCount(uint32_t _numVertices)
  4534. {
  4535. BGFX_CHECK_ENCODER0();
  4536. s_ctx->m_encoder0->setVertexCount(_numVertices);
  4537. }
  4538. void setInstanceDataBuffer(const InstanceDataBuffer* _idb)
  4539. {
  4540. BGFX_CHECK_ENCODER0();
  4541. s_ctx->m_encoder0->setInstanceDataBuffer(_idb);
  4542. }
  4543. void setInstanceDataBuffer(const InstanceDataBuffer* _idb, uint32_t _start, uint32_t _num)
  4544. {
  4545. BGFX_CHECK_ENCODER0();
  4546. s_ctx->m_encoder0->setInstanceDataBuffer(_idb, _start, _num);
  4547. }
  4548. void setInstanceDataBuffer(VertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  4549. {
  4550. BGFX_CHECK_ENCODER0();
  4551. s_ctx->m_encoder0->setInstanceDataBuffer(_handle, _startVertex, _num);
  4552. }
  4553. void setInstanceDataBuffer(DynamicVertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  4554. {
  4555. BGFX_CHECK_ENCODER0();
  4556. s_ctx->m_encoder0->setInstanceDataBuffer(_handle, _startVertex, _num);
  4557. }
  4558. void setInstanceCount(uint32_t _numInstances)
  4559. {
  4560. BGFX_CHECK_ENCODER0();
  4561. s_ctx->m_encoder0->setInstanceCount(_numInstances);
  4562. }
  4563. void setTexture(uint8_t _stage, UniformHandle _sampler, TextureHandle _handle, uint32_t _flags)
  4564. {
  4565. BGFX_CHECK_ENCODER0();
  4566. s_ctx->m_encoder0->setTexture(_stage, _sampler, _handle, _flags);
  4567. }
  4568. void touch(ViewId _id)
  4569. {
  4570. BGFX_CHECK_ENCODER0();
  4571. s_ctx->m_encoder0->touch(_id);
  4572. }
  4573. void submit(ViewId _id, ProgramHandle _program, uint32_t _depth, uint8_t _flags)
  4574. {
  4575. BGFX_CHECK_ENCODER0();
  4576. s_ctx->m_encoder0->submit(_id, _program, _depth, _flags);
  4577. }
  4578. void submit(ViewId _id, ProgramHandle _program, OcclusionQueryHandle _occlusionQuery, uint32_t _depth, uint8_t _flags)
  4579. {
  4580. BGFX_CHECK_ENCODER0();
  4581. s_ctx->m_encoder0->submit(_id, _program, _occlusionQuery, _depth, _flags);
  4582. }
  4583. void submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint16_t _start, uint16_t _num, uint32_t _depth, uint8_t _flags)
  4584. {
  4585. BGFX_CHECK_ENCODER0();
  4586. s_ctx->m_encoder0->submit(_id, _program, _indirectHandle, _start, _num, _depth, _flags);
  4587. }
  4588. void submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint16_t _start, IndexBufferHandle _numHandle, uint32_t _numIndex, uint16_t _numMax, uint32_t _depth, uint8_t _flags)
  4589. {
  4590. BGFX_CHECK_ENCODER0();
  4591. s_ctx->m_encoder0->submit(_id, _program, _indirectHandle, _start, _numHandle, _numIndex, _numMax, _depth, _flags);
  4592. }
  4593. void setBuffer(uint8_t _stage, IndexBufferHandle _handle, Access::Enum _access)
  4594. {
  4595. BGFX_CHECK_ENCODER0();
  4596. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4597. }
  4598. void setBuffer(uint8_t _stage, VertexBufferHandle _handle, Access::Enum _access)
  4599. {
  4600. BGFX_CHECK_ENCODER0();
  4601. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4602. }
  4603. void setBuffer(uint8_t _stage, DynamicIndexBufferHandle _handle, Access::Enum _access)
  4604. {
  4605. BGFX_CHECK_ENCODER0();
  4606. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4607. }
  4608. void setBuffer(uint8_t _stage, DynamicVertexBufferHandle _handle, Access::Enum _access)
  4609. {
  4610. BGFX_CHECK_ENCODER0();
  4611. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4612. }
  4613. void setBuffer(uint8_t _stage, IndirectBufferHandle _handle, Access::Enum _access)
  4614. {
  4615. BGFX_CHECK_ENCODER0();
  4616. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4617. }
  4618. void setImage(uint8_t _stage, TextureHandle _handle, uint8_t _mip, Access::Enum _access, TextureFormat::Enum _format)
  4619. {
  4620. BGFX_CHECK_ENCODER0();
  4621. s_ctx->m_encoder0->setImage(_stage, _handle, _mip, _access, _format);
  4622. }
  4623. void dispatch(ViewId _id, ProgramHandle _handle, uint32_t _numX, uint32_t _numY, uint32_t _numZ, uint8_t _flags)
  4624. {
  4625. BGFX_CHECK_ENCODER0();
  4626. s_ctx->m_encoder0->dispatch(_id, _handle, _numX, _numY, _numZ, _flags);
  4627. }
  4628. void dispatch(ViewId _id, ProgramHandle _handle, IndirectBufferHandle _indirectHandle, uint16_t _start, uint16_t _num, uint8_t _flags)
  4629. {
  4630. BGFX_CHECK_ENCODER0();
  4631. s_ctx->m_encoder0->dispatch(_id, _handle, _indirectHandle, _start, _num, _flags);
  4632. }
  4633. void discard(uint8_t _flags)
  4634. {
  4635. BGFX_CHECK_ENCODER0();
  4636. s_ctx->m_encoder0->discard(_flags);
  4637. }
  4638. void blit(ViewId _id, TextureHandle _dst, uint16_t _dstX, uint16_t _dstY, TextureHandle _src, uint16_t _srcX, uint16_t _srcY, uint16_t _width, uint16_t _height)
  4639. {
  4640. BGFX_CHECK_ENCODER0();
  4641. s_ctx->m_encoder0->blit(_id, _dst, _dstX, _dstY, _src, _srcX, _srcY, _width, _height);
  4642. }
  4643. void blit(ViewId _id, TextureHandle _dst, uint8_t _dstMip, uint16_t _dstX, uint16_t _dstY, uint16_t _dstZ, TextureHandle _src, uint8_t _srcMip, uint16_t _srcX, uint16_t _srcY, uint16_t _srcZ, uint16_t _width, uint16_t _height, uint16_t _depth)
  4644. {
  4645. BGFX_CHECK_ENCODER0();
  4646. s_ctx->m_encoder0->blit(_id, _dst, _dstMip, _dstX, _dstY, _dstZ, _src, _srcMip, _srcX, _srcY, _srcZ, _width, _height, _depth);
  4647. }
  4648. void requestScreenShot(FrameBufferHandle _handle, const char* _filePath)
  4649. {
  4650. BGFX_CHECK_API_THREAD();
  4651. s_ctx->requestScreenShot(_handle, _filePath);
  4652. }
  4653. #undef BGFX_CHECK_ENCODER0
  4654. } // namespace bgfx
  4655. #if BGFX_CONFIG_PREFER_DISCRETE_GPU
  4656. extern "C"
  4657. {
  4658. // When laptop setup has integrated and discrete GPU, following driver workarounds will
  4659. // select discrete GPU:
  4660. // Reference(s):
  4661. // - https://web.archive.org/web/20180722051003/https://docs.nvidia.com/gameworks/content/technologies/desktop/optimus.htm
  4662. //
  4663. __declspec(dllexport) uint32_t NvOptimusEnablement = UINT32_C(1);
  4664. // Reference(s):
  4665. // - https://web.archive.org/web/20180722051032/https://gpuopen.com/amdpowerxpressrequesthighperformance/
  4666. //
  4667. __declspec(dllexport) uint32_t AmdPowerXpressRequestHighPerformance = UINT32_C(1);
  4668. }
  4669. #endif // BGFX_CONFIG_PREFER_DISCRETE_GPU
  4670. #define BGFX_TEXTURE_FORMAT_BIMG(_fmt) \
  4671. BX_STATIC_ASSERT(uint32_t(bgfx::TextureFormat::_fmt) == uint32_t(bimg::TextureFormat::_fmt) )
  4672. BGFX_TEXTURE_FORMAT_BIMG(BC1);
  4673. BGFX_TEXTURE_FORMAT_BIMG(BC2);
  4674. BGFX_TEXTURE_FORMAT_BIMG(BC3);
  4675. BGFX_TEXTURE_FORMAT_BIMG(BC4);
  4676. BGFX_TEXTURE_FORMAT_BIMG(BC5);
  4677. BGFX_TEXTURE_FORMAT_BIMG(BC6H);
  4678. BGFX_TEXTURE_FORMAT_BIMG(BC7);
  4679. BGFX_TEXTURE_FORMAT_BIMG(ETC1);
  4680. BGFX_TEXTURE_FORMAT_BIMG(ETC2);
  4681. BGFX_TEXTURE_FORMAT_BIMG(ETC2A);
  4682. BGFX_TEXTURE_FORMAT_BIMG(ETC2A1);
  4683. BGFX_TEXTURE_FORMAT_BIMG(PTC12);
  4684. BGFX_TEXTURE_FORMAT_BIMG(PTC14);
  4685. BGFX_TEXTURE_FORMAT_BIMG(PTC12A);
  4686. BGFX_TEXTURE_FORMAT_BIMG(PTC14A);
  4687. BGFX_TEXTURE_FORMAT_BIMG(PTC22);
  4688. BGFX_TEXTURE_FORMAT_BIMG(PTC24);
  4689. BGFX_TEXTURE_FORMAT_BIMG(ATC);
  4690. BGFX_TEXTURE_FORMAT_BIMG(ATCE);
  4691. BGFX_TEXTURE_FORMAT_BIMG(ATCI);
  4692. BGFX_TEXTURE_FORMAT_BIMG(ASTC4x4);
  4693. BGFX_TEXTURE_FORMAT_BIMG(ASTC5x4);
  4694. BGFX_TEXTURE_FORMAT_BIMG(ASTC5x5);
  4695. BGFX_TEXTURE_FORMAT_BIMG(ASTC6x5);
  4696. BGFX_TEXTURE_FORMAT_BIMG(ASTC6x6);
  4697. BGFX_TEXTURE_FORMAT_BIMG(ASTC8x5);
  4698. BGFX_TEXTURE_FORMAT_BIMG(ASTC8x6);
  4699. BGFX_TEXTURE_FORMAT_BIMG(ASTC8x8);
  4700. BGFX_TEXTURE_FORMAT_BIMG(ASTC10x5);
  4701. BGFX_TEXTURE_FORMAT_BIMG(ASTC10x6);
  4702. BGFX_TEXTURE_FORMAT_BIMG(ASTC10x8);
  4703. BGFX_TEXTURE_FORMAT_BIMG(ASTC10x10);
  4704. BGFX_TEXTURE_FORMAT_BIMG(ASTC12x10);
  4705. BGFX_TEXTURE_FORMAT_BIMG(ASTC12x12);
  4706. BGFX_TEXTURE_FORMAT_BIMG(Unknown);
  4707. BGFX_TEXTURE_FORMAT_BIMG(R1);
  4708. BGFX_TEXTURE_FORMAT_BIMG(A8);
  4709. BGFX_TEXTURE_FORMAT_BIMG(R8);
  4710. BGFX_TEXTURE_FORMAT_BIMG(R8I);
  4711. BGFX_TEXTURE_FORMAT_BIMG(R8U);
  4712. BGFX_TEXTURE_FORMAT_BIMG(R8S);
  4713. BGFX_TEXTURE_FORMAT_BIMG(R16);
  4714. BGFX_TEXTURE_FORMAT_BIMG(R16I);
  4715. BGFX_TEXTURE_FORMAT_BIMG(R16U);
  4716. BGFX_TEXTURE_FORMAT_BIMG(R16F);
  4717. BGFX_TEXTURE_FORMAT_BIMG(R16S);
  4718. BGFX_TEXTURE_FORMAT_BIMG(R32I);
  4719. BGFX_TEXTURE_FORMAT_BIMG(R32U);
  4720. BGFX_TEXTURE_FORMAT_BIMG(R32F);
  4721. BGFX_TEXTURE_FORMAT_BIMG(RG8);
  4722. BGFX_TEXTURE_FORMAT_BIMG(RG8I);
  4723. BGFX_TEXTURE_FORMAT_BIMG(RG8U);
  4724. BGFX_TEXTURE_FORMAT_BIMG(RG8S);
  4725. BGFX_TEXTURE_FORMAT_BIMG(RG16);
  4726. BGFX_TEXTURE_FORMAT_BIMG(RG16I);
  4727. BGFX_TEXTURE_FORMAT_BIMG(RG16U);
  4728. BGFX_TEXTURE_FORMAT_BIMG(RG16F);
  4729. BGFX_TEXTURE_FORMAT_BIMG(RG16S);
  4730. BGFX_TEXTURE_FORMAT_BIMG(RG32I);
  4731. BGFX_TEXTURE_FORMAT_BIMG(RG32U);
  4732. BGFX_TEXTURE_FORMAT_BIMG(RG32F);
  4733. BGFX_TEXTURE_FORMAT_BIMG(RGB8);
  4734. BGFX_TEXTURE_FORMAT_BIMG(RGB8I);
  4735. BGFX_TEXTURE_FORMAT_BIMG(RGB8U);
  4736. BGFX_TEXTURE_FORMAT_BIMG(RGB8S);
  4737. BGFX_TEXTURE_FORMAT_BIMG(RGB9E5F);
  4738. BGFX_TEXTURE_FORMAT_BIMG(BGRA8);
  4739. BGFX_TEXTURE_FORMAT_BIMG(RGBA8);
  4740. BGFX_TEXTURE_FORMAT_BIMG(RGBA8I);
  4741. BGFX_TEXTURE_FORMAT_BIMG(RGBA8U);
  4742. BGFX_TEXTURE_FORMAT_BIMG(RGBA8S);
  4743. BGFX_TEXTURE_FORMAT_BIMG(RGBA16);
  4744. BGFX_TEXTURE_FORMAT_BIMG(RGBA16I);
  4745. BGFX_TEXTURE_FORMAT_BIMG(RGBA16U);
  4746. BGFX_TEXTURE_FORMAT_BIMG(RGBA16F);
  4747. BGFX_TEXTURE_FORMAT_BIMG(RGBA16S);
  4748. BGFX_TEXTURE_FORMAT_BIMG(RGBA32I);
  4749. BGFX_TEXTURE_FORMAT_BIMG(RGBA32U);
  4750. BGFX_TEXTURE_FORMAT_BIMG(RGBA32F);
  4751. BGFX_TEXTURE_FORMAT_BIMG(B5G6R5);
  4752. BGFX_TEXTURE_FORMAT_BIMG(R5G6B5);
  4753. BGFX_TEXTURE_FORMAT_BIMG(BGRA4);
  4754. BGFX_TEXTURE_FORMAT_BIMG(RGBA4);
  4755. BGFX_TEXTURE_FORMAT_BIMG(BGR5A1);
  4756. BGFX_TEXTURE_FORMAT_BIMG(RGB5A1);
  4757. BGFX_TEXTURE_FORMAT_BIMG(RGB10A2);
  4758. BGFX_TEXTURE_FORMAT_BIMG(RG11B10F);
  4759. BGFX_TEXTURE_FORMAT_BIMG(UnknownDepth);
  4760. BGFX_TEXTURE_FORMAT_BIMG(D16);
  4761. BGFX_TEXTURE_FORMAT_BIMG(D24);
  4762. BGFX_TEXTURE_FORMAT_BIMG(D24S8);
  4763. BGFX_TEXTURE_FORMAT_BIMG(D32);
  4764. BGFX_TEXTURE_FORMAT_BIMG(D16F);
  4765. BGFX_TEXTURE_FORMAT_BIMG(D24F);
  4766. BGFX_TEXTURE_FORMAT_BIMG(D32F);
  4767. BGFX_TEXTURE_FORMAT_BIMG(D0S8);
  4768. BGFX_TEXTURE_FORMAT_BIMG(Count);
  4769. #undef BGFX_TEXTURE_FORMAT_BIMG
  4770. #include <bgfx/c99/bgfx.h>
  4771. #define FLAGS_MASK_TEST(_flags, _mask) ( (_flags) == ( (_flags) & (_mask) ) )
  4772. BX_STATIC_ASSERT(FLAGS_MASK_TEST(0
  4773. | BGFX_SAMPLER_INTERNAL_DEFAULT
  4774. | BGFX_SAMPLER_INTERNAL_SHARED
  4775. , BGFX_SAMPLER_RESERVED_MASK
  4776. ) );
  4777. BX_STATIC_ASSERT(FLAGS_MASK_TEST(0
  4778. | BGFX_RESET_INTERNAL_FORCE
  4779. , BGFX_RESET_RESERVED_MASK
  4780. ) );
  4781. BX_STATIC_ASSERT(FLAGS_MASK_TEST(0
  4782. | BGFX_STATE_INTERNAL_SCISSOR
  4783. | BGFX_STATE_INTERNAL_OCCLUSION_QUERY
  4784. , BGFX_STATE_RESERVED_MASK
  4785. ) );
  4786. BX_STATIC_ASSERT(FLAGS_MASK_TEST(0
  4787. | BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE
  4788. , BGFX_SUBMIT_INTERNAL_RESERVED_MASK
  4789. ) );
  4790. BX_STATIC_ASSERT( (0
  4791. | BGFX_STATE_ALPHA_REF_MASK
  4792. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  4793. | BGFX_STATE_BLEND_EQUATION_MASK
  4794. | BGFX_STATE_BLEND_INDEPENDENT
  4795. | BGFX_STATE_BLEND_MASK
  4796. | BGFX_STATE_CONSERVATIVE_RASTER
  4797. | BGFX_STATE_CULL_MASK
  4798. | BGFX_STATE_DEPTH_TEST_MASK
  4799. | BGFX_STATE_FRONT_CCW
  4800. | BGFX_STATE_LINEAA
  4801. | BGFX_STATE_MSAA
  4802. | BGFX_STATE_POINT_SIZE_MASK
  4803. | BGFX_STATE_PT_MASK
  4804. | BGFX_STATE_RESERVED_MASK
  4805. | BGFX_STATE_WRITE_MASK
  4806. ) == (0
  4807. ^ BGFX_STATE_ALPHA_REF_MASK
  4808. ^ BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  4809. ^ BGFX_STATE_BLEND_EQUATION_MASK
  4810. ^ BGFX_STATE_BLEND_INDEPENDENT
  4811. ^ BGFX_STATE_BLEND_MASK
  4812. ^ BGFX_STATE_CONSERVATIVE_RASTER
  4813. ^ BGFX_STATE_CULL_MASK
  4814. ^ BGFX_STATE_DEPTH_TEST_MASK
  4815. ^ BGFX_STATE_FRONT_CCW
  4816. ^ BGFX_STATE_LINEAA
  4817. ^ BGFX_STATE_MSAA
  4818. ^ BGFX_STATE_POINT_SIZE_MASK
  4819. ^ BGFX_STATE_PT_MASK
  4820. ^ BGFX_STATE_RESERVED_MASK
  4821. ^ BGFX_STATE_WRITE_MASK
  4822. ) );
  4823. BX_STATIC_ASSERT(FLAGS_MASK_TEST(BGFX_CAPS_TEXTURE_COMPARE_LEQUAL, BGFX_CAPS_TEXTURE_COMPARE_ALL) );
  4824. BX_STATIC_ASSERT( (0
  4825. | BGFX_CAPS_ALPHA_TO_COVERAGE
  4826. | BGFX_CAPS_BLEND_INDEPENDENT
  4827. | BGFX_CAPS_COMPUTE
  4828. | BGFX_CAPS_CONSERVATIVE_RASTER
  4829. | BGFX_CAPS_DRAW_INDIRECT
  4830. | BGFX_CAPS_FRAGMENT_DEPTH
  4831. | BGFX_CAPS_FRAGMENT_ORDERING
  4832. | BGFX_CAPS_GRAPHICS_DEBUGGER
  4833. | BGFX_CAPS_HDR10
  4834. | BGFX_CAPS_HIDPI
  4835. | BGFX_CAPS_INDEX32
  4836. | BGFX_CAPS_INSTANCING
  4837. | BGFX_CAPS_OCCLUSION_QUERY
  4838. | BGFX_CAPS_RENDERER_MULTITHREADED
  4839. | BGFX_CAPS_SWAP_CHAIN
  4840. | BGFX_CAPS_TEXTURE_2D_ARRAY
  4841. | BGFX_CAPS_TEXTURE_3D
  4842. | BGFX_CAPS_TEXTURE_BLIT
  4843. | BGFX_CAPS_TEXTURE_CUBE_ARRAY
  4844. | BGFX_CAPS_TEXTURE_DIRECT_ACCESS
  4845. | BGFX_CAPS_TEXTURE_READ_BACK
  4846. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  4847. | BGFX_CAPS_VERTEX_ATTRIB_UINT10
  4848. | BGFX_CAPS_VERTEX_ID
  4849. | BGFX_CAPS_VIEWPORT_LAYER_ARRAY
  4850. | BGFX_CAPS_DRAW_INDIRECT_COUNT
  4851. ) == (0
  4852. ^ BGFX_CAPS_ALPHA_TO_COVERAGE
  4853. ^ BGFX_CAPS_BLEND_INDEPENDENT
  4854. ^ BGFX_CAPS_COMPUTE
  4855. ^ BGFX_CAPS_CONSERVATIVE_RASTER
  4856. ^ BGFX_CAPS_DRAW_INDIRECT
  4857. ^ BGFX_CAPS_FRAGMENT_DEPTH
  4858. ^ BGFX_CAPS_FRAGMENT_ORDERING
  4859. ^ BGFX_CAPS_GRAPHICS_DEBUGGER
  4860. ^ BGFX_CAPS_HDR10
  4861. ^ BGFX_CAPS_HIDPI
  4862. ^ BGFX_CAPS_INDEX32
  4863. ^ BGFX_CAPS_INSTANCING
  4864. ^ BGFX_CAPS_OCCLUSION_QUERY
  4865. ^ BGFX_CAPS_RENDERER_MULTITHREADED
  4866. ^ BGFX_CAPS_SWAP_CHAIN
  4867. ^ BGFX_CAPS_TEXTURE_2D_ARRAY
  4868. ^ BGFX_CAPS_TEXTURE_3D
  4869. ^ BGFX_CAPS_TEXTURE_BLIT
  4870. ^ BGFX_CAPS_TEXTURE_CUBE_ARRAY
  4871. ^ BGFX_CAPS_TEXTURE_DIRECT_ACCESS
  4872. ^ BGFX_CAPS_TEXTURE_READ_BACK
  4873. ^ BGFX_CAPS_VERTEX_ATTRIB_HALF
  4874. ^ BGFX_CAPS_VERTEX_ATTRIB_UINT10
  4875. ^ BGFX_CAPS_VERTEX_ID
  4876. ^ BGFX_CAPS_VIEWPORT_LAYER_ARRAY
  4877. ^ BGFX_CAPS_DRAW_INDIRECT_COUNT
  4878. ) );
  4879. #undef FLAGS_MASK_TEST
  4880. namespace bgfx
  4881. {
  4882. struct CallbackC99 : public CallbackI
  4883. {
  4884. virtual ~CallbackC99()
  4885. {
  4886. }
  4887. virtual void fatal(const char* _filePath, uint16_t _line, Fatal::Enum _code, const char* _str) override
  4888. {
  4889. m_interface->vtbl->fatal(m_interface, _filePath, _line, (bgfx_fatal_t)_code, _str);
  4890. }
  4891. virtual void traceVargs(const char* _filePath, uint16_t _line, const char* _format, va_list _argList) override
  4892. {
  4893. m_interface->vtbl->trace_vargs(m_interface, _filePath, _line, _format, _argList);
  4894. }
  4895. virtual void profilerBegin(const char* _name, uint32_t _abgr, const char* _filePath, uint16_t _line) override
  4896. {
  4897. m_interface->vtbl->profiler_begin(m_interface, _name, _abgr, _filePath, _line);
  4898. }
  4899. virtual void profilerBeginLiteral(const char* _name, uint32_t _abgr, const char* _filePath, uint16_t _line) override
  4900. {
  4901. m_interface->vtbl->profiler_begin_literal(m_interface, _name, _abgr, _filePath, _line);
  4902. }
  4903. virtual void profilerEnd() override
  4904. {
  4905. m_interface->vtbl->profiler_end(m_interface);
  4906. }
  4907. virtual uint32_t cacheReadSize(uint64_t _id) override
  4908. {
  4909. return m_interface->vtbl->cache_read_size(m_interface, _id);
  4910. }
  4911. virtual bool cacheRead(uint64_t _id, void* _data, uint32_t _size) override
  4912. {
  4913. return m_interface->vtbl->cache_read(m_interface, _id, _data, _size);
  4914. }
  4915. virtual void cacheWrite(uint64_t _id, const void* _data, uint32_t _size) override
  4916. {
  4917. m_interface->vtbl->cache_write(m_interface, _id, _data, _size);
  4918. }
  4919. virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t _size, bool _yflip) override
  4920. {
  4921. m_interface->vtbl->screen_shot(m_interface, _filePath, _width, _height, _pitch, _data, _size, _yflip);
  4922. }
  4923. virtual void captureBegin(uint32_t _width, uint32_t _height, uint32_t _pitch, TextureFormat::Enum _format, bool _yflip) override
  4924. {
  4925. m_interface->vtbl->capture_begin(m_interface, _width, _height, _pitch, (bgfx_texture_format_t)_format, _yflip);
  4926. }
  4927. virtual void captureEnd() override
  4928. {
  4929. m_interface->vtbl->capture_end(m_interface);
  4930. }
  4931. virtual void captureFrame(const void* _data, uint32_t _size) override
  4932. {
  4933. m_interface->vtbl->capture_frame(m_interface, _data, _size);
  4934. }
  4935. bgfx_callback_interface_t* m_interface;
  4936. };
  4937. class AllocatorC99 : public bx::AllocatorI
  4938. {
  4939. public:
  4940. virtual ~AllocatorC99()
  4941. {
  4942. }
  4943. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line) override
  4944. {
  4945. return m_interface->vtbl->realloc(m_interface, _ptr, _size, _align, _file, _line);
  4946. }
  4947. bgfx_allocator_interface_t* m_interface;
  4948. };
  4949. } // namespace bgfx
  4950. #include "bgfx.idl.inl"