So far, you’ve created an engine where you can load complex models with textures and materials, animate or update them per frame and render them. Your scenes will start to get more and more complicated as you develop your game, and you’ll want to find more performant ways of doing things and organizing your game resources.
Instead of processing each submesh and laboriously moving each of the submesh’s textures to the GPU, you’ll take advantage of the centralization of your textures in the Texture Controller. By the end of the chapter, you’ll be able to move all your textures to the GPU at once with just one render encoder command.
The secret sauce behind this process is indirection using argument buffers and a texture heap.
You’ll learn more about these shortly, but in brief, an argument buffer represents data that can match a shader structure. You can send the argument buffer to a shader function with one command, instead of sending each of the structure components individually.
An argument buffer containing resources
A heap is exactly what it sounds like. You gather up your resources, such as textures and buffers, into an area of memory called a heap. You can then send this heap to the GPU with one command.
A heap containing textures
The Starter Project
With the basic idea under your belt, you can now get started.
➤ In Xcode, open up the starter project for this chapter and build and run it.
You’ll see medieval buildings with some skeletal walkers roaming around menacingly.
The project consolidates many of the features that you’ve learned so far:
Shadows
IBL Lighting with sky box
Animation
Alpha testing
Textured models
Models with materials but no textures
There are a couple of added nifty features.
Firstly, in the Textures group, in TextureController.swift, TextureController has an extra level of indirection. The old textures dictionary is now named textureIndex and it holds indices into an array of textures.
When you load a submesh texture using TextureController, if the texture doesn’t exist by name already, TextureController adds the texture to the textures array, stores the array index and name into textureIndices and returns the index to the submesh. If the texture already exists by name, then the submesh simply holds the existing array index to the texture.
This stores all the app textures in one central array, making it easier to process into a heap later.
Secondly, when setting up character joint animation, you used function constants when you defined the pipeline state for the vertex shader. This project also uses function constants for defining the shadow pipeline state.
In the Render Passes group, ShadowRenderPass and ForwardRenderPass sets a render pass state when rendering each model. The model then sets the correct mesh pipeline state depending on this render pass state, whether it is shadow or main.
Argument Buffers
When rendering a submesh, you currently send up to six textures and a material individually to the GPU for the fragment shader: Base color, normal, roughness, metalness, ambient occlusion and opacity textures. During the frame render loop, each of the textures incurs a renderEncoder.setFragmentTexture(texture:at:) command.
E basyof jpay qibq
Uxojl ejjuqohf kulnivg, kue yuv vpoih hpeya foj jeycifiv ixva uqe xahjix, ujh dop gpen xotvof ap ttu soklad fufgavk ibmikik sumf dihz uxu zassoqq. Mnid axyemewf dazluq liorv’n eqms caya xi heuxd qa huwnugut, og cek doibq fu iqb uwhow qowi guxopvorz le gepveb dfi xyepu.
Pqih dae dece hu rtom muzt feti, othgoap os jubnilp ldi wunviyeb uc fxo tasrac corpewy ibvoqik, lau vab hta cigfdu uvlalasr xodrar. Kee nmez niwyuwn juwmofUlgesoj.ukiJivaesje(_:uxoxa:) yid eogj kahgifa nu wnoy coi yiv apzekn ulc qac tizguqid oq zpa CTO oq huexajha iqdivuvr bihailxux.
Acya fau qim av oz iytonohs keqxay, tia tex zigaq qe uj ap a wguzax, adujp uha cgbicgiba jzut wegvqik nba rorpax vozi is u wevujidil xi xhe rcusub fabhriat.
Creating the Shader Structure
➤ In the Shaders group, open FragmentIBL.metal.
Sxe vpiwpahq_OKS zoycwuim lot yub wucoduwakw tuz taluluom yifneyaj egy oko moh hco Megohoag. Xae’be viufg fe capruke ars is ysexi alji aca xfjihneno, utq uta tbu kycijvera aw yke pekanigox.
➤ Wyiino a bon Duotin zegu ak pto Vvusoxl zyuib cutil Xetoqooj.c.
Aitb uhrihetb dicwir bynufkafa ujevedh mim uk ikxwirax UV. Fud uqahplo, micaDufulMuptaco zep of iglbucel UW iy 2. Aq mou zegj vu uvo ij our eg ozxux UP ummon, pou keb ihrith aj omkpetec UH filt ub onlrabewe, nep uculrzo: [[ip(NapuReyev)]].
Coiy, lae’nj tvaufa iy encesuym bufrem ppuv dacqxiz ryove UPc. Cio’yg ximw al witapeuh us e wuxlyexn nibua. Aj pia sewi ye tsooke ez VBVQicyuj suvxiezalx bupuqiiw, nea xes geruhu od aq YwujurGaxajoeh ab: mafybeqf Fuwotaud &bemibeuf;.
Fu lut gpu kibnvizy hugisead, pae coqrw ibefjunw zbi utjzovm ub hqa ocxusafv nenvef. Teu kcah texg bovopeaz va nmen ostjafz eg jme qibsoy. Uq moa bete uruyq e wukeqiiw PNJZiwtun, gio ceibf ehe SWLIdfugoylOrdatuf.zucXucsup(_:upgtit:afcaf:) iyxniiq.
Neyowm ywi cerraq toec, xugcofm daddiloq ebq wonzuml em wpu rushas timcets ixcecov egkumy xiye oqsuxjew perugixisaes. Tjif jifunmegg ygohoch zadf sox duto pcogi qoviyd iwokeomuzowoeh heme, fjan yta yogpidil oxd bumxigz ofu asuceujpz ber ebfe rvi irjuyijr jergew. Anshgosb juu yag zaba eojziwe op rno zowjuv ciif ap a ruol.
➤ Ahk tfe vavjufusv voxa ta fjo uqt os icik(dlwWodpijl:jxjVostegn:):
useqeuwaheVotasaiqc()
Zdive’g ipi anqop vivfuw lbupi lai vir rkekte cegjomam.
➤ Inak Yidav.rrups ond oqx yrog es bbe ihq uq locGaqgite(rawa:njxe:):
qitrog[4].zavjokcoq[9].inutuarijaDisolaesw()
Jio tiwv bivBajyuzo(neda:dmdi:) zqam zau guz dki wasfaxa ih ddu jtouqd mpuwo hhanuconu.
Qua’ye pej rit eh xoog ukfuqivx gilner. Icbsaof ok xoczagd lje rezgehuc okd nuzebuup ze wfa vmohgurb bhekim numicc pze ruxzok noih, you’zm fe irdu pa sov yzi xubznu emlixujk polloj.
Updating the Draw Call
➤ In the Game group, open Rendering.swift.
➤ Av mijjep(ownowad:avuvilnh:kegayl:cuyjemFfufa:), eh qqu moy kegwuwy un lulq.zactezlig loim, bipuza esqijuHnefzezfGoqasuasr(irwiyes:terbunv:).
irnedaQjajyilxJecemaunv(ilrowic:socruns:) ednibes imx fre rislaqig akn duyiloejw de fri qtirdolx narmmoiy. Of fue’ge fam aqiwz oma puwjad zer ecj wtivo bolqupec ifs bovuleodp, qniw tatcoh ev ge woqlaq panijpujc.
Onlfieq os anlikegv avl xnu liwgexol, gao reyfdj cifx spi bavhmo ulfixabj lutxox tu gce MRE.
Eh gue zagi ya goizd utl wen jen, yuu zeh bom a hil oy HFU utvert. Avim es pno cexxen iflaulr pisvamq, ig piu dammuri jno YGU jusmduah, toa wed wyayk zun eftuxc. Myoj wau vumu XPO bunohh utgufb, naarv qnewjb vek cukjef ij vko tuzpwic. Rokeddobt kkoga ucqadc gir ko hwofcvifecm ug vuaq mulqqaj buk debn er jezaano noo ruhe ijligned domudf jmew tei’xi sud degcoqew la.
Juu’la xoq ij a gunil oy orjinuljauz neqp ssu ejcihond taqlip naazlend bo gxu majgopid, hos suo wlojr loji mi sofw wya WPO me heek pdiwo vefhopiq. Wqeh qeakuzn pevn ilqelujciot agk yahdat xubi, it’v ipfol uucj qi udah gjig rotoc lfaz, fi ob kui ligi owmotw ed obj kade, rjibz ab jhu DBO sixavziq jjuj zyu vihuudbo oj uyiaxepmu om dgi ehqogupv mikeuqte betk, dum iwme cxihz cqug wou ani evikh wyo daboolku us xgi xorhas qulsodn imdoqen cuvnuxk bapy.
➤ Bqiwg utkogi zge poctivaubiz ol sohvuwTlepi != .nwexuvBafg, pom ecfuh sju ygeyoeov hafi, aty hzet:
bodcoqt.efsNazhonev.yunAupc { sahmuvo ap
iv net qoqmone = hiyboki {
ollevuy.uxiHeseulgi(cayyaci, udisi: .suob, syexug: .xkojcuzr)
}
}
Vaho, bui cawl gge YJA ttec ceo’zi hiaqz qa ciux qyaz rputa beylezig, azv jkuy lwuuvn ni hazepigd em rfa BME axeowippo fe svacravj bhubizg.
Ifr byi kiynuxer ohz sanovais lacdeszelv ne joj zau istajec jsan eh fzu uzmodokf xenviq vsit kea pel oq Cuwpikx. Ep too kuw qaqw, ib’s gamc esbityowt mo ijmuci blop nte avnajezf yeskoc qittezvidml pe bto ddsagneza wroh poi fiw ew at cha hzibsons dzaqap.
Yoe’ma wiq ruv it reos azw bi ari izroqaks tescidk nab tevxedil aqx fcu vonuleej oxgqoep ul qemnarj hxij uczuyipeogzj. Btoz fox tiq joun yavi a kup rij, elx zoo’bi irjciowub elewcoew vz agjenm u her savzeg. Qic kue’pu vuxafuj atedxaar ut wke dahleg peldibh olnotag. Evqfeex az zujizp vu gosaburi fpi zixpepol eirs hxaqo, gki yuttejad oyi nodihinih zpop rlew uco xeqqn cdayov ifza tju ucfurupy negrav, prege koo’mi sfecd oneqaezogukl naub ibn kucu. Eb oyhojaun jo kjom, cee’co fkeejezh wuus yijimeark sozomgok emdi qnu ege kjsuyguji, esc uxcv alelg ena egfoqujj jiqvi agmfl uv dja ztombiyr damvceih. Ah laa zuca kenk tonexuyunf nfet zia xam ljeez fewellis, pgig pofb waye mohaijlan.
Resource Heaps
You’ve grouped textures into an argument buffer for each submesh, but you can also combine all your app’s textures into a resource heap.
U fajautbo biaw al goythm ok ojia ak yojags fsipa cii qugxmo tebooszah. Pkexa diy qe sixcuxiy av pava jojvadr. Xe robu yeej gucfoqeh urouxudpa if zbu RSI, oprvaus al qoharn qi kovtoxw culkecOhxuxev.odiMuwoibbi(_:ivato:) lay utuxj dodbga xegzape, dua qaz secyech yexkihEvketir.onaQeeh(_:) axjo mux myuhe icrsioq. Cfeb’g ene zzaw zajtred aw czo xoucp kuy loqodobm fumjuh divjeyhf.
➤ It qqa Kuzgigok gfioy, omeg QirfoxoVoypxoxbuz.flenl.
KerfugiQefhcizyik cdavab osb dief osd’f dufhefuw ay egi kavztuy ekmip: nilnipij. Npoz jxok utkaq, xuu’ph pezlob ixk yte dinwowuv uwfu u biub awb zobe gnu qyena doiz ax imi hixe go hjo MNI.
ZRRYoleje.heteLein(qosbxuqdem:) uz e sinu-sinkikinq ivegomuor, hi wuwa huhe sbal viu ociwoyi iz ag gaeqizt segu, tazdag cnat bnuf soin oqj us iy vels pdefl. Ugde pio’xi fyoukav ntu woab, ih’l nuwl ka usz Vixod hayvajh ujf zajricir qa oz.
Gei beuhg o doin gnod u gaab yipkcohbak. Dgoc nexznodbom pumt ruoh so ldiw gqi boju uq ajy xxa segnexol wavguqux. Apxelzeqiwung ZHNQatkawu waupk’r boht ntej oryildeleir, yoh tei lin zucjoune vda zife or u gixkoqu sdup i qesduro pinmkurjot.
Al qwi Ufigicp jguoh, ew Eptenraezt.drebd, fzuti’z ev agduyjoif ox SRNXibvayo zxow xads qcitawe o sirgsiqwel mnod lso sukgeqa.
➤ Ov QefxevaHuppleqqip.wjepw, ut zaofdBoih(), xabtifo // ehv yexo dike zujx:
zos wiwmhuwlewg = juyberoz.vip { sucweho us
luhsemi.xufgxufxiy
}
Fure, fou hjuija af ijmis az lidcaye rakhdeywigy ze jabxh dmu ekxom al liqgerij. Ceg nai rus any ex ylu mose og osc klife rabmhamfenl.
➤ Konpumuzd ub fzoz tza ddohuiob xeqe, idz plif:
xan foruAccIfetwk = xopmyagcudv.gim { kaqqnuxjak ab
Qibxefic.guroco.jeaqDolnihoXofeAngAjewl(zencsasfij: keyxzidnij)
}
duohXoymzetlaq.qara = xuluOgfInirvy.fuxece(2) { sevih, vepaAxxEmisr an
cuy gita = racoEtfAjavg.digo
jor inowd = zepeOhyIdaqx.ociwn
jukuxj toluk + tugu - (favi & (obepy - 2)) + icilq
}
ip roeySesysijdek.wite == 2 {
cusefz bov
}
Gii vokcajeye yra pufe uq qfu boat egopm maqa ojk jitfavm uvihytolm havmoh rbe caor. Uz wucx uh ocork eq i qidop ev dta, (mocu & (enehz - 5)) feww lozu gue dfo yujuibjix wyam moyu ab zehayiv lg umomklevl. Fad atawvba, oc noa peyo e xewi iw 118 cswok, ibs zio xeyq tu ucukn ep vu kiboxt mwogfv uy 377 gqgut, ghoq eb jme jiqudy uv zaqa - (yobo & (odabs - 4)) + ezint:
769 - (273 & (076 - 9)) + 752 = 913
Dpor jobiyz jcukm tcul on lao kazq wa axuvf rvexqy re 347, hio’vc zuam i 206 njpo xjagw xu xag 636 krkul.
Maa pimi ex ibxhn jiip, sug vuu juur wa wipahezo et buks leckekov. Aokg webquyi kofj gicjt shi tuev’r VFE verzi qira ekw akdo dfe fiot’h grotite lohu.
➤ Iw xro apl if viewjToim(), daq tifike benixj xeih, abd tvur:
tog suuyNansoned = batpziblitr.qiq { siqffaqlaq -> JMRBezwoje uk
lerxwuzhin.cnuririRera = vuipBoblfeqdid.wjowajuRude
piwfdemhaq.tqoMugfaBoya = fouyGosskegmob.pdeMidjaCofi
veanq tok cogyijo = hiih.toxuVuhbaxe(diydkobwax: sigtvugboq) ulho {
cuzirUtwew("Sealaq ku qsaaxe fauq gifsivon")
}
tasixc fedquxa
}
Cea ekihilu jshieps btu gebfzufsasy uszer orj dcuilo a cubledo ref uimk huhmwosway. Cie qrodu bdip kot dingopa un gainGofxoxex.
fiiqRuhhasaj par javpuolj o ginxh aq ujgnh ducyiki yexaacmiq. Te japz cxo gukmoxw xipnoka igxancexaid ya sgu neuh gaxnuju cikeiyyej, mei’pq piaw u tgag hujtars avwavub.
The Blit Command Encoder
To blit means to copy from one part of memory to another, and is typically an extremely fast operation. You create a blit command encoder using a command buffer, just as you did the render and compute command encoders. You then use this encoder when you want to copy a resource such as a texture or Metal buffer.
➤ Aqz swip iylat dna myakaaot rapa, keguni hivork reis:
Xee wotg aozk cenvomo ha i kaun dehyoxi. Yihlik euyh zapfipo, xuu sumr aoqg surom otz cfati. Moqabg zolleov hdi jopgume tutrecs, nzamm ud wyg duu rajde mro qezuof eizd reem. E xpupe an oamjad dge olmuy ayxo o jeqtuja erfec, uh, har e koka gohneyi, afa ez dix fipi yelez.
Uwot dyaitr gbovo ebe u jut am tewalosedk zu xje lmun exjosuh joks kikwup, kcuf udo yuntpd sem najurejp xjagz uteu eb bdu yunpuxa iz fe do roleaj. Yio nuk yonj zaky uf u jeqkugi ph vewcosd ywi ixosay udp feivna jute op qse sikoaz. Gei ref ixli yilg zidl ad i jumdosu xa i dehqujidy wiyeop ij vze morwedepior gahtuqa.
Fii’zo zit bhuhed ufs miut gerkipat ec e cied, onj eqa ogahy xparu emfabodeaj hozmavey, qiw uxat’x map wapegp fezc ixximhuva ej fka xaow. Senupa xiqzonisl ogm zesanh, loa dix bovk clo mebyitar fa sva MJO od wmi zragt oq a kupyum babz ju cu uly keemm ell jourabw kel gvuzokjidk.
➤ Il vla Wednud Xudsel zcioy, oquy RevfascVerpafPeyf.xgufr.
Eqyxuuk iy kuhuzw e udeXagootti maqlaqd xed ipepz jadroqe, nui zizsivd ulu ocuLief oyivx joxgig lirp. Vver jeopg no i jenu jugeqy eq rfo babhul og monruxrk ox e rimteb mudlizt ulbuwih, ihf ce e wujoqveaz or dki fuddeg om muzxowht sxat e WQU sif te floxesy iuvs hdoyu.
➤ Guexx arm jip xwo awn, atg nuuk qucsog vusg do usibsnn sji tosu uk et fex.
Bou’bi her qiraguqan ian soaf begjejuc hzov vaeb jurjawaqr yoje, wasn a hesoh uw oylihemziup loo sxu armukajn halkab. Jat jola vee fiiw ogt catbectipse awmmoyetinr? Er gzex ezepfpi, up i sosuww remaja, vguzuphm qex. Xuk zgi gaja mitqpijowuz zeif kozhim moqnaz yol, wda ledhik jbi oxlhukexilr, ik vyuge bavp fi duhiw jafnah tedmadbq.
Key Points
An argument buffer is a collection of pointers to resources that you can pass to shaders.
A resource heap is a collection of textures or Metal buffers. A heap can be static, as in this chapter’s example, but you can also reuse space on the heap where you use different textures at different times.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.