renderer_gl.cpp 225 KB

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