renderer_gl.cpp 199 KB

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