renderer_gl.cpp 234 KB

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