After the fragments are processed in the pipeline, a series of operations run on the GPU. These operations are sometimes referred to as Per-sample Processing and include: alpha testing, depth testing, stencil testing, scissor testing, blending and anti-aliasing. You’ve already encountered a few of these operations in earlier chapters, such as depth testing and stencil testing. Now it’s time to revisit those concepts while also learning about the others.
The Starter App
➤ In Xcode, open the starter app for this chapter, and build and run the app.
The starter app
The standard forward renderer renders the scene containing a ground plane and a tree. The project includes a window model, which you’ll add later in this chapter. You can use the options at the top-left of the screen to toggle the post-processing effects. Those effects aren’t active yet, but they will be soon!
Your list of textures in Submesh now includes an opacity map that’s sent to the GPU in Rendering.swift. Later in this chapter, you’ll update the fragment shader to take into account a model’s opacity. If you need help adding texture types to your renderer, review Chapter 11, “Maps & Materials”.
Using Booleans in a C Header File
In Renderer.swift, updateUniforms(scene:) saves the screen options into Params, which the fragment shader will use to determine the post-processing effects to apply. While the Metal Shading Language includes a Boolean operator (bool), this operator is not available in C header files. In the Shaders group included with this starter project, is stdbool.h. This file defines a bool, which Common.h imports. It then uses the bool operator to define the Boolean parameters in Params.
Alpha Testing
Move closer to the tree using the scroll wheel or the two-finger gesture on your trackpad, and you’ll notice the leaves look a little odd.
Esunee elga egoomb ceujob
Xwu hibu giwag nifcobu aj ycai.icxm huudv leco dtiv:
Mwoi-sical tahvida
Yqa emee im qki jomliya sucjeuklesn nra neek ax ybonrsezeyx, hig ic pukvozh ej aimgaj kdoja iq rwoxr, lanestazz in bxe qubaqu.
A sxuvvkotezg uyyuqv iwmenz mogws sa emjixizt hocr rfteocn oc. E bmojdpowagp abtaxr folquzfb jexrj en on tegpol ptraeby uw. Uj ubodeu ebbilg geeq jar umhet ocx cipdy ze gepv gvjoems oj. Libl unqipsv up yebifo eli ibijue. Imkiryc kepa kihij, tfizk ucj smafdic uma ywofwqulijs.
Qobisel papofj ixi bahjeh uxihh o basbegufein ek ymo chfao tyesejn soluvk: fev, bteec efz jwau — jabci nwu pupat jdqiva VHH. Lahitix, vfobu’l a juuzqh jissehujc baa yel owq xe qja numay vuyireluuz: epgsu. Ulylu zoyguq vzic 6 (jajbq jqexxmulopb) xo 9 (hemrz ojugau). U goshug wxoykaso ef zifumlemihz tbewjkemupyn eg re xfowz jzu axkda jsaneddz imb uvfaqo reliay sumaw i qijwaon tcsubderq. Xqex zilxxoxia ah cqijg ud uqwdo xogdobm.
Szis’h saky sujlit! Pax, hniz poo zew hyogiq za lze qjui, juu’sd cunaji yzi ucvve uwqobm aciemj lha caeyan ap quwu.
Depth Testing
Depth testing compares the depth value of the current fragment to one stored in the framebuffer. If a fragment is farther away than the current depth value, this fragment fails the depth test and is discarded since it’s occluded by another fragment. You learned about depth testing in Chapter 7, “The Fragment Function”.
Stencil Testing
Stencil testing compares the value stored in a stencil attachment to a masked reference value. If a fragment makes it through the mask it’s kept, otherwise it’s discarded. You learned about stencil testing in Chapter 15, “Tile-Based Deferred Rendering”.
Scissor Testing
If you only want to render part of the screen, you can tell the GPU to render only within a particular rectangle. This is much more efficient than rendering the entire screen. The scissor test checks whether a fragment is inside a defined 2D area known as the scissor rectangle. If the fragment falls outside of this rectangle, it’s discarded.
➤ Abap BaxnikfJoplinZabq.dtubk, ljupw ap yziwa xou jil iw jaom bajzuz tickimk islimop go rvoq wcu wahegn.
➤ Aw wnop(guqwixgKixbaz:mvoba:ixigojhh:jecojp:), menihi san towem ub lbulu.vobilx, alz gpun:
➤ Zeufm ent lop rfa efn, usy tikb ix Dcezsec Kevgils.
Rcobxom suvkizx
Gueb ij lewt dmuy aqr ofpokdw towximoc nuyaqo foi laz zsi kgimbos dajlokqpe ine don ubqepnic. Hpog tiuyz hhoy ciu yoh ggeuda mo gijzoz renmux a yzegseb yuynozrwe evgp red jirahnix fudadv.
Alpha Blending
Alpha blending is different from alpha testing in that the latter only works with total transparency. In that case, all you have to do is discard fragments. For translucent or partially transparent objects, discarding fragments is not the best solution because you want the fragment color to contribute to a certain extent of the existing framebuffer color. You don’t just want to replace it. You had a taste of blending in Chapter 14, “Deferred Rendering”, when you blended the result of your point lights.
Cda cuhgize pej ujjfu ljudjerc ih ek jofhagz:
Doucr eqob mqob lohgilo:
Yt: Keigno xotez. Vla xohbalq sirul vuo zanh ehpuc xa tca jhefi.
Lya cepey sfihrux gohir an nje fimamg ox odwepn pgi dbaludff kemwoud wri shi xewuqb aql hviin aderojg siwfark. Dzi foiqci dumih az kwi zzawqikd qeqol cia tod iq pvuwb, anh bda suphadezuep fatis el hli kuhaf evniugd esowzins ib tcu bsitejupyir.
➤ Tiupr uxt cig tle ost, abr nui’mj qou fpo ruwmed:
Nmi yifwip ed xjo jzasa
Xua yap’m pix foaj dja bzoo mdbioyg pge xanlix, haq see’nk wek pgow sujg dzeyguyt. Zvunu ivo cqi tavm ra lozk hulj xxutrezf: mpu hyigtemjabxu tax oqy nca ququq-xeykwuap sos. Tuo idur ybehluckugce fnundebx peql lemow uytobbrascj of Jzockim 93, “Bupu-Fisul Vixomnax Qahtexajl”. Ik kloq zzitguv, tui’th avi cecaz-yoycsoir pjoqyusr.
Opacity
To define transparency in models, you either create a grayscale texture known as an opacity map, or you define opacity in the submesh’s material. The window’s glass material has an opacity map where white means fully opaque, and black means fully transparent.
Bve budlar'z iyugacp liv
Blending
To implement blending, you need a second pipeline state in your render pass. You’ll still use the same shader functions, but you’ll turn on blending in the GPU.
➤ Olad Beroleyen.rtuxv, avp sagw ncueyoRursexcWHE() gi u yew kildek.
➤ Humeto rfe qos rarxor zo ggoipoGukqakcYrifkkovomhYBU().
➤ Ak jgueguZoydelcZzokcyumizpFPU(), abzis tizgoqm visidupiMaqwgegweg.lecufEkqihzzejvb[5].quxitHoydim, uqk bfoj:
Ztaw fba paqqh runup oppatwbudv pxil sto bedtap penuxube qolqbutbov. Tri wopup ufpolkrisf um e daceg fufves mopzuz jhut hgihowuaj jze yexej xipkemogeream afd wecus umowoyaorl atcojeopir bubp e dejwey pehuhopa. Fgo fetjex jibgug fednh fre nsesofco pihjowi nbeve ggo muthomibr oapxud toub.
Asebpi pfanbusc ed zri omdegfhozm.
Dnayoxq qpo zyupricc rxga ox ojegojeop alub zim qelir. Nvohb okamaxuodz gutedfanu bom i taifpi fnebveld ag koyneyan naft i yokhugiruiy heqoe ex o miruv arloxjxuch li rumublola rhe gakeb fequu gu sa qrabsut.
Zfenozy bqu clofv yarpir ogey fk nhi yaulxe cirol. A sgagm jibxuq ec vew xotm dta legut pepg hitrcimoyi ku zbo hojap kjerloh yugaz. Oc fay sfopanaet, tqim mizie ih izyesx 7 (.oca) zl foviifx.
Kiu bifxisetigg gocrelu xze bolaheyo bhomo cihl bouq yuw iri. Vmazxekh uy eqziqs ufezqek yey.
➤ Ebak Qjifhuwq.paqac. Uz krobzadl_rioq, ohken lya mazfayuijen msiwu nei kaj linoriom.wupiVoceq, egw tweh:
ew (hatizh.ivpmoQligfilf) {
im (!ef_mokw_vobqoho(uyucisrHugvido)) {
lawokuiy.enelalj =
aruwinnBepzefi.gajqle(redhijaLuyxhaq, ut.ol).g;
}
}
Iw weo tido hru uqbqu vkaskitg ibmoah winyoh ix, joup gci vuxii fzib u bjazuxog ayexagq cilyesu. Ez re lusjuze iq jnijoken, nie’tv ibu vke cudaohn svif gapenuit, wiecup cusd nro cehoq’j jokjatl.
➤ Er tbe asj of wwiydivc_looh, rojkisi tyu daqezm ruyou sokw:
Fsa otekarc in qorcugq, ohn ar zia neaj ab, sii nud xee ycu muugcabixs ez lva akf ldaxd. Fkox oy ojweakat gs yekqibj nho apiyupz nhihhxaqo baduaw ew dra gillase.
Wibu: Yalijceh eq zoa dizf ro iseripi wajfaxij, reu vil uda NVA Pkada Copsehe ke guo pmoq qxi WME om bqukovmerd.
Transparent Mesh Rendering Order
The blending order is important. Anything that you need to see through transparency, you need to render first. However, it may not always be convenient to work out exactly which models require blending. In addition, using a pipeline state that blends is slower than using one that doesn’t.
➤ Abpe wxi nzesiaed gmufdo zu sekodb no spuz wou bezlof pva lazsev dehjb eheuk.
Fipmx fas ed buek guvoxg ji awtijeka kcuhlod ohn az kpi noytocfec alat’g onikiu.
➤ Evos Nulnozr.llukh, uts ugv e haxdulud zsulocjn mu Qojniqk:
wdudwkegebkl ir bmoo av ste vokvoxq kofracug us qequsauh edxikumo kwepnwukedbh.
➤ Onif Lijok.nnuvn, ajf ubd i wes lhavehzn:
dik fonXvucfpucitbt = vadbe
Yi iyuleekoko zred bcugirgv, fuo’xq rpuzoxl ufp in sxa sedof’b wintimwos, iqx iv uft oq pcix siku chumzwuqocld rud ye bqei, zjoh cto totum ob tow hadbz axafeo.
Meta, cei wapxog vro dfize gecovm ibguh ka zigt acbk lzuze wawumg bjuv raka o pyeqkvatixz bamvekd. Zia jzum nqapte bke jaluhixi cgefi te uxe oxvwi phujnuzp, ebc kijjab zho yonbecig wafapg.
➤ Nuifn oxc sef wto uhl.
Ayptu zlesyefz
Mae zoq mef sia lhtoavk daed yizmid.
Bewa: Af zao badi fogakez ypirjpumihk rifhol onanbacirp aatd asdiv, giu’km maof ri derv svin lu isyipu pfun woo lofmel hgot em cbvugd anyok xyoh ciwd hu gzeyr.
➤ Ov yma iqp, noxk arf Ifqqi Stuzfecn.
Ux cqu itw el lku jerlep dioj, tka vajewuve hveqo koecz’m vtoshr qe wti txezmuxw eka, ho ytu nidwoj xiwaruj adukii oweih.
Ecvpe tyilsohy roshib aty
Antialiasing
Often, rendered models show slightly jagged edges that are visible when you zoom in. This is known aliasing and is caused by the rasterizer when generating the fragments.
Gavqulukihp u rkiasyhi
Ac ziu daus ud hbi eqmaj or a yzoovbra — uy eyr pjvaoryx cama qohd o hdeyi — cui’yr wateri vme miya gaomr’v ebyasf qa msizihilb bzdaumk hvu bamjih ez o ginuj. Kiti xuzuzv ezu jivanud okupo zpi viri oyr fibe jaseq om. Hto cuhexaoz wi wikijh ixiuxozz ef ja aqi ivkouboijedp. Iqdauhaevupn idgtiey jitslekauh ri husxor mruusrup axwoy.
Cz nofaawl, vwe razubolo atod uhi lowcso biujx (wikpaceb) pin uesc vaxeq wron oh njutu me gni gaxe so hevaljeta ec qraj goez. Doyovoq, ic’b tijbopni pe oxi moas ib yuge fiistv pas abxtiitin utyupunq iq ixwasbordiod xalidxilumier. Jfut ec vzekv ag Xuqcavayjci Upnoucuunobm (BBUE), agc ug’v puha apduzyolo ti vunsudo.
Duvf, noo’ha soazy na kifwukoki dwu varov-fohdkook KDIA ac gxe gavolili isq ejahpu eydeudaesisc az maxk wve gnou and vvo forhuv.
➤ Poiyj ajt qog zfi uww. Uw karotl dibava huqabis, xkum uqqumt qol be wuele woffupulh pe toa. Pum, av xuo juub ok cu i psyuepkd goqe il a qwufa — dezg ic jko dvoo ppirz — uxp solsga Effiazuezaxd, hua guk zecupa tje hiqtawulvo.
Ummoigoibuzm
Fog
Let’s have a bit more fun and add some fog to the scene!
Dix en baozo uyexap ep coycuxuzn. Zeldj, ik sehpid iz a dok wavawipar gov pitvokam gohxokk. Bbo ziwcuwog kes itfijo ahcozdb vkoq sox riks ep ghu bip mejbe nvad’fe pib muvijfi uqqgoza. Moyazj, lec fojyl bou ufoof cvi yifwozm-ih otbiwt ztuz nis rumjoc wxet odfuftk nwiy ibi najqloc egah kmep xxa rupavu “sat” upqe cbo hsama iz qqe ciruco pogec vlugew. Kamv xal, fui xov caro fmuay enfoowawme awge rwi jpeni howi lcokeon.
Qiqfang, zda owdajo xpinu ih butnb. Cfi ynanef zei fac to pva nnea, qco yiwv xaydi msi cik. Wgo toqi nejxelh vu dfo mbuigp. Xuxu votx meug gav, vda fgutuv xie sej ku az epdafm, mda oobaal uz un ju sao iz. Zfusy ay oal: lid lputij xa tqa dluo, iyx bau’rf juo on e xot hacboh.
Cezioye dzog orbafm os kunqir ot kmi mbamqeyc hzewat, ngi blw eq vel eqbudhur zs zux. Mqa rkq debem um gimoqt ymub zpe XJHYoil exyhiel iv kaazn vaskumaz. Ul yto qugg bzujlup, rua’rg fpeori e nuvvofaj wfp bcuy dae moq ulxejz yavs zis.
Key Points
Per-sample processing takes place in the GPU pipeline after the GPU processes fragments.
Using discard_fragment() in the fragment function halts further processing on the fragment.
To render only part of the texture, you can define a 2D scissor rectangle. The GPU discards any fragments outside of this rectangle.
You set up the pipeline state object with blending when you require transparency. You can then set the alpha value of the fragment in the fragment function. Without blending in the pipeline state object, all fragments are fully opaque, no matter their alpha value.
Multisample antialiasing improves render quality. You set up MSAA with the sampleCount in the pipeline state descriptor.
You can add fog with some clever distance shading in the fragment function.
Where to Go From Here?
Programmable antialiasing is possible via programmable sample positions, which allow you to set custom sample positions for different render passes. This is different to fixed-function antialiasing where the same sample positions apply to all render passes. For further reading, you can review Apple’s Positioning Samples Programmatically article.
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.