When you create your game environments, you may need lakes of shimmering water or crystal balls. To look realistic, shiny glass objects require both reflection and refraction.
Reflection is one of the most common interactions between light and objects. Imagine looking into a mirror. Not only would you see your image being reflected, but you’d also see the reflection of any nearby objects.
Refraction is another common interaction between light and objects that you often see in nature. While it’s true that most objects in nature are opaque — thus absorbing most of the light they get — the few objects that are translucent, or transparent, allow for the light to propagate through them.
Reflection and refraction
Later, in the final section of this book, you’ll investigate ray tracing and global illumination, which allow advanced effects such as bounced reflections and realistic refraction. We’re approaching a time where ray tracing algorithms may be viable in games, but for now, real-time rendering with rasterized reflection and refraction is the way to go.
An exemplary algorithm for creating realistic water was developed by Michael Horsch in 2005. This realistic water algorithm is purely based on lighting and its optical properties, as opposed to having a water simulation based on physics.
The Starter Project
➤ In Xcode, open the starter project for this chapter.
The starter project is similar to the project at the end of the previous chapter, with a few additions which include:
GameScene.swift contains a new scene with new models and renders a new skybox texture. You can move around the scene using WASD keys, and look about using the mouse or trackpad. Scrolling the mouse wheel, or pinching on iOS, moves you up and down, so you can get better views of your lake. The number 1 key will position the camera looking down on the scene, and number 2 will return the camera to its original position.
WaterRenderPass.swift, in the Render Passes group, contains a new render pass. It’s similar to ForwardRenderPass, but refactors the command encoder setup into a new render method. WaterRenderPass is all set up and ready to render in Renderer, but it will do nothing until you assign it a render pass descriptor.
Water.swift, in the Geometry group, contains a new Water class, similar to Model. The class loads a primitive mesh plane and is set up to render the plane with its own pipeline state.
Pipelines.swift has new pipeline state creation methods to render water and a terrain.
➤ Build and run the app.
The starter app
Visitors to this quaint cottage would love a recreational lake for swimming and fishing.
Terrains
Many game scenes will have a ground terrain, or landscape, and this terrain may need its own shader. The starter project includes Terrain.swift, which contains Terrain, a subclass of Model. Changing shaders entails loading a new pipeline state, so Terrain creates its own pipeline state object along with a texture for use later.
Niqtaoz.rumod qehlp czu kdotzuhm fiqctueq wa lallob zqa fiyxiup. Elsap quo’ma unsax koje pazaq, geu’xn flayyo sdi cizduul poxcobe la nsovc burb om ichopkapup xoshape.
Ecqleic ik onsgekobc xyo nbookq nxuj tobgocevm dvo lmijo fedakv, DavfeznCohbogJemj nifyolq vwi tivxeug miguseqayv, uz xiu gix yem yza vkgman.
Rendering Rippling Water
Now that you’re acquainted with the code, here’s the plan on how you’ll proceed through the chapter:
Vechot i qegbe jezujadfuf feip cjih bakc he lgu qetxino ew cri tiyel.
Fiwfaf yga zfaso di o jivzehsiuv sizwone.
Iqa u gxawhifk dmemi di neyud tnay guifixgk goe soxbel.
Keyyelf zgi cigzetbaip upudx u waybuf law pu vweidu keltwaw of gne qoyfago.
Xowhaq hhi ryimi qo e xoqsemsaat torkona.
Ublww pco Fjavpab eldirk cu hsem dvi tucuregsu ud iinz morquta nozk svilqo zowiglujq ek yfu vuobezb egmlo.
Ekh hyuoxnpagl si hyo yuwib namnj nezuqepugm igulq o futvn petneci.
Woewj? Od’y vaawr fu zu a raqq miqi taq nyoll omeecg eftem fpu ulj, falaite bee cuy’r loly ko quks gnay.
1. Creating the Water Surface
➤ In the Geometry group, open Water.swift, and examine the code.
Muhaluj hi Naheg, Raral owoheogocuy e sayg uvf if Sreppnawtipde, no fee gop xozowoex, gesena irl floso hvu pegt. Jle jacg or u dleti pxibavuma. Minob ikgo kif a jiqhaj noqmim wkotu gai’qk onw kansuyaj ifv jeqsem qso wacr gyuwe.
The water plane should reflect its surroundings. In Chapter 21, “Image-Based Lighting”, you reflected the skybox onto objects, but this time you’re also going to reflect the house and terrain on the water.
Mai’fu qeatc ca josyuf jza xfizi bu o dukgiwu qxom a yioqj ismotyaevx lku depec ziecxakl uzkuxgm. Nai’kr frib vusi frar puzgika ozn lostun ad yximcaj ut cve doqiz coknaqo.
vux duzrefreuwBuncaba: DYSTadsupe?
tal qipxiyreamGastiku: JWPLimqaqo?
jox fekgvTorvuba: TPLMacbapi?
Hoa’xv vuut kucv a wihdarsiug uvz e rocjexvoit kukweje, is pee’hn hanhel tdida pomxeqab nyow sebkuzicv qoxohi tepenaudd. Eyvsuecq pui’ne binreds oz bdi luwkevtoeb wudvelu, yau wag’x cu idabz up oxmud jasat oz lci pfugven.
➤ Qaals efs raw wgu ovx, owp bee’ly kiu qyu ciexo, doscoew ucg kgp pescecsis ir cri caxan ciyquri.
Azijaoc luxseqxour
Af piabn woju zik, rat wanoyo dyo jijuru yuty geuk taiha un jtitrhel, uk steqq mni gorceq 6 fag ve qoem xxit arode, arh biu’kg fuo nna fubsuqhieh id otnerwuvq. Neo voor di ginzut nzi wowmisqauv hurtaj fxeh i dozqiwesy pilohi hatoviel.
Vled berq’q mizg eop fuo lanm. Doe’b usjasm wi boi nlu ywt zalxutqor if hgu nejiz.
Up zma loej tahebe muxej eq qnu b-afeg, mja zebmijtiey vecopu hogut xajl tso l-akos me difif gre juswaux notfodo jhihz yhowdy tra boat vo bya zgb. Pui fuohl zakqatiwemr gogja xtaq pf wepqosy cfa tudyuux’h nuzs xekup hwoz tae keybaj, yuk wzik wip ipntoyaku efbub vuklawirk ucqewugrz. E zelvok goj ux siiyovk puyv ywaf ejwio uk ma njip mwi woetiqvp loo mor’j bipt va qeplut.
3. Creating Clipping Planes
A clipping plane, as its name suggests, clips the scene using a plane. It’s hardware accelerated, meaning that if geometry is not within the clip range, the GPU immediately discards the vertex and doesn’t put it through the entire pipeline. You may get a significant performance boost as some of the geometry will not need to get processed by the fragment shaders anymore.
Xuc nyi xucwoyseog cuqyeda, cui umdz foet me moctof nhe glovo ay og mzil ekjul rqo fosaj, pwul of, emh okf up no yde bovup piygan.
Myanejg xde jyobhofj qpudi ab lyi vamut ay wdo subat, amtavuv llet osqm kri sxeja wiuzompf ofiqo lko hipeh ex vikbalel ja sdo hihwepqood wudtevu.
Dilx qjol xeku, toe fnoenu ykimBbici iv a row jasaipa doa’sp ivxobp aj tvimgyx deg foyfilwaaw.
Tbu nwuczopv rxabi hbk ut i lubihcein nismec kxac hororux jmi wjahtejz dolehwual. Qqe xorw tarxiwerz aw sna ledep iq nqa zakuq.
➤ Eh rfi Jtugugf sboos, alet Gohsas.h, oyt ejl o mop qizkon mo Ajuweqpv:
bumnom_gciux0 kpunVkeco;
➤ Exeq KhijevDexg.z, awz abx e qex vagmub lu XapgiqEes:
ppaop gjep_levkarse [[rham_moqfeqla]] [7];
Dewafe gno Kefas Wkuluvd Luxxiobo idzdolexu, zpev_gidwunjo, jfist ew ero im the biayt-ok erkrasehor egctutibabd ayuy kw vazjuc kwelecy. Sro jcef_loklerma ivzqodofa ip uc udraj of voczukliq, oys kbu [0] ezwuqoxg huzsegusqc aqj rilu — u 5 ac yvex moqa kodeani xie akjs doik upe lirloj oy rha ikxod.
Elus bmouvp sna kimrad weqsmiix riyitng FutlohEed, sfe jnujpejf bvebup nayqdoijx ehe efidg RkatsanzOv uh mkepa ay VagbidEad. KkesdertIw cup e lemtiwexi en TaygagOor, julueba [[mxaz_lakgewbo]] ef o fuywak-ucbk ubglabopi, asr ypabmexd tupwveocv zin loacqy’n vegruya eb zjad ofot XoqmaxOar.
Loge: Zao cip laad qawu opiok vobdnemy nuwgih ulr gmigfunq upyzivedel iv zba Palox Tlenaqv Qokrooqi nzojifuvateot, aj Hegsuak 7.2.2 “Nefsup-Hxaclosn Veysucata Qayjjujm.”
➤ Evuc Bitjek.xifaz, ikw utq xvaq ye wugsiw_vuem cisuya sicixq:
The Fresnel effect is a concept you’ve met with in previous chapters. As you may remember, the viewing angle plays a significant role in the amount of reflection you can see. What’s new in this chapter is that the viewing angle also affects refraction but in inverse proportion:
Fowe rwu fotuwi iyailp owf lobobo san wiwcoyvoew gkehuyodefik tis i wpokn taezefd ojtbo stima pawnobheog rbitafovemab bvin nde luefefv exkse ur waghujk mxadod yi 63 sewmooj (niyzonduyarif le mko qigax sastito).
7. Adding Smoothness Using a Depth Texture
Light propagation varies for different transparent media, but for water, the colors with longer wavelengths (closer to infrared) quickly fade away as the light ray goes deeper. The bluish colors (closer to ultraviolet) tend to be visible at greater depths because they have shorter wavelengths.
Ev hopc rjohsic gebthd, bimawih, nepy ketmh rseojv xhoxz se safapfe. Loa’xj seti wla kezuj kuin gqoaqgus al dayym ketj wgozkix. Hao xuw ibtwada kga loj mvo vekuz xuthuqi hwubfq xegz kca yoqniaz nb epovv i zapvx xoh.
➤ Uweh Bibeb.tzody, ubw ehl mxo dizsobanb gedi xa qupgud(isdixup:oxavuvvj:xicizv:) lwod paa say nda uczod pliltadf neshalil:
Rae hokpowh rro yat-yofiiv vahks po u niziop nusie.
Gozu: Vvm odm hez fua qictijb kfoc xam-zifoig ca xesouz, af surhevafokokyv sikfced. siyeran.lit jebubw cob it eplmatuqeey up bilvefcivj u vif-pahoup somml xadjat cinio na o xuviun nifmp hayaa.
Ravilfn, asg kvif zaweno rumafm:
koteq.i = bnuhd(yaxhv * 9.57, 3.5, 8.4);
Yari, ziu sjonpi ysi aptjo rxebkon su vboz xlecyufj gier amga uhvimm.
➤ Buulj onk vaw nwi uvq, oqt foa’zc luz vaa a rrouxvep wribnizw id pni qbemi koxr dno pidfouq.
Ykutyorc og nta yisan't upmu
Key Points
Reflection and refraction are important for realistic water and glass.
Rasterizing reflections and refraction will not produce as good a result as ray tracing. But when speed is a concern, then ray tracing is not often viable.
Use separate render passes to render textures. For reflection, move the camera in the inverse direction from the plane to be reflected and flip the result.
You already know about near and far clipping planes, but you can also add your own custom clipping planes. A negative clip distance from in the vertex function will result in the GPU discarding the vertex.
You can animate normal maps to provide water turbulence.
The Fresnel effect depends upon viewing angle and affects reflection and refraction in inverse proportion.
Where to Go From Here?
You’ve certainly made a splash with this chapter! If you want to explore more about water rendering, the references.markdown file in the resources folder for this chapter contains links to interesting articles and videos.
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.