renderer_gl.cpp 169 KB

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