renderer_gl.cpp 230 KB

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