renderer_gl.cpp 216 KB

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