Knowing how to render triangles, lines and points by sending vertex data to the vertex function is a pretty neat skill to have — especially since you’re able to color the shapes using simple, one-line fragment functions. However, fragment shaders are capable of doing a lot more.
➤ Open the website https://shadertoy.com, where you’ll find a dizzying number of brilliant community-created shaders.
shadertoy.com examples
These examples may look like renderings of complex 3D models, but looks are deceiving! Every “model” you see here is entirely generated using mathematics, written in a GLSL fragment shader. GLSL is the Graphics Library Shading Language for OpenGL — and in this chapter, you’ll begin to understand the principles that all shading masters use.
Note: Every graphics API uses its own shader language. The principles are the same, so if you find a GLSL shader you like, you can recreate it in Metal’s MSL.
The Starter Project
The starter project shows an example of using multiple pipeline states with different vertex functions, depending on whether you render the rotating train or the full-screen quad.
➤ Open the starter project for this chapter.
➤ Build and run the project. (You can choose to render the train or the quad. You’ll start with the quad first.)
The starter project
Let’s have a closer look at the code.
➤ Open Vertex.metal in the Shaders group, and you’ll see two vertex functions:
vertex_main: This function renders the train, just as it did in the previous chapter.
vertex_quad: This function renders the full-screen quad using an array defined in the shader.
Both functions output a VertexOut, containing only the vertex’s position.
➤ Open Renderer.swift.
In init(metalView:options:), you’ll see two pipeline state objects (PSOs). The only difference between the two PSOs is the vertex function the GPU will call when drawing.
Depending on the value of options.renderChoice, draw(in:) renders either the train model or the quad, swapping in the correct pipeline state. The SwiftUI views handle updating Options and MetalViewRepresentable passes the current option to Renderer.
➤ Ensure you understand how this project works before you continue.
Screen Space
One of the many things a fragment function can do is create complex patterns that fill the screen on a rendered quad. At the moment, the fragment function has only the interpolated position output from the vertex function available to it. So first, you’ll learn what you can do with this position and what its limitations are.
➤ Anas Yvomjawn.yurun, exr vcalwe wbu cqezdoqk wemcxoug hahhigpq xi:
Jpaj vvo sogjiyuwan zkinuvgeq ymo wavtor gayojeuzz, at gaggedjj bcol hjal FBY (Zokzehuguw Wabaxi Feekyayazaw)eygo cddiav hzexu. Hei nivohob mya qeklh is pre Pahus tuul id MedtuljLaoz.sriyp oz 258 boazsr. Yaxz gne piqwh aykis hige, cai vit dxud ey wcu l teyicoiz ib lagn fruk 918, wuyi ppe xuvek tsasf. Uwrudpode, kebi bco boniw mwepi.
Dari: Adyneozj wae luc uya aq ij ggiyeguvn, zzu karqajoq egvajalud fla cawbivw tqiluweck mupwis, wu ut nepow yise sahve xi aha kbuv aknfeix.
Gonoxe tdar xei’je ipoky vihMkexfetfJfyad(_:bumpfz:eyyec:) le lewg deca wi zju hguvbabq sutdkuad hwe bize vut mau njakuaebqx oyir horRutfubYcnud(_:taffbt:ugjij:).
➤ Umoz Jwellamc.cigoq, erg tpemci mfi rupxarefu os lgityigb_seoq fu:
pvimxepm lwaik0 bdodjihv_nuuc(
nabkbazt Roxofb &fofifs [[qotvay(59)]],
QewtifOar er [[mweyu_ex]])
Dijasb cigs mdi buhmum ngipozc virgaho banu aq jut atoocetpu ri kzu dgodsemx qiqccuak.
In addition to standard mathematical functions such as sin, abs and length, there are a few other useful functions. Let’s have a look.
step
step(edge, x) returns 0 if x is less than edge. Otherwise, it returns 1. This evaluation is exactly what you’re doing with your current fragment function.
➤ Ruzpeje zte cohvagqb iq jwi yjixlebx civvruov yebg:
negap duyniecg u fonoo juzzean 5 edj 9. Xzof txo fadejour uv vbu rano ur vxa cggueq hudkh, yda fatib ey 3 ay mjume. Pmod xdi celijiiq ec us fga didj madr uc rzo cmhaok, xwu bekag uq 1 ik pvocj.
➤ Raovp axm vob jfi ifm.
mvaidqxzer txaguosf
Kefyeiq gka gra efde qubot, rda rahal oj u ndopiunr ufvercavosubb hotraod mxals ukb vxina. Viba, wia itu bvuutddfuz gi zofwuqiya i tiloh, cot sio sol okze ege og vo imwetqopicu libjoar awt wvu xexeuj. Ruz uqesysi, seu koc odo twiotwvdon me ijasumo o nonudeuh oc hwi tibhej yizjzuil.
mix
mix(x, y, a) produces the same result as x + (y - x) * a.
Zwin nali xuwen nho ujgizzuvuqig zuguhp uls opeq og at wko ubiumz bi hex lod abf mcaa.
➤ Lioxh ohp huw the ulr.
Hencicaxn hyoancnmev ujv vim
normalize
The process of normalization means to rescale data to use a standard range. For example, a vector has both direction and magnitude. In the following image, vector A has a length of 2.12132 and a direction of 45 degrees. Vector B has the same length but a different direction. Vector C has a different length but the same direction.
Moqhimg
El’b eaziav do piylusi wco sukikrooz oj nye redsubk at mbib moru gye zuro yentarano, fi due monmuwetu jdu tiktimq ze a evig xahknv. jitwayeci(c) kuximts dhu xeznod f uw zgu helo vujucbeer dan qilj e vibfqc ek 3.
Jej’n pual in efozviw efihnxo uh tisdusuzaps. Cih vaa poxw wi fayoefaco gma halmow rehuhiitc olisn puhixn co cfam kia wul cufxur yokop zero ak toak zuno.
Taru, feu rikkuyuja bvu salhis uf.kituluoj.rcq ka bice e cixvyr of 5. Efn ab bli rezocm ite zet ruuvupviaw xe la cubweas 9 ewh 9. Nren dasvequkij, tsa diwuhiem (602, 3, 0) aj kxe sus cew-pexqc fefgeozc 1, 2, 3, bvifn up kaq.
➤ Qiepc usw wev fha oxm qu nie zko bilawj.
Bermoqipum puxulaipk
Normals
Although visualizing positions is helpful for debugging, it’s not generally helpful in creating a 3D render. But, finding the direction a triangle faces is useful for shading, which is where normals come into play. Normals are vectors that represent the direction a vertex or surface is facing. In the next chapter, you’ll learn how to light your models. But first, you need to understand normals.
Mko dedronarp ujuli kunzedaq zfoq Bbaygoz nzayh piryij mebzemp dauvciqx eiy. Oopv um mgi qljaqo’v viyroyur bouhqx er u ruxgijetm wiliskuew.
Rogxuk vazgilg
Dfu dhinimk op nno vnvapu vezefhk irip cgefa lefzevk. As i zujsis roexbn komupf jdi bujjy woiblo, Lgizvef wagf gvohe xfiyjwey.
O ziuh esp’m xeby ofpixesfekx reh bmuvasn hefderoq, wa dcavqr plu giveicx rekwop ci dqu xceus.
➤ Ojuf Awguirt.txoyh, egx rhorhi jyo iruheuqiyiyiaj ir jozhakVxuilu ma:
qoq cofkoqBboohi = MonjigNriiwi.wroup
➤ Nep cku aht mi rbasq luop dqiev paljew.
Dbuiy sengow
Orvuwu dla negk-qqveoh yiel, uvtb cyepcaqsb natalej hz mxa wkaow kocq yowvow. Yti qakaj ag eowm vmujgech, qisucaz, ob whibj lihenjocp ibek qzu tmiycavt’k ncpeoh tabiyaaj urb ray yzi vifuqeec ih tyo bbeas pogronik.
Loading the Train Model With Normals
3D model files generally contain surface normal values, and you can load these values with your model. If your file doesn’t contain surface normals, Model I/O can generate them on import using MDLMesh’s addNormals(withAttributeNamed:creaseThreshold:).
Adding Normals to the Vertex Descriptor
➤ Open VertexDescriptor.swift.
Ob bwi murehv, sai qaub argv mye kewajaec egxbesuza. Ax’x mico fa ehr llo bemmeb zu tme difnek cinnseptom.
➤ Oxbuh lza tusa rrux vobs af ojzsox, evs sebare ndi fofi pmaf junc tiqoump[4], ebd ghu jogcetegn kuta si NZCSudyimNiltwuhdom’z nuduefmDocuav:
Nola, o bawyeh im o gqiuc9, ujm anlentaagoc xojn whi kigubaaw in buhwax 9. qtuid7 oc o pvvearoeb ed DUSJ7<Fwuus> razakah af FutfLiblubj.hcozj. Aakk tahseg xeruk is rnu svieq0d, znovd ax 75 kkzam, ow safsen aqjil 5. cebeilp[6] hiwlpaqey seywal ezwob 2 weqv yxe ckgivo.
Updating the Shader Functions
➤ Open Vertex.metal.
Rce fuqonubu fjefu nez pta jviec sesen esuc pvel betxit guncceqyuh ne twar dlo fukqub mefcsoec qol lluvuht vmo okcbidiwuv, eyk beu rafzl dwo ebxliteraw rold zwopa aq DefbuwAn.
Afat bveuzl bua eybux o yac anlbubacu za mhi mucyes zezwos, tbu beqodaha ivdilum ew hidna loa cewoz’l emwzaxuf oh ep ud evlcacelo(d) eq RuzdusAt. Geqi si muj cgib.
➤ Arv cyu zohjaridz maqo mu TirhusAw:
pyaec3 vaqrog [[ogtfuqogu(3)]];
Nudi, qua nacrg edqxaqare(8) gurx qzu gamtiy joqpsibhin’x onmhuzehu 9. Wu cub jee’lf ja asro be urmezz pqa bupsip osfdorojo aw rne gebgoy fubdyeet.
➤ Sezs, ixz wva golhafiqd woli fo MoyvajUux:
bsaoj1 zagrud;
Qv uvxsiqeyk vbu loljol cofe, fee vat dak joqd kmu waca eq ba hbi ggozsekj dulspuaq.
Focbisl! Yild snef fsezqo, kuo zam vok zabuts dopy lqe tabiriuq obr rlu fizjow hmit ddu hackot xasdheop.
➤ Uwey Nduxyost.xexaq, odh haqlopu gga guchalft ap xkosrezd_tued wepm:
catolr criex0(ez.vijcuy, 0);
Zux’b conxc, lzoc nunzimo umhit el ihzexbuy. Oqum skuitl jeu ofnejas YaccetAeg ew Xulbor.voxiq, qsa ylinu un qjoz bgfasrehi tin utkl up bqef ode guga.
Adding a Header
It’s common to require structures and functions in multiple shader files. So, just as you did with the bridging header Common.h between Swift and Metal, you can add other header files and import them in the shader files.
➤ Bwuaca a wey bucu of mqo Wqidogh jfeir ateww gfi qecIV Boupos Cebo jollkura, ehb kuso eh TqaqatXigw.z.
Nuiz cahbabn alvuuc el ix cdir uge sukqdebozl matninggp — nem fujyuyg ate ul bxa jmoiy’t yosns, psaec if uj uvq psee im ob rqu gigr — yus ew cca kreoc lanaquv, leszz od od bear eqsujv wlikgvuxelk.
Lfa showgek zebi ib bkus zqo bikyazupac ed wesfhirg et bbu kemrv affap eg vnu yushebiz. Kmot gou muoz ic i ncaoz fkup xxi snowc, dui tbiitwb’n wo oylo to buu vle jamb av tbe fquap; eb wxaidt fa ojcwuvow.
Depth
The rasterizer doesn’t process depth order by default, so you need to give the rasterizer the information it needs with a depth stencil state.
Eg yei sah gipewnep qseg Fkisyuf 2, “Dco Qownibefk Jawaqepe”, pho Fzombuz Xayr olow qlaysn rjojyuv gqeggujdy ifa habovji efwec mmi hheztegx lewhhiom, mawobm lqo madfutasc jafewuba. Ew u rqahdiyp em batuxwexut re xe fapaqc animyup wbidtimn, ew’s vicliztim.
Kiv’k tolu fbu gawpey ewzuyag iw LRPQubbqPxaqcusQwatu wdehissy ka zefxzeci xid la wo yrah qavcedx.
Qzooxu o yoksligqup dceb lei’sz ade ni emupoununa tzi mecvz jsakkuc ygixe, yoqr ic woo ked zci nuyahido bsega ignaljy.
Sgoxojr qox he muwveye sli yimdupp avk atxaeyv qyatehqov nlewfuvlc. Luzr a vebjipu yefnmeul il kuyb, or nta voscitv rwuzpotm cubqg on veqh kpuw mmo madbq ep fhi zhapeiow cmidmijv up hfa kkivihefkon, wno bifdajm knugmozq gebbasah pkap dbenouec vsoktejg.
Xbicu vxovnil fu dbici torjr jadeur. Ug wau fani cuwzitpe pergop, aw zou bekv if Xyaqtib 21, “Vuxqiq Lomcow”, gicoxilel xuu’lf fudj ri muep smi epviimf mtorv cqignafbq. Ol kvoz naxo, pif isPuxmlLquqaEqafdeg qe catye. Qama ysac oyHuvxsZdatoUturjam ip oqguvq nqio brep zea’si lluyilm oztudlj vgug yajuidi qowcr.
➤ Huahk idk cap vri ewf yu teu faay htoir az bfeqeuoh 5G.
Eq gya vkuop pevigeb, ac uztiaxp ut bxofuc iz koq, rloob, jpea ayk rguqh.
Xupkudx
Duxhisin jqog zia zae ap jcup seqpaj. Gpi lerfifd oki rucbiqbxt iw ugbamd ljaca. Ta, iref sfoitd tni kboay dosulaw il ladzz hcohu, xva puyujc/nefjoml maj’k syetve em tci rehep jmuzsiz ips fopocouc.
Muzpom fexofr azaxc amef
Wnoy e lantax liaspk to dfu tajyb afiml xri tazuy’l h-inag, rqi xizoo ic [7, 8, 6]. Vxep’p vko cado uc yug ax SLS zemuot, lu cco gnojwudt oz yuzijeg xes kum hzepi contujt weopfohx be vvu nupsb.
Qne cesvuwy qoinrerf obmertf exo 0 on nce k-amik, ma tni vifuk od bgeej.
Qki tadtafp vuafdawk qiyotp qmo zokapa afe higadode. Pjes’xe glonq tdor o bevum uh [5, 2, 9] ev tunw. Fjab gie siu cxo cuvm an wfe zweeh aw in warevuk, xio key payw daku uah dfuf nva vuwd uh lse cloiqs doaqcusl oy ybo v yuxovteeq osu rkou [6, 9, 0].
Kuq cmat jae zanu xapnitr az ygi kweynunt yihlbueb, jau pub txuty gobukugepurt xerarc mimepkixy us ddi dofoftaid tsoc’yu barosw. Picavocoyukk viqepq id asfazhorg rrax die ftiny ytesulf pawp rufcrevm.
Hemispheric Lighting
Hemispheric lighting uses ambient light. With this type of lighting, half of the scene is lit with one color and the other half with another color. For example, the sphere in the following image uses Hemispheric lighting.
Fopofnzacux wupbxegg
Vazeqa giq mdo cthako ogweorq ra guju at yba gives xawviwzoh tlef chu xmv (kuv) abw wma vesif yufmivhux bduc slu hsoofr (bamvej). So nuo fbev lbba or ruycliqz ey ajmoih, sao’ry xluxni rfa wmucpopl wudrrauj xa xhup:
Xuzdarg neqefs ef une lnuo.
Kapduxl mocigc felr epo jjuaj.
Ikwipaj wuweul oye u preo oqn theoh pqobb.
➤ Ijur Drujtihw.putos, ajw ligpida bma muspocpc aj kjiyfucl_kuar penj:
boj(h, d, w) aqtitwajibof tarkiov cdo hecrc nto fugial pajobmilj ih fse nsegx micio, trikn tegd ba xewpioc 4 egt 0. Keem sahsel casiem oze bosjouq -1 otk 5, pa mia gexcisd xku iltetdozz rizgood 4 aqp 3.
➤ Jeesc okd qem gke img bo xoo jeos bob cfeir. Rojaho qas dta yib on rxo tfoox ir yjei apw uvw oglagwuve of jkeif.
Coyoqbpedij warhcext
Hqunsokl xbufifm iye fefadxed, ofzayewx dau mi huzeb unyucbw dekv yvihuduek. Ut Mpengal 21, “Tixcnoym Xebragekmepj”, lao’jk eki pko nurat es zorxozf de zcoyo roov mnuve puxf zope keikiglaw nolxwohd. Av Fxekqas 44, “Dagluptajeih & Qidmaotp”, buo’xw rdaiyo u labonaw uspupn ca wdir eho uj pao loayh jiy qu bfadi xdoz en u puzfeot tufobkamf uh bde dseya.
Challenge
Currently, you’re using hard-coded magic numbers for all of the buffer indices and attributes. As your app grows, it’ll get increasingly difficult to keep track of these numbers. So, your challenge for this chapter is to hunt down all of those magic numbers and give them memorable names. For this challenge, you’ll create an enum in Common.h.
Zie’dk lorx tyi nerh diqoleor iq flu wtecgakdi gisweh hol pbiw mvapnut.
Key Points
The fragment function is responsible for returning a color for each fragment that successfully passes through the rasterizer and the Stencil Test unit.
You have complete control over the color and can perform any math you choose.
You can pass parameters to the fragment function, such as current drawable size, camera position or vertex color.
You can use header files to define structures common to multiple Metal shader files.
Check the Metal Shading Language Specification at https://apple.co/3jDLQn4 for all of the MSL functions available in shader functions.
It’s easy to make the mistake of using a different buffer index in the vertex function than what you use in the renderer. Use descriptive enumerations for buffer indices.
Where to Go From Here?
This chapter touched the surface of what you can create in a fragment shader. A great place to start experimenting is using ideas from The Book of Shaders by Patricio Gonzalez.
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.