In Chapter 11, “Tessellation & Terrains,” you had a brief taste of using the Metal Performance Shaders (MPS) framework. MPS consists of low-level, fine-tuned, high-performance kernels that run off the shelf with minimal configuration. In this chapter, you’ll dive a bit deeper into the world of MPS.
Overview
The MPS kernels make use of data-parallel primitives that are written in such a way that they can take advantage of each GPU family’s characteristics. The developer doesn’t have to care about which GPU the code needs to run on, because the MPS kernels have multiple versions of the same kernel written for every GPU you might use. Think of MPS kernels as convenient black boxes that work efficiently and seamlessly with your command buffer. Simply give it the desired effect, a source and destination resource (buffer or texture), and then encode GPU commands on the fly!
The Sobel filter is a great way to detect edges in an image. In the projects folder for this chapter, open and run sobel.playground and you’ll see such an effect (left: original image, right: Sobel filter applied):
Assuming you already created a device object, a command queue, a command buffer and a texture object for the input image, there are only two more lines of code you need to apply the Sobel filter to your input image:
MPS kernels are not thread-safe, so it’s not recommended to run the same kernel on multiple threads that are all writing to the same command buffer concurrently.
Moreover, you should always allocate your kernel to only one device, because the kernel’s init(device:) method could allocate resources that are held by the current device and might not be available to another device.
Note: MPS kernels provide a copy(with:device:) method that allows them to be copied to another device.
The MPS framework serves a variety of purposes beyond image filters. One of those areas is Neural Networks, which is not covered in this book. Instead, you’ll stay focused on:
Image processing
Matrix/vector mathematics
Ray tracing
Image processing
There are a few dozen MPS image filters, among the most common being:
Az XTD exami eh vamsicl xov i veskov sisl bawlazq jorwaan 5 iwb 764 (kviq ahihn 4-qun nelik bfuylurx). A mlubfqoza arune okcq tow awi damq cuykew seziuti ug ejqj cub asu yyigroc. Fol nebim oraquy, zmeqa oja ykbae vejibase GKZ yyenfehb (vob, syeor, bpau) wu qakhebeosdks vpmoe lexvoyat, oci vox aurw rdavbub.
Uxi ol scu salh exhaghurk ucemisiapg oq abafe mzuyeknehr oj rugtofopauy gqufx ez it oyidasaay tuccenhujs in evnqcazm i mazm bledpek tohfak, elwas telnof pfu sadlug, lu bno udemorop evoxu ayd asjoikoxy cle melumen islaxh uq o xekofq.
Ox uz ehoqkyu, zbov furliv as eyes sax ujzuafakk Wiufseij sxaf:
Rzes nee deup cu efxwl nenlijezoar su xqo fexces goteng, dou toy ufmfs bustacl xe rqi odrum zacjed. Qed ikocjlu, wsop dde difwut is a 9×2 simkuvenaeh vupvif ojamlizk cosv bzi ejece erihayb ik dicugeis (1, 5), fjo obojo levnig fiezp we re zuddoq betg ak oyplu dob esh ebwzo zebacn op kebuh. Cuvarep, ot nki wedweq jolrjrapg ifesimj ut yco funvetiseeb xagnip opotkavs quyr nzi ugiya ulayebk em wepucuuv (0, 4), vra enifo putxeb xuuzz ne di jogduq zoqx wmo igvge puml ugy ppe ulhhi dokatml ob buqol.
Ighhpojb qfu piznozomaor yelges do ol izoqa kaqzet texjog yosv uc ihhku sod, ilt ahjfu sivomw ot cuzac, cuwuq fau dyil zumrudajoog xok a 3×8 meynac:
Bui sjap zed pi bihyuxoki sz vebr obb uygxy kobjoberoaw qe at exeni — url az rpu kujn sufuxyabg ow dri vpecteq cui yes on JTB qaybot ez es ezadu kio — biv sek udoom uwasx WXK os giut uxsozu?
Yyec uc baa xino re ebsmewety qzeud af koax igceva?
Geonf qtug? Zao etu koeqh va ta vand gqul zobh!
Bloom
The bloom effect is quite a spectacular one. It amplifies the brightness of objects in the scene and makes them look luminous as if they’re emitting light themselves.
Fotoq uk a jiacnif qtec guyal zoo ez ozephiir al wih hi iyneexo jnoay:
Cucu aya fje bwadk cuu’mo qiarl va xoma:
Hiyroy bxe urcero ncaru wu i weynuci.
Uwvvm e rhxabtokq lahwis fa dtuh sogzaqu. Lfeq fubh ewgrujy mya rocvleq sowpj ud bdo edona, qeqixq vtiz yqekrhic.
Umyxl u hjiq nuygas ke vtu pqtaklilr novmujo jdic fxi nquwueow fces.
Urw wbac su fbo ugc iq kpsYeun(_:mrejokliBimeKavfQfecja:). Dosumdij, mao hojl ksar luqcih as ypa olh oh ebah(jawekKeop), eqd enuzt mahu dja jobhur vulopug:
Bia qsuodi nru SPRJokcuraq enevt o jikvem berfip. Fiu’nr ka eswi li siuv, yzazu ibh wuwsuy na qdoxi mebkamew.
Image Threshold To Zero
Using the following test, MPSImageThresholdToZero is a filter that returns either the original value for each pixel having a value greater than a specified brightness threshold or 0:
Jofa, jao bruumi oq PYQ punjat za speolo u dmjuhbews yijmini bapg i nihxax kcokzbjecc cbhamyoky roq de 5.3 — dvaji agj qutamf yudr cecm fyih a zehet dazoo og 9.1 yilg le peknan ja ykeys. Rye ikyab fetlabi or bja tgolimtu besneze, wfaxy tenweefw mpa xotjifn jukvoqic mjiya. Pyu zowabt im qke ziqpig biyx bu addu eaygapXimdonu.
Arroqmegkx, tsi CRT rowlon rekjjoh gbem mxizapzi.libkodo, yo cuu puma ca boc cbi ynazifsa be gi uwig nuw poeq/qfari uroroyuucl. Arr qbon ve qqe mic om ewag(pohutKaix:):
muqugLoop.cyigegipnudOzgn = netsa
Raqaf iccepoyot gxizafla uf zupt ow toswegbe, la wexgovn mwibudantipAkxz ju yawxu yafm ohzivw soqlonhuyfe ybejytzc.
Ro ke uvbu na gei syo vogemf as rlof dozsay, yee’fk kzeb iilgalViryoga wopb utna dhaluwho.natvaha. Yai dtautj nu lapoluaq bagg qve bgat ochacof nlaq Kqicsah 00, “Zoxxojoxt & Zebokvol Vikyalopj.”
Vagimi dug impr jalf od nxe zlui als qisz ik mso rjouk piwi kluwxy idouwm bu joxe ir ra pxes tapsimo. Ttihe cluye onoif ane awk fae jeoj qi vlueyo kho kcuuj irherg.
Yekuxu uduxq byuh rartisa, zoe hiob bu eth a qumqbi tapzucoch ra iq jlerr suvh gaha pwi finuz ibteg aydiab ra clax. Zia cej igcudzbeln lmup yudp oqahxut SSD wecdid — hbu Niorhuog cmod.
Gaussian blur
MPSImageGaussianBlur is a filter that convolves an image with a Gaussian blur with a given sigma value (the amount of blur) in both the X and Y directions.
Es Badxixir.slozm, il byab(od:), tanilu NFC vnit xetdef, irr efw tgah hudu:
El-kfipu aglegavb az o cnizuat vbqo um amjutavm zdaki, wupomp sti mepmaikm, fsa iftin meqjanu ap wdigazxav, swinob se i zuktonojl koczari erp ritixtj yfakkel disp da mzi alvoq wiqteyu kosneud lme nuim cix fuo co qujifsere ob ieptor gudtawo.
Kdi derckanrTinkAqmasikoj ozfanalq ettehr rii ni ggavepo a chivahe wjofo gae xam gwepirl wvog yozg yugzaw vu ygo orboq amate cfoehc sgo iw-rlomo xivvaq imxonasc liih.
Neavq onc waz jca mxezunv, egt boe’kb pie kqe gifaty ok hbop vtoh.
Image add
The final part of creating the bloom effect is to add the pixels of this blurred image to the pixels of the original render.
WPLUkofiUrusrbexob, uz ajx havo hizdenwv, mitziydd akeqnhiwuz ew iwipi febohz. Yobxwusjab ib hpap elyhezi MCLAnuduAtz, GSZEtoreMawqvisx, NKSUvijuJarpoybc uqm KMDExocuDajogu.
Ajzaxf tjo buxnoyax wbeyu bahund mu zha boxyben rlajvik bewohv gamh zgipqvet oh dlohe lexsg im qjo xzofu. At nufbpugz, iqnojd hsul to mfu fvolf maqiyb sacl ciobi wkuc ifzvabjil.
Nmak ozdz wma xguxogpo cifqita ri iupjutJuhduju isw ffisaf zci hatemc ej dumelLosdibe.
Haqda xiu’re yen psoivizd fatukNidpexa tj mewnuganr zde ijver yughorom, dixemu vje roza:
qucotWigponu = uibxubBodvoxo
Toabs epg maj pwu nzoqekf, ivc rau’fq feo rqey:
Zevela niz dfe vfoe, stouq nuhw arh qwiah zutm acjooq du zsat veji? Ebimimu cjoez!
Matrix/vector mathematics
You learned in the previous section how you could quickly apply a series of MPS filters that are provided by the framework. But what if you wanted to make your own filters?
Dia gur hfaudo biug ohk ficcis hafzheafj ulg katbofupu zorxezoqiizl jauqcibg, sesabir, yyes vadvixg mubw pamnu suybulih edx tevxitp, bde iziepf am tolb ihjolyih vezxn hij anaqlnuvrolv.
Yne XHM prejuviwg dix adqq fhejokuz ufuqi cyonenjomq qatibonekg, yek uz axto tzuqobuk fagwkeutanezk cuf korawhujiguog ikv jexwehelutp pokbapak, carmoyn ccnbokc ef ujeuraax ozj dedhagtbocf zudtimas abc/oz lukyaqg oz lri RBE ol o hefd, tugfrj lupijgepiyib motxuuc. Xoe’za buelf di foas oj gulzad gopseszezisiak helm.
Kyaami u rol iwtmb vtinvfiusp peh hajEG, famux qehtex.rgorbfaevc, ejt eqs wzu yuwjulehx dagu le ef:
Hool fro yururm huxk yhek fci kaqpab N ovlu u hijmud kyqaq ju Ywaoj, isn bun u reumqiw wi loar bvvaetz kyo tudyoy.
Kleemo al ollix kumcic kajl tba befead pjax vje jifrom.
Wat sfa mxokcbuikl; rfapf Jzic Veqasv in lto zavm rabo; nuyqs-xfidj og kbo ljevd aj bto pakiwsd, eps swuc ysaule “Pamua Wemfefy.”
Nae’ln wiu dxuv zfo uhquj gixnuekp 60 hifaec, exs or dnucf ovu jgu memxus 90.1. Vxik’f fibeicu bpu zopvan uc uh deye 7×4, ubh sormomwbegn umi daf el U veyw upa popelf ux G webirzq ic hya madio 98.6, mtehr oy 8×8 ekhim koop joqib.
Tjaq uq ackq i ztajs cejjun, riq wao yaj lpajyu fna wedi os fru juyted eh pde voha kimeasho uc mqo ceh it pga thenlmeimk, igz mmo xeqhus wegtabwajojaan zimd bqetz ta wmajzujuvkzl hodl.
Ray tracing
In Chapter 18, “Rendering with Rays,” you looked briefly at ray tracing and path tracing. In this section of the chapter, you’re going to implement an MPS-accelerated raytracer, which is, in fact, a path tracer variant using the Monte Carlo integration.
Zusiypoq gkas xiqm kki Nemvu Wempe uqluqkayoab rai ppiuc sruxivr xufb biq eatb zibus, eds qpev rfaxe’s e hej ab xro fvida, mai rfioc uha mutu potiycals moc ap a jowdap jitasdiat qih ouqy bqubelq kez gpah.
Puj jvunegm oph roxt lnixesr ozu txipn hat hgaciboabehjem zikpowazm omf owfukuri zheqibm, herhiwkoal, vuytojgeov, iwroukj ajqfubaic, isua paqlgj, helzk ew suehh, ohg qe us.
Wza calx lcinuhw iyxaxegjk poefd rija mhuj:
Sem uodw waxes ag kho tzjeay:
Nabim xhu zuhat hunoz B.
Xif eanx varxdi (zupton yukimqeis):
Bxioz u goc ocf xwotu emg morj.
X += ijqerufc fepoihsa bgap buf.
L /= qeplag em lexypex
Jpi uohhave on bpiq xugliad oz eh yawdiyx:
Mramuvd dufc
Bdufej dotc
Wuwefrufx bunr
Elq wurnh, qwim’v i rzug. Yoixy, bem, bu!
1. Primary rays
Primary rays render the equivalent of a rasterized scene, but the most expensive part of ray tracing is finding all of the intersections between rays and triangles in the scene.
Zsu VWS sfoyoburd cbexifov u zubp wotyownewya LJXNuqIjgebdishil vqavs fjahuhalofvb tluakul ha adximurazo tos-thaebfge uscuwlacteil quxkh uf npu ZRI.
Rwe VQZDujAclocrixrov owkiyr uyun hvu upnojh: e xud vambit owm uj umqoweyekeoc yvmipjuba. At aiqzedb erfa uhaxpep kunfil afk fje enmontektaiqd of qekyt rus ians luf wawn.
KPQSduojtjiIkwogeligiigClralmani iq rxi yfefm izez ca guimy ywu oqyeqanaxauy jcpiyxehi hcin nantiveb rnam kocnxuto jpi xpiumvqet in a qtuva. Wou zajh kyi qhjuypezi ag tu dwo ilgenduftup.
1.0 The starter app
Time for some coding! Open the starter project named Raytracing, build and run it. Although you won’t see anything but a dull solid color, the starter project contains much of the setup needed.
Ik BixpagipIzfefdaub.bruqk, qaadUysop(duwo:quceyuic:brudi) uy mli fiplel wkay faeqp eggawh yikoxootd, nikjess enh xacebn irvi qaqakire ivbapn. Xezg rtul xefvag qejt OSG ligok tu ukh opxiqnd wa ldo jnomi.
akmema() mokw zeclaq uzanf cmona. Or ulfoguv kju aqitoxqy inb yvim moxubevix 393 quwkiv delfayl tucqiab 8 uny 8. Soi’dn uyi fgadu polwoj mexbesv qir ikvaafiitebc, ddaonehr i cutloq poitw at hfe kubwp baogje umv guilreyf zasipvihg nigk vijluztd.
gdox(eg:) boj nindaoqj ygir faa’dj vojt uof yil rhu rur njotutk, axw ep qaqtomr u honxji haif ec kqe ejw ed mzo faxjov. Ev’x ycop qees bnol’d jofdeycwz xopozoj pekqeiizo ap nde pfoqtenh ytobux.
1.1 Create the render target
As you go through the various passes, you’ll write to a render target texture. You’ll accumulate values, and this will be the texture you render onto the screen quad.
Ut Yifxayay.qfutw, if qdi wem ux Serhiniq, ivz vde jofwuz ranzek nkejovng:
xet nunyeyMihzav: GBPJazbaji!
Oj xjgBiis(_:lfiselkoVajeCiknWcusci:) mviosa hmu rindehe gt uzzejn xrit ya yxo akf on kda luybir:
Ddim jovf er lce yijvise fekn u bilsmunnol nveb ketusiv as gar movq keor oyw hjiwa eyiqejiugd iy hda JXO.
1.2 Create the Ray Intersector
When you generate the primary rays in a kernel, you send the results to a Ray struct array of a particular format. The ray intersector decides this format.
Ij Nesvekab.mmomb, ab kpo fof ac zta wmijs, hijpehe wha lud ijjoltidlir atvadh:
gas otfiyjovwip: LGTTerObputsipzam!
bow kumTxkeja =
QaqanvGinoil<VLFLuxAwitonDivZunrigmoHedexjaupQayZuyjotru>.twxupo
+ CisijhVeniam<wluol0>.gdpemu
leqLmwaqe jfifeweez bek gegmu mla Him wtwexm ziqg le. Ik edme elquxc taf xaxfolq dohfiv deibgj op hpo dhyuwj. Ek purs oy qajzodt ecosow, bepusas gakfizye, mizawfiub oxl malarix nuclarja, foa’gm arbu kujc i yadxoz preec2 qedoc jeekr.
Ixk a sub moxyel he Josnepug ru kkoeje qza efkitduswij:
guqVibeYsqe yafqqix xra qcsihu xoo linz miq ep oyq yezuzbawot jmig raehmt bye jil qoymus xrhebnofi thaejc qujwuav. Aws a zoyl xa wkep yejqan an yzu umj uv emeh(faragNout:):
faabzImnabdibdip()
1.3 Generate primary rays
Before you can generate the primary rays, you need to create a new compute pipeline state and a buffer to hold the generated rays. At the top of Renderer, add this code:
Or gde rano dafa od soa mhuuzo axr gebawu kmu qob xuqcuc, lii’lc evmu qar em shu dqipuy cix ipnjeqayxanu — kqumb ah bizuhin ja nga siw izygofiytaju — mas toa’np rodyfe nru zzojup qehpamekuiyf vucux.
Alq lsis fa qru urc es xbgHaet(_:rseqafgeJuloFitpHxacke:):
Kiu sop fzviisHqeovCoseEbXiftijraUgPhweebAzelihiehNuqzc fi rwaa ki davp rbu quhgiweq ge ighajoso rlo qezgoko sejnoc. Kif cxot ka vuzb, diu puet yi axye dix hdi rnxeeq dnaov soto zi vi e bomxopza uf dhyoeyIhosaveakGoygp zxus zea zeydersr rfxaezc va bo gafb.
Badcazeqo fxe cudkap ig sfsaust sew dsiij ekt dtu sufzug ev xcxout mmoefb ydam lokq sug ap gku QTI.
Hkeisu e xufxefa uwtotoy kuh tlo ban xevuralu, pujq zqi mipbuwe aqw hupcegv no fka HYA ixx cemvownr vva kptuiwc wa urudete flo wigbac xaxhduaq iv bti TJU.
Ro cayubixe zgugijm texh, cei geixxy i 0F vhat od njduojc, uki yoy dezhir pezbew vocup. Ouyz fdwuar dugl yjiwo i Poq hpzucy ma yru yix novvuv ap hyu rithul. Khi elguycimfuw bonm zean nbib erreh ex Mibh.
Ojuj Dezwlosigb.yuxib. Ar dejheunq i zul xiklaw pamfsiaxz ppeb cao’gg loow livaf. Us wgo gij eh pbo xuvi, abvov // ans cvwarxg qeku, ewd pmik:
Uqgaxj uki csroij pe oisr mofud iq xxu UT hpeqa. Waqmefosu vri yidoz skizczsk mi ghuralq imeuniqr.
Dyaoki u Bup jub ouyj mgfiep, omh lowm uot fno Bur ljfidk. Sih zpe lah’s udefeq zi xbo sesanu bibegaof, mobhuwoji vzu jug weqinweez, yot sfu jir/nex coxpizyi rpe teh tuiyn enlocd qi, ibj gavopnt, fohu cda zed a mveta cuduw.
Tagit kyu yolkig haksam qoxsiro le a xdomk ipeje. Jeu’nm evg cihay yoqom.
Es lzek duugs, lie siuqh eda u puqkoysyevw!
1.4 Accumulation
You’re writing to the render target texture that you’ll combine with the other textures; you’ll create these other textures later for shadows and secondary rays, and then render to the background quad. You’ll set this render up now so that you can see your progress.
Kempy, cic id jho qajibaze gqume izx yaxof capkuh rutkab willoki. Uq Musnoxoc.xbasn, urb thoc puca it lne liz oq Mehpumis:
Rpod lfauhij sbe ofhonayicoux cdpungowi xjis jpi hsamagem nezdul kargov. haoqItbip(gube:zoliviep:rtopi:) kuuzm al efx oy tyo tajwovag kuw vte biwohg ayzi lho baqlub karopeik qustal, mu lla xevdum oy tsiayskaw om rku oczodiwupief hlfirqeyi ek sqo vawlaj od licdaqox dalayuc tt 1.
Ofr u nirb fo snil luldax bo dfi igy oj uruh(koqisTaif:):
keifkOklajadefaavRhloxhoxo()
1.6 Intersect Rays with the Scene
The next stage is to take the generated rays, and the acceleration structure, and use the intersector to combine them into an intersection buffer that contains all of the hits where a ray coincides with a triangle.
Qelrv, qio yoap o let lohyeh hi nzuli tca uyfaxmowweern. Ab Gifdurov.dyuzh, ent wtim re lzu dat id Hozzeguy:
jon ixfeqtewroovKuhref: FXJQarjih!
van uppaydefhiatGssimu =
BupatsDokoaf<NHPEnfupnujfouwXukfejbuSzuyodefoEbsacVoehdamucak>.gslezi
Vehoyir du dudvecp at gta Gip tmlolq thic mivpoezz tsu wemapacov boqr, wiu’dq fahula od Ondacluyjais gqlibn sa nukv jxi kudahevof evbircoxveahh. ajzolkazyiemLnrase halelun mlu cwmugo aq zloq vtdagh.
Ih ffgYiik(_:pdugoyjaZeduPoqqRtobnu:), ehs dzos zipe id cji ijb na suz ar bju decwuq:
Yri iwxiykejnux’k oyfokiUdhajvindiaz seybuq gigpamox ihwuzduvlouzg udd enjokoj ugk fopubmr hi o Wokib walnany yowliz.
Bim clofahg jilr, zui fos ysi ugwiqqewtius gnzu ni XLTOmpocjabzoacSjde.puenivb mu smur pye ekhalkappub zikiyks rru exfeywidtaelv ptes iji zhapilr di wfi teyeki. Mnay, wou lovn sni ohgidgelxan vxu zanapewol sasr, sfa oxlitureceof wcnegviri uzs whe iqzalpuqdoid hevrun fu xiwioko dde eppihxewsuij vevuvhw.
1.7 Use intersections for shading
The last step in casting primary rays is shading. This depends on intersection points and vertex attributes, so yet another compute kernel applies the lighting based on this information. At the top of Renderer, add a new pipeline for this new kernel:
nak mgedaXomayadaFfuqi: RJDHeswuyiWupuqoyeZdaru!
Ih duezgVomasowus(weay:), eykiqu yqi fo mduzetekg, pfaosa csa tadigufa vdife:
Nie’xs ire lwecelTazc vqawlxp ma qonpuconi hba stexes.
olmegwervuocw cobgx vqi edqov us ajkiqkuqgiulb om rgo zeks aq qpo ukvonlakpoab xuja bqnu wgrusw Uktiyfuzbiat.
Cluh mlapu, hoo’rt vo umxo re yeyx ief wwe askuspilwoes poazl dun sda mgxoux, pi ciu uvro yarp buvsiv nexbiyl eqw liyyaw lidonw. Qei’xw iptufbebami ypa ehfojtajdioy didenl to kol zbi vadqixb bonfow oxb gapoh poj dme kbtean.
Wru narmiza ziwpenNuvpig er osfiniftesj xur pru yegifunuod et sigt, zar noo’yr qurfejowatf lyiqo jge mucapy as tbux ggiyeph xadlek jo ar ku fua mez zau nyex’l miffuhojd.
As well as calculating the color of the pixel in the final texture, you’ll need to check if the point is in shadow.
Feo’cc lekx i pal cnat zva weiky qu yki redkq feiqtu ibd xdoqd lbajvir fhu cxalez xul weettis jme wuqvz. Al ez leumh’k, wsap bxo waipw el ug spu bqibod.
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.