renderer_gl.cpp 234 KB

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