bgfx.cpp 156 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514
  1. /*
  2. * Copyright 2011-2021 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 <= 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. View& view = s_ctx->m_view[ii];
  1185. Rect rect(0, 0, uint16_t(m_resolution.width), uint16_t(m_resolution.height) );
  1186. if (isValid(view.m_fbh) )
  1187. {
  1188. const FrameBufferRef& fbr = s_ctx->m_frameBufferRef[view.m_fbh.idx];
  1189. const BackbufferRatio::Enum bbRatio = fbr.m_window
  1190. ? BackbufferRatio::Count
  1191. : BackbufferRatio::Enum(s_ctx->m_textureRef[fbr.un.m_th[0].idx].m_bbRatio)
  1192. ;
  1193. if (BackbufferRatio::Count != bbRatio)
  1194. {
  1195. getTextureSizeFromRatio(bbRatio, rect.m_width, rect.m_height);
  1196. }
  1197. else
  1198. {
  1199. rect.m_width = fbr.m_width;
  1200. rect.m_height = fbr.m_height;
  1201. }
  1202. }
  1203. view.m_rect.intersect(rect);
  1204. if (!view.m_scissor.isZero() )
  1205. {
  1206. view.m_scissor.intersect(rect);
  1207. }
  1208. }
  1209. for (uint32_t ii = 0, num = m_numRenderItems; ii < num; ++ii)
  1210. {
  1211. m_sortKeys[ii] = SortKey::remapView(m_sortKeys[ii], viewRemap);
  1212. }
  1213. bx::radixSort(m_sortKeys, s_ctx->m_tempKeys, m_sortValues, s_ctx->m_tempValues, m_numRenderItems);
  1214. for (uint32_t ii = 0, num = m_numBlitItems; ii < num; ++ii)
  1215. {
  1216. m_blitKeys[ii] = BlitKey::remapView(m_blitKeys[ii], viewRemap);
  1217. }
  1218. bx::radixSort(m_blitKeys, (uint32_t*)&s_ctx->m_tempKeys, m_numBlitItems);
  1219. }
  1220. RenderFrame::Enum renderFrame(int32_t _msecs)
  1221. {
  1222. if (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) )
  1223. {
  1224. if (s_renderFrameCalled)
  1225. {
  1226. BGFX_CHECK_RENDER_THREAD();
  1227. }
  1228. if (NULL == s_ctx)
  1229. {
  1230. s_renderFrameCalled = true;
  1231. s_threadIndex = ~BGFX_API_THREAD_MAGIC;
  1232. return RenderFrame::NoContext;
  1233. }
  1234. int32_t msecs = -1 == _msecs
  1235. ? BGFX_CONFIG_API_SEMAPHORE_TIMEOUT
  1236. : _msecs
  1237. ;
  1238. RenderFrame::Enum result = s_ctx->renderFrame(msecs);
  1239. if (RenderFrame::Exiting == result)
  1240. {
  1241. Context* ctx = s_ctx;
  1242. ctx->apiSemWait();
  1243. s_ctx = NULL;
  1244. ctx->renderSemPost();
  1245. }
  1246. return result;
  1247. }
  1248. BX_ASSERT(false, "This call only makes sense if used with multi-threaded renderer.");
  1249. return RenderFrame::NoContext;
  1250. }
  1251. const uint32_t g_uniformTypeSize[UniformType::Count+1] =
  1252. {
  1253. sizeof(int32_t),
  1254. 0,
  1255. 4*sizeof(float),
  1256. 3*3*sizeof(float),
  1257. 4*4*sizeof(float),
  1258. 1,
  1259. };
  1260. void UniformBuffer::writeUniform(UniformType::Enum _type, uint16_t _loc, const void* _value, uint16_t _num)
  1261. {
  1262. uint32_t opcode = encodeOpcode(_type, _loc, _num, true);
  1263. write(opcode);
  1264. write(_value, g_uniformTypeSize[_type]*_num);
  1265. }
  1266. void UniformBuffer::writeUniformHandle(UniformType::Enum _type, uint16_t _loc, UniformHandle _handle, uint16_t _num)
  1267. {
  1268. uint32_t opcode = encodeOpcode(_type, _loc, _num, false);
  1269. write(opcode);
  1270. write(&_handle, sizeof(UniformHandle) );
  1271. }
  1272. void UniformBuffer::writeMarker(const char* _marker)
  1273. {
  1274. uint16_t num = (uint16_t)bx::strLen(_marker)+1;
  1275. uint32_t opcode = encodeOpcode(bgfx::UniformType::Count, 0, num, true);
  1276. write(opcode);
  1277. write(_marker, num);
  1278. }
  1279. struct CapsFlags
  1280. {
  1281. uint64_t m_flag;
  1282. const char* m_str;
  1283. };
  1284. static const CapsFlags s_capsFlags[] =
  1285. {
  1286. #define CAPS_FLAGS(_x) { _x, #_x }
  1287. CAPS_FLAGS(BGFX_CAPS_ALPHA_TO_COVERAGE),
  1288. CAPS_FLAGS(BGFX_CAPS_BLEND_INDEPENDENT),
  1289. CAPS_FLAGS(BGFX_CAPS_COMPUTE),
  1290. CAPS_FLAGS(BGFX_CAPS_CONSERVATIVE_RASTER),
  1291. CAPS_FLAGS(BGFX_CAPS_DRAW_INDIRECT),
  1292. CAPS_FLAGS(BGFX_CAPS_FRAGMENT_DEPTH),
  1293. CAPS_FLAGS(BGFX_CAPS_FRAGMENT_ORDERING),
  1294. CAPS_FLAGS(BGFX_CAPS_GRAPHICS_DEBUGGER),
  1295. CAPS_FLAGS(BGFX_CAPS_HDR10),
  1296. CAPS_FLAGS(BGFX_CAPS_HIDPI),
  1297. CAPS_FLAGS(BGFX_CAPS_IMAGE_RW),
  1298. CAPS_FLAGS(BGFX_CAPS_INDEX32),
  1299. CAPS_FLAGS(BGFX_CAPS_INSTANCING),
  1300. CAPS_FLAGS(BGFX_CAPS_OCCLUSION_QUERY),
  1301. CAPS_FLAGS(BGFX_CAPS_RENDERER_MULTITHREADED),
  1302. CAPS_FLAGS(BGFX_CAPS_SWAP_CHAIN),
  1303. CAPS_FLAGS(BGFX_CAPS_TEXTURE_2D_ARRAY),
  1304. CAPS_FLAGS(BGFX_CAPS_TEXTURE_3D),
  1305. CAPS_FLAGS(BGFX_CAPS_TEXTURE_BLIT),
  1306. CAPS_FLAGS(BGFX_CAPS_TEXTURE_COMPARE_ALL),
  1307. CAPS_FLAGS(BGFX_CAPS_TEXTURE_COMPARE_LEQUAL),
  1308. CAPS_FLAGS(BGFX_CAPS_TEXTURE_CUBE_ARRAY),
  1309. CAPS_FLAGS(BGFX_CAPS_TEXTURE_DIRECT_ACCESS),
  1310. CAPS_FLAGS(BGFX_CAPS_TEXTURE_READ_BACK),
  1311. CAPS_FLAGS(BGFX_CAPS_VERTEX_ATTRIB_HALF),
  1312. CAPS_FLAGS(BGFX_CAPS_VERTEX_ATTRIB_UINT10),
  1313. CAPS_FLAGS(BGFX_CAPS_VERTEX_ID),
  1314. CAPS_FLAGS(BGFX_CAPS_VIEWPORT_LAYER_ARRAY),
  1315. #undef CAPS_FLAGS
  1316. };
  1317. static void dumpCaps()
  1318. {
  1319. BX_TRACE("");
  1320. if (0 < g_caps.numGPUs)
  1321. {
  1322. BX_TRACE("Detected GPUs (%d):", g_caps.numGPUs);
  1323. BX_TRACE("\t +---------------- Index");
  1324. BX_TRACE("\t | +------------- Device ID");
  1325. BX_TRACE("\t | | +-------- Vendor ID");
  1326. for (uint32_t ii = 0; ii < g_caps.numGPUs; ++ii)
  1327. {
  1328. const Caps::GPU& gpu = g_caps.gpu[ii];
  1329. BX_UNUSED(gpu);
  1330. BX_TRACE("\t %d: %04x %04x"
  1331. , ii
  1332. , gpu.deviceId
  1333. , gpu.vendorId
  1334. );
  1335. }
  1336. BX_TRACE("");
  1337. }
  1338. RendererType::Enum renderers[RendererType::Count];
  1339. uint8_t num = getSupportedRenderers(BX_COUNTOF(renderers), renderers);
  1340. BX_TRACE("Supported renderer backends (%d):", num);
  1341. for (uint32_t ii = 0; ii < num; ++ii)
  1342. {
  1343. BX_TRACE("\t - %s", getRendererName(renderers[ii]) );
  1344. }
  1345. BX_TRACE("");
  1346. BX_TRACE("Sort key masks:");
  1347. BX_TRACE("\t View %016" PRIx64, kSortKeyViewMask);
  1348. BX_TRACE("\t Draw bit %016" PRIx64, kSortKeyDrawBit);
  1349. BX_TRACE("");
  1350. BX_TRACE("\tD Type %016" PRIx64, kSortKeyDrawTypeMask);
  1351. BX_TRACE("");
  1352. BX_TRACE("\tD0 Blend %016" PRIx64, kSortKeyDraw0BlendMask);
  1353. BX_TRACE("\tD0 Program %016" PRIx64, kSortKeyDraw0ProgramMask);
  1354. BX_TRACE("\tD0 Depth %016" PRIx64, kSortKeyDraw0DepthMask);
  1355. BX_TRACE("");
  1356. BX_TRACE("\tD1 Depth %016" PRIx64, kSortKeyDraw1DepthMask);
  1357. BX_TRACE("\tD1 Blend %016" PRIx64, kSortKeyDraw1BlendMask);
  1358. BX_TRACE("\tD1 Program %016" PRIx64, kSortKeyDraw1ProgramMask);
  1359. BX_TRACE("");
  1360. BX_TRACE("\tD2 Seq %016" PRIx64, kSortKeyDraw2SeqMask);
  1361. BX_TRACE("\tD2 Blend %016" PRIx64, kSortKeyDraw2BlendMask);
  1362. BX_TRACE("\tD2 Program %016" PRIx64, kSortKeyDraw2ProgramMask);
  1363. BX_TRACE("");
  1364. BX_TRACE("\t C Seq %016" PRIx64, kSortKeyComputeSeqMask);
  1365. BX_TRACE("\t C Program %016" PRIx64, kSortKeyComputeProgramMask);
  1366. BX_TRACE("");
  1367. BX_TRACE("Capabilities (renderer %s, vendor 0x%04x, device 0x%04x):"
  1368. , s_ctx->m_renderCtx->getRendererName()
  1369. , g_caps.vendorId
  1370. , g_caps.deviceId
  1371. );
  1372. for (uint32_t ii = 0; ii < BX_COUNTOF(s_capsFlags); ++ii)
  1373. {
  1374. BX_TRACE("\t[%c] %s"
  1375. , 0 != (g_caps.supported & s_capsFlags[ii].m_flag) ? 'x' : ' '
  1376. , s_capsFlags[ii].m_str
  1377. );
  1378. }
  1379. BX_UNUSED(s_capsFlags);
  1380. BX_TRACE("");
  1381. BX_TRACE("Limits:");
  1382. #define LIMITS(_x) BX_TRACE("\t%-24s%10d", #_x, g_caps.limits._x)
  1383. LIMITS(maxDrawCalls);
  1384. LIMITS(maxBlits);
  1385. LIMITS(maxTextureSize);
  1386. LIMITS(maxTextureLayers);
  1387. LIMITS(maxViews);
  1388. LIMITS(maxFrameBuffers);
  1389. LIMITS(maxFBAttachments);
  1390. LIMITS(maxPrograms);
  1391. LIMITS(maxShaders);
  1392. LIMITS(maxTextures);
  1393. LIMITS(maxTextureSamplers);
  1394. LIMITS(maxComputeBindings);
  1395. LIMITS(maxVertexLayouts);
  1396. LIMITS(maxVertexStreams);
  1397. LIMITS(maxIndexBuffers);
  1398. LIMITS(maxVertexBuffers);
  1399. LIMITS(maxDynamicIndexBuffers);
  1400. LIMITS(maxDynamicVertexBuffers);
  1401. LIMITS(maxUniforms);
  1402. LIMITS(maxOcclusionQueries);
  1403. LIMITS(maxEncoders);
  1404. LIMITS(minResourceCbSize);
  1405. LIMITS(transientVbSize);
  1406. LIMITS(transientIbSize);
  1407. #undef LIMITS
  1408. BX_TRACE("");
  1409. BX_TRACE("Supported texture formats:");
  1410. BX_TRACE("\t +---------------- 2D: x = supported / * = emulated");
  1411. BX_TRACE("\t |+--------------- 2D: sRGB format");
  1412. BX_TRACE("\t ||+-------------- 3D: x = supported / * = emulated");
  1413. BX_TRACE("\t |||+------------- 3D: sRGB format");
  1414. BX_TRACE("\t ||||+------------ Cube: x = supported / * = emulated");
  1415. BX_TRACE("\t |||||+----------- Cube: sRGB format");
  1416. BX_TRACE("\t ||||||+---------- vertex format");
  1417. BX_TRACE("\t |||||||+--------- image: i = read-write / r = read / w = write");
  1418. BX_TRACE("\t ||||||||+-------- framebuffer");
  1419. BX_TRACE("\t |||||||||+------- MSAA framebuffer");
  1420. BX_TRACE("\t ||||||||||+------ MSAA texture");
  1421. BX_TRACE("\t |||||||||||+----- Auto-generated mips");
  1422. BX_TRACE("\t |||||||||||| +-- name");
  1423. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1424. {
  1425. if (TextureFormat::Unknown != ii
  1426. && TextureFormat::UnknownDepth != ii)
  1427. {
  1428. uint32_t flags = g_caps.formats[ii];
  1429. BX_TRACE("\t[%c%c%c%c%c%c%c%c%c%c%c%c] %s"
  1430. , flags&BGFX_CAPS_FORMAT_TEXTURE_2D ? 'x' : flags&BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED ? '*' : ' '
  1431. , flags&BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB ? 'l' : ' '
  1432. , flags&BGFX_CAPS_FORMAT_TEXTURE_3D ? 'x' : flags&BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED ? '*' : ' '
  1433. , flags&BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB ? 'l' : ' '
  1434. , flags&BGFX_CAPS_FORMAT_TEXTURE_CUBE ? 'x' : flags&BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED ? '*' : ' '
  1435. , flags&BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB ? 'l' : ' '
  1436. , flags&BGFX_CAPS_FORMAT_TEXTURE_VERTEX ? 'v' : ' '
  1437. , (flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_READ) &&
  1438. (flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_WRITE) ? 'i' : flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_READ ? 'r' : flags&BGFX_CAPS_FORMAT_TEXTURE_IMAGE_WRITE ? 'w' : ' '
  1439. , flags&BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER ? 'f' : ' '
  1440. , flags&BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA ? '+' : ' '
  1441. , flags&BGFX_CAPS_FORMAT_TEXTURE_MSAA ? 'm' : ' '
  1442. , flags&BGFX_CAPS_FORMAT_TEXTURE_MIP_AUTOGEN ? 'M' : ' '
  1443. , getName(TextureFormat::Enum(ii) )
  1444. );
  1445. BX_UNUSED(flags);
  1446. }
  1447. }
  1448. BX_TRACE("");
  1449. BX_TRACE("NDC depth [%d, 1], origin %s left."
  1450. , g_caps.homogeneousDepth ? -1 : 0
  1451. , g_caps.originBottomLeft ? "bottom" : "top"
  1452. );
  1453. BX_TRACE("");
  1454. }
  1455. void dump(const Resolution& _resolution)
  1456. {
  1457. const uint32_t reset = _resolution.reset;
  1458. const uint32_t msaa = (reset&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  1459. BX_UNUSED(reset, msaa);
  1460. BX_TRACE("Reset back-buffer swap chain:");
  1461. BX_TRACE("\t%dx%d, format: %s, numBackBuffers: %d, maxFrameLatency: %d"
  1462. , _resolution.width
  1463. , _resolution.height
  1464. , TextureFormat::Count == _resolution.format
  1465. ? "*default*"
  1466. : bimg::getName(bimg::TextureFormat::Enum(_resolution.format) )
  1467. , _resolution.numBackBuffers
  1468. , _resolution.maxFrameLatency
  1469. );
  1470. BX_TRACE("\t[%c] MSAAx%d", 0 != msaa ? 'x' : ' ', 1<<msaa);
  1471. BX_TRACE("\t[%c] Fullscreen", 0 != (reset & BGFX_RESET_FULLSCREEN) ? 'x' : ' ');
  1472. BX_TRACE("\t[%c] V-sync", 0 != (reset & BGFX_RESET_VSYNC) ? 'x' : ' ');
  1473. BX_TRACE("\t[%c] Max Anisotropy", 0 != (reset & BGFX_RESET_MAXANISOTROPY) ? 'x' : ' ');
  1474. BX_TRACE("\t[%c] Capture", 0 != (reset & BGFX_RESET_CAPTURE) ? 'x' : ' ');
  1475. BX_TRACE("\t[%c] Flush After Render", 0 != (reset & BGFX_RESET_FLUSH_AFTER_RENDER) ? 'x' : ' ');
  1476. BX_TRACE("\t[%c] Flip After Render", 0 != (reset & BGFX_RESET_FLIP_AFTER_RENDER) ? 'x' : ' ');
  1477. BX_TRACE("\t[%c] sRGB Back Buffer", 0 != (reset & BGFX_RESET_SRGB_BACKBUFFER) ? 'x' : ' ');
  1478. BX_TRACE("\t[%c] HDR10", 0 != (reset & BGFX_RESET_HDR10) ? 'x' : ' ');
  1479. BX_TRACE("\t[%c] Hi-DPI", 0 != (reset & BGFX_RESET_HIDPI) ? 'x' : ' ');
  1480. BX_TRACE("\t[%c] Depth Clamp", 0 != (reset & BGFX_RESET_DEPTH_CLAMP) ? 'x' : ' ');
  1481. BX_TRACE("\t[%c] Suspend", 0 != (reset & BGFX_RESET_SUSPEND) ? 'x' : ' ');
  1482. }
  1483. TextureFormat::Enum getViableTextureFormat(const bimg::ImageContainer& _imageContainer)
  1484. {
  1485. const uint32_t formatCaps = g_caps.formats[_imageContainer.m_format];
  1486. bool convert = 0 == formatCaps;
  1487. if (_imageContainer.m_cubeMap)
  1488. {
  1489. convert |= 0 == (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_CUBE)
  1490. && 0 != (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED)
  1491. ;
  1492. }
  1493. else if (_imageContainer.m_depth > 1)
  1494. {
  1495. convert |= 0 == (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_3D)
  1496. && 0 != (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED)
  1497. ;
  1498. }
  1499. else
  1500. {
  1501. convert |= 0 == (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_2D)
  1502. && 0 != (formatCaps & BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED)
  1503. ;
  1504. }
  1505. if (convert)
  1506. {
  1507. return TextureFormat::BGRA8;
  1508. }
  1509. return TextureFormat::Enum(_imageContainer.m_format);
  1510. }
  1511. const char* getName(TextureFormat::Enum _fmt)
  1512. {
  1513. return bimg::getName(bimg::TextureFormat::Enum(_fmt));
  1514. }
  1515. const char* getName(UniformHandle _handle)
  1516. {
  1517. return s_ctx->m_uniformRef[_handle.idx].m_name.getPtr();
  1518. }
  1519. const char* getName(ShaderHandle _handle)
  1520. {
  1521. return s_ctx->m_shaderRef[_handle.idx].m_name.getPtr();
  1522. }
  1523. static const char* s_topologyName[] =
  1524. {
  1525. "Triangles",
  1526. "TriStrip",
  1527. "Lines",
  1528. "LineStrip",
  1529. "Points",
  1530. };
  1531. BX_STATIC_ASSERT(Topology::Count == BX_COUNTOF(s_topologyName) );
  1532. const char* getName(Topology::Enum _topology)
  1533. {
  1534. return s_topologyName[bx::min(_topology, Topology::PointList)];
  1535. }
  1536. const char* getShaderTypeName(uint32_t _magic)
  1537. {
  1538. if (isShaderType(_magic, 'C') )
  1539. {
  1540. return "Compute";
  1541. }
  1542. else if (isShaderType(_magic, 'F') )
  1543. {
  1544. return "Fragment";
  1545. }
  1546. else if (isShaderType(_magic, 'V') )
  1547. {
  1548. return "Vertex";
  1549. }
  1550. BX_ASSERT(false, "Invalid shader type!");
  1551. return NULL;
  1552. }
  1553. static TextureFormat::Enum s_emulatedFormats[] =
  1554. {
  1555. TextureFormat::BC1,
  1556. TextureFormat::BC2,
  1557. TextureFormat::BC3,
  1558. TextureFormat::BC4,
  1559. TextureFormat::BC5,
  1560. TextureFormat::ETC1,
  1561. TextureFormat::ETC2,
  1562. TextureFormat::ETC2A,
  1563. TextureFormat::ETC2A1,
  1564. TextureFormat::PTC12,
  1565. TextureFormat::PTC14,
  1566. TextureFormat::PTC12A,
  1567. TextureFormat::PTC14A,
  1568. TextureFormat::PTC22,
  1569. TextureFormat::PTC24,
  1570. TextureFormat::ATC,
  1571. TextureFormat::ATCE,
  1572. TextureFormat::ATCI,
  1573. TextureFormat::ASTC4x4,
  1574. TextureFormat::ASTC5x5,
  1575. TextureFormat::ASTC6x6,
  1576. TextureFormat::ASTC8x5,
  1577. TextureFormat::ASTC8x6,
  1578. TextureFormat::ASTC10x5,
  1579. TextureFormat::BGRA8, // GL doesn't support BGRA8 without extensions.
  1580. TextureFormat::RGBA8, // D3D9 doesn't support RGBA8
  1581. };
  1582. bool Context::init(const Init& _init)
  1583. {
  1584. BX_ASSERT(!m_rendererInitialized, "Already initialized?");
  1585. m_init = _init;
  1586. m_init.resolution.reset &= ~BGFX_RESET_INTERNAL_FORCE;
  1587. m_init.resolution.numBackBuffers = bx::clamp<uint8_t>(_init.resolution.numBackBuffers, 2, BGFX_CONFIG_MAX_BACK_BUFFERS);
  1588. m_init.resolution.maxFrameLatency = bx::min<uint8_t>(_init.resolution.maxFrameLatency, BGFX_CONFIG_MAX_FRAME_LATENCY);
  1589. dump(m_init.resolution);
  1590. if (g_platformData.ndt == NULL
  1591. && g_platformData.nwh == NULL
  1592. && g_platformData.context == NULL
  1593. && g_platformData.backBuffer == NULL
  1594. && g_platformData.backBufferDS == NULL)
  1595. {
  1596. bx::memCopy(&g_platformData, &m_init.platformData, sizeof(PlatformData) );
  1597. }
  1598. else
  1599. {
  1600. bx::memCopy(&m_init.platformData, &g_platformData, sizeof(PlatformData) );
  1601. }
  1602. if (true
  1603. && !BX_ENABLED(BX_PLATFORM_EMSCRIPTEN || BX_PLATFORM_PS4)
  1604. && RendererType::Noop != m_init.type
  1605. && NULL == m_init.platformData.ndt
  1606. && NULL == m_init.platformData.nwh
  1607. && NULL == m_init.platformData.context
  1608. && NULL == m_init.platformData.backBuffer
  1609. && NULL == m_init.platformData.backBufferDS
  1610. )
  1611. {
  1612. BX_TRACE("bgfx platform data like window handle or backbuffer is not set, creating headless device.");
  1613. }
  1614. m_exit = false;
  1615. m_flipped = true;
  1616. m_frames = 0;
  1617. m_debug = BGFX_DEBUG_NONE;
  1618. m_frameTimeLast = bx::getHPCounter();
  1619. m_submit->create(_init.limits.minResourceCbSize);
  1620. #if BGFX_CONFIG_MULTITHREADED
  1621. m_render->create(_init.limits.minResourceCbSize);
  1622. if (s_renderFrameCalled)
  1623. {
  1624. // When bgfx::renderFrame is called before init render thread
  1625. // should not be created.
  1626. BX_TRACE("Application called bgfx::renderFrame directly, not creating render thread.");
  1627. m_singleThreaded = true
  1628. && ~BGFX_API_THREAD_MAGIC == s_threadIndex
  1629. ;
  1630. }
  1631. else
  1632. {
  1633. BX_TRACE("Creating rendering thread.");
  1634. m_thread.init(renderThread, this, 0, "bgfx - renderer backend thread");
  1635. m_singleThreaded = false;
  1636. }
  1637. #else
  1638. BX_TRACE("Multithreaded renderer is disabled.");
  1639. m_singleThreaded = true;
  1640. #endif // BGFX_CONFIG_MULTITHREADED
  1641. BX_TRACE("Running in %s-threaded mode", m_singleThreaded ? "single" : "multi");
  1642. s_threadIndex = BGFX_API_THREAD_MAGIC;
  1643. for (uint32_t ii = 0; ii < BX_COUNTOF(m_viewRemap); ++ii)
  1644. {
  1645. m_viewRemap[ii] = ViewId(ii);
  1646. }
  1647. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1648. {
  1649. resetView(ViewId(ii) );
  1650. }
  1651. for (uint32_t ii = 0; ii < BX_COUNTOF(m_clearColor); ++ii)
  1652. {
  1653. m_clearColor[ii][0] = 0.0f;
  1654. m_clearColor[ii][1] = 0.0f;
  1655. m_clearColor[ii][2] = 0.0f;
  1656. m_clearColor[ii][3] = 1.0f;
  1657. }
  1658. m_vertexLayoutRef.init();
  1659. CommandBuffer& cmdbuf = getCommandBuffer(CommandBuffer::RendererInit);
  1660. cmdbuf.write(_init);
  1661. frameNoRenderWait();
  1662. m_encoderHandle = bx::createHandleAlloc(g_allocator, _init.limits.maxEncoders);
  1663. m_encoder = (EncoderImpl*)BX_ALIGNED_ALLOC(g_allocator, sizeof(EncoderImpl)*_init.limits.maxEncoders, BX_ALIGNOF(EncoderImpl) );
  1664. m_encoderStats = (EncoderStats*)BX_ALLOC(g_allocator, sizeof(EncoderStats)*_init.limits.maxEncoders);
  1665. for (uint32_t ii = 0, num = _init.limits.maxEncoders; ii < num; ++ii)
  1666. {
  1667. BX_PLACEMENT_NEW(&m_encoder[ii], EncoderImpl);
  1668. }
  1669. uint16_t idx = m_encoderHandle->alloc();
  1670. BX_ASSERT(0 == idx, "Internal encoder handle is not 0 (idx %d).", idx); BX_UNUSED(idx);
  1671. m_encoder[0].begin(m_submit, 0);
  1672. m_encoder0 = reinterpret_cast<Encoder*>(&m_encoder[0]);
  1673. // Make sure renderer init is called from render thread.
  1674. // g_caps is initialized and available after this point.
  1675. frame();
  1676. if (!m_rendererInitialized)
  1677. {
  1678. getCommandBuffer(CommandBuffer::RendererShutdownEnd);
  1679. frame();
  1680. frame();
  1681. m_vertexLayoutRef.shutdown(m_layoutHandle);
  1682. m_submit->destroy();
  1683. #if BGFX_CONFIG_MULTITHREADED
  1684. m_render->destroy();
  1685. #endif // BGFX_CONFIG_MULTITHREADED
  1686. return false;
  1687. }
  1688. for (uint32_t ii = 0; ii < BX_COUNTOF(s_emulatedFormats); ++ii)
  1689. {
  1690. const uint32_t fmt = s_emulatedFormats[ii];
  1691. g_caps.formats[fmt] |= 0 == (g_caps.formats[fmt] & BGFX_CAPS_FORMAT_TEXTURE_2D ) ? BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED : 0;
  1692. g_caps.formats[fmt] |= 0 == (g_caps.formats[fmt] & BGFX_CAPS_FORMAT_TEXTURE_3D ) ? BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED : 0;
  1693. g_caps.formats[fmt] |= 0 == (g_caps.formats[fmt] & BGFX_CAPS_FORMAT_TEXTURE_CUBE) ? BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED : 0;
  1694. }
  1695. for (uint32_t ii = 0; ii < TextureFormat::UnknownDepth; ++ii)
  1696. {
  1697. bool convertable = bimg::imageConvert(bimg::TextureFormat::BGRA8, bimg::TextureFormat::Enum(ii) );
  1698. g_caps.formats[ii] |= 0 == (g_caps.formats[ii] & BGFX_CAPS_FORMAT_TEXTURE_2D ) && convertable ? BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED : 0;
  1699. g_caps.formats[ii] |= 0 == (g_caps.formats[ii] & BGFX_CAPS_FORMAT_TEXTURE_3D ) && convertable ? BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED : 0;
  1700. g_caps.formats[ii] |= 0 == (g_caps.formats[ii] & BGFX_CAPS_FORMAT_TEXTURE_CUBE) && convertable ? BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED : 0;
  1701. }
  1702. g_caps.rendererType = m_renderCtx->getRendererType();
  1703. initAttribTypeSizeTable(g_caps.rendererType);
  1704. g_caps.supported |= 0
  1705. | (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) && !m_singleThreaded ? BGFX_CAPS_RENDERER_MULTITHREADED : 0)
  1706. | (isGraphicsDebuggerPresent() ? BGFX_CAPS_GRAPHICS_DEBUGGER : 0)
  1707. ;
  1708. dumpCaps();
  1709. m_textVideoMemBlitter.init();
  1710. m_clearQuad.init();
  1711. m_submit->m_transientVb = createTransientVertexBuffer(_init.limits.transientVbSize);
  1712. m_submit->m_transientIb = createTransientIndexBuffer(_init.limits.transientIbSize);
  1713. frame();
  1714. if (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) )
  1715. {
  1716. m_submit->m_transientVb = createTransientVertexBuffer(_init.limits.transientVbSize);
  1717. m_submit->m_transientIb = createTransientIndexBuffer(_init.limits.transientIbSize);
  1718. frame();
  1719. }
  1720. g_internalData.caps = getCaps();
  1721. return true;
  1722. }
  1723. void Context::shutdown()
  1724. {
  1725. getCommandBuffer(CommandBuffer::RendererShutdownBegin);
  1726. frame();
  1727. destroyTransientVertexBuffer(m_submit->m_transientVb);
  1728. destroyTransientIndexBuffer(m_submit->m_transientIb);
  1729. m_textVideoMemBlitter.shutdown();
  1730. m_clearQuad.shutdown();
  1731. frame();
  1732. if (BX_ENABLED(BGFX_CONFIG_MULTITHREADED) )
  1733. {
  1734. destroyTransientVertexBuffer(m_submit->m_transientVb);
  1735. destroyTransientIndexBuffer(m_submit->m_transientIb);
  1736. frame();
  1737. }
  1738. frame(); // If any VertexLayouts needs to be destroyed.
  1739. getCommandBuffer(CommandBuffer::RendererShutdownEnd);
  1740. frame();
  1741. m_encoder[0].end(true);
  1742. m_encoderHandle->free(0);
  1743. bx::destroyHandleAlloc(g_allocator, m_encoderHandle);
  1744. m_encoderHandle = NULL;
  1745. for (uint32_t ii = 0, num = g_caps.limits.maxEncoders; ii < num; ++ii)
  1746. {
  1747. m_encoder[ii].~EncoderImpl();
  1748. }
  1749. BX_ALIGNED_FREE(g_allocator, m_encoder, BX_ALIGNOF(EncoderImpl) );
  1750. BX_FREE(g_allocator, m_encoderStats);
  1751. m_dynVertexBufferAllocator.compact();
  1752. m_dynIndexBufferAllocator.compact();
  1753. BX_ASSERT(
  1754. m_layoutHandle.getNumHandles() == m_vertexLayoutRef.m_vertexLayoutMap.getNumElements()
  1755. , "VertexLayoutRef mismatch, num handles %d, handles in hash map %d."
  1756. , m_layoutHandle.getNumHandles()
  1757. , m_vertexLayoutRef.m_vertexLayoutMap.getNumElements()
  1758. );
  1759. m_vertexLayoutRef.shutdown(m_layoutHandle);
  1760. #if BGFX_CONFIG_MULTITHREADED
  1761. // Render thread shutdown sequence.
  1762. renderSemWait(); // Wait for previous frame.
  1763. apiSemPost(); // OK to set context to NULL.
  1764. // s_ctx is NULL here.
  1765. renderSemWait(); // In RenderFrame::Exiting state.
  1766. if (m_thread.isRunning() )
  1767. {
  1768. m_thread.shutdown();
  1769. }
  1770. m_render->destroy();
  1771. #endif // BGFX_CONFIG_MULTITHREADED
  1772. bx::memSet(&g_internalData, 0, sizeof(InternalData) );
  1773. s_ctx = NULL;
  1774. m_submit->destroy();
  1775. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  1776. {
  1777. #define CHECK_HANDLE_LEAK(_name, _handleAlloc) \
  1778. BX_MACRO_BLOCK_BEGIN \
  1779. if (0 != _handleAlloc.getNumHandles() ) \
  1780. { \
  1781. BX_TRACE("LEAK: %s %d (max: %d)" \
  1782. , _name \
  1783. , _handleAlloc.getNumHandles() \
  1784. , _handleAlloc.getMaxHandles() \
  1785. ); \
  1786. for (uint16_t ii = 0, num = _handleAlloc.getNumHandles(); ii < num; ++ii) \
  1787. { \
  1788. BX_TRACE("\t%3d: %4d", ii, _handleAlloc.getHandleAt(ii) ); \
  1789. } \
  1790. } \
  1791. BX_MACRO_BLOCK_END
  1792. #define CHECK_HANDLE_LEAK_NAME(_name, _handleAlloc, _type, _ref) \
  1793. BX_MACRO_BLOCK_BEGIN \
  1794. if (0 != _handleAlloc.getNumHandles() ) \
  1795. { \
  1796. BX_TRACE("LEAK: %s %d (max: %d)" \
  1797. , _name \
  1798. , _handleAlloc.getNumHandles() \
  1799. , _handleAlloc.getMaxHandles() \
  1800. ); \
  1801. for (uint16_t ii = 0, num = _handleAlloc.getNumHandles(); ii < num; ++ii) \
  1802. { \
  1803. uint16_t idx = _handleAlloc.getHandleAt(ii); \
  1804. const _type& ref = _ref[idx]; BX_UNUSED(ref); \
  1805. BX_TRACE("\t%3d: %4d %s" \
  1806. , ii \
  1807. , idx \
  1808. , ref.m_name.getPtr() \
  1809. ); \
  1810. } \
  1811. } \
  1812. BX_MACRO_BLOCK_END
  1813. #define CHECK_HANDLE_LEAK_RC_NAME(_name, _handleAlloc, _type, _ref) \
  1814. BX_MACRO_BLOCK_BEGIN \
  1815. if (0 != _handleAlloc.getNumHandles() ) \
  1816. { \
  1817. BX_TRACE("LEAK: %s %d (max: %d)" \
  1818. , _name \
  1819. , _handleAlloc.getNumHandles() \
  1820. , _handleAlloc.getMaxHandles() \
  1821. ); \
  1822. for (uint16_t ii = 0, num = _handleAlloc.getNumHandles(); ii < num; ++ii) \
  1823. { \
  1824. uint16_t idx = _handleAlloc.getHandleAt(ii); \
  1825. const _type& ref = _ref[idx]; BX_UNUSED(ref); \
  1826. BX_TRACE("\t%3d: %4d %s (count %d)" \
  1827. , ii \
  1828. , idx \
  1829. , ref.m_name.getPtr() \
  1830. , ref.m_refCount \
  1831. ); \
  1832. } \
  1833. } \
  1834. BX_MACRO_BLOCK_END
  1835. CHECK_HANDLE_LEAK ("DynamicIndexBufferHandle", m_dynamicIndexBufferHandle );
  1836. CHECK_HANDLE_LEAK ("DynamicVertexBufferHandle", m_dynamicVertexBufferHandle );
  1837. CHECK_HANDLE_LEAK_NAME ("IndexBufferHandle", m_indexBufferHandle, IndexBuffer, m_indexBuffers );
  1838. CHECK_HANDLE_LEAK ("VertexLayoutHandle", m_layoutHandle );
  1839. CHECK_HANDLE_LEAK_NAME ("VertexBufferHandle", m_vertexBufferHandle, VertexBuffer, m_vertexBuffers );
  1840. CHECK_HANDLE_LEAK_RC_NAME("ShaderHandle", m_shaderHandle, ShaderRef, m_shaderRef );
  1841. CHECK_HANDLE_LEAK ("ProgramHandle", m_programHandle );
  1842. CHECK_HANDLE_LEAK_RC_NAME("TextureHandle", m_textureHandle, TextureRef, m_textureRef );
  1843. CHECK_HANDLE_LEAK_NAME ("FrameBufferHandle", m_frameBufferHandle, FrameBufferRef, m_frameBufferRef);
  1844. CHECK_HANDLE_LEAK_RC_NAME("UniformHandle", m_uniformHandle, UniformRef, m_uniformRef );
  1845. CHECK_HANDLE_LEAK ("OcclusionQueryHandle", m_occlusionQueryHandle );
  1846. #undef CHECK_HANDLE_LEAK
  1847. #undef CHECK_HANDLE_LEAK_NAME
  1848. }
  1849. }
  1850. void Context::freeDynamicBuffers()
  1851. {
  1852. for (uint16_t ii = 0, num = m_numFreeDynamicIndexBufferHandles; ii < num; ++ii)
  1853. {
  1854. destroyDynamicIndexBufferInternal(m_freeDynamicIndexBufferHandle[ii]);
  1855. }
  1856. m_numFreeDynamicIndexBufferHandles = 0;
  1857. for (uint16_t ii = 0, num = m_numFreeDynamicVertexBufferHandles; ii < num; ++ii)
  1858. {
  1859. destroyDynamicVertexBufferInternal(m_freeDynamicVertexBufferHandle[ii]);
  1860. }
  1861. m_numFreeDynamicVertexBufferHandles = 0;
  1862. for (uint16_t ii = 0, num = m_numFreeOcclusionQueryHandles; ii < num; ++ii)
  1863. {
  1864. m_occlusionQueryHandle.free(m_freeOcclusionQueryHandle[ii].idx);
  1865. }
  1866. m_numFreeOcclusionQueryHandles = 0;
  1867. }
  1868. void Context::freeAllHandles(Frame* _frame)
  1869. {
  1870. for (uint16_t ii = 0, num = _frame->m_freeIndexBuffer.getNumQueued(); ii < num; ++ii)
  1871. {
  1872. m_indexBufferHandle.free(_frame->m_freeIndexBuffer.get(ii).idx);
  1873. }
  1874. for (uint16_t ii = 0, num = _frame->m_freeVertexBuffer.getNumQueued(); ii < num; ++ii)
  1875. {
  1876. destroyVertexBufferInternal(_frame->m_freeVertexBuffer.get(ii));
  1877. }
  1878. for (uint16_t ii = 0, num = _frame->m_freeVertexLayout.getNumQueued(); ii < num; ++ii)
  1879. {
  1880. m_layoutHandle.free(_frame->m_freeVertexLayout.get(ii).idx);
  1881. }
  1882. for (uint16_t ii = 0, num = _frame->m_freeShader.getNumQueued(); ii < num; ++ii)
  1883. {
  1884. m_shaderHandle.free(_frame->m_freeShader.get(ii).idx);
  1885. }
  1886. for (uint16_t ii = 0, num = _frame->m_freeProgram.getNumQueued(); ii < num; ++ii)
  1887. {
  1888. m_programHandle.free(_frame->m_freeProgram.get(ii).idx);
  1889. }
  1890. for (uint16_t ii = 0, num = _frame->m_freeTexture.getNumQueued(); ii < num; ++ii)
  1891. {
  1892. m_textureHandle.free(_frame->m_freeTexture.get(ii).idx);
  1893. }
  1894. for (uint16_t ii = 0, num = _frame->m_freeFrameBuffer.getNumQueued(); ii < num; ++ii)
  1895. {
  1896. m_frameBufferHandle.free(_frame->m_freeFrameBuffer.get(ii).idx);
  1897. }
  1898. for (uint16_t ii = 0, num = _frame->m_freeUniform.getNumQueued(); ii < num; ++ii)
  1899. {
  1900. m_uniformHandle.free(_frame->m_freeUniform.get(ii).idx);
  1901. }
  1902. }
  1903. Encoder* Context::begin(bool _forThread)
  1904. {
  1905. EncoderImpl* encoder = &m_encoder[0];
  1906. #if BGFX_CONFIG_MULTITHREADED
  1907. if (_forThread || BGFX_API_THREAD_MAGIC != s_threadIndex)
  1908. {
  1909. bx::MutexScope scopeLock(m_encoderApiLock);
  1910. uint16_t idx = m_encoderHandle->alloc();
  1911. if (kInvalidHandle == idx)
  1912. {
  1913. return NULL;
  1914. }
  1915. encoder = &m_encoder[idx];
  1916. encoder->begin(m_submit, uint8_t(idx) );
  1917. }
  1918. #else
  1919. BX_UNUSED(_forThread);
  1920. #endif // BGFX_CONFIG_MULTITHREADED
  1921. return reinterpret_cast<Encoder*>(encoder);
  1922. }
  1923. void Context::end(Encoder* _encoder)
  1924. {
  1925. #if BGFX_CONFIG_MULTITHREADED
  1926. EncoderImpl* encoder = reinterpret_cast<EncoderImpl*>(_encoder);
  1927. if (encoder != &m_encoder[0])
  1928. {
  1929. encoder->end(true);
  1930. m_encoderEndSem.post();
  1931. }
  1932. #else
  1933. BX_UNUSED(_encoder);
  1934. #endif // BGFX_CONFIG_MULTITHREADED
  1935. }
  1936. uint32_t Context::frame(bool _capture)
  1937. {
  1938. m_encoder[0].end(true);
  1939. #if BGFX_CONFIG_MULTITHREADED
  1940. bx::MutexScope resourceApiScope(m_resourceApiLock);
  1941. encoderApiWait();
  1942. bx::MutexScope encoderApiScope(m_encoderApiLock);
  1943. #else
  1944. encoderApiWait();
  1945. #endif // BGFX_CONFIG_MULTITHREADED
  1946. m_submit->m_capture = _capture;
  1947. BGFX_PROFILER_SCOPE("bgfx/API thread frame", 0xff2040ff);
  1948. // wait for render thread to finish
  1949. renderSemWait();
  1950. frameNoRenderWait();
  1951. m_encoder[0].begin(m_submit, 0);
  1952. return m_frames;
  1953. }
  1954. void Context::frameNoRenderWait()
  1955. {
  1956. swap();
  1957. // release render thread
  1958. apiSemPost();
  1959. }
  1960. void Context::swap()
  1961. {
  1962. freeDynamicBuffers();
  1963. m_submit->m_resolution = m_init.resolution;
  1964. m_init.resolution.reset &= ~BGFX_RESET_INTERNAL_FORCE;
  1965. m_submit->m_debug = m_debug;
  1966. m_submit->m_perfStats.numViews = 0;
  1967. bx::memCopy(m_submit->m_viewRemap, m_viewRemap, sizeof(m_viewRemap) );
  1968. bx::memCopy(m_submit->m_view, m_view, sizeof(m_view) );
  1969. if (m_colorPaletteDirty > 0)
  1970. {
  1971. --m_colorPaletteDirty;
  1972. bx::memCopy(m_submit->m_colorPalette, m_clearColor, sizeof(m_clearColor) );
  1973. }
  1974. freeAllHandles(m_submit);
  1975. m_submit->resetFreeHandles();
  1976. m_submit->finish();
  1977. bx::swap(m_render, m_submit);
  1978. bx::memCopy(m_render->m_occlusion, m_submit->m_occlusion, sizeof(m_submit->m_occlusion) );
  1979. if (!BX_ENABLED(BGFX_CONFIG_MULTITHREADED)
  1980. || m_singleThreaded)
  1981. {
  1982. renderFrame();
  1983. }
  1984. m_frames++;
  1985. m_submit->start();
  1986. bx::memSet(m_seq, 0, sizeof(m_seq) );
  1987. m_submit->m_textVideoMem->resize(
  1988. m_render->m_textVideoMem->m_small
  1989. , m_init.resolution.width
  1990. , m_init.resolution.height
  1991. );
  1992. int64_t now = bx::getHPCounter();
  1993. m_submit->m_perfStats.cpuTimeFrame = now - m_frameTimeLast;
  1994. m_frameTimeLast = now;
  1995. }
  1996. ///
  1997. RendererContextI* rendererCreate(const Init& _init);
  1998. ///
  1999. void rendererDestroy(RendererContextI* _renderCtx);
  2000. void Context::flip()
  2001. {
  2002. if (m_rendererInitialized
  2003. && !m_flipped)
  2004. {
  2005. m_renderCtx->flip();
  2006. m_flipped = true;
  2007. if (m_renderCtx->isDeviceRemoved() )
  2008. {
  2009. // Something horribly went wrong, fallback to noop renderer.
  2010. rendererDestroy(m_renderCtx);
  2011. Init init;
  2012. init.type = RendererType::Noop;
  2013. m_renderCtx = rendererCreate(init);
  2014. g_caps.rendererType = RendererType::Noop;
  2015. }
  2016. }
  2017. }
  2018. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS
  2019. struct NSAutoreleasePoolScope
  2020. {
  2021. NSAutoreleasePoolScope()
  2022. {
  2023. id obj = class_createInstance(objc_getClass("NSAutoreleasePool"), 0);
  2024. typedef id(*objc_msgSend_init)(void*, SEL);
  2025. pool = ((objc_msgSend_init)objc_msgSend)(obj, sel_getUid("init") );
  2026. }
  2027. ~NSAutoreleasePoolScope()
  2028. {
  2029. typedef void(*objc_msgSend_release)(void*, SEL);
  2030. ((objc_msgSend_release)objc_msgSend)(pool, sel_getUid("release") );
  2031. }
  2032. id pool;
  2033. };
  2034. #endif // BX_PLATFORM_OSX
  2035. RenderFrame::Enum Context::renderFrame(int32_t _msecs)
  2036. {
  2037. BGFX_PROFILER_SCOPE("bgfx::renderFrame", 0xff2040ff);
  2038. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS
  2039. NSAutoreleasePoolScope pool;
  2040. #endif // BX_PLATFORM_OSX
  2041. if (!m_flipAfterRender)
  2042. {
  2043. BGFX_PROFILER_SCOPE("bgfx/flip", 0xff2040ff);
  2044. flip();
  2045. }
  2046. if (apiSemWait(_msecs) )
  2047. {
  2048. {
  2049. BGFX_PROFILER_SCOPE("bgfx/Exec commands pre", 0xff2040ff);
  2050. rendererExecCommands(m_render->m_cmdPre);
  2051. }
  2052. if (m_rendererInitialized)
  2053. {
  2054. {
  2055. BGFX_PROFILER_SCOPE("bgfx/Render submit", 0xff2040ff);
  2056. m_renderCtx->submit(m_render, m_clearQuad, m_textVideoMemBlitter);
  2057. m_flipped = false;
  2058. }
  2059. {
  2060. BGFX_PROFILER_SCOPE("bgfx/Screenshot", 0xff2040ff);
  2061. for (uint8_t ii = 0, num = m_render->m_numScreenShots; ii < num; ++ii)
  2062. {
  2063. const ScreenShot& screenShot = m_render->m_screenShot[ii];
  2064. m_renderCtx->requestScreenShot(screenShot.handle, screenShot.filePath.getCPtr() );
  2065. }
  2066. }
  2067. }
  2068. {
  2069. BGFX_PROFILER_SCOPE("bgfx/Exec commands post", 0xff2040ff);
  2070. rendererExecCommands(m_render->m_cmdPost);
  2071. }
  2072. renderSemPost();
  2073. if (m_flipAfterRender)
  2074. {
  2075. BGFX_PROFILER_SCOPE("bgfx/flip", 0xff2040ff);
  2076. flip();
  2077. }
  2078. }
  2079. else
  2080. {
  2081. return RenderFrame::Timeout;
  2082. }
  2083. return m_exit
  2084. ? RenderFrame::Exiting
  2085. : RenderFrame::Render
  2086. ;
  2087. }
  2088. void rendererUpdateUniforms(RendererContextI* _renderCtx, UniformBuffer* _uniformBuffer, uint32_t _begin, uint32_t _end)
  2089. {
  2090. _uniformBuffer->reset(_begin);
  2091. while (_uniformBuffer->getPos() < _end)
  2092. {
  2093. uint32_t opcode = _uniformBuffer->read();
  2094. if (UniformType::End == opcode)
  2095. {
  2096. break;
  2097. }
  2098. UniformType::Enum type;
  2099. uint16_t loc;
  2100. uint16_t num;
  2101. uint16_t copy;
  2102. UniformBuffer::decodeOpcode(opcode, type, loc, num, copy);
  2103. uint32_t size = g_uniformTypeSize[type]*num;
  2104. const char* data = _uniformBuffer->read(size);
  2105. if (UniformType::Count > type)
  2106. {
  2107. if (copy)
  2108. {
  2109. _renderCtx->updateUniform(loc, data, size);
  2110. }
  2111. else
  2112. {
  2113. _renderCtx->updateUniform(loc, *(const char**)(data), size);
  2114. }
  2115. }
  2116. else
  2117. {
  2118. _renderCtx->setMarker(data, uint16_t(size)-1);
  2119. }
  2120. }
  2121. }
  2122. void Context::flushTextureUpdateBatch(CommandBuffer& _cmdbuf)
  2123. {
  2124. if (m_textureUpdateBatch.sort() )
  2125. {
  2126. const uint32_t pos = _cmdbuf.m_pos;
  2127. uint32_t currentKey = UINT32_MAX;
  2128. for (uint32_t ii = 0, num = m_textureUpdateBatch.m_num; ii < num; ++ii)
  2129. {
  2130. _cmdbuf.m_pos = m_textureUpdateBatch.m_values[ii];
  2131. TextureHandle handle;
  2132. _cmdbuf.read(handle);
  2133. uint8_t side;
  2134. _cmdbuf.read(side);
  2135. uint8_t mip;
  2136. _cmdbuf.read(mip);
  2137. Rect rect;
  2138. _cmdbuf.read(rect);
  2139. uint16_t zz;
  2140. _cmdbuf.read(zz);
  2141. uint16_t depth;
  2142. _cmdbuf.read(depth);
  2143. uint16_t pitch;
  2144. _cmdbuf.read(pitch);
  2145. const Memory* mem;
  2146. _cmdbuf.read(mem);
  2147. uint32_t key = m_textureUpdateBatch.m_keys[ii];
  2148. if (key != currentKey)
  2149. {
  2150. if (currentKey != UINT32_MAX)
  2151. {
  2152. m_renderCtx->updateTextureEnd();
  2153. }
  2154. currentKey = key;
  2155. m_renderCtx->updateTextureBegin(handle, side, mip);
  2156. }
  2157. m_renderCtx->updateTexture(handle, side, mip, rect, zz, depth, pitch, mem);
  2158. release(mem);
  2159. }
  2160. if (currentKey != UINT32_MAX)
  2161. {
  2162. m_renderCtx->updateTextureEnd();
  2163. }
  2164. m_textureUpdateBatch.reset();
  2165. _cmdbuf.m_pos = pos;
  2166. }
  2167. }
  2168. typedef RendererContextI* (*RendererCreateFn)(const Init& _init);
  2169. typedef void (*RendererDestroyFn)();
  2170. #define BGFX_RENDERER_CONTEXT(_namespace) \
  2171. namespace _namespace \
  2172. { \
  2173. extern RendererContextI* rendererCreate(const Init& _init); \
  2174. extern void rendererDestroy(); \
  2175. }
  2176. BGFX_RENDERER_CONTEXT(noop);
  2177. BGFX_RENDERER_CONTEXT(d3d9);
  2178. BGFX_RENDERER_CONTEXT(d3d11);
  2179. BGFX_RENDERER_CONTEXT(d3d12);
  2180. BGFX_RENDERER_CONTEXT(gnm);
  2181. BGFX_RENDERER_CONTEXT(mtl);
  2182. BGFX_RENDERER_CONTEXT(nvn);
  2183. BGFX_RENDERER_CONTEXT(gl);
  2184. BGFX_RENDERER_CONTEXT(vk);
  2185. BGFX_RENDERER_CONTEXT(webgpu);
  2186. #undef BGFX_RENDERER_CONTEXT
  2187. struct RendererCreator
  2188. {
  2189. RendererCreateFn createFn;
  2190. RendererDestroyFn destroyFn;
  2191. const char* name;
  2192. bool supported;
  2193. };
  2194. static RendererCreator s_rendererCreator[] =
  2195. {
  2196. { noop::rendererCreate, noop::rendererDestroy, BGFX_RENDERER_NOOP_NAME, true }, // Noop
  2197. { d3d9::rendererCreate, d3d9::rendererDestroy, BGFX_RENDERER_DIRECT3D9_NAME, !!BGFX_CONFIG_RENDERER_DIRECT3D9 }, // Direct3D9
  2198. { d3d11::rendererCreate, d3d11::rendererDestroy, BGFX_RENDERER_DIRECT3D11_NAME, !!BGFX_CONFIG_RENDERER_DIRECT3D11 }, // Direct3D11
  2199. { d3d12::rendererCreate, d3d12::rendererDestroy, BGFX_RENDERER_DIRECT3D12_NAME, !!BGFX_CONFIG_RENDERER_DIRECT3D12 }, // Direct3D12
  2200. { gnm::rendererCreate, gnm::rendererDestroy, BGFX_RENDERER_GNM_NAME, !!BGFX_CONFIG_RENDERER_GNM }, // GNM
  2201. #if BX_PLATFORM_OSX || BX_PLATFORM_IOS
  2202. { mtl::rendererCreate, mtl::rendererDestroy, BGFX_RENDERER_METAL_NAME, !!BGFX_CONFIG_RENDERER_METAL }, // Metal
  2203. #else
  2204. { noop::rendererCreate, noop::rendererDestroy, BGFX_RENDERER_NOOP_NAME, false }, // Noop
  2205. #endif // BX_PLATFORM_OSX || BX_PLATFORM_IOS
  2206. { nvn::rendererCreate, nvn::rendererDestroy, BGFX_RENDERER_NVN_NAME, !!BGFX_CONFIG_RENDERER_NVN }, // NVN
  2207. { gl::rendererCreate, gl::rendererDestroy, BGFX_RENDERER_OPENGL_NAME, !!BGFX_CONFIG_RENDERER_OPENGLES }, // OpenGLES
  2208. { gl::rendererCreate, gl::rendererDestroy, BGFX_RENDERER_OPENGL_NAME, !!BGFX_CONFIG_RENDERER_OPENGL }, // OpenGL
  2209. { vk::rendererCreate, vk::rendererDestroy, BGFX_RENDERER_VULKAN_NAME, !!BGFX_CONFIG_RENDERER_VULKAN }, // Vulkan
  2210. { webgpu::rendererCreate, webgpu::rendererDestroy, BGFX_RENDERER_WEBGPU_NAME, !!BGFX_CONFIG_RENDERER_WEBGPU }, // WebGPU
  2211. };
  2212. BX_STATIC_ASSERT(BX_COUNTOF(s_rendererCreator) == RendererType::Count);
  2213. bool windowsVersionIs(Condition::Enum _op, uint32_t _version)
  2214. {
  2215. #if BX_PLATFORM_WINDOWS
  2216. static const uint8_t s_condition[] =
  2217. {
  2218. VER_LESS_EQUAL,
  2219. VER_GREATER_EQUAL,
  2220. };
  2221. OSVERSIONINFOEXA ovi;
  2222. bx::memSet(&ovi, 0, sizeof(ovi) );
  2223. ovi.dwOSVersionInfoSize = sizeof(ovi);
  2224. // _WIN32_WINNT_WINBLUE 0x0603
  2225. // _WIN32_WINNT_WIN8 0x0602
  2226. // _WIN32_WINNT_WIN7 0x0601
  2227. // _WIN32_WINNT_VISTA 0x0600
  2228. ovi.dwMajorVersion = HIBYTE(_version);
  2229. ovi.dwMinorVersion = LOBYTE(_version);
  2230. DWORDLONG cond = 0;
  2231. VER_SET_CONDITION(cond, VER_MAJORVERSION, s_condition[_op]);
  2232. VER_SET_CONDITION(cond, VER_MINORVERSION, s_condition[_op]);
  2233. return !!VerifyVersionInfoA(&ovi, VER_MAJORVERSION | VER_MINORVERSION, cond);
  2234. #else
  2235. BX_UNUSED(_op, _version);
  2236. return false;
  2237. #endif // BX_PLATFORM_WINDOWS
  2238. }
  2239. static int32_t compareDescending(const void* _lhs, const void* _rhs)
  2240. {
  2241. return *(const int32_t*)_rhs - *(const int32_t*)_lhs;
  2242. }
  2243. RendererContextI* rendererCreate(const Init& _init)
  2244. {
  2245. int32_t scores[RendererType::Count];
  2246. uint32_t numScores = 0;
  2247. for (uint32_t ii = 0; ii < RendererType::Count; ++ii)
  2248. {
  2249. RendererType::Enum renderer = RendererType::Enum(ii);
  2250. if (s_rendererCreator[ii].supported)
  2251. {
  2252. int32_t score = 0;
  2253. if (_init.type == renderer)
  2254. {
  2255. score += 1000;
  2256. }
  2257. score += RendererType::Noop != renderer ? 1 : 0;
  2258. if (BX_ENABLED(BX_PLATFORM_WINDOWS) )
  2259. {
  2260. if (windowsVersionIs(Condition::GreaterEqual, 0x0602) )
  2261. {
  2262. score += RendererType::Direct3D11 == renderer ? 20 : 0;
  2263. score += RendererType::Direct3D12 == renderer ? 10 : 0;
  2264. }
  2265. else if (windowsVersionIs(Condition::GreaterEqual, 0x0601) )
  2266. {
  2267. score += RendererType::Direct3D11 == renderer ? 20 : 0;
  2268. score += RendererType::Direct3D9 == renderer ? 10 : 0;
  2269. score += RendererType::Direct3D12 == renderer ? -100 : 0;
  2270. }
  2271. else
  2272. {
  2273. score += RendererType::Direct3D12 == renderer ? -100 : 0;
  2274. }
  2275. }
  2276. else if (BX_ENABLED(BX_PLATFORM_LINUX) )
  2277. {
  2278. score += RendererType::Vulkan == renderer ? 30 : 0;
  2279. score += RendererType::OpenGL == renderer ? 20 : 0;
  2280. score += RendererType::OpenGLES == renderer ? 10 : 0;
  2281. }
  2282. else if (BX_ENABLED(BX_PLATFORM_OSX) )
  2283. {
  2284. score += RendererType::Metal == renderer ? 20 : 0;
  2285. score += RendererType::OpenGL == renderer ? 10 : 0;
  2286. }
  2287. else if (BX_ENABLED(BX_PLATFORM_IOS) )
  2288. {
  2289. score += RendererType::Metal == renderer ? 20 : 0;
  2290. score += RendererType::OpenGLES == renderer ? 10 : 0;
  2291. }
  2292. else if (BX_ENABLED(0
  2293. || BX_PLATFORM_ANDROID
  2294. || BX_PLATFORM_EMSCRIPTEN
  2295. || BX_PLATFORM_RPI
  2296. ) )
  2297. {
  2298. score += RendererType::OpenGLES == renderer ? 20 : 0;
  2299. }
  2300. else if (BX_ENABLED(BX_PLATFORM_PS4) )
  2301. {
  2302. score += RendererType::Gnm == renderer ? 20 : 0;
  2303. }
  2304. else if (BX_ENABLED(0
  2305. || BX_PLATFORM_XBOXONE
  2306. || BX_PLATFORM_WINRT
  2307. ) )
  2308. {
  2309. score += RendererType::Direct3D12 == renderer ? 20 : 0;
  2310. score += RendererType::Direct3D11 == renderer ? 10 : 0;
  2311. }
  2312. scores[numScores++] = (score<<8) | uint8_t(renderer);
  2313. }
  2314. }
  2315. bx::quickSort(scores, numScores, sizeof(int32_t), compareDescending);
  2316. RendererContextI* renderCtx = NULL;
  2317. for (uint32_t ii = 0; ii < numScores; ++ii)
  2318. {
  2319. RendererType::Enum renderer = RendererType::Enum(scores[ii] & 0xff);
  2320. renderCtx = s_rendererCreator[renderer].createFn(_init);
  2321. if (NULL != renderCtx)
  2322. {
  2323. break;
  2324. }
  2325. s_rendererCreator[renderer].supported = false;
  2326. }
  2327. return renderCtx;
  2328. }
  2329. void rendererDestroy(RendererContextI* _renderCtx)
  2330. {
  2331. if (NULL != _renderCtx)
  2332. {
  2333. s_rendererCreator[_renderCtx->getRendererType()].destroyFn();
  2334. }
  2335. }
  2336. void Context::rendererExecCommands(CommandBuffer& _cmdbuf)
  2337. {
  2338. _cmdbuf.reset();
  2339. bool end = false;
  2340. if (NULL == m_renderCtx)
  2341. {
  2342. uint8_t command;
  2343. _cmdbuf.read(command);
  2344. switch (command)
  2345. {
  2346. case CommandBuffer::RendererShutdownEnd:
  2347. m_exit = true;
  2348. return;
  2349. case CommandBuffer::End:
  2350. return;
  2351. default:
  2352. {
  2353. BX_ASSERT(CommandBuffer::RendererInit == command
  2354. , "RendererInit must be the first command in command buffer before initialization. Unexpected command %d?"
  2355. , command
  2356. );
  2357. BX_ASSERT(!m_rendererInitialized, "This shouldn't happen! Bad synchronization?");
  2358. Init init;
  2359. _cmdbuf.read(init);
  2360. m_renderCtx = rendererCreate(init);
  2361. m_rendererInitialized = NULL != m_renderCtx;
  2362. if (!m_rendererInitialized)
  2363. {
  2364. _cmdbuf.read(command);
  2365. BX_ASSERT(CommandBuffer::End == command, "Unexpected command %d?"
  2366. , command
  2367. );
  2368. return;
  2369. }
  2370. }
  2371. break;
  2372. }
  2373. }
  2374. do
  2375. {
  2376. uint8_t command;
  2377. _cmdbuf.read(command);
  2378. switch (command)
  2379. {
  2380. case CommandBuffer::RendererShutdownBegin:
  2381. {
  2382. BX_ASSERT(m_rendererInitialized, "This shouldn't happen! Bad synchronization?");
  2383. m_rendererInitialized = false;
  2384. }
  2385. break;
  2386. case CommandBuffer::RendererShutdownEnd:
  2387. {
  2388. BX_ASSERT(!m_rendererInitialized && !m_exit, "This shouldn't happen! Bad synchronization?");
  2389. rendererDestroy(m_renderCtx);
  2390. m_renderCtx = NULL;
  2391. m_exit = true;
  2392. }
  2393. BX_FALLTHROUGH;
  2394. case CommandBuffer::End:
  2395. end = true;
  2396. break;
  2397. case CommandBuffer::CreateIndexBuffer:
  2398. {
  2399. BGFX_PROFILER_SCOPE("CreateIndexBuffer", 0xff2040ff);
  2400. IndexBufferHandle handle;
  2401. _cmdbuf.read(handle);
  2402. const Memory* mem;
  2403. _cmdbuf.read(mem);
  2404. uint16_t flags;
  2405. _cmdbuf.read(flags);
  2406. m_renderCtx->createIndexBuffer(handle, mem, flags);
  2407. release(mem);
  2408. }
  2409. break;
  2410. case CommandBuffer::DestroyIndexBuffer:
  2411. {
  2412. BGFX_PROFILER_SCOPE("DestroyIndexBuffer", 0xff2040ff);
  2413. IndexBufferHandle handle;
  2414. _cmdbuf.read(handle);
  2415. m_renderCtx->destroyIndexBuffer(handle);
  2416. }
  2417. break;
  2418. case CommandBuffer::CreateVertexLayout:
  2419. {
  2420. BGFX_PROFILER_SCOPE("CreateVertexLayout", 0xff2040ff);
  2421. VertexLayoutHandle handle;
  2422. _cmdbuf.read(handle);
  2423. VertexLayout layout;
  2424. _cmdbuf.read(layout);
  2425. m_renderCtx->createVertexLayout(handle, layout);
  2426. }
  2427. break;
  2428. case CommandBuffer::DestroyVertexLayout:
  2429. {
  2430. BGFX_PROFILER_SCOPE("DestroyVertexLayout", 0xff2040ff);
  2431. VertexLayoutHandle handle;
  2432. _cmdbuf.read(handle);
  2433. m_renderCtx->destroyVertexLayout(handle);
  2434. }
  2435. break;
  2436. case CommandBuffer::CreateVertexBuffer:
  2437. {
  2438. BGFX_PROFILER_SCOPE("CreateVertexBuffer", 0xff2040ff);
  2439. VertexBufferHandle handle;
  2440. _cmdbuf.read(handle);
  2441. const Memory* mem;
  2442. _cmdbuf.read(mem);
  2443. VertexLayoutHandle layoutHandle;
  2444. _cmdbuf.read(layoutHandle);
  2445. uint16_t flags;
  2446. _cmdbuf.read(flags);
  2447. m_renderCtx->createVertexBuffer(handle, mem, layoutHandle, flags);
  2448. release(mem);
  2449. }
  2450. break;
  2451. case CommandBuffer::DestroyVertexBuffer:
  2452. {
  2453. BGFX_PROFILER_SCOPE("DestroyVertexBuffer", 0xff2040ff);
  2454. VertexBufferHandle handle;
  2455. _cmdbuf.read(handle);
  2456. m_renderCtx->destroyVertexBuffer(handle);
  2457. }
  2458. break;
  2459. case CommandBuffer::CreateDynamicIndexBuffer:
  2460. {
  2461. BGFX_PROFILER_SCOPE("CreateDynamicIndexBuffer", 0xff2040ff);
  2462. IndexBufferHandle handle;
  2463. _cmdbuf.read(handle);
  2464. uint32_t size;
  2465. _cmdbuf.read(size);
  2466. uint16_t flags;
  2467. _cmdbuf.read(flags);
  2468. m_renderCtx->createDynamicIndexBuffer(handle, size, flags);
  2469. }
  2470. break;
  2471. case CommandBuffer::UpdateDynamicIndexBuffer:
  2472. {
  2473. BGFX_PROFILER_SCOPE("UpdateDynamicIndexBuffer", 0xff2040ff);
  2474. IndexBufferHandle handle;
  2475. _cmdbuf.read(handle);
  2476. uint32_t offset;
  2477. _cmdbuf.read(offset);
  2478. uint32_t size;
  2479. _cmdbuf.read(size);
  2480. const Memory* mem;
  2481. _cmdbuf.read(mem);
  2482. m_renderCtx->updateDynamicIndexBuffer(handle, offset, size, mem);
  2483. release(mem);
  2484. }
  2485. break;
  2486. case CommandBuffer::DestroyDynamicIndexBuffer:
  2487. {
  2488. BGFX_PROFILER_SCOPE("DestroyDynamicIndexBuffer", 0xff2040ff);
  2489. IndexBufferHandle handle;
  2490. _cmdbuf.read(handle);
  2491. m_renderCtx->destroyDynamicIndexBuffer(handle);
  2492. }
  2493. break;
  2494. case CommandBuffer::CreateDynamicVertexBuffer:
  2495. {
  2496. BGFX_PROFILER_SCOPE("CreateDynamicVertexBuffer", 0xff2040ff);
  2497. VertexBufferHandle handle;
  2498. _cmdbuf.read(handle);
  2499. uint32_t size;
  2500. _cmdbuf.read(size);
  2501. uint16_t flags;
  2502. _cmdbuf.read(flags);
  2503. m_renderCtx->createDynamicVertexBuffer(handle, size, flags);
  2504. }
  2505. break;
  2506. case CommandBuffer::UpdateDynamicVertexBuffer:
  2507. {
  2508. BGFX_PROFILER_SCOPE("UpdateDynamicVertexBuffer", 0xff2040ff);
  2509. VertexBufferHandle handle;
  2510. _cmdbuf.read(handle);
  2511. uint32_t offset;
  2512. _cmdbuf.read(offset);
  2513. uint32_t size;
  2514. _cmdbuf.read(size);
  2515. const Memory* mem;
  2516. _cmdbuf.read(mem);
  2517. m_renderCtx->updateDynamicVertexBuffer(handle, offset, size, mem);
  2518. release(mem);
  2519. }
  2520. break;
  2521. case CommandBuffer::DestroyDynamicVertexBuffer:
  2522. {
  2523. BGFX_PROFILER_SCOPE("DestroyDynamicVertexBuffer", 0xff2040ff);
  2524. VertexBufferHandle handle;
  2525. _cmdbuf.read(handle);
  2526. m_renderCtx->destroyDynamicVertexBuffer(handle);
  2527. }
  2528. break;
  2529. case CommandBuffer::CreateShader:
  2530. {
  2531. BGFX_PROFILER_SCOPE("CreateShader", 0xff2040ff);
  2532. ShaderHandle handle;
  2533. _cmdbuf.read(handle);
  2534. const Memory* mem;
  2535. _cmdbuf.read(mem);
  2536. m_renderCtx->createShader(handle, mem);
  2537. release(mem);
  2538. }
  2539. break;
  2540. case CommandBuffer::DestroyShader:
  2541. {
  2542. BGFX_PROFILER_SCOPE("DestroyShader", 0xff2040ff);
  2543. ShaderHandle handle;
  2544. _cmdbuf.read(handle);
  2545. m_renderCtx->destroyShader(handle);
  2546. }
  2547. break;
  2548. case CommandBuffer::CreateProgram:
  2549. {
  2550. BGFX_PROFILER_SCOPE("CreateProgram", 0xff2040ff);
  2551. ProgramHandle handle;
  2552. _cmdbuf.read(handle);
  2553. ShaderHandle vsh;
  2554. _cmdbuf.read(vsh);
  2555. ShaderHandle fsh;
  2556. _cmdbuf.read(fsh);
  2557. m_renderCtx->createProgram(handle, vsh, fsh);
  2558. }
  2559. break;
  2560. case CommandBuffer::DestroyProgram:
  2561. {
  2562. BGFX_PROFILER_SCOPE("DestroyProgram", 0xff2040ff);
  2563. ProgramHandle handle;
  2564. _cmdbuf.read(handle);
  2565. m_renderCtx->destroyProgram(handle);
  2566. }
  2567. break;
  2568. case CommandBuffer::CreateTexture:
  2569. {
  2570. BGFX_PROFILER_SCOPE("CreateTexture", 0xff2040ff);
  2571. TextureHandle handle;
  2572. _cmdbuf.read(handle);
  2573. const Memory* mem;
  2574. _cmdbuf.read(mem);
  2575. uint64_t flags;
  2576. _cmdbuf.read(flags);
  2577. uint8_t skip;
  2578. _cmdbuf.read(skip);
  2579. void* ptr = m_renderCtx->createTexture(handle, mem, flags, skip);
  2580. if (NULL != ptr)
  2581. {
  2582. setDirectAccessPtr(handle, ptr);
  2583. }
  2584. bx::MemoryReader reader(mem->data, mem->size);
  2585. uint32_t magic;
  2586. bx::read(&reader, magic);
  2587. if (BGFX_CHUNK_MAGIC_TEX == magic)
  2588. {
  2589. TextureCreate tc;
  2590. bx::read(&reader, tc);
  2591. if (NULL != tc.m_mem)
  2592. {
  2593. release(tc.m_mem);
  2594. }
  2595. }
  2596. release(mem);
  2597. }
  2598. break;
  2599. case CommandBuffer::UpdateTexture:
  2600. {
  2601. BGFX_PROFILER_SCOPE("UpdateTexture", 0xff2040ff);
  2602. if (m_textureUpdateBatch.isFull() )
  2603. {
  2604. flushTextureUpdateBatch(_cmdbuf);
  2605. }
  2606. uint32_t value = _cmdbuf.m_pos;
  2607. TextureHandle handle;
  2608. _cmdbuf.read(handle);
  2609. uint8_t side;
  2610. _cmdbuf.read(side);
  2611. uint8_t mip;
  2612. _cmdbuf.read(mip);
  2613. _cmdbuf.skip<Rect>();
  2614. _cmdbuf.skip<uint16_t>();
  2615. _cmdbuf.skip<uint16_t>();
  2616. _cmdbuf.skip<uint16_t>();
  2617. _cmdbuf.skip<Memory*>();
  2618. uint32_t key = (handle.idx<<16)
  2619. | (side<<8)
  2620. | mip
  2621. ;
  2622. m_textureUpdateBatch.add(key, value);
  2623. }
  2624. break;
  2625. case CommandBuffer::ReadTexture:
  2626. {
  2627. BGFX_PROFILER_SCOPE("ReadTexture", 0xff2040ff);
  2628. TextureHandle handle;
  2629. _cmdbuf.read(handle);
  2630. void* data;
  2631. _cmdbuf.read(data);
  2632. uint8_t mip;
  2633. _cmdbuf.read(mip);
  2634. m_renderCtx->readTexture(handle, data, mip);
  2635. }
  2636. break;
  2637. case CommandBuffer::ResizeTexture:
  2638. {
  2639. BGFX_PROFILER_SCOPE("ResizeTexture", 0xff2040ff);
  2640. TextureHandle handle;
  2641. _cmdbuf.read(handle);
  2642. uint16_t width;
  2643. _cmdbuf.read(width);
  2644. uint16_t height;
  2645. _cmdbuf.read(height);
  2646. uint8_t numMips;
  2647. _cmdbuf.read(numMips);
  2648. uint16_t numLayers;
  2649. _cmdbuf.read(numLayers);
  2650. m_renderCtx->resizeTexture(handle, width, height, numMips, numLayers);
  2651. }
  2652. break;
  2653. case CommandBuffer::DestroyTexture:
  2654. {
  2655. BGFX_PROFILER_SCOPE("DestroyTexture", 0xff2040ff);
  2656. TextureHandle handle;
  2657. _cmdbuf.read(handle);
  2658. m_renderCtx->destroyTexture(handle);
  2659. }
  2660. break;
  2661. case CommandBuffer::CreateFrameBuffer:
  2662. {
  2663. BGFX_PROFILER_SCOPE("CreateFrameBuffer", 0xff2040ff);
  2664. FrameBufferHandle handle;
  2665. _cmdbuf.read(handle);
  2666. bool window;
  2667. _cmdbuf.read(window);
  2668. if (window)
  2669. {
  2670. void* nwh;
  2671. _cmdbuf.read(nwh);
  2672. uint16_t width;
  2673. _cmdbuf.read(width);
  2674. uint16_t height;
  2675. _cmdbuf.read(height);
  2676. TextureFormat::Enum format;
  2677. _cmdbuf.read(format);
  2678. TextureFormat::Enum depthFormat;
  2679. _cmdbuf.read(depthFormat);
  2680. m_renderCtx->createFrameBuffer(handle, nwh, width, height, format, depthFormat);
  2681. }
  2682. else
  2683. {
  2684. uint8_t num;
  2685. _cmdbuf.read(num);
  2686. Attachment attachment[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  2687. _cmdbuf.read(attachment, sizeof(Attachment) * num);
  2688. m_renderCtx->createFrameBuffer(handle, num, attachment);
  2689. }
  2690. }
  2691. break;
  2692. case CommandBuffer::DestroyFrameBuffer:
  2693. {
  2694. BGFX_PROFILER_SCOPE("DestroyFrameBuffer", 0xff2040ff);
  2695. FrameBufferHandle handle;
  2696. _cmdbuf.read(handle);
  2697. m_renderCtx->destroyFrameBuffer(handle);
  2698. }
  2699. break;
  2700. case CommandBuffer::CreateUniform:
  2701. {
  2702. BGFX_PROFILER_SCOPE("CreateUniform", 0xff2040ff);
  2703. UniformHandle handle;
  2704. _cmdbuf.read(handle);
  2705. UniformType::Enum type;
  2706. _cmdbuf.read(type);
  2707. uint16_t num;
  2708. _cmdbuf.read(num);
  2709. uint8_t len;
  2710. _cmdbuf.read(len);
  2711. const char* name = (const char*)_cmdbuf.skip(len);
  2712. m_renderCtx->createUniform(handle, type, num, name);
  2713. }
  2714. break;
  2715. case CommandBuffer::DestroyUniform:
  2716. {
  2717. BGFX_PROFILER_SCOPE("DestroyUniform", 0xff2040ff);
  2718. UniformHandle handle;
  2719. _cmdbuf.read(handle);
  2720. m_renderCtx->destroyUniform(handle);
  2721. }
  2722. break;
  2723. case CommandBuffer::UpdateViewName:
  2724. {
  2725. BGFX_PROFILER_SCOPE("UpdateViewName", 0xff2040ff);
  2726. ViewId id;
  2727. _cmdbuf.read(id);
  2728. uint16_t len;
  2729. _cmdbuf.read(len);
  2730. const char* name = (const char*)_cmdbuf.skip(len);
  2731. m_renderCtx->updateViewName(id, name);
  2732. }
  2733. break;
  2734. case CommandBuffer::InvalidateOcclusionQuery:
  2735. {
  2736. BGFX_PROFILER_SCOPE("InvalidateOcclusionQuery", 0xff2040ff);
  2737. OcclusionQueryHandle handle;
  2738. _cmdbuf.read(handle);
  2739. m_renderCtx->invalidateOcclusionQuery(handle);
  2740. }
  2741. break;
  2742. case CommandBuffer::SetName:
  2743. {
  2744. BGFX_PROFILER_SCOPE("SetName", 0xff2040ff);
  2745. Handle handle;
  2746. _cmdbuf.read(handle);
  2747. uint16_t len;
  2748. _cmdbuf.read(len);
  2749. const char* name = (const char*)_cmdbuf.skip(len);
  2750. m_renderCtx->setName(handle, name, len-1);
  2751. }
  2752. break;
  2753. default:
  2754. BX_ASSERT(false, "Invalid command: %d", command);
  2755. break;
  2756. }
  2757. } while (!end);
  2758. flushTextureUpdateBatch(_cmdbuf);
  2759. }
  2760. uint32_t weldVertices(void* _output, const VertexLayout& _layout, const void* _data, uint32_t _num, bool _index32, float _epsilon)
  2761. {
  2762. return weldVertices(_output, _layout, _data, _num, _index32, _epsilon, g_allocator);
  2763. }
  2764. uint32_t topologyConvert(TopologyConvert::Enum _conversion, void* _dst, uint32_t _dstSize, const void* _indices, uint32_t _numIndices, bool _index32)
  2765. {
  2766. return topologyConvert(_conversion, _dst, _dstSize, _indices, _numIndices, _index32, g_allocator);
  2767. }
  2768. 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)
  2769. {
  2770. topologySortTriList(_sort, _dst, _dstSize, _dir, _pos, _vertices, _stride, _indices, _numIndices, _index32, g_allocator);
  2771. }
  2772. uint8_t getSupportedRenderers(uint8_t _max, RendererType::Enum* _enum)
  2773. {
  2774. _enum = _max == 0 ? NULL : _enum;
  2775. uint8_t num = 0;
  2776. for (uint8_t ii = 0; ii < RendererType::Count; ++ii)
  2777. {
  2778. if ( (RendererType::Direct3D11 == ii || RendererType::Direct3D12 == ii)
  2779. && windowsVersionIs(Condition::LessEqual, 0x0502) )
  2780. {
  2781. continue;
  2782. }
  2783. if (NULL == _enum)
  2784. {
  2785. num++;
  2786. }
  2787. else
  2788. {
  2789. if (num < _max
  2790. && s_rendererCreator[ii].supported)
  2791. {
  2792. _enum[num++] = RendererType::Enum(ii);
  2793. }
  2794. }
  2795. }
  2796. return num;
  2797. }
  2798. const char* getRendererName(RendererType::Enum _type)
  2799. {
  2800. BX_ASSERT(_type < RendererType::Count, "Invalid renderer type %d.", _type);
  2801. return s_rendererCreator[_type].name;
  2802. }
  2803. PlatformData::PlatformData()
  2804. : ndt(NULL)
  2805. , nwh(NULL)
  2806. , context(NULL)
  2807. , backBuffer(NULL)
  2808. , backBufferDS(NULL)
  2809. {
  2810. }
  2811. Resolution::Resolution()
  2812. : format(TextureFormat::RGBA8)
  2813. , width(1280)
  2814. , height(720)
  2815. , reset(BGFX_RESET_NONE)
  2816. , numBackBuffers(2)
  2817. , maxFrameLatency(0)
  2818. {
  2819. }
  2820. Init::Limits::Limits()
  2821. : maxEncoders(BGFX_CONFIG_DEFAULT_MAX_ENCODERS)
  2822. , minResourceCbSize(BGFX_CONFIG_MIN_RESOURCE_COMMAND_BUFFER_SIZE)
  2823. , transientVbSize(BGFX_CONFIG_TRANSIENT_VERTEX_BUFFER_SIZE)
  2824. , transientIbSize(BGFX_CONFIG_TRANSIENT_INDEX_BUFFER_SIZE)
  2825. {
  2826. }
  2827. Init::Init()
  2828. : type(RendererType::Count)
  2829. , vendorId(BGFX_PCI_ID_NONE)
  2830. , deviceId(0)
  2831. , debug(BX_ENABLED(BGFX_CONFIG_DEBUG) )
  2832. , profile(BX_ENABLED(BGFX_CONFIG_DEBUG_ANNOTATION) )
  2833. , callback(NULL)
  2834. , allocator(NULL)
  2835. {
  2836. }
  2837. void Attachment::init(TextureHandle _handle, Access::Enum _access, uint16_t _layer, uint16_t _numLayers, uint16_t _mip, uint8_t _resolve)
  2838. {
  2839. access = _access;
  2840. handle = _handle;
  2841. mip = _mip;
  2842. layer = _layer;
  2843. numLayers = _numLayers;
  2844. resolve = _resolve;
  2845. }
  2846. bool init(const Init& _userInit)
  2847. {
  2848. if (NULL != s_ctx)
  2849. {
  2850. BX_TRACE("bgfx is already initialized.");
  2851. return false;
  2852. }
  2853. Init init = _userInit;
  2854. init.limits.maxEncoders = bx::clamp<uint16_t>(init.limits.maxEncoders, 1, (0 != BGFX_CONFIG_MULTITHREADED) ? 128 : 1);
  2855. init.limits.minResourceCbSize = bx::min<uint32_t>(init.limits.minResourceCbSize, BGFX_CONFIG_MIN_RESOURCE_COMMAND_BUFFER_SIZE);
  2856. struct ErrorState
  2857. {
  2858. enum Enum
  2859. {
  2860. Default,
  2861. ContextAllocated,
  2862. };
  2863. };
  2864. ErrorState::Enum errorState = ErrorState::Default;
  2865. if (NULL != init.allocator)
  2866. {
  2867. g_allocator = init.allocator;
  2868. }
  2869. else
  2870. {
  2871. bx::DefaultAllocator allocator;
  2872. g_allocator =
  2873. s_allocatorStub = BX_NEW(&allocator, AllocatorStub);
  2874. }
  2875. if (NULL != init.callback)
  2876. {
  2877. g_callback = init.callback;
  2878. }
  2879. else
  2880. {
  2881. g_callback =
  2882. s_callbackStub = BX_NEW(g_allocator, CallbackStub);
  2883. }
  2884. bx::memSet(&g_caps, 0, sizeof(g_caps) );
  2885. g_caps.limits.maxDrawCalls = BGFX_CONFIG_MAX_DRAW_CALLS;
  2886. g_caps.limits.maxBlits = BGFX_CONFIG_MAX_BLIT_ITEMS;
  2887. g_caps.limits.maxTextureSize = 0;
  2888. g_caps.limits.maxTextureLayers = 1;
  2889. g_caps.limits.maxViews = BGFX_CONFIG_MAX_VIEWS;
  2890. g_caps.limits.maxFrameBuffers = BGFX_CONFIG_MAX_FRAME_BUFFERS;
  2891. g_caps.limits.maxPrograms = BGFX_CONFIG_MAX_PROGRAMS;
  2892. g_caps.limits.maxShaders = BGFX_CONFIG_MAX_SHADERS;
  2893. g_caps.limits.maxTextures = BGFX_CONFIG_MAX_TEXTURES;
  2894. g_caps.limits.maxTextureSamplers = BGFX_CONFIG_MAX_TEXTURE_SAMPLERS;
  2895. g_caps.limits.maxComputeBindings = 0;
  2896. g_caps.limits.maxVertexLayouts = BGFX_CONFIG_MAX_VERTEX_LAYOUTS;
  2897. g_caps.limits.maxVertexStreams = 1;
  2898. g_caps.limits.maxIndexBuffers = BGFX_CONFIG_MAX_INDEX_BUFFERS;
  2899. g_caps.limits.maxVertexBuffers = BGFX_CONFIG_MAX_VERTEX_BUFFERS;
  2900. g_caps.limits.maxDynamicIndexBuffers = BGFX_CONFIG_MAX_DYNAMIC_INDEX_BUFFERS;
  2901. g_caps.limits.maxDynamicVertexBuffers = BGFX_CONFIG_MAX_DYNAMIC_VERTEX_BUFFERS;
  2902. g_caps.limits.maxUniforms = BGFX_CONFIG_MAX_UNIFORMS;
  2903. g_caps.limits.maxOcclusionQueries = BGFX_CONFIG_MAX_OCCLUSION_QUERIES;
  2904. g_caps.limits.maxFBAttachments = 1;
  2905. g_caps.limits.maxEncoders = init.limits.maxEncoders;
  2906. g_caps.limits.minResourceCbSize = init.limits.minResourceCbSize;
  2907. g_caps.limits.transientVbSize = init.limits.transientVbSize;
  2908. g_caps.limits.transientIbSize = init.limits.transientIbSize;
  2909. g_caps.vendorId = init.vendorId;
  2910. g_caps.deviceId = init.deviceId;
  2911. BX_TRACE("Init...");
  2912. // bgfx 1.104.7082
  2913. // ^ ^^^ ^^^^
  2914. // | | +--- Commit number (https://github.com/bkaradzic/bgfx / git rev-list --count HEAD)
  2915. // | +------- API version (from https://github.com/bkaradzic/bgfx/blob/master/scripts/bgfx.idl#L4)
  2916. // +--------- Major revision (always 1)
  2917. BX_TRACE("Version 1.%d.%d (commit: " BGFX_REV_SHA1 ")", BGFX_API_VERSION, BGFX_REV_NUMBER);
  2918. errorState = ErrorState::ContextAllocated;
  2919. s_ctx = BX_ALIGNED_NEW(g_allocator, Context, Context::kAlignment);
  2920. if (s_ctx->init(init) )
  2921. {
  2922. BX_TRACE("Init complete.");
  2923. return true;
  2924. }
  2925. BX_TRACE("Init failed.");
  2926. switch (errorState)
  2927. {
  2928. case ErrorState::ContextAllocated:
  2929. BX_ALIGNED_DELETE(g_allocator, s_ctx, Context::kAlignment);
  2930. s_ctx = NULL;
  2931. BX_FALLTHROUGH;
  2932. case ErrorState::Default:
  2933. if (NULL != s_callbackStub)
  2934. {
  2935. BX_DELETE(g_allocator, s_callbackStub);
  2936. s_callbackStub = NULL;
  2937. }
  2938. if (NULL != s_allocatorStub)
  2939. {
  2940. bx::DefaultAllocator allocator;
  2941. BX_DELETE(&allocator, s_allocatorStub);
  2942. s_allocatorStub = NULL;
  2943. }
  2944. s_threadIndex = 0;
  2945. g_callback = NULL;
  2946. g_allocator = NULL;
  2947. break;
  2948. }
  2949. return false;
  2950. }
  2951. void shutdown()
  2952. {
  2953. BX_TRACE("Shutdown...");
  2954. BGFX_CHECK_API_THREAD();
  2955. Context* ctx = s_ctx; // it's going to be NULLd inside shutdown.
  2956. ctx->shutdown();
  2957. BX_ASSERT(NULL == s_ctx, "bgfx is should be uninitialized here.");
  2958. BX_ALIGNED_DELETE(g_allocator, ctx, Context::kAlignment);
  2959. BX_TRACE("Shutdown complete.");
  2960. if (NULL != s_allocatorStub)
  2961. {
  2962. s_allocatorStub->checkLeaks();
  2963. }
  2964. if (NULL != s_callbackStub)
  2965. {
  2966. BX_DELETE(g_allocator, s_callbackStub);
  2967. s_callbackStub = NULL;
  2968. }
  2969. if (NULL != s_allocatorStub)
  2970. {
  2971. bx::DefaultAllocator allocator;
  2972. BX_DELETE(&allocator, s_allocatorStub);
  2973. s_allocatorStub = NULL;
  2974. }
  2975. s_threadIndex = 0;
  2976. g_callback = NULL;
  2977. g_allocator = NULL;
  2978. }
  2979. void reset(uint32_t _width, uint32_t _height, uint32_t _flags, TextureFormat::Enum _format)
  2980. {
  2981. BGFX_CHECK_API_THREAD();
  2982. BX_ASSERT(0 == (_flags&BGFX_RESET_RESERVED_MASK), "Do not set reset reserved flags!");
  2983. s_ctx->reset(_width, _height, _flags, _format);
  2984. }
  2985. Encoder* begin(bool _forThread)
  2986. {
  2987. return s_ctx->begin(_forThread);
  2988. }
  2989. #define BGFX_ENCODER(_func) reinterpret_cast<EncoderImpl*>(this)->_func
  2990. void Encoder::setMarker(const char* _marker)
  2991. {
  2992. BGFX_ENCODER(setMarker(_marker) );
  2993. }
  2994. void Encoder::setState(uint64_t _state, uint32_t _rgba)
  2995. {
  2996. BX_ASSERT(0 == (_state&BGFX_STATE_RESERVED_MASK), "Do not set state reserved flags!");
  2997. BGFX_ENCODER(setState(_state, _rgba) );
  2998. }
  2999. void Encoder::setCondition(OcclusionQueryHandle _handle, bool _visible)
  3000. {
  3001. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  3002. BGFX_ENCODER(setCondition(_handle, _visible) );
  3003. }
  3004. void Encoder::setStencil(uint32_t _fstencil, uint32_t _bstencil)
  3005. {
  3006. BGFX_ENCODER(setStencil(_fstencil, _bstencil) );
  3007. }
  3008. uint16_t Encoder::setScissor(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  3009. {
  3010. return BGFX_ENCODER(setScissor(_x, _y, _width, _height) );
  3011. }
  3012. void Encoder::setScissor(uint16_t _cache)
  3013. {
  3014. BGFX_ENCODER(setScissor(_cache) );
  3015. }
  3016. uint32_t Encoder::setTransform(const void* _mtx, uint16_t _num)
  3017. {
  3018. return BGFX_ENCODER(setTransform(_mtx, _num) );
  3019. }
  3020. uint32_t Encoder::allocTransform(Transform* _transform, uint16_t _num)
  3021. {
  3022. return BGFX_ENCODER(allocTransform(_transform, _num) );
  3023. }
  3024. void Encoder::setTransform(uint32_t _cache, uint16_t _num)
  3025. {
  3026. BGFX_ENCODER(setTransform(_cache, _num) );
  3027. }
  3028. void Encoder::setUniform(UniformHandle _handle, const void* _value, uint16_t _num)
  3029. {
  3030. BGFX_CHECK_HANDLE("setUniform", s_ctx->m_uniformHandle, _handle);
  3031. const UniformRef& uniform = s_ctx->m_uniformRef[_handle.idx];
  3032. BX_ASSERT(isValid(_handle) && 0 < uniform.m_refCount, "Setting invalid uniform (handle %3d)!", _handle.idx);
  3033. BX_ASSERT(_num == UINT16_MAX || uniform.m_num >= _num, "Truncated uniform update. %d (max: %d)", _num, uniform.m_num);
  3034. BGFX_ENCODER(setUniform(uniform.m_type, _handle, _value, UINT16_MAX != _num ? _num : uniform.m_num) );
  3035. }
  3036. void Encoder::setIndexBuffer(IndexBufferHandle _handle)
  3037. {
  3038. setIndexBuffer(_handle, 0, UINT32_MAX);
  3039. }
  3040. void Encoder::setIndexBuffer(IndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  3041. {
  3042. BGFX_CHECK_HANDLE("setIndexBuffer", s_ctx->m_indexBufferHandle, _handle);
  3043. const IndexBuffer& ib = s_ctx->m_indexBuffers[_handle.idx];
  3044. BGFX_ENCODER(setIndexBuffer(_handle, ib, _firstIndex, _numIndices) );
  3045. }
  3046. void Encoder::setIndexBuffer(DynamicIndexBufferHandle _handle)
  3047. {
  3048. setIndexBuffer(_handle, 0, UINT32_MAX);
  3049. }
  3050. void Encoder::setIndexBuffer(DynamicIndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  3051. {
  3052. BGFX_CHECK_HANDLE("setIndexBuffer", s_ctx->m_dynamicIndexBufferHandle, _handle);
  3053. const DynamicIndexBuffer& dib = s_ctx->m_dynamicIndexBuffers[_handle.idx];
  3054. BGFX_ENCODER(setIndexBuffer(dib, _firstIndex, _numIndices) );
  3055. }
  3056. void Encoder::setIndexBuffer(const TransientIndexBuffer* _tib)
  3057. {
  3058. setIndexBuffer(_tib, 0, UINT32_MAX);
  3059. }
  3060. void Encoder::setIndexBuffer(const TransientIndexBuffer* _tib, uint32_t _firstIndex, uint32_t _numIndices)
  3061. {
  3062. BX_ASSERT(NULL != _tib, "_tib can't be NULL");
  3063. BGFX_CHECK_HANDLE("setIndexBuffer", s_ctx->m_indexBufferHandle, _tib->handle);
  3064. BGFX_ENCODER(setIndexBuffer(_tib, _firstIndex, _numIndices) );
  3065. }
  3066. void Encoder::setVertexBuffer(
  3067. uint8_t _stream
  3068. , VertexBufferHandle _handle
  3069. , uint32_t _startVertex
  3070. , uint32_t _numVertices
  3071. , VertexLayoutHandle _layoutHandle
  3072. )
  3073. {
  3074. BGFX_CHECK_HANDLE("setVertexBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3075. BGFX_CHECK_HANDLE_INVALID_OK("setVertexBuffer", s_ctx->m_layoutHandle, _layoutHandle);
  3076. BGFX_ENCODER(setVertexBuffer(_stream, _handle, _startVertex, _numVertices, _layoutHandle) );
  3077. }
  3078. void Encoder::setVertexBuffer(uint8_t _stream, VertexBufferHandle _handle)
  3079. {
  3080. setVertexBuffer(_stream, _handle, 0, UINT32_MAX);
  3081. }
  3082. void Encoder::setVertexBuffer(
  3083. uint8_t _stream
  3084. , DynamicVertexBufferHandle _handle
  3085. , uint32_t _startVertex
  3086. , uint32_t _numVertices
  3087. , VertexLayoutHandle _layoutHandle
  3088. )
  3089. {
  3090. BGFX_CHECK_HANDLE("setVertexBuffer", s_ctx->m_dynamicVertexBufferHandle, _handle);
  3091. BGFX_CHECK_HANDLE_INVALID_OK("setVertexBuffer", s_ctx->m_layoutHandle, _layoutHandle);
  3092. const DynamicVertexBuffer& dvb = s_ctx->m_dynamicVertexBuffers[_handle.idx];
  3093. BGFX_ENCODER(setVertexBuffer(_stream, dvb, _startVertex, _numVertices, _layoutHandle) );
  3094. }
  3095. void Encoder::setVertexBuffer(uint8_t _stream, DynamicVertexBufferHandle _handle)
  3096. {
  3097. setVertexBuffer(_stream, _handle, 0, UINT32_MAX);
  3098. }
  3099. void Encoder::setVertexBuffer(
  3100. uint8_t _stream
  3101. , const TransientVertexBuffer* _tvb
  3102. , uint32_t _startVertex
  3103. , uint32_t _numVertices
  3104. , VertexLayoutHandle _layoutHandle
  3105. )
  3106. {
  3107. BX_ASSERT(NULL != _tvb, "_tvb can't be NULL");
  3108. BGFX_CHECK_HANDLE("setVertexBuffer", s_ctx->m_vertexBufferHandle, _tvb->handle);
  3109. BGFX_CHECK_HANDLE_INVALID_OK("setVertexBuffer", s_ctx->m_layoutHandle, _layoutHandle);
  3110. BGFX_ENCODER(setVertexBuffer(_stream, _tvb, _startVertex, _numVertices, _layoutHandle) );
  3111. }
  3112. void Encoder::setVertexBuffer(uint8_t _stream, const TransientVertexBuffer* _tvb)
  3113. {
  3114. setVertexBuffer(_stream, _tvb, 0, UINT32_MAX);
  3115. }
  3116. void Encoder::setVertexCount(uint32_t _numVertices)
  3117. {
  3118. BGFX_CHECK_CAPS(BGFX_CAPS_VERTEX_ID, "Auto generated vertices are not supported!");
  3119. BGFX_ENCODER(setVertexCount(_numVertices) );
  3120. }
  3121. void Encoder::setInstanceDataBuffer(const InstanceDataBuffer* _idb)
  3122. {
  3123. setInstanceDataBuffer(_idb, 0, UINT32_MAX);
  3124. }
  3125. void Encoder::setInstanceDataBuffer(const InstanceDataBuffer* _idb, uint32_t _start, uint32_t _num)
  3126. {
  3127. BX_ASSERT(NULL != _idb, "_idb can't be NULL");
  3128. BGFX_ENCODER(setInstanceDataBuffer(_idb, _start, _num) );
  3129. }
  3130. void Encoder::setInstanceDataBuffer(VertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  3131. {
  3132. BGFX_CHECK_HANDLE("setInstanceDataBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3133. const VertexBuffer& vb = s_ctx->m_vertexBuffers[_handle.idx];
  3134. BGFX_ENCODER(setInstanceDataBuffer(_handle, _startVertex, _num, vb.m_stride) );
  3135. }
  3136. void Encoder::setInstanceDataBuffer(DynamicVertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  3137. {
  3138. BGFX_CHECK_HANDLE("setInstanceDataBuffer", s_ctx->m_dynamicVertexBufferHandle, _handle);
  3139. const DynamicVertexBuffer& dvb = s_ctx->m_dynamicVertexBuffers[_handle.idx];
  3140. BGFX_ENCODER(setInstanceDataBuffer(dvb.m_handle
  3141. , dvb.m_startVertex + _startVertex
  3142. , _num
  3143. , dvb.m_stride
  3144. ) );
  3145. }
  3146. void Encoder::setInstanceCount(uint32_t _numInstances)
  3147. {
  3148. BGFX_CHECK_CAPS(BGFX_CAPS_VERTEX_ID, "Auto generated instances are not supported!");
  3149. BGFX_ENCODER(setInstanceCount(_numInstances) );
  3150. }
  3151. void Encoder::setTexture(uint8_t _stage, UniformHandle _sampler, TextureHandle _handle, uint32_t _flags)
  3152. {
  3153. BGFX_CHECK_HANDLE("setTexture/UniformHandle", s_ctx->m_uniformHandle, _sampler);
  3154. BGFX_CHECK_HANDLE_INVALID_OK("setTexture/TextureHandle", s_ctx->m_textureHandle, _handle);
  3155. BX_ASSERT(_stage < g_caps.limits.maxTextureSamplers, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxTextureSamplers);
  3156. BGFX_ENCODER(setTexture(_stage, _sampler, _handle, _flags) );
  3157. }
  3158. void Encoder::touch(ViewId _id)
  3159. {
  3160. ProgramHandle handle = BGFX_INVALID_HANDLE;
  3161. submit(_id, handle);
  3162. }
  3163. void Encoder::submit(ViewId _id, ProgramHandle _program, uint32_t _depth, uint8_t _flags)
  3164. {
  3165. OcclusionQueryHandle handle = BGFX_INVALID_HANDLE;
  3166. submit(_id, _program, handle, _depth, _flags);
  3167. }
  3168. void Encoder::submit(ViewId _id, ProgramHandle _program, OcclusionQueryHandle _occlusionQuery, uint32_t _depth, uint8_t _flags)
  3169. {
  3170. BX_ASSERT(false
  3171. || !isValid(_occlusionQuery)
  3172. || 0 != (g_caps.supported & BGFX_CAPS_OCCLUSION_QUERY)
  3173. , "Occlusion query is not supported! Use bgfx::getCaps to check BGFX_CAPS_OCCLUSION_QUERY backend renderer capabilities."
  3174. );
  3175. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_programHandle, _program);
  3176. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_occlusionQueryHandle, _occlusionQuery);
  3177. BGFX_ENCODER(submit(_id, _program, _occlusionQuery, _depth, _flags) );
  3178. }
  3179. void Encoder::submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint16_t _start, uint16_t _num, uint32_t _depth, uint8_t _flags)
  3180. {
  3181. BGFX_CHECK_HANDLE_INVALID_OK("submit", s_ctx->m_programHandle, _program);
  3182. BGFX_CHECK_HANDLE("submit", s_ctx->m_vertexBufferHandle, _indirectHandle);
  3183. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT, "Draw indirect is not supported!");
  3184. BGFX_ENCODER(submit(_id, _program, _indirectHandle, _start, _num, _depth, _flags) );
  3185. }
  3186. void Encoder::setBuffer(uint8_t _stage, IndexBufferHandle _handle, Access::Enum _access)
  3187. {
  3188. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3189. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_indexBufferHandle, _handle);
  3190. BGFX_ENCODER(setBuffer(_stage, _handle, _access) );
  3191. }
  3192. void Encoder::setBuffer(uint8_t _stage, VertexBufferHandle _handle, Access::Enum _access)
  3193. {
  3194. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3195. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3196. BGFX_ENCODER(setBuffer(_stage, _handle, _access) );
  3197. }
  3198. void Encoder::setBuffer(uint8_t _stage, DynamicIndexBufferHandle _handle, Access::Enum _access)
  3199. {
  3200. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3201. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_dynamicIndexBufferHandle, _handle);
  3202. const DynamicIndexBuffer& dib = s_ctx->m_dynamicIndexBuffers[_handle.idx];
  3203. BGFX_ENCODER(setBuffer(_stage, dib.m_handle, _access) );
  3204. }
  3205. void Encoder::setBuffer(uint8_t _stage, DynamicVertexBufferHandle _handle, Access::Enum _access)
  3206. {
  3207. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3208. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_dynamicVertexBufferHandle, _handle);
  3209. const DynamicVertexBuffer& dvb = s_ctx->m_dynamicVertexBuffers[_handle.idx];
  3210. BGFX_ENCODER(setBuffer(_stage, dvb.m_handle, _access) );
  3211. }
  3212. void Encoder::setBuffer(uint8_t _stage, IndirectBufferHandle _handle, Access::Enum _access)
  3213. {
  3214. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3215. BGFX_CHECK_HANDLE("setBuffer", s_ctx->m_vertexBufferHandle, _handle);
  3216. VertexBufferHandle handle = { _handle.idx };
  3217. BGFX_ENCODER(setBuffer(_stage, handle, _access) );
  3218. }
  3219. void Encoder::setImage(uint8_t _stage, TextureHandle _handle, uint8_t _mip, Access::Enum _access, TextureFormat::Enum _format)
  3220. {
  3221. BX_ASSERT(_stage < g_caps.limits.maxComputeBindings, "Invalid stage %d (max %d).", _stage, g_caps.limits.maxComputeBindings);
  3222. BGFX_CHECK_HANDLE_INVALID_OK("setImage/TextureHandle", s_ctx->m_textureHandle, _handle);
  3223. _format = TextureFormat::Count == _format
  3224. ? TextureFormat::Enum(s_ctx->m_textureRef[_handle.idx].m_format)
  3225. : _format
  3226. ;
  3227. BX_ASSERT(_format != TextureFormat::BGRA8
  3228. , "Can't use TextureFormat::BGRA8 with compute, use TextureFormat::RGBA8 instead."
  3229. );
  3230. BGFX_ENCODER(setImage(_stage, _handle, _mip, _access, _format) );
  3231. }
  3232. void Encoder::dispatch(ViewId _id, ProgramHandle _program, uint32_t _numX, uint32_t _numY, uint32_t _numZ, uint8_t _flags)
  3233. {
  3234. BGFX_CHECK_CAPS(BGFX_CAPS_COMPUTE, "Compute is not supported!");
  3235. BGFX_CHECK_HANDLE_INVALID_OK("dispatch", s_ctx->m_programHandle, _program);
  3236. BGFX_ENCODER(dispatch(_id, _program, _numX, _numY, _numZ, _flags) );
  3237. }
  3238. void Encoder::dispatch(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint16_t _start, uint16_t _num, uint8_t _flags)
  3239. {
  3240. BGFX_CHECK_CAPS(BGFX_CAPS_DRAW_INDIRECT, "Dispatch indirect is not supported!");
  3241. BGFX_CHECK_CAPS(BGFX_CAPS_COMPUTE, "Compute is not supported!");
  3242. BGFX_CHECK_HANDLE_INVALID_OK("dispatch", s_ctx->m_programHandle, _program);
  3243. BGFX_CHECK_HANDLE("dispatch", s_ctx->m_vertexBufferHandle, _indirectHandle);
  3244. BGFX_ENCODER(dispatch(_id, _program, _indirectHandle, _start, _num, _flags) );
  3245. }
  3246. void Encoder::discard(uint8_t _flags)
  3247. {
  3248. BGFX_ENCODER(discard(_flags) );
  3249. }
  3250. 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)
  3251. {
  3252. blit(_id, _dst, 0, _dstX, _dstY, 0, _src, 0, _srcX, _srcY, 0, _width, _height, 0);
  3253. }
  3254. 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)
  3255. {
  3256. BGFX_CHECK_CAPS(BGFX_CAPS_TEXTURE_BLIT, "Texture blit is not supported!");
  3257. BGFX_CHECK_HANDLE("blit/src TextureHandle", s_ctx->m_textureHandle, _src);
  3258. BGFX_CHECK_HANDLE("blit/dst TextureHandle", s_ctx->m_textureHandle, _dst);
  3259. const TextureRef& src = s_ctx->m_textureRef[_src.idx];
  3260. const TextureRef& dst = s_ctx->m_textureRef[_dst.idx];
  3261. BX_ASSERT(src.m_format == dst.m_format
  3262. , "Texture format must match (src %s, dst %s)."
  3263. , bimg::getName(bimg::TextureFormat::Enum(src.m_format) )
  3264. , bimg::getName(bimg::TextureFormat::Enum(dst.m_format) )
  3265. );
  3266. BX_ASSERT(_srcMip < src.m_numMips, "Invalid blit src mip (%d > %d)", _srcMip, src.m_numMips - 1);
  3267. BX_ASSERT(_dstMip < dst.m_numMips, "Invalid blit dst mip (%d > %d)", _dstMip, dst.m_numMips - 1);
  3268. uint32_t srcWidth = bx::max<uint32_t>(1, src.m_width >> _srcMip);
  3269. uint32_t srcHeight = bx::max<uint32_t>(1, src.m_height >> _srcMip);
  3270. uint32_t dstWidth = bx::max<uint32_t>(1, dst.m_width >> _dstMip);
  3271. uint32_t dstHeight = bx::max<uint32_t>(1, dst.m_height >> _dstMip);
  3272. uint32_t srcDepth = src.isCubeMap() ? 6 : bx::max<uint32_t>(1, src.m_depth >> _srcMip);
  3273. uint32_t dstDepth = dst.isCubeMap() ? 6 : bx::max<uint32_t>(1, dst.m_depth >> _dstMip);
  3274. BX_ASSERT(_srcX < srcWidth && _srcY < srcHeight && _srcZ < srcDepth
  3275. , "Blit src coordinates out of range (%d, %d, %d) >= (%d, %d, %d)"
  3276. , _srcX, _srcY, _srcZ
  3277. , srcWidth, srcHeight, srcDepth
  3278. );
  3279. BX_ASSERT(_dstX < dstWidth && _dstY < dstHeight && _dstZ < dstDepth
  3280. , "Blit dst coordinates out of range (%d, %d, %d) >= (%d, %d, %d)"
  3281. , _dstX, _dstY, _dstZ
  3282. , dstWidth, dstHeight, dstDepth
  3283. );
  3284. srcWidth = bx::min<uint32_t>(srcWidth, _srcX + _width ) - _srcX;
  3285. srcHeight = bx::min<uint32_t>(srcHeight, _srcY + _height) - _srcY;
  3286. srcDepth = bx::min<uint32_t>(srcDepth, _srcZ + _depth ) - _srcZ;
  3287. dstWidth = bx::min<uint32_t>(dstWidth, _dstX + _width ) - _dstX;
  3288. dstHeight = bx::min<uint32_t>(dstHeight, _dstY + _height) - _dstY;
  3289. dstDepth = bx::min<uint32_t>(dstDepth, _dstZ + _depth ) - _dstZ;
  3290. const uint16_t width = uint16_t(bx::min(srcWidth, dstWidth ) );
  3291. const uint16_t height = uint16_t(bx::min(srcHeight, dstHeight) );
  3292. const uint16_t depth = uint16_t(bx::min(srcDepth, dstDepth ) );
  3293. BGFX_ENCODER(blit(_id, _dst, _dstMip, _dstX, _dstY, _dstZ, _src, _srcMip, _srcX, _srcY, _srcZ, width, height, depth) );
  3294. }
  3295. #undef BGFX_ENCODER
  3296. void end(Encoder* _encoder)
  3297. {
  3298. s_ctx->end(_encoder);
  3299. }
  3300. uint32_t frame(bool _capture)
  3301. {
  3302. BGFX_CHECK_API_THREAD();
  3303. return s_ctx->frame(_capture);
  3304. }
  3305. const Caps* getCaps()
  3306. {
  3307. return &g_caps;
  3308. }
  3309. const Stats* getStats()
  3310. {
  3311. return s_ctx->getPerfStats();
  3312. }
  3313. RendererType::Enum getRendererType()
  3314. {
  3315. return g_caps.rendererType;
  3316. }
  3317. const Memory* alloc(uint32_t _size)
  3318. {
  3319. BX_ASSERT(0 < _size, "Invalid memory operation. _size is 0.");
  3320. Memory* mem = (Memory*)BX_ALLOC(g_allocator, sizeof(Memory) + _size);
  3321. mem->size = _size;
  3322. mem->data = (uint8_t*)mem + sizeof(Memory);
  3323. return mem;
  3324. }
  3325. const Memory* copy(const void* _data, uint32_t _size)
  3326. {
  3327. BX_ASSERT(0 < _size, "Invalid memory operation. _size is 0.");
  3328. const Memory* mem = alloc(_size);
  3329. bx::memCopy(mem->data, _data, _size);
  3330. return mem;
  3331. }
  3332. struct MemoryRef
  3333. {
  3334. Memory mem;
  3335. ReleaseFn releaseFn;
  3336. void* userData;
  3337. };
  3338. const Memory* makeRef(const void* _data, uint32_t _size, ReleaseFn _releaseFn, void* _userData)
  3339. {
  3340. MemoryRef* memRef = (MemoryRef*)BX_ALLOC(g_allocator, sizeof(MemoryRef) );
  3341. memRef->mem.size = _size;
  3342. memRef->mem.data = (uint8_t*)_data;
  3343. memRef->releaseFn = _releaseFn;
  3344. memRef->userData = _userData;
  3345. return &memRef->mem;
  3346. }
  3347. bool isMemoryRef(const Memory* _mem)
  3348. {
  3349. return _mem->data != (uint8_t*)_mem + sizeof(Memory);
  3350. }
  3351. void release(const Memory* _mem)
  3352. {
  3353. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3354. Memory* mem = const_cast<Memory*>(_mem);
  3355. if (isMemoryRef(mem) )
  3356. {
  3357. MemoryRef* memRef = reinterpret_cast<MemoryRef*>(mem);
  3358. if (NULL != memRef->releaseFn)
  3359. {
  3360. memRef->releaseFn(mem->data, memRef->userData);
  3361. }
  3362. }
  3363. BX_FREE(g_allocator, mem);
  3364. }
  3365. void setDebug(uint32_t _debug)
  3366. {
  3367. BGFX_CHECK_API_THREAD();
  3368. s_ctx->setDebug(_debug);
  3369. }
  3370. void dbgTextClear(uint8_t _attr, bool _small)
  3371. {
  3372. BGFX_CHECK_API_THREAD();
  3373. s_ctx->dbgTextClear(_attr, _small);
  3374. }
  3375. void dbgTextPrintfVargs(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, va_list _argList)
  3376. {
  3377. s_ctx->dbgTextPrintfVargs(_x, _y, _attr, _format, _argList);
  3378. }
  3379. void dbgTextPrintf(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, ...)
  3380. {
  3381. BGFX_CHECK_API_THREAD();
  3382. va_list argList;
  3383. va_start(argList, _format);
  3384. s_ctx->dbgTextPrintfVargs(_x, _y, _attr, _format, argList);
  3385. va_end(argList);
  3386. }
  3387. void dbgTextImage(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height, const void* _data, uint16_t _pitch)
  3388. {
  3389. BGFX_CHECK_API_THREAD();
  3390. s_ctx->dbgTextImage(_x, _y, _width, _height, _data, _pitch);
  3391. }
  3392. IndexBufferHandle createIndexBuffer(const Memory* _mem, uint16_t _flags)
  3393. {
  3394. BX_ASSERT(
  3395. 0 == (_flags & BGFX_BUFFER_INDEX32) || 0 != (g_caps.supported & BGFX_CAPS_INDEX32)
  3396. , "32-bit indices are not supported. Use bgfx::getCaps to check BGFX_CAPS_INDEX32 backend renderer capabilities."
  3397. );
  3398. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3399. return s_ctx->createIndexBuffer(_mem, _flags);
  3400. }
  3401. void setName(IndexBufferHandle _handle, const char* _name, int32_t _len)
  3402. {
  3403. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3404. }
  3405. void destroy(IndexBufferHandle _handle)
  3406. {
  3407. s_ctx->destroyIndexBuffer(_handle);
  3408. }
  3409. VertexLayoutHandle createVertexLayout(const VertexLayout& _layout)
  3410. {
  3411. return s_ctx->createVertexLayout(_layout);
  3412. }
  3413. void destroy(VertexLayoutHandle _handle)
  3414. {
  3415. s_ctx->destroyVertexLayout(_handle);
  3416. }
  3417. VertexBufferHandle createVertexBuffer(const Memory* _mem, const VertexLayout& _layout, uint16_t _flags)
  3418. {
  3419. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3420. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3421. return s_ctx->createVertexBuffer(_mem, _layout, _flags);
  3422. }
  3423. void setName(VertexBufferHandle _handle, const char* _name, int32_t _len)
  3424. {
  3425. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3426. }
  3427. void destroy(VertexBufferHandle _handle)
  3428. {
  3429. s_ctx->destroyVertexBuffer(_handle);
  3430. }
  3431. DynamicIndexBufferHandle createDynamicIndexBuffer(uint32_t _num, uint16_t _flags)
  3432. {
  3433. return s_ctx->createDynamicIndexBuffer(_num, _flags);
  3434. }
  3435. DynamicIndexBufferHandle createDynamicIndexBuffer(const Memory* _mem, uint16_t _flags)
  3436. {
  3437. BX_ASSERT(
  3438. 0 == (_flags & BGFX_BUFFER_INDEX32) || 0 != (g_caps.supported & BGFX_CAPS_INDEX32)
  3439. , "32-bit indices are not supported. Use bgfx::getCaps to check BGFX_CAPS_INDEX32 backend renderer capabilities."
  3440. );
  3441. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3442. return s_ctx->createDynamicIndexBuffer(_mem, _flags);
  3443. }
  3444. void update(DynamicIndexBufferHandle _handle, uint32_t _startIndex, const Memory* _mem)
  3445. {
  3446. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3447. s_ctx->update(_handle, _startIndex, _mem);
  3448. }
  3449. void destroy(DynamicIndexBufferHandle _handle)
  3450. {
  3451. s_ctx->destroyDynamicIndexBuffer(_handle);
  3452. }
  3453. DynamicVertexBufferHandle createDynamicVertexBuffer(uint32_t _num, const VertexLayout& _layout, uint16_t _flags)
  3454. {
  3455. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3456. return s_ctx->createDynamicVertexBuffer(_num, _layout, _flags);
  3457. }
  3458. DynamicVertexBufferHandle createDynamicVertexBuffer(const Memory* _mem, const VertexLayout& _layout, uint16_t _flags)
  3459. {
  3460. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3461. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3462. return s_ctx->createDynamicVertexBuffer(_mem, _layout, _flags);
  3463. }
  3464. void update(DynamicVertexBufferHandle _handle, uint32_t _startVertex, const Memory* _mem)
  3465. {
  3466. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3467. s_ctx->update(_handle, _startVertex, _mem);
  3468. }
  3469. void destroy(DynamicVertexBufferHandle _handle)
  3470. {
  3471. s_ctx->destroyDynamicVertexBuffer(_handle);
  3472. }
  3473. uint32_t getAvailTransientIndexBuffer(uint32_t _num)
  3474. {
  3475. BX_ASSERT(0 < _num, "Requesting 0 indices.");
  3476. return s_ctx->getAvailTransientIndexBuffer(_num);
  3477. }
  3478. uint32_t getAvailTransientVertexBuffer(uint32_t _num, const VertexLayout& _layout)
  3479. {
  3480. BX_ASSERT(0 < _num, "Requesting 0 vertices.");
  3481. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3482. return s_ctx->getAvailTransientVertexBuffer(_num, _layout.m_stride);
  3483. }
  3484. uint32_t getAvailInstanceDataBuffer(uint32_t _num, uint16_t _stride)
  3485. {
  3486. BX_ASSERT(0 < _num, "Requesting 0 instances.");
  3487. return s_ctx->getAvailTransientVertexBuffer(_num, _stride);
  3488. }
  3489. void allocTransientIndexBuffer(TransientIndexBuffer* _tib, uint32_t _num, bool _index32)
  3490. {
  3491. BX_ASSERT(NULL != _tib, "_tib can't be NULL");
  3492. BX_ASSERT(0 < _num, "Requesting 0 indices.");
  3493. BX_ASSERT(
  3494. !_index32 || 0 != (g_caps.supported & BGFX_CAPS_INDEX32)
  3495. , "32-bit indices are not supported. Use bgfx::getCaps to check BGFX_CAPS_INDEX32 backend renderer capabilities."
  3496. );
  3497. s_ctx->allocTransientIndexBuffer(_tib, _num, _index32);
  3498. const uint32_t indexSize = _tib->isIndex16 ? 2 : 4;
  3499. BX_ASSERT(_num == _tib->size/ indexSize
  3500. , "Failed to allocate transient index buffer (requested %d, available %d). "
  3501. "Use bgfx::getAvailTransient* functions to ensure availability."
  3502. , _num
  3503. , _tib->size/indexSize
  3504. );
  3505. BX_UNUSED(indexSize);
  3506. }
  3507. void allocTransientVertexBuffer(TransientVertexBuffer* _tvb, uint32_t _num, const VertexLayout& _layout)
  3508. {
  3509. BX_ASSERT(NULL != _tvb, "_tvb can't be NULL");
  3510. BX_ASSERT(0 < _num, "Requesting 0 vertices.");
  3511. BX_ASSERT(isValid(_layout), "Invalid VertexLayout.");
  3512. s_ctx->allocTransientVertexBuffer(_tvb, _num, _layout);
  3513. BX_ASSERT(_num == _tvb->size / _layout.m_stride
  3514. , "Failed to allocate transient vertex buffer (requested %d, available %d). "
  3515. "Use bgfx::getAvailTransient* functions to ensure availability."
  3516. , _num
  3517. , _tvb->size / _layout.m_stride
  3518. );
  3519. }
  3520. bool allocTransientBuffers(bgfx::TransientVertexBuffer* _tvb, const bgfx::VertexLayout& _layout, uint32_t _numVertices, bgfx::TransientIndexBuffer* _tib, uint32_t _numIndices)
  3521. {
  3522. BGFX_MUTEX_SCOPE(s_ctx->m_resourceApiLock);
  3523. if (_numVertices == getAvailTransientVertexBuffer(_numVertices, _layout)
  3524. && _numIndices == getAvailTransientIndexBuffer(_numIndices) )
  3525. {
  3526. allocTransientVertexBuffer(_tvb, _numVertices, _layout);
  3527. allocTransientIndexBuffer(_tib, _numIndices);
  3528. return true;
  3529. }
  3530. return false;
  3531. }
  3532. void allocInstanceDataBuffer(InstanceDataBuffer* _idb, uint32_t _num, uint16_t _stride)
  3533. {
  3534. BGFX_CHECK_CAPS(BGFX_CAPS_INSTANCING, "Instancing is not supported!");
  3535. BX_ASSERT(bx::isAligned(_stride, 16), "Stride must be multiple of 16.");
  3536. BX_ASSERT(0 < _num, "Requesting 0 instanced data vertices.");
  3537. s_ctx->allocInstanceDataBuffer(_idb, _num, _stride);
  3538. BX_ASSERT(_num == _idb->size / _stride
  3539. , "Failed to allocate instance data buffer (requested %d, available %d). "
  3540. "Use bgfx::getAvailTransient* functions to ensure availability."
  3541. , _num
  3542. , _idb->size / _stride
  3543. );
  3544. }
  3545. IndirectBufferHandle createIndirectBuffer(uint32_t _num)
  3546. {
  3547. return s_ctx->createIndirectBuffer(_num);
  3548. }
  3549. void destroy(IndirectBufferHandle _handle)
  3550. {
  3551. s_ctx->destroyIndirectBuffer(_handle);
  3552. }
  3553. ShaderHandle createShader(const Memory* _mem)
  3554. {
  3555. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3556. return s_ctx->createShader(_mem);
  3557. }
  3558. uint16_t getShaderUniforms(ShaderHandle _handle, UniformHandle* _uniforms, uint16_t _max)
  3559. {
  3560. BX_WARN(NULL == _uniforms || 0 != _max
  3561. , "Passing uniforms array pointer, but array maximum capacity is set to 0."
  3562. );
  3563. uint16_t num = s_ctx->getShaderUniforms(_handle, _uniforms, _max);
  3564. BX_WARN(0 == _max || num <= _max
  3565. , "Shader has more uniforms that capacity of output array. Output is truncated (num %d, max %d)."
  3566. , num
  3567. , _max
  3568. );
  3569. return num;
  3570. }
  3571. void setName(ShaderHandle _handle, const char* _name, int32_t _len)
  3572. {
  3573. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3574. }
  3575. void destroy(ShaderHandle _handle)
  3576. {
  3577. s_ctx->destroyShader(_handle);
  3578. }
  3579. ProgramHandle createProgram(ShaderHandle _vsh, ShaderHandle _fsh, bool _destroyShaders)
  3580. {
  3581. if (!isValid(_fsh) )
  3582. {
  3583. return createProgram(_vsh, _destroyShaders);
  3584. }
  3585. return s_ctx->createProgram(_vsh, _fsh, _destroyShaders);
  3586. }
  3587. ProgramHandle createProgram(ShaderHandle _csh, bool _destroyShader)
  3588. {
  3589. return s_ctx->createProgram(_csh, _destroyShader);
  3590. }
  3591. void destroy(ProgramHandle _handle)
  3592. {
  3593. s_ctx->destroyProgram(_handle);
  3594. }
  3595. static void isTextureValid(uint16_t _depth, bool _cubeMap, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, bx::Error* _err)
  3596. {
  3597. BX_ERROR_SCOPE(_err);
  3598. const bool is3DTexture = 1 < _depth;
  3599. if (_cubeMap && is3DTexture)
  3600. {
  3601. _err->setError(BGFX_ERROR_TEXTURE_VALIDATION
  3602. , "Texture can't be depth and cube map at the same time."
  3603. );
  3604. return;
  3605. }
  3606. if (is3DTexture
  3607. && 0 == (g_caps.supported & BGFX_CAPS_TEXTURE_3D) )
  3608. {
  3609. _err->setError(BGFX_ERROR_TEXTURE_VALIDATION
  3610. , "Texture3D is not supported! "
  3611. "Use bgfx::getCaps to check BGFX_CAPS_TEXTURE_3D backend renderer capabilities."
  3612. );
  3613. return;
  3614. }
  3615. if (0 != (_flags & BGFX_TEXTURE_RT_MASK)
  3616. && 0 != (_flags & BGFX_TEXTURE_READ_BACK) )
  3617. {
  3618. _err->setError(BGFX_ERROR_TEXTURE_VALIDATION
  3619. , "Can't create render target with BGFX_TEXTURE_READ_BACK flag."
  3620. );
  3621. return;
  3622. }
  3623. if (1 < _numLayers
  3624. && 0 == (g_caps.supported & BGFX_CAPS_TEXTURE_2D_ARRAY) )
  3625. {
  3626. _err->setError(BGFX_ERROR_TEXTURE_VALIDATION
  3627. , "Texture array is not supported! "
  3628. "Use bgfx::getCaps to check BGFX_CAPS_TEXTURE_2D_ARRAY backend renderer capabilities."
  3629. );
  3630. return;
  3631. }
  3632. bool formatSupported;
  3633. if (0 != (_flags & (BGFX_TEXTURE_RT | BGFX_TEXTURE_RT_WRITE_ONLY)) )
  3634. {
  3635. formatSupported = 0 != (g_caps.formats[_format] & BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER);
  3636. }
  3637. else
  3638. {
  3639. formatSupported = 0 != (g_caps.formats[_format] & (0
  3640. | BGFX_CAPS_FORMAT_TEXTURE_2D
  3641. | BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED
  3642. | BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  3643. ) );
  3644. }
  3645. uint16_t srgbCaps = BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB;
  3646. if (_cubeMap)
  3647. {
  3648. formatSupported = 0 != (g_caps.formats[_format] & (0
  3649. | BGFX_CAPS_FORMAT_TEXTURE_CUBE
  3650. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED
  3651. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  3652. ) );
  3653. srgbCaps = BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB;
  3654. }
  3655. else if (is3DTexture)
  3656. {
  3657. formatSupported = 0 != (g_caps.formats[_format] & (0
  3658. | BGFX_CAPS_FORMAT_TEXTURE_3D
  3659. | BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED
  3660. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  3661. ) );
  3662. srgbCaps = BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB;
  3663. }
  3664. if (formatSupported
  3665. && 0 != (_flags & BGFX_TEXTURE_RT_MASK) )
  3666. {
  3667. formatSupported = 0 != (g_caps.formats[_format] & (0
  3668. | BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  3669. ) );
  3670. }
  3671. if (!formatSupported)
  3672. {
  3673. _err->setError(BGFX_ERROR_TEXTURE_VALIDATION
  3674. , "Texture format is not supported! "
  3675. "Use bgfx::isTextureValid to check support for texture format before creating it."
  3676. );
  3677. return;
  3678. }
  3679. if (0 != (_flags & BGFX_TEXTURE_MSAA_SAMPLE)
  3680. && 0 == (g_caps.formats[_format] & BGFX_CAPS_FORMAT_TEXTURE_MSAA) )
  3681. {
  3682. _err->setError(BGFX_ERROR_TEXTURE_VALIDATION
  3683. , "MSAA sampling for this texture format is not supported."
  3684. );
  3685. return;
  3686. }
  3687. if (0 != (_flags & BGFX_TEXTURE_SRGB)
  3688. && 0 == (g_caps.formats[_format] & srgbCaps & (0
  3689. | BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  3690. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  3691. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  3692. ) ) )
  3693. {
  3694. _err->setError(BGFX_ERROR_TEXTURE_VALIDATION
  3695. , "sRGB sampling for this texture format is not supported."
  3696. );
  3697. return;
  3698. }
  3699. }
  3700. bool isTextureValid(uint16_t _depth, bool _cubeMap, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags)
  3701. {
  3702. bx::Error err;
  3703. isTextureValid(_depth, _cubeMap, _numLayers, _format, _flags, &err);
  3704. return err.isOk();
  3705. }
  3706. void calcTextureSize(TextureInfo& _info, uint16_t _width, uint16_t _height, uint16_t _depth, bool _cubeMap, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format)
  3707. {
  3708. bimg::imageGetSize( (bimg::TextureInfo*)&_info, _width, _height, _depth, _cubeMap, _hasMips, _numLayers, bimg::TextureFormat::Enum(_format) );
  3709. }
  3710. TextureHandle createTexture(const Memory* _mem, uint64_t _flags, uint8_t _skip, TextureInfo* _info)
  3711. {
  3712. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3713. return s_ctx->createTexture(_mem, _flags, _skip, _info, BackbufferRatio::Count, false);
  3714. }
  3715. void getTextureSizeFromRatio(BackbufferRatio::Enum _ratio, uint16_t& _width, uint16_t& _height)
  3716. {
  3717. switch (_ratio)
  3718. {
  3719. case BackbufferRatio::Half: _width /= 2; _height /= 2; break;
  3720. case BackbufferRatio::Quarter: _width /= 4; _height /= 4; break;
  3721. case BackbufferRatio::Eighth: _width /= 8; _height /= 8; break;
  3722. case BackbufferRatio::Sixteenth: _width /= 16; _height /= 16; break;
  3723. case BackbufferRatio::Double: _width *= 2; _height *= 2; break;
  3724. default:
  3725. break;
  3726. }
  3727. _width = bx::max<uint16_t>(1, _width);
  3728. _height = bx::max<uint16_t>(1, _height);
  3729. }
  3730. 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)
  3731. {
  3732. bx::Error err;
  3733. isTextureValid(0, false, _numLayers, _format, _flags, &err);
  3734. BX_ASSERT(err.isOk(), "%s (layers %d, format %s)"
  3735. , err.getMessage().getPtr()
  3736. , _numLayers
  3737. , getName(_format)
  3738. );
  3739. if (BackbufferRatio::Count != _ratio)
  3740. {
  3741. _width = uint16_t(s_ctx->m_init.resolution.width);
  3742. _height = uint16_t(s_ctx->m_init.resolution.height);
  3743. getTextureSizeFromRatio(_ratio, _width, _height);
  3744. }
  3745. const uint8_t numMips = calcNumMips(_hasMips, _width, _height);
  3746. _numLayers = bx::max<uint16_t>(_numLayers, 1);
  3747. if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  3748. && NULL != _mem)
  3749. {
  3750. TextureInfo ti;
  3751. calcTextureSize(ti, _width, _height, 1, false, _hasMips, _numLayers, _format);
  3752. BX_ASSERT(ti.storageSize == _mem->size
  3753. , "createTexture2D: Texture storage size doesn't match passed memory size (storage size: %d, memory size: %d)"
  3754. , ti.storageSize
  3755. , _mem->size
  3756. );
  3757. }
  3758. uint32_t size = sizeof(uint32_t)+sizeof(TextureCreate);
  3759. const Memory* mem = alloc(size);
  3760. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  3761. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  3762. bx::write(&writer, magic);
  3763. TextureCreate tc;
  3764. tc.m_width = _width;
  3765. tc.m_height = _height;
  3766. tc.m_depth = 0;
  3767. tc.m_numLayers = _numLayers;
  3768. tc.m_numMips = numMips;
  3769. tc.m_format = _format;
  3770. tc.m_cubeMap = false;
  3771. tc.m_mem = _mem;
  3772. bx::write(&writer, tc);
  3773. return s_ctx->createTexture(mem, _flags, 0, NULL, _ratio, NULL != _mem);
  3774. }
  3775. TextureHandle createTexture2D(uint16_t _width, uint16_t _height, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  3776. {
  3777. BX_ASSERT(_width > 0 && _height > 0, "Invalid texture size (width %d, height %d).", _width, _height);
  3778. return createTexture2D(BackbufferRatio::Count, _width, _height, _hasMips, _numLayers, _format, _flags, _mem);
  3779. }
  3780. TextureHandle createTexture2D(BackbufferRatio::Enum _ratio, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags)
  3781. {
  3782. BX_ASSERT(_ratio < BackbufferRatio::Count, "Invalid back buffer ratio.");
  3783. return createTexture2D(_ratio, 0, 0, _hasMips, _numLayers, _format, _flags, NULL);
  3784. }
  3785. TextureHandle createTexture3D(uint16_t _width, uint16_t _height, uint16_t _depth, bool _hasMips, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  3786. {
  3787. bx::Error err;
  3788. isTextureValid(_depth, false, 1, _format, _flags, &err);
  3789. BX_ASSERT(err.isOk(), "%s", err.getMessage().getPtr() );
  3790. const uint8_t numMips = calcNumMips(_hasMips, _width, _height, _depth);
  3791. if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  3792. && NULL != _mem)
  3793. {
  3794. TextureInfo ti;
  3795. calcTextureSize(ti, _width, _height, _depth, false, _hasMips, 1, _format);
  3796. BX_ASSERT(ti.storageSize == _mem->size
  3797. , "createTexture3D: Texture storage size doesn't match passed memory size (storage size: %d, memory size: %d)"
  3798. , ti.storageSize
  3799. , _mem->size
  3800. );
  3801. }
  3802. uint32_t size = sizeof(uint32_t)+sizeof(TextureCreate);
  3803. const Memory* mem = alloc(size);
  3804. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  3805. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  3806. bx::write(&writer, magic);
  3807. TextureCreate tc;
  3808. tc.m_width = _width;
  3809. tc.m_height = _height;
  3810. tc.m_depth = _depth;
  3811. tc.m_numLayers = 1;
  3812. tc.m_numMips = numMips;
  3813. tc.m_format = _format;
  3814. tc.m_cubeMap = false;
  3815. tc.m_mem = _mem;
  3816. bx::write(&writer, tc);
  3817. return s_ctx->createTexture(mem, _flags, 0, NULL, BackbufferRatio::Count, NULL != _mem);
  3818. }
  3819. TextureHandle createTextureCube(uint16_t _size, bool _hasMips, uint16_t _numLayers, TextureFormat::Enum _format, uint64_t _flags, const Memory* _mem)
  3820. {
  3821. bx::Error err;
  3822. isTextureValid(0, true, _numLayers, _format, _flags, &err);
  3823. BX_ASSERT(err.isOk(), "%s", err.getMessage().getPtr() );
  3824. const uint8_t numMips = calcNumMips(_hasMips, _size, _size);
  3825. _numLayers = bx::max<uint16_t>(_numLayers, 1);
  3826. if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  3827. && NULL != _mem)
  3828. {
  3829. TextureInfo ti;
  3830. calcTextureSize(ti, _size, _size, 1, true, _hasMips, _numLayers, _format);
  3831. BX_ASSERT(ti.storageSize == _mem->size
  3832. , "createTextureCube: Texture storage size doesn't match passed memory size (storage size: %d, memory size: %d)"
  3833. , ti.storageSize
  3834. , _mem->size
  3835. );
  3836. }
  3837. uint32_t size = sizeof(uint32_t)+sizeof(TextureCreate);
  3838. const Memory* mem = alloc(size);
  3839. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  3840. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  3841. bx::write(&writer, magic);
  3842. TextureCreate tc;
  3843. tc.m_width = _size;
  3844. tc.m_height = _size;
  3845. tc.m_depth = 0;
  3846. tc.m_numLayers = _numLayers;
  3847. tc.m_numMips = numMips;
  3848. tc.m_format = _format;
  3849. tc.m_cubeMap = true;
  3850. tc.m_mem = _mem;
  3851. bx::write(&writer, tc);
  3852. return s_ctx->createTexture(mem, _flags, 0, NULL, BackbufferRatio::Count, NULL != _mem);
  3853. }
  3854. void setName(TextureHandle _handle, const char* _name, int32_t _len)
  3855. {
  3856. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3857. }
  3858. void* getDirectAccessPtr(TextureHandle _handle)
  3859. {
  3860. return s_ctx->getDirectAccessPtr(_handle);
  3861. }
  3862. void destroy(TextureHandle _handle)
  3863. {
  3864. s_ctx->destroyTexture(_handle);
  3865. }
  3866. 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)
  3867. {
  3868. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3869. if (_width == 0
  3870. || _height == 0)
  3871. {
  3872. release(_mem);
  3873. }
  3874. else
  3875. {
  3876. s_ctx->updateTexture(_handle, 0, _mip, _x, _y, _layer, _width, _height, 1, _pitch, _mem);
  3877. }
  3878. }
  3879. 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)
  3880. {
  3881. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3882. BGFX_CHECK_CAPS(BGFX_CAPS_TEXTURE_3D, "Texture3D is not supported!");
  3883. if (0 == _width
  3884. || 0 == _height
  3885. || 0 == _depth)
  3886. {
  3887. release(_mem);
  3888. }
  3889. else
  3890. {
  3891. s_ctx->updateTexture(_handle, 0, _mip, _x, _y, _z, _width, _height, _depth, UINT16_MAX, _mem);
  3892. }
  3893. }
  3894. 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)
  3895. {
  3896. BX_ASSERT(NULL != _mem, "_mem can't be NULL");
  3897. BX_ASSERT(_side <= 5, "Invalid side %d.", _side);
  3898. if (0 == _width
  3899. || 0 == _height)
  3900. {
  3901. release(_mem);
  3902. }
  3903. else
  3904. {
  3905. s_ctx->updateTexture(_handle, _side, _mip, _x, _y, _layer, _width, _height, 1, _pitch, _mem);
  3906. }
  3907. }
  3908. uint32_t readTexture(TextureHandle _handle, void* _data, uint8_t _mip)
  3909. {
  3910. BX_ASSERT(NULL != _data, "_data can't be NULL");
  3911. BGFX_CHECK_CAPS(BGFX_CAPS_TEXTURE_READ_BACK, "Texture read-back is not supported!");
  3912. return s_ctx->readTexture(_handle, _data, _mip);
  3913. }
  3914. FrameBufferHandle createFrameBuffer(uint16_t _width, uint16_t _height, TextureFormat::Enum _format, uint64_t _textureFlags)
  3915. {
  3916. _textureFlags |= _textureFlags&BGFX_TEXTURE_RT_MSAA_MASK ? 0 : BGFX_TEXTURE_RT;
  3917. TextureHandle th = createTexture2D(_width, _height, false, 1, _format, _textureFlags);
  3918. return createFrameBuffer(1, &th, true);
  3919. }
  3920. FrameBufferHandle createFrameBuffer(BackbufferRatio::Enum _ratio, TextureFormat::Enum _format, uint64_t _textureFlags)
  3921. {
  3922. BX_ASSERT(_ratio < BackbufferRatio::Count, "Invalid back buffer ratio.");
  3923. _textureFlags |= _textureFlags&BGFX_TEXTURE_RT_MSAA_MASK ? 0 : BGFX_TEXTURE_RT;
  3924. TextureHandle th = createTexture2D(_ratio, false, 1, _format, _textureFlags);
  3925. return createFrameBuffer(1, &th, true);
  3926. }
  3927. FrameBufferHandle createFrameBuffer(uint8_t _num, const TextureHandle* _handles, bool _destroyTextures)
  3928. {
  3929. Attachment attachment[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  3930. for (uint8_t ii = 0; ii < _num; ++ii)
  3931. {
  3932. Attachment& at = attachment[ii];
  3933. at.init(_handles[ii], Access::Write, 0, 1, 0, BGFX_RESOLVE_AUTO_GEN_MIPS);
  3934. }
  3935. return createFrameBuffer(_num, attachment, _destroyTextures);
  3936. }
  3937. FrameBufferHandle createFrameBuffer(uint8_t _num, const Attachment* _attachment, bool _destroyTextures)
  3938. {
  3939. BX_ASSERT(_num != 0, "Number of frame buffer attachments can't be 0.");
  3940. BX_ASSERT(_num <= BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS
  3941. , "Number of frame buffer attachments is larger than allowed %d (max: %d)."
  3942. , _num
  3943. , BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS
  3944. );
  3945. BX_ASSERT(NULL != _attachment, "_attachment can't be NULL");
  3946. return s_ctx->createFrameBuffer(_num, _attachment, _destroyTextures);
  3947. }
  3948. FrameBufferHandle createFrameBuffer(void* _nwh, uint16_t _width, uint16_t _height, TextureFormat::Enum _format, TextureFormat::Enum _depthFormat)
  3949. {
  3950. BGFX_CHECK_CAPS(BGFX_CAPS_SWAP_CHAIN, "Swap chain is not supported!");
  3951. BX_WARN(_width > 0 && _height > 0
  3952. , "Invalid frame buffer dimensions (width %d, height %d)."
  3953. , _width
  3954. , _height
  3955. );
  3956. BX_ASSERT(_format == TextureFormat::Count || bimg::isColor(bimg::TextureFormat::Enum(_format) )
  3957. , "Invalid texture format for color (%s)."
  3958. , bimg::getName(bimg::TextureFormat::Enum(_format) )
  3959. );
  3960. BX_ASSERT(_depthFormat == TextureFormat::Count || bimg::isDepth(bimg::TextureFormat::Enum(_depthFormat) )
  3961. , "Invalid texture format for depth (%s)."
  3962. , bimg::getName(bimg::TextureFormat::Enum(_depthFormat) )
  3963. );
  3964. return s_ctx->createFrameBuffer(
  3965. _nwh
  3966. , bx::max<uint16_t>(_width, 1)
  3967. , bx::max<uint16_t>(_height, 1)
  3968. , _format
  3969. , _depthFormat
  3970. );
  3971. }
  3972. void setName(FrameBufferHandle _handle, const char* _name, int32_t _len)
  3973. {
  3974. s_ctx->setName(_handle, bx::StringView(_name, _len) );
  3975. }
  3976. TextureHandle getTexture(FrameBufferHandle _handle, uint8_t _attachment)
  3977. {
  3978. return s_ctx->getTexture(_handle, _attachment);
  3979. }
  3980. void destroy(FrameBufferHandle _handle)
  3981. {
  3982. s_ctx->destroyFrameBuffer(_handle);
  3983. }
  3984. UniformHandle createUniform(const char* _name, UniformType::Enum _type, uint16_t _num)
  3985. {
  3986. return s_ctx->createUniform(_name, _type, _num);
  3987. }
  3988. void getUniformInfo(UniformHandle _handle, UniformInfo& _info)
  3989. {
  3990. s_ctx->getUniformInfo(_handle, _info);
  3991. }
  3992. void destroy(UniformHandle _handle)
  3993. {
  3994. s_ctx->destroyUniform(_handle);
  3995. }
  3996. OcclusionQueryHandle createOcclusionQuery()
  3997. {
  3998. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  3999. return s_ctx->createOcclusionQuery();
  4000. }
  4001. OcclusionQueryResult::Enum getResult(OcclusionQueryHandle _handle, int32_t* _result)
  4002. {
  4003. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  4004. return s_ctx->getResult(_handle, _result);
  4005. }
  4006. void destroy(OcclusionQueryHandle _handle)
  4007. {
  4008. BGFX_CHECK_CAPS(BGFX_CAPS_OCCLUSION_QUERY, "Occlusion query is not supported!");
  4009. s_ctx->destroyOcclusionQuery(_handle);
  4010. }
  4011. void setPaletteColor(uint8_t _index, uint32_t _rgba)
  4012. {
  4013. const uint8_t rr = uint8_t(_rgba>>24);
  4014. const uint8_t gg = uint8_t(_rgba>>16);
  4015. const uint8_t bb = uint8_t(_rgba>> 8);
  4016. const uint8_t aa = uint8_t(_rgba>> 0);
  4017. const float rgba[4] =
  4018. {
  4019. rr * 1.0f/255.0f,
  4020. gg * 1.0f/255.0f,
  4021. bb * 1.0f/255.0f,
  4022. aa * 1.0f/255.0f,
  4023. };
  4024. s_ctx->setPaletteColor(_index, rgba);
  4025. }
  4026. void setPaletteColor(uint8_t _index, float _r, float _g, float _b, float _a)
  4027. {
  4028. float rgba[4] = { _r, _g, _b, _a };
  4029. s_ctx->setPaletteColor(_index, rgba);
  4030. }
  4031. void setPaletteColor(uint8_t _index, const float _rgba[4])
  4032. {
  4033. s_ctx->setPaletteColor(_index, _rgba);
  4034. }
  4035. bool checkView(ViewId _id)
  4036. {
  4037. // workaround GCC 4.9 type-limit check.
  4038. const uint32_t id = _id;
  4039. return id < BGFX_CONFIG_MAX_VIEWS;
  4040. }
  4041. void setViewName(ViewId _id, const char* _name)
  4042. {
  4043. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4044. s_ctx->setViewName(_id, _name);
  4045. }
  4046. void setViewRect(ViewId _id, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  4047. {
  4048. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4049. s_ctx->setViewRect(_id, _x, _y, _width, _height);
  4050. }
  4051. void setViewRect(ViewId _id, uint16_t _x, uint16_t _y, BackbufferRatio::Enum _ratio)
  4052. {
  4053. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4054. uint16_t width = uint16_t(s_ctx->m_init.resolution.width);
  4055. uint16_t height = uint16_t(s_ctx->m_init.resolution.height);
  4056. getTextureSizeFromRatio(_ratio, width, height);
  4057. setViewRect(_id, _x, _y, width, height);
  4058. }
  4059. void setViewScissor(ViewId _id, uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  4060. {
  4061. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4062. s_ctx->setViewScissor(_id, _x, _y, _width, _height);
  4063. }
  4064. void setViewClear(ViewId _id, uint16_t _flags, uint32_t _rgba, float _depth, uint8_t _stencil)
  4065. {
  4066. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4067. s_ctx->setViewClear(_id, _flags, _rgba, _depth, _stencil);
  4068. }
  4069. 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)
  4070. {
  4071. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4072. s_ctx->setViewClear(_id, _flags, _depth, _stencil, _0, _1, _2, _3, _4, _5, _6, _7);
  4073. }
  4074. void setViewMode(ViewId _id, ViewMode::Enum _mode)
  4075. {
  4076. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4077. s_ctx->setViewMode(_id, _mode);
  4078. }
  4079. void setViewFrameBuffer(ViewId _id, FrameBufferHandle _handle)
  4080. {
  4081. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4082. s_ctx->setViewFrameBuffer(_id, _handle);
  4083. }
  4084. void setViewTransform(ViewId _id, const void* _view, const void* _proj)
  4085. {
  4086. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4087. s_ctx->setViewTransform(_id, _view, _proj);
  4088. }
  4089. void setViewOrder(ViewId _id, uint16_t _num, const ViewId* _order)
  4090. {
  4091. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4092. s_ctx->setViewOrder(_id, _num, _order);
  4093. }
  4094. void resetView(ViewId _id)
  4095. {
  4096. BX_ASSERT(checkView(_id), "Invalid view id: %d", _id);
  4097. s_ctx->resetView(_id);
  4098. }
  4099. void setMarker(const char* _marker)
  4100. {
  4101. BGFX_CHECK_API_THREAD();
  4102. s_ctx->m_encoder0->setMarker(_marker);
  4103. }
  4104. void setState(uint64_t _state, uint32_t _rgba)
  4105. {
  4106. BGFX_CHECK_API_THREAD();
  4107. s_ctx->m_encoder0->setState(_state, _rgba);
  4108. }
  4109. void setCondition(OcclusionQueryHandle _handle, bool _visible)
  4110. {
  4111. BGFX_CHECK_API_THREAD();
  4112. s_ctx->m_encoder0->setCondition(_handle, _visible);
  4113. }
  4114. void setStencil(uint32_t _fstencil, uint32_t _bstencil)
  4115. {
  4116. BGFX_CHECK_API_THREAD();
  4117. s_ctx->m_encoder0->setStencil(_fstencil, _bstencil);
  4118. }
  4119. uint16_t setScissor(uint16_t _x, uint16_t _y, uint16_t _width, uint16_t _height)
  4120. {
  4121. BGFX_CHECK_API_THREAD();
  4122. return s_ctx->m_encoder0->setScissor(_x, _y, _width, _height);
  4123. }
  4124. void setScissor(uint16_t _cache)
  4125. {
  4126. BGFX_CHECK_API_THREAD();
  4127. s_ctx->m_encoder0->setScissor(_cache);
  4128. }
  4129. uint32_t setTransform(const void* _mtx, uint16_t _num)
  4130. {
  4131. BGFX_CHECK_API_THREAD();
  4132. return s_ctx->m_encoder0->setTransform(_mtx, _num);
  4133. }
  4134. uint32_t allocTransform(Transform* _transform, uint16_t _num)
  4135. {
  4136. BGFX_CHECK_API_THREAD();
  4137. return s_ctx->m_encoder0->allocTransform(_transform, _num);
  4138. }
  4139. void setTransform(uint32_t _cache, uint16_t _num)
  4140. {
  4141. BGFX_CHECK_API_THREAD();
  4142. s_ctx->m_encoder0->setTransform(_cache, _num);
  4143. }
  4144. void setUniform(UniformHandle _handle, const void* _value, uint16_t _num)
  4145. {
  4146. BGFX_CHECK_API_THREAD();
  4147. s_ctx->m_encoder0->setUniform(_handle, _value, _num);
  4148. }
  4149. void setIndexBuffer(IndexBufferHandle _handle)
  4150. {
  4151. setIndexBuffer(_handle, 0, UINT32_MAX);
  4152. }
  4153. void setIndexBuffer(IndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  4154. {
  4155. BGFX_CHECK_API_THREAD();
  4156. s_ctx->m_encoder0->setIndexBuffer(_handle, _firstIndex, _numIndices);
  4157. }
  4158. void setIndexBuffer(DynamicIndexBufferHandle _handle)
  4159. {
  4160. setIndexBuffer(_handle, 0, UINT32_MAX);
  4161. }
  4162. void setIndexBuffer(DynamicIndexBufferHandle _handle, uint32_t _firstIndex, uint32_t _numIndices)
  4163. {
  4164. BGFX_CHECK_API_THREAD();
  4165. s_ctx->m_encoder0->setIndexBuffer(_handle, _firstIndex, _numIndices);
  4166. }
  4167. void setIndexBuffer(const TransientIndexBuffer* _tib)
  4168. {
  4169. setIndexBuffer(_tib, 0, UINT32_MAX);
  4170. }
  4171. void setIndexBuffer(const TransientIndexBuffer* _tib, uint32_t _firstIndex, uint32_t _numIndices)
  4172. {
  4173. BGFX_CHECK_API_THREAD();
  4174. s_ctx->m_encoder0->setIndexBuffer(_tib, _firstIndex, _numIndices);
  4175. }
  4176. void setVertexBuffer(
  4177. uint8_t _stream
  4178. , VertexBufferHandle _handle
  4179. , uint32_t _startVertex
  4180. , uint32_t _numVertices
  4181. , VertexLayoutHandle _layoutHandle
  4182. )
  4183. {
  4184. BGFX_CHECK_API_THREAD();
  4185. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle, _startVertex, _numVertices, _layoutHandle);
  4186. }
  4187. void setVertexBuffer(uint8_t _stream, VertexBufferHandle _handle)
  4188. {
  4189. setVertexBuffer(_stream, _handle, 0, UINT32_MAX);
  4190. }
  4191. void setVertexBuffer(
  4192. uint8_t _stream
  4193. , DynamicVertexBufferHandle _handle
  4194. , uint32_t _startVertex
  4195. , uint32_t _numVertices
  4196. , VertexLayoutHandle _layoutHandle
  4197. )
  4198. {
  4199. BGFX_CHECK_API_THREAD();
  4200. s_ctx->m_encoder0->setVertexBuffer(_stream, _handle, _startVertex, _numVertices, _layoutHandle);
  4201. }
  4202. void setVertexBuffer(uint8_t _stream, DynamicVertexBufferHandle _handle)
  4203. {
  4204. setVertexBuffer(_stream, _handle, 0, UINT32_MAX);
  4205. }
  4206. void setVertexBuffer(
  4207. uint8_t _stream
  4208. , const TransientVertexBuffer* _tvb
  4209. , uint32_t _startVertex
  4210. , uint32_t _numVertices
  4211. , VertexLayoutHandle _layoutHandle
  4212. )
  4213. {
  4214. BGFX_CHECK_API_THREAD();
  4215. s_ctx->m_encoder0->setVertexBuffer(_stream, _tvb, _startVertex, _numVertices, _layoutHandle);
  4216. }
  4217. void setVertexBuffer(uint8_t _stream, const TransientVertexBuffer* _tvb)
  4218. {
  4219. setVertexBuffer(_stream, _tvb, 0, UINT32_MAX);
  4220. }
  4221. void setVertexCount(uint32_t _numVertices)
  4222. {
  4223. BGFX_CHECK_API_THREAD();
  4224. s_ctx->m_encoder0->setVertexCount(_numVertices);
  4225. }
  4226. void setInstanceDataBuffer(const InstanceDataBuffer* _idb)
  4227. {
  4228. BGFX_CHECK_API_THREAD();
  4229. s_ctx->m_encoder0->setInstanceDataBuffer(_idb);
  4230. }
  4231. void setInstanceDataBuffer(const InstanceDataBuffer* _idb, uint32_t _start, uint32_t _num)
  4232. {
  4233. BGFX_CHECK_API_THREAD();
  4234. s_ctx->m_encoder0->setInstanceDataBuffer(_idb, _start, _num);
  4235. }
  4236. void setInstanceDataBuffer(VertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  4237. {
  4238. BGFX_CHECK_API_THREAD();
  4239. s_ctx->m_encoder0->setInstanceDataBuffer(_handle, _startVertex, _num);
  4240. }
  4241. void setInstanceDataBuffer(DynamicVertexBufferHandle _handle, uint32_t _startVertex, uint32_t _num)
  4242. {
  4243. BGFX_CHECK_API_THREAD();
  4244. s_ctx->m_encoder0->setInstanceDataBuffer(_handle, _startVertex, _num);
  4245. }
  4246. void setInstanceCount(uint32_t _numInstances)
  4247. {
  4248. BGFX_CHECK_API_THREAD();
  4249. s_ctx->m_encoder0->setInstanceCount(_numInstances);
  4250. }
  4251. void setTexture(uint8_t _stage, UniformHandle _sampler, TextureHandle _handle, uint32_t _flags)
  4252. {
  4253. BGFX_CHECK_API_THREAD();
  4254. s_ctx->m_encoder0->setTexture(_stage, _sampler, _handle, _flags);
  4255. }
  4256. void touch(ViewId _id)
  4257. {
  4258. ProgramHandle handle = BGFX_INVALID_HANDLE;
  4259. submit(_id, handle);
  4260. }
  4261. void submit(ViewId _id, ProgramHandle _program, uint32_t _depth, uint8_t _flags)
  4262. {
  4263. OcclusionQueryHandle handle = BGFX_INVALID_HANDLE;
  4264. submit(_id, _program, handle, _depth, _flags);
  4265. }
  4266. void submit(ViewId _id, ProgramHandle _program, OcclusionQueryHandle _occlusionQuery, uint32_t _depth, uint8_t _flags)
  4267. {
  4268. BGFX_CHECK_API_THREAD();
  4269. s_ctx->m_encoder0->submit(_id, _program, _occlusionQuery, _depth, _flags);
  4270. }
  4271. void submit(ViewId _id, ProgramHandle _program, IndirectBufferHandle _indirectHandle, uint16_t _start, uint16_t _num, uint32_t _depth, uint8_t _flags)
  4272. {
  4273. BGFX_CHECK_API_THREAD();
  4274. s_ctx->m_encoder0->submit(_id, _program, _indirectHandle, _start, _num, _depth, _flags);
  4275. }
  4276. void setBuffer(uint8_t _stage, IndexBufferHandle _handle, Access::Enum _access)
  4277. {
  4278. BGFX_CHECK_API_THREAD();
  4279. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4280. }
  4281. void setBuffer(uint8_t _stage, VertexBufferHandle _handle, Access::Enum _access)
  4282. {
  4283. BGFX_CHECK_API_THREAD();
  4284. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4285. }
  4286. void setBuffer(uint8_t _stage, DynamicIndexBufferHandle _handle, Access::Enum _access)
  4287. {
  4288. BGFX_CHECK_API_THREAD();
  4289. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4290. }
  4291. void setBuffer(uint8_t _stage, DynamicVertexBufferHandle _handle, Access::Enum _access)
  4292. {
  4293. BGFX_CHECK_API_THREAD();
  4294. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4295. }
  4296. void setBuffer(uint8_t _stage, IndirectBufferHandle _handle, Access::Enum _access)
  4297. {
  4298. BGFX_CHECK_API_THREAD();
  4299. s_ctx->m_encoder0->setBuffer(_stage, _handle, _access);
  4300. }
  4301. void setImage(uint8_t _stage, TextureHandle _handle, uint8_t _mip, Access::Enum _access, TextureFormat::Enum _format)
  4302. {
  4303. BGFX_CHECK_API_THREAD();
  4304. s_ctx->m_encoder0->setImage(_stage, _handle, _mip, _access, _format);
  4305. }
  4306. void dispatch(ViewId _id, ProgramHandle _handle, uint32_t _numX, uint32_t _numY, uint32_t _numZ, uint8_t _flags)
  4307. {
  4308. BGFX_CHECK_API_THREAD();
  4309. s_ctx->m_encoder0->dispatch(_id, _handle, _numX, _numY, _numZ, _flags);
  4310. }
  4311. void dispatch(ViewId _id, ProgramHandle _handle, IndirectBufferHandle _indirectHandle, uint16_t _start, uint16_t _num, uint8_t _flags)
  4312. {
  4313. BGFX_CHECK_API_THREAD();
  4314. s_ctx->m_encoder0->dispatch(_id, _handle, _indirectHandle, _start, _num, _flags);
  4315. }
  4316. void discard(uint8_t _flags)
  4317. {
  4318. BGFX_CHECK_API_THREAD();
  4319. s_ctx->m_encoder0->discard(_flags);
  4320. }
  4321. 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)
  4322. {
  4323. blit(_id, _dst, 0, _dstX, _dstY, 0, _src, 0, _srcX, _srcY, 0, _width, _height, 0);
  4324. }
  4325. 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)
  4326. {
  4327. BGFX_CHECK_API_THREAD();
  4328. s_ctx->m_encoder0->blit(_id, _dst, _dstMip, _dstX, _dstY, _dstZ, _src, _srcMip, _srcX, _srcY, _srcZ, _width, _height, _depth);
  4329. }
  4330. void requestScreenShot(FrameBufferHandle _handle, const char* _filePath)
  4331. {
  4332. BGFX_CHECK_API_THREAD();
  4333. s_ctx->requestScreenShot(_handle, _filePath);
  4334. }
  4335. } // namespace bgfx
  4336. #if BGFX_CONFIG_PREFER_DISCRETE_GPU
  4337. extern "C"
  4338. {
  4339. // When laptop setup has integrated and discrete GPU, following driver workarounds will
  4340. // select discrete GPU:
  4341. // Reference(s):
  4342. // - https://web.archive.org/web/20180722051003/https://docs.nvidia.com/gameworks/content/technologies/desktop/optimus.htm
  4343. //
  4344. __declspec(dllexport) uint32_t NvOptimusEnablement = UINT32_C(1);
  4345. // Reference(s):
  4346. // - https://web.archive.org/web/20180722051032/https://gpuopen.com/amdpowerxpressrequesthighperformance/
  4347. //
  4348. __declspec(dllexport) uint32_t AmdPowerXpressRequestHighPerformance = UINT32_C(1);
  4349. }
  4350. #endif // BGFX_CONFIG_PREFER_DISCRETE_GPU
  4351. #define BGFX_TEXTURE_FORMAT_BIMG(_fmt) \
  4352. BX_STATIC_ASSERT(uint32_t(bgfx::TextureFormat::_fmt) == uint32_t(bimg::TextureFormat::_fmt) )
  4353. BGFX_TEXTURE_FORMAT_BIMG(BC1);
  4354. BGFX_TEXTURE_FORMAT_BIMG(BC2);
  4355. BGFX_TEXTURE_FORMAT_BIMG(BC3);
  4356. BGFX_TEXTURE_FORMAT_BIMG(BC4);
  4357. BGFX_TEXTURE_FORMAT_BIMG(BC5);
  4358. BGFX_TEXTURE_FORMAT_BIMG(BC6H);
  4359. BGFX_TEXTURE_FORMAT_BIMG(BC7);
  4360. BGFX_TEXTURE_FORMAT_BIMG(ETC1);
  4361. BGFX_TEXTURE_FORMAT_BIMG(ETC2);
  4362. BGFX_TEXTURE_FORMAT_BIMG(ETC2A);
  4363. BGFX_TEXTURE_FORMAT_BIMG(ETC2A1);
  4364. BGFX_TEXTURE_FORMAT_BIMG(PTC12);
  4365. BGFX_TEXTURE_FORMAT_BIMG(PTC14);
  4366. BGFX_TEXTURE_FORMAT_BIMG(PTC12A);
  4367. BGFX_TEXTURE_FORMAT_BIMG(PTC14A);
  4368. BGFX_TEXTURE_FORMAT_BIMG(PTC22);
  4369. BGFX_TEXTURE_FORMAT_BIMG(PTC24);
  4370. BGFX_TEXTURE_FORMAT_BIMG(ATC);
  4371. BGFX_TEXTURE_FORMAT_BIMG(ATCE);
  4372. BGFX_TEXTURE_FORMAT_BIMG(ATCI);
  4373. BGFX_TEXTURE_FORMAT_BIMG(ASTC4x4);
  4374. BGFX_TEXTURE_FORMAT_BIMG(ASTC5x5);
  4375. BGFX_TEXTURE_FORMAT_BIMG(ASTC6x6);
  4376. BGFX_TEXTURE_FORMAT_BIMG(ASTC8x5);
  4377. BGFX_TEXTURE_FORMAT_BIMG(ASTC8x6);
  4378. BGFX_TEXTURE_FORMAT_BIMG(ASTC10x5);
  4379. BGFX_TEXTURE_FORMAT_BIMG(Unknown);
  4380. BGFX_TEXTURE_FORMAT_BIMG(R1);
  4381. BGFX_TEXTURE_FORMAT_BIMG(A8);
  4382. BGFX_TEXTURE_FORMAT_BIMG(R8);
  4383. BGFX_TEXTURE_FORMAT_BIMG(R8I);
  4384. BGFX_TEXTURE_FORMAT_BIMG(R8U);
  4385. BGFX_TEXTURE_FORMAT_BIMG(R8S);
  4386. BGFX_TEXTURE_FORMAT_BIMG(R16);
  4387. BGFX_TEXTURE_FORMAT_BIMG(R16I);
  4388. BGFX_TEXTURE_FORMAT_BIMG(R16U);
  4389. BGFX_TEXTURE_FORMAT_BIMG(R16F);
  4390. BGFX_TEXTURE_FORMAT_BIMG(R16S);
  4391. BGFX_TEXTURE_FORMAT_BIMG(R32I);
  4392. BGFX_TEXTURE_FORMAT_BIMG(R32U);
  4393. BGFX_TEXTURE_FORMAT_BIMG(R32F);
  4394. BGFX_TEXTURE_FORMAT_BIMG(RG8);
  4395. BGFX_TEXTURE_FORMAT_BIMG(RG8I);
  4396. BGFX_TEXTURE_FORMAT_BIMG(RG8U);
  4397. BGFX_TEXTURE_FORMAT_BIMG(RG8S);
  4398. BGFX_TEXTURE_FORMAT_BIMG(RG16);
  4399. BGFX_TEXTURE_FORMAT_BIMG(RG16I);
  4400. BGFX_TEXTURE_FORMAT_BIMG(RG16U);
  4401. BGFX_TEXTURE_FORMAT_BIMG(RG16F);
  4402. BGFX_TEXTURE_FORMAT_BIMG(RG16S);
  4403. BGFX_TEXTURE_FORMAT_BIMG(RG32I);
  4404. BGFX_TEXTURE_FORMAT_BIMG(RG32U);
  4405. BGFX_TEXTURE_FORMAT_BIMG(RG32F);
  4406. BGFX_TEXTURE_FORMAT_BIMG(RGB8);
  4407. BGFX_TEXTURE_FORMAT_BIMG(RGB8I);
  4408. BGFX_TEXTURE_FORMAT_BIMG(RGB8U);
  4409. BGFX_TEXTURE_FORMAT_BIMG(RGB8S);
  4410. BGFX_TEXTURE_FORMAT_BIMG(RGB9E5F);
  4411. BGFX_TEXTURE_FORMAT_BIMG(BGRA8);
  4412. BGFX_TEXTURE_FORMAT_BIMG(RGBA8);
  4413. BGFX_TEXTURE_FORMAT_BIMG(RGBA8I);
  4414. BGFX_TEXTURE_FORMAT_BIMG(RGBA8U);
  4415. BGFX_TEXTURE_FORMAT_BIMG(RGBA8S);
  4416. BGFX_TEXTURE_FORMAT_BIMG(RGBA16);
  4417. BGFX_TEXTURE_FORMAT_BIMG(RGBA16I);
  4418. BGFX_TEXTURE_FORMAT_BIMG(RGBA16U);
  4419. BGFX_TEXTURE_FORMAT_BIMG(RGBA16F);
  4420. BGFX_TEXTURE_FORMAT_BIMG(RGBA16S);
  4421. BGFX_TEXTURE_FORMAT_BIMG(RGBA32I);
  4422. BGFX_TEXTURE_FORMAT_BIMG(RGBA32U);
  4423. BGFX_TEXTURE_FORMAT_BIMG(RGBA32F);
  4424. BGFX_TEXTURE_FORMAT_BIMG(R5G6B5);
  4425. BGFX_TEXTURE_FORMAT_BIMG(RGBA4);
  4426. BGFX_TEXTURE_FORMAT_BIMG(RGB5A1);
  4427. BGFX_TEXTURE_FORMAT_BIMG(RGB10A2);
  4428. BGFX_TEXTURE_FORMAT_BIMG(RG11B10F);
  4429. BGFX_TEXTURE_FORMAT_BIMG(UnknownDepth);
  4430. BGFX_TEXTURE_FORMAT_BIMG(D16);
  4431. BGFX_TEXTURE_FORMAT_BIMG(D24);
  4432. BGFX_TEXTURE_FORMAT_BIMG(D24S8);
  4433. BGFX_TEXTURE_FORMAT_BIMG(D32);
  4434. BGFX_TEXTURE_FORMAT_BIMG(D16F);
  4435. BGFX_TEXTURE_FORMAT_BIMG(D24F);
  4436. BGFX_TEXTURE_FORMAT_BIMG(D32F);
  4437. BGFX_TEXTURE_FORMAT_BIMG(D0S8);
  4438. BGFX_TEXTURE_FORMAT_BIMG(Count);
  4439. #undef BGFX_TEXTURE_FORMAT_BIMG
  4440. #include <bgfx/c99/bgfx.h>
  4441. #define FLAGS_MASK_TEST(_flags, _mask) ( (_flags) == ( (_flags) & (_mask) ) )
  4442. BX_STATIC_ASSERT(FLAGS_MASK_TEST(0
  4443. | BGFX_SAMPLER_INTERNAL_DEFAULT
  4444. | BGFX_SAMPLER_INTERNAL_SHARED
  4445. , BGFX_SAMPLER_RESERVED_MASK
  4446. ) );
  4447. BX_STATIC_ASSERT(FLAGS_MASK_TEST(0
  4448. | BGFX_RESET_INTERNAL_FORCE
  4449. , BGFX_RESET_RESERVED_MASK
  4450. ) );
  4451. BX_STATIC_ASSERT(FLAGS_MASK_TEST(0
  4452. | BGFX_STATE_INTERNAL_SCISSOR
  4453. | BGFX_STATE_INTERNAL_OCCLUSION_QUERY
  4454. , BGFX_STATE_RESERVED_MASK
  4455. ) );
  4456. BX_STATIC_ASSERT(FLAGS_MASK_TEST(0
  4457. | BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE
  4458. , BGFX_SUBMIT_INTERNAL_RESERVED_MASK
  4459. ) );
  4460. BX_STATIC_ASSERT( (0
  4461. | BGFX_STATE_ALPHA_REF_MASK
  4462. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  4463. | BGFX_STATE_BLEND_EQUATION_MASK
  4464. | BGFX_STATE_BLEND_INDEPENDENT
  4465. | BGFX_STATE_BLEND_MASK
  4466. | BGFX_STATE_CONSERVATIVE_RASTER
  4467. | BGFX_STATE_CULL_MASK
  4468. | BGFX_STATE_DEPTH_TEST_MASK
  4469. | BGFX_STATE_FRONT_CCW
  4470. | BGFX_STATE_LINEAA
  4471. | BGFX_STATE_MSAA
  4472. | BGFX_STATE_POINT_SIZE_MASK
  4473. | BGFX_STATE_PT_MASK
  4474. | BGFX_STATE_RESERVED_MASK
  4475. | BGFX_STATE_WRITE_MASK
  4476. ) == (0
  4477. ^ BGFX_STATE_ALPHA_REF_MASK
  4478. ^ BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  4479. ^ BGFX_STATE_BLEND_EQUATION_MASK
  4480. ^ BGFX_STATE_BLEND_INDEPENDENT
  4481. ^ BGFX_STATE_BLEND_MASK
  4482. ^ BGFX_STATE_CONSERVATIVE_RASTER
  4483. ^ BGFX_STATE_CULL_MASK
  4484. ^ BGFX_STATE_DEPTH_TEST_MASK
  4485. ^ BGFX_STATE_FRONT_CCW
  4486. ^ BGFX_STATE_LINEAA
  4487. ^ BGFX_STATE_MSAA
  4488. ^ BGFX_STATE_POINT_SIZE_MASK
  4489. ^ BGFX_STATE_PT_MASK
  4490. ^ BGFX_STATE_RESERVED_MASK
  4491. ^ BGFX_STATE_WRITE_MASK
  4492. ) );
  4493. BX_STATIC_ASSERT(FLAGS_MASK_TEST(BGFX_CAPS_TEXTURE_COMPARE_LEQUAL, BGFX_CAPS_TEXTURE_COMPARE_ALL) );
  4494. BX_STATIC_ASSERT( (0
  4495. | BGFX_CAPS_ALPHA_TO_COVERAGE
  4496. | BGFX_CAPS_BLEND_INDEPENDENT
  4497. | BGFX_CAPS_COMPUTE
  4498. | BGFX_CAPS_CONSERVATIVE_RASTER
  4499. | BGFX_CAPS_DRAW_INDIRECT
  4500. | BGFX_CAPS_FRAGMENT_DEPTH
  4501. | BGFX_CAPS_FRAGMENT_ORDERING
  4502. | BGFX_CAPS_GRAPHICS_DEBUGGER
  4503. | BGFX_CAPS_HDR10
  4504. | BGFX_CAPS_HIDPI
  4505. | BGFX_CAPS_INDEX32
  4506. | BGFX_CAPS_INSTANCING
  4507. | BGFX_CAPS_OCCLUSION_QUERY
  4508. | BGFX_CAPS_RENDERER_MULTITHREADED
  4509. | BGFX_CAPS_SWAP_CHAIN
  4510. | BGFX_CAPS_TEXTURE_2D_ARRAY
  4511. | BGFX_CAPS_TEXTURE_3D
  4512. | BGFX_CAPS_TEXTURE_BLIT
  4513. | BGFX_CAPS_TEXTURE_CUBE_ARRAY
  4514. | BGFX_CAPS_TEXTURE_DIRECT_ACCESS
  4515. | BGFX_CAPS_TEXTURE_READ_BACK
  4516. | BGFX_CAPS_VERTEX_ATTRIB_HALF
  4517. | BGFX_CAPS_VERTEX_ATTRIB_UINT10
  4518. | BGFX_CAPS_VERTEX_ID
  4519. ) == (0
  4520. ^ BGFX_CAPS_ALPHA_TO_COVERAGE
  4521. ^ BGFX_CAPS_BLEND_INDEPENDENT
  4522. ^ BGFX_CAPS_COMPUTE
  4523. ^ BGFX_CAPS_CONSERVATIVE_RASTER
  4524. ^ BGFX_CAPS_DRAW_INDIRECT
  4525. ^ BGFX_CAPS_FRAGMENT_DEPTH
  4526. ^ BGFX_CAPS_FRAGMENT_ORDERING
  4527. ^ BGFX_CAPS_GRAPHICS_DEBUGGER
  4528. ^ BGFX_CAPS_HDR10
  4529. ^ BGFX_CAPS_HIDPI
  4530. ^ BGFX_CAPS_INDEX32
  4531. ^ BGFX_CAPS_INSTANCING
  4532. ^ BGFX_CAPS_OCCLUSION_QUERY
  4533. ^ BGFX_CAPS_RENDERER_MULTITHREADED
  4534. ^ BGFX_CAPS_SWAP_CHAIN
  4535. ^ BGFX_CAPS_TEXTURE_2D_ARRAY
  4536. ^ BGFX_CAPS_TEXTURE_3D
  4537. ^ BGFX_CAPS_TEXTURE_BLIT
  4538. ^ BGFX_CAPS_TEXTURE_CUBE_ARRAY
  4539. ^ BGFX_CAPS_TEXTURE_DIRECT_ACCESS
  4540. ^ BGFX_CAPS_TEXTURE_READ_BACK
  4541. ^ BGFX_CAPS_VERTEX_ATTRIB_HALF
  4542. ^ BGFX_CAPS_VERTEX_ATTRIB_UINT10
  4543. ^ BGFX_CAPS_VERTEX_ID
  4544. ) );
  4545. #undef FLAGS_MASK_TEST
  4546. namespace bgfx
  4547. {
  4548. struct CallbackC99 : public CallbackI
  4549. {
  4550. virtual ~CallbackC99()
  4551. {
  4552. }
  4553. virtual void fatal(const char* _filePath, uint16_t _line, Fatal::Enum _code, const char* _str) override
  4554. {
  4555. m_interface->vtbl->fatal(m_interface, _filePath, _line, (bgfx_fatal_t)_code, _str);
  4556. }
  4557. virtual void traceVargs(const char* _filePath, uint16_t _line, const char* _format, va_list _argList) override
  4558. {
  4559. m_interface->vtbl->trace_vargs(m_interface, _filePath, _line, _format, _argList);
  4560. }
  4561. virtual void profilerBegin(const char* _name, uint32_t _abgr, const char* _filePath, uint16_t _line) override
  4562. {
  4563. m_interface->vtbl->profiler_begin(m_interface, _name, _abgr, _filePath, _line);
  4564. }
  4565. virtual void profilerBeginLiteral(const char* _name, uint32_t _abgr, const char* _filePath, uint16_t _line) override
  4566. {
  4567. m_interface->vtbl->profiler_begin_literal(m_interface, _name, _abgr, _filePath, _line);
  4568. }
  4569. virtual void profilerEnd() override
  4570. {
  4571. m_interface->vtbl->profiler_end(m_interface);
  4572. }
  4573. virtual uint32_t cacheReadSize(uint64_t _id) override
  4574. {
  4575. return m_interface->vtbl->cache_read_size(m_interface, _id);
  4576. }
  4577. virtual bool cacheRead(uint64_t _id, void* _data, uint32_t _size) override
  4578. {
  4579. return m_interface->vtbl->cache_read(m_interface, _id, _data, _size);
  4580. }
  4581. virtual void cacheWrite(uint64_t _id, const void* _data, uint32_t _size) override
  4582. {
  4583. m_interface->vtbl->cache_write(m_interface, _id, _data, _size);
  4584. }
  4585. virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t _size, bool _yflip) override
  4586. {
  4587. m_interface->vtbl->screen_shot(m_interface, _filePath, _width, _height, _pitch, _data, _size, _yflip);
  4588. }
  4589. virtual void captureBegin(uint32_t _width, uint32_t _height, uint32_t _pitch, TextureFormat::Enum _format, bool _yflip) override
  4590. {
  4591. m_interface->vtbl->capture_begin(m_interface, _width, _height, _pitch, (bgfx_texture_format_t)_format, _yflip);
  4592. }
  4593. virtual void captureEnd() override
  4594. {
  4595. m_interface->vtbl->capture_end(m_interface);
  4596. }
  4597. virtual void captureFrame(const void* _data, uint32_t _size) override
  4598. {
  4599. m_interface->vtbl->capture_frame(m_interface, _data, _size);
  4600. }
  4601. bgfx_callback_interface_t* m_interface;
  4602. };
  4603. class AllocatorC99 : public bx::AllocatorI
  4604. {
  4605. public:
  4606. virtual ~AllocatorC99()
  4607. {
  4608. }
  4609. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line) override
  4610. {
  4611. return m_interface->vtbl->realloc(m_interface, _ptr, _size, _align, _file, _line);
  4612. }
  4613. bgfx_allocator_interface_t* m_interface;
  4614. };
  4615. } // namespace bgfx
  4616. #include "bgfx.idl.inl"