renderer_gl.cpp 210 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819
  1. /*
  2. * Copyright 2011-2016 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "bgfx_p.h"
  6. #if (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)
  7. # include "renderer_gl.h"
  8. # include <bx/timer.h>
  9. # include <bx/uint32_t.h>
  10. #if BGFX_CONFIG_PROFILER_REMOTERY
  11. # define BGFX_GPU_PROFILER_BIND() rmt_BindOpenGL()
  12. # define BGFX_GPU_PROFILER_UNBIND() rmt_UnbindOpenGL()
  13. # define BGFX_GPU_PROFILER_BEGIN(_group, _name, _color) rmt_BeginOpenGLSample(_group##_##_name)
  14. # define BGFX_GPU_PROFILER_BEGIN_DYNAMIC(_namestr) rmt_BeginOpenGLSampleDynamic(_namestr)
  15. # define BGFX_GPU_PROFILER_END() rmt_EndOpenGLSample()
  16. #else
  17. # define BGFX_GPU_PROFILER_BIND() BX_NOOP()
  18. # define BGFX_GPU_PROFILER_UNBIND() BX_NOOP()
  19. # define BGFX_GPU_PROFILER_BEGIN(_group, _name, _color) BX_NOOP()
  20. # define BGFX_GPU_PROFILER_BEGIN_DYNAMIC(_namestr) BX_NOOP()
  21. # define BGFX_GPU_PROFILER_END() BX_NOOP()
  22. #endif // BGFX_CONFIG_PROFILER_REMOTERY
  23. namespace bgfx { namespace gl
  24. {
  25. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  26. struct PrimInfo
  27. {
  28. GLenum m_type;
  29. uint32_t m_min;
  30. uint32_t m_div;
  31. uint32_t m_sub;
  32. };
  33. static const PrimInfo s_primInfo[] =
  34. {
  35. { GL_TRIANGLES, 3, 3, 0 },
  36. { GL_TRIANGLE_STRIP, 3, 1, 2 },
  37. { GL_LINES, 2, 2, 0 },
  38. { GL_LINE_STRIP, 2, 1, 1 },
  39. { GL_POINTS, 1, 1, 0 },
  40. };
  41. static const char* s_primName[] =
  42. {
  43. "TriList",
  44. "TriStrip",
  45. "Line",
  46. "LineStrip",
  47. "Point",
  48. };
  49. static const char* s_attribName[] =
  50. {
  51. "a_position",
  52. "a_normal",
  53. "a_tangent",
  54. "a_bitangent",
  55. "a_color0",
  56. "a_color1",
  57. "a_indices",
  58. "a_weight",
  59. "a_texcoord0",
  60. "a_texcoord1",
  61. "a_texcoord2",
  62. "a_texcoord3",
  63. "a_texcoord4",
  64. "a_texcoord5",
  65. "a_texcoord6",
  66. "a_texcoord7",
  67. };
  68. BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attribName) );
  69. static const char* s_instanceDataName[] =
  70. {
  71. "i_data0",
  72. "i_data1",
  73. "i_data2",
  74. "i_data3",
  75. "i_data4",
  76. };
  77. BX_STATIC_ASSERT(BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT == BX_COUNTOF(s_instanceDataName) );
  78. static const GLenum s_access[] =
  79. {
  80. GL_READ_ONLY,
  81. GL_WRITE_ONLY,
  82. GL_READ_WRITE,
  83. };
  84. BX_STATIC_ASSERT(Access::Count == BX_COUNTOF(s_access) );
  85. static const GLenum s_attribType[] =
  86. {
  87. GL_UNSIGNED_BYTE, // Uint8
  88. GL_UNSIGNED_INT_10_10_10_2, // Uint10
  89. GL_SHORT, // Int16
  90. GL_HALF_FLOAT, // Half
  91. GL_FLOAT, // Float
  92. };
  93. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  94. struct Blend
  95. {
  96. GLenum m_src;
  97. GLenum m_dst;
  98. bool m_factor;
  99. };
  100. static const Blend s_blendFactor[] =
  101. {
  102. { 0, 0, false }, // ignored
  103. { GL_ZERO, GL_ZERO, false }, // ZERO
  104. { GL_ONE, GL_ONE, false }, // ONE
  105. { GL_SRC_COLOR, GL_SRC_COLOR, false }, // SRC_COLOR
  106. { GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, false }, // INV_SRC_COLOR
  107. { GL_SRC_ALPHA, GL_SRC_ALPHA, false }, // SRC_ALPHA
  108. { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, false }, // INV_SRC_ALPHA
  109. { GL_DST_ALPHA, GL_DST_ALPHA, false }, // DST_ALPHA
  110. { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, false }, // INV_DST_ALPHA
  111. { GL_DST_COLOR, GL_DST_COLOR, false }, // DST_COLOR
  112. { GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, false }, // INV_DST_COLOR
  113. { GL_SRC_ALPHA_SATURATE, GL_ONE, false }, // SRC_ALPHA_SAT
  114. { GL_CONSTANT_COLOR, GL_CONSTANT_COLOR, true }, // FACTOR
  115. { GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, true }, // INV_FACTOR
  116. };
  117. static const GLenum s_blendEquation[] =
  118. {
  119. GL_FUNC_ADD,
  120. GL_FUNC_SUBTRACT,
  121. GL_FUNC_REVERSE_SUBTRACT,
  122. GL_MIN,
  123. GL_MAX,
  124. };
  125. static const GLenum s_cmpFunc[] =
  126. {
  127. 0, // ignored
  128. GL_LESS,
  129. GL_LEQUAL,
  130. GL_EQUAL,
  131. GL_GEQUAL,
  132. GL_GREATER,
  133. GL_NOTEQUAL,
  134. GL_NEVER,
  135. GL_ALWAYS,
  136. };
  137. static const GLenum s_stencilOp[] =
  138. {
  139. GL_ZERO,
  140. GL_KEEP,
  141. GL_REPLACE,
  142. GL_INCR_WRAP,
  143. GL_INCR,
  144. GL_DECR_WRAP,
  145. GL_DECR,
  146. GL_INVERT,
  147. };
  148. static const GLenum s_stencilFace[] =
  149. {
  150. GL_FRONT_AND_BACK,
  151. GL_FRONT,
  152. GL_BACK,
  153. };
  154. static GLenum s_textureAddress[] =
  155. {
  156. GL_REPEAT,
  157. GL_MIRRORED_REPEAT,
  158. GL_CLAMP_TO_EDGE,
  159. GL_CLAMP_TO_BORDER,
  160. };
  161. static const GLenum s_textureFilterMag[] =
  162. {
  163. GL_LINEAR,
  164. GL_NEAREST,
  165. GL_LINEAR,
  166. };
  167. static const GLenum s_textureFilterMin[][3] =
  168. {
  169. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST },
  170. { GL_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_NEAREST },
  171. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST },
  172. };
  173. struct TextureFormatInfo
  174. {
  175. GLenum m_internalFmt;
  176. GLenum m_internalFmtSrgb;
  177. GLenum m_fmt;
  178. GLenum m_type;
  179. bool m_supported;
  180. };
  181. static TextureFormatInfo s_textureFormat[] =
  182. {
  183. { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, false }, // BC1
  184. { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, false }, // BC2
  185. { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, false }, // BC3
  186. { GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, false }, // BC4
  187. { GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, false }, // BC5
  188. { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, false }, // BC6H
  189. { GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, false }, // BC7
  190. { GL_ETC1_RGB8_OES, GL_ZERO, GL_ETC1_RGB8_OES, GL_ZERO, false }, // ETC1
  191. { GL_COMPRESSED_RGB8_ETC2, GL_ZERO, GL_COMPRESSED_RGB8_ETC2, GL_ZERO, false }, // ETC2
  192. { GL_COMPRESSED_RGBA8_ETC2_EAC, GL_COMPRESSED_SRGB8_ETC2, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_ZERO, false }, // ETC2A
  193. { GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_ZERO, false }, // ETC2A1
  194. { GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12
  195. { GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14
  196. { GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12A
  197. { GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14A
  198. { GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, false }, // PTC22
  199. { GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, false }, // PTC24
  200. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // Unknown
  201. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // R1
  202. { GL_ALPHA, GL_ZERO, GL_ALPHA, GL_UNSIGNED_BYTE, false }, // A8
  203. { GL_R8, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8
  204. { GL_R8I, GL_ZERO, GL_RED, GL_BYTE, false }, // R8S
  205. { GL_R8UI, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8S
  206. { GL_R8_SNORM, GL_ZERO, GL_RED, GL_BYTE, false }, // R8S
  207. { GL_R16, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16
  208. { GL_R16I, GL_ZERO, GL_RED, GL_SHORT, false }, // R16I
  209. { GL_R16UI, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16U
  210. { GL_R16F, GL_ZERO, GL_RED, GL_HALF_FLOAT, false }, // R16F
  211. { GL_R16_SNORM, GL_ZERO, GL_RED, GL_SHORT, false }, // R16S
  212. { GL_R32I, GL_ZERO, GL_RED, GL_INT, false }, // R32I
  213. { GL_R32UI, GL_ZERO, GL_RED, GL_UNSIGNED_INT, false }, // R32U
  214. { GL_R32F, GL_ZERO, GL_RED, GL_FLOAT, false }, // R32F
  215. { GL_RG8, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8
  216. { GL_RG8I, GL_ZERO, GL_RG, GL_BYTE, false }, // RG8I
  217. { GL_RG8UI, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8U
  218. { GL_RG8_SNORM, GL_ZERO, GL_RG, GL_BYTE, false }, // RG8S
  219. { GL_RG16, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16
  220. { GL_RG16I, GL_ZERO, GL_RG, GL_SHORT, false }, // RG16
  221. { GL_RG16UI, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16
  222. { GL_RG16F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG16F
  223. { GL_RG16_SNORM, GL_ZERO, GL_RG, GL_SHORT, false }, // RG16S
  224. { GL_RG32I, GL_ZERO, GL_RG, GL_INT, false }, // RG32I
  225. { GL_RG32UI, GL_ZERO, GL_RG, GL_UNSIGNED_INT, false }, // RG32U
  226. { GL_RG32F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG32F
  227. { GL_RGB8, GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, false }, // RGB8
  228. { GL_RGB8I, GL_ZERO, GL_RGB, GL_BYTE, false }, // RGB8I
  229. { GL_RGB8UI, GL_ZERO, GL_RGB, GL_UNSIGNED_BYTE, false }, // RGB8U
  230. { GL_RGB8_SNORM, GL_ZERO, GL_RGB, GL_BYTE, false }, // RGB8S
  231. { GL_RGB9_E5, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, false }, // RGB9E5F
  232. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // BGRA8
  233. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8
  234. { GL_RGBA8I, GL_ZERO, GL_RGBA, GL_BYTE, false }, // RGBA8I
  235. { GL_RGBA8UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8U
  236. { GL_RGBA8_SNORM, GL_ZERO, GL_RGBA, GL_BYTE, false }, // RGBA8S
  237. { GL_RGBA16, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT, false }, // RGBA16
  238. { GL_RGBA16I, GL_ZERO, GL_RGBA, GL_SHORT, false }, // RGBA16I
  239. { GL_RGBA16UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT, false }, // RGBA16U
  240. { GL_RGBA16F, GL_ZERO, GL_RGBA, GL_HALF_FLOAT, false }, // RGBA16F
  241. { GL_RGBA16_SNORM, GL_ZERO, GL_RGBA, GL_SHORT, false }, // RGBA16S
  242. { GL_RGBA32I, GL_ZERO, GL_RGBA, GL_INT, false }, // RGBA32I
  243. { GL_RGBA32UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT, false }, // RGBA32U
  244. { GL_RGBA32F, GL_ZERO, GL_RGBA, GL_FLOAT, false }, // RGBA32F
  245. { GL_RGB565, GL_ZERO, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, false }, // R5G6B5
  246. { GL_RGBA4, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV, false }, // RGBA4
  247. { GL_RGB5_A1, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, false }, // RGB5A1
  248. { GL_RGB10_A2, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false }, // RGB10A2
  249. { GL_R11F_G11F_B10F, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false }, // R11G11B10F
  250. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // UnknownDepth
  251. { GL_DEPTH_COMPONENT16, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, // D16
  252. { GL_DEPTH_COMPONENT24, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D24
  253. { GL_DEPTH24_STENCIL8, GL_ZERO, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false }, // D24S8
  254. { GL_DEPTH_COMPONENT32, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D32
  255. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D16F
  256. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D24F
  257. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D32F
  258. { GL_STENCIL_INDEX8, GL_ZERO, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, false }, // D0S8
  259. };
  260. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  261. static bool s_textureFilter[TextureFormat::Count+1];
  262. static GLenum s_rboFormat[] =
  263. {
  264. GL_ZERO, // BC1
  265. GL_ZERO, // BC2
  266. GL_ZERO, // BC3
  267. GL_ZERO, // BC4
  268. GL_ZERO, // BC5
  269. GL_ZERO, // BC6H
  270. GL_ZERO, // BC7
  271. GL_ZERO, // ETC1
  272. GL_ZERO, // ETC2
  273. GL_ZERO, // ETC2A
  274. GL_ZERO, // ETC2A1
  275. GL_ZERO, // PTC12
  276. GL_ZERO, // PTC14
  277. GL_ZERO, // PTC12A
  278. GL_ZERO, // PTC14A
  279. GL_ZERO, // PTC22
  280. GL_ZERO, // PTC24
  281. GL_ZERO, // Unknown
  282. GL_ZERO, // R1
  283. GL_ALPHA, // A8
  284. GL_R8, // R8
  285. GL_R8I, // R8I
  286. GL_R8UI, // R8U
  287. GL_R8_SNORM, // R8S
  288. GL_R16, // R16
  289. GL_R16I, // R16I
  290. GL_R16UI, // R16U
  291. GL_R16F, // R16F
  292. GL_R16_SNORM, // R16S
  293. GL_R32I, // R32I
  294. GL_R32UI, // R32U
  295. GL_R32F, // R32F
  296. GL_RG8, // RG8
  297. GL_RG8I, // RG8I
  298. GL_RG8UI, // RG8U
  299. GL_RG8_SNORM, // RG8S
  300. GL_RG16, // RG16
  301. GL_RG16I, // RG16I
  302. GL_RG16UI, // RG16U
  303. GL_RG16F, // RG16F
  304. GL_RG16_SNORM, // RG16S
  305. GL_RG32I, // RG32I
  306. GL_RG32UI, // RG32U
  307. GL_RG32F, // RG32F
  308. GL_RGB8, // RGB8
  309. GL_RGB8I, // RGB8I
  310. GL_RGB8UI, // RGB8UI
  311. GL_RGB8_SNORM, // RGB8S
  312. GL_RGB9_E5, // RGB9E5F
  313. GL_RGBA8, // BGRA8
  314. GL_RGBA8, // RGBA8
  315. GL_RGBA8I, // RGBA8I
  316. GL_RGBA8UI, // RGBA8UI
  317. GL_RGBA8_SNORM, // RGBA8S
  318. GL_RGBA16, // RGBA16
  319. GL_RGBA16I, // RGBA16I
  320. GL_RGBA16UI, // RGBA16U
  321. GL_RGBA16F, // RGBA16F
  322. GL_RGBA16_SNORM, // RGBA16S
  323. GL_RGBA32I, // RGBA32I
  324. GL_RGBA32UI, // RGBA32U
  325. GL_RGBA32F, // RGBA32F
  326. GL_RGB565, // R5G6B5
  327. GL_RGBA4, // RGBA4
  328. GL_RGB5_A1, // RGB5A1
  329. GL_RGB10_A2, // RGB10A2
  330. GL_R11F_G11F_B10F, // R11G11B10F
  331. GL_ZERO, // UnknownDepth
  332. GL_DEPTH_COMPONENT16, // D16
  333. GL_DEPTH_COMPONENT24, // D24
  334. GL_DEPTH24_STENCIL8, // D24S8
  335. GL_DEPTH_COMPONENT32, // D32
  336. GL_DEPTH_COMPONENT32F, // D16F
  337. GL_DEPTH_COMPONENT32F, // D24F
  338. GL_DEPTH_COMPONENT32F, // D32F
  339. GL_STENCIL_INDEX8, // D0S8
  340. };
  341. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_rboFormat) );
  342. static GLenum s_imageFormat[] =
  343. {
  344. GL_ZERO, // BC1
  345. GL_ZERO, // BC2
  346. GL_ZERO, // BC3
  347. GL_ZERO, // BC4
  348. GL_ZERO, // BC5
  349. GL_ZERO, // BC6H
  350. GL_ZERO, // BC7
  351. GL_ZERO, // ETC1
  352. GL_ZERO, // ETC2
  353. GL_ZERO, // ETC2A
  354. GL_ZERO, // ETC2A1
  355. GL_ZERO, // PTC12
  356. GL_ZERO, // PTC14
  357. GL_ZERO, // PTC12A
  358. GL_ZERO, // PTC14A
  359. GL_ZERO, // PTC22
  360. GL_ZERO, // PTC24
  361. GL_ZERO, // Unknown
  362. GL_ZERO, // R1
  363. GL_ALPHA, // A8
  364. GL_R8, // R8
  365. GL_R8I, // R8I
  366. GL_R8UI, // R8UI
  367. GL_R8_SNORM, // R8S
  368. GL_R16, // R16
  369. GL_R16I, // R16I
  370. GL_R16UI, // R16U
  371. GL_R16F, // R16F
  372. GL_R16_SNORM, // R16S
  373. GL_R32I, // R32I
  374. GL_R32UI, // R32U
  375. GL_R32F, // R32F
  376. GL_RG8, // RG8
  377. GL_RG8I, // RG8I
  378. GL_RG8UI, // RG8U
  379. GL_RG8_SNORM, // RG8S
  380. GL_RG16, // RG16
  381. GL_RG16I, // RG16I
  382. GL_RG16UI, // RG16U
  383. GL_RG16F, // RG16F
  384. GL_RG16_SNORM, // RG16S
  385. GL_RG32I, // RG32I
  386. GL_RG32UI, // RG32U
  387. GL_RG32F, // RG32F
  388. GL_RGB8, // RGB8
  389. GL_RGB8I, // RGB8I
  390. GL_RGB8UI, // RGB8UI
  391. GL_RGB8_SNORM, // RGB8S
  392. GL_RGB9_E5, // RGB9E5F
  393. GL_RGBA8, // BGRA8
  394. GL_RGBA8, // RGBA8
  395. GL_RGBA8I, // RGBA8I
  396. GL_RGBA8UI, // RGBA8UI
  397. GL_RGBA8_SNORM, // RGBA8S
  398. GL_RGBA16, // RGBA16
  399. GL_RGBA16I, // RGBA16I
  400. GL_RGBA16UI, // RGBA16U
  401. GL_RGBA16F, // RGBA16F
  402. GL_RGBA16_SNORM, // RGBA16S
  403. GL_RGBA32I, // RGBA32I
  404. GL_RGBA32UI, // RGBA32U
  405. GL_RGBA32F, // RGBA32F
  406. GL_RGB565, // R5G6B5
  407. GL_RGBA4, // RGBA4
  408. GL_RGB5_A1, // RGB5A1
  409. GL_RGB10_A2, // RGB10A2
  410. GL_R11F_G11F_B10F, // R11G11B10F
  411. GL_ZERO, // UnknownDepth
  412. GL_ZERO, // D16
  413. GL_ZERO, // D24
  414. GL_ZERO, // D24S8
  415. GL_ZERO, // D32
  416. GL_ZERO, // D16F
  417. GL_ZERO, // D24F
  418. GL_ZERO, // D32F
  419. GL_ZERO, // D0S8
  420. };
  421. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_imageFormat) );
  422. struct Extension
  423. {
  424. enum Enum
  425. {
  426. AMD_conservative_depth,
  427. AMD_multi_draw_indirect,
  428. ANGLE_depth_texture,
  429. ANGLE_framebuffer_blit,
  430. ANGLE_framebuffer_multisample,
  431. ANGLE_instanced_arrays,
  432. ANGLE_texture_compression_dxt1,
  433. ANGLE_texture_compression_dxt3,
  434. ANGLE_texture_compression_dxt5,
  435. ANGLE_timer_query,
  436. ANGLE_translated_shader_source,
  437. APPLE_texture_format_BGRA8888,
  438. APPLE_texture_max_level,
  439. ARB_clip_control,
  440. ARB_compute_shader,
  441. ARB_conservative_depth,
  442. ARB_copy_image,
  443. ARB_debug_label,
  444. ARB_debug_output,
  445. ARB_depth_buffer_float,
  446. ARB_depth_clamp,
  447. ARB_draw_buffers_blend,
  448. ARB_draw_indirect,
  449. ARB_draw_instanced,
  450. ARB_ES3_compatibility,
  451. ARB_framebuffer_object,
  452. ARB_framebuffer_sRGB,
  453. ARB_get_program_binary,
  454. ARB_half_float_pixel,
  455. ARB_half_float_vertex,
  456. ARB_instanced_arrays,
  457. ARB_internalformat_query,
  458. ARB_internalformat_query2,
  459. ARB_invalidate_subdata,
  460. ARB_map_buffer_range,
  461. ARB_multi_draw_indirect,
  462. ARB_multisample,
  463. ARB_occlusion_query,
  464. ARB_occlusion_query2,
  465. ARB_program_interface_query,
  466. ARB_sampler_objects,
  467. ARB_seamless_cube_map,
  468. ARB_shader_bit_encoding,
  469. ARB_shader_image_load_store,
  470. ARB_shader_storage_buffer_object,
  471. ARB_shader_texture_lod,
  472. ARB_texture_compression_bptc,
  473. ARB_texture_compression_rgtc,
  474. ARB_texture_float,
  475. ARB_texture_multisample,
  476. ARB_texture_rg,
  477. ARB_texture_rgb10_a2ui,
  478. ARB_texture_stencil8,
  479. ARB_texture_storage,
  480. ARB_texture_swizzle,
  481. ARB_timer_query,
  482. ARB_uniform_buffer_object,
  483. ARB_vertex_array_object,
  484. ARB_vertex_type_2_10_10_10_rev,
  485. ATI_meminfo,
  486. CHROMIUM_color_buffer_float_rgb,
  487. CHROMIUM_color_buffer_float_rgba,
  488. CHROMIUM_depth_texture,
  489. CHROMIUM_framebuffer_multisample,
  490. CHROMIUM_texture_compression_dxt3,
  491. CHROMIUM_texture_compression_dxt5,
  492. EXT_bgra,
  493. EXT_blend_color,
  494. EXT_blend_minmax,
  495. EXT_blend_subtract,
  496. EXT_color_buffer_half_float,
  497. EXT_color_buffer_float,
  498. EXT_copy_image,
  499. EXT_compressed_ETC1_RGB8_sub_texture,
  500. EXT_debug_label,
  501. EXT_debug_marker,
  502. EXT_debug_tool,
  503. EXT_discard_framebuffer,
  504. EXT_disjoint_timer_query,
  505. EXT_draw_buffers,
  506. EXT_draw_instanced,
  507. EXT_instanced_arrays,
  508. EXT_frag_depth,
  509. EXT_framebuffer_blit,
  510. EXT_framebuffer_object,
  511. EXT_framebuffer_sRGB,
  512. EXT_gpu_shader4,
  513. EXT_multi_draw_indirect,
  514. EXT_occlusion_query_boolean,
  515. EXT_packed_float,
  516. EXT_read_format_bgra,
  517. EXT_shader_image_load_store,
  518. EXT_shader_texture_lod,
  519. EXT_shadow_samplers,
  520. EXT_sRGB_write_control,
  521. EXT_texture_array,
  522. EXT_texture_compression_dxt1,
  523. EXT_texture_compression_latc,
  524. EXT_texture_compression_rgtc,
  525. EXT_texture_compression_s3tc,
  526. EXT_texture_filter_anisotropic,
  527. EXT_texture_format_BGRA8888,
  528. EXT_texture_rg,
  529. EXT_texture_shared_exponent,
  530. EXT_texture_snorm,
  531. EXT_texture_sRGB,
  532. EXT_texture_storage,
  533. EXT_texture_swizzle,
  534. EXT_texture_type_2_10_10_10_REV,
  535. EXT_timer_query,
  536. EXT_unpack_subimage,
  537. GOOGLE_depth_texture,
  538. GREMEDY_string_marker,
  539. GREMEDY_frame_terminator,
  540. IMG_multisampled_render_to_texture,
  541. IMG_read_format,
  542. IMG_shader_binary,
  543. IMG_texture_compression_pvrtc,
  544. IMG_texture_compression_pvrtc2,
  545. IMG_texture_format_BGRA8888,
  546. INTEL_fragment_shader_ordering,
  547. KHR_debug,
  548. KHR_no_error,
  549. MOZ_WEBGL_compressed_texture_s3tc,
  550. MOZ_WEBGL_depth_texture,
  551. NV_conservative_raster,
  552. NV_copy_image,
  553. NV_draw_buffers,
  554. NV_occlusion_query,
  555. NV_texture_border_clamp,
  556. NVX_gpu_memory_info,
  557. OES_copy_image,
  558. OES_compressed_ETC1_RGB8_texture,
  559. OES_depth24,
  560. OES_depth32,
  561. OES_depth_texture,
  562. OES_element_index_uint,
  563. OES_fragment_precision_high,
  564. OES_get_program_binary,
  565. OES_required_internalformat,
  566. OES_packed_depth_stencil,
  567. OES_read_format,
  568. OES_rgb8_rgba8,
  569. OES_standard_derivatives,
  570. OES_texture_3D,
  571. OES_texture_float,
  572. OES_texture_float_linear,
  573. OES_texture_npot,
  574. OES_texture_half_float,
  575. OES_texture_half_float_linear,
  576. OES_texture_stencil8,
  577. OES_vertex_array_object,
  578. OES_vertex_half_float,
  579. OES_vertex_type_10_10_10_2,
  580. WEBGL_color_buffer_float,
  581. WEBGL_compressed_texture_etc1,
  582. WEBGL_compressed_texture_s3tc,
  583. WEBGL_compressed_texture_pvrtc,
  584. WEBGL_depth_texture,
  585. WEBGL_draw_buffers,
  586. WEBKIT_EXT_texture_filter_anisotropic,
  587. WEBKIT_WEBGL_compressed_texture_s3tc,
  588. WEBKIT_WEBGL_depth_texture,
  589. Count
  590. };
  591. const char* m_name;
  592. bool m_supported;
  593. bool m_initialize;
  594. };
  595. // Extension registry
  596. //
  597. // ANGLE:
  598. // https://github.com/google/angle/tree/master/extensions
  599. //
  600. // CHROMIUM:
  601. // https://chromium.googlesource.com/chromium/src.git/+/refs/heads/git-svn/gpu/GLES2/extensions/CHROMIUM
  602. //
  603. // EGL:
  604. // https://www.khronos.org/registry/egl/extensions/
  605. //
  606. // GL:
  607. // https://www.opengl.org/registry/
  608. //
  609. // GLES:
  610. // https://www.khronos.org/registry/gles/extensions/
  611. //
  612. // WEBGL:
  613. // https://www.khronos.org/registry/webgl/extensions/
  614. //
  615. static Extension s_extension[] =
  616. {
  617. { "AMD_conservative_depth", false, true },
  618. { "AMD_multi_draw_indirect", false, true },
  619. { "ANGLE_depth_texture", false, true },
  620. { "ANGLE_framebuffer_blit", false, true },
  621. { "ANGLE_framebuffer_multisample", false, false },
  622. { "ANGLE_instanced_arrays", false, true },
  623. { "ANGLE_texture_compression_dxt1", false, true },
  624. { "ANGLE_texture_compression_dxt3", false, true },
  625. { "ANGLE_texture_compression_dxt5", false, true },
  626. { "ANGLE_timer_query", false, true },
  627. { "ANGLE_translated_shader_source", false, true },
  628. { "APPLE_texture_format_BGRA8888", false, true },
  629. { "APPLE_texture_max_level", false, true },
  630. { "ARB_clip_control", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  631. { "ARB_compute_shader", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  632. { "ARB_conservative_depth", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  633. { "ARB_copy_image", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  634. { "ARB_debug_label", false, true },
  635. { "ARB_debug_output", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  636. { "ARB_depth_buffer_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  637. { "ARB_depth_clamp", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  638. { "ARB_draw_buffers_blend", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  639. { "ARB_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  640. { "ARB_draw_instanced", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  641. { "ARB_ES3_compatibility", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  642. { "ARB_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  643. { "ARB_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  644. { "ARB_get_program_binary", BGFX_CONFIG_RENDERER_OPENGL >= 41, true },
  645. { "ARB_half_float_pixel", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  646. { "ARB_half_float_vertex", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  647. { "ARB_instanced_arrays", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  648. { "ARB_internalformat_query", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  649. { "ARB_internalformat_query2", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  650. { "ARB_invalidate_subdata", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  651. { "ARB_map_buffer_range", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  652. { "ARB_multi_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  653. { "ARB_multisample", false, true },
  654. { "ARB_occlusion_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  655. { "ARB_occlusion_query2", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  656. { "ARB_program_interface_query", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  657. { "ARB_sampler_objects", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  658. { "ARB_seamless_cube_map", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  659. { "ARB_shader_bit_encoding", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  660. { "ARB_shader_image_load_store", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  661. { "ARB_shader_storage_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  662. { "ARB_shader_texture_lod", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  663. { "ARB_texture_compression_bptc", BGFX_CONFIG_RENDERER_OPENGL >= 44, true },
  664. { "ARB_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  665. { "ARB_texture_float", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  666. { "ARB_texture_multisample", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  667. { "ARB_texture_rg", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  668. { "ARB_texture_rgb10_a2ui", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  669. { "ARB_texture_stencil8", false, true },
  670. { "ARB_texture_storage", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  671. { "ARB_texture_swizzle", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  672. { "ARB_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  673. { "ARB_uniform_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  674. { "ARB_vertex_array_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  675. { "ARB_vertex_type_2_10_10_10_rev", false, true },
  676. { "ATI_meminfo", false, true },
  677. { "CHROMIUM_color_buffer_float_rgb", false, true },
  678. { "CHROMIUM_color_buffer_float_rgba", false, true },
  679. { "CHROMIUM_depth_texture", false, true },
  680. { "CHROMIUM_framebuffer_multisample", false, true },
  681. { "CHROMIUM_texture_compression_dxt3", false, true },
  682. { "CHROMIUM_texture_compression_dxt5", false, true },
  683. { "EXT_bgra", false, true },
  684. { "EXT_blend_color", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  685. { "EXT_blend_minmax", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  686. { "EXT_blend_subtract", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  687. { "EXT_color_buffer_half_float", false, true }, // GLES2 extension.
  688. { "EXT_color_buffer_float", false, true }, // GLES2 extension.
  689. { "EXT_copy_image", false, true }, // GLES2 extension.
  690. { "EXT_compressed_ETC1_RGB8_sub_texture", false, true }, // GLES2 extension.
  691. { "EXT_debug_label", false, true },
  692. { "EXT_debug_marker", false, true },
  693. { "EXT_debug_tool", false, true }, // RenderDoc extension.
  694. { "EXT_discard_framebuffer", false, true }, // GLES2 extension.
  695. { "EXT_disjoint_timer_query", false, true }, // GLES2 extension.
  696. { "EXT_draw_buffers", false, true }, // GLES2 extension.
  697. { "EXT_draw_instanced", false, true }, // GLES2 extension.
  698. { "EXT_instanced_arrays", false, true }, // GLES2 extension.
  699. { "EXT_frag_depth", false, true }, // GLES2 extension.
  700. { "EXT_framebuffer_blit", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  701. { "EXT_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  702. { "EXT_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  703. { "EXT_gpu_shader4", false, true },
  704. { "EXT_multi_draw_indirect", false, true }, // GLES3.1 extension.
  705. { "EXT_occlusion_query_boolean", false, true }, // GLES2 extension.
  706. { "EXT_packed_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  707. { "EXT_read_format_bgra", false, true },
  708. { "EXT_shader_image_load_store", false, true },
  709. { "EXT_shader_texture_lod", false, true }, // GLES2 extension.
  710. { "EXT_shadow_samplers", false, true },
  711. { "EXT_sRGB_write_control", false, true }, // GLES2 extension.
  712. { "EXT_texture_array", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  713. { "EXT_texture_compression_dxt1", false, true },
  714. { "EXT_texture_compression_latc", false, true },
  715. { "EXT_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  716. { "EXT_texture_compression_s3tc", false, true },
  717. { "EXT_texture_filter_anisotropic", false, true },
  718. { "EXT_texture_format_BGRA8888", false, true },
  719. { "EXT_texture_rg", false, true }, // GLES2 extension.
  720. { "EXT_texture_shared_exponent", false, true },
  721. { "EXT_texture_snorm", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  722. { "EXT_texture_sRGB", false, true },
  723. { "EXT_texture_storage", false, true },
  724. { "EXT_texture_swizzle", false, true },
  725. { "EXT_texture_type_2_10_10_10_REV", false, true },
  726. { "EXT_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  727. { "EXT_unpack_subimage", false, true },
  728. { "GOOGLE_depth_texture", false, true },
  729. { "GREMEDY_string_marker", false, true },
  730. { "GREMEDY_frame_terminator", false, true },
  731. { "IMG_multisampled_render_to_texture", false, true },
  732. { "IMG_read_format", false, true },
  733. { "IMG_shader_binary", false, true },
  734. { "IMG_texture_compression_pvrtc", false, true },
  735. { "IMG_texture_compression_pvrtc2", false, true },
  736. { "IMG_texture_format_BGRA8888", false, true },
  737. { "INTEL_fragment_shader_ordering", false, true },
  738. { "KHR_debug", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  739. { "KHR_no_error", false, true },
  740. { "MOZ_WEBGL_compressed_texture_s3tc", false, true },
  741. { "MOZ_WEBGL_depth_texture", false, true },
  742. { "NV_conservative_raster", false, true },
  743. { "NV_copy_image", false, true },
  744. { "NV_draw_buffers", false, true }, // GLES2 extension.
  745. { "NV_occlusion_query", false, true },
  746. { "NV_texture_border_clamp", false, true }, // GLES2 extension.
  747. { "NVX_gpu_memory_info", false, true },
  748. { "OES_copy_image", false, true },
  749. { "OES_compressed_ETC1_RGB8_texture", false, true },
  750. { "OES_depth24", false, true },
  751. { "OES_depth32", false, true },
  752. { "OES_depth_texture", false, true },
  753. { "OES_element_index_uint", false, true },
  754. { "OES_fragment_precision_high", false, true },
  755. { "OES_get_program_binary", false, true },
  756. { "OES_required_internalformat", false, true },
  757. { "OES_packed_depth_stencil", false, true },
  758. { "OES_read_format", false, true },
  759. { "OES_rgb8_rgba8", false, true },
  760. { "OES_standard_derivatives", false, true },
  761. { "OES_texture_3D", false, true },
  762. { "OES_texture_float", false, true },
  763. { "OES_texture_float_linear", false, true },
  764. { "OES_texture_npot", false, true },
  765. { "OES_texture_half_float", false, true },
  766. { "OES_texture_half_float_linear", false, true },
  767. { "OES_texture_stencil8", false, true },
  768. { "OES_vertex_array_object", false, !BX_PLATFORM_IOS },
  769. { "OES_vertex_half_float", false, true },
  770. { "OES_vertex_type_10_10_10_2", false, true },
  771. { "WEBGL_color_buffer_float", false, true },
  772. { "WEBGL_compressed_texture_etc1", false, true },
  773. { "WEBGL_compressed_texture_s3tc", false, true },
  774. { "WEBGL_compressed_texture_pvrtc", false, true },
  775. { "WEBGL_depth_texture", false, true },
  776. { "WEBGL_draw_buffers", false, true },
  777. { "WEBKIT_EXT_texture_filter_anisotropic", false, true },
  778. { "WEBKIT_WEBGL_compressed_texture_s3tc", false, true },
  779. { "WEBKIT_WEBGL_depth_texture", false, true },
  780. };
  781. BX_STATIC_ASSERT(Extension::Count == BX_COUNTOF(s_extension) );
  782. static const char* s_ARB_shader_texture_lod[] =
  783. {
  784. "texture2DLod",
  785. "texture2DProjLod",
  786. "texture3DLod",
  787. "texture3DProjLod",
  788. "textureCubeLod",
  789. "shadow2DLod",
  790. "shadow2DProjLod",
  791. NULL
  792. // "texture1DLod",
  793. // "texture1DProjLod",
  794. // "shadow1DLod",
  795. // "shadow1DProjLod",
  796. };
  797. static const char* s_EXT_shader_texture_lod[] =
  798. {
  799. "texture2DLod",
  800. "texture2DProjLod",
  801. "textureCubeLod",
  802. NULL
  803. // "texture2DGrad",
  804. // "texture2DProjGrad",
  805. // "textureCubeGrad",
  806. };
  807. static const char* s_EXT_shadow_samplers[] =
  808. {
  809. "shadow2D",
  810. "shadow2DProj",
  811. NULL
  812. };
  813. static const char* s_OES_standard_derivatives[] =
  814. {
  815. "dFdx",
  816. "dFdy",
  817. "fwidth",
  818. NULL
  819. };
  820. static const char* s_OES_texture_3D[] =
  821. {
  822. "texture3D",
  823. "texture3DProj",
  824. "texture3DLod",
  825. "texture3DProjLod",
  826. NULL
  827. };
  828. static const char* s_uisamplers[] =
  829. {
  830. "isampler2D",
  831. "usampler2D",
  832. "isampler3D",
  833. "usampler3D",
  834. "isamplerCube",
  835. "usamplerCube",
  836. NULL
  837. };
  838. static const char* s_texelFetch[] =
  839. {
  840. "texelFetch",
  841. "texelFetchOffset",
  842. NULL
  843. };
  844. static const char* s_ARB_texture_multisample[] =
  845. {
  846. "sampler2DMS",
  847. "isampler2DMS",
  848. "usampler2DMS",
  849. NULL
  850. };
  851. static void GL_APIENTRY stubVertexAttribDivisor(GLuint /*_index*/, GLuint /*_divisor*/)
  852. {
  853. }
  854. static void GL_APIENTRY stubDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei /*_primcount*/)
  855. {
  856. GL_CHECK(glDrawArrays(_mode, _first, _count) );
  857. }
  858. static void GL_APIENTRY stubDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei /*_primcount*/)
  859. {
  860. GL_CHECK(glDrawElements(_mode, _count, _type, _indices) );
  861. }
  862. static void GL_APIENTRY stubFrameTerminatorGREMEDY()
  863. {
  864. }
  865. static void GL_APIENTRY stubInsertEventMarker(GLsizei /*_length*/, const char* /*_marker*/)
  866. {
  867. }
  868. static void GL_APIENTRY stubInsertEventMarkerGREMEDY(GLsizei _length, const char* _marker)
  869. {
  870. // If <marker> is a null-terminated string then <length> should not
  871. // include the terminator.
  872. //
  873. // If <length> is 0 then <marker> is assumed to be null-terminated.
  874. uint32_t size = (0 == _length ? (uint32_t)strlen(_marker) : _length) + 1;
  875. size *= sizeof(wchar_t);
  876. wchar_t* name = (wchar_t*)alloca(size);
  877. mbstowcs(name, _marker, size-2);
  878. GL_CHECK(glStringMarkerGREMEDY(_length, _marker) );
  879. }
  880. static void GL_APIENTRY stubObjectLabel(GLenum /*_identifier*/, GLuint /*_name*/, GLsizei /*_length*/, const char* /*_label*/)
  881. {
  882. }
  883. static void GL_APIENTRY stubInvalidateFramebuffer(GLenum /*_target*/, GLsizei /*_numAttachments*/, const GLenum* /*_attachments*/)
  884. {
  885. }
  886. static void GL_APIENTRY stubMultiDrawArraysIndirect(GLenum _mode, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  887. {
  888. const uint8_t* args = (const uint8_t*)_indirect;
  889. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  890. {
  891. GL_CHECK(glDrawArraysIndirect(_mode, (void*)args) );
  892. args += _stride;
  893. }
  894. }
  895. static void GL_APIENTRY stubMultiDrawElementsIndirect(GLenum _mode, GLenum _type, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  896. {
  897. const uint8_t* args = (const uint8_t*)_indirect;
  898. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  899. {
  900. GL_CHECK(glDrawElementsIndirect(_mode, _type, (void*)args) );
  901. args += _stride;
  902. }
  903. }
  904. typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);
  905. static const char* getGLString(GLenum _name)
  906. {
  907. const char* str = (const char*)glGetString(_name);
  908. glGetError(); // ignore error if glGetString returns NULL.
  909. if (NULL != str)
  910. {
  911. return str;
  912. }
  913. return "<unknown>";
  914. }
  915. static uint32_t getGLStringHash(GLenum _name)
  916. {
  917. const char* str = (const char*)glGetString(_name);
  918. glGetError(); // ignore error if glGetString returns NULL.
  919. if (NULL != str)
  920. {
  921. return bx::hashMurmur2A(str, (uint32_t)strlen(str) );
  922. }
  923. return 0;
  924. }
  925. void dumpExtensions(const char* _extensions)
  926. {
  927. if (NULL != _extensions)
  928. {
  929. char name[1024];
  930. const char* pos = _extensions;
  931. const char* end = _extensions + strlen(_extensions);
  932. while (pos < end)
  933. {
  934. uint32_t len;
  935. const char* space = strchr(pos, ' ');
  936. if (NULL != space)
  937. {
  938. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  939. }
  940. else
  941. {
  942. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  943. }
  944. strncpy(name, pos, len);
  945. name[len] = '\0';
  946. BX_TRACE("\t%s", name);
  947. pos += len+1;
  948. }
  949. }
  950. }
  951. const char* toString(GLenum _enum)
  952. {
  953. switch (_enum)
  954. {
  955. case GL_DEBUG_SOURCE_API: return "API";
  956. case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "WinSys";
  957. case GL_DEBUG_SOURCE_SHADER_COMPILER: return "Shader";
  958. case GL_DEBUG_SOURCE_THIRD_PARTY: return "3rdparty";
  959. case GL_DEBUG_SOURCE_APPLICATION: return "Application";
  960. case GL_DEBUG_SOURCE_OTHER: return "Other";
  961. case GL_DEBUG_TYPE_ERROR: return "Error";
  962. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "Deprecated behavior";
  963. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "Undefined behavior";
  964. case GL_DEBUG_TYPE_PORTABILITY: return "Portability";
  965. case GL_DEBUG_TYPE_PERFORMANCE: return "Performance";
  966. case GL_DEBUG_TYPE_OTHER: return "Other";
  967. case GL_DEBUG_SEVERITY_HIGH: return "High";
  968. case GL_DEBUG_SEVERITY_MEDIUM: return "Medium";
  969. case GL_DEBUG_SEVERITY_LOW: return "Low";
  970. default:
  971. break;
  972. }
  973. return "<unknown>";
  974. }
  975. void GL_APIENTRY debugProcCb(GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar* _message, const void* /*_userParam*/)
  976. {
  977. BX_TRACE("src %s, type %s, id %d, severity %s, '%s'"
  978. , toString(_source)
  979. , toString(_type)
  980. , _id
  981. , toString(_severity)
  982. , _message
  983. );
  984. BX_UNUSED(_source, _type, _id, _severity, _message);
  985. }
  986. GLint glGet(GLenum _pname)
  987. {
  988. GLint result = 0;
  989. glGetIntegerv(_pname, &result);
  990. GLenum err = glGetError();
  991. BX_WARN(0 == err, "glGetIntegerv(0x%04x, ...) failed with GL error: 0x%04x.", _pname, err);
  992. return 0 == err ? result : 0;
  993. }
  994. void setTextureFormat(TextureFormat::Enum _format, GLenum _internalFmt, GLenum _fmt, GLenum _type = GL_ZERO)
  995. {
  996. TextureFormatInfo& tfi = s_textureFormat[_format];
  997. tfi.m_internalFmt = _internalFmt;
  998. tfi.m_fmt = _fmt;
  999. tfi.m_type = _type;
  1000. }
  1001. void initTestTexture(TextureFormat::Enum _format, bool srgb = false)
  1002. {
  1003. const TextureFormatInfo& tfi = s_textureFormat[_format];
  1004. GLenum internalFmt = srgb
  1005. ? tfi.m_internalFmtSrgb
  1006. : tfi.m_internalFmt
  1007. ;
  1008. GLsizei size = (16*16*getBitsPerPixel(_format) )/8;
  1009. void* data = bx::alignPtr(alloca(size+16), 0, 16);
  1010. if (isCompressed(_format) )
  1011. {
  1012. glCompressedTexImage2D(GL_TEXTURE_2D, 0, internalFmt, 16, 16, 0, size, data);
  1013. }
  1014. else
  1015. {
  1016. glTexImage2D(GL_TEXTURE_2D, 0, internalFmt, 16, 16, 0, tfi.m_fmt, tfi.m_type, data);
  1017. }
  1018. }
  1019. static bool isTextureFormatValid(TextureFormat::Enum _format, bool srgb = false)
  1020. {
  1021. const TextureFormatInfo& tfi = s_textureFormat[_format];
  1022. GLenum internalFmt = srgb
  1023. ? tfi.m_internalFmtSrgb
  1024. : tfi.m_internalFmt
  1025. ;
  1026. if (GL_ZERO == internalFmt)
  1027. {
  1028. return false;
  1029. }
  1030. GLuint id;
  1031. GL_CHECK(glGenTextures(1, &id) );
  1032. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  1033. initTestTexture(_format);
  1034. GLenum err = glGetError();
  1035. BX_WARN(0 == err, "TextureFormat::%s is not supported (%x: %s).", getName(_format), err, glEnumName(err) );
  1036. GL_CHECK(glDeleteTextures(1, &id) );
  1037. return 0 == err;
  1038. }
  1039. static bool isImageFormatValid(TextureFormat::Enum _format)
  1040. {
  1041. if (GL_ZERO == s_imageFormat[_format])
  1042. {
  1043. return false;
  1044. }
  1045. GLuint id;
  1046. GL_CHECK(glGenTextures(1, &id) );
  1047. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  1048. glTexStorage2D(GL_TEXTURE_2D, 1, s_imageFormat[_format], 16, 16);
  1049. GLenum err = glGetError();
  1050. if (0 == err)
  1051. {
  1052. glBindImageTexture(0
  1053. , id
  1054. , 0
  1055. , GL_FALSE
  1056. , 0
  1057. , GL_READ_WRITE
  1058. , s_imageFormat[_format]
  1059. );
  1060. err = glGetError();
  1061. }
  1062. GL_CHECK(glDeleteTextures(1, &id) );
  1063. return 0 == err;
  1064. }
  1065. static bool isFramebufferFormatValid(TextureFormat::Enum _format, bool srgb = false)
  1066. {
  1067. const TextureFormatInfo& tfi = s_textureFormat[_format];
  1068. GLenum internalFmt = srgb
  1069. ? tfi.m_internalFmtSrgb
  1070. : tfi.m_internalFmt
  1071. ;
  1072. if (GL_ZERO == internalFmt
  1073. || !tfi.m_supported)
  1074. {
  1075. return false;
  1076. }
  1077. GLuint fbo;
  1078. GL_CHECK(glGenFramebuffers(1, &fbo) );
  1079. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, fbo) );
  1080. GLuint id;
  1081. GL_CHECK(glGenTextures(1, &id) );
  1082. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  1083. initTestTexture(_format);
  1084. GLenum err = glGetError();
  1085. GLenum attachment;
  1086. if (isDepth(_format) )
  1087. {
  1088. const ImageBlockInfo& info = getBlockInfo(_format);
  1089. if (0 == info.depthBits)
  1090. {
  1091. attachment = GL_STENCIL_ATTACHMENT;
  1092. }
  1093. else if (0 == info.stencilBits)
  1094. {
  1095. attachment = GL_DEPTH_ATTACHMENT;
  1096. }
  1097. else
  1098. {
  1099. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  1100. }
  1101. }
  1102. else
  1103. {
  1104. attachment = GL_COLOR_ATTACHMENT0;
  1105. }
  1106. glFramebufferTexture2D(GL_FRAMEBUFFER
  1107. , attachment
  1108. , GL_TEXTURE_2D
  1109. , id
  1110. , 0
  1111. );
  1112. err = glGetError();
  1113. if (0 == err)
  1114. {
  1115. err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  1116. }
  1117. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1118. GL_CHECK(glDeleteFramebuffers(1, &fbo) );
  1119. GL_CHECK(glDeleteTextures(1, &id) );
  1120. return GL_FRAMEBUFFER_COMPLETE == err;
  1121. }
  1122. static void getFilters(uint32_t _flags, bool _hasMips, GLenum& _magFilter, GLenum& _minFilter)
  1123. {
  1124. const uint32_t mag = (_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT;
  1125. const uint32_t min = (_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT;
  1126. const uint32_t mip = (_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT;
  1127. _magFilter = s_textureFilterMag[mag];
  1128. _minFilter = s_textureFilterMin[min][_hasMips ? mip+1 : 0];
  1129. }
  1130. void updateExtension(const char* _name)
  1131. {
  1132. bool supported = false;
  1133. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1134. {
  1135. Extension& extension = s_extension[ii];
  1136. if (!extension.m_supported
  1137. && extension.m_initialize)
  1138. {
  1139. const char* ext = _name;
  1140. if (0 == strncmp(ext, "GL_", 3) ) // skip GL_
  1141. {
  1142. ext += 3;
  1143. }
  1144. if (0 == strcmp(ext, extension.m_name) )
  1145. {
  1146. extension.m_supported = true;
  1147. supported = true;
  1148. break;
  1149. }
  1150. }
  1151. }
  1152. BX_TRACE("GL_EXTENSION %s: %s", supported ? " (supported)" : "", _name);
  1153. BX_UNUSED(supported);
  1154. }
  1155. struct RendererContextGL : public RendererContextI
  1156. {
  1157. RendererContextGL()
  1158. : m_numWindows(1)
  1159. , m_rtMsaa(false)
  1160. , m_fbDiscard(BGFX_CLEAR_NONE)
  1161. , m_capture(NULL)
  1162. , m_captureSize(0)
  1163. , m_maxAnisotropy(0.0f)
  1164. , m_maxAnisotropyDefault(0.0f)
  1165. , m_maxMsaa(0)
  1166. , m_vao(0)
  1167. , m_blitSupported(false)
  1168. , m_readBackSupported(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1169. , m_vaoSupport(false)
  1170. , m_samplerObjectSupport(false)
  1171. , m_shadowSamplersSupport(false)
  1172. , m_srgbWriteControlSupport(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1173. , m_borderColorSupport(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1174. , m_programBinarySupport(false)
  1175. , m_textureSwizzleSupport(false)
  1176. , m_depthTextureSupport(false)
  1177. , m_timerQuerySupport(false)
  1178. , m_occlusionQuerySupport(false)
  1179. , m_atocSupport(false)
  1180. , m_conservativeRasterSupport(false)
  1181. , m_flip(false)
  1182. , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1183. , m_backBufferFbo(0)
  1184. , m_msaaBackBufferFbo(0)
  1185. {
  1186. memset(m_msaaBackBufferRbos, 0, sizeof(m_msaaBackBufferRbos) );
  1187. }
  1188. ~RendererContextGL()
  1189. {
  1190. }
  1191. void init()
  1192. {
  1193. m_renderdocdll = loadRenderDoc();
  1194. m_fbh.idx = invalidHandle;
  1195. memset(m_uniforms, 0, sizeof(m_uniforms) );
  1196. memset(&m_resolution, 0, sizeof(m_resolution) );
  1197. setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  1198. // Must be after context is initialized?!
  1199. m_ovr.init();
  1200. m_vendor = getGLString(GL_VENDOR);
  1201. m_renderer = getGLString(GL_RENDERER);
  1202. m_version = getGLString(GL_VERSION);
  1203. m_glslVersion = getGLString(GL_SHADING_LANGUAGE_VERSION);
  1204. GLint numCmpFormats = 0;
  1205. GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) );
  1206. BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats);
  1207. GLint* cmpFormat = NULL;
  1208. if (0 < numCmpFormats)
  1209. {
  1210. numCmpFormats = numCmpFormats > 256 ? 256 : numCmpFormats;
  1211. cmpFormat = (GLint*)alloca(sizeof(GLint)*numCmpFormats);
  1212. GL_CHECK(glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, cmpFormat) );
  1213. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1214. {
  1215. GLint internalFmt = cmpFormat[ii];
  1216. uint32_t fmt = uint32_t(TextureFormat::Unknown);
  1217. for (uint32_t jj = 0; jj < fmt; ++jj)
  1218. {
  1219. if (s_textureFormat[jj].m_internalFmt == (GLenum)internalFmt)
  1220. {
  1221. s_textureFormat[jj].m_supported = true;
  1222. fmt = jj;
  1223. }
  1224. }
  1225. BX_TRACE(" %3d: %8x %s", ii, internalFmt, getName( (TextureFormat::Enum)fmt) );
  1226. }
  1227. }
  1228. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  1229. {
  1230. #define GL_GET(_pname, _min) BX_TRACE(" " #_pname " %d (min: %d)", glGet(_pname), _min)
  1231. BX_TRACE("Defaults:");
  1232. #if BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1233. GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16);
  1234. GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128);
  1235. GL_GET(GL_MAX_VARYING_VECTORS, 8);
  1236. #else
  1237. GL_GET(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 16 * 4);
  1238. GL_GET(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 128 * 4);
  1239. GL_GET(GL_MAX_VARYING_FLOATS, 8 * 4);
  1240. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1241. GL_GET(GL_MAX_VERTEX_ATTRIBS, 8);
  1242. GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8);
  1243. GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16);
  1244. GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8);
  1245. GL_GET(GL_MAX_TEXTURE_SIZE, 64);
  1246. GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0);
  1247. GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1);
  1248. GL_GET(GL_MAX_COLOR_ATTACHMENTS, 1);
  1249. GL_GET(GL_MAX_DRAW_BUFFERS, 1);
  1250. #undef GL_GET
  1251. BX_TRACE(" Vendor: %s", m_vendor);
  1252. BX_TRACE(" Renderer: %s", m_renderer);
  1253. BX_TRACE(" Version: %s", m_version);
  1254. BX_TRACE("GLSL version: %s", m_glslVersion);
  1255. }
  1256. // Initial binary shader hash depends on driver version.
  1257. m_hash = ( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1258. ^ (uint64_t(getGLStringHash(GL_VENDOR ) )<<32)
  1259. ^ (uint64_t(getGLStringHash(GL_RENDERER) )<<0 )
  1260. ^ (uint64_t(getGLStringHash(GL_VERSION ) )<<16)
  1261. ;
  1262. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  1263. && 0 == strcmp(m_vendor, "Imagination Technologies")
  1264. && NULL != strstr(m_version, "(SDK 3.5@3510720)") )
  1265. {
  1266. // Skip initializing extensions that are broken in emulator.
  1267. s_extension[Extension::ARB_program_interface_query ].m_initialize =
  1268. s_extension[Extension::ARB_shader_storage_buffer_object].m_initialize = false;
  1269. }
  1270. if (BX_ENABLED(BGFX_CONFIG_RENDERER_USE_EXTENSIONS) )
  1271. {
  1272. const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
  1273. glGetError(); // ignore error if glGetString returns NULL.
  1274. if (NULL != extensions)
  1275. {
  1276. char name[1024];
  1277. const char* pos = extensions;
  1278. const char* end = extensions + strlen(extensions);
  1279. uint32_t index = 0;
  1280. while (pos < end)
  1281. {
  1282. uint32_t len;
  1283. const char* space = strchr(pos, ' ');
  1284. if (NULL != space)
  1285. {
  1286. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  1287. }
  1288. else
  1289. {
  1290. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  1291. }
  1292. strncpy(name, pos, len);
  1293. name[len] = '\0';
  1294. updateExtension(name);
  1295. pos += len+1;
  1296. ++index;
  1297. }
  1298. }
  1299. else if (NULL != glGetStringi)
  1300. {
  1301. GLint numExtensions = 0;
  1302. glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
  1303. glGetError(); // ignore error if glGetIntegerv returns NULL.
  1304. for (GLint index = 0; index < numExtensions; ++index)
  1305. {
  1306. const char* name = (const char*)glGetStringi(GL_EXTENSIONS, index);
  1307. updateExtension(name);
  1308. }
  1309. }
  1310. BX_TRACE("Supported extensions:");
  1311. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1312. {
  1313. if (s_extension[ii].m_supported)
  1314. {
  1315. BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name);
  1316. }
  1317. }
  1318. }
  1319. // Allow all texture filters.
  1320. memset(s_textureFilter, true, BX_COUNTOF(s_textureFilter) );
  1321. bool bc123Supported = 0
  1322. || s_extension[Extension::EXT_texture_compression_s3tc ].m_supported
  1323. || s_extension[Extension::MOZ_WEBGL_compressed_texture_s3tc ].m_supported
  1324. || s_extension[Extension::WEBGL_compressed_texture_s3tc ].m_supported
  1325. || s_extension[Extension::WEBKIT_WEBGL_compressed_texture_s3tc].m_supported
  1326. ;
  1327. s_textureFormat[TextureFormat::BC1].m_supported |= bc123Supported
  1328. || s_extension[Extension::ANGLE_texture_compression_dxt1].m_supported
  1329. || s_extension[Extension::EXT_texture_compression_dxt1 ].m_supported
  1330. ;
  1331. if (!s_textureFormat[TextureFormat::BC1].m_supported
  1332. && ( s_textureFormat[TextureFormat::BC2].m_supported || s_textureFormat[TextureFormat::BC3].m_supported) )
  1333. {
  1334. // If RGBA_S3TC_DXT1 is not supported, maybe RGB_S3TC_DXT1 is?
  1335. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1336. {
  1337. if (GL_COMPRESSED_RGB_S3TC_DXT1_EXT == cmpFormat[ii])
  1338. {
  1339. setTextureFormat(TextureFormat::BC1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
  1340. s_textureFormat[TextureFormat::BC1].m_supported = true;
  1341. break;
  1342. }
  1343. }
  1344. }
  1345. s_textureFormat[TextureFormat::BC2].m_supported |= bc123Supported
  1346. || s_extension[Extension::ANGLE_texture_compression_dxt3 ].m_supported
  1347. || s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported
  1348. ;
  1349. s_textureFormat[TextureFormat::BC3].m_supported |= bc123Supported
  1350. || s_extension[Extension::ANGLE_texture_compression_dxt5 ].m_supported
  1351. || s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported
  1352. ;
  1353. if (s_extension[Extension::EXT_texture_compression_latc].m_supported)
  1354. {
  1355. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT);
  1356. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT);
  1357. }
  1358. if (s_extension[Extension::ARB_texture_compression_rgtc].m_supported
  1359. || s_extension[Extension::EXT_texture_compression_rgtc].m_supported)
  1360. {
  1361. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1);
  1362. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2);
  1363. }
  1364. bool etc1Supported = 0
  1365. || s_extension[Extension::OES_compressed_ETC1_RGB8_texture].m_supported
  1366. || s_extension[Extension::WEBGL_compressed_texture_etc1 ].m_supported
  1367. ;
  1368. s_textureFormat[TextureFormat::ETC1].m_supported |= etc1Supported;
  1369. bool etc2Supported = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1370. || s_extension[Extension::ARB_ES3_compatibility].m_supported
  1371. ;
  1372. s_textureFormat[TextureFormat::ETC2 ].m_supported |= etc2Supported;
  1373. s_textureFormat[TextureFormat::ETC2A ].m_supported |= etc2Supported;
  1374. s_textureFormat[TextureFormat::ETC2A1].m_supported |= etc2Supported;
  1375. if (!s_textureFormat[TextureFormat::ETC1].m_supported
  1376. && s_textureFormat[TextureFormat::ETC2].m_supported)
  1377. {
  1378. // When ETC2 is supported override ETC1 texture format settings.
  1379. s_textureFormat[TextureFormat::ETC1].m_internalFmt = GL_COMPRESSED_RGB8_ETC2;
  1380. s_textureFormat[TextureFormat::ETC1].m_fmt = GL_COMPRESSED_RGB8_ETC2;
  1381. s_textureFormat[TextureFormat::ETC1].m_supported = true;
  1382. }
  1383. bool ptc1Supported = 0
  1384. || s_extension[Extension::IMG_texture_compression_pvrtc ].m_supported
  1385. || s_extension[Extension::WEBGL_compressed_texture_pvrtc].m_supported
  1386. ;
  1387. s_textureFormat[TextureFormat::PTC12 ].m_supported |= ptc1Supported;
  1388. s_textureFormat[TextureFormat::PTC14 ].m_supported |= ptc1Supported;
  1389. s_textureFormat[TextureFormat::PTC12A].m_supported |= ptc1Supported;
  1390. s_textureFormat[TextureFormat::PTC14A].m_supported |= ptc1Supported;
  1391. bool ptc2Supported = s_extension[Extension::IMG_texture_compression_pvrtc2].m_supported;
  1392. s_textureFormat[TextureFormat::PTC22].m_supported |= ptc2Supported;
  1393. s_textureFormat[TextureFormat::PTC24].m_supported |= ptc2Supported;
  1394. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) )
  1395. {
  1396. setTextureFormat(TextureFormat::D32, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT);
  1397. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  1398. {
  1399. setTextureFormat(TextureFormat::RGBA16F, GL_RGBA, GL_RGBA, GL_HALF_FLOAT);
  1400. // internalFormat and format must match:
  1401. // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexImage2D.xml
  1402. setTextureFormat(TextureFormat::RGBA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE);
  1403. setTextureFormat(TextureFormat::R5G6B5, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5_REV);
  1404. setTextureFormat(TextureFormat::RGBA4, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV);
  1405. setTextureFormat(TextureFormat::RGB5A1, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV);
  1406. if (s_extension[Extension::OES_texture_half_float].m_supported
  1407. || s_extension[Extension::OES_texture_float ].m_supported)
  1408. {
  1409. // https://www.khronos.org/registry/gles/extensions/OES/OES_texture_float.txt
  1410. // When half/float is available via extensions texture will be marked as
  1411. // incomplete if it uses anything other than nearest filter.
  1412. const bool linear16F = s_extension[Extension::OES_texture_half_float_linear].m_supported;
  1413. const bool linear32F = s_extension[Extension::OES_texture_float_linear ].m_supported;
  1414. s_textureFilter[TextureFormat::R16F] = linear16F;
  1415. s_textureFilter[TextureFormat::RG16F] = linear16F;
  1416. s_textureFilter[TextureFormat::RGBA16F] = linear16F;
  1417. s_textureFilter[TextureFormat::R32F] = linear32F;
  1418. s_textureFilter[TextureFormat::RG32F] = linear32F;
  1419. s_textureFilter[TextureFormat::RGBA32F] = linear32F;
  1420. }
  1421. if (BX_ENABLED(BX_PLATFORM_IOS) )
  1422. {
  1423. setTextureFormat(TextureFormat::D16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT);
  1424. setTextureFormat(TextureFormat::D24S8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8);
  1425. }
  1426. }
  1427. }
  1428. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1429. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1430. {
  1431. setTextureFormat(TextureFormat::R8I, GL_R8I, GL_RED_INTEGER, GL_BYTE);
  1432. setTextureFormat(TextureFormat::R8U, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE);
  1433. setTextureFormat(TextureFormat::R16I, GL_R16I, GL_RED_INTEGER, GL_SHORT);
  1434. setTextureFormat(TextureFormat::R16U, GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT);
  1435. // setTextureFormat(TextureFormat::RG16, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT);
  1436. // setTextureFormat(TextureFormat::RGBA16, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT);
  1437. setTextureFormat(TextureFormat::R32U, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT);
  1438. setTextureFormat(TextureFormat::RG32U, GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT);
  1439. setTextureFormat(TextureFormat::RGBA32U, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT);
  1440. }
  1441. if (s_extension[Extension::EXT_texture_format_BGRA8888 ].m_supported
  1442. || s_extension[Extension::EXT_bgra ].m_supported
  1443. || s_extension[Extension::IMG_texture_format_BGRA8888 ].m_supported
  1444. || s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1445. {
  1446. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1447. {
  1448. m_readPixelsFmt = GL_BGRA;
  1449. }
  1450. // Mixing GLES and GL extensions here. OpenGL EXT_bgra and
  1451. // APPLE_texture_format_BGRA8888 wants
  1452. // format to be BGRA but internal format to stay RGBA, but
  1453. // EXT_texture_format_BGRA8888 wants both format and internal
  1454. // format to be BGRA.
  1455. //
  1456. // Reference:
  1457. // https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_format_BGRA8888.txt
  1458. // https://www.opengl.org/registry/specs/EXT/bgra.txt
  1459. // https://www.khronos.org/registry/gles/extensions/APPLE/APPLE_texture_format_BGRA8888.txt
  1460. if (!s_extension[Extension::EXT_bgra ].m_supported
  1461. && !s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1462. {
  1463. s_textureFormat[TextureFormat::BGRA8].m_internalFmt = GL_BGRA;
  1464. }
  1465. if (!isTextureFormatValid(TextureFormat::BGRA8) )
  1466. {
  1467. // Revert back to RGBA if texture can't be created.
  1468. setTextureFormat(TextureFormat::BGRA8, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE);
  1469. }
  1470. }
  1471. if (BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  1472. || !isTextureFormatValid(TextureFormat::R8) )
  1473. {
  1474. // GL core has to use GL_R8 Issue#208, GLES2 has to use GL_LUMINANCE issue#226
  1475. s_textureFormat[TextureFormat::R8].m_internalFmt = GL_LUMINANCE;
  1476. s_textureFormat[TextureFormat::R8].m_fmt = GL_LUMINANCE;
  1477. }
  1478. for (uint32_t ii = BX_ENABLED(BX_PLATFORM_IOS) ? TextureFormat::Unknown : 0 // skip test on iOS!
  1479. ; ii < TextureFormat::Count
  1480. ; ++ii
  1481. )
  1482. {
  1483. if (TextureFormat::Unknown != ii
  1484. && TextureFormat::UnknownDepth != ii)
  1485. {
  1486. s_textureFormat[ii].m_supported = isTextureFormatValid(TextureFormat::Enum(ii) );
  1487. }
  1488. }
  1489. if (BX_ENABLED(0) )
  1490. {
  1491. // Disable all compressed texture formats. For testing only.
  1492. for (uint32_t ii = 0; ii < TextureFormat::Unknown; ++ii)
  1493. {
  1494. s_textureFormat[ii].m_supported = false;
  1495. }
  1496. }
  1497. const bool computeSupport = false
  1498. || !!(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  1499. || s_extension[Extension::ARB_compute_shader].m_supported
  1500. ;
  1501. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1502. {
  1503. uint8_t supported = 0;
  1504. supported |= s_textureFormat[ii].m_supported
  1505. ? BGFX_CAPS_FORMAT_TEXTURE_2D
  1506. | BGFX_CAPS_FORMAT_TEXTURE_3D
  1507. | BGFX_CAPS_FORMAT_TEXTURE_CUBE
  1508. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1509. ;
  1510. supported |= isTextureFormatValid(TextureFormat::Enum(ii), true)
  1511. ? BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  1512. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  1513. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  1514. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1515. ;
  1516. supported |= computeSupport
  1517. && isImageFormatValid(TextureFormat::Enum(ii) )
  1518. ? BGFX_CAPS_FORMAT_TEXTURE_IMAGE
  1519. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1520. ;
  1521. supported |= isFramebufferFormatValid(TextureFormat::Enum(ii) )
  1522. ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  1523. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1524. ;
  1525. if (NULL != glGetInternalformativ)
  1526. {
  1527. GLint maxSamples;
  1528. glGetInternalformativ(GL_RENDERBUFFER
  1529. , s_textureFormat[ii].m_internalFmt
  1530. , GL_SAMPLES
  1531. , 1
  1532. , &maxSamples
  1533. );
  1534. GLenum err = glGetError();
  1535. supported |= 0 == err && maxSamples > 0
  1536. ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA
  1537. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1538. ;
  1539. glGetInternalformativ(GL_TEXTURE_2D_MULTISAMPLE
  1540. , s_textureFormat[ii].m_internalFmt
  1541. , GL_SAMPLES
  1542. , 1
  1543. , &maxSamples
  1544. );
  1545. err = glGetError();
  1546. supported |= 0 == err && maxSamples > 0
  1547. ? BGFX_CAPS_FORMAT_TEXTURE_MSAA
  1548. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1549. ;
  1550. }
  1551. g_caps.formats[ii] = supported;
  1552. }
  1553. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1554. || s_extension[Extension::OES_texture_3D].m_supported
  1555. ? BGFX_CAPS_TEXTURE_3D
  1556. : 0
  1557. ;
  1558. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1559. || s_extension[Extension::EXT_shadow_samplers].m_supported
  1560. ? BGFX_CAPS_TEXTURE_COMPARE_ALL
  1561. : 0
  1562. ;
  1563. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1564. || s_extension[Extension::OES_vertex_half_float].m_supported
  1565. ? BGFX_CAPS_VERTEX_ATTRIB_HALF
  1566. : 0
  1567. ;
  1568. g_caps.supported |= false
  1569. || s_extension[Extension::ARB_vertex_type_2_10_10_10_rev].m_supported
  1570. || s_extension[Extension::OES_vertex_type_10_10_10_2].m_supported
  1571. ? BGFX_CAPS_VERTEX_ATTRIB_UINT10
  1572. : 0
  1573. ;
  1574. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1575. || s_extension[Extension::EXT_frag_depth].m_supported
  1576. ? BGFX_CAPS_FRAGMENT_DEPTH
  1577. : 0
  1578. ;
  1579. g_caps.supported |= s_extension[Extension::ARB_draw_buffers_blend].m_supported
  1580. ? BGFX_CAPS_BLEND_INDEPENDENT
  1581. : 0
  1582. ;
  1583. g_caps.supported |= s_extension[Extension::INTEL_fragment_shader_ordering].m_supported
  1584. ? BGFX_CAPS_FRAGMENT_ORDERING
  1585. : 0
  1586. ;
  1587. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1588. || s_extension[Extension::OES_element_index_uint].m_supported
  1589. ? BGFX_CAPS_INDEX32
  1590. : 0
  1591. ;
  1592. const bool drawIndirectSupported = false
  1593. || s_extension[Extension::AMD_multi_draw_indirect].m_supported
  1594. || s_extension[Extension::ARB_draw_indirect ].m_supported
  1595. || s_extension[Extension::ARB_multi_draw_indirect].m_supported
  1596. || s_extension[Extension::EXT_multi_draw_indirect].m_supported
  1597. ;
  1598. if (drawIndirectSupported)
  1599. {
  1600. if (NULL == glMultiDrawArraysIndirect
  1601. || NULL == glMultiDrawElementsIndirect)
  1602. {
  1603. glMultiDrawArraysIndirect = stubMultiDrawArraysIndirect;
  1604. glMultiDrawElementsIndirect = stubMultiDrawElementsIndirect;
  1605. }
  1606. }
  1607. g_caps.supported |= drawIndirectSupported
  1608. ? BGFX_CAPS_DRAW_INDIRECT
  1609. : 0
  1610. ;
  1611. if (s_extension[Extension::ARB_copy_image].m_supported
  1612. || s_extension[Extension::EXT_copy_image].m_supported
  1613. || s_extension[Extension:: NV_copy_image].m_supported
  1614. || s_extension[Extension::OES_copy_image].m_supported)
  1615. {
  1616. m_blitSupported = NULL != glCopyImageSubData;
  1617. g_caps.supported |= m_blitSupported
  1618. ? BGFX_CAPS_TEXTURE_BLIT
  1619. : 0
  1620. ;
  1621. }
  1622. g_caps.supported |= m_readBackSupported
  1623. ? BGFX_CAPS_TEXTURE_READ_BACK
  1624. : 0
  1625. ;
  1626. g_caps.maxTextureSize = uint16_t(glGet(GL_MAX_TEXTURE_SIZE) );
  1627. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1628. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1629. || s_extension[Extension::EXT_draw_buffers ].m_supported
  1630. || s_extension[Extension::WEBGL_draw_buffers].m_supported)
  1631. {
  1632. g_caps.maxFBAttachments = uint8_t(bx::uint32_min(glGet(GL_MAX_DRAW_BUFFERS)
  1633. , BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS)
  1634. );
  1635. }
  1636. // if (s_extension[Extension::ARB_clip_control].m_supported)
  1637. // {
  1638. // GL_CHECK(glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE) );
  1639. // g_caps.originBottomLeft = true;
  1640. // }
  1641. // else
  1642. {
  1643. g_caps.homogeneousDepth = true;
  1644. g_caps.originBottomLeft = true;
  1645. }
  1646. m_vaoSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1647. || s_extension[Extension::ARB_vertex_array_object].m_supported
  1648. || s_extension[Extension::OES_vertex_array_object].m_supported
  1649. ;
  1650. if (BX_ENABLED(BX_PLATFORM_NACL) )
  1651. {
  1652. m_vaoSupport &= true
  1653. && NULL != glGenVertexArrays
  1654. && NULL != glDeleteVertexArrays
  1655. && NULL != glBindVertexArray
  1656. ;
  1657. }
  1658. if (m_vaoSupport)
  1659. {
  1660. GL_CHECK(glGenVertexArrays(1, &m_vao) );
  1661. }
  1662. m_samplerObjectSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1663. || s_extension[Extension::ARB_sampler_objects].m_supported
  1664. ;
  1665. m_shadowSamplersSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1666. || s_extension[Extension::EXT_shadow_samplers].m_supported
  1667. ;
  1668. m_programBinarySupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1669. || s_extension[Extension::ARB_get_program_binary].m_supported
  1670. || s_extension[Extension::OES_get_program_binary].m_supported
  1671. || s_extension[Extension::IMG_shader_binary ].m_supported
  1672. ;
  1673. m_textureSwizzleSupport = false
  1674. || s_extension[Extension::ARB_texture_swizzle].m_supported
  1675. || s_extension[Extension::EXT_texture_swizzle].m_supported
  1676. ;
  1677. m_depthTextureSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1678. || s_extension[Extension::ANGLE_depth_texture ].m_supported
  1679. || s_extension[Extension::CHROMIUM_depth_texture ].m_supported
  1680. || s_extension[Extension::GOOGLE_depth_texture ].m_supported
  1681. || s_extension[Extension::OES_depth_texture ].m_supported
  1682. || s_extension[Extension::MOZ_WEBGL_depth_texture ].m_supported
  1683. || s_extension[Extension::WEBGL_depth_texture ].m_supported
  1684. || s_extension[Extension::WEBKIT_WEBGL_depth_texture].m_supported
  1685. ;
  1686. m_timerQuerySupport = false
  1687. || s_extension[Extension::ANGLE_timer_query ].m_supported
  1688. || s_extension[Extension::ARB_timer_query ].m_supported
  1689. || s_extension[Extension::EXT_disjoint_timer_query].m_supported
  1690. || s_extension[Extension::EXT_timer_query ].m_supported
  1691. ;
  1692. m_timerQuerySupport &= true
  1693. && NULL != glQueryCounter
  1694. && NULL != glGetQueryObjectiv
  1695. && NULL != glGetQueryObjectui64v
  1696. ;
  1697. m_occlusionQuerySupport = false
  1698. || s_extension[Extension::ARB_occlusion_query ].m_supported
  1699. || s_extension[Extension::ARB_occlusion_query2 ].m_supported
  1700. || s_extension[Extension::EXT_occlusion_query_boolean].m_supported
  1701. || s_extension[Extension::NV_occlusion_query ].m_supported
  1702. ;
  1703. m_occlusionQuerySupport &= true
  1704. && NULL != glGenQueries
  1705. && NULL != glDeleteQueries
  1706. && NULL != glBeginQuery
  1707. && NULL != glEndQuery
  1708. ;
  1709. m_atocSupport = s_extension[Extension::ARB_multisample].m_supported;
  1710. m_conservativeRasterSupport = s_extension[Extension::NV_conservative_raster].m_supported;
  1711. g_caps.supported |= 0
  1712. | (m_atocSupport ? BGFX_CAPS_ALPHA_TO_COVERAGE : 0)
  1713. | (m_conservativeRasterSupport ? BGFX_CAPS_CONSERVATIVE_RASTER : 0)
  1714. | (m_occlusionQuerySupport ? BGFX_CAPS_OCCLUSION_QUERY : 0)
  1715. | (m_depthTextureSupport ? BGFX_CAPS_TEXTURE_COMPARE_LEQUAL : 0)
  1716. | (computeSupport ? BGFX_CAPS_COMPUTE : 0)
  1717. ;
  1718. g_caps.supported |= m_glctx.getCaps();
  1719. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) )
  1720. {
  1721. m_srgbWriteControlSupport = s_extension[Extension::EXT_sRGB_write_control].m_supported;
  1722. m_borderColorSupport = s_extension[Extension::NV_texture_border_clamp].m_supported;
  1723. s_textureAddress[BGFX_TEXTURE_U_BORDER>>BGFX_TEXTURE_U_SHIFT] = s_extension[Extension::NV_texture_border_clamp].m_supported
  1724. ? GL_CLAMP_TO_BORDER
  1725. : GL_CLAMP_TO_EDGE
  1726. ;
  1727. }
  1728. if (s_extension[Extension::EXT_texture_filter_anisotropic].m_supported)
  1729. {
  1730. GL_CHECK(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &m_maxAnisotropyDefault) );
  1731. }
  1732. if (s_extension[Extension::ARB_texture_multisample].m_supported
  1733. || s_extension[Extension::ANGLE_framebuffer_multisample].m_supported)
  1734. {
  1735. GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES, &m_maxMsaa) );
  1736. }
  1737. if (s_extension[Extension::OES_read_format].m_supported
  1738. && (s_extension[Extension::IMG_read_format].m_supported || s_extension[Extension::EXT_read_format_bgra].m_supported) )
  1739. {
  1740. m_readPixelsFmt = GL_BGRA;
  1741. }
  1742. else
  1743. {
  1744. m_readPixelsFmt = GL_RGBA;
  1745. }
  1746. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1747. {
  1748. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1749. }
  1750. else
  1751. {
  1752. if (s_extension[Extension::ANGLE_instanced_arrays].m_supported
  1753. || s_extension[Extension::ARB_instanced_arrays].m_supported
  1754. || s_extension[Extension::EXT_instanced_arrays].m_supported)
  1755. {
  1756. if (NULL != glVertexAttribDivisor
  1757. && NULL != glDrawArraysInstanced
  1758. && NULL != glDrawElementsInstanced)
  1759. {
  1760. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1761. }
  1762. }
  1763. if (0 == (g_caps.supported & BGFX_CAPS_INSTANCING) )
  1764. {
  1765. glVertexAttribDivisor = stubVertexAttribDivisor;
  1766. glDrawArraysInstanced = stubDrawArraysInstanced;
  1767. glDrawElementsInstanced = stubDrawElementsInstanced;
  1768. }
  1769. }
  1770. if (s_extension[Extension::ARB_debug_output].m_supported
  1771. || s_extension[Extension::KHR_debug].m_supported)
  1772. {
  1773. if (NULL != glDebugMessageControl
  1774. && NULL != glDebugMessageInsert
  1775. && NULL != glDebugMessageCallback
  1776. && NULL != glGetDebugMessageLog)
  1777. {
  1778. GL_CHECK(glDebugMessageCallback(debugProcCb, NULL) );
  1779. GL_CHECK(glDebugMessageControl(GL_DONT_CARE
  1780. , GL_DONT_CARE
  1781. , GL_DEBUG_SEVERITY_MEDIUM
  1782. , 0
  1783. , NULL
  1784. , GL_TRUE
  1785. ) );
  1786. }
  1787. }
  1788. if (s_extension[Extension::ARB_seamless_cube_map].m_supported)
  1789. {
  1790. GL_CHECK(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS) );
  1791. }
  1792. if (NULL == glFrameTerminatorGREMEDY
  1793. || !s_extension[Extension::GREMEDY_frame_terminator].m_supported)
  1794. {
  1795. glFrameTerminatorGREMEDY = stubFrameTerminatorGREMEDY;
  1796. }
  1797. if (NULL == glInsertEventMarker
  1798. || !s_extension[Extension::EXT_debug_marker].m_supported)
  1799. {
  1800. glInsertEventMarker = (NULL != glStringMarkerGREMEDY && s_extension[Extension::GREMEDY_string_marker].m_supported)
  1801. ? stubInsertEventMarkerGREMEDY
  1802. : stubInsertEventMarker
  1803. ;
  1804. }
  1805. setGraphicsDebuggerPresent(s_extension[Extension::EXT_debug_tool].m_supported);
  1806. if (NULL == glObjectLabel)
  1807. {
  1808. glObjectLabel = stubObjectLabel;
  1809. }
  1810. if (NULL == glInvalidateFramebuffer)
  1811. {
  1812. glInvalidateFramebuffer = stubInvalidateFramebuffer;
  1813. }
  1814. if (m_timerQuerySupport)
  1815. {
  1816. m_gpuTimer.create();
  1817. }
  1818. if (m_occlusionQuerySupport)
  1819. {
  1820. m_occlusionQuery.create();
  1821. }
  1822. // Init reserved part of view name.
  1823. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1824. {
  1825. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii);
  1826. }
  1827. ovrPostReset();
  1828. BGFX_GPU_PROFILER_BIND();
  1829. }
  1830. void shutdown()
  1831. {
  1832. BGFX_GPU_PROFILER_UNBIND();
  1833. ovrPreReset();
  1834. m_ovr.shutdown();
  1835. if (m_vaoSupport)
  1836. {
  1837. GL_CHECK(glBindVertexArray(0) );
  1838. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  1839. m_vao = 0;
  1840. }
  1841. captureFinish();
  1842. invalidateCache();
  1843. if (m_timerQuerySupport)
  1844. {
  1845. m_gpuTimer.destroy();
  1846. }
  1847. if (m_occlusionQuerySupport)
  1848. {
  1849. m_occlusionQuery.destroy();
  1850. }
  1851. destroyMsaaFbo();
  1852. m_glctx.destroy();
  1853. m_flip = false;
  1854. unloadRenderDoc(m_renderdocdll);
  1855. }
  1856. RendererType::Enum getRendererType() const BX_OVERRIDE
  1857. {
  1858. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1859. {
  1860. return RendererType::OpenGL;
  1861. }
  1862. return RendererType::OpenGLES;
  1863. }
  1864. const char* getRendererName() const BX_OVERRIDE
  1865. {
  1866. return BGFX_RENDERER_OPENGL_NAME;
  1867. }
  1868. void flip(HMD& _hmd)
  1869. {
  1870. if (m_flip)
  1871. {
  1872. for (uint32_t ii = 1, num = m_numWindows; ii < num; ++ii)
  1873. {
  1874. m_glctx.swap(m_frameBuffers[m_windows[ii].idx].m_swapChain);
  1875. }
  1876. switch (m_ovr.swap(_hmd, true) )
  1877. {
  1878. case OVR::DeviceLost:
  1879. ovrPreReset();
  1880. break;
  1881. default:
  1882. break;
  1883. }
  1884. // need to swap GL render context even if OVR is enabled to get the mirror texture in the output
  1885. m_glctx.swap();
  1886. }
  1887. }
  1888. void createIndexBuffer(IndexBufferHandle _handle, Memory* _mem, uint16_t _flags) BX_OVERRIDE
  1889. {
  1890. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  1891. }
  1892. void destroyIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  1893. {
  1894. m_indexBuffers[_handle.idx].destroy();
  1895. }
  1896. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) BX_OVERRIDE
  1897. {
  1898. VertexDecl& decl = m_vertexDecls[_handle.idx];
  1899. memcpy(&decl, &_decl, sizeof(VertexDecl) );
  1900. dump(decl);
  1901. }
  1902. void destroyVertexDecl(VertexDeclHandle /*_handle*/) BX_OVERRIDE
  1903. {
  1904. }
  1905. void createVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle, uint16_t _flags) BX_OVERRIDE
  1906. {
  1907. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle, _flags);
  1908. }
  1909. void destroyVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  1910. {
  1911. m_vertexBuffers[_handle.idx].destroy();
  1912. }
  1913. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  1914. {
  1915. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  1916. }
  1917. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  1918. {
  1919. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1920. }
  1921. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  1922. {
  1923. m_indexBuffers[_handle.idx].destroy();
  1924. }
  1925. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  1926. {
  1927. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  1928. m_vertexBuffers[_handle.idx].create(_size, NULL, decl, _flags);
  1929. }
  1930. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  1931. {
  1932. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1933. }
  1934. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  1935. {
  1936. m_vertexBuffers[_handle.idx].destroy();
  1937. }
  1938. void createShader(ShaderHandle _handle, Memory* _mem) BX_OVERRIDE
  1939. {
  1940. m_shaders[_handle.idx].create(_mem);
  1941. }
  1942. void destroyShader(ShaderHandle _handle) BX_OVERRIDE
  1943. {
  1944. m_shaders[_handle.idx].destroy();
  1945. }
  1946. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) BX_OVERRIDE
  1947. {
  1948. ShaderGL dummyFragmentShader;
  1949. m_program[_handle.idx].create(m_shaders[_vsh.idx], isValid(_fsh) ? m_shaders[_fsh.idx] : dummyFragmentShader);
  1950. }
  1951. void destroyProgram(ProgramHandle _handle) BX_OVERRIDE
  1952. {
  1953. m_program[_handle.idx].destroy();
  1954. }
  1955. void createTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags, uint8_t _skip) BX_OVERRIDE
  1956. {
  1957. m_textures[_handle.idx].create(_mem, _flags, _skip);
  1958. }
  1959. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) BX_OVERRIDE
  1960. {
  1961. }
  1962. void updateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) BX_OVERRIDE
  1963. {
  1964. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  1965. }
  1966. void updateTextureEnd() BX_OVERRIDE
  1967. {
  1968. }
  1969. void readTexture(TextureHandle _handle, void* _data) BX_OVERRIDE
  1970. {
  1971. if (m_readBackSupported)
  1972. {
  1973. const TextureGL& texture = m_textures[_handle.idx];
  1974. const bool compressed = isCompressed(TextureFormat::Enum(texture.m_textureFormat) );
  1975. GL_CHECK(glBindTexture(texture.m_target, texture.m_id) );
  1976. if (compressed)
  1977. {
  1978. GL_CHECK(glGetCompressedTexImage(texture.m_target
  1979. , 0
  1980. , _data
  1981. ) );
  1982. }
  1983. else
  1984. {
  1985. GL_CHECK(glGetTexImage(texture.m_target
  1986. , 0
  1987. , texture.m_fmt
  1988. , texture.m_type
  1989. , _data
  1990. ) );
  1991. }
  1992. GL_CHECK(glBindTexture(texture.m_target, 0) );
  1993. }
  1994. }
  1995. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height) BX_OVERRIDE
  1996. {
  1997. TextureGL& texture = m_textures[_handle.idx];
  1998. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  1999. const Memory* mem = alloc(size);
  2000. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  2001. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  2002. bx::write(&writer, magic);
  2003. TextureCreate tc;
  2004. tc.m_width = _width;
  2005. tc.m_height = _height;
  2006. tc.m_sides = 0;
  2007. tc.m_depth = 0;
  2008. tc.m_numMips = 1;
  2009. tc.m_format = TextureFormat::Enum(texture.m_requestedFormat);
  2010. tc.m_cubeMap = false;
  2011. tc.m_mem = NULL;
  2012. bx::write(&writer, tc);
  2013. texture.destroy();
  2014. texture.create(mem, texture.m_flags, 0);
  2015. release(mem);
  2016. }
  2017. void overrideInternal(TextureHandle _handle, uintptr_t _ptr) BX_OVERRIDE
  2018. {
  2019. m_textures[_handle.idx].overrideInternal(_ptr);
  2020. }
  2021. uintptr_t getInternal(TextureHandle _handle) BX_OVERRIDE
  2022. {
  2023. return uintptr_t(m_textures[_handle.idx].m_id);
  2024. }
  2025. void destroyTexture(TextureHandle _handle) BX_OVERRIDE
  2026. {
  2027. m_textures[_handle.idx].destroy();
  2028. }
  2029. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const Attachment* _attachment) BX_OVERRIDE
  2030. {
  2031. m_frameBuffers[_handle.idx].create(_num, _attachment);
  2032. }
  2033. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat) BX_OVERRIDE
  2034. {
  2035. uint16_t denseIdx = m_numWindows++;
  2036. m_windows[denseIdx] = _handle;
  2037. m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _depthFormat);
  2038. }
  2039. void destroyFrameBuffer(FrameBufferHandle _handle) BX_OVERRIDE
  2040. {
  2041. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  2042. if (UINT16_MAX != denseIdx)
  2043. {
  2044. --m_numWindows;
  2045. if (m_numWindows > 1)
  2046. {
  2047. FrameBufferHandle handle = m_windows[m_numWindows];
  2048. m_windows[denseIdx] = handle;
  2049. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  2050. }
  2051. }
  2052. }
  2053. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) BX_OVERRIDE
  2054. {
  2055. if (NULL != m_uniforms[_handle.idx])
  2056. {
  2057. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  2058. }
  2059. uint32_t size = g_uniformTypeSize[_type]*_num;
  2060. void* data = BX_ALLOC(g_allocator, size);
  2061. memset(data, 0, size);
  2062. m_uniforms[_handle.idx] = data;
  2063. m_uniformReg.add(_handle, _name, m_uniforms[_handle.idx]);
  2064. }
  2065. void destroyUniform(UniformHandle _handle) BX_OVERRIDE
  2066. {
  2067. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  2068. m_uniforms[_handle.idx] = NULL;
  2069. }
  2070. void saveScreenShot(const char* _filePath) BX_OVERRIDE
  2071. {
  2072. uint32_t length = m_resolution.m_width*m_resolution.m_height*4;
  2073. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2074. uint32_t width = m_resolution.m_width;
  2075. uint32_t height = m_resolution.m_height;
  2076. GL_CHECK(glReadPixels(0
  2077. , 0
  2078. , width
  2079. , height
  2080. , m_readPixelsFmt
  2081. , GL_UNSIGNED_BYTE
  2082. , data
  2083. ) );
  2084. if (GL_RGBA == m_readPixelsFmt)
  2085. {
  2086. imageSwizzleBgra8(width, height, width*4, data, data);
  2087. }
  2088. g_callback->screenShot(_filePath
  2089. , width
  2090. , height
  2091. , width*4
  2092. , data
  2093. , length
  2094. , true
  2095. );
  2096. BX_FREE(g_allocator, data);
  2097. }
  2098. void updateViewName(uint8_t _id, const char* _name) BX_OVERRIDE
  2099. {
  2100. bx::strlcpy(&s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  2101. , _name
  2102. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  2103. );
  2104. }
  2105. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) BX_OVERRIDE
  2106. {
  2107. memcpy(m_uniforms[_loc], _data, _size);
  2108. }
  2109. void setMarker(const char* _marker, uint32_t _size) BX_OVERRIDE
  2110. {
  2111. GL_CHECK(glInsertEventMarker(_size, _marker) );
  2112. }
  2113. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) BX_OVERRIDE;
  2114. void blitSetup(TextVideoMemBlitter& _blitter) BX_OVERRIDE
  2115. {
  2116. if (0 != m_vao)
  2117. {
  2118. GL_CHECK(glBindVertexArray(m_vao) );
  2119. }
  2120. uint32_t width = m_resolution.m_width;
  2121. uint32_t height = m_resolution.m_height;
  2122. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2123. GL_CHECK(glViewport(0, 0, width, height) );
  2124. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2125. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2126. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2127. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2128. GL_CHECK(glDisable(GL_CULL_FACE) );
  2129. GL_CHECK(glDisable(GL_BLEND) );
  2130. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2131. ProgramGL& program = m_program[_blitter.m_program.idx];
  2132. GL_CHECK(glUseProgram(program.m_id) );
  2133. GL_CHECK(glUniform1i(program.m_sampler[0], 0) );
  2134. float proj[16];
  2135. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  2136. GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc
  2137. , 1
  2138. , GL_FALSE
  2139. , proj
  2140. ) );
  2141. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  2142. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_textures[_blitter.m_texture.idx].m_id) );
  2143. if (!BX_ENABLED(BX_PLATFORM_OSX) )
  2144. {
  2145. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2146. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2147. {
  2148. if (m_samplerObjectSupport)
  2149. {
  2150. GL_CHECK(glBindSampler(0, 0) );
  2151. }
  2152. }
  2153. }
  2154. }
  2155. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) BX_OVERRIDE
  2156. {
  2157. const uint32_t numVertices = _numIndices*4/6;
  2158. if (0 < numVertices)
  2159. {
  2160. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices*2, _blitter.m_ib->data);
  2161. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data);
  2162. VertexBufferGL& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  2163. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2164. IndexBufferGL& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  2165. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  2166. ProgramGL& program = m_program[_blitter.m_program.idx];
  2167. program.bindAttributes(_blitter.m_decl, 0);
  2168. GL_CHECK(glDrawElements(GL_TRIANGLES
  2169. , _numIndices
  2170. , GL_UNSIGNED_SHORT
  2171. , (void*)0
  2172. ) );
  2173. }
  2174. }
  2175. void updateResolution(const Resolution& _resolution)
  2176. {
  2177. bool recenter = !!(_resolution.m_flags & BGFX_RESET_HMD_RECENTER);
  2178. m_maxAnisotropy = !!(_resolution.m_flags & BGFX_RESET_MAXANISOTROPY)
  2179. ? m_maxAnisotropyDefault
  2180. : 0.0f
  2181. ;
  2182. if (s_extension[Extension::ARB_depth_clamp].m_supported)
  2183. {
  2184. if (!!(_resolution.m_flags & BGFX_RESET_DEPTH_CLAMP) )
  2185. {
  2186. GL_CHECK(glEnable(GL_DEPTH_CLAMP) );
  2187. }
  2188. else
  2189. {
  2190. GL_CHECK(glDisable(GL_DEPTH_CLAMP) );
  2191. }
  2192. }
  2193. uint32_t flags = _resolution.m_flags & ~(0
  2194. | BGFX_RESET_HMD_RECENTER
  2195. | BGFX_RESET_MAXANISOTROPY
  2196. | BGFX_RESET_DEPTH_CLAMP
  2197. | BGFX_RESET_SUSPEND
  2198. );
  2199. if (m_resolution.m_width != _resolution.m_width
  2200. || m_resolution.m_height != _resolution.m_height
  2201. || m_resolution.m_flags != flags)
  2202. {
  2203. flags &= ~BGFX_RESET_INTERNAL_FORCE;
  2204. m_resolution = _resolution;
  2205. m_resolution.m_flags = flags;
  2206. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  2207. m_textVideoMem.clear();
  2208. if ( (flags & BGFX_RESET_HMD)
  2209. && m_ovr.isInitialized() )
  2210. {
  2211. flags &= ~BGFX_RESET_MSAA_MASK;
  2212. }
  2213. setRenderContextSize(m_resolution.m_width
  2214. , m_resolution.m_height
  2215. , flags
  2216. );
  2217. updateCapture();
  2218. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  2219. {
  2220. m_frameBuffers[ii].postReset();
  2221. }
  2222. ovrPreReset();
  2223. ovrPostReset();
  2224. }
  2225. if (recenter)
  2226. {
  2227. m_ovr.recenter();
  2228. }
  2229. }
  2230. void setShaderUniform4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  2231. {
  2232. GL_CHECK(glUniform4fv(_regIndex
  2233. , _numRegs
  2234. , (const GLfloat*)_val
  2235. ) );
  2236. }
  2237. void setShaderUniform4x4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  2238. {
  2239. GL_CHECK(glUniformMatrix4fv(_regIndex
  2240. , _numRegs
  2241. , GL_FALSE
  2242. , (const GLfloat*)_val
  2243. ) );
  2244. }
  2245. uint32_t setFrameBuffer(FrameBufferHandle _fbh, uint32_t _height, uint16_t _discard = BGFX_CLEAR_NONE, bool _msaa = true)
  2246. {
  2247. if (isValid(m_fbh)
  2248. && m_fbh.idx != _fbh.idx
  2249. && (BGFX_CLEAR_NONE != m_fbDiscard || m_rtMsaa) )
  2250. {
  2251. FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  2252. if (m_rtMsaa)
  2253. {
  2254. frameBuffer.resolve();
  2255. }
  2256. if (BGFX_CLEAR_NONE != m_fbDiscard)
  2257. {
  2258. frameBuffer.discard(m_fbDiscard);
  2259. }
  2260. m_fbDiscard = BGFX_CLEAR_NONE;
  2261. }
  2262. m_glctx.makeCurrent(NULL);
  2263. if (!isValid(_fbh) )
  2264. {
  2265. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2266. if (m_srgbWriteControlSupport)
  2267. {
  2268. if (0 != (m_resolution.m_flags & BGFX_RESET_SRGB_BACKBUFFER) )
  2269. {
  2270. GL_CHECK(glEnable(GL_FRAMEBUFFER_SRGB) );
  2271. }
  2272. else
  2273. {
  2274. GL_CHECK(glDisable(GL_FRAMEBUFFER_SRGB) );
  2275. }
  2276. }
  2277. }
  2278. else
  2279. {
  2280. FrameBufferGL& frameBuffer = m_frameBuffers[_fbh.idx];
  2281. _height = frameBuffer.m_height;
  2282. if (UINT16_MAX != frameBuffer.m_denseIdx)
  2283. {
  2284. m_glctx.makeCurrent(frameBuffer.m_swapChain);
  2285. }
  2286. else
  2287. {
  2288. m_glctx.makeCurrent(NULL);
  2289. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer.m_fbo[0]) );
  2290. }
  2291. }
  2292. m_fbh = _fbh;
  2293. m_fbDiscard = _discard;
  2294. m_rtMsaa = _msaa;
  2295. return _height;
  2296. }
  2297. uint32_t getNumRt() const
  2298. {
  2299. if (isValid(m_fbh) )
  2300. {
  2301. const FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  2302. return frameBuffer.m_num;
  2303. }
  2304. return 1;
  2305. }
  2306. void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa)
  2307. {
  2308. if (0 == m_msaaBackBufferFbo // iOS
  2309. && 1 < _msaa)
  2310. {
  2311. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  2312. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2313. GL_CHECK(glGenRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2314. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2315. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_RGBA8, _width, _height) );
  2316. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2317. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) );
  2318. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2319. GLenum attachment = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2320. ? GL_DEPTH_STENCIL_ATTACHMENT
  2321. : GL_DEPTH_ATTACHMENT
  2322. ;
  2323. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2324. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2325. , "glCheckFramebufferStatus failed 0x%08x"
  2326. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2327. );
  2328. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2329. }
  2330. }
  2331. void destroyMsaaFbo()
  2332. {
  2333. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2334. && 0 != m_msaaBackBufferFbo)
  2335. {
  2336. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  2337. m_msaaBackBufferFbo = 0;
  2338. if (0 != m_msaaBackBufferRbos[0])
  2339. {
  2340. GL_CHECK(glDeleteRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2341. m_msaaBackBufferRbos[0] = 0;
  2342. m_msaaBackBufferRbos[1] = 0;
  2343. }
  2344. }
  2345. }
  2346. void blitMsaaFbo()
  2347. {
  2348. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2349. && 0 != m_msaaBackBufferFbo)
  2350. {
  2351. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2352. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2353. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2354. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  2355. uint32_t width = m_resolution.m_width;
  2356. uint32_t height = m_resolution.m_height;
  2357. GLenum filter = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  2358. ? GL_NEAREST
  2359. : GL_LINEAR
  2360. ;
  2361. GL_CHECK(glBlitFramebuffer(0
  2362. , 0
  2363. , width
  2364. , height
  2365. , 0
  2366. , 0
  2367. , width
  2368. , height
  2369. , GL_COLOR_BUFFER_BIT
  2370. , filter
  2371. ) );
  2372. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2373. }
  2374. }
  2375. void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _flags = 0)
  2376. {
  2377. if (_width != 0
  2378. || _height != 0)
  2379. {
  2380. if (!m_glctx.isValid() )
  2381. {
  2382. m_glctx.create(_width, _height);
  2383. #if BX_PLATFORM_IOS
  2384. // iOS: need to figure out how to deal with FBO created by context.
  2385. m_backBufferFbo = m_msaaBackBufferFbo = m_glctx.getFbo();
  2386. #endif // BX_PLATFORM_IOS
  2387. }
  2388. else
  2389. {
  2390. destroyMsaaFbo();
  2391. m_glctx.resize(_width, _height, _flags);
  2392. uint32_t msaa = (_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  2393. msaa = bx::uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  2394. createMsaaFbo(_width, _height, msaa);
  2395. }
  2396. }
  2397. m_flip = true;
  2398. }
  2399. void invalidateCache()
  2400. {
  2401. if (m_vaoSupport)
  2402. {
  2403. m_vaoStateCache.invalidate();
  2404. }
  2405. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2406. && m_samplerObjectSupport)
  2407. {
  2408. m_samplerStateCache.invalidate();
  2409. }
  2410. }
  2411. void setSamplerState(uint32_t _stage, uint32_t _numMips, uint32_t _flags, const float _rgba[4])
  2412. {
  2413. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2414. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2415. {
  2416. if (0 == (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags) )
  2417. {
  2418. const uint32_t index = (_flags & BGFX_TEXTURE_BORDER_COLOR_MASK) >> BGFX_TEXTURE_BORDER_COLOR_SHIFT;
  2419. _flags &= ~BGFX_TEXTURE_RESERVED_MASK;
  2420. _flags &= BGFX_TEXTURE_SAMPLER_BITS_MASK;
  2421. _flags |= _numMips<<BGFX_TEXTURE_RESERVED_SHIFT;
  2422. GLuint sampler;
  2423. bool hasBorderColor = false;
  2424. bx::HashMurmur2A murmur;
  2425. uint32_t hash;
  2426. murmur.begin();
  2427. murmur.add(_flags);
  2428. if (!needBorderColor(_flags) )
  2429. {
  2430. murmur.add(-1);
  2431. hash = murmur.end();
  2432. sampler = m_samplerStateCache.find(hash);
  2433. }
  2434. else
  2435. {
  2436. murmur.add(index);
  2437. hash = murmur.end();
  2438. if (NULL != _rgba)
  2439. {
  2440. hasBorderColor = true;
  2441. sampler = UINT32_MAX;
  2442. }
  2443. else
  2444. {
  2445. sampler = m_samplerStateCache.find(hash);
  2446. }
  2447. }
  2448. if (UINT32_MAX == sampler)
  2449. {
  2450. sampler = m_samplerStateCache.add(hash);
  2451. GL_CHECK(glSamplerParameteri(sampler
  2452. , GL_TEXTURE_WRAP_S
  2453. , s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]
  2454. ) );
  2455. GL_CHECK(glSamplerParameteri(sampler
  2456. , GL_TEXTURE_WRAP_T
  2457. , s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]
  2458. ) );
  2459. GL_CHECK(glSamplerParameteri(sampler
  2460. , GL_TEXTURE_WRAP_R
  2461. , s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]
  2462. ) );
  2463. GLenum minFilter;
  2464. GLenum magFilter;
  2465. getFilters(_flags, 1 < _numMips, magFilter, minFilter);
  2466. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, magFilter) );
  2467. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, minFilter) );
  2468. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2469. || m_borderColorSupport)
  2470. {
  2471. if (hasBorderColor)
  2472. {
  2473. GL_CHECK(glSamplerParameterfv(sampler, GL_TEXTURE_BORDER_COLOR, _rgba) );
  2474. }
  2475. }
  2476. if (0 != (_flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  2477. && 0.0f < m_maxAnisotropy)
  2478. {
  2479. GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy) );
  2480. }
  2481. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2482. || m_shadowSamplersSupport)
  2483. {
  2484. const uint32_t cmpFunc = (_flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  2485. if (0 == cmpFunc)
  2486. {
  2487. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  2488. }
  2489. else
  2490. {
  2491. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  2492. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  2493. }
  2494. }
  2495. }
  2496. GL_CHECK(glBindSampler(_stage, sampler) );
  2497. }
  2498. else
  2499. {
  2500. GL_CHECK(glBindSampler(_stage, 0) );
  2501. }
  2502. }
  2503. }
  2504. bool isVisible(Frame* _render, OcclusionQueryHandle _handle, bool _visible)
  2505. {
  2506. m_occlusionQuery.resolve(_render);
  2507. return _visible == (0 != _render->m_occlusion[_handle.idx]);
  2508. }
  2509. void ovrPostReset()
  2510. {
  2511. #if BGFX_CONFIG_USE_OVR
  2512. if (m_resolution.m_flags & (BGFX_RESET_HMD | BGFX_RESET_HMD_DEBUG) )
  2513. {
  2514. if (m_ovr.postReset() )
  2515. {
  2516. for (int eyeIdx = 0; eyeIdx < ovrEye_Count; eyeIdx++)
  2517. {
  2518. // eye buffers need to be initialized only once during application lifetime
  2519. if (!m_ovr.m_eyeBuffers[eyeIdx])
  2520. {
  2521. m_ovr.m_eyeBuffers[eyeIdx] = BX_NEW(g_allocator, OVRBufferGL);
  2522. m_ovr.m_eyeBuffers[eyeIdx]->create(m_ovr.m_hmd, eyeIdx);
  2523. }
  2524. }
  2525. // recreate mirror texture
  2526. m_ovr.m_mirror = BX_NEW(g_allocator, OVRMirrorGL);
  2527. m_ovr.m_mirror->create(m_ovr.m_hmd, m_resolution.m_width, m_resolution.m_height);
  2528. }
  2529. }
  2530. #endif // BGFX_CONFIG_USE_OVR
  2531. }
  2532. void ovrPreReset()
  2533. {
  2534. #if BGFX_CONFIG_USE_OVR
  2535. m_ovr.preReset();
  2536. #endif // BGFX_CONFIG_USE_OVR
  2537. }
  2538. void updateCapture()
  2539. {
  2540. if (m_resolution.m_flags&BGFX_RESET_CAPTURE)
  2541. {
  2542. m_captureSize = m_resolution.m_width*m_resolution.m_height*4;
  2543. m_capture = BX_REALLOC(g_allocator, m_capture, m_captureSize);
  2544. g_callback->captureBegin(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, TextureFormat::BGRA8, true);
  2545. }
  2546. else
  2547. {
  2548. captureFinish();
  2549. }
  2550. }
  2551. void capture()
  2552. {
  2553. if (NULL != m_capture)
  2554. {
  2555. GL_CHECK(glReadPixels(0
  2556. , 0
  2557. , m_resolution.m_width
  2558. , m_resolution.m_height
  2559. , m_readPixelsFmt
  2560. , GL_UNSIGNED_BYTE
  2561. , m_capture
  2562. ) );
  2563. if (GL_RGBA == m_readPixelsFmt)
  2564. {
  2565. imageSwizzleBgra8(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, m_capture, m_capture);
  2566. }
  2567. g_callback->captureFrame(m_capture, m_captureSize);
  2568. }
  2569. }
  2570. void captureFinish()
  2571. {
  2572. if (NULL != m_capture)
  2573. {
  2574. g_callback->captureEnd();
  2575. BX_FREE(g_allocator, m_capture);
  2576. m_capture = NULL;
  2577. m_captureSize = 0;
  2578. }
  2579. }
  2580. bool programFetchFromCache(GLuint programId, uint64_t _id)
  2581. {
  2582. _id ^= m_hash;
  2583. bool cached = false;
  2584. if (m_programBinarySupport)
  2585. {
  2586. uint32_t length = g_callback->cacheReadSize(_id);
  2587. cached = length > 0;
  2588. if (cached)
  2589. {
  2590. void* data = BX_ALLOC(g_allocator, length);
  2591. if (g_callback->cacheRead(_id, data, length) )
  2592. {
  2593. bx::MemoryReader reader(data, length);
  2594. GLenum format;
  2595. bx::read(&reader, format);
  2596. GL_CHECK(glProgramBinary(programId, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) );
  2597. }
  2598. BX_FREE(g_allocator, data);
  2599. }
  2600. #if BGFX_CONFIG_RENDERER_OPENGL
  2601. GL_CHECK(glProgramParameteri(programId, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  2602. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2603. }
  2604. return cached;
  2605. }
  2606. void programCache(GLuint programId, uint64_t _id)
  2607. {
  2608. _id ^= m_hash;
  2609. if (m_programBinarySupport)
  2610. {
  2611. GLint programLength;
  2612. GLenum format;
  2613. GL_CHECK(glGetProgramiv(programId, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  2614. if (0 < programLength)
  2615. {
  2616. uint32_t length = programLength + 4;
  2617. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2618. GL_CHECK(glGetProgramBinary(programId, programLength, NULL, &format, &data[4]) );
  2619. *(uint32_t*)data = format;
  2620. g_callback->cacheWrite(_id, data, length);
  2621. BX_FREE(g_allocator, data);
  2622. }
  2623. }
  2624. }
  2625. void commit(UniformBuffer& _uniformBuffer)
  2626. {
  2627. _uniformBuffer.reset();
  2628. for (;;)
  2629. {
  2630. uint32_t opcode = _uniformBuffer.read();
  2631. if (UniformType::End == opcode)
  2632. {
  2633. break;
  2634. }
  2635. UniformType::Enum type;
  2636. uint16_t ignore;
  2637. uint16_t num;
  2638. uint16_t copy;
  2639. UniformBuffer::decodeOpcode(opcode, type, ignore, num, copy);
  2640. const char* data;
  2641. if (copy)
  2642. {
  2643. data = _uniformBuffer.read(g_uniformTypeSize[type]*num);
  2644. }
  2645. else
  2646. {
  2647. UniformHandle handle;
  2648. memcpy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  2649. data = (const char*)m_uniforms[handle.idx];
  2650. }
  2651. uint32_t loc = _uniformBuffer.read();
  2652. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  2653. case UniformType::_uniform: \
  2654. { \
  2655. _type* value = (_type*)data; \
  2656. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  2657. } \
  2658. break;
  2659. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  2660. case UniformType::_uniform: \
  2661. { \
  2662. _type* value = (_type*)data; \
  2663. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  2664. } \
  2665. break;
  2666. switch (type)
  2667. {
  2668. // case ConstantType::Int1:
  2669. // {
  2670. // int* value = (int*)data;
  2671. // BX_TRACE("Int1 sampler %d, loc %d (num %d, copy %d)", *value, loc, num, copy);
  2672. // GL_CHECK(glUniform1iv(loc, num, value) );
  2673. // }
  2674. // break;
  2675. CASE_IMPLEMENT_UNIFORM(Int1, 1iv, I, int);
  2676. CASE_IMPLEMENT_UNIFORM(Vec4, 4fv, F, float);
  2677. CASE_IMPLEMENT_UNIFORM_T(Mat3, Matrix3fv, F, float);
  2678. CASE_IMPLEMENT_UNIFORM_T(Mat4, Matrix4fv, F, float);
  2679. case UniformType::End:
  2680. break;
  2681. default:
  2682. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy);
  2683. break;
  2684. }
  2685. #undef CASE_IMPLEMENT_UNIFORM
  2686. #undef CASE_IMPLEMENT_UNIFORM_T
  2687. }
  2688. }
  2689. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, uint32_t _height, const float _palette[][4])
  2690. {
  2691. uint32_t numMrt = 1;
  2692. FrameBufferHandle fbh = m_fbh;
  2693. if (isValid(fbh) )
  2694. {
  2695. const FrameBufferGL& fb = m_frameBuffers[fbh.idx];
  2696. numMrt = bx::uint32_max(1, fb.m_num);
  2697. }
  2698. if (1 == numMrt)
  2699. {
  2700. GLuint flags = 0;
  2701. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  2702. {
  2703. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2704. {
  2705. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[0]);
  2706. const float* rgba = _palette[index];
  2707. const float rr = rgba[0];
  2708. const float gg = rgba[1];
  2709. const float bb = rgba[2];
  2710. const float aa = rgba[3];
  2711. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2712. }
  2713. else
  2714. {
  2715. float rr = _clear.m_index[0]*1.0f/255.0f;
  2716. float gg = _clear.m_index[1]*1.0f/255.0f;
  2717. float bb = _clear.m_index[2]*1.0f/255.0f;
  2718. float aa = _clear.m_index[3]*1.0f/255.0f;
  2719. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2720. }
  2721. flags |= GL_COLOR_BUFFER_BIT;
  2722. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2723. }
  2724. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2725. {
  2726. flags |= GL_DEPTH_BUFFER_BIT;
  2727. GL_CHECK(glClearDepth(_clear.m_depth) );
  2728. GL_CHECK(glDepthMask(GL_TRUE) );
  2729. }
  2730. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2731. {
  2732. flags |= GL_STENCIL_BUFFER_BIT;
  2733. GL_CHECK(glClearStencil(_clear.m_stencil) );
  2734. }
  2735. if (0 != flags)
  2736. {
  2737. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  2738. GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) );
  2739. GL_CHECK(glClear(flags) );
  2740. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2741. }
  2742. }
  2743. else
  2744. {
  2745. const GLuint defaultVao = m_vao;
  2746. if (0 != defaultVao)
  2747. {
  2748. GL_CHECK(glBindVertexArray(defaultVao) );
  2749. }
  2750. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2751. GL_CHECK(glDisable(GL_CULL_FACE) );
  2752. GL_CHECK(glDisable(GL_BLEND) );
  2753. GLboolean colorMask = !!(BGFX_CLEAR_COLOR & _clear.m_flags);
  2754. GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) );
  2755. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2756. {
  2757. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2758. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2759. GL_CHECK(glDepthMask(GL_TRUE) );
  2760. }
  2761. else
  2762. {
  2763. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2764. }
  2765. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2766. {
  2767. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  2768. GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) );
  2769. GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) );
  2770. }
  2771. else
  2772. {
  2773. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2774. }
  2775. VertexBufferGL& vb = m_vertexBuffers[_clearQuad.m_vb->handle.idx];
  2776. VertexDecl& vertexDecl = m_vertexDecls[_clearQuad.m_vb->decl.idx];
  2777. {
  2778. struct Vertex
  2779. {
  2780. float m_x;
  2781. float m_y;
  2782. float m_z;
  2783. };
  2784. Vertex* vertex = (Vertex*)_clearQuad.m_vb->data;
  2785. BX_CHECK(vertexDecl.m_stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", vertexDecl.m_stride, sizeof(Vertex) );
  2786. const float depth = _clear.m_depth * 2.0f - 1.0f;
  2787. vertex->m_x = -1.0f;
  2788. vertex->m_y = -1.0f;
  2789. vertex->m_z = depth;
  2790. vertex++;
  2791. vertex->m_x = 1.0f;
  2792. vertex->m_y = -1.0f;
  2793. vertex->m_z = depth;
  2794. vertex++;
  2795. vertex->m_x = -1.0f;
  2796. vertex->m_y = 1.0f;
  2797. vertex->m_z = depth;
  2798. vertex++;
  2799. vertex->m_x = 1.0f;
  2800. vertex->m_y = 1.0f;
  2801. vertex->m_z = depth;
  2802. }
  2803. vb.update(0, 4*_clearQuad.m_decl.m_stride, _clearQuad.m_vb->data);
  2804. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2805. ProgramGL& program = m_program[_clearQuad.m_program[numMrt-1].idx];
  2806. GL_CHECK(glUseProgram(program.m_id) );
  2807. program.bindAttributes(vertexDecl, 0);
  2808. float mrtClear[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  2809. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2810. {
  2811. for (uint32_t ii = 0; ii < numMrt; ++ii)
  2812. {
  2813. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[ii]);
  2814. memcpy(mrtClear[ii], _palette[index], 16);
  2815. }
  2816. }
  2817. else
  2818. {
  2819. float rgba[4] =
  2820. {
  2821. _clear.m_index[0] * 1.0f / 255.0f,
  2822. _clear.m_index[1] * 1.0f / 255.0f,
  2823. _clear.m_index[2] * 1.0f / 255.0f,
  2824. _clear.m_index[3] * 1.0f / 255.0f,
  2825. };
  2826. for (uint32_t ii = 0; ii < numMrt; ++ii)
  2827. {
  2828. memcpy(mrtClear[ii], rgba, 16);
  2829. }
  2830. }
  2831. GL_CHECK(glUniform4fv(0, numMrt, mrtClear[0]) );
  2832. GL_CHECK(glDrawArrays(GL_TRIANGLE_STRIP
  2833. , 0
  2834. , 4
  2835. ) );
  2836. }
  2837. }
  2838. void* m_renderdocdll;
  2839. uint16_t m_numWindows;
  2840. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2841. IndexBufferGL m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  2842. VertexBufferGL m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  2843. ShaderGL m_shaders[BGFX_CONFIG_MAX_SHADERS];
  2844. ProgramGL m_program[BGFX_CONFIG_MAX_PROGRAMS];
  2845. TextureGL m_textures[BGFX_CONFIG_MAX_TEXTURES];
  2846. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  2847. FrameBufferGL m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2848. UniformRegistry m_uniformReg;
  2849. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  2850. TimerQueryGL m_gpuTimer;
  2851. OcclusionQueryGL m_occlusionQuery;
  2852. VaoStateCache m_vaoStateCache;
  2853. SamplerStateCache m_samplerStateCache;
  2854. TextVideoMem m_textVideoMem;
  2855. bool m_rtMsaa;
  2856. FrameBufferHandle m_fbh;
  2857. uint16_t m_fbDiscard;
  2858. Resolution m_resolution;
  2859. void* m_capture;
  2860. uint32_t m_captureSize;
  2861. float m_maxAnisotropy;
  2862. float m_maxAnisotropyDefault;
  2863. int32_t m_maxMsaa;
  2864. GLuint m_vao;
  2865. bool m_blitSupported;
  2866. bool m_readBackSupported;
  2867. bool m_vaoSupport;
  2868. bool m_samplerObjectSupport;
  2869. bool m_shadowSamplersSupport;
  2870. bool m_srgbWriteControlSupport;
  2871. bool m_borderColorSupport;
  2872. bool m_programBinarySupport;
  2873. bool m_textureSwizzleSupport;
  2874. bool m_depthTextureSupport;
  2875. bool m_timerQuerySupport;
  2876. bool m_occlusionQuerySupport;
  2877. bool m_atocSupport;
  2878. bool m_conservativeRasterSupport;
  2879. bool m_flip;
  2880. uint64_t m_hash;
  2881. GLenum m_readPixelsFmt;
  2882. GLuint m_backBufferFbo;
  2883. GLuint m_msaaBackBufferFbo;
  2884. GLuint m_msaaBackBufferRbos[2];
  2885. GlContext m_glctx;
  2886. const char* m_vendor;
  2887. const char* m_renderer;
  2888. const char* m_version;
  2889. const char* m_glslVersion;
  2890. OVR m_ovr;
  2891. };
  2892. RendererContextGL* s_renderGL;
  2893. RendererContextI* rendererCreate()
  2894. {
  2895. s_renderGL = BX_NEW(g_allocator, RendererContextGL);
  2896. s_renderGL->init();
  2897. return s_renderGL;
  2898. }
  2899. void rendererDestroy()
  2900. {
  2901. s_renderGL->shutdown();
  2902. BX_DELETE(g_allocator, s_renderGL);
  2903. s_renderGL = NULL;
  2904. }
  2905. #if BGFX_CONFIG_USE_OVR
  2906. void OVRBufferGL::create(const ovrSession& _session, int _eyeIdx)
  2907. {
  2908. ovrHmdDesc hmdDesc = ovr_GetHmdDesc(_session);
  2909. m_eyeTextureSize = ovr_GetFovTextureSize(_session, ovrEyeType(_eyeIdx), hmdDesc.DefaultEyeFov[_eyeIdx], 1.0f);
  2910. ovrTextureSwapChainDesc desc = {};
  2911. desc.Type = ovrTexture_2D;
  2912. desc.ArraySize = 1;
  2913. desc.Width = m_eyeTextureSize.w;
  2914. desc.Height = m_eyeTextureSize.h;
  2915. desc.MipLevels = 1;
  2916. desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
  2917. desc.SampleCount = 1;
  2918. desc.StaticImage = ovrFalse;
  2919. ovr_CreateTextureSwapChainGL(_session, &desc, &m_textureSwapChain);
  2920. int textureCount = 0;
  2921. ovr_GetTextureSwapChainLength(_session, m_textureSwapChain, &textureCount);
  2922. for (int j = 0; j < textureCount; ++j)
  2923. {
  2924. GLuint chainTexId;
  2925. ovr_GetTextureSwapChainBufferGL(_session, m_textureSwapChain, j, &chainTexId);
  2926. GL_CHECK(glBindTexture(GL_TEXTURE_2D, chainTexId) );
  2927. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
  2928. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
  2929. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  2930. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  2931. }
  2932. GL_CHECK(glGenFramebuffers(1, &m_eyeFbo) );
  2933. // create depth buffer
  2934. GL_CHECK(glGenTextures(1, &m_depthBuffer) );
  2935. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_depthBuffer) );
  2936. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
  2937. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
  2938. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  2939. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  2940. GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, m_eyeTextureSize.w, m_eyeTextureSize.h, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL) );
  2941. }
  2942. void OVRBufferGL::render(const ovrSession& _session)
  2943. {
  2944. // set the current eye texture in swap chain
  2945. int curIndex;
  2946. ovr_GetTextureSwapChainCurrentIndex(_session, m_textureSwapChain, &curIndex);
  2947. ovr_GetTextureSwapChainBufferGL(_session, m_textureSwapChain, curIndex, &m_eyeTexId);
  2948. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_eyeFbo) );
  2949. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_eyeTexId, 0) );
  2950. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthBuffer, 0) );
  2951. GL_CHECK(glViewport(0, 0, m_eyeTextureSize.w, m_eyeTextureSize.h) );
  2952. GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) );
  2953. }
  2954. void OVRBufferGL::destroy(const ovrSession& _session)
  2955. {
  2956. GL_CHECK(glDeleteFramebuffers(1, &m_eyeFbo) );
  2957. GL_CHECK(glDeleteTextures(1, &m_depthBuffer) );
  2958. ovr_DestroyTextureSwapChain(_session, m_textureSwapChain);
  2959. }
  2960. void OVRMirrorGL::create(const ovrSession& _session, int _width, int _height)
  2961. {
  2962. memset(&m_mirrorTextureDesc, 0, sizeof(m_mirrorTextureDesc) );
  2963. m_mirrorTextureDesc.Width = _width;
  2964. m_mirrorTextureDesc.Height = _height;
  2965. m_mirrorTextureDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
  2966. ovr_CreateMirrorTextureGL(_session, &m_mirrorTextureDesc, &m_mirrorTexture);
  2967. // Fallback to doing nothing if mirror was not created. This is to prevent errors with fast window resizes
  2968. if (!m_mirrorTexture)
  2969. return;
  2970. // Configure the mirror read buffer
  2971. GLuint texId;
  2972. ovr_GetMirrorTextureBufferGL(_session, m_mirrorTexture, &texId);
  2973. GL_CHECK(glGenFramebuffers(1, &m_mirrorFBO) );
  2974. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_mirrorFBO) );
  2975. GL_CHECK(glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texId, 0) );
  2976. GL_CHECK(glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0) );
  2977. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) );
  2978. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  2979. {
  2980. GL_CHECK(glDeleteFramebuffers(1, &m_mirrorFBO) );
  2981. BX_CHECK(false, "Could not initialize VR buffers!");
  2982. }
  2983. }
  2984. void OVRMirrorGL::destroy(const ovrSession& _session)
  2985. {
  2986. if (NULL != m_mirrorTexture)
  2987. {
  2988. GL_CHECK(glDeleteFramebuffers(1, &m_mirrorFBO) );
  2989. ovr_DestroyMirrorTexture(_session, m_mirrorTexture);
  2990. m_mirrorTexture = NULL;
  2991. }
  2992. }
  2993. void OVRMirrorGL::blit(const ovrSession& /*_session*/)
  2994. {
  2995. if (NULL != m_mirrorTexture)
  2996. {
  2997. // Blit mirror texture to back buffer
  2998. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_mirrorFBO) );
  2999. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  3000. GLint width = m_mirrorTextureDesc.Width;
  3001. GLint height = m_mirrorTextureDesc.Height;
  3002. GL_CHECK(glBlitFramebuffer(0, height, width, 0, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST) );
  3003. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) );
  3004. }
  3005. }
  3006. #endif // BGFX_CONFIG_USE_OVR
  3007. const char* glslTypeName(GLuint _type)
  3008. {
  3009. #define GLSL_TYPE(_ty) case _ty: return #_ty
  3010. switch (_type)
  3011. {
  3012. GLSL_TYPE(GL_INT);
  3013. GLSL_TYPE(GL_INT_VEC2);
  3014. GLSL_TYPE(GL_INT_VEC3);
  3015. GLSL_TYPE(GL_INT_VEC4);
  3016. GLSL_TYPE(GL_UNSIGNED_INT);
  3017. GLSL_TYPE(GL_UNSIGNED_INT_VEC2);
  3018. GLSL_TYPE(GL_UNSIGNED_INT_VEC3);
  3019. GLSL_TYPE(GL_UNSIGNED_INT_VEC4);
  3020. GLSL_TYPE(GL_FLOAT);
  3021. GLSL_TYPE(GL_FLOAT_VEC2);
  3022. GLSL_TYPE(GL_FLOAT_VEC3);
  3023. GLSL_TYPE(GL_FLOAT_VEC4);
  3024. GLSL_TYPE(GL_FLOAT_MAT2);
  3025. GLSL_TYPE(GL_FLOAT_MAT3);
  3026. GLSL_TYPE(GL_FLOAT_MAT4);
  3027. GLSL_TYPE(GL_SAMPLER_2D);
  3028. GLSL_TYPE(GL_INT_SAMPLER_2D);
  3029. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D);
  3030. GLSL_TYPE(GL_SAMPLER_3D);
  3031. GLSL_TYPE(GL_INT_SAMPLER_3D);
  3032. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_3D);
  3033. GLSL_TYPE(GL_SAMPLER_CUBE);
  3034. GLSL_TYPE(GL_INT_SAMPLER_CUBE);
  3035. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_CUBE);
  3036. GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  3037. GLSL_TYPE(GL_IMAGE_1D);
  3038. GLSL_TYPE(GL_INT_IMAGE_1D);
  3039. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_1D);
  3040. GLSL_TYPE(GL_IMAGE_2D);
  3041. GLSL_TYPE(GL_INT_IMAGE_2D);
  3042. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_2D);
  3043. GLSL_TYPE(GL_IMAGE_3D);
  3044. GLSL_TYPE(GL_INT_IMAGE_3D);
  3045. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_3D);
  3046. GLSL_TYPE(GL_IMAGE_CUBE);
  3047. GLSL_TYPE(GL_INT_IMAGE_CUBE);
  3048. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_CUBE);
  3049. }
  3050. #undef GLSL_TYPE
  3051. BX_CHECK(false, "Unknown GLSL type? %x", _type);
  3052. return "UNKNOWN GLSL TYPE!";
  3053. }
  3054. const char* glEnumName(GLenum _enum)
  3055. {
  3056. #define GLENUM(_ty) case _ty: return #_ty
  3057. switch (_enum)
  3058. {
  3059. GLENUM(GL_TEXTURE);
  3060. GLENUM(GL_RENDERBUFFER);
  3061. GLENUM(GL_INVALID_ENUM);
  3062. GLENUM(GL_INVALID_FRAMEBUFFER_OPERATION);
  3063. GLENUM(GL_INVALID_VALUE);
  3064. GLENUM(GL_INVALID_OPERATION);
  3065. GLENUM(GL_OUT_OF_MEMORY);
  3066. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
  3067. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
  3068. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
  3069. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
  3070. GLENUM(GL_FRAMEBUFFER_UNSUPPORTED);
  3071. }
  3072. #undef GLENUM
  3073. BX_WARN(false, "Unknown enum? %x", _enum);
  3074. return "<GLenum?>";
  3075. }
  3076. UniformType::Enum convertGlType(GLenum _type)
  3077. {
  3078. switch (_type)
  3079. {
  3080. case GL_INT:
  3081. case GL_UNSIGNED_INT:
  3082. return UniformType::Int1;
  3083. case GL_FLOAT:
  3084. case GL_FLOAT_VEC2:
  3085. case GL_FLOAT_VEC3:
  3086. case GL_FLOAT_VEC4:
  3087. return UniformType::Vec4;
  3088. case GL_FLOAT_MAT2:
  3089. break;
  3090. case GL_FLOAT_MAT3:
  3091. return UniformType::Mat3;
  3092. case GL_FLOAT_MAT4:
  3093. return UniformType::Mat4;
  3094. case GL_SAMPLER_2D:
  3095. case GL_INT_SAMPLER_2D:
  3096. case GL_UNSIGNED_INT_SAMPLER_2D:
  3097. case GL_SAMPLER_3D:
  3098. case GL_INT_SAMPLER_3D:
  3099. case GL_UNSIGNED_INT_SAMPLER_3D:
  3100. case GL_SAMPLER_CUBE:
  3101. case GL_INT_SAMPLER_CUBE:
  3102. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  3103. case GL_SAMPLER_2D_SHADOW:
  3104. case GL_IMAGE_1D:
  3105. case GL_INT_IMAGE_1D:
  3106. case GL_UNSIGNED_INT_IMAGE_1D:
  3107. case GL_IMAGE_2D:
  3108. case GL_INT_IMAGE_2D:
  3109. case GL_UNSIGNED_INT_IMAGE_2D:
  3110. case GL_IMAGE_3D:
  3111. case GL_INT_IMAGE_3D:
  3112. case GL_UNSIGNED_INT_IMAGE_3D:
  3113. case GL_IMAGE_CUBE:
  3114. case GL_INT_IMAGE_CUBE:
  3115. case GL_UNSIGNED_INT_IMAGE_CUBE:
  3116. return UniformType::Int1;
  3117. };
  3118. BX_CHECK(false, "Unrecognized GL type 0x%04x.", _type);
  3119. return UniformType::End;
  3120. }
  3121. void ProgramGL::create(const ShaderGL& _vsh, const ShaderGL& _fsh)
  3122. {
  3123. m_id = glCreateProgram();
  3124. BX_TRACE("Program create: GL%d: GL%d, GL%d", m_id, _vsh.m_id, _fsh.m_id);
  3125. const uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  3126. const bool cached = s_renderGL->programFetchFromCache(m_id, id);
  3127. if (!cached)
  3128. {
  3129. GLint linked = 0;
  3130. if (0 != _vsh.m_id)
  3131. {
  3132. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  3133. if (0 != _fsh.m_id)
  3134. {
  3135. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  3136. }
  3137. GL_CHECK(glLinkProgram(m_id) );
  3138. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  3139. if (0 == linked)
  3140. {
  3141. char log[1024];
  3142. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  3143. BX_TRACE("%d: %s", linked, log);
  3144. }
  3145. }
  3146. if (0 == linked)
  3147. {
  3148. BX_WARN(0 != _vsh.m_id, "Invalid vertex/compute shader.");
  3149. GL_CHECK(glDeleteProgram(m_id) );
  3150. m_used[0] = Attrib::Count;
  3151. m_id = 0;
  3152. return;
  3153. }
  3154. s_renderGL->programCache(m_id, id);
  3155. }
  3156. init();
  3157. if (!cached)
  3158. {
  3159. // Must be after init, otherwise init might fail to lookup shader
  3160. // info (NVIDIA Tegra 3 OpenGL ES 2.0 14.01003).
  3161. GL_CHECK(glDetachShader(m_id, _vsh.m_id) );
  3162. if (0 != _fsh.m_id)
  3163. {
  3164. GL_CHECK(glDetachShader(m_id, _fsh.m_id) );
  3165. }
  3166. }
  3167. }
  3168. void ProgramGL::destroy()
  3169. {
  3170. if (NULL != m_constantBuffer)
  3171. {
  3172. UniformBuffer::destroy(m_constantBuffer);
  3173. m_constantBuffer = NULL;
  3174. }
  3175. m_numPredefined = 0;
  3176. if (0 != m_id)
  3177. {
  3178. GL_CHECK(glUseProgram(0) );
  3179. GL_CHECK(glDeleteProgram(m_id) );
  3180. m_id = 0;
  3181. }
  3182. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3183. }
  3184. void ProgramGL::init()
  3185. {
  3186. GLint activeAttribs = 0;
  3187. GLint activeUniforms = 0;
  3188. GLint activeBuffers = 0;
  3189. #if BGFX_CONFIG_RENDERER_OPENGL >= 31
  3190. GL_CHECK(glBindFragDataLocation(m_id, 0, "bgfx_FragColor") );
  3191. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
  3192. bool piqSupported = true
  3193. && s_extension[Extension::ARB_program_interface_query ].m_supported
  3194. && s_extension[Extension::ARB_shader_storage_buffer_object].m_supported
  3195. ;
  3196. if (piqSupported)
  3197. {
  3198. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &activeAttribs ) );
  3199. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_ACTIVE_RESOURCES, &activeUniforms) );
  3200. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_BUFFER_VARIABLE, GL_ACTIVE_RESOURCES, &activeBuffers ) );
  3201. }
  3202. else
  3203. {
  3204. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs ) );
  3205. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  3206. }
  3207. GLint max0, max1;
  3208. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  3209. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  3210. uint32_t maxLength = bx::uint32_max(max0, max1);
  3211. char* name = (char*)alloca(maxLength + 1);
  3212. BX_TRACE("Program %d", m_id);
  3213. BX_TRACE("Attributes (%d):", activeAttribs);
  3214. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  3215. {
  3216. GLint size;
  3217. GLenum type;
  3218. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  3219. BX_TRACE("\t%s %s is at location %d"
  3220. , glslTypeName(type)
  3221. , name
  3222. , glGetAttribLocation(m_id, name)
  3223. );
  3224. }
  3225. m_numPredefined = 0;
  3226. m_numSamplers = 0;
  3227. BX_TRACE("Uniforms (%d):", activeUniforms);
  3228. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  3229. {
  3230. struct VariableInfo
  3231. {
  3232. GLenum type;
  3233. GLint loc;
  3234. GLint num;
  3235. };
  3236. VariableInfo vi;
  3237. GLenum props[] ={ GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE };
  3238. GLenum gltype;
  3239. GLint num;
  3240. GLint loc;
  3241. if (piqSupported)
  3242. {
  3243. GL_CHECK(glGetProgramResourceiv(m_id
  3244. , GL_UNIFORM
  3245. , ii
  3246. , BX_COUNTOF(props)
  3247. , props
  3248. , BX_COUNTOF(props)
  3249. , NULL
  3250. , (GLint*)&vi
  3251. ) );
  3252. GL_CHECK(glGetProgramResourceName(m_id
  3253. , GL_UNIFORM
  3254. , ii
  3255. , maxLength + 1
  3256. , NULL
  3257. , name
  3258. ) );
  3259. gltype = vi.type;
  3260. loc = vi.loc;
  3261. num = vi.num;
  3262. }
  3263. else
  3264. {
  3265. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  3266. loc = glGetUniformLocation(m_id, name);
  3267. }
  3268. num = bx::uint32_max(num, 1);
  3269. int offset = 0;
  3270. char* array = strchr(name, '[');
  3271. if (NULL != array)
  3272. {
  3273. BX_TRACE("--- %s", name);
  3274. *array = '\0';
  3275. array++;
  3276. char* end = strchr(array, ']');
  3277. if (NULL != end)
  3278. { // Some devices (Amazon Fire) might not return terminating brace.
  3279. *end = '\0';
  3280. offset = atoi(array);
  3281. }
  3282. }
  3283. switch (gltype)
  3284. {
  3285. case GL_SAMPLER_2D:
  3286. case GL_INT_SAMPLER_2D:
  3287. case GL_UNSIGNED_INT_SAMPLER_2D:
  3288. case GL_SAMPLER_3D:
  3289. case GL_INT_SAMPLER_3D:
  3290. case GL_UNSIGNED_INT_SAMPLER_3D:
  3291. case GL_SAMPLER_CUBE:
  3292. case GL_INT_SAMPLER_CUBE:
  3293. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  3294. case GL_SAMPLER_2D_SHADOW:
  3295. case GL_IMAGE_1D:
  3296. case GL_INT_IMAGE_1D:
  3297. case GL_UNSIGNED_INT_IMAGE_1D:
  3298. case GL_IMAGE_2D:
  3299. case GL_INT_IMAGE_2D:
  3300. case GL_UNSIGNED_INT_IMAGE_2D:
  3301. case GL_IMAGE_3D:
  3302. case GL_INT_IMAGE_3D:
  3303. case GL_UNSIGNED_INT_IMAGE_3D:
  3304. case GL_IMAGE_CUBE:
  3305. case GL_INT_IMAGE_CUBE:
  3306. case GL_UNSIGNED_INT_IMAGE_CUBE:
  3307. if (m_numSamplers < BX_COUNTOF(m_sampler) )
  3308. {
  3309. BX_TRACE("Sampler #%d at location %d.", m_numSamplers, loc);
  3310. m_sampler[m_numSamplers] = loc;
  3311. m_numSamplers++;
  3312. }
  3313. else
  3314. {
  3315. BX_TRACE("Too many samplers (max: %d)! Sampler at location %d."
  3316. , BX_COUNTOF(m_sampler)
  3317. , loc
  3318. );
  3319. }
  3320. break;
  3321. default:
  3322. break;
  3323. }
  3324. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  3325. if (PredefinedUniform::Count != predefined)
  3326. {
  3327. m_predefined[m_numPredefined].m_loc = loc;
  3328. m_predefined[m_numPredefined].m_count = uint16_t(num);
  3329. m_predefined[m_numPredefined].m_type = uint8_t(predefined);
  3330. m_numPredefined++;
  3331. }
  3332. else
  3333. {
  3334. const UniformInfo* info = s_renderGL->m_uniformReg.find(name);
  3335. BX_WARN(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  3336. if (NULL != info)
  3337. {
  3338. if (NULL == m_constantBuffer)
  3339. {
  3340. m_constantBuffer = UniformBuffer::create(1024);
  3341. }
  3342. UniformType::Enum type = convertGlType(gltype);
  3343. m_constantBuffer->writeUniformHandle(type, 0, info->m_handle, uint16_t(num) );
  3344. m_constantBuffer->write(loc);
  3345. BX_TRACE("store %s %d", name, info->m_handle);
  3346. }
  3347. }
  3348. BX_TRACE("\tuniform %s %s%s is at location %d, size %d, offset %d"
  3349. , glslTypeName(gltype)
  3350. , name
  3351. , PredefinedUniform::Count != predefined ? "*" : ""
  3352. , loc
  3353. , num
  3354. , offset
  3355. );
  3356. BX_UNUSED(offset);
  3357. }
  3358. if (NULL != m_constantBuffer)
  3359. {
  3360. m_constantBuffer->finish();
  3361. }
  3362. if (piqSupported)
  3363. {
  3364. struct VariableInfo
  3365. {
  3366. GLenum type;
  3367. };
  3368. VariableInfo vi;
  3369. GLenum props[] = { GL_TYPE };
  3370. BX_TRACE("Buffers (%d):", activeBuffers);
  3371. for (int32_t ii = 0; ii < activeBuffers; ++ii)
  3372. {
  3373. GL_CHECK(glGetProgramResourceiv(m_id
  3374. , GL_BUFFER_VARIABLE
  3375. , ii
  3376. , BX_COUNTOF(props)
  3377. , props
  3378. , BX_COUNTOF(props)
  3379. , NULL
  3380. , (GLint*)&vi
  3381. ) );
  3382. GL_CHECK(glGetProgramResourceName(m_id
  3383. , GL_BUFFER_VARIABLE
  3384. , ii
  3385. , maxLength + 1
  3386. , NULL
  3387. , name
  3388. ) );
  3389. BX_TRACE("\t%s %s at %d"
  3390. , glslTypeName(vi.type)
  3391. , name
  3392. , 0 //vi.loc
  3393. );
  3394. }
  3395. }
  3396. memset(m_attributes, 0xff, sizeof(m_attributes) );
  3397. uint32_t used = 0;
  3398. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  3399. {
  3400. GLint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  3401. if (-1 != loc)
  3402. {
  3403. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  3404. m_attributes[ii] = loc;
  3405. m_used[used++] = ii;
  3406. }
  3407. }
  3408. BX_CHECK(used < BX_COUNTOF(m_used), "Out of bounds %d > array size %d."
  3409. , used
  3410. , BX_COUNTOF(m_used)
  3411. );
  3412. m_used[used] = Attrib::Count;
  3413. used = 0;
  3414. for (uint32_t ii = 0; ii < BX_COUNTOF(s_instanceDataName); ++ii)
  3415. {
  3416. GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]);
  3417. if (GLuint(-1) != loc )
  3418. {
  3419. BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc);
  3420. m_instanceData[used++] = loc;
  3421. }
  3422. }
  3423. BX_CHECK(used < BX_COUNTOF(m_instanceData), "Out of bounds %d > array size %d."
  3424. , used
  3425. , BX_COUNTOF(m_instanceData)
  3426. );
  3427. m_instanceData[used] = 0xffff;
  3428. }
  3429. void ProgramGL::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex) const
  3430. {
  3431. for (uint32_t ii = 0; Attrib::Count != m_used[ii]; ++ii)
  3432. {
  3433. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  3434. GLint loc = m_attributes[attr];
  3435. uint8_t num;
  3436. AttribType::Enum type;
  3437. bool normalized;
  3438. bool asInt;
  3439. _vertexDecl.decode(attr, num, type, normalized, asInt);
  3440. if (-1 != loc)
  3441. {
  3442. if (UINT16_MAX != _vertexDecl.m_attributes[attr])
  3443. {
  3444. GL_CHECK(glEnableVertexAttribArray(loc) );
  3445. GL_CHECK(glVertexAttribDivisor(loc, 0) );
  3446. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  3447. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 30) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  3448. && (AttribType::Uint8 == type || AttribType::Int16 == type)
  3449. && !normalized)
  3450. {
  3451. GL_CHECK(glVertexAttribIPointer(loc
  3452. , num
  3453. , s_attribType[type]
  3454. , _vertexDecl.m_stride
  3455. , (void*)(uintptr_t)baseVertex)
  3456. );
  3457. }
  3458. else
  3459. {
  3460. GL_CHECK(glVertexAttribPointer(loc
  3461. , num
  3462. , s_attribType[type]
  3463. , normalized
  3464. , _vertexDecl.m_stride
  3465. , (void*)(uintptr_t)baseVertex)
  3466. );
  3467. }
  3468. }
  3469. else
  3470. {
  3471. GL_CHECK(glDisableVertexAttribArray(loc) );
  3472. }
  3473. }
  3474. }
  3475. }
  3476. void ProgramGL::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const
  3477. {
  3478. uint32_t baseVertex = _baseVertex;
  3479. for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  3480. {
  3481. GLint loc = m_instanceData[ii];
  3482. GL_CHECK(glEnableVertexAttribArray(loc) );
  3483. GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) );
  3484. GL_CHECK(glVertexAttribDivisor(loc, 1) );
  3485. baseVertex += 16;
  3486. }
  3487. }
  3488. void IndexBufferGL::destroy()
  3489. {
  3490. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  3491. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3492. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3493. }
  3494. void VertexBufferGL::destroy()
  3495. {
  3496. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  3497. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3498. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3499. }
  3500. static void texImage(GLenum _target, GLint _level, GLint _internalFormat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLenum _format, GLenum _type, const GLvoid* _data)
  3501. {
  3502. if (_target == GL_TEXTURE_3D)
  3503. {
  3504. GL_CHECK(glTexImage3D(_target, _level, _internalFormat, _width, _height, _depth, _border, _format, _type, _data) );
  3505. }
  3506. else
  3507. {
  3508. BX_UNUSED(_depth);
  3509. GL_CHECK(glTexImage2D(_target, _level, _internalFormat, _width, _height, _border, _format, _type, _data) );
  3510. }
  3511. }
  3512. static void texSubImage(GLenum _target, GLint _level, GLint _xoffset, GLint _yoffset, GLint _zoffset, GLsizei _width, GLsizei _height, GLsizei _depth, GLenum _format, GLenum _type, const GLvoid* _data)
  3513. {
  3514. if (_target == GL_TEXTURE_3D)
  3515. {
  3516. GL_CHECK(glTexSubImage3D(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _type, _data) );
  3517. }
  3518. else
  3519. {
  3520. BX_UNUSED(_zoffset, _depth);
  3521. GL_CHECK(glTexSubImage2D(_target, _level, _xoffset, _yoffset, _width, _height, _format, _type, _data) );
  3522. }
  3523. }
  3524. static void compressedTexImage(GLenum _target, GLint _level, GLenum _internalformat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLsizei _imageSize, const GLvoid* _data)
  3525. {
  3526. if (_target == GL_TEXTURE_3D)
  3527. {
  3528. GL_CHECK(glCompressedTexImage3D(_target, _level, _internalformat, _width, _height, _depth, _border, _imageSize, _data) );
  3529. }
  3530. else
  3531. {
  3532. BX_UNUSED(_depth);
  3533. GL_CHECK(glCompressedTexImage2D(_target, _level, _internalformat, _width, _height, _border, _imageSize, _data) );
  3534. }
  3535. }
  3536. static void compressedTexSubImage(GLenum _target, GLint _level, GLint _xoffset, GLint _yoffset, GLint _zoffset, GLsizei _width, GLsizei _height, GLsizei _depth, GLenum _format, GLsizei _imageSize, const GLvoid* _data)
  3537. {
  3538. if (_target == GL_TEXTURE_3D)
  3539. {
  3540. GL_CHECK(glCompressedTexSubImage3D(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _imageSize, _data) );
  3541. }
  3542. else
  3543. {
  3544. BX_UNUSED(_zoffset, _depth);
  3545. GL_CHECK(glCompressedTexSubImage2D(_target, _level, _xoffset, _yoffset, _width, _height, _format, _imageSize, _data) );
  3546. }
  3547. }
  3548. bool TextureGL::init(GLenum _target, uint32_t _width, uint32_t _height, uint32_t _depth, uint8_t _numMips, uint32_t _flags)
  3549. {
  3550. m_target = _target;
  3551. m_numMips = _numMips;
  3552. m_flags = _flags;
  3553. m_width = _width;
  3554. m_height = _height;
  3555. m_depth = _depth;
  3556. m_currentSamplerHash = UINT32_MAX;
  3557. const bool writeOnly = 0 != (m_flags&BGFX_TEXTURE_RT_WRITE_ONLY);
  3558. const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE );
  3559. if (!writeOnly)
  3560. {
  3561. GL_CHECK(glGenTextures(1, &m_id) );
  3562. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  3563. GL_CHECK(glBindTexture(_target, m_id) );
  3564. const TextureFormatInfo& tfi = s_textureFormat[m_textureFormat];
  3565. m_fmt = tfi.m_fmt;
  3566. m_type = tfi.m_type;
  3567. const bool swizzle = true
  3568. && TextureFormat::BGRA8 == m_requestedFormat
  3569. && !s_textureFormat[m_requestedFormat].m_supported
  3570. && !s_renderGL->m_textureSwizzleSupport
  3571. ;
  3572. const bool convert = false
  3573. || m_textureFormat != m_requestedFormat
  3574. || swizzle
  3575. ;
  3576. if (convert)
  3577. {
  3578. m_textureFormat = (uint8_t)TextureFormat::RGBA8;
  3579. const TextureFormatInfo& tfiRgba8 = s_textureFormat[TextureFormat::RGBA8];
  3580. m_fmt = tfiRgba8.m_fmt;
  3581. m_type = tfiRgba8.m_type;
  3582. }
  3583. if (computeWrite)
  3584. {
  3585. if (_target == GL_TEXTURE_3D)
  3586. {
  3587. GL_CHECK(glTexStorage3D(_target
  3588. , _numMips
  3589. , s_textureFormat[m_textureFormat].m_internalFmt
  3590. , m_width
  3591. , m_height
  3592. , _depth
  3593. ) );
  3594. }
  3595. else
  3596. {
  3597. GL_CHECK(glTexStorage2D(_target
  3598. , _numMips
  3599. , s_textureFormat[m_textureFormat].m_internalFmt
  3600. , m_width
  3601. , m_height
  3602. ) );
  3603. }
  3604. }
  3605. setSamplerState(_flags, NULL);
  3606. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3607. && TextureFormat::BGRA8 == m_requestedFormat
  3608. && !s_textureFormat[m_requestedFormat].m_supported
  3609. && s_renderGL->m_textureSwizzleSupport)
  3610. {
  3611. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  3612. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  3613. }
  3614. }
  3615. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  3616. if (renderTarget)
  3617. {
  3618. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  3619. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  3620. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  3621. if (0 != msaaQuality
  3622. || writeOnly)
  3623. {
  3624. GL_CHECK(glGenRenderbuffers(1, &m_rbo) );
  3625. BX_CHECK(0 != m_rbo, "Failed to generate renderbuffer id.");
  3626. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_rbo) );
  3627. if (0 == msaaQuality)
  3628. {
  3629. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER
  3630. , s_rboFormat[m_textureFormat]
  3631. , _width
  3632. , _height
  3633. ) );
  3634. }
  3635. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3636. {
  3637. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER
  3638. , msaaQuality
  3639. , s_rboFormat[m_textureFormat]
  3640. , _width
  3641. , _height
  3642. ) );
  3643. }
  3644. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  3645. if (writeOnly)
  3646. {
  3647. // This is render buffer, there is no sampling, no need
  3648. // to create texture.
  3649. return false;
  3650. }
  3651. }
  3652. }
  3653. return true;
  3654. }
  3655. void TextureGL::create(const Memory* _mem, uint32_t _flags, uint8_t _skip)
  3656. {
  3657. ImageContainer imageContainer;
  3658. if (imageParse(imageContainer, _mem->data, _mem->size) )
  3659. {
  3660. uint8_t numMips = imageContainer.m_numMips;
  3661. const uint8_t startLod = uint8_t(bx::uint32_min(_skip, numMips-1) );
  3662. numMips -= startLod;
  3663. uint32_t textureWidth;
  3664. uint32_t textureHeight;
  3665. uint32_t textureDepth;
  3666. {
  3667. const ImageBlockInfo& ibi = getBlockInfo(TextureFormat::Enum(imageContainer.m_format) );
  3668. textureWidth = bx::uint32_max(ibi.blockWidth, imageContainer.m_width >>startLod);
  3669. textureHeight = bx::uint32_max(ibi.blockHeight, imageContainer.m_height>>startLod);
  3670. textureDepth = imageContainer.m_depth;
  3671. }
  3672. m_requestedFormat = uint8_t(imageContainer.m_format);
  3673. m_textureFormat = uint8_t(getViableTextureFormat(imageContainer) );
  3674. GLenum target = GL_TEXTURE_2D;
  3675. if (imageContainer.m_cubeMap)
  3676. {
  3677. target = GL_TEXTURE_CUBE_MAP;
  3678. }
  3679. else if (imageContainer.m_depth > 1)
  3680. {
  3681. target = GL_TEXTURE_3D;
  3682. }
  3683. if (!init(target
  3684. , textureWidth
  3685. , textureHeight
  3686. , textureDepth
  3687. , numMips
  3688. , _flags
  3689. ) )
  3690. {
  3691. return;
  3692. }
  3693. const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE);
  3694. const bool srgb = 0 != (m_flags&BGFX_TEXTURE_SRGB);
  3695. target = GL_TEXTURE_CUBE_MAP == m_target ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target;
  3696. const GLenum internalFmt = srgb
  3697. ? s_textureFormat[m_textureFormat].m_internalFmtSrgb
  3698. : s_textureFormat[m_textureFormat].m_internalFmt
  3699. ;
  3700. const bool swizzle = true
  3701. && TextureFormat::BGRA8 == m_requestedFormat
  3702. && !s_textureFormat[m_requestedFormat].m_supported
  3703. && !s_renderGL->m_textureSwizzleSupport
  3704. ;
  3705. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  3706. const bool convert = false
  3707. || m_textureFormat != m_requestedFormat
  3708. || swizzle
  3709. ;
  3710. BX_TRACE("Texture%-4s %3d: %s (requested: %s), %dx%dx%d%s."
  3711. , imageContainer.m_cubeMap ? "Cube" : (1 < imageContainer.m_depth ? "3D" : "2D")
  3712. , this - s_renderGL->m_textures
  3713. , getName( (TextureFormat::Enum)m_textureFormat)
  3714. , getName( (TextureFormat::Enum)m_requestedFormat)
  3715. , textureWidth
  3716. , textureHeight
  3717. , imageContainer.m_cubeMap ? 6 : (1 < imageContainer.m_depth ? imageContainer.m_depth : 0)
  3718. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  3719. );
  3720. BX_WARN(!convert, "Texture %s%s%s from %s to %s."
  3721. , swizzle ? "swizzle" : ""
  3722. , swizzle&&convert ? " and " : ""
  3723. , convert ? "convert" : ""
  3724. , getName( (TextureFormat::Enum)m_requestedFormat)
  3725. , getName( (TextureFormat::Enum)m_textureFormat)
  3726. );
  3727. uint8_t* temp = NULL;
  3728. if (convert)
  3729. {
  3730. temp = (uint8_t*)BX_ALLOC(g_allocator, textureWidth*textureHeight*4);
  3731. }
  3732. for (uint8_t side = 0, numSides = imageContainer.m_cubeMap ? 6 : 1; side < numSides; ++side)
  3733. {
  3734. uint32_t width = textureWidth;
  3735. uint32_t height = textureHeight;
  3736. uint32_t depth = imageContainer.m_depth;
  3737. for (uint8_t lod = 0, num = numMips; lod < num; ++lod)
  3738. {
  3739. width = bx::uint32_max(1, width);
  3740. height = bx::uint32_max(1, height);
  3741. depth = bx::uint32_max(1, depth);
  3742. ImageMip mip;
  3743. if (imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  3744. {
  3745. if (compressed
  3746. && !convert)
  3747. {
  3748. compressedTexImage(target+side
  3749. , lod
  3750. , internalFmt
  3751. , width
  3752. , height
  3753. , depth
  3754. , 0
  3755. , mip.m_size
  3756. , mip.m_data
  3757. );
  3758. }
  3759. else
  3760. {
  3761. const uint8_t* data = mip.m_data;
  3762. if (convert)
  3763. {
  3764. imageDecodeToRgba8(temp
  3765. , mip.m_data
  3766. , mip.m_width
  3767. , mip.m_height
  3768. , mip.m_width*4
  3769. , mip.m_format
  3770. );
  3771. data = temp;
  3772. }
  3773. texImage(target+side
  3774. , lod
  3775. , internalFmt
  3776. , width
  3777. , height
  3778. , depth
  3779. , 0
  3780. , m_fmt
  3781. , m_type
  3782. , data
  3783. );
  3784. }
  3785. }
  3786. else if (!computeWrite)
  3787. {
  3788. if (compressed)
  3789. {
  3790. uint32_t size = bx::uint32_max(1, (width + 3)>>2)
  3791. * bx::uint32_max(1, (height + 3)>>2)
  3792. * 4*4*getBitsPerPixel(TextureFormat::Enum(m_textureFormat) )/8
  3793. ;
  3794. compressedTexImage(target+side
  3795. , lod
  3796. , internalFmt
  3797. , width
  3798. , height
  3799. , depth
  3800. , 0
  3801. , size
  3802. , NULL
  3803. );
  3804. }
  3805. else
  3806. {
  3807. texImage(target+side
  3808. , lod
  3809. , internalFmt
  3810. , width
  3811. , height
  3812. , depth
  3813. , 0
  3814. , m_fmt
  3815. , m_type
  3816. , NULL
  3817. );
  3818. }
  3819. }
  3820. width >>= 1;
  3821. height >>= 1;
  3822. depth >>= 1;
  3823. }
  3824. }
  3825. if (NULL != temp)
  3826. {
  3827. BX_FREE(g_allocator, temp);
  3828. }
  3829. }
  3830. GL_CHECK(glBindTexture(m_target, 0) );
  3831. }
  3832. void TextureGL::destroy()
  3833. {
  3834. if (0 == (m_flags & BGFX_TEXTURE_INTERNAL_SHARED)
  3835. && 0 != m_id)
  3836. {
  3837. GL_CHECK(glBindTexture(m_target, 0) );
  3838. GL_CHECK(glDeleteTextures(1, &m_id) );
  3839. m_id = 0;
  3840. }
  3841. if (0 != m_rbo)
  3842. {
  3843. GL_CHECK(glDeleteRenderbuffers(1, &m_rbo) );
  3844. m_rbo = 0;
  3845. }
  3846. }
  3847. void TextureGL::overrideInternal(uintptr_t _ptr)
  3848. {
  3849. destroy();
  3850. m_flags |= BGFX_TEXTURE_INTERNAL_SHARED;
  3851. m_id = (GLuint)_ptr;
  3852. }
  3853. void TextureGL::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  3854. {
  3855. BX_UNUSED(_z, _depth);
  3856. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  3857. const uint32_t rectpitch = _rect.m_width*bpp/8;
  3858. uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  3859. GL_CHECK(glBindTexture(m_target, m_id) );
  3860. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  3861. GLenum target = GL_TEXTURE_CUBE_MAP == m_target ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target;
  3862. const bool swizzle = true
  3863. && TextureFormat::BGRA8 == m_requestedFormat
  3864. && !s_textureFormat[m_requestedFormat].m_supported
  3865. && !s_renderGL->m_textureSwizzleSupport
  3866. ;
  3867. const bool unpackRowLength = BX_IGNORE_C4127(!!BGFX_CONFIG_RENDERER_OPENGL || s_extension[Extension::EXT_unpack_subimage].m_supported);
  3868. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  3869. const bool convert = false
  3870. || (compressed && m_textureFormat != m_requestedFormat)
  3871. || swizzle
  3872. ;
  3873. const uint32_t width = _rect.m_width;
  3874. const uint32_t height = _rect.m_height;
  3875. uint8_t* temp = NULL;
  3876. if (convert
  3877. || !unpackRowLength)
  3878. {
  3879. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*height);
  3880. }
  3881. else if (unpackRowLength)
  3882. {
  3883. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, srcpitch*8/bpp) );
  3884. }
  3885. if (compressed)
  3886. {
  3887. const uint8_t* data = _mem->data;
  3888. if (!unpackRowLength)
  3889. {
  3890. imageCopy(width, height, bpp, srcpitch, data, temp);
  3891. data = temp;
  3892. }
  3893. GL_CHECK(compressedTexSubImage(target+_side
  3894. , _mip
  3895. , _rect.m_x
  3896. , _rect.m_y
  3897. , _z
  3898. , _rect.m_width
  3899. , _rect.m_height
  3900. , _depth
  3901. , m_fmt
  3902. , _mem->size
  3903. , data
  3904. ) );
  3905. }
  3906. else
  3907. {
  3908. const uint8_t* data = _mem->data;
  3909. if (convert)
  3910. {
  3911. imageDecodeToRgba8(temp, data, width, height, srcpitch, TextureFormat::Enum(m_requestedFormat) );
  3912. data = temp;
  3913. srcpitch = rectpitch;
  3914. }
  3915. if (!unpackRowLength
  3916. && !convert)
  3917. {
  3918. imageCopy(width, height, bpp, srcpitch, data, temp);
  3919. data = temp;
  3920. }
  3921. GL_CHECK(texSubImage(target+_side
  3922. , _mip
  3923. , _rect.m_x
  3924. , _rect.m_y
  3925. , _z
  3926. , _rect.m_width
  3927. , _rect.m_height
  3928. , _depth
  3929. , m_fmt
  3930. , m_type
  3931. , data
  3932. ) );
  3933. }
  3934. if (!convert
  3935. && unpackRowLength)
  3936. {
  3937. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) );
  3938. }
  3939. if (NULL != temp)
  3940. {
  3941. BX_FREE(g_allocator, temp);
  3942. }
  3943. }
  3944. void TextureGL::setSamplerState(uint32_t _flags, const float _rgba[4])
  3945. {
  3946. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  3947. && !s_textureFilter[m_textureFormat])
  3948. {
  3949. // Force point sampling when texture format doesn't support linear sampling.
  3950. _flags &= ~(0
  3951. | BGFX_TEXTURE_MIN_MASK
  3952. | BGFX_TEXTURE_MAG_MASK
  3953. | BGFX_TEXTURE_MIP_MASK
  3954. );
  3955. _flags |= 0
  3956. | BGFX_TEXTURE_MIN_POINT
  3957. | BGFX_TEXTURE_MAG_POINT
  3958. | BGFX_TEXTURE_MIP_POINT
  3959. ;
  3960. }
  3961. const uint32_t flags = (0 != (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags) ? m_flags : _flags) & BGFX_TEXTURE_SAMPLER_BITS_MASK;
  3962. bool hasBorderColor = false;
  3963. bx::HashMurmur2A murmur;
  3964. murmur.begin();
  3965. murmur.add(flags);
  3966. if (NULL != _rgba)
  3967. {
  3968. if (BGFX_TEXTURE_U_BORDER == (flags & BGFX_TEXTURE_U_BORDER)
  3969. || BGFX_TEXTURE_V_BORDER == (flags & BGFX_TEXTURE_V_BORDER)
  3970. || BGFX_TEXTURE_W_BORDER == (flags & BGFX_TEXTURE_W_BORDER) )
  3971. {
  3972. murmur.add(_rgba, 16);
  3973. hasBorderColor = true;
  3974. }
  3975. }
  3976. uint32_t hash = murmur.end();
  3977. if (hash != m_currentSamplerHash)
  3978. {
  3979. const GLenum target = m_target;
  3980. const uint8_t numMips = m_numMips;
  3981. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_S, s_textureAddress[(flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]) );
  3982. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_T, s_textureAddress[(flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]) );
  3983. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  3984. || s_extension[Extension::APPLE_texture_max_level].m_supported)
  3985. {
  3986. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, numMips-1) );
  3987. }
  3988. if (target == GL_TEXTURE_3D)
  3989. {
  3990. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_R, s_textureAddress[(flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]) );
  3991. }
  3992. GLenum magFilter;
  3993. GLenum minFilter;
  3994. getFilters(flags, 1 < numMips, magFilter, minFilter);
  3995. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter) );
  3996. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter) );
  3997. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3998. || s_renderGL->m_borderColorSupport)
  3999. {
  4000. if (hasBorderColor)
  4001. {
  4002. GL_CHECK(glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, _rgba) );
  4003. }
  4004. }
  4005. if (0 != (flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  4006. && 0.0f < s_renderGL->m_maxAnisotropy)
  4007. {
  4008. GL_CHECK(glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderGL->m_maxAnisotropy) );
  4009. }
  4010. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  4011. || s_renderGL->m_shadowSamplersSupport)
  4012. {
  4013. const uint32_t cmpFunc = (flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  4014. if (0 == cmpFunc)
  4015. {
  4016. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  4017. }
  4018. else
  4019. {
  4020. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  4021. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  4022. }
  4023. }
  4024. m_currentSamplerHash = hash;
  4025. }
  4026. }
  4027. void TextureGL::commit(uint32_t _stage, uint32_t _flags, const float _palette[][4])
  4028. {
  4029. const uint32_t flags = 0 == (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags)
  4030. ? _flags
  4031. : m_flags
  4032. ;
  4033. const uint32_t index = (flags & BGFX_TEXTURE_BORDER_COLOR_MASK) >> BGFX_TEXTURE_BORDER_COLOR_SHIFT;
  4034. GL_CHECK(glActiveTexture(GL_TEXTURE0+_stage) );
  4035. GL_CHECK(glBindTexture(m_target, m_id) );
  4036. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  4037. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  4038. {
  4039. // GLES2 doesn't have support for sampler object.
  4040. setSamplerState(flags, _palette[index]);
  4041. }
  4042. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4043. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL < 31) )
  4044. {
  4045. // In case that GL 2.1 sampler object is supported via extension.
  4046. if (s_renderGL->m_samplerObjectSupport)
  4047. {
  4048. s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]);
  4049. }
  4050. else
  4051. {
  4052. setSamplerState(flags, _palette[index]);
  4053. }
  4054. }
  4055. else
  4056. {
  4057. // Everything else has sampler object.
  4058. s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]);
  4059. }
  4060. }
  4061. void writeString(bx::WriterI* _writer, const char* _str)
  4062. {
  4063. bx::write(_writer, _str, (int32_t)strlen(_str) );
  4064. }
  4065. void writeStringf(bx::WriterI* _writer, const char* _format, ...)
  4066. {
  4067. char temp[512];
  4068. va_list argList;
  4069. va_start(argList, _format);
  4070. int len = bx::vsnprintf(temp, BX_COUNTOF(temp), _format, argList);
  4071. va_end(argList);
  4072. bx::write(_writer, temp, len);
  4073. }
  4074. void strins(char* _str, const char* _insert)
  4075. {
  4076. size_t len = strlen(_insert);
  4077. memmove(&_str[len], _str, strlen(_str)+1);
  4078. memcpy(_str, _insert, len);
  4079. }
  4080. void ShaderGL::create(Memory* _mem)
  4081. {
  4082. bx::MemoryReader reader(_mem->data, _mem->size);
  4083. m_hash = bx::hashMurmur2A(_mem->data, _mem->size);
  4084. uint32_t magic;
  4085. bx::read(&reader, magic);
  4086. switch (magic)
  4087. {
  4088. case BGFX_CHUNK_MAGIC_CSH: m_type = GL_COMPUTE_SHADER; break;
  4089. case BGFX_CHUNK_MAGIC_FSH: m_type = GL_FRAGMENT_SHADER; break;
  4090. case BGFX_CHUNK_MAGIC_VSH: m_type = GL_VERTEX_SHADER; break;
  4091. default:
  4092. BGFX_FATAL(false, Fatal::InvalidShader, "Unknown shader format %x.", magic);
  4093. break;
  4094. }
  4095. uint32_t iohash;
  4096. bx::read(&reader, iohash);
  4097. uint16_t count;
  4098. bx::read(&reader, count);
  4099. BX_TRACE("%s Shader consts %d"
  4100. , BGFX_CHUNK_MAGIC_FSH == magic ? "Fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "Vertex" : "Compute"
  4101. , count
  4102. );
  4103. for (uint32_t ii = 0; ii < count; ++ii)
  4104. {
  4105. uint8_t nameSize = 0;
  4106. bx::read(&reader, nameSize);
  4107. char name[256];
  4108. bx::read(&reader, &name, nameSize);
  4109. name[nameSize] = '\0';
  4110. uint8_t type;
  4111. bx::read(&reader, type);
  4112. uint8_t num;
  4113. bx::read(&reader, num);
  4114. uint16_t regIndex;
  4115. bx::read(&reader, regIndex);
  4116. uint16_t regCount;
  4117. bx::read(&reader, regCount);
  4118. }
  4119. uint32_t shaderSize;
  4120. bx::read(&reader, shaderSize);
  4121. m_id = glCreateShader(m_type);
  4122. BX_WARN(0 != m_id, "Failed to create %s shader."
  4123. , BGFX_CHUNK_MAGIC_FSH == magic ? "fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "vertex" : "compute"
  4124. );
  4125. const char* code = (const char*)reader.getDataPtr();
  4126. if (0 != m_id)
  4127. {
  4128. if (GL_COMPUTE_SHADER != m_type)
  4129. {
  4130. int32_t codeLen = (int32_t)strlen(code);
  4131. int32_t tempLen = codeLen + (4<<10);
  4132. char* temp = (char*)alloca(tempLen);
  4133. bx::StaticMemoryBlockWriter writer(temp, tempLen);
  4134. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  4135. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  4136. {
  4137. writeString(&writer
  4138. , "#define flat\n"
  4139. "#define smooth\n"
  4140. "#define noperspective\n"
  4141. );
  4142. bool usesDerivatives = s_extension[Extension::OES_standard_derivatives].m_supported
  4143. && bx::findIdentifierMatch(code, s_OES_standard_derivatives)
  4144. ;
  4145. bool usesFragData = !!bx::findIdentifierMatch(code, "gl_FragData");
  4146. bool usesFragDepth = !!bx::findIdentifierMatch(code, "gl_FragDepth");
  4147. bool usesShadowSamplers = !!bx::findIdentifierMatch(code, s_EXT_shadow_samplers);
  4148. bool usesTexture3D = s_extension[Extension::OES_texture_3D].m_supported
  4149. && bx::findIdentifierMatch(code, s_OES_texture_3D)
  4150. ;
  4151. bool usesTextureLod = !!bx::findIdentifierMatch(code, s_EXT_shader_texture_lod);
  4152. bool usesFragmentOrdering = !!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering");
  4153. if (usesDerivatives)
  4154. {
  4155. writeString(&writer, "#extension GL_OES_standard_derivatives : enable\n");
  4156. }
  4157. if (usesFragData)
  4158. {
  4159. BX_WARN(s_extension[Extension::EXT_draw_buffers ].m_supported
  4160. || s_extension[Extension::WEBGL_draw_buffers].m_supported
  4161. , "EXT_draw_buffers is used but not supported by GLES2 driver."
  4162. );
  4163. writeString(&writer
  4164. , "#extension GL_EXT_draw_buffers : enable\n"
  4165. );
  4166. }
  4167. bool insertFragDepth = false;
  4168. if (usesFragDepth)
  4169. {
  4170. BX_WARN(s_extension[Extension::EXT_frag_depth].m_supported, "EXT_frag_depth is used but not supported by GLES2 driver.");
  4171. if (s_extension[Extension::EXT_frag_depth].m_supported)
  4172. {
  4173. writeString(&writer
  4174. , "#extension GL_EXT_frag_depth : enable\n"
  4175. "#define bgfx_FragDepth gl_FragDepthEXT\n"
  4176. );
  4177. char str[128];
  4178. bx::snprintf(str, BX_COUNTOF(str), "%s float gl_FragDepthEXT;\n"
  4179. , s_extension[Extension::OES_fragment_precision_high].m_supported ? "highp" : "mediump"
  4180. );
  4181. writeString(&writer, str);
  4182. }
  4183. else
  4184. {
  4185. insertFragDepth = true;
  4186. }
  4187. }
  4188. if (usesShadowSamplers)
  4189. {
  4190. if (s_renderGL->m_shadowSamplersSupport)
  4191. {
  4192. writeString(&writer
  4193. , "#extension GL_EXT_shadow_samplers : enable\n"
  4194. "#define shadow2D shadow2DEXT\n"
  4195. "#define shadow2DProj shadow2DProjEXT\n"
  4196. );
  4197. }
  4198. else
  4199. {
  4200. writeString(&writer
  4201. , "#define sampler2DShadow sampler2D\n"
  4202. "#define shadow2D(_sampler, _coord) step(_coord.z, texture2D(_sampler, _coord.xy).x)\n"
  4203. "#define shadow2DProj(_sampler, _coord) step(_coord.z/_coord.w, texture2DProj(_sampler, _coord).x)\n"
  4204. );
  4205. }
  4206. }
  4207. if (usesTexture3D)
  4208. {
  4209. writeString(&writer, "#extension GL_OES_texture_3D : enable\n");
  4210. }
  4211. if (usesTextureLod)
  4212. {
  4213. BX_WARN(s_extension[Extension::EXT_shader_texture_lod].m_supported, "EXT_shader_texture_lod is used but not supported by GLES2 driver.");
  4214. if (s_extension[Extension::EXT_shader_texture_lod].m_supported
  4215. /*&& GL_VERTEX_SHADER == m_type*/)
  4216. {
  4217. writeString(&writer
  4218. , "#extension GL_EXT_shader_texture_lod : enable\n"
  4219. "#define texture2DLod texture2DLodEXT\n"
  4220. "#define texture2DProjLod texture2DProjLodEXT\n"
  4221. "#define textureCubeLod textureCubeLodEXT\n"
  4222. );
  4223. }
  4224. else
  4225. {
  4226. writeString(&writer
  4227. , "#define texture2DLod(_sampler, _coord, _level) texture2D(_sampler, _coord)\n"
  4228. "#define texture2DProjLod(_sampler, _coord, _level) texture2DProj(_sampler, _coord)\n"
  4229. "#define textureCubeLod(_sampler, _coord, _level) textureCube(_sampler, _coord)\n"
  4230. );
  4231. }
  4232. }
  4233. if (usesFragmentOrdering)
  4234. {
  4235. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  4236. {
  4237. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  4238. }
  4239. else
  4240. {
  4241. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  4242. }
  4243. }
  4244. writeStringf(&writer, "precision %s float;\n"
  4245. , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp"
  4246. );
  4247. bx::write(&writer, code, codeLen);
  4248. bx::write(&writer, '\0');
  4249. if (insertFragDepth)
  4250. {
  4251. char* entry = strstr(temp, "void main ()");
  4252. if (NULL != entry)
  4253. {
  4254. char* brace = strstr(entry, "{");
  4255. if (NULL != brace)
  4256. {
  4257. const char* end = bx::strmb(brace, '{', '}');
  4258. if (NULL != end)
  4259. {
  4260. strins(brace+1, "\n float bgfx_FragDepth = 0.0;\n");
  4261. }
  4262. }
  4263. }
  4264. }
  4265. // Replace all instances of gl_FragDepth with bgfx_FragDepth.
  4266. for (const char* fragDepth = bx::findIdentifierMatch(temp, "gl_FragDepth"); NULL != fragDepth; fragDepth = bx::findIdentifierMatch(fragDepth, "gl_FragDepth") )
  4267. {
  4268. char* insert = const_cast<char*>(fragDepth);
  4269. strins(insert, "bg");
  4270. memcpy(insert + 2, "fx", 2);
  4271. }
  4272. }
  4273. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4274. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL <= 21) )
  4275. {
  4276. const bool usesTextureLod = true
  4277. && s_extension[Extension::ARB_shader_texture_lod].m_supported
  4278. && bx::findIdentifierMatch(code, s_ARB_shader_texture_lod)
  4279. ;
  4280. const bool usesIUsamplers = !!bx::findIdentifierMatch(code, s_uisamplers);
  4281. const bool usesTexelFetch = !!bx::findIdentifierMatch(code, s_texelFetch);
  4282. const bool usesTextureMS = !!bx::findIdentifierMatch(code, s_ARB_texture_multisample);
  4283. uint32_t version =
  4284. usesIUsamplers || usesTexelFetch || usesTextureMS ? 130
  4285. : usesTextureLod ? 120
  4286. : 0
  4287. ;
  4288. if (0 != version)
  4289. {
  4290. writeStringf(&writer, "#version %d\n", version);
  4291. }
  4292. if (usesTextureLod)
  4293. {
  4294. if (m_type == GL_FRAGMENT_SHADER)
  4295. {
  4296. writeString(&writer, "#extension GL_ARB_shader_texture_lod : enable\n");
  4297. }
  4298. }
  4299. if (usesTextureMS)
  4300. {
  4301. writeString(&writer, "#extension GL_ARB_texture_multisample : enable\n");
  4302. }
  4303. if (130 <= version)
  4304. {
  4305. if (m_type == GL_FRAGMENT_SHADER)
  4306. {
  4307. writeString(&writer, "#define varying in\n");
  4308. }
  4309. else
  4310. {
  4311. writeString(&writer, "#define attribute in\n");
  4312. writeString(&writer, "#define varying out\n");
  4313. }
  4314. uint32_t fragData = 0;
  4315. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  4316. {
  4317. for (uint32_t ii = 0, num = g_caps.maxFBAttachments; ii < num; ++ii)
  4318. {
  4319. char tmpFragData[16];
  4320. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  4321. fragData = bx::uint32_max(fragData, NULL == strstr(code, tmpFragData) ? 0 : ii+1);
  4322. }
  4323. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  4324. }
  4325. if (0 != fragData)
  4326. {
  4327. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  4328. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  4329. }
  4330. else
  4331. {
  4332. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  4333. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  4334. }
  4335. }
  4336. writeString(&writer
  4337. , "#define lowp\n"
  4338. "#define mediump\n"
  4339. "#define highp\n"
  4340. "#define flat\n"
  4341. "#define smooth\n"
  4342. "#define noperspective\n"
  4343. );
  4344. bx::write(&writer, code, codeLen);
  4345. bx::write(&writer, '\0');
  4346. }
  4347. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 31)
  4348. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4349. {
  4350. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4351. {
  4352. writeString(&writer
  4353. , "#version 300 es\n"
  4354. "precision mediump float;\n"
  4355. );
  4356. }
  4357. else
  4358. {
  4359. writeString(&writer, "#version 140\n");
  4360. }
  4361. writeString(&writer, "#define texture2DLod textureLod\n");
  4362. writeString(&writer, "#define texture3DLod textureLod\n");
  4363. writeString(&writer, "#define textureCubeLod textureLod\n");
  4364. if (m_type == GL_FRAGMENT_SHADER)
  4365. {
  4366. writeString(&writer, "#define varying in\n");
  4367. writeString(&writer, "#define texture2D texture\n");
  4368. writeString(&writer, "#define texture2DProj textureProj\n");
  4369. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  4370. {
  4371. writeString(&writer, "#define shadow2D(_sampler, _coord) vec2(textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  4372. writeString(&writer, "#define shadow2DProj(_sampler, _coord) vec2(textureProj(_sampler, _coord) ) )\n");
  4373. }
  4374. else
  4375. {
  4376. writeString(&writer, "#define shadow2D(_sampler, _coord) (textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  4377. writeString(&writer, "#define shadow2DProj(_sampler, _coord) (textureProj(_sampler, _coord) ) )\n");
  4378. }
  4379. writeString(&writer, "#define texture3D texture\n");
  4380. writeString(&writer, "#define textureCube texture\n");
  4381. uint32_t fragData = 0;
  4382. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  4383. {
  4384. for (uint32_t ii = 0, num = g_caps.maxFBAttachments; ii < num; ++ii)
  4385. {
  4386. char tmpFragData[16];
  4387. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  4388. fragData = bx::uint32_max(fragData, NULL == strstr(code, tmpFragData) ? 0 : ii+1);
  4389. }
  4390. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  4391. }
  4392. if (!!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering") )
  4393. {
  4394. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  4395. {
  4396. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  4397. }
  4398. else
  4399. {
  4400. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  4401. }
  4402. }
  4403. if (0 != fragData)
  4404. {
  4405. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  4406. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  4407. }
  4408. else
  4409. {
  4410. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  4411. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  4412. }
  4413. }
  4414. else
  4415. {
  4416. writeString(&writer, "#define attribute in\n");
  4417. writeString(&writer, "#define varying out\n");
  4418. }
  4419. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4420. {
  4421. writeString(&writer
  4422. , "#define lowp\n"
  4423. "#define mediump\n"
  4424. "#define highp\n"
  4425. );
  4426. }
  4427. bx::write(&writer, code, codeLen);
  4428. bx::write(&writer, '\0');
  4429. }
  4430. code = temp;
  4431. }
  4432. GL_CHECK(glShaderSource(m_id, 1, (const GLchar**)&code, NULL) );
  4433. GL_CHECK(glCompileShader(m_id) );
  4434. GLint compiled = 0;
  4435. GL_CHECK(glGetShaderiv(m_id, GL_COMPILE_STATUS, &compiled) );
  4436. if (0 == compiled)
  4437. {
  4438. BX_TRACE("\n####\n%s\n####", code);
  4439. GLsizei len;
  4440. char log[1024];
  4441. GL_CHECK(glGetShaderInfoLog(m_id, sizeof(log), &len, log) );
  4442. BX_TRACE("Failed to compile shader. %d: %s", compiled, log);
  4443. GL_CHECK(glDeleteShader(m_id) );
  4444. m_id = 0;
  4445. BGFX_FATAL(false, bgfx::Fatal::InvalidShader, "Failed to compile shader.");
  4446. }
  4447. else if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  4448. && s_extension[Extension::ANGLE_translated_shader_source].m_supported
  4449. && NULL != glGetTranslatedShaderSourceANGLE)
  4450. {
  4451. GLsizei len;
  4452. GL_CHECK(glGetShaderiv(m_id, GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE, &len) );
  4453. char* source = (char*)alloca(len);
  4454. GL_CHECK(glGetTranslatedShaderSourceANGLE(m_id, len, &len, source) );
  4455. BX_TRACE("ANGLE source (len: %d):\n%s\n####", len, source);
  4456. }
  4457. }
  4458. }
  4459. void ShaderGL::destroy()
  4460. {
  4461. if (0 != m_id)
  4462. {
  4463. GL_CHECK(glDeleteShader(m_id) );
  4464. m_id = 0;
  4465. }
  4466. }
  4467. static void frameBufferValidate()
  4468. {
  4469. GLenum complete = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  4470. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == complete
  4471. , "glCheckFramebufferStatus failed 0x%08x: %s"
  4472. , complete
  4473. , glEnumName(complete)
  4474. );
  4475. BX_UNUSED(complete);
  4476. }
  4477. void FrameBufferGL::create(uint8_t _num, const Attachment* _attachment)
  4478. {
  4479. GL_CHECK(glGenFramebuffers(1, &m_fbo[0]) );
  4480. m_numTh = _num;
  4481. memcpy(m_attachment, _attachment, _num*sizeof(Attachment) );
  4482. postReset();
  4483. }
  4484. void FrameBufferGL::postReset()
  4485. {
  4486. if (0 != m_fbo[0])
  4487. {
  4488. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  4489. bool needResolve = false;
  4490. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  4491. uint32_t colorIdx = 0;
  4492. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  4493. {
  4494. TextureHandle handle = m_attachment[ii].handle;
  4495. if (isValid(handle) )
  4496. {
  4497. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  4498. if (0 == colorIdx)
  4499. {
  4500. m_width = bx::uint32_max(texture.m_width >> m_attachment[ii].mip, 1);
  4501. m_height = bx::uint32_max(texture.m_height >> m_attachment[ii].mip, 1);
  4502. }
  4503. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  4504. TextureFormat::Enum format = (TextureFormat::Enum)texture.m_textureFormat;
  4505. if (isDepth(format) )
  4506. {
  4507. const ImageBlockInfo& info = getBlockInfo(format);
  4508. if (0 < info.stencilBits)
  4509. {
  4510. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  4511. }
  4512. else if (0 == info.depthBits)
  4513. {
  4514. attachment = GL_STENCIL_ATTACHMENT;
  4515. }
  4516. else
  4517. {
  4518. attachment = GL_DEPTH_ATTACHMENT;
  4519. }
  4520. }
  4521. else
  4522. {
  4523. buffers[colorIdx] = attachment;
  4524. ++colorIdx;
  4525. }
  4526. if (0 != texture.m_rbo)
  4527. {
  4528. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  4529. , attachment
  4530. , GL_RENDERBUFFER
  4531. , texture.m_rbo
  4532. ) );
  4533. }
  4534. else
  4535. {
  4536. GLenum target = GL_TEXTURE_CUBE_MAP == texture.m_target
  4537. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + m_attachment[ii].layer
  4538. : texture.m_target
  4539. ;
  4540. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  4541. , attachment
  4542. , target
  4543. , texture.m_id
  4544. , m_attachment[ii].mip
  4545. ) );
  4546. }
  4547. needResolve |= (0 != texture.m_rbo) && (0 != texture.m_id);
  4548. }
  4549. }
  4550. m_num = uint8_t(colorIdx);
  4551. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  4552. {
  4553. if (0 == colorIdx)
  4554. {
  4555. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  4556. {
  4557. // When only depth is attached disable draw buffer to avoid
  4558. // GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER.
  4559. GL_CHECK(glDrawBuffer(GL_NONE) );
  4560. }
  4561. }
  4562. else
  4563. {
  4564. GL_CHECK(glDrawBuffers(colorIdx, buffers) );
  4565. }
  4566. // Disable read buffer to avoid GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER.
  4567. GL_CHECK(glReadBuffer(GL_NONE) );
  4568. }
  4569. frameBufferValidate();
  4570. if (needResolve)
  4571. {
  4572. GL_CHECK(glGenFramebuffers(1, &m_fbo[1]) );
  4573. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) );
  4574. colorIdx = 0;
  4575. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  4576. {
  4577. TextureHandle handle = m_attachment[ii].handle;
  4578. if (isValid(handle) )
  4579. {
  4580. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  4581. if (0 != texture.m_id)
  4582. {
  4583. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  4584. if (!isDepth( (TextureFormat::Enum)texture.m_textureFormat) )
  4585. {
  4586. ++colorIdx;
  4587. GLenum target = GL_TEXTURE_CUBE_MAP == texture.m_target
  4588. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + m_attachment[ii].layer
  4589. : texture.m_target
  4590. ;
  4591. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  4592. , attachment
  4593. , target
  4594. , texture.m_id
  4595. , m_attachment[ii].mip
  4596. ) );
  4597. }
  4598. }
  4599. }
  4600. }
  4601. frameBufferValidate();
  4602. }
  4603. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  4604. }
  4605. }
  4606. void FrameBufferGL::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat)
  4607. {
  4608. BX_UNUSED(_depthFormat);
  4609. m_swapChain = s_renderGL->m_glctx.createSwapChain(_nwh);
  4610. m_width = _width;
  4611. m_height = _height;
  4612. m_denseIdx = _denseIdx;
  4613. }
  4614. uint16_t FrameBufferGL::destroy()
  4615. {
  4616. if (0 != m_num)
  4617. {
  4618. GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) );
  4619. m_num = 0;
  4620. }
  4621. if (NULL != m_swapChain)
  4622. {
  4623. s_renderGL->m_glctx.destroySwapChain(m_swapChain);
  4624. m_swapChain = NULL;
  4625. }
  4626. memset(m_fbo, 0, sizeof(m_fbo) );
  4627. uint16_t denseIdx = m_denseIdx;
  4628. m_denseIdx = UINT16_MAX;
  4629. return denseIdx;
  4630. }
  4631. void FrameBufferGL::resolve()
  4632. {
  4633. if (0 != m_fbo[1])
  4634. {
  4635. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  4636. GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0) );
  4637. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) );
  4638. GL_CHECK(glBlitFramebuffer(0
  4639. , 0
  4640. , m_width
  4641. , m_height
  4642. , 0
  4643. , 0
  4644. , m_width
  4645. , m_height
  4646. , GL_COLOR_BUFFER_BIT
  4647. , GL_LINEAR
  4648. ) );
  4649. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  4650. GL_CHECK(glReadBuffer(GL_NONE) );
  4651. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  4652. }
  4653. }
  4654. void FrameBufferGL::discard(uint16_t _flags)
  4655. {
  4656. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS+2];
  4657. uint32_t idx = 0;
  4658. if (BGFX_CLEAR_NONE != (_flags & BGFX_CLEAR_DISCARD_COLOR_MASK) )
  4659. {
  4660. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  4661. {
  4662. if (BGFX_CLEAR_NONE != (_flags & (BGFX_CLEAR_DISCARD_COLOR_0<<ii) ) )
  4663. {
  4664. buffers[idx++] = GL_COLOR_ATTACHMENT0 + ii;
  4665. }
  4666. }
  4667. }
  4668. uint32_t dsFlags = _flags & (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL);
  4669. if (BGFX_CLEAR_NONE != dsFlags)
  4670. {
  4671. if ( (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL) == dsFlags)
  4672. {
  4673. buffers[idx++] = GL_DEPTH_STENCIL_ATTACHMENT;
  4674. }
  4675. else if (BGFX_CLEAR_DISCARD_DEPTH == dsFlags)
  4676. {
  4677. buffers[idx++] = GL_DEPTH_ATTACHMENT;
  4678. }
  4679. else if (BGFX_CLEAR_DISCARD_STENCIL == dsFlags)
  4680. {
  4681. buffers[idx++] = GL_STENCIL_ATTACHMENT;
  4682. }
  4683. }
  4684. GL_CHECK(glInvalidateFramebuffer(GL_FRAMEBUFFER, idx, buffers) );
  4685. }
  4686. void OcclusionQueryGL::create()
  4687. {
  4688. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  4689. {
  4690. Query& query = m_query[ii];
  4691. GL_CHECK(glGenQueries(1, &query.m_id) );
  4692. }
  4693. }
  4694. void OcclusionQueryGL::destroy()
  4695. {
  4696. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  4697. {
  4698. Query& query = m_query[ii];
  4699. GL_CHECK(glDeleteQueries(1, &query.m_id) );
  4700. }
  4701. }
  4702. void OcclusionQueryGL::begin(Frame* _render, OcclusionQueryHandle _handle)
  4703. {
  4704. while (0 == m_control.reserve(1) )
  4705. {
  4706. resolve(_render, true);
  4707. }
  4708. Query& query = m_query[m_control.m_current];
  4709. GL_CHECK(glBeginQuery(GL_SAMPLES_PASSED, query.m_id) );
  4710. query.m_handle = _handle;
  4711. }
  4712. void OcclusionQueryGL::end()
  4713. {
  4714. GL_CHECK(glEndQuery(GL_SAMPLES_PASSED) );
  4715. m_control.commit(1);
  4716. }
  4717. void OcclusionQueryGL::resolve(Frame* _render, bool _wait)
  4718. {
  4719. while (0 != m_control.available() )
  4720. {
  4721. Query& query = m_query[m_control.m_read];
  4722. int32_t result;
  4723. if (!_wait)
  4724. {
  4725. GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT_AVAILABLE, &result) );
  4726. if (!result)
  4727. {
  4728. break;
  4729. }
  4730. }
  4731. GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT, &result) );
  4732. _render->m_occlusion[query.m_handle.idx] = 0 < result;
  4733. m_control.consume(1);
  4734. }
  4735. }
  4736. void RendererContextGL::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  4737. {
  4738. BGFX_GPU_PROFILER_BEGIN_DYNAMIC("rendererSubmit");
  4739. if (1 < m_numWindows
  4740. && m_vaoSupport)
  4741. {
  4742. m_vaoSupport = false;
  4743. GL_CHECK(glBindVertexArray(0) );
  4744. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  4745. m_vao = 0;
  4746. m_vaoStateCache.invalidate();
  4747. }
  4748. m_glctx.makeCurrent(NULL);
  4749. const GLuint defaultVao = m_vao;
  4750. if (0 != defaultVao)
  4751. {
  4752. GL_CHECK(glBindVertexArray(defaultVao) );
  4753. }
  4754. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  4755. updateResolution(_render->m_resolution);
  4756. int64_t elapsed = -bx::getHPCounter();
  4757. int64_t captureElapsed = 0;
  4758. if (m_timerQuerySupport)
  4759. {
  4760. m_gpuTimer.begin();
  4761. }
  4762. if (0 < _render->m_iboffset)
  4763. {
  4764. TransientIndexBuffer* ib = _render->m_transientIb;
  4765. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data, true);
  4766. }
  4767. if (0 < _render->m_vboffset)
  4768. {
  4769. TransientVertexBuffer* vb = _render->m_transientVb;
  4770. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data, true);
  4771. }
  4772. _render->sort();
  4773. RenderDraw currentState;
  4774. currentState.clear();
  4775. currentState.m_stateFlags = BGFX_STATE_NONE;
  4776. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  4777. _render->m_hmdInitialized = m_ovr.isInitialized();
  4778. const bool hmdEnabled = m_ovr.isEnabled();
  4779. ViewState viewState(_render, hmdEnabled);
  4780. uint16_t programIdx = invalidHandle;
  4781. SortKey key;
  4782. uint16_t view = UINT16_MAX;
  4783. FrameBufferHandle fbh = { BGFX_CONFIG_MAX_FRAME_BUFFERS };
  4784. BlitKey blitKey;
  4785. blitKey.decode(_render->m_blitKeys[0]);
  4786. uint16_t numBlitItems = _render->m_numBlitItems;
  4787. uint16_t blitItem = 0;
  4788. int32_t resolutionHeight = hmdEnabled
  4789. ? _render->m_hmd.height
  4790. : _render->m_resolution.m_height
  4791. ;
  4792. uint32_t blendFactor = 0;
  4793. uint8_t primIndex;
  4794. {
  4795. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : 0;
  4796. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  4797. }
  4798. PrimInfo prim = s_primInfo[primIndex];
  4799. uint32_t baseVertex = 0;
  4800. GLuint currentVao = 0;
  4801. bool wasCompute = false;
  4802. bool viewHasScissor = false;
  4803. Rect viewScissorRect;
  4804. viewScissorRect.clear();
  4805. uint16_t discardFlags = BGFX_CLEAR_NONE;
  4806. const bool blendIndependentSupported = s_extension[Extension::ARB_draw_buffers_blend].m_supported;
  4807. const bool computeSupported = (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && s_extension[Extension::ARB_compute_shader].m_supported)
  4808. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  4809. ;
  4810. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  4811. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  4812. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  4813. uint32_t statsNumIndices = 0;
  4814. uint32_t statsKeyType[2] = {};
  4815. if (m_occlusionQuerySupport)
  4816. {
  4817. m_occlusionQuery.resolve(_render);
  4818. }
  4819. uint8_t eye = 0;
  4820. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  4821. {
  4822. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  4823. bool viewRestart = false;
  4824. uint8_t restartState = 0;
  4825. viewState.m_rect = _render->m_rect[0];
  4826. int32_t numItems = _render->m_num;
  4827. for (int32_t item = 0, restartItem = numItems; item < numItems || restartItem < numItems;)
  4828. {
  4829. const bool isCompute = key.decode(_render->m_sortKeys[item], _render->m_viewRemap);
  4830. statsKeyType[isCompute]++;
  4831. const bool viewChanged = 0
  4832. || key.m_view != view
  4833. || item == numItems
  4834. ;
  4835. const RenderItem& renderItem = _render->m_renderItem[_render->m_sortValues[item] ];
  4836. ++item;
  4837. if (viewChanged)
  4838. {
  4839. if (1 == restartState)
  4840. {
  4841. restartState = 2;
  4842. item = restartItem;
  4843. restartItem = numItems;
  4844. view = UINT16_MAX;
  4845. continue;
  4846. }
  4847. view = key.m_view;
  4848. programIdx = invalidHandle;
  4849. if (_render->m_fb[view].idx != fbh.idx)
  4850. {
  4851. fbh = _render->m_fb[view];
  4852. resolutionHeight = hmdEnabled
  4853. ? _render->m_hmd.height
  4854. : _render->m_resolution.m_height
  4855. ;
  4856. resolutionHeight = setFrameBuffer(fbh, resolutionHeight, discardFlags);
  4857. }
  4858. viewRestart = ( (BGFX_VIEW_STEREO == (_render->m_viewFlags[view] & BGFX_VIEW_STEREO) ) );
  4859. viewRestart &= hmdEnabled;
  4860. if (viewRestart)
  4861. {
  4862. if (0 == restartState)
  4863. {
  4864. restartState = 1;
  4865. restartItem = item - 1;
  4866. }
  4867. eye = (restartState - 1) & 1;
  4868. restartState &= 1;
  4869. }
  4870. else
  4871. {
  4872. eye = 0;
  4873. }
  4874. if (item > 1)
  4875. {
  4876. BGFX_GPU_PROFILER_END();
  4877. BGFX_PROFILER_END();
  4878. }
  4879. BGFX_PROFILER_BEGIN_DYNAMIC(s_viewName[view]);
  4880. BGFX_GPU_PROFILER_BEGIN_DYNAMIC(s_viewName[view]);
  4881. viewState.m_rect = _render->m_rect[view];
  4882. if (viewRestart)
  4883. {
  4884. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4885. {
  4886. char* viewName = s_viewName[view];
  4887. viewName[3] = ' ';
  4888. viewName[4] = eye ? 'R' : 'L';
  4889. GL_CHECK(glInsertEventMarker(0, viewName) );
  4890. }
  4891. if (m_ovr.isEnabled() )
  4892. {
  4893. m_ovr.getViewport(eye, &viewState.m_rect);
  4894. m_ovr.renderEyeStart(eye);
  4895. }
  4896. else
  4897. {
  4898. viewState.m_rect.m_x = eye * (viewState.m_rect.m_width+1)/2;
  4899. viewState.m_rect.m_width /= 2;
  4900. }
  4901. }
  4902. else
  4903. {
  4904. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4905. {
  4906. char* viewName = s_viewName[view];
  4907. viewName[3] = ' ';
  4908. viewName[4] = ' ';
  4909. GL_CHECK(glInsertEventMarker(0, viewName) );
  4910. }
  4911. }
  4912. const Rect& scissorRect = _render->m_scissor[view];
  4913. viewHasScissor = !scissorRect.isZero();
  4914. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  4915. GL_CHECK(glViewport(viewState.m_rect.m_x
  4916. , resolutionHeight-viewState.m_rect.m_height-viewState.m_rect.m_y
  4917. , viewState.m_rect.m_width
  4918. , viewState.m_rect.m_height
  4919. ) );
  4920. Clear& clear = _render->m_clear[view];
  4921. discardFlags = clear.m_flags & BGFX_CLEAR_DISCARD_MASK;
  4922. if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) )
  4923. {
  4924. clearQuad(_clearQuad, viewState.m_rect, clear, resolutionHeight, _render->m_colorPalette);
  4925. }
  4926. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  4927. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  4928. GL_CHECK(glDepthFunc(GL_LESS) );
  4929. GL_CHECK(glEnable(GL_CULL_FACE) );
  4930. GL_CHECK(glDisable(GL_BLEND) );
  4931. if (m_blitSupported)
  4932. {
  4933. for (; blitItem < numBlitItems && blitKey.m_view <= view; blitItem++)
  4934. {
  4935. const BlitItem& bi = _render->m_blitItem[blitItem];
  4936. blitKey.decode(_render->m_blitKeys[blitItem + 1]);
  4937. const TextureGL& src = m_textures[bi.m_src.idx];
  4938. const TextureGL& dst = m_textures[bi.m_dst.idx];
  4939. uint32_t srcWidth = bx::uint32_min(src.m_width, bi.m_srcX + bi.m_width) - bi.m_srcX;
  4940. uint32_t srcHeight = bx::uint32_min(src.m_height, bi.m_srcY + bi.m_height) - bi.m_srcY;
  4941. uint32_t srcDepth = bx::uint32_min(src.m_depth, bi.m_srcZ + bi.m_depth) - bi.m_srcZ;
  4942. uint32_t dstWidth = bx::uint32_min(dst.m_width, bi.m_dstX + bi.m_width) - bi.m_dstX;
  4943. uint32_t dstHeight = bx::uint32_min(dst.m_height, bi.m_dstY + bi.m_height) - bi.m_dstY;
  4944. uint32_t dstDepth = bx::uint32_min(dst.m_depth, bi.m_dstZ + bi.m_depth) - bi.m_dstZ;
  4945. uint32_t width = bx::uint32_min(srcWidth, dstWidth);
  4946. uint32_t height = bx::uint32_min(srcHeight, dstHeight);
  4947. uint32_t depth = bx::uint32_min(srcDepth, dstDepth);
  4948. GL_CHECK(glCopyImageSubData(src.m_id
  4949. , src.m_target
  4950. , bi.m_srcMip
  4951. , bi.m_srcX
  4952. , bi.m_srcY
  4953. , bi.m_srcZ
  4954. , dst.m_id
  4955. , dst.m_target
  4956. , bi.m_dstMip
  4957. , bi.m_dstX
  4958. , bi.m_dstY
  4959. , bi.m_dstZ
  4960. , width
  4961. , height
  4962. , bx::uint32_imax(depth, 1)
  4963. ) );
  4964. }
  4965. }
  4966. }
  4967. if (isCompute)
  4968. {
  4969. if (!wasCompute)
  4970. {
  4971. wasCompute = true;
  4972. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4973. {
  4974. char* viewName = s_viewName[view];
  4975. viewName[3] = 'C';
  4976. GL_CHECK(glInsertEventMarker(0, viewName) );
  4977. }
  4978. }
  4979. if (computeSupported)
  4980. {
  4981. const RenderCompute& compute = renderItem.compute;
  4982. ProgramGL& program = m_program[key.m_program];
  4983. GL_CHECK(glUseProgram(program.m_id) );
  4984. GLbitfield barrier = 0;
  4985. for (uint32_t ii = 0; ii < BGFX_MAX_COMPUTE_BINDINGS; ++ii)
  4986. {
  4987. const Binding& bind = compute.m_bind[ii];
  4988. if (invalidHandle != bind.m_idx)
  4989. {
  4990. switch (bind.m_type)
  4991. {
  4992. case Binding::Image:
  4993. {
  4994. const TextureGL& texture = m_textures[bind.m_idx];
  4995. GL_CHECK(glBindImageTexture(ii
  4996. , texture.m_id
  4997. , bind.m_un.m_compute.m_mip
  4998. , GL_FALSE
  4999. , 0
  5000. , s_access[bind.m_un.m_compute.m_access]
  5001. , s_imageFormat[bind.m_un.m_compute.m_format])
  5002. );
  5003. barrier |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
  5004. }
  5005. break;
  5006. case Binding::IndexBuffer:
  5007. {
  5008. const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx];
  5009. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  5010. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  5011. }
  5012. break;
  5013. case Binding::VertexBuffer:
  5014. {
  5015. const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx];
  5016. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  5017. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  5018. }
  5019. break;
  5020. }
  5021. }
  5022. }
  5023. if (0 != barrier)
  5024. {
  5025. bool constantsChanged = compute.m_constBegin < compute.m_constEnd;
  5026. rendererUpdateUniforms(this, _render->m_uniformBuffer, compute.m_constBegin, compute.m_constEnd);
  5027. if (constantsChanged
  5028. && NULL != program.m_constantBuffer)
  5029. {
  5030. commit(*program.m_constantBuffer);
  5031. }
  5032. viewState.setPredefined<1>(this, view, eye, program, _render, compute);
  5033. if (isValid(compute.m_indirectBuffer) )
  5034. {
  5035. const VertexBufferGL& vb = m_vertexBuffers[compute.m_indirectBuffer.idx];
  5036. if (currentState.m_indirectBuffer.idx != compute.m_indirectBuffer.idx)
  5037. {
  5038. currentState.m_indirectBuffer = compute.m_indirectBuffer;
  5039. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, vb.m_id) );
  5040. }
  5041. uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect
  5042. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  5043. : compute.m_numIndirect
  5044. ;
  5045. uintptr_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5046. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  5047. {
  5048. GL_CHECK(glDispatchComputeIndirect((GLintptr)args) );
  5049. args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5050. }
  5051. }
  5052. else
  5053. {
  5054. if (isValid(currentState.m_indirectBuffer) )
  5055. {
  5056. currentState.m_indirectBuffer.idx = invalidHandle;
  5057. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0) );
  5058. }
  5059. GL_CHECK(glDispatchCompute(compute.m_numX, compute.m_numY, compute.m_numZ) );
  5060. }
  5061. GL_CHECK(glMemoryBarrier(barrier) );
  5062. }
  5063. }
  5064. continue;
  5065. }
  5066. bool resetState = viewChanged || wasCompute;
  5067. if (wasCompute)
  5068. {
  5069. wasCompute = false;
  5070. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5071. {
  5072. char* viewName = s_viewName[view];
  5073. viewName[3] = ' ';
  5074. GL_CHECK(glInsertEventMarker(0, viewName) );
  5075. }
  5076. }
  5077. const RenderDraw& draw = renderItem.draw;
  5078. const bool hasOcclusionQuery = 0 != (draw.m_stateFlags & BGFX_STATE_INTERNAL_OCCLUSION_QUERY);
  5079. if (isValid(draw.m_occlusionQuery)
  5080. && !hasOcclusionQuery
  5081. && !isVisible(_render, draw.m_occlusionQuery, 0 != (draw.m_submitFlags&BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE) ) )
  5082. {
  5083. continue;
  5084. }
  5085. const uint64_t newFlags = draw.m_stateFlags;
  5086. uint64_t changedFlags = currentState.m_stateFlags ^ draw.m_stateFlags;
  5087. currentState.m_stateFlags = newFlags;
  5088. const uint64_t newStencil = draw.m_stencil;
  5089. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  5090. currentState.m_stencil = newStencil;
  5091. if (resetState)
  5092. {
  5093. currentState.clear();
  5094. currentState.m_scissor = !draw.m_scissor;
  5095. changedFlags = BGFX_STATE_MASK;
  5096. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  5097. currentState.m_stateFlags = newFlags;
  5098. currentState.m_stencil = newStencil;
  5099. }
  5100. uint16_t scissor = draw.m_scissor;
  5101. if (currentState.m_scissor != scissor)
  5102. {
  5103. currentState.m_scissor = scissor;
  5104. if (UINT16_MAX == scissor)
  5105. {
  5106. if (viewHasScissor)
  5107. {
  5108. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  5109. GL_CHECK(glScissor(viewScissorRect.m_x
  5110. , resolutionHeight-viewScissorRect.m_height-viewScissorRect.m_y
  5111. , viewScissorRect.m_width
  5112. , viewScissorRect.m_height
  5113. ) );
  5114. }
  5115. else
  5116. {
  5117. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  5118. }
  5119. }
  5120. else
  5121. {
  5122. Rect scissorRect;
  5123. scissorRect.intersect(viewScissorRect, _render->m_rectCache.m_cache[scissor]);
  5124. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  5125. GL_CHECK(glScissor(scissorRect.m_x
  5126. , resolutionHeight-scissorRect.m_height-scissorRect.m_y
  5127. , scissorRect.m_width
  5128. , scissorRect.m_height
  5129. ) );
  5130. }
  5131. }
  5132. if (0 != changedStencil)
  5133. {
  5134. if (0 != newStencil)
  5135. {
  5136. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  5137. uint32_t bstencil = unpackStencil(1, newStencil);
  5138. uint8_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil);
  5139. // uint32_t bchanged = unpackStencil(1, changedStencil);
  5140. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  5141. // {
  5142. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  5143. // GL_CHECK(glStencilMask(wmask) );
  5144. // }
  5145. for (uint8_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  5146. {
  5147. uint32_t stencil = unpackStencil(ii, newStencil);
  5148. uint32_t changed = unpackStencil(ii, changedStencil);
  5149. GLenum face = s_stencilFace[frontAndBack+ii];
  5150. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  5151. {
  5152. GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  5153. GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  5154. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  5155. GL_CHECK(glStencilFuncSeparate(face, s_cmpFunc[func], ref, mask) );
  5156. }
  5157. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  5158. {
  5159. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  5160. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  5161. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  5162. GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) );
  5163. }
  5164. }
  5165. }
  5166. else
  5167. {
  5168. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  5169. }
  5170. }
  5171. if ( (0
  5172. | BGFX_STATE_CULL_MASK
  5173. | BGFX_STATE_DEPTH_WRITE
  5174. | BGFX_STATE_DEPTH_TEST_MASK
  5175. | BGFX_STATE_RGB_WRITE
  5176. | BGFX_STATE_ALPHA_WRITE
  5177. | BGFX_STATE_BLEND_MASK
  5178. | BGFX_STATE_BLEND_EQUATION_MASK
  5179. | BGFX_STATE_ALPHA_REF_MASK
  5180. | BGFX_STATE_PT_MASK
  5181. | BGFX_STATE_POINT_SIZE_MASK
  5182. | BGFX_STATE_MSAA
  5183. | BGFX_STATE_LINEAA
  5184. | BGFX_STATE_CONSERVATIVE_RASTER
  5185. ) & changedFlags)
  5186. {
  5187. if (BGFX_STATE_CULL_MASK & changedFlags)
  5188. {
  5189. if (BGFX_STATE_CULL_CW & newFlags)
  5190. {
  5191. GL_CHECK(glEnable(GL_CULL_FACE) );
  5192. GL_CHECK(glCullFace(GL_BACK) );
  5193. }
  5194. else if (BGFX_STATE_CULL_CCW & newFlags)
  5195. {
  5196. GL_CHECK(glEnable(GL_CULL_FACE) );
  5197. GL_CHECK(glCullFace(GL_FRONT) );
  5198. }
  5199. else
  5200. {
  5201. GL_CHECK(glDisable(GL_CULL_FACE) );
  5202. }
  5203. }
  5204. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  5205. {
  5206. GL_CHECK(glDepthMask(!!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  5207. }
  5208. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  5209. {
  5210. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  5211. if (0 != func)
  5212. {
  5213. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5214. GL_CHECK(glDepthFunc(s_cmpFunc[func]) );
  5215. }
  5216. else
  5217. {
  5218. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  5219. }
  5220. }
  5221. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  5222. {
  5223. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  5224. viewState.m_alphaRef = ref/255.0f;
  5225. }
  5226. #if BGFX_CONFIG_RENDERER_OPENGL
  5227. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  5228. {
  5229. float pointSize = (float)(bx::uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  5230. GL_CHECK(glPointSize(pointSize) );
  5231. }
  5232. if (BGFX_STATE_MSAA & changedFlags)
  5233. {
  5234. GL_CHECK(BGFX_STATE_MSAA & newFlags
  5235. ? glEnable(GL_MULTISAMPLE)
  5236. : glDisable(GL_MULTISAMPLE)
  5237. );
  5238. }
  5239. if (BGFX_STATE_LINEAA & changedFlags)
  5240. {
  5241. GL_CHECK(BGFX_STATE_LINEAA & newFlags
  5242. ? glEnable(GL_LINE_SMOOTH)
  5243. : glDisable(GL_LINE_SMOOTH)
  5244. );
  5245. }
  5246. if (m_conservativeRasterSupport
  5247. && BGFX_STATE_CONSERVATIVE_RASTER & changedFlags)
  5248. {
  5249. GL_CHECK(BGFX_STATE_CONSERVATIVE_RASTER & newFlags
  5250. ? glEnable(GL_CONSERVATIVE_RASTERIZATION_NV)
  5251. : glDisable(GL_CONSERVATIVE_RASTERIZATION_NV)
  5252. );
  5253. }
  5254. #endif // BGFX_CONFIG_RENDERER_OPENGL
  5255. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  5256. {
  5257. GLboolean alpha = !!(newFlags&BGFX_STATE_ALPHA_WRITE);
  5258. GLboolean rgb = !!(newFlags&BGFX_STATE_RGB_WRITE);
  5259. GL_CHECK(glColorMask(rgb, rgb, rgb, alpha) );
  5260. }
  5261. if ( ( (0
  5262. | BGFX_STATE_BLEND_MASK
  5263. | BGFX_STATE_BLEND_EQUATION_MASK
  5264. | BGFX_STATE_BLEND_INDEPENDENT
  5265. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  5266. ) & changedFlags)
  5267. || blendFactor != draw.m_rgba)
  5268. {
  5269. if (m_atocSupport)
  5270. {
  5271. if (BGFX_STATE_BLEND_ALPHA_TO_COVERAGE & newFlags)
  5272. {
  5273. GL_CHECK(glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) );
  5274. }
  5275. else
  5276. {
  5277. GL_CHECK(glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE) );
  5278. }
  5279. }
  5280. if ( ( (0
  5281. | BGFX_STATE_BLEND_MASK
  5282. | BGFX_STATE_BLEND_EQUATION_MASK
  5283. | BGFX_STATE_BLEND_INDEPENDENT) & newFlags)
  5284. || blendFactor != draw.m_rgba)
  5285. {
  5286. const bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  5287. const bool independent = !!(BGFX_STATE_BLEND_INDEPENDENT & newFlags)
  5288. && blendIndependentSupported
  5289. ;
  5290. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  5291. const uint32_t srcRGB = (blend )&0xf;
  5292. const uint32_t dstRGB = (blend>> 4)&0xf;
  5293. const uint32_t srcA = (blend>> 8)&0xf;
  5294. const uint32_t dstA = (blend>>12)&0xf;
  5295. const uint32_t equ = uint32_t( (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  5296. const uint32_t equRGB = (equ )&0x7;
  5297. const uint32_t equA = (equ>>3)&0x7;
  5298. const uint32_t numRt = getNumRt();
  5299. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  5300. || 1 >= numRt
  5301. || !independent)
  5302. {
  5303. if (enabled)
  5304. {
  5305. GL_CHECK(glEnable(GL_BLEND) );
  5306. GL_CHECK(glBlendFuncSeparate(s_blendFactor[srcRGB].m_src
  5307. , s_blendFactor[dstRGB].m_dst
  5308. , s_blendFactor[srcA].m_src
  5309. , s_blendFactor[dstA].m_dst
  5310. ) );
  5311. GL_CHECK(glBlendEquationSeparate(s_blendEquation[equRGB], s_blendEquation[equA]) );
  5312. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  5313. && blendFactor != draw.m_rgba)
  5314. {
  5315. const uint32_t rgba = draw.m_rgba;
  5316. GLclampf rr = ( (rgba>>24) )/255.0f;
  5317. GLclampf gg = ( (rgba>>16)&0xff)/255.0f;
  5318. GLclampf bb = ( (rgba>> 8)&0xff)/255.0f;
  5319. GLclampf aa = ( (rgba )&0xff)/255.0f;
  5320. GL_CHECK(glBlendColor(rr, gg, bb, aa) );
  5321. }
  5322. }
  5323. else
  5324. {
  5325. GL_CHECK(glDisable(GL_BLEND) );
  5326. }
  5327. }
  5328. else
  5329. {
  5330. if (enabled)
  5331. {
  5332. GL_CHECK(glEnablei(GL_BLEND, 0) );
  5333. GL_CHECK(glBlendFuncSeparatei(0
  5334. , s_blendFactor[srcRGB].m_src
  5335. , s_blendFactor[dstRGB].m_dst
  5336. , s_blendFactor[srcA].m_src
  5337. , s_blendFactor[dstA].m_dst
  5338. ) );
  5339. GL_CHECK(glBlendEquationSeparatei(0
  5340. , s_blendEquation[equRGB]
  5341. , s_blendEquation[equA]
  5342. ) );
  5343. }
  5344. else
  5345. {
  5346. GL_CHECK(glDisablei(GL_BLEND, 0) );
  5347. }
  5348. for (uint32_t ii = 1, rgba = draw.m_rgba; ii < numRt; ++ii, rgba >>= 11)
  5349. {
  5350. if (0 != (rgba&0x7ff) )
  5351. {
  5352. const uint32_t src = (rgba )&0xf;
  5353. const uint32_t dst = (rgba>>4)&0xf;
  5354. const uint32_t equation = (rgba>>8)&0x7;
  5355. GL_CHECK(glEnablei(GL_BLEND, ii) );
  5356. GL_CHECK(glBlendFunci(ii, s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) );
  5357. GL_CHECK(glBlendEquationi(ii, s_blendEquation[equation]) );
  5358. }
  5359. else
  5360. {
  5361. GL_CHECK(glDisablei(GL_BLEND, ii) );
  5362. }
  5363. }
  5364. }
  5365. }
  5366. else
  5367. {
  5368. GL_CHECK(glDisable(GL_BLEND) );
  5369. }
  5370. blendFactor = draw.m_rgba;
  5371. }
  5372. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : newFlags&BGFX_STATE_PT_MASK;
  5373. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  5374. prim = s_primInfo[primIndex];
  5375. }
  5376. bool programChanged = false;
  5377. bool constantsChanged = draw.m_constBegin < draw.m_constEnd;
  5378. bool bindAttribs = false;
  5379. rendererUpdateUniforms(this, _render->m_uniformBuffer, draw.m_constBegin, draw.m_constEnd);
  5380. if (key.m_program != programIdx)
  5381. {
  5382. programIdx = key.m_program;
  5383. GLuint id = invalidHandle == programIdx ? 0 : m_program[programIdx].m_id;
  5384. // Skip rendering if program index is valid, but program is invalid.
  5385. programIdx = 0 == id ? invalidHandle : programIdx;
  5386. GL_CHECK(glUseProgram(id) );
  5387. programChanged =
  5388. constantsChanged =
  5389. bindAttribs = true;
  5390. }
  5391. if (invalidHandle != programIdx)
  5392. {
  5393. ProgramGL& program = m_program[programIdx];
  5394. if (constantsChanged
  5395. && NULL != program.m_constantBuffer)
  5396. {
  5397. commit(*program.m_constantBuffer);
  5398. }
  5399. viewState.setPredefined<1>(this, view, eye, program, _render, draw);
  5400. {
  5401. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  5402. {
  5403. const Binding& bind = draw.m_bind[stage];
  5404. Binding& current = currentState.m_bind[stage];
  5405. if (current.m_idx != bind.m_idx
  5406. || current.m_un.m_draw.m_textureFlags != bind.m_un.m_draw.m_textureFlags
  5407. || programChanged)
  5408. {
  5409. if (invalidHandle != bind.m_idx)
  5410. {
  5411. TextureGL& texture = m_textures[bind.m_idx];
  5412. texture.commit(stage, bind.m_un.m_draw.m_textureFlags, _render->m_colorPalette);
  5413. }
  5414. }
  5415. current = bind;
  5416. }
  5417. }
  5418. if (0 != defaultVao
  5419. && 0 == draw.m_startVertex
  5420. && 0 == draw.m_instanceDataOffset)
  5421. {
  5422. if (programChanged
  5423. || baseVertex != draw.m_startVertex
  5424. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  5425. || currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx
  5426. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  5427. || currentState.m_instanceDataStride != draw.m_instanceDataStride
  5428. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx)
  5429. {
  5430. bx::HashMurmur2A murmur;
  5431. murmur.begin();
  5432. murmur.add(draw.m_vertexBuffer.idx);
  5433. if (isValid(draw.m_vertexBuffer) )
  5434. {
  5435. const VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  5436. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  5437. murmur.add(decl);
  5438. }
  5439. murmur.add(draw.m_indexBuffer.idx);
  5440. murmur.add(draw.m_instanceDataBuffer.idx);
  5441. murmur.add(draw.m_instanceDataOffset);
  5442. murmur.add(draw.m_instanceDataStride);
  5443. murmur.add(programIdx);
  5444. uint32_t hash = murmur.end();
  5445. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  5446. currentState.m_indexBuffer = draw.m_indexBuffer;
  5447. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  5448. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  5449. baseVertex = draw.m_startVertex;
  5450. GLuint id = m_vaoStateCache.find(hash);
  5451. if (UINT32_MAX != id)
  5452. {
  5453. currentVao = id;
  5454. GL_CHECK(glBindVertexArray(id) );
  5455. }
  5456. else
  5457. {
  5458. id = m_vaoStateCache.add(hash);
  5459. currentVao = id;
  5460. GL_CHECK(glBindVertexArray(id) );
  5461. program.add(hash);
  5462. if (isValid(draw.m_vertexBuffer) )
  5463. {
  5464. VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  5465. vb.add(hash);
  5466. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  5467. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  5468. program.bindAttributes(m_vertexDecls[decl], draw.m_startVertex);
  5469. if (isValid(draw.m_instanceDataBuffer) )
  5470. {
  5471. VertexBufferGL& instanceVb = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  5472. instanceVb.add(hash);
  5473. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, instanceVb.m_id) );
  5474. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  5475. }
  5476. }
  5477. else
  5478. {
  5479. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  5480. }
  5481. if (isValid(draw.m_indexBuffer) )
  5482. {
  5483. IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  5484. ib.add(hash);
  5485. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  5486. }
  5487. else
  5488. {
  5489. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  5490. }
  5491. }
  5492. }
  5493. }
  5494. else
  5495. {
  5496. if (0 != defaultVao
  5497. && 0 != currentVao)
  5498. {
  5499. GL_CHECK(glBindVertexArray(defaultVao) );
  5500. currentState.m_vertexBuffer.idx = invalidHandle;
  5501. currentState.m_indexBuffer.idx = invalidHandle;
  5502. bindAttribs = true;
  5503. currentVao = 0;
  5504. }
  5505. if (programChanged
  5506. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  5507. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  5508. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  5509. || currentState.m_instanceDataStride != draw.m_instanceDataStride)
  5510. {
  5511. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  5512. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  5513. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  5514. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  5515. uint16_t handle = draw.m_vertexBuffer.idx;
  5516. if (invalidHandle != handle)
  5517. {
  5518. VertexBufferGL& vb = m_vertexBuffers[handle];
  5519. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  5520. bindAttribs = true;
  5521. }
  5522. else
  5523. {
  5524. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  5525. }
  5526. }
  5527. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  5528. {
  5529. currentState.m_indexBuffer = draw.m_indexBuffer;
  5530. uint16_t handle = draw.m_indexBuffer.idx;
  5531. if (invalidHandle != handle)
  5532. {
  5533. IndexBufferGL& ib = m_indexBuffers[handle];
  5534. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  5535. }
  5536. else
  5537. {
  5538. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  5539. }
  5540. }
  5541. if (isValid(currentState.m_vertexBuffer) )
  5542. {
  5543. if (baseVertex != draw.m_startVertex
  5544. || bindAttribs)
  5545. {
  5546. baseVertex = draw.m_startVertex;
  5547. const VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  5548. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  5549. program.bindAttributes(m_vertexDecls[decl], draw.m_startVertex);
  5550. if (isValid(draw.m_instanceDataBuffer) )
  5551. {
  5552. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffers[draw.m_instanceDataBuffer.idx].m_id) );
  5553. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  5554. }
  5555. }
  5556. }
  5557. }
  5558. if (isValid(currentState.m_vertexBuffer) )
  5559. {
  5560. uint32_t numVertices = draw.m_numVertices;
  5561. if (UINT32_MAX == numVertices)
  5562. {
  5563. const VertexBufferGL& vb = m_vertexBuffers[currentState.m_vertexBuffer.idx];
  5564. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  5565. const VertexDecl& vertexDecl = m_vertexDecls[decl];
  5566. numVertices = vb.m_size/vertexDecl.m_stride;
  5567. }
  5568. uint32_t numIndices = 0;
  5569. uint32_t numPrimsSubmitted = 0;
  5570. uint32_t numInstances = 0;
  5571. uint32_t numPrimsRendered = 0;
  5572. uint32_t numDrawIndirect = 0;
  5573. if (hasOcclusionQuery)
  5574. {
  5575. m_occlusionQuery.begin(_render, draw.m_occlusionQuery);
  5576. }
  5577. if (isValid(draw.m_indirectBuffer) )
  5578. {
  5579. const VertexBufferGL& vb = m_vertexBuffers[draw.m_indirectBuffer.idx];
  5580. if (currentState.m_indirectBuffer.idx != draw.m_indirectBuffer.idx)
  5581. {
  5582. currentState.m_indirectBuffer = draw.m_indirectBuffer;
  5583. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, vb.m_id) );
  5584. }
  5585. if (isValid(draw.m_indexBuffer) )
  5586. {
  5587. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  5588. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  5589. const GLenum indexFormat = hasIndex16
  5590. ? GL_UNSIGNED_SHORT
  5591. : GL_UNSIGNED_INT
  5592. ;
  5593. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  5594. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  5595. : draw.m_numIndirect
  5596. ;
  5597. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5598. GL_CHECK(glMultiDrawElementsIndirect(prim.m_type, indexFormat
  5599. , (void*)args
  5600. , numDrawIndirect
  5601. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  5602. ) );
  5603. }
  5604. else
  5605. {
  5606. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  5607. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  5608. : draw.m_numIndirect
  5609. ;
  5610. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5611. GL_CHECK(glMultiDrawArraysIndirect(prim.m_type
  5612. , (void*)args
  5613. , numDrawIndirect
  5614. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  5615. ) );
  5616. }
  5617. }
  5618. else
  5619. {
  5620. if (isValid(currentState.m_indirectBuffer) )
  5621. {
  5622. currentState.m_indirectBuffer.idx = invalidHandle;
  5623. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0) );
  5624. }
  5625. if (isValid(draw.m_indexBuffer) )
  5626. {
  5627. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  5628. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  5629. const uint32_t indexSize = hasIndex16 ? 2 : 4;
  5630. const GLenum indexFormat = hasIndex16
  5631. ? GL_UNSIGNED_SHORT
  5632. : GL_UNSIGNED_INT
  5633. ;
  5634. if (UINT32_MAX == draw.m_numIndices)
  5635. {
  5636. numIndices = ib.m_size/indexSize;
  5637. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  5638. numInstances = draw.m_numInstances;
  5639. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  5640. GL_CHECK(glDrawElementsInstanced(prim.m_type
  5641. , numIndices
  5642. , indexFormat
  5643. , (void*)0
  5644. , draw.m_numInstances
  5645. ) );
  5646. }
  5647. else if (prim.m_min <= draw.m_numIndices)
  5648. {
  5649. numIndices = draw.m_numIndices;
  5650. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  5651. numInstances = draw.m_numInstances;
  5652. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  5653. GL_CHECK(glDrawElementsInstanced(prim.m_type
  5654. , numIndices
  5655. , indexFormat
  5656. , (void*)(uintptr_t)(draw.m_startIndex*indexSize)
  5657. , draw.m_numInstances
  5658. ) );
  5659. }
  5660. }
  5661. else
  5662. {
  5663. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  5664. numInstances = draw.m_numInstances;
  5665. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  5666. GL_CHECK(glDrawArraysInstanced(prim.m_type
  5667. , 0
  5668. , numVertices
  5669. , draw.m_numInstances
  5670. ) );
  5671. }
  5672. }
  5673. if (hasOcclusionQuery)
  5674. {
  5675. m_occlusionQuery.end();
  5676. }
  5677. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  5678. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  5679. statsNumInstances[primIndex] += numInstances;
  5680. statsNumIndices += numIndices;
  5681. }
  5682. }
  5683. }
  5684. blitMsaaFbo();
  5685. if (m_vaoSupport)
  5686. {
  5687. GL_CHECK(glBindVertexArray(m_vao) );
  5688. }
  5689. if (0 < _render->m_num)
  5690. {
  5691. if (0 != (m_resolution.m_flags & BGFX_RESET_FLUSH_AFTER_RENDER) )
  5692. {
  5693. GL_CHECK(glFlush() );
  5694. }
  5695. captureElapsed = -bx::getHPCounter();
  5696. capture();
  5697. captureElapsed += bx::getHPCounter();
  5698. BGFX_GPU_PROFILER_END();
  5699. BGFX_PROFILER_END();
  5700. }
  5701. }
  5702. BGFX_GPU_PROFILER_END();
  5703. m_glctx.makeCurrent(NULL);
  5704. int64_t now = bx::getHPCounter();
  5705. elapsed += now;
  5706. static int64_t last = now;
  5707. Stats& perfStats = _render->m_perfStats;
  5708. perfStats.cpuTimeBegin = last;
  5709. int64_t frameTime = now - last;
  5710. last = now;
  5711. static int64_t min = frameTime;
  5712. static int64_t max = frameTime;
  5713. min = min > frameTime ? frameTime : min;
  5714. max = max < frameTime ? frameTime : max;
  5715. static uint32_t maxGpuLatency = 0;
  5716. static double maxGpuElapsed = 0.0f;
  5717. double elapsedGpuMs = 0.0;
  5718. uint64_t elapsedGl = 0;
  5719. if (m_timerQuerySupport)
  5720. {
  5721. m_gpuTimer.end();
  5722. while (m_gpuTimer.get() )
  5723. {
  5724. elapsedGl = m_gpuTimer.m_elapsed;
  5725. elapsedGpuMs = double(elapsedGl)/1e6;
  5726. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  5727. }
  5728. maxGpuLatency = bx::uint32_imax(maxGpuLatency, m_gpuTimer.m_control.available()-1);
  5729. }
  5730. const int64_t timerFreq = bx::getHPFrequency();
  5731. perfStats.cpuTimeEnd = now;
  5732. perfStats.cpuTimerFreq = timerFreq;
  5733. perfStats.gpuTimeBegin = m_gpuTimer.m_begin;
  5734. perfStats.gpuTimeEnd = m_gpuTimer.m_end;
  5735. perfStats.gpuTimerFreq = 1000000000;
  5736. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  5737. {
  5738. TextVideoMem& tvm = m_textVideoMem;
  5739. static int64_t next = now;
  5740. if (now >= next)
  5741. {
  5742. next = now + timerFreq;
  5743. double freq = double(timerFreq);
  5744. double toMs = 1000.0/freq;
  5745. tvm.clear();
  5746. uint16_t pos = 0;
  5747. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  5748. , getRendererName()
  5749. );
  5750. tvm.printf(0, pos++, 0x8f, " Vendor: %s ", m_vendor);
  5751. tvm.printf(0, pos++, 0x8f, " Renderer: %s ", m_renderer);
  5752. tvm.printf(0, pos++, 0x8f, " Version: %s ", m_version);
  5753. tvm.printf(0, pos++, 0x8f, " GLSL version: %s ", m_glslVersion);
  5754. char processMemoryUsed[16];
  5755. bx::prettify(processMemoryUsed, BX_COUNTOF(processMemoryUsed), bx::getProcessMemoryUsed() );
  5756. tvm.printf(0, pos++, 0x8f, " Memory: %s (process) ", processMemoryUsed);
  5757. pos = 10;
  5758. tvm.printf(10, pos++, 0x8e, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  5759. , double(frameTime)*toMs
  5760. , double(min)*toMs
  5761. , double(max)*toMs
  5762. , freq/frameTime
  5763. );
  5764. char hmd[16];
  5765. bx::snprintf(hmd, BX_COUNTOF(hmd), ", [%c] HMD ", hmdEnabled ? '\xfe' : ' ');
  5766. const uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  5767. tvm.printf(10, pos++, 0x8e, " Reset flags: [%c] vsync, [%c] MSAAx%d%s, [%c] MaxAnisotropy "
  5768. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  5769. , 0 != msaa ? '\xfe' : ' '
  5770. , 1<<msaa
  5771. , m_ovr.isInitialized() ? hmd : ", no-HMD "
  5772. , !!(m_resolution.m_flags&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  5773. );
  5774. double elapsedCpuMs = double(elapsed)*toMs;
  5775. tvm.printf(10, pos++, 0x8e, " Submitted: %5d (draw %5d, compute %4d) / CPU %7.4f [ms] %c GPU %7.4f [ms] (latency %d) "
  5776. , _render->m_num
  5777. , statsKeyType[0]
  5778. , statsKeyType[1]
  5779. , elapsedCpuMs
  5780. , elapsedCpuMs > elapsedGpuMs ? '>' : '<'
  5781. , maxGpuElapsed
  5782. , maxGpuLatency
  5783. );
  5784. maxGpuLatency = 0;
  5785. maxGpuElapsed = 0.0;
  5786. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primInfo); ++ii)
  5787. {
  5788. tvm.printf(10, pos++, 0x8e, " %10s: %7d (#inst: %5d), submitted: %7d "
  5789. , s_primName[ii]
  5790. , statsNumPrimsRendered[ii]
  5791. , statsNumInstances[ii]
  5792. , statsNumPrimsSubmitted[ii]
  5793. );
  5794. }
  5795. if (NULL != m_renderdocdll)
  5796. {
  5797. tvm.printf(tvm.m_width-27, 0, 0x1f, " [F11 - RenderDoc capture] ");
  5798. }
  5799. tvm.printf(10, pos++, 0x8e, " Indices: %7d ", statsNumIndices);
  5800. tvm.printf(10, pos++, 0x8e, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax);
  5801. tvm.printf(10, pos++, 0x8e, " DVB size: %7d ", _render->m_vboffset);
  5802. tvm.printf(10, pos++, 0x8e, " DIB size: %7d ", _render->m_iboffset);
  5803. pos++;
  5804. tvm.printf(10, pos++, 0x8e, " State cache: ");
  5805. tvm.printf(10, pos++, 0x8e, " VAO | Sampler ");
  5806. tvm.printf(10, pos++, 0x8e, " %6d | %6d "
  5807. , m_vaoStateCache.getCount()
  5808. , m_samplerStateCache.getCount()
  5809. );
  5810. #if BGFX_CONFIG_RENDERER_OPENGL
  5811. if (s_extension[Extension::ATI_meminfo].m_supported)
  5812. {
  5813. GLint vboFree[4];
  5814. GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) );
  5815. GLint texFree[4];
  5816. GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) );
  5817. GLint rbfFree[4];
  5818. GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) );
  5819. pos++;
  5820. tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb ");
  5821. char tmp0[16];
  5822. char tmp1[16];
  5823. char tmp2[16];
  5824. char tmp3[16];
  5825. bx::prettify(tmp0, BX_COUNTOF(tmp0), vboFree[0]);
  5826. bx::prettify(tmp1, BX_COUNTOF(tmp1), vboFree[1]);
  5827. bx::prettify(tmp2, BX_COUNTOF(tmp2), vboFree[2]);
  5828. bx::prettify(tmp3, BX_COUNTOF(tmp3), vboFree[3]);
  5829. tvm.printf(10, pos++, 0x8e, " VBO: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  5830. bx::prettify(tmp0, BX_COUNTOF(tmp0), texFree[0]);
  5831. bx::prettify(tmp1, BX_COUNTOF(tmp1), texFree[1]);
  5832. bx::prettify(tmp2, BX_COUNTOF(tmp2), texFree[2]);
  5833. bx::prettify(tmp3, BX_COUNTOF(tmp3), texFree[3]);
  5834. tvm.printf(10, pos++, 0x8e, " Texture: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  5835. bx::prettify(tmp0, BX_COUNTOF(tmp0), rbfFree[0]);
  5836. bx::prettify(tmp1, BX_COUNTOF(tmp1), rbfFree[1]);
  5837. bx::prettify(tmp2, BX_COUNTOF(tmp2), rbfFree[2]);
  5838. bx::prettify(tmp3, BX_COUNTOF(tmp3), rbfFree[3]);
  5839. tvm.printf(10, pos++, 0x8e, " Render Buffer: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  5840. }
  5841. else if (s_extension[Extension::NVX_gpu_memory_info].m_supported)
  5842. {
  5843. GLint dedicated;
  5844. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) );
  5845. GLint totalAvail;
  5846. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) );
  5847. GLint currAvail;
  5848. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) );
  5849. GLint evictedCount;
  5850. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) );
  5851. GLint evictedMemory;
  5852. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) );
  5853. pos++;
  5854. char tmp0[16];
  5855. char tmp1[16];
  5856. bx::prettify(tmp0, BX_COUNTOF(tmp0), dedicated);
  5857. tvm.printf(10, pos++, 0x8e, " Dedicated: %10s ", tmp0);
  5858. bx::prettify(tmp0, BX_COUNTOF(tmp0), currAvail);
  5859. bx::prettify(tmp1, BX_COUNTOF(tmp1), totalAvail);
  5860. tvm.printf(10, pos++, 0x8e, " Available: %10s / %10s ", tmp0, tmp1);
  5861. bx::prettify(tmp0, BX_COUNTOF(tmp0), evictedCount);
  5862. bx::prettify(tmp1, BX_COUNTOF(tmp1), evictedMemory);
  5863. tvm.printf(10, pos++, 0x8e, " Eviction: %10s / %10s ", tmp0, tmp1);
  5864. }
  5865. #endif // BGFX_CONFIG_RENDERER_OPENGL
  5866. pos++;
  5867. double captureMs = double(captureElapsed)*toMs;
  5868. tvm.printf(10, pos++, 0x8e, " Capture: %7.4f [ms] ", captureMs);
  5869. uint8_t attr[2] = { 0x89, 0x8a };
  5870. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  5871. tvm.printf(10, pos++, attr[attrIndex&1], " Submit wait: %7.4f [ms] ", double(_render->m_waitSubmit)*toMs);
  5872. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %7.4f [ms] ", double(_render->m_waitRender)*toMs);
  5873. min = frameTime;
  5874. max = frameTime;
  5875. }
  5876. blit(this, _textVideoMemBlitter, tvm);
  5877. }
  5878. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  5879. {
  5880. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  5881. }
  5882. GL_CHECK(glFrameTerminatorGREMEDY() );
  5883. }
  5884. } } // namespace bgfx
  5885. #undef BGFX_GPU_PROFILER_BIND
  5886. #undef BGFX_GPU_PROFILER_UNBIND
  5887. #undef BGFX_GPU_PROFILER_BEGIN
  5888. #undef BGFX_GPU_PROFILER_BEGIN_DYNAMIC
  5889. #undef BGFX_GPU_PROFILER_END
  5890. #else
  5891. namespace bgfx { namespace gl
  5892. {
  5893. RendererContextI* rendererCreate()
  5894. {
  5895. return NULL;
  5896. }
  5897. void rendererDestroy()
  5898. {
  5899. }
  5900. } /* namespace gl */ } // namespace bgfx
  5901. #endif // (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)