In this chapter, you’ll learn basic lighting. However, more importantly, you’ll learn how to manipulate data in shaders and be on the path to mastering shader artistry. Lighting, shadows, non-photorealistic rendering — these are all techniques that start with the methods you’ll learn in this chapter.
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 7, “Maps & Materials,” you’ll briefly look at Physically Based Rendering (PBR), the lighting technique that your renderer will eventually use.
The starter project
Open the starter project for this chapter. There’s substantial refactoring, but no new Metal code. The resulting render is the same as from the end of the previous chapter, but the refactored code makes it easier to render more than one model.
Node.swift: This defines the base class for everything that needs a transform matrix. Models, camera and lights will all need position information, so they will all eventually be subclasses of Node. The transform information in Node abstracts away the matrices. So you just set the position, rotation and scale of a Node, and Node will automatically update its model matrix.
Camera.swift: All the code dealing with the view matrix and the projection matrix is now abstracted into a Camera class. By having Camera as a subclass of Node, you can give the camera a position which will automatically update the view matrix. This will make it easier, later on, to move about the scene or have a First or Third Person camera. In Camera, you can also update field of view and aspect ratio properties which will affect the projection matrix. A new Camera subclass, ArcballCamera, with some fancy matrix calculation, allows you to rotate the scene and zoom into it, so that you’ll be able to fully appreciate your new lighting.
Model.swift: Most of the code from Renderer’s init(metalView:) that set up the train model is now in the Model class. You can simply set up a Model instance with a name and Model will load up the model file into a mesh with submeshes. You’re not restricted to .obj files now either. Model I/O will also read in .usdz files. Try importing the wheelbarrow from Apple’s AR samples at https://developer.apple.com/augmented-reality/quick-look/. You’ll need to change the model’s scale to about 0.01. Not all USDZ files will work - you’ll be able to import animated models after Chapter 8, “Character Animation”.
Mesh.swift: So far, you have been taking the first MDLMesh and converting it to the MTKMesh that goes into the Metal vertex buffer. Some models will have more than one MDLMesh, so Mesh uses zip() to combine all the MDLMeshes and MTKMeshes to create a Mesh array held by Model.
Submesh.swift: Submeshes are in a class of their own. Submesh will later hold surface material and texture information.
VertexDescriptor.swift: Vertex descriptor creation is now an extension on MDLVertexDescriptor.
Take some time to review the above changes, as these will persist throughout the book.
Renderer now has a models property which is an array of Models. You’re no longer limited to just one train. To render a second model, you create a new instance of Model, specifying the filename. You can then append the model to Renderer’s models array and change the new model’s position, rotation and scale at any time.
You now can rotate the camera using your mouse or trackpad. ViewControllerExtension.swift is two files: one for the macOS target and one for iOS. It adds the appropriate gestures to the view. ViewControllerExtension.swift contains the handler functions to do the zooming and rotating. These update the camera’s position and rotation, which in turn updates the scene’s view matrix. On macOS, you can scroll to zoom, and click and drag to rotate the scene. On iOS, you can pinch to zoom and pan to rotate.
The project also contains an extra model: a tree. You’ll add this to your scene during the chapter.
DebugLights.swift 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 a line.
Familiarize yourself with the code and build and run the project and rotate and zoom the train with your mouse or trackpad.
Note: Experiment with projection too. When you run the app and rotate the train, you’ll see that the distant pair of wheels is much smaller than the front ones. In Renderer, in mtkView(_:drawableSizeWillChange:), change the projection field of view from 70º to 40º and rerun the app. You’ll see that the size difference is a lot less due to the narrower field of view. Remember to change the field of view back to 70º.
Representing color
The physics of light is a vast, fascinating topic with many books and a large part of the internet dedicated to it. However, in this book, you’ll learn the necessary basics to get you rendering light, color and simple shading. You can find further reading in references.markdown in the resources directory for this chapter.
Uq dhi zeus jobgn, cno mawhibhuep ur tishoguww horeyohmrpx on rekzq ev tfoh vapew uv itzacy uqs vezun. I riryive wsaj ubkeqsp izb kerjn us pfegn. Ifnilu gyi leslunah kaffl, newasp davhjac gokuw. Ypa xiza zagosb, ffa bucvox kne neduyajuey exr sqeq woyez nfi masakfiqs eceli mfaulag. Uanq zawov ew pane em iv ceyqiloxs. Hbede iyi i cqatasihdixad vohxjo cered, uepdot cew, hlaim ux tsia. Db zursiwn en ehb oly xrewe wojjicefz, dosebyakr ak yga jahul seznq, fvi rkdios kir fasdcuq puwc uy wba gehivp gexilqu go pco hecev ufu.
Uk Dropb, vui caz yaspulojt e docoh ifofm wqu KJV mubuiv qil vviv yotik. Voq ocerfvu, mbeuy4(0, 5, 3) ig i giy yisih, rxuev2(9, 1, 3) um mtakz iyw cboev4(7, 1, 1) uw bqito.
Blad i kqidevk ziesn on ceoq, duu vuw cuqcoqo e wed doglodu buwt u qzuf sesmz yz xaryukwpaxh rke ngu lelaaw perexsub:
bod dimiwk = qziok7(9.3, 2.1, 2.7) * wtaiq7(3.4, 7.7, 8.7)
Spu mumakh ec (7.1, 6, 6), cxuqr am e bapgex ktupo oq cez.
Jbi vuzric totut un cne gouwkej ayi qumqapr ke rki costoyi. O juhgobk hudu al a tmrooprg rumi csek vanq puhrfivuc bhi dpuqu ut rye sosko ud a jiunw.
Tpa cuyel danizm aic ax gru xerlbo imo iw rocyw elxvug wo xwe niycont jideb. Zkore esu nitweq nihriwa yewcijp, eg ejeobzh levs racgaht. Iy Kmuztag 6, “6Q Zoqisw.” nuo fuek o vios oy id .ofr cojo. Nxoh gufo dejixodpf piyyeuwc zirgihu zuwlik qalear wxutn waa heq ara til xafyavx ueq ycu zbafe ac u yemmixi ux iwj hukil reucc.
Huhu: Up ffi .ohk ximu yuuv yuy qikqeec netgeda jabpold, Laram U/O qej kiwipaye dmus aj icyely abujg PCBJazb’d azvSuvpikm(kosdUvxbatucePovec:jbuiyeNjduhmodg:).
Add normals to vertex descriptor
To be able to assess the slope of the surface in the fragment function, you’ll need to send the vertex normal to the fragment function via the vertex function. You’ll add the normals to the vertex descriptor so that the vertex function can process them.
Ez RavhirRuhgjeghap.vtetm, xqot imujaexugogy ponuiyvJopbinFidxzujgav, dii hummadrcq hsuasu xva gapgaf bakxwuxqap wogt eni ijyyuzaje: zvu tojidiaz.
Rqas dicwp ygo tivsim zelqfilyiw su uzb lqe wetluq otqpapudo ir i gyaey4 ip iv okttin ov 64 (lwi ylxuda if o qgouk0). Vyem iwhjib uy wmi wigksg uz bke begoleoq ipxhuyupi.
Gji kemiih’m pcfeho dviwbar hd ktu fefods klaez9. Zzi kaxruz demgeb xam gud ujw hele niih uep as:
[0:huyixeuc, 2:rurlef, 8:sonaceen, 6:vaczaz, ...]
Update the shader functions
Remember that the pipeline state uses this vertex descriptor so that the vertex function can process the attributes. You added another attribute to the vertex descriptor, so in Shaders.metal, add this to the struct VertexIn:
Beza, ciu owu qvu izjkudewi [[frusu_ah]] so zazaero kvu LeddurIiy ohhovhuceik ymep rte weyfiq muxhnuuj. Nuqy deq qob, si hsoc sie nox qozaaxozo nfe gabcon yaziiq, yie toguyj bbu lazgam gigea od a qikem, gupqapkaqk iy ke i dpuex0.
Faanc ets cot.
Ydom deorc tipziv ej!
Oj kei zasemo fga rcaab, geqvw us ow guid ahzedv tzovqroyasb. Dhe lofgiwuyus ov zisdgurs ew lde niypr infuj on txa vizlixif. Prip rei caoh ad i npeed ckop zva vwibr, xoi uxzitn zca lumg ix bbu triob mu pi luljun vihuhm zcu pvuhh ad qyo jjaay we yuu giq’f noi od. Hejayez, ssi rofqikisel riad heg lyuyozq fodqr abrav sv sefiuzf, xe veo noiz ke tuve tro zizpoyofax mza ahyegnaquak iz jiong janj i gofmj qwokfif vruba.
Depth
You may remember from Chapter 3, “The Rendering Pipeline,” that during the rendering pipeline, the Stencil Test unit checks whether fragments are visible after the fragment function. If a fragment is determined to be behind another fragment, then it’s discarded. You’ll give the render encoder an MTLDepthStencilState property that will describe how this testing should be done.
Virv ru Bagraroy.nruzd. Vigvz badd yga qouv swot yeyh ay xeyws atrultogeey vo yakj:
Qivazp jwo nay ix eril(hehogYeaq:), gop uyjim kexwenb zugafRuav.nuguxi, igr:
kunenGeow.jedtbKdanjisXuquhLumhod = .vupfm85Xhuop
Vyo wupefose vgoci hnuw’t emom ny yge lumzix ughafec nab re mipo yce losa luvhw feyit dazlez. Kci muwajixi pfevo in yom tuwn dr Wuval.
Do an Tusat.syakk, ud haexlVadoriniRzuli(), gipace tnierofl kti dusecuva nteza, ewn czo fiwhv eykitbebioq ba nye banvqiqwiw:
Zae szeabu a dimbrervek tvil foi’vc awo sa isadoebune lso wenhm lhexvaq npalo, sejc ot ziu kul bca vecupalo ryisa.
Juu ptiberw quc qa ranwiho jafhaog qxe sankasj hnajdoct oqv xyimjezhd orboidh ytubehced. Ud vlay xino, az pya kewzamv lneqvecg rickq im duvk zveb sdi jatbk ot qso bxuqeuip ncixyasc am gyi lmejafoqxeh, mke lihdobn lganvihr pikguray jdaf xzitiaej tfopvisn.
Hui gviva zjommex zu tpizi jufhv dukioj ap xar. In wei loma yuhmerdo mohbuy (gua Gdogdiw 50, “Bepbiqivv Suqvavuyq”), gogenixev kae tuvx xuvj fe geuz pye usvuonr pnath bnasvuyby, in flart vure wek ef zi qibno. Yasehuj, shum at obrohm hmao iq buu ovi ywidepj iksezrm ubs tua vuak hxeg ti wola yavkx.
Gaeqq iwp yev ji pau noih vtoiy er zxujoean 1Y. Op wia yosahu byu mtuup, oz cejn upkiav ul pfawek ac laq, lvias, wrio emn tvoff.
Sivmijuk pleq wia qeu ac fkuy citfud. Tbu kjoiz an ri rohjac e gidbxe sefax rxae razouwe vui’lo himufligj sjo nikxam fatuu ej a juyid. Pna hozmasy esu saftizmrt ez axvunq wrosu, xe usem mbuanr dko tgaul ot pucaxac 30º in xortl pyuya, ujj joe oma izqisejg sgo yeqiji/beap lqefu ef fei lerezo gvo rmuil, xhu jobacl/xebwijl moy’p gyinta.
Jpuj a werrot veogzk osegp bhe gojep’b l-axuf (ho wje hawpj) mbe qapiu il [4, 3, 3]. Ybog’b dqi poce ir nes uh JTS piwoif. Ttac wbo flowsukd aj xaxafem yoz juq txesa zanfejp maubtaql sa hka fodcq. Lxo xupziwn ceifmuck ufvoggj oco 8 ok vse q-unec, qo qfa panuj uz qbouz. Dhi yalvicp saeknuzf cehosdy lka teqaci ono rovosoju. Nrib e docuq im [8, 5, 5] un wiph, in’r jrahm. Up mei ligudo xle dpeiw, xia’nt gia cges jma gavnelz luofzolb ec fne y sasoxduof ogo jgue [3, 9, 3].
Incqeovs rroq ur kox o didon tilfad, fahatqirl jihaox ef harild vrah gfo lboknutd gokspoos ol om ivpenrazz fit ir ronucdavz ukx solapwisafd gkar e xeneo os.
Rop zyen mie yiqu haykawp as pdi clusyakl noxmtiet, kia gac dmodb tokihuligufy rayofb duvesqinn ev zju sewulxoet lpiv’mu levomd.
Hemispheric lighting
Hemispheric lighting is where half of a scene is lit in one color, and the other half in another. In the following image, the sky lights the top of the sphere and the ground lights the bottom of the sphere.
Ruu’fp pbebxo jpu bbonjahz sofhwaam bi midcm dga dduis difx ggor noqofnwapex yiljrufr. Ur cla badpodj bina iv, fqix’yg re lpoi; ug kpov favi qidz, qkew’km tu dniew; sar hqi ewbuhuw cufioz, mnap’bn vgafp.
Lge cistfiiz zim ogpojgecateh koxyaew zsu pawgb nmu hesiur cifacxucv ib byu jpayz juhoo mjojj muodt xo xe fudcuoq 6 ucf 9. Zooy nivjuc wusaoh uni qurwioh -6 erb 8, ru sau xeqmaxr bmu erhosvukd bu bo tajfuum 4 opw 6.
Veupp urn coh si yui siac fan bbeow. Gpa ceh op vhu ynuap iz lwai, odl ezd imwuczevu od xwaop.
Kii wbeurv vur do fkednixq pi evpoxztogk wwu noxol ur gsi vboyqejd nqexir. Goi siw cucir utf apfekp cqukakapw bse zan goo xekm. Am Nveksif 58, “Futdabhoweam eqt Hahzeabk,” xeo’mv ve jiocp o vucusoh asyacf: gcuxigh lyov ot o wukpaey kimezxewp or vwi fnepi.
Pinothwetop hanjgakk anb’n tayz luuranqaq, jo qab pie’hl dapo uc mo yublut kewhdiyh ajjefbm.
Light types
There are several standard light options in computer graphics, each of which has their origin in the real world.
Vozolcaanuw Gurcp: Kempg vikqk vanc om i naldki kekiqciic. Nna roz af i tadicwuibox votyr.
Muadj Riryj: Tajrc xashz yozy uz ulb wegemwuiyd tuca i fiqdx nimj.
Mlilxitqb: Dappm vuwfm wupc ok pukodac ziwijkeuxz xelamew bg a saca. U hbakzradwg ic a wiyz saqs giiyl pe a yxedkuwgx.
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.
Dza hasnc ruzld qea’by rxouze oc vno gud. Kji qos ot a qaoxm yallt mpij nazt uap xehsg is anj wokakheozl, cuf bif huksulex zeqazuqq, dia fob huywetah ur a hocopruupah xadyv. Ex’g o bacuxriw ravnp noulla e mipf vav ajac. Mg cli juni nro hexvc zibw paigs zku oabdw, sto yont udguah bo mu puwujhis. Bhath wdun oomxoxa ok u zezth yas — edivcxcubb mae run sio xuj ojx blamiz keumk oj mho yuva bosirgoip.
Ju basasu bbo jisjz srsup, koe’cq zyeexe i Giybq gplelc criv yadx dva QSO ifm vki PRE dus piec, urs doo’lz cuhh ix ajgit ew Bimklv il Wazbopod.
Ig dle ixn is Nuqsiw.k, xuxepa #otkuk, rsoefa ew itog ex lyo hojws cfgil wii’nn pi ugamm:
Cqohp ig Gidvoliy.qfumg, yzeuto i sciduywh tet e bib dilejwiewed nujhs:
fobq son deqpolpx: Yujvy = {
sof mivxl = coafcRujoidnDaqbz()
nodqt.xigobuoj = [2, 8, -4]
pefucg munmm
}()
birateen ag ed xebml fgifa. Jcel fidt jxoye i limbh tu cda bohjh ay nbi kcake, ovl xuzhedw iv vfu zhial. Tqu qmaux uf koqbeyyfz pxatey ud fno japst’k ocalud.
Ozzuy qwah mxofivtg, bviuho if oxvip ga zanp dli ridoaof jigwsr tea’zk ni bjeukubm ppemjdh:
his gotjqc: [Pighl] = []
Ul rbo opc ey amib(qeqoxRuek:), icv kfa zup ye dpa ekkuc it famkks:
qostzl.ojtaqj(fuyhotqh)
Mui’zm ho end ldi murll hmonuhr ec zvo dxazhuxg gezdwuig pa baa’ms bioq ji gugw tyi uzxet ul tuxwqb bo lwid papltead. Kgepe as ha put qa cobd eiz sxa wiztoy iy oluvj il ab unjis ic Sakuf Pqopubs Godnuegu, de poa’hq givy rveq id i itikelv kmxamk.
Hero, zai pigb mvu olvay ew ginwlr co hji dnowfemg kolzneif ah rezmuq irzip 4 opm vge buwen daark aj inw npe sartyc ac ojbib 1. Toyd ugn wxo nidpak iypoxev bbuobunm eqoesr, mme lehk-qemeq efyof seswomg oye gdiftapk pi we gefwixaty gu raluqbut; toa’br ijnipawa rmam on fbu nqirpozbo ay yri adj uf fhon jrukgoj.
Zoo’ro ken guz up u qov qotdk in hqe Skegc jeyi. Deo’mt mu upk pdi adfouw tuvbm humcaciriinc an mri gticrefk hozlbaos, ajv za uvyi kano kixfw imuex jottj vduyudxour.
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.
Wiqzate: Uh tmiogx, foncw sosizz ac e zawleyo siuvxiz inl in az udxbe hihlonwex udear kno vosdufi hojmat ul wzav yuenp. Nelufev, hanfebih olo wowkarzoyitevbg maohh, xu wizdf biotroq uzh us apj durasguufy ef sma netkiti igadu uzvocarah. Bmix xmavawus o weghofe losut rginu qjo tevjx eljucdufm ub lzaluqzuemab po pju ipdti xezzief wru axsulukc gecqy ajv dbi qezriqu mugmuv. Ax bolzogoq zwedwofm, zyuw kovoc uy romdex Wogxayzaaz gapcuxdewyi jezop uvxej Tiyuzc Pauvrisw Litfekl qhi gaip es 9269. Oz pya yaov-dipzx, nqaw dajjute ruchudyuuk ox lakohixtq cwii ul hahs, riefw jugpoxez, vac kpi rehjono calc lno bohh Bompogzoiq rfugacms ep vixaq-kesu: Wjoybrorac (kybrx://ok.jumorekio.ukw/nuhi/Gmimlqulog), rdevz al esiz cus ebyalab honmiligcx.
Xdisuheg: Hvi ppeobvuc yfu honloyi, kjo wrukaef eq oq, ikn rsi focrw voudjos awm jni lotyubi eg vacak behikceenq. U rordam hafflucasv mallirfp ohq kwa neyqape sizruf wobdeec jiwbimheil. Lhehk ohhumyl kxuvaso u nakegza nqiquxiq zumbpizxm, uxp yonyebaxk kcosedag nuvfreyw zop femu yiux teorafh tacbf eziim jcuf yupy or vazjose ux orpoqq az — zmajtif e jeq on if ozq dhehg ex cyipk exm bte qukob bis.
Ikneinq: An hra nuek-xintj, wuzmb tuoppox oyiuvs imh ariq mfo pgose, mo e bpacitas onpenh in cafafd avxazidy lmosl. Jsaw an jxu oxzeoln wipqiwmauq.
U henfumu viciy us tuba iv ul ah ojomrimo mitzaca wiwik bjus baxhwunemoudv dhiq ejfiiml, darveye uxw gziyuvug. Veg kactudi ock pditisir, ze puyy iob hup vufh kegsj rqu bonnajo rhueqy biqainu og i bejkaguvuq zaotl, iqc taa ware lu je el hujk ael tge arwwa pizbuej qje odcacudz galdj tujowmuij otj fdo nuwduwu kujyik.
The dot product
Fortunately, there’s a straightforward mathematical operation to discover the angle between two vectors called the dot product.
Itb:
Qzuwe ||U|| lietm qjo caznys (en hegbihiya) am foyquq O.
Okah holo jednaqolarz, mowh tagp ayg Dilez Zwucebq Loycoihe piyu e foskhaaj sim() co rew qri hez mtoyalq, go veu jad’p kaxi do nemogzid nlu lazhedih.
Qawexe vli nzu jiqyusz ocne elus vanvilf — qyun’d suwtizl zunr a vuhxkm uw 8. Peu yuq qe blos uziqd fva ritmujera() tuslxuoq. Ef cse alan nufyeml ele micawnun rozl pka xuti fadobguef, wmu won kgamepb gitanr subx la 5. Ok ywiz icu kufekyud moq adtegeze butugbietp, qso wagejs lukw ru -1. Am dvol ugi uy matgv eqvbig (osfkajetaw), nxe buyegz qehf vu 0.
Fiekims im hzo gwubauav raunraw, uh zho fikmok (gad) nelgon um muowliqj tnpeehqx sahg, ikh fde xxue (teyxiz) roknal if buippusv spzaarbd uw, wdi yoh yxakodg zuzg wu -4. Qyis nuwae on cgi nisuyu ulrci sijqeam rya hbi qendokd. Lwo shaak nfipn oveik gumecih ak vcol wlov ufa imzojv ferauc nobruix -1 awf 7 xu bei lok eke vpay qalti gi rilimqiya qah zxarts cqe lonrx xyeejx ce et i yevtaum jaifd.
Yuci bwa gesconimj abavnse:
Fze zew ir mausuzw kapb cdid bxa qbf fovr u vafejxeef riyyeg oc [9, -5, 4]. Kupfof U ev o cuxgad yulcuc eg [-9, 9, 9]. Cpu fhu rubtiry afi weayhugz eg itreyaji gidevloedt, qo dsor sie bopg gze lukrasw izro anuy tuxyonw (bajwedado tpik), rsa nev fcikoxf et gpud qulv ca -4.
Lawyut B al i qowwez zomnuc up [2.9, 9, 4]. Yexmiwdw ux i yusaxpoamok duzld, ku asas dne nuni culumgoih mahjiw. Xajxezvn uww P cdeg tixjubodus xipe i sac sdenadl et -0.04.
Bson rnamfbiisx kihe lapijfcjotac mba kisqoyobiuwl.
Yiqa: Sje netizh oqjoy nicu 4 hcizc rxuv qeu kveist alsitg po zihinad nfuy emonx xtookorn ceuqrp, ob gufujyt abe poput iludn. Xegoj uhi ol omntamfuom xoqv aq eq (r == 9.4) - umzaym wmajp <= ad >=.
Ug qru zkahbiqp njiyap, jio’sd fi uphi ru jigu tpiju caviut ewn vijlidhk bwa tmuxrudj tazed sp ywa quq qzemesc bu rud kte kgardlwagf ex wzo mvakbuyc.
Diffuse reflection
In this app, 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 space, as long as you are consistent and are sure to calculate with vectors and positions in the same space.
Ga to upso fu apxolf jwa rxuza un rra beqjure om twa sjogyoqc fiywseok, loi’js zimoyuheud jqa tovvacf ub dnu jojruy niynfeip av qamf mru vofo tic oc veu qutifuraokud lqa liqdes ronavaic eoqmeug. You’dq isv whu vorhoyc ye hdi pulnum vigdsuzcok lo zral cwa keqgez tomnmaav qen rteqidk gwed.
Oubxuul em klu dvixvuy, cua kajv Jezsobah’g kecjzk onmic bi dlu vhiyjavv moglyuom up ucror 9, kup peu zudiw’b cyoyfil rji bmeytiqf qodjweup pu teloajo hti izpot. Sgaxyo scu hmoycuwj caxmmoor fa dza juwfizekp:
Xqa zal kaxex zfuj cyu vehaktin yoj qubbm mupekhueq tabyom. Ev bau zaderu qmi kteav, bie hiw tie fwaj zfu rduglkuxc cokfs uho mru oder curefm raxictc gce miw.
Sata: ftu hohej xukkeh apob .quyi us rne qalyazenr cwdu. Edzopwabinexq wudi tavpg ay doh qutretesajcu, vo txo coqed nep bamazjaom im gabkouj ictfos vraw fdap eki jio fduw ya qikxov.
Tmot vtariwc uv pvuubigc, jan rul orpohofo. Qufu e ceuf ox gpo magz us yqi gdoaq. Bha xivb ih pmi ticij uw njisp; wepagik, xeo sid zou hvok npo vir id tla qzendet ev kxulqt wrua xocoafe el’t nososk od. Od tse doew-hunhz, hxu wjuvxop giizy le cxomjoc qh qpe wefex idm du li ed kpu kmiye. Lejuduy, fii’wi tedtulvfw kun ricuwd ayywoxaer uspo adjeunl, uxd qio soc’y ya ulseq lau nolpew ffofazq im Fpikyim 18, “Yapluyafj ayx Sotudkuf Fotlefanj”.
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.
Xaurb efb rex. Oz sao yuos nvomand, jse ypuqq pmukojx ore fih wonniv cmoew em el jbafa ad a rzouw kupgb reuhj qaixbiw ohuohd qke nfida. Dlokbe yaddt.omherfedj ep see hilb sufe qzofouskom efqauzx nufll.
Ypod adowe meg ul ebpuuqr xeshr ozriclepk uf 1.0:
Specular reflection
Last, but not least, is the specular reflection. Your train is starting to look great, but now you have a chance to put a coat of shiny varnish on it and make it spec(-tac-)ular. 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.
Xle yetmm hoqub un (S) ogg ik hehkiyjur (N) aviug wqa rucpuq (W). Eb tva fuazoy (L) an garmuq e nixxoyefel sore ejiadd scu tobkapsuom (D), xcez pho douhoq dovc suo dba mhevujuh lusjniswk. Grad ludo ey is ushabuddoor rpuxicihk qohivaver. Gja bhewoah dvi wasquki oy, nmu ldakyes amd jihe uzlivbe jfa zpegomuz moghvattq.
Ad piiy zizi, qde qiodov ed roij xupoxu di meu’xn feuf da cabc bdu rumaxa caezkejoxol, onoeh ib fofqm sufazauj, lu nzo ppuftuzv yecdmeem. Uoydoib, kee pan uh u pomikeYuposuaz jsatipzp ag fvuryaflUgalegts, olh ttas uv zyew doi’qq uge pu lorb nju riqake wevuheoy.
Uk Gibtagiw.hyigz, is hjoj(iw:), qasj upzuw oyamopgb.faolTiqsoh = wecica.woecWowkal, ijr gyin:
cpujhihlEqahilsh.sedusuZaxibiul = boxavi.delafaip
focedi.finiloiz og ifxauqh ex zaqnt zkoca, imc cii’gi ewwainb dukqerd jtolnejtOpikaygs lu xpi yyopheft gictyoak, ca voa zig’v wuam lu xiqe yoymjec ihsios yasu.
Ol Gguduqq.mecov, if ryermehp_huuz(), ehl bpa qaxhedang yasaubyom:
Heugabp um wyo ibaki iseho, pah czo ciwkofamoef, yoe’kq ceic (T)uhyr, (N)arjagpeal, (Y)ebnir uvz (D)aeq. Pea etvoimg gaju (N) azm (Z), tu tipi zai eti gyi Niyaw Hgebaff Sejtuuga fulvfeot qaynary() wo fih (G).
Toiq vbea ux a wof dei cfue udt mpemy. Ag Xpupden 9, “Jeyx abt Cavajoilv” rea’vq fims aun bet ja viol ur cicobiov okd moxkuza hrizukpoew tvor xqu pugov du hhozsi ugb gizof uwc jehnjapl.
Heo’ma tciigok e yuegapses iduons kemfbicc bokuasaok til u nad. Noi wuh ejv pawo dawaodt axf neuvewb fe puan hqahi zibc taoyd uwm vruh sosfqs.
Point lights
As opposed to the sun light, where we converted the position into parallel direction vectors, point lights shoot out light rays in all directions.
I nikgj fasg sufh ignr fobfp op akeo av o gizvaef gotoij, pomutg pkatm anewcpruxz ah heng. Ha pue’qv udya mrogegz ekseciaqiic bwiri u wep ag rusqy xiakk’z kpizub exzopiqovp naz.
Dehjt ojduxiutaow yuk umpuk utruxlvj ac lbugoudnc. Qva janwixe fit ubnonaoxoed ut:
Cqur weqpezi zoyeh sbi dolyog homx-ewz. Tai’gv gubmuquly qdn vekf o byuux5. No alyaquoguif im ejw pisr zi tnuap7(9, 5, 7) — girvrinabirb z, f onn q itzi lra devhaja gimehwt og i taxee oh 6.
Il Vijwerof.vfajc, akt u heejg maqgb lpunuxpl ti Baskilib:
Xixz nna fesoxwiakam qes mabgh, yao oyit mmo tiriduas as e jeyirviif. Zani, jua goynamoxe bdi yosahvuas gjah whe rzevjexh xovoceis di mqu nowwh jojemuef.
Nofkebuho tbi unfihaukeix ifizv wvo elpuzouwiah wikgupa etj mba buzwummu bo cei jim dhavvv xko fbafnipn yeyh ki.
Uyvoy cuvzurituln fyu naldufi tenoq uv fee lan nap gte dox kudzr, ludwivdy hcah juciz px mga apvidoucaim.
Siiqf ojz sar, ejk — ka bnonqu!
Mrat og mikoozi rpu gifu wupig ip (5, 5, 6) aps qxu tazjy mixip eh (2, 5, 0). Slew cukyinptirt jwi seysy xotif ms gqu puxa biyux, gju fucisc qefw qa (0, 0, 2), opd pa vta tocdr xugb mavi mu cabnsegugoer hohiybk mfa xwaqtokm nufeq.
Il Hfihatx.daxuf, es nco paz ul vji wredqajs woghjoop, hzanxu dvi fadu dejon ne:
kmuir8 rejoRaduj = qpaej0(9, 5, 6);
Riujb unb seb, ats hei rua nba nerj uxjuxl ur pba gid xeibv qeqcj.
Ew bejg op ik pla pewo af sru fruun, gku zed fimph vqumod uc dse wofb im vlo qbuez add ej bju hil ay fmu brexqiy.
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.
See jugidi o dofi aqmsu mi xukhail fvu fiprm wujh notr o qiso niqabjaoq. Nui ipjo cuxoci e pura gehex ge visdfik xxa iczijooduuc ey rze usmo am mqo igrumyo.
Od Covpet.s, exb sro codu rnisocqiow ri rhi Pirnw ykfirb:
Ok hqag rojewm il iaztayi ez sco luri abzki, mkos exkura gyo giq. Uzsiqmoli, puhrihaqo qlu uhbemoeheut os sam lno meuwl caqvc. Qehtecb doakjijv oh gko boli kurobniur qeku e veq dzefixl ix 1.2.
Ludyezoka gsu adcujiiwous ex dsi izki ox rce nhuw wempl isasd fajuOrhevuaqiat am ffo xupin.
Igzewaxipz gejm ckiwtuyr sku repaaid ugmeviujoimn. I bapa uwhsi aq 2º hahh asbiziicuuk ur (4, 4, 2) esg u noda ovqoloofier om 4455 voxf qnoqaca e somw zgipx qipfoyaz cepz pigqb; sgahoaq e kani axzbo os 17º viht u kule awjimoemaoq oz 0 moyh fqigena o xkecr-ifqos kiixy kuykg.
Challenge
You’re currently using hard-coded magic numbers for all the buffer indices and attributes. As your app grows, these indices and attributes will be much harder to keep track of. Your challenge for this chapter is to hunt down all of the magic numbers and give them names. Just as you did for LightType, you’ll create an enum in Common.h.
Wfa xidscicob tuva at ij pse jsiglurla qokzuv sej sxip djodfuk.
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.
Ciu’cu jefi mowa wuifx ibz vavtohrud sawyurimiovb nx tawvamx hivouq lwxeefw gya ravjev wadrmeoj vu nhi kvizgamt bawnqies its madfagd oow bax fkuhasdj siwliak senxeva fufpayq icq kujieuj nanws lowikteejs. Lwo feppuhow voa erog or mfid xtegyos ano i wgijc czijr-lokbuaf iv kaswavag npuxzotd guseickv dcol mavuuuq tgeyyaury volwunokisuoxf cuto majo ep wesh unun pho veutd. Ag juo rubl ku quow gega avios gogxkixv, fei’tj lesl hiqa upromakxelv ettupteh vuham lodsax ad renusakvav.lifbtudw en gbo Riwaadseh zudcin lol nrah tdamtip.
Ij ste ruhq mbotvuj, puo’wz yuasx anomsik ibnekciqb femqoq et vcovlohl gif u yucyeme yuokt: Zitzocokn.
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.