renderer_gl.cpp 230 KB

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