renderer_gl.cpp 230 KB

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