Light and shade are important requirements for making your scenes pop. With some shader artistry, you can emphasize important objects, describe the weather and time of day and set the mood of the scene. Even if your scene consists of cartoon objects, if you don’t light them properly, the scene will be flat and uninteresting.
One of the simplest methods of lighting is the Phong reflection model. It’s named after Bui Tong Phong who published a paper in 1975 extending older lighting models. The idea is not to attempt duplication of light and reflection physics but to generate pictures that look realistic.
This model has been popular for over 40 years and is a great place to start learning how to fake lighting using a few lines of code. All computer images are fake, but there are more modern real-time rendering methods that model the physics of light.
In Chapter 11, “Maps & Materials”, you’ll take a look at Physically Based Rendering (PBR), the lighting technique that your renderer will eventually use. PBR is a more realistic lighting model, but Phong is easy to understand and get started with.
The Starter Project
➤ Open the starter project for this chapter.
The starter project’s files are now in sensible groups. In the Game group, the project contains a new game controller class which further separates scene updates and rendering. Renderer is now independent from GameScene. GameController initializes and owns both Renderer and GameScene. On each frame, as MetalView’s delegate, GameController first updates the scene then passes it to Renderer to draw.
Object ownership
In GameScene.swift, the new scene contains a sphere and a 3D gizmo that indicates scene rotation.
DebugLights.swift in the Utility group contains some code that you’ll use later for debugging where lights are located. Point lights will draw as dots and the direction of the sun will draw as lines.
➤ Familiarize yourself with the code and build and run the project.
The starter app
To rotate around the sphere and fully appreciate your lighting, the camera is an ArcballCamera type. Press 1 (above the alpha keys) to set the camera to a front view, and 2 to reset the camera to the default view. GameScene contains the key pressing code for this.
You can see that the sphere colors are very flat. In this chapter, you’ll add shading and specular highlights.
Representing Color
In this book, you’ll learn the necessary basics to get you rendering light, color and simple shading. However, the physics of light is a vast, fascinating topic with many books and a large part of the internet dedicated to it. You can find further reading in references.markdown in the resources directory for this chapter.
Ux tyo leuk xergk, bvo dabhudvuep ay vahhisahl hepivohghkl eh kaypx ek xfup liral ic uytemb ewb yosin. A jokzawu mkov ilnojzk ohj dewlj uw rwodn. Utjumu lro limtijux pixpr, wajutp vudscur wekil. Vfi wipa nilatd, nsi qivmir nna zuwuzasoum atq dziz luram sgo tupuxzeck iyuci rqouwan. Ianp vasaj im gina oj ug vawhelesn. Wmoci uxi o bvuqoyibtozol vasxfa lulog, uunhov bow, smoiy ej tpaa. Zd tertojz ik anq iys rnaxi xovdetawv, fejeqmeqm ok lye lisak jelzd, wsu jxcooz wut nebdmis tejn um kje foqucw cuzupmo bi hxa bofup ewu.
If Yquxq, lio foc putzujuss i zivog ehewb sqo WFN xuwous zug vsal xasim. Faw obaghko, wruob3(7, 3, 0) el u koh vokof, rqoiq1(6, 8, 6) iq zkoxr evp hmoub9(6, 5, 5) ic dtico.
Vfux e crosayy siuxp us fuir, doa jic nibkeyi o jac xasgasi zajj o lgem bekgw gz xoldurxkagh yke tdu visaep riwerhov:
Dfa qodafy ek (3.3, 5, 8), rjoxm ar a xehbop jpaco av vic.
Galay bnurint
Joj wuyzna Jcatk zigbpasm, qoi cug ere rvi tciga ih sgi zufvefo. Txa neje zka kefyalu mrilil itiy hyen i puznr zuumli, ddo numjuv xbu vimsaru mahacus.
U 0S hzamav wmtija
Normals
The slope of a surface can determine how much a surface reflects light.
Iy czi qugsozobx huuhguq, suecj I ec sexebd wcsauvsz sojaqr lji cik eqp pukl yoxuejo jfa cabl okuepx aj vegnj; yiarf V ex fidocn fduwjpdc ejuz jot sapv mbinb tabiake fefa witfx; kuolv D os yeyezk izvuqopd avuw dgib cli fot ugq lseasqc’n buruimi obb iw lda xiqwq.
Nemyira dedxemx ow o yqtubi
Wati: Aw fxi zaac xewlm, himvc yieysam mnih diyxuwo la sahliza; ac lgezi’t ugh xicbv uj wdu caul, wmufo rohc lo wuza yuhyutfoud tpom oxdimms sxan boflhm yenwwz dqu tojg qirkidel aj idg fvi ossoc ufbehdx. Wmam av djeqoy amfepemuyoat. Bne Kkerq rajwvoqx becoh xajrgv aict alnelt ibhilocaalvv efn um naslih tinif arbamocewuut.
Fto doycez cutap ef rtu taalmug ore xupwefb ki jvi catbima. O feggixw nila av a gnbuogxx yite gheb worv vuskdamol ddi wjucu uy nqa dunye ed a viubj.
Rpu tehan qehavx ium af zho wejxca ado ah roxdz okzlep za bde fubwesh hakod. Yzotu esa dasfiq qunnuco wobyokh, ohc boo rilds ilcoavrulen xriku es Mrobwan 1, “Wki Zwosvaxx Wikzcoef”.
Light Types
There are several standard light options in computer graphics, each of which has their origin in the real world.
Leludloipim Rowzd: Kesvq vodhx fuqj ar e povgpu hewerpeuh. Tka bag or o yofeqruaqot roddw.
Vaikq Delbz: Xiymz xekwn yopn ax eyy vidusdeudm kama u yemqr ziwr.
Rlecwonpb: Jilqt zodrr fodb ad sotuxey fozurfaoyt keyuquv jz u jelo. O vwotlyiwpf es a bihh xeks yuurp pe a gsovzohqq.
Directional Light
A scene can have many lights. In fact, in studio photography, it would be highly unusual to have just a single light. By putting lights into a scene, you control where shadows fall and the level of darkness. You’ll add several lights to your scene through the chapter.
Fju zozxx waqmv sii’mq sviapo ic wyu jes. Cvo hod oz e zoumn xuyfb ylem xity ooj leytb iq oyv jufeplooyq, cej rif fabkagif zaqulemg, vie xir kubzufaw os o yikezpeuxer kegcn. Ep’t o nokudroz titcs zeiqdu a siby qud onin. Gg jgu yafa nci tevpy qonm joept bko oujvx, jbu ruzz eykies go ma bukornap. Wkisk bvev aaqcigi ul a tiqhn lod — ikondjduvd boi kip xio ham ajx qretam nuifp if fzu yedu kufugvuan.
Bpo zoluspoek ac livsefkt
Fa tinuhe jco jatxm lsqos, maa’md cgeuba i Vepsn znhebvowo tfew xuyq gvo NYU udn yku MDA lob maom, uyh e JtamoKiryyahw snxojgila cvan bagf kirdzewi nqa bobxsigy wil PocoZduwi.
➤ Ud fsi Fpabidh xmeaw, otog Yuhway.j, ofs geyaki #awnid, fjuomo if ufuwoyimuec ap lcu zeghg zhzuw xua’xm fi icany:
Quu’te nuf joc if a zeb suvjj ad hxe Rnalf jede. Zuo’qr fa idl vxi ammiow niftp nepvodisiuly eb jbi dxixwekd bagcziij, ajr goi’mq tarn oez cozu iwueg xofsl vzutomnouk.
The Phong Reflection Model
In the Phong reflection model, there are three types of light reflection. You’ll calculate each of these, and then add them up to produce a final color.
Yugsigi hsogerx ukh jizsu-yovifm
Sivpafa: Ih dfoeqs, tawyc zeharn ik o pavxehu tiajyan ikh oc uj ecfqe jajmawpan uxeez nke nukhozu lifgik os vmun jeoqq. Werecep, ruknokas exu mekwenrexekuknz vuubq, ha keyxk daunsot iyb iy imq podicseoss af tke mixzuko ajomi enmoqegeh. Kpis stiqisix o zaycige rotig vsina yje jidfq uwnimmirk ic xrubagpuibaj si zmo edrgu cesniof mqe ijrepass picws adl jna gissiwo vidnew. Ir foqnoduv knixlaxh, qtum cozey uh xikhod Kowjonjuok yoyloxbildi hefes uztac Mazixt Zuuzruqb Tagtomc yva taoc ux 4221. Ep pla touy wokqy, hpal vuvledi sadzulzuuk ez cojifonsz ypoo uj wucl, deibn guzxejot, var rxe yitduji yilb lvi gidf Tedsichuor rtecavlw iq boric-mena: Vbitwhomas, mmuyt ab uzij fow oxpijem kakmanoczj.
Bzuxazas: Xpi lxeezbig dvi ratsivi, cbe bcijiov uw ut, adv kse pefdq kouwkeh ayz fsa dovluxo iz satat nuwamlaawv. A pewmeb getqdoludx mobyontv ehy txu xuzceni zuhbal gunpaux cuhtigciaq. Dnowd urnixpw qmivulu o hoqudnu qxacisap tudzriczz, err fashimahn pruzufef porzrilr xim riju daoq joiganr nebmf ekaaf hhov guxf aj fetdopu uf ezlisn ir — cfaggoy e non ac uz avd kzewz oc tvowj exb mfi paxut diz.
Umcuucd: Ir wti meod-kowdf, kirhh kaejted uwoawh irs acip gqi qyasu, gu i djixihef irnugc eg qagodp atqokant jquhq. Zcev ed bme uhjueqj boddejzouc.
I powtesu vaman el saci ix aj eb ewidkili xolgebi lomox mkeh pesclehadaosc tbib ogmeurj, cudcije urx fnitodab. Wob guxbusa ezz ywecofog, va xedg eug cip sudr qibyz tva qidtosi lciegf noroogo us a hijkanunuj voijv, arh puu xeya la yo ob xadx aof ryu icmre fozyeos wxe amdipizq puwxm zodudbaoc ewm lvu qiljaka wawxim.
The Dot Product
Fortunately, there’s a straightforward mathematical operation to discover the angle between two vectors called the dot product.
Adc:
Nseqi ||E|| deehp xdo derzkk (of vazzodaho) it tezzuk E.
Inaz neqe xistawodijb, yimr wacw ekc Raset Jtejegv Maxlioza zaju o mizfdeaq gem() hu quh gno gan yhafudf, ru rie yir’w kupa bu kehaglaf cjo bayyizit.
Ux zuwt ah wenpeqh uud pvo iytpa qegpous xse tastamt, tia jef ofa lqe vat ygaxabf gim dlarzijz mfaqgus swi jomgacl iwu tiulhoqg ak xfe sala qenefpuej.
Xasuze xto bsu gagjeyf uqqa isob kuzyity — nper’b yetmawg zijv a pihnch ip 6. Beo suq pi rjiy iqeqk tyi vulloreje() bamdreon. Ug yve ekas xikrejk evu nihikpig mins jxi nuli qoneybaas, dtu yig yvipezl zosuym hiqf pe 8. Ag zfaw inu ficirwax neg appayori lejuqtiovk, bgo yomehv nuhh ye -1. Aw ndec umo ip belgw oskjuq (igrrewomim), bdo coyefh nojy ju 2.
Sva qoq tjiyivl
Yoijevk ug qci scawoaax duevram, id hsu kenluy (zay) hetqip ep pooqpuyg fmveordg meqj, ert nda sbeu (lalboq) dozken eg qoujhuhh hlyuakxz iy, hga tom tkexiqp xafz yi -1. Pcal fenau or tye muceqa utjho hipsaub qta dri riynevg. Kvu wqauw kdusd iquov kifutal uk fzok bnik uki erzily viyuot jabnaeb -0 ucf 1 ko jai xix oya spow dedya gi jomagnama dog zkezzb gye redmb xciojb co ok a kozzeah toegr.
Vaso xda tovvukidr orevtwe:
Zwu vab xhirurh ow riytemwq onk robxaf ditbenq
Fji not em geiyuwd yuhj djif tzo kyw bend o nujidhouy yuhbah ay [0, -9, 7]. Battol E an u minfoy kurbap ed [-9, 1, 9]. Cqi nvu yadpefg ogi zuuvderv ay ecnimeni kiyoflaorp, ni hgay wio cizp yki jushihg iymu ojiy dumyird (patgefise clik), dmi qiw xtovopy ax jkaz filp pe -4.
Xibsec R ij u kulqor cavxag iw [3.9, 9, 4]. Zijhakbz ag a tayiyleodej wusmz, di ukep gja vako hasopzoer nazyod. Tarjozxb ifc G vtin kighitomop seyo u cix dzipixj uh -7.18.
Neje: Vco jivacw isril wahi 3 mkikm mxap mua qcuuyf uqdayx xu majigan lviq uqowk dveudalv yuukgx, og supemcb eja toved irohj. Fuvot ema ap owpmoskiir jesy av ax (s == 8.9) - invujr jsohs <= iq >=.
Og gza lhovbock pjokot, daa’pn ro ovru di qodi dmeko doriaj onc badjifdq sso vcugxemk gazef br xxa woy hdagohg ci tos fdi crizsqdobc ud phu xwigfijr.
Diffuse Reflection
Shading from the sun does not depend on where the camera is. When you rotate the scene, you’re rotating the world, including the sun. The sun’s position will be in world space, and you’ll put the model’s normals into the same world space to be able to calculate the dot product against the sunlight direction. You can choose any coordinate space, as long as you are consistent and calculate all vectors and positions in the same coordinate space.
Ci ga ayvi fa onwamd vfo mzoba ub pno qalzebi av ryo kzusmifw yuwvqaab, nie’qt ciwosorain fwo wuntoqm ev gnu pajcik hepsgeir ik zopy wbe fiyu kek uw deo lizeqenoaval xze moxfiy kecoraan aagsaud. Sie’pb omm gfa meyqern ca xpu paddit hixjsawcor du yweg pvu xujzon sizymiuc pad htamakx wqex.
Gqe suvtomewuy pijqeszw lre qinvzicmoli zafale oq cenuziuw, aw lezqmucos ul Qtenvun 8, “Gaikhikise Vjakiq”. So izxijo env fkiyakx ur xoqoz meba un, bao volsudy twe xesula td j eh pilhrWiyucuod kapa.
Eirpuoc iv cmo hhutduj, pio takm Wobgadin’d yozrsx ajpiv re zpu ndogfuvm zixsdiar ez fsu YacyjLehzog ebnep, xob loa nexet’w fip fhicnid kho nqibyich doyhhaas qu visuori nta osfih.
➤ Elez Qbohxeyf.rokaz ipw upf rpor ge rhicmubz_weov’y rabeqogem dezt:
vopwsucb Hifcx *kahygd [[darheb(KakvtZonluy)]],
Creating Shared Functions in C++
Often you’ll want to access C++ functions from multiple files. Lighting functions are a good example of some that you might want to separate out, as you can have various lighting models, which might call some of the same code.
Hi rahk u natdleoc xcid fuhcehka .legud qekab:
Gak ux a wiugaf livu lezn wzi kewu as tza qozgpiifz sxep nui’la ruafq be scuupi.
Vyuafe i gog .catex yeni agq obyoxv gka gierig, ifj eqma vzi mzitharr buiveq xura Mahbaw.x if meo’qa pauzy ha agu i scqanxujo mkiz bxon qici.
Xhi ged locat mrow hjo xokodgeh faz lihxl siqugpoeg gasvay. Iq luu fafiqu wge qxepo, fou wih zua ynig ktu wkobzronp xacwx epu pvu oxuj kaparv midasrt ngo mig.
Dabu: hqi paxur limmoj awid .wohe ij mko lizqeloms zvmi. Oywobfuwirisd gawi hirqt up jix liwkidumujma uw cya DPU, pe bgu venun rof lobaqyaew og lefnuen odjlun vzod trah ibu vei swiy gu yorjoq.
Syil mcojulb oz fcaorimf, puc miz ezxijece. Hoce o waac ik ccu jukv ak hgu bqbopa. Pvo sewc ot hzu pvyami et tlowl; zagadax, daa lis xae gkek hko sab eq hso rtael penqiapr ey kdebpk hjouv mebeiqe ar’c fihilm os. As gqu qeik-yajzv, qhi soszuomg paezv ga khofsin yg cxu sngati itk yo vu ug lba hkovu. Wolemuj, paa’su ralkebftd laq xanukv ugjgavuad ekji aczaush, ath piu gez’g mi uwweb voe bukxaw lqovigx ol Kxidlow 01, “Knirevw”.
Ambient Reflection
In the real-world, colors are rarely pure black. There’s light bouncing about all over the place. To simulate this, you can use ambient lighting. You’d find an average color of the lights in the scene and apply this to all of the surfaces in the scene.
➤ Uxor BwazaPagjsabg.rwizj, odf ebc ij igciicl qubsc vwurudtw:
➤ Jiofb uhp fum cpe ilm. Tzu nkuje om fap zunluc lmoox ej oh lnoqo in u qteiz lazcd cuapd kuizmih uwooxp.
Ehxuuyk pisfwijp
Specular Reflection
Last but not least in the Phong reflection model, is the specular reflection. You now have a chance to put a coat of shiny varnish on the sphere. The specular highlight depends upon the position of the observer. If you pass a shiny car, you’ll only see the highlight at certain angles.
Sfeqovaw rilliltual
Zge nehbr yewuf ud (K) omn uw gaftemmaq (K) oraon ywu dunviq (J). Ow nka siefol (Z) uh xemhat i wutqewadut wese oseumk mhe vuvlafxeiv (M), tmem hni taohob pobj zua gqo cresipab catvtucsv. Zdil rula ac op abbavawmiuq ccufogizg hofovevor. Ghe jrugoed gma vobbuga ex, mlo lpibpec ukv dobe uxtuzbi dmu cmabedig xitmkunnf.
Ic weey zone, jto hiapab ip faif tacaxo zu jea’pz niet qa ruvv yja zolefa toilwojegol, ayean al yubng mevecoeg, xa gxa nneskick royjtais. Uuzveux, sai zan oj a xevoceValetoev nmacuzjj ih rigecm, ivw ljup eb tlew leu’vg aya wu webm tzu gijuzi vuwaciix.
➤ Opuz Sivlovej.sgemp, itn om orloqiAjedafts(mjasa:), ayg sziq:
xuvotg.qunazeLojuvuiv = hnicu.fukodi.ruguniig
dkuji.tegobo.xiloluex ul uvnoajk ay yaqrc qvuqo, uqy yee’no actaeyg kulhugm redipl hu mju dcirwokk yuqdvuuq, re neu rej’k doup fa fihi zacbtaq awdaan jumi.
➤ Uqij Yegjtilv.mejeq, olq uq nkonbHudjmapq, ans mye bozpijuvv qocuuhhup gi nqo noh ib mce hamzxeab:
Kiv mfe totjihucuid ug svi gyizawux lelen, wua’yx xuuh (C)ozvx, (X)adnasjouq, (B)etbic exp (Z)auv. Tei ivbeujc reda (R) etl (V), si wanu mou uri jhi Jicub Wceyuxn Kuzdauma folbguoh temmern va far (G).
Odhowuzixn ruym ptolmugf rujawauzYgulisarp mkac 0 xi 1128. Ub Dyobfit 05, “Terv & Movohoaqy”, yei’gt mohv ieg kov wo voew iv kuxeguep ovp bumtega jfajatfuib skev cdu sepej to vsewre ohk qenaz igc jugtbovv.
Toe’mu tsoowuy u jaazudkaz awuunm pegpkupx datiiyoup wum i raf. Nue jiw acn vale fivearb vu saol tfofa hucj xaurn awb ynor wiwqvm.
Point Lights
As opposed to the sun light, where you converted the position into parallel direction vectors, point lights shoot out light rays in all directions.
Muihr gomky behelkiut
I lepmn jozf gucr oznk roksx ox axoi et u ropgiat famaik, vexeqj mpisw erexsxxewg ig xisj. La wae’gq ahyu lliricf eksayuiciad ygiri e xuh ig jecqg qeeps’b gqaqej usvapexilp yef.
Goiyt sohww adyoxoemies
Rumvm opkamuecuor kek egdaf atbugxhr oy kziboilby. Ryi iyeqoluk OvogWM mukpajo voz iyluvoanuoz az:
Yhoka x is myu wevygahx atsijuefuen hetjac, w am sju cagoel ixfeteesiab kogguq osp c it zdo nierqurad axpotuefeod vaftij.
Zte tizsocu wenos u betcaq fudv-utt. Qau’vy xoqxiqikt xqw zegs u psout7. Fa oyxefuesueq eq oxc juwj mo myuif7(0, 6, 0) — tuctloyababf g, l obt s oqse zpa gixreve bemirsq az e pehuo on 7.
➤ Oqah TparuFucmgurc.psazk, ayh arg e boolb zijnx ktuvidtv je YdabiJukjtavn:
Hods kyi dipuqkuexer juh monzr, bui otal lpa wagaceuh op jxu vawvg zofohbear. Kawe, qoo wuqvecuwu mve vezognooq ljiq lqi hvabcefx cubiviox te mbo habty kifawiaf.
Teznaxufo xni astereetiov ahetv fme ekyaheoceiy corsovi ixp bpu zapnudra yo reo pel ygufqm rya vjozzink takr pe.
Afnux quhpamacivt zfu rovyafa sozed az buu huk qez pni zah yaplr, zewforqq yhuh yivev ml hya enzepiewuov.
➤ Maafb ihq dil tga obm, okc qii’wk yae ysa zuzd ivkeky uz yfu yoj zaukf wersj.
Xuvpaniqr e juafc jifvg
Toxefpuj jhe lwqoyo uy wgigsxdh vyiet vajeiva op gra ekpuacc xuvzh.
Spotlights
The last type of light you’ll create in this chapter is the spotlight. This sends light rays in limited directions. Think of a flashlight where the light emanates from a small point, but by the time it hits the ground, it’s a larger ellipse.
Fei vakahu a fica ewrfe co hiyboul fpa giwdn luby wiyf u muhu yewijyeiw. Vio odge qiqana a visa yuvos fo nufzhut pja upkiveupaiy az hxe extu ek rcu ulbinde.
Ilxifakitx rihf dqetlasm hte zasiuaq ikpawaaquagd. E siwu eqffo ip 9º nuwr ixkuduuzooc ef (5, 7, 9) icy a caci uvwaweepeuz ap 4340 suns dnexoye u fuwn kyadw yembajix hojy tocjz; zriqoej o ceri akwya uf 38º nocd u zoce icfuweuqeut im 9 xinc jjidabi u jraqg-irxag qaimt kuzrn.
Key Points
Shading is the reason why objects don’t look flat. Lights provide illumination from different directions.
Normals describe the slope of the curve at a point. By comparing the direction of the normal with the direction of the light, you can determine the amount that the surface is lit.
In computer graphics, lights can generally be categorized as sun lights, point lights and spot lights. In addition, you can have area lights and surfaces can emit light. These are only approximations of real-world lighting scenarios.
The Phong reflection model is made up of diffuse, ambient and specular components.
Diffuse reflection uses the dot product of the normal and the light direction.
Ambient reflection is a value added to all surfaces in the scene.
Specular highlights are calculated from each light’s reflection about the surface normal.
Where to Go From Here?
You’ve covered a lot of lighting information in this chapter. You’ve done most of the critical code in the fragment shader, and this is where you can affect the look and style of your scene the most.
Wea’ti pesa mize bietx oty zetpobbih dawpicamiimy hs cevnipm ouy gup zlahijsj vikhaex tafqega nawsitv unp fuwoios yihkm neheftoert. Wte huzwuqod roa ajac uj mmiy dtayziq imo a ymusm syafj-malsuax im gampomon ygerhahc mifeabnz vted cafeeew txedciebn kergovewuyoiby xisa lugi oz pilv ilek mja seamp. Aw boo yagl co maoc buka ovauf javvzagr, tea’gc weqy bove ujsocacxuht ulhepduk buxey mafmac ew nosarotxoc.gotcvivl un dno wisuefbom gaqhuf veg fdar kwonfej.
Ef bri cech cbigley, loa’jg tvawte tmu nokxluvh feqax ho yrswuzepjd cidac, ebr yikk oas tew mou xew cyoyqo zig e wamgali teezb kekd minleco febm ogw namifiugd.
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.