bgfx.cpp 154 KB

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