Browse Source

Add fog to terrain example

Quest and WebGL platforms currently don't have working wireframe, and
without it the terrain features are not recognizable. Fog adds depth
perception cue.
Josip Miskovic 4 years ago
parent
commit
0178844baf
1 changed files with 27 additions and 3 deletions
  1. 27 3
      examples/Environment/Terrain/main.lua

+ 27 - 3
examples/Environment/Terrain/main.lua

@@ -1,4 +1,24 @@
-local terrain
+local terrain, shader
+
+local shaderCode = {[[
+/* VERTEX shader */
+out vec4 fragmentView;
+
+vec4 position(mat4 projection, mat4 transform, vec4 vertex) {
+  fragmentView = projection * transform * vertex;
+  return fragmentView;
+} ]], [[ 
+/* FRAGMENT shader */
+#define PI 3.1415926538
+in vec4 fragmentView;
+uniform vec3 fogColor;
+
+vec4 color(vec4 graphicsColor, sampler2D image, vec2 uv)
+{
+  float fogAmount = atan(length(fragmentView) * 0.1) * 2.0 / PI;
+  vec4 color = vec4(mix(graphicsColor.rgb, fogColor, fogAmount), graphicsColor.a);
+  return color;
+}]]}
 
 local function grid(subdivisions)
   local size = 1 / math.floor(subdivisions or 1)
@@ -25,8 +45,11 @@ local function grid(subdivisions)
 end
 
 function lovr.load()
-  lovr.graphics.setBackgroundColor(0.208, 0.208, 0.275)
+  local skyColor = {0.208, 0.208, 0.275}
+  lovr.graphics.setBackgroundColor(skyColor)
   lovr.graphics.setLineWidth(5)
+  shader = lovr.graphics.newShader(unpack(shaderCode))
+  shader:send('fogColor', { lovr.math.gammaToLinear(unpack(skyColor)) })
   terrain = grid(100)
   local offset = lovr.math.noise(0, 0) -- ensure zero height at origin
   for vi = 1, terrain:getVertexCount() do
@@ -37,12 +60,13 @@ function lovr.load()
 end
 
 function lovr.draw()
+  lovr.graphics.setShader(shader)
   lovr.graphics.rotate(math.pi/2, 1, 0, 0)
   lovr.graphics.scale(100)
   lovr.graphics.setWireframe(false)
   lovr.graphics.setColor(0.565, 0.404, 0.463)
   terrain:draw()
   lovr.graphics.setWireframe(true)
-  lovr.graphics.setColor(0.388, 0.302, 0.412, 0.5)
+  lovr.graphics.setColor(0.388, 0.302, 0.412, 0.1)
   terrain:draw()
 end