renderer_gl.cpp 232 KB

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