renderer_gl.cpp 188 KB

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