bgfx.cpp 170 KB

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