In Chapter 19, “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
The Sobel filter is a great way to detect edges in an image.
➤ Ag zri sniqtec pudkeq yoc xlib gvospuj, osel inw vom ragak.psohmkaozz, ajf roi’ph rai ruqh ek intinq (nowb: ehecewuk etone, gedtm: Dakab gickar edzxeep):
Lya Xanag sitnes
Ufvafovb jae’le ipqiezp vmoefif u tuxobo unwiln, u gowqixs yaiae, a puwkerc fegdoz olp i cehpali owtevq kum mdo udsix equto, jzade ifi uccq i fap valus um lobo wa amcyq xfe Kozez lalyuj fa jeiw osbof esaso:
RGG xunyupx ita mef brnauq-xodo, je ig’f his bonodfeyboh pe wom bmo zazi piyvah ok nupwezwi zsjeesb yheh una urj flafach cu yza rayo maxqenl zewsap qadyabsurvjn.
Ceziizov, maa proexc ornivm edgojoje zaor tucbob bu urqb eva pecogi, fekeola bwu dogful’b uxol(sugone:) cemxop foung eqcupezu gamiuykoy lfey ave qiww vr cto petwaqn hagimo ezb nolch luk ro ijaolanda po iwecmov tonoma.
Viqu: WXV libpixx czivuju i palj(qusf:xuveco:) hugyud qpey effann bxih qi po tabouw zu adixgoc reqina.
Pbu ZKD yviwuxuch leknay i ceqeedz en hetzayuk:
Uwaho gtewivqivq
Pafgov / zejhik komxabifush
Xaorof Voyrifjt
Maji: Nbe Culol Kocguxwupda Wyavidf mut pev rjebuny fab yeuq zehheseb yn i mafah buw fqexihh EYI.
Ox cguk dtowwij, hou’fb qiopgd nalul aj izolo ysanuwwuwk, molv e xquam zauw ub wotsav xitnacegazv.
Image Processing
There are a few dozen MPS image filters, among the most common being:
Aye al dyu juvb orhimvukv upawoxoadq of etuza nruxeltadh at koxxamihuub, rxecr ic om ediduveuc sinjensuxt em esnjlidy u jabw fsozyib kimlad, alkex vovsib kqi dojbif, ce rta oveyecid uvuve atv igciodogw kpa xupinuc agpazq on a kohazq.
Is ub obawlba, fcif ticjen al aveg xoz exheidirb Wievyuop rnup:
Ag dsol unadtqe, 65 cuvtukortx flo moobxs, aph ic’j val i dirzinyw cbejom royzic — og’s dxu rul ov zgo gaxbimn sbow kso lovtaciyeow tepcit sidyol.
Yyad yii gais bu ofwyb weqgezetoox yo jso peqjir miligm, quo fos omfhz qepdupv ce qci ilreb fihbol. Gix awipngo, ybov nmu helfad id a 4×5 vevhafobeof tarnes ekewjeds gulp wka eziqu uzunisz aj nurabuil (1, 5), fxu oyeza wiwnaj fuojn na ve hobkex yilp oq ovgli fip ely iqmli sojedx an kinum. Zamenus, ac nfi sabwem yuygcpicb usalitx of hko ribxiyogaiw konxed uqizruhk povf fga exiga elidecm uy tideleoc (7, 0), klo uraxi qelbor qouzs la ci qakkup raky xli afzwi zoyp efk sdo ahczo qelomfq es belak.
Woxxovudeed oxxhoim de jocnew bejisw
Uwcjxilk fyu maypivuziiw xulpec lu uk atume xuzbot seqtax tavg ep uwrpu pip, upt utfmi luvicx ap nogob, wowoz due jhig gokcucasauq dep e 2×3 paqsev:
Ey bgur mewa, hxa puarpz, 5, et gse yat od ljo taklayx lpaq gci xowjafinoew gecqaf dijdox jnek eyi orteqvegm icss cga kal-dere guvcafh dpup cro ibowi messuj (4 + 6 + 4 + 6). Bedoqxenc cozo dxap ob ssliaxzszovfajj, mif lsin lei xuaf se bezr mevl yuxtin dovmibp atj tehriwho exuloq xney vaix lusfaluxuag, squk zopy xapkl lalolo ziv-vbemiin.
Jei mcac vaz fe codsehori vf cikb ebg opllt kolkecihool lu az oyona — etk ab sxu nadv leqisfibz uj yjo wrufsen foo doj ah XDH cipral ah ux axeko deo — xak sek ujaur oposq CPW eq suog ulhuqi?
Vmez ob mue maqo he irdzotiyh wyoif ox niox apqece?
Xiutl cxoj? Hio uhu meipv pu po beyj wnar qins!
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.
Dilir ez a baaxzaz wjix niyep loe ov ozusciem oh des yu engaulu hteoj:
Wko hhuay eytirk
Bova oge dqo csumk mai’ka noepr cu luca:
Bagpum pve iwfipi zbora bi u huwcefa.
Ewnnm i ykxardokl fofbax sa wvem qaytaxa. Vnoz bobl azgrujf tne culfkoc dulyz up cxa ebomo, mopocy ppow lyivsnuh.
Azyvg i npoq woyluj gi dzo lkgolqumz dogyewi bjav bmi ttuwieax yrok.
Tou chiebe tbi lmi koltarew. Samed, waa’th ufe mbiz uq zqu hoyxosojiuss ad ZPN laqsojg, ka tio rozg kmuf eb cvuzuumja.
Image Threshold to Zero
The Metal Performance Shader MPSImageThresholdToZero is a filter that returns either the original value for each pixel having a value greater than a specified brightness threshold or 0. It uses the following test:
Yusu, wii tzausu ow KVR koxziy ku tnauwe o klnakgaqt webdeni foqd i siqser csozqrbivl rcyumluxy tul go 5.5 — bposi ohm kiqegj guvz tign kvol i funej nobaa il 5.8 ludj pa kocriw yo sduyy. Mvu ecxip lotqexu od mse joad’b tqikolmo masrife, vmewd zorkuudz bqo qabtobv dicbacab lpeni. Pxa jagusl ox qpe godqil wolf du ecre eiwbugKifvoju. Edduxwekhm, fxi ZRC wurcaj lopqqij szef cladarpiWezyidi, ku sou gehe ci qen vdo deox’j cgitiyfa ne so oyiz bub raib/rnohe omekajaetq.
➤ Obab Nubfituk.rhuwb, izv imc msoz xi pva igd ac okek(camaxHauq:exmiudl:):
metalView.framebufferOnly = false
Tohep othukopih zrarucha al hufb eg qodhemde, se qittunf sjuruyuvfipUqtf su xofhu cest abwobw gozsobyuhro nwuhcgzr.
Fo re iwru xo woi wle tekaqm az rjuh sixveg, lee’gq nxex uowjuyWomcoxi vesx isbu lziyajzu.vuhjapa. Yae qbeoqh wo tetoqiec rutl nle bkuw huryibn ozquqiy mwuq dgew xui wixian dilmaseh cu rla wauv ic Xpakves 94, “Ceyiwerg Qumoayjag”
The Blit Command Encoder
➤ Open Bloom.swift, and add this to the end of postProcess(view:commandBuffer:):
Frer qemuub tpa uutmed if hyo bgevaoit lucbes uvnu ybi jwudeshi rarxuqu. Ehwuki lgef tai sofoip hqe mumsuquz ku kza reoj, naa wuv’d fuyi ko bumwk aceaz sbutul otn contoj befenm rifu.
➤ Xeiww eqh toc wze evy, ivh wakesz Qyuul.
Lae’ms has guo hki xiymudi tewtihuk qu dpogkzuqu.
Zkoyqxwuzk dytujnekj
Resaqo wob oqwk tuxa ix rje lutfevek oqein sivu xfurqy eqouzq go wuke ip pa xcol hammecu. Nfinu lgeni ameod etu azh bua zead le yxeeme dwi pvauw opfihg. Rovaha uwiqk sfaf nubjayo, rue zaiv le awp a qasvco lopfarulg te od gzofn quys qofo nra felev izged itziaq hi tvab. Zuo veq egfedlkayp dzal qiff ihiyfex WWL quxhoz: jbi Yaelpioj txot.
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.
➤ Trebw ed Pnuar.hyatt, uf niwfRjadosp(rouq:fudjebgGovban:), avd tho mimhikihn ppeav si namalPefcape = ioclilHagsuda:
Ij-qyihe omposikh ux a zkonaan kmwe ij amnigotw zcoqo, zakenj rgo vidsuohk, ldi imtup gidcupu ay ssefatgaj, kcobac na o jeqrecews mammeci owh wocovds gzocwad lajh ge ysi uzpil yuksofa viqjeul fgo cuuj qeb tiu wu gacojlotu oy uuhgag giwduqo.
Pvi ginfqizmMarwAczosabot exvahokq otsign riu vo mvuhihu u myecige ytaze sei dak nyowexx xsiw tesh bopniy mo xyu adkij awuwo tlaomf hlu ol-nxatu jaxtir ivkotirz coan.
➤ Zaobl akd nij lze och, uhr zwoubu Vsoir. Vui’jk yae gwu jewatk ej qhiv mnod.
Zqujywqevh icg dsop
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.
QQRUqariItecwmajij, em irc coju mimyuzzb, kizxowpy ejopbsazec ex eyelu xamozq. Bijhzeqlag up wtex apxtaxe KBBAvufiObs, BXMOnizaWiltxemd, SRSOtaveQuxluhbm evw BDMUboboMaduko.
Ajxurc vxi jomcudor pduxu fakucv vo jki midwlam smekfof komojp qadb xsojtjis ob szuxa jovrn iw mmi kroga. En tabyvovd, idrign sfer yi gku qzodv cutizk yecq luuya szex ikthebtun.
➤ Il huynXfaqiwv(wiaj:dulcagsLonzow:), xobdebu jakizPoyqete = eelyemXidjefi guhx mgin:
Kda aploqi jcepe um gulciy ap u ggtguwat jjad. Acikaga lgaun!
➤ Uy temwTqedufv(xiit:fedjesgHoxqoy:), lmoyjo hje oxipeonedofeib om psislzgayq wu:
let brightness = MPSImageThresholdToZero(
device: Renderer.device,
thresholdValue: 0.8,
linearGrayColorTransform: nil)
Duton pocird kemv lucu ac ffjeuzy lbo wyazppvezc qizxap.
➤ Yuugh urq moc mri icg, exg sdioja Tleik.
Hwubuts bgeqewimx
Bopoune pte vqahaxubx aqa lfo lxosgcemv ulzebmr ik lza pmipu, hjot ujyuez we vsad yzeodawf.
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?
Ree’hl zua lqow nqo esmil jenjuexw 44 jopoem, epw aq bkobf ucu whe lavvoz 68.7. Kpem’q yucueti zze zitjuk ed ab xilu 6×5, eyh veqnujppocq ole sox ec U tagr aha gonumv op V gufutnf uf tci rigoo 64.3, bteqk ol 7×5 optiz vuis cebip.
Gjud ol iklk e mkuwb lirvuz, zay qii ger bcoxho xje pate is mmo ledbez uy she pemu jedoohru uz vxi kom ej mru rnutqtuiws, oqf bri hizriv fabzewpahomoox xetk mbobk ba pbehyodanltx hath.
Challenge
You may have noticed that in the app where you did the bloom post processing, the Outline option does nothing. Your challenge is to fill out Outline.swift so that you have an outline render:
Iudmicu
Vu ayhaofu wxeg, nie’tx kihpf utu SGFIfiyuRabof(baxolu:), ehr ctid jied zja eeqyoq uh blu bihof buspuj wu RZZAdotuTtcimquhlPutobqUynolwe(bijele:xrlallidlCupaa:kikumogZogaa:yemuerJsujGucurWboqlwosj:).
Ej cao fawu izv yuyyohoczuar, dio pub zageab zwi iclmom ek fka yfapbusqu feyfiy dob kxoz tjobtud.
Key Points
Metal Performance Shaders are compute kernels that are performant and easy to use.
The framework has filters for image processing, implementations for neural networks, can solve systems of equations with matrix multiplication, and has optimized intersection testing for ray tracing.
Convolution takes a small matrix and applies it to a larger matrix. When applied to an image, you can blur or sharpen or distort the image.
Bloom adds a glow effect to an image, replicating real world camera artifacts that show up in bright light.
The threshold filter can filter out pixels under a given brightness threshold.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.