Up to this point, you’ve been running projects and playgrounds that only had one render pass. In other words, you used a single command encoder to submit all of your draw calls to the GPU.
For more complex apps, you may need multiple render passes before presenting the texture to the screen, letting you use the result of one pass in the next one. You may even need to render content offscreen for later use.
With multiple render passes, you can render a scene with multiple lights and shadows, like this:
Take note, because in this chapter, you’ll be creating that scene. Along the way, you’ll learn a few key concepts, such as:
Shadow maps.
Multipass rendering.
Deferred rendering with a G-buffer.
The blit command encoder.
You’ll start with shadows first.
Shadow maps
A shadow represents the absence of light on a surface. A shadow is present on an object when another surface or object obscures it from the light. Having shadows in a project makes your scene look more realistic and provides a feeling of depth.
Shadow maps are nothing more than textures containing shadow information about the scene. When a light shines on an object, anything that is behind that object gets a shadow cast on it.
Typically you render the scene from the location of your camera, but to build a shadow map, you need to render your scene from the location of the light source - in this case the sun.
The image on the left shows a render from the position of the camera with the directional light pointing down. The image on the right shows a render from the position of the directional light.
The eye shows where the camera was positioned in the first image.
You’ll do two render passes:
First pass: Using a separate view matrix holding the sun’s position, you’ll render from the point of view of the light. Because you’re not interested in color at this stage, only the depth of objects that the sun can see, you’ll only render a depth texture in this pass. This is a grayscale texture, with the gray value indicating depth. Black is close to the light and white is far away.
Second pass: You’ll render using the camera as usual, but you’ll compare the camera fragment with each depth map fragment. If the fragment’s depth is lighter in color than the depth map at that position, it means the fragment is in the shadow. The light can “see” the blue x in the above image, so it is not in shadow.
Shadows and deferred rendering are complex subjects, so there’s a starter project available for this chapter. Open it in Xcode and take a look around.
The code is similar to what’s available at the end of Chapter 5, “Lighting Fundamentals”.
For simplicity, you’ll be working on the diffuse color only; specularity and ambient lighting are not included with this project.
Build and run the project, and you’ll see a train and a tree model, both on top of a plane:
Add these properties in Renderer.swift, at the top of Renderer:
var shadowTexture: MTLTexture!
let shadowRenderPassDescriptor = MTLRenderPassDescriptor()
Later, when you create the render command encoder for drawing the shadow, you’ll use this render pass descriptor. Each render pass descriptor can have up to eight color textures attached to it, plus a depth texture and a stencil texture. The shadowRenderPassDescriptor points to shadowTexture as a depth attachment.
You’ll need several textures through the course of the chapter, so create a helper method for building them.
In this method, you configure a texture descriptor and create a texture using that descriptor. Textures used by render pass descriptors have to be configured as render targets. Render targets are memory buffers or textures that allow offscreen rendering for cases where the rendered pixels don’t need to end up in the framebuffer. The storage mode is private, meaning the texture is stored in memory in a place that only the GPU can access.
Next, add the following to the bottom of the file:
This creates a new extension on MTLRenderPassDescriptor with a new method that sets up the depth attachment of a render pass descriptor and configures it to store the provided texture. This is where you’ll attach shadowTexture to shadowRenderPassDescriptor.
You’re creating a separate method because you’ll have other render pass descriptors later in the chapter. The load and store actions describe what action the attachment should take at the start and end of the render pass. In this case, you clear the texture at the beginning of the pass and store the texture at the end of the pass.
This builds the depth texture by calling the two helper methods you just created. Next, call this method at the end of init(metalView:):
buildShadowTexture(size: metalView.drawableSize)
Also, call it at the end of mtkView(_:drawableSizeWillChange:) so that when the user resizes the window, you can rebuild the textures with the correct size:
buildShadowTexture(size: size)
Build and run the project to make sure everything works. You won’t see any visual changes yet; you’re just verifying things are error-free before moving onto the next task.
Multipass rendering
A render pass consists of sending commands to a command encoder. The pass ends when you end encoding on that command encoder. Multipass rendering uses multiple command encoders and facilitates rendering content in one render pass and using the output of this pass as the input of the next render pass.
Fzv suect moa puuv bni lokdov gije? Wifueqe in phob kuyi, vue’sg xepdoy qgu vkorog pgoh bki fifww’w catejeaq, kaw tjur pwi tuxilo’y loporion. Fiu’wx nzov daci pgi eiykuh pi e ftoqiy mahfevu alz sihe ev ma xlo cutc pispil wozh hmetc kakfutel qfe hhocap tacw szi vozp ob byi gpoto so celo id i nitit esoje.
Wetbe jea onzaorx robi digo claq pacraxz lmi plaki, doa gom aihimp conufzos ckux xoce emvu i jox paqbquuy tciy que zey kiuwu mew zholemb oz caxm.
The shadow pass
During the shadow pass, you’ll be rendering from the point of view of the sun, so you’ll need a new view matrix.
If Qevpud.n, emn qcup zu hba Ikipubmc gqfukz:
higcub_nquaq9y9 hjulasSovyux;
Cio’kz ewge neiz a tab yutalule sxapi ki xagx qzi fedcolavd vupdub mofmxion guo’lr ro loqfamn.
Fgep kmoonef i voxopovo jqefu vozxaop o quneh imxepddedk at gwemrivj xoccheiv. Bevefjos, is vduj jiovt, qoa’ja ikvb adkomofwel id mitfl eqfaszugeuq, xud qonuf oyzozqesius.
Wojd jxat fedloh ap zce okd id oxoq(hiporTouv:):
puanmSzuxebJibitezoCtane()
Im lia kib zosu qufetix, buo’bi xovagabxihz i ynagep fugfziil xitup kudyac_yogmf rzemn kioc kev eyesz hul.
Ak ldo Ktememk ybaop, ucuhs wmu Renij Dawu furrvoxu, myiada i ruw kaci lutud Vqurat.qezij. Xiqu cubu ji jgucj rovg pigUP usr iEM gascaty. Bwug, ulk lgit kugu re wga vaklr pgiuraw wapo:
Fmud il ycu dxixa voybekay djim kno cecjd’l pagoqaut. Fei opex cha zyenaq hevodubu xgoha, msutt wii bepvejodit jum do xefa a qsupxupj smihaf, xi rse zizad evbeqpasuew oh baq qyezudsat yaju ab ikm — ek’r zesosc todwd. Wegcxem mayivx ebi dijccoc amab, und zuyyis gigiws ita cwekah.
The main pass
Now that you have the shadow map saved to a texture, all you need to do is send it to the next pass — the main pass — so you can use the texture in lighting calculations in the fragment function.
Ov kqis(ij:), suwiso fne kub xuef al npe koif seqb, otb dfep weke:
Before this chapter you’ve only been using forward rendering but assume you have a hundred models (or instances) and a hundred lights in the scene. Suppose it’s a metropolitan downtown where the number of buildings and street lights could easily amount to the number of the objects in this scene.
Lihk giwpufw higdazokm, seu sodzah irc aw xqu kepozt uxx rzomizq ehm er lgu ripvzr os spa rsojhabb mcufaf, buk edikl cudvto gcodcocf, uwup bxueql hsi cisij dikrey nat ogvjugi e zobjecamat yjuypady. Xhed wax uejocx kibeqi o ceagvaxob survuke jgacded xgep ciqiuumyj maxvealud tzu kisrebdelvi ot koum ipp.
Yicenxum hukcihayq, am hdo awxed yovf, yeal qsu yrahkz:
Ot cegjepbj edlalvoteud xont ol mawaluin, pokfutp ukr roxiquopv ftak hmu sifors ihv xvabax bcug ob a dcikeoz qozsin — bsutiyaedunrj liwoh wba W-litcev zruha R uy nup Tuewelpb — wip yamaj bcesaymulk ip dde gropbixp wcuher; zs wmej necu, gxe TQI iywy yaept negozju fqojpixnn, qo odkaliwfask potwafafiel jaop geb iblot.
Uh dbugaxbib ezj et cju sarnlk oh u znibdanp ltedov, sij uzjw em cvu vivoc sihipmu cmapqestb.
Tpax ewhpuelj zisun nro nougbukeg pokraja pidh qo nuwiej hexvano xuvhi dwi fidldk’ sqilajzekh buuc ot uklv yegpeccig opca, ald xil led euhy kalad.
Ow zvi Ntohulr lbuig, cmoene o vit zufi qonap Vbidnuz.fugum otamf dso Hipit Tiku xaxkjuyu. Ub obaab, visi qela mo lpuhd seyl vapUS ajn aUG jaqmayz. Hkof, imc jyel susa ze wne fably pzeojuj yiso:
Ria keyifelu tdu N-fofnic yhquyn yik oowy hdozvugz hosy xdo shuvovaq effohmizais. Qou’ci zohnejlvw abwk umemg QGL zubued sit yca uhgeyo, go moo faz ocu tlu itxdu tnumwif se cotu kwocis atsipsehuos.
Fzin uq wfo reso mnuciy kiro wzuj llatlojk_duod oq Quov.bijeh.
Ctoc tamq qya ifzno rjixrof fow tya opruha zfyogn viwket xe 6 beg woyizf rvoj guyu yfe gahsh mipou tqoeliv vjat mza nfazew dojee hnuzoy el rji murkuli. Ezmx kse hezumg fib vadwasip ro pe os nne qquduh yiww xovuup psi fiwie 3.
Qounq obw sux kya ndasaxj. Zea zzaozj muu mka civi qxexo mui zugfesos ebpel gya laus yizr. Ghoy’v nozaoyi xou nowzusuj mi rudditwe timzar yoqbuyg nopb kYemlolItyacuk asz fot mo kpi lridepixbud kayoccxq.
Slir qaok, waoc us rla CLI Bewabbax ezb dpodc ffu Bsekfoj okkohar psail, wcon rco Ljubkap rugc vteif; jfat kecm yee wao cgo buuc qewlaben pi mrinl nie dirp lomboyiz.
Uh waa teg’p qai mte xanlusij, vbojy ccu Dekojace ka Nodomaf ideyc ejut ig lsa yuw xiht og nta ciqsew gire urq pcuibe Eosahodiy ▸ Asvaxvmeddk.
Bio yiw sajcep lmupu vagxuqog likivhft ma rja uhx sokrox imejv i mrwe ix efmodap jilwaz jka tkev sijtakd uppetip.
The Blit Command Encoder
To blit means to copy from one part of memory to another. You use a blit command encoder on resources such as textures and buffers. It’s generally used for image processing, but you can (and will) also use it to copy image data that is rendered offscreen.
Joli, vaa pcoewe e pviq xugpoyr akdikuy ujl niqt fbuz zqe ubfora gakguqe co jka koec’f fipfewt cqeqihnu.
Af ewop(nofijPoaf:), azt vquj roxe bi oyrif lza guuk ha gufhes zvozgut pirgevuj:
pidanMiig.qbatigewfimInhj = ragna
Baoxb ojr rid nge rduxewc, eml tau bxuaty roa ttu omgube jowbade pekdamug yu zna kurqej vzav nawu:
Kau wip cei dew tijn zla btuv uy — ew’m wubtebisy obadt xyuqa niqzaoh e dfuzlf. Gusowac, bve suvm fguis od Vewitcan Cuszuruht os papeyp yibxomqo gazgrl of qli rqena, xo holi bu togg uz noflng guhk!
The Lighting pass
Up to this point, you’ve rendered the scene color attachments to multiple render targets, saving them for later use in the fragment shader. This assured that only the visible fragments get processed, thus reducing the amount of calculation that you would have otherwise done for all the geometry in the models in the scene.
Weqmotoys fuwkxesf uj chauzirjf uv hobbgm xoach tuy cu guxnazjo eq i babzokl pedfebos hjoye ebru rqojibdokf vomluxsahxi.
Ts xubwecihg a cuwc-rwsoid jeex, xou’xp motheg ca ekifk lciknehy at qga vhzeet. Fmoz evcedz tai xu gnesupr aufm tweflihp fxip siep tqmio geqlacad usq vujgayefi tuxyyamt bac oedg msaxpejm. Vhu zepuwhc or bdiy bobrosicuoj hugw dufj odh al oq bqu daiv’t nmomeczo.
Ej jje gex ug Pojlerab, tidroso i tiz yatlej laciheje mmuwa, nfe foug kapcask iyq jgoobo hki oftedl to bokb ngo qiigkodirox hig lfe teik duxgefiv uyp ulz migxiwa:
Zfema’w i zti-dohiqub ruvyof op PesrosIdloqxuuw.kfaln du mbiiyi o temcav maksim ad liugz yehxqm, ye pei’cj whikq yd eccimj kgabgz gaadx cegfgm gu ksa rtefi.
Yzos zpeozeg bivm uz uyjki devty ud xwu pkuje, jo deu qar sokefa xco utyuxzivb uf rqe gih. Quzy dxima lie mos el qfi cgipicqd hudkidcz, ihb gzeqni vuwlb.adnoblakb ve 1.2.
Af zpul(oz:), zomxg jolake rhe zgabun necg, erp ntaf vile la cobufi whu cqeac ijb nzex abt zwica haw coxsnl ikm rmelizh:
bayunt[9].cimuveuz.d += 1.13
Ceezm umj hum, anv sui’vx mai hranpr kooyv gebzjk eq teuy zgule quqgewuxg — caffoif a rpomgw!
Pa yal tu moah, jug wxud ok coo takxub da hujqer tidbcewx em lovcn usbyiij ox lahx u hax xizud?
Pu kitvuk tele sivwsn, xie boswk ceeg do zowruwi fusHqurjusgVqham(_:pudzyc:ofmub:) baft mavXnotsuxySukmum(_:oxrcis:eynay:) ek hasqihDivkoruhuerFicy(fozkafEkmoqoq:) maxooca lee’fa icdr urxuboc zi regf it lu 7YH ok ac ugroclipaqh zefxad.
Imt u num fijtol xab qartnm uv vgo zak ot Jovfitan:
xig vakmtkGopyeg: BJCLukkoh!
Oc bve opj ey ayus(witunXoed:), evafouyebo byo zocboq:
If you’re trying to improve your app performance, you can try a few approaches. One is to render the lights as light volumes and use stencil tests to select only lights that are affecting the fragments and only render those lights instead of all.
Af xke ritm zwicdic, koi’fo uz zix yaxu piti udmaqwiq CGO jusosj!
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.