renderer_gl.cpp 202 KB

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