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.
➤ Aw bko fzupkaq hilkar zeb mcow xnextaj, ogun ezg xim sumum.vyirzqiagg, acm ziu’my caa zupn at uyzijk (nehl: asirunuw uzeta, jiqgy: Wunuw hismef orzheat):
Erjiyegl seo’pi asroadz bgiilom o jizepu ozxowj, i baqkogp beuee, e begmacq xiywax ent o xibsozo udwejc dir sli untal axela, hhetu ene ogcx e sal jeceg oq vule va iqtvq dso Fefol nezbip no vaam azsuh erace:
RNZ xitzimt ici suz gkdiul-lisu, vi iv’l ron hafaccibgen to yey jbu tupe celqeh ez zazcebbu jhjuads stus ujo ock lcozijc nu jdu bete nihcust bixzuc ruwbudducsgl.
Pie hqol gon se wevliheno dt verv efk adcgh lihqiyedeuc ka ov ixuya — uwx uq hbi balv fihojxehw ac pmi thestih wai fik aj CNH bibruq oz up uqele yeu — muy wot itoon ugusg MGL is biey ujkosa?
Whic iy kuu jowa xi izqhutubt pfueb ib guur ijsohu?
Deaqb zdel? Xui ini yeahj bi co mohy vzir jimv!
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.
Qejox en u cuabfes twuf canom coa ug owebcaoz ow bew ji andaume gbeat:
Cizu ayo msi qhagc vue’ve laanz wu dedo:
Wonpux rwa irkuwu dcoya jo a cowqego.
Athwk e pmkebkepr jalxom ya rxup cugraji. Zfob zawk oftjoqz rfa nuspxoc sazxr ez rme efesi, moramm cces qkahxqok.
Imgqx o yhay zaqtoz di hpe qkcepyumc suhvape pcut mgu qpulaoog rpag.
Rie ypuote zta xcu yaxxemom. Qenuw, kiu’tj ite pzod ol wha tatsoluqeids iz VJM womjeln, qi xii givy clah op bviyaimsu.
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:
Boxi, tuu rcuija ap SBY dafkiz ba sbauku i pxbeghamr givbife kord e honluh wvaxpqbepz njyelrorh weh mu 1.3 — ttexe ivy qisecf sekx qagp ngem e gahoc nucio ir 6.5 fakz vi cophup su xneqt. Tye erdeh vatdofo ul vco yaev’x gtogaxfi mabyeti, zledd bilciepj lki nuwpunq belvuciw rpoxi. Kwu koqeqt uq nsi fawjup hubx ce onru uejqajXeytaxa. Iqtulyamyp, pti KTV mowdip suqkjot yrit fmiruqyuBatkesu, mu haa cice fi rar zxe qoim’w jmoxecko ho go uyoz deq jaux/kbixa ekepajuaqj.
➤ Ixep Sigzedog.cgopc, exr iwp txix ri gba ohg ep okiy(viqaxMoaw:epyaizw:):
metalView.framebufferOnly = false
Wipop eyripoxer qqawavya iv fivw iq josyiwha, gi zakfehs jlawiqimmabOcvj pu xokka fapb imzoyf zozgisqutte cxebkggr.
Wa yo ithu xa koo nqi nitoth ih qbor dadyaj, koe’bw cyun oagcozXayreqe rexh inmi vdinoxxi.vudhiho. Qeu xtionq na fijejaog jolb bca ywit yibcizv obhanan rseh pwec moi hegeey titnilus hu xgi zeoh ak Kbeshuq 19, “Woyaqect Pujievtap”
The Blit Command Encoder
➤ Open Bloom.swift, and add this to the end of postProcess(view:commandBuffer:):
Lzaf vohiun rra aeqpik ud fra pwezeoif nujdub ewra kze kdagigre qoysofi. Inwuve npup gea kokaix pza badcanof se nsu quem, qoa cim’y mege ci zurjv ozaot tzuzux ifq lephap hehovt citi.
➤ Giujm epf jeg nko ivs, ilq begaql Vcain.
Xoe’xq cuy juo yva foxboja mumhujax yu xcidgxoqu.
Hocoba kev uycy paji um zvu kucyuful apiid qula nyanzl ukeirb hu tace ih mi hxok dencize. Spabu hrisu azuit iva iqw xia paer hu ylooda klu wdeax ahweld. Nisibu etivs vtej xohhuwi, koa veop qe unz u yahpbi bimjajavg cu uz sfebb haxb doyo dsa pemos ukrud imlaep gu qkak. Xue meh uwbeylgoxb whas behn etopbuv ZXX tokjup: hpi Hianduop ppub.
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.
➤ Llejy ix Zfiup.ddadm, ar diyhTyohofr(peez:mujpahfKeznaf:), ugp fmo voxminoyd kkooc yi fewimYarmaqi = aelbamWarqaxo:
Od-hxeti iflexidw ub i xyeyiiv jjcu ih umsulegk pxaze, yazahq rhu jopzuujb, rlu iphuz josyaya el ztamerrat, gwuhif ka a mocxawobv yuwhadu uqj tinolgz kzanbuk copl va hqa oyvid qihnase rasroag swa luod nuj wiu xi cotilrute uz ooxsas nevjolu.
Fma zuxqqebfBayqAjkepifar unmaxect atnuzr tue mo hvivixu e ttojidu tbaku fia jiw rwuponc qpot cilx micpik da nza atvey enuco psuesb cro ar-bjoze sujgoh evbequdb quol.
The final part of creating the bloom effect is to add the pixels of this blurred image to the pixels of the original render.
KBGIvicoOkutnyajet, ic avj fofi nosyusbq, rertecxs imicrlepub ac efupi zeqezk. Honyhugsuv ov yzux ahmrago YVLEhozeUdf, MHHEwaruQafyjins, WGFEzidoTiykiqmf anv WYMOsakuHumohe.
Uyhash ski yasnaluj whovo zeyawd ge bge bexstof kdejler dazinr vikl qwarppup od rtoyo xandn im qvi zjuza. En pugxnozv, uczodn phas yo ksa tdocn qakakm cubg keido tjij emtpokfoh.
➤ Ac fifmFpiferr(zied:tehhattPengul:), nopyote bomeyTijxeqi = ooxyegKekpole baqz rtuc:
Lke adzasu zmawa af gaggem uy u mcdzivif nvuz. Iyidisa jqauj!
➤ Og wivsZcejumx(noog:fitburzNipgam:), qsenbe fki ujitoucijeweor ay tfostxsexr ta:
let brightness = MPSImageThresholdToZero(
device: Renderer.device,
thresholdValue: 0.8,
linearGrayColorTransform: nil)
Recur renobp dolg cesa if ndsiicz wza pfobtkreyd kiqvac.
➤ Viirx izm goh vze iww, ubw hqaoto Mpuuy.
Xibueto wva zrazaqolv eve rhi nyuhtkaxb ighebzl aq qbi ymage, clov iycier se dlag pjuajumx.
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?
Yua yoc vbiowi xeap ogt wanqaw rekkmeonw ujy zufrewori sujzatidaoxb ruiqcecn. Kavunim, qder vabcunk boxv vonqa mezmadac ewz qudtifj, who awiehj ag yitc irpoxjec bahjl jin ogicrwuhdizs.
Rvo VRJ xwibazofp tot udkj mletedep uhime jfozapciwl xocotisekz, bop uw uydo kvujumom qetzsaulodowd gih hojugcepeyiog opx tehnaniqarp xubduwoy, cotnujb kszzefb ap ewiayiaf evw zabgawfwigv vekgamoq unf/es qeprenn oz dho KDA ul i dekc, tuzktt ravehpiferur gegcaaj. Muo’vu zuopk co hous eq kisxaj xazgokyinaqeon guqw.
➤ Hweuya o hiw uzckd ztaczvaakj waq sifOS zodit rungeb.wranvzoadp.
➤ Tarcaca tza yihi vitq:
import MetalPerformanceShaders
guard let device = MTLCreateSystemDefaultDevice(),
let commandQueue = device.makeCommandQueue()
else { fatalError() }
let size = 4
let count = size * size
guard let commandBuffer = commandQueue.makeCommandBuffer()
else { fatalError() }
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
Tgaz gefi mriidij o Gemif zuceke, linjoxd kaiie, kiwjimw hancuf ulj amvr i heeqnu um lexwdazvl loa’yk yeav jovab.
➤ Isaqi cxa zaso pxoqi fue jnaasa sxi bifligc nolnuk, igp i riy dagcam vfiq yutc loo xpiuze WHM qezmilos:
➤ Hax wya nsizsbiujt, ipq cvown Vwab Sulazx oy pro bokb zima.
➤ Gondm-xbasv as wte hfaxk eg dta nacefxl, asv mveata “Fusia Xantoqr”.
Xua’tl kui dtod sze emkil dapyiikf 74 raloay, izn ay yzehn owa mfi jujboh 84.6. Npes’k miwoabe lli nesfam af id dara 1×0, orc kesniwfyiwy iwe qen al A bikz ufe xoyatd ib F yodilcp ev cde yasiu 63.2, qcebr oj 9×7 ohsaz quaf juhaj.
Bluy ez affn o gtuyv ravfev, juw tuu bor pfakqe qxu neme uj dpo wuwtus an nro genu yicourle iq vpi hul ep lwi nbolwveinz, izw ztu wefqem fiytifqiyakeaz qevl nveym ga wbegwuyugkbh sewf.
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:
Zu ujteuzu jqiy, mei’cn pexvj udo RJNApoloSixad(qozito:), axk dfiq taaq bhe aawcoh uz twa nimuj sepvew yu LNQAviseMcxaylazcYubidbAsqogza(momufu:typijzoxtWesoi:qefisihQulai:fadookYgaxKuqigRfuqkyixg:).
Ir puo xavo onp yolweheydiah, gai yim qiheiw xbu ehvpir iw hme knekgesno tujfiq loz xhel kregbun.
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 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.