sokol_gfx.h 874 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043
  1. #if defined(SOKOL_IMPL) && !defined(SOKOL_GFX_IMPL)
  2. #define SOKOL_GFX_IMPL
  3. #endif
  4. #ifndef SOKOL_GFX_INCLUDED
  5. /*
  6. sokol_gfx.h -- simple 3D API wrapper
  7. Project URL: https://github.com/floooh/sokol
  8. Example code: https://github.com/floooh/sokol-samples
  9. Do this:
  10. #define SOKOL_IMPL or
  11. #define SOKOL_GFX_IMPL
  12. before you include this file in *one* C or C++ file to create the
  13. implementation.
  14. In the same place define one of the following to select the rendering
  15. backend:
  16. #define SOKOL_GLCORE
  17. #define SOKOL_GLES3
  18. #define SOKOL_D3D11
  19. #define SOKOL_METAL
  20. #define SOKOL_WGPU
  21. #define SOKOL_DUMMY_BACKEND
  22. I.e. for the desktop GL it should look like this:
  23. #include ...
  24. #include ...
  25. #define SOKOL_IMPL
  26. #define SOKOL_GLCORE
  27. #include "sokol_gfx.h"
  28. The dummy backend replaces the platform-specific backend code with empty
  29. stub functions. This is useful for writing tests that need to run on the
  30. command line.
  31. Optionally provide the following defines with your own implementations:
  32. SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
  33. SOKOL_UNREACHABLE() - a guard macro for unreachable code (default: assert(false))
  34. SOKOL_GFX_API_DECL - public function declaration prefix (default: extern)
  35. SOKOL_API_DECL - same as SOKOL_GFX_API_DECL
  36. SOKOL_API_IMPL - public function implementation prefix (default: -)
  37. SOKOL_TRACE_HOOKS - enable trace hook callbacks (search below for TRACE HOOKS)
  38. SOKOL_EXTERNAL_GL_LOADER - indicates that you're using your own GL loader, in this case
  39. sokol_gfx.h will not include any platform GL headers and disable
  40. the integrated Win32 GL loader
  41. If sokol_gfx.h is compiled as a DLL, define the following before
  42. including the declaration or implementation:
  43. SOKOL_DLL
  44. On Windows, SOKOL_DLL will define SOKOL_GFX_API_DECL as __declspec(dllexport)
  45. or __declspec(dllimport) as needed.
  46. If you want to compile without deprecated structs and functions,
  47. define:
  48. SOKOL_NO_DEPRECATED
  49. Optionally define the following to force debug checks and validations
  50. even in release mode:
  51. SOKOL_DEBUG - by default this is defined if _DEBUG is defined
  52. sokol_gfx DOES NOT:
  53. ===================
  54. - create a window, swapchain or the 3D-API context/device, you must do this
  55. before sokol_gfx is initialized, and pass any required information
  56. (like 3D device pointers) to the sokol_gfx initialization call
  57. - present the rendered frame, how this is done exactly usually depends
  58. on how the window and 3D-API context/device was created
  59. - provide a unified shader language, instead 3D-API-specific shader
  60. source-code or shader-bytecode must be provided (for the "official"
  61. offline shader cross-compiler / code-generator, see here:
  62. https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md)
  63. STEP BY STEP
  64. ============
  65. --- to initialize sokol_gfx, after creating a window and a 3D-API
  66. context/device, call:
  67. sg_setup(const sg_desc*)
  68. Depending on the selected 3D backend, sokol-gfx requires some
  69. information, like a device pointer, default swapchain pixel formats
  70. and so on. If you are using sokol_app.h for the window system
  71. glue, you can use a helper function provided in the sokol_glue.h
  72. header:
  73. #include "sokol_gfx.h"
  74. #include "sokol_app.h"
  75. #include "sokol_glue.h"
  76. //...
  77. sg_setup(&(sg_desc){
  78. .environment = sglue_environment(),
  79. });
  80. To get any logging output for errors and from the validation layer, you
  81. need to provide a logging callback. Easiest way is through sokol_log.h:
  82. #include "sokol_log.h"
  83. //...
  84. sg_setup(&(sg_desc){
  85. //...
  86. .logger.func = slog_func,
  87. });
  88. --- create resource objects (at least buffers, shaders and pipelines,
  89. and optionally images, samplers and render-pass-attachments):
  90. sg_buffer sg_make_buffer(const sg_buffer_desc*)
  91. sg_image sg_make_image(const sg_image_desc*)
  92. sg_sampler sg_make_sampler(const sg_sampler_desc*)
  93. sg_shader sg_make_shader(const sg_shader_desc*)
  94. sg_pipeline sg_make_pipeline(const sg_pipeline_desc*)
  95. sg_attachments sg_make_attachments(const sg_attachments_desc*)
  96. --- start a render pass:
  97. sg_begin_pass(const sg_pass* pass);
  98. Typically, passes render into an externally provided swapchain which
  99. presents the rendering result on the display. Such a 'swapchain pass'
  100. is started like this:
  101. sg_begin_pass(&(sg_pass){ .action = { ... }, .swapchain = sglue_swapchain() })
  102. ...where .action is an sg_pass_action struct containing actions to be performed
  103. at the start and end of a render pass (such as clearing the render surfaces to
  104. a specific color), and .swapchain is an sg_swapchain
  105. struct all the required information to render into the swapchain's surfaces.
  106. To start an 'offscreen pass' into sokol-gfx image objects, an sg_attachment
  107. object handle is required instead of an sg_swapchain struct. An offscreen
  108. pass is started like this (assuming attachments is an sg_attachments handle):
  109. sg_begin_pass(&(sg_pass){ .action = { ... }, .attachments = attachments });
  110. --- set the render pipeline state for the next draw call with:
  111. sg_apply_pipeline(sg_pipeline pip)
  112. --- fill an sg_bindings struct with the resource bindings for the next
  113. draw call (0..N vertex buffers, 0 or 1 index buffer, 0..N images,
  114. samplers and storage-buffers), and call:
  115. sg_apply_bindings(const sg_bindings* bindings)
  116. to update the resource bindings
  117. --- optionally update shader uniform data with:
  118. sg_apply_uniforms(int ub_slot, const sg_range* data)
  119. Read the section 'UNIFORM DATA LAYOUT' to learn about the expected memory layout
  120. of the uniform data passed into sg_apply_uniforms().
  121. --- kick off a draw call with:
  122. sg_draw(int base_element, int num_elements, int num_instances)
  123. The sg_draw() function unifies all the different ways to render primitives
  124. in a single call (indexed vs non-indexed rendering, and instanced vs non-instanced
  125. rendering). In case of indexed rendering, base_element and num_element specify
  126. indices in the currently bound index buffer. In case of non-indexed rendering
  127. base_element and num_elements specify vertices in the currently bound
  128. vertex-buffer(s). To perform instanced rendering, the rendering pipeline
  129. must be setup for instancing (see sg_pipeline_desc below), a separate vertex buffer
  130. containing per-instance data must be bound, and the num_instances parameter
  131. must be > 1.
  132. --- finish the current rendering pass with:
  133. sg_end_pass()
  134. --- when done with the current frame, call
  135. sg_commit()
  136. --- at the end of your program, shutdown sokol_gfx with:
  137. sg_shutdown()
  138. --- if you need to destroy resources before sg_shutdown(), call:
  139. sg_destroy_buffer(sg_buffer buf)
  140. sg_destroy_image(sg_image img)
  141. sg_destroy_sampler(sg_sampler smp)
  142. sg_destroy_shader(sg_shader shd)
  143. sg_destroy_pipeline(sg_pipeline pip)
  144. sg_destroy_attachments(sg_attachments atts)
  145. --- to set a new viewport rectangle, call
  146. sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left)
  147. ...or if you want to specify the viewport rectangle with float values:
  148. sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left)
  149. --- to set a new scissor rect, call:
  150. sg_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left)
  151. ...or with float values:
  152. sg_apply_scissor_rectf(float x, float y, float width, float height, bool origin_top_left)
  153. Both sg_apply_viewport() and sg_apply_scissor_rect() must be called
  154. inside a rendering pass
  155. Note that sg_begin_default_pass() and sg_begin_pass() will reset both the
  156. viewport and scissor rectangles to cover the entire framebuffer.
  157. --- to update (overwrite) the content of buffer and image resources, call:
  158. sg_update_buffer(sg_buffer buf, const sg_range* data)
  159. sg_update_image(sg_image img, const sg_image_data* data)
  160. Buffers and images to be updated must have been created with
  161. SG_USAGE_DYNAMIC or SG_USAGE_STREAM
  162. Only one update per frame is allowed for buffer and image resources when
  163. using the sg_update_*() functions. The rationale is to have a simple
  164. countermeasure to avoid the CPU scribbling over data the GPU is currently
  165. using, or the CPU having to wait for the GPU
  166. Buffer and image updates can be partial, as long as a rendering
  167. operation only references the valid (updated) data in the
  168. buffer or image.
  169. --- to append a chunk of data to a buffer resource, call:
  170. int sg_append_buffer(sg_buffer buf, const sg_range* data)
  171. The difference to sg_update_buffer() is that sg_append_buffer()
  172. can be called multiple times per frame to append new data to the
  173. buffer piece by piece, optionally interleaved with draw calls referencing
  174. the previously written data.
  175. sg_append_buffer() returns a byte offset to the start of the
  176. written data, this offset can be assigned to
  177. sg_bindings.vertex_buffer_offsets[n] or
  178. sg_bindings.index_buffer_offset
  179. Code example:
  180. for (...) {
  181. const void* data = ...;
  182. const int num_bytes = ...;
  183. int offset = sg_append_buffer(buf, &(sg_range) { .ptr=data, .size=num_bytes });
  184. bindings.vertex_buffer_offsets[0] = offset;
  185. sg_apply_pipeline(pip);
  186. sg_apply_bindings(&bindings);
  187. sg_apply_uniforms(...);
  188. sg_draw(...);
  189. }
  190. A buffer to be used with sg_append_buffer() must have been created
  191. with SG_USAGE_DYNAMIC or SG_USAGE_STREAM.
  192. If the application appends more data to the buffer then fits into
  193. the buffer, the buffer will go into the "overflow" state for the
  194. rest of the frame.
  195. Any draw calls attempting to render an overflown buffer will be
  196. silently dropped (in debug mode this will also result in a
  197. validation error).
  198. You can also check manually if a buffer is in overflow-state by calling
  199. bool sg_query_buffer_overflow(sg_buffer buf)
  200. You can manually check to see if an overflow would occur before adding
  201. any data to a buffer by calling
  202. bool sg_query_buffer_will_overflow(sg_buffer buf, size_t size)
  203. NOTE: Due to restrictions in underlying 3D-APIs, appended chunks of
  204. data will be 4-byte aligned in the destination buffer. This means
  205. that there will be gaps in index buffers containing 16-bit indices
  206. when the number of indices in a call to sg_append_buffer() is
  207. odd. This isn't a problem when each call to sg_append_buffer()
  208. is associated with one draw call, but will be problematic when
  209. a single indexed draw call spans several appended chunks of indices.
  210. --- to check at runtime for optional features, limits and pixelformat support,
  211. call:
  212. sg_features sg_query_features()
  213. sg_limits sg_query_limits()
  214. sg_pixelformat_info sg_query_pixelformat(sg_pixel_format fmt)
  215. --- if you need to call into the underlying 3D-API directly, you must call:
  216. sg_reset_state_cache()
  217. ...before calling sokol_gfx functions again
  218. --- you can inspect the original sg_desc structure handed to sg_setup()
  219. by calling sg_query_desc(). This will return an sg_desc struct with
  220. the default values patched in instead of any zero-initialized values
  221. --- you can get a desc struct matching the creation attributes of a
  222. specific resource object via:
  223. sg_buffer_desc sg_query_buffer_desc(sg_buffer buf)
  224. sg_image_desc sg_query_image_desc(sg_image img)
  225. sg_sampler_desc sg_query_sampler_desc(sg_sampler smp)
  226. sg_shader_desc sq_query_shader_desc(sg_shader shd)
  227. sg_pipeline_desc sg_query_pipeline_desc(sg_pipeline pip)
  228. sg_attachments_desc sg_query_attachments_desc(sg_attachments atts)
  229. ...but NOTE that the returned desc structs may be incomplete, only
  230. creation attributes that are kept around internally after resource
  231. creation will be filled in, and in some cases (like shaders) that's
  232. very little. Any missing attributes will be set to zero. The returned
  233. desc structs might still be useful as partial blueprint for creating
  234. similar resources if filled up with the missing attributes.
  235. Calling the query-desc functions on an invalid resource will return
  236. completely zeroed structs (it makes sense to check the resource state
  237. with sg_query_*_state() first)
  238. --- you can query the default resource creation parameters through the functions
  239. sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc* desc)
  240. sg_image_desc sg_query_image_defaults(const sg_image_desc* desc)
  241. sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc* desc)
  242. sg_shader_desc sg_query_shader_defaults(const sg_shader_desc* desc)
  243. sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc* desc)
  244. sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc* desc)
  245. These functions take a pointer to a desc structure which may contain
  246. zero-initialized items for default values. These zero-init values
  247. will be replaced with their concrete values in the returned desc
  248. struct.
  249. --- you can inspect various internal resource runtime values via:
  250. sg_buffer_info sg_query_buffer_info(sg_buffer buf)
  251. sg_image_info sg_query_image_info(sg_image img)
  252. sg_sampler_info sg_query_sampler_info(sg_sampler smp)
  253. sg_shader_info sg_query_shader_info(sg_shader shd)
  254. sg_pipeline_info sg_query_pipeline_info(sg_pipeline pip)
  255. sg_attachments_info sg_query_attachments_info(sg_attachments atts)
  256. ...please note that the returned info-structs are tied quite closely
  257. to sokol_gfx.h internals, and may change more often than other
  258. public API functions and structs.
  259. --- you can query frame stats and control stats collection via:
  260. sg_query_frame_stats()
  261. sg_enable_frame_stats()
  262. sg_disable_frame_stats()
  263. sg_frame_stats_enabled()
  264. --- you can ask at runtime what backend sokol_gfx.h has been compiled for:
  265. sg_backend sg_query_backend(void)
  266. --- call the following helper functions to compute the number of
  267. bytes in a texture row or surface for a specific pixel format.
  268. These functions might be helpful when preparing image data for consumption
  269. by sg_make_image() or sg_update_image():
  270. int sg_query_row_pitch(sg_pixel_format fmt, int width, int int row_align_bytes);
  271. int sg_query_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align_bytes);
  272. Width and height are generally in number pixels, but note that 'row' has different meaning
  273. for uncompressed vs compressed pixel formats: for uncompressed formats, a row is identical
  274. with a single line if pixels, while in compressed formats, one row is a line of *compression blocks*.
  275. This is why calling sg_query_surface_pitch() for a compressed pixel format and height
  276. N, N+1, N+2, ... may return the same result.
  277. The row_align_bytes parammeter is for added flexibility. For image data that goes into
  278. the sg_make_image() or sg_update_image() this should generally be 1, because these
  279. functions take tightly packed image data as input no matter what alignment restrictions
  280. exist in the backend 3D APIs.
  281. ON INITIALIZATION:
  282. ==================
  283. When calling sg_setup(), a pointer to an sg_desc struct must be provided
  284. which contains initialization options. These options provide two types
  285. of information to sokol-gfx:
  286. (1) upper bounds and limits needed to allocate various internal
  287. data structures:
  288. - the max number of resources of each type that can
  289. be alive at the same time, this is used for allocating
  290. internal pools
  291. - the max overall size of uniform data that can be
  292. updated per frame, including a worst-case alignment
  293. per uniform update (this worst-case alignment is 256 bytes)
  294. - the max size of all dynamic resource updates (sg_update_buffer,
  295. sg_append_buffer and sg_update_image) per frame
  296. Not all of those limit values are used by all backends, but it is
  297. good practice to provide them none-the-less.
  298. (2) 3D backend "environment information" in a nested sg_environment struct:
  299. - pointers to backend-specific context- or device-objects (for instance
  300. the D3D11, WebGPU or Metal device objects)
  301. - defaults for external swapchain pixel formats and sample counts,
  302. these will be used as default values in image and pipeline objects,
  303. and the sg_swapchain struct passed into sg_begin_pass()
  304. Usually you provide a complete sg_environment struct through
  305. a helper function, as an example look at the sglue_environment()
  306. function in the sokol_glue.h header.
  307. See the documentation block of the sg_desc struct below for more information.
  308. ON RENDER PASSES
  309. ================
  310. Relevant samples:
  311. - https://floooh.github.io/sokol-html5/offscreen-sapp.html
  312. - https://floooh.github.io/sokol-html5/offscreen-msaa-sapp.html
  313. - https://floooh.github.io/sokol-html5/mrt-sapp.html
  314. - https://floooh.github.io/sokol-html5/mrt-pixelformats-sapp.html
  315. A render pass groups rendering commands into a set of render target images
  316. (called 'pass attachments'). Render target images can be used in subsequent
  317. passes as textures (it is invalid to use the same image both as render target
  318. and as texture in the same pass).
  319. The following sokol-gfx functions must only be called inside a render pass:
  320. sg_apply_viewport(f)
  321. sg_apply_scissor_rect(f)
  322. sg_apply_pipeline
  323. sg_apply_bindings
  324. sg_apply_uniforms
  325. sg_draw
  326. A frame must have at least one 'swapchain render pass' which renders into an
  327. externally provided swapchain provided as an sg_swapchain struct to the
  328. sg_begin_pass() function. If you use sokol_gfx.h together with sokol_app.h,
  329. just call the sglue_swapchain() helper function in sokol_glue.h to
  330. provide the swapchain information. Otherwise the following information
  331. must be provided:
  332. - the color pixel-format of the swapchain's render surface
  333. - an optional depth/stencil pixel format if the swapchain
  334. has a depth/stencil buffer
  335. - an optional sample-count for MSAA rendering
  336. - NOTE: the above three values can be zero-initialized, in that
  337. case the defaults from the sg_environment struct will be used that
  338. had been passed to the sg_setup() function.
  339. - a number of backend specific objects:
  340. - GL/GLES3: just a GL framebuffer handle
  341. - D3D11:
  342. - an ID3D11RenderTargetView for the rendering surface
  343. - if MSAA is used, an ID3D11RenderTargetView as
  344. MSAA resolve-target
  345. - an optional ID3D11DepthStencilView for the
  346. depth/stencil buffer
  347. - WebGPU
  348. - a WGPUTextureView object for the rendering surface
  349. - if MSAA is used, a WGPUTextureView object as MSAA resolve target
  350. - an optional WGPUTextureView for the
  351. - Metal (NOTE that the roles of provided surfaces is slightly
  352. different in Metal than in D3D11 or WebGPU, notably, the
  353. CAMetalDrawable is either rendered to directly, or serves
  354. as MSAA resolve target):
  355. - a CAMetalDrawable object which is either rendered
  356. into directly, or in case of MSAA rendering, serves
  357. as MSAA-resolve-target
  358. - if MSAA is used, an multisampled MTLTexture where
  359. rendering goes into
  360. - an optional MTLTexture for the depth/stencil buffer
  361. It's recommended that you create a helper function which returns an
  362. initialized sg_swapchain struct by value. This can then be directly plugged
  363. into the sg_begin_pass function like this:
  364. sg_begin_pass(&(sg_pass){ .swapchain = sglue_swapchain() });
  365. As an example for such a helper function check out the function sglue_swapchain()
  366. in the sokol_glue.h header.
  367. For offscreen render passes, the render target images used in a render pass
  368. are baked into an immutable sg_attachments object.
  369. For a simple offscreen scenario with one color-, one depth-stencil-render
  370. target and without multisampling, creating an attachment object looks like this:
  371. First create two render target images, one with a color pixel format,
  372. and one with the depth- or depth-stencil pixel format. Both images
  373. must have the same dimensions:
  374. const sg_image color_img = sg_make_image(&(sg_image_desc){
  375. .render_target = true,
  376. .width = 256,
  377. .height = 256,
  378. .pixel_format = SG_PIXELFORMAT_RGBA8,
  379. .sample_count = 1,
  380. });
  381. const sg_image depth_img = sg_make_image(&(sg_image_desc){
  382. .render_target = true,
  383. .width = 256,
  384. .height = 256,
  385. .pixel_format = SG_PIXELFORMAT_DEPTH,
  386. .sample_count = 1,
  387. });
  388. NOTE: when creating render target images, have in mind that some default values
  389. are aligned with the default environment attributes in the sg_environment struct
  390. that was passed into the sg_setup() call:
  391. - the default value for sg_image_desc.pixel_format is taken from
  392. sg_environment.defaults.color_format
  393. - the default value for sg_image_desc.sample_count is taken from
  394. sg_environment.defaults.sample_count
  395. - the default value for sg_image_desc.num_mipmaps is always 1
  396. Next create an attachments object:
  397. const sg_attachments atts = sg_make_attachments(&(sg_attachments_desc){
  398. .colors[0].image = color_img,
  399. .depth_stencil.image = depth_img,
  400. });
  401. This attachments object is then passed into the sg_begin_pass() function
  402. in place of the swapchain struct:
  403. sg_begin_pass(&(sg_pass){ .attachments = atts });
  404. Swapchain and offscreen passes form dependency trees each with a swapchain
  405. pass at the root, offscreen passes as nodes, and render target images as
  406. dependencies between passes.
  407. sg_pass_action structs are used to define actions that should happen at the
  408. start and end of rendering passes (such as clearing pass attachments to a
  409. specific color or depth-value, or performing an MSAA resolve operation at
  410. the end of a pass).
  411. A typical sg_pass_action object which clears the color attachment to black
  412. might look like this:
  413. const sg_pass_action = {
  414. .colors[0] = {
  415. .load_action = SG_LOADACTION_CLEAR,
  416. .clear_value = { 0.0f, 0.0f, 0.0f, 1.0f }
  417. }
  418. };
  419. This omits the defaults for the color attachment store action, and
  420. the depth-stencil-attachments actions. The same pass action with the
  421. defaults explicitly filled in would look like this:
  422. const sg_pass_action pass_action = {
  423. .colors[0] = {
  424. .load_action = SG_LOADACTION_CLEAR,
  425. .store_action = SG_STOREACTION_STORE,
  426. .clear_value = { 0.0f, 0.0f, 0.0f, 1.0f }
  427. },
  428. .depth = = {
  429. .load_action = SG_LOADACTION_CLEAR,
  430. .store_action = SG_STOREACTION_DONTCARE,
  431. .clear_value = 1.0f,
  432. },
  433. .stencil = {
  434. .load_action = SG_LOADACTION_CLEAR,
  435. .store_action = SG_STOREACTION_DONTCARE,
  436. .clear_value = 0
  437. }
  438. };
  439. With the sg_pass object and sg_pass_action struct in place everything
  440. is ready now for the actual render pass:
  441. Using such this prepared sg_pass_action in a swapchain pass looks like
  442. this:
  443. sg_begin_pass(&(sg_pass){
  444. .action = pass_action,
  445. .swapchain = sglue_swapchain()
  446. });
  447. ...
  448. sg_end_pass();
  449. ...of alternatively in one offscreen pass:
  450. sg_begin_pass(&(sg_pass){
  451. .action = pass_action,
  452. .attachments = attachments,
  453. });
  454. ...
  455. sg_end_pass();
  456. Offscreen rendering can also go into a mipmap, or a slice/face of
  457. a cube-, array- or 3d-image (which some restrictions, for instance
  458. it's not possible to create a 3D image with a depth/stencil pixel format,
  459. these exceptions are generally caught by the sokol-gfx validation layer).
  460. The mipmap/slice selection happens at attachments creation time, for instance
  461. to render into mipmap 2 of slice 3 of an array texture:
  462. const sg_attachments atts = sg_make_attachments(&(sg_attachments_desc){
  463. .colors[0] = {
  464. .image = color_img,
  465. .mip_level = 2,
  466. .slice = 3,
  467. },
  468. .depth_stencil.image = depth_img,
  469. });
  470. If MSAA offscreen rendering is desired, the multi-sample rendering result
  471. must be 'resolved' into a separate 'resolve image', before that image can
  472. be used as texture.
  473. NOTE: currently multisample-images cannot be bound as textures.
  474. Creating a simple attachments object for multisampled rendering requires
  475. 3 attachment images: the color attachment image which has a sample
  476. count > 1, a resolve attachment image of the same size and pixel format
  477. but a sample count == 1, and a depth/stencil attachment image with
  478. the same size and sample count as the color attachment image:
  479. const sg_image color_img = sg_make_image(&(sg_image_desc){
  480. .render_target = true,
  481. .width = 256,
  482. .height = 256,
  483. .pixel_format = SG_PIXELFORMAT_RGBA8,
  484. .sample_count = 4,
  485. });
  486. const sg_image resolve_img = sg_make_image(&(sg_image_desc){
  487. .render_target = true,
  488. .width = 256,
  489. .height = 256,
  490. .pixel_format = SG_PIXELFORMAT_RGBA8,
  491. .sample_count = 1,
  492. });
  493. const sg_image depth_img = sg_make_image(&(sg_image_desc){
  494. .render_target = true,
  495. .width = 256,
  496. .height = 256,
  497. .pixel_format = SG_PIXELFORMAT_DEPTH,
  498. .sample_count = 4,
  499. });
  500. ...create the attachments object:
  501. const sg_attachments atts = sg_make_attachments(&(sg_attachments_desc){
  502. .colors[0].image = color_img,
  503. .resolves[0].image = resolve_img,
  504. .depth_stencil.image = depth_img,
  505. });
  506. If an attachments object defines a resolve image in a specific resolve attachment slot,
  507. an 'msaa resolve operation' will happen in sg_end_pass().
  508. In this scenario, the content of the MSAA color attachment doesn't need to be
  509. preserved (since it's only needed inside sg_end_pass for the msaa-resolve), so
  510. the .store_action should be set to "don't care":
  511. const sg_pass_action = {
  512. .colors[0] = {
  513. .load_action = SG_LOADACTION_CLEAR,
  514. .store_action = SG_STOREACTION_DONTCARE,
  515. .clear_value = { 0.0f, 0.0f, 0.0f, 1.0f }
  516. }
  517. };
  518. The actual render pass looks as usual:
  519. sg_begin_pass(&(sg_pass){ .action = pass_action, .attachments = atts });
  520. ...
  521. sg_end_pass();
  522. ...after sg_end_pass() the only difference to the non-msaa scenario is that the
  523. rendering result which is going to be used as texture in a followup pass is
  524. in 'resolve_img', not in 'color_img' (in fact, trying to bind color_img as a
  525. texture would result in a validation error).
  526. ON SHADER CREATION
  527. ==================
  528. sokol-gfx doesn't come with an integrated shader cross-compiler, instead
  529. backend-specific shader sources or binary blobs need to be provided when
  530. creating a shader object, along with information about the shader resource
  531. binding interface needed to bind sokol-gfx resources to the proper
  532. shader inputs.
  533. The easiest way to provide all this shader creation data is to use the
  534. sokol-shdc shader compiler tool to compile shaders from a common
  535. GLSL syntax into backend-specific sources or binary blobs, along with
  536. shader interface information and uniform blocks mapped to C structs.
  537. To create a shader using a C header which has been code-generated by sokol-shdc:
  538. // include the C header code-generated by sokol-shdc:
  539. #include "myshader.glsl.h"
  540. ...
  541. // create shader using a code-generated helper function from the C header:
  542. sg_shader shd = sg_make_shader(myshader_shader_desc(sg_query_backend()));
  543. The samples in the 'sapp' subdirectory of the sokol-samples project
  544. also use the sokol-shdc approach:
  545. https://github.com/floooh/sokol-samples/tree/master/sapp
  546. If you're planning to use sokol-shdc, you can stop reading here, instead
  547. continue with the sokol-shdc documentation:
  548. https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md
  549. To create shaders with backend-specific shader code or binary blobs,
  550. the sg_make_shader() function requires the following information:
  551. - Shader code or shader binary blobs for the vertex- and fragment- shader-stage:
  552. - for the desktop GL backend, source code can be provided in '#version 410' or
  553. '#version 430', version 430 is required for storage buffer support, but note
  554. that this is not available on macOS
  555. - for the GLES3 backend, source code must be provided in '#version 300 es' syntax
  556. - for the D3D11 backend, shaders can be provided as source or binary blobs, the
  557. source code should be in HLSL4.0 (for best compatibility) or alternatively
  558. in HLSL5.0 syntax (other versions may work but are not tested), NOTE: when
  559. shader source code is provided for the D3D11 backend, sokol-gfx will dynamically
  560. load 'd3dcompiler_47.dll'
  561. - for the Metal backends, shaders can be provided as source or binary blobs, the
  562. MSL version should be in 'metal-1.1' (other versions may work but are not tested)
  563. - for the WebGPU backend, shaders must be provided as WGSL source code
  564. - optionally the following shader-code related attributes can be provided:
  565. - an entry function name (only on D3D11 or Metal, but not OpenGL)
  566. - on D3D11 only, a compilation target (default is "vs_4_0" and "ps_4_0")
  567. - Depending on backend, information about the input vertex attributes used by the
  568. vertex shader:
  569. - Metal: no information needed since vertex attributes are always bound
  570. by their attribute location defined in the shader via '[[attribute(N)]]'
  571. - WebGPU: no information needed since vertex attributes are always
  572. bound by their attribute location defined in the shader via `@location(N)`
  573. - GLSL: vertex attribute names can be optionally provided, in that case their
  574. location will be looked up by name, otherwise, the vertex attribute location
  575. can be defined with 'layout(location = N)'
  576. - D3D11: a 'semantic name' and 'semantic index' must be provided for each vertex
  577. attribute, e.g. if the vertex attribute is defined as 'TEXCOORD1' in the shader,
  578. the semantic name would be 'TEXCOORD', and the semantic index would be '1'
  579. NOTE that vertex attributes currently must not have gaps. This requirement
  580. may be relaxed in the future.
  581. - Information about each uniform block used in the shader:
  582. - the shader stage of the uniform block (vertex or fragment)
  583. - the size of the uniform block in number of bytes
  584. - a memory layout hint (currently 'native' or 'std140') where 'native' defines a
  585. backend-specific memory layout which shouldn't be used for cross-platform code.
  586. Only std140 guarantees a backend-agnostic memory layout.
  587. - a backend-specific bind slot:
  588. - D3D11/HLSL: the buffer register N (`register(bN)`) where N is 0..7
  589. - Metal/MSL: the buffer bind slot N (`[[buffer(N)]]`) where N is 0..7
  590. - WebGPU: the binding N in `@group(0) @binding(N)` where N is 0..15
  591. - For GLSL only: a description of the internal uniform block layout, which maps
  592. member types and their offsets on the CPU side to uniform variable names
  593. in the GLSL shader
  594. - please also NOTE the documentation sections about UNIFORM DATA LAYOUT
  595. and CROSS-BACKEND COMMON UNIFORM DATA LAYOUT below!
  596. - A description of each storage buffer used in the shader:
  597. - the shader stage of the storage buffer
  598. - a boolean 'readonly' flag, note that currently only
  599. readonly storage buffers are supported
  600. - a backend-specific bind slot:
  601. - D3D11/HLSL: the texture register N (`register(tN)`) where N is 0..23
  602. (in HLSL, storage buffers and texture share the same bind space)
  603. - Metal/MSL: the buffer bind slot N (`[[buffer(N)]]`) where N is 8..15
  604. - WebGPU/WGSL: the binding N in `@group(0) @binding(N)` where N is 0..127
  605. - GL/GLSL: the buffer binding N in `layout(binding=N)` where N is 0..7
  606. - note that storage buffers are not supported on all backends
  607. and platforms
  608. - A description of each texture/image used in the shader:
  609. - the shader stage of the texture (vertex or fragment)
  610. - the expected image type:
  611. - SG_IMAGETYPE_2D
  612. - SG_IMAGETYPE_CUBE
  613. - SG_IMAGETYPE_3D
  614. - SG_IMAGETYPE_ARRAY
  615. - the expected 'image sample type':
  616. - SG_IMAGESAMPLETYPE_FLOAT
  617. - SG_IMAGESAMPLETYPE_DEPTH
  618. - SG_IMAGESAMPLETYPE_SINT
  619. - SG_IMAGESAMPLETYPE_UINT
  620. - SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT
  621. - a flag whether the texture is expected to be multisampled
  622. (currently it's not supported to fetch data from multisampled
  623. textures in shaders, but this is planned for a later time)
  624. - a backend-specific bind slot:
  625. - D3D11/HLSL: the texture register N (`register(tN)`) where N is 0..23
  626. (in HLSL, storage buffers and texture share the same bind space)
  627. - Metal/MSL: the texture bind slot N (`[[texture(N)]]`) where N is 0..15
  628. - WebGPU/WGSL: the binding N in `@group(0) @binding(N)` where N is 0..127
  629. - A description of each sampler used in the shader:
  630. - the shader stage of the sampler (vertex or fragment)
  631. - the expected sampler type:
  632. - SG_SAMPLERTYPE_FILTERING,
  633. - SG_SAMPLERTYPE_NONFILTERING,
  634. - SG_SAMPLERTYPE_COMPARISON,
  635. - a backend-specific bind slot:
  636. - D3D11/HLSL: the sampler register N (`register(sN)`) where N is 0..15
  637. - Metal/MSL: the sampler bind slot N (`[[sampler(N)]]`) where N is 0..15
  638. - WebGPU/WGSL: the binding N in `@group(0) @binding(N)` where N is 0..127
  639. - An array of 'image-sampler-pairs' used by the shader to sample textures,
  640. for D3D11, Metal and WebGPU this is used for validation purposes to check
  641. whether the texture and sampler are compatible with each other (especially
  642. WebGPU is very picky about combining the correct
  643. texture-sample-type with the correct sampler-type). For GLSL an
  644. additional 'combined-image-sampler name' must be provided because 'OpenGL
  645. style GLSL' cannot handle separate texture and sampler objects, but still
  646. groups them into a traditional GLSL 'sampler object'.
  647. Compatibility rules for image-sample-type vs sampler-type are as follows:
  648. - SG_IMAGESAMPLETYPE_FLOAT => (SG_SAMPLERTYPE_FILTERING or SG_SAMPLERTYPE_NONFILTERING)
  649. - SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT => SG_SAMPLERTYPE_NONFILTERING
  650. - SG_IMAGESAMPLETYPE_SINT => SG_SAMPLERTYPE_NONFILTERING
  651. - SG_IMAGESAMPLETYPE_UINT => SG_SAMPLERTYPE_NONFILTERING
  652. - SG_IMAGESAMPLETYPE_DEPTH => SG_SAMPLERTYPE_COMPARISON
  653. Backend-specific bindslot ranges (not relevant when using sokol-shdc):
  654. - D3D11/HLSL:
  655. - separate bindslot space per shader stage
  656. - uniform blocks (as cbuffer): `register(b0..b7)`
  657. - textures and storage buffers: `register(t0..t23)`
  658. - samplers: `register(s0..s15)`
  659. - Metal/MSL:
  660. - separate bindslot space per shader stage
  661. - uniform blocks: `[[buffer(0..7)]]`
  662. - storage buffers: `[[buffer(8..15)]]`
  663. - textures: `[[texture(0..15)]]`
  664. - samplers: `[[sampler(0..15)]]`
  665. - WebGPU/WGSL:
  666. - common bindslot space across shader stages
  667. - uniform blocks: `@group(0) @binding(0..15)`
  668. - textures, samplers and storage buffers: `@group(1) @binding(0..127)`
  669. - GL/GLSL:
  670. - uniforms and image-samplers are bound by name
  671. - storage buffers: `layout(std430, binding=0..7)` (common
  672. bindslot space across shader stages)
  673. For example code of how to create backend-specific shader objects,
  674. please refer to the following samples:
  675. - for D3D11: https://github.com/floooh/sokol-samples/tree/master/d3d11
  676. - for Metal: https://github.com/floooh/sokol-samples/tree/master/metal
  677. - for OpenGL: https://github.com/floooh/sokol-samples/tree/master/glfw
  678. - for GLES3: https://github.com/floooh/sokol-samples/tree/master/html5
  679. - for WebGPI: https://github.com/floooh/sokol-samples/tree/master/wgpu
  680. ON SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT AND SG_SAMPLERTYPE_NONFILTERING
  681. ========================================================================
  682. The WebGPU backend introduces the concept of 'unfilterable-float' textures,
  683. which can only be combined with 'nonfiltering' samplers (this is a restriction
  684. specific to WebGPU, but since the same sokol-gfx code should work across
  685. all backend, the sokol-gfx validation layer also enforces this restriction
  686. - the alternative would be undefined behaviour in some backend APIs on
  687. some devices).
  688. The background is that some mobile devices (most notably iOS devices) can
  689. not perform linear filtering when sampling textures with certain pixel
  690. formats, most notable the 32F formats:
  691. - SG_PIXELFORMAT_R32F
  692. - SG_PIXELFORMAT_RG32F
  693. - SG_PIXELFORMAT_RGBA32F
  694. The information of whether a shader is going to be used with such an
  695. unfilterable-float texture must already be provided in the sg_shader_desc
  696. struct when creating the shader (see the above section "ON SHADER CREATION").
  697. If you are using the sokol-shdc shader compiler, the information whether a
  698. texture/sampler binding expects an 'unfilterable-float/nonfiltering'
  699. texture/sampler combination cannot be inferred from the shader source
  700. alone, you'll need to provide this hint via annotation-tags. For instance
  701. here is an example from the ozz-skin-sapp.c sample shader which samples an
  702. RGBA32F texture with skinning matrices in the vertex shader:
  703. ```glsl
  704. @image_sample_type joint_tex unfilterable_float
  705. uniform texture2D joint_tex;
  706. @sampler_type smp nonfiltering
  707. uniform sampler smp;
  708. ```
  709. This will result in SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT and
  710. SG_SAMPLERTYPE_NONFILTERING being written to the code-generated
  711. sg_shader_desc struct.
  712. UNIFORM DATA LAYOUT:
  713. ====================
  714. NOTE: if you use the sokol-shdc shader compiler tool, you don't need to worry
  715. about the following details.
  716. The data that's passed into the sg_apply_uniforms() function must adhere to
  717. specific layout rules so that the GPU shader finds the uniform block
  718. items at the right offset.
  719. For the D3D11 and Metal backends, sokol-gfx only cares about the size of uniform
  720. blocks, but not about the internal layout. The data will just be copied into
  721. a uniform/constant buffer in a single operation and it's up you to arrange the
  722. CPU-side layout so that it matches the GPU side layout. This also means that with
  723. the D3D11 and Metal backends you are not limited to a 'cross-platform' subset
  724. of uniform variable types.
  725. If you ever only use one of the D3D11, Metal *or* WebGPU backend, you can stop reading here.
  726. For the GL backends, the internal layout of uniform blocks matters though,
  727. and you are limited to a small number of uniform variable types. This is
  728. because sokol-gfx must be able to locate the uniform block members in order
  729. to upload them to the GPU with glUniformXXX() calls.
  730. To describe the uniform block layout to sokol-gfx, the following information
  731. must be passed to the sg_make_shader() call in the sg_shader_desc struct:
  732. - a hint about the used packing rule (either SG_UNIFORMLAYOUT_NATIVE or
  733. SG_UNIFORMLAYOUT_STD140)
  734. - a list of the uniform block members types in the correct order they
  735. appear on the CPU side
  736. For example if the GLSL shader has the following uniform declarations:
  737. uniform mat4 mvp;
  738. uniform vec2 offset0;
  739. uniform vec2 offset1;
  740. uniform vec2 offset2;
  741. ...and on the CPU side, there's a similar C struct:
  742. typedef struct {
  743. float mvp[16];
  744. float offset0[2];
  745. float offset1[2];
  746. float offset2[2];
  747. } params_t;
  748. ...the uniform block description in the sg_shader_desc must look like this:
  749. sg_shader_desc desc = {
  750. .vs.uniform_blocks[0] = {
  751. .size = sizeof(params_t),
  752. .layout = SG_UNIFORMLAYOUT_NATIVE, // this is the default and can be omitted
  753. .uniforms = {
  754. // order must be the same as in 'params_t':
  755. [0] = { .name = "mvp", .type = SG_UNIFORMTYPE_MAT4 },
  756. [1] = { .name = "offset0", .type = SG_UNIFORMTYPE_VEC2 },
  757. [2] = { .name = "offset1", .type = SG_UNIFORMTYPE_VEC2 },
  758. [3] = { .name = "offset2", .type = SG_UNIFORMTYPE_VEC2 },
  759. }
  760. }
  761. };
  762. With this information sokol-gfx can now compute the correct offsets of the data items
  763. within the uniform block struct.
  764. The SG_UNIFORMLAYOUT_NATIVE packing rule works fine if only the GL backends are used,
  765. but for proper D3D11/Metal/GL a subset of the std140 layout must be used which is
  766. described in the next section:
  767. CROSS-BACKEND COMMON UNIFORM DATA LAYOUT
  768. ========================================
  769. For cross-platform / cross-3D-backend code it is important that the same uniform block
  770. layout on the CPU side can be used for all sokol-gfx backends. To achieve this,
  771. a common subset of the std140 layout must be used:
  772. - The uniform block layout hint in sg_shader_desc must be explicitly set to
  773. SG_UNIFORMLAYOUT_STD140.
  774. - Only the following GLSL uniform types can be used (with their associated sokol-gfx enums):
  775. - float => SG_UNIFORMTYPE_FLOAT
  776. - vec2 => SG_UNIFORMTYPE_FLOAT2
  777. - vec3 => SG_UNIFORMTYPE_FLOAT3
  778. - vec4 => SG_UNIFORMTYPE_FLOAT4
  779. - int => SG_UNIFORMTYPE_INT
  780. - ivec2 => SG_UNIFORMTYPE_INT2
  781. - ivec3 => SG_UNIFORMTYPE_INT3
  782. - ivec4 => SG_UNIFORMTYPE_INT4
  783. - mat4 => SG_UNIFORMTYPE_MAT4
  784. - Alignment for those types must be as follows (in bytes):
  785. - float => 4
  786. - vec2 => 8
  787. - vec3 => 16
  788. - vec4 => 16
  789. - int => 4
  790. - ivec2 => 8
  791. - ivec3 => 16
  792. - ivec4 => 16
  793. - mat4 => 16
  794. - Arrays are only allowed for the following types: vec4, int4, mat4.
  795. Note that the HLSL cbuffer layout rules are slightly different from the
  796. std140 layout rules, this means that the cbuffer declarations in HLSL code
  797. must be tweaked so that the layout is compatible with std140.
  798. The by far easiest way to tackle the common uniform block layout problem is
  799. to use the sokol-shdc shader cross-compiler tool!
  800. ON STORAGE BUFFERS
  801. ==================
  802. Storage buffers can be used to pass large amounts of random access structured
  803. data from the CPU side to the shaders. They are similar to data textures, but are
  804. more convenient to use both on the CPU and shader side since they can be accessed
  805. in shaders as as a 1-dimensional array of struct items.
  806. Storage buffers are *NOT* supported on the following platform/backend combos:
  807. - macOS+GL (because storage buffers require GL 4.3, while macOS only goes up to GL 4.1)
  808. - all GLES3 platforms (WebGL2, iOS, Android - with the option that support on
  809. Android may be added at a later point)
  810. Currently only 'readonly' storage buffers are supported (meaning it's not possible
  811. to write to storage buffers from shaders).
  812. To use storage buffers, the following steps are required:
  813. - write a shader which uses storage buffers (also see the example links below)
  814. - create one or more storage buffers via sg_make_buffer() with the
  815. buffer type SG_BUFFERTYPE_STORAGEBUFFER
  816. - when creating a shader via sg_make_shader(), populate the sg_shader_desc
  817. struct with binding info (when using sokol-shdc, this step will be taken care
  818. of automatically)
  819. - which storage buffer bind slots on the vertex- and fragment-stage
  820. are occupied
  821. - whether the storage buffer on that bind slot is readonly (this is currently required
  822. to be true)
  823. - when calling sg_apply_bindings(), apply the matching bind slots with the previously
  824. created storage buffers
  825. - ...and that's it.
  826. For more details, see the following backend-agnostic sokol samples:
  827. - simple vertex pulling from a storage buffer:
  828. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/vertexpull-sapp.c
  829. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/vertexpull-sapp.glsl
  830. - instanced rendering via storage buffers (vertex- and instance-pulling):
  831. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-pull-sapp.c
  832. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/instancing-pull-sapp.glsl
  833. - storage buffers both on the vertex- and fragment-stage:
  834. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/sbuftex-sapp.c
  835. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/sbuftex-sapp.glsl
  836. - the Ozz animation sample rewritten to pull all rendering data from storage buffers:
  837. - C code: https://github.com/floooh/sokol-samples/blob/master/sapp/ozz-storagebuffer-sapp.cc
  838. - shader: https://github.com/floooh/sokol-samples/blob/master/sapp/ozz-storagebuffer-sapp.glsl
  839. ...also see the following backend-specific vertex pulling samples (those also don't use sokol-shdc):
  840. - D3D11: https://github.com/floooh/sokol-samples/blob/master/d3d11/vertexpulling-d3d11.c
  841. - desktop GL: https://github.com/floooh/sokol-samples/blob/master/glfw/vertexpulling-glfw.c
  842. - Metal: https://github.com/floooh/sokol-samples/blob/master/metal/vertexpulling-metal.c
  843. - WebGPU: https://github.com/floooh/sokol-samples/blob/master/wgpu/vertexpulling-wgpu.c
  844. Storage buffer shader authoring caveats when using sokol-shdc:
  845. - declare a storage buffer interface block with `layout(binding=N) readonly buffer [name] { ... }`
  846. (where 'N' is the index in `sg_bindings.storage_buffers[N]`)
  847. - declare a struct which describes a single array item in the storage buffer interface block
  848. - only put a single flexible array member into the storage buffer interface block
  849. E.g. a complete example in 'sokol-shdc GLSL':
  850. ```glsl
  851. // declare a struct:
  852. struct sb_vertex {
  853. vec3 pos;
  854. vec4 color;
  855. }
  856. // declare a buffer interface block with a single flexible struct array:
  857. layout(binding=0) readonly buffer vertices {
  858. sb_vertex vtx[];
  859. }
  860. // in the shader function, access the storage buffer like this:
  861. void main() {
  862. vec3 pos = vtx[gl_VertexIndex].pos;
  863. ...
  864. }
  865. ```
  866. Backend-specific storage-buffer caveats (not relevant when using sokol-shdc):
  867. D3D11:
  868. - storage buffers are created as 'raw' Byte Address Buffers
  869. (https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-intro#raw-views-of-buffers)
  870. - in HLSL, use a ByteAddressBuffer to access the buffer content
  871. (https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-byteaddressbuffer)
  872. - in D3D11, storage buffers and textures share the same bind slots (declared as
  873. `register(tN)` in HLSL), where N must be in the range 0..23)
  874. Metal:
  875. - in Metal there is no internal difference between vertex-, uniform- and
  876. storage-buffers, all are bound to the same 'buffer bind slots' with the
  877. following reserved ranges:
  878. - vertex shader stage:
  879. - uniform buffers: slots 0..7
  880. - storage buffers: slots 8..15
  881. - vertex buffers: slots 15..23
  882. - fragment shader stage:
  883. - uniform buffers: slots 0..7
  884. - storage buffers: slots 8..15
  885. - this means in MSL, storage buffer bindings start at [[buffer(8)]] both in
  886. the vertex and fragment stage
  887. GL:
  888. - the GL backend doesn't use name-lookup to find storage buffer bindings, this
  889. means you must annotate buffers with `layout(std430, binding=N)` in GLSL
  890. - ...where N is 0..7 in the vertex shader, and 8..15 in the fragment shader
  891. WebGPU:
  892. - in WGSL, textures, samplers and storage buffers all use a shared
  893. bindspace across all shader stages on bindgroup 1:
  894. `@group(1) @binding(0..127)
  895. TRACE HOOKS:
  896. ============
  897. sokol_gfx.h optionally allows to install "trace hook" callbacks for
  898. each public API functions. When a public API function is called, and
  899. a trace hook callback has been installed for this function, the
  900. callback will be invoked with the parameters and result of the function.
  901. This is useful for things like debugging- and profiling-tools, or
  902. keeping track of resource creation and destruction.
  903. To use the trace hook feature:
  904. --- Define SOKOL_TRACE_HOOKS before including the implementation.
  905. --- Setup an sg_trace_hooks structure with your callback function
  906. pointers (keep all function pointers you're not interested
  907. in zero-initialized), optionally set the user_data member
  908. in the sg_trace_hooks struct.
  909. --- Install the trace hooks by calling sg_install_trace_hooks(),
  910. the return value of this function is another sg_trace_hooks
  911. struct which contains the previously set of trace hooks.
  912. You should keep this struct around, and call those previous
  913. functions pointers from your own trace callbacks for proper
  914. chaining.
  915. As an example of how trace hooks are used, have a look at the
  916. imgui/sokol_gfx_imgui.h header which implements a realtime
  917. debugging UI for sokol_gfx.h on top of Dear ImGui.
  918. A NOTE ON PORTABLE PACKED VERTEX FORMATS:
  919. =========================================
  920. There are two things to consider when using packed
  921. vertex formats like UBYTE4, SHORT2, etc which need to work
  922. across all backends:
  923. - D3D11 can only convert *normalized* vertex formats to
  924. floating point during vertex fetch, normalized formats
  925. have a trailing 'N', and are "normalized" to a range
  926. -1.0..+1.0 (for the signed formats) or 0.0..1.0 (for the
  927. unsigned formats):
  928. - SG_VERTEXFORMAT_BYTE4N
  929. - SG_VERTEXFORMAT_UBYTE4N
  930. - SG_VERTEXFORMAT_SHORT2N
  931. - SG_VERTEXFORMAT_USHORT2N
  932. - SG_VERTEXFORMAT_SHORT4N
  933. - SG_VERTEXFORMAT_USHORT4N
  934. D3D11 will not convert *non-normalized* vertex formats to floating point
  935. vertex shader inputs, those can only be uses with the *ivecn* vertex shader
  936. input types when D3D11 is used as backend (GL and Metal can use both formats)
  937. - SG_VERTEXFORMAT_BYTE4,
  938. - SG_VERTEXFORMAT_UBYTE4
  939. - SG_VERTEXFORMAT_SHORT2
  940. - SG_VERTEXFORMAT_SHORT4
  941. For a vertex input layout which works on all platforms, only use the following
  942. vertex formats, and if needed "expand" the normalized vertex shader
  943. inputs in the vertex shader by multiplying with 127.0, 255.0, 32767.0 or
  944. 65535.0:
  945. - SG_VERTEXFORMAT_FLOAT,
  946. - SG_VERTEXFORMAT_FLOAT2,
  947. - SG_VERTEXFORMAT_FLOAT3,
  948. - SG_VERTEXFORMAT_FLOAT4,
  949. - SG_VERTEXFORMAT_BYTE4N,
  950. - SG_VERTEXFORMAT_UBYTE4N,
  951. - SG_VERTEXFORMAT_SHORT2N,
  952. - SG_VERTEXFORMAT_USHORT2N
  953. - SG_VERTEXFORMAT_SHORT4N,
  954. - SG_VERTEXFORMAT_USHORT4N
  955. - SG_VERTEXFORMAT_UINT10_N2
  956. - SG_VERTEXFORMAT_HALF2
  957. - SG_VERTEXFORMAT_HALF4
  958. MEMORY ALLOCATION OVERRIDE
  959. ==========================
  960. You can override the memory allocation functions at initialization time
  961. like this:
  962. void* my_alloc(size_t size, void* user_data) {
  963. return malloc(size);
  964. }
  965. void my_free(void* ptr, void* user_data) {
  966. free(ptr);
  967. }
  968. ...
  969. sg_setup(&(sg_desc){
  970. // ...
  971. .allocator = {
  972. .alloc_fn = my_alloc,
  973. .free_fn = my_free,
  974. .user_data = ...,
  975. }
  976. });
  977. ...
  978. If no overrides are provided, malloc and free will be used.
  979. This only affects memory allocation calls done by sokol_gfx.h
  980. itself though, not any allocations in OS libraries.
  981. ERROR REPORTING AND LOGGING
  982. ===========================
  983. To get any logging information at all you need to provide a logging callback in the setup call
  984. the easiest way is to use sokol_log.h:
  985. #include "sokol_log.h"
  986. sg_setup(&(sg_desc){ .logger.func = slog_func });
  987. To override logging with your own callback, first write a logging function like this:
  988. void my_log(const char* tag, // e.g. 'sg'
  989. uint32_t log_level, // 0=panic, 1=error, 2=warn, 3=info
  990. uint32_t log_item_id, // SG_LOGITEM_*
  991. const char* message_or_null, // a message string, may be nullptr in release mode
  992. uint32_t line_nr, // line number in sokol_gfx.h
  993. const char* filename_or_null, // source filename, may be nullptr in release mode
  994. void* user_data)
  995. {
  996. ...
  997. }
  998. ...and then setup sokol-gfx like this:
  999. sg_setup(&(sg_desc){
  1000. .logger = {
  1001. .func = my_log,
  1002. .user_data = my_user_data,
  1003. }
  1004. });
  1005. The provided logging function must be reentrant (e.g. be callable from
  1006. different threads).
  1007. If you don't want to provide your own custom logger it is highly recommended to use
  1008. the standard logger in sokol_log.h instead, otherwise you won't see any warnings or
  1009. errors.
  1010. COMMIT LISTENERS
  1011. ================
  1012. It's possible to hook callback functions into sokol-gfx which are called from
  1013. inside sg_commit() in unspecified order. This is mainly useful for libraries
  1014. that build on top of sokol_gfx.h to be notified about the end/start of a frame.
  1015. To add a commit listener, call:
  1016. static void my_commit_listener(void* user_data) {
  1017. ...
  1018. }
  1019. bool success = sg_add_commit_listener((sg_commit_listener){
  1020. .func = my_commit_listener,
  1021. .user_data = ...,
  1022. });
  1023. The function returns false if the internal array of commit listeners is full,
  1024. or the same commit listener had already been added.
  1025. If the function returns true, my_commit_listener() will be called each frame
  1026. from inside sg_commit().
  1027. By default, 1024 distinct commit listeners can be added, but this number
  1028. can be tweaked in the sg_setup() call:
  1029. sg_setup(&(sg_desc){
  1030. .max_commit_listeners = 2048,
  1031. });
  1032. An sg_commit_listener item is equal to another if both the function
  1033. pointer and user_data field are equal.
  1034. To remove a commit listener:
  1035. bool success = sg_remove_commit_listener((sg_commit_listener){
  1036. .func = my_commit_listener,
  1037. .user_data = ...,
  1038. });
  1039. ...where the .func and .user_data field are equal to a previous
  1040. sg_add_commit_listener() call. The function returns true if the commit
  1041. listener item was found and removed, and false otherwise.
  1042. RESOURCE CREATION AND DESTRUCTION IN DETAIL
  1043. ===========================================
  1044. The 'vanilla' way to create resource objects is with the 'make functions':
  1045. sg_buffer sg_make_buffer(const sg_buffer_desc* desc)
  1046. sg_image sg_make_image(const sg_image_desc* desc)
  1047. sg_sampler sg_make_sampler(const sg_sampler_desc* desc)
  1048. sg_shader sg_make_shader(const sg_shader_desc* desc)
  1049. sg_pipeline sg_make_pipeline(const sg_pipeline_desc* desc)
  1050. sg_attachments sg_make_attachments(const sg_attachments_desc* desc)
  1051. This will result in one of three cases:
  1052. 1. The returned handle is invalid. This happens when there are no more
  1053. free slots in the resource pool for this resource type. An invalid
  1054. handle is associated with the INVALID resource state, for instance:
  1055. sg_buffer buf = sg_make_buffer(...)
  1056. if (sg_query_buffer_state(buf) == SG_RESOURCESTATE_INVALID) {
  1057. // buffer pool is exhausted
  1058. }
  1059. 2. The returned handle is valid, but creating the underlying resource
  1060. has failed for some reason. This results in a resource object in the
  1061. FAILED state. The reason *why* resource creation has failed differ
  1062. by resource type. Look for log messages with more details. A failed
  1063. resource state can be checked with:
  1064. sg_buffer buf = sg_make_buffer(...)
  1065. if (sg_query_buffer_state(buf) == SG_RESOURCESTATE_FAILED) {
  1066. // creating the resource has failed
  1067. }
  1068. 3. And finally, if everything goes right, the returned resource is
  1069. in resource state VALID and ready to use. This can be checked
  1070. with:
  1071. sg_buffer buf = sg_make_buffer(...)
  1072. if (sg_query_buffer_state(buf) == SG_RESOURCESTATE_VALID) {
  1073. // creating the resource has failed
  1074. }
  1075. When calling the 'make functions', the created resource goes through a number
  1076. of states:
  1077. - INITIAL: the resource slot associated with the new resource is currently
  1078. free (technically, there is no resource yet, just an empty pool slot)
  1079. - ALLOC: a handle for the new resource has been allocated, this just means
  1080. a pool slot has been reserved.
  1081. - VALID or FAILED: in VALID state any 3D API backend resource objects have
  1082. been successfully created, otherwise if anything went wrong, the resource
  1083. will be in FAILED state.
  1084. Sometimes it makes sense to first grab a handle, but initialize the
  1085. underlying resource at a later time. For instance when loading data
  1086. asynchronously from a slow data source, you may know what buffers and
  1087. textures are needed at an early stage of the loading process, but actually
  1088. loading the buffer or texture content can only be completed at a later time.
  1089. For such situations, sokol-gfx resource objects can be created in two steps.
  1090. You can allocate a handle upfront with one of the 'alloc functions':
  1091. sg_buffer sg_alloc_buffer(void)
  1092. sg_image sg_alloc_image(void)
  1093. sg_sampler sg_alloc_sampler(void)
  1094. sg_shader sg_alloc_shader(void)
  1095. sg_pipeline sg_alloc_pipeline(void)
  1096. sg_attachments sg_alloc_attachments(void)
  1097. This will return a handle with the underlying resource object in the
  1098. ALLOC state:
  1099. sg_image img = sg_alloc_image();
  1100. if (sg_query_image_state(img) == SG_RESOURCESTATE_ALLOC) {
  1101. // allocating an image handle has succeeded, otherwise
  1102. // the image pool is full
  1103. }
  1104. Such an 'incomplete' handle can be used in most sokol-gfx rendering functions
  1105. without doing any harm, sokol-gfx will simply skip any rendering operation
  1106. that involve resources which are not in VALID state.
  1107. At a later time (for instance once the texture has completed loading
  1108. asynchronously), the resource creation can be completed by calling one of
  1109. the 'init functions', those functions take an existing resource handle and
  1110. 'desc struct':
  1111. void sg_init_buffer(sg_buffer buf, const sg_buffer_desc* desc)
  1112. void sg_init_image(sg_image img, const sg_image_desc* desc)
  1113. void sg_init_sampler(sg_sampler smp, const sg_sampler_desc* desc)
  1114. void sg_init_shader(sg_shader shd, const sg_shader_desc* desc)
  1115. void sg_init_pipeline(sg_pipeline pip, const sg_pipeline_desc* desc)
  1116. void sg_init_attachments(sg_attachments atts, const sg_attachments_desc* desc)
  1117. The init functions expect a resource in ALLOC state, and after the function
  1118. returns, the resource will be either in VALID or FAILED state. Calling
  1119. an 'alloc function' followed by the matching 'init function' is fully
  1120. equivalent with calling the 'make function' alone.
  1121. Destruction can also happen as a two-step process. The 'uninit functions'
  1122. will put a resource object from the VALID or FAILED state back into the
  1123. ALLOC state:
  1124. void sg_uninit_buffer(sg_buffer buf)
  1125. void sg_uninit_image(sg_image img)
  1126. void sg_uninit_sampler(sg_sampler smp)
  1127. void sg_uninit_shader(sg_shader shd)
  1128. void sg_uninit_pipeline(sg_pipeline pip)
  1129. void sg_uninit_attachments(sg_attachments pass)
  1130. Calling the 'uninit functions' with a resource that is not in the VALID or
  1131. FAILED state is a no-op.
  1132. To finally free the pool slot for recycling call the 'dealloc functions':
  1133. void sg_dealloc_buffer(sg_buffer buf)
  1134. void sg_dealloc_image(sg_image img)
  1135. void sg_dealloc_sampler(sg_sampler smp)
  1136. void sg_dealloc_shader(sg_shader shd)
  1137. void sg_dealloc_pipeline(sg_pipeline pip)
  1138. void sg_dealloc_attachments(sg_attachments atts)
  1139. Calling the 'dealloc functions' on a resource that's not in ALLOC state is
  1140. a no-op, but will generate a warning log message.
  1141. Calling an 'uninit function' and 'dealloc function' in sequence is equivalent
  1142. with calling the associated 'destroy function':
  1143. void sg_destroy_buffer(sg_buffer buf)
  1144. void sg_destroy_image(sg_image img)
  1145. void sg_destroy_sampler(sg_sampler smp)
  1146. void sg_destroy_shader(sg_shader shd)
  1147. void sg_destroy_pipeline(sg_pipeline pip)
  1148. void sg_destroy_attachments(sg_attachments atts)
  1149. The 'destroy functions' can be called on resources in any state and generally
  1150. do the right thing (for instance if the resource is in ALLOC state, the destroy
  1151. function will be equivalent to the 'dealloc function' and skip the 'uninit part').
  1152. And finally to close the circle, the 'fail functions' can be called to manually
  1153. put a resource in ALLOC state into the FAILED state:
  1154. sg_fail_buffer(sg_buffer buf)
  1155. sg_fail_image(sg_image img)
  1156. sg_fail_sampler(sg_sampler smp)
  1157. sg_fail_shader(sg_shader shd)
  1158. sg_fail_pipeline(sg_pipeline pip)
  1159. sg_fail_attachments(sg_attachments atts)
  1160. This is recommended if anything went wrong outside of sokol-gfx during asynchronous
  1161. resource setup (for instance a file loading operation failed). In this case,
  1162. the 'fail function' should be called instead of the 'init function'.
  1163. Calling a 'fail function' on a resource that's not in ALLOC state is a no-op,
  1164. but will generate a warning log message.
  1165. NOTE: that two-step resource creation usually only makes sense for buffers
  1166. and images, but not for samplers, shaders, pipelines or attachments. Most notably, trying
  1167. to create a pipeline object with a shader that's not in VALID state will
  1168. trigger a validation layer error, or if the validation layer is disabled,
  1169. result in a pipeline object in FAILED state. Same when trying to create
  1170. an attachments object with invalid image objects.
  1171. WEBGPU CAVEATS
  1172. ==============
  1173. For a general overview and design notes of the WebGPU backend see:
  1174. https://floooh.github.io/2023/10/16/sokol-webgpu.html
  1175. In general, don't expect an automatic speedup when switching from the WebGL2
  1176. backend to the WebGPU backend. Some WebGPU functions currently actually
  1177. have a higher CPU overhead than similar WebGL2 functions, leading to the
  1178. paradoxical situation that some WebGPU code may be slower than similar WebGL2
  1179. code.
  1180. - when writing WGSL shader code by hand, a specific bind-slot convention
  1181. must be used:
  1182. All uniform block structs must use `@group(0)` and bindings in the
  1183. range 0..127:
  1184. @group(0) @binding(0..7)
  1185. All textures, samplers and storage buffers must use `@group(1)` and
  1186. bindings must be in the range 0..127:
  1187. @group(1) @binding(0..127)
  1188. Note that the number of texture, sampler and storage buffer bindings
  1189. is still limited despite the large bind range:
  1190. - up to 16 textures and sampler across all shader stages
  1191. - up to 8 storage buffers across all shader stages
  1192. If you use sokol-shdc to generate WGSL shader code, you don't need to worry
  1193. about the above binding conventions since sokol-shdc.
  1194. - The sokol-gfx WebGPU backend uses the sg_desc.uniform_buffer_size item
  1195. to allocate a single per-frame uniform buffer which must be big enough
  1196. to hold all data written by sg_apply_uniforms() during a single frame,
  1197. including a worst-case 256-byte alignment (e.g. each sg_apply_uniform
  1198. call will cost at least 256 bytes of uniform buffer size). The default size
  1199. is 4 MB, which is enough for 16384 sg_apply_uniform() calls per
  1200. frame (assuming the uniform data 'payload' is less than 256 bytes
  1201. per call). These rules are the same as for the Metal backend, so if
  1202. you are already using the Metal backend you'll be fine.
  1203. - sg_apply_bindings(): the sokol-gfx WebGPU backend implements a bindgroup
  1204. cache to prevent excessive creation and destruction of BindGroup objects
  1205. when calling sg_apply_bindings(). The number of slots in the bindgroups
  1206. cache is defined in sg_desc.wgpu_bindgroups_cache_size when calling
  1207. sg_setup. The cache size must be a power-of-2 number, with the default being
  1208. 1024. The bindgroups cache behaviour can be observed by calling the new
  1209. function sg_query_frame_stats(), where the following struct items are
  1210. of interest:
  1211. .wgpu.num_bindgroup_cache_hits
  1212. .wgpu.num_bindgroup_cache_misses
  1213. .wgpu.num_bindgroup_cache_collisions
  1214. .wgpu_num_bindgroup_cache_invalidates
  1215. .wgpu.num_bindgroup_cache_vs_hash_key_mismatch
  1216. The value to pay attention to is `.wgpu.num_bindgroup_cache_collisions`,
  1217. if this number is consistently higher than a few percent of the
  1218. .wgpu.num_set_bindgroup value, it might be a good idea to bump the
  1219. bindgroups cache size to the next power-of-2.
  1220. - sg_apply_viewport(): WebGPU currently has a unique restriction that viewport
  1221. rectangles must be contained entirely within the framebuffer. As a shitty
  1222. workaround sokol_gfx.h will clip incoming viewport rectangles against
  1223. the framebuffer, but this will distort the clipspace-to-screenspace mapping.
  1224. There's no proper way to handle this inside sokol_gfx.h, this must be fixed
  1225. in a future WebGPU update.
  1226. - The sokol shader compiler generally adds `diagnostic(off, derivative_uniformity);`
  1227. into the WGSL output. Currently only the Chrome WebGPU implementation seems
  1228. to recognize this.
  1229. - The vertex format SG_VERTEXFORMAT_UINT10_N2 is currently not supported because
  1230. WebGPU lacks a matching vertex format (this is currently being worked on though,
  1231. as soon as the vertex format shows up in webgpu.h, sokol_gfx.h will add support.
  1232. - Likewise, the following sokol-gfx vertex formats are not supported in WebGPU:
  1233. R16, R16SN, RG16, RG16SN, RGBA16, RGBA16SN.
  1234. Unlike unsupported vertex formats, unsupported pixel formats can be queried
  1235. in cross-backend code via sg_query_pixel_format() though.
  1236. - The Emscripten WebGPU shim currently doesn't support the Closure minification
  1237. post-link-step (e.g. currently the emcc argument '--closure 1' or '--closure 2'
  1238. will generate broken Javascript code.
  1239. - sokol-gfx requires the WebGPU device feature `depth32float-stencil8` to be enabled
  1240. (this should be widely supported)
  1241. - sokol-gfx expects that the WebGPU device feature `float32-filterable` to *not* be
  1242. enabled (since this would exclude all iOS devices)
  1243. LICENSE
  1244. =======
  1245. zlib/libpng license
  1246. Copyright (c) 2018 Andre Weissflog
  1247. This software is provided 'as-is', without any express or implied warranty.
  1248. In no event will the authors be held liable for any damages arising from the
  1249. use of this software.
  1250. Permission is granted to anyone to use this software for any purpose,
  1251. including commercial applications, and to alter it and redistribute it
  1252. freely, subject to the following restrictions:
  1253. 1. The origin of this software must not be misrepresented; you must not
  1254. claim that you wrote the original software. If you use this software in a
  1255. product, an acknowledgment in the product documentation would be
  1256. appreciated but is not required.
  1257. 2. Altered source versions must be plainly marked as such, and must not
  1258. be misrepresented as being the original software.
  1259. 3. This notice may not be removed or altered from any source
  1260. distribution.
  1261. */
  1262. #define SOKOL_GFX_INCLUDED (1)
  1263. #include <stddef.h> // size_t
  1264. #include <stdint.h>
  1265. #include <stdbool.h>
  1266. #if defined(SOKOL_API_DECL) && !defined(SOKOL_GFX_API_DECL)
  1267. #define SOKOL_GFX_API_DECL SOKOL_API_DECL
  1268. #endif
  1269. #ifndef SOKOL_GFX_API_DECL
  1270. #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_GFX_IMPL)
  1271. #define SOKOL_GFX_API_DECL __declspec(dllexport)
  1272. #elif defined(_WIN32) && defined(SOKOL_DLL)
  1273. #define SOKOL_GFX_API_DECL __declspec(dllimport)
  1274. #else
  1275. #define SOKOL_GFX_API_DECL extern
  1276. #endif
  1277. #endif
  1278. #ifdef __cplusplus
  1279. extern "C" {
  1280. #endif
  1281. /*
  1282. Resource id typedefs:
  1283. sg_buffer: vertex- and index-buffers
  1284. sg_image: images used as textures and render-pass attachments
  1285. sg_sampler sampler objects describing how a texture is sampled in a shader
  1286. sg_shader: vertex- and fragment-shaders and shader interface information
  1287. sg_pipeline: associated shader and vertex-layouts, and render states
  1288. sg_attachments: a baked collection of render pass attachment images
  1289. Instead of pointers, resource creation functions return a 32-bit
  1290. handle which uniquely identifies the resource object.
  1291. The 32-bit resource id is split into a 16-bit pool index in the lower bits,
  1292. and a 16-bit 'generation counter' in the upper bits. The index allows fast
  1293. pool lookups, and combined with the generation-counter it allows to detect
  1294. 'dangling accesses' (trying to use an object which no longer exists, and
  1295. its pool slot has been reused for a new object)
  1296. The resource ids are wrapped into a strongly-typed struct so that
  1297. trying to pass an incompatible resource id is a compile error.
  1298. */
  1299. typedef struct sg_buffer { uint32_t id; } sg_buffer;
  1300. typedef struct sg_image { uint32_t id; } sg_image;
  1301. typedef struct sg_sampler { uint32_t id; } sg_sampler;
  1302. typedef struct sg_shader { uint32_t id; } sg_shader;
  1303. typedef struct sg_pipeline { uint32_t id; } sg_pipeline;
  1304. typedef struct sg_attachments { uint32_t id; } sg_attachments;
  1305. /*
  1306. sg_range is a pointer-size-pair struct used to pass memory blobs into
  1307. sokol-gfx. When initialized from a value type (array or struct), you can
  1308. use the SG_RANGE() macro to build an sg_range struct. For functions which
  1309. take either a sg_range pointer, or a (C++) sg_range reference, use the
  1310. SG_RANGE_REF macro as a solution which compiles both in C and C++.
  1311. */
  1312. typedef struct sg_range {
  1313. const void* ptr;
  1314. size_t size;
  1315. } sg_range;
  1316. // disabling this for every includer isn't great, but the warnings are also quite pointless
  1317. #if defined(_MSC_VER)
  1318. #pragma warning(disable:4221) // /W4 only: nonstandard extension used: 'x': cannot be initialized using address of automatic variable 'y'
  1319. #pragma warning(disable:4204) // VS2015: nonstandard extension used: non-constant aggregate initializer
  1320. #endif
  1321. #if defined(__cplusplus)
  1322. #define SG_RANGE(x) sg_range{ &x, sizeof(x) }
  1323. #define SG_RANGE_REF(x) sg_range{ &x, sizeof(x) }
  1324. #else
  1325. #define SG_RANGE(x) (sg_range){ &x, sizeof(x) }
  1326. #define SG_RANGE_REF(x) &(sg_range){ &x, sizeof(x) }
  1327. #endif
  1328. // various compile-time constants in the public API
  1329. enum {
  1330. SG_INVALID_ID = 0,
  1331. SG_NUM_INFLIGHT_FRAMES = 2,
  1332. SG_MAX_COLOR_ATTACHMENTS = 4,
  1333. SG_MAX_UNIFORMBLOCK_MEMBERS = 16,
  1334. SG_MAX_VERTEX_ATTRIBUTES = 16,
  1335. SG_MAX_MIPMAPS = 16,
  1336. SG_MAX_TEXTUREARRAY_LAYERS = 128,
  1337. SG_MAX_UNIFORMBLOCK_BINDSLOTS = 8,
  1338. SG_MAX_VERTEXBUFFER_BINDSLOTS = 8,
  1339. SG_MAX_IMAGE_BINDSLOTS = 16,
  1340. SG_MAX_SAMPLER_BINDSLOTS = 16,
  1341. SG_MAX_STORAGEBUFFER_BINDSLOTS = 8,
  1342. SG_MAX_IMAGE_SAMPLER_PAIRS = 16,
  1343. };
  1344. /*
  1345. sg_color
  1346. An RGBA color value.
  1347. */
  1348. typedef struct sg_color { float r, g, b, a; } sg_color;
  1349. /*
  1350. sg_backend
  1351. The active 3D-API backend, use the function sg_query_backend()
  1352. to get the currently active backend.
  1353. */
  1354. typedef enum sg_backend {
  1355. SG_BACKEND_GLCORE,
  1356. SG_BACKEND_GLES3,
  1357. SG_BACKEND_D3D11,
  1358. SG_BACKEND_METAL_IOS,
  1359. SG_BACKEND_METAL_MACOS,
  1360. SG_BACKEND_METAL_SIMULATOR,
  1361. SG_BACKEND_WGPU,
  1362. SG_BACKEND_DUMMY,
  1363. } sg_backend;
  1364. /*
  1365. sg_pixel_format
  1366. sokol_gfx.h basically uses the same pixel formats as WebGPU, since these
  1367. are supported on most newer GPUs.
  1368. A pixelformat name consist of three parts:
  1369. - components (R, RG, RGB or RGBA)
  1370. - bit width per component (8, 16 or 32)
  1371. - component data type:
  1372. - unsigned normalized (no postfix)
  1373. - signed normalized (SN postfix)
  1374. - unsigned integer (UI postfix)
  1375. - signed integer (SI postfix)
  1376. - float (F postfix)
  1377. Not all pixel formats can be used for everything, call sg_query_pixelformat()
  1378. to inspect the capabilities of a given pixelformat. The function returns
  1379. an sg_pixelformat_info struct with the following members:
  1380. - sample: the pixelformat can be sampled as texture at least with
  1381. nearest filtering
  1382. - filter: the pixelformat can be sampled as texture with linear
  1383. filtering
  1384. - render: the pixelformat can be used as render-pass attachment
  1385. - blend: blending is supported when used as render-pass attachment
  1386. - msaa: multisample-antialiasing is supported when used
  1387. as render-pass attachment
  1388. - depth: the pixelformat can be used for depth-stencil attachments
  1389. - compressed: this is a block-compressed format
  1390. - bytes_per_pixel: the numbers of bytes in a pixel (0 for compressed formats)
  1391. The default pixel format for texture images is SG_PIXELFORMAT_RGBA8.
  1392. The default pixel format for render target images is platform-dependent
  1393. and taken from the sg_environment struct passed into sg_setup(). Typically
  1394. the default formats are:
  1395. - for the Metal, D3D11 and WebGPU backends: SG_PIXELFORMAT_BGRA8
  1396. - for GL backends: SG_PIXELFORMAT_RGBA8
  1397. */
  1398. typedef enum sg_pixel_format {
  1399. _SG_PIXELFORMAT_DEFAULT, // value 0 reserved for default-init
  1400. SG_PIXELFORMAT_NONE,
  1401. SG_PIXELFORMAT_R8,
  1402. SG_PIXELFORMAT_R8SN,
  1403. SG_PIXELFORMAT_R8UI,
  1404. SG_PIXELFORMAT_R8SI,
  1405. SG_PIXELFORMAT_R16,
  1406. SG_PIXELFORMAT_R16SN,
  1407. SG_PIXELFORMAT_R16UI,
  1408. SG_PIXELFORMAT_R16SI,
  1409. SG_PIXELFORMAT_R16F,
  1410. SG_PIXELFORMAT_RG8,
  1411. SG_PIXELFORMAT_RG8SN,
  1412. SG_PIXELFORMAT_RG8UI,
  1413. SG_PIXELFORMAT_RG8SI,
  1414. SG_PIXELFORMAT_R32UI,
  1415. SG_PIXELFORMAT_R32SI,
  1416. SG_PIXELFORMAT_R32F,
  1417. SG_PIXELFORMAT_RG16,
  1418. SG_PIXELFORMAT_RG16SN,
  1419. SG_PIXELFORMAT_RG16UI,
  1420. SG_PIXELFORMAT_RG16SI,
  1421. SG_PIXELFORMAT_RG16F,
  1422. SG_PIXELFORMAT_RGBA8,
  1423. SG_PIXELFORMAT_SRGB8A8,
  1424. SG_PIXELFORMAT_RGBA8SN,
  1425. SG_PIXELFORMAT_RGBA8UI,
  1426. SG_PIXELFORMAT_RGBA8SI,
  1427. SG_PIXELFORMAT_BGRA8,
  1428. SG_PIXELFORMAT_RGB10A2,
  1429. SG_PIXELFORMAT_RG11B10F,
  1430. SG_PIXELFORMAT_RGB9E5,
  1431. SG_PIXELFORMAT_RG32UI,
  1432. SG_PIXELFORMAT_RG32SI,
  1433. SG_PIXELFORMAT_RG32F,
  1434. SG_PIXELFORMAT_RGBA16,
  1435. SG_PIXELFORMAT_RGBA16SN,
  1436. SG_PIXELFORMAT_RGBA16UI,
  1437. SG_PIXELFORMAT_RGBA16SI,
  1438. SG_PIXELFORMAT_RGBA16F,
  1439. SG_PIXELFORMAT_RGBA32UI,
  1440. SG_PIXELFORMAT_RGBA32SI,
  1441. SG_PIXELFORMAT_RGBA32F,
  1442. // NOTE: when adding/removing pixel formats before DEPTH, also update sokol_app.h/_SAPP_PIXELFORMAT_*
  1443. SG_PIXELFORMAT_DEPTH,
  1444. SG_PIXELFORMAT_DEPTH_STENCIL,
  1445. // NOTE: don't put any new compressed format in front of here
  1446. SG_PIXELFORMAT_BC1_RGBA,
  1447. SG_PIXELFORMAT_BC2_RGBA,
  1448. SG_PIXELFORMAT_BC3_RGBA,
  1449. SG_PIXELFORMAT_BC3_SRGBA,
  1450. SG_PIXELFORMAT_BC4_R,
  1451. SG_PIXELFORMAT_BC4_RSN,
  1452. SG_PIXELFORMAT_BC5_RG,
  1453. SG_PIXELFORMAT_BC5_RGSN,
  1454. SG_PIXELFORMAT_BC6H_RGBF,
  1455. SG_PIXELFORMAT_BC6H_RGBUF,
  1456. SG_PIXELFORMAT_BC7_RGBA,
  1457. SG_PIXELFORMAT_BC7_SRGBA,
  1458. SG_PIXELFORMAT_ETC2_RGB8,
  1459. SG_PIXELFORMAT_ETC2_SRGB8,
  1460. SG_PIXELFORMAT_ETC2_RGB8A1,
  1461. SG_PIXELFORMAT_ETC2_RGBA8,
  1462. SG_PIXELFORMAT_ETC2_SRGB8A8,
  1463. SG_PIXELFORMAT_EAC_R11,
  1464. SG_PIXELFORMAT_EAC_R11SN,
  1465. SG_PIXELFORMAT_EAC_RG11,
  1466. SG_PIXELFORMAT_EAC_RG11SN,
  1467. SG_PIXELFORMAT_ASTC_4x4_RGBA,
  1468. SG_PIXELFORMAT_ASTC_4x4_SRGBA,
  1469. _SG_PIXELFORMAT_NUM,
  1470. _SG_PIXELFORMAT_FORCE_U32 = 0x7FFFFFFF
  1471. } sg_pixel_format;
  1472. /*
  1473. Runtime information about a pixel format, returned by sg_query_pixelformat().
  1474. */
  1475. typedef struct sg_pixelformat_info {
  1476. bool sample; // pixel format can be sampled in shaders at least with nearest filtering
  1477. bool filter; // pixel format can be sampled with linear filtering
  1478. bool render; // pixel format can be used as render-pass attachment
  1479. bool blend; // pixel format supports alpha-blending when used as render-pass attachment
  1480. bool msaa; // pixel format supports MSAA when used as render-pass attachment
  1481. bool depth; // pixel format is a depth format
  1482. bool compressed; // true if this is a hardware-compressed format
  1483. int bytes_per_pixel; // NOTE: this is 0 for compressed formats, use sg_query_row_pitch() / sg_query_surface_pitch() as alternative
  1484. } sg_pixelformat_info;
  1485. /*
  1486. Runtime information about available optional features, returned by sg_query_features()
  1487. */
  1488. typedef struct sg_features {
  1489. bool origin_top_left; // framebuffer- and texture-origin is in top left corner
  1490. bool image_clamp_to_border; // border color and clamp-to-border uv-wrap mode is supported
  1491. bool mrt_independent_blend_state; // multiple-render-target rendering can use per-render-target blend state
  1492. bool mrt_independent_write_mask; // multiple-render-target rendering can use per-render-target color write masks
  1493. bool storage_buffer; // storage buffers are supported
  1494. bool msaa_image_bindings; // if true, multisampled images can be bound as texture resources
  1495. } sg_features;
  1496. /*
  1497. Runtime information about resource limits, returned by sg_query_limit()
  1498. */
  1499. typedef struct sg_limits {
  1500. int max_image_size_2d; // max width/height of SG_IMAGETYPE_2D images
  1501. int max_image_size_cube; // max width/height of SG_IMAGETYPE_CUBE images
  1502. int max_image_size_3d; // max width/height/depth of SG_IMAGETYPE_3D images
  1503. int max_image_size_array; // max width/height of SG_IMAGETYPE_ARRAY images
  1504. int max_image_array_layers; // max number of layers in SG_IMAGETYPE_ARRAY images
  1505. int max_vertex_attrs; // max number of vertex attributes, clamped to SG_MAX_VERTEX_ATTRIBUTES
  1506. int gl_max_vertex_uniform_components; // <= GL_MAX_VERTEX_UNIFORM_COMPONENTS (only on GL backends)
  1507. int gl_max_combined_texture_image_units; // <= GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS (only on GL backends)
  1508. } sg_limits;
  1509. /*
  1510. sg_resource_state
  1511. The current state of a resource in its resource pool.
  1512. Resources start in the INITIAL state, which means the
  1513. pool slot is unoccupied and can be allocated. When a resource is
  1514. created, first an id is allocated, and the resource pool slot
  1515. is set to state ALLOC. After allocation, the resource is
  1516. initialized, which may result in the VALID or FAILED state. The
  1517. reason why allocation and initialization are separate is because
  1518. some resource types (e.g. buffers and images) might be asynchronously
  1519. initialized by the user application. If a resource which is not
  1520. in the VALID state is attempted to be used for rendering, rendering
  1521. operations will silently be dropped.
  1522. The special INVALID state is returned in sg_query_xxx_state() if no
  1523. resource object exists for the provided resource id.
  1524. */
  1525. typedef enum sg_resource_state {
  1526. SG_RESOURCESTATE_INITIAL,
  1527. SG_RESOURCESTATE_ALLOC,
  1528. SG_RESOURCESTATE_VALID,
  1529. SG_RESOURCESTATE_FAILED,
  1530. SG_RESOURCESTATE_INVALID,
  1531. _SG_RESOURCESTATE_FORCE_U32 = 0x7FFFFFFF
  1532. } sg_resource_state;
  1533. /*
  1534. sg_usage
  1535. A resource usage hint describing the update strategy of
  1536. buffers and images. This is used in the sg_buffer_desc.usage
  1537. and sg_image_desc.usage members when creating buffers
  1538. and images:
  1539. SG_USAGE_IMMUTABLE: the resource will never be updated with
  1540. new data, instead the content of the
  1541. resource must be provided on creation
  1542. SG_USAGE_DYNAMIC: the resource will be updated infrequently
  1543. with new data (this could range from "once
  1544. after creation", to "quite often but not
  1545. every frame")
  1546. SG_USAGE_STREAM: the resource will be updated each frame
  1547. with new content
  1548. The rendering backends use this hint to prevent that the
  1549. CPU needs to wait for the GPU when attempting to update
  1550. a resource that might be currently accessed by the GPU.
  1551. Resource content is updated with the functions sg_update_buffer() or
  1552. sg_append_buffer() for buffer objects, and sg_update_image() for image
  1553. objects. For the sg_update_*() functions, only one update is allowed per
  1554. frame and resource object, while sg_append_buffer() can be called
  1555. multiple times per frame on the same buffer. The application must update
  1556. all data required for rendering (this means that the update data can be
  1557. smaller than the resource size, if only a part of the overall resource
  1558. size is used for rendering, you only need to make sure that the data that
  1559. *is* used is valid).
  1560. The default usage is SG_USAGE_IMMUTABLE.
  1561. */
  1562. typedef enum sg_usage {
  1563. _SG_USAGE_DEFAULT, // value 0 reserved for default-init
  1564. SG_USAGE_IMMUTABLE,
  1565. SG_USAGE_DYNAMIC,
  1566. SG_USAGE_STREAM,
  1567. _SG_USAGE_NUM,
  1568. _SG_USAGE_FORCE_U32 = 0x7FFFFFFF
  1569. } sg_usage;
  1570. /*
  1571. sg_buffer_type
  1572. Indicates whether a buffer will be bound as vertex-,
  1573. index- or storage-buffer.
  1574. Used in the sg_buffer_desc.type member when creating a buffer.
  1575. The default value is SG_BUFFERTYPE_VERTEXBUFFER.
  1576. */
  1577. typedef enum sg_buffer_type {
  1578. _SG_BUFFERTYPE_DEFAULT, // value 0 reserved for default-init
  1579. SG_BUFFERTYPE_VERTEXBUFFER,
  1580. SG_BUFFERTYPE_INDEXBUFFER,
  1581. SG_BUFFERTYPE_STORAGEBUFFER,
  1582. _SG_BUFFERTYPE_NUM,
  1583. _SG_BUFFERTYPE_FORCE_U32 = 0x7FFFFFFF
  1584. } sg_buffer_type;
  1585. /*
  1586. sg_index_type
  1587. Indicates whether indexed rendering (fetching vertex-indices from an
  1588. index buffer) is used, and if yes, the index data type (16- or 32-bits).
  1589. This is used in the sg_pipeline_desc.index_type member when creating a
  1590. pipeline object.
  1591. The default index type is SG_INDEXTYPE_NONE.
  1592. */
  1593. typedef enum sg_index_type {
  1594. _SG_INDEXTYPE_DEFAULT, // value 0 reserved for default-init
  1595. SG_INDEXTYPE_NONE,
  1596. SG_INDEXTYPE_UINT16,
  1597. SG_INDEXTYPE_UINT32,
  1598. _SG_INDEXTYPE_NUM,
  1599. _SG_INDEXTYPE_FORCE_U32 = 0x7FFFFFFF
  1600. } sg_index_type;
  1601. /*
  1602. sg_image_type
  1603. Indicates the basic type of an image object (2D-texture, cubemap,
  1604. 3D-texture or 2D-array-texture). Used in the sg_image_desc.type member when
  1605. creating an image, and in sg_shader_image_desc to describe a sampled texture
  1606. in the shader (both must match and will be checked in the validation layer
  1607. when calling sg_apply_bindings).
  1608. The default image type when creating an image is SG_IMAGETYPE_2D.
  1609. */
  1610. typedef enum sg_image_type {
  1611. _SG_IMAGETYPE_DEFAULT, // value 0 reserved for default-init
  1612. SG_IMAGETYPE_2D,
  1613. SG_IMAGETYPE_CUBE,
  1614. SG_IMAGETYPE_3D,
  1615. SG_IMAGETYPE_ARRAY,
  1616. _SG_IMAGETYPE_NUM,
  1617. _SG_IMAGETYPE_FORCE_U32 = 0x7FFFFFFF
  1618. } sg_image_type;
  1619. /*
  1620. sg_image_sample_type
  1621. The basic data type of a texture sample as expected by a shader.
  1622. Must be provided in sg_shader_image and used by the validation
  1623. layer in sg_apply_bindings() to check if the provided image object
  1624. is compatible with what the shader expects. Apart from the sokol-gfx
  1625. validation layer, WebGPU is the only backend API which actually requires
  1626. matching texture and sampler type to be provided upfront for validation
  1627. (other 3D APIs treat texture/sampler type mismatches as undefined behaviour).
  1628. NOTE that the following texture pixel formats require the use
  1629. of SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT, combined with a sampler
  1630. of type SG_SAMPLERTYPE_NONFILTERING:
  1631. - SG_PIXELFORMAT_R32F
  1632. - SG_PIXELFORMAT_RG32F
  1633. - SG_PIXELFORMAT_RGBA32F
  1634. (when using sokol-shdc, also check out the meta tags `@image_sample_type`
  1635. and `@sampler_type`)
  1636. */
  1637. typedef enum sg_image_sample_type {
  1638. _SG_IMAGESAMPLETYPE_DEFAULT, // value 0 reserved for default-init
  1639. SG_IMAGESAMPLETYPE_FLOAT,
  1640. SG_IMAGESAMPLETYPE_DEPTH,
  1641. SG_IMAGESAMPLETYPE_SINT,
  1642. SG_IMAGESAMPLETYPE_UINT,
  1643. SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT,
  1644. _SG_IMAGESAMPLETYPE_NUM,
  1645. _SG_IMAGESAMPLETYPE_FORCE_U32 = 0x7FFFFFFF
  1646. } sg_image_sample_type;
  1647. /*
  1648. sg_sampler_type
  1649. The basic type of a texture sampler (sampling vs comparison) as
  1650. defined in a shader. Must be provided in sg_shader_sampler_desc.
  1651. sg_image_sample_type and sg_sampler_type for a texture/sampler
  1652. pair must be compatible with each other, specifically only
  1653. the following pairs are allowed:
  1654. - SG_IMAGESAMPLETYPE_FLOAT => (SG_SAMPLERTYPE_FILTERING or SG_SAMPLERTYPE_NONFILTERING)
  1655. - SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT => SG_SAMPLERTYPE_NONFILTERING
  1656. - SG_IMAGESAMPLETYPE_SINT => SG_SAMPLERTYPE_NONFILTERING
  1657. - SG_IMAGESAMPLETYPE_UINT => SG_SAMPLERTYPE_NONFILTERING
  1658. - SG_IMAGESAMPLETYPE_DEPTH => SG_SAMPLERTYPE_COMPARISON
  1659. */
  1660. typedef enum sg_sampler_type {
  1661. _SG_SAMPLERTYPE_DEFAULT,
  1662. SG_SAMPLERTYPE_FILTERING,
  1663. SG_SAMPLERTYPE_NONFILTERING,
  1664. SG_SAMPLERTYPE_COMPARISON,
  1665. _SG_SAMPLERTYPE_NUM,
  1666. _SG_SAMPLERTYPE_FORCE_U32,
  1667. } sg_sampler_type;
  1668. /*
  1669. sg_cube_face
  1670. The cubemap faces. Use these as indices in the sg_image_desc.content
  1671. array.
  1672. */
  1673. typedef enum sg_cube_face {
  1674. SG_CUBEFACE_POS_X,
  1675. SG_CUBEFACE_NEG_X,
  1676. SG_CUBEFACE_POS_Y,
  1677. SG_CUBEFACE_NEG_Y,
  1678. SG_CUBEFACE_POS_Z,
  1679. SG_CUBEFACE_NEG_Z,
  1680. SG_CUBEFACE_NUM,
  1681. _SG_CUBEFACE_FORCE_U32 = 0x7FFFFFFF
  1682. } sg_cube_face;
  1683. /*
  1684. sg_primitive_type
  1685. This is the common subset of 3D primitive types supported across all 3D
  1686. APIs. This is used in the sg_pipeline_desc.primitive_type member when
  1687. creating a pipeline object.
  1688. The default primitive type is SG_PRIMITIVETYPE_TRIANGLES.
  1689. */
  1690. typedef enum sg_primitive_type {
  1691. _SG_PRIMITIVETYPE_DEFAULT, // value 0 reserved for default-init
  1692. SG_PRIMITIVETYPE_POINTS,
  1693. SG_PRIMITIVETYPE_LINES,
  1694. SG_PRIMITIVETYPE_LINE_STRIP,
  1695. SG_PRIMITIVETYPE_TRIANGLES,
  1696. SG_PRIMITIVETYPE_TRIANGLE_STRIP,
  1697. _SG_PRIMITIVETYPE_NUM,
  1698. _SG_PRIMITIVETYPE_FORCE_U32 = 0x7FFFFFFF
  1699. } sg_primitive_type;
  1700. /*
  1701. sg_filter
  1702. The filtering mode when sampling a texture image. This is
  1703. used in the sg_sampler_desc.min_filter, sg_sampler_desc.mag_filter
  1704. and sg_sampler_desc.mipmap_filter members when creating a sampler object.
  1705. For the default is SG_FILTER_NEAREST.
  1706. */
  1707. typedef enum sg_filter {
  1708. _SG_FILTER_DEFAULT, // value 0 reserved for default-init
  1709. SG_FILTER_NEAREST,
  1710. SG_FILTER_LINEAR,
  1711. _SG_FILTER_NUM,
  1712. _SG_FILTER_FORCE_U32 = 0x7FFFFFFF
  1713. } sg_filter;
  1714. /*
  1715. sg_wrap
  1716. The texture coordinates wrapping mode when sampling a texture
  1717. image. This is used in the sg_image_desc.wrap_u, .wrap_v
  1718. and .wrap_w members when creating an image.
  1719. The default wrap mode is SG_WRAP_REPEAT.
  1720. NOTE: SG_WRAP_CLAMP_TO_BORDER is not supported on all backends
  1721. and platforms. To check for support, call sg_query_features()
  1722. and check the "clamp_to_border" boolean in the returned
  1723. sg_features struct.
  1724. Platforms which don't support SG_WRAP_CLAMP_TO_BORDER will silently fall back
  1725. to SG_WRAP_CLAMP_TO_EDGE without a validation error.
  1726. */
  1727. typedef enum sg_wrap {
  1728. _SG_WRAP_DEFAULT, // value 0 reserved for default-init
  1729. SG_WRAP_REPEAT,
  1730. SG_WRAP_CLAMP_TO_EDGE,
  1731. SG_WRAP_CLAMP_TO_BORDER,
  1732. SG_WRAP_MIRRORED_REPEAT,
  1733. _SG_WRAP_NUM,
  1734. _SG_WRAP_FORCE_U32 = 0x7FFFFFFF
  1735. } sg_wrap;
  1736. /*
  1737. sg_border_color
  1738. The border color to use when sampling a texture, and the UV wrap
  1739. mode is SG_WRAP_CLAMP_TO_BORDER.
  1740. The default border color is SG_BORDERCOLOR_OPAQUE_BLACK
  1741. */
  1742. typedef enum sg_border_color {
  1743. _SG_BORDERCOLOR_DEFAULT, // value 0 reserved for default-init
  1744. SG_BORDERCOLOR_TRANSPARENT_BLACK,
  1745. SG_BORDERCOLOR_OPAQUE_BLACK,
  1746. SG_BORDERCOLOR_OPAQUE_WHITE,
  1747. _SG_BORDERCOLOR_NUM,
  1748. _SG_BORDERCOLOR_FORCE_U32 = 0x7FFFFFFF
  1749. } sg_border_color;
  1750. /*
  1751. sg_vertex_format
  1752. The data type of a vertex component. This is used to describe
  1753. the layout of vertex data when creating a pipeline object.
  1754. */
  1755. typedef enum sg_vertex_format {
  1756. SG_VERTEXFORMAT_INVALID,
  1757. SG_VERTEXFORMAT_FLOAT,
  1758. SG_VERTEXFORMAT_FLOAT2,
  1759. SG_VERTEXFORMAT_FLOAT3,
  1760. SG_VERTEXFORMAT_FLOAT4,
  1761. SG_VERTEXFORMAT_BYTE4,
  1762. SG_VERTEXFORMAT_BYTE4N,
  1763. SG_VERTEXFORMAT_UBYTE4,
  1764. SG_VERTEXFORMAT_UBYTE4N,
  1765. SG_VERTEXFORMAT_SHORT2,
  1766. SG_VERTEXFORMAT_SHORT2N,
  1767. SG_VERTEXFORMAT_USHORT2N,
  1768. SG_VERTEXFORMAT_SHORT4,
  1769. SG_VERTEXFORMAT_SHORT4N,
  1770. SG_VERTEXFORMAT_USHORT4N,
  1771. SG_VERTEXFORMAT_UINT10_N2,
  1772. SG_VERTEXFORMAT_HALF2,
  1773. SG_VERTEXFORMAT_HALF4,
  1774. _SG_VERTEXFORMAT_NUM,
  1775. _SG_VERTEXFORMAT_FORCE_U32 = 0x7FFFFFFF
  1776. } sg_vertex_format;
  1777. /*
  1778. sg_vertex_step
  1779. Defines whether the input pointer of a vertex input stream is advanced
  1780. 'per vertex' or 'per instance'. The default step-func is
  1781. SG_VERTEXSTEP_PER_VERTEX. SG_VERTEXSTEP_PER_INSTANCE is used with
  1782. instanced-rendering.
  1783. The vertex-step is part of the vertex-layout definition
  1784. when creating pipeline objects.
  1785. */
  1786. typedef enum sg_vertex_step {
  1787. _SG_VERTEXSTEP_DEFAULT, // value 0 reserved for default-init
  1788. SG_VERTEXSTEP_PER_VERTEX,
  1789. SG_VERTEXSTEP_PER_INSTANCE,
  1790. _SG_VERTEXSTEP_NUM,
  1791. _SG_VERTEXSTEP_FORCE_U32 = 0x7FFFFFFF
  1792. } sg_vertex_step;
  1793. /*
  1794. sg_uniform_type
  1795. The data type of a uniform block member. This is used to
  1796. describe the internal layout of uniform blocks when creating
  1797. a shader object. This is only required for the GL backend, all
  1798. other backends will ignore the interior layout of uniform blocks.
  1799. */
  1800. typedef enum sg_uniform_type {
  1801. SG_UNIFORMTYPE_INVALID,
  1802. SG_UNIFORMTYPE_FLOAT,
  1803. SG_UNIFORMTYPE_FLOAT2,
  1804. SG_UNIFORMTYPE_FLOAT3,
  1805. SG_UNIFORMTYPE_FLOAT4,
  1806. SG_UNIFORMTYPE_INT,
  1807. SG_UNIFORMTYPE_INT2,
  1808. SG_UNIFORMTYPE_INT3,
  1809. SG_UNIFORMTYPE_INT4,
  1810. SG_UNIFORMTYPE_MAT4,
  1811. _SG_UNIFORMTYPE_NUM,
  1812. _SG_UNIFORMTYPE_FORCE_U32 = 0x7FFFFFFF
  1813. } sg_uniform_type;
  1814. /*
  1815. sg_uniform_layout
  1816. A hint for the interior memory layout of uniform blocks. This is
  1817. only relevant for the GL backend where the internal layout
  1818. of uniform blocks must be known to sokol-gfx. For all other backends the
  1819. internal memory layout of uniform blocks doesn't matter, sokol-gfx
  1820. will just pass uniform data as a single memory blob to the
  1821. 3D backend.
  1822. SG_UNIFORMLAYOUT_NATIVE (default)
  1823. Native layout means that a 'backend-native' memory layout
  1824. is used. For the GL backend this means that uniforms
  1825. are packed tightly in memory (e.g. there are no padding
  1826. bytes).
  1827. SG_UNIFORMLAYOUT_STD140
  1828. The memory layout is a subset of std140. Arrays are only
  1829. allowed for the FLOAT4, INT4 and MAT4. Alignment is as
  1830. is as follows:
  1831. FLOAT, INT: 4 byte alignment
  1832. FLOAT2, INT2: 8 byte alignment
  1833. FLOAT3, INT3: 16 byte alignment(!)
  1834. FLOAT4, INT4: 16 byte alignment
  1835. MAT4: 16 byte alignment
  1836. FLOAT4[], INT4[]: 16 byte alignment
  1837. The overall size of the uniform block must be a multiple
  1838. of 16.
  1839. For more information search for 'UNIFORM DATA LAYOUT' in the documentation block
  1840. at the start of the header.
  1841. */
  1842. typedef enum sg_uniform_layout {
  1843. _SG_UNIFORMLAYOUT_DEFAULT, // value 0 reserved for default-init
  1844. SG_UNIFORMLAYOUT_NATIVE, // default: layout depends on currently active backend
  1845. SG_UNIFORMLAYOUT_STD140, // std140: memory layout according to std140
  1846. _SG_UNIFORMLAYOUT_NUM,
  1847. _SG_UNIFORMLAYOUT_FORCE_U32 = 0x7FFFFFFF
  1848. } sg_uniform_layout;
  1849. /*
  1850. sg_cull_mode
  1851. The face-culling mode, this is used in the
  1852. sg_pipeline_desc.cull_mode member when creating a
  1853. pipeline object.
  1854. The default cull mode is SG_CULLMODE_NONE
  1855. */
  1856. typedef enum sg_cull_mode {
  1857. _SG_CULLMODE_DEFAULT, // value 0 reserved for default-init
  1858. SG_CULLMODE_NONE,
  1859. SG_CULLMODE_FRONT,
  1860. SG_CULLMODE_BACK,
  1861. _SG_CULLMODE_NUM,
  1862. _SG_CULLMODE_FORCE_U32 = 0x7FFFFFFF
  1863. } sg_cull_mode;
  1864. /*
  1865. sg_face_winding
  1866. The vertex-winding rule that determines a front-facing primitive. This
  1867. is used in the member sg_pipeline_desc.face_winding
  1868. when creating a pipeline object.
  1869. The default winding is SG_FACEWINDING_CW (clockwise)
  1870. */
  1871. typedef enum sg_face_winding {
  1872. _SG_FACEWINDING_DEFAULT, // value 0 reserved for default-init
  1873. SG_FACEWINDING_CCW,
  1874. SG_FACEWINDING_CW,
  1875. _SG_FACEWINDING_NUM,
  1876. _SG_FACEWINDING_FORCE_U32 = 0x7FFFFFFF
  1877. } sg_face_winding;
  1878. /*
  1879. sg_compare_func
  1880. The compare-function for configuring depth- and stencil-ref tests
  1881. in pipeline objects, and for texture samplers which perform a comparison
  1882. instead of regular sampling operation.
  1883. Used in the following structs:
  1884. sg_pipeline_desc
  1885. .depth
  1886. .compare
  1887. .stencil
  1888. .front.compare
  1889. .back.compar
  1890. sg_sampler_desc
  1891. .compare
  1892. The default compare func for depth- and stencil-tests is
  1893. SG_COMPAREFUNC_ALWAYS.
  1894. The default compare func for samplers is SG_COMPAREFUNC_NEVER.
  1895. */
  1896. typedef enum sg_compare_func {
  1897. _SG_COMPAREFUNC_DEFAULT, // value 0 reserved for default-init
  1898. SG_COMPAREFUNC_NEVER,
  1899. SG_COMPAREFUNC_LESS,
  1900. SG_COMPAREFUNC_EQUAL,
  1901. SG_COMPAREFUNC_LESS_EQUAL,
  1902. SG_COMPAREFUNC_GREATER,
  1903. SG_COMPAREFUNC_NOT_EQUAL,
  1904. SG_COMPAREFUNC_GREATER_EQUAL,
  1905. SG_COMPAREFUNC_ALWAYS,
  1906. _SG_COMPAREFUNC_NUM,
  1907. _SG_COMPAREFUNC_FORCE_U32 = 0x7FFFFFFF
  1908. } sg_compare_func;
  1909. /*
  1910. sg_stencil_op
  1911. The operation performed on a currently stored stencil-value when a
  1912. comparison test passes or fails. This is used when creating a pipeline
  1913. object in the following sg_pipeline_desc struct items:
  1914. sg_pipeline_desc
  1915. .stencil
  1916. .front
  1917. .fail_op
  1918. .depth_fail_op
  1919. .pass_op
  1920. .back
  1921. .fail_op
  1922. .depth_fail_op
  1923. .pass_op
  1924. The default value is SG_STENCILOP_KEEP.
  1925. */
  1926. typedef enum sg_stencil_op {
  1927. _SG_STENCILOP_DEFAULT, // value 0 reserved for default-init
  1928. SG_STENCILOP_KEEP,
  1929. SG_STENCILOP_ZERO,
  1930. SG_STENCILOP_REPLACE,
  1931. SG_STENCILOP_INCR_CLAMP,
  1932. SG_STENCILOP_DECR_CLAMP,
  1933. SG_STENCILOP_INVERT,
  1934. SG_STENCILOP_INCR_WRAP,
  1935. SG_STENCILOP_DECR_WRAP,
  1936. _SG_STENCILOP_NUM,
  1937. _SG_STENCILOP_FORCE_U32 = 0x7FFFFFFF
  1938. } sg_stencil_op;
  1939. /*
  1940. sg_blend_factor
  1941. The source and destination factors in blending operations.
  1942. This is used in the following members when creating a pipeline object:
  1943. sg_pipeline_desc
  1944. .colors[i]
  1945. .blend
  1946. .src_factor_rgb
  1947. .dst_factor_rgb
  1948. .src_factor_alpha
  1949. .dst_factor_alpha
  1950. The default value is SG_BLENDFACTOR_ONE for source
  1951. factors, and for the destination SG_BLENDFACTOR_ZERO if the associated
  1952. blend-op is ADD, SUBTRACT or REVERSE_SUBTRACT or SG_BLENDFACTOR_ONE
  1953. if the associated blend-op is MIN or MAX.
  1954. */
  1955. typedef enum sg_blend_factor {
  1956. _SG_BLENDFACTOR_DEFAULT, // value 0 reserved for default-init
  1957. SG_BLENDFACTOR_ZERO,
  1958. SG_BLENDFACTOR_ONE,
  1959. SG_BLENDFACTOR_SRC_COLOR,
  1960. SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR,
  1961. SG_BLENDFACTOR_SRC_ALPHA,
  1962. SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA,
  1963. SG_BLENDFACTOR_DST_COLOR,
  1964. SG_BLENDFACTOR_ONE_MINUS_DST_COLOR,
  1965. SG_BLENDFACTOR_DST_ALPHA,
  1966. SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA,
  1967. SG_BLENDFACTOR_SRC_ALPHA_SATURATED,
  1968. SG_BLENDFACTOR_BLEND_COLOR,
  1969. SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR,
  1970. SG_BLENDFACTOR_BLEND_ALPHA,
  1971. SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA,
  1972. _SG_BLENDFACTOR_NUM,
  1973. _SG_BLENDFACTOR_FORCE_U32 = 0x7FFFFFFF
  1974. } sg_blend_factor;
  1975. /*
  1976. sg_blend_op
  1977. Describes how the source and destination values are combined in the
  1978. fragment blending operation. It is used in the following struct items
  1979. when creating a pipeline object:
  1980. sg_pipeline_desc
  1981. .colors[i]
  1982. .blend
  1983. .op_rgb
  1984. .op_alpha
  1985. The default value is SG_BLENDOP_ADD.
  1986. */
  1987. typedef enum sg_blend_op {
  1988. _SG_BLENDOP_DEFAULT, // value 0 reserved for default-init
  1989. SG_BLENDOP_ADD,
  1990. SG_BLENDOP_SUBTRACT,
  1991. SG_BLENDOP_REVERSE_SUBTRACT,
  1992. SG_BLENDOP_MIN,
  1993. SG_BLENDOP_MAX,
  1994. _SG_BLENDOP_NUM,
  1995. _SG_BLENDOP_FORCE_U32 = 0x7FFFFFFF
  1996. } sg_blend_op;
  1997. /*
  1998. sg_color_mask
  1999. Selects the active color channels when writing a fragment color to the
  2000. framebuffer. This is used in the members
  2001. sg_pipeline_desc.colors[i].write_mask when creating a pipeline object.
  2002. The default colormask is SG_COLORMASK_RGBA (write all colors channels)
  2003. NOTE: since the color mask value 0 is reserved for the default value
  2004. (SG_COLORMASK_RGBA), use SG_COLORMASK_NONE if all color channels
  2005. should be disabled.
  2006. */
  2007. typedef enum sg_color_mask {
  2008. _SG_COLORMASK_DEFAULT = 0, // value 0 reserved for default-init
  2009. SG_COLORMASK_NONE = 0x10, // special value for 'all channels disabled
  2010. SG_COLORMASK_R = 0x1,
  2011. SG_COLORMASK_G = 0x2,
  2012. SG_COLORMASK_RG = 0x3,
  2013. SG_COLORMASK_B = 0x4,
  2014. SG_COLORMASK_RB = 0x5,
  2015. SG_COLORMASK_GB = 0x6,
  2016. SG_COLORMASK_RGB = 0x7,
  2017. SG_COLORMASK_A = 0x8,
  2018. SG_COLORMASK_RA = 0x9,
  2019. SG_COLORMASK_GA = 0xA,
  2020. SG_COLORMASK_RGA = 0xB,
  2021. SG_COLORMASK_BA = 0xC,
  2022. SG_COLORMASK_RBA = 0xD,
  2023. SG_COLORMASK_GBA = 0xE,
  2024. SG_COLORMASK_RGBA = 0xF,
  2025. _SG_COLORMASK_FORCE_U32 = 0x7FFFFFFF
  2026. } sg_color_mask;
  2027. /*
  2028. sg_load_action
  2029. Defines the load action that should be performed at the start of a render pass:
  2030. SG_LOADACTION_CLEAR: clear the render target
  2031. SG_LOADACTION_LOAD: load the previous content of the render target
  2032. SG_LOADACTION_DONTCARE: leave the render target in an undefined state
  2033. This is used in the sg_pass_action structure.
  2034. The default load action for all pass attachments is SG_LOADACTION_CLEAR,
  2035. with the values rgba = { 0.5f, 0.5f, 0.5f, 1.0f }, depth=1.0f and stencil=0.
  2036. If you want to override the default behaviour, it is important to not
  2037. only set the clear color, but the 'action' field as well (as long as this
  2038. is _SG_LOADACTION_DEFAULT, the value fields will be ignored).
  2039. */
  2040. typedef enum sg_load_action {
  2041. _SG_LOADACTION_DEFAULT,
  2042. SG_LOADACTION_CLEAR,
  2043. SG_LOADACTION_LOAD,
  2044. SG_LOADACTION_DONTCARE,
  2045. _SG_LOADACTION_FORCE_U32 = 0x7FFFFFFF
  2046. } sg_load_action;
  2047. /*
  2048. sg_store_action
  2049. Defines the store action that should be performed at the end of a render pass:
  2050. SG_STOREACTION_STORE: store the rendered content to the color attachment image
  2051. SG_STOREACTION_DONTCARE: allows the GPU to discard the rendered content
  2052. */
  2053. typedef enum sg_store_action {
  2054. _SG_STOREACTION_DEFAULT,
  2055. SG_STOREACTION_STORE,
  2056. SG_STOREACTION_DONTCARE,
  2057. _SG_STOREACTION_FORCE_U32 = 0x7FFFFFFF
  2058. } sg_store_action;
  2059. /*
  2060. sg_pass_action
  2061. The sg_pass_action struct defines the actions to be performed
  2062. at the start and end of a render pass.
  2063. - at the start of the pass: whether the render attachments should be cleared,
  2064. loaded with their previous content, or start in an undefined state
  2065. - for clear operations: the clear value (color, depth, or stencil values)
  2066. - at the end of the pass: whether the rendering result should be
  2067. stored back into the render attachment or discarded
  2068. */
  2069. typedef struct sg_color_attachment_action {
  2070. sg_load_action load_action; // default: SG_LOADACTION_CLEAR
  2071. sg_store_action store_action; // default: SG_STOREACTION_STORE
  2072. sg_color clear_value; // default: { 0.5f, 0.5f, 0.5f, 1.0f }
  2073. } sg_color_attachment_action;
  2074. typedef struct sg_depth_attachment_action {
  2075. sg_load_action load_action; // default: SG_LOADACTION_CLEAR
  2076. sg_store_action store_action; // default: SG_STOREACTION_DONTCARE
  2077. float clear_value; // default: 1.0
  2078. } sg_depth_attachment_action;
  2079. typedef struct sg_stencil_attachment_action {
  2080. sg_load_action load_action; // default: SG_LOADACTION_CLEAR
  2081. sg_store_action store_action; // default: SG_STOREACTION_DONTCARE
  2082. uint8_t clear_value; // default: 0
  2083. } sg_stencil_attachment_action;
  2084. typedef struct sg_pass_action {
  2085. sg_color_attachment_action colors[SG_MAX_COLOR_ATTACHMENTS];
  2086. sg_depth_attachment_action depth;
  2087. sg_stencil_attachment_action stencil;
  2088. } sg_pass_action;
  2089. /*
  2090. sg_swapchain
  2091. Used in sg_begin_pass() to provide details about an external swapchain
  2092. (pixel formats, sample count and backend-API specific render surface objects).
  2093. The following information must be provided:
  2094. - the width and height of the swapchain surfaces in number of pixels,
  2095. - the pixel format of the render- and optional msaa-resolve-surface
  2096. - the pixel format of the optional depth- or depth-stencil-surface
  2097. - the MSAA sample count for the render and depth-stencil surface
  2098. If the pixel formats and MSAA sample counts are left zero-initialized,
  2099. their defaults are taken from the sg_environment struct provided in the
  2100. sg_setup() call.
  2101. The width and height *must* be > 0.
  2102. Additionally the following backend API specific objects must be passed in
  2103. as 'type erased' void pointers:
  2104. GL:
  2105. - on all GL backends, a GL framebuffer object must be provided. This
  2106. can be zero for the default framebuffer.
  2107. D3D11:
  2108. - an ID3D11RenderTargetView for the rendering surface, without
  2109. MSAA rendering this surface will also be displayed
  2110. - an optional ID3D11DepthStencilView for the depth- or depth/stencil
  2111. buffer surface
  2112. - when MSAA rendering is used, another ID3D11RenderTargetView
  2113. which serves as MSAA resolve target and will be displayed
  2114. WebGPU (same as D3D11, except different types)
  2115. - a WGPUTextureView for the rendering surface, without
  2116. MSAA rendering this surface will also be displayed
  2117. - an optional WGPUTextureView for the depth- or depth/stencil
  2118. buffer surface
  2119. - when MSAA rendering is used, another WGPUTextureView
  2120. which serves as MSAA resolve target and will be displayed
  2121. Metal (NOTE that the roles of provided surfaces is slightly different
  2122. than on D3D11 or WebGPU in case of MSAA vs non-MSAA rendering):
  2123. - A current CAMetalDrawable (NOT an MTLDrawable!) which will be presented.
  2124. This will either be rendered to directly (if no MSAA is used), or serve
  2125. as MSAA-resolve target.
  2126. - an optional MTLTexture for the depth- or depth-stencil buffer
  2127. - an optional multisampled MTLTexture which serves as intermediate
  2128. rendering surface which will then be resolved into the
  2129. CAMetalDrawable.
  2130. NOTE that for Metal you must use an ObjC __bridge cast to
  2131. properly tunnel the ObjC object id through a C void*, e.g.:
  2132. swapchain.metal.current_drawable = (__bridge const void*) [mtkView currentDrawable];
  2133. On all other backends you shouldn't need to mess with the reference count.
  2134. It's a good practice to write a helper function which returns an initialized
  2135. sg_swapchain structs, which can then be plugged directly into
  2136. sg_pass.swapchain. Look at the function sglue_swapchain() in the sokol_glue.h
  2137. as an example.
  2138. */
  2139. typedef struct sg_metal_swapchain {
  2140. const void* current_drawable; // CAMetalDrawable (NOT MTLDrawable!!!)
  2141. const void* depth_stencil_texture; // MTLTexture
  2142. const void* msaa_color_texture; // MTLTexture
  2143. } sg_metal_swapchain;
  2144. typedef struct sg_d3d11_swapchain {
  2145. const void* render_view; // ID3D11RenderTargetView
  2146. const void* resolve_view; // ID3D11RenderTargetView
  2147. const void* depth_stencil_view; // ID3D11DepthStencilView
  2148. } sg_d3d11_swapchain;
  2149. typedef struct sg_wgpu_swapchain {
  2150. const void* render_view; // WGPUTextureView
  2151. const void* resolve_view; // WGPUTextureView
  2152. const void* depth_stencil_view; // WGPUTextureView
  2153. } sg_wgpu_swapchain;
  2154. typedef struct sg_gl_swapchain {
  2155. uint32_t framebuffer; // GL framebuffer object
  2156. } sg_gl_swapchain;
  2157. typedef struct sg_swapchain {
  2158. int width;
  2159. int height;
  2160. int sample_count;
  2161. sg_pixel_format color_format;
  2162. sg_pixel_format depth_format;
  2163. sg_metal_swapchain metal;
  2164. sg_d3d11_swapchain d3d11;
  2165. sg_wgpu_swapchain wgpu;
  2166. sg_gl_swapchain gl;
  2167. } sg_swapchain;
  2168. /*
  2169. sg_pass
  2170. The sg_pass structure is passed as argument into the sg_begin_pass()
  2171. function.
  2172. For an offscreen rendering pass, an sg_pass_action struct and sg_attachments
  2173. object must be provided, and for swapchain passes, an sg_pass_action and
  2174. an sg_swapchain struct. It is an error to provide both an sg_attachments
  2175. handle and an initialized sg_swapchain struct in the same sg_begin_pass().
  2176. An sg_begin_pass() call for an offscreen pass would look like this (where
  2177. `attachments` is an sg_attachments handle):
  2178. sg_begin_pass(&(sg_pass){
  2179. .action = { ... },
  2180. .attachments = attachments,
  2181. });
  2182. ...and a swapchain render pass would look like this (using the sokol_glue.h
  2183. helper function sglue_swapchain() which gets the swapchain properties from
  2184. sokol_app.h):
  2185. sg_begin_pass(&(sg_pass){
  2186. .action = { ... },
  2187. .swapchain = sglue_swapchain(),
  2188. });
  2189. You can also omit the .action object to get default pass action behaviour
  2190. (clear to color=grey, depth=1 and stencil=0).
  2191. */
  2192. typedef struct sg_pass {
  2193. uint32_t _start_canary;
  2194. sg_pass_action action;
  2195. sg_attachments attachments;
  2196. sg_swapchain swapchain;
  2197. const char* label;
  2198. uint32_t _end_canary;
  2199. } sg_pass;
  2200. /*
  2201. sg_bindings
  2202. The sg_bindings structure defines the buffers, images and
  2203. samplers resource bindings for the next draw call.
  2204. To update the resource bindings, call sg_apply_bindings() with
  2205. a pointer to a populated sg_bindings struct. Note that
  2206. sg_apply_bindings() must be called after sg_apply_pipeline()
  2207. and that bindings are not preserved across sg_apply_pipeline()
  2208. calls, even when the new pipeline uses the same 'bindings layout'.
  2209. A resource binding struct contains:
  2210. - 1..N vertex buffers
  2211. - 0..N vertex buffer offsets
  2212. - 0..1 index buffers
  2213. - 0..1 index buffer offsets
  2214. - 0..N images
  2215. - 0..N samplers
  2216. - 0..N storage buffers
  2217. Where 'N' is defined in the following constants:
  2218. - SG_MAX_VERTEXBUFFER_BINDSLOTS
  2219. - SG_MAX_IMAGE_BINDLOTS
  2220. - SG_MAX_SAMPLER_BINDSLOTS
  2221. - SG_MAX_STORAGEBUFFER_BINDGLOTS
  2222. When using sokol-shdc for shader authoring, the `layout(binding=N)`
  2223. annotation in the shader code directly maps to the slot index for that
  2224. resource type in the bindings struct, for instance the following vertex-
  2225. and fragment-shader interface for sokol-shdc:
  2226. @vs vs
  2227. layout(binding=0) uniform vs_params { ... };
  2228. layout(binding=0) readonly buffer ssbo { ... };
  2229. layout(binding=0) uniform texture2D vs_tex;
  2230. layout(binding=0) uniform sampler vs_smp;
  2231. ...
  2232. @end
  2233. @fs fs
  2234. layout(binding=1) uniform fs_params { ... };
  2235. layout(binding=1) uniform texture2D fs_tex;
  2236. layout(binding=1) uniform sampler fs_smp;
  2237. ...
  2238. @end
  2239. ...would map to the following sg_bindings struct:
  2240. const sg_bindings bnd = {
  2241. .vertex_buffers[0] = ...,
  2242. .images[0] = vs_tex,
  2243. .images[1] = fs_tex,
  2244. .samplers[0] = vs_smp,
  2245. .samplers[1] = fs_smp,
  2246. .storage_buffers[0] = ssbo,
  2247. };
  2248. ...alternatively you can use code-generated slot indices:
  2249. const sg_bindings bnd = {
  2250. .vertex_buffers[0] = ...,
  2251. .images[IMG_vs_tex] = vs_tex,
  2252. .images[IMG_fs_tex] = fs_tex,
  2253. .samplers[SMP_vs_smp] = vs_smp,
  2254. .samplers[SMP_fs_smp] = fs_smp,
  2255. .storage_buffers[SBUF_ssbo] = ssbo,
  2256. };
  2257. Resource bindslots for a specific shader/pipeline may have gaps, and an
  2258. sg_bindings struct may have populated bind slots which are not used by a
  2259. specific shader. This allows to use the same sg_bindings struct across
  2260. different shader variants.
  2261. When not using sokol-shdc, the bindslot indices in the sg_bindings
  2262. struct need to match the per-resource reflection info slot indices
  2263. in the sg_shader_desc struct (for details about that see the
  2264. sg_shader_desc struct documentation).
  2265. The optional buffer offsets can be used to put different unrelated
  2266. chunks of vertex- and/or index-data into the same buffer objects.
  2267. */
  2268. typedef struct sg_bindings {
  2269. uint32_t _start_canary;
  2270. sg_buffer vertex_buffers[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  2271. int vertex_buffer_offsets[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  2272. sg_buffer index_buffer;
  2273. int index_buffer_offset;
  2274. sg_image images[SG_MAX_IMAGE_BINDSLOTS];
  2275. sg_sampler samplers[SG_MAX_SAMPLER_BINDSLOTS];
  2276. sg_buffer storage_buffers[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  2277. uint32_t _end_canary;
  2278. } sg_bindings;
  2279. /*
  2280. sg_buffer_desc
  2281. Creation parameters for sg_buffer objects, used in the
  2282. sg_make_buffer() call.
  2283. The default configuration is:
  2284. .size: 0 (*must* be >0 for buffers without data)
  2285. .type: SG_BUFFERTYPE_VERTEXBUFFER
  2286. .usage: SG_USAGE_IMMUTABLE
  2287. .data.ptr 0 (*must* be valid for immutable buffers)
  2288. .data.size 0 (*must* be > 0 for immutable buffers)
  2289. .label 0 (optional string label)
  2290. For immutable buffers which are initialized with initial data,
  2291. keep the .size item zero-initialized, and set the size together with the
  2292. pointer to the initial data in the .data item.
  2293. For mutable buffers without initial data, keep the .data item
  2294. zero-initialized, and set the buffer size in the .size item instead.
  2295. You can also set both size values, but currently both size values must
  2296. be identical (this may change in the future when the dynamic resource
  2297. management may become more flexible).
  2298. ADVANCED TOPIC: Injecting native 3D-API buffers:
  2299. The following struct members allow to inject your own GL, Metal
  2300. or D3D11 buffers into sokol_gfx:
  2301. .gl_buffers[SG_NUM_INFLIGHT_FRAMES]
  2302. .mtl_buffers[SG_NUM_INFLIGHT_FRAMES]
  2303. .d3d11_buffer
  2304. You must still provide all other struct items except the .data item, and
  2305. these must match the creation parameters of the native buffers you
  2306. provide. For SG_USAGE_IMMUTABLE, only provide a single native 3D-API
  2307. buffer, otherwise you need to provide SG_NUM_INFLIGHT_FRAMES buffers
  2308. (only for GL and Metal, not D3D11). Providing multiple buffers for GL and
  2309. Metal is necessary because sokol_gfx will rotate through them when
  2310. calling sg_update_buffer() to prevent lock-stalls.
  2311. Note that it is expected that immutable injected buffer have already been
  2312. initialized with content, and the .content member must be 0!
  2313. Also you need to call sg_reset_state_cache() after calling native 3D-API
  2314. functions, and before calling any sokol_gfx function.
  2315. */
  2316. typedef struct sg_buffer_desc {
  2317. uint32_t _start_canary;
  2318. size_t size;
  2319. sg_buffer_type type;
  2320. sg_usage usage;
  2321. sg_range data;
  2322. const char* label;
  2323. // optionally inject backend-specific resources
  2324. uint32_t gl_buffers[SG_NUM_INFLIGHT_FRAMES];
  2325. const void* mtl_buffers[SG_NUM_INFLIGHT_FRAMES];
  2326. const void* d3d11_buffer;
  2327. const void* wgpu_buffer;
  2328. uint32_t _end_canary;
  2329. } sg_buffer_desc;
  2330. /*
  2331. sg_image_data
  2332. Defines the content of an image through a 2D array of sg_range structs.
  2333. The first array dimension is the cubemap face, and the second array
  2334. dimension the mipmap level.
  2335. */
  2336. typedef struct sg_image_data {
  2337. sg_range subimage[SG_CUBEFACE_NUM][SG_MAX_MIPMAPS];
  2338. } sg_image_data;
  2339. /*
  2340. sg_image_desc
  2341. Creation parameters for sg_image objects, used in the sg_make_image() call.
  2342. The default configuration is:
  2343. .type: SG_IMAGETYPE_2D
  2344. .render_target: false
  2345. .width 0 (must be set to >0)
  2346. .height 0 (must be set to >0)
  2347. .num_slices 1 (3D textures: depth; array textures: number of layers)
  2348. .num_mipmaps: 1
  2349. .usage: SG_USAGE_IMMUTABLE
  2350. .pixel_format: SG_PIXELFORMAT_RGBA8 for textures, or sg_desc.environment.defaults.color_format for render targets
  2351. .sample_count: 1 for textures, or sg_desc.environment.defaults.sample_count for render targets
  2352. .data an sg_image_data struct to define the initial content
  2353. .label 0 (optional string label for trace hooks)
  2354. Q: Why is the default sample_count for render targets identical with the
  2355. "default sample count" from sg_desc.environment.defaults.sample_count?
  2356. A: So that it matches the default sample count in pipeline objects. Even
  2357. though it is a bit strange/confusing that offscreen render targets by default
  2358. get the same sample count as 'default swapchains', but it's better that
  2359. an offscreen render target created with default parameters matches
  2360. a pipeline object created with default parameters.
  2361. NOTE:
  2362. Images with usage SG_USAGE_IMMUTABLE must be fully initialized by
  2363. providing a valid .data member which points to initialization data.
  2364. ADVANCED TOPIC: Injecting native 3D-API textures:
  2365. The following struct members allow to inject your own GL, Metal or D3D11
  2366. textures into sokol_gfx:
  2367. .gl_textures[SG_NUM_INFLIGHT_FRAMES]
  2368. .mtl_textures[SG_NUM_INFLIGHT_FRAMES]
  2369. .d3d11_texture
  2370. .d3d11_shader_resource_view
  2371. .wgpu_texture
  2372. .wgpu_texture_view
  2373. For GL, you can also specify the texture target or leave it empty to use
  2374. the default texture target for the image type (GL_TEXTURE_2D for
  2375. SG_IMAGETYPE_2D etc)
  2376. For D3D11 and WebGPU, either only provide a texture, or both a texture and
  2377. shader-resource-view / texture-view object. If you want to use access the
  2378. injected texture in a shader you *must* provide a shader-resource-view.
  2379. The same rules apply as for injecting native buffers (see sg_buffer_desc
  2380. documentation for more details).
  2381. */
  2382. typedef struct sg_image_desc {
  2383. uint32_t _start_canary;
  2384. sg_image_type type;
  2385. bool render_target;
  2386. int width;
  2387. int height;
  2388. int num_slices;
  2389. int num_mipmaps;
  2390. sg_usage usage;
  2391. sg_pixel_format pixel_format;
  2392. int sample_count;
  2393. sg_image_data data;
  2394. const char* label;
  2395. // optionally inject backend-specific resources
  2396. uint32_t gl_textures[SG_NUM_INFLIGHT_FRAMES];
  2397. uint32_t gl_texture_target;
  2398. const void* mtl_textures[SG_NUM_INFLIGHT_FRAMES];
  2399. const void* d3d11_texture;
  2400. const void* d3d11_shader_resource_view;
  2401. const void* wgpu_texture;
  2402. const void* wgpu_texture_view;
  2403. uint32_t _end_canary;
  2404. } sg_image_desc;
  2405. /*
  2406. sg_sampler_desc
  2407. Creation parameters for sg_sampler objects, used in the sg_make_sampler() call
  2408. .min_filter: SG_FILTER_NEAREST
  2409. .mag_filter: SG_FILTER_NEAREST
  2410. .mipmap_filter SG_FILTER_NEAREST
  2411. .wrap_u: SG_WRAP_REPEAT
  2412. .wrap_v: SG_WRAP_REPEAT
  2413. .wrap_w: SG_WRAP_REPEAT (only SG_IMAGETYPE_3D)
  2414. .min_lod 0.0f
  2415. .max_lod FLT_MAX
  2416. .border_color SG_BORDERCOLOR_OPAQUE_BLACK
  2417. .compare SG_COMPAREFUNC_NEVER
  2418. .max_anisotropy 1 (must be 1..16)
  2419. */
  2420. typedef struct sg_sampler_desc {
  2421. uint32_t _start_canary;
  2422. sg_filter min_filter;
  2423. sg_filter mag_filter;
  2424. sg_filter mipmap_filter;
  2425. sg_wrap wrap_u;
  2426. sg_wrap wrap_v;
  2427. sg_wrap wrap_w;
  2428. float min_lod;
  2429. float max_lod;
  2430. sg_border_color border_color;
  2431. sg_compare_func compare;
  2432. uint32_t max_anisotropy;
  2433. const char* label;
  2434. // optionally inject backend-specific resources
  2435. uint32_t gl_sampler;
  2436. const void* mtl_sampler;
  2437. const void* d3d11_sampler;
  2438. const void* wgpu_sampler;
  2439. uint32_t _end_canary;
  2440. } sg_sampler_desc;
  2441. /*
  2442. sg_shader_desc
  2443. Used as parameter of sg_make_shader() to create a shader object which
  2444. communicates shader source or bytecode and shader interface
  2445. reflection information to sokol-gfx.
  2446. If you use sokol-shdc you can ignore the following information since
  2447. the sg_shader_desc struct will be code generated.
  2448. Otherwise you need to provide the following information to the
  2449. sg_make_shader() call:
  2450. - a vertex- and fragment-shader function:
  2451. - the shader source or bytecode
  2452. - an optional entry point name
  2453. - for D3D11: an optional compile target when source code is provided
  2454. (the defaults are "vs_4_0" and "ps_4_0")
  2455. - vertex attributes required by some backends:
  2456. - for the GL backend: optional vertex attribute names
  2457. used for name lookup
  2458. - for the D3D11 backend: semantic names and indices
  2459. - reflection information for each uniform block used by the shader:
  2460. - the shader stage the uniform block appears in (SG_SHADERSTAGE_*)
  2461. - the size in bytes of the uniform block
  2462. - backend-specific bindslots:
  2463. - HLSL: the constant buffer register `register(b0..7)`
  2464. - MSL: the buffer attribute `[[buffer(0..7)]]`
  2465. - WGSL: the binding in `@group(0) @binding(0..15)`
  2466. - GLSL only: a description of the uniform block interior
  2467. - the memory layout standard (SG_UNIFORMLAYOUT_*)
  2468. - for each member in the uniform block:
  2469. - the member type (SG_UNIFORM_*)
  2470. - if the member is an array, the array count
  2471. - the member name
  2472. - reflection information for each texture used by the shader:
  2473. - the shader stage the texture appears in (SG_SHADERSTAGE_*)
  2474. - the image type (SG_IMAGETYPE_*)
  2475. - the image-sample type (SG_IMAGESAMPLETYPE_*)
  2476. - whether the texture is multisampled
  2477. - backend specific bindslots:
  2478. - HLSL: the texture register `register(t0..23)`
  2479. - MSL: the texture attribute `[[texture(0..15)]]`
  2480. - WGSL: the binding in `@group(1) @binding(0..127)`
  2481. - reflection information for each sampler used by the shader:
  2482. - the shader stage the sampler appears in (SG_SHADERSTAGE_*)
  2483. - the sampler type (SG_SAMPLERTYPE_*)
  2484. - backend specific bindslots:
  2485. - HLSL: the sampler register `register(s0..15)`
  2486. - MSL: the sampler attribute `[[sampler(0..15)]]`
  2487. - WGSL: the binding in `@group(0) @binding(0..127)`
  2488. - reflection information for each storage buffer used by the shader:
  2489. - the shader stage the storage buffer appears in (SG_SHADERSTAGE_*)
  2490. - whether the storage buffer is readonly (currently this must
  2491. always be true)
  2492. - backend specific bindslots:
  2493. - HLSL: the texture(sic) register `register(t0..23)`
  2494. - MSL: the buffer attribute `[[buffer(8..15)]]`
  2495. - WGSL: the binding in `@group(1) @binding(0..127)`
  2496. - GL: the binding in `layout(binding=0..7)`
  2497. - reflection information for each combined image-sampler object
  2498. used by the shader:
  2499. - the shader stage (SG_SHADERSTAGE_*)
  2500. - the texture's array index in the sg_shader_desc.images[] array
  2501. - the sampler's array index in the sg_shader_desc.samplers[] array
  2502. - GLSL only: the name of the combined image-sampler object
  2503. The number and order of items in the sg_shader_desc.attrs[]
  2504. array corresponds to the items in sg_pipeline_desc.layout.attrs.
  2505. - sg_shader_desc.attrs[N] => sg_pipeline_desc.layout.attrs[N]
  2506. NOTE that vertex attribute indices currently cannot have gaps.
  2507. The items index in the sg_shader_desc.uniform_blocks[] array corresponds
  2508. to the ub_slot arg in sg_apply_uniforms():
  2509. - sg_shader_desc.uniform_blocks[N] => sg_apply_uniforms(N, ...)
  2510. The items in the shader_desc images, samplers and storage_buffers
  2511. arrays correspond to the same array items in the sg_bindings struct:
  2512. - sg_shader_desc.images[N] => sg_bindings.images[N]
  2513. - sg_shader_desc.samplers[N] => sg_bindings.samplers[N]
  2514. - sg_shader_desc.storage_buffers[N] => sg_bindings.storage_buffers[N]
  2515. For all GL backends, shader source-code must be provided. For D3D11 and Metal,
  2516. either shader source-code or byte-code can be provided.
  2517. NOTE that the uniform block, image, sampler and storage_buffer arrays
  2518. can have gaps. This allows to use the same sg_bindings struct for
  2519. different related shader variants.
  2520. For D3D11, if source code is provided, the d3dcompiler_47.dll will be loaded
  2521. on demand. If this fails, shader creation will fail. When compiling HLSL
  2522. source code, you can provide an optional target string via
  2523. sg_shader_stage_desc.d3d11_target, the default target is "vs_4_0" for the
  2524. vertex shader stage and "ps_4_0" for the pixel shader stage.
  2525. */
  2526. typedef enum sg_shader_stage {
  2527. SG_SHADERSTAGE_NONE,
  2528. SG_SHADERSTAGE_VERTEX,
  2529. SG_SHADERSTAGE_FRAGMENT,
  2530. } sg_shader_stage;
  2531. typedef struct sg_shader_function {
  2532. const char* source;
  2533. sg_range bytecode;
  2534. const char* entry;
  2535. const char* d3d11_target; // default: "vs_4_0" or "ps_4_0"
  2536. } sg_shader_function;
  2537. typedef struct sg_shader_vertex_attr {
  2538. const char* glsl_name; // [optional] GLSL attribute name
  2539. const char* hlsl_sem_name; // HLSL semantic name
  2540. uint8_t hlsl_sem_index; // HLSL semantic index
  2541. } sg_shader_vertex_attr;
  2542. typedef struct sg_glsl_shader_uniform {
  2543. sg_uniform_type type;
  2544. uint16_t array_count; // 0 or 1 for scalars, >1 for arrays
  2545. const char* glsl_name; // glsl name binding is required on GL 4.1 and WebGL2
  2546. } sg_glsl_shader_uniform;
  2547. typedef struct sg_shader_uniform_block {
  2548. sg_shader_stage stage;
  2549. uint32_t size;
  2550. uint8_t hlsl_register_b_n; // HLSL register(bn)
  2551. uint8_t msl_buffer_n; // MSL [[buffer(n)]]
  2552. uint8_t wgsl_group0_binding_n; // WGSL @group(0) @binding(n)
  2553. sg_uniform_layout layout;
  2554. sg_glsl_shader_uniform glsl_uniforms[SG_MAX_UNIFORMBLOCK_MEMBERS];
  2555. } sg_shader_uniform_block;
  2556. typedef struct sg_shader_image {
  2557. sg_shader_stage stage;
  2558. sg_image_type image_type;
  2559. sg_image_sample_type sample_type;
  2560. bool multisampled;
  2561. uint8_t hlsl_register_t_n; // HLSL register(tn) bind slot
  2562. uint8_t msl_texture_n; // MSL [[texture(n)]] bind slot
  2563. uint8_t wgsl_group1_binding_n; // WGSL @group(1) @binding(n) bind slot
  2564. } sg_shader_image;
  2565. typedef struct sg_shader_sampler {
  2566. sg_shader_stage stage;
  2567. sg_sampler_type sampler_type;
  2568. uint8_t hlsl_register_s_n; // HLSL register(sn) bind slot
  2569. uint8_t msl_sampler_n; // MSL [[sampler(n)]] bind slot
  2570. uint8_t wgsl_group1_binding_n; // WGSL @group(1) @binding(n) bind slot
  2571. } sg_shader_sampler;
  2572. typedef struct sg_shader_storage_buffer {
  2573. sg_shader_stage stage;
  2574. bool readonly;
  2575. uint8_t hlsl_register_t_n; // HLSL register(tn) bind slot
  2576. uint8_t msl_buffer_n; // MSL [[buffer(n)]] bind slot
  2577. uint8_t wgsl_group1_binding_n; // WGSL @group(1) @binding(n) bind slot
  2578. uint8_t glsl_binding_n; // GLSL layout(binding=n)
  2579. } sg_shader_storage_buffer;
  2580. typedef struct sg_shader_image_sampler_pair {
  2581. sg_shader_stage stage;
  2582. uint8_t image_slot;
  2583. uint8_t sampler_slot;
  2584. const char* glsl_name; // glsl name binding required because of GL 4.1 and WebGL2
  2585. } sg_shader_image_sampler_pair;
  2586. typedef struct sg_shader_desc {
  2587. uint32_t _start_canary;
  2588. sg_shader_function vertex_func;
  2589. sg_shader_function fragment_func;
  2590. sg_shader_vertex_attr attrs[SG_MAX_VERTEX_ATTRIBUTES];
  2591. sg_shader_uniform_block uniform_blocks[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  2592. sg_shader_storage_buffer storage_buffers[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  2593. sg_shader_image images[SG_MAX_IMAGE_BINDSLOTS];
  2594. sg_shader_sampler samplers[SG_MAX_SAMPLER_BINDSLOTS];
  2595. sg_shader_image_sampler_pair image_sampler_pairs[SG_MAX_IMAGE_SAMPLER_PAIRS];
  2596. const char* label;
  2597. uint32_t _end_canary;
  2598. } sg_shader_desc;
  2599. /*
  2600. sg_pipeline_desc
  2601. The sg_pipeline_desc struct defines all creation parameters for an
  2602. sg_pipeline object, used as argument to the sg_make_pipeline() function:
  2603. - the vertex layout for all input vertex buffers
  2604. - a shader object
  2605. - the 3D primitive type (points, lines, triangles, ...)
  2606. - the index type (none, 16- or 32-bit)
  2607. - all the fixed-function-pipeline state (depth-, stencil-, blend-state, etc...)
  2608. If the vertex data has no gaps between vertex components, you can omit
  2609. the .layout.buffers[].stride and layout.attrs[].offset items (leave them
  2610. default-initialized to 0), sokol-gfx will then compute the offsets and
  2611. strides from the vertex component formats (.layout.attrs[].format).
  2612. Please note that ALL vertex attribute offsets must be 0 in order for the
  2613. automatic offset computation to kick in.
  2614. The default configuration is as follows:
  2615. .shader: 0 (must be initialized with a valid sg_shader id!)
  2616. .layout:
  2617. .buffers[]: vertex buffer layouts
  2618. .stride: 0 (if no stride is given it will be computed)
  2619. .step_func SG_VERTEXSTEP_PER_VERTEX
  2620. .step_rate 1
  2621. .attrs[]: vertex attribute declarations
  2622. .buffer_index 0 the vertex buffer bind slot
  2623. .offset 0 (offsets can be omitted if the vertex layout has no gaps)
  2624. .format SG_VERTEXFORMAT_INVALID (must be initialized!)
  2625. .depth:
  2626. .pixel_format: sg_desc.context.depth_format
  2627. .compare: SG_COMPAREFUNC_ALWAYS
  2628. .write_enabled: false
  2629. .bias: 0.0f
  2630. .bias_slope_scale: 0.0f
  2631. .bias_clamp: 0.0f
  2632. .stencil:
  2633. .enabled: false
  2634. .front/back:
  2635. .compare: SG_COMPAREFUNC_ALWAYS
  2636. .fail_op: SG_STENCILOP_KEEP
  2637. .depth_fail_op: SG_STENCILOP_KEEP
  2638. .pass_op: SG_STENCILOP_KEEP
  2639. .read_mask: 0
  2640. .write_mask: 0
  2641. .ref: 0
  2642. .color_count 1
  2643. .colors[0..color_count]
  2644. .pixel_format sg_desc.context.color_format
  2645. .write_mask: SG_COLORMASK_RGBA
  2646. .blend:
  2647. .enabled: false
  2648. .src_factor_rgb: SG_BLENDFACTOR_ONE
  2649. .dst_factor_rgb: SG_BLENDFACTOR_ZERO
  2650. .op_rgb: SG_BLENDOP_ADD
  2651. .src_factor_alpha: SG_BLENDFACTOR_ONE
  2652. .dst_factor_alpha: SG_BLENDFACTOR_ZERO
  2653. .op_alpha: SG_BLENDOP_ADD
  2654. .primitive_type: SG_PRIMITIVETYPE_TRIANGLES
  2655. .index_type: SG_INDEXTYPE_NONE
  2656. .cull_mode: SG_CULLMODE_NONE
  2657. .face_winding: SG_FACEWINDING_CW
  2658. .sample_count: sg_desc.context.sample_count
  2659. .blend_color: (sg_color) { 0.0f, 0.0f, 0.0f, 0.0f }
  2660. .alpha_to_coverage_enabled: false
  2661. .label 0 (optional string label for trace hooks)
  2662. */
  2663. typedef struct sg_vertex_buffer_layout_state {
  2664. int stride;
  2665. sg_vertex_step step_func;
  2666. int step_rate;
  2667. } sg_vertex_buffer_layout_state;
  2668. typedef struct sg_vertex_attr_state {
  2669. int buffer_index;
  2670. int offset;
  2671. sg_vertex_format format;
  2672. } sg_vertex_attr_state;
  2673. typedef struct sg_vertex_layout_state {
  2674. sg_vertex_buffer_layout_state buffers[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  2675. sg_vertex_attr_state attrs[SG_MAX_VERTEX_ATTRIBUTES];
  2676. } sg_vertex_layout_state;
  2677. typedef struct sg_stencil_face_state {
  2678. sg_compare_func compare;
  2679. sg_stencil_op fail_op;
  2680. sg_stencil_op depth_fail_op;
  2681. sg_stencil_op pass_op;
  2682. } sg_stencil_face_state;
  2683. typedef struct sg_stencil_state {
  2684. bool enabled;
  2685. sg_stencil_face_state front;
  2686. sg_stencil_face_state back;
  2687. uint8_t read_mask;
  2688. uint8_t write_mask;
  2689. uint8_t ref;
  2690. } sg_stencil_state;
  2691. typedef struct sg_depth_state {
  2692. sg_pixel_format pixel_format;
  2693. sg_compare_func compare;
  2694. bool write_enabled;
  2695. float bias;
  2696. float bias_slope_scale;
  2697. float bias_clamp;
  2698. } sg_depth_state;
  2699. typedef struct sg_blend_state {
  2700. bool enabled;
  2701. sg_blend_factor src_factor_rgb;
  2702. sg_blend_factor dst_factor_rgb;
  2703. sg_blend_op op_rgb;
  2704. sg_blend_factor src_factor_alpha;
  2705. sg_blend_factor dst_factor_alpha;
  2706. sg_blend_op op_alpha;
  2707. } sg_blend_state;
  2708. typedef struct sg_color_target_state {
  2709. sg_pixel_format pixel_format;
  2710. sg_color_mask write_mask;
  2711. sg_blend_state blend;
  2712. } sg_color_target_state;
  2713. typedef struct sg_pipeline_desc {
  2714. uint32_t _start_canary;
  2715. sg_shader shader;
  2716. sg_vertex_layout_state layout;
  2717. sg_depth_state depth;
  2718. sg_stencil_state stencil;
  2719. int color_count;
  2720. sg_color_target_state colors[SG_MAX_COLOR_ATTACHMENTS];
  2721. sg_primitive_type primitive_type;
  2722. sg_index_type index_type;
  2723. sg_cull_mode cull_mode;
  2724. sg_face_winding face_winding;
  2725. int sample_count;
  2726. sg_color blend_color;
  2727. bool alpha_to_coverage_enabled;
  2728. const char* label;
  2729. uint32_t _end_canary;
  2730. } sg_pipeline_desc;
  2731. /*
  2732. sg_attachments_desc
  2733. Creation parameters for an sg_attachments object, used as argument to the
  2734. sg_make_attachments() function.
  2735. An attachments object bundles 0..4 color attachments, 0..4 msaa-resolve
  2736. attachments, and none or one depth-stencil attachmente for use
  2737. in a render pass. At least one color attachment or one depth-stencil
  2738. attachment must be provided (no color attachment and a depth-stencil
  2739. attachment is useful for a depth-only render pass).
  2740. Each attachment definition consists of an image object, and two additional indices
  2741. describing which subimage the pass will render into: one mipmap index, and if the image
  2742. is a cubemap, array-texture or 3D-texture, the face-index, array-layer or
  2743. depth-slice.
  2744. All attachments must have the same width and height.
  2745. All color attachments and the depth-stencil attachment must have the
  2746. same sample count.
  2747. If a resolve attachment is set, an MSAA-resolve operation from the
  2748. associated color attachment image into the resolve attachment image will take
  2749. place in the sg_end_pass() function. In this case, the color attachment
  2750. must have a (sample_count>1), and the resolve attachment a
  2751. (sample_count==1). The resolve attachment also must have the same pixel
  2752. format as the color attachment.
  2753. NOTE that MSAA depth-stencil attachments cannot be msaa-resolved!
  2754. */
  2755. typedef struct sg_attachment_desc {
  2756. sg_image image;
  2757. int mip_level;
  2758. int slice; // cube texture: face; array texture: layer; 3D texture: slice
  2759. } sg_attachment_desc;
  2760. typedef struct sg_attachments_desc {
  2761. uint32_t _start_canary;
  2762. sg_attachment_desc colors[SG_MAX_COLOR_ATTACHMENTS];
  2763. sg_attachment_desc resolves[SG_MAX_COLOR_ATTACHMENTS];
  2764. sg_attachment_desc depth_stencil;
  2765. const char* label;
  2766. uint32_t _end_canary;
  2767. } sg_attachments_desc;
  2768. /*
  2769. sg_trace_hooks
  2770. Installable callback functions to keep track of the sokol-gfx calls,
  2771. this is useful for debugging, or keeping track of resource creation
  2772. and destruction.
  2773. Trace hooks are installed with sg_install_trace_hooks(), this returns
  2774. another sg_trace_hooks struct with the previous set of
  2775. trace hook function pointers. These should be invoked by the
  2776. new trace hooks to form a proper call chain.
  2777. */
  2778. typedef struct sg_trace_hooks {
  2779. void* user_data;
  2780. void (*reset_state_cache)(void* user_data);
  2781. void (*make_buffer)(const sg_buffer_desc* desc, sg_buffer result, void* user_data);
  2782. void (*make_image)(const sg_image_desc* desc, sg_image result, void* user_data);
  2783. void (*make_sampler)(const sg_sampler_desc* desc, sg_sampler result, void* user_data);
  2784. void (*make_shader)(const sg_shader_desc* desc, sg_shader result, void* user_data);
  2785. void (*make_pipeline)(const sg_pipeline_desc* desc, sg_pipeline result, void* user_data);
  2786. void (*make_attachments)(const sg_attachments_desc* desc, sg_attachments result, void* user_data);
  2787. void (*destroy_buffer)(sg_buffer buf, void* user_data);
  2788. void (*destroy_image)(sg_image img, void* user_data);
  2789. void (*destroy_sampler)(sg_sampler smp, void* user_data);
  2790. void (*destroy_shader)(sg_shader shd, void* user_data);
  2791. void (*destroy_pipeline)(sg_pipeline pip, void* user_data);
  2792. void (*destroy_attachments)(sg_attachments atts, void* user_data);
  2793. void (*update_buffer)(sg_buffer buf, const sg_range* data, void* user_data);
  2794. void (*update_image)(sg_image img, const sg_image_data* data, void* user_data);
  2795. void (*append_buffer)(sg_buffer buf, const sg_range* data, int result, void* user_data);
  2796. void (*begin_pass)(const sg_pass* pass, void* user_data);
  2797. void (*apply_viewport)(int x, int y, int width, int height, bool origin_top_left, void* user_data);
  2798. void (*apply_scissor_rect)(int x, int y, int width, int height, bool origin_top_left, void* user_data);
  2799. void (*apply_pipeline)(sg_pipeline pip, void* user_data);
  2800. void (*apply_bindings)(const sg_bindings* bindings, void* user_data);
  2801. void (*apply_uniforms)(int ub_index, const sg_range* data, void* user_data);
  2802. void (*draw)(int base_element, int num_elements, int num_instances, void* user_data);
  2803. void (*end_pass)(void* user_data);
  2804. void (*commit)(void* user_data);
  2805. void (*alloc_buffer)(sg_buffer result, void* user_data);
  2806. void (*alloc_image)(sg_image result, void* user_data);
  2807. void (*alloc_sampler)(sg_sampler result, void* user_data);
  2808. void (*alloc_shader)(sg_shader result, void* user_data);
  2809. void (*alloc_pipeline)(sg_pipeline result, void* user_data);
  2810. void (*alloc_attachments)(sg_attachments result, void* user_data);
  2811. void (*dealloc_buffer)(sg_buffer buf_id, void* user_data);
  2812. void (*dealloc_image)(sg_image img_id, void* user_data);
  2813. void (*dealloc_sampler)(sg_sampler smp_id, void* user_data);
  2814. void (*dealloc_shader)(sg_shader shd_id, void* user_data);
  2815. void (*dealloc_pipeline)(sg_pipeline pip_id, void* user_data);
  2816. void (*dealloc_attachments)(sg_attachments atts_id, void* user_data);
  2817. void (*init_buffer)(sg_buffer buf_id, const sg_buffer_desc* desc, void* user_data);
  2818. void (*init_image)(sg_image img_id, const sg_image_desc* desc, void* user_data);
  2819. void (*init_sampler)(sg_sampler smp_id, const sg_sampler_desc* desc, void* user_data);
  2820. void (*init_shader)(sg_shader shd_id, const sg_shader_desc* desc, void* user_data);
  2821. void (*init_pipeline)(sg_pipeline pip_id, const sg_pipeline_desc* desc, void* user_data);
  2822. void (*init_attachments)(sg_attachments atts_id, const sg_attachments_desc* desc, void* user_data);
  2823. void (*uninit_buffer)(sg_buffer buf_id, void* user_data);
  2824. void (*uninit_image)(sg_image img_id, void* user_data);
  2825. void (*uninit_sampler)(sg_sampler smp_id, void* user_data);
  2826. void (*uninit_shader)(sg_shader shd_id, void* user_data);
  2827. void (*uninit_pipeline)(sg_pipeline pip_id, void* user_data);
  2828. void (*uninit_attachments)(sg_attachments atts_id, void* user_data);
  2829. void (*fail_buffer)(sg_buffer buf_id, void* user_data);
  2830. void (*fail_image)(sg_image img_id, void* user_data);
  2831. void (*fail_sampler)(sg_sampler smp_id, void* user_data);
  2832. void (*fail_shader)(sg_shader shd_id, void* user_data);
  2833. void (*fail_pipeline)(sg_pipeline pip_id, void* user_data);
  2834. void (*fail_attachments)(sg_attachments atts_id, void* user_data);
  2835. void (*push_debug_group)(const char* name, void* user_data);
  2836. void (*pop_debug_group)(void* user_data);
  2837. } sg_trace_hooks;
  2838. /*
  2839. sg_buffer_info
  2840. sg_image_info
  2841. sg_sampler_info
  2842. sg_shader_info
  2843. sg_pipeline_info
  2844. sg_attachments_info
  2845. These structs contain various internal resource attributes which
  2846. might be useful for debug-inspection. Please don't rely on the
  2847. actual content of those structs too much, as they are quite closely
  2848. tied to sokol_gfx.h internals and may change more frequently than
  2849. the other public API elements.
  2850. The *_info structs are used as the return values of the following functions:
  2851. sg_query_buffer_info()
  2852. sg_query_image_info()
  2853. sg_query_sampler_info()
  2854. sg_query_shader_info()
  2855. sg_query_pipeline_info()
  2856. sg_query_pass_info()
  2857. */
  2858. typedef struct sg_slot_info {
  2859. sg_resource_state state; // the current state of this resource slot
  2860. uint32_t res_id; // type-neutral resource if (e.g. sg_buffer.id)
  2861. } sg_slot_info;
  2862. typedef struct sg_buffer_info {
  2863. sg_slot_info slot; // resource pool slot info
  2864. uint32_t update_frame_index; // frame index of last sg_update_buffer()
  2865. uint32_t append_frame_index; // frame index of last sg_append_buffer()
  2866. int append_pos; // current position in buffer for sg_append_buffer()
  2867. bool append_overflow; // is buffer in overflow state (due to sg_append_buffer)
  2868. int num_slots; // number of renaming-slots for dynamically updated buffers
  2869. int active_slot; // currently active write-slot for dynamically updated buffers
  2870. } sg_buffer_info;
  2871. typedef struct sg_image_info {
  2872. sg_slot_info slot; // resource pool slot info
  2873. uint32_t upd_frame_index; // frame index of last sg_update_image()
  2874. int num_slots; // number of renaming-slots for dynamically updated images
  2875. int active_slot; // currently active write-slot for dynamically updated images
  2876. } sg_image_info;
  2877. typedef struct sg_sampler_info {
  2878. sg_slot_info slot; // resource pool slot info
  2879. } sg_sampler_info;
  2880. typedef struct sg_shader_info {
  2881. sg_slot_info slot; // resource pool slot info
  2882. } sg_shader_info;
  2883. typedef struct sg_pipeline_info {
  2884. sg_slot_info slot; // resource pool slot info
  2885. } sg_pipeline_info;
  2886. typedef struct sg_attachments_info {
  2887. sg_slot_info slot; // resource pool slot info
  2888. } sg_attachments_info;
  2889. /*
  2890. sg_frame_stats
  2891. Allows to track generic and backend-specific stats about a
  2892. render frame. Obtained by calling sg_query_frame_stats(). The returned
  2893. struct contains information about the *previous* frame.
  2894. */
  2895. typedef struct sg_frame_stats_gl {
  2896. uint32_t num_bind_buffer;
  2897. uint32_t num_active_texture;
  2898. uint32_t num_bind_texture;
  2899. uint32_t num_bind_sampler;
  2900. uint32_t num_use_program;
  2901. uint32_t num_render_state;
  2902. uint32_t num_vertex_attrib_pointer;
  2903. uint32_t num_vertex_attrib_divisor;
  2904. uint32_t num_enable_vertex_attrib_array;
  2905. uint32_t num_disable_vertex_attrib_array;
  2906. uint32_t num_uniform;
  2907. } sg_frame_stats_gl;
  2908. typedef struct sg_frame_stats_d3d11_pass {
  2909. uint32_t num_om_set_render_targets;
  2910. uint32_t num_clear_render_target_view;
  2911. uint32_t num_clear_depth_stencil_view;
  2912. uint32_t num_resolve_subresource;
  2913. } sg_frame_stats_d3d11_pass;
  2914. typedef struct sg_frame_stats_d3d11_pipeline {
  2915. uint32_t num_rs_set_state;
  2916. uint32_t num_om_set_depth_stencil_state;
  2917. uint32_t num_om_set_blend_state;
  2918. uint32_t num_ia_set_primitive_topology;
  2919. uint32_t num_ia_set_input_layout;
  2920. uint32_t num_vs_set_shader;
  2921. uint32_t num_vs_set_constant_buffers;
  2922. uint32_t num_ps_set_shader;
  2923. uint32_t num_ps_set_constant_buffers;
  2924. } sg_frame_stats_d3d11_pipeline;
  2925. typedef struct sg_frame_stats_d3d11_bindings {
  2926. uint32_t num_ia_set_vertex_buffers;
  2927. uint32_t num_ia_set_index_buffer;
  2928. uint32_t num_vs_set_shader_resources;
  2929. uint32_t num_ps_set_shader_resources;
  2930. uint32_t num_vs_set_samplers;
  2931. uint32_t num_ps_set_samplers;
  2932. } sg_frame_stats_d3d11_bindings;
  2933. typedef struct sg_frame_stats_d3d11_uniforms {
  2934. uint32_t num_update_subresource;
  2935. } sg_frame_stats_d3d11_uniforms;
  2936. typedef struct sg_frame_stats_d3d11_draw {
  2937. uint32_t num_draw_indexed_instanced;
  2938. uint32_t num_draw_indexed;
  2939. uint32_t num_draw_instanced;
  2940. uint32_t num_draw;
  2941. } sg_frame_stats_d3d11_draw;
  2942. typedef struct sg_frame_stats_d3d11 {
  2943. sg_frame_stats_d3d11_pass pass;
  2944. sg_frame_stats_d3d11_pipeline pipeline;
  2945. sg_frame_stats_d3d11_bindings bindings;
  2946. sg_frame_stats_d3d11_uniforms uniforms;
  2947. sg_frame_stats_d3d11_draw draw;
  2948. uint32_t num_map;
  2949. uint32_t num_unmap;
  2950. } sg_frame_stats_d3d11;
  2951. typedef struct sg_frame_stats_metal_idpool {
  2952. uint32_t num_added;
  2953. uint32_t num_released;
  2954. uint32_t num_garbage_collected;
  2955. } sg_frame_stats_metal_idpool;
  2956. typedef struct sg_frame_stats_metal_pipeline {
  2957. uint32_t num_set_blend_color;
  2958. uint32_t num_set_cull_mode;
  2959. uint32_t num_set_front_facing_winding;
  2960. uint32_t num_set_stencil_reference_value;
  2961. uint32_t num_set_depth_bias;
  2962. uint32_t num_set_render_pipeline_state;
  2963. uint32_t num_set_depth_stencil_state;
  2964. } sg_frame_stats_metal_pipeline;
  2965. typedef struct sg_frame_stats_metal_bindings {
  2966. uint32_t num_set_vertex_buffer;
  2967. uint32_t num_set_vertex_texture;
  2968. uint32_t num_set_vertex_sampler_state;
  2969. uint32_t num_set_fragment_buffer;
  2970. uint32_t num_set_fragment_texture;
  2971. uint32_t num_set_fragment_sampler_state;
  2972. } sg_frame_stats_metal_bindings;
  2973. typedef struct sg_frame_stats_metal_uniforms {
  2974. uint32_t num_set_vertex_buffer_offset;
  2975. uint32_t num_set_fragment_buffer_offset;
  2976. } sg_frame_stats_metal_uniforms;
  2977. typedef struct sg_frame_stats_metal {
  2978. sg_frame_stats_metal_idpool idpool;
  2979. sg_frame_stats_metal_pipeline pipeline;
  2980. sg_frame_stats_metal_bindings bindings;
  2981. sg_frame_stats_metal_uniforms uniforms;
  2982. } sg_frame_stats_metal;
  2983. typedef struct sg_frame_stats_wgpu_uniforms {
  2984. uint32_t num_set_bindgroup;
  2985. uint32_t size_write_buffer;
  2986. } sg_frame_stats_wgpu_uniforms;
  2987. typedef struct sg_frame_stats_wgpu_bindings {
  2988. uint32_t num_set_vertex_buffer;
  2989. uint32_t num_skip_redundant_vertex_buffer;
  2990. uint32_t num_set_index_buffer;
  2991. uint32_t num_skip_redundant_index_buffer;
  2992. uint32_t num_create_bindgroup;
  2993. uint32_t num_discard_bindgroup;
  2994. uint32_t num_set_bindgroup;
  2995. uint32_t num_skip_redundant_bindgroup;
  2996. uint32_t num_bindgroup_cache_hits;
  2997. uint32_t num_bindgroup_cache_misses;
  2998. uint32_t num_bindgroup_cache_collisions;
  2999. uint32_t num_bindgroup_cache_invalidates;
  3000. uint32_t num_bindgroup_cache_hash_vs_key_mismatch;
  3001. } sg_frame_stats_wgpu_bindings;
  3002. typedef struct sg_frame_stats_wgpu {
  3003. sg_frame_stats_wgpu_uniforms uniforms;
  3004. sg_frame_stats_wgpu_bindings bindings;
  3005. } sg_frame_stats_wgpu;
  3006. typedef struct sg_frame_stats {
  3007. uint32_t frame_index; // current frame counter, starts at 0
  3008. uint32_t num_passes;
  3009. uint32_t num_apply_viewport;
  3010. uint32_t num_apply_scissor_rect;
  3011. uint32_t num_apply_pipeline;
  3012. uint32_t num_apply_bindings;
  3013. uint32_t num_apply_uniforms;
  3014. uint32_t num_draw;
  3015. uint32_t num_update_buffer;
  3016. uint32_t num_append_buffer;
  3017. uint32_t num_update_image;
  3018. uint32_t size_apply_uniforms;
  3019. uint32_t size_update_buffer;
  3020. uint32_t size_append_buffer;
  3021. uint32_t size_update_image;
  3022. sg_frame_stats_gl gl;
  3023. sg_frame_stats_d3d11 d3d11;
  3024. sg_frame_stats_metal metal;
  3025. sg_frame_stats_wgpu wgpu;
  3026. } sg_frame_stats;
  3027. /*
  3028. sg_log_item
  3029. An enum with a unique item for each log message, warning, error
  3030. and validation layer message. Note that these messages are only
  3031. visible when a logger function is installed in the sg_setup() call.
  3032. */
  3033. #define _SG_LOG_ITEMS \
  3034. _SG_LOGITEM_XMACRO(OK, "Ok") \
  3035. _SG_LOGITEM_XMACRO(MALLOC_FAILED, "memory allocation failed") \
  3036. _SG_LOGITEM_XMACRO(GL_TEXTURE_FORMAT_NOT_SUPPORTED, "pixel format not supported for texture (gl)") \
  3037. _SG_LOGITEM_XMACRO(GL_3D_TEXTURES_NOT_SUPPORTED, "3d textures not supported (gl)") \
  3038. _SG_LOGITEM_XMACRO(GL_ARRAY_TEXTURES_NOT_SUPPORTED, "array textures not supported (gl)") \
  3039. _SG_LOGITEM_XMACRO(GL_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE, "GLSL storage buffer bindslot is out of range (must be 0..7) (gl)") \
  3040. _SG_LOGITEM_XMACRO(GL_SHADER_COMPILATION_FAILED, "shader compilation failed (gl)") \
  3041. _SG_LOGITEM_XMACRO(GL_SHADER_LINKING_FAILED, "shader linking failed (gl)") \
  3042. _SG_LOGITEM_XMACRO(GL_VERTEX_ATTRIBUTE_NOT_FOUND_IN_SHADER, "vertex attribute not found in shader; NOTE: may be caused by GL driver's GLSL compiler removing unused globals") \
  3043. _SG_LOGITEM_XMACRO(GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER, "uniform block name not found in shader; NOTE: may be caused by GL driver's GLSL compiler removing unused globals") \
  3044. _SG_LOGITEM_XMACRO(GL_IMAGE_SAMPLER_NAME_NOT_FOUND_IN_SHADER, "image-sampler name not found in shader; NOTE: may be caused by GL driver's GLSL compiler removing unused globals") \
  3045. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_UNDEFINED, "framebuffer completeness check failed with GL_FRAMEBUFFER_UNDEFINED (gl)") \
  3046. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_INCOMPLETE_ATTACHMENT, "framebuffer completeness check failed with GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT (gl)") \
  3047. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MISSING_ATTACHMENT, "framebuffer completeness check failed with GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT (gl)") \
  3048. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_UNSUPPORTED, "framebuffer completeness check failed with GL_FRAMEBUFFER_UNSUPPORTED (gl)") \
  3049. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MULTISAMPLE, "framebuffer completeness check failed with GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE (gl)") \
  3050. _SG_LOGITEM_XMACRO(GL_FRAMEBUFFER_STATUS_UNKNOWN, "framebuffer completeness check failed (unknown reason) (gl)") \
  3051. _SG_LOGITEM_XMACRO(D3D11_CREATE_BUFFER_FAILED, "CreateBuffer() failed (d3d11)") \
  3052. _SG_LOGITEM_XMACRO(D3D11_CREATE_BUFFER_SRV_FAILED, "CreateShaderResourceView() failed for storage buffer (d3d11)") \
  3053. _SG_LOGITEM_XMACRO(D3D11_CREATE_DEPTH_TEXTURE_UNSUPPORTED_PIXEL_FORMAT, "pixel format not supported for depth-stencil texture (d3d11)") \
  3054. _SG_LOGITEM_XMACRO(D3D11_CREATE_DEPTH_TEXTURE_FAILED, "CreateTexture2D() failed for depth-stencil texture (d3d11)") \
  3055. _SG_LOGITEM_XMACRO(D3D11_CREATE_2D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT, "pixel format not supported for 2d-, cube- or array-texture (d3d11)") \
  3056. _SG_LOGITEM_XMACRO(D3D11_CREATE_2D_TEXTURE_FAILED, "CreateTexture2D() failed for 2d-, cube- or array-texture (d3d11)") \
  3057. _SG_LOGITEM_XMACRO(D3D11_CREATE_2D_SRV_FAILED, "CreateShaderResourceView() failed for 2d-, cube- or array-texture (d3d11)") \
  3058. _SG_LOGITEM_XMACRO(D3D11_CREATE_3D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT, "pixel format not supported for 3D texture (d3d11)") \
  3059. _SG_LOGITEM_XMACRO(D3D11_CREATE_3D_TEXTURE_FAILED, "CreateTexture3D() failed (d3d11)") \
  3060. _SG_LOGITEM_XMACRO(D3D11_CREATE_3D_SRV_FAILED, "CreateShaderResourceView() failed for 3d texture (d3d11)") \
  3061. _SG_LOGITEM_XMACRO(D3D11_CREATE_MSAA_TEXTURE_FAILED, "CreateTexture2D() failed for MSAA render target texture (d3d11)") \
  3062. _SG_LOGITEM_XMACRO(D3D11_CREATE_SAMPLER_STATE_FAILED, "CreateSamplerState() failed (d3d11)") \
  3063. _SG_LOGITEM_XMACRO(D3D11_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE, "uniform block 'hlsl_register_b_n' is out of range (must be 0..7)") \
  3064. _SG_LOGITEM_XMACRO(D3D11_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE, "storage buffer 'hlsl_register_t_n' is out of range (must be 0..23)") \
  3065. _SG_LOGITEM_XMACRO(D3D11_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE, "image 'hlsl_register_t_n' is out of range (must be 0..23)") \
  3066. _SG_LOGITEM_XMACRO(D3D11_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE, "sampler 'hlsl_register_s_n' is out of rang (must be 0..15)") \
  3067. _SG_LOGITEM_XMACRO(D3D11_LOAD_D3DCOMPILER_47_DLL_FAILED, "loading d3dcompiler_47.dll failed (d3d11)") \
  3068. _SG_LOGITEM_XMACRO(D3D11_SHADER_COMPILATION_FAILED, "shader compilation failed (d3d11)") \
  3069. _SG_LOGITEM_XMACRO(D3D11_SHADER_COMPILATION_OUTPUT, "") \
  3070. _SG_LOGITEM_XMACRO(D3D11_CREATE_CONSTANT_BUFFER_FAILED, "CreateBuffer() failed for uniform constant buffer (d3d11)") \
  3071. _SG_LOGITEM_XMACRO(D3D11_CREATE_INPUT_LAYOUT_FAILED, "CreateInputLayout() failed (d3d11)") \
  3072. _SG_LOGITEM_XMACRO(D3D11_CREATE_RASTERIZER_STATE_FAILED, "CreateRasterizerState() failed (d3d11)") \
  3073. _SG_LOGITEM_XMACRO(D3D11_CREATE_DEPTH_STENCIL_STATE_FAILED, "CreateDepthStencilState() failed (d3d11)") \
  3074. _SG_LOGITEM_XMACRO(D3D11_CREATE_BLEND_STATE_FAILED, "CreateBlendState() failed (d3d11)") \
  3075. _SG_LOGITEM_XMACRO(D3D11_CREATE_RTV_FAILED, "CreateRenderTargetView() failed (d3d11)") \
  3076. _SG_LOGITEM_XMACRO(D3D11_CREATE_DSV_FAILED, "CreateDepthStencilView() failed (d3d11)") \
  3077. _SG_LOGITEM_XMACRO(D3D11_MAP_FOR_UPDATE_BUFFER_FAILED, "Map() failed when updating buffer (d3d11)") \
  3078. _SG_LOGITEM_XMACRO(D3D11_MAP_FOR_APPEND_BUFFER_FAILED, "Map() failed when appending to buffer (d3d11)") \
  3079. _SG_LOGITEM_XMACRO(D3D11_MAP_FOR_UPDATE_IMAGE_FAILED, "Map() failed when updating image (d3d11)") \
  3080. _SG_LOGITEM_XMACRO(METAL_CREATE_BUFFER_FAILED, "failed to create buffer object (metal)") \
  3081. _SG_LOGITEM_XMACRO(METAL_TEXTURE_FORMAT_NOT_SUPPORTED, "pixel format not supported for texture (metal)") \
  3082. _SG_LOGITEM_XMACRO(METAL_CREATE_TEXTURE_FAILED, "failed to create texture object (metal)") \
  3083. _SG_LOGITEM_XMACRO(METAL_CREATE_SAMPLER_FAILED, "failed to create sampler object (metal)") \
  3084. _SG_LOGITEM_XMACRO(METAL_SHADER_COMPILATION_FAILED, "shader compilation failed (metal)") \
  3085. _SG_LOGITEM_XMACRO(METAL_SHADER_CREATION_FAILED, "shader creation failed (metal)") \
  3086. _SG_LOGITEM_XMACRO(METAL_SHADER_COMPILATION_OUTPUT, "") \
  3087. _SG_LOGITEM_XMACRO(METAL_SHADER_ENTRY_NOT_FOUND, "shader entry function not found (metal)") \
  3088. _SG_LOGITEM_XMACRO(METAL_UNIFORMBLOCK_MSL_BUFFER_SLOT_OUT_OF_RANGE, "uniform block 'msl_buffer_n' is out of range (must be 0..7)") \
  3089. _SG_LOGITEM_XMACRO(METAL_STORAGEBUFFER_MSL_BUFFER_SLOT_OUT_OF_RANGE, "storage buffer 'msl_buffer_n' is out of range (must be 8..15)") \
  3090. _SG_LOGITEM_XMACRO(METAL_IMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE, "image 'msl_texture_n' is out of range (must be 0..15)") \
  3091. _SG_LOGITEM_XMACRO(METAL_SAMPLER_MSL_SAMPLER_SLOT_OUT_OF_RANGE, "sampler 'msl_sampler_n' is out of range (must be 0..15)") \
  3092. _SG_LOGITEM_XMACRO(METAL_CREATE_RPS_FAILED, "failed to create render pipeline state (metal)") \
  3093. _SG_LOGITEM_XMACRO(METAL_CREATE_RPS_OUTPUT, "") \
  3094. _SG_LOGITEM_XMACRO(METAL_CREATE_DSS_FAILED, "failed to create depth stencil state (metal)") \
  3095. _SG_LOGITEM_XMACRO(WGPU_BINDGROUPS_POOL_EXHAUSTED, "bindgroups pool exhausted (increase sg_desc.bindgroups_cache_size) (wgpu)") \
  3096. _SG_LOGITEM_XMACRO(WGPU_BINDGROUPSCACHE_SIZE_GREATER_ONE, "sg_desc.wgpu_bindgroups_cache_size must be > 1 (wgpu)") \
  3097. _SG_LOGITEM_XMACRO(WGPU_BINDGROUPSCACHE_SIZE_POW2, "sg_desc.wgpu_bindgroups_cache_size must be a power of 2 (wgpu)") \
  3098. _SG_LOGITEM_XMACRO(WGPU_CREATEBINDGROUP_FAILED, "wgpuDeviceCreateBindGroup failed") \
  3099. _SG_LOGITEM_XMACRO(WGPU_CREATE_BUFFER_FAILED, "wgpuDeviceCreateBuffer() failed") \
  3100. _SG_LOGITEM_XMACRO(WGPU_CREATE_TEXTURE_FAILED, "wgpuDeviceCreateTexture() failed") \
  3101. _SG_LOGITEM_XMACRO(WGPU_CREATE_TEXTURE_VIEW_FAILED, "wgpuTextureCreateView() failed") \
  3102. _SG_LOGITEM_XMACRO(WGPU_CREATE_SAMPLER_FAILED, "wgpuDeviceCreateSampler() failed") \
  3103. _SG_LOGITEM_XMACRO(WGPU_CREATE_SHADER_MODULE_FAILED, "wgpuDeviceCreateShaderModule() failed") \
  3104. _SG_LOGITEM_XMACRO(WGPU_SHADER_CREATE_BINDGROUP_LAYOUT_FAILED, "wgpuDeviceCreateBindGroupLayout() for shader stage failed") \
  3105. _SG_LOGITEM_XMACRO(WGPU_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE, "uniform block 'wgsl_group0_binding_n' is out of range (must be 0..15)") \
  3106. _SG_LOGITEM_XMACRO(WGPU_STORAGEBUFFER_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "storage buffer 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3107. _SG_LOGITEM_XMACRO(WGPU_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "image 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3108. _SG_LOGITEM_XMACRO(WGPU_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "sampler 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3109. _SG_LOGITEM_XMACRO(WGPU_CREATE_PIPELINE_LAYOUT_FAILED, "wgpuDeviceCreatePipelineLayout() failed") \
  3110. _SG_LOGITEM_XMACRO(WGPU_CREATE_RENDER_PIPELINE_FAILED, "wgpuDeviceCreateRenderPipeline() failed") \
  3111. _SG_LOGITEM_XMACRO(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED, "wgpuTextureCreateView() failed in create attachments") \
  3112. _SG_LOGITEM_XMACRO(DRAW_REQUIRED_BINDINGS_OR_UNIFORMS_MISSING, "call to sg_apply_bindings() and/or sg_apply_uniforms() missing after sg_apply_pipeline()") \
  3113. _SG_LOGITEM_XMACRO(IDENTICAL_COMMIT_LISTENER, "attempting to add identical commit listener") \
  3114. _SG_LOGITEM_XMACRO(COMMIT_LISTENER_ARRAY_FULL, "commit listener array full") \
  3115. _SG_LOGITEM_XMACRO(TRACE_HOOKS_NOT_ENABLED, "sg_install_trace_hooks() called, but SOKOL_TRACE_HOOKS is not defined") \
  3116. _SG_LOGITEM_XMACRO(DEALLOC_BUFFER_INVALID_STATE, "sg_dealloc_buffer(): buffer must be in ALLOC state") \
  3117. _SG_LOGITEM_XMACRO(DEALLOC_IMAGE_INVALID_STATE, "sg_dealloc_image(): image must be in alloc state") \
  3118. _SG_LOGITEM_XMACRO(DEALLOC_SAMPLER_INVALID_STATE, "sg_dealloc_sampler(): sampler must be in alloc state") \
  3119. _SG_LOGITEM_XMACRO(DEALLOC_SHADER_INVALID_STATE, "sg_dealloc_shader(): shader must be in ALLOC state") \
  3120. _SG_LOGITEM_XMACRO(DEALLOC_PIPELINE_INVALID_STATE, "sg_dealloc_pipeline(): pipeline must be in ALLOC state") \
  3121. _SG_LOGITEM_XMACRO(DEALLOC_ATTACHMENTS_INVALID_STATE, "sg_dealloc_attachments(): attachments must be in ALLOC state") \
  3122. _SG_LOGITEM_XMACRO(INIT_BUFFER_INVALID_STATE, "sg_init_buffer(): buffer must be in ALLOC state") \
  3123. _SG_LOGITEM_XMACRO(INIT_IMAGE_INVALID_STATE, "sg_init_image(): image must be in ALLOC state") \
  3124. _SG_LOGITEM_XMACRO(INIT_SAMPLER_INVALID_STATE, "sg_init_sampler(): sampler must be in ALLOC state") \
  3125. _SG_LOGITEM_XMACRO(INIT_SHADER_INVALID_STATE, "sg_init_shader(): shader must be in ALLOC state") \
  3126. _SG_LOGITEM_XMACRO(INIT_PIPELINE_INVALID_STATE, "sg_init_pipeline(): pipeline must be in ALLOC state") \
  3127. _SG_LOGITEM_XMACRO(INIT_ATTACHMENTS_INVALID_STATE, "sg_init_attachments(): pass must be in ALLOC state") \
  3128. _SG_LOGITEM_XMACRO(UNINIT_BUFFER_INVALID_STATE, "sg_uninit_buffer(): buffer must be in VALID or FAILED state") \
  3129. _SG_LOGITEM_XMACRO(UNINIT_IMAGE_INVALID_STATE, "sg_uninit_image(): image must be in VALID or FAILED state") \
  3130. _SG_LOGITEM_XMACRO(UNINIT_SAMPLER_INVALID_STATE, "sg_uninit_sampler(): sampler must be in VALID or FAILED state") \
  3131. _SG_LOGITEM_XMACRO(UNINIT_SHADER_INVALID_STATE, "sg_uninit_shader(): shader must be in VALID or FAILED state") \
  3132. _SG_LOGITEM_XMACRO(UNINIT_PIPELINE_INVALID_STATE, "sg_uninit_pipeline(): pipeline must be in VALID or FAILED state") \
  3133. _SG_LOGITEM_XMACRO(UNINIT_ATTACHMENTS_INVALID_STATE, "sg_uninit_attachments(): attachments must be in VALID or FAILED state") \
  3134. _SG_LOGITEM_XMACRO(FAIL_BUFFER_INVALID_STATE, "sg_fail_buffer(): buffer must be in ALLOC state") \
  3135. _SG_LOGITEM_XMACRO(FAIL_IMAGE_INVALID_STATE, "sg_fail_image(): image must be in ALLOC state") \
  3136. _SG_LOGITEM_XMACRO(FAIL_SAMPLER_INVALID_STATE, "sg_fail_sampler(): sampler must be in ALLOC state") \
  3137. _SG_LOGITEM_XMACRO(FAIL_SHADER_INVALID_STATE, "sg_fail_shader(): shader must be in ALLOC state") \
  3138. _SG_LOGITEM_XMACRO(FAIL_PIPELINE_INVALID_STATE, "sg_fail_pipeline(): pipeline must be in ALLOC state") \
  3139. _SG_LOGITEM_XMACRO(FAIL_ATTACHMENTS_INVALID_STATE, "sg_fail_attachments(): attachments must be in ALLOC state") \
  3140. _SG_LOGITEM_XMACRO(BUFFER_POOL_EXHAUSTED, "buffer pool exhausted") \
  3141. _SG_LOGITEM_XMACRO(IMAGE_POOL_EXHAUSTED, "image pool exhausted") \
  3142. _SG_LOGITEM_XMACRO(SAMPLER_POOL_EXHAUSTED, "sampler pool exhausted") \
  3143. _SG_LOGITEM_XMACRO(SHADER_POOL_EXHAUSTED, "shader pool exhausted") \
  3144. _SG_LOGITEM_XMACRO(PIPELINE_POOL_EXHAUSTED, "pipeline pool exhausted") \
  3145. _SG_LOGITEM_XMACRO(PASS_POOL_EXHAUSTED, "pass pool exhausted") \
  3146. _SG_LOGITEM_XMACRO(BEGINPASS_ATTACHMENT_INVALID, "sg_begin_pass: an attachment was provided that no longer exists") \
  3147. _SG_LOGITEM_XMACRO(DRAW_WITHOUT_BINDINGS, "attempting to draw without resource bindings") \
  3148. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_CANARY, "sg_buffer_desc not initialized") \
  3149. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_SIZE, "sg_buffer_desc.size and .data.size cannot both be 0") \
  3150. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_DATA, "immutable buffers must be initialized with data (sg_buffer_desc.data.ptr and sg_buffer_desc.data.size)") \
  3151. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_DATA_SIZE, "immutable buffer data size differs from buffer size") \
  3152. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_NO_DATA, "dynamic/stream usage buffers cannot be initialized with data") \
  3153. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_STORAGEBUFFER_SUPPORTED, "storage buffers not supported by the backend 3D API (requires OpenGL >= 4.3)") \
  3154. _SG_LOGITEM_XMACRO(VALIDATE_BUFFERDESC_STORAGEBUFFER_SIZE_MULTIPLE_4, "size of storage buffers must be a multiple of 4") \
  3155. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDATA_NODATA, "sg_image_data: no data (.ptr and/or .size is zero)") \
  3156. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDATA_DATA_SIZE, "sg_image_data: data size doesn't match expected surface size") \
  3157. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_CANARY, "sg_image_desc not initialized") \
  3158. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_WIDTH, "sg_image_desc.width must be > 0") \
  3159. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_HEIGHT, "sg_image_desc.height must be > 0") \
  3160. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RT_PIXELFORMAT, "invalid pixel format for render-target image") \
  3161. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_NONRT_PIXELFORMAT, "invalid pixel format for non-render-target image") \
  3162. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_MSAA_BUT_NO_RT, "non-render-target images cannot be multisampled") \
  3163. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_NO_MSAA_RT_SUPPORT, "MSAA not supported for this pixel format") \
  3164. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_MSAA_NUM_MIPMAPS, "MSAA images must have num_mipmaps == 1") \
  3165. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_MSAA_3D_IMAGE, "3D images cannot have a sample_count > 1") \
  3166. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_MSAA_CUBE_IMAGE, "cube images cannot have sample_count > 1") \
  3167. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_DEPTH_3D_IMAGE, "3D images cannot have a depth/stencil image format") \
  3168. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RT_IMMUTABLE, "render target images must be SG_USAGE_IMMUTABLE") \
  3169. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_RT_NO_DATA, "render target images cannot be initialized with data") \
  3170. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_INJECTED_NO_DATA, "images with injected textures cannot be initialized with data") \
  3171. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_DYNAMIC_NO_DATA, "dynamic/stream images cannot be initialized with data") \
  3172. _SG_LOGITEM_XMACRO(VALIDATE_IMAGEDESC_COMPRESSED_IMMUTABLE, "compressed images must be immutable") \
  3173. _SG_LOGITEM_XMACRO(VALIDATE_SAMPLERDESC_CANARY, "sg_sampler_desc not initialized") \
  3174. _SG_LOGITEM_XMACRO(VALIDATE_SAMPLERDESC_ANISTROPIC_REQUIRES_LINEAR_FILTERING, "sg_sampler_desc.max_anisotropy > 1 requires min/mag/mipmap_filter to be SG_FILTER_LINEAR") \
  3175. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_CANARY, "sg_shader_desc not initialized") \
  3176. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SOURCE, "shader source code required") \
  3177. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_BYTECODE, "shader byte code required") \
  3178. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SOURCE_OR_BYTECODE, "shader source or byte code required") \
  3179. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_NO_BYTECODE_SIZE, "shader byte code length (in bytes) required") \
  3180. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_CONT_MEMBERS, "uniform block members must occupy continuous slots") \
  3181. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_IS_ZERO, "bound uniform block size cannot be zero") \
  3182. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_OUT_OF_RANGE, "uniform block 'msl_buffer_n' is out of range (must be 0..7)") \
  3183. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_COLLISION, "uniform block 'msl_buffer_n' must be unique across uniform blocks and storage buffers in same shader stage") \
  3184. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE, "uniform block 'hlsl_register_b_n' is out of range (must be 0..7)") \
  3185. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_HLSL_REGISTER_B_COLLISION, "uniform block 'hlsl_register_b_n' must be unique across uniform blocks in same shader stage") \
  3186. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE, "uniform block 'wgsl_group0_binding_n' is out of range (must be 0..15)") \
  3187. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_COLLISION, "uniform block 'wgsl_group0_binding_n' must be unique across all uniform blocks") \
  3188. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_MEMBERS, "GL backend requires uniform block member declarations") \
  3189. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_UNIFORM_GLSL_NAME, "uniform block member 'glsl_name' missing") \
  3190. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_MISMATCH, "size of uniform block members doesn't match uniform block size") \
  3191. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_ARRAY_COUNT, "uniform array count must be >= 1") \
  3192. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_UNIFORMBLOCK_STD140_ARRAY_TYPE, "uniform arrays only allowed for FLOAT4, INT4, MAT4 in std140 layout") \
  3193. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_METAL_BUFFER_SLOT_OUT_OF_RANGE, "storage buffer 'msl_buffer_n' is out of range (must be 8..15)") \
  3194. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_METAL_BUFFER_SLOT_COLLISION, "storage buffer 'msl_buffer_n' must be unique across uniform blocks and storage buffer in same shader stage") \
  3195. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE, "storage buffer 'hlsl_register_t_n' is out of range (must be 0..23)") \
  3196. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_T_COLLISION, "storage_buffer 'hlsl_register_t_n' must be unique across storage buffers and images in same shader stage") \
  3197. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE, "storage buffer 'glsl_binding_n' is out of range (must be 0..7)") \
  3198. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_COLLISION, "storage buffer 'glsl_binding_n' must be unique across shader stages") \
  3199. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "storage buffer 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3200. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_WGSL_GROUP1_BINDING_COLLISION, "storage buffer 'wgsl_group1_binding_n' must be unique across all images, samplers and storage buffers") \
  3201. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_STORAGEBUFFER_READONLY, "shader stage storage buffers must be readonly (sg_shader_desc.storage_buffers[].readonly)") \
  3202. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_OUT_OF_RANGE, "image 'msl_texture_n' is out of range (must be 0..15)") \
  3203. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_COLLISION, "image 'msl_texture_n' must be unique in same shader stage") \
  3204. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE, "image 'hlsl_register_t_n' is out of range (must be 0..23)") \
  3205. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_HLSL_REGISTER_T_COLLISION, "image 'hlsl_register_t_n' must be unique across images and storage buffers in same shader stage") \
  3206. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "image 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3207. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_WGSL_GROUP1_BINDING_COLLISION, "image 'wgsl_group1_binding_n' must be unique across all images, samplers and storage buffers") \
  3208. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_OUT_OF_RANGE, "sampler 'msl_sampler_n' is out of range (must be 0..15)") \
  3209. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_COLLISION, "sampler 'msl_sampler_n' must be unique in same shader stage") \
  3210. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE, "sampler 'hlsl_register_s_n' is out of rang (must be 0..15)") \
  3211. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_COLLISION, "sampler 'hlsl_register_s_n' must be unique in same shader stage") \
  3212. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE, "sampler 'wgsl_group1_binding_n' is out of range (must be 0..127)") \
  3213. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_WGSL_GROUP1_BINDING_COLLISION, "sampler 'wgsl_group1_binding_n' must be unique across all images, samplers and storage buffers") \
  3214. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_SLOT_OUT_OF_RANGE, "image-sampler-pair image slot index is out of range (sg_shader_desc.image_sampler_pairs[].image_slot)") \
  3215. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_SLOT_OUT_OF_RANGE, "image-sampler-pair sampler slot index is out of range (sg_shader_desc.image_sampler_pairs[].sampler_slot)") \
  3216. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_STAGE_MISMATCH, "image-sampler-pair stage doesn't match referenced image stage") \
  3217. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_STAGE_MISMATCH, "image-sampler-pair stage doesn't match referenced sampler stage") \
  3218. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_GLSL_NAME, "image-sampler-pair 'glsl_name' missing") \
  3219. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_NONFILTERING_SAMPLER_REQUIRED, "image sample type UNFILTERABLE_FLOAT, UINT, SINT can only be used with NONFILTERING sampler") \
  3220. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_COMPARISON_SAMPLER_REQUIRED, "image sample type DEPTH can only be used with COMPARISON sampler") \
  3221. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_IMAGE_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS, "one or more images are not referenced by by image-sampler-pairs (sg_shader_desc.image_sampler_pairs[].image_slot)") \
  3222. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_SAMPLER_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS, "one or more samplers are not referenced by image-sampler-pairs (sg_shader_desc.image_sampler_pairs[].sampler_slot)") \
  3223. _SG_LOGITEM_XMACRO(VALIDATE_SHADERDESC_ATTR_STRING_TOO_LONG, "vertex attribute name/semantic string too long (max len 16)") \
  3224. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_CANARY, "sg_pipeline_desc not initialized") \
  3225. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_SHADER, "sg_pipeline_desc.shader missing or invalid") \
  3226. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_NO_CONT_ATTRS, "sg_pipeline_desc.layout.attrs is not continuous") \
  3227. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_LAYOUT_STRIDE4, "sg_pipeline_desc.layout.buffers[].stride must be multiple of 4") \
  3228. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_ATTR_SEMANTICS, "D3D11 missing vertex attribute semantics in shader") \
  3229. _SG_LOGITEM_XMACRO(VALIDATE_PIPELINEDESC_BLENDOP_MINMAX_REQUIRES_BLENDFACTOR_ONE, "SG_BLENDOP_MIN/MAX requires all blend factors to be SG_BLENDFACTOR_ONE") \
  3230. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_CANARY, "sg_attachments_desc not initialized") \
  3231. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_NO_ATTACHMENTS, "sg_attachments_desc no color or depth-stencil attachments") \
  3232. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_NO_CONT_COLOR_ATTS, "color attachments must occupy continuous slots") \
  3233. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_IMAGE, "pass attachment image is not valid") \
  3234. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_MIPLEVEL, "pass attachment mip level is bigger than image has mipmaps") \
  3235. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_FACE, "pass attachment image is cubemap, but face index is too big") \
  3236. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_LAYER, "pass attachment image is array texture, but layer index is too big") \
  3237. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_SLICE, "pass attachment image is 3d texture, but slice value is too big") \
  3238. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_IMAGE_NO_RT, "pass attachment image must be have render_target=true") \
  3239. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_COLOR_INV_PIXELFORMAT, "pass color-attachment images must be renderable color pixel format") \
  3240. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_INV_PIXELFORMAT, "pass depth-attachment image must be depth or depth-stencil pixel format") \
  3241. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_IMAGE_SIZES, "all pass attachments must have the same size") \
  3242. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_IMAGE_SAMPLE_COUNTS, "all pass attachments must have the same sample count") \
  3243. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_COLOR_IMAGE_MSAA, "pass resolve attachments must have a color attachment image with sample count > 1") \
  3244. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE, "pass resolve attachment image not valid") \
  3245. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_SAMPLE_COUNT, "pass resolve attachment image sample count must be 1") \
  3246. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_MIPLEVEL, "pass resolve attachment mip level is bigger than image has mipmaps") \
  3247. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_FACE, "pass resolve attachment is cubemap, but face index is too big") \
  3248. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_LAYER, "pass resolve attachment is array texture, but layer index is too big") \
  3249. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_SLICE, "pass resolve attachment is 3d texture, but slice value is too big") \
  3250. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_NO_RT, "pass resolve attachment image must have render_target=true") \
  3251. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_SIZES, "pass resolve attachment size must match color attachment image size") \
  3252. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_FORMAT, "pass resolve attachment pixel format must match color attachment pixel format") \
  3253. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE, "pass depth attachment image is not valid") \
  3254. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_MIPLEVEL, "pass depth attachment mip level is bigger than image has mipmaps") \
  3255. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_FACE, "pass depth attachment image is cubemap, but face index is too big") \
  3256. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_LAYER, "pass depth attachment image is array texture, but layer index is too big") \
  3257. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_SLICE, "pass depth attachment image is 3d texture, but slice value is too big") \
  3258. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_NO_RT, "pass depth attachment image must be have render_target=true") \
  3259. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SIZES, "pass depth attachment image size must match color attachment image size") \
  3260. _SG_LOGITEM_XMACRO(VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SAMPLE_COUNT, "pass depth attachment sample count must match color attachment sample count") \
  3261. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_CANARY, "sg_begin_pass: pass struct not initialized") \
  3262. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_ATTACHMENTS_EXISTS, "sg_begin_pass: attachments object no longer alive") \
  3263. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_ATTACHMENTS_VALID, "sg_begin_pass: attachments object not in resource state VALID") \
  3264. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE, "sg_begin_pass: one or more color attachment images are not valid") \
  3265. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE, "sg_begin_pass: one or more resolve attachment images are not valid") \
  3266. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE, "sg_begin_pass: one or more depth-stencil attachment images are not valid") \
  3267. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH, "sg_begin_pass: expected pass.swapchain.width > 0") \
  3268. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH_NOTSET, "sg_begin_pass: expected pass.swapchain.width == 0") \
  3269. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT, "sg_begin_pass: expected pass.swapchain.height > 0") \
  3270. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT_NOTSET, "sg_begin_pass: expected pass.swapchain.height == 0") \
  3271. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT, "sg_begin_pass: expected pass.swapchain.sample_count > 0") \
  3272. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT_NOTSET, "sg_begin_pass: expected pass.swapchain.sample_count == 0") \
  3273. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT, "sg_begin_pass: expected pass.swapchain.color_format to be valid") \
  3274. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT_NOTSET, "sg_begin_pass: expected pass.swapchain.color_format to be unset") \
  3275. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_DEPTHFORMAT_NOTSET, "sg_begin_pass: expected pass.swapchain.depth_format to be unset") \
  3276. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE, "sg_begin_pass: expected pass.swapchain.metal.current_drawable != 0") \
  3277. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE_NOTSET, "sg_begin_pass: expected pass.swapchain.metal.current_drawable == 0") \
  3278. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE, "sg_begin_pass: expected pass.swapchain.metal.depth_stencil_texture != 0") \
  3279. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE_NOTSET, "sg_begin_pass: expected pass.swapchain.metal.depth_stencil_texture == 0") \
  3280. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE, "sg_begin_pass: expected pass.swapchain.metal.msaa_color_texture != 0") \
  3281. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE_NOTSET, "sg_begin_pass: expected pass.swapchain.metal.msaa_color_texture == 0") \
  3282. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW, "sg_begin_pass: expected pass.swapchain.d3d11.render_view != 0") \
  3283. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.d3d11.render_view == 0") \
  3284. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW, "sg_begin_pass: expected pass.swapchain.d3d11.resolve_view != 0") \
  3285. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.d3d11.resolve_view == 0") \
  3286. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW, "sg_begin_pass: expected pass.swapchain.d3d11.depth_stencil_view != 0") \
  3287. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.d3d11.depth_stencil_view == 0") \
  3288. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW, "sg_begin_pass: expected pass.swapchain.wgpu.render_view != 0") \
  3289. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.wgpu.render_view == 0") \
  3290. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW, "sg_begin_pass: expected pass.swapchain.wgpu.resolve_view != 0") \
  3291. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.wgpu.resolve_view == 0") \
  3292. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW, "sg_begin_pass: expected pass.swapchain.wgpu.depth_stencil_view != 0") \
  3293. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW_NOTSET, "sg_begin_pass: expected pass.swapchain.wgpu.depth_stencil_view == 0") \
  3294. _SG_LOGITEM_XMACRO(VALIDATE_BEGINPASS_SWAPCHAIN_GL_EXPECT_FRAMEBUFFER_NOTSET, "sg_begin_pass: expected pass.swapchain.gl.framebuffer == 0") \
  3295. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_VALID_ID, "sg_apply_pipeline: invalid pipeline id provided") \
  3296. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_EXISTS, "sg_apply_pipeline: pipeline object no longer alive") \
  3297. _SG_LOGITEM_XMACRO(VALIDATE_APIP_PIPELINE_VALID, "sg_apply_pipeline: pipeline object not in valid state") \
  3298. _SG_LOGITEM_XMACRO(VALIDATE_APIP_SHADER_EXISTS, "sg_apply_pipeline: shader object no longer alive") \
  3299. _SG_LOGITEM_XMACRO(VALIDATE_APIP_SHADER_VALID, "sg_apply_pipeline: shader object not in valid state") \
  3300. _SG_LOGITEM_XMACRO(VALIDATE_APIP_CURPASS_ATTACHMENTS_EXISTS, "sg_apply_pipeline: current pass attachments no longer alive") \
  3301. _SG_LOGITEM_XMACRO(VALIDATE_APIP_CURPASS_ATTACHMENTS_VALID, "sg_apply_pipeline: current pass attachments not in valid state") \
  3302. _SG_LOGITEM_XMACRO(VALIDATE_APIP_ATT_COUNT, "sg_apply_pipeline: number of pipeline color attachments doesn't match number of pass color attachments") \
  3303. _SG_LOGITEM_XMACRO(VALIDATE_APIP_COLOR_FORMAT, "sg_apply_pipeline: pipeline color attachment pixel format doesn't match pass color attachment pixel format") \
  3304. _SG_LOGITEM_XMACRO(VALIDATE_APIP_DEPTH_FORMAT, "sg_apply_pipeline: pipeline depth pixel_format doesn't match pass depth attachment pixel format") \
  3305. _SG_LOGITEM_XMACRO(VALIDATE_APIP_SAMPLE_COUNT, "sg_apply_pipeline: pipeline MSAA sample count doesn't match render pass attachment sample count") \
  3306. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE, "sg_apply_bindings: must be called after sg_apply_pipeline") \
  3307. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_EXISTS, "sg_apply_bindings: currently applied pipeline object no longer alive") \
  3308. _SG_LOGITEM_XMACRO(VALIDATE_ABND_PIPELINE_VALID, "sg_apply_bindings: currently applied pipeline object not in valid state") \
  3309. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_VB, "sg_apply_bindings: vertex buffer binding is missing or buffer handle is invalid") \
  3310. _SG_LOGITEM_XMACRO(VALIDATE_ABND_VB_EXISTS, "sg_apply_bindings: vertex buffer no longer alive") \
  3311. _SG_LOGITEM_XMACRO(VALIDATE_ABND_VB_TYPE, "sg_apply_bindings: buffer in vertex buffer slot is not a SG_BUFFERTYPE_VERTEXBUFFER") \
  3312. _SG_LOGITEM_XMACRO(VALIDATE_ABND_VB_OVERFLOW, "sg_apply_bindings: buffer in vertex buffer slot is overflown") \
  3313. _SG_LOGITEM_XMACRO(VALIDATE_ABND_NO_IB, "sg_apply_bindings: pipeline object defines indexed rendering, but no index buffer provided") \
  3314. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB, "sg_apply_bindings: pipeline object defines non-indexed rendering, but index buffer provided") \
  3315. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB_EXISTS, "sg_apply_bindings: index buffer no longer alive") \
  3316. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB_TYPE, "sg_apply_bindings: buffer in index buffer slot is not a SG_BUFFERTYPE_INDEXBUFFER") \
  3317. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IB_OVERFLOW, "sg_apply_bindings: buffer in index buffer slot is overflown") \
  3318. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_IMAGE_BINDING, "sg_apply_bindings: image binding is missing or the image handle is invalid") \
  3319. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMG_EXISTS, "sg_apply_bindings: bound image no longer alive") \
  3320. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_TYPE_MISMATCH, "sg_apply_bindings: type of bound image doesn't match shader desc") \
  3321. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_MULTISAMPLED_IMAGE, "sg_apply_bindings: expected image with sample_count > 1") \
  3322. _SG_LOGITEM_XMACRO(VALIDATE_ABND_IMAGE_MSAA, "sg_apply_bindings: cannot bind image with sample_count>1") \
  3323. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_FILTERABLE_IMAGE, "sg_apply_bindings: filterable image expected") \
  3324. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_DEPTH_IMAGE, "sg_apply_bindings: depth image expected") \
  3325. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_SAMPLER_BINDING, "sg_apply_bindings: sampler binding is missing or the sampler handle is invalid") \
  3326. _SG_LOGITEM_XMACRO(VALIDATE_ABND_UNEXPECTED_SAMPLER_COMPARE_NEVER, "sg_apply_bindings: shader expects SG_SAMPLERTYPE_COMPARISON but sampler has SG_COMPAREFUNC_NEVER") \
  3327. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_SAMPLER_COMPARE_NEVER, "sg_apply_bindings: shader expects SG_SAMPLERTYPE_FILTERING or SG_SAMPLERTYPE_NONFILTERING but sampler doesn't have SG_COMPAREFUNC_NEVER") \
  3328. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_NONFILTERING_SAMPLER, "sg_apply_bindings: shader expected SG_SAMPLERTYPE_NONFILTERING, but sampler has SG_FILTER_LINEAR filters") \
  3329. _SG_LOGITEM_XMACRO(VALIDATE_ABND_SMP_EXISTS, "sg_apply_bindings: bound sampler no longer alive") \
  3330. _SG_LOGITEM_XMACRO(VALIDATE_ABND_EXPECTED_STORAGEBUFFER_BINDING, "sg_apply_bindings: storage buffer binding is missing or the buffer handle is invalid") \
  3331. _SG_LOGITEM_XMACRO(VALIDATE_ABND_STORAGEBUFFER_EXISTS, "sg_apply_bindings: bound storage buffer no longer alive") \
  3332. _SG_LOGITEM_XMACRO(VALIDATE_ABND_STORAGEBUFFER_BINDING_BUFFERTYPE, "sg_apply_bindings: buffer bound storage buffer slot is not of type storage buffer") \
  3333. _SG_LOGITEM_XMACRO(VALIDATE_AUB_NO_PIPELINE, "sg_apply_uniforms: must be called after sg_apply_pipeline()") \
  3334. _SG_LOGITEM_XMACRO(VALIDATE_AUB_NO_UNIFORMBLOCK_AT_SLOT, "sg_apply_uniforms: no uniform block declaration at this shader stage UB slot") \
  3335. _SG_LOGITEM_XMACRO(VALIDATE_AUB_SIZE, "sg_apply_uniforms: data size doesn't match declared uniform block size") \
  3336. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_USAGE, "sg_update_buffer: cannot update immutable buffer") \
  3337. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_SIZE, "sg_update_buffer: update size is bigger than buffer size") \
  3338. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_ONCE, "sg_update_buffer: only one update allowed per buffer and frame") \
  3339. _SG_LOGITEM_XMACRO(VALIDATE_UPDATEBUF_APPEND, "sg_update_buffer: cannot call sg_update_buffer and sg_append_buffer in same frame") \
  3340. _SG_LOGITEM_XMACRO(VALIDATE_APPENDBUF_USAGE, "sg_append_buffer: cannot append to immutable buffer") \
  3341. _SG_LOGITEM_XMACRO(VALIDATE_APPENDBUF_SIZE, "sg_append_buffer: overall appended size is bigger than buffer size") \
  3342. _SG_LOGITEM_XMACRO(VALIDATE_APPENDBUF_UPDATE, "sg_append_buffer: cannot call sg_append_buffer and sg_update_buffer in same frame") \
  3343. _SG_LOGITEM_XMACRO(VALIDATE_UPDIMG_USAGE, "sg_update_image: cannot update immutable image") \
  3344. _SG_LOGITEM_XMACRO(VALIDATE_UPDIMG_ONCE, "sg_update_image: only one update allowed per image and frame") \
  3345. _SG_LOGITEM_XMACRO(VALIDATION_FAILED, "validation layer checks failed") \
  3346. #define _SG_LOGITEM_XMACRO(item,msg) SG_LOGITEM_##item,
  3347. typedef enum sg_log_item {
  3348. _SG_LOG_ITEMS
  3349. } sg_log_item;
  3350. #undef _SG_LOGITEM_XMACRO
  3351. /*
  3352. sg_desc
  3353. The sg_desc struct contains configuration values for sokol_gfx,
  3354. it is used as parameter to the sg_setup() call.
  3355. The default configuration is:
  3356. .buffer_pool_size 128
  3357. .image_pool_size 128
  3358. .sampler_pool_size 64
  3359. .shader_pool_size 32
  3360. .pipeline_pool_size 64
  3361. .pass_pool_size 16
  3362. .uniform_buffer_size 4 MB (4*1024*1024)
  3363. .max_commit_listeners 1024
  3364. .disable_validation false
  3365. .mtl_force_managed_storage_mode false
  3366. .wgpu_disable_bindgroups_cache false
  3367. .wgpu_bindgroups_cache_size 1024
  3368. .allocator.alloc_fn 0 (in this case, malloc() will be called)
  3369. .allocator.free_fn 0 (in this case, free() will be called)
  3370. .allocator.user_data 0
  3371. .environment.defaults.color_format: default value depends on selected backend:
  3372. all GL backends: SG_PIXELFORMAT_RGBA8
  3373. Metal and D3D11: SG_PIXELFORMAT_BGRA8
  3374. WebGPU: *no default* (must be queried from WebGPU swapchain object)
  3375. .environment.defaults.depth_format: SG_PIXELFORMAT_DEPTH_STENCIL
  3376. .environment.defaults.sample_count: 1
  3377. Metal specific:
  3378. (NOTE: All Objective-C object references are transferred through
  3379. a bridged cast (__bridge const void*) to sokol_gfx, which will use an
  3380. unretained bridged cast (__bridge id<xxx>) to retrieve the Objective-C
  3381. references back. Since the bridge cast is unretained, the caller
  3382. must hold a strong reference to the Objective-C object until sg_setup()
  3383. returns.
  3384. .mtl_force_managed_storage_mode
  3385. when enabled, Metal buffers and texture resources are created in managed storage
  3386. mode, otherwise sokol-gfx will decide whether to create buffers and
  3387. textures in managed or shared storage mode (this is mainly a debugging option)
  3388. .mtl_use_command_buffer_with_retained_references
  3389. when true, the sokol-gfx Metal backend will use Metal command buffers which
  3390. bump the reference count of resource objects as long as they are inflight,
  3391. this is slower than the default command-buffer-with-unretained-references
  3392. method, this may be a workaround when confronted with lifetime validation
  3393. errors from the Metal validation layer until a proper fix has been implemented
  3394. .environment.metal.device
  3395. a pointer to the MTLDevice object
  3396. D3D11 specific:
  3397. .environment.d3d11.device
  3398. a pointer to the ID3D11Device object, this must have been created
  3399. before sg_setup() is called
  3400. .environment.d3d11.device_context
  3401. a pointer to the ID3D11DeviceContext object
  3402. .d3d11_shader_debugging
  3403. set this to true to compile shaders which are provided as HLSL source
  3404. code with debug information and without optimization, this allows
  3405. shader debugging in tools like RenderDoc, to output source code
  3406. instead of byte code from sokol-shdc, omit the `--binary` cmdline
  3407. option
  3408. WebGPU specific:
  3409. .wgpu_disable_bindgroups_cache
  3410. When this is true, the WebGPU backend will create and immediately
  3411. release a BindGroup object in the sg_apply_bindings() call, only
  3412. use this for debugging purposes.
  3413. .wgpu_bindgroups_cache_size
  3414. The size of the bindgroups cache for re-using BindGroup objects
  3415. between sg_apply_bindings() calls. The smaller the cache size,
  3416. the more likely are cache slot collisions which will cause
  3417. a BindGroups object to be destroyed and a new one created.
  3418. Use the information returned by sg_query_stats() to check
  3419. if this is a frequent occurrence, and increase the cache size as
  3420. needed (the default is 1024).
  3421. NOTE: wgpu_bindgroups_cache_size must be a power-of-2 number!
  3422. .environment.wgpu.device
  3423. a WGPUDevice handle
  3424. When using sokol_gfx.h and sokol_app.h together, consider using the
  3425. helper function sglue_environment() in the sokol_glue.h header to
  3426. initialize the sg_desc.environment nested struct. sglue_environment() returns
  3427. a completely initialized sg_environment struct with information
  3428. provided by sokol_app.h.
  3429. */
  3430. typedef struct sg_environment_defaults {
  3431. sg_pixel_format color_format;
  3432. sg_pixel_format depth_format;
  3433. int sample_count;
  3434. } sg_environment_defaults;
  3435. typedef struct sg_metal_environment {
  3436. const void* device;
  3437. } sg_metal_environment;
  3438. typedef struct sg_d3d11_environment {
  3439. const void* device;
  3440. const void* device_context;
  3441. } sg_d3d11_environment;
  3442. typedef struct sg_wgpu_environment {
  3443. const void* device;
  3444. } sg_wgpu_environment;
  3445. typedef struct sg_environment {
  3446. sg_environment_defaults defaults;
  3447. sg_metal_environment metal;
  3448. sg_d3d11_environment d3d11;
  3449. sg_wgpu_environment wgpu;
  3450. } sg_environment;
  3451. /*
  3452. sg_commit_listener
  3453. Used with function sg_add_commit_listener() to add a callback
  3454. which will be called in sg_commit(). This is useful for libraries
  3455. building on top of sokol-gfx to be notified about when a frame
  3456. ends (instead of having to guess, or add a manual 'new-frame'
  3457. function.
  3458. */
  3459. typedef struct sg_commit_listener {
  3460. void (*func)(void* user_data);
  3461. void* user_data;
  3462. } sg_commit_listener;
  3463. /*
  3464. sg_allocator
  3465. Used in sg_desc to provide custom memory-alloc and -free functions
  3466. to sokol_gfx.h. If memory management should be overridden, both the
  3467. alloc_fn and free_fn function must be provided (e.g. it's not valid to
  3468. override one function but not the other).
  3469. */
  3470. typedef struct sg_allocator {
  3471. void* (*alloc_fn)(size_t size, void* user_data);
  3472. void (*free_fn)(void* ptr, void* user_data);
  3473. void* user_data;
  3474. } sg_allocator;
  3475. /*
  3476. sg_logger
  3477. Used in sg_desc to provide a logging function. Please be aware
  3478. that without logging function, sokol-gfx will be completely
  3479. silent, e.g. it will not report errors, warnings and
  3480. validation layer messages. For maximum error verbosity,
  3481. compile in debug mode (e.g. NDEBUG *not* defined) and provide a
  3482. compatible logger function in the sg_setup() call
  3483. (for instance the standard logging function from sokol_log.h).
  3484. */
  3485. typedef struct sg_logger {
  3486. void (*func)(
  3487. const char* tag, // always "sg"
  3488. uint32_t log_level, // 0=panic, 1=error, 2=warning, 3=info
  3489. uint32_t log_item_id, // SG_LOGITEM_*
  3490. const char* message_or_null, // a message string, may be nullptr in release mode
  3491. uint32_t line_nr, // line number in sokol_gfx.h
  3492. const char* filename_or_null, // source filename, may be nullptr in release mode
  3493. void* user_data);
  3494. void* user_data;
  3495. } sg_logger;
  3496. typedef struct sg_desc {
  3497. uint32_t _start_canary;
  3498. int buffer_pool_size;
  3499. int image_pool_size;
  3500. int sampler_pool_size;
  3501. int shader_pool_size;
  3502. int pipeline_pool_size;
  3503. int attachments_pool_size;
  3504. int uniform_buffer_size;
  3505. int max_commit_listeners;
  3506. bool disable_validation; // disable validation layer even in debug mode, useful for tests
  3507. bool d3d11_shader_debugging; // if true, HLSL shaders are compiled with D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION
  3508. bool mtl_force_managed_storage_mode; // for debugging: use Metal managed storage mode for resources even with UMA
  3509. bool mtl_use_command_buffer_with_retained_references; // Metal: use a managed MTLCommandBuffer which ref-counts used resources
  3510. bool wgpu_disable_bindgroups_cache; // set to true to disable the WebGPU backend BindGroup cache
  3511. int wgpu_bindgroups_cache_size; // number of slots in the WebGPU bindgroup cache (must be 2^N)
  3512. sg_allocator allocator;
  3513. sg_logger logger; // optional log function override
  3514. sg_environment environment;
  3515. uint32_t _end_canary;
  3516. } sg_desc;
  3517. // setup and misc functions
  3518. SOKOL_GFX_API_DECL void sg_setup(const sg_desc* desc);
  3519. SOKOL_GFX_API_DECL void sg_shutdown(void);
  3520. SOKOL_GFX_API_DECL bool sg_isvalid(void);
  3521. SOKOL_GFX_API_DECL void sg_reset_state_cache(void);
  3522. SOKOL_GFX_API_DECL sg_trace_hooks sg_install_trace_hooks(const sg_trace_hooks* trace_hooks);
  3523. SOKOL_GFX_API_DECL void sg_push_debug_group(const char* name);
  3524. SOKOL_GFX_API_DECL void sg_pop_debug_group(void);
  3525. SOKOL_GFX_API_DECL bool sg_add_commit_listener(sg_commit_listener listener);
  3526. SOKOL_GFX_API_DECL bool sg_remove_commit_listener(sg_commit_listener listener);
  3527. // resource creation, destruction and updating
  3528. SOKOL_GFX_API_DECL sg_buffer sg_make_buffer(const sg_buffer_desc* desc);
  3529. SOKOL_GFX_API_DECL sg_image sg_make_image(const sg_image_desc* desc);
  3530. SOKOL_GFX_API_DECL sg_sampler sg_make_sampler(const sg_sampler_desc* desc);
  3531. SOKOL_GFX_API_DECL sg_shader sg_make_shader(const sg_shader_desc* desc);
  3532. SOKOL_GFX_API_DECL sg_pipeline sg_make_pipeline(const sg_pipeline_desc* desc);
  3533. SOKOL_GFX_API_DECL sg_attachments sg_make_attachments(const sg_attachments_desc* desc);
  3534. SOKOL_GFX_API_DECL void sg_destroy_buffer(sg_buffer buf);
  3535. SOKOL_GFX_API_DECL void sg_destroy_image(sg_image img);
  3536. SOKOL_GFX_API_DECL void sg_destroy_sampler(sg_sampler smp);
  3537. SOKOL_GFX_API_DECL void sg_destroy_shader(sg_shader shd);
  3538. SOKOL_GFX_API_DECL void sg_destroy_pipeline(sg_pipeline pip);
  3539. SOKOL_GFX_API_DECL void sg_destroy_attachments(sg_attachments atts);
  3540. SOKOL_GFX_API_DECL void sg_update_buffer(sg_buffer buf, const sg_range* data);
  3541. SOKOL_GFX_API_DECL void sg_update_image(sg_image img, const sg_image_data* data);
  3542. SOKOL_GFX_API_DECL int sg_append_buffer(sg_buffer buf, const sg_range* data);
  3543. SOKOL_GFX_API_DECL bool sg_query_buffer_overflow(sg_buffer buf);
  3544. SOKOL_GFX_API_DECL bool sg_query_buffer_will_overflow(sg_buffer buf, size_t size);
  3545. // rendering functions
  3546. SOKOL_GFX_API_DECL void sg_begin_pass(const sg_pass* pass);
  3547. SOKOL_GFX_API_DECL void sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left);
  3548. SOKOL_GFX_API_DECL void sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left);
  3549. SOKOL_GFX_API_DECL void sg_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left);
  3550. SOKOL_GFX_API_DECL void sg_apply_scissor_rectf(float x, float y, float width, float height, bool origin_top_left);
  3551. SOKOL_GFX_API_DECL void sg_apply_pipeline(sg_pipeline pip);
  3552. SOKOL_GFX_API_DECL void sg_apply_bindings(const sg_bindings* bindings);
  3553. SOKOL_GFX_API_DECL void sg_apply_uniforms(int ub_slot, const sg_range* data);
  3554. SOKOL_GFX_API_DECL void sg_draw(int base_element, int num_elements, int num_instances);
  3555. SOKOL_GFX_API_DECL void sg_end_pass(void);
  3556. SOKOL_GFX_API_DECL void sg_commit(void);
  3557. // getting information
  3558. SOKOL_GFX_API_DECL sg_desc sg_query_desc(void);
  3559. SOKOL_GFX_API_DECL sg_backend sg_query_backend(void);
  3560. SOKOL_GFX_API_DECL sg_features sg_query_features(void);
  3561. SOKOL_GFX_API_DECL sg_limits sg_query_limits(void);
  3562. SOKOL_GFX_API_DECL sg_pixelformat_info sg_query_pixelformat(sg_pixel_format fmt);
  3563. SOKOL_GFX_API_DECL int sg_query_row_pitch(sg_pixel_format fmt, int width, int row_align_bytes);
  3564. SOKOL_GFX_API_DECL int sg_query_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align_bytes);
  3565. // get current state of a resource (INITIAL, ALLOC, VALID, FAILED, INVALID)
  3566. SOKOL_GFX_API_DECL sg_resource_state sg_query_buffer_state(sg_buffer buf);
  3567. SOKOL_GFX_API_DECL sg_resource_state sg_query_image_state(sg_image img);
  3568. SOKOL_GFX_API_DECL sg_resource_state sg_query_sampler_state(sg_sampler smp);
  3569. SOKOL_GFX_API_DECL sg_resource_state sg_query_shader_state(sg_shader shd);
  3570. SOKOL_GFX_API_DECL sg_resource_state sg_query_pipeline_state(sg_pipeline pip);
  3571. SOKOL_GFX_API_DECL sg_resource_state sg_query_attachments_state(sg_attachments atts);
  3572. // get runtime information about a resource
  3573. SOKOL_GFX_API_DECL sg_buffer_info sg_query_buffer_info(sg_buffer buf);
  3574. SOKOL_GFX_API_DECL sg_image_info sg_query_image_info(sg_image img);
  3575. SOKOL_GFX_API_DECL sg_sampler_info sg_query_sampler_info(sg_sampler smp);
  3576. SOKOL_GFX_API_DECL sg_shader_info sg_query_shader_info(sg_shader shd);
  3577. SOKOL_GFX_API_DECL sg_pipeline_info sg_query_pipeline_info(sg_pipeline pip);
  3578. SOKOL_GFX_API_DECL sg_attachments_info sg_query_attachments_info(sg_attachments atts);
  3579. // get desc structs matching a specific resource (NOTE that not all creation attributes may be provided)
  3580. SOKOL_GFX_API_DECL sg_buffer_desc sg_query_buffer_desc(sg_buffer buf);
  3581. SOKOL_GFX_API_DECL sg_image_desc sg_query_image_desc(sg_image img);
  3582. SOKOL_GFX_API_DECL sg_sampler_desc sg_query_sampler_desc(sg_sampler smp);
  3583. SOKOL_GFX_API_DECL sg_shader_desc sg_query_shader_desc(sg_shader shd);
  3584. SOKOL_GFX_API_DECL sg_pipeline_desc sg_query_pipeline_desc(sg_pipeline pip);
  3585. SOKOL_GFX_API_DECL sg_attachments_desc sg_query_attachments_desc(sg_attachments atts);
  3586. // get resource creation desc struct with their default values replaced
  3587. SOKOL_GFX_API_DECL sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc* desc);
  3588. SOKOL_GFX_API_DECL sg_image_desc sg_query_image_defaults(const sg_image_desc* desc);
  3589. SOKOL_GFX_API_DECL sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc* desc);
  3590. SOKOL_GFX_API_DECL sg_shader_desc sg_query_shader_defaults(const sg_shader_desc* desc);
  3591. SOKOL_GFX_API_DECL sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc* desc);
  3592. SOKOL_GFX_API_DECL sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc* desc);
  3593. // assorted query functions
  3594. SOKOL_GFX_API_DECL size_t sg_query_buffer_size(sg_buffer buf);
  3595. SOKOL_GFX_API_DECL sg_buffer_type sg_query_buffer_type(sg_buffer buf);
  3596. SOKOL_GFX_API_DECL sg_usage sg_query_buffer_usage(sg_buffer buf);
  3597. SOKOL_GFX_API_DECL sg_image_type sg_query_image_type(sg_image img);
  3598. SOKOL_GFX_API_DECL int sg_query_image_width(sg_image img);
  3599. SOKOL_GFX_API_DECL int sg_query_image_height(sg_image img);
  3600. SOKOL_GFX_API_DECL int sg_query_image_num_slices(sg_image img);
  3601. SOKOL_GFX_API_DECL int sg_query_image_num_mipmaps(sg_image img);
  3602. SOKOL_GFX_API_DECL sg_pixel_format sg_query_image_pixelformat(sg_image img);
  3603. SOKOL_GFX_API_DECL sg_usage sg_query_image_usage(sg_image img);
  3604. SOKOL_GFX_API_DECL int sg_query_image_sample_count(sg_image img);
  3605. // separate resource allocation and initialization (for async setup)
  3606. SOKOL_GFX_API_DECL sg_buffer sg_alloc_buffer(void);
  3607. SOKOL_GFX_API_DECL sg_image sg_alloc_image(void);
  3608. SOKOL_GFX_API_DECL sg_sampler sg_alloc_sampler(void);
  3609. SOKOL_GFX_API_DECL sg_shader sg_alloc_shader(void);
  3610. SOKOL_GFX_API_DECL sg_pipeline sg_alloc_pipeline(void);
  3611. SOKOL_GFX_API_DECL sg_attachments sg_alloc_attachments(void);
  3612. SOKOL_GFX_API_DECL void sg_dealloc_buffer(sg_buffer buf);
  3613. SOKOL_GFX_API_DECL void sg_dealloc_image(sg_image img);
  3614. SOKOL_GFX_API_DECL void sg_dealloc_sampler(sg_sampler smp);
  3615. SOKOL_GFX_API_DECL void sg_dealloc_shader(sg_shader shd);
  3616. SOKOL_GFX_API_DECL void sg_dealloc_pipeline(sg_pipeline pip);
  3617. SOKOL_GFX_API_DECL void sg_dealloc_attachments(sg_attachments attachments);
  3618. SOKOL_GFX_API_DECL void sg_init_buffer(sg_buffer buf, const sg_buffer_desc* desc);
  3619. SOKOL_GFX_API_DECL void sg_init_image(sg_image img, const sg_image_desc* desc);
  3620. SOKOL_GFX_API_DECL void sg_init_sampler(sg_sampler smg, const sg_sampler_desc* desc);
  3621. SOKOL_GFX_API_DECL void sg_init_shader(sg_shader shd, const sg_shader_desc* desc);
  3622. SOKOL_GFX_API_DECL void sg_init_pipeline(sg_pipeline pip, const sg_pipeline_desc* desc);
  3623. SOKOL_GFX_API_DECL void sg_init_attachments(sg_attachments attachments, const sg_attachments_desc* desc);
  3624. SOKOL_GFX_API_DECL void sg_uninit_buffer(sg_buffer buf);
  3625. SOKOL_GFX_API_DECL void sg_uninit_image(sg_image img);
  3626. SOKOL_GFX_API_DECL void sg_uninit_sampler(sg_sampler smp);
  3627. SOKOL_GFX_API_DECL void sg_uninit_shader(sg_shader shd);
  3628. SOKOL_GFX_API_DECL void sg_uninit_pipeline(sg_pipeline pip);
  3629. SOKOL_GFX_API_DECL void sg_uninit_attachments(sg_attachments atts);
  3630. SOKOL_GFX_API_DECL void sg_fail_buffer(sg_buffer buf);
  3631. SOKOL_GFX_API_DECL void sg_fail_image(sg_image img);
  3632. SOKOL_GFX_API_DECL void sg_fail_sampler(sg_sampler smp);
  3633. SOKOL_GFX_API_DECL void sg_fail_shader(sg_shader shd);
  3634. SOKOL_GFX_API_DECL void sg_fail_pipeline(sg_pipeline pip);
  3635. SOKOL_GFX_API_DECL void sg_fail_attachments(sg_attachments atts);
  3636. // frame stats
  3637. SOKOL_GFX_API_DECL void sg_enable_frame_stats(void);
  3638. SOKOL_GFX_API_DECL void sg_disable_frame_stats(void);
  3639. SOKOL_GFX_API_DECL bool sg_frame_stats_enabled(void);
  3640. SOKOL_GFX_API_DECL sg_frame_stats sg_query_frame_stats(void);
  3641. /* Backend-specific structs and functions, these may come in handy for mixing
  3642. sokol-gfx rendering with 'native backend' rendering functions.
  3643. This group of functions will be expanded as needed.
  3644. */
  3645. typedef struct sg_d3d11_buffer_info {
  3646. const void* buf; // ID3D11Buffer*
  3647. } sg_d3d11_buffer_info;
  3648. typedef struct sg_d3d11_image_info {
  3649. const void* tex2d; // ID3D11Texture2D*
  3650. const void* tex3d; // ID3D11Texture3D*
  3651. const void* res; // ID3D11Resource* (either tex2d or tex3d)
  3652. const void* srv; // ID3D11ShaderResourceView*
  3653. } sg_d3d11_image_info;
  3654. typedef struct sg_d3d11_sampler_info {
  3655. const void* smp; // ID3D11SamplerState*
  3656. } sg_d3d11_sampler_info;
  3657. typedef struct sg_d3d11_shader_info {
  3658. const void* cbufs[SG_MAX_UNIFORMBLOCK_BINDSLOTS]; // ID3D11Buffer* (constant buffers by bind slot)
  3659. const void* vs; // ID3D11VertexShader*
  3660. const void* fs; // ID3D11PixelShader*
  3661. } sg_d3d11_shader_info;
  3662. typedef struct sg_d3d11_pipeline_info {
  3663. const void* il; // ID3D11InputLayout*
  3664. const void* rs; // ID3D11RasterizerState*
  3665. const void* dss; // ID3D11DepthStencilState*
  3666. const void* bs; // ID3D11BlendState*
  3667. } sg_d3d11_pipeline_info;
  3668. typedef struct sg_d3d11_attachments_info {
  3669. const void* color_rtv[SG_MAX_COLOR_ATTACHMENTS]; // ID3D11RenderTargetView
  3670. const void* resolve_rtv[SG_MAX_COLOR_ATTACHMENTS]; // ID3D11RenderTargetView
  3671. const void* dsv; // ID3D11DepthStencilView
  3672. } sg_d3d11_attachments_info;
  3673. typedef struct sg_mtl_buffer_info {
  3674. const void* buf[SG_NUM_INFLIGHT_FRAMES]; // id<MTLBuffer>
  3675. int active_slot;
  3676. } sg_mtl_buffer_info;
  3677. typedef struct sg_mtl_image_info {
  3678. const void* tex[SG_NUM_INFLIGHT_FRAMES]; // id<MTLTexture>
  3679. int active_slot;
  3680. } sg_mtl_image_info;
  3681. typedef struct sg_mtl_sampler_info {
  3682. const void* smp; // id<MTLSamplerState>
  3683. } sg_mtl_sampler_info;
  3684. typedef struct sg_mtl_shader_info {
  3685. const void* vertex_lib; // id<MTLLibrary>
  3686. const void* fragment_lib; // id<MTLLibrary>
  3687. const void* vertex_func; // id<MTLFunction>
  3688. const void* fragment_func; // id<MTLFunction>
  3689. } sg_mtl_shader_info;
  3690. typedef struct sg_mtl_pipeline_info {
  3691. const void* rps; // id<MTLRenderPipelineState>
  3692. const void* dss; // id<MTLDepthStencilState>
  3693. } sg_mtl_pipeline_info;
  3694. typedef struct sg_wgpu_buffer_info {
  3695. const void* buf; // WGPUBuffer
  3696. } sg_wgpu_buffer_info;
  3697. typedef struct sg_wgpu_image_info {
  3698. const void* tex; // WGPUTexture
  3699. const void* view; // WGPUTextureView
  3700. } sg_wgpu_image_info;
  3701. typedef struct sg_wgpu_sampler_info {
  3702. const void* smp; // WGPUSampler
  3703. } sg_wgpu_sampler_info;
  3704. typedef struct sg_wgpu_shader_info {
  3705. const void* vs_mod; // WGPUShaderModule
  3706. const void* fs_mod; // WGPUShaderModule
  3707. const void* bgl; // WGPUBindGroupLayout;
  3708. } sg_wgpu_shader_info;
  3709. typedef struct sg_wgpu_pipeline_info {
  3710. const void* pip; // WGPURenderPipeline
  3711. } sg_wgpu_pipeline_info;
  3712. typedef struct sg_wgpu_attachments_info {
  3713. const void* color_view[SG_MAX_COLOR_ATTACHMENTS]; // WGPUTextureView
  3714. const void* resolve_view[SG_MAX_COLOR_ATTACHMENTS]; // WGPUTextureView
  3715. const void* ds_view; // WGPUTextureView
  3716. } sg_wgpu_attachments_info;
  3717. typedef struct sg_gl_buffer_info {
  3718. uint32_t buf[SG_NUM_INFLIGHT_FRAMES];
  3719. int active_slot;
  3720. } sg_gl_buffer_info;
  3721. typedef struct sg_gl_image_info {
  3722. uint32_t tex[SG_NUM_INFLIGHT_FRAMES];
  3723. uint32_t tex_target;
  3724. uint32_t msaa_render_buffer;
  3725. int active_slot;
  3726. } sg_gl_image_info;
  3727. typedef struct sg_gl_sampler_info {
  3728. uint32_t smp;
  3729. } sg_gl_sampler_info;
  3730. typedef struct sg_gl_shader_info {
  3731. uint32_t prog;
  3732. } sg_gl_shader_info;
  3733. typedef struct sg_gl_attachments_info {
  3734. uint32_t framebuffer;
  3735. uint32_t msaa_resolve_framebuffer[SG_MAX_COLOR_ATTACHMENTS];
  3736. } sg_gl_attachments_info;
  3737. // D3D11: return ID3D11Device
  3738. SOKOL_GFX_API_DECL const void* sg_d3d11_device(void);
  3739. // D3D11: return ID3D11DeviceContext
  3740. SOKOL_GFX_API_DECL const void* sg_d3d11_device_context(void);
  3741. // D3D11: get internal buffer resource objects
  3742. SOKOL_GFX_API_DECL sg_d3d11_buffer_info sg_d3d11_query_buffer_info(sg_buffer buf);
  3743. // D3D11: get internal image resource objects
  3744. SOKOL_GFX_API_DECL sg_d3d11_image_info sg_d3d11_query_image_info(sg_image img);
  3745. // D3D11: get internal sampler resource objects
  3746. SOKOL_GFX_API_DECL sg_d3d11_sampler_info sg_d3d11_query_sampler_info(sg_sampler smp);
  3747. // D3D11: get internal shader resource objects
  3748. SOKOL_GFX_API_DECL sg_d3d11_shader_info sg_d3d11_query_shader_info(sg_shader shd);
  3749. // D3D11: get internal pipeline resource objects
  3750. SOKOL_GFX_API_DECL sg_d3d11_pipeline_info sg_d3d11_query_pipeline_info(sg_pipeline pip);
  3751. // D3D11: get internal pass resource objects
  3752. SOKOL_GFX_API_DECL sg_d3d11_attachments_info sg_d3d11_query_attachments_info(sg_attachments atts);
  3753. // Metal: return __bridge-casted MTLDevice
  3754. SOKOL_GFX_API_DECL const void* sg_mtl_device(void);
  3755. // Metal: return __bridge-casted MTLRenderCommandEncoder in current pass (or zero if outside pass)
  3756. SOKOL_GFX_API_DECL const void* sg_mtl_render_command_encoder(void);
  3757. // Metal: get internal __bridge-casted buffer resource objects
  3758. SOKOL_GFX_API_DECL sg_mtl_buffer_info sg_mtl_query_buffer_info(sg_buffer buf);
  3759. // Metal: get internal __bridge-casted image resource objects
  3760. SOKOL_GFX_API_DECL sg_mtl_image_info sg_mtl_query_image_info(sg_image img);
  3761. // Metal: get internal __bridge-casted sampler resource objects
  3762. SOKOL_GFX_API_DECL sg_mtl_sampler_info sg_mtl_query_sampler_info(sg_sampler smp);
  3763. // Metal: get internal __bridge-casted shader resource objects
  3764. SOKOL_GFX_API_DECL sg_mtl_shader_info sg_mtl_query_shader_info(sg_shader shd);
  3765. // Metal: get internal __bridge-casted pipeline resource objects
  3766. SOKOL_GFX_API_DECL sg_mtl_pipeline_info sg_mtl_query_pipeline_info(sg_pipeline pip);
  3767. // WebGPU: return WGPUDevice object
  3768. SOKOL_GFX_API_DECL const void* sg_wgpu_device(void);
  3769. // WebGPU: return WGPUQueue object
  3770. SOKOL_GFX_API_DECL const void* sg_wgpu_queue(void);
  3771. // WebGPU: return this frame's WGPUCommandEncoder
  3772. SOKOL_GFX_API_DECL const void* sg_wgpu_command_encoder(void);
  3773. // WebGPU: return WGPURenderPassEncoder of current pass
  3774. SOKOL_GFX_API_DECL const void* sg_wgpu_render_pass_encoder(void);
  3775. // WebGPU: get internal buffer resource objects
  3776. SOKOL_GFX_API_DECL sg_wgpu_buffer_info sg_wgpu_query_buffer_info(sg_buffer buf);
  3777. // WebGPU: get internal image resource objects
  3778. SOKOL_GFX_API_DECL sg_wgpu_image_info sg_wgpu_query_image_info(sg_image img);
  3779. // WebGPU: get internal sampler resource objects
  3780. SOKOL_GFX_API_DECL sg_wgpu_sampler_info sg_wgpu_query_sampler_info(sg_sampler smp);
  3781. // WebGPU: get internal shader resource objects
  3782. SOKOL_GFX_API_DECL sg_wgpu_shader_info sg_wgpu_query_shader_info(sg_shader shd);
  3783. // WebGPU: get internal pipeline resource objects
  3784. SOKOL_GFX_API_DECL sg_wgpu_pipeline_info sg_wgpu_query_pipeline_info(sg_pipeline pip);
  3785. // WebGPU: get internal pass resource objects
  3786. SOKOL_GFX_API_DECL sg_wgpu_attachments_info sg_wgpu_query_attachments_info(sg_attachments atts);
  3787. // GL: get internal buffer resource objects
  3788. SOKOL_GFX_API_DECL sg_gl_buffer_info sg_gl_query_buffer_info(sg_buffer buf);
  3789. // GL: get internal image resource objects
  3790. SOKOL_GFX_API_DECL sg_gl_image_info sg_gl_query_image_info(sg_image img);
  3791. // GL: get internal sampler resource objects
  3792. SOKOL_GFX_API_DECL sg_gl_sampler_info sg_gl_query_sampler_info(sg_sampler smp);
  3793. // GL: get internal shader resource objects
  3794. SOKOL_GFX_API_DECL sg_gl_shader_info sg_gl_query_shader_info(sg_shader shd);
  3795. // GL: get internal pass resource objects
  3796. SOKOL_GFX_API_DECL sg_gl_attachments_info sg_gl_query_attachments_info(sg_attachments atts);
  3797. #ifdef __cplusplus
  3798. } // extern "C"
  3799. // reference-based equivalents for c++
  3800. inline void sg_setup(const sg_desc& desc) { return sg_setup(&desc); }
  3801. inline sg_buffer sg_make_buffer(const sg_buffer_desc& desc) { return sg_make_buffer(&desc); }
  3802. inline sg_image sg_make_image(const sg_image_desc& desc) { return sg_make_image(&desc); }
  3803. inline sg_sampler sg_make_sampler(const sg_sampler_desc& desc) { return sg_make_sampler(&desc); }
  3804. inline sg_shader sg_make_shader(const sg_shader_desc& desc) { return sg_make_shader(&desc); }
  3805. inline sg_pipeline sg_make_pipeline(const sg_pipeline_desc& desc) { return sg_make_pipeline(&desc); }
  3806. inline sg_attachments sg_make_attachments(const sg_attachments_desc& desc) { return sg_make_attachments(&desc); }
  3807. inline void sg_update_image(sg_image img, const sg_image_data& data) { return sg_update_image(img, &data); }
  3808. inline void sg_begin_pass(const sg_pass& pass) { return sg_begin_pass(&pass); }
  3809. inline void sg_apply_bindings(const sg_bindings& bindings) { return sg_apply_bindings(&bindings); }
  3810. inline void sg_apply_uniforms(int ub_slot, const sg_range& data) { return sg_apply_uniforms(ub_slot, &data); }
  3811. inline sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc& desc) { return sg_query_buffer_defaults(&desc); }
  3812. inline sg_image_desc sg_query_image_defaults(const sg_image_desc& desc) { return sg_query_image_defaults(&desc); }
  3813. inline sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc& desc) { return sg_query_sampler_defaults(&desc); }
  3814. inline sg_shader_desc sg_query_shader_defaults(const sg_shader_desc& desc) { return sg_query_shader_defaults(&desc); }
  3815. inline sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc& desc) { return sg_query_pipeline_defaults(&desc); }
  3816. inline sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc& desc) { return sg_query_attachments_defaults(&desc); }
  3817. inline void sg_init_buffer(sg_buffer buf, const sg_buffer_desc& desc) { return sg_init_buffer(buf, &desc); }
  3818. inline void sg_init_image(sg_image img, const sg_image_desc& desc) { return sg_init_image(img, &desc); }
  3819. inline void sg_init_sampler(sg_sampler smp, const sg_sampler_desc& desc) { return sg_init_sampler(smp, &desc); }
  3820. inline void sg_init_shader(sg_shader shd, const sg_shader_desc& desc) { return sg_init_shader(shd, &desc); }
  3821. inline void sg_init_pipeline(sg_pipeline pip, const sg_pipeline_desc& desc) { return sg_init_pipeline(pip, &desc); }
  3822. inline void sg_init_attachments(sg_attachments atts, const sg_attachments_desc& desc) { return sg_init_attachments(atts, &desc); }
  3823. inline void sg_update_buffer(sg_buffer buf_id, const sg_range& data) { return sg_update_buffer(buf_id, &data); }
  3824. inline int sg_append_buffer(sg_buffer buf_id, const sg_range& data) { return sg_append_buffer(buf_id, &data); }
  3825. #endif
  3826. #endif // SOKOL_GFX_INCLUDED
  3827. // ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
  3828. // ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  3829. // ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  3830. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  3831. // ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
  3832. //
  3833. // >>implementation
  3834. #ifdef SOKOL_GFX_IMPL
  3835. #define SOKOL_GFX_IMPL_INCLUDED (1)
  3836. #if !(defined(SOKOL_GLCORE)||defined(SOKOL_GLES3)||defined(SOKOL_D3D11)||defined(SOKOL_METAL)||defined(SOKOL_WGPU)||defined(SOKOL_DUMMY_BACKEND))
  3837. #error "Please select a backend with SOKOL_GLCORE, SOKOL_GLES3, SOKOL_D3D11, SOKOL_METAL, SOKOL_WGPU or SOKOL_DUMMY_BACKEND"
  3838. #endif
  3839. #if defined(SOKOL_MALLOC) || defined(SOKOL_CALLOC) || defined(SOKOL_FREE)
  3840. #error "SOKOL_MALLOC/CALLOC/FREE macros are no longer supported, please use sg_desc.allocator to override memory allocation functions"
  3841. #endif
  3842. #include <stdlib.h> // malloc, free, qsort
  3843. #include <string.h> // memset
  3844. #include <float.h> // FLT_MAX
  3845. #ifndef SOKOL_API_IMPL
  3846. #define SOKOL_API_IMPL
  3847. #endif
  3848. #ifndef SOKOL_DEBUG
  3849. #ifndef NDEBUG
  3850. #define SOKOL_DEBUG
  3851. #endif
  3852. #endif
  3853. #ifndef SOKOL_ASSERT
  3854. #include <assert.h>
  3855. #define SOKOL_ASSERT(c) assert(c)
  3856. #endif
  3857. #ifndef SOKOL_UNREACHABLE
  3858. #define SOKOL_UNREACHABLE SOKOL_ASSERT(false)
  3859. #endif
  3860. #ifndef _SOKOL_PRIVATE
  3861. #if defined(__GNUC__) || defined(__clang__)
  3862. #define _SOKOL_PRIVATE __attribute__((unused)) static
  3863. #else
  3864. #define _SOKOL_PRIVATE static
  3865. #endif
  3866. #endif
  3867. #ifndef _SOKOL_UNUSED
  3868. #define _SOKOL_UNUSED(x) (void)(x)
  3869. #endif
  3870. #if defined(SOKOL_TRACE_HOOKS)
  3871. #define _SG_TRACE_ARGS(fn, ...) if (_sg.hooks.fn) { _sg.hooks.fn(__VA_ARGS__, _sg.hooks.user_data); }
  3872. #define _SG_TRACE_NOARGS(fn) if (_sg.hooks.fn) { _sg.hooks.fn(_sg.hooks.user_data); }
  3873. #else
  3874. #define _SG_TRACE_ARGS(fn, ...)
  3875. #define _SG_TRACE_NOARGS(fn)
  3876. #endif
  3877. // default clear values
  3878. #ifndef SG_DEFAULT_CLEAR_RED
  3879. #define SG_DEFAULT_CLEAR_RED (0.5f)
  3880. #endif
  3881. #ifndef SG_DEFAULT_CLEAR_GREEN
  3882. #define SG_DEFAULT_CLEAR_GREEN (0.5f)
  3883. #endif
  3884. #ifndef SG_DEFAULT_CLEAR_BLUE
  3885. #define SG_DEFAULT_CLEAR_BLUE (0.5f)
  3886. #endif
  3887. #ifndef SG_DEFAULT_CLEAR_ALPHA
  3888. #define SG_DEFAULT_CLEAR_ALPHA (1.0f)
  3889. #endif
  3890. #ifndef SG_DEFAULT_CLEAR_DEPTH
  3891. #define SG_DEFAULT_CLEAR_DEPTH (1.0f)
  3892. #endif
  3893. #ifndef SG_DEFAULT_CLEAR_STENCIL
  3894. #define SG_DEFAULT_CLEAR_STENCIL (0)
  3895. #endif
  3896. #ifdef _MSC_VER
  3897. #pragma warning(push)
  3898. #pragma warning(disable:4115) // named type definition in parentheses
  3899. #pragma warning(disable:4505) // unreferenced local function has been removed
  3900. #pragma warning(disable:4201) // nonstandard extension used: nameless struct/union (needed by d3d11.h)
  3901. #pragma warning(disable:4054) // 'type cast': from function pointer
  3902. #pragma warning(disable:4055) // 'type cast': from data pointer
  3903. #endif
  3904. #if defined(SOKOL_D3D11)
  3905. #ifndef D3D11_NO_HELPERS
  3906. #define D3D11_NO_HELPERS
  3907. #endif
  3908. #ifndef WIN32_LEAN_AND_MEAN
  3909. #define WIN32_LEAN_AND_MEAN
  3910. #endif
  3911. #ifndef NOMINMAX
  3912. #define NOMINMAX
  3913. #endif
  3914. #include <d3d11.h>
  3915. #include <d3dcompiler.h>
  3916. #ifdef _MSC_VER
  3917. #pragma comment (lib, "kernel32")
  3918. #pragma comment (lib, "user32")
  3919. #pragma comment (lib, "dxgi")
  3920. #pragma comment (lib, "d3d11")
  3921. #endif
  3922. #elif defined(SOKOL_METAL)
  3923. // see https://clang.llvm.org/docs/LanguageExtensions.html#automatic-reference-counting
  3924. #if !defined(__cplusplus)
  3925. #if __has_feature(objc_arc) && !__has_feature(objc_arc_fields)
  3926. #error "sokol_gfx.h requires __has_feature(objc_arc_field) if ARC is enabled (use a more recent compiler version)"
  3927. #endif
  3928. #endif
  3929. #include <TargetConditionals.h>
  3930. #include <AvailabilityMacros.h>
  3931. #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE
  3932. #define _SG_TARGET_MACOS (1)
  3933. #else
  3934. #define _SG_TARGET_IOS (1)
  3935. #if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR
  3936. #define _SG_TARGET_IOS_SIMULATOR (1)
  3937. #endif
  3938. #endif
  3939. #import <Metal/Metal.h>
  3940. #import <QuartzCore/CoreAnimation.h> // needed for CAMetalDrawable
  3941. #elif defined(SOKOL_WGPU)
  3942. #include <webgpu/webgpu.h>
  3943. #if defined(__EMSCRIPTEN__)
  3944. #include <emscripten/emscripten.h>
  3945. #endif
  3946. #elif defined(SOKOL_GLCORE) || defined(SOKOL_GLES3)
  3947. #define _SOKOL_ANY_GL (1)
  3948. // include platform specific GL headers (or on Win32: use an embedded GL loader)
  3949. #if !defined(SOKOL_EXTERNAL_GL_LOADER)
  3950. #if defined(_WIN32)
  3951. #if defined(SOKOL_GLCORE) && !defined(SOKOL_EXTERNAL_GL_LOADER)
  3952. #ifndef WIN32_LEAN_AND_MEAN
  3953. #define WIN32_LEAN_AND_MEAN
  3954. #endif
  3955. #ifndef NOMINMAX
  3956. #define NOMINMAX
  3957. #endif
  3958. #include <windows.h>
  3959. #define _SOKOL_USE_WIN32_GL_LOADER (1)
  3960. #pragma comment (lib, "kernel32") // GetProcAddress()
  3961. #endif
  3962. #elif defined(__APPLE__)
  3963. #include <TargetConditionals.h>
  3964. #ifndef GL_SILENCE_DEPRECATION
  3965. #define GL_SILENCE_DEPRECATION
  3966. #endif
  3967. #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE
  3968. #include <OpenGL/gl3.h>
  3969. #else
  3970. #include <OpenGLES/ES3/gl.h>
  3971. #include <OpenGLES/ES3/glext.h>
  3972. #endif
  3973. #elif defined(__EMSCRIPTEN__) || defined(__ANDROID__)
  3974. #if defined(SOKOL_GLES3)
  3975. #include <GLES3/gl3.h>
  3976. #endif
  3977. #elif defined(__linux__) || defined(__unix__)
  3978. #if defined(SOKOL_GLCORE)
  3979. #define GL_GLEXT_PROTOTYPES
  3980. #include <GL/gl.h>
  3981. #else
  3982. #include <GLES3/gl3.h>
  3983. #include <GLES3/gl3ext.h>
  3984. #endif
  3985. #endif
  3986. #endif
  3987. // optional GL loader definitions (only on Win32)
  3988. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  3989. #define __gl_h_ 1
  3990. #define __gl32_h_ 1
  3991. #define __gl31_h_ 1
  3992. #define __GL_H__ 1
  3993. #define __glext_h_ 1
  3994. #define __GLEXT_H_ 1
  3995. #define __gltypes_h_ 1
  3996. #define __glcorearb_h_ 1
  3997. #define __gl_glcorearb_h_ 1
  3998. #define GL_APIENTRY APIENTRY
  3999. typedef unsigned int GLenum;
  4000. typedef unsigned int GLuint;
  4001. typedef int GLsizei;
  4002. typedef char GLchar;
  4003. typedef ptrdiff_t GLintptr;
  4004. typedef ptrdiff_t GLsizeiptr;
  4005. typedef double GLclampd;
  4006. typedef unsigned short GLushort;
  4007. typedef unsigned char GLubyte;
  4008. typedef unsigned char GLboolean;
  4009. typedef uint64_t GLuint64;
  4010. typedef double GLdouble;
  4011. typedef unsigned short GLhalf;
  4012. typedef float GLclampf;
  4013. typedef unsigned int GLbitfield;
  4014. typedef signed char GLbyte;
  4015. typedef short GLshort;
  4016. typedef void GLvoid;
  4017. typedef int64_t GLint64;
  4018. typedef float GLfloat;
  4019. typedef int GLint;
  4020. #define GL_INT_2_10_10_10_REV 0x8D9F
  4021. #define GL_R32F 0x822E
  4022. #define GL_PROGRAM_POINT_SIZE 0x8642
  4023. #define GL_DEPTH_ATTACHMENT 0x8D00
  4024. #define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
  4025. #define GL_COLOR_ATTACHMENT2 0x8CE2
  4026. #define GL_COLOR_ATTACHMENT0 0x8CE0
  4027. #define GL_R16F 0x822D
  4028. #define GL_COLOR_ATTACHMENT22 0x8CF6
  4029. #define GL_DRAW_FRAMEBUFFER 0x8CA9
  4030. #define GL_FRAMEBUFFER_COMPLETE 0x8CD5
  4031. #define GL_NUM_EXTENSIONS 0x821D
  4032. #define GL_INFO_LOG_LENGTH 0x8B84
  4033. #define GL_VERTEX_SHADER 0x8B31
  4034. #define GL_INCR 0x1E02
  4035. #define GL_DYNAMIC_DRAW 0x88E8
  4036. #define GL_STATIC_DRAW 0x88E4
  4037. #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
  4038. #define GL_TEXTURE_CUBE_MAP 0x8513
  4039. #define GL_FUNC_SUBTRACT 0x800A
  4040. #define GL_FUNC_REVERSE_SUBTRACT 0x800B
  4041. #define GL_CONSTANT_COLOR 0x8001
  4042. #define GL_DECR_WRAP 0x8508
  4043. #define GL_R8 0x8229
  4044. #define GL_LINEAR_MIPMAP_LINEAR 0x2703
  4045. #define GL_ELEMENT_ARRAY_BUFFER 0x8893
  4046. #define GL_SHORT 0x1402
  4047. #define GL_DEPTH_TEST 0x0B71
  4048. #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
  4049. #define GL_LINK_STATUS 0x8B82
  4050. #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
  4051. #define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
  4052. #define GL_RGBA16F 0x881A
  4053. #define GL_CONSTANT_ALPHA 0x8003
  4054. #define GL_READ_FRAMEBUFFER 0x8CA8
  4055. #define GL_TEXTURE0 0x84C0
  4056. #define GL_TEXTURE_MIN_LOD 0x813A
  4057. #define GL_CLAMP_TO_EDGE 0x812F
  4058. #define GL_UNSIGNED_SHORT_5_6_5 0x8363
  4059. #define GL_TEXTURE_WRAP_R 0x8072
  4060. #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034
  4061. #define GL_NEAREST_MIPMAP_NEAREST 0x2700
  4062. #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033
  4063. #define GL_SRC_ALPHA_SATURATE 0x0308
  4064. #define GL_STREAM_DRAW 0x88E0
  4065. #define GL_ONE 1
  4066. #define GL_NEAREST_MIPMAP_LINEAR 0x2702
  4067. #define GL_RGB10_A2 0x8059
  4068. #define GL_RGBA8 0x8058
  4069. #define GL_SRGB8_ALPHA8 0x8C43
  4070. #define GL_COLOR_ATTACHMENT1 0x8CE1
  4071. #define GL_RGBA4 0x8056
  4072. #define GL_RGB8 0x8051
  4073. #define GL_ARRAY_BUFFER 0x8892
  4074. #define GL_STENCIL 0x1802
  4075. #define GL_TEXTURE_2D 0x0DE1
  4076. #define GL_DEPTH 0x1801
  4077. #define GL_FRONT 0x0404
  4078. #define GL_STENCIL_BUFFER_BIT 0x00000400
  4079. #define GL_REPEAT 0x2901
  4080. #define GL_RGBA 0x1908
  4081. #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
  4082. #define GL_DECR 0x1E03
  4083. #define GL_FRAGMENT_SHADER 0x8B30
  4084. #define GL_FLOAT 0x1406
  4085. #define GL_TEXTURE_MAX_LOD 0x813B
  4086. #define GL_DEPTH_COMPONENT 0x1902
  4087. #define GL_ONE_MINUS_DST_ALPHA 0x0305
  4088. #define GL_COLOR 0x1800
  4089. #define GL_TEXTURE_2D_ARRAY 0x8C1A
  4090. #define GL_TRIANGLES 0x0004
  4091. #define GL_UNSIGNED_BYTE 0x1401
  4092. #define GL_TEXTURE_MAG_FILTER 0x2800
  4093. #define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004
  4094. #define GL_NONE 0
  4095. #define GL_SRC_COLOR 0x0300
  4096. #define GL_BYTE 0x1400
  4097. #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
  4098. #define GL_LINE_STRIP 0x0003
  4099. #define GL_TEXTURE_3D 0x806F
  4100. #define GL_CW 0x0900
  4101. #define GL_LINEAR 0x2601
  4102. #define GL_RENDERBUFFER 0x8D41
  4103. #define GL_GEQUAL 0x0206
  4104. #define GL_COLOR_BUFFER_BIT 0x00004000
  4105. #define GL_RGBA32F 0x8814
  4106. #define GL_BLEND 0x0BE2
  4107. #define GL_ONE_MINUS_SRC_ALPHA 0x0303
  4108. #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
  4109. #define GL_TEXTURE_WRAP_T 0x2803
  4110. #define GL_TEXTURE_WRAP_S 0x2802
  4111. #define GL_TEXTURE_MIN_FILTER 0x2801
  4112. #define GL_LINEAR_MIPMAP_NEAREST 0x2701
  4113. #define GL_EXTENSIONS 0x1F03
  4114. #define GL_NO_ERROR 0
  4115. #define GL_REPLACE 0x1E01
  4116. #define GL_KEEP 0x1E00
  4117. #define GL_CCW 0x0901
  4118. #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
  4119. #define GL_RGB 0x1907
  4120. #define GL_TRIANGLE_STRIP 0x0005
  4121. #define GL_FALSE 0
  4122. #define GL_ZERO 0
  4123. #define GL_CULL_FACE 0x0B44
  4124. #define GL_INVERT 0x150A
  4125. #define GL_INT 0x1404
  4126. #define GL_UNSIGNED_INT 0x1405
  4127. #define GL_UNSIGNED_SHORT 0x1403
  4128. #define GL_NEAREST 0x2600
  4129. #define GL_SCISSOR_TEST 0x0C11
  4130. #define GL_LEQUAL 0x0203
  4131. #define GL_STENCIL_TEST 0x0B90
  4132. #define GL_DITHER 0x0BD0
  4133. #define GL_DEPTH_COMPONENT32F 0x8CAC
  4134. #define GL_EQUAL 0x0202
  4135. #define GL_FRAMEBUFFER 0x8D40
  4136. #define GL_RGB5 0x8050
  4137. #define GL_LINES 0x0001
  4138. #define GL_DEPTH_BUFFER_BIT 0x00000100
  4139. #define GL_SRC_ALPHA 0x0302
  4140. #define GL_INCR_WRAP 0x8507
  4141. #define GL_LESS 0x0201
  4142. #define GL_MULTISAMPLE 0x809D
  4143. #define GL_FRAMEBUFFER_BINDING 0x8CA6
  4144. #define GL_BACK 0x0405
  4145. #define GL_ALWAYS 0x0207
  4146. #define GL_FUNC_ADD 0x8006
  4147. #define GL_ONE_MINUS_DST_COLOR 0x0307
  4148. #define GL_NOTEQUAL 0x0205
  4149. #define GL_DST_COLOR 0x0306
  4150. #define GL_COMPILE_STATUS 0x8B81
  4151. #define GL_RED 0x1903
  4152. #define GL_COLOR_ATTACHMENT3 0x8CE3
  4153. #define GL_DST_ALPHA 0x0304
  4154. #define GL_RGB5_A1 0x8057
  4155. #define GL_GREATER 0x0204
  4156. #define GL_POLYGON_OFFSET_FILL 0x8037
  4157. #define GL_TRUE 1
  4158. #define GL_NEVER 0x0200
  4159. #define GL_POINTS 0x0000
  4160. #define GL_ONE_MINUS_SRC_COLOR 0x0301
  4161. #define GL_MIRRORED_REPEAT 0x8370
  4162. #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
  4163. #define GL_R11F_G11F_B10F 0x8C3A
  4164. #define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B
  4165. #define GL_RGB9_E5 0x8C3D
  4166. #define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E
  4167. #define GL_RGBA32UI 0x8D70
  4168. #define GL_RGB32UI 0x8D71
  4169. #define GL_RGBA16UI 0x8D76
  4170. #define GL_RGB16UI 0x8D77
  4171. #define GL_RGBA8UI 0x8D7C
  4172. #define GL_RGB8UI 0x8D7D
  4173. #define GL_RGBA32I 0x8D82
  4174. #define GL_RGB32I 0x8D83
  4175. #define GL_RGBA16I 0x8D88
  4176. #define GL_RGB16I 0x8D89
  4177. #define GL_RGBA8I 0x8D8E
  4178. #define GL_RGB8I 0x8D8F
  4179. #define GL_RED_INTEGER 0x8D94
  4180. #define GL_RG 0x8227
  4181. #define GL_RG_INTEGER 0x8228
  4182. #define GL_R8 0x8229
  4183. #define GL_R16 0x822A
  4184. #define GL_RG8 0x822B
  4185. #define GL_RG16 0x822C
  4186. #define GL_R16F 0x822D
  4187. #define GL_R32F 0x822E
  4188. #define GL_RG16F 0x822F
  4189. #define GL_RG32F 0x8230
  4190. #define GL_R8I 0x8231
  4191. #define GL_R8UI 0x8232
  4192. #define GL_R16I 0x8233
  4193. #define GL_R16UI 0x8234
  4194. #define GL_R32I 0x8235
  4195. #define GL_R32UI 0x8236
  4196. #define GL_RG8I 0x8237
  4197. #define GL_RG8UI 0x8238
  4198. #define GL_RG16I 0x8239
  4199. #define GL_RG16UI 0x823A
  4200. #define GL_RG32I 0x823B
  4201. #define GL_RG32UI 0x823C
  4202. #define GL_RGBA_INTEGER 0x8D99
  4203. #define GL_R8_SNORM 0x8F94
  4204. #define GL_RG8_SNORM 0x8F95
  4205. #define GL_RGB8_SNORM 0x8F96
  4206. #define GL_RGBA8_SNORM 0x8F97
  4207. #define GL_R16_SNORM 0x8F98
  4208. #define GL_RG16_SNORM 0x8F99
  4209. #define GL_RGB16_SNORM 0x8F9A
  4210. #define GL_RGBA16_SNORM 0x8F9B
  4211. #define GL_RGBA16 0x805B
  4212. #define GL_MAX_TEXTURE_SIZE 0x0D33
  4213. #define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
  4214. #define GL_MAX_3D_TEXTURE_SIZE 0x8073
  4215. #define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF
  4216. #define GL_MAX_VERTEX_ATTRIBS 0x8869
  4217. #define GL_CLAMP_TO_BORDER 0x812D
  4218. #define GL_TEXTURE_BORDER_COLOR 0x1004
  4219. #define GL_CURRENT_PROGRAM 0x8B8D
  4220. #define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A
  4221. #define GL_UNPACK_ALIGNMENT 0x0CF5
  4222. #define GL_FRAMEBUFFER_SRGB 0x8DB9
  4223. #define GL_TEXTURE_COMPARE_MODE 0x884C
  4224. #define GL_TEXTURE_COMPARE_FUNC 0x884D
  4225. #define GL_COMPARE_REF_TO_TEXTURE 0x884E
  4226. #define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F
  4227. #define GL_TEXTURE_MAX_LEVEL 0x813D
  4228. #define GL_FRAMEBUFFER_UNDEFINED 0x8219
  4229. #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6
  4230. #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
  4231. #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD
  4232. #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56
  4233. #define GL_MAJOR_VERSION 0x821B
  4234. #define GL_MINOR_VERSION 0x821C
  4235. #define GL_TEXTURE_2D_MULTISAMPLE 0x9100
  4236. #define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102
  4237. #define GL_MIN 0x8007
  4238. #define GL_MAX 0x8008
  4239. #endif
  4240. #ifndef GL_UNSIGNED_INT_2_10_10_10_REV
  4241. #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368
  4242. #endif
  4243. #ifndef GL_UNSIGNED_INT_24_8
  4244. #define GL_UNSIGNED_INT_24_8 0x84FA
  4245. #endif
  4246. #ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT
  4247. #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
  4248. #endif
  4249. #ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT
  4250. #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
  4251. #endif
  4252. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
  4253. #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
  4254. #endif
  4255. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
  4256. #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
  4257. #endif
  4258. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
  4259. #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
  4260. #endif
  4261. #ifndef GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT
  4262. #define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F
  4263. #endif
  4264. #ifndef GL_COMPRESSED_RED_RGTC1
  4265. #define GL_COMPRESSED_RED_RGTC1 0x8DBB
  4266. #endif
  4267. #ifndef GL_COMPRESSED_SIGNED_RED_RGTC1
  4268. #define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC
  4269. #endif
  4270. #ifndef GL_COMPRESSED_RED_GREEN_RGTC2
  4271. #define GL_COMPRESSED_RED_GREEN_RGTC2 0x8DBD
  4272. #endif
  4273. #ifndef GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2
  4274. #define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2 0x8DBE
  4275. #endif
  4276. #ifndef GL_COMPRESSED_RGBA_BPTC_UNORM_ARB
  4277. #define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C
  4278. #endif
  4279. #ifndef GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB
  4280. #define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D
  4281. #endif
  4282. #ifndef GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB
  4283. #define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E
  4284. #endif
  4285. #ifndef GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB
  4286. #define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F
  4287. #endif
  4288. #ifndef GL_COMPRESSED_RGB8_ETC2
  4289. #define GL_COMPRESSED_RGB8_ETC2 0x9274
  4290. #endif
  4291. #ifndef GL_COMPRESSED_SRGB8_ETC2
  4292. #define GL_COMPRESSED_SRGB8_ETC2 0x9275
  4293. #endif
  4294. #ifndef GL_COMPRESSED_RGBA8_ETC2_EAC
  4295. #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278
  4296. #endif
  4297. #ifndef GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
  4298. #define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279
  4299. #endif
  4300. #ifndef GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2
  4301. #define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276
  4302. #endif
  4303. #ifndef GL_COMPRESSED_R11_EAC
  4304. #define GL_COMPRESSED_R11_EAC 0x9270
  4305. #endif
  4306. #ifndef GL_COMPRESSED_SIGNED_R11_EAC
  4307. #define GL_COMPRESSED_SIGNED_R11_EAC 0x9271
  4308. #endif
  4309. #ifndef GL_COMPRESSED_RG11_EAC
  4310. #define GL_COMPRESSED_RG11_EAC 0x9272
  4311. #endif
  4312. #ifndef GL_COMPRESSED_SIGNED_RG11_EAC
  4313. #define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273
  4314. #endif
  4315. #ifndef GL_COMPRESSED_RGBA_ASTC_4x4_KHR
  4316. #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0
  4317. #endif
  4318. #ifndef GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR
  4319. #define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0
  4320. #endif
  4321. #ifndef GL_DEPTH24_STENCIL8
  4322. #define GL_DEPTH24_STENCIL8 0x88F0
  4323. #endif
  4324. #ifndef GL_HALF_FLOAT
  4325. #define GL_HALF_FLOAT 0x140B
  4326. #endif
  4327. #ifndef GL_DEPTH_STENCIL
  4328. #define GL_DEPTH_STENCIL 0x84F9
  4329. #endif
  4330. #ifndef GL_LUMINANCE
  4331. #define GL_LUMINANCE 0x1909
  4332. #endif
  4333. #ifndef _SG_GL_CHECK_ERROR
  4334. #define _SG_GL_CHECK_ERROR() { SOKOL_ASSERT(glGetError() == GL_NO_ERROR); }
  4335. #endif
  4336. #endif
  4337. #if defined(SOKOL_GLES3)
  4338. // on WebGL2, GL_FRAMEBUFFER_UNDEFINED technically doesn't exist (it is defined
  4339. // in the Emscripten headers, but may not exist in other WebGL2 shims)
  4340. // see: https://github.com/floooh/sokol/pull/933
  4341. #ifndef GL_FRAMEBUFFER_UNDEFINED
  4342. #define GL_FRAMEBUFFER_UNDEFINED 0x8219
  4343. #endif
  4344. #endif
  4345. // make some GL constants generally available to simplify compilation,
  4346. // use of those constants will be filtered by runtime flags
  4347. #ifndef GL_SHADER_STORAGE_BUFFER
  4348. #define GL_SHADER_STORAGE_BUFFER 0x90D2
  4349. #endif
  4350. // ███████ ████████ ██████ ██ ██ ██████ ████████ ███████
  4351. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  4352. // ███████ ██ ██████ ██ ██ ██ ██ ███████
  4353. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  4354. // ███████ ██ ██ ██ ██████ ██████ ██ ███████
  4355. //
  4356. // >>structs
  4357. // resource pool slots
  4358. typedef struct {
  4359. uint32_t id;
  4360. sg_resource_state state;
  4361. } _sg_slot_t;
  4362. // resource pool housekeeping struct
  4363. typedef struct {
  4364. int size;
  4365. int queue_top;
  4366. uint32_t* gen_ctrs;
  4367. int* free_queue;
  4368. } _sg_pool_t;
  4369. _SOKOL_PRIVATE void _sg_init_pool(_sg_pool_t* pool, int num);
  4370. _SOKOL_PRIVATE void _sg_discard_pool(_sg_pool_t* pool);
  4371. _SOKOL_PRIVATE int _sg_pool_alloc_index(_sg_pool_t* pool);
  4372. _SOKOL_PRIVATE void _sg_pool_free_index(_sg_pool_t* pool, int slot_index);
  4373. _SOKOL_PRIVATE void _sg_reset_slot(_sg_slot_t* slot);
  4374. _SOKOL_PRIVATE uint32_t _sg_slot_alloc(_sg_pool_t* pool, _sg_slot_t* slot, int slot_index);
  4375. _SOKOL_PRIVATE int _sg_slot_index(uint32_t id);
  4376. // constants
  4377. enum {
  4378. _SG_STRING_SIZE = 32,
  4379. _SG_SLOT_SHIFT = 16,
  4380. _SG_SLOT_MASK = (1<<_SG_SLOT_SHIFT)-1,
  4381. _SG_MAX_POOL_SIZE = (1<<_SG_SLOT_SHIFT),
  4382. _SG_DEFAULT_BUFFER_POOL_SIZE = 128,
  4383. _SG_DEFAULT_IMAGE_POOL_SIZE = 128,
  4384. _SG_DEFAULT_SAMPLER_POOL_SIZE = 64,
  4385. _SG_DEFAULT_SHADER_POOL_SIZE = 32,
  4386. _SG_DEFAULT_PIPELINE_POOL_SIZE = 64,
  4387. _SG_DEFAULT_ATTACHMENTS_POOL_SIZE = 16,
  4388. _SG_DEFAULT_UB_SIZE = 4 * 1024 * 1024,
  4389. _SG_DEFAULT_MAX_COMMIT_LISTENERS = 1024,
  4390. _SG_DEFAULT_WGPU_BINDGROUP_CACHE_SIZE = 1024,
  4391. };
  4392. // fixed-size string
  4393. typedef struct {
  4394. char buf[_SG_STRING_SIZE];
  4395. } _sg_str_t;
  4396. // helper macros
  4397. #define _sg_def(val, def) (((val) == 0) ? (def) : (val))
  4398. #define _sg_def_flt(val, def) (((val) == 0.0f) ? (def) : (val))
  4399. #define _sg_min(a,b) (((a)<(b))?(a):(b))
  4400. #define _sg_max(a,b) (((a)>(b))?(a):(b))
  4401. #define _sg_clamp(v,v0,v1) (((v)<(v0))?(v0):(((v)>(v1))?(v1):(v)))
  4402. #define _sg_fequal(val,cmp,delta) ((((val)-(cmp))> -(delta))&&(((val)-(cmp))<(delta)))
  4403. #define _sg_ispow2(val) ((val&(val-1))==0)
  4404. #define _sg_stats_add(key,val) {if(_sg.stats_enabled){ _sg.stats.key+=val;}}
  4405. _SOKOL_PRIVATE void* _sg_malloc_clear(size_t size);
  4406. _SOKOL_PRIVATE void _sg_free(void* ptr);
  4407. _SOKOL_PRIVATE void _sg_clear(void* ptr, size_t size);
  4408. typedef struct {
  4409. int size;
  4410. int append_pos;
  4411. bool append_overflow;
  4412. uint32_t update_frame_index;
  4413. uint32_t append_frame_index;
  4414. int num_slots;
  4415. int active_slot;
  4416. sg_buffer_type type;
  4417. sg_usage usage;
  4418. } _sg_buffer_common_t;
  4419. _SOKOL_PRIVATE void _sg_buffer_common_init(_sg_buffer_common_t* cmn, const sg_buffer_desc* desc) {
  4420. cmn->size = (int)desc->size;
  4421. cmn->append_pos = 0;
  4422. cmn->append_overflow = false;
  4423. cmn->update_frame_index = 0;
  4424. cmn->append_frame_index = 0;
  4425. cmn->num_slots = (desc->usage == SG_USAGE_IMMUTABLE) ? 1 : SG_NUM_INFLIGHT_FRAMES;
  4426. cmn->active_slot = 0;
  4427. cmn->type = desc->type;
  4428. cmn->usage = desc->usage;
  4429. }
  4430. typedef struct {
  4431. uint32_t upd_frame_index;
  4432. int num_slots;
  4433. int active_slot;
  4434. sg_image_type type;
  4435. bool render_target;
  4436. int width;
  4437. int height;
  4438. int num_slices;
  4439. int num_mipmaps;
  4440. sg_usage usage;
  4441. sg_pixel_format pixel_format;
  4442. int sample_count;
  4443. } _sg_image_common_t;
  4444. _SOKOL_PRIVATE void _sg_image_common_init(_sg_image_common_t* cmn, const sg_image_desc* desc) {
  4445. cmn->upd_frame_index = 0;
  4446. cmn->num_slots = (desc->usage == SG_USAGE_IMMUTABLE) ? 1 : SG_NUM_INFLIGHT_FRAMES;
  4447. cmn->active_slot = 0;
  4448. cmn->type = desc->type;
  4449. cmn->render_target = desc->render_target;
  4450. cmn->width = desc->width;
  4451. cmn->height = desc->height;
  4452. cmn->num_slices = desc->num_slices;
  4453. cmn->num_mipmaps = desc->num_mipmaps;
  4454. cmn->usage = desc->usage;
  4455. cmn->pixel_format = desc->pixel_format;
  4456. cmn->sample_count = desc->sample_count;
  4457. }
  4458. typedef struct {
  4459. sg_filter min_filter;
  4460. sg_filter mag_filter;
  4461. sg_filter mipmap_filter;
  4462. sg_wrap wrap_u;
  4463. sg_wrap wrap_v;
  4464. sg_wrap wrap_w;
  4465. float min_lod;
  4466. float max_lod;
  4467. sg_border_color border_color;
  4468. sg_compare_func compare;
  4469. uint32_t max_anisotropy;
  4470. } _sg_sampler_common_t;
  4471. _SOKOL_PRIVATE void _sg_sampler_common_init(_sg_sampler_common_t* cmn, const sg_sampler_desc* desc) {
  4472. cmn->min_filter = desc->min_filter;
  4473. cmn->mag_filter = desc->mag_filter;
  4474. cmn->mipmap_filter = desc->mipmap_filter;
  4475. cmn->wrap_u = desc->wrap_u;
  4476. cmn->wrap_v = desc->wrap_v;
  4477. cmn->wrap_w = desc->wrap_w;
  4478. cmn->min_lod = desc->min_lod;
  4479. cmn->max_lod = desc->max_lod;
  4480. cmn->border_color = desc->border_color;
  4481. cmn->compare = desc->compare;
  4482. cmn->max_anisotropy = desc->max_anisotropy;
  4483. }
  4484. typedef struct {
  4485. sg_shader_stage stage;
  4486. uint32_t size;
  4487. } _sg_shader_uniform_block_t;
  4488. typedef struct {
  4489. sg_shader_stage stage;
  4490. bool readonly;
  4491. } _sg_shader_storage_buffer_t;
  4492. typedef struct {
  4493. sg_shader_stage stage;
  4494. sg_image_type image_type;
  4495. sg_image_sample_type sample_type;
  4496. bool multisampled;
  4497. } _sg_shader_image_t;
  4498. typedef struct {
  4499. sg_shader_stage stage;
  4500. sg_sampler_type sampler_type;
  4501. } _sg_shader_sampler_t;
  4502. // combined image sampler mappings, only needed on GL
  4503. typedef struct {
  4504. sg_shader_stage stage;
  4505. uint8_t image_slot;
  4506. uint8_t sampler_slot;
  4507. } _sg_shader_image_sampler_t;
  4508. typedef struct {
  4509. uint32_t required_bindings_and_uniforms;
  4510. _sg_shader_uniform_block_t uniform_blocks[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  4511. _sg_shader_storage_buffer_t storage_buffers[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  4512. _sg_shader_image_t images[SG_MAX_IMAGE_BINDSLOTS];
  4513. _sg_shader_sampler_t samplers[SG_MAX_SAMPLER_BINDSLOTS];
  4514. _sg_shader_image_sampler_t image_samplers[SG_MAX_IMAGE_SAMPLER_PAIRS];
  4515. } _sg_shader_common_t;
  4516. _SOKOL_PRIVATE void _sg_shader_common_init(_sg_shader_common_t* cmn, const sg_shader_desc* desc) {
  4517. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  4518. const sg_shader_uniform_block* src = &desc->uniform_blocks[i];
  4519. _sg_shader_uniform_block_t* dst = &cmn->uniform_blocks[i];
  4520. if (src->stage != SG_SHADERSTAGE_NONE) {
  4521. cmn->required_bindings_and_uniforms |= (1 << i);
  4522. dst->stage = src->stage;
  4523. dst->size = src->size;
  4524. }
  4525. }
  4526. const uint32_t required_bindings_flag = (1 << SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  4527. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  4528. const sg_shader_storage_buffer* src = &desc->storage_buffers[i];
  4529. _sg_shader_storage_buffer_t* dst = &cmn->storage_buffers[i];
  4530. if (src->stage != SG_SHADERSTAGE_NONE) {
  4531. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  4532. dst->stage = src->stage;
  4533. dst->readonly = src->readonly;
  4534. }
  4535. }
  4536. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  4537. const sg_shader_image* src = &desc->images[i];
  4538. _sg_shader_image_t* dst = &cmn->images[i];
  4539. if (src->stage != SG_SHADERSTAGE_NONE) {
  4540. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  4541. dst->stage = src->stage;
  4542. dst->image_type = src->image_type;
  4543. dst->sample_type = src->sample_type;
  4544. dst->multisampled = src->multisampled;
  4545. }
  4546. }
  4547. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  4548. const sg_shader_sampler* src = &desc->samplers[i];
  4549. _sg_shader_sampler_t* dst = &cmn->samplers[i];
  4550. if (src->stage != SG_SHADERSTAGE_NONE) {
  4551. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  4552. dst->stage = src->stage;
  4553. dst->sampler_type = src->sampler_type;
  4554. }
  4555. }
  4556. for (size_t i = 0; i < SG_MAX_IMAGE_SAMPLER_PAIRS; i++) {
  4557. const sg_shader_image_sampler_pair* src = &desc->image_sampler_pairs[i];
  4558. _sg_shader_image_sampler_t* dst = &cmn->image_samplers[i];
  4559. if (src->stage != SG_SHADERSTAGE_NONE) {
  4560. dst->stage = src->stage;
  4561. SOKOL_ASSERT((src->image_slot >= 0) && (src->image_slot < SG_MAX_IMAGE_BINDSLOTS));
  4562. SOKOL_ASSERT(desc->images[src->image_slot].stage == src->stage);
  4563. dst->image_slot = src->image_slot;
  4564. SOKOL_ASSERT((src->sampler_slot >= 0) && (src->sampler_slot < SG_MAX_SAMPLER_BINDSLOTS));
  4565. SOKOL_ASSERT(desc->samplers[src->sampler_slot].stage == src->stage);
  4566. dst->sampler_slot = src->sampler_slot;
  4567. }
  4568. }
  4569. }
  4570. typedef struct {
  4571. bool vertex_buffer_layout_active[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  4572. bool use_instanced_draw;
  4573. uint32_t required_bindings_and_uniforms;
  4574. sg_shader shader_id;
  4575. sg_vertex_layout_state layout;
  4576. sg_depth_state depth;
  4577. sg_stencil_state stencil;
  4578. int color_count;
  4579. sg_color_target_state colors[SG_MAX_COLOR_ATTACHMENTS];
  4580. sg_primitive_type primitive_type;
  4581. sg_index_type index_type;
  4582. sg_cull_mode cull_mode;
  4583. sg_face_winding face_winding;
  4584. int sample_count;
  4585. sg_color blend_color;
  4586. bool alpha_to_coverage_enabled;
  4587. } _sg_pipeline_common_t;
  4588. _SOKOL_PRIVATE void _sg_pipeline_common_init(_sg_pipeline_common_t* cmn, const sg_pipeline_desc* desc) {
  4589. SOKOL_ASSERT((desc->color_count >= 0) && (desc->color_count <= SG_MAX_COLOR_ATTACHMENTS));
  4590. const uint32_t required_bindings_flag = (1 << SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  4591. for (int i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  4592. const sg_vertex_attr_state* a_state = &desc->layout.attrs[i];
  4593. if (a_state->format != SG_VERTEXFORMAT_INVALID) {
  4594. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  4595. cmn->vertex_buffer_layout_active[a_state->buffer_index] = true;
  4596. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  4597. }
  4598. }
  4599. cmn->use_instanced_draw = false;
  4600. cmn->shader_id = desc->shader;
  4601. cmn->layout = desc->layout;
  4602. cmn->depth = desc->depth;
  4603. cmn->stencil = desc->stencil;
  4604. cmn->color_count = desc->color_count;
  4605. for (int i = 0; i < desc->color_count; i++) {
  4606. cmn->colors[i] = desc->colors[i];
  4607. }
  4608. cmn->primitive_type = desc->primitive_type;
  4609. cmn->index_type = desc->index_type;
  4610. if (cmn->index_type != SG_INDEXTYPE_NONE) {
  4611. cmn->required_bindings_and_uniforms |= required_bindings_flag;
  4612. }
  4613. cmn->cull_mode = desc->cull_mode;
  4614. cmn->face_winding = desc->face_winding;
  4615. cmn->sample_count = desc->sample_count;
  4616. cmn->blend_color = desc->blend_color;
  4617. cmn->alpha_to_coverage_enabled = desc->alpha_to_coverage_enabled;
  4618. }
  4619. typedef struct {
  4620. sg_image image_id;
  4621. int mip_level;
  4622. int slice;
  4623. } _sg_attachment_common_t;
  4624. typedef struct {
  4625. int width;
  4626. int height;
  4627. int num_colors;
  4628. _sg_attachment_common_t colors[SG_MAX_COLOR_ATTACHMENTS];
  4629. _sg_attachment_common_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  4630. _sg_attachment_common_t depth_stencil;
  4631. } _sg_attachments_common_t;
  4632. _SOKOL_PRIVATE void _sg_attachment_common_init(_sg_attachment_common_t* cmn, const sg_attachment_desc* desc) {
  4633. cmn->image_id = desc->image;
  4634. cmn->mip_level = desc->mip_level;
  4635. cmn->slice = desc->slice;
  4636. }
  4637. _SOKOL_PRIVATE void _sg_attachments_common_init(_sg_attachments_common_t* cmn, const sg_attachments_desc* desc, int width, int height) {
  4638. SOKOL_ASSERT((width > 0) && (height > 0));
  4639. cmn->width = width;
  4640. cmn->height = height;
  4641. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  4642. if (desc->colors[i].image.id != SG_INVALID_ID) {
  4643. cmn->num_colors++;
  4644. _sg_attachment_common_init(&cmn->colors[i], &desc->colors[i]);
  4645. _sg_attachment_common_init(&cmn->resolves[i], &desc->resolves[i]);
  4646. }
  4647. }
  4648. if (desc->depth_stencil.image.id != SG_INVALID_ID) {
  4649. _sg_attachment_common_init(&cmn->depth_stencil, &desc->depth_stencil);
  4650. }
  4651. }
  4652. #if defined(SOKOL_DUMMY_BACKEND)
  4653. typedef struct {
  4654. _sg_slot_t slot;
  4655. _sg_buffer_common_t cmn;
  4656. } _sg_dummy_buffer_t;
  4657. typedef _sg_dummy_buffer_t _sg_buffer_t;
  4658. typedef struct {
  4659. _sg_slot_t slot;
  4660. _sg_image_common_t cmn;
  4661. } _sg_dummy_image_t;
  4662. typedef _sg_dummy_image_t _sg_image_t;
  4663. typedef struct {
  4664. _sg_slot_t slot;
  4665. _sg_sampler_common_t cmn;
  4666. } _sg_dummy_sampler_t;
  4667. typedef _sg_dummy_sampler_t _sg_sampler_t;
  4668. typedef struct {
  4669. _sg_slot_t slot;
  4670. _sg_shader_common_t cmn;
  4671. } _sg_dummy_shader_t;
  4672. typedef _sg_dummy_shader_t _sg_shader_t;
  4673. typedef struct {
  4674. _sg_slot_t slot;
  4675. _sg_shader_t* shader;
  4676. _sg_pipeline_common_t cmn;
  4677. } _sg_dummy_pipeline_t;
  4678. typedef _sg_dummy_pipeline_t _sg_pipeline_t;
  4679. typedef struct {
  4680. _sg_image_t* image;
  4681. } _sg_dummy_attachment_t;
  4682. typedef struct {
  4683. _sg_slot_t slot;
  4684. _sg_attachments_common_t cmn;
  4685. struct {
  4686. _sg_dummy_attachment_t colors[SG_MAX_COLOR_ATTACHMENTS];
  4687. _sg_dummy_attachment_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  4688. _sg_dummy_attachment_t depth_stencil;
  4689. } dmy;
  4690. } _sg_dummy_attachments_t;
  4691. typedef _sg_dummy_attachments_t _sg_attachments_t;
  4692. #elif defined(_SOKOL_ANY_GL)
  4693. typedef struct {
  4694. _sg_slot_t slot;
  4695. _sg_buffer_common_t cmn;
  4696. struct {
  4697. GLuint buf[SG_NUM_INFLIGHT_FRAMES];
  4698. bool injected; // if true, external buffers were injected with sg_buffer_desc.gl_buffers
  4699. } gl;
  4700. } _sg_gl_buffer_t;
  4701. typedef _sg_gl_buffer_t _sg_buffer_t;
  4702. typedef struct {
  4703. _sg_slot_t slot;
  4704. _sg_image_common_t cmn;
  4705. struct {
  4706. GLenum target;
  4707. GLuint msaa_render_buffer;
  4708. GLuint tex[SG_NUM_INFLIGHT_FRAMES];
  4709. bool injected; // if true, external textures were injected with sg_image_desc.gl_textures
  4710. } gl;
  4711. } _sg_gl_image_t;
  4712. typedef _sg_gl_image_t _sg_image_t;
  4713. typedef struct {
  4714. _sg_slot_t slot;
  4715. _sg_sampler_common_t cmn;
  4716. struct {
  4717. GLuint smp;
  4718. bool injected; // true if external sampler was injects in sg_sampler_desc.gl_sampler
  4719. } gl;
  4720. } _sg_gl_sampler_t;
  4721. typedef _sg_gl_sampler_t _sg_sampler_t;
  4722. typedef struct {
  4723. GLint gl_loc;
  4724. sg_uniform_type type;
  4725. uint16_t count;
  4726. uint16_t offset;
  4727. } _sg_gl_uniform_t;
  4728. typedef struct {
  4729. int num_uniforms;
  4730. _sg_gl_uniform_t uniforms[SG_MAX_UNIFORMBLOCK_MEMBERS];
  4731. } _sg_gl_uniform_block_t;
  4732. typedef struct {
  4733. _sg_str_t name;
  4734. } _sg_gl_shader_attr_t;
  4735. typedef struct {
  4736. _sg_slot_t slot;
  4737. _sg_shader_common_t cmn;
  4738. struct {
  4739. GLuint prog;
  4740. _sg_gl_shader_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  4741. _sg_gl_uniform_block_t uniform_blocks[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  4742. uint8_t sbuf_binding[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  4743. int8_t tex_slot[SG_MAX_IMAGE_SAMPLER_PAIRS]; // GL texture unit index
  4744. } gl;
  4745. } _sg_gl_shader_t;
  4746. typedef _sg_gl_shader_t _sg_shader_t;
  4747. typedef struct {
  4748. int8_t vb_index; // -1 if attr is not enabled
  4749. int8_t divisor; // -1 if not initialized
  4750. uint8_t stride;
  4751. uint8_t size;
  4752. uint8_t normalized;
  4753. int offset;
  4754. GLenum type;
  4755. } _sg_gl_attr_t;
  4756. typedef struct {
  4757. _sg_slot_t slot;
  4758. _sg_pipeline_common_t cmn;
  4759. _sg_shader_t* shader;
  4760. struct {
  4761. _sg_gl_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  4762. sg_depth_state depth;
  4763. sg_stencil_state stencil;
  4764. sg_primitive_type primitive_type;
  4765. sg_blend_state blend;
  4766. sg_color_mask color_write_mask[SG_MAX_COLOR_ATTACHMENTS];
  4767. sg_cull_mode cull_mode;
  4768. sg_face_winding face_winding;
  4769. int sample_count;
  4770. bool alpha_to_coverage_enabled;
  4771. } gl;
  4772. } _sg_gl_pipeline_t;
  4773. typedef _sg_gl_pipeline_t _sg_pipeline_t;
  4774. typedef struct {
  4775. _sg_image_t* image;
  4776. } _sg_gl_attachment_t;
  4777. typedef struct {
  4778. _sg_slot_t slot;
  4779. _sg_attachments_common_t cmn;
  4780. struct {
  4781. GLuint fb;
  4782. _sg_gl_attachment_t colors[SG_MAX_COLOR_ATTACHMENTS];
  4783. _sg_gl_attachment_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  4784. _sg_gl_attachment_t depth_stencil;
  4785. GLuint msaa_resolve_framebuffer[SG_MAX_COLOR_ATTACHMENTS];
  4786. } gl;
  4787. } _sg_gl_attachments_t;
  4788. typedef _sg_gl_attachments_t _sg_attachments_t;
  4789. typedef struct {
  4790. _sg_gl_attr_t gl_attr;
  4791. GLuint gl_vbuf;
  4792. } _sg_gl_cache_attr_t;
  4793. typedef struct {
  4794. GLenum target;
  4795. GLuint texture;
  4796. GLuint sampler;
  4797. } _sg_gl_cache_texture_sampler_bind_slot;
  4798. #define _SG_GL_MAX_SBUF_BINDINGS (SG_MAX_STORAGEBUFFER_BINDSLOTS)
  4799. #define _SG_GL_MAX_IMG_SMP_BINDINGS (SG_MAX_IMAGE_SAMPLER_PAIRS)
  4800. typedef struct {
  4801. sg_depth_state depth;
  4802. sg_stencil_state stencil;
  4803. sg_blend_state blend;
  4804. sg_color_mask color_write_mask[SG_MAX_COLOR_ATTACHMENTS];
  4805. sg_cull_mode cull_mode;
  4806. sg_face_winding face_winding;
  4807. bool polygon_offset_enabled;
  4808. int sample_count;
  4809. sg_color blend_color;
  4810. bool alpha_to_coverage_enabled;
  4811. _sg_gl_cache_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  4812. GLuint vertex_buffer;
  4813. GLuint index_buffer;
  4814. GLuint storage_buffer; // general bind point
  4815. GLuint storage_buffers[_SG_GL_MAX_SBUF_BINDINGS];
  4816. GLuint stored_vertex_buffer;
  4817. GLuint stored_index_buffer;
  4818. GLuint stored_storage_buffer;
  4819. GLuint prog;
  4820. _sg_gl_cache_texture_sampler_bind_slot texture_samplers[_SG_GL_MAX_IMG_SMP_BINDINGS];
  4821. _sg_gl_cache_texture_sampler_bind_slot stored_texture_sampler;
  4822. int cur_ib_offset;
  4823. GLenum cur_primitive_type;
  4824. GLenum cur_index_type;
  4825. GLenum cur_active_texture;
  4826. _sg_pipeline_t* cur_pipeline;
  4827. sg_pipeline cur_pipeline_id;
  4828. } _sg_gl_state_cache_t;
  4829. typedef struct {
  4830. bool valid;
  4831. GLuint vao;
  4832. _sg_gl_state_cache_t cache;
  4833. bool ext_anisotropic;
  4834. GLint max_anisotropy;
  4835. sg_store_action color_store_actions[SG_MAX_COLOR_ATTACHMENTS];
  4836. sg_store_action depth_store_action;
  4837. sg_store_action stencil_store_action;
  4838. #if _SOKOL_USE_WIN32_GL_LOADER
  4839. HINSTANCE opengl32_dll;
  4840. #endif
  4841. } _sg_gl_backend_t;
  4842. #elif defined(SOKOL_D3D11)
  4843. typedef struct {
  4844. _sg_slot_t slot;
  4845. _sg_buffer_common_t cmn;
  4846. struct {
  4847. ID3D11Buffer* buf;
  4848. ID3D11ShaderResourceView* srv;
  4849. } d3d11;
  4850. } _sg_d3d11_buffer_t;
  4851. typedef _sg_d3d11_buffer_t _sg_buffer_t;
  4852. typedef struct {
  4853. _sg_slot_t slot;
  4854. _sg_image_common_t cmn;
  4855. struct {
  4856. DXGI_FORMAT format;
  4857. ID3D11Texture2D* tex2d;
  4858. ID3D11Texture3D* tex3d;
  4859. ID3D11Resource* res; // either tex2d or tex3d
  4860. ID3D11ShaderResourceView* srv;
  4861. } d3d11;
  4862. } _sg_d3d11_image_t;
  4863. typedef _sg_d3d11_image_t _sg_image_t;
  4864. typedef struct {
  4865. _sg_slot_t slot;
  4866. _sg_sampler_common_t cmn;
  4867. struct {
  4868. ID3D11SamplerState* smp;
  4869. } d3d11;
  4870. } _sg_d3d11_sampler_t;
  4871. typedef _sg_d3d11_sampler_t _sg_sampler_t;
  4872. typedef struct {
  4873. _sg_str_t sem_name;
  4874. int sem_index;
  4875. } _sg_d3d11_shader_attr_t;
  4876. #define _SG_D3D11_MAX_STAGE_UB_BINDINGS (SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  4877. #define _SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS (SG_MAX_IMAGE_BINDSLOTS + SG_MAX_STORAGEBUFFER_BINDSLOTS)
  4878. #define _SG_D3D11_MAX_STAGE_SMP_BINDINGS (SG_MAX_SAMPLER_BINDSLOTS)
  4879. typedef struct {
  4880. _sg_slot_t slot;
  4881. _sg_shader_common_t cmn;
  4882. struct {
  4883. _sg_d3d11_shader_attr_t attrs[SG_MAX_VERTEX_ATTRIBUTES];
  4884. ID3D11VertexShader* vs;
  4885. ID3D11PixelShader* fs;
  4886. void* vs_blob;
  4887. size_t vs_blob_length;
  4888. uint8_t ub_register_b_n[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  4889. uint8_t img_register_t_n[SG_MAX_IMAGE_BINDSLOTS];
  4890. uint8_t smp_register_s_n[SG_MAX_SAMPLER_BINDSLOTS];
  4891. uint8_t sbuf_register_t_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  4892. ID3D11Buffer* all_cbufs[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  4893. ID3D11Buffer* vs_cbufs[_SG_D3D11_MAX_STAGE_UB_BINDINGS];
  4894. ID3D11Buffer* fs_cbufs[_SG_D3D11_MAX_STAGE_UB_BINDINGS];
  4895. } d3d11;
  4896. } _sg_d3d11_shader_t;
  4897. typedef _sg_d3d11_shader_t _sg_shader_t;
  4898. typedef struct {
  4899. _sg_slot_t slot;
  4900. _sg_pipeline_common_t cmn;
  4901. _sg_shader_t* shader;
  4902. struct {
  4903. UINT stencil_ref;
  4904. UINT vb_strides[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  4905. D3D_PRIMITIVE_TOPOLOGY topology;
  4906. DXGI_FORMAT index_format;
  4907. ID3D11InputLayout* il;
  4908. ID3D11RasterizerState* rs;
  4909. ID3D11DepthStencilState* dss;
  4910. ID3D11BlendState* bs;
  4911. } d3d11;
  4912. } _sg_d3d11_pipeline_t;
  4913. typedef _sg_d3d11_pipeline_t _sg_pipeline_t;
  4914. typedef struct {
  4915. _sg_image_t* image;
  4916. union {
  4917. ID3D11RenderTargetView* rtv;
  4918. ID3D11DepthStencilView* dsv;
  4919. } view;
  4920. } _sg_d3d11_attachment_t;
  4921. typedef struct {
  4922. _sg_slot_t slot;
  4923. _sg_attachments_common_t cmn;
  4924. struct {
  4925. _sg_d3d11_attachment_t colors[SG_MAX_COLOR_ATTACHMENTS];
  4926. _sg_d3d11_attachment_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  4927. _sg_d3d11_attachment_t depth_stencil;
  4928. } d3d11;
  4929. } _sg_d3d11_attachments_t;
  4930. typedef _sg_d3d11_attachments_t _sg_attachments_t;
  4931. typedef struct {
  4932. bool valid;
  4933. ID3D11Device* dev;
  4934. ID3D11DeviceContext* ctx;
  4935. bool use_indexed_draw;
  4936. bool use_instanced_draw;
  4937. _sg_pipeline_t* cur_pipeline;
  4938. sg_pipeline cur_pipeline_id;
  4939. struct {
  4940. ID3D11RenderTargetView* render_view;
  4941. ID3D11RenderTargetView* resolve_view;
  4942. } cur_pass;
  4943. // on-demand loaded d3dcompiler_47.dll handles
  4944. HINSTANCE d3dcompiler_dll;
  4945. bool d3dcompiler_dll_load_failed;
  4946. pD3DCompile D3DCompile_func;
  4947. // global subresourcedata array for texture updates
  4948. D3D11_SUBRESOURCE_DATA subres_data[SG_MAX_MIPMAPS * SG_MAX_TEXTUREARRAY_LAYERS];
  4949. } _sg_d3d11_backend_t;
  4950. #elif defined(SOKOL_METAL)
  4951. #if defined(_SG_TARGET_MACOS) || defined(_SG_TARGET_IOS_SIMULATOR)
  4952. #define _SG_MTL_UB_ALIGN (256)
  4953. #else
  4954. #define _SG_MTL_UB_ALIGN (16)
  4955. #endif
  4956. #define _SG_MTL_INVALID_SLOT_INDEX (0)
  4957. typedef struct {
  4958. uint32_t frame_index; // frame index at which it is safe to release this resource
  4959. int slot_index;
  4960. } _sg_mtl_release_item_t;
  4961. typedef struct {
  4962. NSMutableArray* pool;
  4963. int num_slots;
  4964. int free_queue_top;
  4965. int* free_queue;
  4966. int release_queue_front;
  4967. int release_queue_back;
  4968. _sg_mtl_release_item_t* release_queue;
  4969. } _sg_mtl_idpool_t;
  4970. typedef struct {
  4971. _sg_slot_t slot;
  4972. _sg_buffer_common_t cmn;
  4973. struct {
  4974. int buf[SG_NUM_INFLIGHT_FRAMES]; // index into _sg_mtl_pool
  4975. } mtl;
  4976. } _sg_mtl_buffer_t;
  4977. typedef _sg_mtl_buffer_t _sg_buffer_t;
  4978. typedef struct {
  4979. _sg_slot_t slot;
  4980. _sg_image_common_t cmn;
  4981. struct {
  4982. int tex[SG_NUM_INFLIGHT_FRAMES];
  4983. } mtl;
  4984. } _sg_mtl_image_t;
  4985. typedef _sg_mtl_image_t _sg_image_t;
  4986. typedef struct {
  4987. _sg_slot_t slot;
  4988. _sg_sampler_common_t cmn;
  4989. struct {
  4990. int sampler_state;
  4991. } mtl;
  4992. } _sg_mtl_sampler_t;
  4993. typedef _sg_mtl_sampler_t _sg_sampler_t;
  4994. typedef struct {
  4995. int mtl_lib;
  4996. int mtl_func;
  4997. } _sg_mtl_shader_func_t;
  4998. typedef struct {
  4999. _sg_slot_t slot;
  5000. _sg_shader_common_t cmn;
  5001. struct {
  5002. _sg_mtl_shader_func_t vertex_func;
  5003. _sg_mtl_shader_func_t fragment_func;
  5004. uint8_t ub_buffer_n[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5005. uint8_t img_texture_n[SG_MAX_IMAGE_BINDSLOTS];
  5006. uint8_t smp_sampler_n[SG_MAX_SAMPLER_BINDSLOTS];
  5007. uint8_t sbuf_buffer_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5008. } mtl;
  5009. } _sg_mtl_shader_t;
  5010. typedef _sg_mtl_shader_t _sg_shader_t;
  5011. typedef struct {
  5012. _sg_slot_t slot;
  5013. _sg_pipeline_common_t cmn;
  5014. _sg_shader_t* shader;
  5015. struct {
  5016. MTLPrimitiveType prim_type;
  5017. int index_size;
  5018. MTLIndexType index_type;
  5019. MTLCullMode cull_mode;
  5020. MTLWinding winding;
  5021. uint32_t stencil_ref;
  5022. int rps;
  5023. int dss;
  5024. } mtl;
  5025. } _sg_mtl_pipeline_t;
  5026. typedef _sg_mtl_pipeline_t _sg_pipeline_t;
  5027. typedef struct {
  5028. _sg_image_t* image;
  5029. } _sg_mtl_attachment_t;
  5030. typedef struct {
  5031. _sg_slot_t slot;
  5032. _sg_attachments_common_t cmn;
  5033. struct {
  5034. _sg_mtl_attachment_t colors[SG_MAX_COLOR_ATTACHMENTS];
  5035. _sg_mtl_attachment_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  5036. _sg_mtl_attachment_t depth_stencil;
  5037. } mtl;
  5038. } _sg_mtl_attachments_t;
  5039. typedef _sg_mtl_attachments_t _sg_attachments_t;
  5040. // resource binding state cache
  5041. #define _SG_MTL_MAX_STAGE_UB_BINDINGS (SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5042. #define _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS (_SG_MTL_MAX_STAGE_UB_BINDINGS + SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5043. #define _SG_MTL_MAX_STAGE_BUFFER_BINDINGS (_SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS + SG_MAX_VERTEXBUFFER_BINDSLOTS)
  5044. #define _SG_MTL_MAX_STAGE_IMAGE_BINDINGS (SG_MAX_IMAGE_BINDSLOTS)
  5045. #define _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS (SG_MAX_SAMPLER_BINDSLOTS)
  5046. typedef struct {
  5047. const _sg_pipeline_t* cur_pipeline;
  5048. sg_pipeline cur_pipeline_id;
  5049. const _sg_buffer_t* cur_indexbuffer;
  5050. sg_buffer cur_indexbuffer_id;
  5051. int cur_indexbuffer_offset;
  5052. int cur_vs_buffer_offsets[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5053. sg_buffer cur_vs_buffer_ids[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5054. sg_buffer cur_fs_buffer_ids[_SG_MTL_MAX_STAGE_BUFFER_BINDINGS];
  5055. sg_image cur_vs_image_ids[_SG_MTL_MAX_STAGE_IMAGE_BINDINGS];
  5056. sg_image cur_fs_image_ids[_SG_MTL_MAX_STAGE_IMAGE_BINDINGS];
  5057. sg_sampler cur_vs_sampler_ids[_SG_MTL_MAX_STAGE_SAMPLER_BINDINGS];
  5058. sg_sampler cur_fs_sampler_ids[_SG_MTL_MAX_STAGE_SAMPLER_BINDINGS];
  5059. } _sg_mtl_state_cache_t;
  5060. typedef struct {
  5061. bool valid;
  5062. bool use_shared_storage_mode;
  5063. uint32_t cur_frame_rotate_index;
  5064. int ub_size;
  5065. int cur_ub_offset;
  5066. uint8_t* cur_ub_base_ptr;
  5067. _sg_mtl_state_cache_t state_cache;
  5068. _sg_mtl_idpool_t idpool;
  5069. dispatch_semaphore_t sem;
  5070. id<MTLDevice> device;
  5071. id<MTLCommandQueue> cmd_queue;
  5072. id<MTLCommandBuffer> cmd_buffer;
  5073. id<MTLRenderCommandEncoder> cmd_encoder;
  5074. id<CAMetalDrawable> cur_drawable;
  5075. id<MTLBuffer> uniform_buffers[SG_NUM_INFLIGHT_FRAMES];
  5076. } _sg_mtl_backend_t;
  5077. #elif defined(SOKOL_WGPU)
  5078. #define _SG_WGPU_ROWPITCH_ALIGN (256)
  5079. #define _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE (1<<16) // also see WGPULimits.maxUniformBufferBindingSize
  5080. #define _SG_WGPU_NUM_BINDGROUPS (2) // 0: uniforms, 1: images, samplers, storage buffers
  5081. #define _SG_WGPU_UB_BINDGROUP_INDEX (0)
  5082. #define _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX (1)
  5083. #define _SG_WGPU_MAX_UB_BINDGROUP_ENTRIES (SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5084. #define _SG_WGPU_MAX_UB_BINDGROUP_BIND_SLOTS (2 * SG_MAX_UNIFORMBLOCK_BINDSLOTS)
  5085. #define _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES (SG_MAX_IMAGE_BINDSLOTS + SG_MAX_SAMPLER_BINDSLOTS + SG_MAX_STORAGEBUFFER_BINDSLOTS)
  5086. #define _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS (128)
  5087. typedef struct {
  5088. _sg_slot_t slot;
  5089. _sg_buffer_common_t cmn;
  5090. struct {
  5091. WGPUBuffer buf;
  5092. } wgpu;
  5093. } _sg_wgpu_buffer_t;
  5094. typedef _sg_wgpu_buffer_t _sg_buffer_t;
  5095. typedef struct {
  5096. _sg_slot_t slot;
  5097. _sg_image_common_t cmn;
  5098. struct {
  5099. WGPUTexture tex;
  5100. WGPUTextureView view;
  5101. } wgpu;
  5102. } _sg_wgpu_image_t;
  5103. typedef _sg_wgpu_image_t _sg_image_t;
  5104. typedef struct {
  5105. _sg_slot_t slot;
  5106. _sg_sampler_common_t cmn;
  5107. struct {
  5108. WGPUSampler smp;
  5109. } wgpu;
  5110. } _sg_wgpu_sampler_t;
  5111. typedef _sg_wgpu_sampler_t _sg_sampler_t;
  5112. typedef struct {
  5113. WGPUShaderModule module;
  5114. _sg_str_t entry;
  5115. } _sg_wgpu_shader_func_t;
  5116. typedef struct {
  5117. _sg_slot_t slot;
  5118. _sg_shader_common_t cmn;
  5119. struct {
  5120. _sg_wgpu_shader_func_t vertex_func;
  5121. _sg_wgpu_shader_func_t fragment_func;
  5122. WGPUBindGroupLayout bgl_ub;
  5123. WGPUBindGroup bg_ub;
  5124. WGPUBindGroupLayout bgl_img_smp_sbuf;
  5125. // a mapping of sokol-gfx bind slots to setBindGroup dynamic-offset-array indices
  5126. uint8_t ub_num_dynoffsets;
  5127. uint8_t ub_dynoffsets[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5128. // indexed by sokol-gfx bind slot:
  5129. uint8_t ub_grp0_bnd_n[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  5130. uint8_t img_grp1_bnd_n[SG_MAX_IMAGE_BINDSLOTS];
  5131. uint8_t smp_grp1_bnd_n[SG_MAX_SAMPLER_BINDSLOTS];
  5132. uint8_t sbuf_grp1_bnd_n[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5133. } wgpu;
  5134. } _sg_wgpu_shader_t;
  5135. typedef _sg_wgpu_shader_t _sg_shader_t;
  5136. typedef struct {
  5137. _sg_slot_t slot;
  5138. _sg_pipeline_common_t cmn;
  5139. _sg_shader_t* shader;
  5140. struct {
  5141. WGPURenderPipeline pip;
  5142. WGPUColor blend_color;
  5143. } wgpu;
  5144. } _sg_wgpu_pipeline_t;
  5145. typedef _sg_wgpu_pipeline_t _sg_pipeline_t;
  5146. typedef struct {
  5147. _sg_image_t* image;
  5148. WGPUTextureView view;
  5149. } _sg_wgpu_attachment_t;
  5150. typedef struct {
  5151. _sg_slot_t slot;
  5152. _sg_attachments_common_t cmn;
  5153. struct {
  5154. _sg_wgpu_attachment_t colors[SG_MAX_COLOR_ATTACHMENTS];
  5155. _sg_wgpu_attachment_t resolves[SG_MAX_COLOR_ATTACHMENTS];
  5156. _sg_wgpu_attachment_t depth_stencil;
  5157. } wgpu;
  5158. } _sg_wgpu_attachments_t;
  5159. typedef _sg_wgpu_attachments_t _sg_attachments_t;
  5160. // a pool of per-frame uniform buffers
  5161. typedef struct {
  5162. uint32_t num_bytes;
  5163. uint32_t offset; // current offset into buf
  5164. uint8_t* staging; // intermediate buffer for uniform data updates
  5165. WGPUBuffer buf; // the GPU-side uniform buffer
  5166. uint32_t bind_offsets[SG_MAX_UNIFORMBLOCK_BINDSLOTS]; // NOTE: index is sokol-gfx ub slot index!
  5167. } _sg_wgpu_uniform_buffer_t;
  5168. typedef struct {
  5169. uint32_t id;
  5170. } _sg_wgpu_bindgroup_handle_t;
  5171. typedef enum {
  5172. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_NONE = 0,
  5173. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_IMAGE = 0x00001111,
  5174. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_SAMPLER = 0x00002222,
  5175. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_STORAGEBUFFER = 0x00003333,
  5176. _SG_WGPU_BINDGROUPSCACHEITEMTYPE_PIPELINE = 0x00004444,
  5177. } _sg_wgpu_bindgroups_cache_item_type_t;
  5178. #define _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS (1 + _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES)
  5179. typedef struct {
  5180. uint64_t hash;
  5181. // the format of cache key items is BBBBTTTTIIIIIIII
  5182. // where
  5183. // - BBBB is 2x the WGPU binding
  5184. // - TTTT is the _sg_wgpu_bindgroups_cache_item_type_t
  5185. // - IIIIIIII is the resource id
  5186. //
  5187. // where the item type is a per-resource-type bit pattern
  5188. uint64_t items[_SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS];
  5189. } _sg_wgpu_bindgroups_cache_key_t;
  5190. typedef struct {
  5191. uint32_t num; // must be 2^n
  5192. uint32_t index_mask; // mask to turn hash into valid index
  5193. _sg_wgpu_bindgroup_handle_t* items;
  5194. } _sg_wgpu_bindgroups_cache_t;
  5195. typedef struct {
  5196. _sg_slot_t slot;
  5197. WGPUBindGroup bindgroup;
  5198. _sg_wgpu_bindgroups_cache_key_t key;
  5199. } _sg_wgpu_bindgroup_t;
  5200. typedef struct {
  5201. _sg_pool_t pool;
  5202. _sg_wgpu_bindgroup_t* bindgroups;
  5203. } _sg_wgpu_bindgroups_pool_t;
  5204. typedef struct {
  5205. struct {
  5206. sg_buffer buffer;
  5207. uint64_t offset;
  5208. } vbs[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5209. struct {
  5210. sg_buffer buffer;
  5211. uint64_t offset;
  5212. } ib;
  5213. _sg_wgpu_bindgroup_handle_t bg;
  5214. } _sg_wgpu_bindings_cache_t;
  5215. // the WGPU backend state
  5216. typedef struct {
  5217. bool valid;
  5218. bool use_indexed_draw;
  5219. WGPUDevice dev;
  5220. WGPUSupportedLimits limits;
  5221. WGPUQueue queue;
  5222. WGPUCommandEncoder cmd_enc;
  5223. WGPURenderPassEncoder pass_enc;
  5224. WGPUBindGroup empty_bind_group;
  5225. const _sg_pipeline_t* cur_pipeline;
  5226. sg_pipeline cur_pipeline_id;
  5227. _sg_wgpu_uniform_buffer_t uniform;
  5228. _sg_wgpu_bindings_cache_t bindings_cache;
  5229. _sg_wgpu_bindgroups_cache_t bindgroups_cache;
  5230. _sg_wgpu_bindgroups_pool_t bindgroups_pool;
  5231. } _sg_wgpu_backend_t;
  5232. #endif
  5233. // POOL STRUCTS
  5234. // this *MUST* remain 0
  5235. #define _SG_INVALID_SLOT_INDEX (0)
  5236. typedef struct {
  5237. _sg_pool_t buffer_pool;
  5238. _sg_pool_t image_pool;
  5239. _sg_pool_t sampler_pool;
  5240. _sg_pool_t shader_pool;
  5241. _sg_pool_t pipeline_pool;
  5242. _sg_pool_t attachments_pool;
  5243. _sg_buffer_t* buffers;
  5244. _sg_image_t* images;
  5245. _sg_sampler_t* samplers;
  5246. _sg_shader_t* shaders;
  5247. _sg_pipeline_t* pipelines;
  5248. _sg_attachments_t* attachments;
  5249. } _sg_pools_t;
  5250. typedef struct {
  5251. int num; // number of allocated commit listener items
  5252. int upper; // the current upper index (no valid items past this point)
  5253. sg_commit_listener* items;
  5254. } _sg_commit_listeners_t;
  5255. // resolved resource bindings struct
  5256. typedef struct {
  5257. _sg_pipeline_t* pip;
  5258. int vb_offsets[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5259. int ib_offset;
  5260. _sg_buffer_t* vbs[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  5261. _sg_buffer_t* ib;
  5262. _sg_image_t* imgs[SG_MAX_IMAGE_BINDSLOTS];
  5263. _sg_sampler_t* smps[SG_MAX_SAMPLER_BINDSLOTS];
  5264. _sg_buffer_t* sbufs[SG_MAX_STORAGEBUFFER_BINDSLOTS];
  5265. } _sg_bindings_t;
  5266. typedef struct {
  5267. bool sample;
  5268. bool filter;
  5269. bool render;
  5270. bool blend;
  5271. bool msaa;
  5272. bool depth;
  5273. } _sg_pixelformat_info_t;
  5274. typedef struct {
  5275. bool valid;
  5276. sg_desc desc; // original desc with default values patched in
  5277. uint32_t frame_index;
  5278. struct {
  5279. bool valid;
  5280. bool in_pass;
  5281. sg_attachments atts_id; // SG_INVALID_ID in a swapchain pass
  5282. _sg_attachments_t* atts; // 0 in a swapchain pass
  5283. int width;
  5284. int height;
  5285. struct {
  5286. sg_pixel_format color_fmt;
  5287. sg_pixel_format depth_fmt;
  5288. int sample_count;
  5289. } swapchain;
  5290. } cur_pass;
  5291. sg_pipeline cur_pipeline;
  5292. bool next_draw_valid;
  5293. uint32_t required_bindings_and_uniforms; // used to check that bindings and uniforms are applied after applying pipeline
  5294. uint32_t applied_bindings_and_uniforms; // bits 0..7: uniform blocks, bit 8: bindings
  5295. #if defined(SOKOL_DEBUG)
  5296. sg_log_item validate_error;
  5297. #endif
  5298. _sg_pools_t pools;
  5299. sg_backend backend;
  5300. sg_features features;
  5301. sg_limits limits;
  5302. _sg_pixelformat_info_t formats[_SG_PIXELFORMAT_NUM];
  5303. bool stats_enabled;
  5304. sg_frame_stats stats;
  5305. sg_frame_stats prev_stats;
  5306. #if defined(_SOKOL_ANY_GL)
  5307. _sg_gl_backend_t gl;
  5308. #elif defined(SOKOL_METAL)
  5309. _sg_mtl_backend_t mtl;
  5310. #elif defined(SOKOL_D3D11)
  5311. _sg_d3d11_backend_t d3d11;
  5312. #elif defined(SOKOL_WGPU)
  5313. _sg_wgpu_backend_t wgpu;
  5314. #endif
  5315. #if defined(SOKOL_TRACE_HOOKS)
  5316. sg_trace_hooks hooks;
  5317. #endif
  5318. _sg_commit_listeners_t commit_listeners;
  5319. } _sg_state_t;
  5320. static _sg_state_t _sg;
  5321. // ██ ██████ ██████ ██████ ██ ███ ██ ██████
  5322. // ██ ██ ██ ██ ██ ██ ████ ██ ██
  5323. // ██ ██ ██ ██ ███ ██ ███ ██ ██ ██ ██ ██ ███
  5324. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5325. // ███████ ██████ ██████ ██████ ██ ██ ████ ██████
  5326. //
  5327. // >>logging
  5328. #if defined(SOKOL_DEBUG)
  5329. #define _SG_LOGITEM_XMACRO(item,msg) #item ": " msg,
  5330. static const char* _sg_log_messages[] = {
  5331. _SG_LOG_ITEMS
  5332. };
  5333. #undef _SG_LOGITEM_XMACRO
  5334. #endif // SOKOL_DEBUG
  5335. #define _SG_PANIC(code) _sg_log(SG_LOGITEM_ ##code, 0, 0, __LINE__)
  5336. #define _SG_ERROR(code) _sg_log(SG_LOGITEM_ ##code, 1, 0, __LINE__)
  5337. #define _SG_WARN(code) _sg_log(SG_LOGITEM_ ##code, 2, 0, __LINE__)
  5338. #define _SG_INFO(code) _sg_log(SG_LOGITEM_ ##code, 3, 0, __LINE__)
  5339. #define _SG_LOGMSG(code,msg) _sg_log(SG_LOGITEM_ ##code, 3, msg, __LINE__)
  5340. #define _SG_VALIDATE(cond,code) if (!(cond)){ _sg.validate_error = SG_LOGITEM_ ##code; _sg_log(SG_LOGITEM_ ##code, 1, 0, __LINE__); }
  5341. static void _sg_log(sg_log_item log_item, uint32_t log_level, const char* msg, uint32_t line_nr) {
  5342. if (_sg.desc.logger.func) {
  5343. const char* filename = 0;
  5344. #if defined(SOKOL_DEBUG)
  5345. filename = __FILE__;
  5346. if (0 == msg) {
  5347. msg = _sg_log_messages[log_item];
  5348. }
  5349. #endif
  5350. _sg.desc.logger.func("sg", log_level, log_item, msg, line_nr, filename, _sg.desc.logger.user_data);
  5351. } else {
  5352. // for log level PANIC it would be 'undefined behaviour' to continue
  5353. if (log_level == 0) {
  5354. abort();
  5355. }
  5356. }
  5357. }
  5358. // ███ ███ ███████ ███ ███ ██████ ██████ ██ ██
  5359. // ████ ████ ██ ████ ████ ██ ██ ██ ██ ██ ██
  5360. // ██ ████ ██ █████ ██ ████ ██ ██ ██ ██████ ████
  5361. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5362. // ██ ██ ███████ ██ ██ ██████ ██ ██ ██
  5363. //
  5364. // >>memory
  5365. // a helper macro to clear a struct with potentially ARC'ed ObjC references
  5366. #if defined(SOKOL_METAL)
  5367. #if defined(__cplusplus)
  5368. #define _SG_CLEAR_ARC_STRUCT(type, item) { item = type(); }
  5369. #else
  5370. #define _SG_CLEAR_ARC_STRUCT(type, item) { item = (type) { 0 }; }
  5371. #endif
  5372. #else
  5373. #define _SG_CLEAR_ARC_STRUCT(type, item) { _sg_clear(&item, sizeof(item)); }
  5374. #endif
  5375. _SOKOL_PRIVATE void _sg_clear(void* ptr, size_t size) {
  5376. SOKOL_ASSERT(ptr && (size > 0));
  5377. memset(ptr, 0, size);
  5378. }
  5379. _SOKOL_PRIVATE void* _sg_malloc(size_t size) {
  5380. SOKOL_ASSERT(size > 0);
  5381. void* ptr;
  5382. if (_sg.desc.allocator.alloc_fn) {
  5383. ptr = _sg.desc.allocator.alloc_fn(size, _sg.desc.allocator.user_data);
  5384. } else {
  5385. ptr = malloc(size);
  5386. }
  5387. if (0 == ptr) {
  5388. _SG_PANIC(MALLOC_FAILED);
  5389. }
  5390. return ptr;
  5391. }
  5392. _SOKOL_PRIVATE void* _sg_malloc_clear(size_t size) {
  5393. void* ptr = _sg_malloc(size);
  5394. _sg_clear(ptr, size);
  5395. return ptr;
  5396. }
  5397. _SOKOL_PRIVATE void _sg_free(void* ptr) {
  5398. if (_sg.desc.allocator.free_fn) {
  5399. _sg.desc.allocator.free_fn(ptr, _sg.desc.allocator.user_data);
  5400. } else {
  5401. free(ptr);
  5402. }
  5403. }
  5404. _SOKOL_PRIVATE bool _sg_strempty(const _sg_str_t* str) {
  5405. return 0 == str->buf[0];
  5406. }
  5407. _SOKOL_PRIVATE const char* _sg_strptr(const _sg_str_t* str) {
  5408. return &str->buf[0];
  5409. }
  5410. _SOKOL_PRIVATE void _sg_strcpy(_sg_str_t* dst, const char* src) {
  5411. SOKOL_ASSERT(dst);
  5412. if (src) {
  5413. #if defined(_MSC_VER)
  5414. strncpy_s(dst->buf, _SG_STRING_SIZE, src, (_SG_STRING_SIZE-1));
  5415. #else
  5416. strncpy(dst->buf, src, _SG_STRING_SIZE);
  5417. #endif
  5418. dst->buf[_SG_STRING_SIZE-1] = 0;
  5419. } else {
  5420. _sg_clear(dst->buf, _SG_STRING_SIZE);
  5421. }
  5422. }
  5423. // ██ ██ ███████ ██ ██████ ███████ ██████ ███████
  5424. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5425. // ███████ █████ ██ ██████ █████ ██████ ███████
  5426. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  5427. // ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████
  5428. //
  5429. // >>helpers
  5430. _SOKOL_PRIVATE uint32_t _sg_align_u32(uint32_t val, uint32_t align) {
  5431. SOKOL_ASSERT((align > 0) && ((align & (align - 1)) == 0));
  5432. return (val + (align - 1)) & ~(align - 1);
  5433. }
  5434. typedef struct { int x, y, w, h; } _sg_recti_t;
  5435. _SOKOL_PRIVATE _sg_recti_t _sg_clipi(int x, int y, int w, int h, int clip_width, int clip_height) {
  5436. x = _sg_min(_sg_max(0, x), clip_width-1);
  5437. y = _sg_min(_sg_max(0, y), clip_height-1);
  5438. if ((x + w) > clip_width) {
  5439. w = clip_width - x;
  5440. }
  5441. if ((y + h) > clip_height) {
  5442. h = clip_height - y;
  5443. }
  5444. w = _sg_max(w, 1);
  5445. h = _sg_max(h, 1);
  5446. const _sg_recti_t res = { x, y, w, h };
  5447. return res;
  5448. }
  5449. _SOKOL_PRIVATE int _sg_vertexformat_bytesize(sg_vertex_format fmt) {
  5450. switch (fmt) {
  5451. case SG_VERTEXFORMAT_FLOAT: return 4;
  5452. case SG_VERTEXFORMAT_FLOAT2: return 8;
  5453. case SG_VERTEXFORMAT_FLOAT3: return 12;
  5454. case SG_VERTEXFORMAT_FLOAT4: return 16;
  5455. case SG_VERTEXFORMAT_BYTE4: return 4;
  5456. case SG_VERTEXFORMAT_BYTE4N: return 4;
  5457. case SG_VERTEXFORMAT_UBYTE4: return 4;
  5458. case SG_VERTEXFORMAT_UBYTE4N: return 4;
  5459. case SG_VERTEXFORMAT_SHORT2: return 4;
  5460. case SG_VERTEXFORMAT_SHORT2N: return 4;
  5461. case SG_VERTEXFORMAT_USHORT2N: return 4;
  5462. case SG_VERTEXFORMAT_SHORT4: return 8;
  5463. case SG_VERTEXFORMAT_SHORT4N: return 8;
  5464. case SG_VERTEXFORMAT_USHORT4N: return 8;
  5465. case SG_VERTEXFORMAT_UINT10_N2: return 4;
  5466. case SG_VERTEXFORMAT_HALF2: return 4;
  5467. case SG_VERTEXFORMAT_HALF4: return 8;
  5468. case SG_VERTEXFORMAT_INVALID: return 0;
  5469. default:
  5470. SOKOL_UNREACHABLE;
  5471. return -1;
  5472. }
  5473. }
  5474. _SOKOL_PRIVATE uint32_t _sg_uniform_alignment(sg_uniform_type type, int array_count, sg_uniform_layout ub_layout) {
  5475. if (ub_layout == SG_UNIFORMLAYOUT_NATIVE) {
  5476. return 1;
  5477. } else {
  5478. SOKOL_ASSERT(array_count > 0);
  5479. if (array_count == 1) {
  5480. switch (type) {
  5481. case SG_UNIFORMTYPE_FLOAT:
  5482. case SG_UNIFORMTYPE_INT:
  5483. return 4;
  5484. case SG_UNIFORMTYPE_FLOAT2:
  5485. case SG_UNIFORMTYPE_INT2:
  5486. return 8;
  5487. case SG_UNIFORMTYPE_FLOAT3:
  5488. case SG_UNIFORMTYPE_FLOAT4:
  5489. case SG_UNIFORMTYPE_INT3:
  5490. case SG_UNIFORMTYPE_INT4:
  5491. return 16;
  5492. case SG_UNIFORMTYPE_MAT4:
  5493. return 16;
  5494. default:
  5495. SOKOL_UNREACHABLE;
  5496. return 1;
  5497. }
  5498. } else {
  5499. return 16;
  5500. }
  5501. }
  5502. }
  5503. _SOKOL_PRIVATE uint32_t _sg_uniform_size(sg_uniform_type type, int array_count, sg_uniform_layout ub_layout) {
  5504. SOKOL_ASSERT(array_count > 0);
  5505. if (array_count == 1) {
  5506. switch (type) {
  5507. case SG_UNIFORMTYPE_FLOAT:
  5508. case SG_UNIFORMTYPE_INT:
  5509. return 4;
  5510. case SG_UNIFORMTYPE_FLOAT2:
  5511. case SG_UNIFORMTYPE_INT2:
  5512. return 8;
  5513. case SG_UNIFORMTYPE_FLOAT3:
  5514. case SG_UNIFORMTYPE_INT3:
  5515. return 12;
  5516. case SG_UNIFORMTYPE_FLOAT4:
  5517. case SG_UNIFORMTYPE_INT4:
  5518. return 16;
  5519. case SG_UNIFORMTYPE_MAT4:
  5520. return 64;
  5521. default:
  5522. SOKOL_UNREACHABLE;
  5523. return 0;
  5524. }
  5525. } else {
  5526. if (ub_layout == SG_UNIFORMLAYOUT_NATIVE) {
  5527. switch (type) {
  5528. case SG_UNIFORMTYPE_FLOAT:
  5529. case SG_UNIFORMTYPE_INT:
  5530. return 4 * (uint32_t)array_count;
  5531. case SG_UNIFORMTYPE_FLOAT2:
  5532. case SG_UNIFORMTYPE_INT2:
  5533. return 8 * (uint32_t)array_count;
  5534. case SG_UNIFORMTYPE_FLOAT3:
  5535. case SG_UNIFORMTYPE_INT3:
  5536. return 12 * (uint32_t)array_count;
  5537. case SG_UNIFORMTYPE_FLOAT4:
  5538. case SG_UNIFORMTYPE_INT4:
  5539. return 16 * (uint32_t)array_count;
  5540. case SG_UNIFORMTYPE_MAT4:
  5541. return 64 * (uint32_t)array_count;
  5542. default:
  5543. SOKOL_UNREACHABLE;
  5544. return 0;
  5545. }
  5546. } else {
  5547. switch (type) {
  5548. case SG_UNIFORMTYPE_FLOAT:
  5549. case SG_UNIFORMTYPE_FLOAT2:
  5550. case SG_UNIFORMTYPE_FLOAT3:
  5551. case SG_UNIFORMTYPE_FLOAT4:
  5552. case SG_UNIFORMTYPE_INT:
  5553. case SG_UNIFORMTYPE_INT2:
  5554. case SG_UNIFORMTYPE_INT3:
  5555. case SG_UNIFORMTYPE_INT4:
  5556. return 16 * (uint32_t)array_count;
  5557. case SG_UNIFORMTYPE_MAT4:
  5558. return 64 * (uint32_t)array_count;
  5559. default:
  5560. SOKOL_UNREACHABLE;
  5561. return 0;
  5562. }
  5563. }
  5564. }
  5565. }
  5566. _SOKOL_PRIVATE bool _sg_is_compressed_pixel_format(sg_pixel_format fmt) {
  5567. switch (fmt) {
  5568. case SG_PIXELFORMAT_BC1_RGBA:
  5569. case SG_PIXELFORMAT_BC2_RGBA:
  5570. case SG_PIXELFORMAT_BC3_RGBA:
  5571. case SG_PIXELFORMAT_BC3_SRGBA:
  5572. case SG_PIXELFORMAT_BC4_R:
  5573. case SG_PIXELFORMAT_BC4_RSN:
  5574. case SG_PIXELFORMAT_BC5_RG:
  5575. case SG_PIXELFORMAT_BC5_RGSN:
  5576. case SG_PIXELFORMAT_BC6H_RGBF:
  5577. case SG_PIXELFORMAT_BC6H_RGBUF:
  5578. case SG_PIXELFORMAT_BC7_RGBA:
  5579. case SG_PIXELFORMAT_BC7_SRGBA:
  5580. case SG_PIXELFORMAT_ETC2_RGB8:
  5581. case SG_PIXELFORMAT_ETC2_SRGB8:
  5582. case SG_PIXELFORMAT_ETC2_RGB8A1:
  5583. case SG_PIXELFORMAT_ETC2_RGBA8:
  5584. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  5585. case SG_PIXELFORMAT_EAC_R11:
  5586. case SG_PIXELFORMAT_EAC_R11SN:
  5587. case SG_PIXELFORMAT_EAC_RG11:
  5588. case SG_PIXELFORMAT_EAC_RG11SN:
  5589. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  5590. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  5591. return true;
  5592. default:
  5593. return false;
  5594. }
  5595. }
  5596. _SOKOL_PRIVATE bool _sg_is_valid_rendertarget_color_format(sg_pixel_format fmt) {
  5597. const int fmt_index = (int) fmt;
  5598. SOKOL_ASSERT((fmt_index >= 0) && (fmt_index < _SG_PIXELFORMAT_NUM));
  5599. return _sg.formats[fmt_index].render && !_sg.formats[fmt_index].depth;
  5600. }
  5601. _SOKOL_PRIVATE bool _sg_is_valid_rendertarget_depth_format(sg_pixel_format fmt) {
  5602. const int fmt_index = (int) fmt;
  5603. SOKOL_ASSERT((fmt_index >= 0) && (fmt_index < _SG_PIXELFORMAT_NUM));
  5604. return _sg.formats[fmt_index].render && _sg.formats[fmt_index].depth;
  5605. }
  5606. _SOKOL_PRIVATE bool _sg_is_depth_or_depth_stencil_format(sg_pixel_format fmt) {
  5607. return (SG_PIXELFORMAT_DEPTH == fmt) || (SG_PIXELFORMAT_DEPTH_STENCIL == fmt);
  5608. }
  5609. _SOKOL_PRIVATE bool _sg_is_depth_stencil_format(sg_pixel_format fmt) {
  5610. return (SG_PIXELFORMAT_DEPTH_STENCIL == fmt);
  5611. }
  5612. _SOKOL_PRIVATE int _sg_pixelformat_bytesize(sg_pixel_format fmt) {
  5613. switch (fmt) {
  5614. case SG_PIXELFORMAT_R8:
  5615. case SG_PIXELFORMAT_R8SN:
  5616. case SG_PIXELFORMAT_R8UI:
  5617. case SG_PIXELFORMAT_R8SI:
  5618. return 1;
  5619. case SG_PIXELFORMAT_R16:
  5620. case SG_PIXELFORMAT_R16SN:
  5621. case SG_PIXELFORMAT_R16UI:
  5622. case SG_PIXELFORMAT_R16SI:
  5623. case SG_PIXELFORMAT_R16F:
  5624. case SG_PIXELFORMAT_RG8:
  5625. case SG_PIXELFORMAT_RG8SN:
  5626. case SG_PIXELFORMAT_RG8UI:
  5627. case SG_PIXELFORMAT_RG8SI:
  5628. return 2;
  5629. case SG_PIXELFORMAT_R32UI:
  5630. case SG_PIXELFORMAT_R32SI:
  5631. case SG_PIXELFORMAT_R32F:
  5632. case SG_PIXELFORMAT_RG16:
  5633. case SG_PIXELFORMAT_RG16SN:
  5634. case SG_PIXELFORMAT_RG16UI:
  5635. case SG_PIXELFORMAT_RG16SI:
  5636. case SG_PIXELFORMAT_RG16F:
  5637. case SG_PIXELFORMAT_RGBA8:
  5638. case SG_PIXELFORMAT_SRGB8A8:
  5639. case SG_PIXELFORMAT_RGBA8SN:
  5640. case SG_PIXELFORMAT_RGBA8UI:
  5641. case SG_PIXELFORMAT_RGBA8SI:
  5642. case SG_PIXELFORMAT_BGRA8:
  5643. case SG_PIXELFORMAT_RGB10A2:
  5644. case SG_PIXELFORMAT_RG11B10F:
  5645. case SG_PIXELFORMAT_RGB9E5:
  5646. return 4;
  5647. case SG_PIXELFORMAT_RG32UI:
  5648. case SG_PIXELFORMAT_RG32SI:
  5649. case SG_PIXELFORMAT_RG32F:
  5650. case SG_PIXELFORMAT_RGBA16:
  5651. case SG_PIXELFORMAT_RGBA16SN:
  5652. case SG_PIXELFORMAT_RGBA16UI:
  5653. case SG_PIXELFORMAT_RGBA16SI:
  5654. case SG_PIXELFORMAT_RGBA16F:
  5655. return 8;
  5656. case SG_PIXELFORMAT_RGBA32UI:
  5657. case SG_PIXELFORMAT_RGBA32SI:
  5658. case SG_PIXELFORMAT_RGBA32F:
  5659. return 16;
  5660. case SG_PIXELFORMAT_DEPTH:
  5661. case SG_PIXELFORMAT_DEPTH_STENCIL:
  5662. return 4;
  5663. default:
  5664. SOKOL_UNREACHABLE;
  5665. return 0;
  5666. }
  5667. }
  5668. _SOKOL_PRIVATE int _sg_roundup(int val, int round_to) {
  5669. return (val+(round_to-1)) & ~(round_to-1);
  5670. }
  5671. _SOKOL_PRIVATE uint32_t _sg_roundup_u32(uint32_t val, uint32_t round_to) {
  5672. return (val+(round_to-1)) & ~(round_to-1);
  5673. }
  5674. _SOKOL_PRIVATE uint64_t _sg_roundup_u64(uint64_t val, uint64_t round_to) {
  5675. return (val+(round_to-1)) & ~(round_to-1);
  5676. }
  5677. _SOKOL_PRIVATE bool _sg_multiple_u64(uint64_t val, uint64_t of) {
  5678. return (val & (of-1)) == 0;
  5679. }
  5680. /* return row pitch for an image
  5681. see ComputePitch in https://github.com/microsoft/DirectXTex/blob/master/DirectXTex/DirectXTexUtil.cpp
  5682. */
  5683. _SOKOL_PRIVATE int _sg_row_pitch(sg_pixel_format fmt, int width, int row_align) {
  5684. int pitch;
  5685. switch (fmt) {
  5686. case SG_PIXELFORMAT_BC1_RGBA:
  5687. case SG_PIXELFORMAT_BC4_R:
  5688. case SG_PIXELFORMAT_BC4_RSN:
  5689. case SG_PIXELFORMAT_ETC2_RGB8:
  5690. case SG_PIXELFORMAT_ETC2_SRGB8:
  5691. case SG_PIXELFORMAT_ETC2_RGB8A1:
  5692. case SG_PIXELFORMAT_EAC_R11:
  5693. case SG_PIXELFORMAT_EAC_R11SN:
  5694. pitch = ((width + 3) / 4) * 8;
  5695. pitch = pitch < 8 ? 8 : pitch;
  5696. break;
  5697. case SG_PIXELFORMAT_BC2_RGBA:
  5698. case SG_PIXELFORMAT_BC3_RGBA:
  5699. case SG_PIXELFORMAT_BC3_SRGBA:
  5700. case SG_PIXELFORMAT_BC5_RG:
  5701. case SG_PIXELFORMAT_BC5_RGSN:
  5702. case SG_PIXELFORMAT_BC6H_RGBF:
  5703. case SG_PIXELFORMAT_BC6H_RGBUF:
  5704. case SG_PIXELFORMAT_BC7_RGBA:
  5705. case SG_PIXELFORMAT_BC7_SRGBA:
  5706. case SG_PIXELFORMAT_ETC2_RGBA8:
  5707. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  5708. case SG_PIXELFORMAT_EAC_RG11:
  5709. case SG_PIXELFORMAT_EAC_RG11SN:
  5710. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  5711. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  5712. pitch = ((width + 3) / 4) * 16;
  5713. pitch = pitch < 16 ? 16 : pitch;
  5714. break;
  5715. default:
  5716. pitch = width * _sg_pixelformat_bytesize(fmt);
  5717. break;
  5718. }
  5719. pitch = _sg_roundup(pitch, row_align);
  5720. return pitch;
  5721. }
  5722. // compute the number of rows in a surface depending on pixel format
  5723. _SOKOL_PRIVATE int _sg_num_rows(sg_pixel_format fmt, int height) {
  5724. int num_rows;
  5725. switch (fmt) {
  5726. case SG_PIXELFORMAT_BC1_RGBA:
  5727. case SG_PIXELFORMAT_BC4_R:
  5728. case SG_PIXELFORMAT_BC4_RSN:
  5729. case SG_PIXELFORMAT_ETC2_RGB8:
  5730. case SG_PIXELFORMAT_ETC2_SRGB8:
  5731. case SG_PIXELFORMAT_ETC2_RGB8A1:
  5732. case SG_PIXELFORMAT_ETC2_RGBA8:
  5733. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  5734. case SG_PIXELFORMAT_EAC_R11:
  5735. case SG_PIXELFORMAT_EAC_R11SN:
  5736. case SG_PIXELFORMAT_EAC_RG11:
  5737. case SG_PIXELFORMAT_EAC_RG11SN:
  5738. case SG_PIXELFORMAT_BC2_RGBA:
  5739. case SG_PIXELFORMAT_BC3_RGBA:
  5740. case SG_PIXELFORMAT_BC3_SRGBA:
  5741. case SG_PIXELFORMAT_BC5_RG:
  5742. case SG_PIXELFORMAT_BC5_RGSN:
  5743. case SG_PIXELFORMAT_BC6H_RGBF:
  5744. case SG_PIXELFORMAT_BC6H_RGBUF:
  5745. case SG_PIXELFORMAT_BC7_RGBA:
  5746. case SG_PIXELFORMAT_BC7_SRGBA:
  5747. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  5748. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  5749. num_rows = ((height + 3) / 4);
  5750. break;
  5751. default:
  5752. num_rows = height;
  5753. break;
  5754. }
  5755. if (num_rows < 1) {
  5756. num_rows = 1;
  5757. }
  5758. return num_rows;
  5759. }
  5760. // return size of a mipmap level
  5761. _SOKOL_PRIVATE int _sg_miplevel_dim(int base_dim, int mip_level) {
  5762. return _sg_max(base_dim >> mip_level, 1);
  5763. }
  5764. /* return pitch of a 2D subimage / texture slice
  5765. see ComputePitch in https://github.com/microsoft/DirectXTex/blob/master/DirectXTex/DirectXTexUtil.cpp
  5766. */
  5767. _SOKOL_PRIVATE int _sg_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align) {
  5768. int num_rows = _sg_num_rows(fmt, height);
  5769. return num_rows * _sg_row_pitch(fmt, width, row_align);
  5770. }
  5771. // capability table pixel format helper functions
  5772. _SOKOL_PRIVATE void _sg_pixelformat_all(_sg_pixelformat_info_t* pfi) {
  5773. pfi->sample = true;
  5774. pfi->filter = true;
  5775. pfi->blend = true;
  5776. pfi->render = true;
  5777. pfi->msaa = true;
  5778. }
  5779. _SOKOL_PRIVATE void _sg_pixelformat_s(_sg_pixelformat_info_t* pfi) {
  5780. pfi->sample = true;
  5781. }
  5782. _SOKOL_PRIVATE void _sg_pixelformat_sf(_sg_pixelformat_info_t* pfi) {
  5783. pfi->sample = true;
  5784. pfi->filter = true;
  5785. }
  5786. _SOKOL_PRIVATE void _sg_pixelformat_sr(_sg_pixelformat_info_t* pfi) {
  5787. pfi->sample = true;
  5788. pfi->render = true;
  5789. }
  5790. _SOKOL_PRIVATE void _sg_pixelformat_sfr(_sg_pixelformat_info_t* pfi) {
  5791. pfi->sample = true;
  5792. pfi->filter = true;
  5793. pfi->render = true;
  5794. }
  5795. _SOKOL_PRIVATE void _sg_pixelformat_srmd(_sg_pixelformat_info_t* pfi) {
  5796. pfi->sample = true;
  5797. pfi->render = true;
  5798. pfi->msaa = true;
  5799. pfi->depth = true;
  5800. }
  5801. _SOKOL_PRIVATE void _sg_pixelformat_srm(_sg_pixelformat_info_t* pfi) {
  5802. pfi->sample = true;
  5803. pfi->render = true;
  5804. pfi->msaa = true;
  5805. }
  5806. _SOKOL_PRIVATE void _sg_pixelformat_sfrm(_sg_pixelformat_info_t* pfi) {
  5807. pfi->sample = true;
  5808. pfi->filter = true;
  5809. pfi->render = true;
  5810. pfi->msaa = true;
  5811. }
  5812. _SOKOL_PRIVATE void _sg_pixelformat_sbrm(_sg_pixelformat_info_t* pfi) {
  5813. pfi->sample = true;
  5814. pfi->blend = true;
  5815. pfi->render = true;
  5816. pfi->msaa = true;
  5817. }
  5818. _SOKOL_PRIVATE void _sg_pixelformat_sbr(_sg_pixelformat_info_t* pfi) {
  5819. pfi->sample = true;
  5820. pfi->blend = true;
  5821. pfi->render = true;
  5822. }
  5823. _SOKOL_PRIVATE void _sg_pixelformat_sfbr(_sg_pixelformat_info_t* pfi) {
  5824. pfi->sample = true;
  5825. pfi->filter = true;
  5826. pfi->blend = true;
  5827. pfi->render = true;
  5828. }
  5829. _SOKOL_PRIVATE sg_pass_action _sg_pass_action_defaults(const sg_pass_action* action) {
  5830. SOKOL_ASSERT(action);
  5831. sg_pass_action res = *action;
  5832. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  5833. if (res.colors[i].load_action == _SG_LOADACTION_DEFAULT) {
  5834. res.colors[i].load_action = SG_LOADACTION_CLEAR;
  5835. res.colors[i].clear_value.r = SG_DEFAULT_CLEAR_RED;
  5836. res.colors[i].clear_value.g = SG_DEFAULT_CLEAR_GREEN;
  5837. res.colors[i].clear_value.b = SG_DEFAULT_CLEAR_BLUE;
  5838. res.colors[i].clear_value.a = SG_DEFAULT_CLEAR_ALPHA;
  5839. }
  5840. if (res.colors[i].store_action == _SG_STOREACTION_DEFAULT) {
  5841. res.colors[i].store_action = SG_STOREACTION_STORE;
  5842. }
  5843. }
  5844. if (res.depth.load_action == _SG_LOADACTION_DEFAULT) {
  5845. res.depth.load_action = SG_LOADACTION_CLEAR;
  5846. res.depth.clear_value = SG_DEFAULT_CLEAR_DEPTH;
  5847. }
  5848. if (res.depth.store_action == _SG_STOREACTION_DEFAULT) {
  5849. res.depth.store_action = SG_STOREACTION_DONTCARE;
  5850. }
  5851. if (res.stencil.load_action == _SG_LOADACTION_DEFAULT) {
  5852. res.stencil.load_action = SG_LOADACTION_CLEAR;
  5853. res.stencil.clear_value = SG_DEFAULT_CLEAR_STENCIL;
  5854. }
  5855. if (res.stencil.store_action == _SG_STOREACTION_DEFAULT) {
  5856. res.stencil.store_action = SG_STOREACTION_DONTCARE;
  5857. }
  5858. return res;
  5859. }
  5860. // ██████ ██ ██ ███ ███ ███ ███ ██ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  5861. // ██ ██ ██ ██ ████ ████ ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  5862. // ██ ██ ██ ██ ██ ████ ██ ██ ████ ██ ████ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  5863. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5864. // ██████ ██████ ██ ██ ██ ██ ██ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  5865. //
  5866. // >>dummy backend
  5867. #if defined(SOKOL_DUMMY_BACKEND)
  5868. _SOKOL_PRIVATE void _sg_dummy_setup_backend(const sg_desc* desc) {
  5869. SOKOL_ASSERT(desc);
  5870. _SOKOL_UNUSED(desc);
  5871. _sg.backend = SG_BACKEND_DUMMY;
  5872. for (int i = SG_PIXELFORMAT_R8; i < SG_PIXELFORMAT_BC1_RGBA; i++) {
  5873. _sg.formats[i].sample = true;
  5874. _sg.formats[i].filter = true;
  5875. _sg.formats[i].render = true;
  5876. _sg.formats[i].blend = true;
  5877. _sg.formats[i].msaa = true;
  5878. }
  5879. _sg.formats[SG_PIXELFORMAT_DEPTH].depth = true;
  5880. _sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL].depth = true;
  5881. }
  5882. _SOKOL_PRIVATE void _sg_dummy_discard_backend(void) {
  5883. // empty
  5884. }
  5885. _SOKOL_PRIVATE void _sg_dummy_reset_state_cache(void) {
  5886. // empty
  5887. }
  5888. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  5889. SOKOL_ASSERT(buf && desc);
  5890. _SOKOL_UNUSED(buf);
  5891. _SOKOL_UNUSED(desc);
  5892. return SG_RESOURCESTATE_VALID;
  5893. }
  5894. _SOKOL_PRIVATE void _sg_dummy_discard_buffer(_sg_buffer_t* buf) {
  5895. SOKOL_ASSERT(buf);
  5896. _SOKOL_UNUSED(buf);
  5897. }
  5898. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  5899. SOKOL_ASSERT(img && desc);
  5900. _SOKOL_UNUSED(img);
  5901. _SOKOL_UNUSED(desc);
  5902. return SG_RESOURCESTATE_VALID;
  5903. }
  5904. _SOKOL_PRIVATE void _sg_dummy_discard_image(_sg_image_t* img) {
  5905. SOKOL_ASSERT(img);
  5906. _SOKOL_UNUSED(img);
  5907. }
  5908. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  5909. SOKOL_ASSERT(smp && desc);
  5910. _SOKOL_UNUSED(smp);
  5911. _SOKOL_UNUSED(desc);
  5912. return SG_RESOURCESTATE_VALID;
  5913. }
  5914. _SOKOL_PRIVATE void _sg_dummy_discard_sampler(_sg_sampler_t* smp) {
  5915. SOKOL_ASSERT(smp);
  5916. _SOKOL_UNUSED(smp);
  5917. }
  5918. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  5919. SOKOL_ASSERT(shd && desc);
  5920. _SOKOL_UNUSED(shd);
  5921. _SOKOL_UNUSED(desc);
  5922. return SG_RESOURCESTATE_VALID;
  5923. }
  5924. _SOKOL_PRIVATE void _sg_dummy_discard_shader(_sg_shader_t* shd) {
  5925. SOKOL_ASSERT(shd);
  5926. _SOKOL_UNUSED(shd);
  5927. }
  5928. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_pipeline(_sg_pipeline_t* pip, _sg_shader_t* shd, const sg_pipeline_desc* desc) {
  5929. SOKOL_ASSERT(pip && desc);
  5930. _SOKOL_UNUSED(desc);
  5931. pip->shader = shd;
  5932. return SG_RESOURCESTATE_VALID;
  5933. }
  5934. _SOKOL_PRIVATE void _sg_dummy_discard_pipeline(_sg_pipeline_t* pip) {
  5935. SOKOL_ASSERT(pip);
  5936. _SOKOL_UNUSED(pip);
  5937. }
  5938. _SOKOL_PRIVATE sg_resource_state _sg_dummy_create_attachments(_sg_attachments_t* atts, _sg_image_t** color_images, _sg_image_t** resolve_images, _sg_image_t* ds_img, const sg_attachments_desc* desc) {
  5939. SOKOL_ASSERT(atts && desc);
  5940. SOKOL_ASSERT(color_images && resolve_images);
  5941. for (int i = 0; i < atts->cmn.num_colors; i++) {
  5942. const sg_attachment_desc* color_desc = &desc->colors[i];
  5943. _SOKOL_UNUSED(color_desc);
  5944. SOKOL_ASSERT(color_desc->image.id != SG_INVALID_ID);
  5945. SOKOL_ASSERT(0 == atts->dmy.colors[i].image);
  5946. SOKOL_ASSERT(color_images[i] && (color_images[i]->slot.id == color_desc->image.id));
  5947. SOKOL_ASSERT(_sg_is_valid_rendertarget_color_format(color_images[i]->cmn.pixel_format));
  5948. atts->dmy.colors[i].image = color_images[i];
  5949. const sg_attachment_desc* resolve_desc = &desc->resolves[i];
  5950. if (resolve_desc->image.id != SG_INVALID_ID) {
  5951. SOKOL_ASSERT(0 == atts->dmy.resolves[i].image);
  5952. SOKOL_ASSERT(resolve_images[i] && (resolve_images[i]->slot.id == resolve_desc->image.id));
  5953. SOKOL_ASSERT(color_images[i] && (color_images[i]->cmn.pixel_format == resolve_images[i]->cmn.pixel_format));
  5954. atts->dmy.resolves[i].image = resolve_images[i];
  5955. }
  5956. }
  5957. SOKOL_ASSERT(0 == atts->dmy.depth_stencil.image);
  5958. const sg_attachment_desc* ds_desc = &desc->depth_stencil;
  5959. if (ds_desc->image.id != SG_INVALID_ID) {
  5960. SOKOL_ASSERT(ds_img && (ds_img->slot.id == ds_desc->image.id));
  5961. SOKOL_ASSERT(_sg_is_valid_rendertarget_depth_format(ds_img->cmn.pixel_format));
  5962. atts->dmy.depth_stencil.image = ds_img;
  5963. }
  5964. return SG_RESOURCESTATE_VALID;
  5965. }
  5966. _SOKOL_PRIVATE void _sg_dummy_discard_attachments(_sg_attachments_t* atts) {
  5967. SOKOL_ASSERT(atts);
  5968. _SOKOL_UNUSED(atts);
  5969. }
  5970. _SOKOL_PRIVATE _sg_image_t* _sg_dummy_attachments_color_image(const _sg_attachments_t* atts, int index) {
  5971. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  5972. return atts->dmy.colors[index].image;
  5973. }
  5974. _SOKOL_PRIVATE _sg_image_t* _sg_dummy_attachments_resolve_image(const _sg_attachments_t* atts, int index) {
  5975. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  5976. return atts->dmy.resolves[index].image;
  5977. }
  5978. _SOKOL_PRIVATE _sg_image_t* _sg_dummy_attachments_ds_image(const _sg_attachments_t* atts) {
  5979. SOKOL_ASSERT(atts);
  5980. return atts->dmy.depth_stencil.image;
  5981. }
  5982. _SOKOL_PRIVATE void _sg_dummy_begin_pass(const sg_pass* pass) {
  5983. SOKOL_ASSERT(pass);
  5984. _SOKOL_UNUSED(pass);
  5985. }
  5986. _SOKOL_PRIVATE void _sg_dummy_end_pass(void) {
  5987. // empty
  5988. }
  5989. _SOKOL_PRIVATE void _sg_dummy_commit(void) {
  5990. // empty
  5991. }
  5992. _SOKOL_PRIVATE void _sg_dummy_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  5993. _SOKOL_UNUSED(x);
  5994. _SOKOL_UNUSED(y);
  5995. _SOKOL_UNUSED(w);
  5996. _SOKOL_UNUSED(h);
  5997. _SOKOL_UNUSED(origin_top_left);
  5998. }
  5999. _SOKOL_PRIVATE void _sg_dummy_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  6000. _SOKOL_UNUSED(x);
  6001. _SOKOL_UNUSED(y);
  6002. _SOKOL_UNUSED(w);
  6003. _SOKOL_UNUSED(h);
  6004. _SOKOL_UNUSED(origin_top_left);
  6005. }
  6006. _SOKOL_PRIVATE void _sg_dummy_apply_pipeline(_sg_pipeline_t* pip) {
  6007. SOKOL_ASSERT(pip);
  6008. _SOKOL_UNUSED(pip);
  6009. }
  6010. _SOKOL_PRIVATE bool _sg_dummy_apply_bindings(_sg_bindings_t* bnd) {
  6011. SOKOL_ASSERT(bnd);
  6012. SOKOL_ASSERT(bnd->pip);
  6013. _SOKOL_UNUSED(bnd);
  6014. return true;
  6015. }
  6016. _SOKOL_PRIVATE void _sg_dummy_apply_uniforms(int ub_slot, const sg_range* data) {
  6017. _SOKOL_UNUSED(ub_slot);
  6018. _SOKOL_UNUSED(data);
  6019. }
  6020. _SOKOL_PRIVATE void _sg_dummy_draw(int base_element, int num_elements, int num_instances) {
  6021. _SOKOL_UNUSED(base_element);
  6022. _SOKOL_UNUSED(num_elements);
  6023. _SOKOL_UNUSED(num_instances);
  6024. }
  6025. _SOKOL_PRIVATE void _sg_dummy_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  6026. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  6027. _SOKOL_UNUSED(data);
  6028. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  6029. buf->cmn.active_slot = 0;
  6030. }
  6031. }
  6032. _SOKOL_PRIVATE bool _sg_dummy_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  6033. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  6034. _SOKOL_UNUSED(data);
  6035. if (new_frame) {
  6036. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  6037. buf->cmn.active_slot = 0;
  6038. }
  6039. }
  6040. return true;
  6041. }
  6042. _SOKOL_PRIVATE void _sg_dummy_update_image(_sg_image_t* img, const sg_image_data* data) {
  6043. SOKOL_ASSERT(img && data);
  6044. _SOKOL_UNUSED(data);
  6045. if (++img->cmn.active_slot >= img->cmn.num_slots) {
  6046. img->cmn.active_slot = 0;
  6047. }
  6048. }
  6049. // ██████ ██████ ███████ ███ ██ ██████ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  6050. // ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  6051. // ██ ██ ██████ █████ ██ ██ ██ ██ ███ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  6052. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  6053. // ██████ ██ ███████ ██ ████ ██████ ███████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  6054. //
  6055. // >>opengl backend
  6056. #elif defined(_SOKOL_ANY_GL)
  6057. // optional GL loader for win32
  6058. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  6059. #ifndef SG_GL_FUNCS_EXT
  6060. #define SG_GL_FUNCS_EXT
  6061. #endif
  6062. // X Macro list of GL function names and signatures
  6063. #define _SG_GL_FUNCS \
  6064. SG_GL_FUNCS_EXT \
  6065. _SG_XMACRO(glBindVertexArray, void, (GLuint array)) \
  6066. _SG_XMACRO(glFramebufferTextureLayer, void, (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer)) \
  6067. _SG_XMACRO(glGenFramebuffers, void, (GLsizei n, GLuint * framebuffers)) \
  6068. _SG_XMACRO(glBindFramebuffer, void, (GLenum target, GLuint framebuffer)) \
  6069. _SG_XMACRO(glBindRenderbuffer, void, (GLenum target, GLuint renderbuffer)) \
  6070. _SG_XMACRO(glGetStringi, const GLubyte *, (GLenum name, GLuint index)) \
  6071. _SG_XMACRO(glClearBufferfi, void, (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil)) \
  6072. _SG_XMACRO(glClearBufferfv, void, (GLenum buffer, GLint drawbuffer, const GLfloat * value)) \
  6073. _SG_XMACRO(glClearBufferuiv, void, (GLenum buffer, GLint drawbuffer, const GLuint * value)) \
  6074. _SG_XMACRO(glClearBufferiv, void, (GLenum buffer, GLint drawbuffer, const GLint * value)) \
  6075. _SG_XMACRO(glDeleteRenderbuffers, void, (GLsizei n, const GLuint * renderbuffers)) \
  6076. _SG_XMACRO(glUniform1fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  6077. _SG_XMACRO(glUniform2fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  6078. _SG_XMACRO(glUniform3fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  6079. _SG_XMACRO(glUniform4fv, void, (GLint location, GLsizei count, const GLfloat * value)) \
  6080. _SG_XMACRO(glUniform1iv, void, (GLint location, GLsizei count, const GLint * value)) \
  6081. _SG_XMACRO(glUniform2iv, void, (GLint location, GLsizei count, const GLint * value)) \
  6082. _SG_XMACRO(glUniform3iv, void, (GLint location, GLsizei count, const GLint * value)) \
  6083. _SG_XMACRO(glUniform4iv, void, (GLint location, GLsizei count, const GLint * value)) \
  6084. _SG_XMACRO(glUniformMatrix4fv, void, (GLint location, GLsizei count, GLboolean transpose, const GLfloat * value)) \
  6085. _SG_XMACRO(glUseProgram, void, (GLuint program)) \
  6086. _SG_XMACRO(glShaderSource, void, (GLuint shader, GLsizei count, const GLchar *const* string, const GLint * length)) \
  6087. _SG_XMACRO(glLinkProgram, void, (GLuint program)) \
  6088. _SG_XMACRO(glGetUniformLocation, GLint, (GLuint program, const GLchar * name)) \
  6089. _SG_XMACRO(glGetShaderiv, void, (GLuint shader, GLenum pname, GLint * params)) \
  6090. _SG_XMACRO(glGetProgramInfoLog, void, (GLuint program, GLsizei bufSize, GLsizei * length, GLchar * infoLog)) \
  6091. _SG_XMACRO(glGetAttribLocation, GLint, (GLuint program, const GLchar * name)) \
  6092. _SG_XMACRO(glDisableVertexAttribArray, void, (GLuint index)) \
  6093. _SG_XMACRO(glDeleteShader, void, (GLuint shader)) \
  6094. _SG_XMACRO(glDeleteProgram, void, (GLuint program)) \
  6095. _SG_XMACRO(glCompileShader, void, (GLuint shader)) \
  6096. _SG_XMACRO(glStencilFuncSeparate, void, (GLenum face, GLenum func, GLint ref, GLuint mask)) \
  6097. _SG_XMACRO(glStencilOpSeparate, void, (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass)) \
  6098. _SG_XMACRO(glRenderbufferStorageMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)) \
  6099. _SG_XMACRO(glDrawBuffers, void, (GLsizei n, const GLenum * bufs)) \
  6100. _SG_XMACRO(glVertexAttribDivisor, void, (GLuint index, GLuint divisor)) \
  6101. _SG_XMACRO(glBufferSubData, void, (GLenum target, GLintptr offset, GLsizeiptr size, const void * data)) \
  6102. _SG_XMACRO(glGenBuffers, void, (GLsizei n, GLuint * buffers)) \
  6103. _SG_XMACRO(glCheckFramebufferStatus, GLenum, (GLenum target)) \
  6104. _SG_XMACRO(glFramebufferRenderbuffer, void, (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)) \
  6105. _SG_XMACRO(glCompressedTexImage2D, void, (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void * data)) \
  6106. _SG_XMACRO(glCompressedTexImage3D, void, (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data)) \
  6107. _SG_XMACRO(glActiveTexture, void, (GLenum texture)) \
  6108. _SG_XMACRO(glTexSubImage3D, void, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels)) \
  6109. _SG_XMACRO(glRenderbufferStorage, void, (GLenum target, GLenum internalformat, GLsizei width, GLsizei height)) \
  6110. _SG_XMACRO(glGenTextures, void, (GLsizei n, GLuint * textures)) \
  6111. _SG_XMACRO(glPolygonOffset, void, (GLfloat factor, GLfloat units)) \
  6112. _SG_XMACRO(glDrawElements, void, (GLenum mode, GLsizei count, GLenum type, const void * indices)) \
  6113. _SG_XMACRO(glDeleteFramebuffers, void, (GLsizei n, const GLuint * framebuffers)) \
  6114. _SG_XMACRO(glBlendEquationSeparate, void, (GLenum modeRGB, GLenum modeAlpha)) \
  6115. _SG_XMACRO(glDeleteTextures, void, (GLsizei n, const GLuint * textures)) \
  6116. _SG_XMACRO(glGetProgramiv, void, (GLuint program, GLenum pname, GLint * params)) \
  6117. _SG_XMACRO(glBindTexture, void, (GLenum target, GLuint texture)) \
  6118. _SG_XMACRO(glTexImage3D, void, (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void * pixels)) \
  6119. _SG_XMACRO(glCreateShader, GLuint, (GLenum type)) \
  6120. _SG_XMACRO(glTexSubImage2D, void, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels)) \
  6121. _SG_XMACRO(glFramebufferTexture2D, void, (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)) \
  6122. _SG_XMACRO(glCreateProgram, GLuint, (void)) \
  6123. _SG_XMACRO(glViewport, void, (GLint x, GLint y, GLsizei width, GLsizei height)) \
  6124. _SG_XMACRO(glDeleteBuffers, void, (GLsizei n, const GLuint * buffers)) \
  6125. _SG_XMACRO(glDrawArrays, void, (GLenum mode, GLint first, GLsizei count)) \
  6126. _SG_XMACRO(glDrawElementsInstanced, void, (GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount)) \
  6127. _SG_XMACRO(glVertexAttribPointer, void, (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void * pointer)) \
  6128. _SG_XMACRO(glUniform1i, void, (GLint location, GLint v0)) \
  6129. _SG_XMACRO(glDisable, void, (GLenum cap)) \
  6130. _SG_XMACRO(glColorMask, void, (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)) \
  6131. _SG_XMACRO(glColorMaski, void, (GLuint buf, GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)) \
  6132. _SG_XMACRO(glBindBuffer, void, (GLenum target, GLuint buffer)) \
  6133. _SG_XMACRO(glDeleteVertexArrays, void, (GLsizei n, const GLuint * arrays)) \
  6134. _SG_XMACRO(glDepthMask, void, (GLboolean flag)) \
  6135. _SG_XMACRO(glDrawArraysInstanced, void, (GLenum mode, GLint first, GLsizei count, GLsizei instancecount)) \
  6136. _SG_XMACRO(glScissor, void, (GLint x, GLint y, GLsizei width, GLsizei height)) \
  6137. _SG_XMACRO(glGenRenderbuffers, void, (GLsizei n, GLuint * renderbuffers)) \
  6138. _SG_XMACRO(glBufferData, void, (GLenum target, GLsizeiptr size, const void * data, GLenum usage)) \
  6139. _SG_XMACRO(glBlendFuncSeparate, void, (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha)) \
  6140. _SG_XMACRO(glTexParameteri, void, (GLenum target, GLenum pname, GLint param)) \
  6141. _SG_XMACRO(glGetIntegerv, void, (GLenum pname, GLint * data)) \
  6142. _SG_XMACRO(glEnable, void, (GLenum cap)) \
  6143. _SG_XMACRO(glBlitFramebuffer, void, (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)) \
  6144. _SG_XMACRO(glStencilMask, void, (GLuint mask)) \
  6145. _SG_XMACRO(glAttachShader, void, (GLuint program, GLuint shader)) \
  6146. _SG_XMACRO(glGetError, GLenum, (void)) \
  6147. _SG_XMACRO(glBlendColor, void, (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)) \
  6148. _SG_XMACRO(glTexParameterf, void, (GLenum target, GLenum pname, GLfloat param)) \
  6149. _SG_XMACRO(glTexParameterfv, void, (GLenum target, GLenum pname, const GLfloat* params)) \
  6150. _SG_XMACRO(glGetShaderInfoLog, void, (GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * infoLog)) \
  6151. _SG_XMACRO(glDepthFunc, void, (GLenum func)) \
  6152. _SG_XMACRO(glStencilOp , void, (GLenum fail, GLenum zfail, GLenum zpass)) \
  6153. _SG_XMACRO(glStencilFunc, void, (GLenum func, GLint ref, GLuint mask)) \
  6154. _SG_XMACRO(glEnableVertexAttribArray, void, (GLuint index)) \
  6155. _SG_XMACRO(glBlendFunc, void, (GLenum sfactor, GLenum dfactor)) \
  6156. _SG_XMACRO(glReadBuffer, void, (GLenum src)) \
  6157. _SG_XMACRO(glTexImage2D, void, (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void * pixels)) \
  6158. _SG_XMACRO(glGenVertexArrays, void, (GLsizei n, GLuint * arrays)) \
  6159. _SG_XMACRO(glFrontFace, void, (GLenum mode)) \
  6160. _SG_XMACRO(glCullFace, void, (GLenum mode)) \
  6161. _SG_XMACRO(glPixelStorei, void, (GLenum pname, GLint param)) \
  6162. _SG_XMACRO(glBindSampler, void, (GLuint unit, GLuint sampler)) \
  6163. _SG_XMACRO(glGenSamplers, void, (GLsizei n, GLuint* samplers)) \
  6164. _SG_XMACRO(glSamplerParameteri, void, (GLuint sampler, GLenum pname, GLint param)) \
  6165. _SG_XMACRO(glSamplerParameterf, void, (GLuint sampler, GLenum pname, GLfloat param)) \
  6166. _SG_XMACRO(glSamplerParameterfv, void, (GLuint sampler, GLenum pname, const GLfloat* params)) \
  6167. _SG_XMACRO(glDeleteSamplers, void, (GLsizei n, const GLuint* samplers)) \
  6168. _SG_XMACRO(glBindBufferBase, void, (GLenum target, GLuint index, GLuint buffer)) \
  6169. _SG_XMACRO(glTexImage2DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations)) \
  6170. _SG_XMACRO(glTexImage3DMultisample, void, (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations))
  6171. // generate GL function pointer typedefs
  6172. #define _SG_XMACRO(name, ret, args) typedef ret (GL_APIENTRY* PFN_ ## name) args;
  6173. _SG_GL_FUNCS
  6174. #undef _SG_XMACRO
  6175. // generate GL function pointers
  6176. #define _SG_XMACRO(name, ret, args) static PFN_ ## name name;
  6177. _SG_GL_FUNCS
  6178. #undef _SG_XMACRO
  6179. // helper function to lookup GL functions in GL DLL
  6180. typedef PROC (WINAPI * _sg_wglGetProcAddress)(LPCSTR);
  6181. _SOKOL_PRIVATE void* _sg_gl_getprocaddr(const char* name, _sg_wglGetProcAddress wgl_getprocaddress) {
  6182. void* proc_addr = (void*) wgl_getprocaddress(name);
  6183. if (0 == proc_addr) {
  6184. proc_addr = (void*) GetProcAddress(_sg.gl.opengl32_dll, name);
  6185. }
  6186. SOKOL_ASSERT(proc_addr);
  6187. return proc_addr;
  6188. }
  6189. // populate GL function pointers
  6190. _SOKOL_PRIVATE void _sg_gl_load_opengl(void) {
  6191. SOKOL_ASSERT(0 == _sg.gl.opengl32_dll);
  6192. _sg.gl.opengl32_dll = LoadLibraryA("opengl32.dll");
  6193. SOKOL_ASSERT(_sg.gl.opengl32_dll);
  6194. _sg_wglGetProcAddress wgl_getprocaddress = (_sg_wglGetProcAddress) GetProcAddress(_sg.gl.opengl32_dll, "wglGetProcAddress");
  6195. SOKOL_ASSERT(wgl_getprocaddress);
  6196. #define _SG_XMACRO(name, ret, args) name = (PFN_ ## name) _sg_gl_getprocaddr(#name, wgl_getprocaddress);
  6197. _SG_GL_FUNCS
  6198. #undef _SG_XMACRO
  6199. }
  6200. _SOKOL_PRIVATE void _sg_gl_unload_opengl(void) {
  6201. SOKOL_ASSERT(_sg.gl.opengl32_dll);
  6202. FreeLibrary(_sg.gl.opengl32_dll);
  6203. _sg.gl.opengl32_dll = 0;
  6204. }
  6205. #endif // _SOKOL_USE_WIN32_GL_LOADER
  6206. //-- type translation ----------------------------------------------------------
  6207. _SOKOL_PRIVATE GLenum _sg_gl_buffer_target(sg_buffer_type t) {
  6208. switch (t) {
  6209. case SG_BUFFERTYPE_VERTEXBUFFER: return GL_ARRAY_BUFFER;
  6210. case SG_BUFFERTYPE_INDEXBUFFER: return GL_ELEMENT_ARRAY_BUFFER;
  6211. case SG_BUFFERTYPE_STORAGEBUFFER: return GL_SHADER_STORAGE_BUFFER;
  6212. default: SOKOL_UNREACHABLE; return 0;
  6213. }
  6214. }
  6215. _SOKOL_PRIVATE GLenum _sg_gl_texture_target(sg_image_type t, int sample_count) {
  6216. #if defined(SOKOL_GLCORE)
  6217. const bool msaa = sample_count > 1;
  6218. if (msaa) {
  6219. switch (t) {
  6220. case SG_IMAGETYPE_2D: return GL_TEXTURE_2D_MULTISAMPLE;
  6221. case SG_IMAGETYPE_ARRAY: return GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
  6222. default: SOKOL_UNREACHABLE; return 0;
  6223. }
  6224. } else {
  6225. switch (t) {
  6226. case SG_IMAGETYPE_2D: return GL_TEXTURE_2D;
  6227. case SG_IMAGETYPE_CUBE: return GL_TEXTURE_CUBE_MAP;
  6228. case SG_IMAGETYPE_3D: return GL_TEXTURE_3D;
  6229. case SG_IMAGETYPE_ARRAY: return GL_TEXTURE_2D_ARRAY;
  6230. default: SOKOL_UNREACHABLE; return 0;
  6231. }
  6232. }
  6233. #else
  6234. SOKOL_ASSERT(sample_count == 1); _SOKOL_UNUSED(sample_count);
  6235. switch (t) {
  6236. case SG_IMAGETYPE_2D: return GL_TEXTURE_2D;
  6237. case SG_IMAGETYPE_CUBE: return GL_TEXTURE_CUBE_MAP;
  6238. case SG_IMAGETYPE_3D: return GL_TEXTURE_3D;
  6239. case SG_IMAGETYPE_ARRAY: return GL_TEXTURE_2D_ARRAY;
  6240. default: SOKOL_UNREACHABLE; return 0;
  6241. }
  6242. #endif
  6243. }
  6244. _SOKOL_PRIVATE GLenum _sg_gl_usage(sg_usage u) {
  6245. switch (u) {
  6246. case SG_USAGE_IMMUTABLE: return GL_STATIC_DRAW;
  6247. case SG_USAGE_DYNAMIC: return GL_DYNAMIC_DRAW;
  6248. case SG_USAGE_STREAM: return GL_STREAM_DRAW;
  6249. default: SOKOL_UNREACHABLE; return 0;
  6250. }
  6251. }
  6252. _SOKOL_PRIVATE GLenum _sg_gl_shader_stage(sg_shader_stage stage) {
  6253. switch (stage) {
  6254. case SG_SHADERSTAGE_VERTEX: return GL_VERTEX_SHADER;
  6255. case SG_SHADERSTAGE_FRAGMENT: return GL_FRAGMENT_SHADER;
  6256. default: SOKOL_UNREACHABLE; return 0;
  6257. }
  6258. }
  6259. _SOKOL_PRIVATE GLint _sg_gl_vertexformat_size(sg_vertex_format fmt) {
  6260. switch (fmt) {
  6261. case SG_VERTEXFORMAT_FLOAT: return 1;
  6262. case SG_VERTEXFORMAT_FLOAT2: return 2;
  6263. case SG_VERTEXFORMAT_FLOAT3: return 3;
  6264. case SG_VERTEXFORMAT_FLOAT4: return 4;
  6265. case SG_VERTEXFORMAT_BYTE4: return 4;
  6266. case SG_VERTEXFORMAT_BYTE4N: return 4;
  6267. case SG_VERTEXFORMAT_UBYTE4: return 4;
  6268. case SG_VERTEXFORMAT_UBYTE4N: return 4;
  6269. case SG_VERTEXFORMAT_SHORT2: return 2;
  6270. case SG_VERTEXFORMAT_SHORT2N: return 2;
  6271. case SG_VERTEXFORMAT_USHORT2N: return 2;
  6272. case SG_VERTEXFORMAT_SHORT4: return 4;
  6273. case SG_VERTEXFORMAT_SHORT4N: return 4;
  6274. case SG_VERTEXFORMAT_USHORT4N: return 4;
  6275. case SG_VERTEXFORMAT_UINT10_N2: return 4;
  6276. case SG_VERTEXFORMAT_HALF2: return 2;
  6277. case SG_VERTEXFORMAT_HALF4: return 4;
  6278. default: SOKOL_UNREACHABLE; return 0;
  6279. }
  6280. }
  6281. _SOKOL_PRIVATE GLenum _sg_gl_vertexformat_type(sg_vertex_format fmt) {
  6282. switch (fmt) {
  6283. case SG_VERTEXFORMAT_FLOAT:
  6284. case SG_VERTEXFORMAT_FLOAT2:
  6285. case SG_VERTEXFORMAT_FLOAT3:
  6286. case SG_VERTEXFORMAT_FLOAT4:
  6287. return GL_FLOAT;
  6288. case SG_VERTEXFORMAT_BYTE4:
  6289. case SG_VERTEXFORMAT_BYTE4N:
  6290. return GL_BYTE;
  6291. case SG_VERTEXFORMAT_UBYTE4:
  6292. case SG_VERTEXFORMAT_UBYTE4N:
  6293. return GL_UNSIGNED_BYTE;
  6294. case SG_VERTEXFORMAT_SHORT2:
  6295. case SG_VERTEXFORMAT_SHORT2N:
  6296. case SG_VERTEXFORMAT_SHORT4:
  6297. case SG_VERTEXFORMAT_SHORT4N:
  6298. return GL_SHORT;
  6299. case SG_VERTEXFORMAT_USHORT2N:
  6300. case SG_VERTEXFORMAT_USHORT4N:
  6301. return GL_UNSIGNED_SHORT;
  6302. case SG_VERTEXFORMAT_UINT10_N2:
  6303. return GL_UNSIGNED_INT_2_10_10_10_REV;
  6304. case SG_VERTEXFORMAT_HALF2:
  6305. case SG_VERTEXFORMAT_HALF4:
  6306. return GL_HALF_FLOAT;
  6307. default:
  6308. SOKOL_UNREACHABLE; return 0;
  6309. }
  6310. }
  6311. _SOKOL_PRIVATE GLboolean _sg_gl_vertexformat_normalized(sg_vertex_format fmt) {
  6312. switch (fmt) {
  6313. case SG_VERTEXFORMAT_BYTE4N:
  6314. case SG_VERTEXFORMAT_UBYTE4N:
  6315. case SG_VERTEXFORMAT_SHORT2N:
  6316. case SG_VERTEXFORMAT_USHORT2N:
  6317. case SG_VERTEXFORMAT_SHORT4N:
  6318. case SG_VERTEXFORMAT_USHORT4N:
  6319. case SG_VERTEXFORMAT_UINT10_N2:
  6320. return GL_TRUE;
  6321. default:
  6322. return GL_FALSE;
  6323. }
  6324. }
  6325. _SOKOL_PRIVATE GLenum _sg_gl_primitive_type(sg_primitive_type t) {
  6326. switch (t) {
  6327. case SG_PRIMITIVETYPE_POINTS: return GL_POINTS;
  6328. case SG_PRIMITIVETYPE_LINES: return GL_LINES;
  6329. case SG_PRIMITIVETYPE_LINE_STRIP: return GL_LINE_STRIP;
  6330. case SG_PRIMITIVETYPE_TRIANGLES: return GL_TRIANGLES;
  6331. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return GL_TRIANGLE_STRIP;
  6332. default: SOKOL_UNREACHABLE; return 0;
  6333. }
  6334. }
  6335. _SOKOL_PRIVATE GLenum _sg_gl_index_type(sg_index_type t) {
  6336. switch (t) {
  6337. case SG_INDEXTYPE_NONE: return 0;
  6338. case SG_INDEXTYPE_UINT16: return GL_UNSIGNED_SHORT;
  6339. case SG_INDEXTYPE_UINT32: return GL_UNSIGNED_INT;
  6340. default: SOKOL_UNREACHABLE; return 0;
  6341. }
  6342. }
  6343. _SOKOL_PRIVATE GLenum _sg_gl_compare_func(sg_compare_func cmp) {
  6344. switch (cmp) {
  6345. case SG_COMPAREFUNC_NEVER: return GL_NEVER;
  6346. case SG_COMPAREFUNC_LESS: return GL_LESS;
  6347. case SG_COMPAREFUNC_EQUAL: return GL_EQUAL;
  6348. case SG_COMPAREFUNC_LESS_EQUAL: return GL_LEQUAL;
  6349. case SG_COMPAREFUNC_GREATER: return GL_GREATER;
  6350. case SG_COMPAREFUNC_NOT_EQUAL: return GL_NOTEQUAL;
  6351. case SG_COMPAREFUNC_GREATER_EQUAL: return GL_GEQUAL;
  6352. case SG_COMPAREFUNC_ALWAYS: return GL_ALWAYS;
  6353. default: SOKOL_UNREACHABLE; return 0;
  6354. }
  6355. }
  6356. _SOKOL_PRIVATE GLenum _sg_gl_stencil_op(sg_stencil_op op) {
  6357. switch (op) {
  6358. case SG_STENCILOP_KEEP: return GL_KEEP;
  6359. case SG_STENCILOP_ZERO: return GL_ZERO;
  6360. case SG_STENCILOP_REPLACE: return GL_REPLACE;
  6361. case SG_STENCILOP_INCR_CLAMP: return GL_INCR;
  6362. case SG_STENCILOP_DECR_CLAMP: return GL_DECR;
  6363. case SG_STENCILOP_INVERT: return GL_INVERT;
  6364. case SG_STENCILOP_INCR_WRAP: return GL_INCR_WRAP;
  6365. case SG_STENCILOP_DECR_WRAP: return GL_DECR_WRAP;
  6366. default: SOKOL_UNREACHABLE; return 0;
  6367. }
  6368. }
  6369. _SOKOL_PRIVATE GLenum _sg_gl_blend_factor(sg_blend_factor f) {
  6370. switch (f) {
  6371. case SG_BLENDFACTOR_ZERO: return GL_ZERO;
  6372. case SG_BLENDFACTOR_ONE: return GL_ONE;
  6373. case SG_BLENDFACTOR_SRC_COLOR: return GL_SRC_COLOR;
  6374. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return GL_ONE_MINUS_SRC_COLOR;
  6375. case SG_BLENDFACTOR_SRC_ALPHA: return GL_SRC_ALPHA;
  6376. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return GL_ONE_MINUS_SRC_ALPHA;
  6377. case SG_BLENDFACTOR_DST_COLOR: return GL_DST_COLOR;
  6378. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return GL_ONE_MINUS_DST_COLOR;
  6379. case SG_BLENDFACTOR_DST_ALPHA: return GL_DST_ALPHA;
  6380. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return GL_ONE_MINUS_DST_ALPHA;
  6381. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return GL_SRC_ALPHA_SATURATE;
  6382. case SG_BLENDFACTOR_BLEND_COLOR: return GL_CONSTANT_COLOR;
  6383. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return GL_ONE_MINUS_CONSTANT_COLOR;
  6384. case SG_BLENDFACTOR_BLEND_ALPHA: return GL_CONSTANT_ALPHA;
  6385. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return GL_ONE_MINUS_CONSTANT_ALPHA;
  6386. default: SOKOL_UNREACHABLE; return 0;
  6387. }
  6388. }
  6389. _SOKOL_PRIVATE GLenum _sg_gl_blend_op(sg_blend_op op) {
  6390. switch (op) {
  6391. case SG_BLENDOP_ADD: return GL_FUNC_ADD;
  6392. case SG_BLENDOP_SUBTRACT: return GL_FUNC_SUBTRACT;
  6393. case SG_BLENDOP_REVERSE_SUBTRACT: return GL_FUNC_REVERSE_SUBTRACT;
  6394. case SG_BLENDOP_MIN: return GL_MIN;
  6395. case SG_BLENDOP_MAX: return GL_MAX;
  6396. default: SOKOL_UNREACHABLE; return 0;
  6397. }
  6398. }
  6399. _SOKOL_PRIVATE GLenum _sg_gl_min_filter(sg_filter min_f, sg_filter mipmap_f) {
  6400. if (min_f == SG_FILTER_NEAREST) {
  6401. switch (mipmap_f) {
  6402. case SG_FILTER_NEAREST: return GL_NEAREST_MIPMAP_NEAREST;
  6403. case SG_FILTER_LINEAR: return GL_NEAREST_MIPMAP_LINEAR;
  6404. default: SOKOL_UNREACHABLE; return (GLenum)0;
  6405. }
  6406. } else if (min_f == SG_FILTER_LINEAR) {
  6407. switch (mipmap_f) {
  6408. case SG_FILTER_NEAREST: return GL_LINEAR_MIPMAP_NEAREST;
  6409. case SG_FILTER_LINEAR: return GL_LINEAR_MIPMAP_LINEAR;
  6410. default: SOKOL_UNREACHABLE; return (GLenum)0;
  6411. }
  6412. } else {
  6413. SOKOL_UNREACHABLE; return (GLenum)0;
  6414. }
  6415. }
  6416. _SOKOL_PRIVATE GLenum _sg_gl_mag_filter(sg_filter mag_f) {
  6417. if (mag_f == SG_FILTER_NEAREST) {
  6418. return GL_NEAREST;
  6419. } else {
  6420. return GL_LINEAR;
  6421. }
  6422. }
  6423. _SOKOL_PRIVATE GLenum _sg_gl_wrap(sg_wrap w) {
  6424. switch (w) {
  6425. case SG_WRAP_CLAMP_TO_EDGE: return GL_CLAMP_TO_EDGE;
  6426. #if defined(SOKOL_GLCORE)
  6427. case SG_WRAP_CLAMP_TO_BORDER: return GL_CLAMP_TO_BORDER;
  6428. #else
  6429. case SG_WRAP_CLAMP_TO_BORDER: return GL_CLAMP_TO_EDGE;
  6430. #endif
  6431. case SG_WRAP_REPEAT: return GL_REPEAT;
  6432. case SG_WRAP_MIRRORED_REPEAT: return GL_MIRRORED_REPEAT;
  6433. default: SOKOL_UNREACHABLE; return 0;
  6434. }
  6435. }
  6436. _SOKOL_PRIVATE GLenum _sg_gl_teximage_type(sg_pixel_format fmt) {
  6437. switch (fmt) {
  6438. case SG_PIXELFORMAT_R8:
  6439. case SG_PIXELFORMAT_R8UI:
  6440. case SG_PIXELFORMAT_RG8:
  6441. case SG_PIXELFORMAT_RG8UI:
  6442. case SG_PIXELFORMAT_RGBA8:
  6443. case SG_PIXELFORMAT_SRGB8A8:
  6444. case SG_PIXELFORMAT_RGBA8UI:
  6445. case SG_PIXELFORMAT_BGRA8:
  6446. return GL_UNSIGNED_BYTE;
  6447. case SG_PIXELFORMAT_R8SN:
  6448. case SG_PIXELFORMAT_R8SI:
  6449. case SG_PIXELFORMAT_RG8SN:
  6450. case SG_PIXELFORMAT_RG8SI:
  6451. case SG_PIXELFORMAT_RGBA8SN:
  6452. case SG_PIXELFORMAT_RGBA8SI:
  6453. return GL_BYTE;
  6454. case SG_PIXELFORMAT_R16:
  6455. case SG_PIXELFORMAT_R16UI:
  6456. case SG_PIXELFORMAT_RG16:
  6457. case SG_PIXELFORMAT_RG16UI:
  6458. case SG_PIXELFORMAT_RGBA16:
  6459. case SG_PIXELFORMAT_RGBA16UI:
  6460. return GL_UNSIGNED_SHORT;
  6461. case SG_PIXELFORMAT_R16SN:
  6462. case SG_PIXELFORMAT_R16SI:
  6463. case SG_PIXELFORMAT_RG16SN:
  6464. case SG_PIXELFORMAT_RG16SI:
  6465. case SG_PIXELFORMAT_RGBA16SN:
  6466. case SG_PIXELFORMAT_RGBA16SI:
  6467. return GL_SHORT;
  6468. case SG_PIXELFORMAT_R16F:
  6469. case SG_PIXELFORMAT_RG16F:
  6470. case SG_PIXELFORMAT_RGBA16F:
  6471. return GL_HALF_FLOAT;
  6472. case SG_PIXELFORMAT_R32UI:
  6473. case SG_PIXELFORMAT_RG32UI:
  6474. case SG_PIXELFORMAT_RGBA32UI:
  6475. return GL_UNSIGNED_INT;
  6476. case SG_PIXELFORMAT_R32SI:
  6477. case SG_PIXELFORMAT_RG32SI:
  6478. case SG_PIXELFORMAT_RGBA32SI:
  6479. return GL_INT;
  6480. case SG_PIXELFORMAT_R32F:
  6481. case SG_PIXELFORMAT_RG32F:
  6482. case SG_PIXELFORMAT_RGBA32F:
  6483. return GL_FLOAT;
  6484. case SG_PIXELFORMAT_RGB10A2:
  6485. return GL_UNSIGNED_INT_2_10_10_10_REV;
  6486. case SG_PIXELFORMAT_RG11B10F:
  6487. return GL_UNSIGNED_INT_10F_11F_11F_REV;
  6488. case SG_PIXELFORMAT_RGB9E5:
  6489. return GL_UNSIGNED_INT_5_9_9_9_REV;
  6490. case SG_PIXELFORMAT_DEPTH:
  6491. return GL_FLOAT;
  6492. case SG_PIXELFORMAT_DEPTH_STENCIL:
  6493. return GL_UNSIGNED_INT_24_8;
  6494. default:
  6495. SOKOL_UNREACHABLE; return 0;
  6496. }
  6497. }
  6498. _SOKOL_PRIVATE GLenum _sg_gl_teximage_format(sg_pixel_format fmt) {
  6499. switch (fmt) {
  6500. case SG_PIXELFORMAT_R8:
  6501. case SG_PIXELFORMAT_R8SN:
  6502. case SG_PIXELFORMAT_R16:
  6503. case SG_PIXELFORMAT_R16SN:
  6504. case SG_PIXELFORMAT_R16F:
  6505. case SG_PIXELFORMAT_R32F:
  6506. return GL_RED;
  6507. case SG_PIXELFORMAT_R8UI:
  6508. case SG_PIXELFORMAT_R8SI:
  6509. case SG_PIXELFORMAT_R16UI:
  6510. case SG_PIXELFORMAT_R16SI:
  6511. case SG_PIXELFORMAT_R32UI:
  6512. case SG_PIXELFORMAT_R32SI:
  6513. return GL_RED_INTEGER;
  6514. case SG_PIXELFORMAT_RG8:
  6515. case SG_PIXELFORMAT_RG8SN:
  6516. case SG_PIXELFORMAT_RG16:
  6517. case SG_PIXELFORMAT_RG16SN:
  6518. case SG_PIXELFORMAT_RG16F:
  6519. case SG_PIXELFORMAT_RG32F:
  6520. return GL_RG;
  6521. case SG_PIXELFORMAT_RG8UI:
  6522. case SG_PIXELFORMAT_RG8SI:
  6523. case SG_PIXELFORMAT_RG16UI:
  6524. case SG_PIXELFORMAT_RG16SI:
  6525. case SG_PIXELFORMAT_RG32UI:
  6526. case SG_PIXELFORMAT_RG32SI:
  6527. return GL_RG_INTEGER;
  6528. case SG_PIXELFORMAT_RGBA8:
  6529. case SG_PIXELFORMAT_SRGB8A8:
  6530. case SG_PIXELFORMAT_RGBA8SN:
  6531. case SG_PIXELFORMAT_RGBA16:
  6532. case SG_PIXELFORMAT_RGBA16SN:
  6533. case SG_PIXELFORMAT_RGBA16F:
  6534. case SG_PIXELFORMAT_RGBA32F:
  6535. case SG_PIXELFORMAT_RGB10A2:
  6536. return GL_RGBA;
  6537. case SG_PIXELFORMAT_RGBA8UI:
  6538. case SG_PIXELFORMAT_RGBA8SI:
  6539. case SG_PIXELFORMAT_RGBA16UI:
  6540. case SG_PIXELFORMAT_RGBA16SI:
  6541. case SG_PIXELFORMAT_RGBA32UI:
  6542. case SG_PIXELFORMAT_RGBA32SI:
  6543. return GL_RGBA_INTEGER;
  6544. case SG_PIXELFORMAT_RG11B10F:
  6545. case SG_PIXELFORMAT_RGB9E5:
  6546. return GL_RGB;
  6547. case SG_PIXELFORMAT_DEPTH:
  6548. return GL_DEPTH_COMPONENT;
  6549. case SG_PIXELFORMAT_DEPTH_STENCIL:
  6550. return GL_DEPTH_STENCIL;
  6551. case SG_PIXELFORMAT_BC1_RGBA:
  6552. return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
  6553. case SG_PIXELFORMAT_BC2_RGBA:
  6554. return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
  6555. case SG_PIXELFORMAT_BC3_RGBA:
  6556. return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
  6557. case SG_PIXELFORMAT_BC3_SRGBA:
  6558. return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  6559. case SG_PIXELFORMAT_BC4_R:
  6560. return GL_COMPRESSED_RED_RGTC1;
  6561. case SG_PIXELFORMAT_BC4_RSN:
  6562. return GL_COMPRESSED_SIGNED_RED_RGTC1;
  6563. case SG_PIXELFORMAT_BC5_RG:
  6564. return GL_COMPRESSED_RED_GREEN_RGTC2;
  6565. case SG_PIXELFORMAT_BC5_RGSN:
  6566. return GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2;
  6567. case SG_PIXELFORMAT_BC6H_RGBF:
  6568. return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB;
  6569. case SG_PIXELFORMAT_BC6H_RGBUF:
  6570. return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB;
  6571. case SG_PIXELFORMAT_BC7_RGBA:
  6572. return GL_COMPRESSED_RGBA_BPTC_UNORM_ARB;
  6573. case SG_PIXELFORMAT_BC7_SRGBA:
  6574. return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB;
  6575. case SG_PIXELFORMAT_ETC2_RGB8:
  6576. return GL_COMPRESSED_RGB8_ETC2;
  6577. case SG_PIXELFORMAT_ETC2_SRGB8:
  6578. return GL_COMPRESSED_SRGB8_ETC2;
  6579. case SG_PIXELFORMAT_ETC2_RGB8A1:
  6580. return GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
  6581. case SG_PIXELFORMAT_ETC2_RGBA8:
  6582. return GL_COMPRESSED_RGBA8_ETC2_EAC;
  6583. case SG_PIXELFORMAT_ETC2_SRGB8A8:
  6584. return GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
  6585. case SG_PIXELFORMAT_EAC_R11:
  6586. return GL_COMPRESSED_R11_EAC;
  6587. case SG_PIXELFORMAT_EAC_R11SN:
  6588. return GL_COMPRESSED_SIGNED_R11_EAC;
  6589. case SG_PIXELFORMAT_EAC_RG11:
  6590. return GL_COMPRESSED_RG11_EAC;
  6591. case SG_PIXELFORMAT_EAC_RG11SN:
  6592. return GL_COMPRESSED_SIGNED_RG11_EAC;
  6593. case SG_PIXELFORMAT_ASTC_4x4_RGBA:
  6594. return GL_COMPRESSED_RGBA_ASTC_4x4_KHR;
  6595. case SG_PIXELFORMAT_ASTC_4x4_SRGBA:
  6596. return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
  6597. default:
  6598. SOKOL_UNREACHABLE; return 0;
  6599. }
  6600. }
  6601. _SOKOL_PRIVATE GLenum _sg_gl_teximage_internal_format(sg_pixel_format fmt) {
  6602. switch (fmt) {
  6603. case SG_PIXELFORMAT_R8: return GL_R8;
  6604. case SG_PIXELFORMAT_R8SN: return GL_R8_SNORM;
  6605. case SG_PIXELFORMAT_R8UI: return GL_R8UI;
  6606. case SG_PIXELFORMAT_R8SI: return GL_R8I;
  6607. #if !defined(SOKOL_GLES3)
  6608. case SG_PIXELFORMAT_R16: return GL_R16;
  6609. case SG_PIXELFORMAT_R16SN: return GL_R16_SNORM;
  6610. #endif
  6611. case SG_PIXELFORMAT_R16UI: return GL_R16UI;
  6612. case SG_PIXELFORMAT_R16SI: return GL_R16I;
  6613. case SG_PIXELFORMAT_R16F: return GL_R16F;
  6614. case SG_PIXELFORMAT_RG8: return GL_RG8;
  6615. case SG_PIXELFORMAT_RG8SN: return GL_RG8_SNORM;
  6616. case SG_PIXELFORMAT_RG8UI: return GL_RG8UI;
  6617. case SG_PIXELFORMAT_RG8SI: return GL_RG8I;
  6618. case SG_PIXELFORMAT_R32UI: return GL_R32UI;
  6619. case SG_PIXELFORMAT_R32SI: return GL_R32I;
  6620. case SG_PIXELFORMAT_R32F: return GL_R32F;
  6621. #if !defined(SOKOL_GLES3)
  6622. case SG_PIXELFORMAT_RG16: return GL_RG16;
  6623. case SG_PIXELFORMAT_RG16SN: return GL_RG16_SNORM;
  6624. #endif
  6625. case SG_PIXELFORMAT_RG16UI: return GL_RG16UI;
  6626. case SG_PIXELFORMAT_RG16SI: return GL_RG16I;
  6627. case SG_PIXELFORMAT_RG16F: return GL_RG16F;
  6628. case SG_PIXELFORMAT_RGBA8: return GL_RGBA8;
  6629. case SG_PIXELFORMAT_SRGB8A8: return GL_SRGB8_ALPHA8;
  6630. case SG_PIXELFORMAT_RGBA8SN: return GL_RGBA8_SNORM;
  6631. case SG_PIXELFORMAT_RGBA8UI: return GL_RGBA8UI;
  6632. case SG_PIXELFORMAT_RGBA8SI: return GL_RGBA8I;
  6633. case SG_PIXELFORMAT_RGB10A2: return GL_RGB10_A2;
  6634. case SG_PIXELFORMAT_RG11B10F: return GL_R11F_G11F_B10F;
  6635. case SG_PIXELFORMAT_RGB9E5: return GL_RGB9_E5;
  6636. case SG_PIXELFORMAT_RG32UI: return GL_RG32UI;
  6637. case SG_PIXELFORMAT_RG32SI: return GL_RG32I;
  6638. case SG_PIXELFORMAT_RG32F: return GL_RG32F;
  6639. #if !defined(SOKOL_GLES3)
  6640. case SG_PIXELFORMAT_RGBA16: return GL_RGBA16;
  6641. case SG_PIXELFORMAT_RGBA16SN: return GL_RGBA16_SNORM;
  6642. #endif
  6643. case SG_PIXELFORMAT_RGBA16UI: return GL_RGBA16UI;
  6644. case SG_PIXELFORMAT_RGBA16SI: return GL_RGBA16I;
  6645. case SG_PIXELFORMAT_RGBA16F: return GL_RGBA16F;
  6646. case SG_PIXELFORMAT_RGBA32UI: return GL_RGBA32UI;
  6647. case SG_PIXELFORMAT_RGBA32SI: return GL_RGBA32I;
  6648. case SG_PIXELFORMAT_RGBA32F: return GL_RGBA32F;
  6649. case SG_PIXELFORMAT_DEPTH: return GL_DEPTH_COMPONENT32F;
  6650. case SG_PIXELFORMAT_DEPTH_STENCIL: return GL_DEPTH24_STENCIL8;
  6651. case SG_PIXELFORMAT_BC1_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
  6652. case SG_PIXELFORMAT_BC2_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
  6653. case SG_PIXELFORMAT_BC3_RGBA: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
  6654. case SG_PIXELFORMAT_BC3_SRGBA: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  6655. case SG_PIXELFORMAT_BC4_R: return GL_COMPRESSED_RED_RGTC1;
  6656. case SG_PIXELFORMAT_BC4_RSN: return GL_COMPRESSED_SIGNED_RED_RGTC1;
  6657. case SG_PIXELFORMAT_BC5_RG: return GL_COMPRESSED_RED_GREEN_RGTC2;
  6658. case SG_PIXELFORMAT_BC5_RGSN: return GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2;
  6659. case SG_PIXELFORMAT_BC6H_RGBF: return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB;
  6660. case SG_PIXELFORMAT_BC6H_RGBUF: return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB;
  6661. case SG_PIXELFORMAT_BC7_RGBA: return GL_COMPRESSED_RGBA_BPTC_UNORM_ARB;
  6662. case SG_PIXELFORMAT_BC7_SRGBA: return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB;
  6663. case SG_PIXELFORMAT_ETC2_RGB8: return GL_COMPRESSED_RGB8_ETC2;
  6664. case SG_PIXELFORMAT_ETC2_SRGB8: return GL_COMPRESSED_SRGB8_ETC2;
  6665. case SG_PIXELFORMAT_ETC2_RGB8A1: return GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
  6666. case SG_PIXELFORMAT_ETC2_RGBA8: return GL_COMPRESSED_RGBA8_ETC2_EAC;
  6667. case SG_PIXELFORMAT_ETC2_SRGB8A8: return GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
  6668. case SG_PIXELFORMAT_EAC_R11: return GL_COMPRESSED_R11_EAC;
  6669. case SG_PIXELFORMAT_EAC_R11SN: return GL_COMPRESSED_SIGNED_R11_EAC;
  6670. case SG_PIXELFORMAT_EAC_RG11: return GL_COMPRESSED_RG11_EAC;
  6671. case SG_PIXELFORMAT_EAC_RG11SN: return GL_COMPRESSED_SIGNED_RG11_EAC;
  6672. case SG_PIXELFORMAT_ASTC_4x4_RGBA: return GL_COMPRESSED_RGBA_ASTC_4x4_KHR;
  6673. case SG_PIXELFORMAT_ASTC_4x4_SRGBA: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
  6674. default: SOKOL_UNREACHABLE; return 0;
  6675. }
  6676. }
  6677. _SOKOL_PRIVATE GLenum _sg_gl_cubeface_target(int face_index) {
  6678. switch (face_index) {
  6679. case 0: return GL_TEXTURE_CUBE_MAP_POSITIVE_X;
  6680. case 1: return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
  6681. case 2: return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
  6682. case 3: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
  6683. case 4: return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
  6684. case 5: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
  6685. default: SOKOL_UNREACHABLE; return 0;
  6686. }
  6687. }
  6688. // see: https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  6689. _SOKOL_PRIVATE void _sg_gl_init_pixelformats(bool has_bgra) {
  6690. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8]);
  6691. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R8SN]);
  6692. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8UI]);
  6693. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8SI]);
  6694. #if !defined(SOKOL_GLES3)
  6695. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16]);
  6696. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16SN]);
  6697. #endif
  6698. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16UI]);
  6699. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16SI]);
  6700. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8]);
  6701. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG8SN]);
  6702. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8UI]);
  6703. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8SI]);
  6704. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  6705. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  6706. #if !defined(SOKOL_GLES3)
  6707. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16]);
  6708. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16SN]);
  6709. #endif
  6710. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16UI]);
  6711. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16SI]);
  6712. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  6713. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_SRGB8A8]);
  6714. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  6715. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  6716. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  6717. if (has_bgra) {
  6718. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_BGRA8]);
  6719. }
  6720. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB10A2]);
  6721. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  6722. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  6723. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  6724. #if !defined(SOKOL_GLES3)
  6725. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16]);
  6726. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SN]);
  6727. #endif
  6728. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  6729. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  6730. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  6731. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  6732. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH]);
  6733. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL]);
  6734. }
  6735. // FIXME: OES_half_float_blend
  6736. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_half_float(bool has_colorbuffer_half_float) {
  6737. if (has_colorbuffer_half_float) {
  6738. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16F]);
  6739. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  6740. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  6741. } else {
  6742. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R16F]);
  6743. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  6744. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  6745. }
  6746. }
  6747. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_float(bool has_colorbuffer_float, bool has_texture_float_linear, bool has_float_blend) {
  6748. if (has_texture_float_linear) {
  6749. if (has_colorbuffer_float) {
  6750. if (has_float_blend) {
  6751. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  6752. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  6753. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  6754. } else {
  6755. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_R32F]);
  6756. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  6757. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  6758. }
  6759. _sg_pixelformat_sfrm(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  6760. } else {
  6761. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R32F]);
  6762. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  6763. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  6764. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  6765. }
  6766. } else {
  6767. if (has_colorbuffer_float) {
  6768. _sg_pixelformat_sbrm(&_sg.formats[SG_PIXELFORMAT_R32F]);
  6769. _sg_pixelformat_sbrm(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  6770. _sg_pixelformat_sbrm(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  6771. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  6772. } else {
  6773. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_R32F]);
  6774. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  6775. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  6776. _sg_pixelformat_s(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  6777. }
  6778. }
  6779. }
  6780. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_s3tc(void) {
  6781. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC1_RGBA]);
  6782. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC2_RGBA]);
  6783. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_RGBA]);
  6784. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_SRGBA]);
  6785. }
  6786. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_rgtc(void) {
  6787. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_R]);
  6788. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_RSN]);
  6789. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RG]);
  6790. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RGSN]);
  6791. }
  6792. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_bptc(void) {
  6793. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBF]);
  6794. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBUF]);
  6795. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_RGBA]);
  6796. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_SRGBA]);
  6797. }
  6798. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_etc2(void) {
  6799. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8]);
  6800. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8]);
  6801. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8A1]);
  6802. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGBA8]);
  6803. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8A8]);
  6804. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11]);
  6805. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11SN]);
  6806. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11]);
  6807. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11SN]);
  6808. }
  6809. _SOKOL_PRIVATE void _sg_gl_init_pixelformats_astc(void) {
  6810. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_RGBA]);
  6811. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_SRGBA]);
  6812. }
  6813. _SOKOL_PRIVATE void _sg_gl_init_limits(void) {
  6814. _SG_GL_CHECK_ERROR();
  6815. GLint gl_int;
  6816. glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl_int);
  6817. _SG_GL_CHECK_ERROR();
  6818. _sg.limits.max_image_size_2d = gl_int;
  6819. _sg.limits.max_image_size_array = gl_int;
  6820. glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &gl_int);
  6821. _SG_GL_CHECK_ERROR();
  6822. _sg.limits.max_image_size_cube = gl_int;
  6823. glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &gl_int);
  6824. _SG_GL_CHECK_ERROR();
  6825. if (gl_int > SG_MAX_VERTEX_ATTRIBUTES) {
  6826. gl_int = SG_MAX_VERTEX_ATTRIBUTES;
  6827. }
  6828. _sg.limits.max_vertex_attrs = gl_int;
  6829. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &gl_int);
  6830. _SG_GL_CHECK_ERROR();
  6831. _sg.limits.gl_max_vertex_uniform_components = gl_int;
  6832. glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &gl_int);
  6833. _SG_GL_CHECK_ERROR();
  6834. _sg.limits.max_image_size_3d = gl_int;
  6835. glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &gl_int);
  6836. _SG_GL_CHECK_ERROR();
  6837. _sg.limits.max_image_array_layers = gl_int;
  6838. if (_sg.gl.ext_anisotropic) {
  6839. glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_int);
  6840. _SG_GL_CHECK_ERROR();
  6841. _sg.gl.max_anisotropy = gl_int;
  6842. } else {
  6843. _sg.gl.max_anisotropy = 1;
  6844. }
  6845. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &gl_int);
  6846. _SG_GL_CHECK_ERROR();
  6847. _sg.limits.gl_max_combined_texture_image_units = gl_int;
  6848. }
  6849. #if defined(SOKOL_GLCORE)
  6850. _SOKOL_PRIVATE void _sg_gl_init_caps_glcore(void) {
  6851. _sg.backend = SG_BACKEND_GLCORE;
  6852. GLint major_version = 0;
  6853. GLint minor_version = 0;
  6854. glGetIntegerv(GL_MAJOR_VERSION, &major_version);
  6855. glGetIntegerv(GL_MINOR_VERSION, &minor_version);
  6856. const int version = major_version * 100 + minor_version * 10;
  6857. _sg.features.origin_top_left = false;
  6858. _sg.features.image_clamp_to_border = true;
  6859. _sg.features.mrt_independent_blend_state = false;
  6860. _sg.features.mrt_independent_write_mask = true;
  6861. _sg.features.storage_buffer = version >= 430;
  6862. #if defined(__APPLE__)
  6863. _sg.features.msaa_image_bindings = false;
  6864. #else
  6865. _sg.features.msaa_image_bindings = true;
  6866. #endif
  6867. // scan extensions
  6868. bool has_s3tc = false; // BC1..BC3
  6869. bool has_rgtc = false; // BC4 and BC5
  6870. bool has_bptc = false; // BC6H and BC7
  6871. bool has_etc2 = false;
  6872. bool has_astc = false;
  6873. GLint num_ext = 0;
  6874. glGetIntegerv(GL_NUM_EXTENSIONS, &num_ext);
  6875. for (int i = 0; i < num_ext; i++) {
  6876. const char* ext = (const char*) glGetStringi(GL_EXTENSIONS, (GLuint)i);
  6877. if (ext) {
  6878. if (strstr(ext, "_texture_compression_s3tc")) {
  6879. has_s3tc = true;
  6880. } else if (strstr(ext, "_texture_compression_rgtc")) {
  6881. has_rgtc = true;
  6882. } else if (strstr(ext, "_texture_compression_bptc")) {
  6883. has_bptc = true;
  6884. } else if (strstr(ext, "_ES3_compatibility")) {
  6885. has_etc2 = true;
  6886. } else if (strstr(ext, "_texture_filter_anisotropic")) {
  6887. _sg.gl.ext_anisotropic = true;
  6888. } else if (strstr(ext, "_texture_compression_astc_ldr")) {
  6889. has_astc = true;
  6890. }
  6891. }
  6892. }
  6893. // limits
  6894. _sg_gl_init_limits();
  6895. // pixel formats
  6896. const bool has_bgra = false; // not a bug
  6897. const bool has_colorbuffer_float = true;
  6898. const bool has_colorbuffer_half_float = true;
  6899. const bool has_texture_float_linear = true; // FIXME???
  6900. const bool has_float_blend = true;
  6901. _sg_gl_init_pixelformats(has_bgra);
  6902. _sg_gl_init_pixelformats_float(has_colorbuffer_float, has_texture_float_linear, has_float_blend);
  6903. _sg_gl_init_pixelformats_half_float(has_colorbuffer_half_float);
  6904. if (has_s3tc) {
  6905. _sg_gl_init_pixelformats_s3tc();
  6906. }
  6907. if (has_rgtc) {
  6908. _sg_gl_init_pixelformats_rgtc();
  6909. }
  6910. if (has_bptc) {
  6911. _sg_gl_init_pixelformats_bptc();
  6912. }
  6913. if (has_etc2) {
  6914. _sg_gl_init_pixelformats_etc2();
  6915. }
  6916. if (has_astc) {
  6917. _sg_gl_init_pixelformats_astc();
  6918. }
  6919. }
  6920. #endif
  6921. #if defined(SOKOL_GLES3)
  6922. _SOKOL_PRIVATE void _sg_gl_init_caps_gles3(void) {
  6923. _sg.backend = SG_BACKEND_GLES3;
  6924. _sg.features.origin_top_left = false;
  6925. _sg.features.image_clamp_to_border = false;
  6926. _sg.features.mrt_independent_blend_state = false;
  6927. _sg.features.mrt_independent_write_mask = false;
  6928. _sg.features.storage_buffer = false;
  6929. _sg.features.msaa_image_bindings = false;
  6930. bool has_s3tc = false; // BC1..BC3
  6931. bool has_rgtc = false; // BC4 and BC5
  6932. bool has_bptc = false; // BC6H and BC7
  6933. #if defined(__EMSCRIPTEN__)
  6934. bool has_etc2 = false;
  6935. #else
  6936. bool has_etc2 = true;
  6937. #endif
  6938. bool has_astc = false;
  6939. bool has_colorbuffer_float = false;
  6940. bool has_colorbuffer_half_float = false;
  6941. bool has_texture_float_linear = false;
  6942. bool has_float_blend = false;
  6943. GLint num_ext = 0;
  6944. glGetIntegerv(GL_NUM_EXTENSIONS, &num_ext);
  6945. for (int i = 0; i < num_ext; i++) {
  6946. const char* ext = (const char*) glGetStringi(GL_EXTENSIONS, (GLuint)i);
  6947. if (ext) {
  6948. if (strstr(ext, "_texture_compression_s3tc")) {
  6949. has_s3tc = true;
  6950. } else if (strstr(ext, "_compressed_texture_s3tc")) {
  6951. has_s3tc = true;
  6952. } else if (strstr(ext, "_texture_compression_rgtc")) {
  6953. has_rgtc = true;
  6954. } else if (strstr(ext, "_texture_compression_bptc")) {
  6955. has_bptc = true;
  6956. } else if (strstr(ext, "_compressed_texture_etc")) {
  6957. has_etc2 = true;
  6958. } else if (strstr(ext, "_compressed_texture_astc")) {
  6959. has_astc = true;
  6960. } else if (strstr(ext, "_color_buffer_float")) {
  6961. has_colorbuffer_float = true;
  6962. } else if (strstr(ext, "_color_buffer_half_float")) {
  6963. has_colorbuffer_half_float = true;
  6964. } else if (strstr(ext, "_texture_float_linear")) {
  6965. has_texture_float_linear = true;
  6966. } else if (strstr(ext, "_float_blend")) {
  6967. has_float_blend = true;
  6968. } else if (strstr(ext, "_texture_filter_anisotropic")) {
  6969. _sg.gl.ext_anisotropic = true;
  6970. }
  6971. }
  6972. }
  6973. /* on WebGL2, color_buffer_float also includes 16-bit formats
  6974. see: https://developer.mozilla.org/en-US/docs/Web/API/EXT_color_buffer_float
  6975. */
  6976. #if defined(__EMSCRIPTEN__)
  6977. if (!has_colorbuffer_half_float && has_colorbuffer_float) {
  6978. has_colorbuffer_half_float = has_colorbuffer_float;
  6979. }
  6980. #endif
  6981. // limits
  6982. _sg_gl_init_limits();
  6983. // pixel formats
  6984. const bool has_bgra = false; // not a bug
  6985. _sg_gl_init_pixelformats(has_bgra);
  6986. _sg_gl_init_pixelformats_float(has_colorbuffer_float, has_texture_float_linear, has_float_blend);
  6987. _sg_gl_init_pixelformats_half_float(has_colorbuffer_half_float);
  6988. if (has_s3tc) {
  6989. _sg_gl_init_pixelformats_s3tc();
  6990. }
  6991. if (has_rgtc) {
  6992. _sg_gl_init_pixelformats_rgtc();
  6993. }
  6994. if (has_bptc) {
  6995. _sg_gl_init_pixelformats_bptc();
  6996. }
  6997. if (has_etc2) {
  6998. _sg_gl_init_pixelformats_etc2();
  6999. }
  7000. if (has_astc) {
  7001. _sg_gl_init_pixelformats_astc();
  7002. }
  7003. }
  7004. #endif
  7005. //-- state cache implementation ------------------------------------------------
  7006. _SOKOL_PRIVATE void _sg_gl_cache_clear_buffer_bindings(bool force) {
  7007. if (force || (_sg.gl.cache.vertex_buffer != 0)) {
  7008. glBindBuffer(GL_ARRAY_BUFFER, 0);
  7009. _sg.gl.cache.vertex_buffer = 0;
  7010. _sg_stats_add(gl.num_bind_buffer, 1);
  7011. }
  7012. if (force || (_sg.gl.cache.index_buffer != 0)) {
  7013. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  7014. _sg.gl.cache.index_buffer = 0;
  7015. _sg_stats_add(gl.num_bind_buffer, 1);
  7016. }
  7017. if (force || (_sg.gl.cache.storage_buffer != 0)) {
  7018. if (_sg.features.storage_buffer) {
  7019. glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
  7020. }
  7021. _sg.gl.cache.storage_buffer = 0;
  7022. _sg_stats_add(gl.num_bind_buffer, 1);
  7023. }
  7024. for (size_t i = 0; i < _SG_GL_MAX_SBUF_BINDINGS; i++) {
  7025. if (force || (_sg.gl.cache.storage_buffers[i] != 0)) {
  7026. if (_sg.features.storage_buffer) {
  7027. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, (GLuint)i, 0);
  7028. }
  7029. _sg.gl.cache.storage_buffers[i] = 0;
  7030. _sg_stats_add(gl.num_bind_buffer, 1);
  7031. }
  7032. }
  7033. }
  7034. _SOKOL_PRIVATE void _sg_gl_cache_bind_buffer(GLenum target, GLuint buffer) {
  7035. SOKOL_ASSERT((GL_ARRAY_BUFFER == target) || (GL_ELEMENT_ARRAY_BUFFER == target) || (GL_SHADER_STORAGE_BUFFER == target));
  7036. if (target == GL_ARRAY_BUFFER) {
  7037. if (_sg.gl.cache.vertex_buffer != buffer) {
  7038. _sg.gl.cache.vertex_buffer = buffer;
  7039. glBindBuffer(target, buffer);
  7040. _sg_stats_add(gl.num_bind_buffer, 1);
  7041. }
  7042. } else if (target == GL_ELEMENT_ARRAY_BUFFER) {
  7043. if (_sg.gl.cache.index_buffer != buffer) {
  7044. _sg.gl.cache.index_buffer = buffer;
  7045. glBindBuffer(target, buffer);
  7046. _sg_stats_add(gl.num_bind_buffer, 1);
  7047. }
  7048. } else if (target == GL_SHADER_STORAGE_BUFFER) {
  7049. if (_sg.gl.cache.storage_buffer != buffer) {
  7050. _sg.gl.cache.storage_buffer = buffer;
  7051. if (_sg.features.storage_buffer) {
  7052. glBindBuffer(target, buffer);
  7053. }
  7054. _sg_stats_add(gl.num_bind_buffer, 1);
  7055. }
  7056. } else {
  7057. SOKOL_UNREACHABLE;
  7058. }
  7059. }
  7060. _SOKOL_PRIVATE void _sg_gl_cache_bind_storage_buffer(uint8_t glsl_binding_n, GLuint buffer) {
  7061. SOKOL_ASSERT(glsl_binding_n < _SG_GL_MAX_SBUF_BINDINGS);
  7062. if (_sg.gl.cache.storage_buffers[glsl_binding_n] != buffer) {
  7063. _sg.gl.cache.storage_buffers[glsl_binding_n] = buffer;
  7064. _sg.gl.cache.storage_buffer = buffer; // not a bug
  7065. if (_sg.features.storage_buffer) {
  7066. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, glsl_binding_n, buffer);
  7067. }
  7068. _sg_stats_add(gl.num_bind_buffer, 1);
  7069. }
  7070. }
  7071. _SOKOL_PRIVATE void _sg_gl_cache_store_buffer_binding(GLenum target) {
  7072. if (target == GL_ARRAY_BUFFER) {
  7073. _sg.gl.cache.stored_vertex_buffer = _sg.gl.cache.vertex_buffer;
  7074. } else if (target == GL_ELEMENT_ARRAY_BUFFER) {
  7075. _sg.gl.cache.stored_index_buffer = _sg.gl.cache.index_buffer;
  7076. } else if (target == GL_SHADER_STORAGE_BUFFER) {
  7077. _sg.gl.cache.stored_storage_buffer = _sg.gl.cache.storage_buffer;
  7078. } else {
  7079. SOKOL_UNREACHABLE;
  7080. }
  7081. }
  7082. _SOKOL_PRIVATE void _sg_gl_cache_restore_buffer_binding(GLenum target) {
  7083. if (target == GL_ARRAY_BUFFER) {
  7084. if (_sg.gl.cache.stored_vertex_buffer != 0) {
  7085. // we only care about restoring valid ids
  7086. _sg_gl_cache_bind_buffer(target, _sg.gl.cache.stored_vertex_buffer);
  7087. _sg.gl.cache.stored_vertex_buffer = 0;
  7088. }
  7089. } else if (target == GL_ELEMENT_ARRAY_BUFFER) {
  7090. if (_sg.gl.cache.stored_index_buffer != 0) {
  7091. // we only care about restoring valid ids
  7092. _sg_gl_cache_bind_buffer(target, _sg.gl.cache.stored_index_buffer);
  7093. _sg.gl.cache.stored_index_buffer = 0;
  7094. }
  7095. } else if (target == GL_SHADER_STORAGE_BUFFER) {
  7096. if (_sg.gl.cache.stored_storage_buffer != 0) {
  7097. // we only care about restoring valid ids
  7098. _sg_gl_cache_bind_buffer(target, _sg.gl.cache.stored_storage_buffer);
  7099. _sg.gl.cache.stored_storage_buffer = 0;
  7100. }
  7101. } else {
  7102. SOKOL_UNREACHABLE;
  7103. }
  7104. }
  7105. // called from _sg_gl_discard_buffer()
  7106. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_buffer(GLuint buf) {
  7107. if (buf == _sg.gl.cache.vertex_buffer) {
  7108. _sg.gl.cache.vertex_buffer = 0;
  7109. glBindBuffer(GL_ARRAY_BUFFER, 0);
  7110. _sg_stats_add(gl.num_bind_buffer, 1);
  7111. }
  7112. if (buf == _sg.gl.cache.index_buffer) {
  7113. _sg.gl.cache.index_buffer = 0;
  7114. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  7115. _sg_stats_add(gl.num_bind_buffer, 1);
  7116. }
  7117. if (buf == _sg.gl.cache.storage_buffer) {
  7118. _sg.gl.cache.storage_buffer = 0;
  7119. glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
  7120. _sg_stats_add(gl.num_bind_buffer, 1);
  7121. }
  7122. for (size_t i = 0; i < _SG_GL_MAX_SBUF_BINDINGS; i++) {
  7123. if (buf == _sg.gl.cache.storage_buffers[i]) {
  7124. _sg.gl.cache.storage_buffers[i] = 0;
  7125. _sg.gl.cache.storage_buffer = 0; // not a bug!
  7126. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, (GLuint)i, 0);
  7127. _sg_stats_add(gl.num_bind_buffer, 1);
  7128. }
  7129. }
  7130. if (buf == _sg.gl.cache.stored_vertex_buffer) {
  7131. _sg.gl.cache.stored_vertex_buffer = 0;
  7132. }
  7133. if (buf == _sg.gl.cache.stored_index_buffer) {
  7134. _sg.gl.cache.stored_index_buffer = 0;
  7135. }
  7136. if (buf == _sg.gl.cache.stored_storage_buffer) {
  7137. _sg.gl.cache.stored_storage_buffer = 0;
  7138. }
  7139. for (int i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  7140. if (buf == _sg.gl.cache.attrs[i].gl_vbuf) {
  7141. _sg.gl.cache.attrs[i].gl_vbuf = 0;
  7142. }
  7143. }
  7144. }
  7145. _SOKOL_PRIVATE void _sg_gl_cache_active_texture(GLenum texture) {
  7146. _SG_GL_CHECK_ERROR();
  7147. if (_sg.gl.cache.cur_active_texture != texture) {
  7148. _sg.gl.cache.cur_active_texture = texture;
  7149. glActiveTexture(texture);
  7150. _sg_stats_add(gl.num_active_texture, 1);
  7151. }
  7152. _SG_GL_CHECK_ERROR();
  7153. }
  7154. _SOKOL_PRIVATE void _sg_gl_cache_clear_texture_sampler_bindings(bool force) {
  7155. _SG_GL_CHECK_ERROR();
  7156. for (int i = 0; (i < _SG_GL_MAX_IMG_SMP_BINDINGS) && (i < _sg.limits.gl_max_combined_texture_image_units); i++) {
  7157. if (force || (_sg.gl.cache.texture_samplers[i].texture != 0)) {
  7158. GLenum gl_texture_unit = (GLenum) (GL_TEXTURE0 + i);
  7159. glActiveTexture(gl_texture_unit);
  7160. _sg_stats_add(gl.num_active_texture, 1);
  7161. glBindTexture(GL_TEXTURE_2D, 0);
  7162. glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
  7163. glBindTexture(GL_TEXTURE_3D, 0);
  7164. glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
  7165. _sg_stats_add(gl.num_bind_texture, 4);
  7166. glBindSampler((GLuint)i, 0);
  7167. _sg_stats_add(gl.num_bind_sampler, 1);
  7168. _sg.gl.cache.texture_samplers[i].target = 0;
  7169. _sg.gl.cache.texture_samplers[i].texture = 0;
  7170. _sg.gl.cache.texture_samplers[i].sampler = 0;
  7171. _sg.gl.cache.cur_active_texture = gl_texture_unit;
  7172. }
  7173. }
  7174. _SG_GL_CHECK_ERROR();
  7175. }
  7176. _SOKOL_PRIVATE void _sg_gl_cache_bind_texture_sampler(int8_t gl_tex_slot, GLenum target, GLuint texture, GLuint sampler) {
  7177. /* it's valid to call this function with target=0 and/or texture=0
  7178. target=0 will unbind the previous binding, texture=0 will clear
  7179. the new binding
  7180. */
  7181. SOKOL_ASSERT((gl_tex_slot >= 0) && (gl_tex_slot < _SG_GL_MAX_IMG_SMP_BINDINGS));
  7182. if (gl_tex_slot >= _sg.limits.gl_max_combined_texture_image_units) {
  7183. return;
  7184. }
  7185. _SG_GL_CHECK_ERROR();
  7186. _sg_gl_cache_texture_sampler_bind_slot* slot = &_sg.gl.cache.texture_samplers[gl_tex_slot];
  7187. if ((slot->target != target) || (slot->texture != texture) || (slot->sampler != sampler)) {
  7188. _sg_gl_cache_active_texture((GLenum)(GL_TEXTURE0 + gl_tex_slot));
  7189. // if the target has changed, clear the previous binding on that target
  7190. if ((target != slot->target) && (slot->target != 0)) {
  7191. glBindTexture(slot->target, 0);
  7192. _SG_GL_CHECK_ERROR();
  7193. _sg_stats_add(gl.num_bind_texture, 1);
  7194. }
  7195. // apply new binding (can be 0 to unbind)
  7196. if (target != 0) {
  7197. glBindTexture(target, texture);
  7198. _SG_GL_CHECK_ERROR();
  7199. _sg_stats_add(gl.num_bind_texture, 1);
  7200. }
  7201. // apply new sampler (can be 0 to unbind)
  7202. glBindSampler((GLuint)gl_tex_slot, sampler);
  7203. _SG_GL_CHECK_ERROR();
  7204. _sg_stats_add(gl.num_bind_sampler, 1);
  7205. slot->target = target;
  7206. slot->texture = texture;
  7207. slot->sampler = sampler;
  7208. }
  7209. }
  7210. _SOKOL_PRIVATE void _sg_gl_cache_store_texture_sampler_binding(int8_t gl_tex_slot) {
  7211. SOKOL_ASSERT((gl_tex_slot >= 0) && (gl_tex_slot < _SG_GL_MAX_IMG_SMP_BINDINGS));
  7212. _sg.gl.cache.stored_texture_sampler = _sg.gl.cache.texture_samplers[gl_tex_slot];
  7213. }
  7214. _SOKOL_PRIVATE void _sg_gl_cache_restore_texture_sampler_binding(int8_t gl_tex_slot) {
  7215. SOKOL_ASSERT((gl_tex_slot >= 0) && (gl_tex_slot < _SG_GL_MAX_IMG_SMP_BINDINGS));
  7216. _sg_gl_cache_texture_sampler_bind_slot* slot = &_sg.gl.cache.stored_texture_sampler;
  7217. if (slot->texture != 0) {
  7218. // we only care about restoring valid ids
  7219. SOKOL_ASSERT(slot->target != 0);
  7220. _sg_gl_cache_bind_texture_sampler(gl_tex_slot, slot->target, slot->texture, slot->sampler);
  7221. slot->target = 0;
  7222. slot->texture = 0;
  7223. slot->sampler = 0;
  7224. }
  7225. }
  7226. // called from _sg_gl_discard_texture() and _sg_gl_discard_sampler()
  7227. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_texture_sampler(GLuint tex, GLuint smp) {
  7228. _SG_GL_CHECK_ERROR();
  7229. for (size_t i = 0; i < _SG_GL_MAX_IMG_SMP_BINDINGS; i++) {
  7230. _sg_gl_cache_texture_sampler_bind_slot* slot = &_sg.gl.cache.texture_samplers[i];
  7231. if ((0 != slot->target) && ((tex == slot->texture) || (smp == slot->sampler))) {
  7232. _sg_gl_cache_active_texture((GLenum)(GL_TEXTURE0 + i));
  7233. glBindTexture(slot->target, 0);
  7234. _SG_GL_CHECK_ERROR();
  7235. _sg_stats_add(gl.num_bind_texture, 1);
  7236. glBindSampler((GLuint)i, 0);
  7237. _SG_GL_CHECK_ERROR();
  7238. _sg_stats_add(gl.num_bind_sampler, 1);
  7239. slot->target = 0;
  7240. slot->texture = 0;
  7241. slot->sampler = 0;
  7242. }
  7243. }
  7244. if ((tex == _sg.gl.cache.stored_texture_sampler.texture) || (smp == _sg.gl.cache.stored_texture_sampler.sampler)) {
  7245. _sg.gl.cache.stored_texture_sampler.target = 0;
  7246. _sg.gl.cache.stored_texture_sampler.texture = 0;
  7247. _sg.gl.cache.stored_texture_sampler.sampler = 0;
  7248. }
  7249. }
  7250. // called from _sg_gl_discard_shader()
  7251. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_program(GLuint prog) {
  7252. if (prog == _sg.gl.cache.prog) {
  7253. _sg.gl.cache.prog = 0;
  7254. glUseProgram(0);
  7255. _sg_stats_add(gl.num_use_program, 1);
  7256. }
  7257. }
  7258. // called from _sg_gl_discard_pipeline()
  7259. _SOKOL_PRIVATE void _sg_gl_cache_invalidate_pipeline(_sg_pipeline_t* pip) {
  7260. if (pip == _sg.gl.cache.cur_pipeline) {
  7261. _sg.gl.cache.cur_pipeline = 0;
  7262. _sg.gl.cache.cur_pipeline_id.id = SG_INVALID_ID;
  7263. }
  7264. }
  7265. _SOKOL_PRIVATE void _sg_gl_reset_state_cache(void) {
  7266. _SG_GL_CHECK_ERROR();
  7267. glBindVertexArray(_sg.gl.vao);
  7268. _SG_GL_CHECK_ERROR();
  7269. _sg_clear(&_sg.gl.cache, sizeof(_sg.gl.cache));
  7270. _sg_gl_cache_clear_buffer_bindings(true);
  7271. _SG_GL_CHECK_ERROR();
  7272. _sg_gl_cache_clear_texture_sampler_bindings(true);
  7273. _SG_GL_CHECK_ERROR();
  7274. for (int i = 0; i < _sg.limits.max_vertex_attrs; i++) {
  7275. _sg_gl_attr_t* attr = &_sg.gl.cache.attrs[i].gl_attr;
  7276. attr->vb_index = -1;
  7277. attr->divisor = -1;
  7278. glDisableVertexAttribArray((GLuint)i);
  7279. _SG_GL_CHECK_ERROR();
  7280. _sg_stats_add(gl.num_disable_vertex_attrib_array, 1);
  7281. }
  7282. _sg.gl.cache.cur_primitive_type = GL_TRIANGLES;
  7283. // shader program
  7284. glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&_sg.gl.cache.prog);
  7285. _SG_GL_CHECK_ERROR();
  7286. // depth and stencil state
  7287. _sg.gl.cache.depth.compare = SG_COMPAREFUNC_ALWAYS;
  7288. _sg.gl.cache.stencil.front.compare = SG_COMPAREFUNC_ALWAYS;
  7289. _sg.gl.cache.stencil.front.fail_op = SG_STENCILOP_KEEP;
  7290. _sg.gl.cache.stencil.front.depth_fail_op = SG_STENCILOP_KEEP;
  7291. _sg.gl.cache.stencil.front.pass_op = SG_STENCILOP_KEEP;
  7292. _sg.gl.cache.stencil.back.compare = SG_COMPAREFUNC_ALWAYS;
  7293. _sg.gl.cache.stencil.back.fail_op = SG_STENCILOP_KEEP;
  7294. _sg.gl.cache.stencil.back.depth_fail_op = SG_STENCILOP_KEEP;
  7295. _sg.gl.cache.stencil.back.pass_op = SG_STENCILOP_KEEP;
  7296. glEnable(GL_DEPTH_TEST);
  7297. glDepthFunc(GL_ALWAYS);
  7298. glDepthMask(GL_FALSE);
  7299. glDisable(GL_STENCIL_TEST);
  7300. glStencilFunc(GL_ALWAYS, 0, 0);
  7301. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  7302. glStencilMask(0);
  7303. _sg_stats_add(gl.num_render_state, 7);
  7304. // blend state
  7305. _sg.gl.cache.blend.src_factor_rgb = SG_BLENDFACTOR_ONE;
  7306. _sg.gl.cache.blend.dst_factor_rgb = SG_BLENDFACTOR_ZERO;
  7307. _sg.gl.cache.blend.op_rgb = SG_BLENDOP_ADD;
  7308. _sg.gl.cache.blend.src_factor_alpha = SG_BLENDFACTOR_ONE;
  7309. _sg.gl.cache.blend.dst_factor_alpha = SG_BLENDFACTOR_ZERO;
  7310. _sg.gl.cache.blend.op_alpha = SG_BLENDOP_ADD;
  7311. glDisable(GL_BLEND);
  7312. glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO);
  7313. glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
  7314. glBlendColor(0.0f, 0.0f, 0.0f, 0.0f);
  7315. _sg_stats_add(gl.num_render_state, 4);
  7316. // standalone state
  7317. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  7318. _sg.gl.cache.color_write_mask[i] = SG_COLORMASK_RGBA;
  7319. }
  7320. _sg.gl.cache.cull_mode = SG_CULLMODE_NONE;
  7321. _sg.gl.cache.face_winding = SG_FACEWINDING_CW;
  7322. _sg.gl.cache.sample_count = 1;
  7323. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  7324. glPolygonOffset(0.0f, 0.0f);
  7325. glDisable(GL_POLYGON_OFFSET_FILL);
  7326. glDisable(GL_CULL_FACE);
  7327. glFrontFace(GL_CW);
  7328. glCullFace(GL_BACK);
  7329. glEnable(GL_SCISSOR_TEST);
  7330. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  7331. glEnable(GL_DITHER);
  7332. glDisable(GL_POLYGON_OFFSET_FILL);
  7333. _sg_stats_add(gl.num_render_state, 10);
  7334. #if defined(SOKOL_GLCORE)
  7335. glEnable(GL_MULTISAMPLE);
  7336. glEnable(GL_PROGRAM_POINT_SIZE);
  7337. _sg_stats_add(gl.num_render_state, 2);
  7338. #endif
  7339. }
  7340. _SOKOL_PRIVATE void _sg_gl_setup_backend(const sg_desc* desc) {
  7341. _SOKOL_UNUSED(desc);
  7342. // assumes that _sg.gl is already zero-initialized
  7343. _sg.gl.valid = true;
  7344. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  7345. _sg_gl_load_opengl();
  7346. #endif
  7347. // clear initial GL error state
  7348. #if defined(SOKOL_DEBUG)
  7349. while (glGetError() != GL_NO_ERROR);
  7350. #endif
  7351. #if defined(SOKOL_GLCORE)
  7352. _sg_gl_init_caps_glcore();
  7353. #elif defined(SOKOL_GLES3)
  7354. _sg_gl_init_caps_gles3();
  7355. #endif
  7356. glGenVertexArrays(1, &_sg.gl.vao);
  7357. glBindVertexArray(_sg.gl.vao);
  7358. _SG_GL_CHECK_ERROR();
  7359. // incoming texture data is generally expected to be packed tightly
  7360. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  7361. #if defined(SOKOL_GLCORE)
  7362. // enable seamless cubemap sampling (only desktop GL)
  7363. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  7364. #endif
  7365. _sg_gl_reset_state_cache();
  7366. }
  7367. _SOKOL_PRIVATE void _sg_gl_discard_backend(void) {
  7368. SOKOL_ASSERT(_sg.gl.valid);
  7369. if (_sg.gl.vao) {
  7370. glDeleteVertexArrays(1, &_sg.gl.vao);
  7371. }
  7372. #if defined(_SOKOL_USE_WIN32_GL_LOADER)
  7373. _sg_gl_unload_opengl();
  7374. #endif
  7375. _sg.gl.valid = false;
  7376. }
  7377. //-- GL backend resource creation and destruction ------------------------------
  7378. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  7379. SOKOL_ASSERT(buf && desc);
  7380. _SG_GL_CHECK_ERROR();
  7381. buf->gl.injected = (0 != desc->gl_buffers[0]);
  7382. const GLenum gl_target = _sg_gl_buffer_target(buf->cmn.type);
  7383. const GLenum gl_usage = _sg_gl_usage(buf->cmn.usage);
  7384. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  7385. GLuint gl_buf = 0;
  7386. if (buf->gl.injected) {
  7387. SOKOL_ASSERT(desc->gl_buffers[slot]);
  7388. gl_buf = desc->gl_buffers[slot];
  7389. } else {
  7390. glGenBuffers(1, &gl_buf);
  7391. SOKOL_ASSERT(gl_buf);
  7392. _sg_gl_cache_store_buffer_binding(gl_target);
  7393. _sg_gl_cache_bind_buffer(gl_target, gl_buf);
  7394. glBufferData(gl_target, buf->cmn.size, 0, gl_usage);
  7395. if (buf->cmn.usage == SG_USAGE_IMMUTABLE) {
  7396. SOKOL_ASSERT(desc->data.ptr);
  7397. glBufferSubData(gl_target, 0, buf->cmn.size, desc->data.ptr);
  7398. }
  7399. _sg_gl_cache_restore_buffer_binding(gl_target);
  7400. }
  7401. buf->gl.buf[slot] = gl_buf;
  7402. }
  7403. _SG_GL_CHECK_ERROR();
  7404. return SG_RESOURCESTATE_VALID;
  7405. }
  7406. _SOKOL_PRIVATE void _sg_gl_discard_buffer(_sg_buffer_t* buf) {
  7407. SOKOL_ASSERT(buf);
  7408. _SG_GL_CHECK_ERROR();
  7409. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  7410. if (buf->gl.buf[slot]) {
  7411. _sg_gl_cache_invalidate_buffer(buf->gl.buf[slot]);
  7412. if (!buf->gl.injected) {
  7413. glDeleteBuffers(1, &buf->gl.buf[slot]);
  7414. }
  7415. }
  7416. }
  7417. _SG_GL_CHECK_ERROR();
  7418. }
  7419. _SOKOL_PRIVATE bool _sg_gl_supported_texture_format(sg_pixel_format fmt) {
  7420. const int fmt_index = (int) fmt;
  7421. SOKOL_ASSERT((fmt_index > SG_PIXELFORMAT_NONE) && (fmt_index < _SG_PIXELFORMAT_NUM));
  7422. return _sg.formats[fmt_index].sample;
  7423. }
  7424. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  7425. SOKOL_ASSERT(img && desc);
  7426. _SG_GL_CHECK_ERROR();
  7427. const bool msaa = img->cmn.sample_count > 1;
  7428. img->gl.injected = (0 != desc->gl_textures[0]);
  7429. // check if texture format is support
  7430. if (!_sg_gl_supported_texture_format(img->cmn.pixel_format)) {
  7431. _SG_ERROR(GL_TEXTURE_FORMAT_NOT_SUPPORTED);
  7432. return SG_RESOURCESTATE_FAILED;
  7433. }
  7434. const GLenum gl_internal_format = _sg_gl_teximage_internal_format(img->cmn.pixel_format);
  7435. // GLES3/WebGL2/macOS doesn't have support for multisampled textures, so create a render buffer object instead
  7436. if (!_sg.features.msaa_image_bindings && img->cmn.render_target && msaa) {
  7437. glGenRenderbuffers(1, &img->gl.msaa_render_buffer);
  7438. glBindRenderbuffer(GL_RENDERBUFFER, img->gl.msaa_render_buffer);
  7439. glRenderbufferStorageMultisample(GL_RENDERBUFFER, img->cmn.sample_count, gl_internal_format, img->cmn.width, img->cmn.height);
  7440. } else if (img->gl.injected) {
  7441. img->gl.target = _sg_gl_texture_target(img->cmn.type, img->cmn.sample_count);
  7442. // inject externally GL textures
  7443. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  7444. SOKOL_ASSERT(desc->gl_textures[slot]);
  7445. img->gl.tex[slot] = desc->gl_textures[slot];
  7446. }
  7447. if (desc->gl_texture_target) {
  7448. img->gl.target = (GLenum)desc->gl_texture_target;
  7449. }
  7450. } else {
  7451. // create our own GL texture(s)
  7452. img->gl.target = _sg_gl_texture_target(img->cmn.type, img->cmn.sample_count);
  7453. const GLenum gl_format = _sg_gl_teximage_format(img->cmn.pixel_format);
  7454. const bool is_compressed = _sg_is_compressed_pixel_format(img->cmn.pixel_format);
  7455. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  7456. glGenTextures(1, &img->gl.tex[slot]);
  7457. SOKOL_ASSERT(img->gl.tex[slot]);
  7458. _sg_gl_cache_store_texture_sampler_binding(0);
  7459. _sg_gl_cache_bind_texture_sampler(0, img->gl.target, img->gl.tex[slot], 0);
  7460. glTexParameteri(img->gl.target, GL_TEXTURE_MAX_LEVEL, img->cmn.num_mipmaps - 1);
  7461. // NOTE: workaround for https://issues.chromium.org/issues/355605685
  7462. // FIXME: on GLES3 and GL 4.3 (e.g. not macOS) the texture initialization
  7463. // should be rewritten to use glTexStorage + glTexSubImage
  7464. bool tex_storage_allocated = false;
  7465. #if defined(__EMSCRIPTEN__)
  7466. if (desc->data.subimage[0][0].ptr == 0) {
  7467. SOKOL_ASSERT(!msaa);
  7468. tex_storage_allocated = true;
  7469. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  7470. glTexStorage2D(img->gl.target, img->cmn.num_mipmaps, gl_internal_format, img->cmn.width, img->cmn.height);
  7471. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  7472. glTexStorage3D(img->gl.target, img->cmn.num_mipmaps, gl_internal_format, img->cmn.width, img->cmn.height, img->cmn.num_slices);
  7473. }
  7474. }
  7475. #endif
  7476. if (!tex_storage_allocated) {
  7477. const int num_faces = img->cmn.type == SG_IMAGETYPE_CUBE ? 6 : 1;
  7478. int data_index = 0;
  7479. for (int face_index = 0; face_index < num_faces; face_index++) {
  7480. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++, data_index++) {
  7481. GLenum gl_img_target = img->gl.target;
  7482. if (SG_IMAGETYPE_CUBE == img->cmn.type) {
  7483. gl_img_target = _sg_gl_cubeface_target(face_index);
  7484. }
  7485. const GLvoid* data_ptr = desc->data.subimage[face_index][mip_index].ptr;
  7486. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  7487. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  7488. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  7489. if (is_compressed) {
  7490. SOKOL_ASSERT(!msaa);
  7491. const GLsizei data_size = (GLsizei) desc->data.subimage[face_index][mip_index].size;
  7492. glCompressedTexImage2D(gl_img_target, mip_index, gl_internal_format,
  7493. mip_width, mip_height, 0, data_size, data_ptr);
  7494. } else {
  7495. const GLenum gl_type = _sg_gl_teximage_type(img->cmn.pixel_format);
  7496. #if defined(SOKOL_GLCORE) && !defined(__APPLE__)
  7497. if (msaa) {
  7498. glTexImage2DMultisample(gl_img_target, img->cmn.sample_count, gl_internal_format,
  7499. mip_width, mip_height, GL_TRUE);
  7500. } else {
  7501. glTexImage2D(gl_img_target, mip_index, (GLint)gl_internal_format,
  7502. mip_width, mip_height, 0, gl_format, gl_type, data_ptr);
  7503. }
  7504. #else
  7505. SOKOL_ASSERT(!msaa);
  7506. glTexImage2D(gl_img_target, mip_index, (GLint)gl_internal_format,
  7507. mip_width, mip_height, 0, gl_format, gl_type, data_ptr);
  7508. #endif
  7509. }
  7510. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  7511. int mip_depth = img->cmn.num_slices;
  7512. if (SG_IMAGETYPE_3D == img->cmn.type) {
  7513. mip_depth = _sg_miplevel_dim(mip_depth, mip_index);
  7514. }
  7515. if (is_compressed) {
  7516. SOKOL_ASSERT(!msaa);
  7517. const GLsizei data_size = (GLsizei) desc->data.subimage[face_index][mip_index].size;
  7518. glCompressedTexImage3D(gl_img_target, mip_index, gl_internal_format,
  7519. mip_width, mip_height, mip_depth, 0, data_size, data_ptr);
  7520. } else {
  7521. const GLenum gl_type = _sg_gl_teximage_type(img->cmn.pixel_format);
  7522. #if defined(SOKOL_GLCORE) && !defined(__APPLE__)
  7523. if (msaa) {
  7524. // NOTE: only for array textures, not actual 3D textures!
  7525. glTexImage3DMultisample(gl_img_target, img->cmn.sample_count, gl_internal_format,
  7526. mip_width, mip_height, mip_depth, GL_TRUE);
  7527. } else {
  7528. glTexImage3D(gl_img_target, mip_index, (GLint)gl_internal_format,
  7529. mip_width, mip_height, mip_depth, 0, gl_format, gl_type, data_ptr);
  7530. }
  7531. #else
  7532. SOKOL_ASSERT(!msaa);
  7533. glTexImage3D(gl_img_target, mip_index, (GLint)gl_internal_format,
  7534. mip_width, mip_height, mip_depth, 0, gl_format, gl_type, data_ptr);
  7535. #endif
  7536. }
  7537. }
  7538. }
  7539. }
  7540. }
  7541. _sg_gl_cache_restore_texture_sampler_binding(0);
  7542. }
  7543. }
  7544. _SG_GL_CHECK_ERROR();
  7545. return SG_RESOURCESTATE_VALID;
  7546. }
  7547. _SOKOL_PRIVATE void _sg_gl_discard_image(_sg_image_t* img) {
  7548. SOKOL_ASSERT(img);
  7549. _SG_GL_CHECK_ERROR();
  7550. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  7551. if (img->gl.tex[slot]) {
  7552. _sg_gl_cache_invalidate_texture_sampler(img->gl.tex[slot], 0);
  7553. if (!img->gl.injected) {
  7554. glDeleteTextures(1, &img->gl.tex[slot]);
  7555. }
  7556. }
  7557. }
  7558. if (img->gl.msaa_render_buffer) {
  7559. glDeleteRenderbuffers(1, &img->gl.msaa_render_buffer);
  7560. }
  7561. _SG_GL_CHECK_ERROR();
  7562. }
  7563. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  7564. SOKOL_ASSERT(smp && desc);
  7565. _SG_GL_CHECK_ERROR();
  7566. smp->gl.injected = (0 != desc->gl_sampler);
  7567. if (smp->gl.injected) {
  7568. smp->gl.smp = (GLuint) desc->gl_sampler;
  7569. } else {
  7570. glGenSamplers(1, &smp->gl.smp);
  7571. SOKOL_ASSERT(smp->gl.smp);
  7572. const GLenum gl_min_filter = _sg_gl_min_filter(smp->cmn.min_filter, smp->cmn.mipmap_filter);
  7573. const GLenum gl_mag_filter = _sg_gl_mag_filter(smp->cmn.mag_filter);
  7574. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_MIN_FILTER, (GLint)gl_min_filter);
  7575. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_MAG_FILTER, (GLint)gl_mag_filter);
  7576. // GL spec has strange defaults for mipmap min/max lod: -1000 to +1000
  7577. const float min_lod = _sg_clamp(desc->min_lod, 0.0f, 1000.0f);
  7578. const float max_lod = _sg_clamp(desc->max_lod, 0.0f, 1000.0f);
  7579. glSamplerParameterf(smp->gl.smp, GL_TEXTURE_MIN_LOD, min_lod);
  7580. glSamplerParameterf(smp->gl.smp, GL_TEXTURE_MAX_LOD, max_lod);
  7581. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_WRAP_S, (GLint)_sg_gl_wrap(smp->cmn.wrap_u));
  7582. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_WRAP_T, (GLint)_sg_gl_wrap(smp->cmn.wrap_v));
  7583. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_WRAP_R, (GLint)_sg_gl_wrap(smp->cmn.wrap_w));
  7584. #if defined(SOKOL_GLCORE)
  7585. float border[4];
  7586. switch (smp->cmn.border_color) {
  7587. case SG_BORDERCOLOR_TRANSPARENT_BLACK:
  7588. border[0] = 0.0f; border[1] = 0.0f; border[2] = 0.0f; border[3] = 0.0f;
  7589. break;
  7590. case SG_BORDERCOLOR_OPAQUE_WHITE:
  7591. border[0] = 1.0f; border[1] = 1.0f; border[2] = 1.0f; border[3] = 1.0f;
  7592. break;
  7593. default:
  7594. border[0] = 0.0f; border[1] = 0.0f; border[2] = 0.0f; border[3] = 1.0f;
  7595. break;
  7596. }
  7597. glSamplerParameterfv(smp->gl.smp, GL_TEXTURE_BORDER_COLOR, border);
  7598. #endif
  7599. if (smp->cmn.compare != SG_COMPAREFUNC_NEVER) {
  7600. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  7601. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_COMPARE_FUNC, (GLint)_sg_gl_compare_func(smp->cmn.compare));
  7602. } else {
  7603. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  7604. }
  7605. if (_sg.gl.ext_anisotropic && (smp->cmn.max_anisotropy > 1)) {
  7606. GLint max_aniso = (GLint) smp->cmn.max_anisotropy;
  7607. if (max_aniso > _sg.gl.max_anisotropy) {
  7608. max_aniso = _sg.gl.max_anisotropy;
  7609. }
  7610. glSamplerParameteri(smp->gl.smp, GL_TEXTURE_MAX_ANISOTROPY_EXT, max_aniso);
  7611. }
  7612. }
  7613. _SG_GL_CHECK_ERROR();
  7614. return SG_RESOURCESTATE_VALID;
  7615. }
  7616. _SOKOL_PRIVATE void _sg_gl_discard_sampler(_sg_sampler_t* smp) {
  7617. SOKOL_ASSERT(smp);
  7618. _SG_GL_CHECK_ERROR();
  7619. _sg_gl_cache_invalidate_texture_sampler(0, smp->gl.smp);
  7620. if (!smp->gl.injected) {
  7621. glDeleteSamplers(1, &smp->gl.smp);
  7622. }
  7623. _SG_GL_CHECK_ERROR();
  7624. }
  7625. _SOKOL_PRIVATE GLuint _sg_gl_compile_shader(sg_shader_stage stage, const char* src) {
  7626. SOKOL_ASSERT(src);
  7627. _SG_GL_CHECK_ERROR();
  7628. GLuint gl_shd = glCreateShader(_sg_gl_shader_stage(stage));
  7629. glShaderSource(gl_shd, 1, &src, 0);
  7630. glCompileShader(gl_shd);
  7631. GLint compile_status = 0;
  7632. glGetShaderiv(gl_shd, GL_COMPILE_STATUS, &compile_status);
  7633. if (!compile_status) {
  7634. // compilation failed, log error and delete shader
  7635. GLint log_len = 0;
  7636. glGetShaderiv(gl_shd, GL_INFO_LOG_LENGTH, &log_len);
  7637. if (log_len > 0) {
  7638. GLchar* log_buf = (GLchar*) _sg_malloc((size_t)log_len);
  7639. glGetShaderInfoLog(gl_shd, log_len, &log_len, log_buf);
  7640. _SG_ERROR(GL_SHADER_COMPILATION_FAILED);
  7641. _SG_LOGMSG(GL_SHADER_COMPILATION_FAILED, log_buf);
  7642. _sg_free(log_buf);
  7643. }
  7644. glDeleteShader(gl_shd);
  7645. gl_shd = 0;
  7646. }
  7647. _SG_GL_CHECK_ERROR();
  7648. return gl_shd;
  7649. }
  7650. // NOTE: this is an out-of-range check for GLSL bindslots that's also active in release mode
  7651. _SOKOL_PRIVATE bool _sg_gl_ensure_glsl_bindslot_ranges(const sg_shader_desc* desc) {
  7652. SOKOL_ASSERT(desc);
  7653. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  7654. if (desc->storage_buffers[i].glsl_binding_n >= _SG_GL_MAX_SBUF_BINDINGS) {
  7655. _SG_ERROR(GL_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE);
  7656. return false;
  7657. }
  7658. }
  7659. return true;
  7660. }
  7661. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  7662. SOKOL_ASSERT(shd && desc);
  7663. SOKOL_ASSERT(!shd->gl.prog);
  7664. _SG_GL_CHECK_ERROR();
  7665. // perform a fatal range-check on GLSL bindslots that's also active
  7666. // in release mode to avoid potential out-of-bounds array accesses
  7667. if (!_sg_gl_ensure_glsl_bindslot_ranges(desc)) {
  7668. return SG_RESOURCESTATE_FAILED;
  7669. }
  7670. // copy the optional vertex attribute names over
  7671. for (int i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  7672. _sg_strcpy(&shd->gl.attrs[i].name, desc->attrs[i].glsl_name);
  7673. }
  7674. GLuint gl_vs = _sg_gl_compile_shader(SG_SHADERSTAGE_VERTEX, desc->vertex_func.source);
  7675. GLuint gl_fs = _sg_gl_compile_shader(SG_SHADERSTAGE_FRAGMENT, desc->fragment_func.source);
  7676. if (!(gl_vs && gl_fs)) {
  7677. return SG_RESOURCESTATE_FAILED;
  7678. }
  7679. GLuint gl_prog = glCreateProgram();
  7680. glAttachShader(gl_prog, gl_vs);
  7681. glAttachShader(gl_prog, gl_fs);
  7682. glLinkProgram(gl_prog);
  7683. glDeleteShader(gl_vs);
  7684. glDeleteShader(gl_fs);
  7685. _SG_GL_CHECK_ERROR();
  7686. GLint link_status;
  7687. glGetProgramiv(gl_prog, GL_LINK_STATUS, &link_status);
  7688. if (!link_status) {
  7689. GLint log_len = 0;
  7690. glGetProgramiv(gl_prog, GL_INFO_LOG_LENGTH, &log_len);
  7691. if (log_len > 0) {
  7692. GLchar* log_buf = (GLchar*) _sg_malloc((size_t)log_len);
  7693. glGetProgramInfoLog(gl_prog, log_len, &log_len, log_buf);
  7694. _SG_ERROR(GL_SHADER_LINKING_FAILED);
  7695. _SG_LOGMSG(GL_SHADER_LINKING_FAILED, log_buf);
  7696. _sg_free(log_buf);
  7697. }
  7698. glDeleteProgram(gl_prog);
  7699. return SG_RESOURCESTATE_FAILED;
  7700. }
  7701. shd->gl.prog = gl_prog;
  7702. // resolve uniforms
  7703. _SG_GL_CHECK_ERROR();
  7704. for (size_t ub_index = 0; ub_index < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_index++) {
  7705. const sg_shader_uniform_block* ub_desc = &desc->uniform_blocks[ub_index];
  7706. if (ub_desc->stage == SG_SHADERSTAGE_NONE) {
  7707. continue;
  7708. }
  7709. SOKOL_ASSERT(ub_desc->size > 0);
  7710. _sg_gl_uniform_block_t* ub = &shd->gl.uniform_blocks[ub_index];
  7711. SOKOL_ASSERT(ub->num_uniforms == 0);
  7712. uint32_t cur_uniform_offset = 0;
  7713. for (int u_index = 0; u_index < SG_MAX_UNIFORMBLOCK_MEMBERS; u_index++) {
  7714. const sg_glsl_shader_uniform* u_desc = &ub_desc->glsl_uniforms[u_index];
  7715. if (u_desc->type == SG_UNIFORMTYPE_INVALID) {
  7716. break;
  7717. }
  7718. const uint32_t u_align = _sg_uniform_alignment(u_desc->type, u_desc->array_count, ub_desc->layout);
  7719. const uint32_t u_size = _sg_uniform_size(u_desc->type, u_desc->array_count, ub_desc->layout);
  7720. cur_uniform_offset = _sg_align_u32(cur_uniform_offset, u_align);
  7721. _sg_gl_uniform_t* u = &ub->uniforms[u_index];
  7722. u->type = u_desc->type;
  7723. u->count = (uint16_t) u_desc->array_count;
  7724. u->offset = (uint16_t) cur_uniform_offset;
  7725. SOKOL_ASSERT(u_desc->glsl_name);
  7726. u->gl_loc = glGetUniformLocation(gl_prog, u_desc->glsl_name);
  7727. if (u->gl_loc == -1) {
  7728. _SG_WARN(GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER);
  7729. _SG_LOGMSG(GL_UNIFORMBLOCK_NAME_NOT_FOUND_IN_SHADER, u_desc->glsl_name);
  7730. }
  7731. cur_uniform_offset += u_size;
  7732. ub->num_uniforms++;
  7733. }
  7734. if (ub_desc->layout == SG_UNIFORMLAYOUT_STD140) {
  7735. cur_uniform_offset = _sg_align_u32(cur_uniform_offset, 16);
  7736. }
  7737. SOKOL_ASSERT(ub_desc->size == (size_t)cur_uniform_offset);
  7738. _SOKOL_UNUSED(cur_uniform_offset);
  7739. }
  7740. // copy storage buffer bind slots
  7741. for (size_t sbuf_index = 0; sbuf_index < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_index++) {
  7742. const sg_shader_storage_buffer* sbuf_desc = &desc->storage_buffers[sbuf_index];
  7743. if (sbuf_desc->stage == SG_SHADERSTAGE_NONE) {
  7744. continue;
  7745. }
  7746. SOKOL_ASSERT(sbuf_desc->glsl_binding_n < _SG_GL_MAX_SBUF_BINDINGS);
  7747. shd->gl.sbuf_binding[sbuf_index] = sbuf_desc->glsl_binding_n;
  7748. }
  7749. // record image sampler location in shader program
  7750. _SG_GL_CHECK_ERROR();
  7751. GLuint cur_prog = 0;
  7752. glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&cur_prog);
  7753. glUseProgram(gl_prog);
  7754. GLint gl_tex_slot = 0;
  7755. for (size_t img_smp_index = 0; img_smp_index < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_index++) {
  7756. const sg_shader_image_sampler_pair* img_smp_desc = &desc->image_sampler_pairs[img_smp_index];
  7757. if (img_smp_desc->stage == SG_SHADERSTAGE_NONE) {
  7758. continue;
  7759. }
  7760. SOKOL_ASSERT(img_smp_desc->glsl_name);
  7761. GLint gl_loc = glGetUniformLocation(gl_prog, img_smp_desc->glsl_name);
  7762. if (gl_loc != -1) {
  7763. glUniform1i(gl_loc, gl_tex_slot);
  7764. shd->gl.tex_slot[img_smp_index] = (int8_t)gl_tex_slot++;
  7765. } else {
  7766. shd->gl.tex_slot[img_smp_index] = -1;
  7767. _SG_WARN(GL_IMAGE_SAMPLER_NAME_NOT_FOUND_IN_SHADER);
  7768. _SG_LOGMSG(GL_IMAGE_SAMPLER_NAME_NOT_FOUND_IN_SHADER, img_smp_desc->glsl_name);
  7769. }
  7770. }
  7771. // it's legal to call glUseProgram with 0
  7772. glUseProgram(cur_prog);
  7773. _SG_GL_CHECK_ERROR();
  7774. return SG_RESOURCESTATE_VALID;
  7775. }
  7776. _SOKOL_PRIVATE void _sg_gl_discard_shader(_sg_shader_t* shd) {
  7777. SOKOL_ASSERT(shd);
  7778. _SG_GL_CHECK_ERROR();
  7779. if (shd->gl.prog) {
  7780. _sg_gl_cache_invalidate_program(shd->gl.prog);
  7781. glDeleteProgram(shd->gl.prog);
  7782. }
  7783. _SG_GL_CHECK_ERROR();
  7784. }
  7785. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_pipeline(_sg_pipeline_t* pip, _sg_shader_t* shd, const sg_pipeline_desc* desc) {
  7786. SOKOL_ASSERT(pip && shd && desc);
  7787. SOKOL_ASSERT((pip->shader == 0) && (pip->cmn.shader_id.id != SG_INVALID_ID));
  7788. SOKOL_ASSERT(desc->shader.id == shd->slot.id);
  7789. SOKOL_ASSERT(shd->gl.prog);
  7790. SOKOL_ASSERT(_sg.limits.max_vertex_attrs <= SG_MAX_VERTEX_ATTRIBUTES);
  7791. pip->shader = shd;
  7792. pip->gl.primitive_type = desc->primitive_type;
  7793. pip->gl.depth = desc->depth;
  7794. pip->gl.stencil = desc->stencil;
  7795. // FIXME: blend color and write mask per draw-buffer-attachment (requires GL4)
  7796. pip->gl.blend = desc->colors[0].blend;
  7797. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  7798. pip->gl.color_write_mask[i] = desc->colors[i].write_mask;
  7799. }
  7800. pip->gl.cull_mode = desc->cull_mode;
  7801. pip->gl.face_winding = desc->face_winding;
  7802. pip->gl.sample_count = desc->sample_count;
  7803. pip->gl.alpha_to_coverage_enabled = desc->alpha_to_coverage_enabled;
  7804. // NOTE: GLSL compilers may remove unused vertex attributes so we can't rely
  7805. // on the 'prepopulated' vertex_buffer_layout_active[] state and need to
  7806. // fill this array from scratch with the actual info after GLSL compilation
  7807. for (int i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  7808. pip->cmn.vertex_buffer_layout_active[i] = false;
  7809. }
  7810. // resolve vertex attributes
  7811. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  7812. pip->gl.attrs[attr_index].vb_index = -1;
  7813. }
  7814. for (int attr_index = 0; attr_index < _sg.limits.max_vertex_attrs; attr_index++) {
  7815. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  7816. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  7817. break;
  7818. }
  7819. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  7820. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[a_state->buffer_index];
  7821. const sg_vertex_step step_func = l_state->step_func;
  7822. const int step_rate = l_state->step_rate;
  7823. GLint attr_loc = attr_index;
  7824. if (!_sg_strempty(&shd->gl.attrs[attr_index].name)) {
  7825. attr_loc = glGetAttribLocation(pip->shader->gl.prog, _sg_strptr(&shd->gl.attrs[attr_index].name));
  7826. }
  7827. if (attr_loc != -1) {
  7828. SOKOL_ASSERT(attr_loc < (GLint)_sg.limits.max_vertex_attrs);
  7829. _sg_gl_attr_t* gl_attr = &pip->gl.attrs[attr_loc];
  7830. SOKOL_ASSERT(gl_attr->vb_index == -1);
  7831. gl_attr->vb_index = (int8_t) a_state->buffer_index;
  7832. if (step_func == SG_VERTEXSTEP_PER_VERTEX) {
  7833. gl_attr->divisor = 0;
  7834. } else {
  7835. gl_attr->divisor = (int8_t) step_rate;
  7836. pip->cmn.use_instanced_draw = true;
  7837. }
  7838. SOKOL_ASSERT(l_state->stride > 0);
  7839. gl_attr->stride = (uint8_t) l_state->stride;
  7840. gl_attr->offset = a_state->offset;
  7841. gl_attr->size = (uint8_t) _sg_gl_vertexformat_size(a_state->format);
  7842. gl_attr->type = _sg_gl_vertexformat_type(a_state->format);
  7843. gl_attr->normalized = _sg_gl_vertexformat_normalized(a_state->format);
  7844. pip->cmn.vertex_buffer_layout_active[a_state->buffer_index] = true;
  7845. } else {
  7846. _SG_WARN(GL_VERTEX_ATTRIBUTE_NOT_FOUND_IN_SHADER);
  7847. _SG_LOGMSG(GL_VERTEX_ATTRIBUTE_NOT_FOUND_IN_SHADER, _sg_strptr(&shd->gl.attrs[attr_index].name));
  7848. }
  7849. }
  7850. return SG_RESOURCESTATE_VALID;
  7851. }
  7852. _SOKOL_PRIVATE void _sg_gl_discard_pipeline(_sg_pipeline_t* pip) {
  7853. SOKOL_ASSERT(pip);
  7854. _sg_gl_cache_invalidate_pipeline(pip);
  7855. }
  7856. _SOKOL_PRIVATE void _sg_gl_fb_attach_texture(const _sg_gl_attachment_t* gl_att, const _sg_attachment_common_t* cmn_att, GLenum gl_att_type) {
  7857. const _sg_image_t* img = gl_att->image;
  7858. SOKOL_ASSERT(img);
  7859. const GLuint gl_tex = img->gl.tex[0];
  7860. SOKOL_ASSERT(gl_tex);
  7861. const GLuint gl_target = img->gl.target;
  7862. SOKOL_ASSERT(gl_target);
  7863. const int mip_level = cmn_att->mip_level;
  7864. const int slice = cmn_att->slice;
  7865. switch (img->cmn.type) {
  7866. case SG_IMAGETYPE_2D:
  7867. glFramebufferTexture2D(GL_FRAMEBUFFER, gl_att_type, gl_target, gl_tex, mip_level);
  7868. break;
  7869. case SG_IMAGETYPE_CUBE:
  7870. glFramebufferTexture2D(GL_FRAMEBUFFER, gl_att_type, _sg_gl_cubeface_target(slice), gl_tex, mip_level);
  7871. break;
  7872. default:
  7873. glFramebufferTextureLayer(GL_FRAMEBUFFER, gl_att_type, gl_tex, mip_level, slice);
  7874. break;
  7875. }
  7876. }
  7877. _SOKOL_PRIVATE GLenum _sg_gl_depth_stencil_attachment_type(const _sg_gl_attachment_t* ds_att) {
  7878. const _sg_image_t* img = ds_att->image;
  7879. SOKOL_ASSERT(img);
  7880. if (_sg_is_depth_stencil_format(img->cmn.pixel_format)) {
  7881. return GL_DEPTH_STENCIL_ATTACHMENT;
  7882. } else {
  7883. return GL_DEPTH_ATTACHMENT;
  7884. }
  7885. }
  7886. _SOKOL_PRIVATE sg_resource_state _sg_gl_create_attachments(_sg_attachments_t* atts, _sg_image_t** color_images, _sg_image_t** resolve_images, _sg_image_t* ds_image, const sg_attachments_desc* desc) {
  7887. SOKOL_ASSERT(atts && desc);
  7888. SOKOL_ASSERT(color_images && resolve_images);
  7889. _SG_GL_CHECK_ERROR();
  7890. // copy image pointers
  7891. for (int i = 0; i < atts->cmn.num_colors; i++) {
  7892. const sg_attachment_desc* color_desc = &desc->colors[i];
  7893. _SOKOL_UNUSED(color_desc);
  7894. SOKOL_ASSERT(color_desc->image.id != SG_INVALID_ID);
  7895. SOKOL_ASSERT(0 == atts->gl.colors[i].image);
  7896. SOKOL_ASSERT(color_images[i] && (color_images[i]->slot.id == color_desc->image.id));
  7897. SOKOL_ASSERT(_sg_is_valid_rendertarget_color_format(color_images[i]->cmn.pixel_format));
  7898. atts->gl.colors[i].image = color_images[i];
  7899. const sg_attachment_desc* resolve_desc = &desc->resolves[i];
  7900. if (resolve_desc->image.id != SG_INVALID_ID) {
  7901. SOKOL_ASSERT(0 == atts->gl.resolves[i].image);
  7902. SOKOL_ASSERT(resolve_images[i] && (resolve_images[i]->slot.id == resolve_desc->image.id));
  7903. SOKOL_ASSERT(color_images[i] && (color_images[i]->cmn.pixel_format == resolve_images[i]->cmn.pixel_format));
  7904. atts->gl.resolves[i].image = resolve_images[i];
  7905. }
  7906. }
  7907. SOKOL_ASSERT(0 == atts->gl.depth_stencil.image);
  7908. const sg_attachment_desc* ds_desc = &desc->depth_stencil;
  7909. if (ds_desc->image.id != SG_INVALID_ID) {
  7910. SOKOL_ASSERT(ds_image && (ds_image->slot.id == ds_desc->image.id));
  7911. SOKOL_ASSERT(_sg_is_valid_rendertarget_depth_format(ds_image->cmn.pixel_format));
  7912. atts->gl.depth_stencil.image = ds_image;
  7913. }
  7914. // store current framebuffer binding (restored at end of function)
  7915. GLuint gl_orig_fb;
  7916. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&gl_orig_fb);
  7917. // create a framebuffer object
  7918. glGenFramebuffers(1, &atts->gl.fb);
  7919. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.fb);
  7920. // attach color attachments to framebuffer
  7921. for (int i = 0; i < atts->cmn.num_colors; i++) {
  7922. const _sg_image_t* color_img = atts->gl.colors[i].image;
  7923. SOKOL_ASSERT(color_img);
  7924. const GLuint gl_msaa_render_buffer = color_img->gl.msaa_render_buffer;
  7925. if (gl_msaa_render_buffer) {
  7926. glFramebufferRenderbuffer(GL_FRAMEBUFFER, (GLenum)(GL_COLOR_ATTACHMENT0+i), GL_RENDERBUFFER, gl_msaa_render_buffer);
  7927. } else {
  7928. const GLenum gl_att_type = (GLenum)(GL_COLOR_ATTACHMENT0 + i);
  7929. _sg_gl_fb_attach_texture(&atts->gl.colors[i], &atts->cmn.colors[i], gl_att_type);
  7930. }
  7931. }
  7932. // attach depth-stencil attachment
  7933. if (atts->gl.depth_stencil.image) {
  7934. const GLenum gl_att = _sg_gl_depth_stencil_attachment_type(&atts->gl.depth_stencil);
  7935. const _sg_image_t* ds_img = atts->gl.depth_stencil.image;
  7936. const GLuint gl_msaa_render_buffer = ds_img->gl.msaa_render_buffer;
  7937. if (gl_msaa_render_buffer) {
  7938. glFramebufferRenderbuffer(GL_FRAMEBUFFER, gl_att, GL_RENDERBUFFER, gl_msaa_render_buffer);
  7939. } else {
  7940. const GLenum gl_att_type = _sg_gl_depth_stencil_attachment_type(&atts->gl.depth_stencil);
  7941. _sg_gl_fb_attach_texture(&atts->gl.depth_stencil, &atts->cmn.depth_stencil, gl_att_type);
  7942. }
  7943. }
  7944. // check if framebuffer is complete
  7945. {
  7946. const GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  7947. if (fb_status != GL_FRAMEBUFFER_COMPLETE) {
  7948. switch (fb_status) {
  7949. case GL_FRAMEBUFFER_UNDEFINED:
  7950. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNDEFINED);
  7951. break;
  7952. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  7953. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_ATTACHMENT);
  7954. break;
  7955. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  7956. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MISSING_ATTACHMENT);
  7957. break;
  7958. case GL_FRAMEBUFFER_UNSUPPORTED:
  7959. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNSUPPORTED);
  7960. break;
  7961. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  7962. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MULTISAMPLE);
  7963. break;
  7964. default:
  7965. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNKNOWN);
  7966. break;
  7967. }
  7968. return SG_RESOURCESTATE_FAILED;
  7969. }
  7970. }
  7971. // setup color attachments for the framebuffer
  7972. static const GLenum gl_draw_bufs[SG_MAX_COLOR_ATTACHMENTS] = {
  7973. GL_COLOR_ATTACHMENT0,
  7974. GL_COLOR_ATTACHMENT1,
  7975. GL_COLOR_ATTACHMENT2,
  7976. GL_COLOR_ATTACHMENT3
  7977. };
  7978. glDrawBuffers(atts->cmn.num_colors, gl_draw_bufs);
  7979. // create MSAA resolve framebuffers if necessary
  7980. for (int i = 0; i < atts->cmn.num_colors; i++) {
  7981. _sg_gl_attachment_t* gl_resolve_att = &atts->gl.resolves[i];
  7982. if (gl_resolve_att->image) {
  7983. _sg_attachment_common_t* cmn_resolve_att = &atts->cmn.resolves[i];
  7984. SOKOL_ASSERT(0 == atts->gl.msaa_resolve_framebuffer[i]);
  7985. glGenFramebuffers(1, &atts->gl.msaa_resolve_framebuffer[i]);
  7986. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.msaa_resolve_framebuffer[i]);
  7987. _sg_gl_fb_attach_texture(gl_resolve_att, cmn_resolve_att, GL_COLOR_ATTACHMENT0);
  7988. // check if framebuffer is complete
  7989. const GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  7990. if (fb_status != GL_FRAMEBUFFER_COMPLETE) {
  7991. switch (fb_status) {
  7992. case GL_FRAMEBUFFER_UNDEFINED:
  7993. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNDEFINED);
  7994. break;
  7995. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  7996. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_ATTACHMENT);
  7997. break;
  7998. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  7999. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MISSING_ATTACHMENT);
  8000. break;
  8001. case GL_FRAMEBUFFER_UNSUPPORTED:
  8002. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNSUPPORTED);
  8003. break;
  8004. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  8005. _SG_ERROR(GL_FRAMEBUFFER_STATUS_INCOMPLETE_MULTISAMPLE);
  8006. break;
  8007. default:
  8008. _SG_ERROR(GL_FRAMEBUFFER_STATUS_UNKNOWN);
  8009. break;
  8010. }
  8011. return SG_RESOURCESTATE_FAILED;
  8012. }
  8013. // setup color attachments for the framebuffer
  8014. glDrawBuffers(1, &gl_draw_bufs[0]);
  8015. }
  8016. }
  8017. // restore original framebuffer binding
  8018. glBindFramebuffer(GL_FRAMEBUFFER, gl_orig_fb);
  8019. _SG_GL_CHECK_ERROR();
  8020. return SG_RESOURCESTATE_VALID;
  8021. }
  8022. _SOKOL_PRIVATE void _sg_gl_discard_attachments(_sg_attachments_t* atts) {
  8023. SOKOL_ASSERT(atts);
  8024. _SG_GL_CHECK_ERROR();
  8025. if (0 != atts->gl.fb) {
  8026. glDeleteFramebuffers(1, &atts->gl.fb);
  8027. }
  8028. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  8029. if (atts->gl.msaa_resolve_framebuffer[i]) {
  8030. glDeleteFramebuffers(1, &atts->gl.msaa_resolve_framebuffer[i]);
  8031. }
  8032. }
  8033. _SG_GL_CHECK_ERROR();
  8034. }
  8035. _SOKOL_PRIVATE _sg_image_t* _sg_gl_attachments_color_image(const _sg_attachments_t* atts, int index) {
  8036. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  8037. return atts->gl.colors[index].image;
  8038. }
  8039. _SOKOL_PRIVATE _sg_image_t* _sg_gl_attachments_resolve_image(const _sg_attachments_t* atts, int index) {
  8040. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  8041. return atts->gl.resolves[index].image;
  8042. }
  8043. _SOKOL_PRIVATE _sg_image_t* _sg_gl_attachments_ds_image(const _sg_attachments_t* atts) {
  8044. SOKOL_ASSERT(atts);
  8045. return atts->gl.depth_stencil.image;
  8046. }
  8047. _SOKOL_PRIVATE void _sg_gl_begin_pass(const sg_pass* pass) {
  8048. // FIXME: what if a texture used as render target is still bound, should we
  8049. // unbind all currently bound textures in begin pass?
  8050. SOKOL_ASSERT(pass);
  8051. _SG_GL_CHECK_ERROR();
  8052. const _sg_attachments_t* atts = _sg.cur_pass.atts;
  8053. const sg_swapchain* swapchain = &pass->swapchain;
  8054. const sg_pass_action* action = &pass->action;
  8055. // bind the render pass framebuffer
  8056. //
  8057. // FIXME: Disabling SRGB conversion for the default framebuffer is
  8058. // a crude hack to make behaviour for sRGB render target textures
  8059. // identical with the Metal and D3D11 swapchains created by sokol-app.
  8060. //
  8061. // This will need a cleaner solution (e.g. allowing to configure
  8062. // sokol_app.h with an sRGB or RGB framebuffer.
  8063. if (atts) {
  8064. // offscreen pass
  8065. SOKOL_ASSERT(atts->gl.fb);
  8066. #if defined(SOKOL_GLCORE)
  8067. glEnable(GL_FRAMEBUFFER_SRGB);
  8068. #endif
  8069. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.fb);
  8070. } else {
  8071. // default pass
  8072. #if defined(SOKOL_GLCORE)
  8073. glDisable(GL_FRAMEBUFFER_SRGB);
  8074. #endif
  8075. // NOTE: on some platforms, the default framebuffer of a context
  8076. // is null, so we can't actually assert here that the
  8077. // framebuffer has been provided
  8078. glBindFramebuffer(GL_FRAMEBUFFER, swapchain->gl.framebuffer);
  8079. }
  8080. glViewport(0, 0, _sg.cur_pass.width, _sg.cur_pass.height);
  8081. glScissor(0, 0, _sg.cur_pass.width, _sg.cur_pass.height);
  8082. // number of color attachments
  8083. const int num_color_atts = atts ? atts->cmn.num_colors : 1;
  8084. // clear color and depth-stencil attachments if needed
  8085. bool clear_any_color = false;
  8086. for (int i = 0; i < num_color_atts; i++) {
  8087. if (SG_LOADACTION_CLEAR == action->colors[i].load_action) {
  8088. clear_any_color = true;
  8089. break;
  8090. }
  8091. }
  8092. const bool clear_depth = (action->depth.load_action == SG_LOADACTION_CLEAR);
  8093. const bool clear_stencil = (action->stencil.load_action == SG_LOADACTION_CLEAR);
  8094. bool need_pip_cache_flush = false;
  8095. if (clear_any_color) {
  8096. bool need_color_mask_flush = false;
  8097. // NOTE: not a bug to iterate over all possible color attachments
  8098. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  8099. if (SG_COLORMASK_RGBA != _sg.gl.cache.color_write_mask[i]) {
  8100. need_pip_cache_flush = true;
  8101. need_color_mask_flush = true;
  8102. _sg.gl.cache.color_write_mask[i] = SG_COLORMASK_RGBA;
  8103. }
  8104. }
  8105. if (need_color_mask_flush) {
  8106. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  8107. }
  8108. }
  8109. if (clear_depth) {
  8110. if (!_sg.gl.cache.depth.write_enabled) {
  8111. need_pip_cache_flush = true;
  8112. _sg.gl.cache.depth.write_enabled = true;
  8113. glDepthMask(GL_TRUE);
  8114. }
  8115. if (_sg.gl.cache.depth.compare != SG_COMPAREFUNC_ALWAYS) {
  8116. need_pip_cache_flush = true;
  8117. _sg.gl.cache.depth.compare = SG_COMPAREFUNC_ALWAYS;
  8118. glDepthFunc(GL_ALWAYS);
  8119. }
  8120. }
  8121. if (clear_stencil) {
  8122. if (_sg.gl.cache.stencil.write_mask != 0xFF) {
  8123. need_pip_cache_flush = true;
  8124. _sg.gl.cache.stencil.write_mask = 0xFF;
  8125. glStencilMask(0xFF);
  8126. }
  8127. }
  8128. if (need_pip_cache_flush) {
  8129. // we messed with the state cache directly, need to clear cached
  8130. // pipeline to force re-evaluation in next sg_apply_pipeline()
  8131. _sg.gl.cache.cur_pipeline = 0;
  8132. _sg.gl.cache.cur_pipeline_id.id = SG_INVALID_ID;
  8133. }
  8134. for (int i = 0; i < num_color_atts; i++) {
  8135. if (action->colors[i].load_action == SG_LOADACTION_CLEAR) {
  8136. glClearBufferfv(GL_COLOR, i, &action->colors[i].clear_value.r);
  8137. }
  8138. }
  8139. if ((atts == 0) || (atts->gl.depth_stencil.image)) {
  8140. if (clear_depth && clear_stencil) {
  8141. glClearBufferfi(GL_DEPTH_STENCIL, 0, action->depth.clear_value, action->stencil.clear_value);
  8142. } else if (clear_depth) {
  8143. glClearBufferfv(GL_DEPTH, 0, &action->depth.clear_value);
  8144. } else if (clear_stencil) {
  8145. GLint val = (GLint) action->stencil.clear_value;
  8146. glClearBufferiv(GL_STENCIL, 0, &val);
  8147. }
  8148. }
  8149. // keep store actions for end-pass
  8150. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  8151. _sg.gl.color_store_actions[i] = action->colors[i].store_action;
  8152. }
  8153. _sg.gl.depth_store_action = action->depth.store_action;
  8154. _sg.gl.stencil_store_action = action->stencil.store_action;
  8155. _SG_GL_CHECK_ERROR();
  8156. }
  8157. _SOKOL_PRIVATE void _sg_gl_end_pass(void) {
  8158. _SG_GL_CHECK_ERROR();
  8159. if (_sg.cur_pass.atts) {
  8160. const _sg_attachments_t* atts = _sg.cur_pass.atts;
  8161. SOKOL_ASSERT(atts->slot.id == _sg.cur_pass.atts_id.id);
  8162. bool fb_read_bound = false;
  8163. bool fb_draw_bound = false;
  8164. const int num_color_atts = atts->cmn.num_colors;
  8165. for (int i = 0; i < num_color_atts; i++) {
  8166. // perform MSAA resolve if needed
  8167. if (atts->gl.msaa_resolve_framebuffer[i] != 0) {
  8168. if (!fb_read_bound) {
  8169. SOKOL_ASSERT(atts->gl.fb);
  8170. glBindFramebuffer(GL_READ_FRAMEBUFFER, atts->gl.fb);
  8171. fb_read_bound = true;
  8172. }
  8173. const int w = atts->gl.colors[i].image->cmn.width;
  8174. const int h = atts->gl.colors[i].image->cmn.height;
  8175. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, atts->gl.msaa_resolve_framebuffer[i]);
  8176. glReadBuffer((GLenum)(GL_COLOR_ATTACHMENT0 + i));
  8177. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  8178. fb_draw_bound = true;
  8179. }
  8180. }
  8181. // invalidate framebuffers
  8182. _SOKOL_UNUSED(fb_draw_bound);
  8183. #if defined(SOKOL_GLES3)
  8184. // need to restore framebuffer binding before invalidate if the MSAA resolve had changed the binding
  8185. if (fb_draw_bound) {
  8186. glBindFramebuffer(GL_FRAMEBUFFER, atts->gl.fb);
  8187. }
  8188. GLenum invalidate_atts[SG_MAX_COLOR_ATTACHMENTS + 2] = { 0 };
  8189. int att_index = 0;
  8190. for (int i = 0; i < num_color_atts; i++) {
  8191. if (_sg.gl.color_store_actions[i] == SG_STOREACTION_DONTCARE) {
  8192. invalidate_atts[att_index++] = (GLenum)(GL_COLOR_ATTACHMENT0 + i);
  8193. }
  8194. }
  8195. if ((_sg.gl.depth_store_action == SG_STOREACTION_DONTCARE) && (_sg.cur_pass.atts->cmn.depth_stencil.image_id.id != SG_INVALID_ID)) {
  8196. invalidate_atts[att_index++] = GL_DEPTH_ATTACHMENT;
  8197. }
  8198. if ((_sg.gl.stencil_store_action == SG_STOREACTION_DONTCARE) && (_sg.cur_pass.atts->cmn.depth_stencil.image_id.id != SG_INVALID_ID)) {
  8199. invalidate_atts[att_index++] = GL_STENCIL_ATTACHMENT;
  8200. }
  8201. if (att_index > 0) {
  8202. glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, att_index, invalidate_atts);
  8203. }
  8204. #endif
  8205. }
  8206. _SG_GL_CHECK_ERROR();
  8207. }
  8208. _SOKOL_PRIVATE void _sg_gl_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  8209. y = origin_top_left ? (_sg.cur_pass.height - (y+h)) : y;
  8210. glViewport(x, y, w, h);
  8211. }
  8212. _SOKOL_PRIVATE void _sg_gl_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  8213. y = origin_top_left ? (_sg.cur_pass.height - (y+h)) : y;
  8214. glScissor(x, y, w, h);
  8215. }
  8216. _SOKOL_PRIVATE void _sg_gl_apply_pipeline(_sg_pipeline_t* pip) {
  8217. SOKOL_ASSERT(pip);
  8218. SOKOL_ASSERT(pip->shader && (pip->cmn.shader_id.id == pip->shader->slot.id));
  8219. _SG_GL_CHECK_ERROR();
  8220. if ((_sg.gl.cache.cur_pipeline != pip) || (_sg.gl.cache.cur_pipeline_id.id != pip->slot.id)) {
  8221. _sg.gl.cache.cur_pipeline = pip;
  8222. _sg.gl.cache.cur_pipeline_id.id = pip->slot.id;
  8223. _sg.gl.cache.cur_primitive_type = _sg_gl_primitive_type(pip->gl.primitive_type);
  8224. _sg.gl.cache.cur_index_type = _sg_gl_index_type(pip->cmn.index_type);
  8225. // update depth state
  8226. {
  8227. const sg_depth_state* state_ds = &pip->gl.depth;
  8228. sg_depth_state* cache_ds = &_sg.gl.cache.depth;
  8229. if (state_ds->compare != cache_ds->compare) {
  8230. cache_ds->compare = state_ds->compare;
  8231. glDepthFunc(_sg_gl_compare_func(state_ds->compare));
  8232. _sg_stats_add(gl.num_render_state, 1);
  8233. }
  8234. if (state_ds->write_enabled != cache_ds->write_enabled) {
  8235. cache_ds->write_enabled = state_ds->write_enabled;
  8236. glDepthMask(state_ds->write_enabled);
  8237. _sg_stats_add(gl.num_render_state, 1);
  8238. }
  8239. if (!_sg_fequal(state_ds->bias, cache_ds->bias, 0.000001f) ||
  8240. !_sg_fequal(state_ds->bias_slope_scale, cache_ds->bias_slope_scale, 0.000001f))
  8241. {
  8242. /* according to ANGLE's D3D11 backend:
  8243. D3D11 SlopeScaledDepthBias ==> GL polygonOffsetFactor
  8244. D3D11 DepthBias ==> GL polygonOffsetUnits
  8245. DepthBiasClamp has no meaning on GL
  8246. */
  8247. cache_ds->bias = state_ds->bias;
  8248. cache_ds->bias_slope_scale = state_ds->bias_slope_scale;
  8249. glPolygonOffset(state_ds->bias_slope_scale, state_ds->bias);
  8250. _sg_stats_add(gl.num_render_state, 1);
  8251. bool po_enabled = true;
  8252. if (_sg_fequal(state_ds->bias, 0.0f, 0.000001f) &&
  8253. _sg_fequal(state_ds->bias_slope_scale, 0.0f, 0.000001f))
  8254. {
  8255. po_enabled = false;
  8256. }
  8257. if (po_enabled != _sg.gl.cache.polygon_offset_enabled) {
  8258. _sg.gl.cache.polygon_offset_enabled = po_enabled;
  8259. if (po_enabled) {
  8260. glEnable(GL_POLYGON_OFFSET_FILL);
  8261. } else {
  8262. glDisable(GL_POLYGON_OFFSET_FILL);
  8263. }
  8264. _sg_stats_add(gl.num_render_state, 1);
  8265. }
  8266. }
  8267. }
  8268. // update stencil state
  8269. {
  8270. const sg_stencil_state* state_ss = &pip->gl.stencil;
  8271. sg_stencil_state* cache_ss = &_sg.gl.cache.stencil;
  8272. if (state_ss->enabled != cache_ss->enabled) {
  8273. cache_ss->enabled = state_ss->enabled;
  8274. if (state_ss->enabled) {
  8275. glEnable(GL_STENCIL_TEST);
  8276. } else {
  8277. glDisable(GL_STENCIL_TEST);
  8278. }
  8279. _sg_stats_add(gl.num_render_state, 1);
  8280. }
  8281. if (state_ss->write_mask != cache_ss->write_mask) {
  8282. cache_ss->write_mask = state_ss->write_mask;
  8283. glStencilMask(state_ss->write_mask);
  8284. _sg_stats_add(gl.num_render_state, 1);
  8285. }
  8286. for (int i = 0; i < 2; i++) {
  8287. const sg_stencil_face_state* state_sfs = (i==0)? &state_ss->front : &state_ss->back;
  8288. sg_stencil_face_state* cache_sfs = (i==0)? &cache_ss->front : &cache_ss->back;
  8289. GLenum gl_face = (i==0)? GL_FRONT : GL_BACK;
  8290. if ((state_sfs->compare != cache_sfs->compare) ||
  8291. (state_ss->read_mask != cache_ss->read_mask) ||
  8292. (state_ss->ref != cache_ss->ref))
  8293. {
  8294. cache_sfs->compare = state_sfs->compare;
  8295. glStencilFuncSeparate(gl_face,
  8296. _sg_gl_compare_func(state_sfs->compare),
  8297. state_ss->ref,
  8298. state_ss->read_mask);
  8299. _sg_stats_add(gl.num_render_state, 1);
  8300. }
  8301. if ((state_sfs->fail_op != cache_sfs->fail_op) ||
  8302. (state_sfs->depth_fail_op != cache_sfs->depth_fail_op) ||
  8303. (state_sfs->pass_op != cache_sfs->pass_op))
  8304. {
  8305. cache_sfs->fail_op = state_sfs->fail_op;
  8306. cache_sfs->depth_fail_op = state_sfs->depth_fail_op;
  8307. cache_sfs->pass_op = state_sfs->pass_op;
  8308. glStencilOpSeparate(gl_face,
  8309. _sg_gl_stencil_op(state_sfs->fail_op),
  8310. _sg_gl_stencil_op(state_sfs->depth_fail_op),
  8311. _sg_gl_stencil_op(state_sfs->pass_op));
  8312. _sg_stats_add(gl.num_render_state, 1);
  8313. }
  8314. }
  8315. cache_ss->read_mask = state_ss->read_mask;
  8316. cache_ss->ref = state_ss->ref;
  8317. }
  8318. if (pip->cmn.color_count > 0) {
  8319. // update blend state
  8320. // FIXME: separate blend state per color attachment not support, needs GL4
  8321. const sg_blend_state* state_bs = &pip->gl.blend;
  8322. sg_blend_state* cache_bs = &_sg.gl.cache.blend;
  8323. if (state_bs->enabled != cache_bs->enabled) {
  8324. cache_bs->enabled = state_bs->enabled;
  8325. if (state_bs->enabled) {
  8326. glEnable(GL_BLEND);
  8327. } else {
  8328. glDisable(GL_BLEND);
  8329. }
  8330. _sg_stats_add(gl.num_render_state, 1);
  8331. }
  8332. if ((state_bs->src_factor_rgb != cache_bs->src_factor_rgb) ||
  8333. (state_bs->dst_factor_rgb != cache_bs->dst_factor_rgb) ||
  8334. (state_bs->src_factor_alpha != cache_bs->src_factor_alpha) ||
  8335. (state_bs->dst_factor_alpha != cache_bs->dst_factor_alpha))
  8336. {
  8337. cache_bs->src_factor_rgb = state_bs->src_factor_rgb;
  8338. cache_bs->dst_factor_rgb = state_bs->dst_factor_rgb;
  8339. cache_bs->src_factor_alpha = state_bs->src_factor_alpha;
  8340. cache_bs->dst_factor_alpha = state_bs->dst_factor_alpha;
  8341. glBlendFuncSeparate(_sg_gl_blend_factor(state_bs->src_factor_rgb),
  8342. _sg_gl_blend_factor(state_bs->dst_factor_rgb),
  8343. _sg_gl_blend_factor(state_bs->src_factor_alpha),
  8344. _sg_gl_blend_factor(state_bs->dst_factor_alpha));
  8345. _sg_stats_add(gl.num_render_state, 1);
  8346. }
  8347. if ((state_bs->op_rgb != cache_bs->op_rgb) || (state_bs->op_alpha != cache_bs->op_alpha)) {
  8348. cache_bs->op_rgb = state_bs->op_rgb;
  8349. cache_bs->op_alpha = state_bs->op_alpha;
  8350. glBlendEquationSeparate(_sg_gl_blend_op(state_bs->op_rgb), _sg_gl_blend_op(state_bs->op_alpha));
  8351. _sg_stats_add(gl.num_render_state, 1);
  8352. }
  8353. // standalone color target state
  8354. for (GLuint i = 0; i < (GLuint)pip->cmn.color_count; i++) {
  8355. if (pip->gl.color_write_mask[i] != _sg.gl.cache.color_write_mask[i]) {
  8356. const sg_color_mask cm = pip->gl.color_write_mask[i];
  8357. _sg.gl.cache.color_write_mask[i] = cm;
  8358. #ifdef SOKOL_GLCORE
  8359. glColorMaski(i,
  8360. (cm & SG_COLORMASK_R) != 0,
  8361. (cm & SG_COLORMASK_G) != 0,
  8362. (cm & SG_COLORMASK_B) != 0,
  8363. (cm & SG_COLORMASK_A) != 0);
  8364. #else
  8365. if (0 == i) {
  8366. glColorMask((cm & SG_COLORMASK_R) != 0,
  8367. (cm & SG_COLORMASK_G) != 0,
  8368. (cm & SG_COLORMASK_B) != 0,
  8369. (cm & SG_COLORMASK_A) != 0);
  8370. }
  8371. #endif
  8372. _sg_stats_add(gl.num_render_state, 1);
  8373. }
  8374. }
  8375. if (!_sg_fequal(pip->cmn.blend_color.r, _sg.gl.cache.blend_color.r, 0.0001f) ||
  8376. !_sg_fequal(pip->cmn.blend_color.g, _sg.gl.cache.blend_color.g, 0.0001f) ||
  8377. !_sg_fequal(pip->cmn.blend_color.b, _sg.gl.cache.blend_color.b, 0.0001f) ||
  8378. !_sg_fequal(pip->cmn.blend_color.a, _sg.gl.cache.blend_color.a, 0.0001f))
  8379. {
  8380. sg_color c = pip->cmn.blend_color;
  8381. _sg.gl.cache.blend_color = c;
  8382. glBlendColor(c.r, c.g, c.b, c.a);
  8383. _sg_stats_add(gl.num_render_state, 1);
  8384. }
  8385. } // pip->cmn.color_count > 0
  8386. if (pip->gl.cull_mode != _sg.gl.cache.cull_mode) {
  8387. _sg.gl.cache.cull_mode = pip->gl.cull_mode;
  8388. if (SG_CULLMODE_NONE == pip->gl.cull_mode) {
  8389. glDisable(GL_CULL_FACE);
  8390. _sg_stats_add(gl.num_render_state, 1);
  8391. } else {
  8392. glEnable(GL_CULL_FACE);
  8393. GLenum gl_mode = (SG_CULLMODE_FRONT == pip->gl.cull_mode) ? GL_FRONT : GL_BACK;
  8394. glCullFace(gl_mode);
  8395. _sg_stats_add(gl.num_render_state, 2);
  8396. }
  8397. }
  8398. if (pip->gl.face_winding != _sg.gl.cache.face_winding) {
  8399. _sg.gl.cache.face_winding = pip->gl.face_winding;
  8400. GLenum gl_winding = (SG_FACEWINDING_CW == pip->gl.face_winding) ? GL_CW : GL_CCW;
  8401. glFrontFace(gl_winding);
  8402. _sg_stats_add(gl.num_render_state, 1);
  8403. }
  8404. if (pip->gl.alpha_to_coverage_enabled != _sg.gl.cache.alpha_to_coverage_enabled) {
  8405. _sg.gl.cache.alpha_to_coverage_enabled = pip->gl.alpha_to_coverage_enabled;
  8406. if (pip->gl.alpha_to_coverage_enabled) {
  8407. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  8408. } else {
  8409. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  8410. }
  8411. _sg_stats_add(gl.num_render_state, 1);
  8412. }
  8413. #ifdef SOKOL_GLCORE
  8414. if (pip->gl.sample_count != _sg.gl.cache.sample_count) {
  8415. _sg.gl.cache.sample_count = pip->gl.sample_count;
  8416. if (pip->gl.sample_count > 1) {
  8417. glEnable(GL_MULTISAMPLE);
  8418. } else {
  8419. glDisable(GL_MULTISAMPLE);
  8420. }
  8421. _sg_stats_add(gl.num_render_state, 1);
  8422. }
  8423. #endif
  8424. // bind shader program
  8425. if (pip->shader->gl.prog != _sg.gl.cache.prog) {
  8426. _sg.gl.cache.prog = pip->shader->gl.prog;
  8427. glUseProgram(pip->shader->gl.prog);
  8428. _sg_stats_add(gl.num_use_program, 1);
  8429. }
  8430. }
  8431. _SG_GL_CHECK_ERROR();
  8432. }
  8433. _SOKOL_PRIVATE bool _sg_gl_apply_bindings(_sg_bindings_t* bnd) {
  8434. SOKOL_ASSERT(bnd);
  8435. SOKOL_ASSERT(bnd->pip && bnd->pip->shader);
  8436. SOKOL_ASSERT(bnd->pip->shader->slot.id == bnd->pip->cmn.shader_id.id);
  8437. _SG_GL_CHECK_ERROR();
  8438. const _sg_shader_t* shd = bnd->pip->shader;
  8439. // bind combined image-samplers
  8440. _SG_GL_CHECK_ERROR();
  8441. for (size_t img_smp_index = 0; img_smp_index < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_index++) {
  8442. const _sg_shader_image_sampler_t* img_smp = &shd->cmn.image_samplers[img_smp_index];
  8443. if (img_smp->stage == SG_SHADERSTAGE_NONE) {
  8444. continue;
  8445. }
  8446. const int8_t gl_tex_slot = (GLint)shd->gl.tex_slot[img_smp_index];
  8447. if (gl_tex_slot != -1) {
  8448. SOKOL_ASSERT(img_smp->image_slot < SG_MAX_IMAGE_BINDSLOTS);
  8449. SOKOL_ASSERT(img_smp->sampler_slot < SG_MAX_SAMPLER_BINDSLOTS);
  8450. const _sg_image_t* img = bnd->imgs[img_smp->image_slot];
  8451. const _sg_sampler_t* smp = bnd->smps[img_smp->sampler_slot];
  8452. SOKOL_ASSERT(img);
  8453. SOKOL_ASSERT(smp);
  8454. const GLenum gl_tgt = img->gl.target;
  8455. const GLuint gl_tex = img->gl.tex[img->cmn.active_slot];
  8456. const GLuint gl_smp = smp->gl.smp;
  8457. _sg_gl_cache_bind_texture_sampler(gl_tex_slot, gl_tgt, gl_tex, gl_smp);
  8458. }
  8459. }
  8460. _SG_GL_CHECK_ERROR();
  8461. // bind storage buffers
  8462. for (size_t sbuf_index = 0; sbuf_index < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_index++) {
  8463. if (shd->cmn.storage_buffers[sbuf_index].stage == SG_SHADERSTAGE_NONE) {
  8464. continue;
  8465. }
  8466. const _sg_buffer_t* sbuf = bnd->sbufs[sbuf_index];
  8467. const uint8_t binding = shd->gl.sbuf_binding[sbuf_index];
  8468. GLuint gl_sbuf = sbuf->gl.buf[sbuf->cmn.active_slot];
  8469. _sg_gl_cache_bind_storage_buffer(binding, gl_sbuf);
  8470. }
  8471. // index buffer (can be 0)
  8472. const GLuint gl_ib = bnd->ib ? bnd->ib->gl.buf[bnd->ib->cmn.active_slot] : 0;
  8473. _sg_gl_cache_bind_buffer(GL_ELEMENT_ARRAY_BUFFER, gl_ib);
  8474. _sg.gl.cache.cur_ib_offset = bnd->ib_offset;
  8475. // vertex attributes
  8476. for (GLuint attr_index = 0; attr_index < (GLuint)_sg.limits.max_vertex_attrs; attr_index++) {
  8477. _sg_gl_attr_t* attr = &bnd->pip->gl.attrs[attr_index];
  8478. _sg_gl_cache_attr_t* cache_attr = &_sg.gl.cache.attrs[attr_index];
  8479. bool cache_attr_dirty = false;
  8480. int vb_offset = 0;
  8481. GLuint gl_vb = 0;
  8482. if (attr->vb_index >= 0) {
  8483. // attribute is enabled
  8484. SOKOL_ASSERT(attr->vb_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  8485. _sg_buffer_t* vb = bnd->vbs[attr->vb_index];
  8486. SOKOL_ASSERT(vb);
  8487. gl_vb = vb->gl.buf[vb->cmn.active_slot];
  8488. vb_offset = bnd->vb_offsets[attr->vb_index] + attr->offset;
  8489. if ((gl_vb != cache_attr->gl_vbuf) ||
  8490. (attr->size != cache_attr->gl_attr.size) ||
  8491. (attr->type != cache_attr->gl_attr.type) ||
  8492. (attr->normalized != cache_attr->gl_attr.normalized) ||
  8493. (attr->stride != cache_attr->gl_attr.stride) ||
  8494. (vb_offset != cache_attr->gl_attr.offset) ||
  8495. (cache_attr->gl_attr.divisor != attr->divisor))
  8496. {
  8497. _sg_gl_cache_bind_buffer(GL_ARRAY_BUFFER, gl_vb);
  8498. glVertexAttribPointer(attr_index, attr->size, attr->type, attr->normalized, attr->stride, (const GLvoid*)(GLintptr)vb_offset);
  8499. _sg_stats_add(gl.num_vertex_attrib_pointer, 1);
  8500. glVertexAttribDivisor(attr_index, (GLuint)attr->divisor);
  8501. _sg_stats_add(gl.num_vertex_attrib_divisor, 1);
  8502. cache_attr_dirty = true;
  8503. }
  8504. if (cache_attr->gl_attr.vb_index == -1) {
  8505. glEnableVertexAttribArray(attr_index);
  8506. _sg_stats_add(gl.num_enable_vertex_attrib_array, 1);
  8507. cache_attr_dirty = true;
  8508. }
  8509. } else {
  8510. // attribute is disabled
  8511. if (cache_attr->gl_attr.vb_index != -1) {
  8512. glDisableVertexAttribArray(attr_index);
  8513. _sg_stats_add(gl.num_disable_vertex_attrib_array, 1);
  8514. cache_attr_dirty = true;
  8515. }
  8516. }
  8517. if (cache_attr_dirty) {
  8518. cache_attr->gl_attr = *attr;
  8519. cache_attr->gl_attr.offset = vb_offset;
  8520. cache_attr->gl_vbuf = gl_vb;
  8521. }
  8522. }
  8523. _SG_GL_CHECK_ERROR();
  8524. return true;
  8525. }
  8526. _SOKOL_PRIVATE void _sg_gl_apply_uniforms(int ub_slot, const sg_range* data) {
  8527. SOKOL_ASSERT(_sg.gl.cache.cur_pipeline);
  8528. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  8529. const _sg_pipeline_t* pip = _sg.gl.cache.cur_pipeline;
  8530. SOKOL_ASSERT(pip && pip->shader);
  8531. SOKOL_ASSERT(pip->slot.id == _sg.gl.cache.cur_pipeline_id.id);
  8532. const _sg_shader_t* shd = pip->shader;
  8533. SOKOL_ASSERT(shd->slot.id == pip->cmn.shader_id.id);
  8534. SOKOL_ASSERT(SG_SHADERSTAGE_NONE != shd->cmn.uniform_blocks[ub_slot].stage);
  8535. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  8536. const _sg_gl_uniform_block_t* gl_ub = &shd->gl.uniform_blocks[ub_slot];
  8537. for (int u_index = 0; u_index < gl_ub->num_uniforms; u_index++) {
  8538. const _sg_gl_uniform_t* u = &gl_ub->uniforms[u_index];
  8539. SOKOL_ASSERT(u->type != SG_UNIFORMTYPE_INVALID);
  8540. if (u->gl_loc == -1) {
  8541. continue;
  8542. }
  8543. _sg_stats_add(gl.num_uniform, 1);
  8544. GLfloat* fptr = (GLfloat*) (((uint8_t*)data->ptr) + u->offset);
  8545. GLint* iptr = (GLint*) (((uint8_t*)data->ptr) + u->offset);
  8546. switch (u->type) {
  8547. case SG_UNIFORMTYPE_INVALID:
  8548. break;
  8549. case SG_UNIFORMTYPE_FLOAT:
  8550. glUniform1fv(u->gl_loc, u->count, fptr);
  8551. break;
  8552. case SG_UNIFORMTYPE_FLOAT2:
  8553. glUniform2fv(u->gl_loc, u->count, fptr);
  8554. break;
  8555. case SG_UNIFORMTYPE_FLOAT3:
  8556. glUniform3fv(u->gl_loc, u->count, fptr);
  8557. break;
  8558. case SG_UNIFORMTYPE_FLOAT4:
  8559. glUniform4fv(u->gl_loc, u->count, fptr);
  8560. break;
  8561. case SG_UNIFORMTYPE_INT:
  8562. glUniform1iv(u->gl_loc, u->count, iptr);
  8563. break;
  8564. case SG_UNIFORMTYPE_INT2:
  8565. glUniform2iv(u->gl_loc, u->count, iptr);
  8566. break;
  8567. case SG_UNIFORMTYPE_INT3:
  8568. glUniform3iv(u->gl_loc, u->count, iptr);
  8569. break;
  8570. case SG_UNIFORMTYPE_INT4:
  8571. glUniform4iv(u->gl_loc, u->count, iptr);
  8572. break;
  8573. case SG_UNIFORMTYPE_MAT4:
  8574. glUniformMatrix4fv(u->gl_loc, u->count, GL_FALSE, fptr);
  8575. break;
  8576. default:
  8577. SOKOL_UNREACHABLE;
  8578. break;
  8579. }
  8580. }
  8581. }
  8582. _SOKOL_PRIVATE void _sg_gl_draw(int base_element, int num_elements, int num_instances) {
  8583. SOKOL_ASSERT(_sg.gl.cache.cur_pipeline);
  8584. const GLenum i_type = _sg.gl.cache.cur_index_type;
  8585. const GLenum p_type = _sg.gl.cache.cur_primitive_type;
  8586. const bool use_instanced_draw = (num_instances > 1) || (_sg.gl.cache.cur_pipeline->cmn.use_instanced_draw);
  8587. if (0 != i_type) {
  8588. // indexed rendering
  8589. const int i_size = (i_type == GL_UNSIGNED_SHORT) ? 2 : 4;
  8590. const int ib_offset = _sg.gl.cache.cur_ib_offset;
  8591. const GLvoid* indices = (const GLvoid*)(GLintptr)(base_element*i_size+ib_offset);
  8592. if (use_instanced_draw) {
  8593. glDrawElementsInstanced(p_type, num_elements, i_type, indices, num_instances);
  8594. } else {
  8595. glDrawElements(p_type, num_elements, i_type, indices);
  8596. }
  8597. } else {
  8598. // non-indexed rendering
  8599. if (use_instanced_draw) {
  8600. glDrawArraysInstanced(p_type, base_element, num_elements, num_instances);
  8601. } else {
  8602. glDrawArrays(p_type, base_element, num_elements);
  8603. }
  8604. }
  8605. }
  8606. _SOKOL_PRIVATE void _sg_gl_commit(void) {
  8607. // "soft" clear bindings (only those that are actually bound)
  8608. _sg_gl_cache_clear_buffer_bindings(false);
  8609. _sg_gl_cache_clear_texture_sampler_bindings(false);
  8610. }
  8611. _SOKOL_PRIVATE void _sg_gl_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  8612. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  8613. // only one update per buffer per frame allowed
  8614. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  8615. buf->cmn.active_slot = 0;
  8616. }
  8617. GLenum gl_tgt = _sg_gl_buffer_target(buf->cmn.type);
  8618. SOKOL_ASSERT(buf->cmn.active_slot < SG_NUM_INFLIGHT_FRAMES);
  8619. GLuint gl_buf = buf->gl.buf[buf->cmn.active_slot];
  8620. SOKOL_ASSERT(gl_buf);
  8621. _SG_GL_CHECK_ERROR();
  8622. _sg_gl_cache_store_buffer_binding(gl_tgt);
  8623. _sg_gl_cache_bind_buffer(gl_tgt, gl_buf);
  8624. glBufferSubData(gl_tgt, 0, (GLsizeiptr)data->size, data->ptr);
  8625. _sg_gl_cache_restore_buffer_binding(gl_tgt);
  8626. _SG_GL_CHECK_ERROR();
  8627. }
  8628. _SOKOL_PRIVATE void _sg_gl_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  8629. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  8630. if (new_frame) {
  8631. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  8632. buf->cmn.active_slot = 0;
  8633. }
  8634. }
  8635. GLenum gl_tgt = _sg_gl_buffer_target(buf->cmn.type);
  8636. SOKOL_ASSERT(buf->cmn.active_slot < SG_NUM_INFLIGHT_FRAMES);
  8637. GLuint gl_buf = buf->gl.buf[buf->cmn.active_slot];
  8638. SOKOL_ASSERT(gl_buf);
  8639. _SG_GL_CHECK_ERROR();
  8640. _sg_gl_cache_store_buffer_binding(gl_tgt);
  8641. _sg_gl_cache_bind_buffer(gl_tgt, gl_buf);
  8642. glBufferSubData(gl_tgt, buf->cmn.append_pos, (GLsizeiptr)data->size, data->ptr);
  8643. _sg_gl_cache_restore_buffer_binding(gl_tgt);
  8644. _SG_GL_CHECK_ERROR();
  8645. }
  8646. _SOKOL_PRIVATE void _sg_gl_update_image(_sg_image_t* img, const sg_image_data* data) {
  8647. SOKOL_ASSERT(img && data);
  8648. // only one update per image per frame allowed
  8649. if (++img->cmn.active_slot >= img->cmn.num_slots) {
  8650. img->cmn.active_slot = 0;
  8651. }
  8652. SOKOL_ASSERT(img->cmn.active_slot < SG_NUM_INFLIGHT_FRAMES);
  8653. SOKOL_ASSERT(0 != img->gl.tex[img->cmn.active_slot]);
  8654. _sg_gl_cache_store_texture_sampler_binding(0);
  8655. _sg_gl_cache_bind_texture_sampler(0, img->gl.target, img->gl.tex[img->cmn.active_slot], 0);
  8656. const GLenum gl_img_format = _sg_gl_teximage_format(img->cmn.pixel_format);
  8657. const GLenum gl_img_type = _sg_gl_teximage_type(img->cmn.pixel_format);
  8658. const int num_faces = img->cmn.type == SG_IMAGETYPE_CUBE ? 6 : 1;
  8659. const int num_mips = img->cmn.num_mipmaps;
  8660. for (int face_index = 0; face_index < num_faces; face_index++) {
  8661. for (int mip_index = 0; mip_index < num_mips; mip_index++) {
  8662. GLenum gl_img_target = img->gl.target;
  8663. if (SG_IMAGETYPE_CUBE == img->cmn.type) {
  8664. gl_img_target = _sg_gl_cubeface_target(face_index);
  8665. }
  8666. const GLvoid* data_ptr = data->subimage[face_index][mip_index].ptr;
  8667. int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  8668. int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  8669. if ((SG_IMAGETYPE_2D == img->cmn.type) || (SG_IMAGETYPE_CUBE == img->cmn.type)) {
  8670. glTexSubImage2D(gl_img_target, mip_index,
  8671. 0, 0,
  8672. mip_width, mip_height,
  8673. gl_img_format, gl_img_type,
  8674. data_ptr);
  8675. } else if ((SG_IMAGETYPE_3D == img->cmn.type) || (SG_IMAGETYPE_ARRAY == img->cmn.type)) {
  8676. int mip_depth = img->cmn.num_slices;
  8677. if (SG_IMAGETYPE_3D == img->cmn.type) {
  8678. mip_depth = _sg_miplevel_dim(img->cmn.num_slices, mip_index);
  8679. }
  8680. glTexSubImage3D(gl_img_target, mip_index,
  8681. 0, 0, 0,
  8682. mip_width, mip_height, mip_depth,
  8683. gl_img_format, gl_img_type,
  8684. data_ptr);
  8685. }
  8686. }
  8687. }
  8688. _sg_gl_cache_restore_texture_sampler_binding(0);
  8689. }
  8690. // ██████ ██████ ██████ ██ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  8691. // ██ ██ ██ ██ ██ ███ ███ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  8692. // ██ ██ █████ ██ ██ ██ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  8693. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  8694. // ██████ ██████ ██████ ██ ██ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  8695. //
  8696. // >>d3d11 backend
  8697. #elif defined(SOKOL_D3D11)
  8698. #if defined(__cplusplus)
  8699. #define _sg_d3d11_AddRef(self) (self)->AddRef()
  8700. #else
  8701. #define _sg_d3d11_AddRef(self) (self)->lpVtbl->AddRef(self)
  8702. #endif
  8703. #if defined(__cplusplus)
  8704. #define _sg_d3d11_Release(self) (self)->Release()
  8705. #else
  8706. #define _sg_d3d11_Release(self) (self)->lpVtbl->Release(self)
  8707. #endif
  8708. // NOTE: This needs to be a macro since we can't use the polymorphism in C. It's called on many kinds of resources.
  8709. // NOTE: Based on microsoft docs, it's fine to call this with pData=NULL if DataSize is also zero.
  8710. #if defined(__cplusplus)
  8711. #define _sg_d3d11_SetPrivateData(self, guid, DataSize, pData) (self)->SetPrivateData(guid, DataSize, pData)
  8712. #else
  8713. #define _sg_d3d11_SetPrivateData(self, guid, DataSize, pData) (self)->lpVtbl->SetPrivateData(self, guid, DataSize, pData)
  8714. #endif
  8715. #if defined(__cplusplus)
  8716. #define _sg_win32_refguid(guid) guid
  8717. #else
  8718. #define _sg_win32_refguid(guid) &guid
  8719. #endif
  8720. static const GUID _sg_d3d11_WKPDID_D3DDebugObjectName = { 0x429b8c22,0x9188,0x4b0c, {0x87,0x42,0xac,0xb0,0xbf,0x85,0xc2,0x00} };
  8721. #if defined(SOKOL_DEBUG)
  8722. #define _sg_d3d11_setlabel(self, label) _sg_d3d11_SetPrivateData(self, _sg_win32_refguid(_sg_d3d11_WKPDID_D3DDebugObjectName), label ? (UINT)strlen(label) : 0, label)
  8723. #else
  8724. #define _sg_d3d11_setlabel(self, label)
  8725. #endif
  8726. //-- D3D11 C/C++ wrappers ------------------------------------------------------
  8727. static inline HRESULT _sg_d3d11_CheckFormatSupport(ID3D11Device* self, DXGI_FORMAT Format, UINT* pFormatSupport) {
  8728. #if defined(__cplusplus)
  8729. return self->CheckFormatSupport(Format, pFormatSupport);
  8730. #else
  8731. return self->lpVtbl->CheckFormatSupport(self, Format, pFormatSupport);
  8732. #endif
  8733. }
  8734. static inline void _sg_d3d11_OMSetRenderTargets(ID3D11DeviceContext* self, UINT NumViews, ID3D11RenderTargetView* const* ppRenderTargetViews, ID3D11DepthStencilView *pDepthStencilView) {
  8735. #if defined(__cplusplus)
  8736. self->OMSetRenderTargets(NumViews, ppRenderTargetViews, pDepthStencilView);
  8737. #else
  8738. self->lpVtbl->OMSetRenderTargets(self, NumViews, ppRenderTargetViews, pDepthStencilView);
  8739. #endif
  8740. }
  8741. static inline void _sg_d3d11_RSSetState(ID3D11DeviceContext* self, ID3D11RasterizerState* pRasterizerState) {
  8742. #if defined(__cplusplus)
  8743. self->RSSetState(pRasterizerState);
  8744. #else
  8745. self->lpVtbl->RSSetState(self, pRasterizerState);
  8746. #endif
  8747. }
  8748. static inline void _sg_d3d11_OMSetDepthStencilState(ID3D11DeviceContext* self, ID3D11DepthStencilState* pDepthStencilState, UINT StencilRef) {
  8749. #if defined(__cplusplus)
  8750. self->OMSetDepthStencilState(pDepthStencilState, StencilRef);
  8751. #else
  8752. self->lpVtbl->OMSetDepthStencilState(self, pDepthStencilState, StencilRef);
  8753. #endif
  8754. }
  8755. static inline void _sg_d3d11_OMSetBlendState(ID3D11DeviceContext* self, ID3D11BlendState* pBlendState, const FLOAT BlendFactor[4], UINT SampleMask) {
  8756. #if defined(__cplusplus)
  8757. self->OMSetBlendState(pBlendState, BlendFactor, SampleMask);
  8758. #else
  8759. self->lpVtbl->OMSetBlendState(self, pBlendState, BlendFactor, SampleMask);
  8760. #endif
  8761. }
  8762. static inline void _sg_d3d11_IASetVertexBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppVertexBuffers, const UINT* pStrides, const UINT* pOffsets) {
  8763. #if defined(__cplusplus)
  8764. self->IASetVertexBuffers(StartSlot, NumBuffers, ppVertexBuffers, pStrides, pOffsets);
  8765. #else
  8766. self->lpVtbl->IASetVertexBuffers(self, StartSlot, NumBuffers, ppVertexBuffers, pStrides, pOffsets);
  8767. #endif
  8768. }
  8769. static inline void _sg_d3d11_IASetIndexBuffer(ID3D11DeviceContext* self, ID3D11Buffer* pIndexBuffer, DXGI_FORMAT Format, UINT Offset) {
  8770. #if defined(__cplusplus)
  8771. self->IASetIndexBuffer(pIndexBuffer, Format, Offset);
  8772. #else
  8773. self->lpVtbl->IASetIndexBuffer(self, pIndexBuffer, Format, Offset);
  8774. #endif
  8775. }
  8776. static inline void _sg_d3d11_IASetInputLayout(ID3D11DeviceContext* self, ID3D11InputLayout* pInputLayout) {
  8777. #if defined(__cplusplus)
  8778. self->IASetInputLayout(pInputLayout);
  8779. #else
  8780. self->lpVtbl->IASetInputLayout(self, pInputLayout);
  8781. #endif
  8782. }
  8783. static inline void _sg_d3d11_VSSetShader(ID3D11DeviceContext* self, ID3D11VertexShader* pVertexShader, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) {
  8784. #if defined(__cplusplus)
  8785. self->VSSetShader(pVertexShader, ppClassInstances, NumClassInstances);
  8786. #else
  8787. self->lpVtbl->VSSetShader(self, pVertexShader, ppClassInstances, NumClassInstances);
  8788. #endif
  8789. }
  8790. static inline void _sg_d3d11_PSSetShader(ID3D11DeviceContext* self, ID3D11PixelShader* pPixelShader, ID3D11ClassInstance* const* ppClassInstances, UINT NumClassInstances) {
  8791. #if defined(__cplusplus)
  8792. self->PSSetShader(pPixelShader, ppClassInstances, NumClassInstances);
  8793. #else
  8794. self->lpVtbl->PSSetShader(self, pPixelShader, ppClassInstances, NumClassInstances);
  8795. #endif
  8796. }
  8797. static inline void _sg_d3d11_VSSetConstantBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers) {
  8798. #if defined(__cplusplus)
  8799. self->VSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers);
  8800. #else
  8801. self->lpVtbl->VSSetConstantBuffers(self, StartSlot, NumBuffers, ppConstantBuffers);
  8802. #endif
  8803. }
  8804. static inline void _sg_d3d11_PSSetConstantBuffers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumBuffers, ID3D11Buffer* const* ppConstantBuffers) {
  8805. #if defined(__cplusplus)
  8806. self->PSSetConstantBuffers(StartSlot, NumBuffers, ppConstantBuffers);
  8807. #else
  8808. self->lpVtbl->PSSetConstantBuffers(self, StartSlot, NumBuffers, ppConstantBuffers);
  8809. #endif
  8810. }
  8811. static inline void _sg_d3d11_VSSetShaderResources(ID3D11DeviceContext* self, UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView* const* ppShaderResourceViews) {
  8812. #if defined(__cplusplus)
  8813. self->VSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews);
  8814. #else
  8815. self->lpVtbl->VSSetShaderResources(self, StartSlot, NumViews, ppShaderResourceViews);
  8816. #endif
  8817. }
  8818. static inline void _sg_d3d11_PSSetShaderResources(ID3D11DeviceContext* self, UINT StartSlot, UINT NumViews, ID3D11ShaderResourceView* const* ppShaderResourceViews) {
  8819. #if defined(__cplusplus)
  8820. self->PSSetShaderResources(StartSlot, NumViews, ppShaderResourceViews);
  8821. #else
  8822. self->lpVtbl->PSSetShaderResources(self, StartSlot, NumViews, ppShaderResourceViews);
  8823. #endif
  8824. }
  8825. static inline void _sg_d3d11_VSSetSamplers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumSamplers, ID3D11SamplerState* const* ppSamplers) {
  8826. #if defined(__cplusplus)
  8827. self->VSSetSamplers(StartSlot, NumSamplers, ppSamplers);
  8828. #else
  8829. self->lpVtbl->VSSetSamplers(self, StartSlot, NumSamplers, ppSamplers);
  8830. #endif
  8831. }
  8832. static inline void _sg_d3d11_PSSetSamplers(ID3D11DeviceContext* self, UINT StartSlot, UINT NumSamplers, ID3D11SamplerState* const* ppSamplers) {
  8833. #if defined(__cplusplus)
  8834. self->PSSetSamplers(StartSlot, NumSamplers, ppSamplers);
  8835. #else
  8836. self->lpVtbl->PSSetSamplers(self, StartSlot, NumSamplers, ppSamplers);
  8837. #endif
  8838. }
  8839. static inline HRESULT _sg_d3d11_CreateBuffer(ID3D11Device* self, const D3D11_BUFFER_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Buffer** ppBuffer) {
  8840. #if defined(__cplusplus)
  8841. return self->CreateBuffer(pDesc, pInitialData, ppBuffer);
  8842. #else
  8843. return self->lpVtbl->CreateBuffer(self, pDesc, pInitialData, ppBuffer);
  8844. #endif
  8845. }
  8846. static inline HRESULT _sg_d3d11_CreateTexture2D(ID3D11Device* self, const D3D11_TEXTURE2D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture2D** ppTexture2D) {
  8847. #if defined(__cplusplus)
  8848. return self->CreateTexture2D(pDesc, pInitialData, ppTexture2D);
  8849. #else
  8850. return self->lpVtbl->CreateTexture2D(self, pDesc, pInitialData, ppTexture2D);
  8851. #endif
  8852. }
  8853. static inline HRESULT _sg_d3d11_CreateShaderResourceView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_SHADER_RESOURCE_VIEW_DESC* pDesc, ID3D11ShaderResourceView** ppSRView) {
  8854. #if defined(__cplusplus)
  8855. return self->CreateShaderResourceView(pResource, pDesc, ppSRView);
  8856. #else
  8857. return self->lpVtbl->CreateShaderResourceView(self, pResource, pDesc, ppSRView);
  8858. #endif
  8859. }
  8860. static inline void _sg_d3d11_GetResource(ID3D11View* self, ID3D11Resource** ppResource) {
  8861. #if defined(__cplusplus)
  8862. self->GetResource(ppResource);
  8863. #else
  8864. self->lpVtbl->GetResource(self, ppResource);
  8865. #endif
  8866. }
  8867. static inline HRESULT _sg_d3d11_CreateTexture3D(ID3D11Device* self, const D3D11_TEXTURE3D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture3D** ppTexture3D) {
  8868. #if defined(__cplusplus)
  8869. return self->CreateTexture3D(pDesc, pInitialData, ppTexture3D);
  8870. #else
  8871. return self->lpVtbl->CreateTexture3D(self, pDesc, pInitialData, ppTexture3D);
  8872. #endif
  8873. }
  8874. static inline HRESULT _sg_d3d11_CreateSamplerState(ID3D11Device* self, const D3D11_SAMPLER_DESC* pSamplerDesc, ID3D11SamplerState** ppSamplerState) {
  8875. #if defined(__cplusplus)
  8876. return self->CreateSamplerState(pSamplerDesc, ppSamplerState);
  8877. #else
  8878. return self->lpVtbl->CreateSamplerState(self, pSamplerDesc, ppSamplerState);
  8879. #endif
  8880. }
  8881. static inline LPVOID _sg_d3d11_GetBufferPointer(ID3D10Blob* self) {
  8882. #if defined(__cplusplus)
  8883. return self->GetBufferPointer();
  8884. #else
  8885. return self->lpVtbl->GetBufferPointer(self);
  8886. #endif
  8887. }
  8888. static inline SIZE_T _sg_d3d11_GetBufferSize(ID3D10Blob* self) {
  8889. #if defined(__cplusplus)
  8890. return self->GetBufferSize();
  8891. #else
  8892. return self->lpVtbl->GetBufferSize(self);
  8893. #endif
  8894. }
  8895. static inline HRESULT _sg_d3d11_CreateVertexShader(ID3D11Device* self, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11VertexShader** ppVertexShader) {
  8896. #if defined(__cplusplus)
  8897. return self->CreateVertexShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppVertexShader);
  8898. #else
  8899. return self->lpVtbl->CreateVertexShader(self, pShaderBytecode, BytecodeLength, pClassLinkage, ppVertexShader);
  8900. #endif
  8901. }
  8902. static inline HRESULT _sg_d3d11_CreatePixelShader(ID3D11Device* self, const void* pShaderBytecode, SIZE_T BytecodeLength, ID3D11ClassLinkage* pClassLinkage, ID3D11PixelShader** ppPixelShader) {
  8903. #if defined(__cplusplus)
  8904. return self->CreatePixelShader(pShaderBytecode, BytecodeLength, pClassLinkage, ppPixelShader);
  8905. #else
  8906. return self->lpVtbl->CreatePixelShader(self, pShaderBytecode, BytecodeLength, pClassLinkage, ppPixelShader);
  8907. #endif
  8908. }
  8909. static inline HRESULT _sg_d3d11_CreateInputLayout(ID3D11Device* self, const D3D11_INPUT_ELEMENT_DESC* pInputElementDescs, UINT NumElements, const void* pShaderBytecodeWithInputSignature, SIZE_T BytecodeLength, ID3D11InputLayout **ppInputLayout) {
  8910. #if defined(__cplusplus)
  8911. return self->CreateInputLayout(pInputElementDescs, NumElements, pShaderBytecodeWithInputSignature, BytecodeLength, ppInputLayout);
  8912. #else
  8913. return self->lpVtbl->CreateInputLayout(self, pInputElementDescs, NumElements, pShaderBytecodeWithInputSignature, BytecodeLength, ppInputLayout);
  8914. #endif
  8915. }
  8916. static inline HRESULT _sg_d3d11_CreateRasterizerState(ID3D11Device* self, const D3D11_RASTERIZER_DESC* pRasterizerDesc, ID3D11RasterizerState** ppRasterizerState) {
  8917. #if defined(__cplusplus)
  8918. return self->CreateRasterizerState(pRasterizerDesc, ppRasterizerState);
  8919. #else
  8920. return self->lpVtbl->CreateRasterizerState(self, pRasterizerDesc, ppRasterizerState);
  8921. #endif
  8922. }
  8923. static inline HRESULT _sg_d3d11_CreateDepthStencilState(ID3D11Device* self, const D3D11_DEPTH_STENCIL_DESC* pDepthStencilDesc, ID3D11DepthStencilState** ppDepthStencilState) {
  8924. #if defined(__cplusplus)
  8925. return self->CreateDepthStencilState(pDepthStencilDesc, ppDepthStencilState);
  8926. #else
  8927. return self->lpVtbl->CreateDepthStencilState(self, pDepthStencilDesc, ppDepthStencilState);
  8928. #endif
  8929. }
  8930. static inline HRESULT _sg_d3d11_CreateBlendState(ID3D11Device* self, const D3D11_BLEND_DESC* pBlendStateDesc, ID3D11BlendState** ppBlendState) {
  8931. #if defined(__cplusplus)
  8932. return self->CreateBlendState(pBlendStateDesc, ppBlendState);
  8933. #else
  8934. return self->lpVtbl->CreateBlendState(self, pBlendStateDesc, ppBlendState);
  8935. #endif
  8936. }
  8937. static inline HRESULT _sg_d3d11_CreateRenderTargetView(ID3D11Device* self, ID3D11Resource *pResource, const D3D11_RENDER_TARGET_VIEW_DESC* pDesc, ID3D11RenderTargetView** ppRTView) {
  8938. #if defined(__cplusplus)
  8939. return self->CreateRenderTargetView(pResource, pDesc, ppRTView);
  8940. #else
  8941. return self->lpVtbl->CreateRenderTargetView(self, pResource, pDesc, ppRTView);
  8942. #endif
  8943. }
  8944. static inline HRESULT _sg_d3d11_CreateDepthStencilView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_DEPTH_STENCIL_VIEW_DESC* pDesc, ID3D11DepthStencilView** ppDepthStencilView) {
  8945. #if defined(__cplusplus)
  8946. return self->CreateDepthStencilView(pResource, pDesc, ppDepthStencilView);
  8947. #else
  8948. return self->lpVtbl->CreateDepthStencilView(self, pResource, pDesc, ppDepthStencilView);
  8949. #endif
  8950. }
  8951. static inline void _sg_d3d11_RSSetViewports(ID3D11DeviceContext* self, UINT NumViewports, const D3D11_VIEWPORT* pViewports) {
  8952. #if defined(__cplusplus)
  8953. self->RSSetViewports(NumViewports, pViewports);
  8954. #else
  8955. self->lpVtbl->RSSetViewports(self, NumViewports, pViewports);
  8956. #endif
  8957. }
  8958. static inline void _sg_d3d11_RSSetScissorRects(ID3D11DeviceContext* self, UINT NumRects, const D3D11_RECT* pRects) {
  8959. #if defined(__cplusplus)
  8960. self->RSSetScissorRects(NumRects, pRects);
  8961. #else
  8962. self->lpVtbl->RSSetScissorRects(self, NumRects, pRects);
  8963. #endif
  8964. }
  8965. static inline void _sg_d3d11_ClearRenderTargetView(ID3D11DeviceContext* self, ID3D11RenderTargetView* pRenderTargetView, const FLOAT ColorRGBA[4]) {
  8966. #if defined(__cplusplus)
  8967. self->ClearRenderTargetView(pRenderTargetView, ColorRGBA);
  8968. #else
  8969. self->lpVtbl->ClearRenderTargetView(self, pRenderTargetView, ColorRGBA);
  8970. #endif
  8971. }
  8972. static inline void _sg_d3d11_ClearDepthStencilView(ID3D11DeviceContext* self, ID3D11DepthStencilView* pDepthStencilView, UINT ClearFlags, FLOAT Depth, UINT8 Stencil) {
  8973. #if defined(__cplusplus)
  8974. self->ClearDepthStencilView(pDepthStencilView, ClearFlags, Depth, Stencil);
  8975. #else
  8976. self->lpVtbl->ClearDepthStencilView(self, pDepthStencilView, ClearFlags, Depth, Stencil);
  8977. #endif
  8978. }
  8979. static inline void _sg_d3d11_ResolveSubresource(ID3D11DeviceContext* self, ID3D11Resource* pDstResource, UINT DstSubresource, ID3D11Resource* pSrcResource, UINT SrcSubresource, DXGI_FORMAT Format) {
  8980. #if defined(__cplusplus)
  8981. self->ResolveSubresource(pDstResource, DstSubresource, pSrcResource, SrcSubresource, Format);
  8982. #else
  8983. self->lpVtbl->ResolveSubresource(self, pDstResource, DstSubresource, pSrcResource, SrcSubresource, Format);
  8984. #endif
  8985. }
  8986. static inline void _sg_d3d11_IASetPrimitiveTopology(ID3D11DeviceContext* self, D3D11_PRIMITIVE_TOPOLOGY Topology) {
  8987. #if defined(__cplusplus)
  8988. self->IASetPrimitiveTopology(Topology);
  8989. #else
  8990. self->lpVtbl->IASetPrimitiveTopology(self, Topology);
  8991. #endif
  8992. }
  8993. static inline void _sg_d3d11_UpdateSubresource(ID3D11DeviceContext* self, ID3D11Resource* pDstResource, UINT DstSubresource, const D3D11_BOX* pDstBox, const void* pSrcData, UINT SrcRowPitch, UINT SrcDepthPitch) {
  8994. #if defined(__cplusplus)
  8995. self->UpdateSubresource(pDstResource, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch);
  8996. #else
  8997. self->lpVtbl->UpdateSubresource(self, pDstResource, DstSubresource, pDstBox, pSrcData, SrcRowPitch, SrcDepthPitch);
  8998. #endif
  8999. }
  9000. static inline void _sg_d3d11_DrawIndexed(ID3D11DeviceContext* self, UINT IndexCount, UINT StartIndexLocation, INT BaseVertexLocation) {
  9001. #if defined(__cplusplus)
  9002. self->DrawIndexed(IndexCount, StartIndexLocation, BaseVertexLocation);
  9003. #else
  9004. self->lpVtbl->DrawIndexed(self, IndexCount, StartIndexLocation, BaseVertexLocation);
  9005. #endif
  9006. }
  9007. static inline void _sg_d3d11_DrawIndexedInstanced(ID3D11DeviceContext* self, UINT IndexCountPerInstance, UINT InstanceCount, UINT StartIndexLocation, INT BaseVertexLocation, UINT StartInstanceLocation) {
  9008. #if defined(__cplusplus)
  9009. self->DrawIndexedInstanced(IndexCountPerInstance, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation);
  9010. #else
  9011. self->lpVtbl->DrawIndexedInstanced(self, IndexCountPerInstance, InstanceCount, StartIndexLocation, BaseVertexLocation, StartInstanceLocation);
  9012. #endif
  9013. }
  9014. static inline void _sg_d3d11_Draw(ID3D11DeviceContext* self, UINT VertexCount, UINT StartVertexLocation) {
  9015. #if defined(__cplusplus)
  9016. self->Draw(VertexCount, StartVertexLocation);
  9017. #else
  9018. self->lpVtbl->Draw(self, VertexCount, StartVertexLocation);
  9019. #endif
  9020. }
  9021. static inline void _sg_d3d11_DrawInstanced(ID3D11DeviceContext* self, UINT VertexCountPerInstance, UINT InstanceCount, UINT StartVertexLocation, UINT StartInstanceLocation) {
  9022. #if defined(__cplusplus)
  9023. self->DrawInstanced(VertexCountPerInstance, InstanceCount, StartVertexLocation, StartInstanceLocation);
  9024. #else
  9025. self->lpVtbl->DrawInstanced(self, VertexCountPerInstance, InstanceCount, StartVertexLocation, StartInstanceLocation);
  9026. #endif
  9027. }
  9028. static inline HRESULT _sg_d3d11_Map(ID3D11DeviceContext* self, ID3D11Resource* pResource, UINT Subresource, D3D11_MAP MapType, UINT MapFlags, D3D11_MAPPED_SUBRESOURCE* pMappedResource) {
  9029. #if defined(__cplusplus)
  9030. return self->Map(pResource, Subresource, MapType, MapFlags, pMappedResource);
  9031. #else
  9032. return self->lpVtbl->Map(self, pResource, Subresource, MapType, MapFlags, pMappedResource);
  9033. #endif
  9034. }
  9035. static inline void _sg_d3d11_Unmap(ID3D11DeviceContext* self, ID3D11Resource* pResource, UINT Subresource) {
  9036. #if defined(__cplusplus)
  9037. self->Unmap(pResource, Subresource);
  9038. #else
  9039. self->lpVtbl->Unmap(self, pResource, Subresource);
  9040. #endif
  9041. }
  9042. static inline void _sg_d3d11_ClearState(ID3D11DeviceContext* self) {
  9043. #if defined(__cplusplus)
  9044. self->ClearState();
  9045. #else
  9046. self->lpVtbl->ClearState(self);
  9047. #endif
  9048. }
  9049. //-- enum translation functions ------------------------------------------------
  9050. _SOKOL_PRIVATE D3D11_USAGE _sg_d3d11_usage(sg_usage usg) {
  9051. switch (usg) {
  9052. case SG_USAGE_IMMUTABLE:
  9053. return D3D11_USAGE_IMMUTABLE;
  9054. case SG_USAGE_DYNAMIC:
  9055. case SG_USAGE_STREAM:
  9056. return D3D11_USAGE_DYNAMIC;
  9057. default:
  9058. SOKOL_UNREACHABLE;
  9059. return (D3D11_USAGE) 0;
  9060. }
  9061. }
  9062. _SOKOL_PRIVATE UINT _sg_d3d11_buffer_bind_flags(sg_buffer_type t) {
  9063. switch (t) {
  9064. case SG_BUFFERTYPE_VERTEXBUFFER:
  9065. return D3D11_BIND_VERTEX_BUFFER;
  9066. case SG_BUFFERTYPE_INDEXBUFFER:
  9067. return D3D11_BIND_INDEX_BUFFER;
  9068. case SG_BUFFERTYPE_STORAGEBUFFER:
  9069. // FIXME: for compute shaders we'd want UNORDERED_ACCESS?
  9070. return D3D11_BIND_SHADER_RESOURCE;
  9071. default:
  9072. SOKOL_UNREACHABLE;
  9073. return 0;
  9074. }
  9075. }
  9076. _SOKOL_PRIVATE UINT _sg_d3d11_buffer_misc_flags(sg_buffer_type t) {
  9077. switch (t) {
  9078. case SG_BUFFERTYPE_VERTEXBUFFER:
  9079. case SG_BUFFERTYPE_INDEXBUFFER:
  9080. return 0;
  9081. case SG_BUFFERTYPE_STORAGEBUFFER:
  9082. return D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS;
  9083. default:
  9084. SOKOL_UNREACHABLE;
  9085. return 0;
  9086. }
  9087. }
  9088. _SOKOL_PRIVATE UINT _sg_d3d11_cpu_access_flags(sg_usage usg) {
  9089. switch (usg) {
  9090. case SG_USAGE_IMMUTABLE:
  9091. return 0;
  9092. case SG_USAGE_DYNAMIC:
  9093. case SG_USAGE_STREAM:
  9094. return D3D11_CPU_ACCESS_WRITE;
  9095. default:
  9096. SOKOL_UNREACHABLE;
  9097. return 0;
  9098. }
  9099. }
  9100. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_texture_pixel_format(sg_pixel_format fmt) {
  9101. switch (fmt) {
  9102. case SG_PIXELFORMAT_R8: return DXGI_FORMAT_R8_UNORM;
  9103. case SG_PIXELFORMAT_R8SN: return DXGI_FORMAT_R8_SNORM;
  9104. case SG_PIXELFORMAT_R8UI: return DXGI_FORMAT_R8_UINT;
  9105. case SG_PIXELFORMAT_R8SI: return DXGI_FORMAT_R8_SINT;
  9106. case SG_PIXELFORMAT_R16: return DXGI_FORMAT_R16_UNORM;
  9107. case SG_PIXELFORMAT_R16SN: return DXGI_FORMAT_R16_SNORM;
  9108. case SG_PIXELFORMAT_R16UI: return DXGI_FORMAT_R16_UINT;
  9109. case SG_PIXELFORMAT_R16SI: return DXGI_FORMAT_R16_SINT;
  9110. case SG_PIXELFORMAT_R16F: return DXGI_FORMAT_R16_FLOAT;
  9111. case SG_PIXELFORMAT_RG8: return DXGI_FORMAT_R8G8_UNORM;
  9112. case SG_PIXELFORMAT_RG8SN: return DXGI_FORMAT_R8G8_SNORM;
  9113. case SG_PIXELFORMAT_RG8UI: return DXGI_FORMAT_R8G8_UINT;
  9114. case SG_PIXELFORMAT_RG8SI: return DXGI_FORMAT_R8G8_SINT;
  9115. case SG_PIXELFORMAT_R32UI: return DXGI_FORMAT_R32_UINT;
  9116. case SG_PIXELFORMAT_R32SI: return DXGI_FORMAT_R32_SINT;
  9117. case SG_PIXELFORMAT_R32F: return DXGI_FORMAT_R32_FLOAT;
  9118. case SG_PIXELFORMAT_RG16: return DXGI_FORMAT_R16G16_UNORM;
  9119. case SG_PIXELFORMAT_RG16SN: return DXGI_FORMAT_R16G16_SNORM;
  9120. case SG_PIXELFORMAT_RG16UI: return DXGI_FORMAT_R16G16_UINT;
  9121. case SG_PIXELFORMAT_RG16SI: return DXGI_FORMAT_R16G16_SINT;
  9122. case SG_PIXELFORMAT_RG16F: return DXGI_FORMAT_R16G16_FLOAT;
  9123. case SG_PIXELFORMAT_RGBA8: return DXGI_FORMAT_R8G8B8A8_UNORM;
  9124. case SG_PIXELFORMAT_SRGB8A8: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
  9125. case SG_PIXELFORMAT_RGBA8SN: return DXGI_FORMAT_R8G8B8A8_SNORM;
  9126. case SG_PIXELFORMAT_RGBA8UI: return DXGI_FORMAT_R8G8B8A8_UINT;
  9127. case SG_PIXELFORMAT_RGBA8SI: return DXGI_FORMAT_R8G8B8A8_SINT;
  9128. case SG_PIXELFORMAT_BGRA8: return DXGI_FORMAT_B8G8R8A8_UNORM;
  9129. case SG_PIXELFORMAT_RGB10A2: return DXGI_FORMAT_R10G10B10A2_UNORM;
  9130. case SG_PIXELFORMAT_RG11B10F: return DXGI_FORMAT_R11G11B10_FLOAT;
  9131. case SG_PIXELFORMAT_RGB9E5: return DXGI_FORMAT_R9G9B9E5_SHAREDEXP;
  9132. case SG_PIXELFORMAT_RG32UI: return DXGI_FORMAT_R32G32_UINT;
  9133. case SG_PIXELFORMAT_RG32SI: return DXGI_FORMAT_R32G32_SINT;
  9134. case SG_PIXELFORMAT_RG32F: return DXGI_FORMAT_R32G32_FLOAT;
  9135. case SG_PIXELFORMAT_RGBA16: return DXGI_FORMAT_R16G16B16A16_UNORM;
  9136. case SG_PIXELFORMAT_RGBA16SN: return DXGI_FORMAT_R16G16B16A16_SNORM;
  9137. case SG_PIXELFORMAT_RGBA16UI: return DXGI_FORMAT_R16G16B16A16_UINT;
  9138. case SG_PIXELFORMAT_RGBA16SI: return DXGI_FORMAT_R16G16B16A16_SINT;
  9139. case SG_PIXELFORMAT_RGBA16F: return DXGI_FORMAT_R16G16B16A16_FLOAT;
  9140. case SG_PIXELFORMAT_RGBA32UI: return DXGI_FORMAT_R32G32B32A32_UINT;
  9141. case SG_PIXELFORMAT_RGBA32SI: return DXGI_FORMAT_R32G32B32A32_SINT;
  9142. case SG_PIXELFORMAT_RGBA32F: return DXGI_FORMAT_R32G32B32A32_FLOAT;
  9143. case SG_PIXELFORMAT_DEPTH: return DXGI_FORMAT_R32_TYPELESS;
  9144. case SG_PIXELFORMAT_DEPTH_STENCIL: return DXGI_FORMAT_R24G8_TYPELESS;
  9145. case SG_PIXELFORMAT_BC1_RGBA: return DXGI_FORMAT_BC1_UNORM;
  9146. case SG_PIXELFORMAT_BC2_RGBA: return DXGI_FORMAT_BC2_UNORM;
  9147. case SG_PIXELFORMAT_BC3_RGBA: return DXGI_FORMAT_BC3_UNORM;
  9148. case SG_PIXELFORMAT_BC3_SRGBA: return DXGI_FORMAT_BC3_UNORM_SRGB;
  9149. case SG_PIXELFORMAT_BC4_R: return DXGI_FORMAT_BC4_UNORM;
  9150. case SG_PIXELFORMAT_BC4_RSN: return DXGI_FORMAT_BC4_SNORM;
  9151. case SG_PIXELFORMAT_BC5_RG: return DXGI_FORMAT_BC5_UNORM;
  9152. case SG_PIXELFORMAT_BC5_RGSN: return DXGI_FORMAT_BC5_SNORM;
  9153. case SG_PIXELFORMAT_BC6H_RGBF: return DXGI_FORMAT_BC6H_SF16;
  9154. case SG_PIXELFORMAT_BC6H_RGBUF: return DXGI_FORMAT_BC6H_UF16;
  9155. case SG_PIXELFORMAT_BC7_RGBA: return DXGI_FORMAT_BC7_UNORM;
  9156. case SG_PIXELFORMAT_BC7_SRGBA: return DXGI_FORMAT_BC7_UNORM_SRGB;
  9157. default: return DXGI_FORMAT_UNKNOWN;
  9158. };
  9159. }
  9160. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_srv_pixel_format(sg_pixel_format fmt) {
  9161. if (fmt == SG_PIXELFORMAT_DEPTH) {
  9162. return DXGI_FORMAT_R32_FLOAT;
  9163. } else if (fmt == SG_PIXELFORMAT_DEPTH_STENCIL) {
  9164. return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
  9165. } else {
  9166. return _sg_d3d11_texture_pixel_format(fmt);
  9167. }
  9168. }
  9169. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_dsv_pixel_format(sg_pixel_format fmt) {
  9170. if (fmt == SG_PIXELFORMAT_DEPTH) {
  9171. return DXGI_FORMAT_D32_FLOAT;
  9172. } else if (fmt == SG_PIXELFORMAT_DEPTH_STENCIL) {
  9173. return DXGI_FORMAT_D24_UNORM_S8_UINT;
  9174. } else {
  9175. return _sg_d3d11_texture_pixel_format(fmt);
  9176. }
  9177. }
  9178. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_rtv_pixel_format(sg_pixel_format fmt) {
  9179. if (fmt == SG_PIXELFORMAT_DEPTH) {
  9180. return DXGI_FORMAT_R32_FLOAT;
  9181. } else if (fmt == SG_PIXELFORMAT_DEPTH_STENCIL) {
  9182. return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
  9183. } else {
  9184. return _sg_d3d11_texture_pixel_format(fmt);
  9185. }
  9186. }
  9187. _SOKOL_PRIVATE D3D11_PRIMITIVE_TOPOLOGY _sg_d3d11_primitive_topology(sg_primitive_type prim_type) {
  9188. switch (prim_type) {
  9189. case SG_PRIMITIVETYPE_POINTS: return D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
  9190. case SG_PRIMITIVETYPE_LINES: return D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
  9191. case SG_PRIMITIVETYPE_LINE_STRIP: return D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP;
  9192. case SG_PRIMITIVETYPE_TRIANGLES: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  9193. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
  9194. default: SOKOL_UNREACHABLE; return (D3D11_PRIMITIVE_TOPOLOGY) 0;
  9195. }
  9196. }
  9197. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_index_format(sg_index_type index_type) {
  9198. switch (index_type) {
  9199. case SG_INDEXTYPE_NONE: return DXGI_FORMAT_UNKNOWN;
  9200. case SG_INDEXTYPE_UINT16: return DXGI_FORMAT_R16_UINT;
  9201. case SG_INDEXTYPE_UINT32: return DXGI_FORMAT_R32_UINT;
  9202. default: SOKOL_UNREACHABLE; return (DXGI_FORMAT) 0;
  9203. }
  9204. }
  9205. _SOKOL_PRIVATE D3D11_FILTER _sg_d3d11_filter(sg_filter min_f, sg_filter mag_f, sg_filter mipmap_f, bool comparison, uint32_t max_anisotropy) {
  9206. uint32_t d3d11_filter = 0;
  9207. if (max_anisotropy > 1) {
  9208. // D3D11_FILTER_ANISOTROPIC = 0x55,
  9209. d3d11_filter |= 0x55;
  9210. } else {
  9211. // D3D11_FILTER_MIN_MAG_MIP_POINT = 0,
  9212. // D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1,
  9213. // D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4,
  9214. // D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5,
  9215. // D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10,
  9216. // D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11,
  9217. // D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14,
  9218. // D3D11_FILTER_MIN_MAG_MIP_LINEAR = 0x15,
  9219. if (mipmap_f == SG_FILTER_LINEAR) {
  9220. d3d11_filter |= 0x01;
  9221. }
  9222. if (mag_f == SG_FILTER_LINEAR) {
  9223. d3d11_filter |= 0x04;
  9224. }
  9225. if (min_f == SG_FILTER_LINEAR) {
  9226. d3d11_filter |= 0x10;
  9227. }
  9228. }
  9229. // D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80,
  9230. // D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81,
  9231. // D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84,
  9232. // D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85,
  9233. // D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90,
  9234. // D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91,
  9235. // D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94,
  9236. // D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95,
  9237. // D3D11_FILTER_COMPARISON_ANISOTROPIC = 0xd5,
  9238. if (comparison) {
  9239. d3d11_filter |= 0x80;
  9240. }
  9241. return (D3D11_FILTER)d3d11_filter;
  9242. }
  9243. _SOKOL_PRIVATE D3D11_TEXTURE_ADDRESS_MODE _sg_d3d11_address_mode(sg_wrap m) {
  9244. switch (m) {
  9245. case SG_WRAP_REPEAT: return D3D11_TEXTURE_ADDRESS_WRAP;
  9246. case SG_WRAP_CLAMP_TO_EDGE: return D3D11_TEXTURE_ADDRESS_CLAMP;
  9247. case SG_WRAP_CLAMP_TO_BORDER: return D3D11_TEXTURE_ADDRESS_BORDER;
  9248. case SG_WRAP_MIRRORED_REPEAT: return D3D11_TEXTURE_ADDRESS_MIRROR;
  9249. default: SOKOL_UNREACHABLE; return (D3D11_TEXTURE_ADDRESS_MODE) 0;
  9250. }
  9251. }
  9252. _SOKOL_PRIVATE DXGI_FORMAT _sg_d3d11_vertex_format(sg_vertex_format fmt) {
  9253. switch (fmt) {
  9254. case SG_VERTEXFORMAT_FLOAT: return DXGI_FORMAT_R32_FLOAT;
  9255. case SG_VERTEXFORMAT_FLOAT2: return DXGI_FORMAT_R32G32_FLOAT;
  9256. case SG_VERTEXFORMAT_FLOAT3: return DXGI_FORMAT_R32G32B32_FLOAT;
  9257. case SG_VERTEXFORMAT_FLOAT4: return DXGI_FORMAT_R32G32B32A32_FLOAT;
  9258. case SG_VERTEXFORMAT_BYTE4: return DXGI_FORMAT_R8G8B8A8_SINT;
  9259. case SG_VERTEXFORMAT_BYTE4N: return DXGI_FORMAT_R8G8B8A8_SNORM;
  9260. case SG_VERTEXFORMAT_UBYTE4: return DXGI_FORMAT_R8G8B8A8_UINT;
  9261. case SG_VERTEXFORMAT_UBYTE4N: return DXGI_FORMAT_R8G8B8A8_UNORM;
  9262. case SG_VERTEXFORMAT_SHORT2: return DXGI_FORMAT_R16G16_SINT;
  9263. case SG_VERTEXFORMAT_SHORT2N: return DXGI_FORMAT_R16G16_SNORM;
  9264. case SG_VERTEXFORMAT_USHORT2N: return DXGI_FORMAT_R16G16_UNORM;
  9265. case SG_VERTEXFORMAT_SHORT4: return DXGI_FORMAT_R16G16B16A16_SINT;
  9266. case SG_VERTEXFORMAT_SHORT4N: return DXGI_FORMAT_R16G16B16A16_SNORM;
  9267. case SG_VERTEXFORMAT_USHORT4N: return DXGI_FORMAT_R16G16B16A16_UNORM;
  9268. case SG_VERTEXFORMAT_UINT10_N2: return DXGI_FORMAT_R10G10B10A2_UNORM;
  9269. case SG_VERTEXFORMAT_HALF2: return DXGI_FORMAT_R16G16_FLOAT;
  9270. case SG_VERTEXFORMAT_HALF4: return DXGI_FORMAT_R16G16B16A16_FLOAT;
  9271. default: SOKOL_UNREACHABLE; return (DXGI_FORMAT) 0;
  9272. }
  9273. }
  9274. _SOKOL_PRIVATE D3D11_INPUT_CLASSIFICATION _sg_d3d11_input_classification(sg_vertex_step step) {
  9275. switch (step) {
  9276. case SG_VERTEXSTEP_PER_VERTEX: return D3D11_INPUT_PER_VERTEX_DATA;
  9277. case SG_VERTEXSTEP_PER_INSTANCE: return D3D11_INPUT_PER_INSTANCE_DATA;
  9278. default: SOKOL_UNREACHABLE; return (D3D11_INPUT_CLASSIFICATION) 0;
  9279. }
  9280. }
  9281. _SOKOL_PRIVATE D3D11_CULL_MODE _sg_d3d11_cull_mode(sg_cull_mode m) {
  9282. switch (m) {
  9283. case SG_CULLMODE_NONE: return D3D11_CULL_NONE;
  9284. case SG_CULLMODE_FRONT: return D3D11_CULL_FRONT;
  9285. case SG_CULLMODE_BACK: return D3D11_CULL_BACK;
  9286. default: SOKOL_UNREACHABLE; return (D3D11_CULL_MODE) 0;
  9287. }
  9288. }
  9289. _SOKOL_PRIVATE D3D11_COMPARISON_FUNC _sg_d3d11_compare_func(sg_compare_func f) {
  9290. switch (f) {
  9291. case SG_COMPAREFUNC_NEVER: return D3D11_COMPARISON_NEVER;
  9292. case SG_COMPAREFUNC_LESS: return D3D11_COMPARISON_LESS;
  9293. case SG_COMPAREFUNC_EQUAL: return D3D11_COMPARISON_EQUAL;
  9294. case SG_COMPAREFUNC_LESS_EQUAL: return D3D11_COMPARISON_LESS_EQUAL;
  9295. case SG_COMPAREFUNC_GREATER: return D3D11_COMPARISON_GREATER;
  9296. case SG_COMPAREFUNC_NOT_EQUAL: return D3D11_COMPARISON_NOT_EQUAL;
  9297. case SG_COMPAREFUNC_GREATER_EQUAL: return D3D11_COMPARISON_GREATER_EQUAL;
  9298. case SG_COMPAREFUNC_ALWAYS: return D3D11_COMPARISON_ALWAYS;
  9299. default: SOKOL_UNREACHABLE; return (D3D11_COMPARISON_FUNC) 0;
  9300. }
  9301. }
  9302. _SOKOL_PRIVATE D3D11_STENCIL_OP _sg_d3d11_stencil_op(sg_stencil_op op) {
  9303. switch (op) {
  9304. case SG_STENCILOP_KEEP: return D3D11_STENCIL_OP_KEEP;
  9305. case SG_STENCILOP_ZERO: return D3D11_STENCIL_OP_ZERO;
  9306. case SG_STENCILOP_REPLACE: return D3D11_STENCIL_OP_REPLACE;
  9307. case SG_STENCILOP_INCR_CLAMP: return D3D11_STENCIL_OP_INCR_SAT;
  9308. case SG_STENCILOP_DECR_CLAMP: return D3D11_STENCIL_OP_DECR_SAT;
  9309. case SG_STENCILOP_INVERT: return D3D11_STENCIL_OP_INVERT;
  9310. case SG_STENCILOP_INCR_WRAP: return D3D11_STENCIL_OP_INCR;
  9311. case SG_STENCILOP_DECR_WRAP: return D3D11_STENCIL_OP_DECR;
  9312. default: SOKOL_UNREACHABLE; return (D3D11_STENCIL_OP) 0;
  9313. }
  9314. }
  9315. _SOKOL_PRIVATE D3D11_BLEND _sg_d3d11_blend_factor(sg_blend_factor f) {
  9316. switch (f) {
  9317. case SG_BLENDFACTOR_ZERO: return D3D11_BLEND_ZERO;
  9318. case SG_BLENDFACTOR_ONE: return D3D11_BLEND_ONE;
  9319. case SG_BLENDFACTOR_SRC_COLOR: return D3D11_BLEND_SRC_COLOR;
  9320. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return D3D11_BLEND_INV_SRC_COLOR;
  9321. case SG_BLENDFACTOR_SRC_ALPHA: return D3D11_BLEND_SRC_ALPHA;
  9322. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return D3D11_BLEND_INV_SRC_ALPHA;
  9323. case SG_BLENDFACTOR_DST_COLOR: return D3D11_BLEND_DEST_COLOR;
  9324. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return D3D11_BLEND_INV_DEST_COLOR;
  9325. case SG_BLENDFACTOR_DST_ALPHA: return D3D11_BLEND_DEST_ALPHA;
  9326. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return D3D11_BLEND_INV_DEST_ALPHA;
  9327. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return D3D11_BLEND_SRC_ALPHA_SAT;
  9328. case SG_BLENDFACTOR_BLEND_COLOR: return D3D11_BLEND_BLEND_FACTOR;
  9329. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return D3D11_BLEND_INV_BLEND_FACTOR;
  9330. case SG_BLENDFACTOR_BLEND_ALPHA: return D3D11_BLEND_BLEND_FACTOR;
  9331. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return D3D11_BLEND_INV_BLEND_FACTOR;
  9332. default: SOKOL_UNREACHABLE; return (D3D11_BLEND) 0;
  9333. }
  9334. }
  9335. _SOKOL_PRIVATE D3D11_BLEND_OP _sg_d3d11_blend_op(sg_blend_op op) {
  9336. switch (op) {
  9337. case SG_BLENDOP_ADD: return D3D11_BLEND_OP_ADD;
  9338. case SG_BLENDOP_SUBTRACT: return D3D11_BLEND_OP_SUBTRACT;
  9339. case SG_BLENDOP_REVERSE_SUBTRACT: return D3D11_BLEND_OP_REV_SUBTRACT;
  9340. case SG_BLENDOP_MIN: return D3D11_BLEND_OP_MIN;
  9341. case SG_BLENDOP_MAX: return D3D11_BLEND_OP_MAX;
  9342. default: SOKOL_UNREACHABLE; return (D3D11_BLEND_OP) 0;
  9343. }
  9344. }
  9345. _SOKOL_PRIVATE UINT8 _sg_d3d11_color_write_mask(sg_color_mask m) {
  9346. UINT8 res = 0;
  9347. if (m & SG_COLORMASK_R) {
  9348. res |= D3D11_COLOR_WRITE_ENABLE_RED;
  9349. }
  9350. if (m & SG_COLORMASK_G) {
  9351. res |= D3D11_COLOR_WRITE_ENABLE_GREEN;
  9352. }
  9353. if (m & SG_COLORMASK_B) {
  9354. res |= D3D11_COLOR_WRITE_ENABLE_BLUE;
  9355. }
  9356. if (m & SG_COLORMASK_A) {
  9357. res |= D3D11_COLOR_WRITE_ENABLE_ALPHA;
  9358. }
  9359. return res;
  9360. }
  9361. _SOKOL_PRIVATE UINT _sg_d3d11_dxgi_fmt_caps(DXGI_FORMAT dxgi_fmt) {
  9362. UINT dxgi_fmt_caps = 0;
  9363. if (dxgi_fmt != DXGI_FORMAT_UNKNOWN) {
  9364. HRESULT hr = _sg_d3d11_CheckFormatSupport(_sg.d3d11.dev, dxgi_fmt, &dxgi_fmt_caps);
  9365. SOKOL_ASSERT(SUCCEEDED(hr) || (E_FAIL == hr));
  9366. if (!SUCCEEDED(hr)) {
  9367. dxgi_fmt_caps = 0;
  9368. }
  9369. }
  9370. return dxgi_fmt_caps;
  9371. }
  9372. // see: https://docs.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-limits#resource-limits-for-feature-level-11-hardware
  9373. _SOKOL_PRIVATE void _sg_d3d11_init_caps(void) {
  9374. _sg.backend = SG_BACKEND_D3D11;
  9375. _sg.features.origin_top_left = true;
  9376. _sg.features.image_clamp_to_border = true;
  9377. _sg.features.mrt_independent_blend_state = true;
  9378. _sg.features.mrt_independent_write_mask = true;
  9379. _sg.features.storage_buffer = true;
  9380. _sg.features.msaa_image_bindings = true;
  9381. _sg.limits.max_image_size_2d = 16 * 1024;
  9382. _sg.limits.max_image_size_cube = 16 * 1024;
  9383. _sg.limits.max_image_size_3d = 2 * 1024;
  9384. _sg.limits.max_image_size_array = 16 * 1024;
  9385. _sg.limits.max_image_array_layers = 2 * 1024;
  9386. _sg.limits.max_vertex_attrs = SG_MAX_VERTEX_ATTRIBUTES;
  9387. // see: https://docs.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_format_support
  9388. for (int fmt = (SG_PIXELFORMAT_NONE+1); fmt < _SG_PIXELFORMAT_NUM; fmt++) {
  9389. const UINT srv_dxgi_fmt_caps = _sg_d3d11_dxgi_fmt_caps(_sg_d3d11_srv_pixel_format((sg_pixel_format)fmt));
  9390. const UINT rtv_dxgi_fmt_caps = _sg_d3d11_dxgi_fmt_caps(_sg_d3d11_rtv_pixel_format((sg_pixel_format)fmt));
  9391. const UINT dsv_dxgi_fmt_caps = _sg_d3d11_dxgi_fmt_caps(_sg_d3d11_dsv_pixel_format((sg_pixel_format)fmt));
  9392. _sg_pixelformat_info_t* info = &_sg.formats[fmt];
  9393. const bool render = 0 != (rtv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_RENDER_TARGET);
  9394. const bool depth = 0 != (dsv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_DEPTH_STENCIL);
  9395. info->sample = 0 != (srv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_TEXTURE2D);
  9396. info->filter = 0 != (srv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_SHADER_SAMPLE);
  9397. info->render = render || depth;
  9398. if (depth) {
  9399. info->blend = 0 != (dsv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_BLENDABLE);
  9400. info->msaa = 0 != (dsv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET);
  9401. } else {
  9402. info->blend = 0 != (rtv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_BLENDABLE);
  9403. info->msaa = 0 != (rtv_dxgi_fmt_caps & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET);
  9404. }
  9405. info->depth = depth;
  9406. }
  9407. }
  9408. _SOKOL_PRIVATE void _sg_d3d11_setup_backend(const sg_desc* desc) {
  9409. // assume _sg.d3d11 already is zero-initialized
  9410. SOKOL_ASSERT(desc);
  9411. SOKOL_ASSERT(desc->environment.d3d11.device);
  9412. SOKOL_ASSERT(desc->environment.d3d11.device_context);
  9413. _sg.d3d11.valid = true;
  9414. _sg.d3d11.dev = (ID3D11Device*) desc->environment.d3d11.device;
  9415. _sg.d3d11.ctx = (ID3D11DeviceContext*) desc->environment.d3d11.device_context;
  9416. _sg_d3d11_init_caps();
  9417. }
  9418. _SOKOL_PRIVATE void _sg_d3d11_discard_backend(void) {
  9419. SOKOL_ASSERT(_sg.d3d11.valid);
  9420. _sg.d3d11.valid = false;
  9421. }
  9422. _SOKOL_PRIVATE void _sg_d3d11_clear_state(void) {
  9423. // clear all the device context state, so that resource refs don't keep stuck in the d3d device context
  9424. _sg_d3d11_ClearState(_sg.d3d11.ctx);
  9425. }
  9426. _SOKOL_PRIVATE void _sg_d3d11_reset_state_cache(void) {
  9427. // there's currently no state cache in the D3D11 backend, so this is a no-op
  9428. }
  9429. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  9430. SOKOL_ASSERT(buf && desc);
  9431. SOKOL_ASSERT(!buf->d3d11.buf);
  9432. const bool injected = (0 != desc->d3d11_buffer);
  9433. if (injected) {
  9434. buf->d3d11.buf = (ID3D11Buffer*) desc->d3d11_buffer;
  9435. _sg_d3d11_AddRef(buf->d3d11.buf);
  9436. // FIXME: for storage buffers also need to inject resource view
  9437. } else {
  9438. D3D11_BUFFER_DESC d3d11_buf_desc;
  9439. _sg_clear(&d3d11_buf_desc, sizeof(d3d11_buf_desc));
  9440. d3d11_buf_desc.ByteWidth = (UINT)buf->cmn.size;
  9441. d3d11_buf_desc.Usage = _sg_d3d11_usage(buf->cmn.usage);
  9442. d3d11_buf_desc.BindFlags = _sg_d3d11_buffer_bind_flags(buf->cmn.type);
  9443. d3d11_buf_desc.CPUAccessFlags = _sg_d3d11_cpu_access_flags(buf->cmn.usage);
  9444. d3d11_buf_desc.MiscFlags = _sg_d3d11_buffer_misc_flags(buf->cmn.type);
  9445. D3D11_SUBRESOURCE_DATA* init_data_ptr = 0;
  9446. D3D11_SUBRESOURCE_DATA init_data;
  9447. _sg_clear(&init_data, sizeof(init_data));
  9448. if (buf->cmn.usage == SG_USAGE_IMMUTABLE) {
  9449. SOKOL_ASSERT(desc->data.ptr);
  9450. init_data.pSysMem = desc->data.ptr;
  9451. init_data_ptr = &init_data;
  9452. }
  9453. HRESULT hr = _sg_d3d11_CreateBuffer(_sg.d3d11.dev, &d3d11_buf_desc, init_data_ptr, &buf->d3d11.buf);
  9454. if (!(SUCCEEDED(hr) && buf->d3d11.buf)) {
  9455. _SG_ERROR(D3D11_CREATE_BUFFER_FAILED);
  9456. return SG_RESOURCESTATE_FAILED;
  9457. }
  9458. // for storage buffers need to create a view object
  9459. if (buf->cmn.type == SG_BUFFERTYPE_STORAGEBUFFER) {
  9460. // FIXME: currently only shader-resource-view, in future also UAV
  9461. // storage buffer size must be multiple of 4
  9462. SOKOL_ASSERT(_sg_multiple_u64(buf->cmn.size, 4));
  9463. D3D11_SHADER_RESOURCE_VIEW_DESC d3d11_srv_desc;
  9464. _sg_clear(&d3d11_srv_desc, sizeof(d3d11_srv_desc));
  9465. d3d11_srv_desc.Format = DXGI_FORMAT_R32_TYPELESS;
  9466. d3d11_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX;
  9467. d3d11_srv_desc.BufferEx.FirstElement = 0;
  9468. d3d11_srv_desc.BufferEx.NumElements = buf->cmn.size / 4;
  9469. d3d11_srv_desc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW;
  9470. hr = _sg_d3d11_CreateShaderResourceView(_sg.d3d11.dev, (ID3D11Resource*)buf->d3d11.buf, &d3d11_srv_desc, &buf->d3d11.srv);
  9471. if (!(SUCCEEDED(hr) && buf->d3d11.srv)) {
  9472. _SG_ERROR(D3D11_CREATE_BUFFER_SRV_FAILED);
  9473. return SG_RESOURCESTATE_FAILED;
  9474. }
  9475. }
  9476. _sg_d3d11_setlabel(buf->d3d11.buf, desc->label);
  9477. }
  9478. return SG_RESOURCESTATE_VALID;
  9479. }
  9480. _SOKOL_PRIVATE void _sg_d3d11_discard_buffer(_sg_buffer_t* buf) {
  9481. SOKOL_ASSERT(buf);
  9482. if (buf->d3d11.buf) {
  9483. _sg_d3d11_Release(buf->d3d11.buf);
  9484. }
  9485. if (buf->d3d11.srv) {
  9486. _sg_d3d11_Release(buf->d3d11.srv);
  9487. }
  9488. }
  9489. _SOKOL_PRIVATE void _sg_d3d11_fill_subres_data(const _sg_image_t* img, const sg_image_data* data) {
  9490. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6:1;
  9491. const int num_slices = (img->cmn.type == SG_IMAGETYPE_ARRAY) ? img->cmn.num_slices:1;
  9492. int subres_index = 0;
  9493. for (int face_index = 0; face_index < num_faces; face_index++) {
  9494. for (int slice_index = 0; slice_index < num_slices; slice_index++) {
  9495. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++, subres_index++) {
  9496. SOKOL_ASSERT(subres_index < (SG_MAX_MIPMAPS * SG_MAX_TEXTUREARRAY_LAYERS));
  9497. D3D11_SUBRESOURCE_DATA* subres_data = &_sg.d3d11.subres_data[subres_index];
  9498. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  9499. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  9500. const sg_range* subimg_data = &(data->subimage[face_index][mip_index]);
  9501. const size_t slice_size = subimg_data->size / (size_t)num_slices;
  9502. const size_t slice_offset = slice_size * (size_t)slice_index;
  9503. const uint8_t* ptr = (const uint8_t*) subimg_data->ptr;
  9504. subres_data->pSysMem = ptr + slice_offset;
  9505. subres_data->SysMemPitch = (UINT)_sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  9506. if (img->cmn.type == SG_IMAGETYPE_3D) {
  9507. // FIXME? const int mip_depth = _sg_miplevel_dim(img->depth, mip_index);
  9508. subres_data->SysMemSlicePitch = (UINT)_sg_surface_pitch(img->cmn.pixel_format, mip_width, mip_height, 1);
  9509. } else {
  9510. subres_data->SysMemSlicePitch = 0;
  9511. }
  9512. }
  9513. }
  9514. }
  9515. }
  9516. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  9517. SOKOL_ASSERT(img && desc);
  9518. SOKOL_ASSERT((0 == img->d3d11.tex2d) && (0 == img->d3d11.tex3d) && (0 == img->d3d11.res) && (0 == img->d3d11.srv));
  9519. HRESULT hr;
  9520. const bool injected = (0 != desc->d3d11_texture);
  9521. const bool msaa = (img->cmn.sample_count > 1);
  9522. SOKOL_ASSERT(!(msaa && (img->cmn.type == SG_IMAGETYPE_CUBE)));
  9523. img->d3d11.format = _sg_d3d11_texture_pixel_format(img->cmn.pixel_format);
  9524. if (img->d3d11.format == DXGI_FORMAT_UNKNOWN) {
  9525. _SG_ERROR(D3D11_CREATE_2D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT);
  9526. return SG_RESOURCESTATE_FAILED;
  9527. }
  9528. // prepare initial content pointers
  9529. D3D11_SUBRESOURCE_DATA* init_data = 0;
  9530. if (!injected && (img->cmn.usage == SG_USAGE_IMMUTABLE) && !img->cmn.render_target) {
  9531. _sg_d3d11_fill_subres_data(img, &desc->data);
  9532. init_data = _sg.d3d11.subres_data;
  9533. }
  9534. if (img->cmn.type != SG_IMAGETYPE_3D) {
  9535. // 2D-, cube- or array-texture
  9536. // first check for injected texture and/or resource view
  9537. if (injected) {
  9538. img->d3d11.tex2d = (ID3D11Texture2D*) desc->d3d11_texture;
  9539. _sg_d3d11_AddRef(img->d3d11.tex2d);
  9540. img->d3d11.srv = (ID3D11ShaderResourceView*) desc->d3d11_shader_resource_view;
  9541. if (img->d3d11.srv) {
  9542. _sg_d3d11_AddRef(img->d3d11.srv);
  9543. }
  9544. } else {
  9545. // if not injected, create 2D texture
  9546. D3D11_TEXTURE2D_DESC d3d11_tex_desc;
  9547. _sg_clear(&d3d11_tex_desc, sizeof(d3d11_tex_desc));
  9548. d3d11_tex_desc.Width = (UINT)img->cmn.width;
  9549. d3d11_tex_desc.Height = (UINT)img->cmn.height;
  9550. d3d11_tex_desc.MipLevels = (UINT)img->cmn.num_mipmaps;
  9551. switch (img->cmn.type) {
  9552. case SG_IMAGETYPE_ARRAY: d3d11_tex_desc.ArraySize = (UINT)img->cmn.num_slices; break;
  9553. case SG_IMAGETYPE_CUBE: d3d11_tex_desc.ArraySize = 6; break;
  9554. default: d3d11_tex_desc.ArraySize = 1; break;
  9555. }
  9556. d3d11_tex_desc.Format = img->d3d11.format;
  9557. d3d11_tex_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  9558. if (img->cmn.render_target) {
  9559. d3d11_tex_desc.Usage = D3D11_USAGE_DEFAULT;
  9560. if (_sg_is_depth_or_depth_stencil_format(img->cmn.pixel_format)) {
  9561. d3d11_tex_desc.BindFlags |= D3D11_BIND_DEPTH_STENCIL;
  9562. } else {
  9563. d3d11_tex_desc.BindFlags |= D3D11_BIND_RENDER_TARGET;
  9564. }
  9565. d3d11_tex_desc.CPUAccessFlags = 0;
  9566. } else {
  9567. d3d11_tex_desc.Usage = _sg_d3d11_usage(img->cmn.usage);
  9568. d3d11_tex_desc.CPUAccessFlags = _sg_d3d11_cpu_access_flags(img->cmn.usage);
  9569. }
  9570. d3d11_tex_desc.SampleDesc.Count = (UINT)img->cmn.sample_count;
  9571. d3d11_tex_desc.SampleDesc.Quality = (UINT) (msaa ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0);
  9572. d3d11_tex_desc.MiscFlags = (img->cmn.type == SG_IMAGETYPE_CUBE) ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0;
  9573. hr = _sg_d3d11_CreateTexture2D(_sg.d3d11.dev, &d3d11_tex_desc, init_data, &img->d3d11.tex2d);
  9574. if (!(SUCCEEDED(hr) && img->d3d11.tex2d)) {
  9575. _SG_ERROR(D3D11_CREATE_2D_TEXTURE_FAILED);
  9576. return SG_RESOURCESTATE_FAILED;
  9577. }
  9578. _sg_d3d11_setlabel(img->d3d11.tex2d, desc->label);
  9579. // create shader-resource-view for 2D texture
  9580. D3D11_SHADER_RESOURCE_VIEW_DESC d3d11_srv_desc;
  9581. _sg_clear(&d3d11_srv_desc, sizeof(d3d11_srv_desc));
  9582. d3d11_srv_desc.Format = _sg_d3d11_srv_pixel_format(img->cmn.pixel_format);
  9583. switch (img->cmn.type) {
  9584. case SG_IMAGETYPE_2D:
  9585. d3d11_srv_desc.ViewDimension = msaa ? D3D11_SRV_DIMENSION_TEXTURE2DMS : D3D11_SRV_DIMENSION_TEXTURE2D;
  9586. d3d11_srv_desc.Texture2D.MipLevels = (UINT)img->cmn.num_mipmaps;
  9587. break;
  9588. case SG_IMAGETYPE_CUBE:
  9589. d3d11_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
  9590. d3d11_srv_desc.TextureCube.MipLevels = (UINT)img->cmn.num_mipmaps;
  9591. break;
  9592. case SG_IMAGETYPE_ARRAY:
  9593. d3d11_srv_desc.ViewDimension = msaa ? D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY : D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
  9594. d3d11_srv_desc.Texture2DArray.MipLevels = (UINT)img->cmn.num_mipmaps;
  9595. d3d11_srv_desc.Texture2DArray.ArraySize = (UINT)img->cmn.num_slices;
  9596. break;
  9597. default:
  9598. SOKOL_UNREACHABLE; break;
  9599. }
  9600. hr = _sg_d3d11_CreateShaderResourceView(_sg.d3d11.dev, (ID3D11Resource*)img->d3d11.tex2d, &d3d11_srv_desc, &img->d3d11.srv);
  9601. if (!(SUCCEEDED(hr) && img->d3d11.srv)) {
  9602. _SG_ERROR(D3D11_CREATE_2D_SRV_FAILED);
  9603. return SG_RESOURCESTATE_FAILED;
  9604. }
  9605. _sg_d3d11_setlabel(img->d3d11.srv, desc->label);
  9606. }
  9607. SOKOL_ASSERT(img->d3d11.tex2d);
  9608. img->d3d11.res = (ID3D11Resource*)img->d3d11.tex2d;
  9609. _sg_d3d11_AddRef(img->d3d11.res);
  9610. } else {
  9611. // 3D texture - same procedure, first check if injected, than create non-injected
  9612. if (injected) {
  9613. img->d3d11.tex3d = (ID3D11Texture3D*) desc->d3d11_texture;
  9614. _sg_d3d11_AddRef(img->d3d11.tex3d);
  9615. img->d3d11.srv = (ID3D11ShaderResourceView*) desc->d3d11_shader_resource_view;
  9616. if (img->d3d11.srv) {
  9617. _sg_d3d11_AddRef(img->d3d11.srv);
  9618. }
  9619. } else {
  9620. // not injected, create 3d texture
  9621. D3D11_TEXTURE3D_DESC d3d11_tex_desc;
  9622. _sg_clear(&d3d11_tex_desc, sizeof(d3d11_tex_desc));
  9623. d3d11_tex_desc.Width = (UINT)img->cmn.width;
  9624. d3d11_tex_desc.Height = (UINT)img->cmn.height;
  9625. d3d11_tex_desc.Depth = (UINT)img->cmn.num_slices;
  9626. d3d11_tex_desc.MipLevels = (UINT)img->cmn.num_mipmaps;
  9627. d3d11_tex_desc.Format = img->d3d11.format;
  9628. if (img->cmn.render_target) {
  9629. d3d11_tex_desc.Usage = D3D11_USAGE_DEFAULT;
  9630. d3d11_tex_desc.BindFlags = D3D11_BIND_RENDER_TARGET;
  9631. d3d11_tex_desc.CPUAccessFlags = 0;
  9632. } else {
  9633. d3d11_tex_desc.Usage = _sg_d3d11_usage(img->cmn.usage);
  9634. d3d11_tex_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
  9635. d3d11_tex_desc.CPUAccessFlags = _sg_d3d11_cpu_access_flags(img->cmn.usage);
  9636. }
  9637. if (img->d3d11.format == DXGI_FORMAT_UNKNOWN) {
  9638. _SG_ERROR(D3D11_CREATE_3D_TEXTURE_UNSUPPORTED_PIXEL_FORMAT);
  9639. return SG_RESOURCESTATE_FAILED;
  9640. }
  9641. hr = _sg_d3d11_CreateTexture3D(_sg.d3d11.dev, &d3d11_tex_desc, init_data, &img->d3d11.tex3d);
  9642. if (!(SUCCEEDED(hr) && img->d3d11.tex3d)) {
  9643. _SG_ERROR(D3D11_CREATE_3D_TEXTURE_FAILED);
  9644. return SG_RESOURCESTATE_FAILED;
  9645. }
  9646. _sg_d3d11_setlabel(img->d3d11.tex3d, desc->label);
  9647. // create shader-resource-view for 3D texture
  9648. if (!msaa) {
  9649. D3D11_SHADER_RESOURCE_VIEW_DESC d3d11_srv_desc;
  9650. _sg_clear(&d3d11_srv_desc, sizeof(d3d11_srv_desc));
  9651. d3d11_srv_desc.Format = _sg_d3d11_srv_pixel_format(img->cmn.pixel_format);
  9652. d3d11_srv_desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
  9653. d3d11_srv_desc.Texture3D.MipLevels = (UINT)img->cmn.num_mipmaps;
  9654. hr = _sg_d3d11_CreateShaderResourceView(_sg.d3d11.dev, (ID3D11Resource*)img->d3d11.tex3d, &d3d11_srv_desc, &img->d3d11.srv);
  9655. if (!(SUCCEEDED(hr) && img->d3d11.srv)) {
  9656. _SG_ERROR(D3D11_CREATE_3D_SRV_FAILED);
  9657. return SG_RESOURCESTATE_FAILED;
  9658. }
  9659. _sg_d3d11_setlabel(img->d3d11.srv, desc->label);
  9660. }
  9661. }
  9662. SOKOL_ASSERT(img->d3d11.tex3d);
  9663. img->d3d11.res = (ID3D11Resource*)img->d3d11.tex3d;
  9664. _sg_d3d11_AddRef(img->d3d11.res);
  9665. }
  9666. return SG_RESOURCESTATE_VALID;
  9667. }
  9668. _SOKOL_PRIVATE void _sg_d3d11_discard_image(_sg_image_t* img) {
  9669. SOKOL_ASSERT(img);
  9670. if (img->d3d11.tex2d) {
  9671. _sg_d3d11_Release(img->d3d11.tex2d);
  9672. }
  9673. if (img->d3d11.tex3d) {
  9674. _sg_d3d11_Release(img->d3d11.tex3d);
  9675. }
  9676. if (img->d3d11.res) {
  9677. _sg_d3d11_Release(img->d3d11.res);
  9678. }
  9679. if (img->d3d11.srv) {
  9680. _sg_d3d11_Release(img->d3d11.srv);
  9681. }
  9682. }
  9683. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  9684. SOKOL_ASSERT(smp && desc);
  9685. SOKOL_ASSERT(0 == smp->d3d11.smp);
  9686. const bool injected = (0 != desc->d3d11_sampler);
  9687. if (injected) {
  9688. smp->d3d11.smp = (ID3D11SamplerState*)desc->d3d11_sampler;
  9689. _sg_d3d11_AddRef(smp->d3d11.smp);
  9690. } else {
  9691. D3D11_SAMPLER_DESC d3d11_smp_desc;
  9692. _sg_clear(&d3d11_smp_desc, sizeof(d3d11_smp_desc));
  9693. d3d11_smp_desc.Filter = _sg_d3d11_filter(desc->min_filter, desc->mag_filter, desc->mipmap_filter, desc->compare != SG_COMPAREFUNC_NEVER, desc->max_anisotropy);
  9694. d3d11_smp_desc.AddressU = _sg_d3d11_address_mode(desc->wrap_u);
  9695. d3d11_smp_desc.AddressV = _sg_d3d11_address_mode(desc->wrap_v);
  9696. d3d11_smp_desc.AddressW = _sg_d3d11_address_mode(desc->wrap_w);
  9697. d3d11_smp_desc.MipLODBias = 0.0f; // FIXME?
  9698. switch (desc->border_color) {
  9699. case SG_BORDERCOLOR_TRANSPARENT_BLACK:
  9700. // all 0.0f
  9701. break;
  9702. case SG_BORDERCOLOR_OPAQUE_WHITE:
  9703. for (int i = 0; i < 4; i++) {
  9704. d3d11_smp_desc.BorderColor[i] = 1.0f;
  9705. }
  9706. break;
  9707. default:
  9708. // opaque black
  9709. d3d11_smp_desc.BorderColor[3] = 1.0f;
  9710. break;
  9711. }
  9712. d3d11_smp_desc.MaxAnisotropy = desc->max_anisotropy;
  9713. d3d11_smp_desc.ComparisonFunc = _sg_d3d11_compare_func(desc->compare);
  9714. d3d11_smp_desc.MinLOD = desc->min_lod;
  9715. d3d11_smp_desc.MaxLOD = desc->max_lod;
  9716. HRESULT hr = _sg_d3d11_CreateSamplerState(_sg.d3d11.dev, &d3d11_smp_desc, &smp->d3d11.smp);
  9717. if (!(SUCCEEDED(hr) && smp->d3d11.smp)) {
  9718. _SG_ERROR(D3D11_CREATE_SAMPLER_STATE_FAILED);
  9719. return SG_RESOURCESTATE_FAILED;
  9720. }
  9721. _sg_d3d11_setlabel(smp->d3d11.smp, desc->label);
  9722. }
  9723. return SG_RESOURCESTATE_VALID;
  9724. }
  9725. _SOKOL_PRIVATE void _sg_d3d11_discard_sampler(_sg_sampler_t* smp) {
  9726. SOKOL_ASSERT(smp);
  9727. if (smp->d3d11.smp) {
  9728. _sg_d3d11_Release(smp->d3d11.smp);
  9729. }
  9730. }
  9731. _SOKOL_PRIVATE bool _sg_d3d11_load_d3dcompiler_dll(void) {
  9732. if ((0 == _sg.d3d11.d3dcompiler_dll) && !_sg.d3d11.d3dcompiler_dll_load_failed) {
  9733. _sg.d3d11.d3dcompiler_dll = LoadLibraryA("d3dcompiler_47.dll");
  9734. if (0 == _sg.d3d11.d3dcompiler_dll) {
  9735. // don't attempt to load missing DLL in the future
  9736. _SG_ERROR(D3D11_LOAD_D3DCOMPILER_47_DLL_FAILED);
  9737. _sg.d3d11.d3dcompiler_dll_load_failed = true;
  9738. return false;
  9739. }
  9740. // look up function pointers
  9741. _sg.d3d11.D3DCompile_func = (pD3DCompile)(void*) GetProcAddress(_sg.d3d11.d3dcompiler_dll, "D3DCompile");
  9742. SOKOL_ASSERT(_sg.d3d11.D3DCompile_func);
  9743. }
  9744. return 0 != _sg.d3d11.d3dcompiler_dll;
  9745. }
  9746. _SOKOL_PRIVATE ID3DBlob* _sg_d3d11_compile_shader(const sg_shader_function* shd_func) {
  9747. if (!_sg_d3d11_load_d3dcompiler_dll()) {
  9748. return NULL;
  9749. }
  9750. SOKOL_ASSERT(shd_func->d3d11_target);
  9751. UINT flags1 = D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR;
  9752. if (_sg.desc.d3d11_shader_debugging) {
  9753. flags1 |= D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
  9754. } else {
  9755. flags1 |= D3DCOMPILE_OPTIMIZATION_LEVEL3;
  9756. }
  9757. ID3DBlob* output = NULL;
  9758. ID3DBlob* errors_or_warnings = NULL;
  9759. HRESULT hr = _sg.d3d11.D3DCompile_func(
  9760. shd_func->source, // pSrcData
  9761. strlen(shd_func->source), // SrcDataSize
  9762. NULL, // pSourceName
  9763. NULL, // pDefines
  9764. NULL, // pInclude
  9765. shd_func->entry ? shd_func->entry : "main", // pEntryPoint
  9766. shd_func->d3d11_target, // pTarget
  9767. flags1, // Flags1
  9768. 0, // Flags2
  9769. &output, // ppCode
  9770. &errors_or_warnings); // ppErrorMsgs
  9771. if (FAILED(hr)) {
  9772. _SG_ERROR(D3D11_SHADER_COMPILATION_FAILED);
  9773. }
  9774. if (errors_or_warnings) {
  9775. _SG_WARN(D3D11_SHADER_COMPILATION_OUTPUT);
  9776. _SG_LOGMSG(D3D11_SHADER_COMPILATION_OUTPUT, (LPCSTR)_sg_d3d11_GetBufferPointer(errors_or_warnings));
  9777. _sg_d3d11_Release(errors_or_warnings); errors_or_warnings = NULL;
  9778. }
  9779. if (FAILED(hr)) {
  9780. // just in case, usually output is NULL here
  9781. if (output) {
  9782. _sg_d3d11_Release(output);
  9783. output = NULL;
  9784. }
  9785. }
  9786. return output;
  9787. }
  9788. // NOTE: this is an out-of-range check for HLSL bindslots that's also active in release mode
  9789. _SOKOL_PRIVATE bool _sg_d3d11_ensure_hlsl_bindslot_ranges(const sg_shader_desc* desc) {
  9790. SOKOL_ASSERT(desc);
  9791. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  9792. if (desc->uniform_blocks[i].hlsl_register_b_n >= _SG_D3D11_MAX_STAGE_UB_BINDINGS) {
  9793. _SG_ERROR(D3D11_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE);
  9794. return false;
  9795. }
  9796. }
  9797. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  9798. if (desc->storage_buffers[i].hlsl_register_t_n >= _SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS) {
  9799. _SG_ERROR(D3D11_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE);
  9800. return false;
  9801. }
  9802. }
  9803. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  9804. if (desc->images[i].hlsl_register_t_n >= _SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS) {
  9805. _SG_ERROR(D3D11_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE);
  9806. return false;
  9807. }
  9808. }
  9809. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  9810. if (desc->samplers[i].hlsl_register_s_n >= _SG_D3D11_MAX_STAGE_SMP_BINDINGS) {
  9811. _SG_ERROR(D3D11_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE);
  9812. return false;
  9813. }
  9814. }
  9815. return true;
  9816. }
  9817. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  9818. SOKOL_ASSERT(shd && desc);
  9819. SOKOL_ASSERT(!shd->d3d11.vs && !shd->d3d11.fs && !shd->d3d11.vs_blob);
  9820. HRESULT hr;
  9821. // perform a range-check on HLSL bindslots that's also active in release
  9822. // mode to avoid potential out-of-bounds array accesses
  9823. if (!_sg_d3d11_ensure_hlsl_bindslot_ranges(desc)) {
  9824. return SG_RESOURCESTATE_FAILED;
  9825. }
  9826. // copy vertex attribute semantic names and indices
  9827. for (size_t i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  9828. _sg_strcpy(&shd->d3d11.attrs[i].sem_name, desc->attrs[i].hlsl_sem_name);
  9829. shd->d3d11.attrs[i].sem_index = desc->attrs[i].hlsl_sem_index;
  9830. }
  9831. // copy HLSL bind slots
  9832. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  9833. shd->d3d11.ub_register_b_n[i] = desc->uniform_blocks[i].hlsl_register_b_n;
  9834. }
  9835. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  9836. shd->d3d11.sbuf_register_t_n[i] = desc->storage_buffers[i].hlsl_register_t_n;
  9837. }
  9838. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  9839. shd->d3d11.img_register_t_n[i] = desc->images[i].hlsl_register_t_n;
  9840. }
  9841. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  9842. shd->d3d11.smp_register_s_n[i] = desc->samplers[i].hlsl_register_s_n;
  9843. }
  9844. // create a D3D constant buffer for each uniform block
  9845. for (size_t ub_index = 0; ub_index < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_index++) {
  9846. const sg_shader_stage stage = desc->uniform_blocks[ub_index].stage;
  9847. if (stage == SG_SHADERSTAGE_NONE) {
  9848. continue;
  9849. }
  9850. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT));
  9851. const _sg_shader_uniform_block_t* ub = &shd->cmn.uniform_blocks[ub_index];
  9852. ID3D11Buffer* cbuf = 0;
  9853. D3D11_BUFFER_DESC cb_desc;
  9854. _sg_clear(&cb_desc, sizeof(cb_desc));
  9855. cb_desc.ByteWidth = (UINT)_sg_roundup((int)ub->size, 16);
  9856. cb_desc.Usage = D3D11_USAGE_DEFAULT;
  9857. cb_desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  9858. hr = _sg_d3d11_CreateBuffer(_sg.d3d11.dev, &cb_desc, NULL, &cbuf);
  9859. if (!(SUCCEEDED(hr) && cbuf)) {
  9860. _SG_ERROR(D3D11_CREATE_CONSTANT_BUFFER_FAILED);
  9861. return SG_RESOURCESTATE_FAILED;
  9862. }
  9863. _sg_d3d11_setlabel(cbuf, desc->label);
  9864. shd->d3d11.all_cbufs[ub_index] = cbuf;
  9865. const uint8_t d3d11_slot = shd->d3d11.ub_register_b_n[ub_index];
  9866. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_UB_BINDINGS);
  9867. if (stage == SG_SHADERSTAGE_VERTEX) {
  9868. SOKOL_ASSERT(0 == shd->d3d11.vs_cbufs[d3d11_slot]);
  9869. shd->d3d11.vs_cbufs[d3d11_slot] = cbuf;
  9870. } else {
  9871. SOKOL_ASSERT(0 == shd->d3d11.fs_cbufs[d3d11_slot]);
  9872. shd->d3d11.fs_cbufs[d3d11_slot] = cbuf;
  9873. }
  9874. }
  9875. // create shader functions
  9876. const void* vs_ptr = 0, *fs_ptr = 0;
  9877. SIZE_T vs_length = 0, fs_length = 0;
  9878. ID3DBlob* vs_blob = 0, *fs_blob = 0;
  9879. if (desc->vertex_func.bytecode.ptr && desc->fragment_func.bytecode.ptr) {
  9880. // create from shader byte code
  9881. vs_ptr = desc->vertex_func.bytecode.ptr;
  9882. fs_ptr = desc->fragment_func.bytecode.ptr;
  9883. vs_length = desc->vertex_func.bytecode.size;
  9884. fs_length = desc->fragment_func.bytecode.size;
  9885. } else {
  9886. // compile from shader source code
  9887. vs_blob = _sg_d3d11_compile_shader(&desc->vertex_func);
  9888. fs_blob = _sg_d3d11_compile_shader(&desc->fragment_func);
  9889. if (vs_blob && fs_blob) {
  9890. vs_ptr = _sg_d3d11_GetBufferPointer(vs_blob);
  9891. vs_length = _sg_d3d11_GetBufferSize(vs_blob);
  9892. fs_ptr = _sg_d3d11_GetBufferPointer(fs_blob);
  9893. fs_length = _sg_d3d11_GetBufferSize(fs_blob);
  9894. }
  9895. }
  9896. sg_resource_state result = SG_RESOURCESTATE_FAILED;
  9897. if (vs_ptr && fs_ptr && (vs_length > 0) && (fs_length > 0)) {
  9898. // create the D3D vertex- and pixel-shader objects
  9899. hr = _sg_d3d11_CreateVertexShader(_sg.d3d11.dev, vs_ptr, vs_length, NULL, &shd->d3d11.vs);
  9900. bool vs_succeeded = SUCCEEDED(hr) && shd->d3d11.vs;
  9901. hr = _sg_d3d11_CreatePixelShader(_sg.d3d11.dev, fs_ptr, fs_length, NULL, &shd->d3d11.fs);
  9902. bool fs_succeeded = SUCCEEDED(hr) && shd->d3d11.fs;
  9903. // need to store the vertex shader byte code, this is needed later in sg_create_pipeline
  9904. if (vs_succeeded && fs_succeeded) {
  9905. shd->d3d11.vs_blob_length = vs_length;
  9906. shd->d3d11.vs_blob = _sg_malloc((size_t)vs_length);
  9907. SOKOL_ASSERT(shd->d3d11.vs_blob);
  9908. memcpy(shd->d3d11.vs_blob, vs_ptr, vs_length);
  9909. result = SG_RESOURCESTATE_VALID;
  9910. _sg_d3d11_setlabel(shd->d3d11.vs, desc->label);
  9911. _sg_d3d11_setlabel(shd->d3d11.fs, desc->label);
  9912. }
  9913. }
  9914. if (vs_blob) {
  9915. _sg_d3d11_Release(vs_blob); vs_blob = 0;
  9916. }
  9917. if (fs_blob) {
  9918. _sg_d3d11_Release(fs_blob); fs_blob = 0;
  9919. }
  9920. return result;
  9921. }
  9922. _SOKOL_PRIVATE void _sg_d3d11_discard_shader(_sg_shader_t* shd) {
  9923. SOKOL_ASSERT(shd);
  9924. if (shd->d3d11.vs) {
  9925. _sg_d3d11_Release(shd->d3d11.vs);
  9926. }
  9927. if (shd->d3d11.fs) {
  9928. _sg_d3d11_Release(shd->d3d11.fs);
  9929. }
  9930. if (shd->d3d11.vs_blob) {
  9931. _sg_free(shd->d3d11.vs_blob);
  9932. }
  9933. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  9934. if (shd->d3d11.all_cbufs[i]) {
  9935. _sg_d3d11_Release(shd->d3d11.all_cbufs[i]);
  9936. }
  9937. }
  9938. }
  9939. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_pipeline(_sg_pipeline_t* pip, _sg_shader_t* shd, const sg_pipeline_desc* desc) {
  9940. SOKOL_ASSERT(pip && shd && desc);
  9941. SOKOL_ASSERT(desc->shader.id == shd->slot.id);
  9942. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_VALID);
  9943. SOKOL_ASSERT(shd->d3d11.vs_blob && shd->d3d11.vs_blob_length > 0);
  9944. SOKOL_ASSERT(!pip->d3d11.il && !pip->d3d11.rs && !pip->d3d11.dss && !pip->d3d11.bs);
  9945. pip->shader = shd;
  9946. pip->d3d11.index_format = _sg_d3d11_index_format(pip->cmn.index_type);
  9947. pip->d3d11.topology = _sg_d3d11_primitive_topology(desc->primitive_type);
  9948. pip->d3d11.stencil_ref = desc->stencil.ref;
  9949. // create input layout object
  9950. HRESULT hr;
  9951. D3D11_INPUT_ELEMENT_DESC d3d11_comps[SG_MAX_VERTEX_ATTRIBUTES];
  9952. _sg_clear(d3d11_comps, sizeof(d3d11_comps));
  9953. int attr_index = 0;
  9954. for (; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  9955. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  9956. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  9957. break;
  9958. }
  9959. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  9960. SOKOL_ASSERT(pip->cmn.vertex_buffer_layout_active[a_state->buffer_index]);
  9961. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[a_state->buffer_index];
  9962. const sg_vertex_step step_func = l_state->step_func;
  9963. const int step_rate = l_state->step_rate;
  9964. D3D11_INPUT_ELEMENT_DESC* d3d11_comp = &d3d11_comps[attr_index];
  9965. d3d11_comp->SemanticName = _sg_strptr(&shd->d3d11.attrs[attr_index].sem_name);
  9966. d3d11_comp->SemanticIndex = (UINT)shd->d3d11.attrs[attr_index].sem_index;
  9967. d3d11_comp->Format = _sg_d3d11_vertex_format(a_state->format);
  9968. d3d11_comp->InputSlot = (UINT)a_state->buffer_index;
  9969. d3d11_comp->AlignedByteOffset = (UINT)a_state->offset;
  9970. d3d11_comp->InputSlotClass = _sg_d3d11_input_classification(step_func);
  9971. if (SG_VERTEXSTEP_PER_INSTANCE == step_func) {
  9972. d3d11_comp->InstanceDataStepRate = (UINT)step_rate;
  9973. pip->cmn.use_instanced_draw = true;
  9974. }
  9975. }
  9976. for (int layout_index = 0; layout_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; layout_index++) {
  9977. if (pip->cmn.vertex_buffer_layout_active[layout_index]) {
  9978. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[layout_index];
  9979. SOKOL_ASSERT(l_state->stride > 0);
  9980. pip->d3d11.vb_strides[layout_index] = (UINT)l_state->stride;
  9981. } else {
  9982. pip->d3d11.vb_strides[layout_index] = 0;
  9983. }
  9984. }
  9985. if (attr_index > 0) {
  9986. hr = _sg_d3d11_CreateInputLayout(_sg.d3d11.dev,
  9987. d3d11_comps, // pInputElementDesc
  9988. (UINT)attr_index, // NumElements
  9989. shd->d3d11.vs_blob, // pShaderByteCodeWithInputSignature
  9990. shd->d3d11.vs_blob_length, // BytecodeLength
  9991. &pip->d3d11.il);
  9992. if (!(SUCCEEDED(hr) && pip->d3d11.il)) {
  9993. _SG_ERROR(D3D11_CREATE_INPUT_LAYOUT_FAILED);
  9994. return SG_RESOURCESTATE_FAILED;
  9995. }
  9996. _sg_d3d11_setlabel(pip->d3d11.il, desc->label);
  9997. }
  9998. // create rasterizer state
  9999. D3D11_RASTERIZER_DESC rs_desc;
  10000. _sg_clear(&rs_desc, sizeof(rs_desc));
  10001. rs_desc.FillMode = D3D11_FILL_SOLID;
  10002. rs_desc.CullMode = _sg_d3d11_cull_mode(desc->cull_mode);
  10003. rs_desc.FrontCounterClockwise = desc->face_winding == SG_FACEWINDING_CCW;
  10004. rs_desc.DepthBias = (INT) pip->cmn.depth.bias;
  10005. rs_desc.DepthBiasClamp = pip->cmn.depth.bias_clamp;
  10006. rs_desc.SlopeScaledDepthBias = pip->cmn.depth.bias_slope_scale;
  10007. rs_desc.DepthClipEnable = TRUE;
  10008. rs_desc.ScissorEnable = TRUE;
  10009. rs_desc.MultisampleEnable = desc->sample_count > 1;
  10010. rs_desc.AntialiasedLineEnable = FALSE;
  10011. hr = _sg_d3d11_CreateRasterizerState(_sg.d3d11.dev, &rs_desc, &pip->d3d11.rs);
  10012. if (!(SUCCEEDED(hr) && pip->d3d11.rs)) {
  10013. _SG_ERROR(D3D11_CREATE_RASTERIZER_STATE_FAILED);
  10014. return SG_RESOURCESTATE_FAILED;
  10015. }
  10016. _sg_d3d11_setlabel(pip->d3d11.rs, desc->label);
  10017. // create depth-stencil state
  10018. D3D11_DEPTH_STENCIL_DESC dss_desc;
  10019. _sg_clear(&dss_desc, sizeof(dss_desc));
  10020. dss_desc.DepthEnable = TRUE;
  10021. dss_desc.DepthWriteMask = desc->depth.write_enabled ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
  10022. dss_desc.DepthFunc = _sg_d3d11_compare_func(desc->depth.compare);
  10023. dss_desc.StencilEnable = desc->stencil.enabled;
  10024. dss_desc.StencilReadMask = desc->stencil.read_mask;
  10025. dss_desc.StencilWriteMask = desc->stencil.write_mask;
  10026. const sg_stencil_face_state* sf = &desc->stencil.front;
  10027. dss_desc.FrontFace.StencilFailOp = _sg_d3d11_stencil_op(sf->fail_op);
  10028. dss_desc.FrontFace.StencilDepthFailOp = _sg_d3d11_stencil_op(sf->depth_fail_op);
  10029. dss_desc.FrontFace.StencilPassOp = _sg_d3d11_stencil_op(sf->pass_op);
  10030. dss_desc.FrontFace.StencilFunc = _sg_d3d11_compare_func(sf->compare);
  10031. const sg_stencil_face_state* sb = &desc->stencil.back;
  10032. dss_desc.BackFace.StencilFailOp = _sg_d3d11_stencil_op(sb->fail_op);
  10033. dss_desc.BackFace.StencilDepthFailOp = _sg_d3d11_stencil_op(sb->depth_fail_op);
  10034. dss_desc.BackFace.StencilPassOp = _sg_d3d11_stencil_op(sb->pass_op);
  10035. dss_desc.BackFace.StencilFunc = _sg_d3d11_compare_func(sb->compare);
  10036. hr = _sg_d3d11_CreateDepthStencilState(_sg.d3d11.dev, &dss_desc, &pip->d3d11.dss);
  10037. if (!(SUCCEEDED(hr) && pip->d3d11.dss)) {
  10038. _SG_ERROR(D3D11_CREATE_DEPTH_STENCIL_STATE_FAILED);
  10039. return SG_RESOURCESTATE_FAILED;
  10040. }
  10041. _sg_d3d11_setlabel(pip->d3d11.dss, desc->label);
  10042. // create blend state
  10043. D3D11_BLEND_DESC bs_desc;
  10044. _sg_clear(&bs_desc, sizeof(bs_desc));
  10045. bs_desc.AlphaToCoverageEnable = desc->alpha_to_coverage_enabled;
  10046. bs_desc.IndependentBlendEnable = TRUE;
  10047. {
  10048. int i = 0;
  10049. for (i = 0; i < desc->color_count; i++) {
  10050. const sg_blend_state* src = &desc->colors[i].blend;
  10051. D3D11_RENDER_TARGET_BLEND_DESC* dst = &bs_desc.RenderTarget[i];
  10052. dst->BlendEnable = src->enabled;
  10053. dst->SrcBlend = _sg_d3d11_blend_factor(src->src_factor_rgb);
  10054. dst->DestBlend = _sg_d3d11_blend_factor(src->dst_factor_rgb);
  10055. dst->BlendOp = _sg_d3d11_blend_op(src->op_rgb);
  10056. dst->SrcBlendAlpha = _sg_d3d11_blend_factor(src->src_factor_alpha);
  10057. dst->DestBlendAlpha = _sg_d3d11_blend_factor(src->dst_factor_alpha);
  10058. dst->BlendOpAlpha = _sg_d3d11_blend_op(src->op_alpha);
  10059. dst->RenderTargetWriteMask = _sg_d3d11_color_write_mask(desc->colors[i].write_mask);
  10060. }
  10061. for (; i < 8; i++) {
  10062. D3D11_RENDER_TARGET_BLEND_DESC* dst = &bs_desc.RenderTarget[i];
  10063. dst->BlendEnable = FALSE;
  10064. dst->SrcBlend = dst->SrcBlendAlpha = D3D11_BLEND_ONE;
  10065. dst->DestBlend = dst->DestBlendAlpha = D3D11_BLEND_ZERO;
  10066. dst->BlendOp = dst->BlendOpAlpha = D3D11_BLEND_OP_ADD;
  10067. dst->RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
  10068. }
  10069. }
  10070. hr = _sg_d3d11_CreateBlendState(_sg.d3d11.dev, &bs_desc, &pip->d3d11.bs);
  10071. if (!(SUCCEEDED(hr) && pip->d3d11.bs)) {
  10072. _SG_ERROR(D3D11_CREATE_BLEND_STATE_FAILED);
  10073. return SG_RESOURCESTATE_FAILED;
  10074. }
  10075. _sg_d3d11_setlabel(pip->d3d11.bs, desc->label);
  10076. return SG_RESOURCESTATE_VALID;
  10077. }
  10078. _SOKOL_PRIVATE void _sg_d3d11_discard_pipeline(_sg_pipeline_t* pip) {
  10079. SOKOL_ASSERT(pip);
  10080. if (pip == _sg.d3d11.cur_pipeline) {
  10081. _sg.d3d11.cur_pipeline = 0;
  10082. _sg.d3d11.cur_pipeline_id.id = SG_INVALID_ID;
  10083. }
  10084. if (pip->d3d11.il) {
  10085. _sg_d3d11_Release(pip->d3d11.il);
  10086. }
  10087. if (pip->d3d11.rs) {
  10088. _sg_d3d11_Release(pip->d3d11.rs);
  10089. }
  10090. if (pip->d3d11.dss) {
  10091. _sg_d3d11_Release(pip->d3d11.dss);
  10092. }
  10093. if (pip->d3d11.bs) {
  10094. _sg_d3d11_Release(pip->d3d11.bs);
  10095. }
  10096. }
  10097. _SOKOL_PRIVATE sg_resource_state _sg_d3d11_create_attachments(_sg_attachments_t* atts, _sg_image_t** color_images, _sg_image_t** resolve_images, _sg_image_t* ds_img, const sg_attachments_desc* desc) {
  10098. SOKOL_ASSERT(atts && desc);
  10099. SOKOL_ASSERT(color_images && resolve_images);
  10100. SOKOL_ASSERT(_sg.d3d11.dev);
  10101. // copy image pointers
  10102. for (int i = 0; i < atts->cmn.num_colors; i++) {
  10103. const sg_attachment_desc* color_desc = &desc->colors[i];
  10104. _SOKOL_UNUSED(color_desc);
  10105. SOKOL_ASSERT(color_desc->image.id != SG_INVALID_ID);
  10106. SOKOL_ASSERT(0 == atts->d3d11.colors[i].image);
  10107. SOKOL_ASSERT(color_images[i] && (color_images[i]->slot.id == color_desc->image.id));
  10108. SOKOL_ASSERT(_sg_is_valid_rendertarget_color_format(color_images[i]->cmn.pixel_format));
  10109. atts->d3d11.colors[i].image = color_images[i];
  10110. const sg_attachment_desc* resolve_desc = &desc->resolves[i];
  10111. if (resolve_desc->image.id != SG_INVALID_ID) {
  10112. SOKOL_ASSERT(0 == atts->d3d11.resolves[i].image);
  10113. SOKOL_ASSERT(resolve_images[i] && (resolve_images[i]->slot.id == resolve_desc->image.id));
  10114. SOKOL_ASSERT(color_images[i] && (color_images[i]->cmn.pixel_format == resolve_images[i]->cmn.pixel_format));
  10115. atts->d3d11.resolves[i].image = resolve_images[i];
  10116. }
  10117. }
  10118. SOKOL_ASSERT(0 == atts->d3d11.depth_stencil.image);
  10119. const sg_attachment_desc* ds_desc = &desc->depth_stencil;
  10120. if (ds_desc->image.id != SG_INVALID_ID) {
  10121. SOKOL_ASSERT(ds_img && (ds_img->slot.id == ds_desc->image.id));
  10122. SOKOL_ASSERT(_sg_is_valid_rendertarget_depth_format(ds_img->cmn.pixel_format));
  10123. atts->d3d11.depth_stencil.image = ds_img;
  10124. }
  10125. // create render-target views
  10126. for (int i = 0; i < atts->cmn.num_colors; i++) {
  10127. const _sg_attachment_common_t* cmn_color_att = &atts->cmn.colors[i];
  10128. const _sg_image_t* color_img = color_images[i];
  10129. SOKOL_ASSERT(0 == atts->d3d11.colors[i].view.rtv);
  10130. const bool msaa = color_img->cmn.sample_count > 1;
  10131. D3D11_RENDER_TARGET_VIEW_DESC d3d11_rtv_desc;
  10132. _sg_clear(&d3d11_rtv_desc, sizeof(d3d11_rtv_desc));
  10133. d3d11_rtv_desc.Format = _sg_d3d11_rtv_pixel_format(color_img->cmn.pixel_format);
  10134. if (color_img->cmn.type == SG_IMAGETYPE_2D) {
  10135. if (msaa) {
  10136. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
  10137. } else {
  10138. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
  10139. d3d11_rtv_desc.Texture2D.MipSlice = (UINT)cmn_color_att->mip_level;
  10140. }
  10141. } else if ((color_img->cmn.type == SG_IMAGETYPE_CUBE) || (color_img->cmn.type == SG_IMAGETYPE_ARRAY)) {
  10142. if (msaa) {
  10143. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY;
  10144. d3d11_rtv_desc.Texture2DMSArray.FirstArraySlice = (UINT)cmn_color_att->slice;
  10145. d3d11_rtv_desc.Texture2DMSArray.ArraySize = 1;
  10146. } else {
  10147. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
  10148. d3d11_rtv_desc.Texture2DArray.MipSlice = (UINT)cmn_color_att->mip_level;
  10149. d3d11_rtv_desc.Texture2DArray.FirstArraySlice = (UINT)cmn_color_att->slice;
  10150. d3d11_rtv_desc.Texture2DArray.ArraySize = 1;
  10151. }
  10152. } else {
  10153. SOKOL_ASSERT(color_img->cmn.type == SG_IMAGETYPE_3D);
  10154. SOKOL_ASSERT(!msaa);
  10155. d3d11_rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D;
  10156. d3d11_rtv_desc.Texture3D.MipSlice = (UINT)cmn_color_att->mip_level;
  10157. d3d11_rtv_desc.Texture3D.FirstWSlice = (UINT)cmn_color_att->slice;
  10158. d3d11_rtv_desc.Texture3D.WSize = 1;
  10159. }
  10160. SOKOL_ASSERT(color_img->d3d11.res);
  10161. HRESULT hr = _sg_d3d11_CreateRenderTargetView(_sg.d3d11.dev, color_img->d3d11.res, &d3d11_rtv_desc, &atts->d3d11.colors[i].view.rtv);
  10162. if (!(SUCCEEDED(hr) && atts->d3d11.colors[i].view.rtv)) {
  10163. _SG_ERROR(D3D11_CREATE_RTV_FAILED);
  10164. return SG_RESOURCESTATE_FAILED;
  10165. }
  10166. _sg_d3d11_setlabel(atts->d3d11.colors[i].view.rtv, desc->label);
  10167. }
  10168. SOKOL_ASSERT(0 == atts->d3d11.depth_stencil.view.dsv);
  10169. if (ds_desc->image.id != SG_INVALID_ID) {
  10170. const _sg_attachment_common_t* cmn_ds_att = &atts->cmn.depth_stencil;
  10171. const bool msaa = ds_img->cmn.sample_count > 1;
  10172. D3D11_DEPTH_STENCIL_VIEW_DESC d3d11_dsv_desc;
  10173. _sg_clear(&d3d11_dsv_desc, sizeof(d3d11_dsv_desc));
  10174. d3d11_dsv_desc.Format = _sg_d3d11_dsv_pixel_format(ds_img->cmn.pixel_format);
  10175. SOKOL_ASSERT(ds_img && ds_img->cmn.type != SG_IMAGETYPE_3D);
  10176. if (ds_img->cmn.type == SG_IMAGETYPE_2D) {
  10177. if (msaa) {
  10178. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
  10179. } else {
  10180. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
  10181. d3d11_dsv_desc.Texture2D.MipSlice = (UINT)cmn_ds_att->mip_level;
  10182. }
  10183. } else if ((ds_img->cmn.type == SG_IMAGETYPE_CUBE) || (ds_img->cmn.type == SG_IMAGETYPE_ARRAY)) {
  10184. if (msaa) {
  10185. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY;
  10186. d3d11_dsv_desc.Texture2DMSArray.FirstArraySlice = (UINT)cmn_ds_att->slice;
  10187. d3d11_dsv_desc.Texture2DMSArray.ArraySize = 1;
  10188. } else {
  10189. d3d11_dsv_desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
  10190. d3d11_dsv_desc.Texture2DArray.MipSlice = (UINT)cmn_ds_att->mip_level;
  10191. d3d11_dsv_desc.Texture2DArray.FirstArraySlice = (UINT)cmn_ds_att->slice;
  10192. d3d11_dsv_desc.Texture2DArray.ArraySize = 1;
  10193. }
  10194. }
  10195. SOKOL_ASSERT(ds_img->d3d11.res);
  10196. HRESULT hr = _sg_d3d11_CreateDepthStencilView(_sg.d3d11.dev, ds_img->d3d11.res, &d3d11_dsv_desc, &atts->d3d11.depth_stencil.view.dsv);
  10197. if (!(SUCCEEDED(hr) && atts->d3d11.depth_stencil.view.dsv)) {
  10198. _SG_ERROR(D3D11_CREATE_DSV_FAILED);
  10199. return SG_RESOURCESTATE_FAILED;
  10200. }
  10201. _sg_d3d11_setlabel(atts->d3d11.depth_stencil.view.dsv, desc->label);
  10202. }
  10203. return SG_RESOURCESTATE_VALID;
  10204. }
  10205. _SOKOL_PRIVATE void _sg_d3d11_discard_attachments(_sg_attachments_t* atts) {
  10206. SOKOL_ASSERT(atts);
  10207. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  10208. if (atts->d3d11.colors[i].view.rtv) {
  10209. _sg_d3d11_Release(atts->d3d11.colors[i].view.rtv);
  10210. }
  10211. if (atts->d3d11.resolves[i].view.rtv) {
  10212. _sg_d3d11_Release(atts->d3d11.resolves[i].view.rtv);
  10213. }
  10214. }
  10215. if (atts->d3d11.depth_stencil.view.dsv) {
  10216. _sg_d3d11_Release(atts->d3d11.depth_stencil.view.dsv);
  10217. }
  10218. }
  10219. _SOKOL_PRIVATE _sg_image_t* _sg_d3d11_attachments_color_image(const _sg_attachments_t* atts, int index) {
  10220. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  10221. return atts->d3d11.colors[index].image;
  10222. }
  10223. _SOKOL_PRIVATE _sg_image_t* _sg_d3d11_attachments_resolve_image(const _sg_attachments_t* atts, int index) {
  10224. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  10225. return atts->d3d11.resolves[index].image;
  10226. }
  10227. _SOKOL_PRIVATE _sg_image_t* _sg_d3d11_attachments_ds_image(const _sg_attachments_t* atts) {
  10228. SOKOL_ASSERT(atts);
  10229. return atts->d3d11.depth_stencil.image;
  10230. }
  10231. _SOKOL_PRIVATE void _sg_d3d11_begin_pass(const sg_pass* pass) {
  10232. SOKOL_ASSERT(pass);
  10233. const _sg_attachments_t* atts = _sg.cur_pass.atts;
  10234. const sg_swapchain* swapchain = &pass->swapchain;
  10235. const sg_pass_action* action = &pass->action;
  10236. int num_rtvs = 0;
  10237. ID3D11RenderTargetView* rtvs[SG_MAX_COLOR_ATTACHMENTS] = { 0 };
  10238. ID3D11DepthStencilView* dsv = 0;
  10239. _sg.d3d11.cur_pass.render_view = 0;
  10240. _sg.d3d11.cur_pass.resolve_view = 0;
  10241. if (atts) {
  10242. num_rtvs = atts->cmn.num_colors;
  10243. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  10244. rtvs[i] = atts->d3d11.colors[i].view.rtv;
  10245. }
  10246. dsv = atts->d3d11.depth_stencil.view.dsv;
  10247. } else {
  10248. // NOTE: depth-stencil-view is optional
  10249. SOKOL_ASSERT(swapchain->d3d11.render_view);
  10250. num_rtvs = 1;
  10251. rtvs[0] = (ID3D11RenderTargetView*) swapchain->d3d11.render_view;
  10252. dsv = (ID3D11DepthStencilView*) swapchain->d3d11.depth_stencil_view;
  10253. _sg.d3d11.cur_pass.render_view = (ID3D11RenderTargetView*) swapchain->d3d11.render_view;
  10254. _sg.d3d11.cur_pass.resolve_view = (ID3D11RenderTargetView*) swapchain->d3d11.resolve_view;
  10255. }
  10256. // apply the render-target- and depth-stencil-views
  10257. _sg_d3d11_OMSetRenderTargets(_sg.d3d11.ctx, SG_MAX_COLOR_ATTACHMENTS, rtvs, dsv);
  10258. _sg_stats_add(d3d11.pass.num_om_set_render_targets, 1);
  10259. // set viewport and scissor rect to cover whole screen
  10260. D3D11_VIEWPORT vp;
  10261. _sg_clear(&vp, sizeof(vp));
  10262. vp.Width = (FLOAT) _sg.cur_pass.width;
  10263. vp.Height = (FLOAT) _sg.cur_pass.height;
  10264. vp.MaxDepth = 1.0f;
  10265. _sg_d3d11_RSSetViewports(_sg.d3d11.ctx, 1, &vp);
  10266. D3D11_RECT rect;
  10267. rect.left = 0;
  10268. rect.top = 0;
  10269. rect.right = _sg.cur_pass.width;
  10270. rect.bottom = _sg.cur_pass.height;
  10271. _sg_d3d11_RSSetScissorRects(_sg.d3d11.ctx, 1, &rect);
  10272. // perform clear action
  10273. for (int i = 0; i < num_rtvs; i++) {
  10274. if (action->colors[i].load_action == SG_LOADACTION_CLEAR) {
  10275. _sg_d3d11_ClearRenderTargetView(_sg.d3d11.ctx, rtvs[i], (float*)&action->colors[i].clear_value);
  10276. _sg_stats_add(d3d11.pass.num_clear_render_target_view, 1);
  10277. }
  10278. }
  10279. UINT ds_flags = 0;
  10280. if (action->depth.load_action == SG_LOADACTION_CLEAR) {
  10281. ds_flags |= D3D11_CLEAR_DEPTH;
  10282. }
  10283. if (action->stencil.load_action == SG_LOADACTION_CLEAR) {
  10284. ds_flags |= D3D11_CLEAR_STENCIL;
  10285. }
  10286. if ((0 != ds_flags) && dsv) {
  10287. _sg_d3d11_ClearDepthStencilView(_sg.d3d11.ctx, dsv, ds_flags, action->depth.clear_value, action->stencil.clear_value);
  10288. _sg_stats_add(d3d11.pass.num_clear_depth_stencil_view, 1);
  10289. }
  10290. }
  10291. // D3D11CalcSubresource only exists for C++
  10292. _SOKOL_PRIVATE UINT _sg_d3d11_calcsubresource(UINT mip_slice, UINT array_slice, UINT mip_levels) {
  10293. return mip_slice + array_slice * mip_levels;
  10294. }
  10295. _SOKOL_PRIVATE void _sg_d3d11_end_pass(void) {
  10296. SOKOL_ASSERT(_sg.d3d11.ctx);
  10297. // need to resolve MSAA render attachments into texture?
  10298. if (_sg.cur_pass.atts_id.id != SG_INVALID_ID) {
  10299. // ...for offscreen pass...
  10300. SOKOL_ASSERT(_sg.cur_pass.atts && _sg.cur_pass.atts->slot.id == _sg.cur_pass.atts_id.id);
  10301. for (int i = 0; i < _sg.cur_pass.atts->cmn.num_colors; i++) {
  10302. const _sg_image_t* resolve_img = _sg.cur_pass.atts->d3d11.resolves[i].image;
  10303. if (resolve_img) {
  10304. const _sg_image_t* color_img = _sg.cur_pass.atts->d3d11.colors[i].image;
  10305. const _sg_attachment_common_t* cmn_color_att = &_sg.cur_pass.atts->cmn.colors[i];
  10306. const _sg_attachment_common_t* cmn_resolve_att = &_sg.cur_pass.atts->cmn.resolves[i];
  10307. SOKOL_ASSERT(resolve_img->slot.id == cmn_resolve_att->image_id.id);
  10308. SOKOL_ASSERT(color_img && (color_img->slot.id == cmn_color_att->image_id.id));
  10309. SOKOL_ASSERT(color_img->cmn.sample_count > 1);
  10310. SOKOL_ASSERT(resolve_img->cmn.sample_count == 1);
  10311. const UINT src_subres = _sg_d3d11_calcsubresource(
  10312. (UINT)cmn_color_att->mip_level,
  10313. (UINT)cmn_color_att->slice,
  10314. (UINT)color_img->cmn.num_mipmaps);
  10315. const UINT dst_subres = _sg_d3d11_calcsubresource(
  10316. (UINT)cmn_resolve_att->mip_level,
  10317. (UINT)cmn_resolve_att->slice,
  10318. (UINT)resolve_img->cmn.num_mipmaps);
  10319. _sg_d3d11_ResolveSubresource(_sg.d3d11.ctx,
  10320. resolve_img->d3d11.res,
  10321. dst_subres,
  10322. color_img->d3d11.res,
  10323. src_subres,
  10324. color_img->d3d11.format);
  10325. _sg_stats_add(d3d11.pass.num_resolve_subresource, 1);
  10326. }
  10327. }
  10328. } else {
  10329. // ...for swapchain pass...
  10330. if (_sg.d3d11.cur_pass.resolve_view) {
  10331. SOKOL_ASSERT(_sg.d3d11.cur_pass.render_view);
  10332. SOKOL_ASSERT(_sg.cur_pass.swapchain.sample_count > 1);
  10333. SOKOL_ASSERT(_sg.cur_pass.swapchain.color_fmt > SG_PIXELFORMAT_NONE);
  10334. ID3D11Resource* d3d11_render_res = 0;
  10335. ID3D11Resource* d3d11_resolve_res = 0;
  10336. _sg_d3d11_GetResource((ID3D11View*)_sg.d3d11.cur_pass.render_view, &d3d11_render_res);
  10337. _sg_d3d11_GetResource((ID3D11View*)_sg.d3d11.cur_pass.resolve_view, &d3d11_resolve_res);
  10338. SOKOL_ASSERT(d3d11_render_res);
  10339. SOKOL_ASSERT(d3d11_resolve_res);
  10340. const sg_pixel_format color_fmt = _sg.cur_pass.swapchain.color_fmt;
  10341. _sg_d3d11_ResolveSubresource(_sg.d3d11.ctx, d3d11_resolve_res, 0, d3d11_render_res, 0, _sg_d3d11_rtv_pixel_format(color_fmt));
  10342. _sg_d3d11_Release(d3d11_render_res);
  10343. _sg_d3d11_Release(d3d11_resolve_res);
  10344. _sg_stats_add(d3d11.pass.num_resolve_subresource, 1);
  10345. }
  10346. }
  10347. _sg.d3d11.cur_pass.render_view = 0;
  10348. _sg.d3d11.cur_pass.resolve_view = 0;
  10349. _sg.d3d11.cur_pipeline = 0;
  10350. _sg.d3d11.cur_pipeline_id.id = SG_INVALID_ID;
  10351. _sg_d3d11_clear_state();
  10352. }
  10353. _SOKOL_PRIVATE void _sg_d3d11_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  10354. SOKOL_ASSERT(_sg.d3d11.ctx);
  10355. D3D11_VIEWPORT vp;
  10356. vp.TopLeftX = (FLOAT) x;
  10357. vp.TopLeftY = (FLOAT) (origin_top_left ? y : (_sg.cur_pass.height - (y + h)));
  10358. vp.Width = (FLOAT) w;
  10359. vp.Height = (FLOAT) h;
  10360. vp.MinDepth = 0.0f;
  10361. vp.MaxDepth = 1.0f;
  10362. _sg_d3d11_RSSetViewports(_sg.d3d11.ctx, 1, &vp);
  10363. }
  10364. _SOKOL_PRIVATE void _sg_d3d11_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  10365. SOKOL_ASSERT(_sg.d3d11.ctx);
  10366. D3D11_RECT rect;
  10367. rect.left = x;
  10368. rect.top = (origin_top_left ? y : (_sg.cur_pass.height - (y + h)));
  10369. rect.right = x + w;
  10370. rect.bottom = origin_top_left ? (y + h) : (_sg.cur_pass.height - y);
  10371. _sg_d3d11_RSSetScissorRects(_sg.d3d11.ctx, 1, &rect);
  10372. }
  10373. _SOKOL_PRIVATE void _sg_d3d11_apply_pipeline(_sg_pipeline_t* pip) {
  10374. SOKOL_ASSERT(pip);
  10375. SOKOL_ASSERT(pip->shader && (pip->cmn.shader_id.id == pip->shader->slot.id));
  10376. SOKOL_ASSERT(_sg.d3d11.ctx);
  10377. SOKOL_ASSERT(pip->d3d11.rs && pip->d3d11.bs && pip->d3d11.dss);
  10378. _sg.d3d11.cur_pipeline = pip;
  10379. _sg.d3d11.cur_pipeline_id.id = pip->slot.id;
  10380. _sg.d3d11.use_indexed_draw = (pip->d3d11.index_format != DXGI_FORMAT_UNKNOWN);
  10381. _sg.d3d11.use_instanced_draw = pip->cmn.use_instanced_draw;
  10382. _sg_d3d11_RSSetState(_sg.d3d11.ctx, pip->d3d11.rs);
  10383. _sg_d3d11_OMSetDepthStencilState(_sg.d3d11.ctx, pip->d3d11.dss, pip->d3d11.stencil_ref);
  10384. _sg_d3d11_OMSetBlendState(_sg.d3d11.ctx, pip->d3d11.bs, (float*)&pip->cmn.blend_color, 0xFFFFFFFF);
  10385. _sg_d3d11_IASetPrimitiveTopology(_sg.d3d11.ctx, pip->d3d11.topology);
  10386. _sg_d3d11_IASetInputLayout(_sg.d3d11.ctx, pip->d3d11.il);
  10387. _sg_d3d11_VSSetShader(_sg.d3d11.ctx, pip->shader->d3d11.vs, NULL, 0);
  10388. _sg_d3d11_VSSetConstantBuffers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UB_BINDINGS, pip->shader->d3d11.vs_cbufs);
  10389. _sg_d3d11_PSSetShader(_sg.d3d11.ctx, pip->shader->d3d11.fs, NULL, 0);
  10390. _sg_d3d11_PSSetConstantBuffers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_UB_BINDINGS, pip->shader->d3d11.fs_cbufs);
  10391. _sg_stats_add(d3d11.pipeline.num_rs_set_state, 1);
  10392. _sg_stats_add(d3d11.pipeline.num_om_set_depth_stencil_state, 1);
  10393. _sg_stats_add(d3d11.pipeline.num_om_set_blend_state, 1);
  10394. _sg_stats_add(d3d11.pipeline.num_ia_set_primitive_topology, 1);
  10395. _sg_stats_add(d3d11.pipeline.num_ia_set_input_layout, 1);
  10396. _sg_stats_add(d3d11.pipeline.num_vs_set_shader, 1);
  10397. _sg_stats_add(d3d11.pipeline.num_vs_set_constant_buffers, 1);
  10398. _sg_stats_add(d3d11.pipeline.num_ps_set_shader, 1);
  10399. _sg_stats_add(d3d11.pipeline.num_ps_set_constant_buffers, 1);
  10400. }
  10401. _SOKOL_PRIVATE bool _sg_d3d11_apply_bindings(_sg_bindings_t* bnd) {
  10402. SOKOL_ASSERT(bnd);
  10403. SOKOL_ASSERT(bnd->pip && bnd->pip->shader);
  10404. SOKOL_ASSERT(bnd->pip->shader->slot.id == bnd->pip->cmn.shader_id.id);
  10405. SOKOL_ASSERT(_sg.d3d11.ctx);
  10406. const _sg_shader_t* shd = bnd->pip->shader;
  10407. // gather all the D3D11 resources into arrays
  10408. ID3D11Buffer* d3d11_ib = bnd->ib ? bnd->ib->d3d11.buf : 0;
  10409. ID3D11Buffer* d3d11_vbs[SG_MAX_VERTEXBUFFER_BINDSLOTS] = {0};
  10410. UINT d3d11_vb_offsets[SG_MAX_VERTEXBUFFER_BINDSLOTS] = {0};
  10411. ID3D11ShaderResourceView* d3d11_vs_srvs[_SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS] = {0};
  10412. ID3D11ShaderResourceView* d3d11_fs_srvs[_SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS] = {0};
  10413. ID3D11SamplerState* d3d11_vs_smps[_SG_D3D11_MAX_STAGE_SMP_BINDINGS] = {0};
  10414. ID3D11SamplerState* d3d11_fs_smps[_SG_D3D11_MAX_STAGE_SMP_BINDINGS] = {0};
  10415. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  10416. const _sg_buffer_t* vb = bnd->vbs[i];
  10417. if (vb == 0) {
  10418. continue;
  10419. }
  10420. SOKOL_ASSERT(vb->d3d11.buf);
  10421. d3d11_vbs[i] = vb->d3d11.buf;
  10422. d3d11_vb_offsets[i] = (UINT)bnd->vb_offsets[i];
  10423. }
  10424. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  10425. const _sg_image_t* img = bnd->imgs[i];
  10426. if (img == 0) {
  10427. continue;
  10428. }
  10429. const sg_shader_stage stage = shd->cmn.images[i].stage;
  10430. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT));
  10431. const uint8_t d3d11_slot = shd->d3d11.img_register_t_n[i];
  10432. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS);
  10433. SOKOL_ASSERT(img->d3d11.srv);
  10434. if (stage == SG_SHADERSTAGE_VERTEX) {
  10435. d3d11_vs_srvs[d3d11_slot] = img->d3d11.srv;
  10436. } else {
  10437. d3d11_fs_srvs[d3d11_slot] = img->d3d11.srv;
  10438. }
  10439. }
  10440. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  10441. const _sg_buffer_t* sbuf = bnd->sbufs[i];
  10442. if (sbuf == 0) {
  10443. continue;
  10444. }
  10445. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  10446. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT));
  10447. const uint8_t d3d11_slot = shd->d3d11.sbuf_register_t_n[i];
  10448. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS);
  10449. SOKOL_ASSERT(sbuf->d3d11.srv);
  10450. if (stage == SG_SHADERSTAGE_VERTEX) {
  10451. d3d11_vs_srvs[d3d11_slot] = sbuf->d3d11.srv;
  10452. } else {
  10453. d3d11_fs_srvs[d3d11_slot] = sbuf->d3d11.srv;
  10454. }
  10455. }
  10456. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  10457. const _sg_sampler_t* smp = bnd->smps[i];
  10458. if (smp == 0) {
  10459. continue;
  10460. }
  10461. const sg_shader_stage stage = shd->cmn.samplers[i].stage;
  10462. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT));
  10463. const uint8_t d3d11_slot = shd->d3d11.smp_register_s_n[i];
  10464. SOKOL_ASSERT(d3d11_slot < _SG_D3D11_MAX_STAGE_SMP_BINDINGS);
  10465. SOKOL_ASSERT(smp->d3d11.smp);
  10466. if (stage == SG_SHADERSTAGE_VERTEX) {
  10467. d3d11_vs_smps[d3d11_slot] = smp->d3d11.smp;
  10468. } else {
  10469. d3d11_fs_smps[d3d11_slot] = smp->d3d11.smp;
  10470. }
  10471. }
  10472. _sg_d3d11_IASetVertexBuffers(_sg.d3d11.ctx, 0, SG_MAX_VERTEXBUFFER_BINDSLOTS, d3d11_vbs, bnd->pip->d3d11.vb_strides, d3d11_vb_offsets);
  10473. _sg_d3d11_IASetIndexBuffer(_sg.d3d11.ctx, d3d11_ib, bnd->pip->d3d11.index_format, (UINT)bnd->ib_offset);
  10474. _sg_d3d11_VSSetShaderResources(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS, d3d11_vs_srvs);
  10475. _sg_d3d11_PSSetShaderResources(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS, d3d11_fs_srvs);
  10476. _sg_d3d11_VSSetSamplers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SMP_BINDINGS, d3d11_vs_smps);
  10477. _sg_d3d11_PSSetSamplers(_sg.d3d11.ctx, 0, _SG_D3D11_MAX_STAGE_SMP_BINDINGS, d3d11_fs_smps);
  10478. _sg_stats_add(d3d11.bindings.num_ia_set_vertex_buffers, 1);
  10479. _sg_stats_add(d3d11.bindings.num_ia_set_index_buffer, 1);
  10480. _sg_stats_add(d3d11.bindings.num_vs_set_shader_resources, 1);
  10481. _sg_stats_add(d3d11.bindings.num_ps_set_shader_resources, 1);
  10482. _sg_stats_add(d3d11.bindings.num_vs_set_samplers, 1);
  10483. _sg_stats_add(d3d11.bindings.num_ps_set_samplers, 1);
  10484. return true;
  10485. }
  10486. _SOKOL_PRIVATE void _sg_d3d11_apply_uniforms(int ub_slot, const sg_range* data) {
  10487. SOKOL_ASSERT(_sg.d3d11.ctx);
  10488. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  10489. SOKOL_ASSERT(_sg.d3d11.cur_pipeline && _sg.d3d11.cur_pipeline->slot.id == _sg.d3d11.cur_pipeline_id.id);
  10490. const _sg_shader_t* shd = _sg.d3d11.cur_pipeline->shader;
  10491. SOKOL_ASSERT(shd && (shd->slot.id == _sg.d3d11.cur_pipeline->cmn.shader_id.id));
  10492. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  10493. ID3D11Buffer* cbuf = shd->d3d11.all_cbufs[ub_slot];
  10494. SOKOL_ASSERT(cbuf);
  10495. _sg_d3d11_UpdateSubresource(_sg.d3d11.ctx, (ID3D11Resource*)cbuf, 0, NULL, data->ptr, 0, 0);
  10496. _sg_stats_add(d3d11.uniforms.num_update_subresource, 1);
  10497. }
  10498. _SOKOL_PRIVATE void _sg_d3d11_draw(int base_element, int num_elements, int num_instances) {
  10499. const bool use_instanced_draw = (num_instances > 1) || (_sg.d3d11.use_instanced_draw);
  10500. if (_sg.d3d11.use_indexed_draw) {
  10501. if (use_instanced_draw) {
  10502. _sg_d3d11_DrawIndexedInstanced(_sg.d3d11.ctx, (UINT)num_elements, (UINT)num_instances, (UINT)base_element, 0, 0);
  10503. _sg_stats_add(d3d11.draw.num_draw_indexed_instanced, 1);
  10504. } else {
  10505. _sg_d3d11_DrawIndexed(_sg.d3d11.ctx, (UINT)num_elements, (UINT)base_element, 0);
  10506. _sg_stats_add(d3d11.draw.num_draw_indexed, 1);
  10507. }
  10508. } else {
  10509. if (use_instanced_draw) {
  10510. _sg_d3d11_DrawInstanced(_sg.d3d11.ctx, (UINT)num_elements, (UINT)num_instances, (UINT)base_element, 0);
  10511. _sg_stats_add(d3d11.draw.num_draw_instanced, 1);
  10512. } else {
  10513. _sg_d3d11_Draw(_sg.d3d11.ctx, (UINT)num_elements, (UINT)base_element);
  10514. _sg_stats_add(d3d11.draw.num_draw, 1);
  10515. }
  10516. }
  10517. }
  10518. _SOKOL_PRIVATE void _sg_d3d11_commit(void) {
  10519. // empty
  10520. }
  10521. _SOKOL_PRIVATE void _sg_d3d11_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  10522. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  10523. SOKOL_ASSERT(_sg.d3d11.ctx);
  10524. SOKOL_ASSERT(buf->d3d11.buf);
  10525. D3D11_MAPPED_SUBRESOURCE d3d11_msr;
  10526. HRESULT hr = _sg_d3d11_Map(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0, D3D11_MAP_WRITE_DISCARD, 0, &d3d11_msr);
  10527. _sg_stats_add(d3d11.num_map, 1);
  10528. if (SUCCEEDED(hr)) {
  10529. memcpy(d3d11_msr.pData, data->ptr, data->size);
  10530. _sg_d3d11_Unmap(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0);
  10531. _sg_stats_add(d3d11.num_unmap, 1);
  10532. } else {
  10533. _SG_ERROR(D3D11_MAP_FOR_UPDATE_BUFFER_FAILED);
  10534. }
  10535. }
  10536. _SOKOL_PRIVATE void _sg_d3d11_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  10537. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  10538. SOKOL_ASSERT(_sg.d3d11.ctx);
  10539. SOKOL_ASSERT(buf->d3d11.buf);
  10540. D3D11_MAP map_type = new_frame ? D3D11_MAP_WRITE_DISCARD : D3D11_MAP_WRITE_NO_OVERWRITE;
  10541. D3D11_MAPPED_SUBRESOURCE d3d11_msr;
  10542. HRESULT hr = _sg_d3d11_Map(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0, map_type, 0, &d3d11_msr);
  10543. _sg_stats_add(d3d11.num_map, 1);
  10544. if (SUCCEEDED(hr)) {
  10545. uint8_t* dst_ptr = (uint8_t*)d3d11_msr.pData + buf->cmn.append_pos;
  10546. memcpy(dst_ptr, data->ptr, data->size);
  10547. _sg_d3d11_Unmap(_sg.d3d11.ctx, (ID3D11Resource*)buf->d3d11.buf, 0);
  10548. _sg_stats_add(d3d11.num_unmap, 1);
  10549. } else {
  10550. _SG_ERROR(D3D11_MAP_FOR_APPEND_BUFFER_FAILED);
  10551. }
  10552. }
  10553. // see: https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-subresources
  10554. // also see: https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-d3d11calcsubresource
  10555. _SOKOL_PRIVATE void _sg_d3d11_update_image(_sg_image_t* img, const sg_image_data* data) {
  10556. SOKOL_ASSERT(img && data);
  10557. SOKOL_ASSERT(_sg.d3d11.ctx);
  10558. SOKOL_ASSERT(img->d3d11.res);
  10559. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6:1;
  10560. const int num_slices = (img->cmn.type == SG_IMAGETYPE_ARRAY) ? img->cmn.num_slices:1;
  10561. const int num_depth_slices = (img->cmn.type == SG_IMAGETYPE_3D) ? img->cmn.num_slices:1;
  10562. UINT subres_index = 0;
  10563. HRESULT hr;
  10564. D3D11_MAPPED_SUBRESOURCE d3d11_msr;
  10565. for (int face_index = 0; face_index < num_faces; face_index++) {
  10566. for (int slice_index = 0; slice_index < num_slices; slice_index++) {
  10567. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++, subres_index++) {
  10568. SOKOL_ASSERT(subres_index < (SG_MAX_MIPMAPS * SG_MAX_TEXTUREARRAY_LAYERS));
  10569. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  10570. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  10571. const int src_row_pitch = _sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  10572. const int src_depth_pitch = _sg_surface_pitch(img->cmn.pixel_format, mip_width, mip_height, 1);
  10573. const sg_range* subimg_data = &(data->subimage[face_index][mip_index]);
  10574. const size_t slice_size = subimg_data->size / (size_t)num_slices;
  10575. SOKOL_ASSERT(slice_size == (size_t)(src_depth_pitch * num_depth_slices));
  10576. const size_t slice_offset = slice_size * (size_t)slice_index;
  10577. const uint8_t* slice_ptr = ((const uint8_t*)subimg_data->ptr) + slice_offset;
  10578. hr = _sg_d3d11_Map(_sg.d3d11.ctx, img->d3d11.res, subres_index, D3D11_MAP_WRITE_DISCARD, 0, &d3d11_msr);
  10579. _sg_stats_add(d3d11.num_map, 1);
  10580. if (SUCCEEDED(hr)) {
  10581. const uint8_t* src_ptr = slice_ptr;
  10582. uint8_t* dst_ptr = (uint8_t*)d3d11_msr.pData;
  10583. for (int depth_index = 0; depth_index < num_depth_slices; depth_index++) {
  10584. if (src_row_pitch == (int)d3d11_msr.RowPitch) {
  10585. const size_t copy_size = slice_size / (size_t)num_depth_slices;
  10586. SOKOL_ASSERT((copy_size * (size_t)num_depth_slices) == slice_size);
  10587. memcpy(dst_ptr, src_ptr, copy_size);
  10588. } else {
  10589. SOKOL_ASSERT(src_row_pitch < (int)d3d11_msr.RowPitch);
  10590. const uint8_t* src_row_ptr = src_ptr;
  10591. uint8_t* dst_row_ptr = dst_ptr;
  10592. for (int row_index = 0; row_index < mip_height; row_index++) {
  10593. memcpy(dst_row_ptr, src_row_ptr, (size_t)src_row_pitch);
  10594. src_row_ptr += src_row_pitch;
  10595. dst_row_ptr += d3d11_msr.RowPitch;
  10596. }
  10597. }
  10598. src_ptr += src_depth_pitch;
  10599. dst_ptr += d3d11_msr.DepthPitch;
  10600. }
  10601. _sg_d3d11_Unmap(_sg.d3d11.ctx, img->d3d11.res, subres_index);
  10602. _sg_stats_add(d3d11.num_unmap, 1);
  10603. } else {
  10604. _SG_ERROR(D3D11_MAP_FOR_UPDATE_IMAGE_FAILED);
  10605. }
  10606. }
  10607. }
  10608. }
  10609. }
  10610. // ███ ███ ███████ ████████ █████ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  10611. // ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  10612. // ██ ████ ██ █████ ██ ███████ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  10613. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  10614. // ██ ██ ███████ ██ ██ ██ ███████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  10615. //
  10616. // >>metal backend
  10617. #elif defined(SOKOL_METAL)
  10618. #if __has_feature(objc_arc)
  10619. #define _SG_OBJC_RETAIN(obj) { }
  10620. #define _SG_OBJC_RELEASE(obj) { obj = nil; }
  10621. #else
  10622. #define _SG_OBJC_RETAIN(obj) { [obj retain]; }
  10623. #define _SG_OBJC_RELEASE(obj) { [obj release]; obj = nil; }
  10624. #endif
  10625. //-- enum translation functions ------------------------------------------------
  10626. _SOKOL_PRIVATE MTLLoadAction _sg_mtl_load_action(sg_load_action a) {
  10627. switch (a) {
  10628. case SG_LOADACTION_CLEAR: return MTLLoadActionClear;
  10629. case SG_LOADACTION_LOAD: return MTLLoadActionLoad;
  10630. case SG_LOADACTION_DONTCARE: return MTLLoadActionDontCare;
  10631. default: SOKOL_UNREACHABLE; return (MTLLoadAction)0;
  10632. }
  10633. }
  10634. _SOKOL_PRIVATE MTLStoreAction _sg_mtl_store_action(sg_store_action a, bool resolve) {
  10635. switch (a) {
  10636. case SG_STOREACTION_STORE:
  10637. if (resolve) {
  10638. return MTLStoreActionStoreAndMultisampleResolve;
  10639. } else {
  10640. return MTLStoreActionStore;
  10641. }
  10642. break;
  10643. case SG_STOREACTION_DONTCARE:
  10644. if (resolve) {
  10645. return MTLStoreActionMultisampleResolve;
  10646. } else {
  10647. return MTLStoreActionDontCare;
  10648. }
  10649. break;
  10650. default: SOKOL_UNREACHABLE; return (MTLStoreAction)0;
  10651. }
  10652. }
  10653. _SOKOL_PRIVATE MTLResourceOptions _sg_mtl_resource_options_storage_mode_managed_or_shared(void) {
  10654. #if defined(_SG_TARGET_MACOS)
  10655. if (_sg.mtl.use_shared_storage_mode) {
  10656. return MTLResourceStorageModeShared;
  10657. } else {
  10658. return MTLResourceStorageModeManaged;
  10659. }
  10660. #else
  10661. // MTLResourceStorageModeManaged is not even defined on iOS SDK
  10662. return MTLResourceStorageModeShared;
  10663. #endif
  10664. }
  10665. _SOKOL_PRIVATE MTLResourceOptions _sg_mtl_buffer_resource_options(sg_usage usg) {
  10666. switch (usg) {
  10667. case SG_USAGE_IMMUTABLE:
  10668. return _sg_mtl_resource_options_storage_mode_managed_or_shared();
  10669. case SG_USAGE_DYNAMIC:
  10670. case SG_USAGE_STREAM:
  10671. return MTLResourceCPUCacheModeWriteCombined | _sg_mtl_resource_options_storage_mode_managed_or_shared();
  10672. default:
  10673. SOKOL_UNREACHABLE;
  10674. return 0;
  10675. }
  10676. }
  10677. _SOKOL_PRIVATE MTLVertexStepFunction _sg_mtl_step_function(sg_vertex_step step) {
  10678. switch (step) {
  10679. case SG_VERTEXSTEP_PER_VERTEX: return MTLVertexStepFunctionPerVertex;
  10680. case SG_VERTEXSTEP_PER_INSTANCE: return MTLVertexStepFunctionPerInstance;
  10681. default: SOKOL_UNREACHABLE; return (MTLVertexStepFunction)0;
  10682. }
  10683. }
  10684. _SOKOL_PRIVATE MTLVertexFormat _sg_mtl_vertex_format(sg_vertex_format fmt) {
  10685. switch (fmt) {
  10686. case SG_VERTEXFORMAT_FLOAT: return MTLVertexFormatFloat;
  10687. case SG_VERTEXFORMAT_FLOAT2: return MTLVertexFormatFloat2;
  10688. case SG_VERTEXFORMAT_FLOAT3: return MTLVertexFormatFloat3;
  10689. case SG_VERTEXFORMAT_FLOAT4: return MTLVertexFormatFloat4;
  10690. case SG_VERTEXFORMAT_BYTE4: return MTLVertexFormatChar4;
  10691. case SG_VERTEXFORMAT_BYTE4N: return MTLVertexFormatChar4Normalized;
  10692. case SG_VERTEXFORMAT_UBYTE4: return MTLVertexFormatUChar4;
  10693. case SG_VERTEXFORMAT_UBYTE4N: return MTLVertexFormatUChar4Normalized;
  10694. case SG_VERTEXFORMAT_SHORT2: return MTLVertexFormatShort2;
  10695. case SG_VERTEXFORMAT_SHORT2N: return MTLVertexFormatShort2Normalized;
  10696. case SG_VERTEXFORMAT_USHORT2N: return MTLVertexFormatUShort2Normalized;
  10697. case SG_VERTEXFORMAT_SHORT4: return MTLVertexFormatShort4;
  10698. case SG_VERTEXFORMAT_SHORT4N: return MTLVertexFormatShort4Normalized;
  10699. case SG_VERTEXFORMAT_USHORT4N: return MTLVertexFormatUShort4Normalized;
  10700. case SG_VERTEXFORMAT_UINT10_N2: return MTLVertexFormatUInt1010102Normalized;
  10701. case SG_VERTEXFORMAT_HALF2: return MTLVertexFormatHalf2;
  10702. case SG_VERTEXFORMAT_HALF4: return MTLVertexFormatHalf4;
  10703. default: SOKOL_UNREACHABLE; return (MTLVertexFormat)0;
  10704. }
  10705. }
  10706. _SOKOL_PRIVATE MTLPrimitiveType _sg_mtl_primitive_type(sg_primitive_type t) {
  10707. switch (t) {
  10708. case SG_PRIMITIVETYPE_POINTS: return MTLPrimitiveTypePoint;
  10709. case SG_PRIMITIVETYPE_LINES: return MTLPrimitiveTypeLine;
  10710. case SG_PRIMITIVETYPE_LINE_STRIP: return MTLPrimitiveTypeLineStrip;
  10711. case SG_PRIMITIVETYPE_TRIANGLES: return MTLPrimitiveTypeTriangle;
  10712. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return MTLPrimitiveTypeTriangleStrip;
  10713. default: SOKOL_UNREACHABLE; return (MTLPrimitiveType)0;
  10714. }
  10715. }
  10716. _SOKOL_PRIVATE MTLPixelFormat _sg_mtl_pixel_format(sg_pixel_format fmt) {
  10717. switch (fmt) {
  10718. case SG_PIXELFORMAT_R8: return MTLPixelFormatR8Unorm;
  10719. case SG_PIXELFORMAT_R8SN: return MTLPixelFormatR8Snorm;
  10720. case SG_PIXELFORMAT_R8UI: return MTLPixelFormatR8Uint;
  10721. case SG_PIXELFORMAT_R8SI: return MTLPixelFormatR8Sint;
  10722. case SG_PIXELFORMAT_R16: return MTLPixelFormatR16Unorm;
  10723. case SG_PIXELFORMAT_R16SN: return MTLPixelFormatR16Snorm;
  10724. case SG_PIXELFORMAT_R16UI: return MTLPixelFormatR16Uint;
  10725. case SG_PIXELFORMAT_R16SI: return MTLPixelFormatR16Sint;
  10726. case SG_PIXELFORMAT_R16F: return MTLPixelFormatR16Float;
  10727. case SG_PIXELFORMAT_RG8: return MTLPixelFormatRG8Unorm;
  10728. case SG_PIXELFORMAT_RG8SN: return MTLPixelFormatRG8Snorm;
  10729. case SG_PIXELFORMAT_RG8UI: return MTLPixelFormatRG8Uint;
  10730. case SG_PIXELFORMAT_RG8SI: return MTLPixelFormatRG8Sint;
  10731. case SG_PIXELFORMAT_R32UI: return MTLPixelFormatR32Uint;
  10732. case SG_PIXELFORMAT_R32SI: return MTLPixelFormatR32Sint;
  10733. case SG_PIXELFORMAT_R32F: return MTLPixelFormatR32Float;
  10734. case SG_PIXELFORMAT_RG16: return MTLPixelFormatRG16Unorm;
  10735. case SG_PIXELFORMAT_RG16SN: return MTLPixelFormatRG16Snorm;
  10736. case SG_PIXELFORMAT_RG16UI: return MTLPixelFormatRG16Uint;
  10737. case SG_PIXELFORMAT_RG16SI: return MTLPixelFormatRG16Sint;
  10738. case SG_PIXELFORMAT_RG16F: return MTLPixelFormatRG16Float;
  10739. case SG_PIXELFORMAT_RGBA8: return MTLPixelFormatRGBA8Unorm;
  10740. case SG_PIXELFORMAT_SRGB8A8: return MTLPixelFormatRGBA8Unorm_sRGB;
  10741. case SG_PIXELFORMAT_RGBA8SN: return MTLPixelFormatRGBA8Snorm;
  10742. case SG_PIXELFORMAT_RGBA8UI: return MTLPixelFormatRGBA8Uint;
  10743. case SG_PIXELFORMAT_RGBA8SI: return MTLPixelFormatRGBA8Sint;
  10744. case SG_PIXELFORMAT_BGRA8: return MTLPixelFormatBGRA8Unorm;
  10745. case SG_PIXELFORMAT_RGB10A2: return MTLPixelFormatRGB10A2Unorm;
  10746. case SG_PIXELFORMAT_RG11B10F: return MTLPixelFormatRG11B10Float;
  10747. case SG_PIXELFORMAT_RGB9E5: return MTLPixelFormatRGB9E5Float;
  10748. case SG_PIXELFORMAT_RG32UI: return MTLPixelFormatRG32Uint;
  10749. case SG_PIXELFORMAT_RG32SI: return MTLPixelFormatRG32Sint;
  10750. case SG_PIXELFORMAT_RG32F: return MTLPixelFormatRG32Float;
  10751. case SG_PIXELFORMAT_RGBA16: return MTLPixelFormatRGBA16Unorm;
  10752. case SG_PIXELFORMAT_RGBA16SN: return MTLPixelFormatRGBA16Snorm;
  10753. case SG_PIXELFORMAT_RGBA16UI: return MTLPixelFormatRGBA16Uint;
  10754. case SG_PIXELFORMAT_RGBA16SI: return MTLPixelFormatRGBA16Sint;
  10755. case SG_PIXELFORMAT_RGBA16F: return MTLPixelFormatRGBA16Float;
  10756. case SG_PIXELFORMAT_RGBA32UI: return MTLPixelFormatRGBA32Uint;
  10757. case SG_PIXELFORMAT_RGBA32SI: return MTLPixelFormatRGBA32Sint;
  10758. case SG_PIXELFORMAT_RGBA32F: return MTLPixelFormatRGBA32Float;
  10759. case SG_PIXELFORMAT_DEPTH: return MTLPixelFormatDepth32Float;
  10760. case SG_PIXELFORMAT_DEPTH_STENCIL: return MTLPixelFormatDepth32Float_Stencil8;
  10761. #if defined(_SG_TARGET_MACOS)
  10762. case SG_PIXELFORMAT_BC1_RGBA: return MTLPixelFormatBC1_RGBA;
  10763. case SG_PIXELFORMAT_BC2_RGBA: return MTLPixelFormatBC2_RGBA;
  10764. case SG_PIXELFORMAT_BC3_RGBA: return MTLPixelFormatBC3_RGBA;
  10765. case SG_PIXELFORMAT_BC3_SRGBA: return MTLPixelFormatBC3_RGBA_sRGB;
  10766. case SG_PIXELFORMAT_BC4_R: return MTLPixelFormatBC4_RUnorm;
  10767. case SG_PIXELFORMAT_BC4_RSN: return MTLPixelFormatBC4_RSnorm;
  10768. case SG_PIXELFORMAT_BC5_RG: return MTLPixelFormatBC5_RGUnorm;
  10769. case SG_PIXELFORMAT_BC5_RGSN: return MTLPixelFormatBC5_RGSnorm;
  10770. case SG_PIXELFORMAT_BC6H_RGBF: return MTLPixelFormatBC6H_RGBFloat;
  10771. case SG_PIXELFORMAT_BC6H_RGBUF: return MTLPixelFormatBC6H_RGBUfloat;
  10772. case SG_PIXELFORMAT_BC7_RGBA: return MTLPixelFormatBC7_RGBAUnorm;
  10773. case SG_PIXELFORMAT_BC7_SRGBA: return MTLPixelFormatBC7_RGBAUnorm_sRGB;
  10774. #else
  10775. case SG_PIXELFORMAT_ETC2_RGB8: return MTLPixelFormatETC2_RGB8;
  10776. case SG_PIXELFORMAT_ETC2_SRGB8: return MTLPixelFormatETC2_RGB8_sRGB;
  10777. case SG_PIXELFORMAT_ETC2_RGB8A1: return MTLPixelFormatETC2_RGB8A1;
  10778. case SG_PIXELFORMAT_ETC2_RGBA8: return MTLPixelFormatEAC_RGBA8;
  10779. case SG_PIXELFORMAT_ETC2_SRGB8A8: return MTLPixelFormatEAC_RGBA8_sRGB;
  10780. case SG_PIXELFORMAT_EAC_R11: return MTLPixelFormatEAC_R11Unorm;
  10781. case SG_PIXELFORMAT_EAC_R11SN: return MTLPixelFormatEAC_R11Snorm;
  10782. case SG_PIXELFORMAT_EAC_RG11: return MTLPixelFormatEAC_RG11Unorm;
  10783. case SG_PIXELFORMAT_EAC_RG11SN: return MTLPixelFormatEAC_RG11Snorm;
  10784. case SG_PIXELFORMAT_ASTC_4x4_RGBA: return MTLPixelFormatASTC_4x4_LDR;
  10785. case SG_PIXELFORMAT_ASTC_4x4_SRGBA: return MTLPixelFormatASTC_4x4_sRGB;
  10786. #endif
  10787. default: return MTLPixelFormatInvalid;
  10788. }
  10789. }
  10790. _SOKOL_PRIVATE MTLColorWriteMask _sg_mtl_color_write_mask(sg_color_mask m) {
  10791. MTLColorWriteMask mtl_mask = MTLColorWriteMaskNone;
  10792. if (m & SG_COLORMASK_R) {
  10793. mtl_mask |= MTLColorWriteMaskRed;
  10794. }
  10795. if (m & SG_COLORMASK_G) {
  10796. mtl_mask |= MTLColorWriteMaskGreen;
  10797. }
  10798. if (m & SG_COLORMASK_B) {
  10799. mtl_mask |= MTLColorWriteMaskBlue;
  10800. }
  10801. if (m & SG_COLORMASK_A) {
  10802. mtl_mask |= MTLColorWriteMaskAlpha;
  10803. }
  10804. return mtl_mask;
  10805. }
  10806. _SOKOL_PRIVATE MTLBlendOperation _sg_mtl_blend_op(sg_blend_op op) {
  10807. switch (op) {
  10808. case SG_BLENDOP_ADD: return MTLBlendOperationAdd;
  10809. case SG_BLENDOP_SUBTRACT: return MTLBlendOperationSubtract;
  10810. case SG_BLENDOP_REVERSE_SUBTRACT: return MTLBlendOperationReverseSubtract;
  10811. case SG_BLENDOP_MIN: return MTLBlendOperationMin;
  10812. case SG_BLENDOP_MAX: return MTLBlendOperationMax;
  10813. default: SOKOL_UNREACHABLE; return (MTLBlendOperation)0;
  10814. }
  10815. }
  10816. _SOKOL_PRIVATE MTLBlendFactor _sg_mtl_blend_factor(sg_blend_factor f) {
  10817. switch (f) {
  10818. case SG_BLENDFACTOR_ZERO: return MTLBlendFactorZero;
  10819. case SG_BLENDFACTOR_ONE: return MTLBlendFactorOne;
  10820. case SG_BLENDFACTOR_SRC_COLOR: return MTLBlendFactorSourceColor;
  10821. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return MTLBlendFactorOneMinusSourceColor;
  10822. case SG_BLENDFACTOR_SRC_ALPHA: return MTLBlendFactorSourceAlpha;
  10823. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return MTLBlendFactorOneMinusSourceAlpha;
  10824. case SG_BLENDFACTOR_DST_COLOR: return MTLBlendFactorDestinationColor;
  10825. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return MTLBlendFactorOneMinusDestinationColor;
  10826. case SG_BLENDFACTOR_DST_ALPHA: return MTLBlendFactorDestinationAlpha;
  10827. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return MTLBlendFactorOneMinusDestinationAlpha;
  10828. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return MTLBlendFactorSourceAlphaSaturated;
  10829. case SG_BLENDFACTOR_BLEND_COLOR: return MTLBlendFactorBlendColor;
  10830. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return MTLBlendFactorOneMinusBlendColor;
  10831. case SG_BLENDFACTOR_BLEND_ALPHA: return MTLBlendFactorBlendAlpha;
  10832. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return MTLBlendFactorOneMinusBlendAlpha;
  10833. default: SOKOL_UNREACHABLE; return (MTLBlendFactor)0;
  10834. }
  10835. }
  10836. _SOKOL_PRIVATE MTLCompareFunction _sg_mtl_compare_func(sg_compare_func f) {
  10837. switch (f) {
  10838. case SG_COMPAREFUNC_NEVER: return MTLCompareFunctionNever;
  10839. case SG_COMPAREFUNC_LESS: return MTLCompareFunctionLess;
  10840. case SG_COMPAREFUNC_EQUAL: return MTLCompareFunctionEqual;
  10841. case SG_COMPAREFUNC_LESS_EQUAL: return MTLCompareFunctionLessEqual;
  10842. case SG_COMPAREFUNC_GREATER: return MTLCompareFunctionGreater;
  10843. case SG_COMPAREFUNC_NOT_EQUAL: return MTLCompareFunctionNotEqual;
  10844. case SG_COMPAREFUNC_GREATER_EQUAL: return MTLCompareFunctionGreaterEqual;
  10845. case SG_COMPAREFUNC_ALWAYS: return MTLCompareFunctionAlways;
  10846. default: SOKOL_UNREACHABLE; return (MTLCompareFunction)0;
  10847. }
  10848. }
  10849. _SOKOL_PRIVATE MTLStencilOperation _sg_mtl_stencil_op(sg_stencil_op op) {
  10850. switch (op) {
  10851. case SG_STENCILOP_KEEP: return MTLStencilOperationKeep;
  10852. case SG_STENCILOP_ZERO: return MTLStencilOperationZero;
  10853. case SG_STENCILOP_REPLACE: return MTLStencilOperationReplace;
  10854. case SG_STENCILOP_INCR_CLAMP: return MTLStencilOperationIncrementClamp;
  10855. case SG_STENCILOP_DECR_CLAMP: return MTLStencilOperationDecrementClamp;
  10856. case SG_STENCILOP_INVERT: return MTLStencilOperationInvert;
  10857. case SG_STENCILOP_INCR_WRAP: return MTLStencilOperationIncrementWrap;
  10858. case SG_STENCILOP_DECR_WRAP: return MTLStencilOperationDecrementWrap;
  10859. default: SOKOL_UNREACHABLE; return (MTLStencilOperation)0;
  10860. }
  10861. }
  10862. _SOKOL_PRIVATE MTLCullMode _sg_mtl_cull_mode(sg_cull_mode m) {
  10863. switch (m) {
  10864. case SG_CULLMODE_NONE: return MTLCullModeNone;
  10865. case SG_CULLMODE_FRONT: return MTLCullModeFront;
  10866. case SG_CULLMODE_BACK: return MTLCullModeBack;
  10867. default: SOKOL_UNREACHABLE; return (MTLCullMode)0;
  10868. }
  10869. }
  10870. _SOKOL_PRIVATE MTLWinding _sg_mtl_winding(sg_face_winding w) {
  10871. switch (w) {
  10872. case SG_FACEWINDING_CW: return MTLWindingClockwise;
  10873. case SG_FACEWINDING_CCW: return MTLWindingCounterClockwise;
  10874. default: SOKOL_UNREACHABLE; return (MTLWinding)0;
  10875. }
  10876. }
  10877. _SOKOL_PRIVATE MTLIndexType _sg_mtl_index_type(sg_index_type t) {
  10878. switch (t) {
  10879. case SG_INDEXTYPE_UINT16: return MTLIndexTypeUInt16;
  10880. case SG_INDEXTYPE_UINT32: return MTLIndexTypeUInt32;
  10881. default: SOKOL_UNREACHABLE; return (MTLIndexType)0;
  10882. }
  10883. }
  10884. _SOKOL_PRIVATE int _sg_mtl_index_size(sg_index_type t) {
  10885. switch (t) {
  10886. case SG_INDEXTYPE_NONE: return 0;
  10887. case SG_INDEXTYPE_UINT16: return 2;
  10888. case SG_INDEXTYPE_UINT32: return 4;
  10889. default: SOKOL_UNREACHABLE; return 0;
  10890. }
  10891. }
  10892. _SOKOL_PRIVATE MTLTextureType _sg_mtl_texture_type(sg_image_type t) {
  10893. switch (t) {
  10894. case SG_IMAGETYPE_2D: return MTLTextureType2D;
  10895. case SG_IMAGETYPE_CUBE: return MTLTextureTypeCube;
  10896. case SG_IMAGETYPE_3D: return MTLTextureType3D;
  10897. case SG_IMAGETYPE_ARRAY: return MTLTextureType2DArray;
  10898. default: SOKOL_UNREACHABLE; return (MTLTextureType)0;
  10899. }
  10900. }
  10901. _SOKOL_PRIVATE MTLSamplerAddressMode _sg_mtl_address_mode(sg_wrap w) {
  10902. if (_sg.features.image_clamp_to_border) {
  10903. if (@available(macOS 12.0, iOS 14.0, *)) {
  10904. // border color feature available
  10905. switch (w) {
  10906. case SG_WRAP_REPEAT: return MTLSamplerAddressModeRepeat;
  10907. case SG_WRAP_CLAMP_TO_EDGE: return MTLSamplerAddressModeClampToEdge;
  10908. case SG_WRAP_CLAMP_TO_BORDER: return MTLSamplerAddressModeClampToBorderColor;
  10909. case SG_WRAP_MIRRORED_REPEAT: return MTLSamplerAddressModeMirrorRepeat;
  10910. default: SOKOL_UNREACHABLE; return (MTLSamplerAddressMode)0;
  10911. }
  10912. }
  10913. }
  10914. // fallthrough: clamp to border no supported
  10915. switch (w) {
  10916. case SG_WRAP_REPEAT: return MTLSamplerAddressModeRepeat;
  10917. case SG_WRAP_CLAMP_TO_EDGE: return MTLSamplerAddressModeClampToEdge;
  10918. case SG_WRAP_CLAMP_TO_BORDER: return MTLSamplerAddressModeClampToEdge;
  10919. case SG_WRAP_MIRRORED_REPEAT: return MTLSamplerAddressModeMirrorRepeat;
  10920. default: SOKOL_UNREACHABLE; return (MTLSamplerAddressMode)0;
  10921. }
  10922. }
  10923. _SOKOL_PRIVATE API_AVAILABLE(ios(14.0), macos(12.0)) MTLSamplerBorderColor _sg_mtl_border_color(sg_border_color c) {
  10924. switch (c) {
  10925. case SG_BORDERCOLOR_TRANSPARENT_BLACK: return MTLSamplerBorderColorTransparentBlack;
  10926. case SG_BORDERCOLOR_OPAQUE_BLACK: return MTLSamplerBorderColorOpaqueBlack;
  10927. case SG_BORDERCOLOR_OPAQUE_WHITE: return MTLSamplerBorderColorOpaqueWhite;
  10928. default: SOKOL_UNREACHABLE; return (MTLSamplerBorderColor)0;
  10929. }
  10930. }
  10931. _SOKOL_PRIVATE MTLSamplerMinMagFilter _sg_mtl_minmag_filter(sg_filter f) {
  10932. switch (f) {
  10933. case SG_FILTER_NEAREST:
  10934. return MTLSamplerMinMagFilterNearest;
  10935. case SG_FILTER_LINEAR:
  10936. return MTLSamplerMinMagFilterLinear;
  10937. default:
  10938. SOKOL_UNREACHABLE; return (MTLSamplerMinMagFilter)0;
  10939. }
  10940. }
  10941. _SOKOL_PRIVATE MTLSamplerMipFilter _sg_mtl_mipmap_filter(sg_filter f) {
  10942. switch (f) {
  10943. case SG_FILTER_NEAREST:
  10944. return MTLSamplerMipFilterNearest;
  10945. case SG_FILTER_LINEAR:
  10946. return MTLSamplerMipFilterLinear;
  10947. default:
  10948. SOKOL_UNREACHABLE; return (MTLSamplerMipFilter)0;
  10949. }
  10950. }
  10951. //-- a pool for all Metal resource objects, with deferred release queue ---------
  10952. _SOKOL_PRIVATE void _sg_mtl_init_pool(const sg_desc* desc) {
  10953. _sg.mtl.idpool.num_slots = 2 *
  10954. (
  10955. 2 * desc->buffer_pool_size +
  10956. 4 * desc->image_pool_size +
  10957. 1 * desc->sampler_pool_size +
  10958. 4 * desc->shader_pool_size +
  10959. 2 * desc->pipeline_pool_size +
  10960. desc->attachments_pool_size +
  10961. 128
  10962. );
  10963. _sg.mtl.idpool.pool = [NSMutableArray arrayWithCapacity:(NSUInteger)_sg.mtl.idpool.num_slots];
  10964. _SG_OBJC_RETAIN(_sg.mtl.idpool.pool);
  10965. NSNull* null = [NSNull null];
  10966. for (int i = 0; i < _sg.mtl.idpool.num_slots; i++) {
  10967. [_sg.mtl.idpool.pool addObject:null];
  10968. }
  10969. SOKOL_ASSERT([_sg.mtl.idpool.pool count] == (NSUInteger)_sg.mtl.idpool.num_slots);
  10970. // a queue of currently free slot indices
  10971. _sg.mtl.idpool.free_queue_top = 0;
  10972. _sg.mtl.idpool.free_queue = (int*)_sg_malloc_clear((size_t)_sg.mtl.idpool.num_slots * sizeof(int));
  10973. // pool slot 0 is reserved!
  10974. for (int i = _sg.mtl.idpool.num_slots-1; i >= 1; i--) {
  10975. _sg.mtl.idpool.free_queue[_sg.mtl.idpool.free_queue_top++] = i;
  10976. }
  10977. // a circular queue which holds release items (frame index when a resource is to be released, and the resource's pool index
  10978. _sg.mtl.idpool.release_queue_front = 0;
  10979. _sg.mtl.idpool.release_queue_back = 0;
  10980. _sg.mtl.idpool.release_queue = (_sg_mtl_release_item_t*)_sg_malloc_clear((size_t)_sg.mtl.idpool.num_slots * sizeof(_sg_mtl_release_item_t));
  10981. for (int i = 0; i < _sg.mtl.idpool.num_slots; i++) {
  10982. _sg.mtl.idpool.release_queue[i].frame_index = 0;
  10983. _sg.mtl.idpool.release_queue[i].slot_index = _SG_MTL_INVALID_SLOT_INDEX;
  10984. }
  10985. }
  10986. _SOKOL_PRIVATE void _sg_mtl_destroy_pool(void) {
  10987. _sg_free(_sg.mtl.idpool.release_queue); _sg.mtl.idpool.release_queue = 0;
  10988. _sg_free(_sg.mtl.idpool.free_queue); _sg.mtl.idpool.free_queue = 0;
  10989. _SG_OBJC_RELEASE(_sg.mtl.idpool.pool);
  10990. }
  10991. // get a new free resource pool slot
  10992. _SOKOL_PRIVATE int _sg_mtl_alloc_pool_slot(void) {
  10993. SOKOL_ASSERT(_sg.mtl.idpool.free_queue_top > 0);
  10994. const int slot_index = _sg.mtl.idpool.free_queue[--_sg.mtl.idpool.free_queue_top];
  10995. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  10996. return slot_index;
  10997. }
  10998. // put a free resource pool slot back into the free-queue
  10999. _SOKOL_PRIVATE void _sg_mtl_free_pool_slot(int slot_index) {
  11000. SOKOL_ASSERT(_sg.mtl.idpool.free_queue_top < _sg.mtl.idpool.num_slots);
  11001. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  11002. _sg.mtl.idpool.free_queue[_sg.mtl.idpool.free_queue_top++] = slot_index;
  11003. }
  11004. // add an MTLResource to the pool, return pool index or 0 if input was 'nil'
  11005. _SOKOL_PRIVATE int _sg_mtl_add_resource(id res) {
  11006. if (nil == res) {
  11007. return _SG_MTL_INVALID_SLOT_INDEX;
  11008. }
  11009. _sg_stats_add(metal.idpool.num_added, 1);
  11010. const int slot_index = _sg_mtl_alloc_pool_slot();
  11011. // NOTE: the NSMutableArray will take ownership of its items
  11012. SOKOL_ASSERT([NSNull null] == _sg.mtl.idpool.pool[(NSUInteger)slot_index]);
  11013. _sg.mtl.idpool.pool[(NSUInteger)slot_index] = res;
  11014. return slot_index;
  11015. }
  11016. /* mark an MTLResource for release, this will put the resource into the
  11017. deferred-release queue, and the resource will then be released N frames later,
  11018. the special pool index 0 will be ignored (this means that a nil
  11019. value was provided to _sg_mtl_add_resource()
  11020. */
  11021. _SOKOL_PRIVATE void _sg_mtl_release_resource(uint32_t frame_index, int slot_index) {
  11022. if (slot_index == _SG_MTL_INVALID_SLOT_INDEX) {
  11023. return;
  11024. }
  11025. _sg_stats_add(metal.idpool.num_released, 1);
  11026. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  11027. SOKOL_ASSERT([NSNull null] != _sg.mtl.idpool.pool[(NSUInteger)slot_index]);
  11028. int release_index = _sg.mtl.idpool.release_queue_front++;
  11029. if (_sg.mtl.idpool.release_queue_front >= _sg.mtl.idpool.num_slots) {
  11030. // wrap-around
  11031. _sg.mtl.idpool.release_queue_front = 0;
  11032. }
  11033. // release queue full?
  11034. SOKOL_ASSERT(_sg.mtl.idpool.release_queue_front != _sg.mtl.idpool.release_queue_back);
  11035. SOKOL_ASSERT(0 == _sg.mtl.idpool.release_queue[release_index].frame_index);
  11036. const uint32_t safe_to_release_frame_index = frame_index + SG_NUM_INFLIGHT_FRAMES + 1;
  11037. _sg.mtl.idpool.release_queue[release_index].frame_index = safe_to_release_frame_index;
  11038. _sg.mtl.idpool.release_queue[release_index].slot_index = slot_index;
  11039. }
  11040. // run garbage-collection pass on all resources in the release-queue
  11041. _SOKOL_PRIVATE void _sg_mtl_garbage_collect(uint32_t frame_index) {
  11042. while (_sg.mtl.idpool.release_queue_back != _sg.mtl.idpool.release_queue_front) {
  11043. if (frame_index < _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].frame_index) {
  11044. // don't need to check further, release-items past this are too young
  11045. break;
  11046. }
  11047. _sg_stats_add(metal.idpool.num_garbage_collected, 1);
  11048. // safe to release this resource
  11049. const int slot_index = _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].slot_index;
  11050. SOKOL_ASSERT((slot_index > 0) && (slot_index < _sg.mtl.idpool.num_slots));
  11051. // note: the NSMutableArray takes ownership of its items, assigning an NSNull object will
  11052. // release the object, no matter if using ARC or not
  11053. SOKOL_ASSERT(_sg.mtl.idpool.pool[(NSUInteger)slot_index] != [NSNull null]);
  11054. _sg.mtl.idpool.pool[(NSUInteger)slot_index] = [NSNull null];
  11055. // put the now free pool index back on the free queue
  11056. _sg_mtl_free_pool_slot(slot_index);
  11057. // reset the release queue slot and advance the back index
  11058. _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].frame_index = 0;
  11059. _sg.mtl.idpool.release_queue[_sg.mtl.idpool.release_queue_back].slot_index = _SG_MTL_INVALID_SLOT_INDEX;
  11060. _sg.mtl.idpool.release_queue_back++;
  11061. if (_sg.mtl.idpool.release_queue_back >= _sg.mtl.idpool.num_slots) {
  11062. // wrap-around
  11063. _sg.mtl.idpool.release_queue_back = 0;
  11064. }
  11065. }
  11066. }
  11067. _SOKOL_PRIVATE id _sg_mtl_id(int slot_index) {
  11068. return _sg.mtl.idpool.pool[(NSUInteger)slot_index];
  11069. }
  11070. _SOKOL_PRIVATE void _sg_mtl_clear_state_cache(void) {
  11071. _sg_clear(&_sg.mtl.state_cache, sizeof(_sg.mtl.state_cache));
  11072. }
  11073. // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf
  11074. _SOKOL_PRIVATE void _sg_mtl_init_caps(void) {
  11075. #if defined(_SG_TARGET_MACOS)
  11076. _sg.backend = SG_BACKEND_METAL_MACOS;
  11077. #elif defined(_SG_TARGET_IOS)
  11078. #if defined(_SG_TARGET_IOS_SIMULATOR)
  11079. _sg.backend = SG_BACKEND_METAL_SIMULATOR;
  11080. #else
  11081. _sg.backend = SG_BACKEND_METAL_IOS;
  11082. #endif
  11083. #endif
  11084. _sg.features.origin_top_left = true;
  11085. _sg.features.mrt_independent_blend_state = true;
  11086. _sg.features.mrt_independent_write_mask = true;
  11087. _sg.features.storage_buffer = true;
  11088. _sg.features.msaa_image_bindings = true;
  11089. _sg.features.image_clamp_to_border = false;
  11090. #if (MAC_OS_X_VERSION_MAX_ALLOWED >= 120000) || (__IPHONE_OS_VERSION_MAX_ALLOWED >= 140000)
  11091. if (@available(macOS 12.0, iOS 14.0, *)) {
  11092. _sg.features.image_clamp_to_border = [_sg.mtl.device supportsFamily:MTLGPUFamilyApple7]
  11093. || [_sg.mtl.device supportsFamily:MTLGPUFamilyMac2];
  11094. #if (MAC_OS_X_VERSION_MAX_ALLOWED >= 130000) || (__IPHONE_OS_VERSION_MAX_ALLOWED >= 160000)
  11095. if (!_sg.features.image_clamp_to_border) {
  11096. if (@available(macOS 13.0, iOS 16.0, *)) {
  11097. _sg.features.image_clamp_to_border = [_sg.mtl.device supportsFamily:MTLGPUFamilyMetal3];
  11098. }
  11099. }
  11100. #endif
  11101. }
  11102. #endif
  11103. #if defined(_SG_TARGET_MACOS)
  11104. _sg.limits.max_image_size_2d = 16 * 1024;
  11105. _sg.limits.max_image_size_cube = 16 * 1024;
  11106. _sg.limits.max_image_size_3d = 2 * 1024;
  11107. _sg.limits.max_image_size_array = 16 * 1024;
  11108. _sg.limits.max_image_array_layers = 2 * 1024;
  11109. #else
  11110. // FIXME: newer iOS devices support 16k textures
  11111. _sg.limits.max_image_size_2d = 8 * 1024;
  11112. _sg.limits.max_image_size_cube = 8 * 1024;
  11113. _sg.limits.max_image_size_3d = 2 * 1024;
  11114. _sg.limits.max_image_size_array = 8 * 1024;
  11115. _sg.limits.max_image_array_layers = 2 * 1024;
  11116. #endif
  11117. _sg.limits.max_vertex_attrs = SG_MAX_VERTEX_ATTRIBUTES;
  11118. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8]);
  11119. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8SN]);
  11120. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8UI]);
  11121. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R8SI]);
  11122. #if defined(_SG_TARGET_MACOS)
  11123. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16]);
  11124. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16SN]);
  11125. #else
  11126. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_R16]);
  11127. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_R16SN]);
  11128. #endif
  11129. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16UI]);
  11130. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_R16SI]);
  11131. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16F]);
  11132. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8]);
  11133. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8SN]);
  11134. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8UI]);
  11135. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG8SI]);
  11136. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  11137. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  11138. #if defined(_SG_TARGET_MACOS)
  11139. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R32F]);
  11140. #else
  11141. _sg_pixelformat_sbr(&_sg.formats[SG_PIXELFORMAT_R32F]);
  11142. #endif
  11143. #if defined(_SG_TARGET_MACOS)
  11144. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16]);
  11145. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16SN]);
  11146. #else
  11147. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RG16]);
  11148. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RG16SN]);
  11149. #endif
  11150. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16UI]);
  11151. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG16SI]);
  11152. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  11153. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  11154. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_SRGB8A8]);
  11155. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  11156. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  11157. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  11158. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_BGRA8]);
  11159. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB10A2]);
  11160. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  11161. #if defined(_SG_TARGET_MACOS)
  11162. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  11163. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  11164. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  11165. #else
  11166. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  11167. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  11168. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  11169. #endif
  11170. #if defined(_SG_TARGET_MACOS)
  11171. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  11172. #else
  11173. _sg_pixelformat_sbr(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  11174. #endif
  11175. #if defined(_SG_TARGET_MACOS)
  11176. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16]);
  11177. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16SN]);
  11178. #else
  11179. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RGBA16]);
  11180. _sg_pixelformat_sfbr(&_sg.formats[SG_PIXELFORMAT_RGBA16SN]);
  11181. #endif
  11182. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  11183. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  11184. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  11185. #if defined(_SG_TARGET_MACOS)
  11186. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  11187. _sg_pixelformat_srm(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  11188. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  11189. #else
  11190. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  11191. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  11192. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  11193. #endif
  11194. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH]);
  11195. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL]);
  11196. #if defined(_SG_TARGET_MACOS)
  11197. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC1_RGBA]);
  11198. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC2_RGBA]);
  11199. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_RGBA]);
  11200. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_SRGBA]);
  11201. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_R]);
  11202. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_RSN]);
  11203. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RG]);
  11204. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RGSN]);
  11205. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBF]);
  11206. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBUF]);
  11207. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_RGBA]);
  11208. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_SRGBA]);
  11209. #else
  11210. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8]);
  11211. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8]);
  11212. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8A1]);
  11213. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGBA8]);
  11214. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8A8]);
  11215. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11]);
  11216. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11SN]);
  11217. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11]);
  11218. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11SN]);
  11219. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_RGBA]);
  11220. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_SRGBA]);
  11221. #endif
  11222. }
  11223. //-- main Metal backend state and functions ------------------------------------
  11224. _SOKOL_PRIVATE void _sg_mtl_setup_backend(const sg_desc* desc) {
  11225. // assume already zero-initialized
  11226. SOKOL_ASSERT(desc);
  11227. SOKOL_ASSERT(desc->environment.metal.device);
  11228. SOKOL_ASSERT(desc->uniform_buffer_size > 0);
  11229. _sg_mtl_init_pool(desc);
  11230. _sg_mtl_clear_state_cache();
  11231. _sg.mtl.valid = true;
  11232. _sg.mtl.ub_size = desc->uniform_buffer_size;
  11233. _sg.mtl.sem = dispatch_semaphore_create(SG_NUM_INFLIGHT_FRAMES);
  11234. _sg.mtl.device = (__bridge id<MTLDevice>) desc->environment.metal.device;
  11235. _sg.mtl.cmd_queue = [_sg.mtl.device newCommandQueue];
  11236. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  11237. _sg.mtl.uniform_buffers[i] = [_sg.mtl.device
  11238. newBufferWithLength:(NSUInteger)_sg.mtl.ub_size
  11239. options:MTLResourceCPUCacheModeWriteCombined|MTLResourceStorageModeShared
  11240. ];
  11241. #if defined(SOKOL_DEBUG)
  11242. _sg.mtl.uniform_buffers[i].label = [NSString stringWithFormat:@"sg-uniform-buffer.%d", i];
  11243. #endif
  11244. }
  11245. if (desc->mtl_force_managed_storage_mode) {
  11246. _sg.mtl.use_shared_storage_mode = false;
  11247. } else if (@available(macOS 10.15, iOS 13.0, *)) {
  11248. // on Intel Macs, always use managed resources even though the
  11249. // device says it supports unified memory (because of texture restrictions)
  11250. const bool is_apple_gpu = [_sg.mtl.device supportsFamily:MTLGPUFamilyApple1];
  11251. if (!is_apple_gpu) {
  11252. _sg.mtl.use_shared_storage_mode = false;
  11253. } else {
  11254. _sg.mtl.use_shared_storage_mode = true;
  11255. }
  11256. } else {
  11257. #if defined(_SG_TARGET_MACOS)
  11258. _sg.mtl.use_shared_storage_mode = false;
  11259. #else
  11260. _sg.mtl.use_shared_storage_mode = true;
  11261. #endif
  11262. }
  11263. _sg_mtl_init_caps();
  11264. }
  11265. _SOKOL_PRIVATE void _sg_mtl_discard_backend(void) {
  11266. SOKOL_ASSERT(_sg.mtl.valid);
  11267. // wait for the last frame to finish
  11268. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  11269. dispatch_semaphore_wait(_sg.mtl.sem, DISPATCH_TIME_FOREVER);
  11270. }
  11271. // semaphore must be "relinquished" before destruction
  11272. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  11273. dispatch_semaphore_signal(_sg.mtl.sem);
  11274. }
  11275. _sg_mtl_garbage_collect(_sg.frame_index + SG_NUM_INFLIGHT_FRAMES + 2);
  11276. _sg_mtl_destroy_pool();
  11277. _sg.mtl.valid = false;
  11278. _SG_OBJC_RELEASE(_sg.mtl.sem);
  11279. _SG_OBJC_RELEASE(_sg.mtl.device);
  11280. _SG_OBJC_RELEASE(_sg.mtl.cmd_queue);
  11281. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  11282. _SG_OBJC_RELEASE(_sg.mtl.uniform_buffers[i]);
  11283. }
  11284. // NOTE: MTLCommandBuffer and MTLRenderCommandEncoder are auto-released
  11285. _sg.mtl.cmd_buffer = nil;
  11286. _sg.mtl.cmd_encoder = nil;
  11287. }
  11288. _SOKOL_PRIVATE void _sg_mtl_reset_state_cache(void) {
  11289. _sg_mtl_clear_state_cache();
  11290. }
  11291. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  11292. SOKOL_ASSERT(buf && desc);
  11293. const bool injected = (0 != desc->mtl_buffers[0]);
  11294. MTLResourceOptions mtl_options = _sg_mtl_buffer_resource_options(buf->cmn.usage);
  11295. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  11296. id<MTLBuffer> mtl_buf;
  11297. if (injected) {
  11298. SOKOL_ASSERT(desc->mtl_buffers[slot]);
  11299. mtl_buf = (__bridge id<MTLBuffer>) desc->mtl_buffers[slot];
  11300. } else {
  11301. if (buf->cmn.usage == SG_USAGE_IMMUTABLE) {
  11302. SOKOL_ASSERT(desc->data.ptr);
  11303. mtl_buf = [_sg.mtl.device newBufferWithBytes:desc->data.ptr length:(NSUInteger)buf->cmn.size options:mtl_options];
  11304. } else {
  11305. mtl_buf = [_sg.mtl.device newBufferWithLength:(NSUInteger)buf->cmn.size options:mtl_options];
  11306. }
  11307. if (nil == mtl_buf) {
  11308. _SG_ERROR(METAL_CREATE_BUFFER_FAILED);
  11309. return SG_RESOURCESTATE_FAILED;
  11310. }
  11311. }
  11312. #if defined(SOKOL_DEBUG)
  11313. if (desc->label) {
  11314. mtl_buf.label = [NSString stringWithFormat:@"%s.%d", desc->label, slot];
  11315. }
  11316. #endif
  11317. buf->mtl.buf[slot] = _sg_mtl_add_resource(mtl_buf);
  11318. _SG_OBJC_RELEASE(mtl_buf);
  11319. }
  11320. return SG_RESOURCESTATE_VALID;
  11321. }
  11322. _SOKOL_PRIVATE void _sg_mtl_discard_buffer(_sg_buffer_t* buf) {
  11323. SOKOL_ASSERT(buf);
  11324. for (int slot = 0; slot < buf->cmn.num_slots; slot++) {
  11325. // it's valid to call release resource with '0'
  11326. _sg_mtl_release_resource(_sg.frame_index, buf->mtl.buf[slot]);
  11327. }
  11328. }
  11329. _SOKOL_PRIVATE void _sg_mtl_copy_image_data(const _sg_image_t* img, __unsafe_unretained id<MTLTexture> mtl_tex, const sg_image_data* data) {
  11330. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6:1;
  11331. const int num_slices = (img->cmn.type == SG_IMAGETYPE_ARRAY) ? img->cmn.num_slices : 1;
  11332. for (int face_index = 0; face_index < num_faces; face_index++) {
  11333. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++) {
  11334. SOKOL_ASSERT(data->subimage[face_index][mip_index].ptr);
  11335. SOKOL_ASSERT(data->subimage[face_index][mip_index].size > 0);
  11336. const uint8_t* data_ptr = (const uint8_t*)data->subimage[face_index][mip_index].ptr;
  11337. const int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  11338. const int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  11339. int bytes_per_row = _sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  11340. int bytes_per_slice = _sg_surface_pitch(img->cmn.pixel_format, mip_width, mip_height, 1);
  11341. /* bytesPerImage special case: https://developer.apple.com/documentation/metal/mtltexture/1515679-replaceregion
  11342. "Supply a nonzero value only when you copy data to a MTLTextureType3D type texture"
  11343. */
  11344. MTLRegion region;
  11345. int bytes_per_image;
  11346. if (img->cmn.type == SG_IMAGETYPE_3D) {
  11347. const int mip_depth = _sg_miplevel_dim(img->cmn.num_slices, mip_index);
  11348. region = MTLRegionMake3D(0, 0, 0, (NSUInteger)mip_width, (NSUInteger)mip_height, (NSUInteger)mip_depth);
  11349. bytes_per_image = bytes_per_slice;
  11350. // FIXME: apparently the minimal bytes_per_image size for 3D texture is 4 KByte... somehow need to handle this
  11351. } else {
  11352. region = MTLRegionMake2D(0, 0, (NSUInteger)mip_width, (NSUInteger)mip_height);
  11353. bytes_per_image = 0;
  11354. }
  11355. for (int slice_index = 0; slice_index < num_slices; slice_index++) {
  11356. const int mtl_slice_index = (img->cmn.type == SG_IMAGETYPE_CUBE) ? face_index : slice_index;
  11357. const int slice_offset = slice_index * bytes_per_slice;
  11358. SOKOL_ASSERT((slice_offset + bytes_per_slice) <= (int)data->subimage[face_index][mip_index].size);
  11359. [mtl_tex replaceRegion:region
  11360. mipmapLevel:(NSUInteger)mip_index
  11361. slice:(NSUInteger)mtl_slice_index
  11362. withBytes:data_ptr + slice_offset
  11363. bytesPerRow:(NSUInteger)bytes_per_row
  11364. bytesPerImage:(NSUInteger)bytes_per_image];
  11365. }
  11366. }
  11367. }
  11368. }
  11369. // initialize MTLTextureDescriptor with common attributes
  11370. _SOKOL_PRIVATE bool _sg_mtl_init_texdesc_common(MTLTextureDescriptor* mtl_desc, _sg_image_t* img) {
  11371. mtl_desc.textureType = _sg_mtl_texture_type(img->cmn.type);
  11372. mtl_desc.pixelFormat = _sg_mtl_pixel_format(img->cmn.pixel_format);
  11373. if (MTLPixelFormatInvalid == mtl_desc.pixelFormat) {
  11374. _SG_ERROR(METAL_TEXTURE_FORMAT_NOT_SUPPORTED);
  11375. return false;
  11376. }
  11377. mtl_desc.width = (NSUInteger)img->cmn.width;
  11378. mtl_desc.height = (NSUInteger)img->cmn.height;
  11379. if (SG_IMAGETYPE_3D == img->cmn.type) {
  11380. mtl_desc.depth = (NSUInteger)img->cmn.num_slices;
  11381. } else {
  11382. mtl_desc.depth = 1;
  11383. }
  11384. mtl_desc.mipmapLevelCount = (NSUInteger)img->cmn.num_mipmaps;
  11385. if (SG_IMAGETYPE_ARRAY == img->cmn.type) {
  11386. mtl_desc.arrayLength = (NSUInteger)img->cmn.num_slices;
  11387. } else {
  11388. mtl_desc.arrayLength = 1;
  11389. }
  11390. mtl_desc.usage = MTLTextureUsageShaderRead;
  11391. MTLResourceOptions res_options = 0;
  11392. if (img->cmn.usage != SG_USAGE_IMMUTABLE) {
  11393. res_options |= MTLResourceCPUCacheModeWriteCombined;
  11394. }
  11395. res_options |= _sg_mtl_resource_options_storage_mode_managed_or_shared();
  11396. mtl_desc.resourceOptions = res_options;
  11397. return true;
  11398. }
  11399. // initialize MTLTextureDescriptor with rendertarget attributes
  11400. _SOKOL_PRIVATE void _sg_mtl_init_texdesc_rt(MTLTextureDescriptor* mtl_desc, _sg_image_t* img) {
  11401. SOKOL_ASSERT(img->cmn.render_target);
  11402. _SOKOL_UNUSED(img);
  11403. mtl_desc.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget;
  11404. mtl_desc.resourceOptions = MTLResourceStorageModePrivate;
  11405. }
  11406. // initialize MTLTextureDescriptor with MSAA attributes
  11407. _SOKOL_PRIVATE void _sg_mtl_init_texdesc_rt_msaa(MTLTextureDescriptor* mtl_desc, _sg_image_t* img) {
  11408. SOKOL_ASSERT(img->cmn.sample_count > 1);
  11409. mtl_desc.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget;
  11410. mtl_desc.resourceOptions = MTLResourceStorageModePrivate;
  11411. mtl_desc.textureType = MTLTextureType2DMultisample;
  11412. mtl_desc.sampleCount = (NSUInteger)img->cmn.sample_count;
  11413. }
  11414. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  11415. SOKOL_ASSERT(img && desc);
  11416. const bool injected = (0 != desc->mtl_textures[0]);
  11417. // first initialize all Metal resource pool slots to 'empty'
  11418. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  11419. img->mtl.tex[i] = _sg_mtl_add_resource(nil);
  11420. }
  11421. // initialize a Metal texture descriptor
  11422. MTLTextureDescriptor* mtl_desc = [[MTLTextureDescriptor alloc] init];
  11423. if (!_sg_mtl_init_texdesc_common(mtl_desc, img)) {
  11424. _SG_OBJC_RELEASE(mtl_desc);
  11425. return SG_RESOURCESTATE_FAILED;
  11426. }
  11427. if (img->cmn.render_target) {
  11428. if (img->cmn.sample_count > 1) {
  11429. _sg_mtl_init_texdesc_rt_msaa(mtl_desc, img);
  11430. } else {
  11431. _sg_mtl_init_texdesc_rt(mtl_desc, img);
  11432. }
  11433. }
  11434. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  11435. id<MTLTexture> mtl_tex;
  11436. if (injected) {
  11437. SOKOL_ASSERT(desc->mtl_textures[slot]);
  11438. mtl_tex = (__bridge id<MTLTexture>) desc->mtl_textures[slot];
  11439. } else {
  11440. mtl_tex = [_sg.mtl.device newTextureWithDescriptor:mtl_desc];
  11441. if (nil == mtl_tex) {
  11442. _SG_OBJC_RELEASE(mtl_desc);
  11443. _SG_ERROR(METAL_CREATE_TEXTURE_FAILED);
  11444. return SG_RESOURCESTATE_FAILED;
  11445. }
  11446. if ((img->cmn.usage == SG_USAGE_IMMUTABLE) && !img->cmn.render_target) {
  11447. _sg_mtl_copy_image_data(img, mtl_tex, &desc->data);
  11448. }
  11449. }
  11450. #if defined(SOKOL_DEBUG)
  11451. if (desc->label) {
  11452. mtl_tex.label = [NSString stringWithFormat:@"%s.%d", desc->label, slot];
  11453. }
  11454. #endif
  11455. img->mtl.tex[slot] = _sg_mtl_add_resource(mtl_tex);
  11456. _SG_OBJC_RELEASE(mtl_tex);
  11457. }
  11458. _SG_OBJC_RELEASE(mtl_desc);
  11459. return SG_RESOURCESTATE_VALID;
  11460. }
  11461. _SOKOL_PRIVATE void _sg_mtl_discard_image(_sg_image_t* img) {
  11462. SOKOL_ASSERT(img);
  11463. // it's valid to call release resource with a 'null resource'
  11464. for (int slot = 0; slot < img->cmn.num_slots; slot++) {
  11465. _sg_mtl_release_resource(_sg.frame_index, img->mtl.tex[slot]);
  11466. }
  11467. }
  11468. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  11469. SOKOL_ASSERT(smp && desc);
  11470. id<MTLSamplerState> mtl_smp;
  11471. const bool injected = (0 != desc->mtl_sampler);
  11472. if (injected) {
  11473. SOKOL_ASSERT(desc->mtl_sampler);
  11474. mtl_smp = (__bridge id<MTLSamplerState>) desc->mtl_sampler;
  11475. } else {
  11476. MTLSamplerDescriptor* mtl_desc = [[MTLSamplerDescriptor alloc] init];
  11477. mtl_desc.sAddressMode = _sg_mtl_address_mode(desc->wrap_u);
  11478. mtl_desc.tAddressMode = _sg_mtl_address_mode(desc->wrap_v);
  11479. mtl_desc.rAddressMode = _sg_mtl_address_mode(desc->wrap_w);
  11480. if (_sg.features.image_clamp_to_border) {
  11481. if (@available(macOS 12.0, iOS 14.0, *)) {
  11482. mtl_desc.borderColor = _sg_mtl_border_color(desc->border_color);
  11483. }
  11484. }
  11485. mtl_desc.minFilter = _sg_mtl_minmag_filter(desc->min_filter);
  11486. mtl_desc.magFilter = _sg_mtl_minmag_filter(desc->mag_filter);
  11487. mtl_desc.mipFilter = _sg_mtl_mipmap_filter(desc->mipmap_filter);
  11488. mtl_desc.lodMinClamp = desc->min_lod;
  11489. mtl_desc.lodMaxClamp = desc->max_lod;
  11490. // FIXME: lodAverage?
  11491. mtl_desc.maxAnisotropy = desc->max_anisotropy;
  11492. mtl_desc.normalizedCoordinates = YES;
  11493. mtl_desc.compareFunction = _sg_mtl_compare_func(desc->compare);
  11494. #if defined(SOKOL_DEBUG)
  11495. if (desc->label) {
  11496. mtl_desc.label = [NSString stringWithUTF8String:desc->label];
  11497. }
  11498. #endif
  11499. mtl_smp = [_sg.mtl.device newSamplerStateWithDescriptor:mtl_desc];
  11500. _SG_OBJC_RELEASE(mtl_desc);
  11501. if (nil == mtl_smp) {
  11502. _SG_ERROR(METAL_CREATE_SAMPLER_FAILED);
  11503. return SG_RESOURCESTATE_FAILED;
  11504. }
  11505. }
  11506. smp->mtl.sampler_state = _sg_mtl_add_resource(mtl_smp);
  11507. _SG_OBJC_RELEASE(mtl_smp);
  11508. return SG_RESOURCESTATE_VALID;
  11509. }
  11510. _SOKOL_PRIVATE void _sg_mtl_discard_sampler(_sg_sampler_t* smp) {
  11511. SOKOL_ASSERT(smp);
  11512. // it's valid to call release resource with a 'null resource'
  11513. _sg_mtl_release_resource(_sg.frame_index, smp->mtl.sampler_state);
  11514. }
  11515. _SOKOL_PRIVATE id<MTLLibrary> _sg_mtl_compile_library(const char* src) {
  11516. NSError* err = NULL;
  11517. id<MTLLibrary> lib = [_sg.mtl.device
  11518. newLibraryWithSource:[NSString stringWithUTF8String:src]
  11519. options:nil
  11520. error:&err
  11521. ];
  11522. if (err) {
  11523. _SG_ERROR(METAL_SHADER_COMPILATION_FAILED);
  11524. _SG_LOGMSG(METAL_SHADER_COMPILATION_OUTPUT, [err.localizedDescription UTF8String]);
  11525. }
  11526. return lib;
  11527. }
  11528. _SOKOL_PRIVATE id<MTLLibrary> _sg_mtl_library_from_bytecode(const void* ptr, size_t num_bytes) {
  11529. NSError* err = NULL;
  11530. dispatch_data_t lib_data = dispatch_data_create(ptr, num_bytes, NULL, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
  11531. id<MTLLibrary> lib = [_sg.mtl.device newLibraryWithData:lib_data error:&err];
  11532. if (err) {
  11533. _SG_ERROR(METAL_SHADER_CREATION_FAILED);
  11534. _SG_LOGMSG(METAL_SHADER_COMPILATION_OUTPUT, [err.localizedDescription UTF8String]);
  11535. }
  11536. _SG_OBJC_RELEASE(lib_data);
  11537. return lib;
  11538. }
  11539. _SOKOL_PRIVATE bool _sg_mtl_create_shader_func(const sg_shader_function* func, const char* label, const char* label_ext, _sg_mtl_shader_func_t* res) {
  11540. SOKOL_ASSERT(res->mtl_lib == _SG_MTL_INVALID_SLOT_INDEX);
  11541. SOKOL_ASSERT(res->mtl_func == _SG_MTL_INVALID_SLOT_INDEX);
  11542. id<MTLLibrary> mtl_lib = nil;
  11543. if (func->bytecode.ptr) {
  11544. SOKOL_ASSERT(func->bytecode.size > 0);
  11545. mtl_lib = _sg_mtl_library_from_bytecode(func->bytecode.ptr, func->bytecode.size);
  11546. } else if (func->source) {
  11547. mtl_lib = _sg_mtl_compile_library(func->source);
  11548. }
  11549. if (mtl_lib == nil) {
  11550. return false;
  11551. }
  11552. #if defined(SOKOL_DEBUG)
  11553. if (label) {
  11554. SOKOL_ASSERT(label_ext);
  11555. mtl_lib.label = [NSString stringWithFormat:@"%s.%s", label, label_ext];
  11556. }
  11557. #else
  11558. _SOKOL_UNUSED(label);
  11559. _SOKOL_UNUSED(label_ext);
  11560. #endif
  11561. SOKOL_ASSERT(func->entry);
  11562. id<MTLFunction> mtl_func = [mtl_lib newFunctionWithName:[NSString stringWithUTF8String:func->entry]];
  11563. if (mtl_func == nil) {
  11564. _SG_ERROR(METAL_SHADER_ENTRY_NOT_FOUND);
  11565. _SG_OBJC_RELEASE(mtl_lib);
  11566. return false;
  11567. }
  11568. res->mtl_lib = _sg_mtl_add_resource(mtl_lib);
  11569. res->mtl_func = _sg_mtl_add_resource(mtl_func);
  11570. _SG_OBJC_RELEASE(mtl_lib);
  11571. _SG_OBJC_RELEASE(mtl_func);
  11572. return true;
  11573. }
  11574. _SOKOL_PRIVATE void _sg_mtl_discard_shader_func(const _sg_mtl_shader_func_t* func) {
  11575. // it is valid to call _sg_mtl_release_resource with a 'null resource'
  11576. _sg_mtl_release_resource(_sg.frame_index, func->mtl_func);
  11577. _sg_mtl_release_resource(_sg.frame_index, func->mtl_lib);
  11578. }
  11579. // NOTE: this is an out-of-range check for MSL bindslots that's also active in release mode
  11580. _SOKOL_PRIVATE bool _sg_mtl_ensure_msl_bindslot_ranges(const sg_shader_desc* desc) {
  11581. SOKOL_ASSERT(desc);
  11582. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  11583. if (desc->uniform_blocks[i].msl_buffer_n >= _SG_MTL_MAX_STAGE_UB_BINDINGS) {
  11584. _SG_ERROR(METAL_UNIFORMBLOCK_MSL_BUFFER_SLOT_OUT_OF_RANGE);
  11585. return false;
  11586. }
  11587. }
  11588. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  11589. if (desc->storage_buffers[i].msl_buffer_n >= _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS) {
  11590. _SG_ERROR(METAL_STORAGEBUFFER_MSL_BUFFER_SLOT_OUT_OF_RANGE);
  11591. return false;
  11592. }
  11593. }
  11594. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  11595. if (desc->images[i].msl_texture_n >= _SG_MTL_MAX_STAGE_IMAGE_BINDINGS) {
  11596. _SG_ERROR(METAL_IMAGE_MSL_TEXTURE_SLOT_OUT_OF_RANGE);
  11597. return false;
  11598. }
  11599. }
  11600. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  11601. if (desc->samplers[i].msl_sampler_n >= _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS) {
  11602. _SG_ERROR(METAL_SAMPLER_MSL_SAMPLER_SLOT_OUT_OF_RANGE);
  11603. return false;
  11604. }
  11605. }
  11606. return true;
  11607. }
  11608. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  11609. SOKOL_ASSERT(shd && desc);
  11610. // do a MSL bindslot range check also in release mode, and if that fails,
  11611. // also fail shader creation
  11612. if (!_sg_mtl_ensure_msl_bindslot_ranges(desc)) {
  11613. return SG_RESOURCESTATE_FAILED;
  11614. }
  11615. // copy resource bindslot mappings
  11616. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  11617. shd->mtl.ub_buffer_n[i] = desc->uniform_blocks[i].msl_buffer_n;
  11618. }
  11619. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  11620. shd->mtl.sbuf_buffer_n[i] = desc->storage_buffers[i].msl_buffer_n;
  11621. }
  11622. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  11623. shd->mtl.img_texture_n[i] = desc->images[i].msl_texture_n;
  11624. }
  11625. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  11626. shd->mtl.smp_sampler_n[i] = desc->samplers[i].msl_sampler_n;
  11627. }
  11628. // create metal library and function objects
  11629. bool shd_valid = _sg_mtl_create_shader_func(&desc->vertex_func, desc->label, "vs", &shd->mtl.vertex_func);
  11630. shd_valid &= _sg_mtl_create_shader_func(&desc->fragment_func, desc->label, "fs", &shd->mtl.fragment_func);
  11631. if (!shd_valid) {
  11632. _sg_mtl_discard_shader_func(&shd->mtl.vertex_func);
  11633. _sg_mtl_discard_shader_func(&shd->mtl.fragment_func);
  11634. }
  11635. return shd_valid ? SG_RESOURCESTATE_VALID : SG_RESOURCESTATE_FAILED;
  11636. }
  11637. _SOKOL_PRIVATE void _sg_mtl_discard_shader(_sg_shader_t* shd) {
  11638. SOKOL_ASSERT(shd);
  11639. _sg_mtl_discard_shader_func(&shd->mtl.vertex_func);
  11640. _sg_mtl_discard_shader_func(&shd->mtl.fragment_func);
  11641. }
  11642. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_pipeline(_sg_pipeline_t* pip, _sg_shader_t* shd, const sg_pipeline_desc* desc) {
  11643. SOKOL_ASSERT(pip && shd && desc);
  11644. SOKOL_ASSERT(desc->shader.id == shd->slot.id);
  11645. pip->shader = shd;
  11646. sg_primitive_type prim_type = desc->primitive_type;
  11647. pip->mtl.prim_type = _sg_mtl_primitive_type(prim_type);
  11648. pip->mtl.index_size = _sg_mtl_index_size(pip->cmn.index_type);
  11649. if (SG_INDEXTYPE_NONE != pip->cmn.index_type) {
  11650. pip->mtl.index_type = _sg_mtl_index_type(pip->cmn.index_type);
  11651. }
  11652. pip->mtl.cull_mode = _sg_mtl_cull_mode(desc->cull_mode);
  11653. pip->mtl.winding = _sg_mtl_winding(desc->face_winding);
  11654. pip->mtl.stencil_ref = desc->stencil.ref;
  11655. // create vertex-descriptor
  11656. MTLVertexDescriptor* vtx_desc = [MTLVertexDescriptor vertexDescriptor];
  11657. for (NSUInteger attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  11658. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  11659. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  11660. break;
  11661. }
  11662. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  11663. SOKOL_ASSERT(pip->cmn.vertex_buffer_layout_active[a_state->buffer_index]);
  11664. vtx_desc.attributes[attr_index].format = _sg_mtl_vertex_format(a_state->format);
  11665. vtx_desc.attributes[attr_index].offset = (NSUInteger)a_state->offset;
  11666. vtx_desc.attributes[attr_index].bufferIndex = (NSUInteger)(a_state->buffer_index + SG_MAX_UNIFORMBLOCK_BINDSLOTS + SG_MAX_STORAGEBUFFER_BINDSLOTS);
  11667. }
  11668. for (NSUInteger layout_index = 0; layout_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; layout_index++) {
  11669. if (pip->cmn.vertex_buffer_layout_active[layout_index]) {
  11670. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[layout_index];
  11671. const NSUInteger mtl_vb_slot = layout_index + SG_MAX_UNIFORMBLOCK_BINDSLOTS + SG_MAX_STORAGEBUFFER_BINDSLOTS;
  11672. SOKOL_ASSERT(l_state->stride > 0);
  11673. vtx_desc.layouts[mtl_vb_slot].stride = (NSUInteger)l_state->stride;
  11674. vtx_desc.layouts[mtl_vb_slot].stepFunction = _sg_mtl_step_function(l_state->step_func);
  11675. vtx_desc.layouts[mtl_vb_slot].stepRate = (NSUInteger)l_state->step_rate;
  11676. if (SG_VERTEXSTEP_PER_INSTANCE == l_state->step_func) {
  11677. // NOTE: not actually used in _sg_mtl_draw()
  11678. pip->cmn.use_instanced_draw = true;
  11679. }
  11680. }
  11681. }
  11682. // render-pipeline descriptor
  11683. MTLRenderPipelineDescriptor* rp_desc = [[MTLRenderPipelineDescriptor alloc] init];
  11684. rp_desc.vertexDescriptor = vtx_desc;
  11685. SOKOL_ASSERT(shd->mtl.vertex_func.mtl_func != _SG_MTL_INVALID_SLOT_INDEX);
  11686. rp_desc.vertexFunction = _sg_mtl_id(shd->mtl.vertex_func.mtl_func);
  11687. SOKOL_ASSERT(shd->mtl.fragment_func.mtl_func != _SG_MTL_INVALID_SLOT_INDEX);
  11688. rp_desc.fragmentFunction = _sg_mtl_id(shd->mtl.fragment_func.mtl_func);
  11689. rp_desc.rasterSampleCount = (NSUInteger)desc->sample_count;
  11690. rp_desc.alphaToCoverageEnabled = desc->alpha_to_coverage_enabled;
  11691. rp_desc.alphaToOneEnabled = NO;
  11692. rp_desc.rasterizationEnabled = YES;
  11693. rp_desc.depthAttachmentPixelFormat = _sg_mtl_pixel_format(desc->depth.pixel_format);
  11694. if (desc->depth.pixel_format == SG_PIXELFORMAT_DEPTH_STENCIL) {
  11695. rp_desc.stencilAttachmentPixelFormat = _sg_mtl_pixel_format(desc->depth.pixel_format);
  11696. }
  11697. for (NSUInteger i = 0; i < (NSUInteger)desc->color_count; i++) {
  11698. SOKOL_ASSERT(i < SG_MAX_COLOR_ATTACHMENTS);
  11699. const sg_color_target_state* cs = &desc->colors[i];
  11700. rp_desc.colorAttachments[i].pixelFormat = _sg_mtl_pixel_format(cs->pixel_format);
  11701. rp_desc.colorAttachments[i].writeMask = _sg_mtl_color_write_mask(cs->write_mask);
  11702. rp_desc.colorAttachments[i].blendingEnabled = cs->blend.enabled;
  11703. rp_desc.colorAttachments[i].alphaBlendOperation = _sg_mtl_blend_op(cs->blend.op_alpha);
  11704. rp_desc.colorAttachments[i].rgbBlendOperation = _sg_mtl_blend_op(cs->blend.op_rgb);
  11705. rp_desc.colorAttachments[i].destinationAlphaBlendFactor = _sg_mtl_blend_factor(cs->blend.dst_factor_alpha);
  11706. rp_desc.colorAttachments[i].destinationRGBBlendFactor = _sg_mtl_blend_factor(cs->blend.dst_factor_rgb);
  11707. rp_desc.colorAttachments[i].sourceAlphaBlendFactor = _sg_mtl_blend_factor(cs->blend.src_factor_alpha);
  11708. rp_desc.colorAttachments[i].sourceRGBBlendFactor = _sg_mtl_blend_factor(cs->blend.src_factor_rgb);
  11709. }
  11710. #if defined(SOKOL_DEBUG)
  11711. if (desc->label) {
  11712. rp_desc.label = [NSString stringWithFormat:@"%s", desc->label];
  11713. }
  11714. #endif
  11715. NSError* err = NULL;
  11716. id<MTLRenderPipelineState> mtl_rps = [_sg.mtl.device newRenderPipelineStateWithDescriptor:rp_desc error:&err];
  11717. _SG_OBJC_RELEASE(rp_desc);
  11718. if (nil == mtl_rps) {
  11719. SOKOL_ASSERT(err);
  11720. _SG_ERROR(METAL_CREATE_RPS_FAILED);
  11721. _SG_LOGMSG(METAL_CREATE_RPS_OUTPUT, [err.localizedDescription UTF8String]);
  11722. return SG_RESOURCESTATE_FAILED;
  11723. }
  11724. pip->mtl.rps = _sg_mtl_add_resource(mtl_rps);
  11725. _SG_OBJC_RELEASE(mtl_rps);
  11726. // depth-stencil-state
  11727. MTLDepthStencilDescriptor* ds_desc = [[MTLDepthStencilDescriptor alloc] init];
  11728. ds_desc.depthCompareFunction = _sg_mtl_compare_func(desc->depth.compare);
  11729. ds_desc.depthWriteEnabled = desc->depth.write_enabled;
  11730. if (desc->stencil.enabled) {
  11731. const sg_stencil_face_state* sb = &desc->stencil.back;
  11732. ds_desc.backFaceStencil = [[MTLStencilDescriptor alloc] init];
  11733. ds_desc.backFaceStencil.stencilFailureOperation = _sg_mtl_stencil_op(sb->fail_op);
  11734. ds_desc.backFaceStencil.depthFailureOperation = _sg_mtl_stencil_op(sb->depth_fail_op);
  11735. ds_desc.backFaceStencil.depthStencilPassOperation = _sg_mtl_stencil_op(sb->pass_op);
  11736. ds_desc.backFaceStencil.stencilCompareFunction = _sg_mtl_compare_func(sb->compare);
  11737. ds_desc.backFaceStencil.readMask = desc->stencil.read_mask;
  11738. ds_desc.backFaceStencil.writeMask = desc->stencil.write_mask;
  11739. const sg_stencil_face_state* sf = &desc->stencil.front;
  11740. ds_desc.frontFaceStencil = [[MTLStencilDescriptor alloc] init];
  11741. ds_desc.frontFaceStencil.stencilFailureOperation = _sg_mtl_stencil_op(sf->fail_op);
  11742. ds_desc.frontFaceStencil.depthFailureOperation = _sg_mtl_stencil_op(sf->depth_fail_op);
  11743. ds_desc.frontFaceStencil.depthStencilPassOperation = _sg_mtl_stencil_op(sf->pass_op);
  11744. ds_desc.frontFaceStencil.stencilCompareFunction = _sg_mtl_compare_func(sf->compare);
  11745. ds_desc.frontFaceStencil.readMask = desc->stencil.read_mask;
  11746. ds_desc.frontFaceStencil.writeMask = desc->stencil.write_mask;
  11747. }
  11748. #if defined(SOKOL_DEBUG)
  11749. if (desc->label) {
  11750. ds_desc.label = [NSString stringWithFormat:@"%s.dss", desc->label];
  11751. }
  11752. #endif
  11753. id<MTLDepthStencilState> mtl_dss = [_sg.mtl.device newDepthStencilStateWithDescriptor:ds_desc];
  11754. _SG_OBJC_RELEASE(ds_desc);
  11755. if (nil == mtl_dss) {
  11756. _SG_ERROR(METAL_CREATE_DSS_FAILED);
  11757. return SG_RESOURCESTATE_FAILED;
  11758. }
  11759. pip->mtl.dss = _sg_mtl_add_resource(mtl_dss);
  11760. _SG_OBJC_RELEASE(mtl_dss);
  11761. return SG_RESOURCESTATE_VALID;
  11762. }
  11763. _SOKOL_PRIVATE void _sg_mtl_discard_pipeline(_sg_pipeline_t* pip) {
  11764. SOKOL_ASSERT(pip);
  11765. // it's valid to call release resource with a 'null resource'
  11766. _sg_mtl_release_resource(_sg.frame_index, pip->mtl.rps);
  11767. _sg_mtl_release_resource(_sg.frame_index, pip->mtl.dss);
  11768. }
  11769. _SOKOL_PRIVATE sg_resource_state _sg_mtl_create_attachments(_sg_attachments_t* atts, _sg_image_t** color_images, _sg_image_t** resolve_images, _sg_image_t* ds_img, const sg_attachments_desc* desc) {
  11770. SOKOL_ASSERT(atts && desc);
  11771. SOKOL_ASSERT(color_images && resolve_images);
  11772. // copy image pointers
  11773. for (int i = 0; i < atts->cmn.num_colors; i++) {
  11774. const sg_attachment_desc* color_desc = &desc->colors[i];
  11775. _SOKOL_UNUSED(color_desc);
  11776. SOKOL_ASSERT(color_desc->image.id != SG_INVALID_ID);
  11777. SOKOL_ASSERT(0 == atts->mtl.colors[i].image);
  11778. SOKOL_ASSERT(color_images[i] && (color_images[i]->slot.id == color_desc->image.id));
  11779. SOKOL_ASSERT(_sg_is_valid_rendertarget_color_format(color_images[i]->cmn.pixel_format));
  11780. atts->mtl.colors[i].image = color_images[i];
  11781. const sg_attachment_desc* resolve_desc = &desc->resolves[i];
  11782. if (resolve_desc->image.id != SG_INVALID_ID) {
  11783. SOKOL_ASSERT(0 == atts->mtl.resolves[i].image);
  11784. SOKOL_ASSERT(resolve_images[i] && (resolve_images[i]->slot.id == resolve_desc->image.id));
  11785. SOKOL_ASSERT(color_images[i] && (color_images[i]->cmn.pixel_format == resolve_images[i]->cmn.pixel_format));
  11786. atts->mtl.resolves[i].image = resolve_images[i];
  11787. }
  11788. }
  11789. SOKOL_ASSERT(0 == atts->mtl.depth_stencil.image);
  11790. const sg_attachment_desc* ds_desc = &desc->depth_stencil;
  11791. if (ds_desc->image.id != SG_INVALID_ID) {
  11792. SOKOL_ASSERT(ds_img && (ds_img->slot.id == ds_desc->image.id));
  11793. SOKOL_ASSERT(_sg_is_valid_rendertarget_depth_format(ds_img->cmn.pixel_format));
  11794. atts->mtl.depth_stencil.image = ds_img;
  11795. }
  11796. return SG_RESOURCESTATE_VALID;
  11797. }
  11798. _SOKOL_PRIVATE void _sg_mtl_discard_attachments(_sg_attachments_t* atts) {
  11799. SOKOL_ASSERT(atts);
  11800. _SOKOL_UNUSED(atts);
  11801. }
  11802. _SOKOL_PRIVATE _sg_image_t* _sg_mtl_attachments_color_image(const _sg_attachments_t* atts, int index) {
  11803. // NOTE: may return null
  11804. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  11805. return atts->mtl.colors[index].image;
  11806. }
  11807. _SOKOL_PRIVATE _sg_image_t* _sg_mtl_attachments_resolve_image(const _sg_attachments_t* atts, int index) {
  11808. // NOTE: may return null
  11809. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  11810. return atts->mtl.resolves[index].image;
  11811. }
  11812. _SOKOL_PRIVATE _sg_image_t* _sg_mtl_attachments_ds_image(const _sg_attachments_t* atts) {
  11813. // NOTE: may return null
  11814. SOKOL_ASSERT(atts);
  11815. return atts->mtl.depth_stencil.image;
  11816. }
  11817. _SOKOL_PRIVATE void _sg_mtl_bind_uniform_buffers(void) {
  11818. SOKOL_ASSERT(nil != _sg.mtl.cmd_encoder);
  11819. // On Metal, uniform buffer bindings happen once in sg_begin_pass() and
  11820. // remain valid for the entire pass. Only binding offsets will be updated
  11821. // in sg_apply_uniforms()
  11822. for (size_t slot = 0; slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS; slot++) {
  11823. [_sg.mtl.cmd_encoder
  11824. setVertexBuffer:_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index]
  11825. offset:0
  11826. atIndex:slot];
  11827. [_sg.mtl.cmd_encoder
  11828. setFragmentBuffer:_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index]
  11829. offset:0
  11830. atIndex:slot];
  11831. }
  11832. }
  11833. _SOKOL_PRIVATE void _sg_mtl_begin_pass(const sg_pass* pass) {
  11834. SOKOL_ASSERT(pass);
  11835. SOKOL_ASSERT(_sg.mtl.cmd_queue);
  11836. SOKOL_ASSERT(nil == _sg.mtl.cmd_encoder);
  11837. SOKOL_ASSERT(nil == _sg.mtl.cur_drawable);
  11838. _sg_mtl_clear_state_cache();
  11839. const _sg_attachments_t* atts = _sg.cur_pass.atts;
  11840. const sg_swapchain* swapchain = &pass->swapchain;
  11841. const sg_pass_action* action = &pass->action;
  11842. /*
  11843. if this is the first pass in the frame, create command buffers
  11844. NOTE: we're creating two command buffers here, one with unretained references
  11845. for storing the regular commands, and one with retained references for
  11846. storing the presentDrawable call (this needs to hold on the drawable until
  11847. presentation has happened - and the easiest way to do this is to let the
  11848. command buffer manage the lifetime of the drawable).
  11849. Also see: https://github.com/floooh/sokol/issues/762
  11850. */
  11851. if (nil == _sg.mtl.cmd_buffer) {
  11852. // block until the oldest frame in flight has finished
  11853. dispatch_semaphore_wait(_sg.mtl.sem, DISPATCH_TIME_FOREVER);
  11854. if (_sg.desc.mtl_use_command_buffer_with_retained_references) {
  11855. _sg.mtl.cmd_buffer = [_sg.mtl.cmd_queue commandBuffer];
  11856. } else {
  11857. _sg.mtl.cmd_buffer = [_sg.mtl.cmd_queue commandBufferWithUnretainedReferences];
  11858. }
  11859. [_sg.mtl.cmd_buffer enqueue];
  11860. [_sg.mtl.cmd_buffer addCompletedHandler:^(id<MTLCommandBuffer> cmd_buf) {
  11861. // NOTE: this code is called on a different thread!
  11862. _SOKOL_UNUSED(cmd_buf);
  11863. dispatch_semaphore_signal(_sg.mtl.sem);
  11864. }];
  11865. }
  11866. // if this is first pass in frame, get uniform buffer base pointer
  11867. if (0 == _sg.mtl.cur_ub_base_ptr) {
  11868. _sg.mtl.cur_ub_base_ptr = (uint8_t*)[_sg.mtl.uniform_buffers[_sg.mtl.cur_frame_rotate_index] contents];
  11869. }
  11870. MTLRenderPassDescriptor* pass_desc = [MTLRenderPassDescriptor renderPassDescriptor];
  11871. SOKOL_ASSERT(pass_desc);
  11872. if (atts) {
  11873. // setup pass descriptor for offscreen rendering
  11874. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_VALID);
  11875. for (NSUInteger i = 0; i < (NSUInteger)atts->cmn.num_colors; i++) {
  11876. const _sg_attachment_common_t* cmn_color_att = &atts->cmn.colors[i];
  11877. const _sg_mtl_attachment_t* mtl_color_att = &atts->mtl.colors[i];
  11878. const _sg_image_t* color_att_img = mtl_color_att->image;
  11879. const _sg_attachment_common_t* cmn_resolve_att = &atts->cmn.resolves[i];
  11880. const _sg_mtl_attachment_t* mtl_resolve_att = &atts->mtl.resolves[i];
  11881. const _sg_image_t* resolve_att_img = mtl_resolve_att->image;
  11882. SOKOL_ASSERT(color_att_img->slot.state == SG_RESOURCESTATE_VALID);
  11883. SOKOL_ASSERT(color_att_img->slot.id == cmn_color_att->image_id.id);
  11884. SOKOL_ASSERT(color_att_img->mtl.tex[color_att_img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  11885. pass_desc.colorAttachments[i].loadAction = _sg_mtl_load_action(action->colors[i].load_action);
  11886. pass_desc.colorAttachments[i].storeAction = _sg_mtl_store_action(action->colors[i].store_action, resolve_att_img != 0);
  11887. sg_color c = action->colors[i].clear_value;
  11888. pass_desc.colorAttachments[i].clearColor = MTLClearColorMake(c.r, c.g, c.b, c.a);
  11889. pass_desc.colorAttachments[i].texture = _sg_mtl_id(color_att_img->mtl.tex[color_att_img->cmn.active_slot]);
  11890. pass_desc.colorAttachments[i].level = (NSUInteger)cmn_color_att->mip_level;
  11891. switch (color_att_img->cmn.type) {
  11892. case SG_IMAGETYPE_CUBE:
  11893. case SG_IMAGETYPE_ARRAY:
  11894. pass_desc.colorAttachments[i].slice = (NSUInteger)cmn_color_att->slice;
  11895. break;
  11896. case SG_IMAGETYPE_3D:
  11897. pass_desc.colorAttachments[i].depthPlane = (NSUInteger)cmn_color_att->slice;
  11898. break;
  11899. default: break;
  11900. }
  11901. if (resolve_att_img) {
  11902. SOKOL_ASSERT(resolve_att_img->slot.state == SG_RESOURCESTATE_VALID);
  11903. SOKOL_ASSERT(resolve_att_img->slot.id == cmn_resolve_att->image_id.id);
  11904. SOKOL_ASSERT(resolve_att_img->mtl.tex[resolve_att_img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  11905. pass_desc.colorAttachments[i].resolveTexture = _sg_mtl_id(resolve_att_img->mtl.tex[resolve_att_img->cmn.active_slot]);
  11906. pass_desc.colorAttachments[i].resolveLevel = (NSUInteger)cmn_resolve_att->mip_level;
  11907. switch (resolve_att_img->cmn.type) {
  11908. case SG_IMAGETYPE_CUBE:
  11909. case SG_IMAGETYPE_ARRAY:
  11910. pass_desc.colorAttachments[i].resolveSlice = (NSUInteger)cmn_resolve_att->slice;
  11911. break;
  11912. case SG_IMAGETYPE_3D:
  11913. pass_desc.colorAttachments[i].resolveDepthPlane = (NSUInteger)cmn_resolve_att->slice;
  11914. break;
  11915. default: break;
  11916. }
  11917. }
  11918. }
  11919. const _sg_image_t* ds_att_img = atts->mtl.depth_stencil.image;
  11920. if (0 != ds_att_img) {
  11921. SOKOL_ASSERT(ds_att_img->slot.state == SG_RESOURCESTATE_VALID);
  11922. SOKOL_ASSERT(ds_att_img->slot.id == atts->cmn.depth_stencil.image_id.id);
  11923. SOKOL_ASSERT(ds_att_img->mtl.tex[ds_att_img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  11924. pass_desc.depthAttachment.texture = _sg_mtl_id(ds_att_img->mtl.tex[ds_att_img->cmn.active_slot]);
  11925. pass_desc.depthAttachment.loadAction = _sg_mtl_load_action(action->depth.load_action);
  11926. pass_desc.depthAttachment.storeAction = _sg_mtl_store_action(action->depth.store_action, false);
  11927. pass_desc.depthAttachment.clearDepth = action->depth.clear_value;
  11928. const _sg_attachment_common_t* cmn_ds_att = &atts->cmn.depth_stencil;
  11929. switch (ds_att_img->cmn.type) {
  11930. case SG_IMAGETYPE_CUBE:
  11931. case SG_IMAGETYPE_ARRAY:
  11932. pass_desc.depthAttachment.slice = (NSUInteger)cmn_ds_att->slice;
  11933. break;
  11934. case SG_IMAGETYPE_3D:
  11935. pass_desc.depthAttachment.resolveDepthPlane = (NSUInteger)cmn_ds_att->slice;
  11936. break;
  11937. default: break;
  11938. }
  11939. if (_sg_is_depth_stencil_format(ds_att_img->cmn.pixel_format)) {
  11940. pass_desc.stencilAttachment.texture = _sg_mtl_id(ds_att_img->mtl.tex[ds_att_img->cmn.active_slot]);
  11941. pass_desc.stencilAttachment.loadAction = _sg_mtl_load_action(action->stencil.load_action);
  11942. pass_desc.stencilAttachment.storeAction = _sg_mtl_store_action(action->depth.store_action, false);
  11943. pass_desc.stencilAttachment.clearStencil = action->stencil.clear_value;
  11944. switch (ds_att_img->cmn.type) {
  11945. case SG_IMAGETYPE_CUBE:
  11946. case SG_IMAGETYPE_ARRAY:
  11947. pass_desc.stencilAttachment.slice = (NSUInteger)cmn_ds_att->slice;
  11948. break;
  11949. case SG_IMAGETYPE_3D:
  11950. pass_desc.stencilAttachment.resolveDepthPlane = (NSUInteger)cmn_ds_att->slice;
  11951. break;
  11952. default: break;
  11953. }
  11954. }
  11955. }
  11956. } else {
  11957. // setup pass descriptor for swapchain rendering
  11958. //
  11959. // NOTE: at least in macOS Sonoma this no longer seems to be the case, the
  11960. // current drawable is also valid in a minimized window
  11961. // ===
  11962. // an MTKView current_drawable will not be valid if window is minimized, don't do any rendering in this case
  11963. if (0 == swapchain->metal.current_drawable) {
  11964. _sg.cur_pass.valid = false;
  11965. return;
  11966. }
  11967. // pin the swapchain resources into memory so that they outlive their command buffer
  11968. // (this is necessary because the command buffer doesn't retain references)
  11969. int pass_desc_ref = _sg_mtl_add_resource(pass_desc);
  11970. _sg_mtl_release_resource(_sg.frame_index, pass_desc_ref);
  11971. _sg.mtl.cur_drawable = (__bridge id<CAMetalDrawable>) swapchain->metal.current_drawable;
  11972. if (swapchain->sample_count > 1) {
  11973. // multi-sampling: render into msaa texture, resolve into drawable texture
  11974. id<MTLTexture> msaa_tex = (__bridge id<MTLTexture>) swapchain->metal.msaa_color_texture;
  11975. SOKOL_ASSERT(msaa_tex != nil);
  11976. pass_desc.colorAttachments[0].texture = msaa_tex;
  11977. pass_desc.colorAttachments[0].resolveTexture = _sg.mtl.cur_drawable.texture;
  11978. pass_desc.colorAttachments[0].storeAction = MTLStoreActionMultisampleResolve;
  11979. } else {
  11980. // non-msaa: render into current_drawable
  11981. pass_desc.colorAttachments[0].texture = _sg.mtl.cur_drawable.texture;
  11982. pass_desc.colorAttachments[0].storeAction = MTLStoreActionStore;
  11983. }
  11984. pass_desc.colorAttachments[0].loadAction = _sg_mtl_load_action(action->colors[0].load_action);
  11985. const sg_color c = action->colors[0].clear_value;
  11986. pass_desc.colorAttachments[0].clearColor = MTLClearColorMake(c.r, c.g, c.b, c.a);
  11987. // optional depth-stencil texture
  11988. if (swapchain->metal.depth_stencil_texture) {
  11989. id<MTLTexture> ds_tex = (__bridge id<MTLTexture>) swapchain->metal.depth_stencil_texture;
  11990. SOKOL_ASSERT(ds_tex != nil);
  11991. pass_desc.depthAttachment.texture = ds_tex;
  11992. pass_desc.depthAttachment.storeAction = MTLStoreActionDontCare;
  11993. pass_desc.depthAttachment.loadAction = _sg_mtl_load_action(action->depth.load_action);
  11994. pass_desc.depthAttachment.clearDepth = action->depth.clear_value;
  11995. if (_sg_is_depth_stencil_format(swapchain->depth_format)) {
  11996. pass_desc.stencilAttachment.texture = ds_tex;
  11997. pass_desc.stencilAttachment.storeAction = MTLStoreActionDontCare;
  11998. pass_desc.stencilAttachment.loadAction = _sg_mtl_load_action(action->stencil.load_action);
  11999. pass_desc.stencilAttachment.clearStencil = action->stencil.clear_value;
  12000. }
  12001. }
  12002. }
  12003. // NOTE: at least in macOS Sonoma, the following is no longer the case, a valid
  12004. // render command encoder is also returned in a minimized window
  12005. // ===
  12006. // create a render command encoder, this might return nil if window is minimized
  12007. _sg.mtl.cmd_encoder = [_sg.mtl.cmd_buffer renderCommandEncoderWithDescriptor:pass_desc];
  12008. if (nil == _sg.mtl.cmd_encoder) {
  12009. _sg.cur_pass.valid = false;
  12010. return;
  12011. }
  12012. #if defined(SOKOL_DEBUG)
  12013. if (pass->label) {
  12014. _sg.mtl.cmd_encoder.label = [NSString stringWithUTF8String:pass->label];
  12015. }
  12016. #endif
  12017. // bind uniform buffers, those bindings remain valid for the entire pass
  12018. _sg_mtl_bind_uniform_buffers();
  12019. }
  12020. _SOKOL_PRIVATE void _sg_mtl_end_pass(void) {
  12021. if (nil != _sg.mtl.cmd_encoder) {
  12022. [_sg.mtl.cmd_encoder endEncoding];
  12023. // NOTE: MTLRenderCommandEncoder is autoreleased
  12024. _sg.mtl.cmd_encoder = nil;
  12025. }
  12026. // if this is a swapchain pass, present the drawable
  12027. if (nil != _sg.mtl.cur_drawable) {
  12028. [_sg.mtl.cmd_buffer presentDrawable:_sg.mtl.cur_drawable];
  12029. _sg.mtl.cur_drawable = nil;
  12030. }
  12031. }
  12032. _SOKOL_PRIVATE void _sg_mtl_commit(void) {
  12033. SOKOL_ASSERT(nil == _sg.mtl.cmd_encoder);
  12034. SOKOL_ASSERT(nil != _sg.mtl.cmd_buffer);
  12035. // commit the frame's command buffer
  12036. [_sg.mtl.cmd_buffer commit];
  12037. // garbage-collect resources pending for release
  12038. _sg_mtl_garbage_collect(_sg.frame_index);
  12039. // rotate uniform buffer slot
  12040. if (++_sg.mtl.cur_frame_rotate_index >= SG_NUM_INFLIGHT_FRAMES) {
  12041. _sg.mtl.cur_frame_rotate_index = 0;
  12042. }
  12043. _sg.mtl.cur_ub_offset = 0;
  12044. _sg.mtl.cur_ub_base_ptr = 0;
  12045. // NOTE: MTLCommandBuffer is autoreleased
  12046. _sg.mtl.cmd_buffer = nil;
  12047. }
  12048. _SOKOL_PRIVATE void _sg_mtl_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  12049. SOKOL_ASSERT(nil != _sg.mtl.cmd_encoder);
  12050. SOKOL_ASSERT(_sg.cur_pass.height > 0);
  12051. MTLViewport vp;
  12052. vp.originX = (double) x;
  12053. vp.originY = (double) (origin_top_left ? y : (_sg.cur_pass.height - (y + h)));
  12054. vp.width = (double) w;
  12055. vp.height = (double) h;
  12056. vp.znear = 0.0;
  12057. vp.zfar = 1.0;
  12058. [_sg.mtl.cmd_encoder setViewport:vp];
  12059. }
  12060. _SOKOL_PRIVATE void _sg_mtl_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  12061. SOKOL_ASSERT(nil != _sg.mtl.cmd_encoder);
  12062. SOKOL_ASSERT(_sg.cur_pass.width > 0);
  12063. SOKOL_ASSERT(_sg.cur_pass.height > 0);
  12064. // clip against framebuffer rect
  12065. const _sg_recti_t clip = _sg_clipi(x, y, w, h, _sg.cur_pass.width, _sg.cur_pass.height);
  12066. MTLScissorRect r;
  12067. r.x = (NSUInteger)clip.x;
  12068. r.y = (NSUInteger) (origin_top_left ? clip.y : (_sg.cur_pass.height - (clip.y + clip.h)));
  12069. r.width = (NSUInteger)clip.w;
  12070. r.height = (NSUInteger)clip.h;
  12071. [_sg.mtl.cmd_encoder setScissorRect:r];
  12072. }
  12073. _SOKOL_PRIVATE void _sg_mtl_apply_pipeline(_sg_pipeline_t* pip) {
  12074. SOKOL_ASSERT(pip);
  12075. SOKOL_ASSERT(pip->shader && (pip->cmn.shader_id.id == pip->shader->slot.id));
  12076. SOKOL_ASSERT(nil != _sg.mtl.cmd_encoder);
  12077. if (_sg.mtl.state_cache.cur_pipeline_id.id != pip->slot.id) {
  12078. _sg.mtl.state_cache.cur_pipeline = pip;
  12079. _sg.mtl.state_cache.cur_pipeline_id.id = pip->slot.id;
  12080. sg_color c = pip->cmn.blend_color;
  12081. [_sg.mtl.cmd_encoder setBlendColorRed:c.r green:c.g blue:c.b alpha:c.a];
  12082. _sg_stats_add(metal.pipeline.num_set_blend_color, 1);
  12083. [_sg.mtl.cmd_encoder setCullMode:pip->mtl.cull_mode];
  12084. _sg_stats_add(metal.pipeline.num_set_cull_mode, 1);
  12085. [_sg.mtl.cmd_encoder setFrontFacingWinding:pip->mtl.winding];
  12086. _sg_stats_add(metal.pipeline.num_set_front_facing_winding, 1);
  12087. [_sg.mtl.cmd_encoder setStencilReferenceValue:pip->mtl.stencil_ref];
  12088. _sg_stats_add(metal.pipeline.num_set_stencil_reference_value, 1);
  12089. [_sg.mtl.cmd_encoder setDepthBias:pip->cmn.depth.bias slopeScale:pip->cmn.depth.bias_slope_scale clamp:pip->cmn.depth.bias_clamp];
  12090. _sg_stats_add(metal.pipeline.num_set_depth_bias, 1);
  12091. SOKOL_ASSERT(pip->mtl.rps != _SG_MTL_INVALID_SLOT_INDEX);
  12092. [_sg.mtl.cmd_encoder setRenderPipelineState:_sg_mtl_id(pip->mtl.rps)];
  12093. _sg_stats_add(metal.pipeline.num_set_render_pipeline_state, 1);
  12094. SOKOL_ASSERT(pip->mtl.dss != _SG_MTL_INVALID_SLOT_INDEX);
  12095. [_sg.mtl.cmd_encoder setDepthStencilState:_sg_mtl_id(pip->mtl.dss)];
  12096. _sg_stats_add(metal.pipeline.num_set_depth_stencil_state, 1);
  12097. }
  12098. }
  12099. _SOKOL_PRIVATE bool _sg_mtl_apply_bindings(_sg_bindings_t* bnd) {
  12100. SOKOL_ASSERT(bnd);
  12101. SOKOL_ASSERT(bnd->pip);
  12102. SOKOL_ASSERT(nil != _sg.mtl.cmd_encoder);
  12103. SOKOL_ASSERT(bnd->pip && bnd->pip->shader);
  12104. SOKOL_ASSERT(bnd->pip->shader->slot.id == bnd->pip->cmn.shader_id.id);
  12105. const _sg_shader_t* shd = bnd->pip->shader;
  12106. // store index buffer binding, this will be needed later in sg_draw()
  12107. _sg.mtl.state_cache.cur_indexbuffer = bnd->ib;
  12108. _sg.mtl.state_cache.cur_indexbuffer_offset = bnd->ib_offset;
  12109. if (bnd->ib) {
  12110. SOKOL_ASSERT(bnd->pip->cmn.index_type != SG_INDEXTYPE_NONE);
  12111. _sg.mtl.state_cache.cur_indexbuffer_id.id = bnd->ib->slot.id;
  12112. } else {
  12113. SOKOL_ASSERT(bnd->pip->cmn.index_type == SG_INDEXTYPE_NONE);
  12114. _sg.mtl.state_cache.cur_indexbuffer_id.id = SG_INVALID_ID;
  12115. }
  12116. // apply vertex buffers
  12117. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  12118. const _sg_buffer_t* vb = bnd->vbs[i];
  12119. if (vb == 0) {
  12120. continue;
  12121. }
  12122. const NSUInteger mtl_slot = _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS + i;
  12123. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_BUFFER_BINDINGS);
  12124. const int vb_offset = bnd->vb_offsets[i];
  12125. if ((_sg.mtl.state_cache.cur_vs_buffer_ids[mtl_slot].id != vb->slot.id) ||
  12126. (_sg.mtl.state_cache.cur_vs_buffer_offsets[mtl_slot] != vb_offset))
  12127. {
  12128. _sg.mtl.state_cache.cur_vs_buffer_offsets[mtl_slot] = vb_offset;
  12129. if (_sg.mtl.state_cache.cur_vs_buffer_ids[mtl_slot].id != vb->slot.id) {
  12130. _sg.mtl.state_cache.cur_vs_buffer_ids[mtl_slot].id = vb->slot.id;
  12131. SOKOL_ASSERT(vb->mtl.buf[vb->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  12132. [_sg.mtl.cmd_encoder setVertexBuffer:_sg_mtl_id(vb->mtl.buf[vb->cmn.active_slot])
  12133. offset:(NSUInteger)vb_offset
  12134. atIndex:mtl_slot];
  12135. } else {
  12136. [_sg.mtl.cmd_encoder setVertexBufferOffset:(NSUInteger)vb_offset atIndex:mtl_slot];
  12137. }
  12138. _sg_stats_add(metal.bindings.num_set_vertex_buffer, 1);
  12139. }
  12140. }
  12141. // apply image bindings
  12142. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  12143. const _sg_image_t* img = bnd->imgs[i];
  12144. if (img == 0) {
  12145. continue;
  12146. }
  12147. SOKOL_ASSERT(img->mtl.tex[img->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  12148. const sg_shader_stage stage = shd->cmn.images[i].stage;
  12149. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT));
  12150. const NSUInteger mtl_slot = shd->mtl.img_texture_n[i];
  12151. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_IMAGE_BINDINGS);
  12152. if (stage == SG_SHADERSTAGE_VERTEX) {
  12153. if (_sg.mtl.state_cache.cur_vs_image_ids[mtl_slot].id != img->slot.id) {
  12154. _sg.mtl.state_cache.cur_vs_image_ids[mtl_slot].id = img->slot.id;
  12155. [_sg.mtl.cmd_encoder setVertexTexture:_sg_mtl_id(img->mtl.tex[img->cmn.active_slot]) atIndex:mtl_slot];
  12156. _sg_stats_add(metal.bindings.num_set_vertex_texture, 1);
  12157. }
  12158. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  12159. if (_sg.mtl.state_cache.cur_fs_image_ids[mtl_slot].id != img->slot.id) {
  12160. _sg.mtl.state_cache.cur_fs_image_ids[mtl_slot].id = img->slot.id;
  12161. [_sg.mtl.cmd_encoder setFragmentTexture:_sg_mtl_id(img->mtl.tex[img->cmn.active_slot]) atIndex:mtl_slot];
  12162. _sg_stats_add(metal.bindings.num_set_fragment_texture, 1);
  12163. }
  12164. }
  12165. }
  12166. // apply sampler bindings
  12167. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  12168. const _sg_sampler_t* smp = bnd->smps[i];
  12169. if (smp == 0) {
  12170. continue;
  12171. }
  12172. const sg_shader_stage stage = shd->cmn.samplers[i].stage;
  12173. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT));
  12174. const NSUInteger mtl_slot = shd->mtl.smp_sampler_n[i];
  12175. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS);
  12176. if (stage == SG_SHADERSTAGE_VERTEX) {
  12177. if (_sg.mtl.state_cache.cur_vs_sampler_ids[mtl_slot].id != smp->slot.id) {
  12178. _sg.mtl.state_cache.cur_vs_sampler_ids[mtl_slot].id = smp->slot.id;
  12179. SOKOL_ASSERT(smp->mtl.sampler_state != _SG_MTL_INVALID_SLOT_INDEX);
  12180. [_sg.mtl.cmd_encoder setVertexSamplerState:_sg_mtl_id(smp->mtl.sampler_state) atIndex:mtl_slot];
  12181. _sg_stats_add(metal.bindings.num_set_vertex_sampler_state, 1);
  12182. }
  12183. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  12184. if (_sg.mtl.state_cache.cur_fs_sampler_ids[mtl_slot].id != smp->slot.id) {
  12185. _sg.mtl.state_cache.cur_fs_sampler_ids[mtl_slot].id = smp->slot.id;
  12186. SOKOL_ASSERT(smp->mtl.sampler_state != _SG_MTL_INVALID_SLOT_INDEX);
  12187. [_sg.mtl.cmd_encoder setFragmentSamplerState:_sg_mtl_id(smp->mtl.sampler_state) atIndex:mtl_slot];
  12188. _sg_stats_add(metal.bindings.num_set_fragment_sampler_state, 1);
  12189. }
  12190. }
  12191. }
  12192. // apply storage buffer bindings
  12193. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  12194. const _sg_buffer_t* sbuf = bnd->sbufs[i];
  12195. if (sbuf == 0) {
  12196. continue;
  12197. }
  12198. const sg_shader_stage stage = shd->cmn.storage_buffers[i].stage;
  12199. SOKOL_ASSERT((stage == SG_SHADERSTAGE_VERTEX) || (stage == SG_SHADERSTAGE_FRAGMENT));
  12200. const NSUInteger mtl_slot = shd->mtl.sbuf_buffer_n[i];
  12201. SOKOL_ASSERT(mtl_slot < _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS);
  12202. if (stage == SG_SHADERSTAGE_VERTEX) {
  12203. if (_sg.mtl.state_cache.cur_vs_buffer_ids[mtl_slot].id != sbuf->slot.id) {
  12204. _sg.mtl.state_cache.cur_vs_buffer_ids[mtl_slot].id = sbuf->slot.id;
  12205. SOKOL_ASSERT(sbuf->mtl.buf[sbuf->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  12206. [_sg.mtl.cmd_encoder setVertexBuffer:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot]) offset:0 atIndex:mtl_slot];
  12207. _sg_stats_add(metal.bindings.num_set_vertex_buffer, 1);
  12208. }
  12209. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  12210. if (_sg.mtl.state_cache.cur_fs_buffer_ids[mtl_slot].id != sbuf->slot.id) {
  12211. _sg.mtl.state_cache.cur_fs_buffer_ids[mtl_slot].id = sbuf->slot.id;
  12212. SOKOL_ASSERT(sbuf->mtl.buf[sbuf->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  12213. [_sg.mtl.cmd_encoder setFragmentBuffer:_sg_mtl_id(sbuf->mtl.buf[sbuf->cmn.active_slot]) offset:0 atIndex:mtl_slot];
  12214. _sg_stats_add(metal.bindings.num_set_fragment_buffer, 1);
  12215. }
  12216. }
  12217. }
  12218. return true;
  12219. }
  12220. _SOKOL_PRIVATE void _sg_mtl_apply_uniforms(int ub_slot, const sg_range* data) {
  12221. SOKOL_ASSERT(nil != _sg.mtl.cmd_encoder);
  12222. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  12223. SOKOL_ASSERT(((size_t)_sg.mtl.cur_ub_offset + data->size) <= (size_t)_sg.mtl.ub_size);
  12224. SOKOL_ASSERT((_sg.mtl.cur_ub_offset & (_SG_MTL_UB_ALIGN-1)) == 0);
  12225. const _sg_pipeline_t* pip = _sg.mtl.state_cache.cur_pipeline;
  12226. SOKOL_ASSERT(pip && pip->shader);
  12227. SOKOL_ASSERT(pip->slot.id == _sg.mtl.state_cache.cur_pipeline_id.id);
  12228. const _sg_shader_t* shd = pip->shader;
  12229. SOKOL_ASSERT(shd->slot.id == pip->cmn.shader_id.id);
  12230. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  12231. const sg_shader_stage stage = shd->cmn.uniform_blocks[ub_slot].stage;
  12232. const NSUInteger mtl_slot = shd->mtl.ub_buffer_n[ub_slot];
  12233. // copy to global uniform buffer, record offset into cmd encoder, and advance offset
  12234. uint8_t* dst = &_sg.mtl.cur_ub_base_ptr[_sg.mtl.cur_ub_offset];
  12235. memcpy(dst, data->ptr, data->size);
  12236. if (stage == SG_SHADERSTAGE_VERTEX) {
  12237. [_sg.mtl.cmd_encoder setVertexBufferOffset:(NSUInteger)_sg.mtl.cur_ub_offset atIndex:mtl_slot];
  12238. _sg_stats_add(metal.uniforms.num_set_vertex_buffer_offset, 1);
  12239. } else if (stage == SG_SHADERSTAGE_FRAGMENT) {
  12240. [_sg.mtl.cmd_encoder setFragmentBufferOffset:(NSUInteger)_sg.mtl.cur_ub_offset atIndex:mtl_slot];
  12241. _sg_stats_add(metal.uniforms.num_set_fragment_buffer_offset, 1);
  12242. } else {
  12243. SOKOL_UNREACHABLE;
  12244. }
  12245. _sg.mtl.cur_ub_offset = _sg_roundup(_sg.mtl.cur_ub_offset + (int)data->size, _SG_MTL_UB_ALIGN);
  12246. }
  12247. _SOKOL_PRIVATE void _sg_mtl_draw(int base_element, int num_elements, int num_instances) {
  12248. SOKOL_ASSERT(nil != _sg.mtl.cmd_encoder);
  12249. SOKOL_ASSERT(_sg.mtl.state_cache.cur_pipeline && (_sg.mtl.state_cache.cur_pipeline->slot.id == _sg.mtl.state_cache.cur_pipeline_id.id));
  12250. if (SG_INDEXTYPE_NONE != _sg.mtl.state_cache.cur_pipeline->cmn.index_type) {
  12251. // indexed rendering
  12252. SOKOL_ASSERT(_sg.mtl.state_cache.cur_indexbuffer && (_sg.mtl.state_cache.cur_indexbuffer->slot.id == _sg.mtl.state_cache.cur_indexbuffer_id.id));
  12253. const _sg_buffer_t* ib = _sg.mtl.state_cache.cur_indexbuffer;
  12254. SOKOL_ASSERT(ib->mtl.buf[ib->cmn.active_slot] != _SG_MTL_INVALID_SLOT_INDEX);
  12255. const NSUInteger index_buffer_offset = (NSUInteger) (_sg.mtl.state_cache.cur_indexbuffer_offset + base_element * _sg.mtl.state_cache.cur_pipeline->mtl.index_size);
  12256. [_sg.mtl.cmd_encoder drawIndexedPrimitives:_sg.mtl.state_cache.cur_pipeline->mtl.prim_type
  12257. indexCount:(NSUInteger)num_elements
  12258. indexType:_sg.mtl.state_cache.cur_pipeline->mtl.index_type
  12259. indexBuffer:_sg_mtl_id(ib->mtl.buf[ib->cmn.active_slot])
  12260. indexBufferOffset:index_buffer_offset
  12261. instanceCount:(NSUInteger)num_instances];
  12262. } else {
  12263. // non-indexed rendering
  12264. [_sg.mtl.cmd_encoder drawPrimitives:_sg.mtl.state_cache.cur_pipeline->mtl.prim_type
  12265. vertexStart:(NSUInteger)base_element
  12266. vertexCount:(NSUInteger)num_elements
  12267. instanceCount:(NSUInteger)num_instances];
  12268. }
  12269. }
  12270. _SOKOL_PRIVATE void _sg_mtl_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  12271. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  12272. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  12273. buf->cmn.active_slot = 0;
  12274. }
  12275. __unsafe_unretained id<MTLBuffer> mtl_buf = _sg_mtl_id(buf->mtl.buf[buf->cmn.active_slot]);
  12276. void* dst_ptr = [mtl_buf contents];
  12277. memcpy(dst_ptr, data->ptr, data->size);
  12278. #if defined(_SG_TARGET_MACOS)
  12279. if (_sg_mtl_resource_options_storage_mode_managed_or_shared() == MTLResourceStorageModeManaged) {
  12280. [mtl_buf didModifyRange:NSMakeRange(0, data->size)];
  12281. }
  12282. #endif
  12283. }
  12284. _SOKOL_PRIVATE void _sg_mtl_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  12285. SOKOL_ASSERT(buf && data && data->ptr && (data->size > 0));
  12286. if (new_frame) {
  12287. if (++buf->cmn.active_slot >= buf->cmn.num_slots) {
  12288. buf->cmn.active_slot = 0;
  12289. }
  12290. }
  12291. __unsafe_unretained id<MTLBuffer> mtl_buf = _sg_mtl_id(buf->mtl.buf[buf->cmn.active_slot]);
  12292. uint8_t* dst_ptr = (uint8_t*) [mtl_buf contents];
  12293. dst_ptr += buf->cmn.append_pos;
  12294. memcpy(dst_ptr, data->ptr, data->size);
  12295. #if defined(_SG_TARGET_MACOS)
  12296. if (_sg_mtl_resource_options_storage_mode_managed_or_shared() == MTLResourceStorageModeManaged) {
  12297. [mtl_buf didModifyRange:NSMakeRange((NSUInteger)buf->cmn.append_pos, (NSUInteger)data->size)];
  12298. }
  12299. #endif
  12300. }
  12301. _SOKOL_PRIVATE void _sg_mtl_update_image(_sg_image_t* img, const sg_image_data* data) {
  12302. SOKOL_ASSERT(img && data);
  12303. if (++img->cmn.active_slot >= img->cmn.num_slots) {
  12304. img->cmn.active_slot = 0;
  12305. }
  12306. __unsafe_unretained id<MTLTexture> mtl_tex = _sg_mtl_id(img->mtl.tex[img->cmn.active_slot]);
  12307. _sg_mtl_copy_image_data(img, mtl_tex, data);
  12308. }
  12309. _SOKOL_PRIVATE void _sg_mtl_push_debug_group(const char* name) {
  12310. SOKOL_ASSERT(name);
  12311. if (_sg.mtl.cmd_encoder) {
  12312. [_sg.mtl.cmd_encoder pushDebugGroup:[NSString stringWithUTF8String:name]];
  12313. }
  12314. }
  12315. _SOKOL_PRIVATE void _sg_mtl_pop_debug_group(void) {
  12316. if (_sg.mtl.cmd_encoder) {
  12317. [_sg.mtl.cmd_encoder popDebugGroup];
  12318. }
  12319. }
  12320. // ██ ██ ███████ ██████ ██████ ██████ ██ ██ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  12321. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  12322. // ██ █ ██ █████ ██████ ██ ███ ██████ ██ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  12323. // ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  12324. // ███ ███ ███████ ██████ ██████ ██ ██████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  12325. //
  12326. // >>webgpu
  12327. // >>wgpu
  12328. #elif defined(SOKOL_WGPU)
  12329. #if !defined(__EMSCRIPTEN__)
  12330. // FIXME: webgpu.h differences between Dawn and Emscripten webgpu.h
  12331. #define wgpuBufferReference wgpuBufferAddRef
  12332. #define wgpuTextureReference wgpuTextureAddRef
  12333. #define wgpuTextureViewReference wgpuTextureViewAddRef
  12334. #define wgpuSamplerReference wgpuSamplerAddRef
  12335. #define WGPUSType_ShaderModuleWGSLDescriptor WGPUSType_ShaderSourceWGSL
  12336. _SOKOL_PRIVATE WGPUStringView _sg_wgpu_stringview(const char* str) {
  12337. WGPUStringView res;
  12338. if (str) {
  12339. res.data = str;
  12340. res.length = strlen(str);
  12341. } else {
  12342. res.data = 0;
  12343. res.length = 0;
  12344. }
  12345. return res;
  12346. }
  12347. _SOKOL_PRIVATE WGPUOptionalBool _sg_wgpu_optional_bool(bool b) {
  12348. return b ? WGPUOptionalBool_True : WGPUOptionalBool_False;
  12349. }
  12350. #else
  12351. #define _sg_wgpu_stringview(str) str
  12352. #define _sg_wgpu_optional_bool(b) (b)
  12353. #endif
  12354. _SOKOL_PRIVATE WGPUBufferUsage _sg_wgpu_buffer_usage(sg_buffer_type t, sg_usage u) {
  12355. // FIXME: change to WGPUBufferUsage once Emscripten and Dawn webgpu.h agree
  12356. int res = 0;
  12357. if (SG_BUFFERTYPE_VERTEXBUFFER == t) {
  12358. res = WGPUBufferUsage_Vertex;
  12359. } else if (SG_BUFFERTYPE_STORAGEBUFFER == t) {
  12360. res = WGPUBufferUsage_Storage;
  12361. } else {
  12362. res = WGPUBufferUsage_Index;
  12363. }
  12364. if (SG_USAGE_IMMUTABLE != u) {
  12365. res |= WGPUBufferUsage_CopyDst;
  12366. }
  12367. return (WGPUBufferUsage)res;
  12368. }
  12369. _SOKOL_PRIVATE WGPULoadOp _sg_wgpu_load_op(WGPUTextureView view, sg_load_action a) {
  12370. if (0 == view) {
  12371. return WGPULoadOp_Undefined;
  12372. } else switch (a) {
  12373. case SG_LOADACTION_CLEAR:
  12374. case SG_LOADACTION_DONTCARE:
  12375. return WGPULoadOp_Clear;
  12376. case SG_LOADACTION_LOAD:
  12377. return WGPULoadOp_Load;
  12378. default:
  12379. SOKOL_UNREACHABLE;
  12380. return WGPULoadOp_Force32;
  12381. }
  12382. }
  12383. _SOKOL_PRIVATE WGPUStoreOp _sg_wgpu_store_op(WGPUTextureView view, sg_store_action a) {
  12384. if (0 == view) {
  12385. return WGPUStoreOp_Undefined;
  12386. } else switch (a) {
  12387. case SG_STOREACTION_STORE:
  12388. return WGPUStoreOp_Store;
  12389. case SG_STOREACTION_DONTCARE:
  12390. return WGPUStoreOp_Discard;
  12391. default:
  12392. SOKOL_UNREACHABLE;
  12393. return WGPUStoreOp_Force32;
  12394. }
  12395. }
  12396. _SOKOL_PRIVATE WGPUTextureViewDimension _sg_wgpu_texture_view_dimension(sg_image_type t) {
  12397. switch (t) {
  12398. case SG_IMAGETYPE_2D: return WGPUTextureViewDimension_2D;
  12399. case SG_IMAGETYPE_CUBE: return WGPUTextureViewDimension_Cube;
  12400. case SG_IMAGETYPE_3D: return WGPUTextureViewDimension_3D;
  12401. case SG_IMAGETYPE_ARRAY: return WGPUTextureViewDimension_2DArray;
  12402. default: SOKOL_UNREACHABLE; return WGPUTextureViewDimension_Force32;
  12403. }
  12404. }
  12405. _SOKOL_PRIVATE WGPUTextureDimension _sg_wgpu_texture_dimension(sg_image_type t) {
  12406. if (SG_IMAGETYPE_3D == t) {
  12407. return WGPUTextureDimension_3D;
  12408. } else {
  12409. return WGPUTextureDimension_2D;
  12410. }
  12411. }
  12412. _SOKOL_PRIVATE WGPUTextureSampleType _sg_wgpu_texture_sample_type(sg_image_sample_type t, bool msaa) {
  12413. switch (t) {
  12414. case SG_IMAGESAMPLETYPE_FLOAT: return msaa ? WGPUTextureSampleType_UnfilterableFloat : WGPUTextureSampleType_Float;
  12415. case SG_IMAGESAMPLETYPE_DEPTH: return WGPUTextureSampleType_Depth;
  12416. case SG_IMAGESAMPLETYPE_SINT: return WGPUTextureSampleType_Sint;
  12417. case SG_IMAGESAMPLETYPE_UINT: return WGPUTextureSampleType_Uint;
  12418. case SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT: return WGPUTextureSampleType_UnfilterableFloat;
  12419. default: SOKOL_UNREACHABLE; return WGPUTextureSampleType_Force32;
  12420. }
  12421. }
  12422. _SOKOL_PRIVATE WGPUSamplerBindingType _sg_wgpu_sampler_binding_type(sg_sampler_type t) {
  12423. switch (t) {
  12424. case SG_SAMPLERTYPE_FILTERING: return WGPUSamplerBindingType_Filtering;
  12425. case SG_SAMPLERTYPE_COMPARISON: return WGPUSamplerBindingType_Comparison;
  12426. case SG_SAMPLERTYPE_NONFILTERING: return WGPUSamplerBindingType_NonFiltering;
  12427. default: SOKOL_UNREACHABLE; return WGPUSamplerBindingType_Force32;
  12428. }
  12429. }
  12430. _SOKOL_PRIVATE WGPUAddressMode _sg_wgpu_sampler_address_mode(sg_wrap m) {
  12431. switch (m) {
  12432. case SG_WRAP_REPEAT:
  12433. return WGPUAddressMode_Repeat;
  12434. case SG_WRAP_CLAMP_TO_EDGE:
  12435. case SG_WRAP_CLAMP_TO_BORDER:
  12436. return WGPUAddressMode_ClampToEdge;
  12437. case SG_WRAP_MIRRORED_REPEAT:
  12438. return WGPUAddressMode_MirrorRepeat;
  12439. default:
  12440. SOKOL_UNREACHABLE;
  12441. return WGPUAddressMode_Force32;
  12442. }
  12443. }
  12444. _SOKOL_PRIVATE WGPUFilterMode _sg_wgpu_sampler_minmag_filter(sg_filter f) {
  12445. switch (f) {
  12446. case SG_FILTER_NEAREST:
  12447. return WGPUFilterMode_Nearest;
  12448. case SG_FILTER_LINEAR:
  12449. return WGPUFilterMode_Linear;
  12450. default:
  12451. SOKOL_UNREACHABLE;
  12452. return WGPUFilterMode_Force32;
  12453. }
  12454. }
  12455. _SOKOL_PRIVATE WGPUMipmapFilterMode _sg_wgpu_sampler_mipmap_filter(sg_filter f) {
  12456. switch (f) {
  12457. case SG_FILTER_NEAREST:
  12458. return WGPUMipmapFilterMode_Nearest;
  12459. case SG_FILTER_LINEAR:
  12460. return WGPUMipmapFilterMode_Linear;
  12461. default:
  12462. SOKOL_UNREACHABLE;
  12463. return WGPUMipmapFilterMode_Force32;
  12464. }
  12465. }
  12466. _SOKOL_PRIVATE WGPUIndexFormat _sg_wgpu_indexformat(sg_index_type t) {
  12467. // NOTE: there's no WGPUIndexFormat_None
  12468. return (t == SG_INDEXTYPE_UINT16) ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32;
  12469. }
  12470. _SOKOL_PRIVATE WGPUIndexFormat _sg_wgpu_stripindexformat(sg_primitive_type prim_type, sg_index_type idx_type) {
  12471. if (idx_type == SG_INDEXTYPE_NONE) {
  12472. return WGPUIndexFormat_Undefined;
  12473. } else if ((prim_type == SG_PRIMITIVETYPE_LINE_STRIP) || (prim_type == SG_PRIMITIVETYPE_TRIANGLE_STRIP)) {
  12474. return _sg_wgpu_indexformat(idx_type);
  12475. } else {
  12476. return WGPUIndexFormat_Undefined;
  12477. }
  12478. }
  12479. _SOKOL_PRIVATE WGPUVertexStepMode _sg_wgpu_stepmode(sg_vertex_step s) {
  12480. return (s == SG_VERTEXSTEP_PER_VERTEX) ? WGPUVertexStepMode_Vertex : WGPUVertexStepMode_Instance;
  12481. }
  12482. _SOKOL_PRIVATE WGPUVertexFormat _sg_wgpu_vertexformat(sg_vertex_format f) {
  12483. switch (f) {
  12484. case SG_VERTEXFORMAT_FLOAT: return WGPUVertexFormat_Float32;
  12485. case SG_VERTEXFORMAT_FLOAT2: return WGPUVertexFormat_Float32x2;
  12486. case SG_VERTEXFORMAT_FLOAT3: return WGPUVertexFormat_Float32x3;
  12487. case SG_VERTEXFORMAT_FLOAT4: return WGPUVertexFormat_Float32x4;
  12488. case SG_VERTEXFORMAT_BYTE4: return WGPUVertexFormat_Sint8x4;
  12489. case SG_VERTEXFORMAT_BYTE4N: return WGPUVertexFormat_Snorm8x4;
  12490. case SG_VERTEXFORMAT_UBYTE4: return WGPUVertexFormat_Uint8x4;
  12491. case SG_VERTEXFORMAT_UBYTE4N: return WGPUVertexFormat_Unorm8x4;
  12492. case SG_VERTEXFORMAT_SHORT2: return WGPUVertexFormat_Sint16x2;
  12493. case SG_VERTEXFORMAT_SHORT2N: return WGPUVertexFormat_Snorm16x2;
  12494. case SG_VERTEXFORMAT_USHORT2N: return WGPUVertexFormat_Unorm16x2;
  12495. case SG_VERTEXFORMAT_SHORT4: return WGPUVertexFormat_Sint16x4;
  12496. case SG_VERTEXFORMAT_SHORT4N: return WGPUVertexFormat_Snorm16x4;
  12497. case SG_VERTEXFORMAT_USHORT4N: return WGPUVertexFormat_Unorm16x4;
  12498. case SG_VERTEXFORMAT_HALF2: return WGPUVertexFormat_Float16x2;
  12499. case SG_VERTEXFORMAT_HALF4: return WGPUVertexFormat_Float16x4;
  12500. case SG_VERTEXFORMAT_UINT10_N2: return WGPUVertexFormat_Unorm10_10_10_2;
  12501. default:
  12502. SOKOL_UNREACHABLE;
  12503. return WGPUVertexFormat_Force32;
  12504. }
  12505. }
  12506. _SOKOL_PRIVATE WGPUPrimitiveTopology _sg_wgpu_topology(sg_primitive_type t) {
  12507. switch (t) {
  12508. case SG_PRIMITIVETYPE_POINTS: return WGPUPrimitiveTopology_PointList;
  12509. case SG_PRIMITIVETYPE_LINES: return WGPUPrimitiveTopology_LineList;
  12510. case SG_PRIMITIVETYPE_LINE_STRIP: return WGPUPrimitiveTopology_LineStrip;
  12511. case SG_PRIMITIVETYPE_TRIANGLES: return WGPUPrimitiveTopology_TriangleList;
  12512. case SG_PRIMITIVETYPE_TRIANGLE_STRIP: return WGPUPrimitiveTopology_TriangleStrip;
  12513. default:
  12514. SOKOL_UNREACHABLE;
  12515. return WGPUPrimitiveTopology_Force32;
  12516. }
  12517. }
  12518. _SOKOL_PRIVATE WGPUFrontFace _sg_wgpu_frontface(sg_face_winding fw) {
  12519. return (fw == SG_FACEWINDING_CCW) ? WGPUFrontFace_CCW : WGPUFrontFace_CW;
  12520. }
  12521. _SOKOL_PRIVATE WGPUCullMode _sg_wgpu_cullmode(sg_cull_mode cm) {
  12522. switch (cm) {
  12523. case SG_CULLMODE_NONE: return WGPUCullMode_None;
  12524. case SG_CULLMODE_FRONT: return WGPUCullMode_Front;
  12525. case SG_CULLMODE_BACK: return WGPUCullMode_Back;
  12526. default:
  12527. SOKOL_UNREACHABLE;
  12528. return WGPUCullMode_Force32;
  12529. }
  12530. }
  12531. _SOKOL_PRIVATE WGPUTextureFormat _sg_wgpu_textureformat(sg_pixel_format p) {
  12532. switch (p) {
  12533. case SG_PIXELFORMAT_NONE: return WGPUTextureFormat_Undefined;
  12534. case SG_PIXELFORMAT_R8: return WGPUTextureFormat_R8Unorm;
  12535. case SG_PIXELFORMAT_R8SN: return WGPUTextureFormat_R8Snorm;
  12536. case SG_PIXELFORMAT_R8UI: return WGPUTextureFormat_R8Uint;
  12537. case SG_PIXELFORMAT_R8SI: return WGPUTextureFormat_R8Sint;
  12538. case SG_PIXELFORMAT_R16UI: return WGPUTextureFormat_R16Uint;
  12539. case SG_PIXELFORMAT_R16SI: return WGPUTextureFormat_R16Sint;
  12540. case SG_PIXELFORMAT_R16F: return WGPUTextureFormat_R16Float;
  12541. case SG_PIXELFORMAT_RG8: return WGPUTextureFormat_RG8Unorm;
  12542. case SG_PIXELFORMAT_RG8SN: return WGPUTextureFormat_RG8Snorm;
  12543. case SG_PIXELFORMAT_RG8UI: return WGPUTextureFormat_RG8Uint;
  12544. case SG_PIXELFORMAT_RG8SI: return WGPUTextureFormat_RG8Sint;
  12545. case SG_PIXELFORMAT_R32UI: return WGPUTextureFormat_R32Uint;
  12546. case SG_PIXELFORMAT_R32SI: return WGPUTextureFormat_R32Sint;
  12547. case SG_PIXELFORMAT_R32F: return WGPUTextureFormat_R32Float;
  12548. case SG_PIXELFORMAT_RG16UI: return WGPUTextureFormat_RG16Uint;
  12549. case SG_PIXELFORMAT_RG16SI: return WGPUTextureFormat_RG16Sint;
  12550. case SG_PIXELFORMAT_RG16F: return WGPUTextureFormat_RG16Float;
  12551. case SG_PIXELFORMAT_RGBA8: return WGPUTextureFormat_RGBA8Unorm;
  12552. case SG_PIXELFORMAT_SRGB8A8: return WGPUTextureFormat_RGBA8UnormSrgb;
  12553. case SG_PIXELFORMAT_RGBA8SN: return WGPUTextureFormat_RGBA8Snorm;
  12554. case SG_PIXELFORMAT_RGBA8UI: return WGPUTextureFormat_RGBA8Uint;
  12555. case SG_PIXELFORMAT_RGBA8SI: return WGPUTextureFormat_RGBA8Sint;
  12556. case SG_PIXELFORMAT_BGRA8: return WGPUTextureFormat_BGRA8Unorm;
  12557. case SG_PIXELFORMAT_RGB10A2: return WGPUTextureFormat_RGB10A2Unorm;
  12558. case SG_PIXELFORMAT_RG11B10F: return WGPUTextureFormat_RG11B10Ufloat;
  12559. case SG_PIXELFORMAT_RG32UI: return WGPUTextureFormat_RG32Uint;
  12560. case SG_PIXELFORMAT_RG32SI: return WGPUTextureFormat_RG32Sint;
  12561. case SG_PIXELFORMAT_RG32F: return WGPUTextureFormat_RG32Float;
  12562. case SG_PIXELFORMAT_RGBA16UI: return WGPUTextureFormat_RGBA16Uint;
  12563. case SG_PIXELFORMAT_RGBA16SI: return WGPUTextureFormat_RGBA16Sint;
  12564. case SG_PIXELFORMAT_RGBA16F: return WGPUTextureFormat_RGBA16Float;
  12565. case SG_PIXELFORMAT_RGBA32UI: return WGPUTextureFormat_RGBA32Uint;
  12566. case SG_PIXELFORMAT_RGBA32SI: return WGPUTextureFormat_RGBA32Sint;
  12567. case SG_PIXELFORMAT_RGBA32F: return WGPUTextureFormat_RGBA32Float;
  12568. case SG_PIXELFORMAT_DEPTH: return WGPUTextureFormat_Depth32Float;
  12569. case SG_PIXELFORMAT_DEPTH_STENCIL: return WGPUTextureFormat_Depth32FloatStencil8;
  12570. case SG_PIXELFORMAT_BC1_RGBA: return WGPUTextureFormat_BC1RGBAUnorm;
  12571. case SG_PIXELFORMAT_BC2_RGBA: return WGPUTextureFormat_BC2RGBAUnorm;
  12572. case SG_PIXELFORMAT_BC3_RGBA: return WGPUTextureFormat_BC3RGBAUnorm;
  12573. case SG_PIXELFORMAT_BC3_SRGBA: return WGPUTextureFormat_BC3RGBAUnormSrgb;
  12574. case SG_PIXELFORMAT_BC4_R: return WGPUTextureFormat_BC4RUnorm;
  12575. case SG_PIXELFORMAT_BC4_RSN: return WGPUTextureFormat_BC4RSnorm;
  12576. case SG_PIXELFORMAT_BC5_RG: return WGPUTextureFormat_BC5RGUnorm;
  12577. case SG_PIXELFORMAT_BC5_RGSN: return WGPUTextureFormat_BC5RGSnorm;
  12578. case SG_PIXELFORMAT_BC6H_RGBF: return WGPUTextureFormat_BC6HRGBFloat;
  12579. case SG_PIXELFORMAT_BC6H_RGBUF: return WGPUTextureFormat_BC6HRGBUfloat;
  12580. case SG_PIXELFORMAT_BC7_RGBA: return WGPUTextureFormat_BC7RGBAUnorm;
  12581. case SG_PIXELFORMAT_BC7_SRGBA: return WGPUTextureFormat_BC7RGBAUnormSrgb;
  12582. case SG_PIXELFORMAT_ETC2_RGB8: return WGPUTextureFormat_ETC2RGB8Unorm;
  12583. case SG_PIXELFORMAT_ETC2_RGB8A1: return WGPUTextureFormat_ETC2RGB8A1Unorm;
  12584. case SG_PIXELFORMAT_ETC2_RGBA8: return WGPUTextureFormat_ETC2RGBA8Unorm;
  12585. case SG_PIXELFORMAT_ETC2_SRGB8: return WGPUTextureFormat_ETC2RGB8UnormSrgb;
  12586. case SG_PIXELFORMAT_ETC2_SRGB8A8: return WGPUTextureFormat_ETC2RGBA8UnormSrgb;
  12587. case SG_PIXELFORMAT_EAC_R11: return WGPUTextureFormat_EACR11Unorm;
  12588. case SG_PIXELFORMAT_EAC_R11SN: return WGPUTextureFormat_EACR11Snorm;
  12589. case SG_PIXELFORMAT_EAC_RG11: return WGPUTextureFormat_EACRG11Unorm;
  12590. case SG_PIXELFORMAT_EAC_RG11SN: return WGPUTextureFormat_EACRG11Snorm;
  12591. case SG_PIXELFORMAT_RGB9E5: return WGPUTextureFormat_RGB9E5Ufloat;
  12592. case SG_PIXELFORMAT_ASTC_4x4_RGBA: return WGPUTextureFormat_ASTC4x4Unorm;
  12593. case SG_PIXELFORMAT_ASTC_4x4_SRGBA: return WGPUTextureFormat_ASTC4x4UnormSrgb;
  12594. // NOT SUPPORTED
  12595. case SG_PIXELFORMAT_R16:
  12596. case SG_PIXELFORMAT_R16SN:
  12597. case SG_PIXELFORMAT_RG16:
  12598. case SG_PIXELFORMAT_RG16SN:
  12599. case SG_PIXELFORMAT_RGBA16:
  12600. case SG_PIXELFORMAT_RGBA16SN:
  12601. return WGPUTextureFormat_Undefined;
  12602. default:
  12603. SOKOL_UNREACHABLE;
  12604. return WGPUTextureFormat_Force32;
  12605. }
  12606. }
  12607. _SOKOL_PRIVATE WGPUCompareFunction _sg_wgpu_comparefunc(sg_compare_func f) {
  12608. switch (f) {
  12609. case SG_COMPAREFUNC_NEVER: return WGPUCompareFunction_Never;
  12610. case SG_COMPAREFUNC_LESS: return WGPUCompareFunction_Less;
  12611. case SG_COMPAREFUNC_EQUAL: return WGPUCompareFunction_Equal;
  12612. case SG_COMPAREFUNC_LESS_EQUAL: return WGPUCompareFunction_LessEqual;
  12613. case SG_COMPAREFUNC_GREATER: return WGPUCompareFunction_Greater;
  12614. case SG_COMPAREFUNC_NOT_EQUAL: return WGPUCompareFunction_NotEqual;
  12615. case SG_COMPAREFUNC_GREATER_EQUAL: return WGPUCompareFunction_GreaterEqual;
  12616. case SG_COMPAREFUNC_ALWAYS: return WGPUCompareFunction_Always;
  12617. default:
  12618. SOKOL_UNREACHABLE;
  12619. return WGPUCompareFunction_Force32;
  12620. }
  12621. }
  12622. _SOKOL_PRIVATE WGPUStencilOperation _sg_wgpu_stencilop(sg_stencil_op op) {
  12623. switch (op) {
  12624. case SG_STENCILOP_KEEP: return WGPUStencilOperation_Keep;
  12625. case SG_STENCILOP_ZERO: return WGPUStencilOperation_Zero;
  12626. case SG_STENCILOP_REPLACE: return WGPUStencilOperation_Replace;
  12627. case SG_STENCILOP_INCR_CLAMP: return WGPUStencilOperation_IncrementClamp;
  12628. case SG_STENCILOP_DECR_CLAMP: return WGPUStencilOperation_DecrementClamp;
  12629. case SG_STENCILOP_INVERT: return WGPUStencilOperation_Invert;
  12630. case SG_STENCILOP_INCR_WRAP: return WGPUStencilOperation_IncrementWrap;
  12631. case SG_STENCILOP_DECR_WRAP: return WGPUStencilOperation_DecrementWrap;
  12632. default:
  12633. SOKOL_UNREACHABLE;
  12634. return WGPUStencilOperation_Force32;
  12635. }
  12636. }
  12637. _SOKOL_PRIVATE WGPUBlendOperation _sg_wgpu_blendop(sg_blend_op op) {
  12638. switch (op) {
  12639. case SG_BLENDOP_ADD: return WGPUBlendOperation_Add;
  12640. case SG_BLENDOP_SUBTRACT: return WGPUBlendOperation_Subtract;
  12641. case SG_BLENDOP_REVERSE_SUBTRACT: return WGPUBlendOperation_ReverseSubtract;
  12642. case SG_BLENDOP_MIN: return WGPUBlendOperation_Min;
  12643. case SG_BLENDOP_MAX: return WGPUBlendOperation_Max;
  12644. default:
  12645. SOKOL_UNREACHABLE;
  12646. return WGPUBlendOperation_Force32;
  12647. }
  12648. }
  12649. _SOKOL_PRIVATE WGPUBlendFactor _sg_wgpu_blendfactor(sg_blend_factor f) {
  12650. switch (f) {
  12651. case SG_BLENDFACTOR_ZERO: return WGPUBlendFactor_Zero;
  12652. case SG_BLENDFACTOR_ONE: return WGPUBlendFactor_One;
  12653. case SG_BLENDFACTOR_SRC_COLOR: return WGPUBlendFactor_Src;
  12654. case SG_BLENDFACTOR_ONE_MINUS_SRC_COLOR: return WGPUBlendFactor_OneMinusSrc;
  12655. case SG_BLENDFACTOR_SRC_ALPHA: return WGPUBlendFactor_SrcAlpha;
  12656. case SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return WGPUBlendFactor_OneMinusSrcAlpha;
  12657. case SG_BLENDFACTOR_DST_COLOR: return WGPUBlendFactor_Dst;
  12658. case SG_BLENDFACTOR_ONE_MINUS_DST_COLOR: return WGPUBlendFactor_OneMinusDst;
  12659. case SG_BLENDFACTOR_DST_ALPHA: return WGPUBlendFactor_DstAlpha;
  12660. case SG_BLENDFACTOR_ONE_MINUS_DST_ALPHA: return WGPUBlendFactor_OneMinusDstAlpha;
  12661. case SG_BLENDFACTOR_SRC_ALPHA_SATURATED: return WGPUBlendFactor_SrcAlphaSaturated;
  12662. case SG_BLENDFACTOR_BLEND_COLOR: return WGPUBlendFactor_Constant;
  12663. case SG_BLENDFACTOR_ONE_MINUS_BLEND_COLOR: return WGPUBlendFactor_OneMinusConstant;
  12664. // FIXME: separate blend alpha value not supported?
  12665. case SG_BLENDFACTOR_BLEND_ALPHA: return WGPUBlendFactor_Constant;
  12666. case SG_BLENDFACTOR_ONE_MINUS_BLEND_ALPHA: return WGPUBlendFactor_OneMinusConstant;
  12667. default:
  12668. SOKOL_UNREACHABLE;
  12669. return WGPUBlendFactor_Force32;
  12670. }
  12671. }
  12672. _SOKOL_PRIVATE WGPUColorWriteMask _sg_wgpu_colorwritemask(uint8_t m) {
  12673. // FIXME: change to WGPUColorWriteMask once Emscripten and Dawn webgpu.h agree
  12674. int res = 0;
  12675. if (0 != (m & SG_COLORMASK_R)) {
  12676. res |= WGPUColorWriteMask_Red;
  12677. }
  12678. if (0 != (m & SG_COLORMASK_G)) {
  12679. res |= WGPUColorWriteMask_Green;
  12680. }
  12681. if (0 != (m & SG_COLORMASK_B)) {
  12682. res |= WGPUColorWriteMask_Blue;
  12683. }
  12684. if (0 != (m & SG_COLORMASK_A)) {
  12685. res |= WGPUColorWriteMask_Alpha;
  12686. }
  12687. return (WGPUColorWriteMask)res;
  12688. }
  12689. _SOKOL_PRIVATE WGPUShaderStage _sg_wgpu_shader_stage(sg_shader_stage stage) {
  12690. switch (stage) {
  12691. case SG_SHADERSTAGE_VERTEX: return WGPUShaderStage_Vertex;
  12692. case SG_SHADERSTAGE_FRAGMENT: return WGPUShaderStage_Fragment;
  12693. default: SOKOL_UNREACHABLE; return WGPUShaderStage_None;
  12694. }
  12695. }
  12696. _SOKOL_PRIVATE void _sg_wgpu_init_caps(void) {
  12697. _sg.backend = SG_BACKEND_WGPU;
  12698. _sg.features.origin_top_left = true;
  12699. _sg.features.image_clamp_to_border = false;
  12700. _sg.features.mrt_independent_blend_state = true;
  12701. _sg.features.mrt_independent_write_mask = true;
  12702. _sg.features.storage_buffer = true;
  12703. _sg.features.msaa_image_bindings = true;
  12704. wgpuDeviceGetLimits(_sg.wgpu.dev, &_sg.wgpu.limits);
  12705. const WGPULimits* l = &_sg.wgpu.limits.limits;
  12706. _sg.limits.max_image_size_2d = (int) l->maxTextureDimension2D;
  12707. _sg.limits.max_image_size_cube = (int) l->maxTextureDimension2D; // not a bug, see: https://github.com/gpuweb/gpuweb/issues/1327
  12708. _sg.limits.max_image_size_3d = (int) l->maxTextureDimension3D;
  12709. _sg.limits.max_image_size_array = (int) l->maxTextureDimension2D;
  12710. _sg.limits.max_image_array_layers = (int) l->maxTextureArrayLayers;
  12711. _sg.limits.max_vertex_attrs = SG_MAX_VERTEX_ATTRIBUTES;
  12712. // NOTE: no WGPUTextureFormat_R16Unorm
  12713. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R8]);
  12714. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG8]);
  12715. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA8]);
  12716. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_SRGB8A8]);
  12717. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_BGRA8]);
  12718. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_R16F]);
  12719. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RG16F]);
  12720. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGBA16F]);
  12721. _sg_pixelformat_all(&_sg.formats[SG_PIXELFORMAT_RGB10A2]);
  12722. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_R8SN]);
  12723. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG8SN]);
  12724. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGBA8SN]);
  12725. // FIXME: can be made renderable via extension
  12726. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RG11B10F]);
  12727. // NOTE: msaa rendering is possible in WebGPU, but no resolve
  12728. // which is a combination that's not currently supported in sokol-gfx
  12729. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R8UI]);
  12730. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R8SI]);
  12731. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG8UI]);
  12732. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG8SI]);
  12733. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA8UI]);
  12734. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA8SI]);
  12735. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R16UI]);
  12736. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R16SI]);
  12737. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG16UI]);
  12738. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG16SI]);
  12739. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA16UI]);
  12740. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA16SI]);
  12741. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32UI]);
  12742. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32SI]);
  12743. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32UI]);
  12744. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32SI]);
  12745. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32UI]);
  12746. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32SI]);
  12747. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_Float32Filterable)) {
  12748. _sg_pixelformat_sfr(&_sg.formats[SG_PIXELFORMAT_R32F]);
  12749. _sg_pixelformat_sfr(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  12750. _sg_pixelformat_sfr(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  12751. } else {
  12752. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_R32F]);
  12753. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RG32F]);
  12754. _sg_pixelformat_sr(&_sg.formats[SG_PIXELFORMAT_RGBA32F]);
  12755. }
  12756. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH]);
  12757. _sg_pixelformat_srmd(&_sg.formats[SG_PIXELFORMAT_DEPTH_STENCIL]);
  12758. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_RGB9E5]);
  12759. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_TextureCompressionBC)) {
  12760. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC1_RGBA]);
  12761. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC2_RGBA]);
  12762. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_RGBA]);
  12763. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC3_SRGBA]);
  12764. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_R]);
  12765. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC4_RSN]);
  12766. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RG]);
  12767. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC5_RGSN]);
  12768. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBF]);
  12769. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC6H_RGBUF]);
  12770. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_RGBA]);
  12771. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_BC7_SRGBA]);
  12772. }
  12773. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_TextureCompressionETC2)) {
  12774. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8]);
  12775. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8]);
  12776. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGB8A1]);
  12777. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_RGBA8]);
  12778. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ETC2_SRGB8A8]);
  12779. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11]);
  12780. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_R11SN]);
  12781. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11]);
  12782. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_EAC_RG11SN]);
  12783. }
  12784. if (wgpuDeviceHasFeature(_sg.wgpu.dev, WGPUFeatureName_TextureCompressionASTC)) {
  12785. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_RGBA]);
  12786. _sg_pixelformat_sf(&_sg.formats[SG_PIXELFORMAT_ASTC_4x4_SRGBA]);
  12787. }
  12788. }
  12789. _SOKOL_PRIVATE void _sg_wgpu_uniform_buffer_init(const sg_desc* desc) {
  12790. SOKOL_ASSERT(0 == _sg.wgpu.uniform.staging);
  12791. SOKOL_ASSERT(0 == _sg.wgpu.uniform.buf);
  12792. // Add the max-uniform-update size (64 KB) to the requested buffer size,
  12793. // this is to prevent validation errors in the WebGPU implementation
  12794. // if the entire buffer size is used per frame. 64 KB is the allowed
  12795. // max uniform update size on NVIDIA
  12796. //
  12797. // FIXME: is this still needed?
  12798. _sg.wgpu.uniform.num_bytes = (uint32_t)(desc->uniform_buffer_size + _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE);
  12799. _sg.wgpu.uniform.staging = (uint8_t*)_sg_malloc(_sg.wgpu.uniform.num_bytes);
  12800. WGPUBufferDescriptor ub_desc;
  12801. _sg_clear(&ub_desc, sizeof(ub_desc));
  12802. ub_desc.size = _sg.wgpu.uniform.num_bytes;
  12803. ub_desc.usage = WGPUBufferUsage_Uniform|WGPUBufferUsage_CopyDst;
  12804. _sg.wgpu.uniform.buf = wgpuDeviceCreateBuffer(_sg.wgpu.dev, &ub_desc);
  12805. SOKOL_ASSERT(_sg.wgpu.uniform.buf);
  12806. }
  12807. _SOKOL_PRIVATE void _sg_wgpu_uniform_buffer_discard(void) {
  12808. if (_sg.wgpu.uniform.buf) {
  12809. wgpuBufferRelease(_sg.wgpu.uniform.buf);
  12810. _sg.wgpu.uniform.buf = 0;
  12811. }
  12812. if (_sg.wgpu.uniform.staging) {
  12813. _sg_free(_sg.wgpu.uniform.staging);
  12814. _sg.wgpu.uniform.staging = 0;
  12815. }
  12816. }
  12817. _SOKOL_PRIVATE void _sg_wgpu_uniform_buffer_on_commit(void) {
  12818. wgpuQueueWriteBuffer(_sg.wgpu.queue, _sg.wgpu.uniform.buf, 0, _sg.wgpu.uniform.staging, _sg.wgpu.uniform.offset);
  12819. _sg_stats_add(wgpu.uniforms.size_write_buffer, _sg.wgpu.uniform.offset);
  12820. _sg.wgpu.uniform.offset = 0;
  12821. _sg_clear(_sg.wgpu.uniform.bind_offsets, sizeof(_sg.wgpu.uniform.bind_offsets));
  12822. }
  12823. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_pool_init(const sg_desc* desc) {
  12824. SOKOL_ASSERT((desc->wgpu_bindgroups_cache_size > 0) && (desc->wgpu_bindgroups_cache_size < _SG_MAX_POOL_SIZE));
  12825. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  12826. SOKOL_ASSERT(0 == p->bindgroups);
  12827. const int pool_size = desc->wgpu_bindgroups_cache_size;
  12828. _sg_init_pool(&p->pool, pool_size);
  12829. size_t pool_byte_size = sizeof(_sg_wgpu_bindgroup_t) * (size_t)p->pool.size;
  12830. p->bindgroups = (_sg_wgpu_bindgroup_t*) _sg_malloc_clear(pool_byte_size);
  12831. }
  12832. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_pool_discard(void) {
  12833. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  12834. SOKOL_ASSERT(p->bindgroups);
  12835. _sg_free(p->bindgroups); p->bindgroups = 0;
  12836. _sg_discard_pool(&p->pool);
  12837. }
  12838. _SOKOL_PRIVATE _sg_wgpu_bindgroup_t* _sg_wgpu_bindgroup_at(uint32_t bg_id) {
  12839. SOKOL_ASSERT(SG_INVALID_ID != bg_id);
  12840. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  12841. int slot_index = _sg_slot_index(bg_id);
  12842. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < p->pool.size));
  12843. return &p->bindgroups[slot_index];
  12844. }
  12845. _SOKOL_PRIVATE _sg_wgpu_bindgroup_t* _sg_wgpu_lookup_bindgroup(uint32_t bg_id) {
  12846. if (SG_INVALID_ID != bg_id) {
  12847. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_bindgroup_at(bg_id);
  12848. if (bg->slot.id == bg_id) {
  12849. return bg;
  12850. }
  12851. }
  12852. return 0;
  12853. }
  12854. _SOKOL_PRIVATE _sg_wgpu_bindgroup_handle_t _sg_wgpu_alloc_bindgroup(void) {
  12855. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  12856. _sg_wgpu_bindgroup_handle_t res;
  12857. int slot_index = _sg_pool_alloc_index(&p->pool);
  12858. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  12859. res.id = _sg_slot_alloc(&p->pool, &p->bindgroups[slot_index].slot, slot_index);
  12860. } else {
  12861. res.id = SG_INVALID_ID;
  12862. _SG_ERROR(WGPU_BINDGROUPS_POOL_EXHAUSTED);
  12863. }
  12864. return res;
  12865. }
  12866. _SOKOL_PRIVATE void _sg_wgpu_dealloc_bindgroup(_sg_wgpu_bindgroup_t* bg) {
  12867. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_ALLOC) && (bg->slot.id != SG_INVALID_ID));
  12868. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  12869. _sg_pool_free_index(&p->pool, _sg_slot_index(bg->slot.id));
  12870. _sg_reset_slot(&bg->slot);
  12871. }
  12872. _SOKOL_PRIVATE void _sg_wgpu_reset_bindgroup_to_alloc_state(_sg_wgpu_bindgroup_t* bg) {
  12873. SOKOL_ASSERT(bg);
  12874. _sg_slot_t slot = bg->slot;
  12875. _sg_clear(bg, sizeof(_sg_wgpu_bindgroup_t));
  12876. bg->slot = slot;
  12877. bg->slot.state = SG_RESOURCESTATE_ALLOC;
  12878. }
  12879. // MurmurHash64B (see: https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L142)
  12880. _SOKOL_PRIVATE uint64_t _sg_wgpu_hash(const void* key, int len, uint64_t seed) {
  12881. const uint32_t m = 0x5bd1e995;
  12882. const int r = 24;
  12883. uint32_t h1 = (uint32_t)seed ^ (uint32_t)len;
  12884. uint32_t h2 = (uint32_t)(seed >> 32);
  12885. const uint32_t * data = (const uint32_t *)key;
  12886. while (len >= 8) {
  12887. uint32_t k1 = *data++;
  12888. k1 *= m; k1 ^= k1 >> r; k1 *= m;
  12889. h1 *= m; h1 ^= k1;
  12890. len -= 4;
  12891. uint32_t k2 = *data++;
  12892. k2 *= m; k2 ^= k2 >> r; k2 *= m;
  12893. h2 *= m; h2 ^= k2;
  12894. len -= 4;
  12895. }
  12896. if (len >= 4) {
  12897. uint32_t k1 = *data++;
  12898. k1 *= m; k1 ^= k1 >> r; k1 *= m;
  12899. h1 *= m; h1 ^= k1;
  12900. len -= 4;
  12901. }
  12902. switch(len) {
  12903. case 3: h2 ^= (uint32_t)(((unsigned char*)data)[2] << 16);
  12904. case 2: h2 ^= (uint32_t)(((unsigned char*)data)[1] << 8);
  12905. case 1: h2 ^= ((unsigned char*)data)[0];
  12906. h2 *= m;
  12907. };
  12908. h1 ^= h2 >> 18; h1 *= m;
  12909. h2 ^= h1 >> 22; h2 *= m;
  12910. h1 ^= h2 >> 17; h1 *= m;
  12911. h2 ^= h1 >> 19; h2 *= m;
  12912. uint64_t h = h1;
  12913. h = (h << 32) | h2;
  12914. return h;
  12915. }
  12916. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_item(_sg_wgpu_bindgroups_cache_item_type_t type, uint8_t wgpu_binding, uint32_t id) {
  12917. // key pattern is bbbbttttiiiiiiii
  12918. const uint64_t bb = (uint64_t)wgpu_binding;
  12919. const uint64_t tttt = (uint64_t)type;
  12920. const uint64_t iiiiiiii = (uint64_t)id;
  12921. return (bb << 56) | (bb << 48) | (tttt << 32) | iiiiiiii;
  12922. }
  12923. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_pip_item(uint32_t id) {
  12924. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_PIPELINE, 0xFF, id);
  12925. }
  12926. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_image_item(uint8_t wgpu_binding, uint32_t id) {
  12927. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_IMAGE, wgpu_binding, id);
  12928. }
  12929. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_sampler_item(uint8_t wgpu_binding, uint32_t id) {
  12930. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_SAMPLER, wgpu_binding, id);
  12931. }
  12932. _SOKOL_PRIVATE uint64_t _sg_wgpu_bindgroups_cache_sbuf_item(uint8_t wgpu_binding, uint32_t id) {
  12933. return _sg_wgpu_bindgroups_cache_item(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_STORAGEBUFFER, wgpu_binding, id);
  12934. }
  12935. _SOKOL_PRIVATE void _sg_wgpu_init_bindgroups_cache_key(_sg_wgpu_bindgroups_cache_key_t* key, const _sg_bindings_t* bnd) {
  12936. SOKOL_ASSERT(bnd);
  12937. SOKOL_ASSERT(bnd->pip);
  12938. const _sg_shader_t* shd = bnd->pip->shader;
  12939. SOKOL_ASSERT(shd && shd->slot.id == bnd->pip->cmn.shader_id.id);
  12940. _sg_clear(key->items, sizeof(key->items));
  12941. key->items[0] = _sg_wgpu_bindgroups_cache_pip_item(bnd->pip->slot.id);
  12942. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  12943. if (shd->cmn.images[i].stage == SG_SHADERSTAGE_NONE) {
  12944. continue;
  12945. }
  12946. SOKOL_ASSERT(bnd->imgs[i]);
  12947. const size_t item_idx = i + 1;
  12948. SOKOL_ASSERT(item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS);
  12949. SOKOL_ASSERT(0 == key->items[item_idx]);
  12950. const uint8_t wgpu_binding = shd->wgpu.img_grp1_bnd_n[i];
  12951. const uint32_t id = bnd->imgs[i]->slot.id;
  12952. key->items[item_idx] = _sg_wgpu_bindgroups_cache_image_item(wgpu_binding, id);
  12953. }
  12954. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  12955. if (shd->cmn.samplers[i].stage == SG_SHADERSTAGE_NONE) {
  12956. continue;
  12957. }
  12958. SOKOL_ASSERT(bnd->smps[i]);
  12959. const size_t item_idx = i + 1 + SG_MAX_IMAGE_BINDSLOTS;
  12960. SOKOL_ASSERT(item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS);
  12961. SOKOL_ASSERT(0 == key->items[item_idx]);
  12962. const uint8_t wgpu_binding = shd->wgpu.smp_grp1_bnd_n[i];
  12963. const uint32_t id = bnd->smps[i]->slot.id;
  12964. key->items[item_idx] = _sg_wgpu_bindgroups_cache_sampler_item(wgpu_binding, id);
  12965. }
  12966. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  12967. if (shd->cmn.storage_buffers[i].stage == SG_SHADERSTAGE_NONE) {
  12968. continue;
  12969. }
  12970. SOKOL_ASSERT(bnd->sbufs[i]);
  12971. const size_t item_idx = i + 1 + SG_MAX_IMAGE_BINDSLOTS + SG_MAX_SAMPLER_BINDSLOTS;
  12972. SOKOL_ASSERT(item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS);
  12973. SOKOL_ASSERT(0 == key->items[item_idx]);
  12974. const uint8_t wgpu_binding = shd->wgpu.sbuf_grp1_bnd_n[i];
  12975. const uint32_t id = bnd->sbufs[i]->slot.id;
  12976. key->items[item_idx] = _sg_wgpu_bindgroups_cache_sbuf_item(wgpu_binding, id);
  12977. }
  12978. key->hash = _sg_wgpu_hash(&key->items, (int)sizeof(key->items), 0x1234567887654321);
  12979. }
  12980. _SOKOL_PRIVATE bool _sg_wgpu_compare_bindgroups_cache_key(_sg_wgpu_bindgroups_cache_key_t* k0, _sg_wgpu_bindgroups_cache_key_t* k1) {
  12981. SOKOL_ASSERT(k0 && k1);
  12982. if (k0->hash != k1->hash) {
  12983. return false;
  12984. }
  12985. if (memcmp(&k0->items, &k1->items, sizeof(k0->items)) != 0) {
  12986. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_hash_vs_key_mismatch, 1);
  12987. return false;
  12988. }
  12989. return true;
  12990. }
  12991. _SOKOL_PRIVATE _sg_wgpu_bindgroup_t* _sg_wgpu_create_bindgroup(_sg_bindings_t* bnd) {
  12992. SOKOL_ASSERT(_sg.wgpu.dev);
  12993. SOKOL_ASSERT(bnd->pip);
  12994. const _sg_shader_t* shd = bnd->pip->shader;
  12995. SOKOL_ASSERT(shd && (shd->slot.id == bnd->pip->cmn.shader_id.id));
  12996. _sg_stats_add(wgpu.bindings.num_create_bindgroup, 1);
  12997. _sg_wgpu_bindgroup_handle_t bg_id = _sg_wgpu_alloc_bindgroup();
  12998. if (bg_id.id == SG_INVALID_ID) {
  12999. return 0;
  13000. }
  13001. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_bindgroup_at(bg_id.id);
  13002. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_ALLOC));
  13003. // create wgpu bindgroup object (also see _sg_wgpu_create_shader())
  13004. WGPUBindGroupLayout bgl = bnd->pip->shader->wgpu.bgl_img_smp_sbuf;
  13005. SOKOL_ASSERT(bgl);
  13006. WGPUBindGroupEntry bg_entries[_SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES];
  13007. _sg_clear(&bg_entries, sizeof(bg_entries));
  13008. size_t bgl_index = 0;
  13009. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  13010. if (shd->cmn.images[i].stage == SG_SHADERSTAGE_NONE) {
  13011. continue;
  13012. }
  13013. SOKOL_ASSERT(bnd->imgs[i]);
  13014. SOKOL_ASSERT(bgl_index < _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  13015. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  13016. bg_entry->binding = shd->wgpu.img_grp1_bnd_n[i];
  13017. bg_entry->textureView = bnd->imgs[i]->wgpu.view;
  13018. bgl_index += 1;
  13019. }
  13020. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  13021. if (shd->cmn.samplers[i].stage == SG_SHADERSTAGE_NONE) {
  13022. continue;
  13023. }
  13024. SOKOL_ASSERT(bnd->smps[i]);
  13025. SOKOL_ASSERT(bgl_index < _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  13026. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  13027. bg_entry->binding = shd->wgpu.smp_grp1_bnd_n[i];
  13028. bg_entry->sampler = bnd->smps[i]->wgpu.smp;
  13029. bgl_index += 1;
  13030. }
  13031. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13032. if (shd->cmn.storage_buffers[i].stage == SG_SHADERSTAGE_NONE) {
  13033. continue;
  13034. }
  13035. SOKOL_ASSERT(bnd->sbufs[i]);
  13036. SOKOL_ASSERT(bgl_index < _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  13037. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  13038. bg_entry->binding = shd->wgpu.sbuf_grp1_bnd_n[i];
  13039. bg_entry->buffer = bnd->sbufs[i]->wgpu.buf;
  13040. bg_entry->size = (uint64_t) bnd->sbufs[i]->cmn.size;
  13041. bgl_index += 1;
  13042. }
  13043. WGPUBindGroupDescriptor bg_desc;
  13044. _sg_clear(&bg_desc, sizeof(bg_desc));
  13045. bg_desc.layout = bgl;
  13046. bg_desc.entryCount = bgl_index;
  13047. bg_desc.entries = bg_entries;
  13048. bg->bindgroup = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  13049. if (bg->bindgroup == 0) {
  13050. _SG_ERROR(WGPU_CREATEBINDGROUP_FAILED);
  13051. bg->slot.state = SG_RESOURCESTATE_FAILED;
  13052. return bg;
  13053. }
  13054. _sg_wgpu_init_bindgroups_cache_key(&bg->key, bnd);
  13055. bg->slot.state = SG_RESOURCESTATE_VALID;
  13056. return bg;
  13057. }
  13058. _SOKOL_PRIVATE void _sg_wgpu_discard_bindgroup(_sg_wgpu_bindgroup_t* bg) {
  13059. SOKOL_ASSERT(bg);
  13060. _sg_stats_add(wgpu.bindings.num_discard_bindgroup, 1);
  13061. if (bg->slot.state == SG_RESOURCESTATE_VALID) {
  13062. if (bg->bindgroup) {
  13063. wgpuBindGroupRelease(bg->bindgroup);
  13064. bg->bindgroup = 0;
  13065. }
  13066. _sg_wgpu_reset_bindgroup_to_alloc_state(bg);
  13067. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_ALLOC);
  13068. }
  13069. if (bg->slot.state == SG_RESOURCESTATE_ALLOC) {
  13070. _sg_wgpu_dealloc_bindgroup(bg);
  13071. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_INITIAL);
  13072. }
  13073. }
  13074. _SOKOL_PRIVATE void _sg_wgpu_discard_all_bindgroups(void) {
  13075. _sg_wgpu_bindgroups_pool_t* p = &_sg.wgpu.bindgroups_pool;
  13076. for (int i = 0; i < p->pool.size; i++) {
  13077. sg_resource_state state = p->bindgroups[i].slot.state;
  13078. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  13079. _sg_wgpu_discard_bindgroup(&p->bindgroups[i]);
  13080. }
  13081. }
  13082. }
  13083. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_init(const sg_desc* desc) {
  13084. SOKOL_ASSERT(desc);
  13085. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.num == 0);
  13086. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.index_mask == 0);
  13087. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items == 0);
  13088. const int num = desc->wgpu_bindgroups_cache_size;
  13089. if (num <= 1) {
  13090. _SG_PANIC(WGPU_BINDGROUPSCACHE_SIZE_GREATER_ONE);
  13091. }
  13092. if (!_sg_ispow2(num)) {
  13093. _SG_PANIC(WGPU_BINDGROUPSCACHE_SIZE_POW2);
  13094. }
  13095. _sg.wgpu.bindgroups_cache.num = (uint32_t)desc->wgpu_bindgroups_cache_size;
  13096. _sg.wgpu.bindgroups_cache.index_mask = _sg.wgpu.bindgroups_cache.num - 1;
  13097. size_t size_in_bytes = sizeof(_sg_wgpu_bindgroup_handle_t) * (size_t)num;
  13098. _sg.wgpu.bindgroups_cache.items = (_sg_wgpu_bindgroup_handle_t*)_sg_malloc_clear(size_in_bytes);
  13099. }
  13100. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_discard(void) {
  13101. if (_sg.wgpu.bindgroups_cache.items) {
  13102. _sg_free(_sg.wgpu.bindgroups_cache.items);
  13103. _sg.wgpu.bindgroups_cache.items = 0;
  13104. }
  13105. _sg.wgpu.bindgroups_cache.num = 0;
  13106. _sg.wgpu.bindgroups_cache.index_mask = 0;
  13107. }
  13108. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_set(uint64_t hash, uint32_t bg_id) {
  13109. uint32_t index = hash & _sg.wgpu.bindgroups_cache.index_mask;
  13110. SOKOL_ASSERT(index < _sg.wgpu.bindgroups_cache.num);
  13111. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items);
  13112. _sg.wgpu.bindgroups_cache.items[index].id = bg_id;
  13113. }
  13114. _SOKOL_PRIVATE uint32_t _sg_wgpu_bindgroups_cache_get(uint64_t hash) {
  13115. uint32_t index = hash & _sg.wgpu.bindgroups_cache.index_mask;
  13116. SOKOL_ASSERT(index < _sg.wgpu.bindgroups_cache.num);
  13117. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items);
  13118. return _sg.wgpu.bindgroups_cache.items[index].id;
  13119. }
  13120. // called from wgpu resource destroy functions to also invalidate any
  13121. // bindgroups cache slot and bindgroup referencing that resource
  13122. _SOKOL_PRIVATE void _sg_wgpu_bindgroups_cache_invalidate(_sg_wgpu_bindgroups_cache_item_type_t type, uint32_t id) {
  13123. const uint64_t key_mask = 0x0000FFFFFFFFFFFF;
  13124. const uint64_t key_item = _sg_wgpu_bindgroups_cache_item(type, 0, id) & key_mask;
  13125. SOKOL_ASSERT(_sg.wgpu.bindgroups_cache.items);
  13126. for (uint32_t cache_item_idx = 0; cache_item_idx < _sg.wgpu.bindgroups_cache.num; cache_item_idx++) {
  13127. const uint32_t bg_id = _sg.wgpu.bindgroups_cache.items[cache_item_idx].id;
  13128. if (bg_id != SG_INVALID_ID) {
  13129. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_lookup_bindgroup(bg_id);
  13130. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_VALID));
  13131. // check if resource is in bindgroup, if yes discard bindgroup and invalidate cache slot
  13132. bool invalidate_cache_item = false;
  13133. for (int key_item_idx = 0; key_item_idx < _SG_WGPU_BINDGROUPSCACHEKEY_NUM_ITEMS; key_item_idx++) {
  13134. if ((bg->key.items[key_item_idx] & key_mask) == key_item) {
  13135. invalidate_cache_item = true;
  13136. break;
  13137. }
  13138. }
  13139. if (invalidate_cache_item) {
  13140. _sg_wgpu_discard_bindgroup(bg); bg = 0;
  13141. _sg_wgpu_bindgroups_cache_set(cache_item_idx, SG_INVALID_ID);
  13142. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_invalidates, 1);
  13143. }
  13144. }
  13145. }
  13146. }
  13147. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_clear(void) {
  13148. memset(&_sg.wgpu.bindings_cache, 0, sizeof(_sg.wgpu.bindings_cache));
  13149. }
  13150. _SOKOL_PRIVATE bool _sg_wgpu_bindings_cache_vb_dirty(size_t index, const _sg_buffer_t* vb, uint64_t offset) {
  13151. SOKOL_ASSERT((index >= 0) && (index < SG_MAX_VERTEXBUFFER_BINDSLOTS));
  13152. if (vb) {
  13153. return (_sg.wgpu.bindings_cache.vbs[index].buffer.id != vb->slot.id)
  13154. || (_sg.wgpu.bindings_cache.vbs[index].offset != offset);
  13155. } else {
  13156. return _sg.wgpu.bindings_cache.vbs[index].buffer.id != SG_INVALID_ID;
  13157. }
  13158. }
  13159. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_vb_update(size_t index, const _sg_buffer_t* vb, uint64_t offset) {
  13160. SOKOL_ASSERT((index >= 0) && (index < SG_MAX_VERTEXBUFFER_BINDSLOTS));
  13161. if (vb) {
  13162. _sg.wgpu.bindings_cache.vbs[index].buffer.id = vb->slot.id;
  13163. _sg.wgpu.bindings_cache.vbs[index].offset = offset;
  13164. } else {
  13165. _sg.wgpu.bindings_cache.vbs[index].buffer.id = SG_INVALID_ID;
  13166. _sg.wgpu.bindings_cache.vbs[index].offset = 0;
  13167. }
  13168. }
  13169. _SOKOL_PRIVATE bool _sg_wgpu_bindings_cache_ib_dirty(const _sg_buffer_t* ib, uint64_t offset) {
  13170. if (ib) {
  13171. return (_sg.wgpu.bindings_cache.ib.buffer.id != ib->slot.id)
  13172. || (_sg.wgpu.bindings_cache.ib.offset != offset);
  13173. } else {
  13174. return _sg.wgpu.bindings_cache.ib.buffer.id != SG_INVALID_ID;
  13175. }
  13176. }
  13177. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_ib_update(const _sg_buffer_t* ib, uint64_t offset) {
  13178. if (ib) {
  13179. _sg.wgpu.bindings_cache.ib.buffer.id = ib->slot.id;
  13180. _sg.wgpu.bindings_cache.ib.offset = offset;
  13181. } else {
  13182. _sg.wgpu.bindings_cache.ib.buffer.id = SG_INVALID_ID;
  13183. _sg.wgpu.bindings_cache.ib.offset = 0;
  13184. }
  13185. }
  13186. _SOKOL_PRIVATE bool _sg_wgpu_bindings_cache_bg_dirty(const _sg_wgpu_bindgroup_t* bg) {
  13187. if (bg) {
  13188. return _sg.wgpu.bindings_cache.bg.id != bg->slot.id;
  13189. } else {
  13190. return _sg.wgpu.bindings_cache.bg.id != SG_INVALID_ID;
  13191. }
  13192. }
  13193. _SOKOL_PRIVATE void _sg_wgpu_bindings_cache_bg_update(const _sg_wgpu_bindgroup_t* bg) {
  13194. if (bg) {
  13195. _sg.wgpu.bindings_cache.bg.id = bg->slot.id;
  13196. } else {
  13197. _sg.wgpu.bindings_cache.bg.id = SG_INVALID_ID;
  13198. }
  13199. }
  13200. _SOKOL_PRIVATE void _sg_wgpu_set_img_smp_sbuf_bindgroup(_sg_wgpu_bindgroup_t* bg) {
  13201. if (_sg_wgpu_bindings_cache_bg_dirty(bg)) {
  13202. _sg_wgpu_bindings_cache_bg_update(bg);
  13203. _sg_stats_add(wgpu.bindings.num_set_bindgroup, 1);
  13204. if (bg) {
  13205. SOKOL_ASSERT(bg->slot.state == SG_RESOURCESTATE_VALID);
  13206. SOKOL_ASSERT(bg->bindgroup);
  13207. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.pass_enc, _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, bg->bindgroup, 0, 0);
  13208. } else {
  13209. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.pass_enc, _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  13210. }
  13211. } else {
  13212. _sg_stats_add(wgpu.bindings.num_skip_redundant_bindgroup, 1);
  13213. }
  13214. }
  13215. _SOKOL_PRIVATE bool _sg_wgpu_apply_bindgroup(_sg_bindings_t* bnd) {
  13216. if (!_sg.desc.wgpu_disable_bindgroups_cache) {
  13217. _sg_wgpu_bindgroup_t* bg = 0;
  13218. _sg_wgpu_bindgroups_cache_key_t key;
  13219. _sg_wgpu_init_bindgroups_cache_key(&key, bnd);
  13220. uint32_t bg_id = _sg_wgpu_bindgroups_cache_get(key.hash);
  13221. if (bg_id != SG_INVALID_ID) {
  13222. // potential cache hit
  13223. bg = _sg_wgpu_lookup_bindgroup(bg_id);
  13224. SOKOL_ASSERT(bg && (bg->slot.state == SG_RESOURCESTATE_VALID));
  13225. if (!_sg_wgpu_compare_bindgroups_cache_key(&key, &bg->key)) {
  13226. // cache collision, need to delete cached bindgroup
  13227. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_collisions, 1);
  13228. _sg_wgpu_discard_bindgroup(bg);
  13229. _sg_wgpu_bindgroups_cache_set(key.hash, SG_INVALID_ID);
  13230. bg = 0;
  13231. } else {
  13232. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_hits, 1);
  13233. }
  13234. } else {
  13235. _sg_stats_add(wgpu.bindings.num_bindgroup_cache_misses, 1);
  13236. }
  13237. if (bg == 0) {
  13238. // either no cache entry yet, or cache collision, create new bindgroup and store in cache
  13239. bg = _sg_wgpu_create_bindgroup(bnd);
  13240. _sg_wgpu_bindgroups_cache_set(key.hash, bg->slot.id);
  13241. }
  13242. if (bg && bg->slot.state == SG_RESOURCESTATE_VALID) {
  13243. _sg_wgpu_set_img_smp_sbuf_bindgroup(bg);
  13244. } else {
  13245. return false;
  13246. }
  13247. } else {
  13248. // bindgroups cache disabled, create and destroy bindgroup on the fly (expensive!)
  13249. _sg_wgpu_bindgroup_t* bg = _sg_wgpu_create_bindgroup(bnd);
  13250. if (bg) {
  13251. if (bg->slot.state == SG_RESOURCESTATE_VALID) {
  13252. _sg_wgpu_set_img_smp_sbuf_bindgroup(bg);
  13253. }
  13254. _sg_wgpu_discard_bindgroup(bg);
  13255. } else {
  13256. return false;
  13257. }
  13258. }
  13259. return true;
  13260. }
  13261. _SOKOL_PRIVATE bool _sg_wgpu_apply_index_buffer(_sg_bindings_t* bnd) {
  13262. const _sg_buffer_t* ib = bnd->ib;
  13263. uint64_t offset = (uint64_t)bnd->ib_offset;
  13264. if (_sg_wgpu_bindings_cache_ib_dirty(ib, offset)) {
  13265. _sg_wgpu_bindings_cache_ib_update(ib, offset);
  13266. if (ib) {
  13267. const WGPUIndexFormat format = _sg_wgpu_indexformat(bnd->pip->cmn.index_type);
  13268. const uint64_t buf_size = (uint64_t)ib->cmn.size;
  13269. SOKOL_ASSERT(buf_size > offset);
  13270. const uint64_t max_bytes = buf_size - offset;
  13271. wgpuRenderPassEncoderSetIndexBuffer(_sg.wgpu.pass_enc, ib->wgpu.buf, format, offset, max_bytes);
  13272. /* FIXME: the else-pass should actually set a null index buffer, but that doesn't seem to work yet
  13273. } else {
  13274. wgpuRenderPassEncoderSetIndexBuffer(_sg.wgpu.pass_enc, 0, WGPUIndexFormat_Undefined, 0, 0);
  13275. */
  13276. }
  13277. _sg_stats_add(wgpu.bindings.num_set_index_buffer, 1);
  13278. } else {
  13279. _sg_stats_add(wgpu.bindings.num_skip_redundant_index_buffer, 1);
  13280. }
  13281. return true;
  13282. }
  13283. _SOKOL_PRIVATE bool _sg_wgpu_apply_vertex_buffers(_sg_bindings_t* bnd) {
  13284. for (size_t slot = 0; slot < SG_MAX_VERTEXBUFFER_BINDSLOTS; slot++) {
  13285. const _sg_buffer_t* vb = bnd->vbs[slot];
  13286. const uint64_t offset = (uint64_t)bnd->vb_offsets[slot];
  13287. if (_sg_wgpu_bindings_cache_vb_dirty(slot, vb, offset)) {
  13288. _sg_wgpu_bindings_cache_vb_update(slot, vb, offset);
  13289. if (vb) {
  13290. const uint64_t buf_size = (uint64_t)vb->cmn.size;
  13291. SOKOL_ASSERT(buf_size > offset);
  13292. const uint64_t max_bytes = buf_size - offset;
  13293. wgpuRenderPassEncoderSetVertexBuffer(_sg.wgpu.pass_enc, slot, vb->wgpu.buf, offset, max_bytes);
  13294. /* FIXME: the else-pass should actually set a null vertex buffer, but that doesn't seem to work yet
  13295. } else {
  13296. wgpuRenderPassEncoderSetVertexBuffer(_sg.wgpu.pass_enc, slot, 0, 0, 0);
  13297. */
  13298. }
  13299. _sg_stats_add(wgpu.bindings.num_set_vertex_buffer, 1);
  13300. } else {
  13301. _sg_stats_add(wgpu.bindings.num_skip_redundant_vertex_buffer, 1);
  13302. }
  13303. }
  13304. return true;
  13305. }
  13306. _SOKOL_PRIVATE void _sg_wgpu_setup_backend(const sg_desc* desc) {
  13307. SOKOL_ASSERT(desc);
  13308. SOKOL_ASSERT(desc->environment.wgpu.device);
  13309. SOKOL_ASSERT(desc->uniform_buffer_size > 0);
  13310. _sg.backend = SG_BACKEND_WGPU;
  13311. _sg.wgpu.valid = true;
  13312. _sg.wgpu.dev = (WGPUDevice) desc->environment.wgpu.device;
  13313. _sg.wgpu.queue = wgpuDeviceGetQueue(_sg.wgpu.dev);
  13314. SOKOL_ASSERT(_sg.wgpu.queue);
  13315. _sg_wgpu_init_caps();
  13316. _sg_wgpu_uniform_buffer_init(desc);
  13317. _sg_wgpu_bindgroups_pool_init(desc);
  13318. _sg_wgpu_bindgroups_cache_init(desc);
  13319. _sg_wgpu_bindings_cache_clear();
  13320. // create an empty bind group
  13321. WGPUBindGroupLayoutDescriptor bgl_desc;
  13322. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  13323. WGPUBindGroupLayout empty_bgl = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  13324. SOKOL_ASSERT(empty_bgl);
  13325. WGPUBindGroupDescriptor bg_desc;
  13326. _sg_clear(&bg_desc, sizeof(bg_desc));
  13327. bg_desc.layout = empty_bgl;
  13328. _sg.wgpu.empty_bind_group = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  13329. SOKOL_ASSERT(_sg.wgpu.empty_bind_group);
  13330. wgpuBindGroupLayoutRelease(empty_bgl);
  13331. // create initial per-frame command encoder
  13332. WGPUCommandEncoderDescriptor cmd_enc_desc;
  13333. _sg_clear(&cmd_enc_desc, sizeof(cmd_enc_desc));
  13334. _sg.wgpu.cmd_enc = wgpuDeviceCreateCommandEncoder(_sg.wgpu.dev, &cmd_enc_desc);
  13335. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  13336. }
  13337. _SOKOL_PRIVATE void _sg_wgpu_discard_backend(void) {
  13338. SOKOL_ASSERT(_sg.wgpu.valid);
  13339. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  13340. _sg.wgpu.valid = false;
  13341. _sg_wgpu_discard_all_bindgroups();
  13342. _sg_wgpu_bindgroups_cache_discard();
  13343. _sg_wgpu_bindgroups_pool_discard();
  13344. _sg_wgpu_uniform_buffer_discard();
  13345. wgpuBindGroupRelease(_sg.wgpu.empty_bind_group); _sg.wgpu.empty_bind_group = 0;
  13346. wgpuCommandEncoderRelease(_sg.wgpu.cmd_enc); _sg.wgpu.cmd_enc = 0;
  13347. wgpuQueueRelease(_sg.wgpu.queue); _sg.wgpu.queue = 0;
  13348. }
  13349. _SOKOL_PRIVATE void _sg_wgpu_reset_state_cache(void) {
  13350. _sg_wgpu_bindings_cache_clear();
  13351. }
  13352. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  13353. SOKOL_ASSERT(buf && desc);
  13354. const bool injected = (0 != desc->wgpu_buffer);
  13355. if (injected) {
  13356. buf->wgpu.buf = (WGPUBuffer) desc->wgpu_buffer;
  13357. wgpuBufferReference(buf->wgpu.buf);
  13358. } else {
  13359. // buffer mapping size must be multiple of 4, so round up buffer size (only a problem
  13360. // with index buffers containing odd number of indices)
  13361. const uint64_t wgpu_buf_size = _sg_roundup_u64((uint64_t)buf->cmn.size, 4);
  13362. const bool map_at_creation = (SG_USAGE_IMMUTABLE == buf->cmn.usage);
  13363. WGPUBufferDescriptor wgpu_buf_desc;
  13364. _sg_clear(&wgpu_buf_desc, sizeof(wgpu_buf_desc));
  13365. wgpu_buf_desc.usage = _sg_wgpu_buffer_usage(buf->cmn.type, buf->cmn.usage);
  13366. wgpu_buf_desc.size = wgpu_buf_size;
  13367. wgpu_buf_desc.mappedAtCreation = map_at_creation;
  13368. wgpu_buf_desc.label = _sg_wgpu_stringview(desc->label);
  13369. buf->wgpu.buf = wgpuDeviceCreateBuffer(_sg.wgpu.dev, &wgpu_buf_desc);
  13370. if (0 == buf->wgpu.buf) {
  13371. _SG_ERROR(WGPU_CREATE_BUFFER_FAILED);
  13372. return SG_RESOURCESTATE_FAILED;
  13373. }
  13374. if (map_at_creation) {
  13375. SOKOL_ASSERT(desc->data.ptr && (desc->data.size > 0));
  13376. SOKOL_ASSERT(desc->data.size <= (size_t)buf->cmn.size);
  13377. // FIXME: inefficient on WASM
  13378. void* ptr = wgpuBufferGetMappedRange(buf->wgpu.buf, 0, wgpu_buf_size);
  13379. SOKOL_ASSERT(ptr);
  13380. memcpy(ptr, desc->data.ptr, desc->data.size);
  13381. wgpuBufferUnmap(buf->wgpu.buf);
  13382. }
  13383. }
  13384. return SG_RESOURCESTATE_VALID;
  13385. }
  13386. _SOKOL_PRIVATE void _sg_wgpu_discard_buffer(_sg_buffer_t* buf) {
  13387. SOKOL_ASSERT(buf);
  13388. if (buf->cmn.type == SG_BUFFERTYPE_STORAGEBUFFER) {
  13389. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_STORAGEBUFFER, buf->slot.id);
  13390. }
  13391. if (buf->wgpu.buf) {
  13392. wgpuBufferRelease(buf->wgpu.buf);
  13393. }
  13394. }
  13395. _SOKOL_PRIVATE void _sg_wgpu_copy_buffer_data(const _sg_buffer_t* buf, uint64_t offset, const sg_range* data) {
  13396. SOKOL_ASSERT((offset + data->size) <= (size_t)buf->cmn.size);
  13397. // WebGPU's write-buffer requires the size to be a multiple of four, so we may need to split the copy
  13398. // operation into two writeBuffer calls
  13399. uint64_t clamped_size = data->size & ~3UL;
  13400. uint64_t extra_size = data->size & 3UL;
  13401. SOKOL_ASSERT(extra_size < 4);
  13402. wgpuQueueWriteBuffer(_sg.wgpu.queue, buf->wgpu.buf, offset, data->ptr, clamped_size);
  13403. if (extra_size > 0) {
  13404. const uint64_t extra_src_offset = clamped_size;
  13405. const uint64_t extra_dst_offset = offset + clamped_size;
  13406. uint8_t extra_data[4] = { 0 };
  13407. uint8_t* extra_src_ptr = ((uint8_t*)data->ptr) + extra_src_offset;
  13408. for (size_t i = 0; i < extra_size; i++) {
  13409. extra_data[i] = extra_src_ptr[i];
  13410. }
  13411. wgpuQueueWriteBuffer(_sg.wgpu.queue, buf->wgpu.buf, extra_dst_offset, extra_src_ptr, 4);
  13412. }
  13413. }
  13414. _SOKOL_PRIVATE void _sg_wgpu_copy_image_data(const _sg_image_t* img, WGPUTexture wgpu_tex, const sg_image_data* data) {
  13415. WGPUTextureDataLayout wgpu_layout;
  13416. _sg_clear(&wgpu_layout, sizeof(wgpu_layout));
  13417. WGPUImageCopyTexture wgpu_copy_tex;
  13418. _sg_clear(&wgpu_copy_tex, sizeof(wgpu_copy_tex));
  13419. wgpu_copy_tex.texture = wgpu_tex;
  13420. wgpu_copy_tex.aspect = WGPUTextureAspect_All;
  13421. WGPUExtent3D wgpu_extent;
  13422. _sg_clear(&wgpu_extent, sizeof(wgpu_extent));
  13423. const int num_faces = (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6 : 1;
  13424. for (int face_index = 0; face_index < num_faces; face_index++) {
  13425. for (int mip_index = 0; mip_index < img->cmn.num_mipmaps; mip_index++) {
  13426. wgpu_copy_tex.mipLevel = (uint32_t)mip_index;
  13427. wgpu_copy_tex.origin.z = (uint32_t)face_index;
  13428. int mip_width = _sg_miplevel_dim(img->cmn.width, mip_index);
  13429. int mip_height = _sg_miplevel_dim(img->cmn.height, mip_index);
  13430. int mip_slices;
  13431. switch (img->cmn.type) {
  13432. case SG_IMAGETYPE_CUBE:
  13433. mip_slices = 1;
  13434. break;
  13435. case SG_IMAGETYPE_3D:
  13436. mip_slices = _sg_miplevel_dim(img->cmn.num_slices, mip_index);
  13437. break;
  13438. default:
  13439. mip_slices = img->cmn.num_slices;
  13440. break;
  13441. }
  13442. const int row_pitch = _sg_row_pitch(img->cmn.pixel_format, mip_width, 1);
  13443. const int num_rows = _sg_num_rows(img->cmn.pixel_format, mip_height);
  13444. if (_sg_is_compressed_pixel_format(img->cmn.pixel_format)) {
  13445. mip_width = _sg_roundup(mip_width, 4);
  13446. mip_height = _sg_roundup(mip_height, 4);
  13447. }
  13448. wgpu_layout.offset = 0;
  13449. wgpu_layout.bytesPerRow = (uint32_t)row_pitch;
  13450. wgpu_layout.rowsPerImage = (uint32_t)num_rows;
  13451. wgpu_extent.width = (uint32_t)mip_width;
  13452. wgpu_extent.height = (uint32_t)mip_height;
  13453. wgpu_extent.depthOrArrayLayers = (uint32_t)mip_slices;
  13454. const sg_range* mip_data = &data->subimage[face_index][mip_index];
  13455. wgpuQueueWriteTexture(_sg.wgpu.queue, &wgpu_copy_tex, mip_data->ptr, mip_data->size, &wgpu_layout, &wgpu_extent);
  13456. }
  13457. }
  13458. }
  13459. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  13460. SOKOL_ASSERT(img && desc);
  13461. const bool injected = (0 != desc->wgpu_texture);
  13462. if (injected) {
  13463. img->wgpu.tex = (WGPUTexture)desc->wgpu_texture;
  13464. wgpuTextureReference(img->wgpu.tex);
  13465. img->wgpu.view = (WGPUTextureView)desc->wgpu_texture_view;
  13466. if (img->wgpu.view) {
  13467. wgpuTextureViewReference(img->wgpu.view);
  13468. }
  13469. } else {
  13470. WGPUTextureDescriptor wgpu_tex_desc;
  13471. _sg_clear(&wgpu_tex_desc, sizeof(wgpu_tex_desc));
  13472. wgpu_tex_desc.label = _sg_wgpu_stringview(desc->label);
  13473. wgpu_tex_desc.usage = WGPUTextureUsage_TextureBinding|WGPUTextureUsage_CopyDst;
  13474. if (desc->render_target) {
  13475. wgpu_tex_desc.usage |= WGPUTextureUsage_RenderAttachment;
  13476. }
  13477. wgpu_tex_desc.dimension = _sg_wgpu_texture_dimension(img->cmn.type);
  13478. wgpu_tex_desc.size.width = (uint32_t) img->cmn.width;
  13479. wgpu_tex_desc.size.height = (uint32_t) img->cmn.height;
  13480. if (desc->type == SG_IMAGETYPE_CUBE) {
  13481. wgpu_tex_desc.size.depthOrArrayLayers = 6;
  13482. } else {
  13483. wgpu_tex_desc.size.depthOrArrayLayers = (uint32_t) img->cmn.num_slices;
  13484. }
  13485. wgpu_tex_desc.format = _sg_wgpu_textureformat(img->cmn.pixel_format);
  13486. wgpu_tex_desc.mipLevelCount = (uint32_t) img->cmn.num_mipmaps;
  13487. wgpu_tex_desc.sampleCount = (uint32_t) img->cmn.sample_count;
  13488. img->wgpu.tex = wgpuDeviceCreateTexture(_sg.wgpu.dev, &wgpu_tex_desc);
  13489. if (0 == img->wgpu.tex) {
  13490. _SG_ERROR(WGPU_CREATE_TEXTURE_FAILED);
  13491. return SG_RESOURCESTATE_FAILED;
  13492. }
  13493. if ((img->cmn.usage == SG_USAGE_IMMUTABLE) && !img->cmn.render_target) {
  13494. _sg_wgpu_copy_image_data(img, img->wgpu.tex, &desc->data);
  13495. }
  13496. WGPUTextureViewDescriptor wgpu_texview_desc;
  13497. _sg_clear(&wgpu_texview_desc, sizeof(wgpu_texview_desc));
  13498. wgpu_texview_desc.label = _sg_wgpu_stringview(desc->label);
  13499. wgpu_texview_desc.dimension = _sg_wgpu_texture_view_dimension(img->cmn.type);
  13500. wgpu_texview_desc.mipLevelCount = (uint32_t)img->cmn.num_mipmaps;
  13501. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  13502. wgpu_texview_desc.arrayLayerCount = 6;
  13503. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  13504. wgpu_texview_desc.arrayLayerCount = (uint32_t)img->cmn.num_slices;
  13505. } else {
  13506. wgpu_texview_desc.arrayLayerCount = 1;
  13507. }
  13508. if (_sg_is_depth_or_depth_stencil_format(img->cmn.pixel_format)) {
  13509. wgpu_texview_desc.aspect = WGPUTextureAspect_DepthOnly;
  13510. } else {
  13511. wgpu_texview_desc.aspect = WGPUTextureAspect_All;
  13512. }
  13513. img->wgpu.view = wgpuTextureCreateView(img->wgpu.tex, &wgpu_texview_desc);
  13514. if (0 == img->wgpu.view) {
  13515. _SG_ERROR(WGPU_CREATE_TEXTURE_VIEW_FAILED);
  13516. return SG_RESOURCESTATE_FAILED;
  13517. }
  13518. }
  13519. return SG_RESOURCESTATE_VALID;
  13520. }
  13521. _SOKOL_PRIVATE void _sg_wgpu_discard_image(_sg_image_t* img) {
  13522. SOKOL_ASSERT(img);
  13523. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_IMAGE, img->slot.id);
  13524. if (img->wgpu.view) {
  13525. wgpuTextureViewRelease(img->wgpu.view);
  13526. img->wgpu.view = 0;
  13527. }
  13528. if (img->wgpu.tex) {
  13529. wgpuTextureRelease(img->wgpu.tex);
  13530. img->wgpu.tex = 0;
  13531. }
  13532. }
  13533. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  13534. SOKOL_ASSERT(smp && desc);
  13535. SOKOL_ASSERT(_sg.wgpu.dev);
  13536. const bool injected = (0 != desc->wgpu_sampler);
  13537. if (injected) {
  13538. smp->wgpu.smp = (WGPUSampler) desc->wgpu_sampler;
  13539. wgpuSamplerReference(smp->wgpu.smp);
  13540. } else {
  13541. WGPUSamplerDescriptor wgpu_desc;
  13542. _sg_clear(&wgpu_desc, sizeof(wgpu_desc));
  13543. wgpu_desc.label = _sg_wgpu_stringview(desc->label);
  13544. wgpu_desc.addressModeU = _sg_wgpu_sampler_address_mode(desc->wrap_u);
  13545. wgpu_desc.addressModeV = _sg_wgpu_sampler_address_mode(desc->wrap_v);
  13546. wgpu_desc.addressModeW = _sg_wgpu_sampler_address_mode(desc->wrap_w);
  13547. wgpu_desc.magFilter = _sg_wgpu_sampler_minmag_filter(desc->mag_filter);
  13548. wgpu_desc.minFilter = _sg_wgpu_sampler_minmag_filter(desc->min_filter);
  13549. wgpu_desc.mipmapFilter = _sg_wgpu_sampler_mipmap_filter(desc->mipmap_filter);
  13550. wgpu_desc.lodMinClamp = desc->min_lod;
  13551. wgpu_desc.lodMaxClamp = desc->max_lod;
  13552. wgpu_desc.compare = _sg_wgpu_comparefunc(desc->compare);
  13553. if (wgpu_desc.compare == WGPUCompareFunction_Never) {
  13554. wgpu_desc.compare = WGPUCompareFunction_Undefined;
  13555. }
  13556. wgpu_desc.maxAnisotropy = (uint16_t)desc->max_anisotropy;
  13557. smp->wgpu.smp = wgpuDeviceCreateSampler(_sg.wgpu.dev, &wgpu_desc);
  13558. if (0 == smp->wgpu.smp) {
  13559. _SG_ERROR(WGPU_CREATE_SAMPLER_FAILED);
  13560. return SG_RESOURCESTATE_FAILED;
  13561. }
  13562. }
  13563. return SG_RESOURCESTATE_VALID;
  13564. }
  13565. _SOKOL_PRIVATE void _sg_wgpu_discard_sampler(_sg_sampler_t* smp) {
  13566. SOKOL_ASSERT(smp);
  13567. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_SAMPLER, smp->slot.id);
  13568. if (smp->wgpu.smp) {
  13569. wgpuSamplerRelease(smp->wgpu.smp);
  13570. smp->wgpu.smp = 0;
  13571. }
  13572. }
  13573. _SOKOL_PRIVATE _sg_wgpu_shader_func_t _sg_wgpu_create_shader_func(const sg_shader_function* func, const char* label) {
  13574. SOKOL_ASSERT(func);
  13575. SOKOL_ASSERT(func->source);
  13576. SOKOL_ASSERT(func->entry);
  13577. _sg_wgpu_shader_func_t res;
  13578. _sg_clear(&res, sizeof(res));
  13579. _sg_strcpy(&res.entry, func->entry);
  13580. WGPUShaderModuleWGSLDescriptor wgpu_shdmod_wgsl_desc;
  13581. _sg_clear(&wgpu_shdmod_wgsl_desc, sizeof(wgpu_shdmod_wgsl_desc));
  13582. wgpu_shdmod_wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
  13583. wgpu_shdmod_wgsl_desc.code = _sg_wgpu_stringview(func->source);
  13584. WGPUShaderModuleDescriptor wgpu_shdmod_desc;
  13585. _sg_clear(&wgpu_shdmod_desc, sizeof(wgpu_shdmod_desc));
  13586. wgpu_shdmod_desc.nextInChain = &wgpu_shdmod_wgsl_desc.chain;
  13587. wgpu_shdmod_desc.label = _sg_wgpu_stringview(label);
  13588. res.module = wgpuDeviceCreateShaderModule(_sg.wgpu.dev, &wgpu_shdmod_desc);
  13589. if (0 == res.module) {
  13590. _SG_ERROR(WGPU_CREATE_SHADER_MODULE_FAILED);
  13591. }
  13592. return res;
  13593. }
  13594. _SOKOL_PRIVATE void _sg_wgpu_discard_shader_func(_sg_wgpu_shader_func_t* func) {
  13595. if (func->module) {
  13596. wgpuShaderModuleRelease(func->module);
  13597. func->module = 0;
  13598. }
  13599. }
  13600. typedef struct { uint8_t sokol_slot, wgpu_slot; } _sg_wgpu_dynoffset_mapping_t;
  13601. _SOKOL_PRIVATE int _sg_wgpu_dynoffset_cmp(const void* a, const void* b) {
  13602. const _sg_wgpu_dynoffset_mapping_t* aa = (const _sg_wgpu_dynoffset_mapping_t*)a;
  13603. const _sg_wgpu_dynoffset_mapping_t* bb = (const _sg_wgpu_dynoffset_mapping_t*)b;
  13604. if (aa->wgpu_slot < bb->wgpu_slot) return -1;
  13605. else if (aa->wgpu_slot > bb->wgpu_slot) return 1;
  13606. return 0;
  13607. }
  13608. // NOTE: this is an out-of-range check for WGSL bindslots that's also active in release mode
  13609. _SOKOL_PRIVATE bool _sg_wgpu_ensure_wgsl_bindslot_ranges(const sg_shader_desc* desc) {
  13610. SOKOL_ASSERT(desc);
  13611. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  13612. if (desc->uniform_blocks[i].wgsl_group0_binding_n >= _SG_WGPU_MAX_UB_BINDGROUP_BIND_SLOTS) {
  13613. _SG_ERROR(WGPU_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE);
  13614. return false;
  13615. }
  13616. }
  13617. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13618. if (desc->storage_buffers[i].wgsl_group1_binding_n >= _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS) {
  13619. _SG_ERROR(WGPU_STORAGEBUFFER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  13620. return false;
  13621. }
  13622. }
  13623. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  13624. if (desc->images[i].wgsl_group1_binding_n >= _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS) {
  13625. _SG_ERROR(WGPU_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  13626. return false;
  13627. }
  13628. }
  13629. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  13630. if (desc->samplers[i].wgsl_group1_binding_n >= _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS) {
  13631. _SG_ERROR(WGPU_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  13632. return false;
  13633. }
  13634. }
  13635. return true;
  13636. }
  13637. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  13638. SOKOL_ASSERT(shd && desc);
  13639. SOKOL_ASSERT(desc->vertex_func.source && desc->fragment_func.source);
  13640. SOKOL_ASSERT(shd->wgpu.vertex_func.module == 0);
  13641. SOKOL_ASSERT(shd->wgpu.fragment_func.module == 0);
  13642. SOKOL_ASSERT(shd->wgpu.bgl_ub == 0);
  13643. SOKOL_ASSERT(shd->wgpu.bg_ub == 0);
  13644. SOKOL_ASSERT(shd->wgpu.bgl_img_smp_sbuf == 0);
  13645. // do a release-mode bounds-check on wgsl bindslots, even though out-of-range
  13646. // bindslots can't cause out-of-bounds accesses in the wgpu backend, this
  13647. // is done to be consistent with the other backends
  13648. if (!_sg_wgpu_ensure_wgsl_bindslot_ranges(desc)) {
  13649. return SG_RESOURCESTATE_FAILED;
  13650. }
  13651. // build shader modules
  13652. shd->wgpu.vertex_func = _sg_wgpu_create_shader_func(&desc->vertex_func, desc->label);
  13653. shd->wgpu.fragment_func = _sg_wgpu_create_shader_func(&desc->fragment_func, desc->label);
  13654. if ((shd->wgpu.vertex_func.module == 0) || (shd->wgpu.fragment_func.module == 0)) {
  13655. return SG_RESOURCESTATE_FAILED;
  13656. }
  13657. // create bind group layout and bind group for uniform blocks
  13658. // NOTE also need to create a mapping of sokol ub bind slots to array indices
  13659. // for the dynamic offsets array in the setBindGroup call
  13660. SOKOL_ASSERT(_SG_WGPU_MAX_UB_BINDGROUP_ENTRIES <= _SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES);
  13661. WGPUBindGroupLayoutEntry bgl_entries[_SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES];
  13662. _sg_clear(bgl_entries, sizeof(bgl_entries));
  13663. WGPUBindGroupLayoutDescriptor bgl_desc;
  13664. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  13665. WGPUBindGroupEntry bg_entries[_SG_WGPU_MAX_IMG_SMP_SBUF_BINDGROUP_ENTRIES];
  13666. _sg_clear(&bg_entries, sizeof(bg_entries));
  13667. WGPUBindGroupDescriptor bg_desc;
  13668. _sg_clear(&bg_desc, sizeof(bg_desc));
  13669. _sg_wgpu_dynoffset_mapping_t dynoffset_map[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  13670. _sg_clear(dynoffset_map, sizeof(dynoffset_map));
  13671. size_t bgl_index = 0;
  13672. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  13673. if (shd->cmn.uniform_blocks[i].stage == SG_SHADERSTAGE_NONE) {
  13674. continue;
  13675. }
  13676. shd->wgpu.ub_grp0_bnd_n[i] = desc->uniform_blocks[i].wgsl_group0_binding_n;
  13677. WGPUBindGroupEntry* bg_entry = &bg_entries[bgl_index];
  13678. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  13679. bgl_entry->binding = shd->wgpu.ub_grp0_bnd_n[i];
  13680. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.uniform_blocks[i].stage);
  13681. bgl_entry->buffer.type = WGPUBufferBindingType_Uniform;
  13682. bgl_entry->buffer.hasDynamicOffset = true;
  13683. bg_entry->binding = bgl_entry->binding;
  13684. bg_entry->buffer = _sg.wgpu.uniform.buf;
  13685. bg_entry->size = _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE;
  13686. dynoffset_map[i].sokol_slot = i;
  13687. dynoffset_map[i].wgpu_slot = bgl_entry->binding;
  13688. bgl_index += 1;
  13689. }
  13690. bgl_desc.entryCount = bgl_index;
  13691. bgl_desc.entries = bgl_entries;
  13692. shd->wgpu.bgl_ub = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  13693. SOKOL_ASSERT(shd->wgpu.bgl_ub);
  13694. bg_desc.layout = shd->wgpu.bgl_ub;
  13695. bg_desc.entryCount = bgl_index;
  13696. bg_desc.entries = bg_entries;
  13697. shd->wgpu.bg_ub = wgpuDeviceCreateBindGroup(_sg.wgpu.dev, &bg_desc);
  13698. SOKOL_ASSERT(shd->wgpu.bg_ub);
  13699. // sort the dynoffset_map by wgpu bindings, this is because the
  13700. // dynamic offsets of the WebGPU setBindGroup call must be in
  13701. // 'binding order', not 'bindgroup entry order'
  13702. qsort(dynoffset_map, bgl_index, sizeof(_sg_wgpu_dynoffset_mapping_t), _sg_wgpu_dynoffset_cmp);
  13703. shd->wgpu.ub_num_dynoffsets = bgl_index;
  13704. for (uint8_t i = 0; i < bgl_index; i++) {
  13705. const uint8_t sokol_slot = dynoffset_map[i].sokol_slot;
  13706. shd->wgpu.ub_dynoffsets[sokol_slot] = i;
  13707. }
  13708. // create bind group layout for images, samplers and storage buffers
  13709. _sg_clear(bgl_entries, sizeof(bgl_entries));
  13710. _sg_clear(&bgl_desc, sizeof(bgl_desc));
  13711. bgl_index = 0;
  13712. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  13713. if (shd->cmn.images[i].stage == SG_SHADERSTAGE_NONE) {
  13714. continue;
  13715. }
  13716. const bool msaa = shd->cmn.images[i].multisampled;
  13717. shd->wgpu.img_grp1_bnd_n[i] = desc->images[i].wgsl_group1_binding_n;
  13718. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  13719. bgl_entry->binding = shd->wgpu.img_grp1_bnd_n[i];
  13720. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.images[i].stage);
  13721. bgl_entry->texture.viewDimension = _sg_wgpu_texture_view_dimension(shd->cmn.images[i].image_type);
  13722. bgl_entry->texture.sampleType = _sg_wgpu_texture_sample_type(shd->cmn.images[i].sample_type, msaa);
  13723. bgl_entry->texture.multisampled = msaa;
  13724. bgl_index += 1;
  13725. }
  13726. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  13727. if (shd->cmn.samplers[i].stage == SG_SHADERSTAGE_NONE) {
  13728. continue;
  13729. }
  13730. shd->wgpu.smp_grp1_bnd_n[i] = desc->samplers[i].wgsl_group1_binding_n;
  13731. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  13732. bgl_entry->binding = shd->wgpu.smp_grp1_bnd_n[i];
  13733. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.samplers[i].stage);
  13734. bgl_entry->sampler.type = _sg_wgpu_sampler_binding_type(shd->cmn.samplers[i].sampler_type);
  13735. bgl_index += 1;
  13736. }
  13737. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  13738. if (shd->cmn.storage_buffers[i].stage == SG_SHADERSTAGE_NONE) {
  13739. continue;
  13740. }
  13741. shd->wgpu.sbuf_grp1_bnd_n[i] = desc->storage_buffers[i].wgsl_group1_binding_n;
  13742. WGPUBindGroupLayoutEntry* bgl_entry = &bgl_entries[bgl_index];
  13743. bgl_entry->binding = shd->wgpu.sbuf_grp1_bnd_n[i];
  13744. bgl_entry->visibility = _sg_wgpu_shader_stage(shd->cmn.storage_buffers[i].stage);
  13745. if (shd->cmn.storage_buffers[i].readonly) {
  13746. bgl_entry->buffer.type = WGPUBufferBindingType_ReadOnlyStorage;
  13747. } else {
  13748. bgl_entry->buffer.type = WGPUBufferBindingType_Storage;
  13749. }
  13750. bgl_index += 1;
  13751. }
  13752. bgl_desc.entryCount = bgl_index;
  13753. bgl_desc.entries = bgl_entries;
  13754. shd->wgpu.bgl_img_smp_sbuf = wgpuDeviceCreateBindGroupLayout(_sg.wgpu.dev, &bgl_desc);
  13755. if (shd->wgpu.bgl_img_smp_sbuf == 0) {
  13756. _SG_ERROR(WGPU_SHADER_CREATE_BINDGROUP_LAYOUT_FAILED);
  13757. return SG_RESOURCESTATE_FAILED;
  13758. }
  13759. return SG_RESOURCESTATE_VALID;
  13760. }
  13761. _SOKOL_PRIVATE void _sg_wgpu_discard_shader(_sg_shader_t* shd) {
  13762. SOKOL_ASSERT(shd);
  13763. _sg_wgpu_discard_shader_func(&shd->wgpu.vertex_func);
  13764. _sg_wgpu_discard_shader_func(&shd->wgpu.fragment_func);
  13765. if (shd->wgpu.bgl_ub) {
  13766. wgpuBindGroupLayoutRelease(shd->wgpu.bgl_ub);
  13767. shd->wgpu.bgl_ub = 0;
  13768. }
  13769. if (shd->wgpu.bg_ub) {
  13770. wgpuBindGroupRelease(shd->wgpu.bg_ub);
  13771. shd->wgpu.bg_ub = 0;
  13772. }
  13773. if (shd->wgpu.bgl_img_smp_sbuf) {
  13774. wgpuBindGroupLayoutRelease(shd->wgpu.bgl_img_smp_sbuf);
  13775. shd->wgpu.bgl_img_smp_sbuf = 0;
  13776. }
  13777. }
  13778. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_pipeline(_sg_pipeline_t* pip, _sg_shader_t* shd, const sg_pipeline_desc* desc) {
  13779. SOKOL_ASSERT(pip && shd && desc);
  13780. SOKOL_ASSERT(desc->shader.id == shd->slot.id);
  13781. SOKOL_ASSERT(shd->wgpu.bgl_ub);
  13782. SOKOL_ASSERT(shd->wgpu.bgl_img_smp_sbuf);
  13783. pip->shader = shd;
  13784. pip->wgpu.blend_color.r = (double) desc->blend_color.r;
  13785. pip->wgpu.blend_color.g = (double) desc->blend_color.g;
  13786. pip->wgpu.blend_color.b = (double) desc->blend_color.b;
  13787. pip->wgpu.blend_color.a = (double) desc->blend_color.a;
  13788. // - @group(0) for uniform blocks
  13789. // - @group(1) for all image, sampler and storagebuffer resources
  13790. WGPUBindGroupLayout wgpu_bgl[_SG_WGPU_NUM_BINDGROUPS];
  13791. _sg_clear(&wgpu_bgl, sizeof(wgpu_bgl));
  13792. wgpu_bgl[_SG_WGPU_UB_BINDGROUP_INDEX ] = shd->wgpu.bgl_ub;
  13793. wgpu_bgl[_SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX] = shd->wgpu.bgl_img_smp_sbuf;
  13794. WGPUPipelineLayoutDescriptor wgpu_pl_desc;
  13795. _sg_clear(&wgpu_pl_desc, sizeof(wgpu_pl_desc));
  13796. wgpu_pl_desc.bindGroupLayoutCount = _SG_WGPU_NUM_BINDGROUPS;
  13797. wgpu_pl_desc.bindGroupLayouts = &wgpu_bgl[0];
  13798. const WGPUPipelineLayout wgpu_pip_layout = wgpuDeviceCreatePipelineLayout(_sg.wgpu.dev, &wgpu_pl_desc);
  13799. if (0 == wgpu_pip_layout) {
  13800. _SG_ERROR(WGPU_CREATE_PIPELINE_LAYOUT_FAILED);
  13801. return SG_RESOURCESTATE_FAILED;
  13802. }
  13803. SOKOL_ASSERT(wgpu_pip_layout);
  13804. WGPUVertexBufferLayout wgpu_vb_layouts[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  13805. _sg_clear(wgpu_vb_layouts, sizeof(wgpu_vb_layouts));
  13806. WGPUVertexAttribute wgpu_vtx_attrs[SG_MAX_VERTEXBUFFER_BINDSLOTS][SG_MAX_VERTEX_ATTRIBUTES];
  13807. _sg_clear(wgpu_vtx_attrs, sizeof(wgpu_vtx_attrs));
  13808. int wgpu_vb_num = 0;
  13809. for (int vb_idx = 0; vb_idx < SG_MAX_VERTEXBUFFER_BINDSLOTS; vb_idx++, wgpu_vb_num++) {
  13810. const sg_vertex_buffer_layout_state* vbl_state = &desc->layout.buffers[vb_idx];
  13811. if (0 == vbl_state->stride) {
  13812. break;
  13813. }
  13814. wgpu_vb_layouts[vb_idx].arrayStride = (uint64_t)vbl_state->stride;
  13815. wgpu_vb_layouts[vb_idx].stepMode = _sg_wgpu_stepmode(vbl_state->step_func);
  13816. wgpu_vb_layouts[vb_idx].attributes = &wgpu_vtx_attrs[vb_idx][0];
  13817. }
  13818. for (int va_idx = 0; va_idx < SG_MAX_VERTEX_ATTRIBUTES; va_idx++) {
  13819. const sg_vertex_attr_state* va_state = &desc->layout.attrs[va_idx];
  13820. if (SG_VERTEXFORMAT_INVALID == va_state->format) {
  13821. break;
  13822. }
  13823. const int vb_idx = va_state->buffer_index;
  13824. SOKOL_ASSERT(vb_idx < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  13825. SOKOL_ASSERT(pip->cmn.vertex_buffer_layout_active[vb_idx]);
  13826. const size_t wgpu_attr_idx = wgpu_vb_layouts[vb_idx].attributeCount;
  13827. wgpu_vb_layouts[vb_idx].attributeCount += 1;
  13828. wgpu_vtx_attrs[vb_idx][wgpu_attr_idx].format = _sg_wgpu_vertexformat(va_state->format);
  13829. wgpu_vtx_attrs[vb_idx][wgpu_attr_idx].offset = (uint64_t)va_state->offset;
  13830. wgpu_vtx_attrs[vb_idx][wgpu_attr_idx].shaderLocation = (uint32_t)va_idx;
  13831. }
  13832. WGPURenderPipelineDescriptor wgpu_pip_desc;
  13833. _sg_clear(&wgpu_pip_desc, sizeof(wgpu_pip_desc));
  13834. WGPUDepthStencilState wgpu_ds_state;
  13835. _sg_clear(&wgpu_ds_state, sizeof(wgpu_ds_state));
  13836. WGPUFragmentState wgpu_frag_state;
  13837. _sg_clear(&wgpu_frag_state, sizeof(wgpu_frag_state));
  13838. WGPUColorTargetState wgpu_ctgt_state[SG_MAX_COLOR_ATTACHMENTS];
  13839. _sg_clear(&wgpu_ctgt_state, sizeof(wgpu_ctgt_state));
  13840. WGPUBlendState wgpu_blend_state[SG_MAX_COLOR_ATTACHMENTS];
  13841. _sg_clear(&wgpu_blend_state, sizeof(wgpu_blend_state));
  13842. wgpu_pip_desc.label = _sg_wgpu_stringview(desc->label);
  13843. wgpu_pip_desc.layout = wgpu_pip_layout;
  13844. wgpu_pip_desc.vertex.module = shd->wgpu.vertex_func.module;
  13845. wgpu_pip_desc.vertex.entryPoint = shd->wgpu.vertex_func.entry.buf;
  13846. wgpu_pip_desc.vertex.bufferCount = (size_t)wgpu_vb_num;
  13847. wgpu_pip_desc.vertex.buffers = &wgpu_vb_layouts[0];
  13848. wgpu_pip_desc.primitive.topology = _sg_wgpu_topology(desc->primitive_type);
  13849. wgpu_pip_desc.primitive.stripIndexFormat = _sg_wgpu_stripindexformat(desc->primitive_type, desc->index_type);
  13850. wgpu_pip_desc.primitive.frontFace = _sg_wgpu_frontface(desc->face_winding);
  13851. wgpu_pip_desc.primitive.cullMode = _sg_wgpu_cullmode(desc->cull_mode);
  13852. if (SG_PIXELFORMAT_NONE != desc->depth.pixel_format) {
  13853. wgpu_ds_state.format = _sg_wgpu_textureformat(desc->depth.pixel_format);
  13854. wgpu_ds_state.depthWriteEnabled = _sg_wgpu_optional_bool(desc->depth.write_enabled);
  13855. wgpu_ds_state.depthCompare = _sg_wgpu_comparefunc(desc->depth.compare);
  13856. wgpu_ds_state.stencilFront.compare = _sg_wgpu_comparefunc(desc->stencil.front.compare);
  13857. wgpu_ds_state.stencilFront.failOp = _sg_wgpu_stencilop(desc->stencil.front.fail_op);
  13858. wgpu_ds_state.stencilFront.depthFailOp = _sg_wgpu_stencilop(desc->stencil.front.depth_fail_op);
  13859. wgpu_ds_state.stencilFront.passOp = _sg_wgpu_stencilop(desc->stencil.front.pass_op);
  13860. wgpu_ds_state.stencilBack.compare = _sg_wgpu_comparefunc(desc->stencil.back.compare);
  13861. wgpu_ds_state.stencilBack.failOp = _sg_wgpu_stencilop(desc->stencil.back.fail_op);
  13862. wgpu_ds_state.stencilBack.depthFailOp = _sg_wgpu_stencilop(desc->stencil.back.depth_fail_op);
  13863. wgpu_ds_state.stencilBack.passOp = _sg_wgpu_stencilop(desc->stencil.back.pass_op);
  13864. wgpu_ds_state.stencilReadMask = desc->stencil.read_mask;
  13865. wgpu_ds_state.stencilWriteMask = desc->stencil.write_mask;
  13866. wgpu_ds_state.depthBias = (int32_t)desc->depth.bias;
  13867. wgpu_ds_state.depthBiasSlopeScale = desc->depth.bias_slope_scale;
  13868. wgpu_ds_state.depthBiasClamp = desc->depth.bias_clamp;
  13869. wgpu_pip_desc.depthStencil = &wgpu_ds_state;
  13870. }
  13871. wgpu_pip_desc.multisample.count = (uint32_t)desc->sample_count;
  13872. wgpu_pip_desc.multisample.mask = 0xFFFFFFFF;
  13873. wgpu_pip_desc.multisample.alphaToCoverageEnabled = desc->alpha_to_coverage_enabled;
  13874. if (desc->color_count > 0) {
  13875. wgpu_frag_state.module = shd->wgpu.fragment_func.module;
  13876. wgpu_frag_state.entryPoint = shd->wgpu.fragment_func.entry.buf;
  13877. wgpu_frag_state.targetCount = (size_t)desc->color_count;
  13878. wgpu_frag_state.targets = &wgpu_ctgt_state[0];
  13879. for (int i = 0; i < desc->color_count; i++) {
  13880. SOKOL_ASSERT(i < SG_MAX_COLOR_ATTACHMENTS);
  13881. wgpu_ctgt_state[i].format = _sg_wgpu_textureformat(desc->colors[i].pixel_format);
  13882. wgpu_ctgt_state[i].writeMask = _sg_wgpu_colorwritemask(desc->colors[i].write_mask);
  13883. if (desc->colors[i].blend.enabled) {
  13884. wgpu_ctgt_state[i].blend = &wgpu_blend_state[i];
  13885. wgpu_blend_state[i].color.operation = _sg_wgpu_blendop(desc->colors[i].blend.op_rgb);
  13886. wgpu_blend_state[i].color.srcFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.src_factor_rgb);
  13887. wgpu_blend_state[i].color.dstFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.dst_factor_rgb);
  13888. wgpu_blend_state[i].alpha.operation = _sg_wgpu_blendop(desc->colors[i].blend.op_alpha);
  13889. wgpu_blend_state[i].alpha.srcFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.src_factor_alpha);
  13890. wgpu_blend_state[i].alpha.dstFactor = _sg_wgpu_blendfactor(desc->colors[i].blend.dst_factor_alpha);
  13891. }
  13892. }
  13893. wgpu_pip_desc.fragment = &wgpu_frag_state;
  13894. }
  13895. pip->wgpu.pip = wgpuDeviceCreateRenderPipeline(_sg.wgpu.dev, &wgpu_pip_desc);
  13896. wgpuPipelineLayoutRelease(wgpu_pip_layout);
  13897. if (0 == pip->wgpu.pip) {
  13898. _SG_ERROR(WGPU_CREATE_RENDER_PIPELINE_FAILED);
  13899. return SG_RESOURCESTATE_FAILED;
  13900. }
  13901. return SG_RESOURCESTATE_VALID;
  13902. }
  13903. _SOKOL_PRIVATE void _sg_wgpu_discard_pipeline(_sg_pipeline_t* pip) {
  13904. SOKOL_ASSERT(pip);
  13905. _sg_wgpu_bindgroups_cache_invalidate(_SG_WGPU_BINDGROUPSCACHEITEMTYPE_PIPELINE, pip->slot.id);
  13906. if (pip == _sg.wgpu.cur_pipeline) {
  13907. _sg.wgpu.cur_pipeline = 0;
  13908. _sg.wgpu.cur_pipeline_id.id = SG_INVALID_ID;
  13909. }
  13910. if (pip->wgpu.pip) {
  13911. wgpuRenderPipelineRelease(pip->wgpu.pip);
  13912. pip->wgpu.pip = 0;
  13913. }
  13914. }
  13915. _SOKOL_PRIVATE sg_resource_state _sg_wgpu_create_attachments(_sg_attachments_t* atts, _sg_image_t** color_images, _sg_image_t** resolve_images, _sg_image_t* ds_img, const sg_attachments_desc* desc) {
  13916. SOKOL_ASSERT(atts && desc);
  13917. SOKOL_ASSERT(color_images && resolve_images);
  13918. // copy image pointers and create renderable wgpu texture views
  13919. for (int i = 0; i < atts->cmn.num_colors; i++) {
  13920. const sg_attachment_desc* color_desc = &desc->colors[i];
  13921. _SOKOL_UNUSED(color_desc);
  13922. SOKOL_ASSERT(color_desc->image.id != SG_INVALID_ID);
  13923. SOKOL_ASSERT(0 == atts->wgpu.colors[i].image);
  13924. SOKOL_ASSERT(color_images[i] && (color_images[i]->slot.id == color_desc->image.id));
  13925. SOKOL_ASSERT(_sg_is_valid_rendertarget_color_format(color_images[i]->cmn.pixel_format));
  13926. SOKOL_ASSERT(color_images[i]->wgpu.tex);
  13927. atts->wgpu.colors[i].image = color_images[i];
  13928. WGPUTextureViewDescriptor wgpu_color_view_desc;
  13929. _sg_clear(&wgpu_color_view_desc, sizeof(wgpu_color_view_desc));
  13930. wgpu_color_view_desc.baseMipLevel = (uint32_t) color_desc->mip_level;
  13931. wgpu_color_view_desc.mipLevelCount = 1;
  13932. wgpu_color_view_desc.baseArrayLayer = (uint32_t) color_desc->slice;
  13933. wgpu_color_view_desc.arrayLayerCount = 1;
  13934. atts->wgpu.colors[i].view = wgpuTextureCreateView(color_images[i]->wgpu.tex, &wgpu_color_view_desc);
  13935. if (0 == atts->wgpu.colors[i].view) {
  13936. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  13937. return SG_RESOURCESTATE_FAILED;
  13938. }
  13939. const sg_attachment_desc* resolve_desc = &desc->resolves[i];
  13940. if (resolve_desc->image.id != SG_INVALID_ID) {
  13941. SOKOL_ASSERT(0 == atts->wgpu.resolves[i].image);
  13942. SOKOL_ASSERT(resolve_images[i] && (resolve_images[i]->slot.id == resolve_desc->image.id));
  13943. SOKOL_ASSERT(color_images[i] && (color_images[i]->cmn.pixel_format == resolve_images[i]->cmn.pixel_format));
  13944. SOKOL_ASSERT(resolve_images[i]->wgpu.tex);
  13945. atts->wgpu.resolves[i].image = resolve_images[i];
  13946. WGPUTextureViewDescriptor wgpu_resolve_view_desc;
  13947. _sg_clear(&wgpu_resolve_view_desc, sizeof(wgpu_resolve_view_desc));
  13948. wgpu_resolve_view_desc.baseMipLevel = (uint32_t) resolve_desc->mip_level;
  13949. wgpu_resolve_view_desc.mipLevelCount = 1;
  13950. wgpu_resolve_view_desc.baseArrayLayer = (uint32_t) resolve_desc->slice;
  13951. wgpu_resolve_view_desc.arrayLayerCount = 1;
  13952. atts->wgpu.resolves[i].view = wgpuTextureCreateView(resolve_images[i]->wgpu.tex, &wgpu_resolve_view_desc);
  13953. if (0 == atts->wgpu.resolves[i].view) {
  13954. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  13955. return SG_RESOURCESTATE_FAILED;
  13956. }
  13957. }
  13958. }
  13959. SOKOL_ASSERT(0 == atts->wgpu.depth_stencil.image);
  13960. const sg_attachment_desc* ds_desc = &desc->depth_stencil;
  13961. if (ds_desc->image.id != SG_INVALID_ID) {
  13962. SOKOL_ASSERT(ds_img && (ds_img->slot.id == ds_desc->image.id));
  13963. SOKOL_ASSERT(_sg_is_valid_rendertarget_depth_format(ds_img->cmn.pixel_format));
  13964. SOKOL_ASSERT(ds_img->wgpu.tex);
  13965. atts->wgpu.depth_stencil.image = ds_img;
  13966. WGPUTextureViewDescriptor wgpu_ds_view_desc;
  13967. _sg_clear(&wgpu_ds_view_desc, sizeof(wgpu_ds_view_desc));
  13968. wgpu_ds_view_desc.baseMipLevel = (uint32_t) ds_desc->mip_level;
  13969. wgpu_ds_view_desc.mipLevelCount = 1;
  13970. wgpu_ds_view_desc.baseArrayLayer = (uint32_t) ds_desc->slice;
  13971. wgpu_ds_view_desc.arrayLayerCount = 1;
  13972. atts->wgpu.depth_stencil.view = wgpuTextureCreateView(ds_img->wgpu.tex, &wgpu_ds_view_desc);
  13973. if (0 == atts->wgpu.depth_stencil.view) {
  13974. _SG_ERROR(WGPU_ATTACHMENTS_CREATE_TEXTURE_VIEW_FAILED);
  13975. return SG_RESOURCESTATE_FAILED;
  13976. }
  13977. }
  13978. return SG_RESOURCESTATE_VALID;
  13979. }
  13980. _SOKOL_PRIVATE void _sg_wgpu_discard_attachments(_sg_attachments_t* atts) {
  13981. SOKOL_ASSERT(atts);
  13982. for (int i = 0; i < atts->cmn.num_colors; i++) {
  13983. if (atts->wgpu.colors[i].view) {
  13984. wgpuTextureViewRelease(atts->wgpu.colors[i].view);
  13985. atts->wgpu.colors[i].view = 0;
  13986. }
  13987. if (atts->wgpu.resolves[i].view) {
  13988. wgpuTextureViewRelease(atts->wgpu.resolves[i].view);
  13989. atts->wgpu.resolves[i].view = 0;
  13990. }
  13991. }
  13992. if (atts->wgpu.depth_stencil.view) {
  13993. wgpuTextureViewRelease(atts->wgpu.depth_stencil.view);
  13994. atts->wgpu.depth_stencil.view = 0;
  13995. }
  13996. }
  13997. _SOKOL_PRIVATE _sg_image_t* _sg_wgpu_attachments_color_image(const _sg_attachments_t* atts, int index) {
  13998. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  13999. // NOTE: may return null
  14000. return atts->wgpu.colors[index].image;
  14001. }
  14002. _SOKOL_PRIVATE _sg_image_t* _sg_wgpu_attachments_resolve_image(const _sg_attachments_t* atts, int index) {
  14003. SOKOL_ASSERT(atts && (index >= 0) && (index < SG_MAX_COLOR_ATTACHMENTS));
  14004. // NOTE: may return null
  14005. return atts->wgpu.resolves[index].image;
  14006. }
  14007. _SOKOL_PRIVATE _sg_image_t* _sg_wgpu_attachments_ds_image(const _sg_attachments_t* atts) {
  14008. // NOTE: may return null
  14009. SOKOL_ASSERT(atts);
  14010. return atts->wgpu.depth_stencil.image;
  14011. }
  14012. _SOKOL_PRIVATE void _sg_wgpu_init_color_att(WGPURenderPassColorAttachment* wgpu_att, const sg_color_attachment_action* action, WGPUTextureView color_view, WGPUTextureView resolve_view) {
  14013. wgpu_att->depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
  14014. wgpu_att->view = color_view;
  14015. wgpu_att->resolveTarget = resolve_view;
  14016. wgpu_att->loadOp = _sg_wgpu_load_op(color_view, action->load_action);
  14017. wgpu_att->storeOp = _sg_wgpu_store_op(color_view, action->store_action);
  14018. wgpu_att->clearValue.r = action->clear_value.r;
  14019. wgpu_att->clearValue.g = action->clear_value.g;
  14020. wgpu_att->clearValue.b = action->clear_value.b;
  14021. wgpu_att->clearValue.a = action->clear_value.a;
  14022. }
  14023. _SOKOL_PRIVATE void _sg_wgpu_init_ds_att(WGPURenderPassDepthStencilAttachment* wgpu_att, const sg_pass_action* action, sg_pixel_format fmt, WGPUTextureView view) {
  14024. wgpu_att->view = view;
  14025. wgpu_att->depthLoadOp = _sg_wgpu_load_op(view, action->depth.load_action);
  14026. wgpu_att->depthStoreOp = _sg_wgpu_store_op(view, action->depth.store_action);
  14027. wgpu_att->depthClearValue = action->depth.clear_value;
  14028. wgpu_att->depthReadOnly = false;
  14029. if (_sg_is_depth_stencil_format(fmt)) {
  14030. wgpu_att->stencilLoadOp = _sg_wgpu_load_op(view, action->stencil.load_action);
  14031. wgpu_att->stencilStoreOp = _sg_wgpu_store_op(view, action->stencil.store_action);
  14032. } else {
  14033. wgpu_att->stencilLoadOp = WGPULoadOp_Undefined;
  14034. wgpu_att->stencilStoreOp = WGPUStoreOp_Undefined;
  14035. }
  14036. wgpu_att->stencilClearValue = action->stencil.clear_value;
  14037. wgpu_att->stencilReadOnly = false;
  14038. }
  14039. _SOKOL_PRIVATE void _sg_wgpu_begin_pass(const sg_pass* pass) {
  14040. SOKOL_ASSERT(pass);
  14041. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  14042. SOKOL_ASSERT(_sg.wgpu.dev);
  14043. const _sg_attachments_t* atts = _sg.cur_pass.atts;
  14044. const sg_swapchain* swapchain = &pass->swapchain;
  14045. const sg_pass_action* action = &pass->action;
  14046. _sg.wgpu.cur_pipeline = 0;
  14047. _sg.wgpu.cur_pipeline_id.id = SG_INVALID_ID;
  14048. WGPURenderPassDescriptor wgpu_pass_desc;
  14049. WGPURenderPassColorAttachment wgpu_color_att[SG_MAX_COLOR_ATTACHMENTS];
  14050. WGPURenderPassDepthStencilAttachment wgpu_ds_att;
  14051. _sg_clear(&wgpu_pass_desc, sizeof(wgpu_pass_desc));
  14052. _sg_clear(&wgpu_color_att, sizeof(wgpu_color_att));
  14053. _sg_clear(&wgpu_ds_att, sizeof(wgpu_ds_att));
  14054. wgpu_pass_desc.label = _sg_wgpu_stringview(pass->label);
  14055. if (atts) {
  14056. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_VALID);
  14057. for (int i = 0; i < atts->cmn.num_colors; i++) {
  14058. _sg_wgpu_init_color_att(&wgpu_color_att[i], &action->colors[i], atts->wgpu.colors[i].view, atts->wgpu.resolves[i].view);
  14059. }
  14060. wgpu_pass_desc.colorAttachmentCount = (size_t)atts->cmn.num_colors;
  14061. wgpu_pass_desc.colorAttachments = &wgpu_color_att[0];
  14062. if (atts->wgpu.depth_stencil.image) {
  14063. _sg_wgpu_init_ds_att(&wgpu_ds_att, action, atts->wgpu.depth_stencil.image->cmn.pixel_format, atts->wgpu.depth_stencil.view);
  14064. wgpu_pass_desc.depthStencilAttachment = &wgpu_ds_att;
  14065. }
  14066. } else {
  14067. WGPUTextureView wgpu_color_view = (WGPUTextureView) swapchain->wgpu.render_view;
  14068. WGPUTextureView wgpu_resolve_view = (WGPUTextureView) swapchain->wgpu.resolve_view;
  14069. WGPUTextureView wgpu_depth_stencil_view = (WGPUTextureView) swapchain->wgpu.depth_stencil_view;
  14070. _sg_wgpu_init_color_att(&wgpu_color_att[0], &action->colors[0], wgpu_color_view, wgpu_resolve_view);
  14071. wgpu_pass_desc.colorAttachmentCount = 1;
  14072. wgpu_pass_desc.colorAttachments = &wgpu_color_att[0];
  14073. if (wgpu_depth_stencil_view) {
  14074. SOKOL_ASSERT(swapchain->depth_format > SG_PIXELFORMAT_NONE);
  14075. _sg_wgpu_init_ds_att(&wgpu_ds_att, action, swapchain->depth_format, wgpu_depth_stencil_view);
  14076. wgpu_pass_desc.depthStencilAttachment = &wgpu_ds_att;
  14077. }
  14078. }
  14079. _sg.wgpu.pass_enc = wgpuCommandEncoderBeginRenderPass(_sg.wgpu.cmd_enc, &wgpu_pass_desc);
  14080. SOKOL_ASSERT(_sg.wgpu.pass_enc);
  14081. // clear bindings cache and bindings
  14082. _sg_wgpu_bindings_cache_clear();
  14083. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.pass_enc, _SG_WGPU_UB_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  14084. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.pass_enc, _SG_WGPU_IMG_SMP_SBUF_BINDGROUP_INDEX, _sg.wgpu.empty_bind_group, 0, 0);
  14085. _sg_stats_add(wgpu.bindings.num_set_bindgroup, 1);
  14086. }
  14087. _SOKOL_PRIVATE void _sg_wgpu_end_pass(void) {
  14088. if (_sg.wgpu.pass_enc) {
  14089. wgpuRenderPassEncoderEnd(_sg.wgpu.pass_enc);
  14090. wgpuRenderPassEncoderRelease(_sg.wgpu.pass_enc);
  14091. _sg.wgpu.pass_enc = 0;
  14092. }
  14093. }
  14094. _SOKOL_PRIVATE void _sg_wgpu_commit(void) {
  14095. SOKOL_ASSERT(_sg.wgpu.cmd_enc);
  14096. _sg_wgpu_uniform_buffer_on_commit();
  14097. WGPUCommandBufferDescriptor cmd_buf_desc;
  14098. _sg_clear(&cmd_buf_desc, sizeof(cmd_buf_desc));
  14099. WGPUCommandBuffer wgpu_cmd_buf = wgpuCommandEncoderFinish(_sg.wgpu.cmd_enc, &cmd_buf_desc);
  14100. SOKOL_ASSERT(wgpu_cmd_buf);
  14101. wgpuCommandEncoderRelease(_sg.wgpu.cmd_enc);
  14102. _sg.wgpu.cmd_enc = 0;
  14103. wgpuQueueSubmit(_sg.wgpu.queue, 1, &wgpu_cmd_buf);
  14104. wgpuCommandBufferRelease(wgpu_cmd_buf);
  14105. // create a new render-command-encoder for next frame
  14106. WGPUCommandEncoderDescriptor cmd_enc_desc;
  14107. _sg_clear(&cmd_enc_desc, sizeof(cmd_enc_desc));
  14108. _sg.wgpu.cmd_enc = wgpuDeviceCreateCommandEncoder(_sg.wgpu.dev, &cmd_enc_desc);
  14109. }
  14110. _SOKOL_PRIVATE void _sg_wgpu_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  14111. SOKOL_ASSERT(_sg.wgpu.pass_enc);
  14112. // FIXME FIXME FIXME: CLIPPING THE VIEWPORT HERE IS WRONG!!!
  14113. // (but currently required because WebGPU insists that the viewport rectangle must be
  14114. // fully contained inside the framebuffer, but this doesn't make any sense, and also
  14115. // isn't required by the backend APIs)
  14116. const _sg_recti_t clip = _sg_clipi(x, y, w, h, _sg.cur_pass.width, _sg.cur_pass.height);
  14117. float xf = (float) clip.x;
  14118. float yf = (float) (origin_top_left ? clip.y : (_sg.cur_pass.height - (clip.y + clip.h)));
  14119. float wf = (float) clip.w;
  14120. float hf = (float) clip.h;
  14121. wgpuRenderPassEncoderSetViewport(_sg.wgpu.pass_enc, xf, yf, wf, hf, 0.0f, 1.0f);
  14122. }
  14123. _SOKOL_PRIVATE void _sg_wgpu_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  14124. SOKOL_ASSERT(_sg.wgpu.pass_enc);
  14125. const _sg_recti_t clip = _sg_clipi(x, y, w, h, _sg.cur_pass.width, _sg.cur_pass.height);
  14126. uint32_t sx = (uint32_t) clip.x;
  14127. uint32_t sy = (uint32_t) (origin_top_left ? clip.y : (_sg.cur_pass.height - (clip.y + clip.h)));
  14128. uint32_t sw = (uint32_t) clip.w;
  14129. uint32_t sh = (uint32_t) clip.h;
  14130. wgpuRenderPassEncoderSetScissorRect(_sg.wgpu.pass_enc, sx, sy, sw, sh);
  14131. }
  14132. _SOKOL_PRIVATE void _sg_wgpu_set_ub_bindgroup(const _sg_shader_t* shd) {
  14133. // NOTE: dynamic offsets must be in binding order, not in BindGroupEntry order
  14134. SOKOL_ASSERT(shd->wgpu.ub_num_dynoffsets < SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  14135. uint32_t dyn_offsets[SG_MAX_UNIFORMBLOCK_BINDSLOTS];
  14136. _sg_clear(dyn_offsets, sizeof(dyn_offsets));
  14137. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  14138. if (shd->cmn.uniform_blocks[i].stage == SG_SHADERSTAGE_NONE) {
  14139. continue;
  14140. }
  14141. uint8_t dynoffset_index = shd->wgpu.ub_dynoffsets[i];
  14142. SOKOL_ASSERT(dynoffset_index < shd->wgpu.ub_num_dynoffsets);
  14143. dyn_offsets[dynoffset_index] = _sg.wgpu.uniform.bind_offsets[i];
  14144. }
  14145. wgpuRenderPassEncoderSetBindGroup(_sg.wgpu.pass_enc,
  14146. _SG_WGPU_UB_BINDGROUP_INDEX,
  14147. shd->wgpu.bg_ub,
  14148. shd->wgpu.ub_num_dynoffsets,
  14149. dyn_offsets);
  14150. }
  14151. _SOKOL_PRIVATE void _sg_wgpu_apply_pipeline(_sg_pipeline_t* pip) {
  14152. SOKOL_ASSERT(pip);
  14153. SOKOL_ASSERT(pip->wgpu.pip);
  14154. SOKOL_ASSERT(_sg.wgpu.pass_enc);
  14155. SOKOL_ASSERT(pip->shader && (pip->shader->slot.id == pip->cmn.shader_id.id));
  14156. _sg.wgpu.use_indexed_draw = (pip->cmn.index_type != SG_INDEXTYPE_NONE);
  14157. _sg.wgpu.cur_pipeline = pip;
  14158. _sg.wgpu.cur_pipeline_id.id = pip->slot.id;
  14159. wgpuRenderPassEncoderSetPipeline(_sg.wgpu.pass_enc, pip->wgpu.pip);
  14160. wgpuRenderPassEncoderSetBlendConstant(_sg.wgpu.pass_enc, &pip->wgpu.blend_color);
  14161. wgpuRenderPassEncoderSetStencilReference(_sg.wgpu.pass_enc, pip->cmn.stencil.ref);
  14162. // bind groups must be set because pipelines without uniform blocks or resource bindings
  14163. // will still create 'empty' BindGroupLayouts
  14164. _sg_wgpu_set_ub_bindgroup(pip->shader);
  14165. _sg_wgpu_set_img_smp_sbuf_bindgroup(0); // this will set the 'empty bind group'
  14166. }
  14167. _SOKOL_PRIVATE bool _sg_wgpu_apply_bindings(_sg_bindings_t* bnd) {
  14168. SOKOL_ASSERT(_sg.wgpu.pass_enc);
  14169. SOKOL_ASSERT(bnd);
  14170. SOKOL_ASSERT(bnd->pip->shader && (bnd->pip->cmn.shader_id.id == bnd->pip->shader->slot.id));
  14171. bool retval = true;
  14172. retval &= _sg_wgpu_apply_index_buffer(bnd);
  14173. retval &= _sg_wgpu_apply_vertex_buffers(bnd);
  14174. retval &= _sg_wgpu_apply_bindgroup(bnd);
  14175. return retval;
  14176. }
  14177. _SOKOL_PRIVATE void _sg_wgpu_apply_uniforms(int ub_slot, const sg_range* data) {
  14178. const uint32_t alignment = _sg.wgpu.limits.limits.minUniformBufferOffsetAlignment;
  14179. SOKOL_ASSERT(_sg.wgpu.pass_enc);
  14180. SOKOL_ASSERT(_sg.wgpu.uniform.staging);
  14181. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  14182. SOKOL_ASSERT((_sg.wgpu.uniform.offset + data->size) <= _sg.wgpu.uniform.num_bytes);
  14183. SOKOL_ASSERT((_sg.wgpu.uniform.offset & (alignment - 1)) == 0);
  14184. const _sg_pipeline_t* pip = _sg.wgpu.cur_pipeline;
  14185. SOKOL_ASSERT(pip && pip->shader);
  14186. SOKOL_ASSERT(pip->slot.id == _sg.wgpu.cur_pipeline_id.id);
  14187. const _sg_shader_t* shd = pip->shader;
  14188. SOKOL_ASSERT(shd->slot.id == pip->cmn.shader_id.id);
  14189. SOKOL_ASSERT(data->size == shd->cmn.uniform_blocks[ub_slot].size);
  14190. SOKOL_ASSERT(data->size <= _SG_WGPU_MAX_UNIFORM_UPDATE_SIZE);
  14191. _sg_stats_add(wgpu.uniforms.num_set_bindgroup, 1);
  14192. memcpy(_sg.wgpu.uniform.staging + _sg.wgpu.uniform.offset, data->ptr, data->size);
  14193. _sg.wgpu.uniform.bind_offsets[ub_slot] = _sg.wgpu.uniform.offset;
  14194. _sg.wgpu.uniform.offset = _sg_roundup_u32(_sg.wgpu.uniform.offset + (uint32_t)data->size, alignment);
  14195. _sg_wgpu_set_ub_bindgroup(shd);
  14196. }
  14197. _SOKOL_PRIVATE void _sg_wgpu_draw(int base_element, int num_elements, int num_instances) {
  14198. SOKOL_ASSERT(_sg.wgpu.pass_enc);
  14199. SOKOL_ASSERT(_sg.wgpu.cur_pipeline && (_sg.wgpu.cur_pipeline->slot.id == _sg.wgpu.cur_pipeline_id.id));
  14200. if (SG_INDEXTYPE_NONE != _sg.wgpu.cur_pipeline->cmn.index_type) {
  14201. wgpuRenderPassEncoderDrawIndexed(_sg.wgpu.pass_enc, (uint32_t)num_elements, (uint32_t)num_instances, (uint32_t)base_element, 0, 0);
  14202. } else {
  14203. wgpuRenderPassEncoderDraw(_sg.wgpu.pass_enc, (uint32_t)num_elements, (uint32_t)num_instances, (uint32_t)base_element, 0);
  14204. }
  14205. }
  14206. _SOKOL_PRIVATE void _sg_wgpu_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  14207. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  14208. SOKOL_ASSERT(buf);
  14209. _sg_wgpu_copy_buffer_data(buf, 0, data);
  14210. }
  14211. _SOKOL_PRIVATE void _sg_wgpu_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  14212. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  14213. _SOKOL_UNUSED(new_frame);
  14214. _sg_wgpu_copy_buffer_data(buf, (uint64_t)buf->cmn.append_pos, data);
  14215. }
  14216. _SOKOL_PRIVATE void _sg_wgpu_update_image(_sg_image_t* img, const sg_image_data* data) {
  14217. SOKOL_ASSERT(img && data);
  14218. _sg_wgpu_copy_image_data(img, img->wgpu.tex, data);
  14219. }
  14220. #endif
  14221. // ██████ ███████ ███ ██ ███████ ██████ ██ ██████ ██████ █████ ██████ ██ ██ ███████ ███ ██ ██████
  14222. // ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██
  14223. // ██ ███ █████ ██ ██ ██ █████ ██████ ██ ██ ██████ ███████ ██ █████ █████ ██ ██ ██ ██ ██
  14224. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  14225. // ██████ ███████ ██ ████ ███████ ██ ██ ██ ██████ ██████ ██ ██ ██████ ██ ██ ███████ ██ ████ ██████
  14226. //
  14227. // >>generic backend
  14228. static inline void _sg_setup_backend(const sg_desc* desc) {
  14229. #if defined(_SOKOL_ANY_GL)
  14230. _sg_gl_setup_backend(desc);
  14231. #elif defined(SOKOL_METAL)
  14232. _sg_mtl_setup_backend(desc);
  14233. #elif defined(SOKOL_D3D11)
  14234. _sg_d3d11_setup_backend(desc);
  14235. #elif defined(SOKOL_WGPU)
  14236. _sg_wgpu_setup_backend(desc);
  14237. #elif defined(SOKOL_DUMMY_BACKEND)
  14238. _sg_dummy_setup_backend(desc);
  14239. #else
  14240. #error("INVALID BACKEND");
  14241. #endif
  14242. }
  14243. static inline void _sg_discard_backend(void) {
  14244. #if defined(_SOKOL_ANY_GL)
  14245. _sg_gl_discard_backend();
  14246. #elif defined(SOKOL_METAL)
  14247. _sg_mtl_discard_backend();
  14248. #elif defined(SOKOL_D3D11)
  14249. _sg_d3d11_discard_backend();
  14250. #elif defined(SOKOL_WGPU)
  14251. _sg_wgpu_discard_backend();
  14252. #elif defined(SOKOL_DUMMY_BACKEND)
  14253. _sg_dummy_discard_backend();
  14254. #else
  14255. #error("INVALID BACKEND");
  14256. #endif
  14257. }
  14258. static inline void _sg_reset_state_cache(void) {
  14259. #if defined(_SOKOL_ANY_GL)
  14260. _sg_gl_reset_state_cache();
  14261. #elif defined(SOKOL_METAL)
  14262. _sg_mtl_reset_state_cache();
  14263. #elif defined(SOKOL_D3D11)
  14264. _sg_d3d11_reset_state_cache();
  14265. #elif defined(SOKOL_WGPU)
  14266. _sg_wgpu_reset_state_cache();
  14267. #elif defined(SOKOL_DUMMY_BACKEND)
  14268. _sg_dummy_reset_state_cache();
  14269. #else
  14270. #error("INVALID BACKEND");
  14271. #endif
  14272. }
  14273. static inline sg_resource_state _sg_create_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  14274. #if defined(_SOKOL_ANY_GL)
  14275. return _sg_gl_create_buffer(buf, desc);
  14276. #elif defined(SOKOL_METAL)
  14277. return _sg_mtl_create_buffer(buf, desc);
  14278. #elif defined(SOKOL_D3D11)
  14279. return _sg_d3d11_create_buffer(buf, desc);
  14280. #elif defined(SOKOL_WGPU)
  14281. return _sg_wgpu_create_buffer(buf, desc);
  14282. #elif defined(SOKOL_DUMMY_BACKEND)
  14283. return _sg_dummy_create_buffer(buf, desc);
  14284. #else
  14285. #error("INVALID BACKEND");
  14286. #endif
  14287. }
  14288. static inline void _sg_discard_buffer(_sg_buffer_t* buf) {
  14289. #if defined(_SOKOL_ANY_GL)
  14290. _sg_gl_discard_buffer(buf);
  14291. #elif defined(SOKOL_METAL)
  14292. _sg_mtl_discard_buffer(buf);
  14293. #elif defined(SOKOL_D3D11)
  14294. _sg_d3d11_discard_buffer(buf);
  14295. #elif defined(SOKOL_WGPU)
  14296. _sg_wgpu_discard_buffer(buf);
  14297. #elif defined(SOKOL_DUMMY_BACKEND)
  14298. _sg_dummy_discard_buffer(buf);
  14299. #else
  14300. #error("INVALID BACKEND");
  14301. #endif
  14302. }
  14303. static inline sg_resource_state _sg_create_image(_sg_image_t* img, const sg_image_desc* desc) {
  14304. #if defined(_SOKOL_ANY_GL)
  14305. return _sg_gl_create_image(img, desc);
  14306. #elif defined(SOKOL_METAL)
  14307. return _sg_mtl_create_image(img, desc);
  14308. #elif defined(SOKOL_D3D11)
  14309. return _sg_d3d11_create_image(img, desc);
  14310. #elif defined(SOKOL_WGPU)
  14311. return _sg_wgpu_create_image(img, desc);
  14312. #elif defined(SOKOL_DUMMY_BACKEND)
  14313. return _sg_dummy_create_image(img, desc);
  14314. #else
  14315. #error("INVALID BACKEND");
  14316. #endif
  14317. }
  14318. static inline void _sg_discard_image(_sg_image_t* img) {
  14319. #if defined(_SOKOL_ANY_GL)
  14320. _sg_gl_discard_image(img);
  14321. #elif defined(SOKOL_METAL)
  14322. _sg_mtl_discard_image(img);
  14323. #elif defined(SOKOL_D3D11)
  14324. _sg_d3d11_discard_image(img);
  14325. #elif defined(SOKOL_WGPU)
  14326. _sg_wgpu_discard_image(img);
  14327. #elif defined(SOKOL_DUMMY_BACKEND)
  14328. _sg_dummy_discard_image(img);
  14329. #else
  14330. #error("INVALID BACKEND");
  14331. #endif
  14332. }
  14333. static inline sg_resource_state _sg_create_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  14334. #if defined(_SOKOL_ANY_GL)
  14335. return _sg_gl_create_sampler(smp, desc);
  14336. #elif defined(SOKOL_METAL)
  14337. return _sg_mtl_create_sampler(smp, desc);
  14338. #elif defined(SOKOL_D3D11)
  14339. return _sg_d3d11_create_sampler(smp, desc);
  14340. #elif defined(SOKOL_WGPU)
  14341. return _sg_wgpu_create_sampler(smp, desc);
  14342. #elif defined(SOKOL_DUMMY_BACKEND)
  14343. return _sg_dummy_create_sampler(smp, desc);
  14344. #else
  14345. #error("INVALID BACKEND");
  14346. #endif
  14347. }
  14348. static inline void _sg_discard_sampler(_sg_sampler_t* smp) {
  14349. #if defined(_SOKOL_ANY_GL)
  14350. _sg_gl_discard_sampler(smp);
  14351. #elif defined(SOKOL_METAL)
  14352. _sg_mtl_discard_sampler(smp);
  14353. #elif defined(SOKOL_D3D11)
  14354. _sg_d3d11_discard_sampler(smp);
  14355. #elif defined(SOKOL_WGPU)
  14356. _sg_wgpu_discard_sampler(smp);
  14357. #elif defined(SOKOL_DUMMY_BACKEND)
  14358. _sg_dummy_discard_sampler(smp);
  14359. #else
  14360. #error("INVALID BACKEND");
  14361. #endif
  14362. }
  14363. static inline sg_resource_state _sg_create_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  14364. #if defined(_SOKOL_ANY_GL)
  14365. return _sg_gl_create_shader(shd, desc);
  14366. #elif defined(SOKOL_METAL)
  14367. return _sg_mtl_create_shader(shd, desc);
  14368. #elif defined(SOKOL_D3D11)
  14369. return _sg_d3d11_create_shader(shd, desc);
  14370. #elif defined(SOKOL_WGPU)
  14371. return _sg_wgpu_create_shader(shd, desc);
  14372. #elif defined(SOKOL_DUMMY_BACKEND)
  14373. return _sg_dummy_create_shader(shd, desc);
  14374. #else
  14375. #error("INVALID BACKEND");
  14376. #endif
  14377. }
  14378. static inline void _sg_discard_shader(_sg_shader_t* shd) {
  14379. #if defined(_SOKOL_ANY_GL)
  14380. _sg_gl_discard_shader(shd);
  14381. #elif defined(SOKOL_METAL)
  14382. _sg_mtl_discard_shader(shd);
  14383. #elif defined(SOKOL_D3D11)
  14384. _sg_d3d11_discard_shader(shd);
  14385. #elif defined(SOKOL_WGPU)
  14386. _sg_wgpu_discard_shader(shd);
  14387. #elif defined(SOKOL_DUMMY_BACKEND)
  14388. _sg_dummy_discard_shader(shd);
  14389. #else
  14390. #error("INVALID BACKEND");
  14391. #endif
  14392. }
  14393. static inline sg_resource_state _sg_create_pipeline(_sg_pipeline_t* pip, _sg_shader_t* shd, const sg_pipeline_desc* desc) {
  14394. #if defined(_SOKOL_ANY_GL)
  14395. return _sg_gl_create_pipeline(pip, shd, desc);
  14396. #elif defined(SOKOL_METAL)
  14397. return _sg_mtl_create_pipeline(pip, shd, desc);
  14398. #elif defined(SOKOL_D3D11)
  14399. return _sg_d3d11_create_pipeline(pip, shd, desc);
  14400. #elif defined(SOKOL_WGPU)
  14401. return _sg_wgpu_create_pipeline(pip, shd, desc);
  14402. #elif defined(SOKOL_DUMMY_BACKEND)
  14403. return _sg_dummy_create_pipeline(pip, shd, desc);
  14404. #else
  14405. #error("INVALID BACKEND");
  14406. #endif
  14407. }
  14408. static inline void _sg_discard_pipeline(_sg_pipeline_t* pip) {
  14409. #if defined(_SOKOL_ANY_GL)
  14410. _sg_gl_discard_pipeline(pip);
  14411. #elif defined(SOKOL_METAL)
  14412. _sg_mtl_discard_pipeline(pip);
  14413. #elif defined(SOKOL_D3D11)
  14414. _sg_d3d11_discard_pipeline(pip);
  14415. #elif defined(SOKOL_WGPU)
  14416. _sg_wgpu_discard_pipeline(pip);
  14417. #elif defined(SOKOL_DUMMY_BACKEND)
  14418. _sg_dummy_discard_pipeline(pip);
  14419. #else
  14420. #error("INVALID BACKEND");
  14421. #endif
  14422. }
  14423. static inline sg_resource_state _sg_create_attachments(_sg_attachments_t* atts, _sg_image_t** color_images, _sg_image_t** resolve_images, _sg_image_t* ds_image, const sg_attachments_desc* desc) {
  14424. #if defined(_SOKOL_ANY_GL)
  14425. return _sg_gl_create_attachments(atts, color_images, resolve_images, ds_image, desc);
  14426. #elif defined(SOKOL_METAL)
  14427. return _sg_mtl_create_attachments(atts, color_images, resolve_images, ds_image, desc);
  14428. #elif defined(SOKOL_D3D11)
  14429. return _sg_d3d11_create_attachments(atts, color_images, resolve_images, ds_image, desc);
  14430. #elif defined(SOKOL_WGPU)
  14431. return _sg_wgpu_create_attachments(atts, color_images, resolve_images, ds_image, desc);
  14432. #elif defined(SOKOL_DUMMY_BACKEND)
  14433. return _sg_dummy_create_attachments(atts, color_images, resolve_images, ds_image, desc);
  14434. #else
  14435. #error("INVALID BACKEND");
  14436. #endif
  14437. }
  14438. static inline void _sg_discard_attachments(_sg_attachments_t* atts) {
  14439. #if defined(_SOKOL_ANY_GL)
  14440. _sg_gl_discard_attachments(atts);
  14441. #elif defined(SOKOL_METAL)
  14442. _sg_mtl_discard_attachments(atts);
  14443. #elif defined(SOKOL_D3D11)
  14444. _sg_d3d11_discard_attachments(atts);
  14445. #elif defined(SOKOL_WGPU)
  14446. return _sg_wgpu_discard_attachments(atts);
  14447. #elif defined(SOKOL_DUMMY_BACKEND)
  14448. _sg_dummy_discard_attachments(atts);
  14449. #else
  14450. #error("INVALID BACKEND");
  14451. #endif
  14452. }
  14453. static inline _sg_image_t* _sg_attachments_color_image(const _sg_attachments_t* atts, int index) {
  14454. #if defined(_SOKOL_ANY_GL)
  14455. return _sg_gl_attachments_color_image(atts, index);
  14456. #elif defined(SOKOL_METAL)
  14457. return _sg_mtl_attachments_color_image(atts, index);
  14458. #elif defined(SOKOL_D3D11)
  14459. return _sg_d3d11_attachments_color_image(atts, index);
  14460. #elif defined(SOKOL_WGPU)
  14461. return _sg_wgpu_attachments_color_image(atts, index);
  14462. #elif defined(SOKOL_DUMMY_BACKEND)
  14463. return _sg_dummy_attachments_color_image(atts, index);
  14464. #else
  14465. #error("INVALID BACKEND");
  14466. #endif
  14467. }
  14468. static inline _sg_image_t* _sg_attachments_resolve_image(const _sg_attachments_t* atts, int index) {
  14469. #if defined(_SOKOL_ANY_GL)
  14470. return _sg_gl_attachments_resolve_image(atts, index);
  14471. #elif defined(SOKOL_METAL)
  14472. return _sg_mtl_attachments_resolve_image(atts, index);
  14473. #elif defined(SOKOL_D3D11)
  14474. return _sg_d3d11_attachments_resolve_image(atts, index);
  14475. #elif defined(SOKOL_WGPU)
  14476. return _sg_wgpu_attachments_resolve_image(atts, index);
  14477. #elif defined(SOKOL_DUMMY_BACKEND)
  14478. return _sg_dummy_attachments_resolve_image(atts, index);
  14479. #else
  14480. #error("INVALID BACKEND");
  14481. #endif
  14482. }
  14483. static inline _sg_image_t* _sg_attachments_ds_image(const _sg_attachments_t* atts) {
  14484. #if defined(_SOKOL_ANY_GL)
  14485. return _sg_gl_attachments_ds_image(atts);
  14486. #elif defined(SOKOL_METAL)
  14487. return _sg_mtl_attachments_ds_image(atts);
  14488. #elif defined(SOKOL_D3D11)
  14489. return _sg_d3d11_attachments_ds_image(atts);
  14490. #elif defined(SOKOL_WGPU)
  14491. return _sg_wgpu_attachments_ds_image(atts);
  14492. #elif defined(SOKOL_DUMMY_BACKEND)
  14493. return _sg_dummy_attachments_ds_image(atts);
  14494. #else
  14495. #error("INVALID BACKEND");
  14496. #endif
  14497. }
  14498. static inline void _sg_begin_pass(const sg_pass* pass) {
  14499. #if defined(_SOKOL_ANY_GL)
  14500. _sg_gl_begin_pass(pass);
  14501. #elif defined(SOKOL_METAL)
  14502. _sg_mtl_begin_pass(pass);
  14503. #elif defined(SOKOL_D3D11)
  14504. _sg_d3d11_begin_pass(pass);
  14505. #elif defined(SOKOL_WGPU)
  14506. _sg_wgpu_begin_pass(pass);
  14507. #elif defined(SOKOL_DUMMY_BACKEND)
  14508. _sg_dummy_begin_pass(pass);
  14509. #else
  14510. #error("INVALID BACKEND");
  14511. #endif
  14512. }
  14513. static inline void _sg_end_pass(void) {
  14514. #if defined(_SOKOL_ANY_GL)
  14515. _sg_gl_end_pass();
  14516. #elif defined(SOKOL_METAL)
  14517. _sg_mtl_end_pass();
  14518. #elif defined(SOKOL_D3D11)
  14519. _sg_d3d11_end_pass();
  14520. #elif defined(SOKOL_WGPU)
  14521. _sg_wgpu_end_pass();
  14522. #elif defined(SOKOL_DUMMY_BACKEND)
  14523. _sg_dummy_end_pass();
  14524. #else
  14525. #error("INVALID BACKEND");
  14526. #endif
  14527. }
  14528. static inline void _sg_apply_viewport(int x, int y, int w, int h, bool origin_top_left) {
  14529. #if defined(_SOKOL_ANY_GL)
  14530. _sg_gl_apply_viewport(x, y, w, h, origin_top_left);
  14531. #elif defined(SOKOL_METAL)
  14532. _sg_mtl_apply_viewport(x, y, w, h, origin_top_left);
  14533. #elif defined(SOKOL_D3D11)
  14534. _sg_d3d11_apply_viewport(x, y, w, h, origin_top_left);
  14535. #elif defined(SOKOL_WGPU)
  14536. _sg_wgpu_apply_viewport(x, y, w, h, origin_top_left);
  14537. #elif defined(SOKOL_DUMMY_BACKEND)
  14538. _sg_dummy_apply_viewport(x, y, w, h, origin_top_left);
  14539. #else
  14540. #error("INVALID BACKEND");
  14541. #endif
  14542. }
  14543. static inline void _sg_apply_scissor_rect(int x, int y, int w, int h, bool origin_top_left) {
  14544. #if defined(_SOKOL_ANY_GL)
  14545. _sg_gl_apply_scissor_rect(x, y, w, h, origin_top_left);
  14546. #elif defined(SOKOL_METAL)
  14547. _sg_mtl_apply_scissor_rect(x, y, w, h, origin_top_left);
  14548. #elif defined(SOKOL_D3D11)
  14549. _sg_d3d11_apply_scissor_rect(x, y, w, h, origin_top_left);
  14550. #elif defined(SOKOL_WGPU)
  14551. _sg_wgpu_apply_scissor_rect(x, y, w, h, origin_top_left);
  14552. #elif defined(SOKOL_DUMMY_BACKEND)
  14553. _sg_dummy_apply_scissor_rect(x, y, w, h, origin_top_left);
  14554. #else
  14555. #error("INVALID BACKEND");
  14556. #endif
  14557. }
  14558. static inline void _sg_apply_pipeline(_sg_pipeline_t* pip) {
  14559. #if defined(_SOKOL_ANY_GL)
  14560. _sg_gl_apply_pipeline(pip);
  14561. #elif defined(SOKOL_METAL)
  14562. _sg_mtl_apply_pipeline(pip);
  14563. #elif defined(SOKOL_D3D11)
  14564. _sg_d3d11_apply_pipeline(pip);
  14565. #elif defined(SOKOL_WGPU)
  14566. _sg_wgpu_apply_pipeline(pip);
  14567. #elif defined(SOKOL_DUMMY_BACKEND)
  14568. _sg_dummy_apply_pipeline(pip);
  14569. #else
  14570. #error("INVALID BACKEND");
  14571. #endif
  14572. }
  14573. static inline bool _sg_apply_bindings(_sg_bindings_t* bnd) {
  14574. #if defined(_SOKOL_ANY_GL)
  14575. return _sg_gl_apply_bindings(bnd);
  14576. #elif defined(SOKOL_METAL)
  14577. return _sg_mtl_apply_bindings(bnd);
  14578. #elif defined(SOKOL_D3D11)
  14579. return _sg_d3d11_apply_bindings(bnd);
  14580. #elif defined(SOKOL_WGPU)
  14581. return _sg_wgpu_apply_bindings(bnd);
  14582. #elif defined(SOKOL_DUMMY_BACKEND)
  14583. return _sg_dummy_apply_bindings(bnd);
  14584. #else
  14585. #error("INVALID BACKEND");
  14586. #endif
  14587. }
  14588. static inline void _sg_apply_uniforms(int ub_slot, const sg_range* data) {
  14589. #if defined(_SOKOL_ANY_GL)
  14590. _sg_gl_apply_uniforms(ub_slot, data);
  14591. #elif defined(SOKOL_METAL)
  14592. _sg_mtl_apply_uniforms(ub_slot, data);
  14593. #elif defined(SOKOL_D3D11)
  14594. _sg_d3d11_apply_uniforms(ub_slot, data);
  14595. #elif defined(SOKOL_WGPU)
  14596. _sg_wgpu_apply_uniforms(ub_slot, data);
  14597. #elif defined(SOKOL_DUMMY_BACKEND)
  14598. _sg_dummy_apply_uniforms(ub_slot, data);
  14599. #else
  14600. #error("INVALID BACKEND");
  14601. #endif
  14602. }
  14603. static inline void _sg_draw(int base_element, int num_elements, int num_instances) {
  14604. #if defined(_SOKOL_ANY_GL)
  14605. _sg_gl_draw(base_element, num_elements, num_instances);
  14606. #elif defined(SOKOL_METAL)
  14607. _sg_mtl_draw(base_element, num_elements, num_instances);
  14608. #elif defined(SOKOL_D3D11)
  14609. _sg_d3d11_draw(base_element, num_elements, num_instances);
  14610. #elif defined(SOKOL_WGPU)
  14611. _sg_wgpu_draw(base_element, num_elements, num_instances);
  14612. #elif defined(SOKOL_DUMMY_BACKEND)
  14613. _sg_dummy_draw(base_element, num_elements, num_instances);
  14614. #else
  14615. #error("INVALID BACKEND");
  14616. #endif
  14617. }
  14618. static inline void _sg_commit(void) {
  14619. #if defined(_SOKOL_ANY_GL)
  14620. _sg_gl_commit();
  14621. #elif defined(SOKOL_METAL)
  14622. _sg_mtl_commit();
  14623. #elif defined(SOKOL_D3D11)
  14624. _sg_d3d11_commit();
  14625. #elif defined(SOKOL_WGPU)
  14626. _sg_wgpu_commit();
  14627. #elif defined(SOKOL_DUMMY_BACKEND)
  14628. _sg_dummy_commit();
  14629. #else
  14630. #error("INVALID BACKEND");
  14631. #endif
  14632. }
  14633. static inline void _sg_update_buffer(_sg_buffer_t* buf, const sg_range* data) {
  14634. #if defined(_SOKOL_ANY_GL)
  14635. _sg_gl_update_buffer(buf, data);
  14636. #elif defined(SOKOL_METAL)
  14637. _sg_mtl_update_buffer(buf, data);
  14638. #elif defined(SOKOL_D3D11)
  14639. _sg_d3d11_update_buffer(buf, data);
  14640. #elif defined(SOKOL_WGPU)
  14641. _sg_wgpu_update_buffer(buf, data);
  14642. #elif defined(SOKOL_DUMMY_BACKEND)
  14643. _sg_dummy_update_buffer(buf, data);
  14644. #else
  14645. #error("INVALID BACKEND");
  14646. #endif
  14647. }
  14648. static inline void _sg_append_buffer(_sg_buffer_t* buf, const sg_range* data, bool new_frame) {
  14649. #if defined(_SOKOL_ANY_GL)
  14650. _sg_gl_append_buffer(buf, data, new_frame);
  14651. #elif defined(SOKOL_METAL)
  14652. _sg_mtl_append_buffer(buf, data, new_frame);
  14653. #elif defined(SOKOL_D3D11)
  14654. _sg_d3d11_append_buffer(buf, data, new_frame);
  14655. #elif defined(SOKOL_WGPU)
  14656. _sg_wgpu_append_buffer(buf, data, new_frame);
  14657. #elif defined(SOKOL_DUMMY_BACKEND)
  14658. _sg_dummy_append_buffer(buf, data, new_frame);
  14659. #else
  14660. #error("INVALID BACKEND");
  14661. #endif
  14662. }
  14663. static inline void _sg_update_image(_sg_image_t* img, const sg_image_data* data) {
  14664. #if defined(_SOKOL_ANY_GL)
  14665. _sg_gl_update_image(img, data);
  14666. #elif defined(SOKOL_METAL)
  14667. _sg_mtl_update_image(img, data);
  14668. #elif defined(SOKOL_D3D11)
  14669. _sg_d3d11_update_image(img, data);
  14670. #elif defined(SOKOL_WGPU)
  14671. _sg_wgpu_update_image(img, data);
  14672. #elif defined(SOKOL_DUMMY_BACKEND)
  14673. _sg_dummy_update_image(img, data);
  14674. #else
  14675. #error("INVALID BACKEND");
  14676. #endif
  14677. }
  14678. static inline void _sg_push_debug_group(const char* name) {
  14679. #if defined(SOKOL_METAL)
  14680. _sg_mtl_push_debug_group(name);
  14681. #else
  14682. _SOKOL_UNUSED(name);
  14683. #endif
  14684. }
  14685. static inline void _sg_pop_debug_group(void) {
  14686. #if defined(SOKOL_METAL)
  14687. _sg_mtl_pop_debug_group();
  14688. #endif
  14689. }
  14690. // ██████ ██████ ██████ ██
  14691. // ██ ██ ██ ██ ██ ██ ██
  14692. // ██████ ██ ██ ██ ██ ██
  14693. // ██ ██ ██ ██ ██ ██
  14694. // ██ ██████ ██████ ███████
  14695. //
  14696. // >>pool
  14697. _SOKOL_PRIVATE void _sg_init_pool(_sg_pool_t* pool, int num) {
  14698. SOKOL_ASSERT(pool && (num >= 1));
  14699. // slot 0 is reserved for the 'invalid id', so bump the pool size by 1
  14700. pool->size = num + 1;
  14701. pool->queue_top = 0;
  14702. // generation counters indexable by pool slot index, slot 0 is reserved
  14703. size_t gen_ctrs_size = sizeof(uint32_t) * (size_t)pool->size;
  14704. pool->gen_ctrs = (uint32_t*)_sg_malloc_clear(gen_ctrs_size);
  14705. // it's not a bug to only reserve 'num' here
  14706. pool->free_queue = (int*) _sg_malloc_clear(sizeof(int) * (size_t)num);
  14707. // never allocate the zero-th pool item since the invalid id is 0
  14708. for (int i = pool->size-1; i >= 1; i--) {
  14709. pool->free_queue[pool->queue_top++] = i;
  14710. }
  14711. }
  14712. _SOKOL_PRIVATE void _sg_discard_pool(_sg_pool_t* pool) {
  14713. SOKOL_ASSERT(pool);
  14714. SOKOL_ASSERT(pool->free_queue);
  14715. _sg_free(pool->free_queue);
  14716. pool->free_queue = 0;
  14717. SOKOL_ASSERT(pool->gen_ctrs);
  14718. _sg_free(pool->gen_ctrs);
  14719. pool->gen_ctrs = 0;
  14720. pool->size = 0;
  14721. pool->queue_top = 0;
  14722. }
  14723. _SOKOL_PRIVATE int _sg_pool_alloc_index(_sg_pool_t* pool) {
  14724. SOKOL_ASSERT(pool);
  14725. SOKOL_ASSERT(pool->free_queue);
  14726. if (pool->queue_top > 0) {
  14727. int slot_index = pool->free_queue[--pool->queue_top];
  14728. SOKOL_ASSERT((slot_index > 0) && (slot_index < pool->size));
  14729. return slot_index;
  14730. } else {
  14731. // pool exhausted
  14732. return _SG_INVALID_SLOT_INDEX;
  14733. }
  14734. }
  14735. _SOKOL_PRIVATE void _sg_pool_free_index(_sg_pool_t* pool, int slot_index) {
  14736. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < pool->size));
  14737. SOKOL_ASSERT(pool);
  14738. SOKOL_ASSERT(pool->free_queue);
  14739. SOKOL_ASSERT(pool->queue_top < pool->size);
  14740. #ifdef SOKOL_DEBUG
  14741. // debug check against double-free
  14742. for (int i = 0; i < pool->queue_top; i++) {
  14743. SOKOL_ASSERT(pool->free_queue[i] != slot_index);
  14744. }
  14745. #endif
  14746. pool->free_queue[pool->queue_top++] = slot_index;
  14747. SOKOL_ASSERT(pool->queue_top <= (pool->size-1));
  14748. }
  14749. _SOKOL_PRIVATE void _sg_reset_slot(_sg_slot_t* slot) {
  14750. SOKOL_ASSERT(slot);
  14751. _sg_clear(slot, sizeof(_sg_slot_t));
  14752. }
  14753. _SOKOL_PRIVATE void _sg_reset_buffer_to_alloc_state(_sg_buffer_t* buf) {
  14754. SOKOL_ASSERT(buf);
  14755. _sg_slot_t slot = buf->slot;
  14756. _sg_clear(buf, sizeof(*buf));
  14757. buf->slot = slot;
  14758. buf->slot.state = SG_RESOURCESTATE_ALLOC;
  14759. }
  14760. _SOKOL_PRIVATE void _sg_reset_image_to_alloc_state(_sg_image_t* img) {
  14761. SOKOL_ASSERT(img);
  14762. _sg_slot_t slot = img->slot;
  14763. _sg_clear(img, sizeof(*img));
  14764. img->slot = slot;
  14765. img->slot.state = SG_RESOURCESTATE_ALLOC;
  14766. }
  14767. _SOKOL_PRIVATE void _sg_reset_sampler_to_alloc_state(_sg_sampler_t* smp) {
  14768. SOKOL_ASSERT(smp);
  14769. _sg_slot_t slot = smp->slot;
  14770. _sg_clear(smp, sizeof(*smp));
  14771. smp->slot = slot;
  14772. smp->slot.state = SG_RESOURCESTATE_ALLOC;
  14773. }
  14774. _SOKOL_PRIVATE void _sg_reset_shader_to_alloc_state(_sg_shader_t* shd) {
  14775. SOKOL_ASSERT(shd);
  14776. _sg_slot_t slot = shd->slot;
  14777. _sg_clear(shd, sizeof(*shd));
  14778. shd->slot = slot;
  14779. shd->slot.state = SG_RESOURCESTATE_ALLOC;
  14780. }
  14781. _SOKOL_PRIVATE void _sg_reset_pipeline_to_alloc_state(_sg_pipeline_t* pip) {
  14782. SOKOL_ASSERT(pip);
  14783. _sg_slot_t slot = pip->slot;
  14784. _sg_clear(pip, sizeof(*pip));
  14785. pip->slot = slot;
  14786. pip->slot.state = SG_RESOURCESTATE_ALLOC;
  14787. }
  14788. _SOKOL_PRIVATE void _sg_reset_attachments_to_alloc_state(_sg_attachments_t* atts) {
  14789. SOKOL_ASSERT(atts);
  14790. _sg_slot_t slot = atts->slot;
  14791. _sg_clear(atts, sizeof(*atts));
  14792. atts->slot = slot;
  14793. atts->slot.state = SG_RESOURCESTATE_ALLOC;
  14794. }
  14795. _SOKOL_PRIVATE void _sg_setup_pools(_sg_pools_t* p, const sg_desc* desc) {
  14796. SOKOL_ASSERT(p);
  14797. SOKOL_ASSERT(desc);
  14798. // note: the pools here will have an additional item, since slot 0 is reserved
  14799. SOKOL_ASSERT((desc->buffer_pool_size > 0) && (desc->buffer_pool_size < _SG_MAX_POOL_SIZE));
  14800. _sg_init_pool(&p->buffer_pool, desc->buffer_pool_size);
  14801. size_t buffer_pool_byte_size = sizeof(_sg_buffer_t) * (size_t)p->buffer_pool.size;
  14802. p->buffers = (_sg_buffer_t*) _sg_malloc_clear(buffer_pool_byte_size);
  14803. SOKOL_ASSERT((desc->image_pool_size > 0) && (desc->image_pool_size < _SG_MAX_POOL_SIZE));
  14804. _sg_init_pool(&p->image_pool, desc->image_pool_size);
  14805. size_t image_pool_byte_size = sizeof(_sg_image_t) * (size_t)p->image_pool.size;
  14806. p->images = (_sg_image_t*) _sg_malloc_clear(image_pool_byte_size);
  14807. SOKOL_ASSERT((desc->sampler_pool_size > 0) && (desc->sampler_pool_size < _SG_MAX_POOL_SIZE));
  14808. _sg_init_pool(&p->sampler_pool, desc->sampler_pool_size);
  14809. size_t sampler_pool_byte_size = sizeof(_sg_sampler_t) * (size_t)p->sampler_pool.size;
  14810. p->samplers = (_sg_sampler_t*) _sg_malloc_clear(sampler_pool_byte_size);
  14811. SOKOL_ASSERT((desc->shader_pool_size > 0) && (desc->shader_pool_size < _SG_MAX_POOL_SIZE));
  14812. _sg_init_pool(&p->shader_pool, desc->shader_pool_size);
  14813. size_t shader_pool_byte_size = sizeof(_sg_shader_t) * (size_t)p->shader_pool.size;
  14814. p->shaders = (_sg_shader_t*) _sg_malloc_clear(shader_pool_byte_size);
  14815. SOKOL_ASSERT((desc->pipeline_pool_size > 0) && (desc->pipeline_pool_size < _SG_MAX_POOL_SIZE));
  14816. _sg_init_pool(&p->pipeline_pool, desc->pipeline_pool_size);
  14817. size_t pipeline_pool_byte_size = sizeof(_sg_pipeline_t) * (size_t)p->pipeline_pool.size;
  14818. p->pipelines = (_sg_pipeline_t*) _sg_malloc_clear(pipeline_pool_byte_size);
  14819. SOKOL_ASSERT((desc->attachments_pool_size > 0) && (desc->attachments_pool_size < _SG_MAX_POOL_SIZE));
  14820. _sg_init_pool(&p->attachments_pool, desc->attachments_pool_size);
  14821. size_t attachments_pool_byte_size = sizeof(_sg_attachments_t) * (size_t)p->attachments_pool.size;
  14822. p->attachments = (_sg_attachments_t*) _sg_malloc_clear(attachments_pool_byte_size);
  14823. }
  14824. _SOKOL_PRIVATE void _sg_discard_pools(_sg_pools_t* p) {
  14825. SOKOL_ASSERT(p);
  14826. _sg_free(p->attachments); p->attachments = 0;
  14827. _sg_free(p->pipelines); p->pipelines = 0;
  14828. _sg_free(p->shaders); p->shaders = 0;
  14829. _sg_free(p->samplers); p->samplers = 0;
  14830. _sg_free(p->images); p->images = 0;
  14831. _sg_free(p->buffers); p->buffers = 0;
  14832. _sg_discard_pool(&p->attachments_pool);
  14833. _sg_discard_pool(&p->pipeline_pool);
  14834. _sg_discard_pool(&p->shader_pool);
  14835. _sg_discard_pool(&p->sampler_pool);
  14836. _sg_discard_pool(&p->image_pool);
  14837. _sg_discard_pool(&p->buffer_pool);
  14838. }
  14839. /* allocate the slot at slot_index:
  14840. - bump the slot's generation counter
  14841. - create a resource id from the generation counter and slot index
  14842. - set the slot's id to this id
  14843. - set the slot's state to ALLOC
  14844. - return the resource id
  14845. */
  14846. _SOKOL_PRIVATE uint32_t _sg_slot_alloc(_sg_pool_t* pool, _sg_slot_t* slot, int slot_index) {
  14847. /* FIXME: add handling for an overflowing generation counter,
  14848. for now, just overflow (another option is to disable
  14849. the slot)
  14850. */
  14851. SOKOL_ASSERT(pool && pool->gen_ctrs);
  14852. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < pool->size));
  14853. SOKOL_ASSERT(slot->id == SG_INVALID_ID);
  14854. SOKOL_ASSERT(slot->state == SG_RESOURCESTATE_INITIAL);
  14855. uint32_t ctr = ++pool->gen_ctrs[slot_index];
  14856. slot->id = (ctr<<_SG_SLOT_SHIFT)|(slot_index & _SG_SLOT_MASK);
  14857. slot->state = SG_RESOURCESTATE_ALLOC;
  14858. return slot->id;
  14859. }
  14860. // extract slot index from id
  14861. _SOKOL_PRIVATE int _sg_slot_index(uint32_t id) {
  14862. int slot_index = (int) (id & _SG_SLOT_MASK);
  14863. SOKOL_ASSERT(_SG_INVALID_SLOT_INDEX != slot_index);
  14864. return slot_index;
  14865. }
  14866. // returns pointer to resource by id without matching id check
  14867. _SOKOL_PRIVATE _sg_buffer_t* _sg_buffer_at(const _sg_pools_t* p, uint32_t buf_id) {
  14868. SOKOL_ASSERT(p && (SG_INVALID_ID != buf_id));
  14869. int slot_index = _sg_slot_index(buf_id);
  14870. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < p->buffer_pool.size));
  14871. return &p->buffers[slot_index];
  14872. }
  14873. _SOKOL_PRIVATE _sg_image_t* _sg_image_at(const _sg_pools_t* p, uint32_t img_id) {
  14874. SOKOL_ASSERT(p && (SG_INVALID_ID != img_id));
  14875. int slot_index = _sg_slot_index(img_id);
  14876. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < p->image_pool.size));
  14877. return &p->images[slot_index];
  14878. }
  14879. _SOKOL_PRIVATE _sg_sampler_t* _sg_sampler_at(const _sg_pools_t* p, uint32_t smp_id) {
  14880. SOKOL_ASSERT(p && (SG_INVALID_ID != smp_id));
  14881. int slot_index = _sg_slot_index(smp_id);
  14882. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < p->sampler_pool.size));
  14883. return &p->samplers[slot_index];
  14884. }
  14885. _SOKOL_PRIVATE _sg_shader_t* _sg_shader_at(const _sg_pools_t* p, uint32_t shd_id) {
  14886. SOKOL_ASSERT(p && (SG_INVALID_ID != shd_id));
  14887. int slot_index = _sg_slot_index(shd_id);
  14888. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < p->shader_pool.size));
  14889. return &p->shaders[slot_index];
  14890. }
  14891. _SOKOL_PRIVATE _sg_pipeline_t* _sg_pipeline_at(const _sg_pools_t* p, uint32_t pip_id) {
  14892. SOKOL_ASSERT(p && (SG_INVALID_ID != pip_id));
  14893. int slot_index = _sg_slot_index(pip_id);
  14894. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < p->pipeline_pool.size));
  14895. return &p->pipelines[slot_index];
  14896. }
  14897. _SOKOL_PRIVATE _sg_attachments_t* _sg_attachments_at(const _sg_pools_t* p, uint32_t atts_id) {
  14898. SOKOL_ASSERT(p && (SG_INVALID_ID != atts_id));
  14899. int slot_index = _sg_slot_index(atts_id);
  14900. SOKOL_ASSERT((slot_index > _SG_INVALID_SLOT_INDEX) && (slot_index < p->attachments_pool.size));
  14901. return &p->attachments[slot_index];
  14902. }
  14903. // returns pointer to resource with matching id check, may return 0
  14904. _SOKOL_PRIVATE _sg_buffer_t* _sg_lookup_buffer(const _sg_pools_t* p, uint32_t buf_id) {
  14905. if (SG_INVALID_ID != buf_id) {
  14906. _sg_buffer_t* buf = _sg_buffer_at(p, buf_id);
  14907. if (buf->slot.id == buf_id) {
  14908. return buf;
  14909. }
  14910. }
  14911. return 0;
  14912. }
  14913. _SOKOL_PRIVATE _sg_image_t* _sg_lookup_image(const _sg_pools_t* p, uint32_t img_id) {
  14914. if (SG_INVALID_ID != img_id) {
  14915. _sg_image_t* img = _sg_image_at(p, img_id);
  14916. if (img->slot.id == img_id) {
  14917. return img;
  14918. }
  14919. }
  14920. return 0;
  14921. }
  14922. _SOKOL_PRIVATE _sg_sampler_t* _sg_lookup_sampler(const _sg_pools_t* p, uint32_t smp_id) {
  14923. if (SG_INVALID_ID != smp_id) {
  14924. _sg_sampler_t* smp = _sg_sampler_at(p, smp_id);
  14925. if (smp->slot.id == smp_id) {
  14926. return smp;
  14927. }
  14928. }
  14929. return 0;
  14930. }
  14931. _SOKOL_PRIVATE _sg_shader_t* _sg_lookup_shader(const _sg_pools_t* p, uint32_t shd_id) {
  14932. SOKOL_ASSERT(p);
  14933. if (SG_INVALID_ID != shd_id) {
  14934. _sg_shader_t* shd = _sg_shader_at(p, shd_id);
  14935. if (shd->slot.id == shd_id) {
  14936. return shd;
  14937. }
  14938. }
  14939. return 0;
  14940. }
  14941. _SOKOL_PRIVATE _sg_pipeline_t* _sg_lookup_pipeline(const _sg_pools_t* p, uint32_t pip_id) {
  14942. SOKOL_ASSERT(p);
  14943. if (SG_INVALID_ID != pip_id) {
  14944. _sg_pipeline_t* pip = _sg_pipeline_at(p, pip_id);
  14945. if (pip->slot.id == pip_id) {
  14946. return pip;
  14947. }
  14948. }
  14949. return 0;
  14950. }
  14951. _SOKOL_PRIVATE _sg_attachments_t* _sg_lookup_attachments(const _sg_pools_t* p, uint32_t atts_id) {
  14952. SOKOL_ASSERT(p);
  14953. if (SG_INVALID_ID != atts_id) {
  14954. _sg_attachments_t* atts = _sg_attachments_at(p, atts_id);
  14955. if (atts->slot.id == atts_id) {
  14956. return atts;
  14957. }
  14958. }
  14959. return 0;
  14960. }
  14961. _SOKOL_PRIVATE void _sg_discard_all_resources(_sg_pools_t* p) {
  14962. /* this is a bit dumb since it loops over all pool slots to
  14963. find the occupied slots, on the other hand it is only ever
  14964. executed at shutdown
  14965. NOTE: ONLY EXECUTE THIS AT SHUTDOWN
  14966. ...because the free queues will not be reset
  14967. and the resource slots not be cleared!
  14968. */
  14969. for (int i = 1; i < p->buffer_pool.size; i++) {
  14970. sg_resource_state state = p->buffers[i].slot.state;
  14971. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  14972. _sg_discard_buffer(&p->buffers[i]);
  14973. }
  14974. }
  14975. for (int i = 1; i < p->image_pool.size; i++) {
  14976. sg_resource_state state = p->images[i].slot.state;
  14977. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  14978. _sg_discard_image(&p->images[i]);
  14979. }
  14980. }
  14981. for (int i = 1; i < p->sampler_pool.size; i++) {
  14982. sg_resource_state state = p->samplers[i].slot.state;
  14983. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  14984. _sg_discard_sampler(&p->samplers[i]);
  14985. }
  14986. }
  14987. for (int i = 1; i < p->shader_pool.size; i++) {
  14988. sg_resource_state state = p->shaders[i].slot.state;
  14989. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  14990. _sg_discard_shader(&p->shaders[i]);
  14991. }
  14992. }
  14993. for (int i = 1; i < p->pipeline_pool.size; i++) {
  14994. sg_resource_state state = p->pipelines[i].slot.state;
  14995. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  14996. _sg_discard_pipeline(&p->pipelines[i]);
  14997. }
  14998. }
  14999. for (int i = 1; i < p->attachments_pool.size; i++) {
  15000. sg_resource_state state = p->attachments[i].slot.state;
  15001. if ((state == SG_RESOURCESTATE_VALID) || (state == SG_RESOURCESTATE_FAILED)) {
  15002. _sg_discard_attachments(&p->attachments[i]);
  15003. }
  15004. }
  15005. }
  15006. // ██ ██ █████ ██ ██ ██████ █████ ████████ ██ ██████ ███ ██
  15007. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  15008. // ██ ██ ███████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  15009. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  15010. // ████ ██ ██ ███████ ██ ██████ ██ ██ ██ ██ ██████ ██ ████
  15011. //
  15012. // >>validation
  15013. #if defined(SOKOL_DEBUG)
  15014. _SOKOL_PRIVATE void _sg_validate_begin(void) {
  15015. _sg.validate_error = SG_LOGITEM_OK;
  15016. }
  15017. _SOKOL_PRIVATE bool _sg_validate_end(void) {
  15018. if (_sg.validate_error != SG_LOGITEM_OK) {
  15019. #if !defined(SOKOL_VALIDATE_NON_FATAL)
  15020. _SG_PANIC(VALIDATION_FAILED);
  15021. return false;
  15022. #else
  15023. return false;
  15024. #endif
  15025. } else {
  15026. return true;
  15027. }
  15028. }
  15029. #endif
  15030. _SOKOL_PRIVATE bool _sg_validate_buffer_desc(const sg_buffer_desc* desc) {
  15031. #if !defined(SOKOL_DEBUG)
  15032. _SOKOL_UNUSED(desc);
  15033. return true;
  15034. #else
  15035. if (_sg.desc.disable_validation) {
  15036. return true;
  15037. }
  15038. SOKOL_ASSERT(desc);
  15039. _sg_validate_begin();
  15040. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_BUFFERDESC_CANARY);
  15041. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_BUFFERDESC_CANARY);
  15042. _SG_VALIDATE(desc->size > 0, VALIDATE_BUFFERDESC_SIZE);
  15043. bool injected = (0 != desc->gl_buffers[0]) ||
  15044. (0 != desc->mtl_buffers[0]) ||
  15045. (0 != desc->d3d11_buffer) ||
  15046. (0 != desc->wgpu_buffer);
  15047. if (!injected && (desc->usage == SG_USAGE_IMMUTABLE)) {
  15048. _SG_VALIDATE((0 != desc->data.ptr) && (desc->data.size > 0), VALIDATE_BUFFERDESC_DATA);
  15049. _SG_VALIDATE(desc->size == desc->data.size, VALIDATE_BUFFERDESC_DATA_SIZE);
  15050. } else {
  15051. _SG_VALIDATE(0 == desc->data.ptr, VALIDATE_BUFFERDESC_NO_DATA);
  15052. }
  15053. if (desc->type == SG_BUFFERTYPE_STORAGEBUFFER) {
  15054. _SG_VALIDATE(_sg.features.storage_buffer, VALIDATE_BUFFERDESC_STORAGEBUFFER_SUPPORTED);
  15055. _SG_VALIDATE(_sg_multiple_u64(desc->size, 4), VALIDATE_BUFFERDESC_STORAGEBUFFER_SIZE_MULTIPLE_4);
  15056. }
  15057. return _sg_validate_end();
  15058. #endif
  15059. }
  15060. _SOKOL_PRIVATE void _sg_validate_image_data(const sg_image_data* data, sg_pixel_format fmt, int width, int height, int num_faces, int num_mips, int num_slices) {
  15061. #if !defined(SOKOL_DEBUG)
  15062. _SOKOL_UNUSED(data);
  15063. _SOKOL_UNUSED(fmt);
  15064. _SOKOL_UNUSED(width);
  15065. _SOKOL_UNUSED(height);
  15066. _SOKOL_UNUSED(num_faces);
  15067. _SOKOL_UNUSED(num_mips);
  15068. _SOKOL_UNUSED(num_slices);
  15069. #else
  15070. for (int face_index = 0; face_index < num_faces; face_index++) {
  15071. for (int mip_index = 0; mip_index < num_mips; mip_index++) {
  15072. const bool has_data = data->subimage[face_index][mip_index].ptr != 0;
  15073. const bool has_size = data->subimage[face_index][mip_index].size > 0;
  15074. _SG_VALIDATE(has_data && has_size, VALIDATE_IMAGEDATA_NODATA);
  15075. const int mip_width = _sg_miplevel_dim(width, mip_index);
  15076. const int mip_height = _sg_miplevel_dim(height, mip_index);
  15077. const int bytes_per_slice = _sg_surface_pitch(fmt, mip_width, mip_height, 1);
  15078. const int expected_size = bytes_per_slice * num_slices;
  15079. _SG_VALIDATE(expected_size == (int)data->subimage[face_index][mip_index].size, VALIDATE_IMAGEDATA_DATA_SIZE);
  15080. }
  15081. }
  15082. #endif
  15083. }
  15084. _SOKOL_PRIVATE bool _sg_validate_image_desc(const sg_image_desc* desc) {
  15085. #if !defined(SOKOL_DEBUG)
  15086. _SOKOL_UNUSED(desc);
  15087. return true;
  15088. #else
  15089. if (_sg.desc.disable_validation) {
  15090. return true;
  15091. }
  15092. SOKOL_ASSERT(desc);
  15093. _sg_validate_begin();
  15094. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_IMAGEDESC_CANARY);
  15095. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_IMAGEDESC_CANARY);
  15096. _SG_VALIDATE(desc->width > 0, VALIDATE_IMAGEDESC_WIDTH);
  15097. _SG_VALIDATE(desc->height > 0, VALIDATE_IMAGEDESC_HEIGHT);
  15098. const sg_pixel_format fmt = desc->pixel_format;
  15099. const sg_usage usage = desc->usage;
  15100. const bool injected = (0 != desc->gl_textures[0]) ||
  15101. (0 != desc->mtl_textures[0]) ||
  15102. (0 != desc->d3d11_texture) ||
  15103. (0 != desc->wgpu_texture);
  15104. if (_sg_is_depth_or_depth_stencil_format(fmt)) {
  15105. _SG_VALIDATE(desc->type != SG_IMAGETYPE_3D, VALIDATE_IMAGEDESC_DEPTH_3D_IMAGE);
  15106. }
  15107. if (desc->render_target) {
  15108. SOKOL_ASSERT(((int)fmt >= 0) && ((int)fmt < _SG_PIXELFORMAT_NUM));
  15109. _SG_VALIDATE(_sg.formats[fmt].render, VALIDATE_IMAGEDESC_RT_PIXELFORMAT);
  15110. _SG_VALIDATE(usage == SG_USAGE_IMMUTABLE, VALIDATE_IMAGEDESC_RT_IMMUTABLE);
  15111. _SG_VALIDATE(desc->data.subimage[0][0].ptr==0, VALIDATE_IMAGEDESC_RT_NO_DATA);
  15112. if (desc->sample_count > 1) {
  15113. _SG_VALIDATE(_sg.formats[fmt].msaa, VALIDATE_IMAGEDESC_NO_MSAA_RT_SUPPORT);
  15114. _SG_VALIDATE(desc->num_mipmaps == 1, VALIDATE_IMAGEDESC_MSAA_NUM_MIPMAPS);
  15115. _SG_VALIDATE(desc->type != SG_IMAGETYPE_3D, VALIDATE_IMAGEDESC_MSAA_3D_IMAGE);
  15116. _SG_VALIDATE(desc->type != SG_IMAGETYPE_CUBE, VALIDATE_IMAGEDESC_MSAA_CUBE_IMAGE);
  15117. }
  15118. } else {
  15119. _SG_VALIDATE(desc->sample_count == 1, VALIDATE_IMAGEDESC_MSAA_BUT_NO_RT);
  15120. const bool valid_nonrt_fmt = !_sg_is_valid_rendertarget_depth_format(fmt);
  15121. _SG_VALIDATE(valid_nonrt_fmt, VALIDATE_IMAGEDESC_NONRT_PIXELFORMAT);
  15122. const bool is_compressed = _sg_is_compressed_pixel_format(desc->pixel_format);
  15123. const bool is_immutable = (usage == SG_USAGE_IMMUTABLE);
  15124. if (is_compressed) {
  15125. _SG_VALIDATE(is_immutable, VALIDATE_IMAGEDESC_COMPRESSED_IMMUTABLE);
  15126. }
  15127. if (!injected && is_immutable) {
  15128. // image desc must have valid data
  15129. _sg_validate_image_data(&desc->data,
  15130. desc->pixel_format,
  15131. desc->width,
  15132. desc->height,
  15133. (desc->type == SG_IMAGETYPE_CUBE) ? 6 : 1,
  15134. desc->num_mipmaps,
  15135. desc->num_slices);
  15136. } else {
  15137. // image desc must not have data
  15138. for (int face_index = 0; face_index < SG_CUBEFACE_NUM; face_index++) {
  15139. for (int mip_index = 0; mip_index < SG_MAX_MIPMAPS; mip_index++) {
  15140. const bool no_data = 0 == desc->data.subimage[face_index][mip_index].ptr;
  15141. const bool no_size = 0 == desc->data.subimage[face_index][mip_index].size;
  15142. if (injected) {
  15143. _SG_VALIDATE(no_data && no_size, VALIDATE_IMAGEDESC_INJECTED_NO_DATA);
  15144. }
  15145. if (!is_immutable) {
  15146. _SG_VALIDATE(no_data && no_size, VALIDATE_IMAGEDESC_DYNAMIC_NO_DATA);
  15147. }
  15148. }
  15149. }
  15150. }
  15151. }
  15152. return _sg_validate_end();
  15153. #endif
  15154. }
  15155. _SOKOL_PRIVATE bool _sg_validate_sampler_desc(const sg_sampler_desc* desc) {
  15156. #if !defined(SOKOL_DEBUG)
  15157. _SOKOL_UNUSED(desc);
  15158. return true;
  15159. #else
  15160. if (_sg.desc.disable_validation) {
  15161. return true;
  15162. }
  15163. SOKOL_ASSERT(desc);
  15164. _sg_validate_begin();
  15165. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_SAMPLERDESC_CANARY);
  15166. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_SAMPLERDESC_CANARY);
  15167. // restriction from WebGPU: when anisotropy > 1, all filters must be linear
  15168. if (desc->max_anisotropy > 1) {
  15169. _SG_VALIDATE((desc->min_filter == SG_FILTER_LINEAR)
  15170. && (desc->mag_filter == SG_FILTER_LINEAR)
  15171. && (desc->mipmap_filter == SG_FILTER_LINEAR),
  15172. VALIDATE_SAMPLERDESC_ANISTROPIC_REQUIRES_LINEAR_FILTERING);
  15173. }
  15174. return _sg_validate_end();
  15175. #endif
  15176. }
  15177. typedef struct {
  15178. uint64_t lo, hi;
  15179. } _sg_u128_t;
  15180. _SOKOL_PRIVATE _sg_u128_t _sg_u128(void) {
  15181. _sg_u128_t res;
  15182. _sg_clear(&res, sizeof(res));
  15183. return res;
  15184. }
  15185. _SOKOL_PRIVATE _sg_u128_t _sg_validate_set_slot_bit(_sg_u128_t bits, sg_shader_stage stage, uint8_t slot) {
  15186. switch (stage) {
  15187. case SG_SHADERSTAGE_NONE:
  15188. SOKOL_ASSERT(slot < 128);
  15189. if (slot < 64) {
  15190. bits.lo |= 1ULL << slot;
  15191. } else {
  15192. bits.hi |= 1ULL << (slot - 64);
  15193. }
  15194. break;
  15195. case SG_SHADERSTAGE_VERTEX:
  15196. SOKOL_ASSERT(slot < 64);
  15197. bits.lo |= 1ULL << slot;
  15198. break;
  15199. case SG_SHADERSTAGE_FRAGMENT:
  15200. SOKOL_ASSERT(slot < 64);
  15201. bits.hi |= 1ULL << slot;
  15202. break;
  15203. }
  15204. return bits;
  15205. }
  15206. _SOKOL_PRIVATE bool _sg_validate_slot_bits(_sg_u128_t bits, sg_shader_stage stage, uint8_t slot) {
  15207. _sg_u128_t mask = _sg_u128();
  15208. switch (stage) {
  15209. case SG_SHADERSTAGE_NONE:
  15210. SOKOL_ASSERT(slot < 128);
  15211. if (slot < 64) {
  15212. mask.lo = 1ULL << slot;
  15213. } else {
  15214. mask.hi = 1ULL << (slot - 64);
  15215. }
  15216. break;
  15217. case SG_SHADERSTAGE_VERTEX:
  15218. SOKOL_ASSERT(slot < 64);
  15219. mask.lo = 1ULL << slot;
  15220. break;
  15221. case SG_SHADERSTAGE_FRAGMENT:
  15222. SOKOL_ASSERT(slot < 64);
  15223. mask.hi = 1ULL << slot;
  15224. break;
  15225. default:
  15226. SOKOL_UNREACHABLE;
  15227. break;
  15228. }
  15229. return ((bits.lo & mask.lo) == 0) && ((bits.hi & mask.hi) == 0);
  15230. }
  15231. _SOKOL_PRIVATE bool _sg_validate_shader_desc(const sg_shader_desc* desc) {
  15232. #if !defined(SOKOL_DEBUG)
  15233. _SOKOL_UNUSED(desc);
  15234. return true;
  15235. #else
  15236. if (_sg.desc.disable_validation) {
  15237. return true;
  15238. }
  15239. SOKOL_ASSERT(desc);
  15240. _sg_validate_begin();
  15241. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_SHADERDESC_CANARY);
  15242. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_SHADERDESC_CANARY);
  15243. #if defined(SOKOL_GLCORE) || defined(SOKOL_GLES3) || defined(SOKOL_WGPU)
  15244. // on GL or WebGPU, must provide shader source code
  15245. _SG_VALIDATE(0 != desc->vertex_func.source, VALIDATE_SHADERDESC_SOURCE);
  15246. _SG_VALIDATE(0 != desc->fragment_func.source, VALIDATE_SHADERDESC_SOURCE);
  15247. #elif defined(SOKOL_METAL) || defined(SOKOL_D3D11)
  15248. // on Metal or D3D11, must provide shader source code or byte code
  15249. _SG_VALIDATE((0 != desc->vertex_func.source)||(0 != desc->vertex_func.bytecode.ptr), VALIDATE_SHADERDESC_SOURCE_OR_BYTECODE);
  15250. _SG_VALIDATE((0 != desc->fragment_func.source)||(0 != desc->fragment_func.bytecode.ptr), VALIDATE_SHADERDESC_SOURCE_OR_BYTECODE);
  15251. #else
  15252. // Dummy Backend, don't require source or bytecode
  15253. #endif
  15254. for (size_t i = 0; i < SG_MAX_VERTEX_ATTRIBUTES; i++) {
  15255. if (desc->attrs[i].glsl_name) {
  15256. _SG_VALIDATE(strlen(desc->attrs[i].glsl_name) < _SG_STRING_SIZE, VALIDATE_SHADERDESC_ATTR_STRING_TOO_LONG);
  15257. }
  15258. if (desc->attrs[i].hlsl_sem_name) {
  15259. _SG_VALIDATE(strlen(desc->attrs[i].hlsl_sem_name) < _SG_STRING_SIZE, VALIDATE_SHADERDESC_ATTR_STRING_TOO_LONG);
  15260. }
  15261. }
  15262. // if shader byte code, the size must also be provided
  15263. if (0 != desc->vertex_func.bytecode.ptr) {
  15264. _SG_VALIDATE(desc->vertex_func.bytecode.size > 0, VALIDATE_SHADERDESC_NO_BYTECODE_SIZE);
  15265. }
  15266. if (0 != desc->fragment_func.bytecode.ptr) {
  15267. _SG_VALIDATE(desc->fragment_func.bytecode.size > 0, VALIDATE_SHADERDESC_NO_BYTECODE_SIZE);
  15268. }
  15269. #if defined(SOKOL_METAL)
  15270. _sg_u128_t msl_buf_bits = _sg_u128();
  15271. _sg_u128_t msl_tex_bits = _sg_u128();
  15272. _sg_u128_t msl_smp_bits = _sg_u128();
  15273. #elif defined(SOKOL_D3D11)
  15274. _sg_u128_t hlsl_buf_bits = _sg_u128();
  15275. _sg_u128_t hlsl_tex_bits = _sg_u128();
  15276. _sg_u128_t hlsl_smp_bits = _sg_u128();
  15277. #elif defined(_SOKOL_ANY_GL)
  15278. _sg_u128_t glsl_bnd_bits = _sg_u128();
  15279. #elif defined(SOKOL_WGPU)
  15280. _sg_u128_t wgsl_group0_bits = _sg_u128();
  15281. _sg_u128_t wgsl_group1_bits = _sg_u128();
  15282. #endif
  15283. for (size_t ub_idx = 0; ub_idx < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_idx++) {
  15284. const sg_shader_uniform_block* ub_desc = &desc->uniform_blocks[ub_idx];
  15285. if (ub_desc->stage == SG_SHADERSTAGE_NONE) {
  15286. continue;
  15287. }
  15288. _SG_VALIDATE(ub_desc->size > 0, VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_IS_ZERO);
  15289. #if defined(SOKOL_METAL)
  15290. _SG_VALIDATE(ub_desc->msl_buffer_n < _SG_MTL_MAX_STAGE_UB_BINDINGS, VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_OUT_OF_RANGE);
  15291. _SG_VALIDATE(_sg_validate_slot_bits(msl_buf_bits, ub_desc->stage, ub_desc->msl_buffer_n), VALIDATE_SHADERDESC_UNIFORMBLOCK_METAL_BUFFER_SLOT_COLLISION);
  15292. msl_buf_bits = _sg_validate_set_slot_bit(msl_buf_bits, ub_desc->stage, ub_desc->msl_buffer_n);
  15293. #elif defined(SOKOL_D3D11)
  15294. _SG_VALIDATE(ub_desc->hlsl_register_b_n < _SG_D3D11_MAX_STAGE_UB_BINDINGS, VALIDATE_SHADERDESC_UNIFORMBLOCK_HLSL_REGISTER_B_OUT_OF_RANGE);
  15295. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_buf_bits, ub_desc->stage, ub_desc->hlsl_register_b_n), VALIDATE_SHADERDESC_UNIFORMBLOCK_HLSL_REGISTER_B_COLLISION);
  15296. hlsl_buf_bits = _sg_validate_set_slot_bit(hlsl_buf_bits, ub_desc->stage, ub_desc->hlsl_register_b_n);
  15297. #elif defined(SOKOL_WGPU)
  15298. _SG_VALIDATE(ub_desc->wgsl_group0_binding_n < _SG_WGPU_MAX_UB_BINDGROUP_BIND_SLOTS, VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_OUT_OF_RANGE);
  15299. _SG_VALIDATE(_sg_validate_slot_bits(wgsl_group0_bits, SG_SHADERSTAGE_NONE, ub_desc->wgsl_group0_binding_n), VALIDATE_SHADERDESC_UNIFORMBLOCK_WGSL_GROUP0_BINDING_COLLISION);
  15300. wgsl_group0_bits = _sg_validate_set_slot_bit(wgsl_group0_bits, SG_SHADERSTAGE_NONE, ub_desc->wgsl_group0_binding_n);
  15301. #endif
  15302. #if defined(_SOKOL_ANY_GL)
  15303. bool uniforms_continuous = true;
  15304. uint32_t uniform_offset = 0;
  15305. int num_uniforms = 0;
  15306. for (size_t u_index = 0; u_index < SG_MAX_UNIFORMBLOCK_MEMBERS; u_index++) {
  15307. const sg_glsl_shader_uniform* u_desc = &ub_desc->glsl_uniforms[u_index];
  15308. if (u_desc->type != SG_UNIFORMTYPE_INVALID) {
  15309. _SG_VALIDATE(uniforms_continuous, VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_CONT_MEMBERS);
  15310. _SG_VALIDATE(u_desc->glsl_name, VALIDATE_SHADERDESC_UNIFORMBLOCK_UNIFORM_GLSL_NAME);
  15311. const int array_count = u_desc->array_count;
  15312. _SG_VALIDATE(array_count > 0, VALIDATE_SHADERDESC_UNIFORMBLOCK_ARRAY_COUNT);
  15313. const uint32_t u_align = _sg_uniform_alignment(u_desc->type, array_count, ub_desc->layout);
  15314. const uint32_t u_size = _sg_uniform_size(u_desc->type, array_count, ub_desc->layout);
  15315. uniform_offset = _sg_align_u32(uniform_offset, u_align);
  15316. uniform_offset += u_size;
  15317. num_uniforms++;
  15318. // with std140, arrays are only allowed for FLOAT4, INT4, MAT4
  15319. if (ub_desc->layout == SG_UNIFORMLAYOUT_STD140) {
  15320. if (array_count > 1) {
  15321. _SG_VALIDATE((u_desc->type == SG_UNIFORMTYPE_FLOAT4) || (u_desc->type == SG_UNIFORMTYPE_INT4) || (u_desc->type == SG_UNIFORMTYPE_MAT4), VALIDATE_SHADERDESC_UNIFORMBLOCK_STD140_ARRAY_TYPE);
  15322. }
  15323. }
  15324. } else {
  15325. uniforms_continuous = false;
  15326. }
  15327. }
  15328. if (ub_desc->layout == SG_UNIFORMLAYOUT_STD140) {
  15329. uniform_offset = _sg_align_u32(uniform_offset, 16);
  15330. }
  15331. _SG_VALIDATE((size_t)uniform_offset == ub_desc->size, VALIDATE_SHADERDESC_UNIFORMBLOCK_SIZE_MISMATCH);
  15332. _SG_VALIDATE(num_uniforms > 0, VALIDATE_SHADERDESC_UNIFORMBLOCK_NO_MEMBERS);
  15333. #endif
  15334. }
  15335. for (size_t sbuf_idx = 0; sbuf_idx < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_idx++) {
  15336. const sg_shader_storage_buffer* sbuf_desc = &desc->storage_buffers[sbuf_idx];
  15337. if (sbuf_desc->stage == SG_SHADERSTAGE_NONE) {
  15338. continue;
  15339. }
  15340. _SG_VALIDATE(sbuf_desc->readonly, VALIDATE_SHADERDESC_STORAGEBUFFER_READONLY);
  15341. #if defined(SOKOL_METAL)
  15342. _SG_VALIDATE((sbuf_desc->msl_buffer_n >= _SG_MTL_MAX_STAGE_UB_BINDINGS) && (sbuf_desc->msl_buffer_n < _SG_MTL_MAX_STAGE_UB_SBUF_BINDINGS), VALIDATE_SHADERDESC_STORAGEBUFFER_METAL_BUFFER_SLOT_OUT_OF_RANGE);
  15343. _SG_VALIDATE(_sg_validate_slot_bits(msl_buf_bits, sbuf_desc->stage, sbuf_desc->msl_buffer_n), VALIDATE_SHADERDESC_STORAGEBUFFER_METAL_BUFFER_SLOT_COLLISION);
  15344. msl_buf_bits = _sg_validate_set_slot_bit(msl_buf_bits, sbuf_desc->stage, sbuf_desc->msl_buffer_n);
  15345. #elif defined(SOKOL_D3D11)
  15346. _SG_VALIDATE(sbuf_desc->hlsl_register_t_n < _SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS, VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_T_OUT_OF_RANGE);
  15347. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_tex_bits, sbuf_desc->stage, sbuf_desc->hlsl_register_t_n), VALIDATE_SHADERDESC_STORAGEBUFFER_HLSL_REGISTER_T_COLLISION);
  15348. hlsl_tex_bits = _sg_validate_set_slot_bit(hlsl_tex_bits, sbuf_desc->stage, sbuf_desc->hlsl_register_t_n);
  15349. #elif defined(_SOKOL_ANY_GL)
  15350. _SG_VALIDATE(sbuf_desc->glsl_binding_n < _SG_GL_MAX_SBUF_BINDINGS, VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_OUT_OF_RANGE);
  15351. _SG_VALIDATE(_sg_validate_slot_bits(glsl_bnd_bits, SG_SHADERSTAGE_NONE, sbuf_desc->glsl_binding_n), VALIDATE_SHADERDESC_STORAGEBUFFER_GLSL_BINDING_COLLISION);
  15352. glsl_bnd_bits = _sg_validate_set_slot_bit(glsl_bnd_bits, SG_SHADERSTAGE_NONE, sbuf_desc->glsl_binding_n);
  15353. #elif defined(SOKOL_WGPU)
  15354. _SG_VALIDATE(sbuf_desc->wgsl_group1_binding_n < _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS, VALIDATE_SHADERDESC_STORAGEBUFFER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  15355. _SG_VALIDATE(_sg_validate_slot_bits(wgsl_group1_bits, SG_SHADERSTAGE_NONE, sbuf_desc->wgsl_group1_binding_n), VALIDATE_SHADERDESC_STORAGEBUFFER_WGSL_GROUP1_BINDING_COLLISION);
  15356. wgsl_group1_bits = _sg_validate_set_slot_bit(wgsl_group1_bits, SG_SHADERSTAGE_NONE, sbuf_desc->wgsl_group1_binding_n);
  15357. #endif
  15358. }
  15359. uint32_t img_slot_mask = 0;
  15360. for (size_t img_idx = 0; img_idx < SG_MAX_IMAGE_BINDSLOTS; img_idx++) {
  15361. const sg_shader_image* img_desc = &desc->images[img_idx];
  15362. if (img_desc->stage == SG_SHADERSTAGE_NONE) {
  15363. continue;
  15364. }
  15365. img_slot_mask |= (1 << img_idx);
  15366. #if defined(SOKOL_METAL)
  15367. _SG_VALIDATE(img_desc->msl_texture_n < _SG_MTL_MAX_STAGE_IMAGE_BINDINGS, VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_OUT_OF_RANGE);
  15368. _SG_VALIDATE(_sg_validate_slot_bits(msl_tex_bits, img_desc->stage, img_desc->msl_texture_n), VALIDATE_SHADERDESC_IMAGE_METAL_TEXTURE_SLOT_COLLISION);
  15369. msl_tex_bits = _sg_validate_set_slot_bit(msl_tex_bits, img_desc->stage, img_desc->msl_texture_n);
  15370. #elif defined(SOKOL_D3D11)
  15371. _SG_VALIDATE(img_desc->hlsl_register_t_n < _SG_D3D11_MAX_STAGE_TEX_SBUF_BINDINGS, VALIDATE_SHADERDESC_IMAGE_HLSL_REGISTER_T_OUT_OF_RANGE);
  15372. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_tex_bits, img_desc->stage, img_desc->hlsl_register_t_n), VALIDATE_SHADERDESC_IMAGE_HLSL_REGISTER_T_COLLISION);
  15373. hlsl_tex_bits = _sg_validate_set_slot_bit(hlsl_tex_bits, img_desc->stage, img_desc->hlsl_register_t_n);
  15374. #elif defined(SOKOL_WGPU)
  15375. _SG_VALIDATE(img_desc->wgsl_group1_binding_n < _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS, VALIDATE_SHADERDESC_IMAGE_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  15376. _SG_VALIDATE(_sg_validate_slot_bits(wgsl_group1_bits, SG_SHADERSTAGE_NONE, img_desc->wgsl_group1_binding_n), VALIDATE_SHADERDESC_IMAGE_WGSL_GROUP1_BINDING_COLLISION);
  15377. wgsl_group1_bits = _sg_validate_set_slot_bit(wgsl_group1_bits, SG_SHADERSTAGE_NONE, img_desc->wgsl_group1_binding_n);
  15378. #endif
  15379. }
  15380. uint32_t smp_slot_mask = 0;
  15381. for (size_t smp_idx = 0; smp_idx < SG_MAX_SAMPLER_BINDSLOTS; smp_idx++) {
  15382. const sg_shader_sampler* smp_desc = &desc->samplers[smp_idx];
  15383. if (smp_desc->stage == SG_SHADERSTAGE_NONE) {
  15384. continue;
  15385. }
  15386. smp_slot_mask |= (1 << smp_idx);
  15387. #if defined(SOKOL_METAL)
  15388. _SG_VALIDATE(smp_desc->msl_sampler_n < _SG_MTL_MAX_STAGE_SAMPLER_BINDINGS, VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_OUT_OF_RANGE);
  15389. _SG_VALIDATE(_sg_validate_slot_bits(msl_smp_bits, smp_desc->stage, smp_desc->msl_sampler_n), VALIDATE_SHADERDESC_SAMPLER_METAL_SAMPLER_SLOT_COLLISION);
  15390. msl_smp_bits = _sg_validate_set_slot_bit(msl_smp_bits, smp_desc->stage, smp_desc->msl_sampler_n);
  15391. #elif defined(SOKOL_D3D11)
  15392. _SG_VALIDATE(smp_desc->hlsl_register_s_n < _SG_D3D11_MAX_STAGE_SMP_BINDINGS, VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_OUT_OF_RANGE);
  15393. _SG_VALIDATE(_sg_validate_slot_bits(hlsl_smp_bits, smp_desc->stage, smp_desc->hlsl_register_s_n), VALIDATE_SHADERDESC_SAMPLER_HLSL_REGISTER_S_COLLISION);
  15394. hlsl_smp_bits = _sg_validate_set_slot_bit(hlsl_smp_bits, smp_desc->stage, smp_desc->hlsl_register_s_n);
  15395. #elif defined(SOKOL_WGPU)
  15396. _SG_VALIDATE(smp_desc->wgsl_group1_binding_n < _SG_WGPU_MAX_IMG_SMP_SBUF_BIND_SLOTS, VALIDATE_SHADERDESC_SAMPLER_WGSL_GROUP1_BINDING_OUT_OF_RANGE);
  15397. _SG_VALIDATE(_sg_validate_slot_bits(wgsl_group1_bits, SG_SHADERSTAGE_NONE, smp_desc->wgsl_group1_binding_n), VALIDATE_SHADERDESC_SAMPLER_WGSL_GROUP1_BINDING_COLLISION);
  15398. wgsl_group1_bits = _sg_validate_set_slot_bit(wgsl_group1_bits, SG_SHADERSTAGE_NONE, smp_desc->wgsl_group1_binding_n);
  15399. #endif
  15400. }
  15401. uint32_t ref_img_slot_mask = 0;
  15402. uint32_t ref_smp_slot_mask = 0;
  15403. for (size_t img_smp_idx = 0; img_smp_idx < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_idx++) {
  15404. const sg_shader_image_sampler_pair* img_smp_desc = &desc->image_sampler_pairs[img_smp_idx];
  15405. if (img_smp_desc->stage == SG_SHADERSTAGE_NONE) {
  15406. continue;
  15407. }
  15408. #if defined(_SOKOL_ANY_GL)
  15409. _SG_VALIDATE(img_smp_desc->glsl_name != 0, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_GLSL_NAME);
  15410. #endif
  15411. const bool img_slot_in_range = img_smp_desc->image_slot < SG_MAX_IMAGE_BINDSLOTS;
  15412. const bool smp_slot_in_range = img_smp_desc->sampler_slot < SG_MAX_SAMPLER_BINDSLOTS;
  15413. _SG_VALIDATE(img_slot_in_range, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_SLOT_OUT_OF_RANGE);
  15414. _SG_VALIDATE(smp_slot_in_range, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_SLOT_OUT_OF_RANGE);
  15415. if (img_slot_in_range && smp_slot_in_range) {
  15416. ref_img_slot_mask |= 1 << img_smp_desc->image_slot;
  15417. ref_smp_slot_mask |= 1 << img_smp_desc->sampler_slot;
  15418. const sg_shader_image* img_desc = &desc->images[img_smp_desc->image_slot];
  15419. const sg_shader_sampler* smp_desc = &desc->samplers[img_smp_desc->sampler_slot];
  15420. _SG_VALIDATE(img_desc->stage == img_smp_desc->stage, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_IMAGE_STAGE_MISMATCH);
  15421. _SG_VALIDATE(smp_desc->stage == img_smp_desc->stage, VALIDATE_SHADERDESC_IMAGE_SAMPLER_PAIR_SAMPLER_STAGE_MISMATCH);
  15422. const bool needs_nonfiltering = (img_desc->sample_type == SG_IMAGESAMPLETYPE_UINT)
  15423. || (img_desc->sample_type == SG_IMAGESAMPLETYPE_SINT)
  15424. || (img_desc->sample_type == SG_IMAGESAMPLETYPE_UNFILTERABLE_FLOAT);
  15425. const bool needs_comparison = img_desc->sample_type == SG_IMAGESAMPLETYPE_DEPTH;
  15426. if (needs_nonfiltering) {
  15427. _SG_VALIDATE(needs_nonfiltering && (smp_desc->sampler_type == SG_SAMPLERTYPE_NONFILTERING), VALIDATE_SHADERDESC_NONFILTERING_SAMPLER_REQUIRED);
  15428. }
  15429. if (needs_comparison) {
  15430. _SG_VALIDATE(needs_comparison && (smp_desc->sampler_type == SG_SAMPLERTYPE_COMPARISON), VALIDATE_SHADERDESC_COMPARISON_SAMPLER_REQUIRED);
  15431. }
  15432. }
  15433. }
  15434. // each image and sampler must be referenced by an image sampler
  15435. _SG_VALIDATE(img_slot_mask == ref_img_slot_mask, VALIDATE_SHADERDESC_IMAGE_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS);
  15436. _SG_VALIDATE(smp_slot_mask == ref_smp_slot_mask, VALIDATE_SHADERDESC_SAMPLER_NOT_REFERENCED_BY_IMAGE_SAMPLER_PAIRS);
  15437. return _sg_validate_end();
  15438. #endif
  15439. }
  15440. _SOKOL_PRIVATE bool _sg_validate_pipeline_desc(const sg_pipeline_desc* desc) {
  15441. #if !defined(SOKOL_DEBUG)
  15442. _SOKOL_UNUSED(desc);
  15443. return true;
  15444. #else
  15445. if (_sg.desc.disable_validation) {
  15446. return true;
  15447. }
  15448. SOKOL_ASSERT(desc);
  15449. _sg_validate_begin();
  15450. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_PIPELINEDESC_CANARY);
  15451. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_PIPELINEDESC_CANARY);
  15452. _SG_VALIDATE(desc->shader.id != SG_INVALID_ID, VALIDATE_PIPELINEDESC_SHADER);
  15453. for (size_t buf_index = 0; buf_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; buf_index++) {
  15454. const sg_vertex_buffer_layout_state* l_state = &desc->layout.buffers[buf_index];
  15455. if (l_state->stride == 0) {
  15456. continue;
  15457. }
  15458. _SG_VALIDATE(_sg_multiple_u64((uint64_t)l_state->stride, 4), VALIDATE_PIPELINEDESC_LAYOUT_STRIDE4);
  15459. }
  15460. const _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, desc->shader.id);
  15461. _SG_VALIDATE(0 != shd, VALIDATE_PIPELINEDESC_SHADER);
  15462. if (shd) {
  15463. _SG_VALIDATE(shd->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_PIPELINEDESC_SHADER);
  15464. bool attrs_cont = true;
  15465. for (size_t attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  15466. const sg_vertex_attr_state* a_state = &desc->layout.attrs[attr_index];
  15467. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  15468. attrs_cont = false;
  15469. continue;
  15470. }
  15471. _SG_VALIDATE(attrs_cont, VALIDATE_PIPELINEDESC_NO_CONT_ATTRS);
  15472. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  15473. #if defined(SOKOL_D3D11)
  15474. // on D3D11, semantic names (and semantic indices) must be provided
  15475. _SG_VALIDATE(!_sg_strempty(&shd->d3d11.attrs[attr_index].sem_name), VALIDATE_PIPELINEDESC_ATTR_SEMANTICS);
  15476. #endif
  15477. }
  15478. }
  15479. for (size_t color_index = 0; color_index < (size_t)desc->color_count; color_index++) {
  15480. const sg_blend_state* bs = &desc->colors[color_index].blend;
  15481. if ((bs->op_rgb == SG_BLENDOP_MIN) || (bs->op_rgb == SG_BLENDOP_MAX)) {
  15482. _SG_VALIDATE((bs->src_factor_rgb == SG_BLENDFACTOR_ONE) && (bs->dst_factor_rgb == SG_BLENDFACTOR_ONE), VALIDATE_PIPELINEDESC_BLENDOP_MINMAX_REQUIRES_BLENDFACTOR_ONE);
  15483. }
  15484. if ((bs->op_alpha == SG_BLENDOP_MIN) || (bs->op_alpha == SG_BLENDOP_MAX)) {
  15485. _SG_VALIDATE((bs->src_factor_alpha == SG_BLENDFACTOR_ONE) && (bs->dst_factor_alpha == SG_BLENDFACTOR_ONE), VALIDATE_PIPELINEDESC_BLENDOP_MINMAX_REQUIRES_BLENDFACTOR_ONE);
  15486. }
  15487. }
  15488. return _sg_validate_end();
  15489. #endif
  15490. }
  15491. _SOKOL_PRIVATE bool _sg_validate_attachments_desc(const sg_attachments_desc* desc) {
  15492. #if !defined(SOKOL_DEBUG)
  15493. _SOKOL_UNUSED(desc);
  15494. return true;
  15495. #else
  15496. if (_sg.desc.disable_validation) {
  15497. return true;
  15498. }
  15499. SOKOL_ASSERT(desc);
  15500. _sg_validate_begin();
  15501. _SG_VALIDATE(desc->_start_canary == 0, VALIDATE_ATTACHMENTSDESC_CANARY);
  15502. _SG_VALIDATE(desc->_end_canary == 0, VALIDATE_ATTACHMENTSDESC_CANARY);
  15503. bool atts_cont = true;
  15504. int color_width = -1, color_height = -1, color_sample_count = -1;
  15505. bool has_color_atts = false;
  15506. for (int att_index = 0; att_index < SG_MAX_COLOR_ATTACHMENTS; att_index++) {
  15507. const sg_attachment_desc* att = &desc->colors[att_index];
  15508. if (att->image.id == SG_INVALID_ID) {
  15509. atts_cont = false;
  15510. continue;
  15511. }
  15512. _SG_VALIDATE(atts_cont, VALIDATE_ATTACHMENTSDESC_NO_CONT_COLOR_ATTS);
  15513. has_color_atts = true;
  15514. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, att->image.id);
  15515. _SG_VALIDATE(img, VALIDATE_ATTACHMENTSDESC_IMAGE);
  15516. if (0 != img) {
  15517. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_IMAGE);
  15518. _SG_VALIDATE(img->cmn.render_target, VALIDATE_ATTACHMENTSDESC_IMAGE_NO_RT);
  15519. _SG_VALIDATE(att->mip_level < img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_MIPLEVEL);
  15520. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  15521. _SG_VALIDATE(att->slice < 6, VALIDATE_ATTACHMENTSDESC_FACE);
  15522. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  15523. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_LAYER);
  15524. } else if (img->cmn.type == SG_IMAGETYPE_3D) {
  15525. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_SLICE);
  15526. }
  15527. if (att_index == 0) {
  15528. color_width = _sg_miplevel_dim(img->cmn.width, att->mip_level);
  15529. color_height = _sg_miplevel_dim(img->cmn.height, att->mip_level);
  15530. color_sample_count = img->cmn.sample_count;
  15531. } else {
  15532. _SG_VALIDATE(color_width == _sg_miplevel_dim(img->cmn.width, att->mip_level), VALIDATE_ATTACHMENTSDESC_IMAGE_SIZES);
  15533. _SG_VALIDATE(color_height == _sg_miplevel_dim(img->cmn.height, att->mip_level), VALIDATE_ATTACHMENTSDESC_IMAGE_SIZES);
  15534. _SG_VALIDATE(color_sample_count == img->cmn.sample_count, VALIDATE_ATTACHMENTSDESC_IMAGE_SAMPLE_COUNTS);
  15535. }
  15536. _SG_VALIDATE(_sg_is_valid_rendertarget_color_format(img->cmn.pixel_format), VALIDATE_ATTACHMENTSDESC_COLOR_INV_PIXELFORMAT);
  15537. // check resolve attachment
  15538. const sg_attachment_desc* res_att = &desc->resolves[att_index];
  15539. if (res_att->image.id != SG_INVALID_ID) {
  15540. // associated color attachment must be MSAA
  15541. _SG_VALIDATE(img->cmn.sample_count > 1, VALIDATE_ATTACHMENTSDESC_RESOLVE_COLOR_IMAGE_MSAA);
  15542. const _sg_image_t* res_img = _sg_lookup_image(&_sg.pools, res_att->image.id);
  15543. _SG_VALIDATE(res_img, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE);
  15544. if (res_img != 0) {
  15545. _SG_VALIDATE(res_img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE);
  15546. _SG_VALIDATE(res_img->cmn.render_target, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_NO_RT);
  15547. _SG_VALIDATE(res_img->cmn.sample_count == 1, VALIDATE_ATTACHMENTSDESC_RESOLVE_SAMPLE_COUNT);
  15548. _SG_VALIDATE(res_att->mip_level < res_img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_RESOLVE_MIPLEVEL);
  15549. if (res_img->cmn.type == SG_IMAGETYPE_CUBE) {
  15550. _SG_VALIDATE(res_att->slice < 6, VALIDATE_ATTACHMENTSDESC_RESOLVE_FACE);
  15551. } else if (res_img->cmn.type == SG_IMAGETYPE_ARRAY) {
  15552. _SG_VALIDATE(res_att->slice < res_img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_RESOLVE_LAYER);
  15553. } else if (res_img->cmn.type == SG_IMAGETYPE_3D) {
  15554. _SG_VALIDATE(res_att->slice < res_img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_RESOLVE_SLICE);
  15555. }
  15556. _SG_VALIDATE(img->cmn.pixel_format == res_img->cmn.pixel_format, VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_FORMAT);
  15557. _SG_VALIDATE(color_width == _sg_miplevel_dim(res_img->cmn.width, res_att->mip_level), VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_SIZES);
  15558. _SG_VALIDATE(color_height == _sg_miplevel_dim(res_img->cmn.height, res_att->mip_level), VALIDATE_ATTACHMENTSDESC_RESOLVE_IMAGE_SIZES);
  15559. }
  15560. }
  15561. }
  15562. }
  15563. bool has_depth_stencil_att = false;
  15564. if (desc->depth_stencil.image.id != SG_INVALID_ID) {
  15565. const sg_attachment_desc* att = &desc->depth_stencil;
  15566. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, att->image.id);
  15567. _SG_VALIDATE(img, VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE);
  15568. has_depth_stencil_att = true;
  15569. if (img) {
  15570. _SG_VALIDATE(img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE);
  15571. _SG_VALIDATE(att->mip_level < img->cmn.num_mipmaps, VALIDATE_ATTACHMENTSDESC_DEPTH_MIPLEVEL);
  15572. if (img->cmn.type == SG_IMAGETYPE_CUBE) {
  15573. _SG_VALIDATE(att->slice < 6, VALIDATE_ATTACHMENTSDESC_DEPTH_FACE);
  15574. } else if (img->cmn.type == SG_IMAGETYPE_ARRAY) {
  15575. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_DEPTH_LAYER);
  15576. } else if (img->cmn.type == SG_IMAGETYPE_3D) {
  15577. // NOTE: this can't actually happen because of VALIDATE_IMAGEDESC_DEPTH_3D_IMAGE
  15578. _SG_VALIDATE(att->slice < img->cmn.num_slices, VALIDATE_ATTACHMENTSDESC_DEPTH_SLICE);
  15579. }
  15580. _SG_VALIDATE(img->cmn.render_target, VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_NO_RT);
  15581. _SG_VALIDATE((color_width == -1) || (color_width == _sg_miplevel_dim(img->cmn.width, att->mip_level)), VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SIZES);
  15582. _SG_VALIDATE((color_height == -1) || (color_height == _sg_miplevel_dim(img->cmn.height, att->mip_level)), VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SIZES);
  15583. _SG_VALIDATE((color_sample_count == -1) || (color_sample_count == img->cmn.sample_count), VALIDATE_ATTACHMENTSDESC_DEPTH_IMAGE_SAMPLE_COUNT);
  15584. _SG_VALIDATE(_sg_is_valid_rendertarget_depth_format(img->cmn.pixel_format), VALIDATE_ATTACHMENTSDESC_DEPTH_INV_PIXELFORMAT);
  15585. }
  15586. }
  15587. _SG_VALIDATE(has_color_atts || has_depth_stencil_att, VALIDATE_ATTACHMENTSDESC_NO_ATTACHMENTS);
  15588. return _sg_validate_end();
  15589. #endif
  15590. }
  15591. _SOKOL_PRIVATE bool _sg_validate_begin_pass(const sg_pass* pass) {
  15592. #if !defined(SOKOL_DEBUG)
  15593. _SOKOL_UNUSED(pass);
  15594. return true;
  15595. #else
  15596. if (_sg.desc.disable_validation) {
  15597. return true;
  15598. }
  15599. _sg_validate_begin();
  15600. _SG_VALIDATE(pass->_start_canary == 0, VALIDATE_BEGINPASS_CANARY);
  15601. _SG_VALIDATE(pass->_end_canary == 0, VALIDATE_BEGINPASS_CANARY);
  15602. if (pass->attachments.id == SG_INVALID_ID) {
  15603. // this is a swapchain pass
  15604. _SG_VALIDATE(pass->swapchain.width > 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH);
  15605. _SG_VALIDATE(pass->swapchain.height > 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT);
  15606. _SG_VALIDATE(pass->swapchain.sample_count > 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT);
  15607. _SG_VALIDATE(pass->swapchain.color_format > SG_PIXELFORMAT_NONE, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT);
  15608. // NOTE: depth buffer is optional, so depth_format is allowed to be invalid
  15609. // NOTE: the GL framebuffer handle may actually be 0
  15610. #if defined(SOKOL_METAL)
  15611. _SG_VALIDATE(pass->swapchain.metal.current_drawable != 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE);
  15612. if (pass->swapchain.depth_format == SG_PIXELFORMAT_NONE) {
  15613. _SG_VALIDATE(pass->swapchain.metal.depth_stencil_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE_NOTSET);
  15614. } else {
  15615. _SG_VALIDATE(pass->swapchain.metal.depth_stencil_texture != 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE);
  15616. }
  15617. if (pass->swapchain.sample_count > 1) {
  15618. _SG_VALIDATE(pass->swapchain.metal.msaa_color_texture != 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE);
  15619. } else {
  15620. _SG_VALIDATE(pass->swapchain.metal.msaa_color_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE_NOTSET);
  15621. }
  15622. #elif defined(SOKOL_D3D11)
  15623. _SG_VALIDATE(pass->swapchain.d3d11.render_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW);
  15624. if (pass->swapchain.depth_format == SG_PIXELFORMAT_NONE) {
  15625. _SG_VALIDATE(pass->swapchain.d3d11.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  15626. } else {
  15627. _SG_VALIDATE(pass->swapchain.d3d11.depth_stencil_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW);
  15628. }
  15629. if (pass->swapchain.sample_count > 1) {
  15630. _SG_VALIDATE(pass->swapchain.d3d11.resolve_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW);
  15631. } else {
  15632. _SG_VALIDATE(pass->swapchain.d3d11.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW_NOTSET);
  15633. }
  15634. #elif defined(SOKOL_WGPU)
  15635. _SG_VALIDATE(pass->swapchain.wgpu.render_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW);
  15636. if (pass->swapchain.depth_format == SG_PIXELFORMAT_NONE) {
  15637. _SG_VALIDATE(pass->swapchain.wgpu.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  15638. } else {
  15639. _SG_VALIDATE(pass->swapchain.wgpu.depth_stencil_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW);
  15640. }
  15641. if (pass->swapchain.sample_count > 1) {
  15642. _SG_VALIDATE(pass->swapchain.wgpu.resolve_view != 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW);
  15643. } else {
  15644. _SG_VALIDATE(pass->swapchain.wgpu.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW_NOTSET);
  15645. }
  15646. #endif
  15647. } else {
  15648. // this is an 'offscreen pass'
  15649. const _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, pass->attachments.id);
  15650. if (atts) {
  15651. _SG_VALIDATE(atts->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_ATTACHMENTS_VALID);
  15652. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  15653. const _sg_attachment_common_t* color_att = &atts->cmn.colors[i];
  15654. const _sg_image_t* color_img = _sg_attachments_color_image(atts, i);
  15655. if (color_img) {
  15656. _SG_VALIDATE(color_img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE);
  15657. _SG_VALIDATE(color_img->slot.id == color_att->image_id.id, VALIDATE_BEGINPASS_COLOR_ATTACHMENT_IMAGE);
  15658. }
  15659. const _sg_attachment_common_t* resolve_att = &atts->cmn.resolves[i];
  15660. const _sg_image_t* resolve_img = _sg_attachments_resolve_image(atts, i);
  15661. if (resolve_img) {
  15662. _SG_VALIDATE(resolve_img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE);
  15663. _SG_VALIDATE(resolve_img->slot.id == resolve_att->image_id.id, VALIDATE_BEGINPASS_RESOLVE_ATTACHMENT_IMAGE);
  15664. }
  15665. }
  15666. const _sg_image_t* ds_img = _sg_attachments_ds_image(atts);
  15667. if (ds_img) {
  15668. const _sg_attachment_common_t* att = &atts->cmn.depth_stencil;
  15669. _SG_VALIDATE(ds_img->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE);
  15670. _SG_VALIDATE(ds_img->slot.id == att->image_id.id, VALIDATE_BEGINPASS_DEPTHSTENCIL_ATTACHMENT_IMAGE);
  15671. }
  15672. } else {
  15673. _SG_VALIDATE(atts != 0, VALIDATE_BEGINPASS_ATTACHMENTS_EXISTS);
  15674. }
  15675. // swapchain params must be all zero!
  15676. _SG_VALIDATE(pass->swapchain.width == 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_WIDTH_NOTSET);
  15677. _SG_VALIDATE(pass->swapchain.height == 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_HEIGHT_NOTSET);
  15678. _SG_VALIDATE(pass->swapchain.sample_count == 0, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_SAMPLECOUNT_NOTSET);
  15679. _SG_VALIDATE(pass->swapchain.color_format == _SG_PIXELFORMAT_DEFAULT, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_COLORFORMAT_NOTSET);
  15680. _SG_VALIDATE(pass->swapchain.depth_format == _SG_PIXELFORMAT_DEFAULT, VALIDATE_BEGINPASS_SWAPCHAIN_EXPECT_DEPTHFORMAT_NOTSET);
  15681. #if defined(SOKOL_METAL)
  15682. _SG_VALIDATE(pass->swapchain.metal.current_drawable == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_CURRENTDRAWABLE_NOTSET);
  15683. _SG_VALIDATE(pass->swapchain.metal.depth_stencil_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_DEPTHSTENCILTEXTURE_NOTSET);
  15684. _SG_VALIDATE(pass->swapchain.metal.msaa_color_texture == 0, VALIDATE_BEGINPASS_SWAPCHAIN_METAL_EXPECT_MSAACOLORTEXTURE_NOTSET);
  15685. #elif defined(SOKOL_D3D11)
  15686. _SG_VALIDATE(pass->swapchain.d3d11.render_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RENDERVIEW_NOTSET);
  15687. _SG_VALIDATE(pass->swapchain.d3d11.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  15688. _SG_VALIDATE(pass->swapchain.d3d11.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_D3D11_EXPECT_RESOLVEVIEW_NOTSET);
  15689. #elif defined(SOKOL_WGPU)
  15690. _SG_VALIDATE(pass->swapchain.wgpu.render_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RENDERVIEW_NOTSET);
  15691. _SG_VALIDATE(pass->swapchain.wgpu.depth_stencil_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_DEPTHSTENCILVIEW_NOTSET);
  15692. _SG_VALIDATE(pass->swapchain.wgpu.resolve_view == 0, VALIDATE_BEGINPASS_SWAPCHAIN_WGPU_EXPECT_RESOLVEVIEW_NOTSET);
  15693. #elif defined(_SOKOL_ANY_GL)
  15694. _SG_VALIDATE(pass->swapchain.gl.framebuffer == 0, VALIDATE_BEGINPASS_SWAPCHAIN_GL_EXPECT_FRAMEBUFFER_NOTSET);
  15695. #endif
  15696. }
  15697. return _sg_validate_end();
  15698. #endif
  15699. }
  15700. _SOKOL_PRIVATE bool _sg_validate_apply_pipeline(sg_pipeline pip_id) {
  15701. #if !defined(SOKOL_DEBUG)
  15702. _SOKOL_UNUSED(pip_id);
  15703. return true;
  15704. #else
  15705. if (_sg.desc.disable_validation) {
  15706. return true;
  15707. }
  15708. _sg_validate_begin();
  15709. // the pipeline object must be alive and valid
  15710. _SG_VALIDATE(pip_id.id != SG_INVALID_ID, VALIDATE_APIP_PIPELINE_VALID_ID);
  15711. const _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  15712. _SG_VALIDATE(pip != 0, VALIDATE_APIP_PIPELINE_EXISTS);
  15713. if (!pip) {
  15714. return _sg_validate_end();
  15715. }
  15716. _SG_VALIDATE(pip->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_PIPELINE_VALID);
  15717. // the pipeline's shader must be alive and valid
  15718. SOKOL_ASSERT(pip->shader);
  15719. _SG_VALIDATE(pip->shader->slot.id == pip->cmn.shader_id.id, VALIDATE_APIP_SHADER_EXISTS);
  15720. _SG_VALIDATE(pip->shader->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_SHADER_VALID);
  15721. // check that pipeline attributes match current pass attributes
  15722. if (_sg.cur_pass.atts_id.id != SG_INVALID_ID) {
  15723. // an offscreen pass
  15724. const _sg_attachments_t* atts = _sg.cur_pass.atts;
  15725. SOKOL_ASSERT(atts);
  15726. _SG_VALIDATE(atts->slot.id == _sg.cur_pass.atts_id.id, VALIDATE_APIP_CURPASS_ATTACHMENTS_EXISTS);
  15727. _SG_VALIDATE(atts->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_APIP_CURPASS_ATTACHMENTS_VALID);
  15728. _SG_VALIDATE(pip->cmn.color_count == atts->cmn.num_colors, VALIDATE_APIP_ATT_COUNT);
  15729. for (int i = 0; i < pip->cmn.color_count; i++) {
  15730. const _sg_image_t* att_img = _sg_attachments_color_image(atts, i);
  15731. _SG_VALIDATE(pip->cmn.colors[i].pixel_format == att_img->cmn.pixel_format, VALIDATE_APIP_COLOR_FORMAT);
  15732. _SG_VALIDATE(pip->cmn.sample_count == att_img->cmn.sample_count, VALIDATE_APIP_SAMPLE_COUNT);
  15733. }
  15734. const _sg_image_t* att_dsimg = _sg_attachments_ds_image(atts);
  15735. if (att_dsimg) {
  15736. _SG_VALIDATE(pip->cmn.depth.pixel_format == att_dsimg->cmn.pixel_format, VALIDATE_APIP_DEPTH_FORMAT);
  15737. } else {
  15738. _SG_VALIDATE(pip->cmn.depth.pixel_format == SG_PIXELFORMAT_NONE, VALIDATE_APIP_DEPTH_FORMAT);
  15739. }
  15740. } else {
  15741. // default pass
  15742. _SG_VALIDATE(pip->cmn.color_count == 1, VALIDATE_APIP_ATT_COUNT);
  15743. _SG_VALIDATE(pip->cmn.colors[0].pixel_format == _sg.cur_pass.swapchain.color_fmt, VALIDATE_APIP_COLOR_FORMAT);
  15744. _SG_VALIDATE(pip->cmn.depth.pixel_format == _sg.cur_pass.swapchain.depth_fmt, VALIDATE_APIP_DEPTH_FORMAT);
  15745. _SG_VALIDATE(pip->cmn.sample_count == _sg.cur_pass.swapchain.sample_count, VALIDATE_APIP_SAMPLE_COUNT);
  15746. }
  15747. return _sg_validate_end();
  15748. #endif
  15749. }
  15750. _SOKOL_PRIVATE bool _sg_validate_apply_bindings(const sg_bindings* bindings) {
  15751. #if !defined(SOKOL_DEBUG)
  15752. _SOKOL_UNUSED(bindings);
  15753. return true;
  15754. #else
  15755. if (_sg.desc.disable_validation) {
  15756. return true;
  15757. }
  15758. _sg_validate_begin();
  15759. // a pipeline object must have been applied
  15760. _SG_VALIDATE(_sg.cur_pipeline.id != SG_INVALID_ID, VALIDATE_ABND_PIPELINE);
  15761. const _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, _sg.cur_pipeline.id);
  15762. _SG_VALIDATE(pip != 0, VALIDATE_ABND_PIPELINE_EXISTS);
  15763. if (!pip) {
  15764. return _sg_validate_end();
  15765. }
  15766. _SG_VALIDATE(pip->slot.state == SG_RESOURCESTATE_VALID, VALIDATE_ABND_PIPELINE_VALID);
  15767. SOKOL_ASSERT(pip->shader && (pip->cmn.shader_id.id == pip->shader->slot.id));
  15768. const _sg_shader_t* shd = pip->shader;
  15769. // has expected vertex buffers, and vertex buffers still exist
  15770. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  15771. if (pip->cmn.vertex_buffer_layout_active[i]) {
  15772. _SG_VALIDATE(bindings->vertex_buffers[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_VB);
  15773. // buffers in vertex-buffer-slots must be of type SG_BUFFERTYPE_VERTEXBUFFER
  15774. if (bindings->vertex_buffers[i].id != SG_INVALID_ID) {
  15775. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, bindings->vertex_buffers[i].id);
  15776. _SG_VALIDATE(buf != 0, VALIDATE_ABND_VB_EXISTS);
  15777. if (buf && buf->slot.state == SG_RESOURCESTATE_VALID) {
  15778. _SG_VALIDATE(SG_BUFFERTYPE_VERTEXBUFFER == buf->cmn.type, VALIDATE_ABND_VB_TYPE);
  15779. _SG_VALIDATE(!buf->cmn.append_overflow, VALIDATE_ABND_VB_OVERFLOW);
  15780. }
  15781. }
  15782. }
  15783. }
  15784. // index buffer expected or not, and index buffer still exists
  15785. if (pip->cmn.index_type == SG_INDEXTYPE_NONE) {
  15786. // pipeline defines non-indexed rendering, but index buffer provided
  15787. _SG_VALIDATE(bindings->index_buffer.id == SG_INVALID_ID, VALIDATE_ABND_IB);
  15788. } else {
  15789. // pipeline defines indexed rendering, but no index buffer provided
  15790. _SG_VALIDATE(bindings->index_buffer.id != SG_INVALID_ID, VALIDATE_ABND_NO_IB);
  15791. }
  15792. if (bindings->index_buffer.id != SG_INVALID_ID) {
  15793. // buffer in index-buffer-slot must be of type SG_BUFFERTYPE_INDEXBUFFER
  15794. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, bindings->index_buffer.id);
  15795. _SG_VALIDATE(buf != 0, VALIDATE_ABND_IB_EXISTS);
  15796. if (buf && buf->slot.state == SG_RESOURCESTATE_VALID) {
  15797. _SG_VALIDATE(SG_BUFFERTYPE_INDEXBUFFER == buf->cmn.type, VALIDATE_ABND_IB_TYPE);
  15798. _SG_VALIDATE(!buf->cmn.append_overflow, VALIDATE_ABND_IB_OVERFLOW);
  15799. }
  15800. }
  15801. // has expected images
  15802. for (size_t i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  15803. if (shd->cmn.images[i].stage != SG_SHADERSTAGE_NONE) {
  15804. _SG_VALIDATE(bindings->images[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_IMAGE_BINDING);
  15805. if (bindings->images[i].id != SG_INVALID_ID) {
  15806. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, bindings->images[i].id);
  15807. _SG_VALIDATE(img != 0, VALIDATE_ABND_IMG_EXISTS);
  15808. if (img && img->slot.state == SG_RESOURCESTATE_VALID) {
  15809. _SG_VALIDATE(img->cmn.type == shd->cmn.images[i].image_type, VALIDATE_ABND_IMAGE_TYPE_MISMATCH);
  15810. if (!_sg.features.msaa_image_bindings) {
  15811. _SG_VALIDATE(img->cmn.sample_count == 1, VALIDATE_ABND_IMAGE_MSAA);
  15812. }
  15813. if (shd->cmn.images[i].multisampled) {
  15814. _SG_VALIDATE(img->cmn.sample_count > 1, VALIDATE_ABND_EXPECTED_MULTISAMPLED_IMAGE);
  15815. }
  15816. const _sg_pixelformat_info_t* info = &_sg.formats[img->cmn.pixel_format];
  15817. switch (shd->cmn.images[i].sample_type) {
  15818. case SG_IMAGESAMPLETYPE_FLOAT:
  15819. _SG_VALIDATE(info->filter, VALIDATE_ABND_EXPECTED_FILTERABLE_IMAGE);
  15820. break;
  15821. case SG_IMAGESAMPLETYPE_DEPTH:
  15822. _SG_VALIDATE(info->depth, VALIDATE_ABND_EXPECTED_DEPTH_IMAGE);
  15823. break;
  15824. default:
  15825. break;
  15826. }
  15827. }
  15828. }
  15829. }
  15830. }
  15831. // has expected samplers
  15832. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  15833. if (shd->cmn.samplers[i].stage != SG_SHADERSTAGE_NONE) {
  15834. _SG_VALIDATE(bindings->samplers[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_SAMPLER_BINDING);
  15835. if (bindings->samplers[i].id != SG_INVALID_ID) {
  15836. const _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, bindings->samplers[i].id);
  15837. _SG_VALIDATE(smp != 0, VALIDATE_ABND_SMP_EXISTS);
  15838. if (smp) {
  15839. if (shd->cmn.samplers[i].sampler_type == SG_SAMPLERTYPE_COMPARISON) {
  15840. _SG_VALIDATE(smp->cmn.compare != SG_COMPAREFUNC_NEVER, VALIDATE_ABND_UNEXPECTED_SAMPLER_COMPARE_NEVER);
  15841. } else {
  15842. _SG_VALIDATE(smp->cmn.compare == SG_COMPAREFUNC_NEVER, VALIDATE_ABND_EXPECTED_SAMPLER_COMPARE_NEVER);
  15843. }
  15844. if (shd->cmn.samplers[i].sampler_type == SG_SAMPLERTYPE_NONFILTERING) {
  15845. const bool nonfiltering = (smp->cmn.min_filter != SG_FILTER_LINEAR)
  15846. && (smp->cmn.mag_filter != SG_FILTER_LINEAR)
  15847. && (smp->cmn.mipmap_filter != SG_FILTER_LINEAR);
  15848. _SG_VALIDATE(nonfiltering, VALIDATE_ABND_EXPECTED_NONFILTERING_SAMPLER);
  15849. }
  15850. }
  15851. }
  15852. }
  15853. }
  15854. // has expected storage buffers
  15855. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  15856. if (shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE) {
  15857. _SG_VALIDATE(bindings->storage_buffers[i].id != SG_INVALID_ID, VALIDATE_ABND_EXPECTED_STORAGEBUFFER_BINDING);
  15858. if (bindings->storage_buffers[i].id != SG_INVALID_ID) {
  15859. const _sg_buffer_t* sbuf = _sg_lookup_buffer(&_sg.pools, bindings->storage_buffers[i].id);
  15860. _SG_VALIDATE(sbuf != 0, VALIDATE_ABND_STORAGEBUFFER_EXISTS);
  15861. if (sbuf) {
  15862. _SG_VALIDATE(sbuf->cmn.type == SG_BUFFERTYPE_STORAGEBUFFER, VALIDATE_ABND_STORAGEBUFFER_BINDING_BUFFERTYPE);
  15863. }
  15864. }
  15865. }
  15866. }
  15867. return _sg_validate_end();
  15868. #endif
  15869. }
  15870. _SOKOL_PRIVATE bool _sg_validate_apply_uniforms(int ub_slot, const sg_range* data) {
  15871. #if !defined(SOKOL_DEBUG)
  15872. _SOKOL_UNUSED(ub_slot);
  15873. _SOKOL_UNUSED(data);
  15874. return true;
  15875. #else
  15876. if (_sg.desc.disable_validation) {
  15877. return true;
  15878. }
  15879. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  15880. _sg_validate_begin();
  15881. _SG_VALIDATE(_sg.cur_pipeline.id != SG_INVALID_ID, VALIDATE_AUB_NO_PIPELINE);
  15882. const _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, _sg.cur_pipeline.id);
  15883. SOKOL_ASSERT(pip && (pip->slot.id == _sg.cur_pipeline.id));
  15884. SOKOL_ASSERT(pip->shader && (pip->shader->slot.id == pip->cmn.shader_id.id));
  15885. const _sg_shader_t* shd = pip->shader;
  15886. _SG_VALIDATE(shd->cmn.uniform_blocks[ub_slot].stage != SG_SHADERSTAGE_NONE, VALIDATE_AUB_NO_UNIFORMBLOCK_AT_SLOT);
  15887. _SG_VALIDATE(data->size == shd->cmn.uniform_blocks[ub_slot].size, VALIDATE_AUB_SIZE);
  15888. return _sg_validate_end();
  15889. #endif
  15890. }
  15891. _SOKOL_PRIVATE bool _sg_validate_update_buffer(const _sg_buffer_t* buf, const sg_range* data) {
  15892. #if !defined(SOKOL_DEBUG)
  15893. _SOKOL_UNUSED(buf);
  15894. _SOKOL_UNUSED(data);
  15895. return true;
  15896. #else
  15897. if (_sg.desc.disable_validation) {
  15898. return true;
  15899. }
  15900. SOKOL_ASSERT(buf && data && data->ptr);
  15901. _sg_validate_begin();
  15902. _SG_VALIDATE(buf->cmn.usage != SG_USAGE_IMMUTABLE, VALIDATE_UPDATEBUF_USAGE);
  15903. _SG_VALIDATE(buf->cmn.size >= (int)data->size, VALIDATE_UPDATEBUF_SIZE);
  15904. _SG_VALIDATE(buf->cmn.update_frame_index != _sg.frame_index, VALIDATE_UPDATEBUF_ONCE);
  15905. _SG_VALIDATE(buf->cmn.append_frame_index != _sg.frame_index, VALIDATE_UPDATEBUF_APPEND);
  15906. return _sg_validate_end();
  15907. #endif
  15908. }
  15909. _SOKOL_PRIVATE bool _sg_validate_append_buffer(const _sg_buffer_t* buf, const sg_range* data) {
  15910. #if !defined(SOKOL_DEBUG)
  15911. _SOKOL_UNUSED(buf);
  15912. _SOKOL_UNUSED(data);
  15913. return true;
  15914. #else
  15915. if (_sg.desc.disable_validation) {
  15916. return true;
  15917. }
  15918. SOKOL_ASSERT(buf && data && data->ptr);
  15919. _sg_validate_begin();
  15920. _SG_VALIDATE(buf->cmn.usage != SG_USAGE_IMMUTABLE, VALIDATE_APPENDBUF_USAGE);
  15921. _SG_VALIDATE(buf->cmn.size >= (buf->cmn.append_pos + (int)data->size), VALIDATE_APPENDBUF_SIZE);
  15922. _SG_VALIDATE(buf->cmn.update_frame_index != _sg.frame_index, VALIDATE_APPENDBUF_UPDATE);
  15923. return _sg_validate_end();
  15924. #endif
  15925. }
  15926. _SOKOL_PRIVATE bool _sg_validate_update_image(const _sg_image_t* img, const sg_image_data* data) {
  15927. #if !defined(SOKOL_DEBUG)
  15928. _SOKOL_UNUSED(img);
  15929. _SOKOL_UNUSED(data);
  15930. return true;
  15931. #else
  15932. if (_sg.desc.disable_validation) {
  15933. return true;
  15934. }
  15935. SOKOL_ASSERT(img && data);
  15936. _sg_validate_begin();
  15937. _SG_VALIDATE(img->cmn.usage != SG_USAGE_IMMUTABLE, VALIDATE_UPDIMG_USAGE);
  15938. _SG_VALIDATE(img->cmn.upd_frame_index != _sg.frame_index, VALIDATE_UPDIMG_ONCE);
  15939. _sg_validate_image_data(data,
  15940. img->cmn.pixel_format,
  15941. img->cmn.width,
  15942. img->cmn.height,
  15943. (img->cmn.type == SG_IMAGETYPE_CUBE) ? 6 : 1,
  15944. img->cmn.num_mipmaps,
  15945. img->cmn.num_slices);
  15946. return _sg_validate_end();
  15947. #endif
  15948. }
  15949. // ██████ ███████ ███████ ██████ ██ ██ ██████ ██████ ███████ ███████
  15950. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  15951. // ██████ █████ ███████ ██ ██ ██ ██ ██████ ██ █████ ███████
  15952. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  15953. // ██ ██ ███████ ███████ ██████ ██████ ██ ██ ██████ ███████ ███████
  15954. //
  15955. // >>resources
  15956. _SOKOL_PRIVATE sg_buffer_desc _sg_buffer_desc_defaults(const sg_buffer_desc* desc) {
  15957. sg_buffer_desc def = *desc;
  15958. def.type = _sg_def(def.type, SG_BUFFERTYPE_VERTEXBUFFER);
  15959. def.usage = _sg_def(def.usage, SG_USAGE_IMMUTABLE);
  15960. if (def.size == 0) {
  15961. def.size = def.data.size;
  15962. } else if (def.data.size == 0) {
  15963. def.data.size = def.size;
  15964. }
  15965. return def;
  15966. }
  15967. _SOKOL_PRIVATE sg_image_desc _sg_image_desc_defaults(const sg_image_desc* desc) {
  15968. sg_image_desc def = *desc;
  15969. def.type = _sg_def(def.type, SG_IMAGETYPE_2D);
  15970. def.num_slices = _sg_def(def.num_slices, 1);
  15971. def.num_mipmaps = _sg_def(def.num_mipmaps, 1);
  15972. def.usage = _sg_def(def.usage, SG_USAGE_IMMUTABLE);
  15973. if (desc->render_target) {
  15974. def.pixel_format = _sg_def(def.pixel_format, _sg.desc.environment.defaults.color_format);
  15975. def.sample_count = _sg_def(def.sample_count, _sg.desc.environment.defaults.sample_count);
  15976. } else {
  15977. def.pixel_format = _sg_def(def.pixel_format, SG_PIXELFORMAT_RGBA8);
  15978. def.sample_count = _sg_def(def.sample_count, 1);
  15979. }
  15980. return def;
  15981. }
  15982. _SOKOL_PRIVATE sg_sampler_desc _sg_sampler_desc_defaults(const sg_sampler_desc* desc) {
  15983. sg_sampler_desc def = *desc;
  15984. def.min_filter = _sg_def(def.min_filter, SG_FILTER_NEAREST);
  15985. def.mag_filter = _sg_def(def.mag_filter, SG_FILTER_NEAREST);
  15986. def.mipmap_filter = _sg_def(def.mipmap_filter, SG_FILTER_NEAREST);
  15987. def.wrap_u = _sg_def(def.wrap_u, SG_WRAP_REPEAT);
  15988. def.wrap_v = _sg_def(def.wrap_v, SG_WRAP_REPEAT);
  15989. def.wrap_w = _sg_def(def.wrap_w, SG_WRAP_REPEAT);
  15990. def.max_lod = _sg_def_flt(def.max_lod, FLT_MAX);
  15991. def.border_color = _sg_def(def.border_color, SG_BORDERCOLOR_OPAQUE_BLACK);
  15992. def.compare = _sg_def(def.compare, SG_COMPAREFUNC_NEVER);
  15993. def.max_anisotropy = _sg_def(def.max_anisotropy, 1);
  15994. return def;
  15995. }
  15996. _SOKOL_PRIVATE sg_shader_desc _sg_shader_desc_defaults(const sg_shader_desc* desc) {
  15997. sg_shader_desc def = *desc;
  15998. #if defined(SOKOL_METAL)
  15999. def.vertex_func.entry = _sg_def(def.vertex_func.entry, "_main");
  16000. def.fragment_func.entry = _sg_def(def.fragment_func.entry, "_main");
  16001. #else
  16002. def.vertex_func.entry = _sg_def(def.vertex_func.entry, "main");
  16003. def.fragment_func.entry = _sg_def(def.fragment_func.entry, "main");
  16004. #endif
  16005. #if defined(SOKOL_D3D11)
  16006. if (def.vertex_func.source) {
  16007. def.vertex_func.d3d11_target = _sg_def(def.vertex_func.d3d11_target, "vs_4_0");
  16008. }
  16009. if (def.fragment_func.source) {
  16010. def.fragment_func.d3d11_target = _sg_def(def.fragment_func.d3d11_target, "ps_4_0");
  16011. }
  16012. #endif
  16013. for (size_t ub_index = 0; ub_index < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_index++) {
  16014. sg_shader_uniform_block* ub_desc = &def.uniform_blocks[ub_index];
  16015. if (ub_desc->stage != SG_SHADERSTAGE_NONE) {
  16016. ub_desc->layout = _sg_def(ub_desc->layout, SG_UNIFORMLAYOUT_NATIVE);
  16017. for (size_t u_index = 0; u_index < SG_MAX_UNIFORMBLOCK_MEMBERS; u_index++) {
  16018. sg_glsl_shader_uniform* u_desc = &ub_desc->glsl_uniforms[u_index];
  16019. if (u_desc->type == SG_UNIFORMTYPE_INVALID) {
  16020. break;
  16021. }
  16022. u_desc->array_count = _sg_def(u_desc->array_count, 1);
  16023. }
  16024. }
  16025. }
  16026. for (size_t img_index = 0; img_index < SG_MAX_IMAGE_BINDSLOTS; img_index++) {
  16027. sg_shader_image* img_desc = &def.images[img_index];
  16028. if (img_desc->stage != SG_SHADERSTAGE_NONE) {
  16029. img_desc->image_type = _sg_def(img_desc->image_type, SG_IMAGETYPE_2D);
  16030. img_desc->sample_type = _sg_def(img_desc->sample_type, SG_IMAGESAMPLETYPE_FLOAT);
  16031. }
  16032. }
  16033. for (size_t smp_index = 0; smp_index < SG_MAX_SAMPLER_BINDSLOTS; smp_index++) {
  16034. sg_shader_sampler* smp_desc = &def.samplers[smp_index];
  16035. if (smp_desc->stage != SG_SHADERSTAGE_NONE) {
  16036. smp_desc->sampler_type = _sg_def(smp_desc->sampler_type, SG_SAMPLERTYPE_FILTERING);
  16037. }
  16038. }
  16039. return def;
  16040. }
  16041. _SOKOL_PRIVATE sg_pipeline_desc _sg_pipeline_desc_defaults(const sg_pipeline_desc* desc) {
  16042. sg_pipeline_desc def = *desc;
  16043. def.primitive_type = _sg_def(def.primitive_type, SG_PRIMITIVETYPE_TRIANGLES);
  16044. def.index_type = _sg_def(def.index_type, SG_INDEXTYPE_NONE);
  16045. def.cull_mode = _sg_def(def.cull_mode, SG_CULLMODE_NONE);
  16046. def.face_winding = _sg_def(def.face_winding, SG_FACEWINDING_CW);
  16047. def.sample_count = _sg_def(def.sample_count, _sg.desc.environment.defaults.sample_count);
  16048. def.stencil.front.compare = _sg_def(def.stencil.front.compare, SG_COMPAREFUNC_ALWAYS);
  16049. def.stencil.front.fail_op = _sg_def(def.stencil.front.fail_op, SG_STENCILOP_KEEP);
  16050. def.stencil.front.depth_fail_op = _sg_def(def.stencil.front.depth_fail_op, SG_STENCILOP_KEEP);
  16051. def.stencil.front.pass_op = _sg_def(def.stencil.front.pass_op, SG_STENCILOP_KEEP);
  16052. def.stencil.back.compare = _sg_def(def.stencil.back.compare, SG_COMPAREFUNC_ALWAYS);
  16053. def.stencil.back.fail_op = _sg_def(def.stencil.back.fail_op, SG_STENCILOP_KEEP);
  16054. def.stencil.back.depth_fail_op = _sg_def(def.stencil.back.depth_fail_op, SG_STENCILOP_KEEP);
  16055. def.stencil.back.pass_op = _sg_def(def.stencil.back.pass_op, SG_STENCILOP_KEEP);
  16056. def.depth.compare = _sg_def(def.depth.compare, SG_COMPAREFUNC_ALWAYS);
  16057. def.depth.pixel_format = _sg_def(def.depth.pixel_format, _sg.desc.environment.defaults.depth_format);
  16058. if (def.colors[0].pixel_format == SG_PIXELFORMAT_NONE) {
  16059. // special case depth-only rendering, enforce a color count of 0
  16060. def.color_count = 0;
  16061. } else {
  16062. def.color_count = _sg_def(def.color_count, 1);
  16063. }
  16064. if (def.color_count > SG_MAX_COLOR_ATTACHMENTS) {
  16065. def.color_count = SG_MAX_COLOR_ATTACHMENTS;
  16066. }
  16067. for (int i = 0; i < def.color_count; i++) {
  16068. sg_color_target_state* cs = &def.colors[i];
  16069. cs->pixel_format = _sg_def(cs->pixel_format, _sg.desc.environment.defaults.color_format);
  16070. cs->write_mask = _sg_def(cs->write_mask, SG_COLORMASK_RGBA);
  16071. sg_blend_state* bs = &def.colors[i].blend;
  16072. bs->op_rgb = _sg_def(bs->op_rgb, SG_BLENDOP_ADD);
  16073. bs->src_factor_rgb = _sg_def(bs->src_factor_rgb, SG_BLENDFACTOR_ONE);
  16074. if ((bs->op_rgb == SG_BLENDOP_MIN) || (bs->op_rgb == SG_BLENDOP_MAX)) {
  16075. bs->dst_factor_rgb = _sg_def(bs->dst_factor_rgb, SG_BLENDFACTOR_ONE);
  16076. } else {
  16077. bs->dst_factor_rgb = _sg_def(bs->dst_factor_rgb, SG_BLENDFACTOR_ZERO);
  16078. }
  16079. bs->op_alpha = _sg_def(bs->op_alpha, SG_BLENDOP_ADD);
  16080. bs->src_factor_alpha = _sg_def(bs->src_factor_alpha, SG_BLENDFACTOR_ONE);
  16081. if ((bs->op_alpha == SG_BLENDOP_MIN) || (bs->op_alpha == SG_BLENDOP_MAX)) {
  16082. bs->dst_factor_alpha = _sg_def(bs->dst_factor_alpha, SG_BLENDFACTOR_ONE);
  16083. } else {
  16084. bs->dst_factor_alpha = _sg_def(bs->dst_factor_alpha, SG_BLENDFACTOR_ZERO);
  16085. }
  16086. }
  16087. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  16088. sg_vertex_attr_state* a_state = &def.layout.attrs[attr_index];
  16089. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  16090. break;
  16091. }
  16092. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  16093. sg_vertex_buffer_layout_state* l_state = &def.layout.buffers[a_state->buffer_index];
  16094. l_state->step_func = _sg_def(l_state->step_func, SG_VERTEXSTEP_PER_VERTEX);
  16095. l_state->step_rate = _sg_def(l_state->step_rate, 1);
  16096. }
  16097. // resolve vertex layout strides and offsets
  16098. int auto_offset[SG_MAX_VERTEXBUFFER_BINDSLOTS];
  16099. _sg_clear(auto_offset, sizeof(auto_offset));
  16100. bool use_auto_offset = true;
  16101. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  16102. // to use computed offsets, *all* attr offsets must be 0
  16103. if (def.layout.attrs[attr_index].offset != 0) {
  16104. use_auto_offset = false;
  16105. }
  16106. }
  16107. for (int attr_index = 0; attr_index < SG_MAX_VERTEX_ATTRIBUTES; attr_index++) {
  16108. sg_vertex_attr_state* a_state = &def.layout.attrs[attr_index];
  16109. if (a_state->format == SG_VERTEXFORMAT_INVALID) {
  16110. break;
  16111. }
  16112. SOKOL_ASSERT(a_state->buffer_index < SG_MAX_VERTEXBUFFER_BINDSLOTS);
  16113. if (use_auto_offset) {
  16114. a_state->offset = auto_offset[a_state->buffer_index];
  16115. }
  16116. auto_offset[a_state->buffer_index] += _sg_vertexformat_bytesize(a_state->format);
  16117. }
  16118. // compute vertex strides if needed
  16119. for (int buf_index = 0; buf_index < SG_MAX_VERTEXBUFFER_BINDSLOTS; buf_index++) {
  16120. sg_vertex_buffer_layout_state* l_state = &def.layout.buffers[buf_index];
  16121. if (l_state->stride == 0) {
  16122. l_state->stride = auto_offset[buf_index];
  16123. }
  16124. }
  16125. return def;
  16126. }
  16127. _SOKOL_PRIVATE sg_attachments_desc _sg_attachments_desc_defaults(const sg_attachments_desc* desc) {
  16128. sg_attachments_desc def = *desc;
  16129. return def;
  16130. }
  16131. _SOKOL_PRIVATE sg_buffer _sg_alloc_buffer(void) {
  16132. sg_buffer res;
  16133. int slot_index = _sg_pool_alloc_index(&_sg.pools.buffer_pool);
  16134. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  16135. res.id = _sg_slot_alloc(&_sg.pools.buffer_pool, &_sg.pools.buffers[slot_index].slot, slot_index);
  16136. } else {
  16137. res.id = SG_INVALID_ID;
  16138. _SG_ERROR(BUFFER_POOL_EXHAUSTED);
  16139. }
  16140. return res;
  16141. }
  16142. _SOKOL_PRIVATE sg_image _sg_alloc_image(void) {
  16143. sg_image res;
  16144. int slot_index = _sg_pool_alloc_index(&_sg.pools.image_pool);
  16145. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  16146. res.id = _sg_slot_alloc(&_sg.pools.image_pool, &_sg.pools.images[slot_index].slot, slot_index);
  16147. } else {
  16148. res.id = SG_INVALID_ID;
  16149. _SG_ERROR(IMAGE_POOL_EXHAUSTED);
  16150. }
  16151. return res;
  16152. }
  16153. _SOKOL_PRIVATE sg_sampler _sg_alloc_sampler(void) {
  16154. sg_sampler res;
  16155. int slot_index = _sg_pool_alloc_index(&_sg.pools.sampler_pool);
  16156. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  16157. res.id = _sg_slot_alloc(&_sg.pools.sampler_pool, &_sg.pools.samplers[slot_index].slot, slot_index);
  16158. } else {
  16159. res.id = SG_INVALID_ID;
  16160. _SG_ERROR(SAMPLER_POOL_EXHAUSTED);
  16161. }
  16162. return res;
  16163. }
  16164. _SOKOL_PRIVATE sg_shader _sg_alloc_shader(void) {
  16165. sg_shader res;
  16166. int slot_index = _sg_pool_alloc_index(&_sg.pools.shader_pool);
  16167. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  16168. res.id = _sg_slot_alloc(&_sg.pools.shader_pool, &_sg.pools.shaders[slot_index].slot, slot_index);
  16169. } else {
  16170. res.id = SG_INVALID_ID;
  16171. _SG_ERROR(SHADER_POOL_EXHAUSTED);
  16172. }
  16173. return res;
  16174. }
  16175. _SOKOL_PRIVATE sg_pipeline _sg_alloc_pipeline(void) {
  16176. sg_pipeline res;
  16177. int slot_index = _sg_pool_alloc_index(&_sg.pools.pipeline_pool);
  16178. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  16179. res.id =_sg_slot_alloc(&_sg.pools.pipeline_pool, &_sg.pools.pipelines[slot_index].slot, slot_index);
  16180. } else {
  16181. res.id = SG_INVALID_ID;
  16182. _SG_ERROR(PIPELINE_POOL_EXHAUSTED);
  16183. }
  16184. return res;
  16185. }
  16186. _SOKOL_PRIVATE sg_attachments _sg_alloc_attachments(void) {
  16187. sg_attachments res;
  16188. int slot_index = _sg_pool_alloc_index(&_sg.pools.attachments_pool);
  16189. if (_SG_INVALID_SLOT_INDEX != slot_index) {
  16190. res.id = _sg_slot_alloc(&_sg.pools.attachments_pool, &_sg.pools.attachments[slot_index].slot, slot_index);
  16191. } else {
  16192. res.id = SG_INVALID_ID;
  16193. _SG_ERROR(PASS_POOL_EXHAUSTED);
  16194. }
  16195. return res;
  16196. }
  16197. _SOKOL_PRIVATE void _sg_dealloc_buffer(_sg_buffer_t* buf) {
  16198. SOKOL_ASSERT(buf && (buf->slot.state == SG_RESOURCESTATE_ALLOC) && (buf->slot.id != SG_INVALID_ID));
  16199. _sg_pool_free_index(&_sg.pools.buffer_pool, _sg_slot_index(buf->slot.id));
  16200. _sg_reset_slot(&buf->slot);
  16201. }
  16202. _SOKOL_PRIVATE void _sg_dealloc_image(_sg_image_t* img) {
  16203. SOKOL_ASSERT(img && (img->slot.state == SG_RESOURCESTATE_ALLOC) && (img->slot.id != SG_INVALID_ID));
  16204. _sg_pool_free_index(&_sg.pools.image_pool, _sg_slot_index(img->slot.id));
  16205. _sg_reset_slot(&img->slot);
  16206. }
  16207. _SOKOL_PRIVATE void _sg_dealloc_sampler(_sg_sampler_t* smp) {
  16208. SOKOL_ASSERT(smp && (smp->slot.state == SG_RESOURCESTATE_ALLOC) && (smp->slot.id != SG_INVALID_ID));
  16209. _sg_pool_free_index(&_sg.pools.sampler_pool, _sg_slot_index(smp->slot.id));
  16210. _sg_reset_slot(&smp->slot);
  16211. }
  16212. _SOKOL_PRIVATE void _sg_dealloc_shader(_sg_shader_t* shd) {
  16213. SOKOL_ASSERT(shd && (shd->slot.state == SG_RESOURCESTATE_ALLOC) && (shd->slot.id != SG_INVALID_ID));
  16214. _sg_pool_free_index(&_sg.pools.shader_pool, _sg_slot_index(shd->slot.id));
  16215. _sg_reset_slot(&shd->slot);
  16216. }
  16217. _SOKOL_PRIVATE void _sg_dealloc_pipeline(_sg_pipeline_t* pip) {
  16218. SOKOL_ASSERT(pip && (pip->slot.state == SG_RESOURCESTATE_ALLOC) && (pip->slot.id != SG_INVALID_ID));
  16219. _sg_pool_free_index(&_sg.pools.pipeline_pool, _sg_slot_index(pip->slot.id));
  16220. _sg_reset_slot(&pip->slot);
  16221. }
  16222. _SOKOL_PRIVATE void _sg_dealloc_attachments(_sg_attachments_t* atts) {
  16223. SOKOL_ASSERT(atts && (atts->slot.state == SG_RESOURCESTATE_ALLOC) && (atts->slot.id != SG_INVALID_ID));
  16224. _sg_pool_free_index(&_sg.pools.attachments_pool, _sg_slot_index(atts->slot.id));
  16225. _sg_reset_slot(&atts->slot);
  16226. }
  16227. _SOKOL_PRIVATE void _sg_init_buffer(_sg_buffer_t* buf, const sg_buffer_desc* desc) {
  16228. SOKOL_ASSERT(buf && (buf->slot.state == SG_RESOURCESTATE_ALLOC));
  16229. SOKOL_ASSERT(desc);
  16230. if (_sg_validate_buffer_desc(desc)) {
  16231. _sg_buffer_common_init(&buf->cmn, desc);
  16232. buf->slot.state = _sg_create_buffer(buf, desc);
  16233. } else {
  16234. buf->slot.state = SG_RESOURCESTATE_FAILED;
  16235. }
  16236. SOKOL_ASSERT((buf->slot.state == SG_RESOURCESTATE_VALID)||(buf->slot.state == SG_RESOURCESTATE_FAILED));
  16237. }
  16238. _SOKOL_PRIVATE void _sg_init_image(_sg_image_t* img, const sg_image_desc* desc) {
  16239. SOKOL_ASSERT(img && (img->slot.state == SG_RESOURCESTATE_ALLOC));
  16240. SOKOL_ASSERT(desc);
  16241. if (_sg_validate_image_desc(desc)) {
  16242. _sg_image_common_init(&img->cmn, desc);
  16243. img->slot.state = _sg_create_image(img, desc);
  16244. } else {
  16245. img->slot.state = SG_RESOURCESTATE_FAILED;
  16246. }
  16247. SOKOL_ASSERT((img->slot.state == SG_RESOURCESTATE_VALID)||(img->slot.state == SG_RESOURCESTATE_FAILED));
  16248. }
  16249. _SOKOL_PRIVATE void _sg_init_sampler(_sg_sampler_t* smp, const sg_sampler_desc* desc) {
  16250. SOKOL_ASSERT(smp && (smp->slot.state == SG_RESOURCESTATE_ALLOC));
  16251. SOKOL_ASSERT(desc);
  16252. if (_sg_validate_sampler_desc(desc)) {
  16253. _sg_sampler_common_init(&smp->cmn, desc);
  16254. smp->slot.state = _sg_create_sampler(smp, desc);
  16255. } else {
  16256. smp->slot.state = SG_RESOURCESTATE_FAILED;
  16257. }
  16258. SOKOL_ASSERT((smp->slot.state == SG_RESOURCESTATE_VALID)||(smp->slot.state == SG_RESOURCESTATE_FAILED));
  16259. }
  16260. _SOKOL_PRIVATE void _sg_init_shader(_sg_shader_t* shd, const sg_shader_desc* desc) {
  16261. SOKOL_ASSERT(shd && (shd->slot.state == SG_RESOURCESTATE_ALLOC));
  16262. SOKOL_ASSERT(desc);
  16263. if (_sg_validate_shader_desc(desc)) {
  16264. _sg_shader_common_init(&shd->cmn, desc);
  16265. shd->slot.state = _sg_create_shader(shd, desc);
  16266. } else {
  16267. shd->slot.state = SG_RESOURCESTATE_FAILED;
  16268. }
  16269. SOKOL_ASSERT((shd->slot.state == SG_RESOURCESTATE_VALID)||(shd->slot.state == SG_RESOURCESTATE_FAILED));
  16270. }
  16271. _SOKOL_PRIVATE void _sg_init_pipeline(_sg_pipeline_t* pip, const sg_pipeline_desc* desc) {
  16272. SOKOL_ASSERT(pip && (pip->slot.state == SG_RESOURCESTATE_ALLOC));
  16273. SOKOL_ASSERT(desc);
  16274. if (_sg_validate_pipeline_desc(desc)) {
  16275. _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, desc->shader.id);
  16276. if (shd && (shd->slot.state == SG_RESOURCESTATE_VALID)) {
  16277. _sg_pipeline_common_init(&pip->cmn, desc);
  16278. pip->slot.state = _sg_create_pipeline(pip, shd, desc);
  16279. } else {
  16280. pip->slot.state = SG_RESOURCESTATE_FAILED;
  16281. }
  16282. } else {
  16283. pip->slot.state = SG_RESOURCESTATE_FAILED;
  16284. }
  16285. SOKOL_ASSERT((pip->slot.state == SG_RESOURCESTATE_VALID)||(pip->slot.state == SG_RESOURCESTATE_FAILED));
  16286. }
  16287. _SOKOL_PRIVATE void _sg_init_attachments(_sg_attachments_t* atts, const sg_attachments_desc* desc) {
  16288. SOKOL_ASSERT(atts && atts->slot.state == SG_RESOURCESTATE_ALLOC);
  16289. SOKOL_ASSERT(desc);
  16290. if (_sg_validate_attachments_desc(desc)) {
  16291. // lookup pass attachment image pointers
  16292. _sg_image_t* color_images[SG_MAX_COLOR_ATTACHMENTS] = { 0 };
  16293. _sg_image_t* resolve_images[SG_MAX_COLOR_ATTACHMENTS] = { 0 };
  16294. _sg_image_t* ds_image = 0;
  16295. // NOTE: validation already checked that all surfaces are same width/height
  16296. int width = 0;
  16297. int height = 0;
  16298. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  16299. if (desc->colors[i].image.id) {
  16300. color_images[i] = _sg_lookup_image(&_sg.pools, desc->colors[i].image.id);
  16301. if (!(color_images[i] && color_images[i]->slot.state == SG_RESOURCESTATE_VALID)) {
  16302. atts->slot.state = SG_RESOURCESTATE_FAILED;
  16303. return;
  16304. }
  16305. const int mip_level = desc->colors[i].mip_level;
  16306. width = _sg_miplevel_dim(color_images[i]->cmn.width, mip_level);
  16307. height = _sg_miplevel_dim(color_images[i]->cmn.height, mip_level);
  16308. }
  16309. if (desc->resolves[i].image.id) {
  16310. resolve_images[i] = _sg_lookup_image(&_sg.pools, desc->resolves[i].image.id);
  16311. if (!(resolve_images[i] && resolve_images[i]->slot.state == SG_RESOURCESTATE_VALID)) {
  16312. atts->slot.state = SG_RESOURCESTATE_FAILED;
  16313. return;
  16314. }
  16315. }
  16316. }
  16317. if (desc->depth_stencil.image.id) {
  16318. ds_image = _sg_lookup_image(&_sg.pools, desc->depth_stencil.image.id);
  16319. if (!(ds_image && ds_image->slot.state == SG_RESOURCESTATE_VALID)) {
  16320. atts->slot.state = SG_RESOURCESTATE_FAILED;
  16321. return;
  16322. }
  16323. const int mip_level = desc->depth_stencil.mip_level;
  16324. width = _sg_miplevel_dim(ds_image->cmn.width, mip_level);
  16325. height = _sg_miplevel_dim(ds_image->cmn.height, mip_level);
  16326. }
  16327. _sg_attachments_common_init(&atts->cmn, desc, width, height);
  16328. atts->slot.state = _sg_create_attachments(atts, color_images, resolve_images, ds_image, desc);
  16329. } else {
  16330. atts->slot.state = SG_RESOURCESTATE_FAILED;
  16331. }
  16332. SOKOL_ASSERT((atts->slot.state == SG_RESOURCESTATE_VALID)||(atts->slot.state == SG_RESOURCESTATE_FAILED));
  16333. }
  16334. _SOKOL_PRIVATE void _sg_uninit_buffer(_sg_buffer_t* buf) {
  16335. SOKOL_ASSERT(buf && ((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED)));
  16336. _sg_discard_buffer(buf);
  16337. _sg_reset_buffer_to_alloc_state(buf);
  16338. }
  16339. _SOKOL_PRIVATE void _sg_uninit_image(_sg_image_t* img) {
  16340. SOKOL_ASSERT(img && ((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED)));
  16341. _sg_discard_image(img);
  16342. _sg_reset_image_to_alloc_state(img);
  16343. }
  16344. _SOKOL_PRIVATE void _sg_uninit_sampler(_sg_sampler_t* smp) {
  16345. SOKOL_ASSERT(smp && ((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED)));
  16346. _sg_discard_sampler(smp);
  16347. _sg_reset_sampler_to_alloc_state(smp);
  16348. }
  16349. _SOKOL_PRIVATE void _sg_uninit_shader(_sg_shader_t* shd) {
  16350. SOKOL_ASSERT(shd && ((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED)));
  16351. _sg_discard_shader(shd);
  16352. _sg_reset_shader_to_alloc_state(shd);
  16353. }
  16354. _SOKOL_PRIVATE void _sg_uninit_pipeline(_sg_pipeline_t* pip) {
  16355. SOKOL_ASSERT(pip && ((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED)));
  16356. _sg_discard_pipeline(pip);
  16357. _sg_reset_pipeline_to_alloc_state(pip);
  16358. }
  16359. _SOKOL_PRIVATE void _sg_uninit_attachments(_sg_attachments_t* atts) {
  16360. SOKOL_ASSERT(atts && ((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED)));
  16361. _sg_discard_attachments(atts);
  16362. _sg_reset_attachments_to_alloc_state(atts);
  16363. }
  16364. _SOKOL_PRIVATE void _sg_setup_commit_listeners(const sg_desc* desc) {
  16365. SOKOL_ASSERT(desc->max_commit_listeners > 0);
  16366. SOKOL_ASSERT(0 == _sg.commit_listeners.items);
  16367. SOKOL_ASSERT(0 == _sg.commit_listeners.num);
  16368. SOKOL_ASSERT(0 == _sg.commit_listeners.upper);
  16369. _sg.commit_listeners.num = desc->max_commit_listeners;
  16370. const size_t size = (size_t)_sg.commit_listeners.num * sizeof(sg_commit_listener);
  16371. _sg.commit_listeners.items = (sg_commit_listener*)_sg_malloc_clear(size);
  16372. }
  16373. _SOKOL_PRIVATE void _sg_discard_commit_listeners(void) {
  16374. SOKOL_ASSERT(0 != _sg.commit_listeners.items);
  16375. _sg_free(_sg.commit_listeners.items);
  16376. _sg.commit_listeners.items = 0;
  16377. }
  16378. _SOKOL_PRIVATE void _sg_notify_commit_listeners(void) {
  16379. SOKOL_ASSERT(_sg.commit_listeners.items);
  16380. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  16381. const sg_commit_listener* listener = &_sg.commit_listeners.items[i];
  16382. if (listener->func) {
  16383. listener->func(listener->user_data);
  16384. }
  16385. }
  16386. }
  16387. _SOKOL_PRIVATE bool _sg_add_commit_listener(const sg_commit_listener* new_listener) {
  16388. SOKOL_ASSERT(new_listener && new_listener->func);
  16389. SOKOL_ASSERT(_sg.commit_listeners.items);
  16390. // first check if the listener hadn't been added already
  16391. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  16392. const sg_commit_listener* slot = &_sg.commit_listeners.items[i];
  16393. if ((slot->func == new_listener->func) && (slot->user_data == new_listener->user_data)) {
  16394. _SG_ERROR(IDENTICAL_COMMIT_LISTENER);
  16395. return false;
  16396. }
  16397. }
  16398. // first try to plug a hole
  16399. sg_commit_listener* slot = 0;
  16400. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  16401. if (_sg.commit_listeners.items[i].func == 0) {
  16402. slot = &_sg.commit_listeners.items[i];
  16403. break;
  16404. }
  16405. }
  16406. if (!slot) {
  16407. // append to end
  16408. if (_sg.commit_listeners.upper < _sg.commit_listeners.num) {
  16409. slot = &_sg.commit_listeners.items[_sg.commit_listeners.upper++];
  16410. }
  16411. }
  16412. if (!slot) {
  16413. _SG_ERROR(COMMIT_LISTENER_ARRAY_FULL);
  16414. return false;
  16415. }
  16416. *slot = *new_listener;
  16417. return true;
  16418. }
  16419. _SOKOL_PRIVATE bool _sg_remove_commit_listener(const sg_commit_listener* listener) {
  16420. SOKOL_ASSERT(listener && listener->func);
  16421. SOKOL_ASSERT(_sg.commit_listeners.items);
  16422. for (int i = 0; i < _sg.commit_listeners.upper; i++) {
  16423. sg_commit_listener* slot = &_sg.commit_listeners.items[i];
  16424. // both the function pointer and user data must match!
  16425. if ((slot->func == listener->func) && (slot->user_data == listener->user_data)) {
  16426. slot->func = 0;
  16427. slot->user_data = 0;
  16428. // NOTE: since _sg_add_commit_listener() already catches duplicates,
  16429. // we don't need to worry about them here
  16430. return true;
  16431. }
  16432. }
  16433. return false;
  16434. }
  16435. _SOKOL_PRIVATE sg_desc _sg_desc_defaults(const sg_desc* desc) {
  16436. /*
  16437. NOTE: on WebGPU, the default color pixel format MUST be provided,
  16438. cannot be a default compile-time constant.
  16439. */
  16440. sg_desc res = *desc;
  16441. #if defined(SOKOL_WGPU)
  16442. SOKOL_ASSERT(SG_PIXELFORMAT_NONE < res.environment.defaults.color_format);
  16443. #elif defined(SOKOL_METAL) || defined(SOKOL_D3D11)
  16444. res.environment.defaults.color_format = _sg_def(res.environment.defaults.color_format, SG_PIXELFORMAT_BGRA8);
  16445. #else
  16446. res.environment.defaults.color_format = _sg_def(res.environment.defaults.color_format, SG_PIXELFORMAT_RGBA8);
  16447. #endif
  16448. res.environment.defaults.depth_format = _sg_def(res.environment.defaults.depth_format, SG_PIXELFORMAT_DEPTH_STENCIL);
  16449. res.environment.defaults.sample_count = _sg_def(res.environment.defaults.sample_count, 1);
  16450. res.buffer_pool_size = _sg_def(res.buffer_pool_size, _SG_DEFAULT_BUFFER_POOL_SIZE);
  16451. res.image_pool_size = _sg_def(res.image_pool_size, _SG_DEFAULT_IMAGE_POOL_SIZE);
  16452. res.sampler_pool_size = _sg_def(res.sampler_pool_size, _SG_DEFAULT_SAMPLER_POOL_SIZE);
  16453. res.shader_pool_size = _sg_def(res.shader_pool_size, _SG_DEFAULT_SHADER_POOL_SIZE);
  16454. res.pipeline_pool_size = _sg_def(res.pipeline_pool_size, _SG_DEFAULT_PIPELINE_POOL_SIZE);
  16455. res.attachments_pool_size = _sg_def(res.attachments_pool_size, _SG_DEFAULT_ATTACHMENTS_POOL_SIZE);
  16456. res.uniform_buffer_size = _sg_def(res.uniform_buffer_size, _SG_DEFAULT_UB_SIZE);
  16457. res.max_commit_listeners = _sg_def(res.max_commit_listeners, _SG_DEFAULT_MAX_COMMIT_LISTENERS);
  16458. res.wgpu_bindgroups_cache_size = _sg_def(res.wgpu_bindgroups_cache_size, _SG_DEFAULT_WGPU_BINDGROUP_CACHE_SIZE);
  16459. return res;
  16460. }
  16461. _SOKOL_PRIVATE sg_pass _sg_pass_defaults(const sg_pass* pass) {
  16462. sg_pass res = *pass;
  16463. if (res.attachments.id == SG_INVALID_ID) {
  16464. // this is a swapchain-pass
  16465. res.swapchain.sample_count = _sg_def(res.swapchain.sample_count, _sg.desc.environment.defaults.sample_count);
  16466. res.swapchain.color_format = _sg_def(res.swapchain.color_format, _sg.desc.environment.defaults.color_format);
  16467. res.swapchain.depth_format = _sg_def(res.swapchain.depth_format, _sg.desc.environment.defaults.depth_format);
  16468. }
  16469. res.action = _sg_pass_action_defaults(&res.action);
  16470. return res;
  16471. }
  16472. // ██████ ██ ██ ██████ ██ ██ ██████
  16473. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  16474. // ██████ ██ ██ ██████ ██ ██ ██
  16475. // ██ ██ ██ ██ ██ ██ ██ ██
  16476. // ██ ██████ ██████ ███████ ██ ██████
  16477. //
  16478. // >>public
  16479. SOKOL_API_IMPL void sg_setup(const sg_desc* desc) {
  16480. SOKOL_ASSERT(desc);
  16481. SOKOL_ASSERT((desc->_start_canary == 0) && (desc->_end_canary == 0));
  16482. SOKOL_ASSERT((desc->allocator.alloc_fn && desc->allocator.free_fn) || (!desc->allocator.alloc_fn && !desc->allocator.free_fn));
  16483. _SG_CLEAR_ARC_STRUCT(_sg_state_t, _sg);
  16484. _sg.desc = _sg_desc_defaults(desc);
  16485. _sg_setup_pools(&_sg.pools, &_sg.desc);
  16486. _sg_setup_commit_listeners(&_sg.desc);
  16487. _sg.frame_index = 1;
  16488. _sg.stats_enabled = true;
  16489. _sg_setup_backend(&_sg.desc);
  16490. _sg.valid = true;
  16491. }
  16492. SOKOL_API_IMPL void sg_shutdown(void) {
  16493. _sg_discard_all_resources(&_sg.pools);
  16494. _sg_discard_backend();
  16495. _sg_discard_commit_listeners();
  16496. _sg_discard_pools(&_sg.pools);
  16497. _SG_CLEAR_ARC_STRUCT(_sg_state_t, _sg);
  16498. }
  16499. SOKOL_API_IMPL bool sg_isvalid(void) {
  16500. return _sg.valid;
  16501. }
  16502. SOKOL_API_IMPL sg_desc sg_query_desc(void) {
  16503. SOKOL_ASSERT(_sg.valid);
  16504. return _sg.desc;
  16505. }
  16506. SOKOL_API_IMPL sg_backend sg_query_backend(void) {
  16507. SOKOL_ASSERT(_sg.valid);
  16508. return _sg.backend;
  16509. }
  16510. SOKOL_API_IMPL sg_features sg_query_features(void) {
  16511. SOKOL_ASSERT(_sg.valid);
  16512. return _sg.features;
  16513. }
  16514. SOKOL_API_IMPL sg_limits sg_query_limits(void) {
  16515. SOKOL_ASSERT(_sg.valid);
  16516. return _sg.limits;
  16517. }
  16518. SOKOL_API_IMPL sg_pixelformat_info sg_query_pixelformat(sg_pixel_format fmt) {
  16519. SOKOL_ASSERT(_sg.valid);
  16520. int fmt_index = (int) fmt;
  16521. SOKOL_ASSERT((fmt_index > SG_PIXELFORMAT_NONE) && (fmt_index < _SG_PIXELFORMAT_NUM));
  16522. const _sg_pixelformat_info_t* src = &_sg.formats[fmt_index];
  16523. sg_pixelformat_info res;
  16524. _sg_clear(&res, sizeof(res));
  16525. res.sample = src->sample;
  16526. res.filter = src->filter;
  16527. res.render = src->render;
  16528. res.blend = src->blend;
  16529. res.msaa = src->msaa;
  16530. res.depth = src->depth;
  16531. res.compressed = _sg_is_compressed_pixel_format(fmt);
  16532. if (!res.compressed) {
  16533. res.bytes_per_pixel = _sg_pixelformat_bytesize(fmt);
  16534. }
  16535. return res;
  16536. }
  16537. SOKOL_API_IMPL int sg_query_row_pitch(sg_pixel_format fmt, int width, int row_align_bytes) {
  16538. SOKOL_ASSERT(_sg.valid);
  16539. SOKOL_ASSERT(width > 0);
  16540. SOKOL_ASSERT((row_align_bytes > 0) && _sg_ispow2(row_align_bytes));
  16541. SOKOL_ASSERT(((int)fmt > SG_PIXELFORMAT_NONE) && ((int)fmt < _SG_PIXELFORMAT_NUM));
  16542. return _sg_row_pitch(fmt, width, row_align_bytes);
  16543. }
  16544. SOKOL_API_IMPL int sg_query_surface_pitch(sg_pixel_format fmt, int width, int height, int row_align_bytes) {
  16545. SOKOL_ASSERT(_sg.valid);
  16546. SOKOL_ASSERT((width > 0) && (height > 0));
  16547. SOKOL_ASSERT((row_align_bytes > 0) && _sg_ispow2(row_align_bytes));
  16548. SOKOL_ASSERT(((int)fmt > SG_PIXELFORMAT_NONE) && ((int)fmt < _SG_PIXELFORMAT_NUM));
  16549. return _sg_surface_pitch(fmt, width, height, row_align_bytes);
  16550. }
  16551. SOKOL_API_IMPL sg_frame_stats sg_query_frame_stats(void) {
  16552. SOKOL_ASSERT(_sg.valid);
  16553. return _sg.prev_stats;
  16554. }
  16555. SOKOL_API_IMPL sg_trace_hooks sg_install_trace_hooks(const sg_trace_hooks* trace_hooks) {
  16556. SOKOL_ASSERT(_sg.valid);
  16557. SOKOL_ASSERT(trace_hooks);
  16558. _SOKOL_UNUSED(trace_hooks);
  16559. #if defined(SOKOL_TRACE_HOOKS)
  16560. sg_trace_hooks old_hooks = _sg.hooks;
  16561. _sg.hooks = *trace_hooks;
  16562. #else
  16563. static sg_trace_hooks old_hooks;
  16564. _SG_WARN(TRACE_HOOKS_NOT_ENABLED);
  16565. #endif
  16566. return old_hooks;
  16567. }
  16568. SOKOL_API_IMPL sg_buffer sg_alloc_buffer(void) {
  16569. SOKOL_ASSERT(_sg.valid);
  16570. sg_buffer res = _sg_alloc_buffer();
  16571. _SG_TRACE_ARGS(alloc_buffer, res);
  16572. return res;
  16573. }
  16574. SOKOL_API_IMPL sg_image sg_alloc_image(void) {
  16575. SOKOL_ASSERT(_sg.valid);
  16576. sg_image res = _sg_alloc_image();
  16577. _SG_TRACE_ARGS(alloc_image, res);
  16578. return res;
  16579. }
  16580. SOKOL_API_IMPL sg_sampler sg_alloc_sampler(void) {
  16581. SOKOL_ASSERT(_sg.valid);
  16582. sg_sampler res = _sg_alloc_sampler();
  16583. _SG_TRACE_ARGS(alloc_sampler, res);
  16584. return res;
  16585. }
  16586. SOKOL_API_IMPL sg_shader sg_alloc_shader(void) {
  16587. SOKOL_ASSERT(_sg.valid);
  16588. sg_shader res = _sg_alloc_shader();
  16589. _SG_TRACE_ARGS(alloc_shader, res);
  16590. return res;
  16591. }
  16592. SOKOL_API_IMPL sg_pipeline sg_alloc_pipeline(void) {
  16593. SOKOL_ASSERT(_sg.valid);
  16594. sg_pipeline res = _sg_alloc_pipeline();
  16595. _SG_TRACE_ARGS(alloc_pipeline, res);
  16596. return res;
  16597. }
  16598. SOKOL_API_IMPL sg_attachments sg_alloc_attachments(void) {
  16599. SOKOL_ASSERT(_sg.valid);
  16600. sg_attachments res = _sg_alloc_attachments();
  16601. _SG_TRACE_ARGS(alloc_attachments, res);
  16602. return res;
  16603. }
  16604. SOKOL_API_IMPL void sg_dealloc_buffer(sg_buffer buf_id) {
  16605. SOKOL_ASSERT(_sg.valid);
  16606. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  16607. if (buf) {
  16608. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  16609. _sg_dealloc_buffer(buf);
  16610. } else {
  16611. _SG_ERROR(DEALLOC_BUFFER_INVALID_STATE);
  16612. }
  16613. }
  16614. _SG_TRACE_ARGS(dealloc_buffer, buf_id);
  16615. }
  16616. SOKOL_API_IMPL void sg_dealloc_image(sg_image img_id) {
  16617. SOKOL_ASSERT(_sg.valid);
  16618. _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  16619. if (img) {
  16620. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  16621. _sg_dealloc_image(img);
  16622. } else {
  16623. _SG_ERROR(DEALLOC_IMAGE_INVALID_STATE);
  16624. }
  16625. }
  16626. _SG_TRACE_ARGS(dealloc_image, img_id);
  16627. }
  16628. SOKOL_API_IMPL void sg_dealloc_sampler(sg_sampler smp_id) {
  16629. SOKOL_ASSERT(_sg.valid);
  16630. _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  16631. if (smp) {
  16632. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  16633. _sg_dealloc_sampler(smp);
  16634. } else {
  16635. _SG_ERROR(DEALLOC_SAMPLER_INVALID_STATE);
  16636. }
  16637. }
  16638. _SG_TRACE_ARGS(dealloc_sampler, smp_id);
  16639. }
  16640. SOKOL_API_IMPL void sg_dealloc_shader(sg_shader shd_id) {
  16641. SOKOL_ASSERT(_sg.valid);
  16642. _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  16643. if (shd) {
  16644. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  16645. _sg_dealloc_shader(shd);
  16646. } else {
  16647. _SG_ERROR(DEALLOC_SHADER_INVALID_STATE);
  16648. }
  16649. }
  16650. _SG_TRACE_ARGS(dealloc_shader, shd_id);
  16651. }
  16652. SOKOL_API_IMPL void sg_dealloc_pipeline(sg_pipeline pip_id) {
  16653. SOKOL_ASSERT(_sg.valid);
  16654. _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  16655. if (pip) {
  16656. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  16657. _sg_dealloc_pipeline(pip);
  16658. } else {
  16659. _SG_ERROR(DEALLOC_PIPELINE_INVALID_STATE);
  16660. }
  16661. }
  16662. _SG_TRACE_ARGS(dealloc_pipeline, pip_id);
  16663. }
  16664. SOKOL_API_IMPL void sg_dealloc_attachments(sg_attachments atts_id) {
  16665. SOKOL_ASSERT(_sg.valid);
  16666. _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  16667. if (atts) {
  16668. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  16669. _sg_dealloc_attachments(atts);
  16670. } else {
  16671. _SG_ERROR(DEALLOC_ATTACHMENTS_INVALID_STATE);
  16672. }
  16673. }
  16674. _SG_TRACE_ARGS(dealloc_attachments, atts_id);
  16675. }
  16676. SOKOL_API_IMPL void sg_init_buffer(sg_buffer buf_id, const sg_buffer_desc* desc) {
  16677. SOKOL_ASSERT(_sg.valid);
  16678. sg_buffer_desc desc_def = _sg_buffer_desc_defaults(desc);
  16679. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  16680. if (buf) {
  16681. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  16682. _sg_init_buffer(buf, &desc_def);
  16683. SOKOL_ASSERT((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED));
  16684. } else {
  16685. _SG_ERROR(INIT_BUFFER_INVALID_STATE);
  16686. }
  16687. }
  16688. _SG_TRACE_ARGS(init_buffer, buf_id, &desc_def);
  16689. }
  16690. SOKOL_API_IMPL void sg_init_image(sg_image img_id, const sg_image_desc* desc) {
  16691. SOKOL_ASSERT(_sg.valid);
  16692. sg_image_desc desc_def = _sg_image_desc_defaults(desc);
  16693. _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  16694. if (img) {
  16695. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  16696. _sg_init_image(img, &desc_def);
  16697. SOKOL_ASSERT((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED));
  16698. } else {
  16699. _SG_ERROR(INIT_IMAGE_INVALID_STATE);
  16700. }
  16701. }
  16702. _SG_TRACE_ARGS(init_image, img_id, &desc_def);
  16703. }
  16704. SOKOL_API_IMPL void sg_init_sampler(sg_sampler smp_id, const sg_sampler_desc* desc) {
  16705. SOKOL_ASSERT(_sg.valid);
  16706. sg_sampler_desc desc_def = _sg_sampler_desc_defaults(desc);
  16707. _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  16708. if (smp) {
  16709. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  16710. _sg_init_sampler(smp, &desc_def);
  16711. SOKOL_ASSERT((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED));
  16712. } else {
  16713. _SG_ERROR(INIT_SAMPLER_INVALID_STATE);
  16714. }
  16715. }
  16716. _SG_TRACE_ARGS(init_sampler, smp_id, &desc_def);
  16717. }
  16718. SOKOL_API_IMPL void sg_init_shader(sg_shader shd_id, const sg_shader_desc* desc) {
  16719. SOKOL_ASSERT(_sg.valid);
  16720. sg_shader_desc desc_def = _sg_shader_desc_defaults(desc);
  16721. _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  16722. if (shd) {
  16723. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  16724. _sg_init_shader(shd, &desc_def);
  16725. SOKOL_ASSERT((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED));
  16726. } else {
  16727. _SG_ERROR(INIT_SHADER_INVALID_STATE);
  16728. }
  16729. }
  16730. _SG_TRACE_ARGS(init_shader, shd_id, &desc_def);
  16731. }
  16732. SOKOL_API_IMPL void sg_init_pipeline(sg_pipeline pip_id, const sg_pipeline_desc* desc) {
  16733. SOKOL_ASSERT(_sg.valid);
  16734. sg_pipeline_desc desc_def = _sg_pipeline_desc_defaults(desc);
  16735. _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  16736. if (pip) {
  16737. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  16738. _sg_init_pipeline(pip, &desc_def);
  16739. SOKOL_ASSERT((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED));
  16740. } else {
  16741. _SG_ERROR(INIT_PIPELINE_INVALID_STATE);
  16742. }
  16743. }
  16744. _SG_TRACE_ARGS(init_pipeline, pip_id, &desc_def);
  16745. }
  16746. SOKOL_API_IMPL void sg_init_attachments(sg_attachments atts_id, const sg_attachments_desc* desc) {
  16747. SOKOL_ASSERT(_sg.valid);
  16748. sg_attachments_desc desc_def = _sg_attachments_desc_defaults(desc);
  16749. _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  16750. if (atts) {
  16751. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  16752. _sg_init_attachments(atts, &desc_def);
  16753. SOKOL_ASSERT((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED));
  16754. } else {
  16755. _SG_ERROR(INIT_ATTACHMENTS_INVALID_STATE);
  16756. }
  16757. }
  16758. _SG_TRACE_ARGS(init_attachments, atts_id, &desc_def);
  16759. }
  16760. SOKOL_API_IMPL void sg_uninit_buffer(sg_buffer buf_id) {
  16761. SOKOL_ASSERT(_sg.valid);
  16762. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  16763. if (buf) {
  16764. if ((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED)) {
  16765. _sg_uninit_buffer(buf);
  16766. SOKOL_ASSERT(buf->slot.state == SG_RESOURCESTATE_ALLOC);
  16767. } else {
  16768. _SG_ERROR(UNINIT_BUFFER_INVALID_STATE);
  16769. }
  16770. }
  16771. _SG_TRACE_ARGS(uninit_buffer, buf_id);
  16772. }
  16773. SOKOL_API_IMPL void sg_uninit_image(sg_image img_id) {
  16774. SOKOL_ASSERT(_sg.valid);
  16775. _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  16776. if (img) {
  16777. if ((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED)) {
  16778. _sg_uninit_image(img);
  16779. SOKOL_ASSERT(img->slot.state == SG_RESOURCESTATE_ALLOC);
  16780. } else {
  16781. _SG_ERROR(UNINIT_IMAGE_INVALID_STATE);
  16782. }
  16783. }
  16784. _SG_TRACE_ARGS(uninit_image, img_id);
  16785. }
  16786. SOKOL_API_IMPL void sg_uninit_sampler(sg_sampler smp_id) {
  16787. SOKOL_ASSERT(_sg.valid);
  16788. _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  16789. if (smp) {
  16790. if ((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED)) {
  16791. _sg_uninit_sampler(smp);
  16792. SOKOL_ASSERT(smp->slot.state == SG_RESOURCESTATE_ALLOC);
  16793. } else {
  16794. _SG_ERROR(UNINIT_SAMPLER_INVALID_STATE);
  16795. }
  16796. }
  16797. _SG_TRACE_ARGS(uninit_sampler, smp_id);
  16798. }
  16799. SOKOL_API_IMPL void sg_uninit_shader(sg_shader shd_id) {
  16800. SOKOL_ASSERT(_sg.valid);
  16801. _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  16802. if (shd) {
  16803. if ((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED)) {
  16804. _sg_uninit_shader(shd);
  16805. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_ALLOC);
  16806. } else {
  16807. _SG_ERROR(UNINIT_SHADER_INVALID_STATE);
  16808. }
  16809. }
  16810. _SG_TRACE_ARGS(uninit_shader, shd_id);
  16811. }
  16812. SOKOL_API_IMPL void sg_uninit_pipeline(sg_pipeline pip_id) {
  16813. SOKOL_ASSERT(_sg.valid);
  16814. _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  16815. if (pip) {
  16816. if ((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED)) {
  16817. _sg_uninit_pipeline(pip);
  16818. SOKOL_ASSERT(pip->slot.state == SG_RESOURCESTATE_ALLOC);
  16819. } else {
  16820. _SG_ERROR(UNINIT_PIPELINE_INVALID_STATE);
  16821. }
  16822. }
  16823. _SG_TRACE_ARGS(uninit_pipeline, pip_id);
  16824. }
  16825. SOKOL_API_IMPL void sg_uninit_attachments(sg_attachments atts_id) {
  16826. SOKOL_ASSERT(_sg.valid);
  16827. _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  16828. if (atts) {
  16829. if ((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED)) {
  16830. _sg_uninit_attachments(atts);
  16831. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_ALLOC);
  16832. } else {
  16833. _SG_ERROR(UNINIT_ATTACHMENTS_INVALID_STATE);
  16834. }
  16835. }
  16836. _SG_TRACE_ARGS(uninit_attachments, atts_id);
  16837. }
  16838. SOKOL_API_IMPL void sg_fail_buffer(sg_buffer buf_id) {
  16839. SOKOL_ASSERT(_sg.valid);
  16840. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  16841. if (buf) {
  16842. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  16843. buf->slot.state = SG_RESOURCESTATE_FAILED;
  16844. } else {
  16845. _SG_ERROR(FAIL_BUFFER_INVALID_STATE);
  16846. }
  16847. }
  16848. _SG_TRACE_ARGS(fail_buffer, buf_id);
  16849. }
  16850. SOKOL_API_IMPL void sg_fail_image(sg_image img_id) {
  16851. SOKOL_ASSERT(_sg.valid);
  16852. _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  16853. if (img) {
  16854. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  16855. img->slot.state = SG_RESOURCESTATE_FAILED;
  16856. } else {
  16857. _SG_ERROR(FAIL_IMAGE_INVALID_STATE);
  16858. }
  16859. }
  16860. _SG_TRACE_ARGS(fail_image, img_id);
  16861. }
  16862. SOKOL_API_IMPL void sg_fail_sampler(sg_sampler smp_id) {
  16863. SOKOL_ASSERT(_sg.valid);
  16864. _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  16865. if (smp) {
  16866. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  16867. smp->slot.state = SG_RESOURCESTATE_FAILED;
  16868. } else {
  16869. _SG_ERROR(FAIL_SAMPLER_INVALID_STATE);
  16870. }
  16871. }
  16872. _SG_TRACE_ARGS(fail_sampler, smp_id);
  16873. }
  16874. SOKOL_API_IMPL void sg_fail_shader(sg_shader shd_id) {
  16875. SOKOL_ASSERT(_sg.valid);
  16876. _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  16877. if (shd) {
  16878. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  16879. shd->slot.state = SG_RESOURCESTATE_FAILED;
  16880. } else {
  16881. _SG_ERROR(FAIL_SHADER_INVALID_STATE);
  16882. }
  16883. }
  16884. _SG_TRACE_ARGS(fail_shader, shd_id);
  16885. }
  16886. SOKOL_API_IMPL void sg_fail_pipeline(sg_pipeline pip_id) {
  16887. SOKOL_ASSERT(_sg.valid);
  16888. _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  16889. if (pip) {
  16890. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  16891. pip->slot.state = SG_RESOURCESTATE_FAILED;
  16892. } else {
  16893. _SG_ERROR(FAIL_PIPELINE_INVALID_STATE);
  16894. }
  16895. }
  16896. _SG_TRACE_ARGS(fail_pipeline, pip_id);
  16897. }
  16898. SOKOL_API_IMPL void sg_fail_attachments(sg_attachments atts_id) {
  16899. SOKOL_ASSERT(_sg.valid);
  16900. _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  16901. if (atts) {
  16902. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  16903. atts->slot.state = SG_RESOURCESTATE_FAILED;
  16904. } else {
  16905. _SG_ERROR(FAIL_ATTACHMENTS_INVALID_STATE);
  16906. }
  16907. }
  16908. _SG_TRACE_ARGS(fail_attachments, atts_id);
  16909. }
  16910. SOKOL_API_IMPL sg_resource_state sg_query_buffer_state(sg_buffer buf_id) {
  16911. SOKOL_ASSERT(_sg.valid);
  16912. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  16913. sg_resource_state res = buf ? buf->slot.state : SG_RESOURCESTATE_INVALID;
  16914. return res;
  16915. }
  16916. SOKOL_API_IMPL sg_resource_state sg_query_image_state(sg_image img_id) {
  16917. SOKOL_ASSERT(_sg.valid);
  16918. _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  16919. sg_resource_state res = img ? img->slot.state : SG_RESOURCESTATE_INVALID;
  16920. return res;
  16921. }
  16922. SOKOL_API_IMPL sg_resource_state sg_query_sampler_state(sg_sampler smp_id) {
  16923. SOKOL_ASSERT(_sg.valid);
  16924. _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  16925. sg_resource_state res = smp ? smp->slot.state : SG_RESOURCESTATE_INVALID;
  16926. return res;
  16927. }
  16928. SOKOL_API_IMPL sg_resource_state sg_query_shader_state(sg_shader shd_id) {
  16929. SOKOL_ASSERT(_sg.valid);
  16930. _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  16931. sg_resource_state res = shd ? shd->slot.state : SG_RESOURCESTATE_INVALID;
  16932. return res;
  16933. }
  16934. SOKOL_API_IMPL sg_resource_state sg_query_pipeline_state(sg_pipeline pip_id) {
  16935. SOKOL_ASSERT(_sg.valid);
  16936. _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  16937. sg_resource_state res = pip ? pip->slot.state : SG_RESOURCESTATE_INVALID;
  16938. return res;
  16939. }
  16940. SOKOL_API_IMPL sg_resource_state sg_query_attachments_state(sg_attachments atts_id) {
  16941. SOKOL_ASSERT(_sg.valid);
  16942. _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  16943. sg_resource_state res = atts ? atts->slot.state : SG_RESOURCESTATE_INVALID;
  16944. return res;
  16945. }
  16946. SOKOL_API_IMPL sg_buffer sg_make_buffer(const sg_buffer_desc* desc) {
  16947. SOKOL_ASSERT(_sg.valid);
  16948. SOKOL_ASSERT(desc);
  16949. sg_buffer_desc desc_def = _sg_buffer_desc_defaults(desc);
  16950. sg_buffer buf_id = _sg_alloc_buffer();
  16951. if (buf_id.id != SG_INVALID_ID) {
  16952. _sg_buffer_t* buf = _sg_buffer_at(&_sg.pools, buf_id.id);
  16953. SOKOL_ASSERT(buf && (buf->slot.state == SG_RESOURCESTATE_ALLOC));
  16954. _sg_init_buffer(buf, &desc_def);
  16955. SOKOL_ASSERT((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED));
  16956. }
  16957. _SG_TRACE_ARGS(make_buffer, &desc_def, buf_id);
  16958. return buf_id;
  16959. }
  16960. SOKOL_API_IMPL sg_image sg_make_image(const sg_image_desc* desc) {
  16961. SOKOL_ASSERT(_sg.valid);
  16962. SOKOL_ASSERT(desc);
  16963. sg_image_desc desc_def = _sg_image_desc_defaults(desc);
  16964. sg_image img_id = _sg_alloc_image();
  16965. if (img_id.id != SG_INVALID_ID) {
  16966. _sg_image_t* img = _sg_image_at(&_sg.pools, img_id.id);
  16967. SOKOL_ASSERT(img && (img->slot.state == SG_RESOURCESTATE_ALLOC));
  16968. _sg_init_image(img, &desc_def);
  16969. SOKOL_ASSERT((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED));
  16970. }
  16971. _SG_TRACE_ARGS(make_image, &desc_def, img_id);
  16972. return img_id;
  16973. }
  16974. SOKOL_API_IMPL sg_sampler sg_make_sampler(const sg_sampler_desc* desc) {
  16975. SOKOL_ASSERT(_sg.valid);
  16976. SOKOL_ASSERT(desc);
  16977. sg_sampler_desc desc_def = _sg_sampler_desc_defaults(desc);
  16978. sg_sampler smp_id = _sg_alloc_sampler();
  16979. if (smp_id.id != SG_INVALID_ID) {
  16980. _sg_sampler_t* smp = _sg_sampler_at(&_sg.pools, smp_id.id);
  16981. SOKOL_ASSERT(smp && (smp->slot.state == SG_RESOURCESTATE_ALLOC));
  16982. _sg_init_sampler(smp, &desc_def);
  16983. SOKOL_ASSERT((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED));
  16984. }
  16985. _SG_TRACE_ARGS(make_sampler, &desc_def, smp_id);
  16986. return smp_id;
  16987. }
  16988. SOKOL_API_IMPL sg_shader sg_make_shader(const sg_shader_desc* desc) {
  16989. SOKOL_ASSERT(_sg.valid);
  16990. SOKOL_ASSERT(desc);
  16991. sg_shader_desc desc_def = _sg_shader_desc_defaults(desc);
  16992. sg_shader shd_id = _sg_alloc_shader();
  16993. if (shd_id.id != SG_INVALID_ID) {
  16994. _sg_shader_t* shd = _sg_shader_at(&_sg.pools, shd_id.id);
  16995. SOKOL_ASSERT(shd && (shd->slot.state == SG_RESOURCESTATE_ALLOC));
  16996. _sg_init_shader(shd, &desc_def);
  16997. SOKOL_ASSERT((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED));
  16998. }
  16999. _SG_TRACE_ARGS(make_shader, &desc_def, shd_id);
  17000. return shd_id;
  17001. }
  17002. SOKOL_API_IMPL sg_pipeline sg_make_pipeline(const sg_pipeline_desc* desc) {
  17003. SOKOL_ASSERT(_sg.valid);
  17004. SOKOL_ASSERT(desc);
  17005. sg_pipeline_desc desc_def = _sg_pipeline_desc_defaults(desc);
  17006. sg_pipeline pip_id = _sg_alloc_pipeline();
  17007. if (pip_id.id != SG_INVALID_ID) {
  17008. _sg_pipeline_t* pip = _sg_pipeline_at(&_sg.pools, pip_id.id);
  17009. SOKOL_ASSERT(pip && (pip->slot.state == SG_RESOURCESTATE_ALLOC));
  17010. _sg_init_pipeline(pip, &desc_def);
  17011. SOKOL_ASSERT((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED));
  17012. }
  17013. _SG_TRACE_ARGS(make_pipeline, &desc_def, pip_id);
  17014. return pip_id;
  17015. }
  17016. SOKOL_API_IMPL sg_attachments sg_make_attachments(const sg_attachments_desc* desc) {
  17017. SOKOL_ASSERT(_sg.valid);
  17018. SOKOL_ASSERT(desc);
  17019. sg_attachments_desc desc_def = _sg_attachments_desc_defaults(desc);
  17020. sg_attachments atts_id = _sg_alloc_attachments();
  17021. if (atts_id.id != SG_INVALID_ID) {
  17022. _sg_attachments_t* atts = _sg_attachments_at(&_sg.pools, atts_id.id);
  17023. SOKOL_ASSERT(atts && (atts->slot.state == SG_RESOURCESTATE_ALLOC));
  17024. _sg_init_attachments(atts, &desc_def);
  17025. SOKOL_ASSERT((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED));
  17026. }
  17027. _SG_TRACE_ARGS(make_attachments, &desc_def, atts_id);
  17028. return atts_id;
  17029. }
  17030. SOKOL_API_IMPL void sg_destroy_buffer(sg_buffer buf_id) {
  17031. SOKOL_ASSERT(_sg.valid);
  17032. _SG_TRACE_ARGS(destroy_buffer, buf_id);
  17033. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17034. if (buf) {
  17035. if ((buf->slot.state == SG_RESOURCESTATE_VALID) || (buf->slot.state == SG_RESOURCESTATE_FAILED)) {
  17036. _sg_uninit_buffer(buf);
  17037. SOKOL_ASSERT(buf->slot.state == SG_RESOURCESTATE_ALLOC);
  17038. }
  17039. if (buf->slot.state == SG_RESOURCESTATE_ALLOC) {
  17040. _sg_dealloc_buffer(buf);
  17041. SOKOL_ASSERT(buf->slot.state == SG_RESOURCESTATE_INITIAL);
  17042. }
  17043. }
  17044. }
  17045. SOKOL_API_IMPL void sg_destroy_image(sg_image img_id) {
  17046. SOKOL_ASSERT(_sg.valid);
  17047. _SG_TRACE_ARGS(destroy_image, img_id);
  17048. _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17049. if (img) {
  17050. if ((img->slot.state == SG_RESOURCESTATE_VALID) || (img->slot.state == SG_RESOURCESTATE_FAILED)) {
  17051. _sg_uninit_image(img);
  17052. SOKOL_ASSERT(img->slot.state == SG_RESOURCESTATE_ALLOC);
  17053. }
  17054. if (img->slot.state == SG_RESOURCESTATE_ALLOC) {
  17055. _sg_dealloc_image(img);
  17056. SOKOL_ASSERT(img->slot.state == SG_RESOURCESTATE_INITIAL);
  17057. }
  17058. }
  17059. }
  17060. SOKOL_API_IMPL void sg_destroy_sampler(sg_sampler smp_id) {
  17061. SOKOL_ASSERT(_sg.valid);
  17062. _SG_TRACE_ARGS(destroy_sampler, smp_id);
  17063. _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  17064. if (smp) {
  17065. if ((smp->slot.state == SG_RESOURCESTATE_VALID) || (smp->slot.state == SG_RESOURCESTATE_FAILED)) {
  17066. _sg_uninit_sampler(smp);
  17067. SOKOL_ASSERT(smp->slot.state == SG_RESOURCESTATE_ALLOC);
  17068. }
  17069. if (smp->slot.state == SG_RESOURCESTATE_ALLOC) {
  17070. _sg_dealloc_sampler(smp);
  17071. SOKOL_ASSERT(smp->slot.state == SG_RESOURCESTATE_INITIAL);
  17072. }
  17073. }
  17074. }
  17075. SOKOL_API_IMPL void sg_destroy_shader(sg_shader shd_id) {
  17076. SOKOL_ASSERT(_sg.valid);
  17077. _SG_TRACE_ARGS(destroy_shader, shd_id);
  17078. _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  17079. if (shd) {
  17080. if ((shd->slot.state == SG_RESOURCESTATE_VALID) || (shd->slot.state == SG_RESOURCESTATE_FAILED)) {
  17081. _sg_uninit_shader(shd);
  17082. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_ALLOC);
  17083. }
  17084. if (shd->slot.state == SG_RESOURCESTATE_ALLOC) {
  17085. _sg_dealloc_shader(shd);
  17086. SOKOL_ASSERT(shd->slot.state == SG_RESOURCESTATE_INITIAL);
  17087. }
  17088. }
  17089. }
  17090. SOKOL_API_IMPL void sg_destroy_pipeline(sg_pipeline pip_id) {
  17091. SOKOL_ASSERT(_sg.valid);
  17092. _SG_TRACE_ARGS(destroy_pipeline, pip_id);
  17093. _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  17094. if (pip) {
  17095. if ((pip->slot.state == SG_RESOURCESTATE_VALID) || (pip->slot.state == SG_RESOURCESTATE_FAILED)) {
  17096. _sg_uninit_pipeline(pip);
  17097. SOKOL_ASSERT(pip->slot.state == SG_RESOURCESTATE_ALLOC);
  17098. }
  17099. if (pip->slot.state == SG_RESOURCESTATE_ALLOC) {
  17100. _sg_dealloc_pipeline(pip);
  17101. SOKOL_ASSERT(pip->slot.state == SG_RESOURCESTATE_INITIAL);
  17102. }
  17103. }
  17104. }
  17105. SOKOL_API_IMPL void sg_destroy_attachments(sg_attachments atts_id) {
  17106. SOKOL_ASSERT(_sg.valid);
  17107. _SG_TRACE_ARGS(destroy_attachments, atts_id);
  17108. _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  17109. if (atts) {
  17110. if ((atts->slot.state == SG_RESOURCESTATE_VALID) || (atts->slot.state == SG_RESOURCESTATE_FAILED)) {
  17111. _sg_uninit_attachments(atts);
  17112. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_ALLOC);
  17113. }
  17114. if (atts->slot.state == SG_RESOURCESTATE_ALLOC) {
  17115. _sg_dealloc_attachments(atts);
  17116. SOKOL_ASSERT(atts->slot.state == SG_RESOURCESTATE_INITIAL);
  17117. }
  17118. }
  17119. }
  17120. SOKOL_API_IMPL void sg_begin_pass(const sg_pass* pass) {
  17121. SOKOL_ASSERT(_sg.valid);
  17122. SOKOL_ASSERT(!_sg.cur_pass.valid);
  17123. SOKOL_ASSERT(!_sg.cur_pass.in_pass);
  17124. SOKOL_ASSERT(pass);
  17125. SOKOL_ASSERT((pass->_start_canary == 0) && (pass->_end_canary == 0));
  17126. const sg_pass pass_def = _sg_pass_defaults(pass);
  17127. if (!_sg_validate_begin_pass(&pass_def)) {
  17128. return;
  17129. }
  17130. if (pass_def.attachments.id != SG_INVALID_ID) {
  17131. // an offscreen pass
  17132. SOKOL_ASSERT(_sg.cur_pass.atts == 0);
  17133. _sg.cur_pass.atts = _sg_lookup_attachments(&_sg.pools, pass_def.attachments.id);
  17134. if (0 == _sg.cur_pass.atts) {
  17135. _SG_ERROR(BEGINPASS_ATTACHMENT_INVALID);
  17136. return;
  17137. }
  17138. _sg.cur_pass.atts_id = pass_def.attachments;
  17139. _sg.cur_pass.width = _sg.cur_pass.atts->cmn.width;
  17140. _sg.cur_pass.height = _sg.cur_pass.atts->cmn.height;
  17141. } else {
  17142. // a swapchain pass
  17143. SOKOL_ASSERT(pass_def.swapchain.width > 0);
  17144. SOKOL_ASSERT(pass_def.swapchain.height > 0);
  17145. SOKOL_ASSERT(pass_def.swapchain.color_format > SG_PIXELFORMAT_NONE);
  17146. SOKOL_ASSERT(pass_def.swapchain.sample_count > 0);
  17147. _sg.cur_pass.width = pass_def.swapchain.width;
  17148. _sg.cur_pass.height = pass_def.swapchain.height;
  17149. _sg.cur_pass.swapchain.color_fmt = pass_def.swapchain.color_format;
  17150. _sg.cur_pass.swapchain.depth_fmt = pass_def.swapchain.depth_format;
  17151. _sg.cur_pass.swapchain.sample_count = pass_def.swapchain.sample_count;
  17152. }
  17153. _sg.cur_pass.valid = true; // may be overruled by backend begin-pass functions
  17154. _sg.cur_pass.in_pass = true;
  17155. _sg_begin_pass(&pass_def);
  17156. _SG_TRACE_ARGS(begin_pass, &pass_def);
  17157. }
  17158. SOKOL_API_IMPL void sg_apply_viewport(int x, int y, int width, int height, bool origin_top_left) {
  17159. SOKOL_ASSERT(_sg.valid);
  17160. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  17161. _sg_stats_add(num_apply_viewport, 1);
  17162. if (!_sg.cur_pass.valid) {
  17163. return;
  17164. }
  17165. _sg_apply_viewport(x, y, width, height, origin_top_left);
  17166. _SG_TRACE_ARGS(apply_viewport, x, y, width, height, origin_top_left);
  17167. }
  17168. SOKOL_API_IMPL void sg_apply_viewportf(float x, float y, float width, float height, bool origin_top_left) {
  17169. sg_apply_viewport((int)x, (int)y, (int)width, (int)height, origin_top_left);
  17170. }
  17171. SOKOL_API_IMPL void sg_apply_scissor_rect(int x, int y, int width, int height, bool origin_top_left) {
  17172. SOKOL_ASSERT(_sg.valid);
  17173. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  17174. _sg_stats_add(num_apply_scissor_rect, 1);
  17175. if (!_sg.cur_pass.valid) {
  17176. return;
  17177. }
  17178. _sg_apply_scissor_rect(x, y, width, height, origin_top_left);
  17179. _SG_TRACE_ARGS(apply_scissor_rect, x, y, width, height, origin_top_left);
  17180. }
  17181. SOKOL_API_IMPL void sg_apply_scissor_rectf(float x, float y, float width, float height, bool origin_top_left) {
  17182. sg_apply_scissor_rect((int)x, (int)y, (int)width, (int)height, origin_top_left);
  17183. }
  17184. SOKOL_API_IMPL void sg_apply_pipeline(sg_pipeline pip_id) {
  17185. SOKOL_ASSERT(_sg.valid);
  17186. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  17187. _sg_stats_add(num_apply_pipeline, 1);
  17188. if (!_sg_validate_apply_pipeline(pip_id)) {
  17189. _sg.next_draw_valid = false;
  17190. return;
  17191. }
  17192. if (!_sg.cur_pass.valid) {
  17193. return;
  17194. }
  17195. _sg.cur_pipeline = pip_id;
  17196. _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  17197. SOKOL_ASSERT(pip);
  17198. _sg.next_draw_valid = (SG_RESOURCESTATE_VALID == pip->slot.state);
  17199. if (!_sg.next_draw_valid) {
  17200. return;
  17201. }
  17202. SOKOL_ASSERT(pip->shader && (pip->shader->slot.id == pip->cmn.shader_id.id));
  17203. _sg_apply_pipeline(pip);
  17204. // set the expected bindings and uniform block flags
  17205. _sg.required_bindings_and_uniforms = pip->cmn.required_bindings_and_uniforms | pip->shader->cmn.required_bindings_and_uniforms;
  17206. _sg.applied_bindings_and_uniforms = 0;
  17207. _SG_TRACE_ARGS(apply_pipeline, pip_id);
  17208. }
  17209. SOKOL_API_IMPL void sg_apply_bindings(const sg_bindings* bindings) {
  17210. SOKOL_ASSERT(_sg.valid);
  17211. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  17212. SOKOL_ASSERT(bindings);
  17213. SOKOL_ASSERT((bindings->_start_canary == 0) && (bindings->_end_canary==0));
  17214. _sg_stats_add(num_apply_bindings, 1);
  17215. _sg.applied_bindings_and_uniforms |= (1 << SG_MAX_UNIFORMBLOCK_BINDSLOTS);
  17216. if (!_sg_validate_apply_bindings(bindings)) {
  17217. _sg.next_draw_valid = false;
  17218. return;
  17219. }
  17220. if (!_sg.cur_pass.valid) {
  17221. return;
  17222. }
  17223. if (!_sg.next_draw_valid) {
  17224. return;
  17225. }
  17226. _sg_bindings_t bnd;
  17227. _sg_clear(&bnd, sizeof(bnd));
  17228. bnd.pip = _sg_lookup_pipeline(&_sg.pools, _sg.cur_pipeline.id);
  17229. if (0 == bnd.pip) {
  17230. _sg.next_draw_valid = false;
  17231. }
  17232. SOKOL_ASSERT(bnd.pip->shader && (bnd.pip->cmn.shader_id.id == bnd.pip->shader->slot.id));
  17233. const _sg_shader_t* shd = bnd.pip->shader;
  17234. for (size_t i = 0; i < SG_MAX_VERTEXBUFFER_BINDSLOTS; i++) {
  17235. if (bnd.pip->cmn.vertex_buffer_layout_active[i]) {
  17236. SOKOL_ASSERT(bindings->vertex_buffers[i].id != SG_INVALID_ID);
  17237. bnd.vbs[i] = _sg_lookup_buffer(&_sg.pools, bindings->vertex_buffers[i].id);
  17238. bnd.vb_offsets[i] = bindings->vertex_buffer_offsets[i];
  17239. if (bnd.vbs[i]) {
  17240. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.vbs[i]->slot.state);
  17241. _sg.next_draw_valid &= !bnd.vbs[i]->cmn.append_overflow;
  17242. } else {
  17243. _sg.next_draw_valid = false;
  17244. }
  17245. }
  17246. }
  17247. if (bindings->index_buffer.id) {
  17248. bnd.ib = _sg_lookup_buffer(&_sg.pools, bindings->index_buffer.id);
  17249. bnd.ib_offset = bindings->index_buffer_offset;
  17250. if (bnd.ib) {
  17251. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.ib->slot.state);
  17252. _sg.next_draw_valid &= !bnd.ib->cmn.append_overflow;
  17253. } else {
  17254. _sg.next_draw_valid = false;
  17255. }
  17256. }
  17257. for (int i = 0; i < SG_MAX_IMAGE_BINDSLOTS; i++) {
  17258. if (shd->cmn.images[i].stage != SG_SHADERSTAGE_NONE) {
  17259. SOKOL_ASSERT(bindings->images[i].id != SG_INVALID_ID);
  17260. bnd.imgs[i] = _sg_lookup_image(&_sg.pools, bindings->images[i].id);
  17261. if (bnd.imgs[i]) {
  17262. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.imgs[i]->slot.state);
  17263. } else {
  17264. _sg.next_draw_valid = false;
  17265. }
  17266. }
  17267. }
  17268. for (size_t i = 0; i < SG_MAX_SAMPLER_BINDSLOTS; i++) {
  17269. if (shd->cmn.samplers[i].stage != SG_SHADERSTAGE_NONE) {
  17270. SOKOL_ASSERT(bindings->samplers[i].id != SG_INVALID_ID);
  17271. bnd.smps[i] = _sg_lookup_sampler(&_sg.pools, bindings->samplers[i].id);
  17272. if (bnd.smps[i]) {
  17273. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.smps[i]->slot.state);
  17274. } else {
  17275. _sg.next_draw_valid = false;
  17276. }
  17277. }
  17278. }
  17279. for (size_t i = 0; i < SG_MAX_STORAGEBUFFER_BINDSLOTS; i++) {
  17280. if (shd->cmn.storage_buffers[i].stage != SG_SHADERSTAGE_NONE) {
  17281. SOKOL_ASSERT(bindings->storage_buffers[i].id != SG_INVALID_ID);
  17282. bnd.sbufs[i] = _sg_lookup_buffer(&_sg.pools, bindings->storage_buffers[i].id);
  17283. if (bnd.sbufs[i]) {
  17284. _sg.next_draw_valid &= (SG_RESOURCESTATE_VALID == bnd.sbufs[i]->slot.state);
  17285. } else {
  17286. _sg.next_draw_valid = false;
  17287. }
  17288. }
  17289. }
  17290. if (_sg.next_draw_valid) {
  17291. _sg.next_draw_valid &= _sg_apply_bindings(&bnd);
  17292. _SG_TRACE_ARGS(apply_bindings, bindings);
  17293. }
  17294. }
  17295. SOKOL_API_IMPL void sg_apply_uniforms(int ub_slot, const sg_range* data) {
  17296. SOKOL_ASSERT(_sg.valid);
  17297. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  17298. SOKOL_ASSERT((ub_slot >= 0) && (ub_slot < SG_MAX_UNIFORMBLOCK_BINDSLOTS));
  17299. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  17300. _sg_stats_add(num_apply_uniforms, 1);
  17301. _sg_stats_add(size_apply_uniforms, (uint32_t)data->size);
  17302. _sg.applied_bindings_and_uniforms |= 1 << ub_slot;
  17303. if (!_sg_validate_apply_uniforms(ub_slot, data)) {
  17304. _sg.next_draw_valid = false;
  17305. return;
  17306. }
  17307. if (!_sg.cur_pass.valid) {
  17308. return;
  17309. }
  17310. if (!_sg.next_draw_valid) {
  17311. return;
  17312. }
  17313. _sg_apply_uniforms(ub_slot, data);
  17314. _SG_TRACE_ARGS(apply_uniforms, ub_slot, data);
  17315. }
  17316. SOKOL_API_IMPL void sg_draw(int base_element, int num_elements, int num_instances) {
  17317. SOKOL_ASSERT(_sg.valid);
  17318. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  17319. SOKOL_ASSERT(base_element >= 0);
  17320. SOKOL_ASSERT(num_elements >= 0);
  17321. SOKOL_ASSERT(num_instances >= 0);
  17322. _sg_stats_add(num_draw, 1);
  17323. if (!_sg.cur_pass.valid) {
  17324. return;
  17325. }
  17326. if (!_sg.next_draw_valid) {
  17327. return;
  17328. }
  17329. #if defined(SOKOL_DEBUG)
  17330. if (_sg.required_bindings_and_uniforms != _sg.applied_bindings_and_uniforms) {
  17331. _SG_ERROR(DRAW_REQUIRED_BINDINGS_OR_UNIFORMS_MISSING);
  17332. return;
  17333. }
  17334. #endif
  17335. /* attempting to draw with zero elements or instances is not technically an
  17336. error, but might be handled as an error in the backend API (e.g. on Metal)
  17337. */
  17338. if ((0 == num_elements) || (0 == num_instances)) {
  17339. return;
  17340. }
  17341. _sg_draw(base_element, num_elements, num_instances);
  17342. _SG_TRACE_ARGS(draw, base_element, num_elements, num_instances);
  17343. }
  17344. SOKOL_API_IMPL void sg_end_pass(void) {
  17345. SOKOL_ASSERT(_sg.valid);
  17346. SOKOL_ASSERT(_sg.cur_pass.in_pass);
  17347. _sg_stats_add(num_passes, 1);
  17348. // NOTE: don't exit early if !_sg.cur_pass.valid
  17349. _sg_end_pass();
  17350. _sg.cur_pipeline.id = SG_INVALID_ID;
  17351. _sg_clear(&_sg.cur_pass, sizeof(_sg.cur_pass));
  17352. _SG_TRACE_NOARGS(end_pass);
  17353. }
  17354. SOKOL_API_IMPL void sg_commit(void) {
  17355. SOKOL_ASSERT(_sg.valid);
  17356. SOKOL_ASSERT(!_sg.cur_pass.valid);
  17357. SOKOL_ASSERT(!_sg.cur_pass.in_pass);
  17358. _sg_commit();
  17359. _sg.stats.frame_index = _sg.frame_index;
  17360. _sg.prev_stats = _sg.stats;
  17361. _sg_clear(&_sg.stats, sizeof(_sg.stats));
  17362. _sg_notify_commit_listeners();
  17363. _SG_TRACE_NOARGS(commit);
  17364. _sg.frame_index++;
  17365. }
  17366. SOKOL_API_IMPL void sg_reset_state_cache(void) {
  17367. SOKOL_ASSERT(_sg.valid);
  17368. _sg_reset_state_cache();
  17369. _SG_TRACE_NOARGS(reset_state_cache);
  17370. }
  17371. SOKOL_API_IMPL void sg_update_buffer(sg_buffer buf_id, const sg_range* data) {
  17372. SOKOL_ASSERT(_sg.valid);
  17373. SOKOL_ASSERT(data && data->ptr && (data->size > 0));
  17374. _sg_stats_add(num_update_buffer, 1);
  17375. _sg_stats_add(size_update_buffer, (uint32_t)data->size);
  17376. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17377. if ((data->size > 0) && buf && (buf->slot.state == SG_RESOURCESTATE_VALID)) {
  17378. if (_sg_validate_update_buffer(buf, data)) {
  17379. SOKOL_ASSERT(data->size <= (size_t)buf->cmn.size);
  17380. // only one update allowed per buffer and frame
  17381. SOKOL_ASSERT(buf->cmn.update_frame_index != _sg.frame_index);
  17382. // update and append on same buffer in same frame not allowed
  17383. SOKOL_ASSERT(buf->cmn.append_frame_index != _sg.frame_index);
  17384. _sg_update_buffer(buf, data);
  17385. buf->cmn.update_frame_index = _sg.frame_index;
  17386. }
  17387. }
  17388. _SG_TRACE_ARGS(update_buffer, buf_id, data);
  17389. }
  17390. SOKOL_API_IMPL int sg_append_buffer(sg_buffer buf_id, const sg_range* data) {
  17391. SOKOL_ASSERT(_sg.valid);
  17392. SOKOL_ASSERT(data && data->ptr);
  17393. _sg_stats_add(num_append_buffer, 1);
  17394. _sg_stats_add(size_append_buffer, (uint32_t)data->size);
  17395. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17396. int result;
  17397. if (buf) {
  17398. // rewind append cursor in a new frame
  17399. if (buf->cmn.append_frame_index != _sg.frame_index) {
  17400. buf->cmn.append_pos = 0;
  17401. buf->cmn.append_overflow = false;
  17402. }
  17403. if (((size_t)buf->cmn.append_pos + data->size) > (size_t)buf->cmn.size) {
  17404. buf->cmn.append_overflow = true;
  17405. }
  17406. const int start_pos = buf->cmn.append_pos;
  17407. // NOTE: the multiple-of-4 requirement for the buffer offset is coming
  17408. // from WebGPU, but we want identical behaviour between backends
  17409. SOKOL_ASSERT(_sg_multiple_u64((uint64_t)start_pos, 4));
  17410. if (buf->slot.state == SG_RESOURCESTATE_VALID) {
  17411. if (_sg_validate_append_buffer(buf, data)) {
  17412. if (!buf->cmn.append_overflow && (data->size > 0)) {
  17413. // update and append on same buffer in same frame not allowed
  17414. SOKOL_ASSERT(buf->cmn.update_frame_index != _sg.frame_index);
  17415. _sg_append_buffer(buf, data, buf->cmn.append_frame_index != _sg.frame_index);
  17416. buf->cmn.append_pos += (int) _sg_roundup_u64(data->size, 4);
  17417. buf->cmn.append_frame_index = _sg.frame_index;
  17418. }
  17419. }
  17420. }
  17421. result = start_pos;
  17422. } else {
  17423. // FIXME: should we return -1 here?
  17424. result = 0;
  17425. }
  17426. _SG_TRACE_ARGS(append_buffer, buf_id, data, result);
  17427. return result;
  17428. }
  17429. SOKOL_API_IMPL bool sg_query_buffer_overflow(sg_buffer buf_id) {
  17430. SOKOL_ASSERT(_sg.valid);
  17431. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17432. bool result = buf ? buf->cmn.append_overflow : false;
  17433. return result;
  17434. }
  17435. SOKOL_API_IMPL bool sg_query_buffer_will_overflow(sg_buffer buf_id, size_t size) {
  17436. SOKOL_ASSERT(_sg.valid);
  17437. _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17438. bool result = false;
  17439. if (buf) {
  17440. int append_pos = buf->cmn.append_pos;
  17441. // rewind append cursor in a new frame
  17442. if (buf->cmn.append_frame_index != _sg.frame_index) {
  17443. append_pos = 0;
  17444. }
  17445. if ((append_pos + _sg_roundup((int)size, 4)) > buf->cmn.size) {
  17446. result = true;
  17447. }
  17448. }
  17449. return result;
  17450. }
  17451. SOKOL_API_IMPL void sg_update_image(sg_image img_id, const sg_image_data* data) {
  17452. SOKOL_ASSERT(_sg.valid);
  17453. _sg_stats_add(num_update_image, 1);
  17454. for (int face_index = 0; face_index < SG_CUBEFACE_NUM; face_index++) {
  17455. for (int mip_index = 0; mip_index < SG_MAX_MIPMAPS; mip_index++) {
  17456. if (data->subimage[face_index][mip_index].size == 0) {
  17457. break;
  17458. }
  17459. _sg_stats_add(size_update_image, (uint32_t)data->subimage[face_index][mip_index].size);
  17460. }
  17461. }
  17462. _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17463. if (img && img->slot.state == SG_RESOURCESTATE_VALID) {
  17464. if (_sg_validate_update_image(img, data)) {
  17465. SOKOL_ASSERT(img->cmn.upd_frame_index != _sg.frame_index);
  17466. _sg_update_image(img, data);
  17467. img->cmn.upd_frame_index = _sg.frame_index;
  17468. }
  17469. }
  17470. _SG_TRACE_ARGS(update_image, img_id, data);
  17471. }
  17472. SOKOL_API_IMPL void sg_push_debug_group(const char* name) {
  17473. SOKOL_ASSERT(_sg.valid);
  17474. SOKOL_ASSERT(name);
  17475. _sg_push_debug_group(name);
  17476. _SG_TRACE_ARGS(push_debug_group, name);
  17477. }
  17478. SOKOL_API_IMPL void sg_pop_debug_group(void) {
  17479. SOKOL_ASSERT(_sg.valid);
  17480. _sg_pop_debug_group();
  17481. _SG_TRACE_NOARGS(pop_debug_group);
  17482. }
  17483. SOKOL_API_IMPL bool sg_add_commit_listener(sg_commit_listener listener) {
  17484. SOKOL_ASSERT(_sg.valid);
  17485. return _sg_add_commit_listener(&listener);
  17486. }
  17487. SOKOL_API_IMPL bool sg_remove_commit_listener(sg_commit_listener listener) {
  17488. SOKOL_ASSERT(_sg.valid);
  17489. return _sg_remove_commit_listener(&listener);
  17490. }
  17491. SOKOL_API_IMPL void sg_enable_frame_stats(void) {
  17492. SOKOL_ASSERT(_sg.valid);
  17493. _sg.stats_enabled = true;
  17494. }
  17495. SOKOL_API_IMPL void sg_disable_frame_stats(void) {
  17496. SOKOL_ASSERT(_sg.valid);
  17497. _sg.stats_enabled = false;
  17498. }
  17499. SOKOL_API_IMPL bool sg_frame_stats_enabled(void) {
  17500. return _sg.stats_enabled;
  17501. }
  17502. SOKOL_API_IMPL sg_buffer_info sg_query_buffer_info(sg_buffer buf_id) {
  17503. SOKOL_ASSERT(_sg.valid);
  17504. sg_buffer_info info;
  17505. _sg_clear(&info, sizeof(info));
  17506. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17507. if (buf) {
  17508. info.slot.state = buf->slot.state;
  17509. info.slot.res_id = buf->slot.id;
  17510. info.update_frame_index = buf->cmn.update_frame_index;
  17511. info.append_frame_index = buf->cmn.append_frame_index;
  17512. info.append_pos = buf->cmn.append_pos;
  17513. info.append_overflow = buf->cmn.append_overflow;
  17514. #if defined(SOKOL_D3D11)
  17515. info.num_slots = 1;
  17516. info.active_slot = 0;
  17517. #else
  17518. info.num_slots = buf->cmn.num_slots;
  17519. info.active_slot = buf->cmn.active_slot;
  17520. #endif
  17521. }
  17522. return info;
  17523. }
  17524. SOKOL_API_IMPL sg_image_info sg_query_image_info(sg_image img_id) {
  17525. SOKOL_ASSERT(_sg.valid);
  17526. sg_image_info info;
  17527. _sg_clear(&info, sizeof(info));
  17528. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17529. if (img) {
  17530. info.slot.state = img->slot.state;
  17531. info.slot.res_id = img->slot.id;
  17532. info.upd_frame_index = img->cmn.upd_frame_index;
  17533. #if defined(SOKOL_D3D11)
  17534. info.num_slots = 1;
  17535. info.active_slot = 0;
  17536. #else
  17537. info.num_slots = img->cmn.num_slots;
  17538. info.active_slot = img->cmn.active_slot;
  17539. #endif
  17540. }
  17541. return info;
  17542. }
  17543. SOKOL_API_IMPL sg_sampler_info sg_query_sampler_info(sg_sampler smp_id) {
  17544. SOKOL_ASSERT(_sg.valid);
  17545. sg_sampler_info info;
  17546. _sg_clear(&info, sizeof(info));
  17547. const _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  17548. if (smp) {
  17549. info.slot.state = smp->slot.state;
  17550. info.slot.res_id = smp->slot.id;
  17551. }
  17552. return info;
  17553. }
  17554. SOKOL_API_IMPL sg_shader_info sg_query_shader_info(sg_shader shd_id) {
  17555. SOKOL_ASSERT(_sg.valid);
  17556. sg_shader_info info;
  17557. _sg_clear(&info, sizeof(info));
  17558. const _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  17559. if (shd) {
  17560. info.slot.state = shd->slot.state;
  17561. info.slot.res_id = shd->slot.id;
  17562. }
  17563. return info;
  17564. }
  17565. SOKOL_API_IMPL sg_pipeline_info sg_query_pipeline_info(sg_pipeline pip_id) {
  17566. SOKOL_ASSERT(_sg.valid);
  17567. sg_pipeline_info info;
  17568. _sg_clear(&info, sizeof(info));
  17569. const _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  17570. if (pip) {
  17571. info.slot.state = pip->slot.state;
  17572. info.slot.res_id = pip->slot.id;
  17573. }
  17574. return info;
  17575. }
  17576. SOKOL_API_IMPL sg_attachments_info sg_query_attachments_info(sg_attachments atts_id) {
  17577. SOKOL_ASSERT(_sg.valid);
  17578. sg_attachments_info info;
  17579. _sg_clear(&info, sizeof(info));
  17580. const _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  17581. if (atts) {
  17582. info.slot.state = atts->slot.state;
  17583. info.slot.res_id = atts->slot.id;
  17584. }
  17585. return info;
  17586. }
  17587. SOKOL_API_IMPL sg_buffer_desc sg_query_buffer_desc(sg_buffer buf_id) {
  17588. SOKOL_ASSERT(_sg.valid);
  17589. sg_buffer_desc desc;
  17590. _sg_clear(&desc, sizeof(desc));
  17591. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17592. if (buf) {
  17593. desc.size = (size_t)buf->cmn.size;
  17594. desc.type = buf->cmn.type;
  17595. desc.usage = buf->cmn.usage;
  17596. }
  17597. return desc;
  17598. }
  17599. SOKOL_API_IMPL size_t sg_query_buffer_size(sg_buffer buf_id) {
  17600. SOKOL_ASSERT(_sg.valid);
  17601. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17602. if (buf) {
  17603. return (size_t)buf->cmn.size;
  17604. }
  17605. return 0;
  17606. }
  17607. SOKOL_API_IMPL sg_buffer_type sg_query_buffer_type(sg_buffer buf_id) {
  17608. SOKOL_ASSERT(_sg.valid);
  17609. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17610. if (buf) {
  17611. return buf->cmn.type;
  17612. }
  17613. return _SG_BUFFERTYPE_DEFAULT;
  17614. }
  17615. SOKOL_API_IMPL sg_usage sg_query_buffer_usage(sg_buffer buf_id) {
  17616. SOKOL_ASSERT(_sg.valid);
  17617. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17618. if (buf) {
  17619. return buf->cmn.usage;
  17620. }
  17621. return _SG_USAGE_DEFAULT;
  17622. }
  17623. SOKOL_API_IMPL sg_image_desc sg_query_image_desc(sg_image img_id) {
  17624. SOKOL_ASSERT(_sg.valid);
  17625. sg_image_desc desc;
  17626. _sg_clear(&desc, sizeof(desc));
  17627. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17628. if (img) {
  17629. desc.type = img->cmn.type;
  17630. desc.render_target = img->cmn.render_target;
  17631. desc.width = img->cmn.width;
  17632. desc.height = img->cmn.height;
  17633. desc.num_slices = img->cmn.num_slices;
  17634. desc.num_mipmaps = img->cmn.num_mipmaps;
  17635. desc.usage = img->cmn.usage;
  17636. desc.pixel_format = img->cmn.pixel_format;
  17637. desc.sample_count = img->cmn.sample_count;
  17638. }
  17639. return desc;
  17640. }
  17641. SOKOL_API_IMPL sg_image_type sg_query_image_type(sg_image img_id) {
  17642. SOKOL_ASSERT(_sg.valid);
  17643. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17644. if (img) {
  17645. return img->cmn.type;
  17646. }
  17647. return _SG_IMAGETYPE_DEFAULT;
  17648. }
  17649. SOKOL_API_IMPL int sg_query_image_width(sg_image img_id) {
  17650. SOKOL_ASSERT(_sg.valid);
  17651. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17652. if (img) {
  17653. return img->cmn.width;
  17654. }
  17655. return 0;
  17656. }
  17657. SOKOL_API_IMPL int sg_query_image_height(sg_image img_id) {
  17658. SOKOL_ASSERT(_sg.valid);
  17659. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17660. if (img) {
  17661. return img->cmn.height;
  17662. }
  17663. return 0;
  17664. }
  17665. SOKOL_API_IMPL int sg_query_image_num_slices(sg_image img_id) {
  17666. SOKOL_ASSERT(_sg.valid);
  17667. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17668. if (img) {
  17669. return img->cmn.num_slices;
  17670. }
  17671. return 0;
  17672. }
  17673. SOKOL_API_IMPL int sg_query_image_num_mipmaps(sg_image img_id) {
  17674. SOKOL_ASSERT(_sg.valid);
  17675. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17676. if (img) {
  17677. return img->cmn.num_mipmaps;
  17678. }
  17679. return 0;
  17680. }
  17681. SOKOL_API_IMPL sg_pixel_format sg_query_image_pixelformat(sg_image img_id) {
  17682. SOKOL_ASSERT(_sg.valid);
  17683. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17684. if (img) {
  17685. return img->cmn.pixel_format;
  17686. }
  17687. return _SG_PIXELFORMAT_DEFAULT;
  17688. }
  17689. SOKOL_API_IMPL sg_usage sg_query_image_usage(sg_image img_id) {
  17690. SOKOL_ASSERT(_sg.valid);
  17691. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17692. if (img) {
  17693. return img->cmn.usage;
  17694. }
  17695. return _SG_USAGE_DEFAULT;
  17696. }
  17697. SOKOL_API_IMPL int sg_query_image_sample_count(sg_image img_id) {
  17698. SOKOL_ASSERT(_sg.valid);
  17699. SOKOL_ASSERT(_sg.valid);
  17700. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17701. if (img) {
  17702. return img->cmn.sample_count;
  17703. }
  17704. return 0;
  17705. }
  17706. SOKOL_API_IMPL sg_sampler_desc sg_query_sampler_desc(sg_sampler smp_id) {
  17707. SOKOL_ASSERT(_sg.valid);
  17708. sg_sampler_desc desc;
  17709. _sg_clear(&desc, sizeof(desc));
  17710. const _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  17711. if (smp) {
  17712. desc.min_filter = smp->cmn.min_filter;
  17713. desc.mag_filter = smp->cmn.mag_filter;
  17714. desc.mipmap_filter = smp->cmn.mipmap_filter;
  17715. desc.wrap_u = smp->cmn.wrap_u;
  17716. desc.wrap_v = smp->cmn.wrap_v;
  17717. desc.wrap_w = smp->cmn.wrap_w;
  17718. desc.min_lod = smp->cmn.min_lod;
  17719. desc.max_lod = smp->cmn.max_lod;
  17720. desc.border_color = smp->cmn.border_color;
  17721. desc.compare = smp->cmn.compare;
  17722. desc.max_anisotropy = smp->cmn.max_anisotropy;
  17723. }
  17724. return desc;
  17725. }
  17726. SOKOL_API_IMPL sg_shader_desc sg_query_shader_desc(sg_shader shd_id) {
  17727. SOKOL_ASSERT(_sg.valid);
  17728. sg_shader_desc desc;
  17729. _sg_clear(&desc, sizeof(desc));
  17730. const _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  17731. if (shd) {
  17732. for (size_t ub_idx = 0; ub_idx < SG_MAX_UNIFORMBLOCK_BINDSLOTS; ub_idx++) {
  17733. sg_shader_uniform_block* ub_desc = &desc.uniform_blocks[ub_idx];
  17734. const _sg_shader_uniform_block_t* ub = &shd->cmn.uniform_blocks[ub_idx];
  17735. ub_desc->stage = ub->stage;
  17736. ub_desc->size = ub->size;
  17737. }
  17738. for (size_t sbuf_idx = 0; sbuf_idx < SG_MAX_STORAGEBUFFER_BINDSLOTS; sbuf_idx++) {
  17739. sg_shader_storage_buffer* sbuf_desc = &desc.storage_buffers[sbuf_idx];
  17740. const _sg_shader_storage_buffer_t* sbuf = &shd->cmn.storage_buffers[sbuf_idx];
  17741. sbuf_desc->stage = sbuf->stage;
  17742. sbuf_desc->readonly = sbuf->readonly;
  17743. }
  17744. for (size_t img_idx = 0; img_idx < SG_MAX_IMAGE_BINDSLOTS; img_idx++) {
  17745. sg_shader_image* img_desc = &desc.images[img_idx];
  17746. const _sg_shader_image_t* img = &shd->cmn.images[img_idx];
  17747. img_desc->stage = img->stage;
  17748. img_desc->image_type = img->image_type;
  17749. img_desc->sample_type = img->sample_type;
  17750. img_desc->multisampled = img->multisampled;
  17751. }
  17752. for (size_t smp_idx = 0; smp_idx < SG_MAX_SAMPLER_BINDSLOTS; smp_idx++) {
  17753. sg_shader_sampler* smp_desc = &desc.samplers[smp_idx];
  17754. const _sg_shader_sampler_t* smp = &shd->cmn.samplers[smp_idx];
  17755. smp_desc->stage = smp->stage;
  17756. smp_desc->sampler_type = smp->sampler_type;
  17757. }
  17758. for (size_t img_smp_idx = 0; img_smp_idx < SG_MAX_IMAGE_SAMPLER_PAIRS; img_smp_idx++) {
  17759. sg_shader_image_sampler_pair* img_smp_desc = &desc.image_sampler_pairs[img_smp_idx];
  17760. const _sg_shader_image_sampler_t* img_smp = &shd->cmn.image_samplers[img_smp_idx];
  17761. img_smp_desc->stage = img_smp->stage;
  17762. img_smp_desc->image_slot = img_smp->image_slot;
  17763. img_smp_desc->sampler_slot = img_smp->sampler_slot;
  17764. }
  17765. }
  17766. return desc;
  17767. }
  17768. SOKOL_API_IMPL sg_pipeline_desc sg_query_pipeline_desc(sg_pipeline pip_id) {
  17769. SOKOL_ASSERT(_sg.valid);
  17770. sg_pipeline_desc desc;
  17771. _sg_clear(&desc, sizeof(desc));
  17772. const _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  17773. if (pip) {
  17774. desc.shader = pip->cmn.shader_id;
  17775. desc.layout = pip->cmn.layout;
  17776. desc.depth = pip->cmn.depth;
  17777. desc.stencil = pip->cmn.stencil;
  17778. desc.color_count = pip->cmn.color_count;
  17779. for (int i = 0; i < pip->cmn.color_count; i++) {
  17780. desc.colors[i] = pip->cmn.colors[i];
  17781. }
  17782. desc.primitive_type = pip->cmn.primitive_type;
  17783. desc.index_type = pip->cmn.index_type;
  17784. desc.cull_mode = pip->cmn.cull_mode;
  17785. desc.face_winding = pip->cmn.face_winding;
  17786. desc.sample_count = pip->cmn.sample_count;
  17787. desc.blend_color = pip->cmn.blend_color;
  17788. desc.alpha_to_coverage_enabled = pip->cmn.alpha_to_coverage_enabled;
  17789. }
  17790. return desc;
  17791. }
  17792. SOKOL_API_IMPL sg_attachments_desc sg_query_attachments_desc(sg_attachments atts_id) {
  17793. SOKOL_ASSERT(_sg.valid);
  17794. sg_attachments_desc desc;
  17795. _sg_clear(&desc, sizeof(desc));
  17796. const _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  17797. if (atts) {
  17798. for (int i = 0; i < atts->cmn.num_colors; i++) {
  17799. desc.colors[i].image = atts->cmn.colors[i].image_id;
  17800. desc.colors[i].mip_level = atts->cmn.colors[i].mip_level;
  17801. desc.colors[i].slice = atts->cmn.colors[i].slice;
  17802. }
  17803. desc.depth_stencil.image = atts->cmn.depth_stencil.image_id;
  17804. desc.depth_stencil.mip_level = atts->cmn.depth_stencil.mip_level;
  17805. desc.depth_stencil.slice = atts->cmn.depth_stencil.slice;
  17806. }
  17807. return desc;
  17808. }
  17809. SOKOL_API_IMPL sg_buffer_desc sg_query_buffer_defaults(const sg_buffer_desc* desc) {
  17810. SOKOL_ASSERT(_sg.valid && desc);
  17811. return _sg_buffer_desc_defaults(desc);
  17812. }
  17813. SOKOL_API_IMPL sg_image_desc sg_query_image_defaults(const sg_image_desc* desc) {
  17814. SOKOL_ASSERT(_sg.valid && desc);
  17815. return _sg_image_desc_defaults(desc);
  17816. }
  17817. SOKOL_API_IMPL sg_sampler_desc sg_query_sampler_defaults(const sg_sampler_desc* desc) {
  17818. SOKOL_ASSERT(_sg.valid && desc);
  17819. return _sg_sampler_desc_defaults(desc);
  17820. }
  17821. SOKOL_API_IMPL sg_shader_desc sg_query_shader_defaults(const sg_shader_desc* desc) {
  17822. SOKOL_ASSERT(_sg.valid && desc);
  17823. return _sg_shader_desc_defaults(desc);
  17824. }
  17825. SOKOL_API_IMPL sg_pipeline_desc sg_query_pipeline_defaults(const sg_pipeline_desc* desc) {
  17826. SOKOL_ASSERT(_sg.valid && desc);
  17827. return _sg_pipeline_desc_defaults(desc);
  17828. }
  17829. SOKOL_API_IMPL sg_attachments_desc sg_query_attachments_defaults(const sg_attachments_desc* desc) {
  17830. SOKOL_ASSERT(_sg.valid && desc);
  17831. return _sg_attachments_desc_defaults(desc);
  17832. }
  17833. SOKOL_API_IMPL const void* sg_d3d11_device(void) {
  17834. #if defined(SOKOL_D3D11)
  17835. return (const void*) _sg.d3d11.dev;
  17836. #else
  17837. return 0;
  17838. #endif
  17839. }
  17840. SOKOL_API_IMPL const void* sg_d3d11_device_context(void) {
  17841. #if defined(SOKOL_D3D11)
  17842. return (const void*) _sg.d3d11.ctx;
  17843. #else
  17844. return 0;
  17845. #endif
  17846. }
  17847. SOKOL_API_IMPL sg_d3d11_buffer_info sg_d3d11_query_buffer_info(sg_buffer buf_id) {
  17848. SOKOL_ASSERT(_sg.valid);
  17849. sg_d3d11_buffer_info res;
  17850. _sg_clear(&res, sizeof(res));
  17851. #if defined(SOKOL_D3D11)
  17852. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17853. if (buf) {
  17854. res.buf = (const void*) buf->d3d11.buf;
  17855. }
  17856. #else
  17857. _SOKOL_UNUSED(buf_id);
  17858. #endif
  17859. return res;
  17860. }
  17861. SOKOL_API_IMPL sg_d3d11_image_info sg_d3d11_query_image_info(sg_image img_id) {
  17862. SOKOL_ASSERT(_sg.valid);
  17863. sg_d3d11_image_info res;
  17864. _sg_clear(&res, sizeof(res));
  17865. #if defined(SOKOL_D3D11)
  17866. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17867. if (img) {
  17868. res.tex2d = (const void*) img->d3d11.tex2d;
  17869. res.tex3d = (const void*) img->d3d11.tex3d;
  17870. res.res = (const void*) img->d3d11.res;
  17871. res.srv = (const void*) img->d3d11.srv;
  17872. }
  17873. #else
  17874. _SOKOL_UNUSED(img_id);
  17875. #endif
  17876. return res;
  17877. }
  17878. SOKOL_API_IMPL sg_d3d11_sampler_info sg_d3d11_query_sampler_info(sg_sampler smp_id) {
  17879. SOKOL_ASSERT(_sg.valid);
  17880. sg_d3d11_sampler_info res;
  17881. _sg_clear(&res, sizeof(res));
  17882. #if defined(SOKOL_D3D11)
  17883. const _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  17884. if (smp) {
  17885. res.smp = (const void*) smp->d3d11.smp;
  17886. }
  17887. #else
  17888. _SOKOL_UNUSED(smp_id);
  17889. #endif
  17890. return res;
  17891. }
  17892. SOKOL_API_IMPL sg_d3d11_shader_info sg_d3d11_query_shader_info(sg_shader shd_id) {
  17893. SOKOL_ASSERT(_sg.valid);
  17894. sg_d3d11_shader_info res;
  17895. _sg_clear(&res, sizeof(res));
  17896. #if defined(SOKOL_D3D11)
  17897. const _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  17898. if (shd) {
  17899. for (size_t i = 0; i < SG_MAX_UNIFORMBLOCK_BINDSLOTS; i++) {
  17900. res.cbufs[i] = (const void*) shd->d3d11.all_cbufs[i];
  17901. }
  17902. res.vs = (const void*) shd->d3d11.vs;
  17903. res.fs = (const void*) shd->d3d11.fs;
  17904. }
  17905. #else
  17906. _SOKOL_UNUSED(shd_id);
  17907. #endif
  17908. return res;
  17909. }
  17910. SOKOL_API_IMPL sg_d3d11_pipeline_info sg_d3d11_query_pipeline_info(sg_pipeline pip_id) {
  17911. SOKOL_ASSERT(_sg.valid);
  17912. sg_d3d11_pipeline_info res;
  17913. _sg_clear(&res, sizeof(res));
  17914. #if defined(SOKOL_D3D11)
  17915. const _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  17916. if (pip) {
  17917. res.il = (const void*) pip->d3d11.il;
  17918. res.rs = (const void*) pip->d3d11.rs;
  17919. res.dss = (const void*) pip->d3d11.dss;
  17920. res.bs = (const void*) pip->d3d11.bs;
  17921. }
  17922. #else
  17923. _SOKOL_UNUSED(pip_id);
  17924. #endif
  17925. return res;
  17926. }
  17927. SOKOL_API_IMPL sg_d3d11_attachments_info sg_d3d11_query_attachments_info(sg_attachments atts_id) {
  17928. SOKOL_ASSERT(_sg.valid);
  17929. sg_d3d11_attachments_info res;
  17930. _sg_clear(&res, sizeof(res));
  17931. #if defined(SOKOL_D3D11)
  17932. const _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  17933. if (atts) {
  17934. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  17935. res.color_rtv[i] = (const void*) atts->d3d11.colors[i].view.rtv;
  17936. res.resolve_rtv[i] = (const void*) atts->d3d11.resolves[i].view.rtv;
  17937. }
  17938. res.dsv = (const void*) atts->d3d11.depth_stencil.view.dsv;
  17939. }
  17940. #else
  17941. _SOKOL_UNUSED(atts_id);
  17942. #endif
  17943. return res;
  17944. }
  17945. SOKOL_API_IMPL const void* sg_mtl_device(void) {
  17946. #if defined(SOKOL_METAL)
  17947. if (nil != _sg.mtl.device) {
  17948. return (__bridge const void*) _sg.mtl.device;
  17949. } else {
  17950. return 0;
  17951. }
  17952. #else
  17953. return 0;
  17954. #endif
  17955. }
  17956. SOKOL_API_IMPL const void* sg_mtl_render_command_encoder(void) {
  17957. #if defined(SOKOL_METAL)
  17958. if (nil != _sg.mtl.cmd_encoder) {
  17959. return (__bridge const void*) _sg.mtl.cmd_encoder;
  17960. } else {
  17961. return 0;
  17962. }
  17963. #else
  17964. return 0;
  17965. #endif
  17966. }
  17967. SOKOL_API_IMPL sg_mtl_buffer_info sg_mtl_query_buffer_info(sg_buffer buf_id) {
  17968. SOKOL_ASSERT(_sg.valid);
  17969. sg_mtl_buffer_info res;
  17970. _sg_clear(&res, sizeof(res));
  17971. #if defined(SOKOL_METAL)
  17972. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  17973. if (buf) {
  17974. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  17975. if (buf->mtl.buf[i] != 0) {
  17976. res.buf[i] = (__bridge void*) _sg_mtl_id(buf->mtl.buf[i]);
  17977. }
  17978. }
  17979. res.active_slot = buf->cmn.active_slot;
  17980. }
  17981. #else
  17982. _SOKOL_UNUSED(buf_id);
  17983. #endif
  17984. return res;
  17985. }
  17986. SOKOL_API_IMPL sg_mtl_image_info sg_mtl_query_image_info(sg_image img_id) {
  17987. SOKOL_ASSERT(_sg.valid);
  17988. sg_mtl_image_info res;
  17989. _sg_clear(&res, sizeof(res));
  17990. #if defined(SOKOL_METAL)
  17991. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  17992. if (img) {
  17993. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  17994. if (img->mtl.tex[i] != 0) {
  17995. res.tex[i] = (__bridge void*) _sg_mtl_id(img->mtl.tex[i]);
  17996. }
  17997. }
  17998. res.active_slot = img->cmn.active_slot;
  17999. }
  18000. #else
  18001. _SOKOL_UNUSED(img_id);
  18002. #endif
  18003. return res;
  18004. }
  18005. SOKOL_API_IMPL sg_mtl_sampler_info sg_mtl_query_sampler_info(sg_sampler smp_id) {
  18006. SOKOL_ASSERT(_sg.valid);
  18007. sg_mtl_sampler_info res;
  18008. _sg_clear(&res, sizeof(res));
  18009. #if defined(SOKOL_METAL)
  18010. const _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  18011. if (smp) {
  18012. if (smp->mtl.sampler_state != 0) {
  18013. res.smp = (__bridge void*) _sg_mtl_id(smp->mtl.sampler_state);
  18014. }
  18015. }
  18016. #else
  18017. _SOKOL_UNUSED(smp_id);
  18018. #endif
  18019. return res;
  18020. }
  18021. SOKOL_API_IMPL sg_mtl_shader_info sg_mtl_query_shader_info(sg_shader shd_id) {
  18022. SOKOL_ASSERT(_sg.valid);
  18023. sg_mtl_shader_info res;
  18024. _sg_clear(&res, sizeof(res));
  18025. #if defined(SOKOL_METAL)
  18026. const _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  18027. if (shd) {
  18028. const int vertex_lib = shd->mtl.vertex_func.mtl_lib;
  18029. const int vertex_func = shd->mtl.vertex_func.mtl_func;
  18030. const int fragment_lib = shd->mtl.fragment_func.mtl_lib;
  18031. const int fragment_func = shd->mtl.fragment_func.mtl_func;
  18032. if (vertex_lib != 0) {
  18033. res.vertex_lib = (__bridge void*) _sg_mtl_id(vertex_lib);
  18034. }
  18035. if (fragment_lib != 0) {
  18036. res.fragment_lib = (__bridge void*) _sg_mtl_id(fragment_lib);
  18037. }
  18038. if (vertex_func != 0) {
  18039. res.vertex_func = (__bridge void*) _sg_mtl_id(vertex_func);
  18040. }
  18041. if (fragment_func != 0) {
  18042. res.fragment_func = (__bridge void*) _sg_mtl_id(fragment_func);
  18043. }
  18044. }
  18045. #else
  18046. _SOKOL_UNUSED(shd_id);
  18047. #endif
  18048. return res;
  18049. }
  18050. SOKOL_API_IMPL sg_mtl_pipeline_info sg_mtl_query_pipeline_info(sg_pipeline pip_id) {
  18051. SOKOL_ASSERT(_sg.valid);
  18052. sg_mtl_pipeline_info res;
  18053. _sg_clear(&res, sizeof(res));
  18054. #if defined(SOKOL_METAL)
  18055. const _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  18056. if (pip) {
  18057. if (pip->mtl.rps != 0) {
  18058. res.rps = (__bridge void*) _sg_mtl_id(pip->mtl.rps);
  18059. }
  18060. if (pip->mtl.dss != 0) {
  18061. res.dss = (__bridge void*) _sg_mtl_id(pip->mtl.dss);
  18062. }
  18063. }
  18064. #else
  18065. _SOKOL_UNUSED(pip_id);
  18066. #endif
  18067. return res;
  18068. }
  18069. SOKOL_API_IMPL const void* sg_wgpu_device(void) {
  18070. #if defined(SOKOL_WGPU)
  18071. return (const void*) _sg.wgpu.dev;
  18072. #else
  18073. return 0;
  18074. #endif
  18075. }
  18076. SOKOL_API_IMPL const void* sg_wgpu_queue(void) {
  18077. #if defined(SOKOL_WGPU)
  18078. return (const void*) _sg.wgpu.queue;
  18079. #else
  18080. return 0;
  18081. #endif
  18082. }
  18083. SOKOL_API_IMPL const void* sg_wgpu_command_encoder(void) {
  18084. #if defined(SOKOL_WGPU)
  18085. return (const void*) _sg.wgpu.cmd_enc;
  18086. #else
  18087. return 0;
  18088. #endif
  18089. }
  18090. SOKOL_API_IMPL const void* sg_wgpu_render_pass_encoder(void) {
  18091. #if defined(SOKOL_WGPU)
  18092. return (const void*) _sg.wgpu.pass_enc;
  18093. #else
  18094. return 0;
  18095. #endif
  18096. }
  18097. SOKOL_API_IMPL sg_wgpu_buffer_info sg_wgpu_query_buffer_info(sg_buffer buf_id) {
  18098. SOKOL_ASSERT(_sg.valid);
  18099. sg_wgpu_buffer_info res;
  18100. _sg_clear(&res, sizeof(res));
  18101. #if defined(SOKOL_WGPU)
  18102. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  18103. if (buf) {
  18104. res.buf = (const void*) buf->wgpu.buf;
  18105. }
  18106. #else
  18107. _SOKOL_UNUSED(buf_id);
  18108. #endif
  18109. return res;
  18110. }
  18111. SOKOL_API_IMPL sg_wgpu_image_info sg_wgpu_query_image_info(sg_image img_id) {
  18112. SOKOL_ASSERT(_sg.valid);
  18113. sg_wgpu_image_info res;
  18114. _sg_clear(&res, sizeof(res));
  18115. #if defined(SOKOL_WGPU)
  18116. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  18117. if (img) {
  18118. res.tex = (const void*) img->wgpu.tex;
  18119. res.view = (const void*) img->wgpu.view;
  18120. }
  18121. #else
  18122. _SOKOL_UNUSED(img_id);
  18123. #endif
  18124. return res;
  18125. }
  18126. SOKOL_API_IMPL sg_wgpu_sampler_info sg_wgpu_query_sampler_info(sg_sampler smp_id) {
  18127. SOKOL_ASSERT(_sg.valid);
  18128. sg_wgpu_sampler_info res;
  18129. _sg_clear(&res, sizeof(res));
  18130. #if defined(SOKOL_WGPU)
  18131. const _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  18132. if (smp) {
  18133. res.smp = (const void*) smp->wgpu.smp;
  18134. }
  18135. #else
  18136. _SOKOL_UNUSED(smp_id);
  18137. #endif
  18138. return res;
  18139. }
  18140. SOKOL_API_IMPL sg_wgpu_shader_info sg_wgpu_query_shader_info(sg_shader shd_id) {
  18141. SOKOL_ASSERT(_sg.valid);
  18142. sg_wgpu_shader_info res;
  18143. _sg_clear(&res, sizeof(res));
  18144. #if defined(SOKOL_WGPU)
  18145. const _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  18146. if (shd) {
  18147. res.vs_mod = (const void*) shd->wgpu.vertex_func.module;
  18148. res.fs_mod = (const void*) shd->wgpu.fragment_func.module;
  18149. res.bgl = (const void*) shd->wgpu.bgl_img_smp_sbuf;
  18150. }
  18151. #else
  18152. _SOKOL_UNUSED(shd_id);
  18153. #endif
  18154. return res;
  18155. }
  18156. SOKOL_API_IMPL sg_wgpu_pipeline_info sg_wgpu_query_pipeline_info(sg_pipeline pip_id) {
  18157. SOKOL_ASSERT(_sg.valid);
  18158. sg_wgpu_pipeline_info res;
  18159. _sg_clear(&res, sizeof(res));
  18160. #if defined(SOKOL_WGPU)
  18161. const _sg_pipeline_t* pip = _sg_lookup_pipeline(&_sg.pools, pip_id.id);
  18162. if (pip) {
  18163. res.pip = (const void*) pip->wgpu.pip;
  18164. }
  18165. #else
  18166. _SOKOL_UNUSED(pip_id);
  18167. #endif
  18168. return res;
  18169. }
  18170. SOKOL_API_IMPL sg_wgpu_attachments_info sg_wgpu_query_attachments_info(sg_attachments atts_id) {
  18171. SOKOL_ASSERT(_sg.valid);
  18172. sg_wgpu_attachments_info res;
  18173. _sg_clear(&res, sizeof(res));
  18174. #if defined(SOKOL_WGPU)
  18175. const _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  18176. if (atts) {
  18177. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  18178. res.color_view[i] = (const void*) atts->wgpu.colors[i].view;
  18179. res.resolve_view[i] = (const void*) atts->wgpu.resolves[i].view;
  18180. }
  18181. res.ds_view = (const void*) atts->wgpu.depth_stencil.view;
  18182. }
  18183. #else
  18184. _SOKOL_UNUSED(atts_id);
  18185. #endif
  18186. return res;
  18187. }
  18188. SOKOL_API_IMPL sg_gl_buffer_info sg_gl_query_buffer_info(sg_buffer buf_id) {
  18189. SOKOL_ASSERT(_sg.valid);
  18190. sg_gl_buffer_info res;
  18191. _sg_clear(&res, sizeof(res));
  18192. #if defined(_SOKOL_ANY_GL)
  18193. const _sg_buffer_t* buf = _sg_lookup_buffer(&_sg.pools, buf_id.id);
  18194. if (buf) {
  18195. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  18196. res.buf[i] = buf->gl.buf[i];
  18197. }
  18198. res.active_slot = buf->cmn.active_slot;
  18199. }
  18200. #else
  18201. _SOKOL_UNUSED(buf_id);
  18202. #endif
  18203. return res;
  18204. }
  18205. SOKOL_API_IMPL sg_gl_image_info sg_gl_query_image_info(sg_image img_id) {
  18206. SOKOL_ASSERT(_sg.valid);
  18207. sg_gl_image_info res;
  18208. _sg_clear(&res, sizeof(res));
  18209. #if defined(_SOKOL_ANY_GL)
  18210. const _sg_image_t* img = _sg_lookup_image(&_sg.pools, img_id.id);
  18211. if (img) {
  18212. for (int i = 0; i < SG_NUM_INFLIGHT_FRAMES; i++) {
  18213. res.tex[i] = img->gl.tex[i];
  18214. }
  18215. res.tex_target = img->gl.target;
  18216. res.msaa_render_buffer = img->gl.msaa_render_buffer;
  18217. res.active_slot = img->cmn.active_slot;
  18218. }
  18219. #else
  18220. _SOKOL_UNUSED(img_id);
  18221. #endif
  18222. return res;
  18223. }
  18224. SOKOL_API_IMPL sg_gl_sampler_info sg_gl_query_sampler_info(sg_sampler smp_id) {
  18225. SOKOL_ASSERT(_sg.valid);
  18226. sg_gl_sampler_info res;
  18227. _sg_clear(&res, sizeof(res));
  18228. #if defined(_SOKOL_ANY_GL)
  18229. const _sg_sampler_t* smp = _sg_lookup_sampler(&_sg.pools, smp_id.id);
  18230. if (smp) {
  18231. res.smp = smp->gl.smp;
  18232. }
  18233. #else
  18234. _SOKOL_UNUSED(smp_id);
  18235. #endif
  18236. return res;
  18237. }
  18238. SOKOL_API_IMPL sg_gl_shader_info sg_gl_query_shader_info(sg_shader shd_id) {
  18239. SOKOL_ASSERT(_sg.valid);
  18240. sg_gl_shader_info res;
  18241. _sg_clear(&res, sizeof(res));
  18242. #if defined(_SOKOL_ANY_GL)
  18243. const _sg_shader_t* shd = _sg_lookup_shader(&_sg.pools, shd_id.id);
  18244. if (shd) {
  18245. res.prog = shd->gl.prog;
  18246. }
  18247. #else
  18248. _SOKOL_UNUSED(shd_id);
  18249. #endif
  18250. return res;
  18251. }
  18252. SOKOL_API_IMPL sg_gl_attachments_info sg_gl_query_attachments_info(sg_attachments atts_id) {
  18253. SOKOL_ASSERT(_sg.valid);
  18254. sg_gl_attachments_info res;
  18255. _sg_clear(&res, sizeof(res));
  18256. #if defined(_SOKOL_ANY_GL)
  18257. const _sg_attachments_t* atts = _sg_lookup_attachments(&_sg.pools, atts_id.id);
  18258. if (atts) {
  18259. res.framebuffer = atts->gl.fb;
  18260. for (int i = 0; i < SG_MAX_COLOR_ATTACHMENTS; i++) {
  18261. res.msaa_resolve_framebuffer[i] = atts->gl.msaa_resolve_framebuffer[i];
  18262. }
  18263. }
  18264. #else
  18265. _SOKOL_UNUSED(atts_id);
  18266. #endif
  18267. return res;
  18268. }
  18269. #ifdef _MSC_VER
  18270. #pragma warning(pop)
  18271. #endif
  18272. #endif // SOKOL_GFX_IMPL