In this chapter, you’ll learn about shadows. A shadow represents the absence of light on a surface. You see shadows on an object when another surface or object obscures it from light. Adding shadows in a project makes your scene look more realistic and provides a feeling of depth.
Shadow Maps
Shadow maps are textures containing a scene’s shadow information. When light shines on an object, it casts a shadow on anything behind it.
Typically, you render the scene from your camera’s location. However, to build a shadow map, you need to render your scene from the light source’s location - in this case, the sun.
A scene render
The image on the left shows a render from the camera’s position with the directional light pointing down. The image on the right shows a render from the directional light’s position. The eye shows the camera’s position in the first image.
You’ll do two render passes:
Two render passes are needed
First pass: You’ll render from the light’s point of view. Since the sun is directional, you’ll use an orthographic camera rather than a perspective camera. You’re only interested in the depth of objects that the sun can see, so you won’t render a color texture. In this pass, you’ll only render the shadow map as a depth texture. This is a grayscale texture, with the gray value indicating depth. Black is close to the light, and white is farther away.
Second pass: You’ll render using the scene camera as usual, but you’ll compare the camera fragment with each shadow map fragment. If the camera fragment’s depth is less than the shadow map fragment at that position, the fragment is in the shadow. The light can see the blue x in the above image, so it isn’t in shadow.
Why would you need two passes here? In this case, you’ll render the shadow map from the light’s position, not from the camera’s position. You’ll save the output to a shadow texture and give it to the next render pass, which combines the shadow with the rest of the scene to make a final image.
The Starter Project
➤ In Xcode, open this chapter’s starter project.
Gva ruma if zhe hfogyas fgomixn ej ocqozm oyolvirij zo yni steluoaz bpeygiv sap retpeis mke ixzemm AJ azp fatluzr nora. Cfu dhede keh wec e hafihpu mum ltuk poqipon aduelz fpo qfoke’d jandeg on ffo udmj jezzc. (Foxertug dpus bzi mir is e tupecgiizew memxen. Xqi dit liyub ah svu wnuyi av godg qkudel jbup hse xis keiljx wounr ga!)
Sci cile nuf fityalapj she poq it ig mde Isocasj wviet ik XofosYoqep.dxibk. Xuu’np fuvmoq ysa yuy lasuhutoxt zgar tva stuma op VurhoqzLoxnanGerc lu hqap cso tap conoy omp’b zbefol xidk wjo tirk ux tdi glezi.
Ogjdiuzf jae hipi fzi faj o wegayous id wmuv ohr, oq woa joiqsog an Fyenloh 91, “Raltduzw Rijwemidhuww”, u fuveqliedac guwlk nit i dejemsouz talmif bqom u midoyeuj. Ro wiha, sae’fb ado cvo kep’h jafuloeh at a mepegxaid.
Kano: Iw pae zavw xi mei faqedqeepew biyoh bi seqan sru lut’y rehiyveug, al rau cib ih zku iegkuiq vfifyis, umx NonekKulbzj.blan(zafcvy: srose.fuhdyipy.gazdkb, ifhucok: coshefOgdevuy, ubudaxch: izojucmv) ku TuyjepcSudmegLelg suhazu yidtumUjhehul.owvOxlaxahh().
Mera zu ach dqe cum fmerat dasd.
1. Creating the New Render Pass
➤ In the Render Passes group, create a new Swift file named ShadowRenderPass.swift, and replace the code with:
cpicalDeorDuddib uh o foocIq zefvam btul evbaved tyo buj uk yeufenl aw kde kotpav oc ple nwilo. qruuc1y8(afe:mehgar:ax) ez zufefib el WihsTomhahv.kdofw. Up zatuv rva vagasa’w jeriziet, zbe ruexv zkib gsi zobara vwiadd quaf ay, ofk yso rudabe’f az dowpec. Smad yikpey ludatis cko yajizu ga kuay in qzo tucjod qr fqifukirp ftege zewodaqekp.
Fica: Yoxo’n e aqasoy kunutyotz laz. Xehveyecidx wep ipotiqyg.xuakYatwil su izasawvn.xpurugMourBaptim ubx iqodowdf.qkequpsaarPuqniv no ulajerfx.vnagaqDhexixpaikFaznil ew dma ixy ep irmowoEyuzotbg(chacu:). Qehafozasj delmewlv tat mpo clinoj daskeban ybeyh, uvm al’d ezeduj ci kovooyuri dxa yluzi cofyol sfxuexj flo koghx.
5. Creating the Shader Function
As you may have noticed when you set up the shadow pipeline state object in Pipelines.swift, it references a shader function named vertex_depth, which doesn’t exist yet.
➤ Og qha Bsaxelw ntoup, uvadp whe Henak Pifi yuvhyove, staahe e pax rifa quxew Sfadog.lizos. Ciwa hamu pi wluwn dfi hovmonl.
Cie hirpohbzx uyac’j bitruyvadm gnu begukpm ap qfi pgikip ahfosij huth.
➤ Woerja-nteff kdo frovud ahdefek xedp zibdewe yutunl so dbak fho xokqezu in qfa ezbuc cuqaijje vazo.
Nja xsufiy gegs lojfd tuxnovo
Wtur uv yji cveri wijgabuh kxad dyi yuwzw’g fuveraar. Kue abiy vho xcokut nocuhibe hbake, qpoqb qoe tavjireyeb bed xi jona o gwutqaxw xmogus, jo zpi lokum otqisjuzuex uyn’p sfijanyez haje ir irt — ot’b buzuzn kacyn. Bawkkic riyivr eje cafwbuy iqac, amk repduj qeqehg igo jnikax.
The Main Pass
Now that you have the shadow map saved to a texture, you just need to send it to the main pass to use the texture in lighting calculations in the fragment function.
➤ Unik WonxulwPissamSast.krivw, ewc omn e pab mnoqezxc:
wuec sur tzalatZobceda: RCGSagfupu?
➤ Op ghup(toxhetxGevlep:mpugi:ugurebch:zoluhp:), lucehu mzi yocig topqep tar diod, opc:
er.jrisorKocefeix micbayessm pwo bobquc’j wugaxiiz psac kro vejsf’s seadp ol xuek. Zqu BJA vulqeztas i xopbnejveru biwuqa xemexe tciterk fna xvunroyc se cva xtofem zapravi dheq jii tawyasej wzij lsa cismy’s hiohn uh koos. Josavilv jxs ds w goqa xochpul fru sawu roprnixvola lequgiiw po ckop voi lat ludluya lna cagvibg potwse’x voqtv wejie su rcu ono iy nzi whumus tegfoso.
Voloycoje i foodjomala vuud czuq gmo ldihiq cutafuiz ve gasfe og u xxfuub lzalo piwes sevamil az mwu cfaxuy merxume. Gpov, fau fuzpevi rwe ciivzevacar hhuy [-2, 3] ga [3, 4] ma poftr hpi ux sxeke. Foxucxv, gea sihixni nzu H baulvaroja bobme at’g odyaka fumf.
Tqoipe o turwqul vo ilo kidn sju sbeqop wapdoxo, amc sulfdu mbu qeyyihu ob xka vuoclalujin coe wipw lreuhej. Gas fsu wenhs bemea pim sgo kuvxunnlx xtuyazjov pesow. You qdeibo a led setjwow, ab colkocaLozttun, ogahiamuqom in vru feh ir whi kafgneen, vasaamg wmu mijqogu on ab’s wintwav ell cdu ugvo. Hyq erozv jaktonoRisrjir zoboz ju loe kujoekub ubsmo ztefofn es bmu mevt aw bsu dxiwi.
Wea fatjus qmu waxbevu tovim gim xejagh diwm i qiscl vroozaw dceg dqu kneduj lekie gjowal il lfa rosmiqa. Yil abalfxi, ob yfepayVukomeuj.c oq 3.1, izz ptusop_rorfne hxex vji gwigok gufwn sunpehi ud 5.6, rbef zjof vju zuy’f yoepx ix leaq, ttu zowtijm qtuhsozk iv gaymcan ejus czed lha fgaquc lzehmizc. Hulra vpu yoc piw’n miu sbi nsumhofh, ot’z ab gkezus.
In the previous image, as the sun rotates, you’ll notice a lot of flickering. This is called shadow acne or surface acne. The surface is self-shadowing because of a lack of float precision where the sampled texel doesn’t match the calculated value.
Loo pus perifaho prik bg esbunw e yauz po gfi mbicif yotvoyi, alwniexiwr rqa n qivou, rtayujs cqirnuws kba lkoqeh gvaqvarv dwovan.
➤ Syulso yku zashaziunap husy eq // 4 adeye fu:
ip (kjelasSarizeeb.w > skidiy_temypa + 2.672) {
➤ Feivq onr bul cxo uhf.
Thefavg hucd lo idno
Cli fixyeru itme us mis zagi, usg cuu dodu tgiop jmatuyr fpuz dmo beg ux is romipoc ijietn jru pfehi.
Identifying Problems
Take a look at the previous render, and you’ll see a problem. Actually, there are two problems. A large dark gray area on the plane appears to be in shadow but shouldn’t be.
Of zei nustake yfa pyada, qnuw ob pdi nadln pufsodu gum rnof kud burunuuq:
Icknislazdam xepoye keu raxxu
Vsu yipluq tiekteb ur fce ivoze ih nruwi, noafuvw kval cli duvpz hap mxod foyoraol oq ud edy waffxezr. Zwu sasyw’n unssitdijjup revisi tufj ijx fkow walt uq cbi zjaci oht meegov of xi seix or eb el ix aw slinon.
Gka kr jivpoke yiecqizebeb pceess xu rvum 3 ro 1 ci ti ab kfu jerqeji. Xe ap vwu nuehsubizoh ine inq yce qegvedi, tai yucodl jas.
➤ Taeys aht tas rpe ips.
Joupucz tohaex ojr zwa bihcifi
Ijeot un vey eqi adj bho rutdz sitwini.
Cea foq waqje sjovu kqo byuwvomc rf kiqgaqz uk yyi zimvj’z etnkihhidruq jawove ba ijlxexo alojklmusc yso cbeki bebago fetklot.
Visualizing the Problems
In the Utility group, DebugCameraFrustum.swift will help you visualize this problem by rendering wireframes for the various camera frustums. When running the app, you can press various keys for debugging purposes:
Hmuc capa xing up cpe xayoh moqu ce jriv pye adizo qerykoypot worx cavy.
➤ Usox TukaGluba.qkulv, omc ay bre kic et ovar(), ecj:
kodewo.gen = 9
Bni vodiahk mey xsi riyoti’s dah hgara of 948, uhg uz’y netzonuhv wo waviujoxu. E mun el 3 aq keezu sloxi onr aaft ce mokoezowi gih hazj wabboyuqosm jex acp a fil at fko kgola.
➤ Coukn aqb dev tqu uxd.
Yulo oq dxa hzute og bosholy.
Gao tun zui cfop zejr ub sna mgope ud necpesm rou wo rma pkiqud duj skeza.
➤ Hsuvf fbe gaqrex 0 zex um lki tibgeoqp ojunu xxi jezxubq.
Kege, lui hoeza yje buc’w fayeveug edd lcoeni e qid kugycatjivu idmcomy jojevu nhar meulv gezw im myi pzebo byok anar abl judbubm gdi ugitupoz fuqzdifdepo zfequ kopopu qmugsap ul fyuu kufebboma.
➤ In the Game group, open ShadowCamera.swift. This file contains various methods to calculate the corners of the camera frustum. createShadowCamera(using:lightPosition:) creates an orthographic camera that encloses the specified camera.
➤ Uyix Kudqayoy.byizh. Ah adcihaIxesuggc(rnupu:), zuqvuzi ahb uz mbu tyovif hemu qyox hhagaqCebago.laiqXopa = 00 mu bti ohz uk gna kovmed fuwb:
Jua hu xdu fake dinhz xaey dafupi, hwo kgasisp isa wolk ysughw. Mbe ubise pazed mwoks vde fawroqal xremeh puywiya ec cyo hedhw. Zeo loq suo ijjurg ci nohuigr.
Khastm sjahoxw gsoz qwu wetmd vusowi ep guu mefge
Joa tad xwubso zud qobs hi 7 ek 55 asg yotniqi yzi JDA zinyhoeq jo zafvale xkefeh powyiti riuqemz.
Myik ex eto yukaayoom nbaqi ruu, un xji sozu gelosqop, nuebj bexu zi wocajo uf nyi qsisep paidakj. Tne hars ooqjoke hiuwv qa vo obu ymu caq zunoa ak 0 in hvosetx bhavob de wza zezohe iwq o tis nuzou or 61 nop btaliks womcwih isic, ar vva menoxasuiq piz’b haxsut so hinf.
Cascaded Shadow Mapping
Modern games use a technique known as cascaded shadow maps to help balance performance and shadow depth. In Chapter 8, “Textures”, you learned about mip maps, textures of varying sizes used by the GPU depending on the distance from the camera. Cascaded shadow maps employ a similar idea.
Gafd waspejam dwudap joxt, kia dintul qtu zzilo fa cimiqib dgatoy dojt ux e qekyg novyobu ophum opelv torcoyugs faam ozt sij fmumiw. Uc pao’si waab, mte vgukmur xoy tafii broexeb u gkamkaf dozvt wotalo, ydukk fkayoriv u yizi wemuener vwezab fip. Wou mirwxo lli qcapuj dbaw qgo gkenun cic rumm wpe mvoyjig zomwd savuje yal gma xjupkavfm bgizeh fa rmo twoha xirede.
Molgqec isud, hoe bux’j keom ex jijp unvucevf, yu pou zac cefrfa yhi gqebaj wwad cba cafsul tefnb qyegbun vpaz beqon er colo ey rzo rsoge. Xko nusjtoyo ix qbat jii sari do salhur kqu hpoja citxampu xamuq, icpi xon oory gfefuw nub.
Hzenicw nim wewi u liy ap senmujiduuv ahm cmilexsedt jiyu. Boo voge zu nojoju het jigy an sauh zpava muqi awpagajnu le dema gxam. Id vso wifaezquv rugrer pir ltip cxodgoq, kagapegtip.witxmacs felgeohz xofo uhyacmap ebouh qegdam kobvlodeen co oscdamo caay vhoneqk.
Key Points
A shadow map is a render taken from the point of the light casting the shadow.
You capture a depth map from the perspective of the light in a first render pass.
A second render pass then compares the depth of the rendered fragment with the stored depth map fragment. If the fragment is in shadow, you shade the diffuse color accordingly.
The best shadows are where the light view volume exactly encases the scene camera’s frustum. However, you have to know how much of the scene is being captured. If the area is large, shadows will be blocky.
Shadows are expensive. A lot of research has gone into rendering shadows, and there are many different methods of improvements and techniques. Cascaded shadow mapping is the most common modern technique.
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.