renderer_gl.cpp 201 KB

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