renderer_gl.cpp 216 KB

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