renderer_gl.cpp 271 KB

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