renderer_gl.cpp 234 KB

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