renderer_gl.cpp 230 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669
  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 = bx::strnchr(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. bx::strlncpy(name, BX_COUNTOF(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 == bx::strncmp(ext, "GL_", 3) ) // skip GL_
  1224. {
  1225. ext += 3;
  1226. }
  1227. if (0 == bx::strncmp(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. bx::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. bx::memSet(m_uniforms, 0, sizeof(m_uniforms) );
  1312. bx::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 == bx::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 == bx::strncmp(m_vendor, "Imagination Technologies")
  1393. && NULL != bx::strnstr(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 = bx::strnchr(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. bx::strlncpy(name, BX_COUNTOF(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. bx::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. // Ensure the back buffer is bound as the source of the flip
  2038. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo));
  2039. // need to swap GL render context even if OVR is enabled to get
  2040. // the mirror texture in the output
  2041. m_glctx.swap();
  2042. m_needPresent = false;
  2043. }
  2044. }
  2045. }
  2046. void createIndexBuffer(IndexBufferHandle _handle, Memory* _mem, uint16_t _flags) BX_OVERRIDE
  2047. {
  2048. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  2049. }
  2050. void destroyIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  2051. {
  2052. m_indexBuffers[_handle.idx].destroy();
  2053. }
  2054. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) BX_OVERRIDE
  2055. {
  2056. VertexDecl& decl = m_vertexDecls[_handle.idx];
  2057. bx::memCopy(&decl, &_decl, sizeof(VertexDecl) );
  2058. dump(decl);
  2059. }
  2060. void destroyVertexDecl(VertexDeclHandle /*_handle*/) BX_OVERRIDE
  2061. {
  2062. }
  2063. void createVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle, uint16_t _flags) BX_OVERRIDE
  2064. {
  2065. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle, _flags);
  2066. }
  2067. void destroyVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  2068. {
  2069. m_vertexBuffers[_handle.idx].destroy();
  2070. }
  2071. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  2072. {
  2073. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  2074. }
  2075. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  2076. {
  2077. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  2078. }
  2079. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  2080. {
  2081. m_indexBuffers[_handle.idx].destroy();
  2082. }
  2083. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  2084. {
  2085. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  2086. m_vertexBuffers[_handle.idx].create(_size, NULL, decl, _flags);
  2087. }
  2088. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  2089. {
  2090. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  2091. }
  2092. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  2093. {
  2094. m_vertexBuffers[_handle.idx].destroy();
  2095. }
  2096. void createShader(ShaderHandle _handle, Memory* _mem) BX_OVERRIDE
  2097. {
  2098. m_shaders[_handle.idx].create(_mem);
  2099. }
  2100. void destroyShader(ShaderHandle _handle) BX_OVERRIDE
  2101. {
  2102. m_shaders[_handle.idx].destroy();
  2103. }
  2104. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) BX_OVERRIDE
  2105. {
  2106. ShaderGL dummyFragmentShader;
  2107. m_program[_handle.idx].create(m_shaders[_vsh.idx], isValid(_fsh) ? m_shaders[_fsh.idx] : dummyFragmentShader);
  2108. }
  2109. void destroyProgram(ProgramHandle _handle) BX_OVERRIDE
  2110. {
  2111. m_program[_handle.idx].destroy();
  2112. }
  2113. void createTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags, uint8_t _skip) BX_OVERRIDE
  2114. {
  2115. m_textures[_handle.idx].create(_mem, _flags, _skip);
  2116. }
  2117. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) BX_OVERRIDE
  2118. {
  2119. }
  2120. 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
  2121. {
  2122. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  2123. }
  2124. void updateTextureEnd() BX_OVERRIDE
  2125. {
  2126. }
  2127. void readTexture(TextureHandle _handle, void* _data, uint8_t _mip) BX_OVERRIDE
  2128. {
  2129. if (m_readBackSupported)
  2130. {
  2131. const TextureGL& texture = m_textures[_handle.idx];
  2132. const bool compressed = isCompressed(TextureFormat::Enum(texture.m_textureFormat) );
  2133. GL_CHECK(glBindTexture(texture.m_target, texture.m_id) );
  2134. if (compressed)
  2135. {
  2136. GL_CHECK(glGetCompressedTexImage(texture.m_target
  2137. , _mip
  2138. , _data
  2139. ) );
  2140. }
  2141. else
  2142. {
  2143. GL_CHECK(glGetTexImage(texture.m_target
  2144. , _mip
  2145. , texture.m_fmt
  2146. , texture.m_type
  2147. , _data
  2148. ) );
  2149. }
  2150. GL_CHECK(glBindTexture(texture.m_target, 0) );
  2151. }
  2152. }
  2153. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips) BX_OVERRIDE
  2154. {
  2155. TextureGL& texture = m_textures[_handle.idx];
  2156. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  2157. const Memory* mem = alloc(size);
  2158. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  2159. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  2160. bx::write(&writer, magic);
  2161. TextureCreate tc;
  2162. tc.m_width = _width;
  2163. tc.m_height = _height;
  2164. tc.m_depth = 0;
  2165. tc.m_numLayers = 1;
  2166. tc.m_numMips = _numMips;
  2167. tc.m_format = TextureFormat::Enum(texture.m_requestedFormat);
  2168. tc.m_cubeMap = false;
  2169. tc.m_mem = NULL;
  2170. bx::write(&writer, tc);
  2171. texture.destroy();
  2172. texture.create(mem, texture.m_flags, 0);
  2173. release(mem);
  2174. }
  2175. void overrideInternal(TextureHandle _handle, uintptr_t _ptr) BX_OVERRIDE
  2176. {
  2177. m_textures[_handle.idx].overrideInternal(_ptr);
  2178. }
  2179. uintptr_t getInternal(TextureHandle _handle) BX_OVERRIDE
  2180. {
  2181. return uintptr_t(m_textures[_handle.idx].m_id);
  2182. }
  2183. void destroyTexture(TextureHandle _handle) BX_OVERRIDE
  2184. {
  2185. m_textures[_handle.idx].destroy();
  2186. }
  2187. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const Attachment* _attachment) BX_OVERRIDE
  2188. {
  2189. m_frameBuffers[_handle.idx].create(_num, _attachment);
  2190. }
  2191. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat) BX_OVERRIDE
  2192. {
  2193. uint16_t denseIdx = m_numWindows++;
  2194. m_windows[denseIdx] = _handle;
  2195. m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _depthFormat);
  2196. }
  2197. void destroyFrameBuffer(FrameBufferHandle _handle) BX_OVERRIDE
  2198. {
  2199. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  2200. if (UINT16_MAX != denseIdx)
  2201. {
  2202. --m_numWindows;
  2203. if (m_numWindows > 1)
  2204. {
  2205. FrameBufferHandle handle = m_windows[m_numWindows];
  2206. m_windows[denseIdx] = handle;
  2207. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  2208. }
  2209. }
  2210. }
  2211. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) BX_OVERRIDE
  2212. {
  2213. if (NULL != m_uniforms[_handle.idx])
  2214. {
  2215. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  2216. }
  2217. uint32_t size = g_uniformTypeSize[_type]*_num;
  2218. void* data = BX_ALLOC(g_allocator, size);
  2219. bx::memSet(data, 0, size);
  2220. m_uniforms[_handle.idx] = data;
  2221. m_uniformReg.add(_handle, _name, m_uniforms[_handle.idx]);
  2222. }
  2223. void destroyUniform(UniformHandle _handle) BX_OVERRIDE
  2224. {
  2225. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  2226. m_uniforms[_handle.idx] = NULL;
  2227. m_uniformReg.remove(_handle);
  2228. }
  2229. void requestScreenShot(FrameBufferHandle _handle, const char* _filePath) BX_OVERRIDE
  2230. {
  2231. SwapChainGL* swapChain = NULL;
  2232. uint32_t width = m_resolution.m_width;
  2233. uint32_t height = m_resolution.m_height;
  2234. if (isValid(_handle) )
  2235. {
  2236. const FrameBufferGL& frameBuffer = m_frameBuffers[_handle.idx];
  2237. swapChain = frameBuffer.m_swapChain;
  2238. width = frameBuffer.m_width;
  2239. height = frameBuffer.m_height;
  2240. }
  2241. m_glctx.makeCurrent(swapChain);
  2242. uint32_t length = width*height*4;
  2243. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2244. GL_CHECK(glReadPixels(0
  2245. , 0
  2246. , width
  2247. , height
  2248. , m_readPixelsFmt
  2249. , GL_UNSIGNED_BYTE
  2250. , data
  2251. ) );
  2252. if (GL_RGBA == m_readPixelsFmt)
  2253. {
  2254. imageSwizzleBgra8(data, width, height, width*4, data);
  2255. }
  2256. g_callback->screenShot(_filePath
  2257. , width
  2258. , height
  2259. , width*4
  2260. , data
  2261. , length
  2262. , true
  2263. );
  2264. BX_FREE(g_allocator, data);
  2265. }
  2266. void updateViewName(uint8_t _id, const char* _name) BX_OVERRIDE
  2267. {
  2268. bx::strlcpy(&s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  2269. , _name
  2270. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  2271. );
  2272. }
  2273. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) BX_OVERRIDE
  2274. {
  2275. bx::memCopy(m_uniforms[_loc], _data, _size);
  2276. }
  2277. void setMarker(const char* _marker, uint32_t _size) BX_OVERRIDE
  2278. {
  2279. GL_CHECK(glInsertEventMarker(_size, _marker) );
  2280. }
  2281. void invalidateOcclusionQuery(OcclusionQueryHandle _handle) BX_OVERRIDE
  2282. {
  2283. m_occlusionQuery.invalidate(_handle);
  2284. }
  2285. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) BX_OVERRIDE;
  2286. void blitSetup(TextVideoMemBlitter& _blitter) BX_OVERRIDE
  2287. {
  2288. if (0 != m_vao)
  2289. {
  2290. GL_CHECK(glBindVertexArray(m_vao) );
  2291. }
  2292. uint32_t width = m_resolution.m_width;
  2293. uint32_t height = m_resolution.m_height;
  2294. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2295. GL_CHECK(glViewport(0, 0, width, height) );
  2296. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2297. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2298. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2299. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2300. GL_CHECK(glDisable(GL_CULL_FACE) );
  2301. GL_CHECK(glDisable(GL_BLEND) );
  2302. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2303. ProgramGL& program = m_program[_blitter.m_program.idx];
  2304. GL_CHECK(glUseProgram(program.m_id) );
  2305. GL_CHECK(glUniform1i(program.m_sampler[0], 0) );
  2306. float proj[16];
  2307. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  2308. GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc
  2309. , 1
  2310. , GL_FALSE
  2311. , proj
  2312. ) );
  2313. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  2314. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_textures[_blitter.m_texture.idx].m_id) );
  2315. if (!BX_ENABLED(BX_PLATFORM_OSX) )
  2316. {
  2317. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2318. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2319. {
  2320. if (m_samplerObjectSupport)
  2321. {
  2322. GL_CHECK(glBindSampler(0, 0) );
  2323. }
  2324. }
  2325. }
  2326. }
  2327. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) BX_OVERRIDE
  2328. {
  2329. const uint32_t numVertices = _numIndices*4/6;
  2330. if (0 < numVertices)
  2331. {
  2332. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices*2, _blitter.m_ib->data);
  2333. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data);
  2334. VertexBufferGL& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  2335. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2336. IndexBufferGL& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  2337. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  2338. ProgramGL& program = m_program[_blitter.m_program.idx];
  2339. program.bindAttributesBegin();
  2340. program.bindAttributes(_blitter.m_decl, 0);
  2341. program.bindAttributesEnd();
  2342. GL_CHECK(glDrawElements(GL_TRIANGLES
  2343. , _numIndices
  2344. , GL_UNSIGNED_SHORT
  2345. , (void*)0
  2346. ) );
  2347. }
  2348. }
  2349. void updateResolution(const Resolution& _resolution)
  2350. {
  2351. bool recenter = !!(_resolution.m_flags & BGFX_RESET_HMD_RECENTER);
  2352. m_maxAnisotropy = !!(_resolution.m_flags & BGFX_RESET_MAXANISOTROPY)
  2353. ? m_maxAnisotropyDefault
  2354. : 0.0f
  2355. ;
  2356. if (s_extension[Extension::ARB_depth_clamp].m_supported)
  2357. {
  2358. if (!!(_resolution.m_flags & BGFX_RESET_DEPTH_CLAMP) )
  2359. {
  2360. GL_CHECK(glEnable(GL_DEPTH_CLAMP) );
  2361. }
  2362. else
  2363. {
  2364. GL_CHECK(glDisable(GL_DEPTH_CLAMP) );
  2365. }
  2366. }
  2367. const uint32_t maskFlags = ~(0
  2368. | BGFX_RESET_HMD_RECENTER
  2369. | BGFX_RESET_MAXANISOTROPY
  2370. | BGFX_RESET_DEPTH_CLAMP
  2371. | BGFX_RESET_SUSPEND
  2372. );
  2373. if (m_resolution.m_width != _resolution.m_width
  2374. || m_resolution.m_height != _resolution.m_height
  2375. || (m_resolution.m_flags&maskFlags) != (_resolution.m_flags&maskFlags) )
  2376. {
  2377. uint32_t flags = _resolution.m_flags & (~BGFX_RESET_INTERNAL_FORCE);
  2378. m_resolution = _resolution;
  2379. m_resolution.m_flags = flags;
  2380. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  2381. m_textVideoMem.clear();
  2382. if ( (flags & BGFX_RESET_HMD)
  2383. && m_ovr.isInitialized() )
  2384. {
  2385. flags &= ~BGFX_RESET_MSAA_MASK;
  2386. }
  2387. setRenderContextSize(m_resolution.m_width
  2388. , m_resolution.m_height
  2389. , flags
  2390. );
  2391. updateCapture();
  2392. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  2393. {
  2394. m_frameBuffers[ii].postReset();
  2395. }
  2396. ovrPreReset();
  2397. ovrPostReset();
  2398. if (m_ovr.isEnabled() )
  2399. {
  2400. m_ovr.makeRenderTargetActive();
  2401. }
  2402. else
  2403. {
  2404. m_currentFbo = 0;
  2405. }
  2406. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_currentFbo) );
  2407. }
  2408. if (recenter)
  2409. {
  2410. m_ovr.recenter();
  2411. }
  2412. }
  2413. void setShaderUniform4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  2414. {
  2415. GL_CHECK(glUniform4fv(_regIndex
  2416. , _numRegs
  2417. , (const GLfloat*)_val
  2418. ) );
  2419. }
  2420. void setShaderUniform4x4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  2421. {
  2422. GL_CHECK(glUniformMatrix4fv(_regIndex
  2423. , _numRegs
  2424. , GL_FALSE
  2425. , (const GLfloat*)_val
  2426. ) );
  2427. }
  2428. uint32_t setFrameBuffer(FrameBufferHandle _fbh, uint32_t _height, uint16_t _discard = BGFX_CLEAR_NONE, bool _msaa = true)
  2429. {
  2430. if (isValid(m_fbh)
  2431. && m_fbh.idx != _fbh.idx)
  2432. {
  2433. FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  2434. frameBuffer.resolve();
  2435. if (BGFX_CLEAR_NONE != m_fbDiscard)
  2436. {
  2437. frameBuffer.discard(m_fbDiscard);
  2438. m_fbDiscard = BGFX_CLEAR_NONE;
  2439. }
  2440. }
  2441. m_glctx.makeCurrent(NULL);
  2442. if (!isValid(_fbh) )
  2443. {
  2444. m_needPresent |= true;
  2445. if (m_ovr.isEnabled() )
  2446. {
  2447. m_ovr.makeRenderTargetActive();
  2448. }
  2449. else
  2450. {
  2451. m_currentFbo = m_msaaBackBufferFbo;
  2452. }
  2453. if (m_srgbWriteControlSupport)
  2454. {
  2455. if (0 != (m_resolution.m_flags & BGFX_RESET_SRGB_BACKBUFFER) )
  2456. {
  2457. GL_CHECK(glEnable(GL_FRAMEBUFFER_SRGB) );
  2458. }
  2459. else
  2460. {
  2461. GL_CHECK(glDisable(GL_FRAMEBUFFER_SRGB) );
  2462. }
  2463. }
  2464. }
  2465. else
  2466. {
  2467. FrameBufferGL& frameBuffer = m_frameBuffers[_fbh.idx];
  2468. _height = frameBuffer.m_height;
  2469. if (UINT16_MAX != frameBuffer.m_denseIdx)
  2470. {
  2471. m_glctx.makeCurrent(frameBuffer.m_swapChain);
  2472. frameBuffer.m_needPresent = true;
  2473. m_currentFbo = 0;
  2474. }
  2475. else
  2476. {
  2477. m_glctx.makeCurrent(NULL);
  2478. m_currentFbo = frameBuffer.m_fbo[0];
  2479. }
  2480. }
  2481. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_currentFbo) );
  2482. m_fbh = _fbh;
  2483. m_fbDiscard = _discard;
  2484. m_rtMsaa = _msaa;
  2485. return _height;
  2486. }
  2487. uint32_t getNumRt() const
  2488. {
  2489. if (isValid(m_fbh) )
  2490. {
  2491. const FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  2492. return frameBuffer.m_num;
  2493. }
  2494. return 1;
  2495. }
  2496. void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa)
  2497. {
  2498. if (0 == m_msaaBackBufferFbo // iOS
  2499. && 1 < _msaa)
  2500. {
  2501. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  2502. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2503. GL_CHECK(glGenRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2504. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2505. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_RGBA8, _width, _height) );
  2506. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2507. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) );
  2508. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2509. GLenum attachment = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2510. ? GL_DEPTH_STENCIL_ATTACHMENT
  2511. : GL_DEPTH_ATTACHMENT
  2512. ;
  2513. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2514. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2515. , "glCheckFramebufferStatus failed 0x%08x"
  2516. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2517. );
  2518. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2519. }
  2520. }
  2521. void destroyMsaaFbo()
  2522. {
  2523. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2524. && 0 != m_msaaBackBufferFbo)
  2525. {
  2526. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  2527. m_msaaBackBufferFbo = 0;
  2528. if (0 != m_msaaBackBufferRbos[0])
  2529. {
  2530. GL_CHECK(glDeleteRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2531. m_msaaBackBufferRbos[0] = 0;
  2532. m_msaaBackBufferRbos[1] = 0;
  2533. }
  2534. }
  2535. }
  2536. void blitMsaaFbo()
  2537. {
  2538. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2539. && 0 != m_msaaBackBufferFbo)
  2540. {
  2541. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2542. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2543. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2544. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  2545. uint32_t width = m_resolution.m_width;
  2546. uint32_t height = m_resolution.m_height;
  2547. GLenum filter = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  2548. ? GL_NEAREST
  2549. : GL_LINEAR
  2550. ;
  2551. GL_CHECK(glBlitFramebuffer(0
  2552. , 0
  2553. , width
  2554. , height
  2555. , 0
  2556. , 0
  2557. , width
  2558. , height
  2559. , GL_COLOR_BUFFER_BIT
  2560. , filter
  2561. ) );
  2562. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2563. }
  2564. }
  2565. void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _flags = 0)
  2566. {
  2567. if (_width != 0
  2568. || _height != 0)
  2569. {
  2570. if (!m_glctx.isValid() )
  2571. {
  2572. m_glctx.create(_width, _height);
  2573. #if BX_PLATFORM_IOS
  2574. // iOS: need to figure out how to deal with FBO created by context.
  2575. m_backBufferFbo = m_msaaBackBufferFbo = m_glctx.getFbo();
  2576. #endif // BX_PLATFORM_IOS
  2577. }
  2578. else
  2579. {
  2580. destroyMsaaFbo();
  2581. m_glctx.resize(_width, _height, _flags);
  2582. uint32_t msaa = (_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  2583. msaa = bx::uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  2584. createMsaaFbo(_width, _height, msaa);
  2585. }
  2586. }
  2587. m_flip = true;
  2588. }
  2589. void invalidateCache()
  2590. {
  2591. if (m_vaoSupport)
  2592. {
  2593. m_vaoStateCache.invalidate();
  2594. }
  2595. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2596. && m_samplerObjectSupport)
  2597. {
  2598. m_samplerStateCache.invalidate();
  2599. }
  2600. }
  2601. void setSamplerState(uint32_t _stage, uint32_t _numMips, uint32_t _flags, const float _rgba[4])
  2602. {
  2603. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2604. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2605. {
  2606. if (0 == (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags) )
  2607. {
  2608. const uint32_t index = (_flags & BGFX_TEXTURE_BORDER_COLOR_MASK) >> BGFX_TEXTURE_BORDER_COLOR_SHIFT;
  2609. _flags &= ~BGFX_TEXTURE_RESERVED_MASK;
  2610. _flags &= BGFX_TEXTURE_SAMPLER_BITS_MASK;
  2611. _flags |= _numMips<<BGFX_TEXTURE_RESERVED_SHIFT;
  2612. GLuint sampler;
  2613. bool hasBorderColor = false;
  2614. bx::HashMurmur2A murmur;
  2615. uint32_t hash;
  2616. murmur.begin();
  2617. murmur.add(_flags);
  2618. if (!needBorderColor(_flags) )
  2619. {
  2620. murmur.add(-1);
  2621. hash = murmur.end();
  2622. sampler = m_samplerStateCache.find(hash);
  2623. }
  2624. else
  2625. {
  2626. murmur.add(index);
  2627. hash = murmur.end();
  2628. if (NULL != _rgba)
  2629. {
  2630. hasBorderColor = true;
  2631. sampler = UINT32_MAX;
  2632. }
  2633. else
  2634. {
  2635. sampler = m_samplerStateCache.find(hash);
  2636. }
  2637. }
  2638. if (UINT32_MAX == sampler)
  2639. {
  2640. sampler = m_samplerStateCache.add(hash);
  2641. GL_CHECK(glSamplerParameteri(sampler
  2642. , GL_TEXTURE_WRAP_S
  2643. , s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]
  2644. ) );
  2645. GL_CHECK(glSamplerParameteri(sampler
  2646. , GL_TEXTURE_WRAP_T
  2647. , s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]
  2648. ) );
  2649. GL_CHECK(glSamplerParameteri(sampler
  2650. , GL_TEXTURE_WRAP_R
  2651. , s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]
  2652. ) );
  2653. GLenum minFilter;
  2654. GLenum magFilter;
  2655. getFilters(_flags, 1 < _numMips, magFilter, minFilter);
  2656. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, magFilter) );
  2657. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, minFilter) );
  2658. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2659. || m_borderColorSupport)
  2660. {
  2661. if (hasBorderColor)
  2662. {
  2663. GL_CHECK(glSamplerParameterfv(sampler, GL_TEXTURE_BORDER_COLOR, _rgba) );
  2664. }
  2665. }
  2666. if (0 != (_flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  2667. && 0.0f < m_maxAnisotropy)
  2668. {
  2669. GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy) );
  2670. }
  2671. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2672. || m_shadowSamplersSupport)
  2673. {
  2674. const uint32_t cmpFunc = (_flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  2675. if (0 == cmpFunc)
  2676. {
  2677. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  2678. }
  2679. else
  2680. {
  2681. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  2682. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  2683. }
  2684. }
  2685. }
  2686. GL_CHECK(glBindSampler(_stage, sampler) );
  2687. }
  2688. else
  2689. {
  2690. GL_CHECK(glBindSampler(_stage, 0) );
  2691. }
  2692. }
  2693. }
  2694. bool isVisible(Frame* _render, OcclusionQueryHandle _handle, bool _visible)
  2695. {
  2696. m_occlusionQuery.resolve(_render);
  2697. return _visible == (0 != _render->m_occlusion[_handle.idx]);
  2698. }
  2699. void ovrPostReset()
  2700. {
  2701. #if BGFX_CONFIG_USE_OVR
  2702. if (m_resolution.m_flags & (BGFX_RESET_HMD|BGFX_RESET_HMD_DEBUG) )
  2703. {
  2704. const uint32_t msaaSamples = 1 << ( (m_resolution.m_flags&BGFX_RESET_MSAA_MASK) >> BGFX_RESET_MSAA_SHIFT);
  2705. m_ovr.postReset(msaaSamples, m_resolution.m_width, m_resolution.m_height);
  2706. }
  2707. #endif // BGFX_CONFIG_USE_OVR
  2708. }
  2709. void ovrPreReset()
  2710. {
  2711. #if BGFX_CONFIG_USE_OVR
  2712. m_ovr.preReset();
  2713. #endif // BGFX_CONFIG_USE_OVR
  2714. }
  2715. void updateCapture()
  2716. {
  2717. if (m_resolution.m_flags&BGFX_RESET_CAPTURE)
  2718. {
  2719. m_captureSize = m_resolution.m_width*m_resolution.m_height*4;
  2720. m_capture = BX_REALLOC(g_allocator, m_capture, m_captureSize);
  2721. g_callback->captureBegin(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, TextureFormat::BGRA8, true);
  2722. }
  2723. else
  2724. {
  2725. captureFinish();
  2726. }
  2727. }
  2728. void capture()
  2729. {
  2730. if (NULL != m_capture)
  2731. {
  2732. GL_CHECK(glReadPixels(0
  2733. , 0
  2734. , m_resolution.m_width
  2735. , m_resolution.m_height
  2736. , m_readPixelsFmt
  2737. , GL_UNSIGNED_BYTE
  2738. , m_capture
  2739. ) );
  2740. if (GL_RGBA == m_readPixelsFmt)
  2741. {
  2742. imageSwizzleBgra8(m_capture, m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, m_capture);
  2743. }
  2744. g_callback->captureFrame(m_capture, m_captureSize);
  2745. }
  2746. }
  2747. void captureFinish()
  2748. {
  2749. if (NULL != m_capture)
  2750. {
  2751. g_callback->captureEnd();
  2752. BX_FREE(g_allocator, m_capture);
  2753. m_capture = NULL;
  2754. m_captureSize = 0;
  2755. }
  2756. }
  2757. bool programFetchFromCache(GLuint programId, uint64_t _id)
  2758. {
  2759. _id ^= m_hash;
  2760. bool cached = false;
  2761. if (m_programBinarySupport)
  2762. {
  2763. uint32_t length = g_callback->cacheReadSize(_id);
  2764. cached = length > 0;
  2765. if (cached)
  2766. {
  2767. void* data = BX_ALLOC(g_allocator, length);
  2768. if (g_callback->cacheRead(_id, data, length) )
  2769. {
  2770. bx::MemoryReader reader(data, length);
  2771. GLenum format;
  2772. bx::read(&reader, format);
  2773. GL_CHECK(glProgramBinary(programId, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) );
  2774. }
  2775. BX_FREE(g_allocator, data);
  2776. }
  2777. #if BGFX_CONFIG_RENDERER_OPENGL
  2778. GL_CHECK(glProgramParameteri(programId, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  2779. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2780. }
  2781. return cached;
  2782. }
  2783. void programCache(GLuint programId, uint64_t _id)
  2784. {
  2785. _id ^= m_hash;
  2786. if (m_programBinarySupport)
  2787. {
  2788. GLint programLength;
  2789. GLenum format;
  2790. GL_CHECK(glGetProgramiv(programId, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  2791. if (0 < programLength)
  2792. {
  2793. uint32_t length = programLength + 4;
  2794. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2795. GL_CHECK(glGetProgramBinary(programId, programLength, NULL, &format, &data[4]) );
  2796. *(uint32_t*)data = format;
  2797. g_callback->cacheWrite(_id, data, length);
  2798. BX_FREE(g_allocator, data);
  2799. }
  2800. }
  2801. }
  2802. void commit(UniformBuffer& _uniformBuffer)
  2803. {
  2804. _uniformBuffer.reset();
  2805. for (;;)
  2806. {
  2807. uint32_t opcode = _uniformBuffer.read();
  2808. if (UniformType::End == opcode)
  2809. {
  2810. break;
  2811. }
  2812. UniformType::Enum type;
  2813. uint16_t ignore;
  2814. uint16_t num;
  2815. uint16_t copy;
  2816. UniformBuffer::decodeOpcode(opcode, type, ignore, num, copy);
  2817. const char* data;
  2818. if (copy)
  2819. {
  2820. data = _uniformBuffer.read(g_uniformTypeSize[type]*num);
  2821. }
  2822. else
  2823. {
  2824. UniformHandle handle;
  2825. bx::memCopy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  2826. data = (const char*)m_uniforms[handle.idx];
  2827. }
  2828. uint32_t loc = _uniformBuffer.read();
  2829. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  2830. case UniformType::_uniform: \
  2831. { \
  2832. _type* value = (_type*)data; \
  2833. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  2834. } \
  2835. break;
  2836. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  2837. case UniformType::_uniform: \
  2838. { \
  2839. _type* value = (_type*)data; \
  2840. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  2841. } \
  2842. break;
  2843. switch (type)
  2844. {
  2845. // case ConstantType::Int1:
  2846. // {
  2847. // int* value = (int*)data;
  2848. // BX_TRACE("Int1 sampler %d, loc %d (num %d, copy %d)", *value, loc, num, copy);
  2849. // GL_CHECK(glUniform1iv(loc, num, value) );
  2850. // }
  2851. // break;
  2852. CASE_IMPLEMENT_UNIFORM(Int1, 1iv, I, int);
  2853. CASE_IMPLEMENT_UNIFORM(Vec4, 4fv, F, float);
  2854. CASE_IMPLEMENT_UNIFORM_T(Mat3, Matrix3fv, F, float);
  2855. CASE_IMPLEMENT_UNIFORM_T(Mat4, Matrix4fv, F, float);
  2856. case UniformType::End:
  2857. break;
  2858. default:
  2859. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy);
  2860. break;
  2861. }
  2862. #undef CASE_IMPLEMENT_UNIFORM
  2863. #undef CASE_IMPLEMENT_UNIFORM_T
  2864. }
  2865. }
  2866. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, uint32_t _height, const float _palette[][4])
  2867. {
  2868. uint32_t numMrt = 1;
  2869. FrameBufferHandle fbh = m_fbh;
  2870. if (isValid(fbh) )
  2871. {
  2872. const FrameBufferGL& fb = m_frameBuffers[fbh.idx];
  2873. numMrt = bx::uint32_max(1, fb.m_num);
  2874. }
  2875. if (1 == numMrt)
  2876. {
  2877. GLuint flags = 0;
  2878. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  2879. {
  2880. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2881. {
  2882. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[0]);
  2883. const float* rgba = _palette[index];
  2884. const float rr = rgba[0];
  2885. const float gg = rgba[1];
  2886. const float bb = rgba[2];
  2887. const float aa = rgba[3];
  2888. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2889. }
  2890. else
  2891. {
  2892. float rr = _clear.m_index[0]*1.0f/255.0f;
  2893. float gg = _clear.m_index[1]*1.0f/255.0f;
  2894. float bb = _clear.m_index[2]*1.0f/255.0f;
  2895. float aa = _clear.m_index[3]*1.0f/255.0f;
  2896. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2897. }
  2898. flags |= GL_COLOR_BUFFER_BIT;
  2899. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2900. }
  2901. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2902. {
  2903. flags |= GL_DEPTH_BUFFER_BIT;
  2904. GL_CHECK(glClearDepth(_clear.m_depth) );
  2905. GL_CHECK(glDepthMask(GL_TRUE) );
  2906. }
  2907. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2908. {
  2909. flags |= GL_STENCIL_BUFFER_BIT;
  2910. GL_CHECK(glClearStencil(_clear.m_stencil) );
  2911. }
  2912. if (0 != flags)
  2913. {
  2914. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  2915. GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) );
  2916. GL_CHECK(glClear(flags) );
  2917. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2918. }
  2919. }
  2920. else
  2921. {
  2922. const GLuint defaultVao = m_vao;
  2923. if (0 != defaultVao)
  2924. {
  2925. GL_CHECK(glBindVertexArray(defaultVao) );
  2926. }
  2927. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2928. GL_CHECK(glDisable(GL_CULL_FACE) );
  2929. GL_CHECK(glDisable(GL_BLEND) );
  2930. GLboolean colorMask = !!(BGFX_CLEAR_COLOR & _clear.m_flags);
  2931. GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) );
  2932. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2933. {
  2934. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2935. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2936. GL_CHECK(glDepthMask(GL_TRUE) );
  2937. }
  2938. else
  2939. {
  2940. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2941. }
  2942. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2943. {
  2944. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  2945. GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) );
  2946. GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) );
  2947. }
  2948. else
  2949. {
  2950. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2951. }
  2952. VertexBufferGL& vb = m_vertexBuffers[_clearQuad.m_vb->handle.idx];
  2953. VertexDecl& vertexDecl = m_vertexDecls[_clearQuad.m_vb->decl.idx];
  2954. {
  2955. struct Vertex
  2956. {
  2957. float m_x;
  2958. float m_y;
  2959. float m_z;
  2960. };
  2961. Vertex* vertex = (Vertex*)_clearQuad.m_vb->data;
  2962. BX_CHECK(vertexDecl.m_stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", vertexDecl.m_stride, sizeof(Vertex) );
  2963. const float depth = _clear.m_depth * 2.0f - 1.0f;
  2964. vertex->m_x = -1.0f;
  2965. vertex->m_y = -1.0f;
  2966. vertex->m_z = depth;
  2967. vertex++;
  2968. vertex->m_x = 1.0f;
  2969. vertex->m_y = -1.0f;
  2970. vertex->m_z = depth;
  2971. vertex++;
  2972. vertex->m_x = -1.0f;
  2973. vertex->m_y = 1.0f;
  2974. vertex->m_z = depth;
  2975. vertex++;
  2976. vertex->m_x = 1.0f;
  2977. vertex->m_y = 1.0f;
  2978. vertex->m_z = depth;
  2979. }
  2980. vb.update(0, 4*_clearQuad.m_decl.m_stride, _clearQuad.m_vb->data);
  2981. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2982. ProgramGL& program = m_program[_clearQuad.m_program[numMrt-1].idx];
  2983. GL_CHECK(glUseProgram(program.m_id) );
  2984. program.bindAttributesBegin();
  2985. program.bindAttributes(vertexDecl, 0);
  2986. program.bindAttributesEnd();
  2987. float mrtClear[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  2988. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2989. {
  2990. for (uint32_t ii = 0; ii < numMrt; ++ii)
  2991. {
  2992. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[ii]);
  2993. bx::memCopy(mrtClear[ii], _palette[index], 16);
  2994. }
  2995. }
  2996. else
  2997. {
  2998. float rgba[4] =
  2999. {
  3000. _clear.m_index[0] * 1.0f / 255.0f,
  3001. _clear.m_index[1] * 1.0f / 255.0f,
  3002. _clear.m_index[2] * 1.0f / 255.0f,
  3003. _clear.m_index[3] * 1.0f / 255.0f,
  3004. };
  3005. for (uint32_t ii = 0; ii < numMrt; ++ii)
  3006. {
  3007. bx::memCopy(mrtClear[ii], rgba, 16);
  3008. }
  3009. }
  3010. GL_CHECK(glUniform4fv(0, numMrt, mrtClear[0]) );
  3011. GL_CHECK(glDrawArrays(GL_TRIANGLE_STRIP
  3012. , 0
  3013. , 4
  3014. ) );
  3015. }
  3016. }
  3017. void* m_renderdocdll;
  3018. uint16_t m_numWindows;
  3019. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  3020. IndexBufferGL m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  3021. VertexBufferGL m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  3022. ShaderGL m_shaders[BGFX_CONFIG_MAX_SHADERS];
  3023. ProgramGL m_program[BGFX_CONFIG_MAX_PROGRAMS];
  3024. TextureGL m_textures[BGFX_CONFIG_MAX_TEXTURES];
  3025. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  3026. FrameBufferGL m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  3027. UniformRegistry m_uniformReg;
  3028. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  3029. TimerQueryGL m_gpuTimer;
  3030. OcclusionQueryGL m_occlusionQuery;
  3031. VaoStateCache m_vaoStateCache;
  3032. SamplerStateCache m_samplerStateCache;
  3033. TextVideoMem m_textVideoMem;
  3034. bool m_rtMsaa;
  3035. FrameBufferHandle m_fbh;
  3036. uint16_t m_fbDiscard;
  3037. Resolution m_resolution;
  3038. void* m_capture;
  3039. uint32_t m_captureSize;
  3040. float m_maxAnisotropy;
  3041. float m_maxAnisotropyDefault;
  3042. int32_t m_maxMsaa;
  3043. GLuint m_vao;
  3044. bool m_blitSupported;
  3045. bool m_readBackSupported;
  3046. bool m_vaoSupport;
  3047. bool m_samplerObjectSupport;
  3048. bool m_shadowSamplersSupport;
  3049. bool m_srgbWriteControlSupport;
  3050. bool m_borderColorSupport;
  3051. bool m_programBinarySupport;
  3052. bool m_textureSwizzleSupport;
  3053. bool m_depthTextureSupport;
  3054. bool m_timerQuerySupport;
  3055. bool m_occlusionQuerySupport;
  3056. bool m_atocSupport;
  3057. bool m_conservativeRasterSupport;
  3058. bool m_flip;
  3059. uint64_t m_hash;
  3060. GLenum m_readPixelsFmt;
  3061. GLuint m_backBufferFbo;
  3062. GLuint m_msaaBackBufferFbo;
  3063. GLuint m_msaaBackBufferRbos[2];
  3064. GlContext m_glctx;
  3065. bool m_needPresent;
  3066. const char* m_vendor;
  3067. const char* m_renderer;
  3068. const char* m_version;
  3069. const char* m_glslVersion;
  3070. GLuint m_currentFbo;
  3071. VR m_ovr;
  3072. #if BGFX_CONFIG_USE_OVR
  3073. VRImplOVRGL m_ovrRender;
  3074. #endif // BGFX_CONFIG_USE_OVR
  3075. };
  3076. RendererContextGL* s_renderGL;
  3077. RendererContextI* rendererCreate()
  3078. {
  3079. s_renderGL = BX_NEW(g_allocator, RendererContextGL);
  3080. s_renderGL->init();
  3081. return s_renderGL;
  3082. }
  3083. void rendererDestroy()
  3084. {
  3085. s_renderGL->shutdown();
  3086. BX_DELETE(g_allocator, s_renderGL);
  3087. s_renderGL = NULL;
  3088. }
  3089. static void frameBufferValidate()
  3090. {
  3091. GLenum complete = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3092. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == complete
  3093. , "glCheckFramebufferStatus failed 0x%08x: %s"
  3094. , complete
  3095. , glEnumName(complete)
  3096. );
  3097. BX_UNUSED(complete);
  3098. }
  3099. #if BGFX_CONFIG_USE_OVR
  3100. VRImplOVRGL::VRImplOVRGL()
  3101. : m_depthRbo(0)
  3102. , m_msaaTexture(0)
  3103. , m_msaaTarget(0)
  3104. , m_textureSwapChain(NULL)
  3105. , m_mirrorTexture(NULL)
  3106. {
  3107. bx::memSet(&m_eyeTarget, 0, sizeof(m_eyeTarget) );
  3108. }
  3109. static void setDefaultSamplerState()
  3110. {
  3111. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
  3112. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
  3113. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  3114. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  3115. }
  3116. bool VRImplOVRGL::createSwapChain(const VRDesc& _desc, int _msaaSamples, int _mirrorWidth, int _mirrorHeight)
  3117. {
  3118. if (!m_session)
  3119. {
  3120. return false;
  3121. }
  3122. if (NULL == m_textureSwapChain)
  3123. {
  3124. const GLsizei width = _desc.m_eyeSize[0].m_w + _desc.m_eyeSize[1].m_w;
  3125. const GLsizei height = bx::uint16_max(_desc.m_eyeSize[0].m_h, _desc.m_eyeSize[1].m_h);
  3126. ovrTextureSwapChainDesc swapchainDesc = {};
  3127. swapchainDesc.Type = ovrTexture_2D;
  3128. swapchainDesc.Width = width;
  3129. swapchainDesc.Height = height;
  3130. swapchainDesc.MipLevels = 1;
  3131. swapchainDesc.ArraySize = 1;
  3132. swapchainDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
  3133. swapchainDesc.SampleCount = 1;
  3134. swapchainDesc.StaticImage = ovrFalse;
  3135. ovrResult result = ovr_CreateTextureSwapChainGL(m_session, &swapchainDesc, &m_textureSwapChain);
  3136. if (!OVR_SUCCESS(result) )
  3137. {
  3138. destroySwapChain();
  3139. return false;
  3140. }
  3141. m_renderLayer.Header.Flags |= ovrLayerFlag_TextureOriginAtBottomLeft;
  3142. for (int eye = 0; eye < 2; ++eye)
  3143. {
  3144. m_renderLayer.ColorTexture[eye] = m_textureSwapChain;
  3145. }
  3146. // create depth buffer
  3147. GL_CHECK(glGenRenderbuffers(1, &m_depthRbo));
  3148. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_depthRbo));
  3149. if (_msaaSamples > 1)
  3150. {
  3151. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaaSamples, GL_DEPTH_COMPONENT32F, width, height));
  3152. }
  3153. else
  3154. {
  3155. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32F, width, height));
  3156. }
  3157. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0));
  3158. int count;
  3159. result = ovr_GetTextureSwapChainLength(m_session, m_textureSwapChain, &count);
  3160. if (!OVR_SUCCESS(result) )
  3161. {
  3162. destroySwapChain();
  3163. return false;
  3164. }
  3165. BX_CHECK(count <= BX_COUNTOF(m_eyeTarget), "Too many OVR swap chain textures. %d", count);
  3166. for (int ii = 0; ii < count; ++ii)
  3167. {
  3168. GLuint texture;
  3169. ovr_GetTextureSwapChainBufferGL(m_session, m_textureSwapChain, ii, &texture);
  3170. // create eye target
  3171. GL_CHECK(glGenFramebuffers(1, &m_eyeTarget[ii]) );
  3172. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_eyeTarget[ii]) );
  3173. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0) );
  3174. if (2 > _msaaSamples && 0 != m_depthRbo)
  3175. {
  3176. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthRbo) );
  3177. }
  3178. frameBufferValidate();
  3179. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  3180. }
  3181. // create MSAA target
  3182. if (1 < _msaaSamples)
  3183. {
  3184. GL_CHECK(glGenTextures(1, &m_msaaTexture) );
  3185. GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_msaaTexture) );
  3186. GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, _msaaSamples, GL_RGBA, width, height, GL_TRUE) );
  3187. setDefaultSamplerState();
  3188. GL_CHECK(glGenFramebuffers(1, &m_msaaTarget) );
  3189. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaTarget) );
  3190. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, m_msaaTexture, 0) );
  3191. if (0 != m_depthRbo)
  3192. {
  3193. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthRbo) );
  3194. }
  3195. frameBufferValidate();
  3196. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  3197. }
  3198. }
  3199. if (NULL == m_mirrorTexture)
  3200. {
  3201. m_mirrorFbo = 0;
  3202. ovrMirrorTextureDesc mirrorDesc = {};
  3203. mirrorDesc.Width = _mirrorWidth;
  3204. mirrorDesc.Height = _mirrorHeight;
  3205. mirrorDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
  3206. // Fallback to doing nothing if mirror was not created. This is to prevent errors with fast window resizes
  3207. ovr_CreateMirrorTextureGL(m_session, &mirrorDesc, &m_mirrorTexture);
  3208. if (m_mirrorTexture)
  3209. {
  3210. m_mirrorWidth = _mirrorWidth;
  3211. m_mirrorHeight = _mirrorHeight;
  3212. // Configure the mirror read buffer
  3213. GLuint texId;
  3214. ovr_GetMirrorTextureBufferGL(m_session, m_mirrorTexture, &texId);
  3215. GL_CHECK(glGenFramebuffers(1, &m_mirrorFbo) );
  3216. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_mirrorFbo) );
  3217. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texId, 0) );
  3218. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0) );
  3219. frameBufferValidate();
  3220. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  3221. }
  3222. }
  3223. return true;
  3224. }
  3225. void VRImplOVRGL::destroySwapChain()
  3226. {
  3227. destroyMirror();
  3228. if (0 != m_msaaTarget)
  3229. {
  3230. GL_CHECK(glDeleteFramebuffers(1, &m_msaaTarget) );
  3231. m_msaaTarget = 0;
  3232. }
  3233. if (0 != m_msaaTexture)
  3234. {
  3235. GL_CHECK(glDeleteTextures(1, &m_msaaTexture) );
  3236. m_msaaTexture = 0;
  3237. }
  3238. if (0 != m_depthRbo)
  3239. {
  3240. GL_CHECK(glDeleteRenderbuffers(1, &m_depthRbo) );
  3241. m_depthRbo = 0;
  3242. }
  3243. for (int ii = 0, nn = BX_COUNTOF(m_eyeTarget); ii < nn; ++ii)
  3244. {
  3245. if (0 != m_eyeTarget[ii])
  3246. {
  3247. GL_CHECK(glDeleteFramebuffers(1, &m_eyeTarget[ii]) );
  3248. m_eyeTarget[ii] = 0;
  3249. }
  3250. }
  3251. if (NULL != m_textureSwapChain)
  3252. {
  3253. ovr_DestroyTextureSwapChain(m_session, m_textureSwapChain);
  3254. m_textureSwapChain = NULL;
  3255. }
  3256. }
  3257. void VRImplOVRGL::destroyMirror()
  3258. {
  3259. if (NULL != m_mirrorTexture)
  3260. {
  3261. GL_CHECK(glDeleteFramebuffers(1, &m_mirrorFbo) );
  3262. ovr_DestroyMirrorTexture(m_session, m_mirrorTexture);
  3263. m_mirrorTexture = NULL;
  3264. }
  3265. }
  3266. void VRImplOVRGL::makeRenderTargetActive(const VRDesc& /*_desc*/)
  3267. {
  3268. if (0 != m_msaaTarget)
  3269. {
  3270. s_renderGL->m_currentFbo = m_msaaTarget;
  3271. }
  3272. else
  3273. {
  3274. int index;
  3275. ovr_GetTextureSwapChainCurrentIndex(m_session, m_textureSwapChain, &index);
  3276. s_renderGL->m_currentFbo = m_eyeTarget[index];
  3277. }
  3278. }
  3279. bool VRImplOVRGL::submitSwapChain(const VRDesc& _desc)
  3280. {
  3281. BX_CHECK(NULL != m_textureSwapChain, "VRImplOVRGL submitted without a valid swap chain");
  3282. if (0 != m_msaaTarget)
  3283. {
  3284. const uint32_t width = _desc.m_eyeSize[0].m_w+_desc.m_eyeSize[1].m_w;
  3285. const uint32_t height = _desc.m_eyeSize[0].m_h;
  3286. int index;
  3287. ovr_GetTextureSwapChainCurrentIndex(m_session, m_textureSwapChain, &index);
  3288. // resolve MSAA
  3289. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaTarget) );
  3290. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_eyeTarget[index]) );
  3291. GL_CHECK(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST) );
  3292. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) );
  3293. }
  3294. ovrResult result = ovr_CommitTextureSwapChain(m_session, m_textureSwapChain);
  3295. if (!OVR_SUCCESS(result) )
  3296. {
  3297. return false;
  3298. }
  3299. ovrLayerHeader* layerList = &m_renderLayer.Header;
  3300. result = ovr_SubmitFrame(m_session, 0, &m_viewScale, &layerList, 1);
  3301. if (!OVR_SUCCESS(result) )
  3302. {
  3303. return false;
  3304. }
  3305. if (result != ovrSuccess_NotVisible && NULL != m_mirrorTexture)
  3306. {
  3307. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_mirrorFbo) );
  3308. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  3309. GL_CHECK(glBlitFramebuffer(0, m_mirrorHeight, m_mirrorWidth, 0, 0, 0, m_mirrorWidth, m_mirrorHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST) );
  3310. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) );
  3311. }
  3312. return true;
  3313. }
  3314. #endif // BGFX_CONFIG_USE_OVR
  3315. const char* glslTypeName(GLuint _type)
  3316. {
  3317. #define GLSL_TYPE(_ty) case _ty: return #_ty
  3318. switch (_type)
  3319. {
  3320. GLSL_TYPE(GL_INT);
  3321. GLSL_TYPE(GL_INT_VEC2);
  3322. GLSL_TYPE(GL_INT_VEC3);
  3323. GLSL_TYPE(GL_INT_VEC4);
  3324. GLSL_TYPE(GL_UNSIGNED_INT);
  3325. GLSL_TYPE(GL_UNSIGNED_INT_VEC2);
  3326. GLSL_TYPE(GL_UNSIGNED_INT_VEC3);
  3327. GLSL_TYPE(GL_UNSIGNED_INT_VEC4);
  3328. GLSL_TYPE(GL_FLOAT);
  3329. GLSL_TYPE(GL_FLOAT_VEC2);
  3330. GLSL_TYPE(GL_FLOAT_VEC3);
  3331. GLSL_TYPE(GL_FLOAT_VEC4);
  3332. GLSL_TYPE(GL_FLOAT_MAT2);
  3333. GLSL_TYPE(GL_FLOAT_MAT3);
  3334. GLSL_TYPE(GL_FLOAT_MAT4);
  3335. GLSL_TYPE(GL_SAMPLER_2D);
  3336. GLSL_TYPE(GL_SAMPLER_2D_ARRAY);
  3337. GLSL_TYPE(GL_SAMPLER_2D_MULTISAMPLE);
  3338. GLSL_TYPE(GL_INT_SAMPLER_2D);
  3339. GLSL_TYPE(GL_INT_SAMPLER_2D_ARRAY);
  3340. GLSL_TYPE(GL_INT_SAMPLER_2D_MULTISAMPLE);
  3341. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D);
  3342. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY);
  3343. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE);
  3344. GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  3345. GLSL_TYPE(GL_SAMPLER_2D_ARRAY_SHADOW);
  3346. GLSL_TYPE(GL_SAMPLER_3D);
  3347. GLSL_TYPE(GL_INT_SAMPLER_3D);
  3348. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_3D);
  3349. GLSL_TYPE(GL_SAMPLER_CUBE);
  3350. GLSL_TYPE(GL_INT_SAMPLER_CUBE);
  3351. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_CUBE);
  3352. GLSL_TYPE(GL_IMAGE_1D);
  3353. GLSL_TYPE(GL_INT_IMAGE_1D);
  3354. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_1D);
  3355. GLSL_TYPE(GL_IMAGE_2D);
  3356. GLSL_TYPE(GL_IMAGE_2D_ARRAY);
  3357. GLSL_TYPE(GL_INT_IMAGE_2D);
  3358. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_2D);
  3359. GLSL_TYPE(GL_IMAGE_3D);
  3360. GLSL_TYPE(GL_INT_IMAGE_3D);
  3361. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_3D);
  3362. GLSL_TYPE(GL_IMAGE_CUBE);
  3363. GLSL_TYPE(GL_INT_IMAGE_CUBE);
  3364. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_CUBE);
  3365. }
  3366. #undef GLSL_TYPE
  3367. BX_CHECK(false, "Unknown GLSL type? %x", _type);
  3368. return "UNKNOWN GLSL TYPE!";
  3369. }
  3370. const char* glEnumName(GLenum _enum)
  3371. {
  3372. #define GLENUM(_ty) case _ty: return #_ty
  3373. switch (_enum)
  3374. {
  3375. GLENUM(GL_TEXTURE);
  3376. GLENUM(GL_RENDERBUFFER);
  3377. GLENUM(GL_INVALID_ENUM);
  3378. GLENUM(GL_INVALID_FRAMEBUFFER_OPERATION);
  3379. GLENUM(GL_INVALID_VALUE);
  3380. GLENUM(GL_INVALID_OPERATION);
  3381. GLENUM(GL_OUT_OF_MEMORY);
  3382. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
  3383. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
  3384. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
  3385. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
  3386. GLENUM(GL_FRAMEBUFFER_UNSUPPORTED);
  3387. }
  3388. #undef GLENUM
  3389. BX_WARN(false, "Unknown enum? %x", _enum);
  3390. return "<GLenum?>";
  3391. }
  3392. UniformType::Enum convertGlType(GLenum _type)
  3393. {
  3394. switch (_type)
  3395. {
  3396. case GL_INT:
  3397. case GL_UNSIGNED_INT:
  3398. return UniformType::Int1;
  3399. case GL_FLOAT:
  3400. case GL_FLOAT_VEC2:
  3401. case GL_FLOAT_VEC3:
  3402. case GL_FLOAT_VEC4:
  3403. return UniformType::Vec4;
  3404. case GL_FLOAT_MAT2:
  3405. break;
  3406. case GL_FLOAT_MAT3:
  3407. return UniformType::Mat3;
  3408. case GL_FLOAT_MAT4:
  3409. return UniformType::Mat4;
  3410. case GL_SAMPLER_2D:
  3411. case GL_SAMPLER_2D_ARRAY:
  3412. case GL_SAMPLER_2D_MULTISAMPLE:
  3413. case GL_INT_SAMPLER_2D:
  3414. case GL_INT_SAMPLER_2D_ARRAY:
  3415. case GL_INT_SAMPLER_2D_MULTISAMPLE:
  3416. case GL_UNSIGNED_INT_SAMPLER_2D:
  3417. case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
  3418. case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
  3419. case GL_SAMPLER_2D_SHADOW:
  3420. case GL_SAMPLER_2D_ARRAY_SHADOW:
  3421. case GL_SAMPLER_3D:
  3422. case GL_INT_SAMPLER_3D:
  3423. case GL_UNSIGNED_INT_SAMPLER_3D:
  3424. case GL_SAMPLER_CUBE:
  3425. case GL_INT_SAMPLER_CUBE:
  3426. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  3427. case GL_IMAGE_1D:
  3428. case GL_INT_IMAGE_1D:
  3429. case GL_UNSIGNED_INT_IMAGE_1D:
  3430. case GL_IMAGE_2D:
  3431. case GL_IMAGE_2D_ARRAY:
  3432. case GL_INT_IMAGE_2D:
  3433. case GL_UNSIGNED_INT_IMAGE_2D:
  3434. case GL_IMAGE_3D:
  3435. case GL_INT_IMAGE_3D:
  3436. case GL_UNSIGNED_INT_IMAGE_3D:
  3437. case GL_IMAGE_CUBE:
  3438. case GL_INT_IMAGE_CUBE:
  3439. case GL_UNSIGNED_INT_IMAGE_CUBE:
  3440. return UniformType::Int1;
  3441. };
  3442. BX_CHECK(false, "Unrecognized GL type 0x%04x.", _type);
  3443. return UniformType::End;
  3444. }
  3445. void ProgramGL::create(const ShaderGL& _vsh, const ShaderGL& _fsh)
  3446. {
  3447. m_id = glCreateProgram();
  3448. BX_TRACE("Program create: GL%d: GL%d, GL%d", m_id, _vsh.m_id, _fsh.m_id);
  3449. const uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  3450. const bool cached = s_renderGL->programFetchFromCache(m_id, id);
  3451. if (!cached)
  3452. {
  3453. GLint linked = 0;
  3454. if (0 != _vsh.m_id)
  3455. {
  3456. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  3457. if (0 != _fsh.m_id)
  3458. {
  3459. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  3460. }
  3461. GL_CHECK(glLinkProgram(m_id) );
  3462. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  3463. if (0 == linked)
  3464. {
  3465. char log[1024];
  3466. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  3467. BX_TRACE("%d: %s", linked, log);
  3468. }
  3469. }
  3470. if (0 == linked)
  3471. {
  3472. BX_WARN(0 != _vsh.m_id, "Invalid vertex/compute shader.");
  3473. GL_CHECK(glDeleteProgram(m_id) );
  3474. m_usedCount = 0;
  3475. m_id = 0;
  3476. return;
  3477. }
  3478. s_renderGL->programCache(m_id, id);
  3479. }
  3480. init();
  3481. if (!cached)
  3482. {
  3483. // Must be after init, otherwise init might fail to lookup shader
  3484. // info (NVIDIA Tegra 3 OpenGL ES 2.0 14.01003).
  3485. GL_CHECK(glDetachShader(m_id, _vsh.m_id) );
  3486. if (0 != _fsh.m_id)
  3487. {
  3488. GL_CHECK(glDetachShader(m_id, _fsh.m_id) );
  3489. }
  3490. }
  3491. }
  3492. void ProgramGL::destroy()
  3493. {
  3494. if (NULL != m_constantBuffer)
  3495. {
  3496. UniformBuffer::destroy(m_constantBuffer);
  3497. m_constantBuffer = NULL;
  3498. }
  3499. m_numPredefined = 0;
  3500. if (0 != m_id)
  3501. {
  3502. GL_CHECK(glUseProgram(0) );
  3503. GL_CHECK(glDeleteProgram(m_id) );
  3504. m_id = 0;
  3505. }
  3506. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3507. }
  3508. void ProgramGL::init()
  3509. {
  3510. GLint activeAttribs = 0;
  3511. GLint activeUniforms = 0;
  3512. GLint activeBuffers = 0;
  3513. #if BGFX_CONFIG_RENDERER_OPENGL >= 31
  3514. GL_CHECK(glBindFragDataLocation(m_id, 0, "bgfx_FragColor") );
  3515. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
  3516. GLint max0, max1;
  3517. bool piqSupported = true
  3518. && s_extension[Extension::ARB_program_interface_query ].m_supported
  3519. && s_extension[Extension::ARB_shader_storage_buffer_object].m_supported
  3520. ;
  3521. if (piqSupported)
  3522. {
  3523. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &activeAttribs ) );
  3524. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_ACTIVE_RESOURCES, &activeUniforms) );
  3525. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_BUFFER_VARIABLE, GL_ACTIVE_RESOURCES, &activeBuffers ) );
  3526. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_MAX_NAME_LENGTH, &max0 ) );
  3527. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_MAX_NAME_LENGTH, &max1 ) );
  3528. }
  3529. else
  3530. {
  3531. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs ) );
  3532. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  3533. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  3534. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  3535. }
  3536. uint32_t maxLength = bx::uint32_max(max0, max1);
  3537. char* name = (char*)alloca(maxLength + 1);
  3538. BX_TRACE("Program %d", m_id);
  3539. BX_TRACE("Attributes (%d):", activeAttribs);
  3540. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  3541. {
  3542. GLint size;
  3543. GLenum type = 0;
  3544. if (piqSupported)
  3545. {
  3546. GL_CHECK(glGetProgramResourceName(m_id, GL_PROGRAM_INPUT, ii, maxLength + 1, &size, name) );
  3547. GLenum typeProp[] = { GL_TYPE };
  3548. GL_CHECK(glGetProgramResourceiv(m_id
  3549. , GL_PROGRAM_INPUT
  3550. , ii
  3551. , BX_COUNTOF(typeProp)
  3552. , typeProp
  3553. , 1
  3554. , NULL
  3555. , (GLint *)&type)
  3556. );
  3557. }
  3558. else
  3559. {
  3560. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  3561. }
  3562. BX_TRACE("\t%s %s is at location %d"
  3563. , glslTypeName(type)
  3564. , name
  3565. , glGetAttribLocation(m_id, name)
  3566. );
  3567. }
  3568. m_numPredefined = 0;
  3569. m_numSamplers = 0;
  3570. BX_TRACE("Uniforms (%d):", activeUniforms);
  3571. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  3572. {
  3573. struct VariableInfo
  3574. {
  3575. GLenum type;
  3576. GLint loc;
  3577. GLint num;
  3578. };
  3579. VariableInfo vi;
  3580. GLenum props[] = { GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE };
  3581. GLenum gltype;
  3582. GLint num;
  3583. GLint loc;
  3584. if (piqSupported)
  3585. {
  3586. GL_CHECK(glGetProgramResourceiv(m_id
  3587. , GL_UNIFORM
  3588. , ii
  3589. , BX_COUNTOF(props)
  3590. , props
  3591. , BX_COUNTOF(props)
  3592. , NULL
  3593. , (GLint*)&vi
  3594. ) );
  3595. GL_CHECK(glGetProgramResourceName(m_id
  3596. , GL_UNIFORM
  3597. , ii
  3598. , maxLength + 1
  3599. , NULL
  3600. , name
  3601. ) );
  3602. gltype = vi.type;
  3603. loc = vi.loc;
  3604. num = vi.num;
  3605. }
  3606. else
  3607. {
  3608. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  3609. loc = glGetUniformLocation(m_id, name);
  3610. }
  3611. num = bx::uint32_max(num, 1);
  3612. int offset = 0;
  3613. char* array = const_cast<char*>(bx::strnchr(name, '[') );
  3614. if (NULL != array)
  3615. {
  3616. BX_TRACE("--- %s", name);
  3617. *array = '\0';
  3618. array++;
  3619. char* end = const_cast<char*>(bx::strnchr(array, ']') );
  3620. if (NULL != end)
  3621. { // Some devices (Amazon Fire) might not return terminating brace.
  3622. *end = '\0';
  3623. offset = atoi(array);
  3624. }
  3625. }
  3626. switch (gltype)
  3627. {
  3628. case GL_SAMPLER_2D:
  3629. case GL_SAMPLER_2D_ARRAY:
  3630. case GL_SAMPLER_2D_MULTISAMPLE:
  3631. case GL_INT_SAMPLER_2D:
  3632. case GL_INT_SAMPLER_2D_ARRAY:
  3633. case GL_INT_SAMPLER_2D_MULTISAMPLE:
  3634. case GL_UNSIGNED_INT_SAMPLER_2D:
  3635. case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
  3636. case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
  3637. case GL_SAMPLER_2D_SHADOW:
  3638. case GL_SAMPLER_2D_ARRAY_SHADOW:
  3639. case GL_SAMPLER_3D:
  3640. case GL_INT_SAMPLER_3D:
  3641. case GL_UNSIGNED_INT_SAMPLER_3D:
  3642. case GL_SAMPLER_CUBE:
  3643. case GL_INT_SAMPLER_CUBE:
  3644. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  3645. case GL_IMAGE_1D:
  3646. case GL_INT_IMAGE_1D:
  3647. case GL_UNSIGNED_INT_IMAGE_1D:
  3648. case GL_IMAGE_2D:
  3649. case GL_INT_IMAGE_2D:
  3650. case GL_UNSIGNED_INT_IMAGE_2D:
  3651. case GL_IMAGE_3D:
  3652. case GL_INT_IMAGE_3D:
  3653. case GL_UNSIGNED_INT_IMAGE_3D:
  3654. case GL_IMAGE_CUBE:
  3655. case GL_INT_IMAGE_CUBE:
  3656. case GL_UNSIGNED_INT_IMAGE_CUBE:
  3657. if (m_numSamplers < BX_COUNTOF(m_sampler) )
  3658. {
  3659. BX_TRACE("Sampler #%d at location %d.", m_numSamplers, loc);
  3660. m_sampler[m_numSamplers] = loc;
  3661. m_numSamplers++;
  3662. }
  3663. else
  3664. {
  3665. BX_TRACE("Too many samplers (max: %d)! Sampler at location %d."
  3666. , BX_COUNTOF(m_sampler)
  3667. , loc
  3668. );
  3669. }
  3670. break;
  3671. default:
  3672. break;
  3673. }
  3674. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  3675. if (PredefinedUniform::Count != predefined)
  3676. {
  3677. m_predefined[m_numPredefined].m_loc = loc;
  3678. m_predefined[m_numPredefined].m_count = uint16_t(num);
  3679. m_predefined[m_numPredefined].m_type = uint8_t(predefined);
  3680. m_numPredefined++;
  3681. }
  3682. else
  3683. {
  3684. const UniformRegInfo* info = s_renderGL->m_uniformReg.find(name);
  3685. BX_WARN(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  3686. if (NULL != info)
  3687. {
  3688. if (NULL == m_constantBuffer)
  3689. {
  3690. m_constantBuffer = UniformBuffer::create(1024);
  3691. }
  3692. UniformType::Enum type = convertGlType(gltype);
  3693. m_constantBuffer->writeUniformHandle(type, 0, info->m_handle, uint16_t(num) );
  3694. m_constantBuffer->write(loc);
  3695. BX_TRACE("store %s %d", name, info->m_handle);
  3696. }
  3697. }
  3698. BX_TRACE("\tuniform %s %s%s is at location %d, size %d, offset %d"
  3699. , glslTypeName(gltype)
  3700. , name
  3701. , PredefinedUniform::Count != predefined ? "*" : ""
  3702. , loc
  3703. , num
  3704. , offset
  3705. );
  3706. BX_UNUSED(offset);
  3707. }
  3708. if (NULL != m_constantBuffer)
  3709. {
  3710. m_constantBuffer->finish();
  3711. }
  3712. if (piqSupported)
  3713. {
  3714. struct VariableInfo
  3715. {
  3716. GLenum type;
  3717. };
  3718. VariableInfo vi;
  3719. GLenum props[] = { GL_TYPE };
  3720. BX_TRACE("Buffers (%d):", activeBuffers);
  3721. for (int32_t ii = 0; ii < activeBuffers; ++ii)
  3722. {
  3723. GL_CHECK(glGetProgramResourceiv(m_id
  3724. , GL_BUFFER_VARIABLE
  3725. , ii
  3726. , BX_COUNTOF(props)
  3727. , props
  3728. , BX_COUNTOF(props)
  3729. , NULL
  3730. , (GLint*)&vi
  3731. ) );
  3732. GL_CHECK(glGetProgramResourceName(m_id
  3733. , GL_BUFFER_VARIABLE
  3734. , ii
  3735. , maxLength + 1
  3736. , NULL
  3737. , name
  3738. ) );
  3739. BX_TRACE("\t%s %s at %d"
  3740. , glslTypeName(vi.type)
  3741. , name
  3742. , 0 //vi.loc
  3743. );
  3744. }
  3745. }
  3746. bx::memSet(m_attributes, 0xff, sizeof(m_attributes) );
  3747. uint32_t used = 0;
  3748. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  3749. {
  3750. GLint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  3751. if (-1 != loc)
  3752. {
  3753. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  3754. m_attributes[ii] = loc;
  3755. m_used[used++] = ii;
  3756. }
  3757. }
  3758. BX_CHECK(used < BX_COUNTOF(m_used), "Out of bounds %d > array size %d.", used, Attrib::Count);
  3759. m_usedCount = (uint8_t)used;
  3760. used = 0;
  3761. for (uint32_t ii = 0; ii < BX_COUNTOF(s_instanceDataName); ++ii)
  3762. {
  3763. GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]);
  3764. if (GLuint(-1) != loc )
  3765. {
  3766. BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc);
  3767. m_instanceData[used++] = loc;
  3768. }
  3769. }
  3770. BX_CHECK(used < BX_COUNTOF(m_instanceData), "Out of bounds %d > array size %d."
  3771. , used
  3772. , BX_COUNTOF(m_instanceData)
  3773. );
  3774. m_instanceData[used] = 0xffff;
  3775. }
  3776. void ProgramGL::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex)
  3777. {
  3778. for (uint32_t ii = 0, iiEnd = m_usedCount; ii < iiEnd; ++ii)
  3779. {
  3780. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  3781. GLint loc = m_attributes[attr];
  3782. uint8_t num;
  3783. AttribType::Enum type;
  3784. bool normalized;
  3785. bool asInt;
  3786. _vertexDecl.decode(attr, num, type, normalized, asInt);
  3787. if (-1 != loc)
  3788. {
  3789. if (UINT16_MAX != _vertexDecl.m_attributes[attr])
  3790. {
  3791. GL_CHECK(glEnableVertexAttribArray(loc) );
  3792. GL_CHECK(glVertexAttribDivisor(loc, 0) );
  3793. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  3794. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 30) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  3795. && (AttribType::Uint8 == type || AttribType::Int16 == type)
  3796. && !normalized)
  3797. {
  3798. GL_CHECK(glVertexAttribIPointer(loc
  3799. , num
  3800. , s_attribType[type]
  3801. , _vertexDecl.m_stride
  3802. , (void*)(uintptr_t)baseVertex)
  3803. );
  3804. }
  3805. else
  3806. {
  3807. GL_CHECK(glVertexAttribPointer(loc
  3808. , num
  3809. , s_attribType[type]
  3810. , normalized
  3811. , _vertexDecl.m_stride
  3812. , (void*)(uintptr_t)baseVertex)
  3813. );
  3814. }
  3815. m_unboundUsedAttrib[ii] = Attrib::Count;
  3816. }
  3817. }
  3818. }
  3819. }
  3820. void ProgramGL::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const
  3821. {
  3822. uint32_t baseVertex = _baseVertex;
  3823. for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  3824. {
  3825. GLint loc = m_instanceData[ii];
  3826. GL_CHECK(glEnableVertexAttribArray(loc) );
  3827. GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) );
  3828. GL_CHECK(glVertexAttribDivisor(loc, 1) );
  3829. baseVertex += 16;
  3830. }
  3831. }
  3832. void IndexBufferGL::destroy()
  3833. {
  3834. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  3835. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3836. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3837. }
  3838. void VertexBufferGL::destroy()
  3839. {
  3840. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  3841. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3842. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3843. }
  3844. static void texSubImage(
  3845. GLenum _target
  3846. , GLint _level
  3847. , GLint _xoffset
  3848. , GLint _yoffset
  3849. , GLint _zoffset
  3850. , GLsizei _width
  3851. , GLsizei _height
  3852. , GLsizei _depth
  3853. , GLenum _format
  3854. , GLenum _type
  3855. , const GLvoid* _data
  3856. )
  3857. {
  3858. if (NULL == _data)
  3859. {
  3860. return;
  3861. }
  3862. if (_target == GL_TEXTURE_3D
  3863. || _target == GL_TEXTURE_2D_ARRAY
  3864. || _target == GL_TEXTURE_CUBE_MAP_ARRAY)
  3865. {
  3866. GL_CHECK(glTexSubImage3D(
  3867. _target
  3868. , _level
  3869. , _xoffset
  3870. , _yoffset
  3871. , _zoffset
  3872. , _width
  3873. , _height
  3874. , _depth
  3875. , _format
  3876. , _type
  3877. , _data
  3878. ) );
  3879. }
  3880. else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
  3881. {
  3882. }
  3883. else
  3884. {
  3885. BX_UNUSED(_zoffset, _depth);
  3886. GL_CHECK(glTexSubImage2D(
  3887. _target
  3888. , _level
  3889. , _xoffset
  3890. , _yoffset
  3891. , _width
  3892. , _height
  3893. , _format
  3894. , _type
  3895. , _data
  3896. ) );
  3897. }
  3898. }
  3899. static void texImage(
  3900. GLenum _target
  3901. , uint32_t _msaaQuality
  3902. , GLint _level
  3903. , GLint _internalFormat
  3904. , GLsizei _width
  3905. , GLsizei _height
  3906. , GLsizei _depth
  3907. , GLint _border
  3908. , GLenum _format
  3909. , GLenum _type
  3910. , const GLvoid* _data
  3911. )
  3912. {
  3913. if (_target == GL_TEXTURE_3D)
  3914. {
  3915. GL_CHECK(glTexImage3D(
  3916. _target
  3917. , _level
  3918. , _internalFormat
  3919. , _width
  3920. , _height
  3921. , _depth
  3922. , _border
  3923. , _format
  3924. , _type
  3925. , _data
  3926. ) );
  3927. }
  3928. else if (_target == GL_TEXTURE_2D_ARRAY
  3929. || _target == GL_TEXTURE_CUBE_MAP_ARRAY)
  3930. {
  3931. texSubImage(
  3932. _target
  3933. , _level
  3934. , 0
  3935. , 0
  3936. , _depth
  3937. , _width
  3938. , _height
  3939. , 1
  3940. , _format
  3941. , _type
  3942. , _data
  3943. );
  3944. }
  3945. else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
  3946. {
  3947. }
  3948. else if (_target == GL_TEXTURE_2D_MULTISAMPLE)
  3949. {
  3950. GL_CHECK(glTexImage2DMultisample(
  3951. _target
  3952. , _msaaQuality
  3953. , _internalFormat
  3954. , _width
  3955. , _height
  3956. , false
  3957. ) );
  3958. }
  3959. else
  3960. {
  3961. GL_CHECK(glTexImage2D(
  3962. _target
  3963. , _level
  3964. , _internalFormat
  3965. , _width
  3966. , _height
  3967. , _border
  3968. , _format
  3969. , _type
  3970. , _data
  3971. ) );
  3972. }
  3973. BX_UNUSED(_msaaQuality, _depth, _border, _data);
  3974. }
  3975. static void compressedTexSubImage(
  3976. GLenum _target
  3977. , GLint _level
  3978. , GLint _xoffset
  3979. , GLint _yoffset
  3980. , GLint _zoffset
  3981. , GLsizei _width
  3982. , GLsizei _height
  3983. , GLsizei _depth
  3984. , GLenum _format
  3985. , GLsizei _imageSize
  3986. , const GLvoid* _data
  3987. )
  3988. {
  3989. if (_target == GL_TEXTURE_3D)
  3990. {
  3991. GL_CHECK(glCompressedTexSubImage3D(
  3992. _target
  3993. , _level
  3994. , _xoffset
  3995. , _yoffset
  3996. , _zoffset
  3997. , _width
  3998. , _height
  3999. , _depth
  4000. , _format
  4001. , _imageSize
  4002. , _data
  4003. ) );
  4004. }
  4005. else
  4006. {
  4007. BX_UNUSED(_zoffset, _depth);
  4008. GL_CHECK(glCompressedTexSubImage2D(
  4009. _target
  4010. , _level
  4011. , _xoffset
  4012. , _yoffset
  4013. , _width
  4014. , _height
  4015. , _format
  4016. , _imageSize
  4017. , _data
  4018. ) );
  4019. }
  4020. }
  4021. static void compressedTexImage(
  4022. GLenum _target
  4023. , GLint _level
  4024. , GLenum _internalformat
  4025. , GLsizei _width
  4026. , GLsizei _height
  4027. , GLsizei _depth
  4028. , GLint _border
  4029. , GLsizei _imageSize
  4030. , const GLvoid* _data
  4031. )
  4032. {
  4033. if (_target == GL_TEXTURE_3D)
  4034. {
  4035. GL_CHECK(glCompressedTexImage3D(
  4036. _target
  4037. , _level
  4038. , _internalformat
  4039. , _width
  4040. , _height
  4041. , _depth
  4042. , _border
  4043. , _imageSize
  4044. , _data
  4045. ) );
  4046. }
  4047. else if (_target == GL_TEXTURE_2D_ARRAY
  4048. || _target == GL_TEXTURE_CUBE_MAP_ARRAY)
  4049. {
  4050. compressedTexSubImage(_target, _level, 0, 0, _depth, _width, _height, 1, _internalformat, _imageSize, _data);
  4051. }
  4052. else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
  4053. {
  4054. }
  4055. else
  4056. {
  4057. BX_UNUSED(_depth);
  4058. GL_CHECK(glCompressedTexImage2D(
  4059. _target
  4060. , _level
  4061. , _internalformat
  4062. , _width
  4063. , _height
  4064. , _border
  4065. , _imageSize
  4066. , _data
  4067. ) );
  4068. }
  4069. }
  4070. bool TextureGL::init(GLenum _target, uint32_t _width, uint32_t _height, uint32_t _depth, uint8_t _numMips, uint32_t _flags)
  4071. {
  4072. m_target = _target;
  4073. m_numMips = _numMips;
  4074. m_flags = _flags;
  4075. m_width = _width;
  4076. m_height = _height;
  4077. m_depth = _depth;
  4078. m_currentSamplerHash = UINT32_MAX;
  4079. const bool writeOnly = 0 != (m_flags&BGFX_TEXTURE_RT_WRITE_ONLY);
  4080. const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE );
  4081. const bool textureArray = false
  4082. || _target == GL_TEXTURE_2D_ARRAY
  4083. || _target == GL_TEXTURE_CUBE_MAP_ARRAY
  4084. ;
  4085. if (!writeOnly)
  4086. {
  4087. GL_CHECK(glGenTextures(1, &m_id) );
  4088. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  4089. GL_CHECK(glBindTexture(_target, m_id) );
  4090. const TextureFormatInfo& tfi = s_textureFormat[m_textureFormat];
  4091. m_fmt = tfi.m_fmt;
  4092. m_type = tfi.m_type;
  4093. const bool swizzle = true
  4094. && TextureFormat::BGRA8 == m_requestedFormat
  4095. && !s_textureFormat[m_requestedFormat].m_supported
  4096. && !s_renderGL->m_textureSwizzleSupport
  4097. ;
  4098. const bool convert = false
  4099. || m_textureFormat != m_requestedFormat
  4100. || swizzle
  4101. ;
  4102. if (convert)
  4103. {
  4104. m_textureFormat = (uint8_t)TextureFormat::RGBA8;
  4105. const TextureFormatInfo& tfiRgba8 = s_textureFormat[TextureFormat::RGBA8];
  4106. m_fmt = tfiRgba8.m_fmt;
  4107. m_type = tfiRgba8.m_type;
  4108. }
  4109. if (textureArray)
  4110. {
  4111. GL_CHECK(glTexStorage3D(_target
  4112. , _numMips
  4113. , s_textureFormat[m_textureFormat].m_internalFmt
  4114. , m_width
  4115. , m_height
  4116. , _depth
  4117. ) );
  4118. }
  4119. if (computeWrite)
  4120. {
  4121. if (_target == GL_TEXTURE_3D)
  4122. {
  4123. GL_CHECK(glTexStorage3D(_target
  4124. , _numMips
  4125. , s_textureFormat[m_textureFormat].m_internalFmt
  4126. , m_width
  4127. , m_height
  4128. , _depth
  4129. ) );
  4130. }
  4131. else
  4132. {
  4133. GL_CHECK(glTexStorage2D(_target
  4134. , _numMips
  4135. , s_textureFormat[m_textureFormat].m_internalFmt
  4136. , m_width
  4137. , m_height
  4138. ) );
  4139. }
  4140. }
  4141. setSamplerState(_flags, NULL);
  4142. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4143. && TextureFormat::BGRA8 == m_requestedFormat
  4144. && !s_textureFormat[m_requestedFormat].m_supported
  4145. && s_renderGL->m_textureSwizzleSupport)
  4146. {
  4147. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  4148. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  4149. }
  4150. }
  4151. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  4152. if (renderTarget)
  4153. {
  4154. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  4155. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  4156. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  4157. const bool msaaSample = 0 != (m_flags&BGFX_TEXTURE_MSAA_SAMPLE);
  4158. if (!msaaSample
  4159. && (0 != msaaQuality || writeOnly) )
  4160. {
  4161. GL_CHECK(glGenRenderbuffers(1, &m_rbo) );
  4162. BX_CHECK(0 != m_rbo, "Failed to generate renderbuffer id.");
  4163. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_rbo) );
  4164. if (0 == msaaQuality)
  4165. {
  4166. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER
  4167. , s_rboFormat[m_textureFormat]
  4168. , _width
  4169. , _height
  4170. ) );
  4171. }
  4172. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4173. {
  4174. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER
  4175. , msaaQuality
  4176. , s_rboFormat[m_textureFormat]
  4177. , _width
  4178. , _height
  4179. ) );
  4180. }
  4181. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  4182. if (writeOnly)
  4183. {
  4184. // This is render buffer, there is no sampling, no need
  4185. // to create texture.
  4186. return false;
  4187. }
  4188. }
  4189. }
  4190. return true;
  4191. }
  4192. void TextureGL::create(const Memory* _mem, uint32_t _flags, uint8_t _skip)
  4193. {
  4194. ImageContainer imageContainer;
  4195. if (imageParse(imageContainer, _mem->data, _mem->size) )
  4196. {
  4197. uint8_t numMips = imageContainer.m_numMips;
  4198. const uint8_t startLod = uint8_t(bx::uint32_min(_skip, numMips-1) );
  4199. numMips -= startLod;
  4200. const uint16_t numLayers = imageContainer.m_numLayers;
  4201. uint32_t textureWidth;
  4202. uint32_t textureHeight;
  4203. uint32_t textureDepth;
  4204. {
  4205. const ImageBlockInfo& ibi = getBlockInfo(TextureFormat::Enum(imageContainer.m_format) );
  4206. textureWidth = bx::uint32_max(ibi.blockWidth, imageContainer.m_width >>startLod);
  4207. textureHeight = bx::uint32_max(ibi.blockHeight, imageContainer.m_height>>startLod);
  4208. textureDepth = 1 < imageContainer.m_depth
  4209. ? imageContainer.m_depth
  4210. : imageContainer.m_numLayers
  4211. ;
  4212. }
  4213. m_requestedFormat = uint8_t(imageContainer.m_format);
  4214. m_textureFormat = uint8_t(getViableTextureFormat(imageContainer) );
  4215. const bool computeWrite = 0 != (_flags&BGFX_TEXTURE_COMPUTE_WRITE);
  4216. const bool srgb = 0 != (_flags&BGFX_TEXTURE_SRGB);
  4217. const bool msaaSample = 0 != (_flags&BGFX_TEXTURE_MSAA_SAMPLE);
  4218. uint32_t msaaQuality = ( (_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  4219. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  4220. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  4221. GLenum target = msaaSample ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
  4222. if (imageContainer.m_cubeMap)
  4223. {
  4224. target = GL_TEXTURE_CUBE_MAP;
  4225. }
  4226. else if (imageContainer.m_depth > 1)
  4227. {
  4228. target = GL_TEXTURE_3D;
  4229. }
  4230. const bool textureArray = 1 < numLayers;
  4231. if (textureArray)
  4232. {
  4233. switch (target)
  4234. {
  4235. case GL_TEXTURE_CUBE_MAP: target = GL_TEXTURE_CUBE_MAP_ARRAY;
  4236. case GL_TEXTURE_2D_MULTISAMPLE: target = GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
  4237. default: target = GL_TEXTURE_2D_ARRAY;
  4238. }
  4239. }
  4240. if (!init(target
  4241. , textureWidth
  4242. , textureHeight
  4243. , textureDepth
  4244. , numMips
  4245. , _flags
  4246. ) )
  4247. {
  4248. return;
  4249. }
  4250. target = isCubeMap()
  4251. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X
  4252. : m_target
  4253. ;
  4254. const GLenum internalFmt = srgb
  4255. ? s_textureFormat[m_textureFormat].m_internalFmtSrgb
  4256. : s_textureFormat[m_textureFormat].m_internalFmt
  4257. ;
  4258. const bool swizzle = true
  4259. && TextureFormat::BGRA8 == m_requestedFormat
  4260. && !s_textureFormat[m_requestedFormat].m_supported
  4261. && !s_renderGL->m_textureSwizzleSupport
  4262. ;
  4263. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  4264. const bool convert = false
  4265. || m_textureFormat != m_requestedFormat
  4266. || swizzle
  4267. ;
  4268. BX_TRACE("Texture%-4s %3d: %s (requested: %s), layers %d, %dx%dx%d%s."
  4269. , imageContainer.m_cubeMap ? "Cube" : (1 < imageContainer.m_depth ? "3D" : "2D")
  4270. , this - s_renderGL->m_textures
  4271. , getName( (TextureFormat::Enum)m_textureFormat)
  4272. , getName( (TextureFormat::Enum)m_requestedFormat)
  4273. , numLayers
  4274. , textureWidth
  4275. , textureHeight
  4276. , imageContainer.m_cubeMap ? 6 : (1 < imageContainer.m_depth ? imageContainer.m_depth : 0)
  4277. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  4278. );
  4279. BX_WARN(!convert, "Texture %s%s%s from %s to %s."
  4280. , swizzle ? "swizzle" : ""
  4281. , swizzle&&convert ? " and " : ""
  4282. , convert ? "convert" : ""
  4283. , getName( (TextureFormat::Enum)m_requestedFormat)
  4284. , getName( (TextureFormat::Enum)m_textureFormat)
  4285. );
  4286. uint8_t* temp = NULL;
  4287. if (convert)
  4288. {
  4289. temp = (uint8_t*)BX_ALLOC(g_allocator, textureWidth*textureHeight*4);
  4290. }
  4291. const uint16_t numSides = numLayers * (imageContainer.m_cubeMap ? 6 : 1);
  4292. for (uint16_t side = 0; side < numSides; ++side)
  4293. {
  4294. uint32_t width = textureWidth;
  4295. uint32_t height = textureHeight;
  4296. uint32_t depth = imageContainer.m_depth;
  4297. GLenum imageTarget = imageContainer.m_cubeMap && !textureArray
  4298. ? target+side
  4299. : target
  4300. ;
  4301. for (uint8_t lod = 0, num = numMips; lod < num; ++lod)
  4302. {
  4303. width = bx::uint32_max(1, width);
  4304. height = bx::uint32_max(1, height);
  4305. depth = 1 < imageContainer.m_depth
  4306. ? bx::uint32_max(1, depth)
  4307. : side
  4308. ;
  4309. ImageMip mip;
  4310. if (imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  4311. {
  4312. if (compressed
  4313. && !convert)
  4314. {
  4315. compressedTexImage(imageTarget
  4316. , lod
  4317. , internalFmt
  4318. , width
  4319. , height
  4320. , depth
  4321. , 0
  4322. , mip.m_size
  4323. , mip.m_data
  4324. );
  4325. }
  4326. else
  4327. {
  4328. const uint8_t* data = mip.m_data;
  4329. if (convert)
  4330. {
  4331. imageDecodeToRgba8(temp
  4332. , mip.m_data
  4333. , mip.m_width
  4334. , mip.m_height
  4335. , mip.m_width*4
  4336. , mip.m_format
  4337. );
  4338. data = temp;
  4339. }
  4340. texImage(imageTarget
  4341. , msaaQuality
  4342. , lod
  4343. , internalFmt
  4344. , width
  4345. , height
  4346. , depth
  4347. , 0
  4348. , m_fmt
  4349. , m_type
  4350. , data
  4351. );
  4352. }
  4353. }
  4354. else if (!computeWrite)
  4355. {
  4356. if (compressed)
  4357. {
  4358. uint32_t size = bx::uint32_max(1, (width + 3)>>2)
  4359. * bx::uint32_max(1, (height + 3)>>2)
  4360. * 4*4*getBitsPerPixel(TextureFormat::Enum(m_textureFormat) )/8
  4361. ;
  4362. compressedTexImage(imageTarget
  4363. , lod
  4364. , internalFmt
  4365. , width
  4366. , height
  4367. , depth
  4368. , 0
  4369. , size
  4370. , NULL
  4371. );
  4372. }
  4373. else
  4374. {
  4375. texImage(imageTarget
  4376. , msaaQuality
  4377. , lod
  4378. , internalFmt
  4379. , width
  4380. , height
  4381. , depth
  4382. , 0
  4383. , m_fmt
  4384. , m_type
  4385. , NULL
  4386. );
  4387. }
  4388. }
  4389. width >>= 1;
  4390. height >>= 1;
  4391. depth >>= 1;
  4392. }
  4393. }
  4394. if (NULL != temp)
  4395. {
  4396. BX_FREE(g_allocator, temp);
  4397. }
  4398. }
  4399. GL_CHECK(glBindTexture(m_target, 0) );
  4400. }
  4401. void TextureGL::destroy()
  4402. {
  4403. if (0 == (m_flags & BGFX_TEXTURE_INTERNAL_SHARED)
  4404. && 0 != m_id)
  4405. {
  4406. GL_CHECK(glBindTexture(m_target, 0) );
  4407. GL_CHECK(glDeleteTextures(1, &m_id) );
  4408. m_id = 0;
  4409. }
  4410. if (0 != m_rbo)
  4411. {
  4412. GL_CHECK(glDeleteRenderbuffers(1, &m_rbo) );
  4413. m_rbo = 0;
  4414. }
  4415. }
  4416. void TextureGL::overrideInternal(uintptr_t _ptr)
  4417. {
  4418. destroy();
  4419. m_flags |= BGFX_TEXTURE_INTERNAL_SHARED;
  4420. m_id = (GLuint)_ptr;
  4421. }
  4422. void TextureGL::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  4423. {
  4424. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  4425. const uint32_t rectpitch = _rect.m_width*bpp/8;
  4426. uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  4427. GL_CHECK(glBindTexture(m_target, m_id) );
  4428. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  4429. GLenum target = isCubeMap()
  4430. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X
  4431. : m_target
  4432. ;
  4433. const bool swizzle = true
  4434. && TextureFormat::BGRA8 == m_requestedFormat
  4435. && !s_textureFormat[m_requestedFormat].m_supported
  4436. && !s_renderGL->m_textureSwizzleSupport
  4437. ;
  4438. const bool unpackRowLength = BX_IGNORE_C4127(!!BGFX_CONFIG_RENDERER_OPENGL || s_extension[Extension::EXT_unpack_subimage].m_supported);
  4439. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  4440. const bool convert = false
  4441. || (compressed && m_textureFormat != m_requestedFormat)
  4442. || swizzle
  4443. ;
  4444. const uint32_t width = _rect.m_width;
  4445. const uint32_t height = _rect.m_height;
  4446. uint8_t* temp = NULL;
  4447. if (convert
  4448. || !unpackRowLength)
  4449. {
  4450. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*height);
  4451. }
  4452. else if (unpackRowLength)
  4453. {
  4454. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, srcpitch*8/bpp) );
  4455. }
  4456. if (compressed)
  4457. {
  4458. const uint8_t* data = _mem->data;
  4459. if (!unpackRowLength)
  4460. {
  4461. imageCopy(temp, width, height, bpp, srcpitch, data);
  4462. data = temp;
  4463. }
  4464. GL_CHECK(compressedTexSubImage(target+_side
  4465. , _mip
  4466. , _rect.m_x
  4467. , _rect.m_y
  4468. , _z
  4469. , _rect.m_width
  4470. , _rect.m_height
  4471. , _depth
  4472. , m_fmt
  4473. , _mem->size
  4474. , data
  4475. ) );
  4476. }
  4477. else
  4478. {
  4479. const uint8_t* data = _mem->data;
  4480. if (convert)
  4481. {
  4482. imageDecodeToRgba8(temp, data, width, height, srcpitch, TextureFormat::Enum(m_requestedFormat) );
  4483. data = temp;
  4484. srcpitch = rectpitch;
  4485. }
  4486. if (!unpackRowLength
  4487. && !convert)
  4488. {
  4489. imageCopy(temp, width, height, bpp, srcpitch, data);
  4490. data = temp;
  4491. }
  4492. GL_CHECK(texSubImage(target+_side
  4493. , _mip
  4494. , _rect.m_x
  4495. , _rect.m_y
  4496. , _z
  4497. , _rect.m_width
  4498. , _rect.m_height
  4499. , _depth
  4500. , m_fmt
  4501. , m_type
  4502. , data
  4503. ) );
  4504. }
  4505. if (!convert
  4506. && unpackRowLength)
  4507. {
  4508. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) );
  4509. }
  4510. if (NULL != temp)
  4511. {
  4512. BX_FREE(g_allocator, temp);
  4513. }
  4514. }
  4515. void TextureGL::setSamplerState(uint32_t _flags, const float _rgba[4])
  4516. {
  4517. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  4518. && !s_textureFilter[m_textureFormat])
  4519. {
  4520. // Force point sampling when texture format doesn't support linear sampling.
  4521. _flags &= ~(0
  4522. | BGFX_TEXTURE_MIN_MASK
  4523. | BGFX_TEXTURE_MAG_MASK
  4524. | BGFX_TEXTURE_MIP_MASK
  4525. );
  4526. _flags |= 0
  4527. | BGFX_TEXTURE_MIN_POINT
  4528. | BGFX_TEXTURE_MAG_POINT
  4529. | BGFX_TEXTURE_MIP_POINT
  4530. ;
  4531. }
  4532. const uint32_t flags = (0 != (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags) ? m_flags : _flags) & BGFX_TEXTURE_SAMPLER_BITS_MASK;
  4533. bool hasBorderColor = false;
  4534. bx::HashMurmur2A murmur;
  4535. murmur.begin();
  4536. murmur.add(flags);
  4537. if (NULL != _rgba)
  4538. {
  4539. if (BGFX_TEXTURE_U_BORDER == (flags & BGFX_TEXTURE_U_BORDER)
  4540. || BGFX_TEXTURE_V_BORDER == (flags & BGFX_TEXTURE_V_BORDER)
  4541. || BGFX_TEXTURE_W_BORDER == (flags & BGFX_TEXTURE_W_BORDER) )
  4542. {
  4543. murmur.add(_rgba, 16);
  4544. hasBorderColor = true;
  4545. }
  4546. }
  4547. uint32_t hash = murmur.end();
  4548. if (hash != m_currentSamplerHash)
  4549. {
  4550. const GLenum target = m_target == GL_TEXTURE_2D_MULTISAMPLE ? GL_TEXTURE_2D : m_target;
  4551. const GLenum targetMsaa = m_target;
  4552. const uint8_t numMips = m_numMips;
  4553. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_S, s_textureAddress[(flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]) );
  4554. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_T, s_textureAddress[(flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]) );
  4555. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  4556. || s_extension[Extension::APPLE_texture_max_level].m_supported)
  4557. {
  4558. GL_CHECK(glTexParameteri(targetMsaa, GL_TEXTURE_MAX_LEVEL, numMips-1) );
  4559. }
  4560. if (target == GL_TEXTURE_3D)
  4561. {
  4562. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_R, s_textureAddress[(flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]) );
  4563. }
  4564. GLenum magFilter;
  4565. GLenum minFilter;
  4566. getFilters(flags, 1 < numMips, magFilter, minFilter);
  4567. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter) );
  4568. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter) );
  4569. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4570. || s_renderGL->m_borderColorSupport)
  4571. {
  4572. if (hasBorderColor)
  4573. {
  4574. GL_CHECK(glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, _rgba) );
  4575. }
  4576. }
  4577. if (0 != (flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  4578. && 0.0f < s_renderGL->m_maxAnisotropy)
  4579. {
  4580. GL_CHECK(glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderGL->m_maxAnisotropy) );
  4581. }
  4582. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  4583. || s_renderGL->m_shadowSamplersSupport)
  4584. {
  4585. const uint32_t cmpFunc = (flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  4586. if (0 == cmpFunc)
  4587. {
  4588. GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  4589. }
  4590. else
  4591. {
  4592. GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  4593. GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  4594. }
  4595. }
  4596. m_currentSamplerHash = hash;
  4597. }
  4598. }
  4599. void TextureGL::commit(uint32_t _stage, uint32_t _flags, const float _palette[][4])
  4600. {
  4601. const uint32_t flags = 0 == (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags)
  4602. ? _flags
  4603. : m_flags
  4604. ;
  4605. const uint32_t index = (flags & BGFX_TEXTURE_BORDER_COLOR_MASK) >> BGFX_TEXTURE_BORDER_COLOR_SHIFT;
  4606. GL_CHECK(glActiveTexture(GL_TEXTURE0+_stage) );
  4607. GL_CHECK(glBindTexture(m_target, m_id) );
  4608. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  4609. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  4610. {
  4611. // GLES2 doesn't have support for sampler object.
  4612. setSamplerState(flags, _palette[index]);
  4613. }
  4614. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4615. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL < 31) )
  4616. {
  4617. // In case that GL 2.1 sampler object is supported via extension.
  4618. if (s_renderGL->m_samplerObjectSupport)
  4619. {
  4620. s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]);
  4621. }
  4622. else
  4623. {
  4624. setSamplerState(flags, _palette[index]);
  4625. }
  4626. }
  4627. else
  4628. {
  4629. // Everything else has sampler object.
  4630. s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]);
  4631. }
  4632. }
  4633. void TextureGL::resolve() const
  4634. {
  4635. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  4636. if (renderTarget
  4637. && 1 < m_numMips)
  4638. {
  4639. GL_CHECK(glBindTexture(m_target, m_id) );
  4640. GL_CHECK(glGenerateMipmap(m_target) );
  4641. GL_CHECK(glBindTexture(m_target, 0) );
  4642. }
  4643. }
  4644. void writeString(bx::WriterI* _writer, const char* _str)
  4645. {
  4646. bx::write(_writer, _str, (int32_t)bx::strnlen(_str) );
  4647. }
  4648. void writeStringf(bx::WriterI* _writer, const char* _format, ...)
  4649. {
  4650. char temp[512];
  4651. va_list argList;
  4652. va_start(argList, _format);
  4653. int len = bx::vsnprintf(temp, BX_COUNTOF(temp), _format, argList);
  4654. va_end(argList);
  4655. bx::write(_writer, temp, len);
  4656. }
  4657. void strins(char* _str, const char* _insert)
  4658. {
  4659. size_t len = bx::strnlen(_insert);
  4660. bx::memMove(&_str[len], _str, bx::strnlen(_str)+1);
  4661. bx::memCopy(_str, _insert, len);
  4662. }
  4663. void ShaderGL::create(Memory* _mem)
  4664. {
  4665. bx::MemoryReader reader(_mem->data, _mem->size);
  4666. m_hash = bx::hashMurmur2A(_mem->data, _mem->size);
  4667. uint32_t magic;
  4668. bx::read(&reader, magic);
  4669. switch (magic)
  4670. {
  4671. case BGFX_CHUNK_MAGIC_CSH: m_type = GL_COMPUTE_SHADER; break;
  4672. case BGFX_CHUNK_MAGIC_FSH: m_type = GL_FRAGMENT_SHADER; break;
  4673. case BGFX_CHUNK_MAGIC_VSH: m_type = GL_VERTEX_SHADER; break;
  4674. default:
  4675. BGFX_FATAL(false, Fatal::InvalidShader, "Unknown shader format %x.", magic);
  4676. break;
  4677. }
  4678. uint32_t iohash;
  4679. bx::read(&reader, iohash);
  4680. uint16_t count;
  4681. bx::read(&reader, count);
  4682. BX_TRACE("%s Shader consts %d"
  4683. , BGFX_CHUNK_MAGIC_FSH == magic ? "Fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "Vertex" : "Compute"
  4684. , count
  4685. );
  4686. for (uint32_t ii = 0; ii < count; ++ii)
  4687. {
  4688. uint8_t nameSize = 0;
  4689. bx::read(&reader, nameSize);
  4690. char name[256];
  4691. bx::read(&reader, &name, nameSize);
  4692. name[nameSize] = '\0';
  4693. uint8_t type;
  4694. bx::read(&reader, type);
  4695. uint8_t num;
  4696. bx::read(&reader, num);
  4697. uint16_t regIndex;
  4698. bx::read(&reader, regIndex);
  4699. uint16_t regCount;
  4700. bx::read(&reader, regCount);
  4701. }
  4702. uint32_t shaderSize;
  4703. bx::read(&reader, shaderSize);
  4704. m_id = glCreateShader(m_type);
  4705. BX_WARN(0 != m_id, "Failed to create %s shader."
  4706. , BGFX_CHUNK_MAGIC_FSH == magic ? "fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "vertex" : "compute"
  4707. );
  4708. const char* code = (const char*)reader.getDataPtr();
  4709. if (0 != m_id)
  4710. {
  4711. if (GL_COMPUTE_SHADER != m_type)
  4712. {
  4713. int32_t codeLen = (int32_t)bx::strnlen(code);
  4714. int32_t tempLen = codeLen + (4<<10);
  4715. char* temp = (char*)alloca(tempLen);
  4716. bx::StaticMemoryBlockWriter writer(temp, tempLen);
  4717. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  4718. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  4719. {
  4720. writeString(&writer,
  4721. "#define centroid\n"
  4722. "#define flat\n"
  4723. "#define noperspective\n"
  4724. "#define smooth\n"
  4725. );
  4726. bool usesDerivatives = s_extension[Extension::OES_standard_derivatives].m_supported
  4727. && bx::findIdentifierMatch(code, s_OES_standard_derivatives)
  4728. ;
  4729. bool usesFragData = !!bx::findIdentifierMatch(code, "gl_FragData");
  4730. bool usesFragDepth = !!bx::findIdentifierMatch(code, "gl_FragDepth");
  4731. bool usesShadowSamplers = !!bx::findIdentifierMatch(code, s_EXT_shadow_samplers);
  4732. bool usesTexture3D = s_extension[Extension::OES_texture_3D].m_supported
  4733. && bx::findIdentifierMatch(code, s_OES_texture_3D)
  4734. ;
  4735. bool usesTextureLod = !!bx::findIdentifierMatch(code, s_EXT_shader_texture_lod);
  4736. bool usesFragmentOrdering = !!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering");
  4737. if (usesDerivatives)
  4738. {
  4739. writeString(&writer, "#extension GL_OES_standard_derivatives : enable\n");
  4740. }
  4741. if (usesFragData)
  4742. {
  4743. BX_WARN(s_extension[Extension::EXT_draw_buffers ].m_supported
  4744. || s_extension[Extension::WEBGL_draw_buffers].m_supported
  4745. , "EXT_draw_buffers is used but not supported by GLES2 driver."
  4746. );
  4747. writeString(&writer
  4748. , "#extension GL_EXT_draw_buffers : enable\n"
  4749. );
  4750. }
  4751. bool insertFragDepth = false;
  4752. if (usesFragDepth)
  4753. {
  4754. BX_WARN(s_extension[Extension::EXT_frag_depth].m_supported, "EXT_frag_depth is used but not supported by GLES2 driver.");
  4755. if (s_extension[Extension::EXT_frag_depth].m_supported)
  4756. {
  4757. writeString(&writer
  4758. , "#extension GL_EXT_frag_depth : enable\n"
  4759. "#define bgfx_FragDepth gl_FragDepthEXT\n"
  4760. );
  4761. char str[128];
  4762. bx::snprintf(str, BX_COUNTOF(str), "%s float gl_FragDepthEXT;\n"
  4763. , s_extension[Extension::OES_fragment_precision_high].m_supported ? "highp" : "mediump"
  4764. );
  4765. writeString(&writer, str);
  4766. }
  4767. else
  4768. {
  4769. insertFragDepth = true;
  4770. }
  4771. }
  4772. if (usesShadowSamplers)
  4773. {
  4774. if (s_renderGL->m_shadowSamplersSupport)
  4775. {
  4776. writeString(&writer
  4777. , "#extension GL_EXT_shadow_samplers : enable\n"
  4778. "#define shadow2D shadow2DEXT\n"
  4779. "#define shadow2DProj shadow2DProjEXT\n"
  4780. );
  4781. }
  4782. else
  4783. {
  4784. writeString(&writer
  4785. , "#define sampler2DShadow sampler2D\n"
  4786. "#define shadow2D(_sampler, _coord) step(_coord.z, texture2D(_sampler, _coord.xy).x)\n"
  4787. "#define shadow2DProj(_sampler, _coord) step(_coord.z/_coord.w, texture2DProj(_sampler, _coord).x)\n"
  4788. );
  4789. }
  4790. }
  4791. if (usesTexture3D)
  4792. {
  4793. writeString(&writer, "#extension GL_OES_texture_3D : enable\n");
  4794. }
  4795. if (usesTextureLod)
  4796. {
  4797. BX_WARN(s_extension[Extension::EXT_shader_texture_lod].m_supported, "EXT_shader_texture_lod is used but not supported by GLES2 driver.");
  4798. if (s_extension[Extension::EXT_shader_texture_lod].m_supported
  4799. /*&& GL_VERTEX_SHADER == m_type*/)
  4800. {
  4801. writeString(&writer
  4802. , "#extension GL_EXT_shader_texture_lod : enable\n"
  4803. "#define texture2DLod texture2DLodEXT\n"
  4804. "#define texture2DProjLod texture2DProjLodEXT\n"
  4805. "#define textureCubeLod textureCubeLodEXT\n"
  4806. );
  4807. }
  4808. else
  4809. {
  4810. writeString(&writer
  4811. , "#define texture2DLod(_sampler, _coord, _level) texture2D(_sampler, _coord)\n"
  4812. "#define texture2DProjLod(_sampler, _coord, _level) texture2DProj(_sampler, _coord)\n"
  4813. "#define textureCubeLod(_sampler, _coord, _level) textureCube(_sampler, _coord)\n"
  4814. );
  4815. }
  4816. }
  4817. if (usesFragmentOrdering)
  4818. {
  4819. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  4820. {
  4821. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  4822. }
  4823. else
  4824. {
  4825. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  4826. }
  4827. }
  4828. writeStringf(&writer, "precision %s float;\n"
  4829. , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp"
  4830. );
  4831. bx::write(&writer, code, codeLen);
  4832. bx::write(&writer, '\0');
  4833. if (insertFragDepth)
  4834. {
  4835. const char* entry = bx::strnstr(temp, "void main ()");
  4836. if (NULL != entry)
  4837. {
  4838. char* brace = const_cast<char*>(bx::strnstr(entry, "{") );
  4839. if (NULL != brace)
  4840. {
  4841. const char* end = bx::strmb(brace, '{', '}');
  4842. if (NULL != end)
  4843. {
  4844. strins(brace+1, "\n float bgfx_FragDepth = 0.0;\n");
  4845. }
  4846. }
  4847. }
  4848. }
  4849. // Replace all instances of gl_FragDepth with bgfx_FragDepth.
  4850. for (const char* fragDepth = bx::findIdentifierMatch(temp, "gl_FragDepth"); NULL != fragDepth; fragDepth = bx::findIdentifierMatch(fragDepth, "gl_FragDepth") )
  4851. {
  4852. char* insert = const_cast<char*>(fragDepth);
  4853. strins(insert, "bg");
  4854. bx::memCopy(insert + 2, "fx", 2);
  4855. }
  4856. }
  4857. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4858. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL <= 21) )
  4859. {
  4860. const bool usesTextureLod = true
  4861. && s_extension[Extension::ARB_shader_texture_lod].m_supported
  4862. && bx::findIdentifierMatch(code, s_ARB_shader_texture_lod)
  4863. ;
  4864. const bool usesGpuShader5 = !!bx::findIdentifierMatch(code, s_ARB_gpu_shader5);
  4865. const bool usesIUsamplers = !!bx::findIdentifierMatch(code, s_uisamplers);
  4866. const bool usesTexelFetch = !!bx::findIdentifierMatch(code, s_texelFetch);
  4867. const bool usesTextureArray = !!bx::findIdentifierMatch(code, s_textureArray);
  4868. const bool usesTextureMS = !!bx::findIdentifierMatch(code, s_ARB_texture_multisample);
  4869. const bool usesPacking = !!bx::findIdentifierMatch(code, s_ARB_shading_language_packing);
  4870. uint32_t version =
  4871. usesIUsamplers || usesTexelFetch ? 130
  4872. : usesTextureLod ? 120
  4873. : 120
  4874. ;
  4875. if (0 != version)
  4876. {
  4877. writeStringf(&writer, "#version %d\n", version);
  4878. }
  4879. if (usesTextureLod)
  4880. {
  4881. if (m_type == GL_FRAGMENT_SHADER)
  4882. {
  4883. writeString(&writer, "#extension GL_ARB_shader_texture_lod : enable\n");
  4884. }
  4885. }
  4886. if (usesGpuShader5)
  4887. {
  4888. writeString(&writer, "#extension GL_ARB_gpu_shader5 : enable\n");
  4889. }
  4890. if (usesPacking)
  4891. {
  4892. writeString(&writer, "#extension GL_ARB_shading_language_packing : enable\n");
  4893. }
  4894. if (usesTextureMS)
  4895. {
  4896. writeString(&writer, "#extension GL_ARB_texture_multisample : enable\n");
  4897. }
  4898. if (usesTextureArray)
  4899. {
  4900. writeString(&writer, "#extension GL_EXT_texture_array : enable\n");
  4901. }
  4902. if (130 <= version)
  4903. {
  4904. if (m_type == GL_FRAGMENT_SHADER)
  4905. {
  4906. writeString(&writer, "#define varying in\n");
  4907. }
  4908. else
  4909. {
  4910. writeString(&writer, "#define attribute in\n");
  4911. writeString(&writer, "#define varying out\n");
  4912. }
  4913. uint32_t fragData = 0;
  4914. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  4915. {
  4916. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  4917. {
  4918. char tmpFragData[16];
  4919. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  4920. fragData = bx::uint32_max(fragData, NULL == bx::strnstr(code, tmpFragData) ? 0 : ii+1);
  4921. }
  4922. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  4923. }
  4924. if (0 != fragData)
  4925. {
  4926. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  4927. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  4928. }
  4929. else
  4930. {
  4931. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  4932. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  4933. }
  4934. }
  4935. else
  4936. {
  4937. if (m_type == GL_FRAGMENT_SHADER)
  4938. {
  4939. writeString(&writer, "#define in varying\n");
  4940. }
  4941. else
  4942. {
  4943. writeString(&writer, "#define in attribute\n");
  4944. writeString(&writer, "#define out varying\n");
  4945. }
  4946. }
  4947. writeString(&writer,
  4948. "#define lowp\n"
  4949. "#define mediump\n"
  4950. "#define highp\n"
  4951. "#define centroid\n"
  4952. "#define flat\n"
  4953. "#define noperspective\n"
  4954. "#define smooth\n"
  4955. );
  4956. bx::write(&writer, code, codeLen);
  4957. bx::write(&writer, '\0');
  4958. }
  4959. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 31)
  4960. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4961. {
  4962. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4963. {
  4964. writeString(&writer
  4965. , "#version 300 es\n"
  4966. "precision mediump float;\n"
  4967. );
  4968. }
  4969. else
  4970. {
  4971. writeString(&writer, "#version 140\n");
  4972. }
  4973. writeString(&writer, "#define texture2DLod textureLod\n");
  4974. writeString(&writer, "#define texture3DLod textureLod\n");
  4975. writeString(&writer, "#define textureCubeLod textureLod\n");
  4976. if (m_type == GL_FRAGMENT_SHADER)
  4977. {
  4978. writeString(&writer, "#define varying in\n");
  4979. writeString(&writer, "#define texture2D texture\n");
  4980. writeString(&writer, "#define texture2DProj textureProj\n");
  4981. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  4982. {
  4983. writeString(&writer, "#define shadow2D(_sampler, _coord) vec2(textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  4984. writeString(&writer, "#define shadow2DProj(_sampler, _coord) vec2(textureProj(_sampler, _coord) ) )\n");
  4985. }
  4986. else
  4987. {
  4988. writeString(&writer, "#define shadow2D(_sampler, _coord) (textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  4989. writeString(&writer, "#define shadow2DProj(_sampler, _coord) (textureProj(_sampler, _coord) ) )\n");
  4990. }
  4991. writeString(&writer, "#define texture3D texture\n");
  4992. writeString(&writer, "#define textureCube texture\n");
  4993. uint32_t fragData = 0;
  4994. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  4995. {
  4996. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  4997. {
  4998. char tmpFragData[16];
  4999. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  5000. fragData = bx::uint32_max(fragData, NULL == bx::strnstr(code, tmpFragData) ? 0 : ii+1);
  5001. }
  5002. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  5003. }
  5004. if (!!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering") )
  5005. {
  5006. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  5007. {
  5008. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  5009. }
  5010. else
  5011. {
  5012. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  5013. }
  5014. }
  5015. if (!!bx::findIdentifierMatch(code, s_ARB_texture_multisample) )
  5016. {
  5017. writeString(&writer, "#extension GL_ARB_texture_multisample : enable\n");
  5018. }
  5019. if (0 != fragData)
  5020. {
  5021. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  5022. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  5023. }
  5024. else
  5025. {
  5026. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  5027. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  5028. }
  5029. }
  5030. else
  5031. {
  5032. writeString(&writer, "#define attribute in\n");
  5033. writeString(&writer, "#define varying out\n");
  5034. }
  5035. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  5036. {
  5037. writeString(&writer
  5038. , "#define lowp\n"
  5039. "#define mediump\n"
  5040. "#define highp\n"
  5041. );
  5042. }
  5043. bx::write(&writer, code, codeLen);
  5044. bx::write(&writer, '\0');
  5045. }
  5046. code = temp;
  5047. }
  5048. GL_CHECK(glShaderSource(m_id, 1, (const GLchar**)&code, NULL) );
  5049. GL_CHECK(glCompileShader(m_id) );
  5050. GLint compiled = 0;
  5051. GL_CHECK(glGetShaderiv(m_id, GL_COMPILE_STATUS, &compiled) );
  5052. if (0 == compiled)
  5053. {
  5054. BX_TRACE("\n####\n%s\n####", code);
  5055. GLsizei len;
  5056. char log[1024];
  5057. GL_CHECK(glGetShaderInfoLog(m_id, sizeof(log), &len, log) );
  5058. BX_TRACE("Failed to compile shader. %d: %s", compiled, log);
  5059. GL_CHECK(glDeleteShader(m_id) );
  5060. m_id = 0;
  5061. BGFX_FATAL(false, bgfx::Fatal::InvalidShader, "Failed to compile shader.");
  5062. }
  5063. else if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  5064. && s_extension[Extension::ANGLE_translated_shader_source].m_supported
  5065. && NULL != glGetTranslatedShaderSourceANGLE)
  5066. {
  5067. GLsizei len;
  5068. GL_CHECK(glGetShaderiv(m_id, GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE, &len) );
  5069. char* source = (char*)alloca(len);
  5070. GL_CHECK(glGetTranslatedShaderSourceANGLE(m_id, len, &len, source) );
  5071. BX_TRACE("ANGLE source (len: %d):\n%s\n####", len, source);
  5072. }
  5073. }
  5074. }
  5075. void ShaderGL::destroy()
  5076. {
  5077. if (0 != m_id)
  5078. {
  5079. GL_CHECK(glDeleteShader(m_id) );
  5080. m_id = 0;
  5081. }
  5082. }
  5083. void FrameBufferGL::create(uint8_t _num, const Attachment* _attachment)
  5084. {
  5085. GL_CHECK(glGenFramebuffers(1, &m_fbo[0]) );
  5086. m_denseIdx = UINT16_MAX;
  5087. m_numTh = _num;
  5088. bx::memCopy(m_attachment, _attachment, _num*sizeof(Attachment) );
  5089. m_needPresent = false;
  5090. postReset();
  5091. }
  5092. void FrameBufferGL::postReset()
  5093. {
  5094. if (0 != m_fbo[0])
  5095. {
  5096. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  5097. bool needResolve = false;
  5098. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  5099. uint32_t colorIdx = 0;
  5100. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5101. {
  5102. TextureHandle handle = m_attachment[ii].handle;
  5103. if (isValid(handle) )
  5104. {
  5105. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  5106. if (0 == colorIdx)
  5107. {
  5108. m_width = bx::uint32_max(texture.m_width >> m_attachment[ii].mip, 1);
  5109. m_height = bx::uint32_max(texture.m_height >> m_attachment[ii].mip, 1);
  5110. }
  5111. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  5112. TextureFormat::Enum format = (TextureFormat::Enum)texture.m_textureFormat;
  5113. if (isDepth(format) )
  5114. {
  5115. const ImageBlockInfo& info = getBlockInfo(format);
  5116. if (0 < info.stencilBits)
  5117. {
  5118. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  5119. }
  5120. else if (0 == info.depthBits)
  5121. {
  5122. attachment = GL_STENCIL_ATTACHMENT;
  5123. }
  5124. else
  5125. {
  5126. attachment = GL_DEPTH_ATTACHMENT;
  5127. }
  5128. }
  5129. else
  5130. {
  5131. buffers[colorIdx] = attachment;
  5132. ++colorIdx;
  5133. }
  5134. if (0 != texture.m_rbo)
  5135. {
  5136. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  5137. , attachment
  5138. , GL_RENDERBUFFER
  5139. , texture.m_rbo
  5140. ) );
  5141. }
  5142. else
  5143. {
  5144. GLenum target = texture.isCubeMap()
  5145. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + m_attachment[ii].layer
  5146. : texture.m_target
  5147. ;
  5148. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  5149. , attachment
  5150. , target
  5151. , texture.m_id
  5152. , m_attachment[ii].mip
  5153. ) );
  5154. }
  5155. needResolve |= (0 != texture.m_rbo) && (0 != texture.m_id);
  5156. }
  5157. }
  5158. m_num = uint8_t(colorIdx);
  5159. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  5160. {
  5161. if (0 == colorIdx)
  5162. {
  5163. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  5164. {
  5165. // When only depth is attached disable draw buffer to avoid
  5166. // GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER.
  5167. GL_CHECK(glDrawBuffer(GL_NONE) );
  5168. }
  5169. }
  5170. else
  5171. {
  5172. GL_CHECK(glDrawBuffers(colorIdx, buffers) );
  5173. }
  5174. // Disable read buffer to avoid GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER.
  5175. GL_CHECK(glReadBuffer(GL_NONE) );
  5176. }
  5177. frameBufferValidate();
  5178. if (needResolve)
  5179. {
  5180. GL_CHECK(glGenFramebuffers(1, &m_fbo[1]) );
  5181. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) );
  5182. colorIdx = 0;
  5183. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5184. {
  5185. TextureHandle handle = m_attachment[ii].handle;
  5186. if (isValid(handle) )
  5187. {
  5188. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  5189. if (0 != texture.m_id)
  5190. {
  5191. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  5192. if (!isDepth( (TextureFormat::Enum)texture.m_textureFormat) )
  5193. {
  5194. ++colorIdx;
  5195. GLenum target = texture.isCubeMap()
  5196. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + m_attachment[ii].layer
  5197. : texture.m_target
  5198. ;
  5199. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  5200. , attachment
  5201. , target
  5202. , texture.m_id
  5203. , m_attachment[ii].mip
  5204. ) );
  5205. }
  5206. }
  5207. }
  5208. }
  5209. frameBufferValidate();
  5210. }
  5211. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  5212. }
  5213. }
  5214. void FrameBufferGL::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat)
  5215. {
  5216. BX_UNUSED(_depthFormat);
  5217. m_swapChain = s_renderGL->m_glctx.createSwapChain(_nwh);
  5218. m_width = _width;
  5219. m_height = _height;
  5220. m_numTh = 0;
  5221. m_denseIdx = _denseIdx;
  5222. m_needPresent = false;
  5223. }
  5224. uint16_t FrameBufferGL::destroy()
  5225. {
  5226. if (0 != m_num)
  5227. {
  5228. GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) );
  5229. m_num = 0;
  5230. }
  5231. if (NULL != m_swapChain)
  5232. {
  5233. s_renderGL->m_glctx.destroySwapChain(m_swapChain);
  5234. m_swapChain = NULL;
  5235. }
  5236. bx::memSet(m_fbo, 0, sizeof(m_fbo) );
  5237. uint16_t denseIdx = m_denseIdx;
  5238. m_denseIdx = UINT16_MAX;
  5239. m_needPresent = false;
  5240. m_numTh = 0;
  5241. return denseIdx;
  5242. }
  5243. void FrameBufferGL::resolve()
  5244. {
  5245. if (0 != m_fbo[1])
  5246. {
  5247. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  5248. GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0) );
  5249. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) );
  5250. GL_CHECK(glBlitFramebuffer(0
  5251. , 0
  5252. , m_width
  5253. , m_height
  5254. , 0
  5255. , 0
  5256. , m_width
  5257. , m_height
  5258. , GL_COLOR_BUFFER_BIT
  5259. , GL_LINEAR
  5260. ) );
  5261. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  5262. GL_CHECK(glReadBuffer(GL_NONE) );
  5263. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  5264. }
  5265. if (0 < m_numTh)
  5266. {
  5267. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5268. {
  5269. TextureHandle handle = m_attachment[ii].handle;
  5270. if (isValid(handle) )
  5271. {
  5272. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  5273. texture.resolve();
  5274. }
  5275. }
  5276. }
  5277. }
  5278. void FrameBufferGL::discard(uint16_t _flags)
  5279. {
  5280. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS+2];
  5281. uint32_t idx = 0;
  5282. if (BGFX_CLEAR_NONE != (_flags & BGFX_CLEAR_DISCARD_COLOR_MASK) )
  5283. {
  5284. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  5285. {
  5286. if (BGFX_CLEAR_NONE != (_flags & (BGFX_CLEAR_DISCARD_COLOR_0<<ii) ) )
  5287. {
  5288. buffers[idx++] = GL_COLOR_ATTACHMENT0 + ii;
  5289. }
  5290. }
  5291. }
  5292. uint32_t dsFlags = _flags & (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL);
  5293. if (BGFX_CLEAR_NONE != dsFlags)
  5294. {
  5295. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  5296. && (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL) == dsFlags)
  5297. {
  5298. buffers[idx++] = GL_DEPTH_STENCIL_ATTACHMENT;
  5299. }
  5300. else if (BGFX_CLEAR_DISCARD_DEPTH == dsFlags)
  5301. {
  5302. buffers[idx++] = GL_DEPTH_ATTACHMENT;
  5303. }
  5304. else if (BGFX_CLEAR_DISCARD_STENCIL == dsFlags)
  5305. {
  5306. buffers[idx++] = GL_STENCIL_ATTACHMENT;
  5307. }
  5308. }
  5309. GL_CHECK(glInvalidateFramebuffer(GL_FRAMEBUFFER, idx, buffers) );
  5310. }
  5311. void OcclusionQueryGL::create()
  5312. {
  5313. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  5314. {
  5315. Query& query = m_query[ii];
  5316. GL_CHECK(glGenQueries(1, &query.m_id) );
  5317. }
  5318. }
  5319. void OcclusionQueryGL::destroy()
  5320. {
  5321. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  5322. {
  5323. Query& query = m_query[ii];
  5324. GL_CHECK(glDeleteQueries(1, &query.m_id) );
  5325. }
  5326. }
  5327. void OcclusionQueryGL::begin(Frame* _render, OcclusionQueryHandle _handle)
  5328. {
  5329. while (0 == m_control.reserve(1) )
  5330. {
  5331. resolve(_render, true);
  5332. }
  5333. Query& query = m_query[m_control.m_current];
  5334. GL_CHECK(glBeginQuery(GL_SAMPLES_PASSED, query.m_id) );
  5335. query.m_handle = _handle;
  5336. }
  5337. void OcclusionQueryGL::end()
  5338. {
  5339. GL_CHECK(glEndQuery(GL_SAMPLES_PASSED) );
  5340. m_control.commit(1);
  5341. }
  5342. void OcclusionQueryGL::resolve(Frame* _render, bool _wait)
  5343. {
  5344. while (0 != m_control.available() )
  5345. {
  5346. Query& query = m_query[m_control.m_read];
  5347. if (isValid(query.m_handle) )
  5348. {
  5349. int32_t result;
  5350. if (!_wait)
  5351. {
  5352. GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT_AVAILABLE, &result) );
  5353. if (!result)
  5354. {
  5355. break;
  5356. }
  5357. }
  5358. GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT, &result) );
  5359. _render->m_occlusion[query.m_handle.idx] = int32_t(result);
  5360. }
  5361. m_control.consume(1);
  5362. }
  5363. }
  5364. void OcclusionQueryGL::invalidate(OcclusionQueryHandle _handle)
  5365. {
  5366. const uint32_t size = m_control.m_size;
  5367. for (uint32_t ii = 0, num = m_control.available(); ii < num; ++ii)
  5368. {
  5369. Query& query = m_query[(m_control.m_read + ii) % size];
  5370. if (query.m_handle.idx == _handle.idx)
  5371. {
  5372. query.m_handle.idx = bgfx::invalidHandle;
  5373. }
  5374. }
  5375. }
  5376. void RendererContextGL::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  5377. {
  5378. BGFX_GPU_PROFILER_BEGIN_DYNAMIC("rendererSubmit");
  5379. if (_render->m_capture)
  5380. {
  5381. renderDocTriggerCapture();
  5382. }
  5383. if (1 < m_numWindows
  5384. && m_vaoSupport)
  5385. {
  5386. m_vaoSupport = false;
  5387. GL_CHECK(glBindVertexArray(0) );
  5388. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  5389. m_vao = 0;
  5390. m_vaoStateCache.invalidate();
  5391. }
  5392. m_glctx.makeCurrent(NULL);
  5393. const GLuint defaultVao = m_vao;
  5394. if (0 != defaultVao)
  5395. {
  5396. GL_CHECK(glBindVertexArray(defaultVao) );
  5397. }
  5398. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  5399. updateResolution(_render->m_resolution);
  5400. int64_t elapsed = -bx::getHPCounter();
  5401. int64_t captureElapsed = 0;
  5402. if (m_timerQuerySupport)
  5403. {
  5404. m_gpuTimer.begin();
  5405. }
  5406. if (0 < _render->m_iboffset)
  5407. {
  5408. TransientIndexBuffer* ib = _render->m_transientIb;
  5409. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data, true);
  5410. }
  5411. if (0 < _render->m_vboffset)
  5412. {
  5413. TransientVertexBuffer* vb = _render->m_transientVb;
  5414. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data, true);
  5415. }
  5416. _render->sort();
  5417. RenderDraw currentState;
  5418. currentState.clear();
  5419. currentState.m_stateFlags = BGFX_STATE_NONE;
  5420. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  5421. _render->m_hmdInitialized = m_ovr.isInitialized();
  5422. const bool hmdEnabled = m_ovr.isEnabled();
  5423. static ViewState viewState;
  5424. viewState.reset(_render, hmdEnabled);
  5425. uint16_t programIdx = invalidHandle;
  5426. SortKey key;
  5427. uint16_t view = UINT16_MAX;
  5428. FrameBufferHandle fbh = { BGFX_CONFIG_MAX_FRAME_BUFFERS };
  5429. BlitKey blitKey;
  5430. blitKey.decode(_render->m_blitKeys[0]);
  5431. uint16_t numBlitItems = _render->m_numBlitItems;
  5432. uint16_t blitItem = 0;
  5433. int32_t resolutionHeight = hmdEnabled
  5434. ? _render->m_hmd.height
  5435. : _render->m_resolution.m_height
  5436. ;
  5437. uint32_t blendFactor = 0;
  5438. uint8_t primIndex;
  5439. {
  5440. const uint64_t pt = 0;
  5441. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  5442. }
  5443. PrimInfo prim = s_primInfo[primIndex];
  5444. GL_CHECK(glPolygonMode(GL_FRONT_AND_BACK
  5445. , _render->m_debug&BGFX_DEBUG_WIREFRAME
  5446. ? GL_LINE
  5447. : GL_FILL
  5448. ) );
  5449. GLuint currentVao = 0;
  5450. bool wasCompute = false;
  5451. bool viewHasScissor = false;
  5452. Rect viewScissorRect;
  5453. viewScissorRect.clear();
  5454. uint16_t discardFlags = BGFX_CLEAR_NONE;
  5455. const bool blendIndependentSupported = s_extension[Extension::ARB_draw_buffers_blend].m_supported;
  5456. const bool computeSupported = (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && s_extension[Extension::ARB_compute_shader].m_supported)
  5457. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  5458. ;
  5459. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  5460. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  5461. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  5462. uint32_t statsNumIndices = 0;
  5463. uint32_t statsKeyType[2] = {};
  5464. if (m_occlusionQuerySupport)
  5465. {
  5466. m_occlusionQuery.resolve(_render);
  5467. }
  5468. uint8_t eye = 0;
  5469. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  5470. {
  5471. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  5472. bool viewRestart = false;
  5473. uint8_t restartState = 0;
  5474. viewState.m_rect = _render->m_rect[0];
  5475. int32_t numItems = _render->m_num;
  5476. for (int32_t item = 0, restartItem = numItems; item < numItems || restartItem < numItems;)
  5477. {
  5478. const uint64_t encodedKey = _render->m_sortKeys[item];
  5479. const bool isCompute = key.decode(encodedKey, _render->m_viewRemap);
  5480. statsKeyType[isCompute]++;
  5481. const bool viewChanged = 0
  5482. || key.m_view != view
  5483. || item == numItems
  5484. ;
  5485. const RenderItem& renderItem = _render->m_renderItem[_render->m_sortValues[item] ];
  5486. ++item;
  5487. if (viewChanged)
  5488. {
  5489. if (1 == restartState)
  5490. {
  5491. restartState = 2;
  5492. item = restartItem;
  5493. restartItem = numItems;
  5494. view = UINT16_MAX;
  5495. continue;
  5496. }
  5497. view = key.m_view;
  5498. programIdx = invalidHandle;
  5499. if (_render->m_fb[view].idx != fbh.idx)
  5500. {
  5501. fbh = _render->m_fb[view];
  5502. resolutionHeight = hmdEnabled
  5503. ? _render->m_hmd.height
  5504. : _render->m_resolution.m_height
  5505. ;
  5506. resolutionHeight = setFrameBuffer(fbh, resolutionHeight, discardFlags);
  5507. }
  5508. viewRestart = ( (BGFX_VIEW_STEREO == (_render->m_viewFlags[view] & BGFX_VIEW_STEREO) ) );
  5509. viewRestart &= hmdEnabled;
  5510. if (viewRestart)
  5511. {
  5512. if (0 == restartState)
  5513. {
  5514. restartState = 1;
  5515. restartItem = item - 1;
  5516. }
  5517. eye = (restartState - 1) & 1;
  5518. restartState &= 1;
  5519. }
  5520. else
  5521. {
  5522. eye = 0;
  5523. }
  5524. if (item > 1)
  5525. {
  5526. BGFX_GPU_PROFILER_END();
  5527. BGFX_PROFILER_END();
  5528. }
  5529. BGFX_PROFILER_BEGIN_DYNAMIC(s_viewName[view]);
  5530. BGFX_GPU_PROFILER_BEGIN_DYNAMIC(s_viewName[view]);
  5531. viewState.m_rect = _render->m_rect[view];
  5532. if (viewRestart)
  5533. {
  5534. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5535. {
  5536. char* viewName = s_viewName[view];
  5537. viewName[3] = ' ';
  5538. viewName[4] = eye ? 'R' : 'L';
  5539. GL_CHECK(glInsertEventMarker(0, viewName) );
  5540. }
  5541. if (m_ovr.isEnabled() )
  5542. {
  5543. m_ovr.getViewport(eye, &viewState.m_rect);
  5544. }
  5545. else
  5546. {
  5547. viewState.m_rect.m_x = eye * (viewState.m_rect.m_width+1)/2;
  5548. viewState.m_rect.m_width /= 2;
  5549. }
  5550. }
  5551. else
  5552. {
  5553. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5554. {
  5555. char* viewName = s_viewName[view];
  5556. viewName[3] = ' ';
  5557. viewName[4] = ' ';
  5558. GL_CHECK(glInsertEventMarker(0, viewName) );
  5559. }
  5560. }
  5561. const Rect& scissorRect = _render->m_scissor[view];
  5562. viewHasScissor = !scissorRect.isZero();
  5563. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  5564. GL_CHECK(glViewport(viewState.m_rect.m_x
  5565. , resolutionHeight-viewState.m_rect.m_height-viewState.m_rect.m_y
  5566. , viewState.m_rect.m_width
  5567. , viewState.m_rect.m_height
  5568. ) );
  5569. Clear& clear = _render->m_clear[view];
  5570. discardFlags = clear.m_flags & BGFX_CLEAR_DISCARD_MASK;
  5571. if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) )
  5572. {
  5573. clearQuad(_clearQuad, viewState.m_rect, clear, resolutionHeight, _render->m_colorPalette);
  5574. currentVao = UINT32_MAX; // clearQuad will mess with VAO, invalidate it.
  5575. }
  5576. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  5577. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5578. GL_CHECK(glDepthFunc(GL_LESS) );
  5579. GL_CHECK(glEnable(GL_CULL_FACE) );
  5580. GL_CHECK(glDisable(GL_BLEND) );
  5581. if (m_blitSupported)
  5582. {
  5583. const uint8_t blitView = SortKey::decodeView(encodedKey);
  5584. for (; blitItem < numBlitItems && blitKey.m_view <= blitView; blitItem++)
  5585. {
  5586. const BlitItem& bi = _render->m_blitItem[blitItem];
  5587. blitKey.decode(_render->m_blitKeys[blitItem + 1]);
  5588. const TextureGL& src = m_textures[bi.m_src.idx];
  5589. const TextureGL& dst = m_textures[bi.m_dst.idx];
  5590. uint32_t srcWidth = bx::uint32_min(src.m_width, bi.m_srcX + bi.m_width) - bi.m_srcX;
  5591. uint32_t srcHeight = bx::uint32_min(src.m_height, bi.m_srcY + bi.m_height) - bi.m_srcY;
  5592. uint32_t srcDepth = bx::uint32_min(src.m_depth, bi.m_srcZ + bi.m_depth) - bi.m_srcZ;
  5593. uint32_t dstWidth = bx::uint32_min(dst.m_width, bi.m_dstX + bi.m_width) - bi.m_dstX;
  5594. uint32_t dstHeight = bx::uint32_min(dst.m_height, bi.m_dstY + bi.m_height) - bi.m_dstY;
  5595. uint32_t dstDepth = bx::uint32_min(dst.m_depth, bi.m_dstZ + bi.m_depth) - bi.m_dstZ;
  5596. uint32_t width = bx::uint32_min(srcWidth, dstWidth);
  5597. uint32_t height = bx::uint32_min(srcHeight, dstHeight);
  5598. uint32_t depth = bx::uint32_min(srcDepth, dstDepth);
  5599. GL_CHECK(glCopyImageSubData(src.m_id
  5600. , src.m_target
  5601. , bi.m_srcMip
  5602. , bi.m_srcX
  5603. , bi.m_srcY
  5604. , bi.m_srcZ
  5605. , dst.m_id
  5606. , dst.m_target
  5607. , bi.m_dstMip
  5608. , bi.m_dstX
  5609. , bi.m_dstY
  5610. , bi.m_dstZ
  5611. , width
  5612. , height
  5613. , bx::uint32_imax(depth, 1)
  5614. ) );
  5615. }
  5616. }
  5617. }
  5618. if (isCompute)
  5619. {
  5620. if (!wasCompute)
  5621. {
  5622. wasCompute = true;
  5623. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5624. {
  5625. char* viewName = s_viewName[view];
  5626. viewName[3] = 'C';
  5627. GL_CHECK(glInsertEventMarker(0, viewName) );
  5628. }
  5629. }
  5630. if (computeSupported)
  5631. {
  5632. const RenderCompute& compute = renderItem.compute;
  5633. ProgramGL& program = m_program[key.m_program];
  5634. GL_CHECK(glUseProgram(program.m_id) );
  5635. GLbitfield barrier = 0;
  5636. for (uint32_t ii = 0; ii < BGFX_MAX_COMPUTE_BINDINGS; ++ii)
  5637. {
  5638. const Binding& bind = compute.m_bind[ii];
  5639. if (invalidHandle != bind.m_idx)
  5640. {
  5641. switch (bind.m_type)
  5642. {
  5643. case Binding::Image:
  5644. {
  5645. const TextureGL& texture = m_textures[bind.m_idx];
  5646. GL_CHECK(glBindImageTexture(ii
  5647. , texture.m_id
  5648. , bind.m_un.m_compute.m_mip
  5649. , texture.isCubeMap()?GL_TRUE:GL_FALSE
  5650. , 0
  5651. , s_access[bind.m_un.m_compute.m_access]
  5652. , s_imageFormat[bind.m_un.m_compute.m_format])
  5653. );
  5654. barrier |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
  5655. }
  5656. break;
  5657. case Binding::IndexBuffer:
  5658. {
  5659. const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx];
  5660. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  5661. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  5662. }
  5663. break;
  5664. case Binding::VertexBuffer:
  5665. {
  5666. const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx];
  5667. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  5668. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  5669. }
  5670. break;
  5671. }
  5672. }
  5673. }
  5674. if (0 != barrier)
  5675. {
  5676. bool constantsChanged = compute.m_constBegin < compute.m_constEnd;
  5677. rendererUpdateUniforms(this, _render->m_uniformBuffer, compute.m_constBegin, compute.m_constEnd);
  5678. if (constantsChanged
  5679. && NULL != program.m_constantBuffer)
  5680. {
  5681. commit(*program.m_constantBuffer);
  5682. }
  5683. viewState.setPredefined<1>(this, view, eye, program, _render, compute);
  5684. if (isValid(compute.m_indirectBuffer) )
  5685. {
  5686. const VertexBufferGL& vb = m_vertexBuffers[compute.m_indirectBuffer.idx];
  5687. if (currentState.m_indirectBuffer.idx != compute.m_indirectBuffer.idx)
  5688. {
  5689. currentState.m_indirectBuffer = compute.m_indirectBuffer;
  5690. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, vb.m_id) );
  5691. }
  5692. uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect
  5693. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  5694. : compute.m_numIndirect
  5695. ;
  5696. uintptr_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5697. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  5698. {
  5699. GL_CHECK(glDispatchComputeIndirect( (GLintptr)args) );
  5700. args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5701. }
  5702. }
  5703. else
  5704. {
  5705. if (isValid(currentState.m_indirectBuffer) )
  5706. {
  5707. currentState.m_indirectBuffer.idx = invalidHandle;
  5708. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0) );
  5709. }
  5710. GL_CHECK(glDispatchCompute(compute.m_numX, compute.m_numY, compute.m_numZ) );
  5711. }
  5712. GL_CHECK(glMemoryBarrier(barrier) );
  5713. }
  5714. }
  5715. continue;
  5716. }
  5717. bool resetState = viewChanged || wasCompute;
  5718. if (wasCompute)
  5719. {
  5720. wasCompute = false;
  5721. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5722. {
  5723. char* viewName = s_viewName[view];
  5724. viewName[3] = ' ';
  5725. GL_CHECK(glInsertEventMarker(0, viewName) );
  5726. }
  5727. }
  5728. const RenderDraw& draw = renderItem.draw;
  5729. const bool hasOcclusionQuery = 0 != (draw.m_stateFlags & BGFX_STATE_INTERNAL_OCCLUSION_QUERY);
  5730. if (isValid(draw.m_occlusionQuery)
  5731. && !hasOcclusionQuery
  5732. && !isVisible(_render, draw.m_occlusionQuery, 0 != (draw.m_submitFlags&BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE) ) )
  5733. {
  5734. continue;
  5735. }
  5736. const uint64_t newFlags = draw.m_stateFlags;
  5737. uint64_t changedFlags = currentState.m_stateFlags ^ draw.m_stateFlags;
  5738. currentState.m_stateFlags = newFlags;
  5739. const uint64_t newStencil = draw.m_stencil;
  5740. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  5741. currentState.m_stencil = newStencil;
  5742. if (resetState)
  5743. {
  5744. currentState.clear();
  5745. currentState.m_scissor = !draw.m_scissor;
  5746. changedFlags = BGFX_STATE_MASK;
  5747. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  5748. currentState.m_stateFlags = newFlags;
  5749. currentState.m_stencil = newStencil;
  5750. }
  5751. uint16_t scissor = draw.m_scissor;
  5752. if (currentState.m_scissor != scissor)
  5753. {
  5754. currentState.m_scissor = scissor;
  5755. if (UINT16_MAX == scissor)
  5756. {
  5757. if (viewHasScissor)
  5758. {
  5759. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  5760. GL_CHECK(glScissor(viewScissorRect.m_x
  5761. , resolutionHeight-viewScissorRect.m_height-viewScissorRect.m_y
  5762. , viewScissorRect.m_width
  5763. , viewScissorRect.m_height
  5764. ) );
  5765. }
  5766. else
  5767. {
  5768. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  5769. }
  5770. }
  5771. else
  5772. {
  5773. Rect scissorRect;
  5774. scissorRect.setIntersect(viewScissorRect, _render->m_rectCache.m_cache[scissor]);
  5775. if (scissorRect.isZeroArea() )
  5776. {
  5777. continue;
  5778. }
  5779. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  5780. GL_CHECK(glScissor(scissorRect.m_x
  5781. , resolutionHeight-scissorRect.m_height-scissorRect.m_y
  5782. , scissorRect.m_width
  5783. , scissorRect.m_height
  5784. ) );
  5785. }
  5786. }
  5787. if (0 != changedStencil)
  5788. {
  5789. if (0 != newStencil)
  5790. {
  5791. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  5792. uint32_t bstencil = unpackStencil(1, newStencil);
  5793. uint8_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil);
  5794. // uint32_t bchanged = unpackStencil(1, changedStencil);
  5795. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  5796. // {
  5797. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  5798. // GL_CHECK(glStencilMask(wmask) );
  5799. // }
  5800. for (uint8_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  5801. {
  5802. uint32_t stencil = unpackStencil(ii, newStencil);
  5803. uint32_t changed = unpackStencil(ii, changedStencil);
  5804. GLenum face = s_stencilFace[frontAndBack+ii];
  5805. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  5806. {
  5807. GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  5808. GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  5809. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  5810. GL_CHECK(glStencilFuncSeparate(face, s_cmpFunc[func], ref, mask) );
  5811. }
  5812. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  5813. {
  5814. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  5815. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  5816. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  5817. GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) );
  5818. }
  5819. }
  5820. }
  5821. else
  5822. {
  5823. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  5824. }
  5825. }
  5826. if ( (0
  5827. | BGFX_STATE_CULL_MASK
  5828. | BGFX_STATE_DEPTH_WRITE
  5829. | BGFX_STATE_DEPTH_TEST_MASK
  5830. | BGFX_STATE_RGB_WRITE
  5831. | BGFX_STATE_ALPHA_WRITE
  5832. | BGFX_STATE_BLEND_MASK
  5833. | BGFX_STATE_BLEND_EQUATION_MASK
  5834. | BGFX_STATE_ALPHA_REF_MASK
  5835. | BGFX_STATE_PT_MASK
  5836. | BGFX_STATE_POINT_SIZE_MASK
  5837. | BGFX_STATE_MSAA
  5838. | BGFX_STATE_LINEAA
  5839. | BGFX_STATE_CONSERVATIVE_RASTER
  5840. ) & changedFlags)
  5841. {
  5842. if (BGFX_STATE_CULL_MASK & changedFlags)
  5843. {
  5844. if (BGFX_STATE_CULL_CW & newFlags)
  5845. {
  5846. GL_CHECK(glEnable(GL_CULL_FACE) );
  5847. GL_CHECK(glCullFace(GL_BACK) );
  5848. }
  5849. else if (BGFX_STATE_CULL_CCW & newFlags)
  5850. {
  5851. GL_CHECK(glEnable(GL_CULL_FACE) );
  5852. GL_CHECK(glCullFace(GL_FRONT) );
  5853. }
  5854. else
  5855. {
  5856. GL_CHECK(glDisable(GL_CULL_FACE) );
  5857. }
  5858. }
  5859. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  5860. {
  5861. GL_CHECK(glDepthMask(!!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  5862. }
  5863. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  5864. {
  5865. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  5866. if (0 != func)
  5867. {
  5868. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5869. GL_CHECK(glDepthFunc(s_cmpFunc[func]) );
  5870. }
  5871. else
  5872. {
  5873. if (BGFX_STATE_DEPTH_WRITE & newFlags)
  5874. {
  5875. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5876. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  5877. }
  5878. else
  5879. {
  5880. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  5881. }
  5882. }
  5883. }
  5884. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  5885. {
  5886. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  5887. viewState.m_alphaRef = ref/255.0f;
  5888. }
  5889. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  5890. {
  5891. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  5892. {
  5893. float pointSize = (float)(bx::uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  5894. GL_CHECK(glPointSize(pointSize) );
  5895. }
  5896. if (BGFX_STATE_MSAA & changedFlags)
  5897. {
  5898. GL_CHECK(BGFX_STATE_MSAA & newFlags
  5899. ? glEnable(GL_MULTISAMPLE)
  5900. : glDisable(GL_MULTISAMPLE)
  5901. );
  5902. }
  5903. if (BGFX_STATE_LINEAA & changedFlags)
  5904. {
  5905. GL_CHECK(BGFX_STATE_LINEAA & newFlags
  5906. ? glEnable(GL_LINE_SMOOTH)
  5907. : glDisable(GL_LINE_SMOOTH)
  5908. );
  5909. }
  5910. if (m_conservativeRasterSupport
  5911. && BGFX_STATE_CONSERVATIVE_RASTER & changedFlags)
  5912. {
  5913. GL_CHECK(BGFX_STATE_CONSERVATIVE_RASTER & newFlags
  5914. ? glEnable(GL_CONSERVATIVE_RASTERIZATION_NV)
  5915. : glDisable(GL_CONSERVATIVE_RASTERIZATION_NV)
  5916. );
  5917. }
  5918. }
  5919. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  5920. {
  5921. GLboolean alpha = !!(newFlags&BGFX_STATE_ALPHA_WRITE);
  5922. GLboolean rgb = !!(newFlags&BGFX_STATE_RGB_WRITE);
  5923. GL_CHECK(glColorMask(rgb, rgb, rgb, alpha) );
  5924. }
  5925. if ( ( (0
  5926. | BGFX_STATE_BLEND_MASK
  5927. | BGFX_STATE_BLEND_EQUATION_MASK
  5928. | BGFX_STATE_BLEND_INDEPENDENT
  5929. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  5930. ) & changedFlags)
  5931. || blendFactor != draw.m_rgba)
  5932. {
  5933. if (m_atocSupport)
  5934. {
  5935. if (BGFX_STATE_BLEND_ALPHA_TO_COVERAGE & newFlags)
  5936. {
  5937. GL_CHECK(glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) );
  5938. }
  5939. else
  5940. {
  5941. GL_CHECK(glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE) );
  5942. }
  5943. }
  5944. if ( ( (0
  5945. | BGFX_STATE_BLEND_MASK
  5946. | BGFX_STATE_BLEND_EQUATION_MASK
  5947. | BGFX_STATE_BLEND_INDEPENDENT) & newFlags)
  5948. || blendFactor != draw.m_rgba)
  5949. {
  5950. const bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  5951. const bool independent = !!(BGFX_STATE_BLEND_INDEPENDENT & newFlags)
  5952. && blendIndependentSupported
  5953. ;
  5954. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  5955. const uint32_t srcRGB = (blend )&0xf;
  5956. const uint32_t dstRGB = (blend>> 4)&0xf;
  5957. const uint32_t srcA = (blend>> 8)&0xf;
  5958. const uint32_t dstA = (blend>>12)&0xf;
  5959. const uint32_t equ = uint32_t( (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  5960. const uint32_t equRGB = (equ )&0x7;
  5961. const uint32_t equA = (equ>>3)&0x7;
  5962. const uint32_t numRt = getNumRt();
  5963. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  5964. || 1 >= numRt
  5965. || !independent)
  5966. {
  5967. if (enabled)
  5968. {
  5969. GL_CHECK(glEnable(GL_BLEND) );
  5970. GL_CHECK(glBlendFuncSeparate(s_blendFactor[srcRGB].m_src
  5971. , s_blendFactor[dstRGB].m_dst
  5972. , s_blendFactor[srcA].m_src
  5973. , s_blendFactor[dstA].m_dst
  5974. ) );
  5975. GL_CHECK(glBlendEquationSeparate(s_blendEquation[equRGB], s_blendEquation[equA]) );
  5976. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  5977. && blendFactor != draw.m_rgba)
  5978. {
  5979. const uint32_t rgba = draw.m_rgba;
  5980. GLclampf rr = ( (rgba>>24) )/255.0f;
  5981. GLclampf gg = ( (rgba>>16)&0xff)/255.0f;
  5982. GLclampf bb = ( (rgba>> 8)&0xff)/255.0f;
  5983. GLclampf aa = ( (rgba )&0xff)/255.0f;
  5984. GL_CHECK(glBlendColor(rr, gg, bb, aa) );
  5985. }
  5986. }
  5987. else
  5988. {
  5989. GL_CHECK(glDisable(GL_BLEND) );
  5990. }
  5991. }
  5992. else
  5993. {
  5994. if (enabled)
  5995. {
  5996. GL_CHECK(glEnablei(GL_BLEND, 0) );
  5997. GL_CHECK(glBlendFuncSeparatei(0
  5998. , s_blendFactor[srcRGB].m_src
  5999. , s_blendFactor[dstRGB].m_dst
  6000. , s_blendFactor[srcA].m_src
  6001. , s_blendFactor[dstA].m_dst
  6002. ) );
  6003. GL_CHECK(glBlendEquationSeparatei(0
  6004. , s_blendEquation[equRGB]
  6005. , s_blendEquation[equA]
  6006. ) );
  6007. }
  6008. else
  6009. {
  6010. GL_CHECK(glDisablei(GL_BLEND, 0) );
  6011. }
  6012. for (uint32_t ii = 1, rgba = draw.m_rgba; ii < numRt; ++ii, rgba >>= 11)
  6013. {
  6014. if (0 != (rgba&0x7ff) )
  6015. {
  6016. const uint32_t src = (rgba )&0xf;
  6017. const uint32_t dst = (rgba>>4)&0xf;
  6018. const uint32_t equation = (rgba>>8)&0x7;
  6019. GL_CHECK(glEnablei(GL_BLEND, ii) );
  6020. GL_CHECK(glBlendFunci(ii, s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) );
  6021. GL_CHECK(glBlendEquationi(ii, s_blendEquation[equation]) );
  6022. }
  6023. else
  6024. {
  6025. GL_CHECK(glDisablei(GL_BLEND, ii) );
  6026. }
  6027. }
  6028. }
  6029. }
  6030. else
  6031. {
  6032. GL_CHECK(glDisable(GL_BLEND) );
  6033. }
  6034. blendFactor = draw.m_rgba;
  6035. }
  6036. const uint64_t pt = newFlags&BGFX_STATE_PT_MASK;
  6037. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  6038. prim = s_primInfo[primIndex];
  6039. }
  6040. bool programChanged = false;
  6041. bool constantsChanged = draw.m_constBegin < draw.m_constEnd;
  6042. bool bindAttribs = false;
  6043. rendererUpdateUniforms(this, _render->m_uniformBuffer, draw.m_constBegin, draw.m_constEnd);
  6044. if (key.m_program != programIdx)
  6045. {
  6046. programIdx = key.m_program;
  6047. GLuint id = invalidHandle == programIdx ? 0 : m_program[programIdx].m_id;
  6048. // Skip rendering if program index is valid, but program is invalid.
  6049. programIdx = 0 == id ? invalidHandle : programIdx;
  6050. GL_CHECK(glUseProgram(id) );
  6051. programChanged =
  6052. constantsChanged =
  6053. bindAttribs = true;
  6054. }
  6055. if (invalidHandle != programIdx)
  6056. {
  6057. ProgramGL& program = m_program[programIdx];
  6058. if (constantsChanged
  6059. && NULL != program.m_constantBuffer)
  6060. {
  6061. commit(*program.m_constantBuffer);
  6062. }
  6063. viewState.setPredefined<1>(this, view, eye, program, _render, draw);
  6064. {
  6065. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  6066. {
  6067. const Binding& bind = draw.m_bind[stage];
  6068. Binding& current = currentState.m_bind[stage];
  6069. if (current.m_idx != bind.m_idx
  6070. || current.m_un.m_draw.m_textureFlags != bind.m_un.m_draw.m_textureFlags
  6071. || programChanged)
  6072. {
  6073. if (invalidHandle != bind.m_idx)
  6074. {
  6075. TextureGL& texture = m_textures[bind.m_idx];
  6076. texture.commit(stage, bind.m_un.m_draw.m_textureFlags, _render->m_colorPalette);
  6077. }
  6078. }
  6079. current = bind;
  6080. }
  6081. }
  6082. if (0 != defaultVao
  6083. && 0 == draw.m_stream[0].m_startVertex
  6084. && 0 == draw.m_instanceDataOffset)
  6085. {
  6086. bool diffStartVertex = false;
  6087. bool diffStreamHandles = false;
  6088. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6089. ; 0 != streamMask
  6090. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6091. )
  6092. {
  6093. streamMask >>= ntz;
  6094. idx += ntz;
  6095. if (currentState.m_stream[idx].m_handle.idx != draw.m_stream[idx].m_handle.idx)
  6096. {
  6097. diffStreamHandles = true;
  6098. break;
  6099. }
  6100. if (currentState.m_stream[idx].m_startVertex != draw.m_stream[idx].m_startVertex)
  6101. {
  6102. diffStartVertex = true;
  6103. break;
  6104. }
  6105. }
  6106. if (programChanged
  6107. || currentState.m_streamMask != draw.m_streamMask
  6108. || currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx
  6109. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  6110. || currentState.m_instanceDataStride != draw.m_instanceDataStride
  6111. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  6112. || diffStartVertex
  6113. || diffStreamHandles)
  6114. {
  6115. bx::HashMurmur2A murmur;
  6116. murmur.begin();
  6117. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6118. ; 0 != streamMask
  6119. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6120. )
  6121. {
  6122. streamMask >>= ntz;
  6123. idx += ntz;
  6124. const Stream& stream = draw.m_stream[idx];
  6125. murmur.add(stream.m_handle.idx);
  6126. if (isValid(stream.m_handle) )
  6127. {
  6128. const VertexBufferGL& vb = m_vertexBuffers[stream.m_handle.idx];
  6129. uint16_t decl = !isValid(vb.m_decl) ? stream.m_decl.idx : vb.m_decl.idx;
  6130. murmur.add(decl);
  6131. }
  6132. currentState.m_stream[idx].m_handle = stream.m_handle;
  6133. currentState.m_stream[idx].m_startVertex = stream.m_startVertex;
  6134. }
  6135. currentState.m_streamMask = draw.m_streamMask;
  6136. murmur.add(draw.m_indexBuffer.idx);
  6137. murmur.add(draw.m_instanceDataBuffer.idx);
  6138. murmur.add(draw.m_instanceDataOffset);
  6139. murmur.add(draw.m_instanceDataStride);
  6140. murmur.add(programIdx);
  6141. uint32_t hash = murmur.end();
  6142. currentState.m_indexBuffer = draw.m_indexBuffer;
  6143. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  6144. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  6145. GLuint id = m_vaoStateCache.find(hash);
  6146. if (UINT32_MAX != id)
  6147. {
  6148. currentVao = id;
  6149. GL_CHECK(glBindVertexArray(id) );
  6150. }
  6151. else
  6152. {
  6153. id = m_vaoStateCache.add(hash);
  6154. currentVao = id;
  6155. GL_CHECK(glBindVertexArray(id) );
  6156. program.add(hash);
  6157. program.bindAttributesBegin();
  6158. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6159. ; 0 != streamMask
  6160. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6161. )
  6162. {
  6163. streamMask >>= ntz;
  6164. idx += ntz;
  6165. const Stream& stream = draw.m_stream[idx];
  6166. if (isValid(stream.m_handle) )
  6167. {
  6168. VertexBufferGL& vb = m_vertexBuffers[stream.m_handle.idx];
  6169. vb.add(hash);
  6170. uint16_t decl = !isValid(vb.m_decl) ? stream.m_decl.idx : vb.m_decl.idx;
  6171. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  6172. program.bindAttributes(m_vertexDecls[decl], stream.m_startVertex);
  6173. }
  6174. if (isValid(draw.m_instanceDataBuffer) )
  6175. {
  6176. VertexBufferGL& instanceVb = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  6177. instanceVb.add(hash);
  6178. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, instanceVb.m_id) );
  6179. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  6180. }
  6181. }
  6182. program.bindAttributesEnd();
  6183. if (isValid(draw.m_indexBuffer) )
  6184. {
  6185. IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  6186. ib.add(hash);
  6187. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  6188. }
  6189. else
  6190. {
  6191. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  6192. }
  6193. }
  6194. }
  6195. }
  6196. else
  6197. {
  6198. if (0 != defaultVao
  6199. && 0 != currentVao)
  6200. {
  6201. GL_CHECK(glBindVertexArray(defaultVao) );
  6202. currentState.m_streamMask = 0;
  6203. for (size_t ii = 0; ii < BGFX_CONFIG_MAX_VERTEX_STREAMS; ++ii)
  6204. {
  6205. currentState.m_stream[ii].m_handle.idx = invalidHandle;
  6206. }
  6207. currentState.m_indexBuffer.idx = invalidHandle;
  6208. bindAttribs = true;
  6209. currentVao = 0;
  6210. }
  6211. bool diffStreamHandles = false;
  6212. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6213. ; 0 != streamMask
  6214. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6215. )
  6216. {
  6217. streamMask >>= ntz;
  6218. idx += ntz;
  6219. if (currentState.m_stream[idx].m_handle.idx != draw.m_stream[idx].m_handle.idx)
  6220. {
  6221. diffStreamHandles = true;
  6222. break;
  6223. }
  6224. }
  6225. if (programChanged
  6226. || currentState.m_streamMask != draw.m_streamMask
  6227. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  6228. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  6229. || currentState.m_instanceDataStride != draw.m_instanceDataStride
  6230. || diffStreamHandles)
  6231. {
  6232. currentState.m_streamMask = draw.m_streamMask;
  6233. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  6234. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  6235. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  6236. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6237. ; 0 != streamMask
  6238. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6239. )
  6240. {
  6241. streamMask >>= ntz;
  6242. idx += ntz;
  6243. uint16_t handle = draw.m_stream[idx].m_handle.idx;
  6244. if (invalidHandle != handle)
  6245. {
  6246. VertexBufferGL& vb = m_vertexBuffers[handle];
  6247. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  6248. bindAttribs = true;
  6249. }
  6250. else
  6251. {
  6252. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  6253. }
  6254. }
  6255. }
  6256. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  6257. {
  6258. currentState.m_indexBuffer = draw.m_indexBuffer;
  6259. uint16_t handle = draw.m_indexBuffer.idx;
  6260. if (invalidHandle != handle)
  6261. {
  6262. IndexBufferGL& ib = m_indexBuffers[handle];
  6263. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  6264. }
  6265. else
  6266. {
  6267. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  6268. }
  6269. }
  6270. if (0 != currentState.m_streamMask)
  6271. {
  6272. bool diffStartVertex = false;
  6273. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6274. ; 0 != streamMask
  6275. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6276. )
  6277. {
  6278. streamMask >>= ntz;
  6279. idx += ntz;
  6280. if (currentState.m_stream[idx].m_startVertex != draw.m_stream[idx].m_startVertex)
  6281. {
  6282. diffStartVertex = true;
  6283. break;
  6284. }
  6285. }
  6286. if (bindAttribs || diffStartVertex)
  6287. {
  6288. program.bindAttributesBegin();
  6289. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6290. ; 0 != streamMask
  6291. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6292. )
  6293. {
  6294. streamMask >>= ntz;
  6295. idx += ntz;
  6296. const VertexBufferGL& vb = m_vertexBuffers[draw.m_stream[idx].m_handle.idx];
  6297. uint16_t decl = !isValid(vb.m_decl) ? draw.m_stream[idx].m_decl.idx : vb.m_decl.idx;
  6298. program.bindAttributes(m_vertexDecls[decl], draw.m_stream[idx].m_startVertex);
  6299. }
  6300. program.bindAttributesEnd();
  6301. if (isValid(draw.m_instanceDataBuffer) )
  6302. {
  6303. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffers[draw.m_instanceDataBuffer.idx].m_id) );
  6304. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  6305. }
  6306. }
  6307. }
  6308. }
  6309. if (0 != currentState.m_streamMask)
  6310. {
  6311. uint32_t numVertices = draw.m_numVertices;
  6312. if (UINT32_MAX == numVertices)
  6313. {
  6314. for (uint32_t idx = 0, streamMask = draw.m_streamMask, ntz = bx::uint32_cnttz(streamMask)
  6315. ; 0 != streamMask
  6316. ; streamMask >>= 1, idx += 1, ntz = bx::uint32_cnttz(streamMask)
  6317. )
  6318. {
  6319. streamMask >>= ntz;
  6320. idx += ntz;
  6321. const VertexBufferGL& vb = m_vertexBuffers[draw.m_stream[idx].m_handle.idx];
  6322. uint16_t decl = !isValid(vb.m_decl) ? draw.m_stream[idx].m_decl.idx : vb.m_decl.idx;
  6323. const VertexDecl& vertexDecl = m_vertexDecls[decl];
  6324. numVertices = bx::uint32_min(numVertices, vb.m_size/vertexDecl.m_stride);
  6325. }
  6326. }
  6327. uint32_t numIndices = 0;
  6328. uint32_t numPrimsSubmitted = 0;
  6329. uint32_t numInstances = 0;
  6330. uint32_t numPrimsRendered = 0;
  6331. uint32_t numDrawIndirect = 0;
  6332. if (hasOcclusionQuery)
  6333. {
  6334. m_occlusionQuery.begin(_render, draw.m_occlusionQuery);
  6335. }
  6336. if (isValid(draw.m_indirectBuffer) )
  6337. {
  6338. const VertexBufferGL& vb = m_vertexBuffers[draw.m_indirectBuffer.idx];
  6339. if (currentState.m_indirectBuffer.idx != draw.m_indirectBuffer.idx)
  6340. {
  6341. currentState.m_indirectBuffer = draw.m_indirectBuffer;
  6342. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, vb.m_id) );
  6343. }
  6344. if (isValid(draw.m_indexBuffer) )
  6345. {
  6346. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  6347. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  6348. const GLenum indexFormat = hasIndex16
  6349. ? GL_UNSIGNED_SHORT
  6350. : GL_UNSIGNED_INT
  6351. ;
  6352. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  6353. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6354. : draw.m_numIndirect
  6355. ;
  6356. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  6357. GL_CHECK(glMultiDrawElementsIndirect(prim.m_type, indexFormat
  6358. , (void*)args
  6359. , numDrawIndirect
  6360. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6361. ) );
  6362. }
  6363. else
  6364. {
  6365. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  6366. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6367. : draw.m_numIndirect
  6368. ;
  6369. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  6370. GL_CHECK(glMultiDrawArraysIndirect(prim.m_type
  6371. , (void*)args
  6372. , numDrawIndirect
  6373. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6374. ) );
  6375. }
  6376. }
  6377. else
  6378. {
  6379. if (isValid(currentState.m_indirectBuffer) )
  6380. {
  6381. currentState.m_indirectBuffer.idx = invalidHandle;
  6382. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0) );
  6383. }
  6384. if (isValid(draw.m_indexBuffer) )
  6385. {
  6386. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  6387. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  6388. const uint32_t indexSize = hasIndex16 ? 2 : 4;
  6389. const GLenum indexFormat = hasIndex16
  6390. ? GL_UNSIGNED_SHORT
  6391. : GL_UNSIGNED_INT
  6392. ;
  6393. if (UINT32_MAX == draw.m_numIndices)
  6394. {
  6395. numIndices = ib.m_size/indexSize;
  6396. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  6397. numInstances = draw.m_numInstances;
  6398. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  6399. GL_CHECK(glDrawElementsInstanced(prim.m_type
  6400. , numIndices
  6401. , indexFormat
  6402. , (void*)0
  6403. , draw.m_numInstances
  6404. ) );
  6405. }
  6406. else if (prim.m_min <= draw.m_numIndices)
  6407. {
  6408. numIndices = draw.m_numIndices;
  6409. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  6410. numInstances = draw.m_numInstances;
  6411. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  6412. GL_CHECK(glDrawElementsInstanced(prim.m_type
  6413. , numIndices
  6414. , indexFormat
  6415. , (void*)(uintptr_t)(draw.m_startIndex*indexSize)
  6416. , draw.m_numInstances
  6417. ) );
  6418. }
  6419. }
  6420. else
  6421. {
  6422. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  6423. numInstances = draw.m_numInstances;
  6424. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  6425. GL_CHECK(glDrawArraysInstanced(prim.m_type
  6426. , 0
  6427. , numVertices
  6428. , draw.m_numInstances
  6429. ) );
  6430. }
  6431. }
  6432. if (hasOcclusionQuery)
  6433. {
  6434. m_occlusionQuery.end();
  6435. }
  6436. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  6437. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  6438. statsNumInstances[primIndex] += numInstances;
  6439. statsNumIndices += numIndices;
  6440. }
  6441. }
  6442. }
  6443. blitMsaaFbo();
  6444. if (m_vaoSupport)
  6445. {
  6446. GL_CHECK(glBindVertexArray(m_vao) );
  6447. }
  6448. if (0 < _render->m_num)
  6449. {
  6450. if (0 != (m_resolution.m_flags & BGFX_RESET_FLUSH_AFTER_RENDER) )
  6451. {
  6452. GL_CHECK(glFlush() );
  6453. }
  6454. captureElapsed = -bx::getHPCounter();
  6455. capture();
  6456. captureElapsed += bx::getHPCounter();
  6457. BGFX_GPU_PROFILER_END();
  6458. BGFX_PROFILER_END();
  6459. }
  6460. }
  6461. BGFX_GPU_PROFILER_END();
  6462. m_glctx.makeCurrent(NULL);
  6463. int64_t now = bx::getHPCounter();
  6464. elapsed += now;
  6465. static int64_t last = now;
  6466. Stats& perfStats = _render->m_perfStats;
  6467. perfStats.cpuTimeBegin = last;
  6468. int64_t frameTime = now - last;
  6469. last = now;
  6470. static int64_t min = frameTime;
  6471. static int64_t max = frameTime;
  6472. min = min > frameTime ? frameTime : min;
  6473. max = max < frameTime ? frameTime : max;
  6474. static uint32_t maxGpuLatency = 0;
  6475. static double maxGpuElapsed = 0.0f;
  6476. double elapsedGpuMs = 0.0;
  6477. uint64_t elapsedGl = 0;
  6478. if (m_timerQuerySupport)
  6479. {
  6480. m_gpuTimer.end();
  6481. do
  6482. {
  6483. elapsedGl = m_gpuTimer.m_elapsed;
  6484. elapsedGpuMs = double(elapsedGl)/1e6;
  6485. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  6486. }
  6487. while (m_gpuTimer.get() );
  6488. maxGpuLatency = bx::uint32_imax(maxGpuLatency, m_gpuTimer.m_control.available()-1);
  6489. }
  6490. const int64_t timerFreq = bx::getHPFrequency();
  6491. perfStats.cpuTimeEnd = now;
  6492. perfStats.cpuTimerFreq = timerFreq;
  6493. perfStats.gpuTimeBegin = m_gpuTimer.m_begin;
  6494. perfStats.gpuTimeEnd = m_gpuTimer.m_end;
  6495. perfStats.gpuTimerFreq = 1000000000;
  6496. perfStats.numDraw = statsKeyType[0];
  6497. perfStats.numCompute = statsKeyType[1];
  6498. perfStats.maxGpuLatency = maxGpuLatency;
  6499. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  6500. {
  6501. m_needPresent = true;
  6502. TextVideoMem& tvm = m_textVideoMem;
  6503. static int64_t next = now;
  6504. if (now >= next)
  6505. {
  6506. next = now + timerFreq;
  6507. double freq = double(timerFreq);
  6508. double toMs = 1000.0/freq;
  6509. tvm.clear();
  6510. uint16_t pos = 0;
  6511. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  6512. , getRendererName()
  6513. );
  6514. tvm.printf(0, pos++, 0x8f, " Vendor: %s ", m_vendor);
  6515. tvm.printf(0, pos++, 0x8f, " Renderer: %s ", m_renderer);
  6516. tvm.printf(0, pos++, 0x8f, " Version: %s ", m_version);
  6517. tvm.printf(0, pos++, 0x8f, " GLSL version: %s ", m_glslVersion);
  6518. char processMemoryUsed[16];
  6519. bx::prettify(processMemoryUsed, BX_COUNTOF(processMemoryUsed), bx::getProcessMemoryUsed() );
  6520. tvm.printf(0, pos++, 0x8f, " Memory: %s (process) ", processMemoryUsed);
  6521. pos = 10;
  6522. tvm.printf(10, pos++, 0x8e, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  6523. , double(frameTime)*toMs
  6524. , double(min)*toMs
  6525. , double(max)*toMs
  6526. , freq/frameTime
  6527. );
  6528. char hmd[16];
  6529. bx::snprintf(hmd, BX_COUNTOF(hmd), ", [%c] HMD ", hmdEnabled ? '\xfe' : ' ');
  6530. const uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  6531. tvm.printf(10, pos++, 0x8e, " Reset flags: [%c] vsync, [%c] MSAAx%d%s, [%c] MaxAnisotropy "
  6532. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  6533. , 0 != msaa ? '\xfe' : ' '
  6534. , 1<<msaa
  6535. , m_ovr.isInitialized() ? hmd : ", no-HMD "
  6536. , !!(m_resolution.m_flags&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  6537. );
  6538. double elapsedCpuMs = double(elapsed)*toMs;
  6539. tvm.printf(10, pos++, 0x8e, " Submitted: %5d (draw %5d, compute %4d) / CPU %7.4f [ms] %c GPU %7.4f [ms] (latency %d) "
  6540. , _render->m_num
  6541. , statsKeyType[0]
  6542. , statsKeyType[1]
  6543. , elapsedCpuMs
  6544. , elapsedCpuMs > elapsedGpuMs ? '>' : '<'
  6545. , maxGpuElapsed
  6546. , maxGpuLatency
  6547. );
  6548. maxGpuLatency = 0;
  6549. maxGpuElapsed = 0.0;
  6550. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primInfo); ++ii)
  6551. {
  6552. tvm.printf(10, pos++, 0x8e, " %10s: %7d (#inst: %5d), submitted: %7d "
  6553. , s_primName[ii]
  6554. , statsNumPrimsRendered[ii]
  6555. , statsNumInstances[ii]
  6556. , statsNumPrimsSubmitted[ii]
  6557. );
  6558. }
  6559. if (NULL != m_renderdocdll)
  6560. {
  6561. tvm.printf(tvm.m_width-27, 0, 0x1f, " [F11 - RenderDoc capture] ");
  6562. }
  6563. tvm.printf(10, pos++, 0x8e, " Indices: %7d ", statsNumIndices);
  6564. tvm.printf(10, pos++, 0x8e, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax);
  6565. tvm.printf(10, pos++, 0x8e, " DVB size: %7d ", _render->m_vboffset);
  6566. tvm.printf(10, pos++, 0x8e, " DIB size: %7d ", _render->m_iboffset);
  6567. pos++;
  6568. tvm.printf(10, pos++, 0x8e, " State cache: ");
  6569. tvm.printf(10, pos++, 0x8e, " VAO | Sampler ");
  6570. tvm.printf(10, pos++, 0x8e, " %6d | %6d "
  6571. , m_vaoStateCache.getCount()
  6572. , m_samplerStateCache.getCount()
  6573. );
  6574. #if BGFX_CONFIG_RENDERER_OPENGL
  6575. if (s_extension[Extension::ATI_meminfo].m_supported)
  6576. {
  6577. GLint vboFree[4];
  6578. GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) );
  6579. GLint texFree[4];
  6580. GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) );
  6581. GLint rbfFree[4];
  6582. GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) );
  6583. pos++;
  6584. tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb ");
  6585. char tmp0[16];
  6586. char tmp1[16];
  6587. char tmp2[16];
  6588. char tmp3[16];
  6589. bx::prettify(tmp0, BX_COUNTOF(tmp0), vboFree[0]);
  6590. bx::prettify(tmp1, BX_COUNTOF(tmp1), vboFree[1]);
  6591. bx::prettify(tmp2, BX_COUNTOF(tmp2), vboFree[2]);
  6592. bx::prettify(tmp3, BX_COUNTOF(tmp3), vboFree[3]);
  6593. tvm.printf(10, pos++, 0x8e, " VBO: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  6594. bx::prettify(tmp0, BX_COUNTOF(tmp0), texFree[0]);
  6595. bx::prettify(tmp1, BX_COUNTOF(tmp1), texFree[1]);
  6596. bx::prettify(tmp2, BX_COUNTOF(tmp2), texFree[2]);
  6597. bx::prettify(tmp3, BX_COUNTOF(tmp3), texFree[3]);
  6598. tvm.printf(10, pos++, 0x8e, " Texture: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  6599. bx::prettify(tmp0, BX_COUNTOF(tmp0), rbfFree[0]);
  6600. bx::prettify(tmp1, BX_COUNTOF(tmp1), rbfFree[1]);
  6601. bx::prettify(tmp2, BX_COUNTOF(tmp2), rbfFree[2]);
  6602. bx::prettify(tmp3, BX_COUNTOF(tmp3), rbfFree[3]);
  6603. tvm.printf(10, pos++, 0x8e, " Render Buffer: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  6604. }
  6605. else if (s_extension[Extension::NVX_gpu_memory_info].m_supported)
  6606. {
  6607. GLint dedicated;
  6608. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) );
  6609. GLint totalAvail;
  6610. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) );
  6611. GLint currAvail;
  6612. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) );
  6613. GLint evictedCount;
  6614. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) );
  6615. GLint evictedMemory;
  6616. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) );
  6617. pos++;
  6618. char tmp0[16];
  6619. char tmp1[16];
  6620. bx::prettify(tmp0, BX_COUNTOF(tmp0), dedicated);
  6621. tvm.printf(10, pos++, 0x8e, " Dedicated: %10s ", tmp0);
  6622. bx::prettify(tmp0, BX_COUNTOF(tmp0), currAvail);
  6623. bx::prettify(tmp1, BX_COUNTOF(tmp1), totalAvail);
  6624. tvm.printf(10, pos++, 0x8e, " Available: %10s / %10s ", tmp0, tmp1);
  6625. bx::prettify(tmp0, BX_COUNTOF(tmp0), evictedCount);
  6626. bx::prettify(tmp1, BX_COUNTOF(tmp1), evictedMemory);
  6627. tvm.printf(10, pos++, 0x8e, " Eviction: %10s / %10s ", tmp0, tmp1);
  6628. }
  6629. #endif // BGFX_CONFIG_RENDERER_OPENGL
  6630. pos++;
  6631. double captureMs = double(captureElapsed)*toMs;
  6632. tvm.printf(10, pos++, 0x8e, " Capture: %7.4f [ms] ", captureMs);
  6633. uint8_t attr[2] = { 0x89, 0x8a };
  6634. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  6635. tvm.printf(10, pos++, attr[attrIndex&1], " Submit wait: %7.4f [ms] ", double(_render->m_waitSubmit)*toMs);
  6636. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %7.4f [ms] ", double(_render->m_waitRender)*toMs);
  6637. min = frameTime;
  6638. max = frameTime;
  6639. }
  6640. blit(this, _textVideoMemBlitter, tvm);
  6641. }
  6642. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  6643. {
  6644. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  6645. }
  6646. GL_CHECK(glFrameTerminatorGREMEDY() );
  6647. }
  6648. } } // namespace bgfx
  6649. #undef BGFX_GPU_PROFILER_BIND
  6650. #undef BGFX_GPU_PROFILER_UNBIND
  6651. #undef BGFX_GPU_PROFILER_BEGIN
  6652. #undef BGFX_GPU_PROFILER_BEGIN_DYNAMIC
  6653. #undef BGFX_GPU_PROFILER_END
  6654. #else
  6655. namespace bgfx { namespace gl
  6656. {
  6657. RendererContextI* rendererCreate()
  6658. {
  6659. return NULL;
  6660. }
  6661. void rendererDestroy()
  6662. {
  6663. }
  6664. } /* namespace gl */ } // namespace bgfx
  6665. #endif // (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)