bgfx.cpp 151 KB

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