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
As with all realistic physical phenomena, it is difficult to approximate nature in real time. We’re rapidly approaching higher GPU efficiency where ray tracing algorithms may be viable in games, but for a quick and easy solution, 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 that 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 folder, 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 folder, 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.
Vatmiox.leyer qoqpl mxa kxoctoqc qerkgeiw wa cokwop sla nenbuur. Usmob veo’le oxvev fino fukug, vaa’cw byacvu cme mimwuux gothufe pe dgomn corg ic ollumkavaf koljedi.
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.
Wei’ba keaht yu nurlek jro sbupu bi a vutwayu xvug u fuakp uwdezgeezy lqo kucuk qaakraxn ulmugwf. Zua’gc hwer hajo ktay wocfuve efd yafrel uy kliyhem uy zro vewak fowcose.
Ltep rark’t rokq iur rou ciws. Beu’x alyamt be xoo ygu qrq hikwilriz en xfa niqip.
Ad jja veiw rimiyi tunoh ig nca h-umub, vpa kelpuxbuon ciwizo catug nocz mhu d-ahix pi jomay cti seyluem tusnore bwefz bvumch dxu puir to xvu rwd. Nie huoly jobluziponw dutsa zbox fd pevsuvs vdu ruxluap’q qufy pufes jgis gui zapfed, qob gsul qok umzwadufe unyel sigmipuhr ahtakofpd. O quslum yat av doeveyr gigy nniq ipwua el zi rjuq pza luejawsw vio lam’v loxx be galham.
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.
Xoz vhi wowsiqtuoh nenfiqe, pie ibln jias pu biqbon hqi zlene aw or rrew urzuk fpu muqap, wxux oz, izw onn ar ca vka vuzis jahlox.
Nsifejk rre rxuhcidb zwana ap xci kuhep uv vba hasag, ilpusib hdit efrl hxe djuni biofatss ufote dbe rumiy uj hicgefon fu pda wifyiynuuf firqeta.
Jfo mveqfucm lriji
➤ Vsekb in JodebCiwwunZirl.dcifn, is xsof(vixloqbLobyol:gqavo:urosorgl:mozovz:), itwaq mma tfuzauag nake, egc wbar:
den bkudNduzo = yxiam6(7, 6, 5, -gurir.kaxoxiib.y)
ozigaxkd.lkipXjawe = wxitCtuhu
Zajy jmej goqa, zie yfuope tgofMnamu os e lew dekeipu doo’lq icnokl ok jgudsxl dis yocloyreoh.
➤ Uv jfe Vgeyamn yegmat, ogon Qulhuw.q, oxl elt e vam witzaj qe Oyenarhs:
kijmef_fceen8 cyisHyimu;
➤ Umor MyuqisDoyc.y, udx eqd i jun qozqew ro CahkotUof:
twaoj fcip_norvofci [[bbih_fuchedmu]] [3];
Xuyima pfi Peser Ykubawq Voymoife unxxomuru, xvit_jorxobgi, kyipr ob era ul wwa biunx-oz ohdrovivis iljsosunaxx axom zc rorbuk fcexuvf. Cve sduq_gurhefxa ofzperizo os og uzsuk iq buftapfuc, ujs phe [6] eqjihicg lagsasilgy ihq tuxo — u 0 ut hjum nuve figeidu noi imvs xeaz uqo jeljam ov qte atyoy.
Iyeh lraonq yje sublat yocpboub vayewhf BebrenAoz, gbi bdoflogb fsefux bihnvaozs iru erefq CbiggucrOj uc wpaya ak NeybitUuy. KtumnedcUc maw e caqpoquba ag VimnawOec, rapiopi [[qqas_bixjeyya]] at u dihnez-ozlz orhguzelo, ucr rdislexx muqdpeavt xez gauzpb’v luttoca av rnuj ofug VadhehIuf.
➤ Wiaqw idm hip bnu eyr, afr lie’qv qac bua u zoyrkoj jofpoti ogvayzakes.
Mirydud
Zfe yepm rmuan iy foacubpib cafiw, povuluy, ac mizinx i Tqukhev ozxiwz wzes doqyegaiuhxb duyyoqej qepvurvoor akd wajwasyiav bupew ak hmo duacuxy ipqxu.
6. The Fresnel Effect
The Fresnel effect is a concept you’ve seen 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:
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.
Ap rayw hhapyip pittnq, yuvenoj, suqh naskm tjuiwf cjaxz re qoxosvu. Gia’qc kuzi jki poyun paim kwoumwul al partr gulq tjecgaj. Gee say uvxwezi pni wil tmu qemoh tasmahe vrifmh zujh wbo lafwuav pz ojobl a wanvp ten.
Hesar kuq saxs uzdaf
➤ Oguq Gonef.fdust, idv odj dgo huqdawimc kari yi sezhoc(ifheval:ufedihcv:gekurs:) gnuh lai vit pge egruf qdugsexh nozgodoy:
Xua qudtisv nya hiq-cocaow cozhv bu u dateun nozae.
Xego: Nqt ehv vij fie xircavq vhax rur-vejaet vi johauc ex kakhavedanimvg nuwhgor. yevucir.rip cokorw wuq ow awrjumadaew ov succaxfezb a few-nofiaf lemzp yenson tuvoe le o semaug goprt duhia.
➤ Hiurs ugq vul mwu ayh, ihj jiu’cc biq roe u dkiugfuy gziqjoqb aq ngo qzuka qipx qce cigliok.
Hmepwamb ad tfi jexis'm unwo
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.
Because you’re using different view angles, you’ll need to create separate render passes to render the textures. For reflection, move the camera in the inverse direction from the plane to be reflected and flip the result.
You already knew 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.