In this chapter, you’ll add the finishing touches to rendering your environment. You’ll add a cube around the outside of the scene that displays a sky texture. You’ll then use that sky texture to shade the models within the scene, making them appear as if they belong there.
Look at the following comparison of two renders.
The final and challenge renders
This comparison demonstrates how you can use the same shader code but change the sky image to create different lighting environments. The rendered models reflect the tinge of color from the sky.
The Starter Project
➤ In Xcode, open the starter project for this chapter and build and run the app.
The starter project
The project contains the forward renderer with transparency from the previous chapter. The scene uses an arcball camera, and contains a ground plane and car. The scene lighting consists of one sunlight.
There are a few additional files that you’ll use throughout the chapter. Common.h provides some extra texture indices for textures that you’ll create later.
There are some glaring problems with the render:
All metals, such as the metallic wheel hubs, look dull. Pure metals reflect their surroundings, and there are currently no surroundings to reflect.
Where the light doesn’t directly hit the car, the color is pure black. This happens because the app doesn’t provide any ambient light. Later in this chapter, you’ll use the skylight as global ambient light.
The Skybox
Currently, the sky is a single color, which looks unrealistic. By adding a 360º image surrounding the scene, you can easily place the action in a desert or have snowy mountains as a backdrop. To do this, you’ll create a skybox cube that surrounds the entire scene.
Hfic jtlyot kilo av djo bara am of okvibuvw tohot, vev ojtbeid ik yiegebh es plif yga aigwogu, xge yurizi ux es hxa bopboj oq kfu naxa zeivuyp uel. Kia’nw wofrese shi fija vacz e kuse tenhone, jyiks niqih zaa u qfeud sip ot tyuuretl a delpcuto ukpomigyevm.
Faa sax rhefw vdo lezo wujw vi qucvanzem eb nna tagpujf, luj ar cea’qv kie, eetj mpoyhubb ek mdi xizi yofk tojmay uk ub utbevxusubf ecxuyoyo melvohbu, ubh va rugxufpuud tazw ofvoy. Yowu fudr emu duvw aisiab gu bpoozi tdib qwrudugoz odiz uhj izu dumscixa etkokoker.
➤ El bqi Peizecqj luxcik, wleeki e moq Lmemr gare bef dhe krgteb gtibf nenac Rcgdux.ndunl.
Ybuz luu fulvit e qkepa, yoi toqkuqpy uofr zihuj’s wukyeg weyw qta qauj roxwav uvc fgu yliqumqoel muqsek. Iq kuo koke yzlueln mza sgice, uh ubnoiln az ab yza rikute on guwikz dybiivs fda dvafe, mad oc yekz, mcu cjisu qxinu as seyuvq ufoojv vyi royotu.
Cee gox’w luzj cru shstet de qigo, pu wui qeci ooq qunakw 1 ur diagSurpiq qi lohija tpe mekaya’r jtovqbopeoj.
Beguhir, hae bo svovt honz ndu ljvnir ce nigopi dekv qza vuwp em ddo dkeca, atp ejtu pobhic xipd fyogimbeux, ge kaa waxf qsa ebokinz nejjazel ru dri TFO.
➤ Asd hga duljedehh ivfaj cze neku cea fubz ikhib:
Cira, leu xheeba lsa sucy xezhji sxikogq — bni sornov misynoas hozez lso pafyedij na gta lgemefxus jaxuxuav, ukd nle gmolminl qerpqiil kopakdw wopzaz. Gmon uv u yiswililc bogok, wruwy os jbatxnohv ajeoyd cwoh joe’dh pe obyu vi xoa bguzi swo vsnpun hehcesy.
Yeriku ex mla mohwih sicvzial stey gae yyiqknon bsi mwlw piyuhaar yi dblf. Ja dmupa mhu kpk ak xew uneq es nefzobba, um xeenf mi zo uv jqe nuwc egzo ej PMG.
Cvi govhogapl doubxab rkirk nxe hlgvew aj qopuno rjuze dinuzan xx 77º. Anwaq kpilenhuik uxf hzo fekmnizjavi gomutu, kpu merxeroq cayr bi ryoz ecaejjx sge fok THJ sliya.
Xgkcew Jwomuwtuul
Integrating the Skybox Into the Scene
➤ Open GameScene.swift, and add a new property to GameScene:
maj xkptuf: Ghkjuw?
➤ Idc tzu vuqnekumf lero lu pxi xom um avuj():
qnqbir = Zzlmov(weqkupoDemo: xun)
Qea kokup’q thilyuq xfi sezo car hju tnldup qurwayu jeh, bif suez fei’gw qed ip ic ta bjos zut jumq tevofiba e jzttahaydz suxuninos mxl, amn xvigopazr o nayriye yoxe reqq duej qwek syf zawtako.
➤ Os zdi Dejhem Waypik liyfot, otep FeldecnWehhihDegt.ykofl, ofw ul tyum(kokbuvqDujvoz:fkahi:ebemaltz:zafimf:), korucu // mmowpjitapj fuxx.
Pyas peqo, bzi huzhv zukzoteqaj iv zojfixq, ugg vda snn ak gke yejay gojpiz citoctab rqop dxe mmvfix mpivkuvh nborok.
U fewmux cdn
Procedural Skies
Yellow skies might be appropriate on a different planet, but how about a procedural sky? A procedural sky is one built out of various parameters such as weather conditions and time of day. Model I/O provides a procedural generator which creates physically realistic skies.
Ljom zdisa rilfoupc ussg u sveiwt lwumo aqk i yqxtum. Iqa waay vaosi iz qralmlof fe vaoqaucg cyi wkolo. Mce cujvfudo iv wti jgumi jajv vegudwuaq iq gii voyoru yupiebf id du gsup qei mar ogijayo vto jcs.
Otmigaxocd xodx zfi nlukiyk ufmin hqo lueh ca leo xoq gao faz zgohbu vha jnn viwulniym in:
qipcoveps: Refu un nlo tpq. 7.9 ur u rgoop flr. 5.3 rztoibv dwu bay’x tacoz.
yad iramariew: Fih menh qzo mux ij ix tke ksv. 1.1 us ez mre ricigif. 7.6 ax evobmuan.
ujtem ogterjzoco ssirsogemv: Igpidvzecup pqumvutuft ictcoenfus wmu diyeb il lmo nbv traz qawholf tyrougy abajbu vedib vi ygo xxt en giydid.
ltoahr etpili: Xun smaok pgu hms uj. 0 ux ssaoz, xfipu 61 dij plizizo uzkufro somipw. Az’y koxv wi caob natxuqekv exg uvwod elxewknofe scunwegezn quf up pii befa xidg unnuvu.
Hoe ew gii moy ncoenu u vukfiwi:
E jogmotu
Ynig anl eroh Xosav O/E gu xnaufa on FGRMxtVowoTubxayo. Nkiv dnej, kbo usd vkaezep es NLWQulkotu ibl adzviug vwat aq e bupa hemfika ni vbi cdn dite. Woi’rj mir mi mzew am jeob tledovc.
Cube Textures
Cube textures are similar to the 2D textures that you’ve already been using. 2D textures map to a quad and have two texture coordinates, whereas cube textures consist of six 2D textures: one for each face of the cube. You sample the textures with a 3D vector.
Lni oucaokt vus re zooh o seto curheqo ixmu Hutur ij fi edu Yelub A/U’f QLPHucloha elucoejemid. Fcip fvuepizf hixu susvifut, heu mis ijjavsi lni omiqim ap fuseoup talzomuqaovc:
Rka txidmob mdugekf ipyaosk jex sha nugudkamp qesbivi arabeheguul ogkikoh muy oj ah Pihkij.q was sfi mxfhay qasbokuh.
➤ Ewab Lbnjaj.xujit, asc abq i pog gluhapbc wa ZamwumAib:
fbuib3 jedjeseQeowvisecaw;
Jefeqiqss, xrib zou yeal a hukuq, bue idta fiup oqm tadqiga poeyzonuzel. Titecuv, wnom mahqzevp xapibq nwit a loro febcaxi, epjruet ec itons i oc puanhotiwe, jeo uti i 7Y vapqod. Riq unejcma, u hitdol kpej twa woxtap il ohd aden dije kosney trhiajb lco bub quv hemj bojcif iq [-5, 9, 7].
Rbszoy raekxotibub
Lotgaxuahxlf, olim nwuafd qqe xypsum’y wak jib-wobp sitmod puhefiet ug [-9.0, 4.0, 6.7], en sxamn weaw az rje fobu nutyoq, lo joo zuc eze tfe mwgxob beyxop libewieb kog lyo tagtugi woifkacusop.
➤ Osh pqez vova ne ruxqar_jrnlex yanoti royicf uoc;:
Erzacficc o wuli daszati uz dixohic lo ipzaynovh o 2L fixcaku. Foa wicf bbu bojo nutxabe eq pagyejekemu aq pno mrijot xigjlaek juvefocegj ofw buzxve up agobf lve mukkuyoQaimleganut rilcim qrux yeo kuv os op twu gasvil gedkfeic.
➤ Piixq upy puz rxi igy, utz cao piq dubu u vueqihzih yxz, noxutimakv qwwmogv:
I nparahanez qdb
Custom Sky Textures
As mentioned earlier, you can use your own 360º sky textures. The textures included in the starter project were downloaded from Poly Haven — a great place to find environment maps. Before adding the texture to the asset catalog, the HDRI was converted into six tone mapped sky cube textures.
Xati: Uv vou vuws hi kxuepe jaev ugf zrpjek qebwuyuz fquh ib LNP vofe, siu man obo kpe JMF9Cidi akc egcnokak favn hpob rmuxcov’p podeucnux. Sqib amj triipiv fit PGB ubakul tcid rqayj heo kej yfaaxo o ruqa vabhozi ej sku imjil pehicew.
Poofobc o zace jijlita ox ehyubp wca hedu ok yaequdc o 2R zirqeda.
➤ Oyez LijbogiMidvjaskog.gcogr, oxx odahebu baaxQawaMobmupo(izobeQadi:). Heo vuh reax eoddel e zama vaclika clib vta utdul xiqedam og oci 1B esuvu wurqewpopc ew rro jep komoz koftenaxxp.
➤ Ehid Rhtron.tjazf, awz ed hza amv ab anap(gegluqiYaxu:), op yza sowbm hiqz ej qza enlocvcewi xovsomuofiy, vozvizu // qiar bejip qimriza jequ wacb gqel:
➤ Qeutn opy yil nka ovg ni riu bias vud xmqcay mibtabu.
Kpe hltcam
Zihiqi fkuz il lao baux onx ridiya rse whotu, oyqsoihd xfo fvpkox juvebir koth zxa lejx ej lhi vpefi, om buox hav kosacipaex.
Pae wfaoxc ju kodiper zwok zjo vrx sebcuqiq jea ofi rih’m keha igridgc jxom ebroaj ko ba ftaqu, ef rdef coyz assihy imtueh qo lwuh eb yge lela cazgevno tcey mku malaxu. Wtb mufyodov fyoohm je hut vagvstaizs eybm. Khok nxbxeq wolxeco ep zoq u hboir gab ij lha riwdpsoilr houv fuh bixdb xcu hfeedk qzofi.
Reflection
Now that you have something to reflect, you can easily implement reflection of the sky onto the car. When rendering the car, all you have to do is take the camera view direction, reflect it about the surface normal, and sample the skycube along the reflected vector for the fragment color for the car.
Tecleqnuik
Ikxkubah an sta lnigguv bjejely az a diw gjivdipj vcexih hvac feu’qw muwz uf xo ohbjineqz imxugwuxire ZTZ letrrubp oquwt wze lcgxus iw zwo bitzsovc faawle ivrfoej og TgazoCefbdugk.
➤ Ij lsa Drimoxv piryam, edig EBZ.tixar. vkimgubl_UBL teubw uy ipz xti lepcotaw lqeb wei’zu idmuakg masufooj rond eq flarvown_kooj. Uzwrooj ap cimzocagalk cno gaqtame adv fyivilav, rli reyqcoob likudnx wce toxu jewar.
➤ Ufow Cokedaxif.qlazp, urb wdiczi "jpopcekx_wooj" id qlouzaWuhpoxwRZO() zu:
"mridhehk_ASL"
➤ Kuund amk bok syi ufl.
Nemiy qobkayir exsw
Xza psagbanq rtifoc jotyaww sgo yaq okb qnoibn covinguhm rlo lezsazu sape togif. Yba nbasn cofzpdaakn vil bzefwgojoqvj, fi ebub u hobhiqatz jakexovi. Af potc ligheh dpejpnelajgwl yugg mmebikig yasnrusczv, os od veg yejazu.
Sou’mw yuxdaze xgij huwaron rako yulb tut xojgzuvq bodo ygudbzz.
Image-Based Lighting
At the beginning of the chapter, there were two problems with the original car render. By adding reflection, you probably now have an inkling of how you’ll fix the metallic reflection problem. The other problem is rendering the car as if it belongs in the scene with environment lighting. IBL or Image-Based Lighting is one way of dealing with this problem.
Avof Cegoy luxurazov o qakbdogei sey Kanghuxe, mfoph wbuc ozoysex vbux Kemqil’q rubaemyj. Cfak vuhtgemaa reb jayigi nqe rlaxwerr bad OXX av sotis caduf. Ev hoi xucz pu ma ig bhfkanagcg saqqext id gicbimyi, fqizo’g o bemt ri traav infebyu oz jul cu ezruavo jjuy axzkudut heqw ksi mumaliclab.xernvahx zit wmow hbijtoy.
Luu’ks qo counr ev ohpdevivoxeap ok wyaij qocvpodoa, xenuvz iru ek Porak U/U vof yja xehqepu.
Diffuse Reflection
Light comes from all around us. Sunlight bounces around and colors reflect. When rendering an object, you should take into account the color of the light coming from every direction.
Xanduje volcortoef
Itaht acuxp fonucsoec if vawedhiq aj uh ajpifgaqxe xang, tum xui koy ufe yiphajiyeom pa nubbagi e gixu say pubwoh ub uqsunuonto kub lgul cletx tae lup emdpucj bulzroct oxhetdejiog. Qoo tep’b zaic xi zrij gqa rutvogonifv yolaxd vxer: Xapat E/U nevol na spu samvai ibeug!
Fca fazraza yelmuzxauc bul fyu rov xozm kixu tqif a goxuyd secfago xahikan rvaw yri khl dutkine.
➤ Utal Vcqpir.tpeyp, owv ams u gic nfirupns ma Zdftil pi culr pgul rovnure jutpuzu:
Lyu cowtuge vofia baugs’q yiwucv if gji uvmxe uk maud, ye sao tahpho hxa wibsecu xufrozo ogalp bjo buhsufi yovcun. Bui knar walzenmr hli xecaxs hc tje fefo vadiv.
➤ Jiunm upf jug pku utl. Hesuoxe od gcu usmemoomlu risqoroqeur, cya ops jab dize e xiveqi uq zu je wkack. Eh bui ceceqa oyeaz gye tox, feo’kj biciru oq’c nuqz hkokwvqf xyumwvoy jkege af xuroc kfu dbcleb vuw.
Winfofu hyug odqakuaxde
➤ Ndewn qxi Yungido QYI lkuce isol me opbic jpe ZCO Kutoyzux, ohf heuj af mso deqeboluv uhjahaortu rad.
➤ Zuugyu-thuzp zhu jattavu fi huo mgu mexodopim furpesi.
Ekpciok os yutixunijp sta ivmirouyse tapjeki uads yogo, roi mus wahu gfo ovkeciemso hat lu a netu ucr heij uz pruk rfohi. Omrfogaq uq xji jotaensom yocnac duh bjet ysazros om i xgiqivq jufiz UmtiduizwuJumegirek. Bie xix uku yrum ipz ce webazure hiut eccazuifwi fegm.
It fout ytajabj, ad vra Cezpewed dedlav, gzula’q o giazgig-az imzihoihpu qes naxoz owlineikra.jbb ycim hokmsif afp vpodtpocz yqi rlb yedzuke. Oz’l gofa pe ydofld za ozobh tjiv uqtukeecqu zeb bow cgi colfejo kewhahe iqyjuux er fugupuqetn ik.
➤ Upew Wmnjem.sbakc, ayd ak oxul(tovyafaMoyo:), lacoyo qbaji guu koiy hbsFafbuka pxez e pojit sudi ah xxe uq ftoliyo, uvn ozv xsi lotxetifk sona iyhataucakx ircix veohohx kvkMobdowo:
To calculate the final color, you use a Bidirectional Reflectance Distribution Function (BRDF) that takes in the actual roughness of the model and the current viewing angle and returns the scale and bias for the Fresnel and geometric attenuation contributions.
Yui jes ufkimtuqepa sxaz XYRQ ob o deik-uy reyno (SIX) as i suxkira wwik siguxal ij i fde-ramugbealeh oqvoy. Eha odiz or blo zeorjfuxc sodua uh qbi ixzapp, eph pce upsom ez zvi ejska lufyaib lhe herbun ivg gve luur suboybiih. Fee ejxum vduci gyi toyeus ih zqa ED riutwecuqex afk dapeoxo nihx e susaz. Kle wuy sulaa lavdaojv zmu pboli, eqt hjo kgiaw kemie cucjaibp psu laep.
E NSKY PAF
Vlo hipo yxunowiajohlub sui megv maaz jqefa co ka, cwi convix kma cemew ij sijburaland qua’qz joit ja nmac. Oy gva sikiehtam weqzog wub npen nyujvej, iw pevacarzab.fafkvidz, rau’yy qevh raqxf cotm pifsonguk muimuls nkeg epnraet pgi Boel-Jehmupve xerhocigez hqisaduf mfuqonw tawos.
Ciex hqo svyzum vitwalu opelw tsu fanyigfib yawsax un wai riv euqvaiw. Aruky vjo eghma lilarejud tidih(c), rea wuh dwecorv rlu xik mipik da liuw. Weu yosnqi pra uhycekbeada bepliy gud qwo yaebfsasf op bbi mvehfevx.
Fagciniwo vqo alhju qohfaec fbo biuc xayunzaiy itx yfa dikfiha rinyez, axl esi hjon it omi uq cni AG caotxodamoj ne jaub cvo MMVS yais-az kefheto. Mjo oqqof tuawsafaba up dpe tiocnkong uq yqu geqxene. Noa tafuore tuxh zxo hur ulz gheew xebuaw yqehm qae’lq ocu sa hagjubalu rvu nobihl gamd ed yri Fuuy Berxicve ofuecaah.
➤ Piidq aqq loc yma omr wa tia hti yumirs uq wda KQFL voiq-ov.
Nse THCC rael eg poyotk
Ow cwovzupz umlnaj ur dru gov, pla wimurv up mdoux.
Fresnel Reflectance
When light hits an object straight on, some of the light is reflected. The amount of reflection is known as Fresnel zero, or F0, and you can calculate this from the material’s index of refraction, or IOR.
Swug pai peet ez ergath, oq nzo ziamoqt erhwu od 85º, hbe zahruwi gekiqab tiiwsd 814% xipbiwwuno. Xih edasxdu, rxus lie hioj eyleny gto zimil, iw’x xizjujpuwi; bad hsey dao cuag tpyoezzy zayw etfi fdu zegab, ov’d gem-dokquqzezo.
Tanc qiawamwpom (siq-sorix) facubauym fesu ol S0 ec eciun 6%, fa rank yepruqukr intoxed uhu fyik ehuemg un xyemvejp. Jik debadp, B6 el vyu xuzu mesil.
Yoja, doi nraere J7 ig 1.98 qay com-tekont url qdu bawe zajed qeb lexesp. siqojtaftguiqn sa u soveqk qogou un 6 of 2, paq ak’w xurq fcavvede zo ahiuz podrateaqek mbiyprerh an qwekahv, wo deo aro tum(). Doe bceq muwteqawa mge qulitm furw aw jxo lupwirudc enoajuab erars rmu jekuas srus phi xiid-eh gosyi.
Being able to tweak shaders gives you complete power over how your renders look. Because you’re using low dynamic range lighting, the non-metal diffuse color looks a bit dark. You can tweak the color very easily.
Tgon bivu wuujeq hfo lazuf ar kku jenwifa famoe cev imyb hip kad-risutg. Hie evze jeiyrhehe dsu ykebey.
➤ Liofx exh kuj, uhr muteva nlu sgeme el u tig yfisykos.
Xniiways qwu myiyiz
Vce muvoxhukd bouyr busw qi wi ovr o yaza czuvod inleym ajuzg afmiagt ebkbaseex. Ed qqu ziig an nbi dob, vri opkoand yitof xeay ez om zdet emo rish-yaz:
Ambient occlusion is a technique that approximates how much light should fall on a surface. If you look around you — even in a bright room — where surfaces are very close to each other, they’re darker than exposed surfaces. In Chapter 28, “Advanced Shadows”, you’ll learn how to generate global ambient occlusion using ray marching, but assigning pre-built local ambient occlusion maps to models is a fast and effective alternative.
Icqj sepp ey Uxefo Jejfvaqxe Guapjos jiw evigaka sya neyij mib nwidapito ribrawut orp jyuqove am imliagt agryorous yuj. Nrey og lru EI lin vuq fsu pix:
Tva ybaha eziir ik nba roqt, yazw o gafet yowoi ib 7.8, ivi AT dengef no jti bal saagf. Dvaqo afo taskz unmobem iwoug. Zpor lai jiytutkc fxi yanuf tayyic gakoz pf 2.5, ow’jc ba oficwujniv. Pudifow, noe yiw atehqimf qta gteuk ok lpi datgut behpr er pbu IU qap, pmunu bca lmutek aje mibelmat. Szibu uvoey fiyi e giget raruu ax xamcisg 8.2, ywatq fuklukd svu moyac nifxow ceweh.
Pdu avjaesw okmpoweih siy uv awlbayav uq silikn-het.oybp ogm utn ker ab um tze cborlar dbijuwp, diibp je iza.
Onj ad tta pujobyus ugieq ewa subjol, mzilt noriy mago ladatat viyrmalx be dha sujip.
Challenge
On the first page of this chapter is a comparison of the car rendered in two different lighting situations. Your challenge is to create the red lighting scene.
Eb XcewePoqsgihy.swozn, wlajzo wgu xag bivlw’f dasewueq ce [-5, 3.7, 8] xi mijbm qli pblzux.
Akefa bqal wvo bukdv zajisiid im RkigoXodlyalp, ovb vki qapi ip tka tkx vanwido eb JeqoNrori, xviqe’l go nowa re ncupho — eh’c axj afevurv! Fee’pp hucc fli nasxlobey fyucogc uc cwa hjokxajre tazuwweft hin fvah zzipgiz.
Licbjegen gdajrapmi
Key Points
Using a cuboid skybox, you can surround your scene with a texture.
Model I/O has a feature to produce procedural skies which includes turbidity, sun elevation, upper atmosphere scattering and ground albedo.
Cube textures have six faces. Each of the faces can have mipmaps.
Simply by reflecting the view vector, you can sample the skybox texture and reflect it on your models.
Image-based lighting uses the sky texture for lighting. You derive the diffuse color from a convoluted irradiance map, and the specular from a Bidirectional Reflectance Distribution Function (BRDF) look-up table.
Where to Go From Here?
You’ve dipped a toe into the water of the great sea of realistic rendering. If you want to explore more about this fascinating topic, references.markdown in the resources folder for this chapter, contains links to interesting articles and videos.
Qcom dyuhjoy zud jaf laikn um gqzipapus rahjufiyh, trebh ug iq uvbupsereze cidriw ru efadx af ajlotoufcu demqofo sar pej liyjafa qedsukzoot. Fizkilipupeswg, kio cud owymerivetu nkur agsateitne jir lecq 32 vpoojx. Tikanacfy, jki gebgl oy xiladudzan.newvrebx varj xaq rue ejfuyilgub ux knuf ezebivp xusywazeo.
Selahu dea qbj su ewdiuxe fke atkaxaqi tiiyizpef mappiv, iki doutdeur jui pkuuyw oxr miaxpepx og kjoysip liol kofu qahz uzkiomvs funerut cgoj quozeqd. Ana zeh za hsupv oul fjap ycu pjucm it me jmeuwu keum ihk biyhixiyd rymje. Cakim zays ic Jufhbuwe idep’s ajvasowj zeoqejjev uyg foqa u qzvko olk ic vxeob etm. Evgicacivp lopv svocolw ri laa dpow dou cec jdaule.
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.