BLOG

Notes from the KAYAC hyper-casual team

Height-Dependent Fog - Getting That "Gas Pooling in the Low Ground" Look

Takashi Hirayama

Screenshot of the sample

Click the screenshot to go to the WebGL build.

Hello. I'm Hirayama from the Technology Department.

This time I'm covering "fog that changes with height". It's a kind Unity doesn't include out of the box, and you can use it to create the feel of "water vapor pooling near the ground" or "a suspicious mist rising from a poison swamp". It runs reasonably well even on a Kyocera S2 (GPU performance about 1/8 of a 2014 iPhone 6 Plus), so speed shouldn't be much of a problem.

The source code is on GitHub, but unfortunately it isn't a copy of the standard shader with the fog added; I just made shaders that do nothing but fog, so you can't use them straight away. If you take calcFogHeightExp() from Fog.cginc and put it into your own shader, it should work. Or better still, learn how it's made and make your own, since I'm not confident it's bug-free and I already know there's room to make it faster.

About the sample

The sample with the WebGL build is for comparing the effect of three fog techniques. The four strings on the left, Exp, HeightUniform, HeightExp and None, are buttons; press them to switch.

  • Exp: ordinary fog.
  • HeightUniform: the fog disappears above a certain height
  • HeightExp: the fog gradually thins out the higher you go
  • None: no fog.

You can rotate the camera by dragging. The sliders on the right are as follows.

  • Strength : the distance at which the fog color is half mixed in. For the height-attenuated ones, this is the setting at y=0.
  • Attenuation : how much the fog thins with height.
    • HeightUniform : the fog suddenly vanishes at twice this height.
    • HeightExp : the distance over which the fog's density halves. If it says 1, the density halves for every 1 m you go up.
  • Cam Distance : the camera's distance from (0,0,0). Increase it when you want to see from farther back.

For each of the three techniques, you can choose whether to do it in the vertex shader or the fragment shader. The vertex shader is lighter, but the picture you get changes. With few vertices, as in this example, the difference is obvious, but if the mesh is reasonably dense nobody will notice.

Fragment shader versionVertex shader version

The left is the fragment shader, the right is the vertex shader. Since this is the HeightUniform setting, the fog should disappear sharply at a certain height, but because there are few vertices, on the long, tall boxes the fog's influence reaches all the way to the top. It would also be a problem if you made flat ground out of 4 vertices. If you do it per vertex, you need to subdivide a bit even when the lighting doesn't call for it.

By the way, the slider at the bottom of the screen sets the resolution, for measuring load. Be careful: at the right end it draws at 4096x4096 and gets ridiculously heavy. On my Kyocera S2 it only manages about 2 FPS.

About speed

To give the conclusion first, the load is barely visible on the Kyocera S2. HeightExp is the heaviest: at a resolution of 1510x1510 it adds about 1 ms compared with no fog, but even without fog it takes 47 ms, so it only goes to 48 ms. And if you do it per vertex, even that load disappears completely.

On any machine that can run an ordinary 3D game, I don't think you'd notice it. Still, it doesn't hurt to at least try doing it per vertex. Then again, "47 ms without fog" is itself a little suspicious, so the cost may just be hidden behind some other load. A bit of caution is probably wise.

Motivation

Just the other day, a request came in: "I want to draw three-dimensional fog!!" Thinking about it, I realized I had never really given fog serious thought.

These days I think expressing fog as part of volumetric lighting is the more elegant approach in theory, but techniques of that kind tend to involve things like:

  • using 3D textures
  • looping inside the shader
  • using post-processing

But we're dealing with smartphones, and as I wrote before, their performance varies by a factor of several dozen. On top of that, fog and the like cover the whole screen rather than part of it, so they easily become a problem. It seems to be built into the High Definition RenderPipeline, but even LWRP is heavy, so that's out of the question.

So I'm looking for a way to "tack a little something onto a forward-rendering shader, at a level where nobody notices the extra load". I want to go with the circa-2005 mindset of "write a for statement and you lose" and "write an if statement and you lose" (sadly I couldn't get rid of the if statements).

First, write the simplest one

Before doing anything complicated, let's build the simple, basic version ourselves: "the farther away something is, the more fog color gets mixed in". It's in Unity's standard shaders, so there's no real point in making it, but I've forgotten the theory too, so I need the warm-up.

Incidentally, what you want the fog for matters quite a bit, so let's sort that out before building it.

  • To give a sense of depth
    • Showing colors getting paler with distance gives a sense of depth, and makes nearby things stand out from the background.
  • To show mist or smoke
    • A steamy bathroom counts too, right? Combined with particles and the like, you can use it for snow and rain as well.
  • To avoid having to show the distant background
    • A pressing matter given development budgets and processing speed, but I don't like it when everything suddenly turns pure white less than 100 m away on a sunny day. You used to see that a lot.

Broadly speaking, there are about three. It's worth remembering that fog can serve these three purposes. The last reason isn't something you can tell customers directly; you use mist or smoke as the excuse, so visually it ends up the same.

And while colors losing saturation in the distance and your view being blocked by mist or smoke seem like different phenomena, they're the same in the sense that "the farther away, the harder it is to see the original color". That's why a single mechanism called fog can express both.

Thinking physically

If you "replace an object's color with the fog color the farther away it is", you get fog. "How far away" and "how much color to replace" are a matter of judgment, and there are infinitely many ways to do it. That's a question of art, and you could say you just need to build the mechanism so that it makes good art.

But apart from the art, I don't think it's a bad idea to know how the real world works. Everyone is used to seeing the real world, so it looks natural. If you want realism, using the same mechanism as reality will be more realistic, and even if you don't, it should be a good starting point.

An object's color reaches the viewpoint as light of that color. Along the way, something in the air blocks that light. Maybe it absorbs it, maybe it bounces it away, but let's not worry about which.

Hitting the dust, water droplets and whatever else is floating in the air is a probabilistic phenomenon, so let's say, for example, that every meter it travels, the light has a 10% chance of hitting something and being blocked. If there were only 10 particles of light, losing just one would be the most likely outcome, but sometimes none would be lost and sometimes two. But there are an insane number of particles of light, so it's fine to say "exactly 10% is lost". This is the central limit theorem at work, too.

  • Travel 1 m and 10% of the light is lost, leaving 90%.
  • Travel another 1 m and another 10% is lost, leaving 81%.
  • Travel another 1 m and another 10% is lost, leaving 72.9%.

It goes roughly like that. Now let's turn this into an expression.

color -= color * 0.1;

You do this every time it travels 1 m. But doing that literally in a shader is a bit heavy. For something 1 km away, you'd have to loop 1000 times. So let's transform it a little.

Subtracting 10% is the same as leaving 90%, so let's multiply by 0.9. And if you repeat that, you can use a power.

color = color * pow((1.0 - 0.1), distance);

If distance is 5, it's the 5th power. For an in-between value like 4.5, you'll get some suitably in-between value (sloppy!).

For distance, compute the world position in the vertex shader, pass it to the fragment shader, and subtract the camera position.

struct v2f{
    float3 worldPosition : TEXCOORD2;
    float4 vertex : SV_POSITION;
};

v2f vert (appdata v){
    v2f o;
    o.vertex = UnityObjectToClipPos(v.vertex);
    o.worldPosition = mul(unity_ObjectToWorld, v.vertex);
    return o;
}

fixed4 frag (v2f i) : SV_Target{
    float distance = length(i.worldPosition - _WorldSpaceCameraPos);

mul with unity_ObjectToWorld gives you the world position, which you pass to the fragment shader, and _WorldSpaceCameraPos is the camera position, so you subtract and take the length (the official docs have a list of the built-in variables).

If the original color is RGB(1, 0.5, 0) and it's 2 m away, 0.9 squared is 0.81, so the RGB becomes (0.81, 0.405, 0).

Basic fog that only darkens with distance

It looks roughly like this. This shader is included in the sample too. The original color is yellow, and it gets darker the farther away it is. Wait, what? We didn't want to make it darker, did we?

We don't want it darker

If light decreases with distance, it naturally gets darker. But that's not what we want, is it? Mist would turn things white, and distant scenery would turn gray. In other words, we need a mechanism that adds some other color.

Actually, in the same way that light coming from an object gets knocked away and lost, light that was knocked away somewhere else can also fly into the viewpoint. So it doesn't just keep getting darker.

If you think about it seriously, you start to wonder things like "what color of light was knocked away where, and came over here?", but there's no way to compute that, so let's keep it breezy: "just add as much light of whatever color we like as was knocked away and lost!" For an outdoor scene it would be white; for a poison swamp, purple, maybe.

So we need "the amount lost".

color = color * pow((1.0 - 0.1), distance);

Here pow((1 - 0.1), distance) is the amount left after the decrease, so subtracting it from 1 gives us that.

var lost = 1.0 - pow((1.0 - 0.1), distance);

Then we add some arbitrary color by that amount. You could add a property to the material and set it, but the fog color should already be set through the standard mechanism, so let's use that.

color = color * (1.0 - lost);
color += unity_FogColor * lost;

A variable called unity_FogColor is available in shaders without you doing anything, so we use that.

Using linear interpolation

By the way, a calculation of the form

(x * a) + (y * (1 - a))

is called linear interpolation (Linear intERPolation: LERP), and shaders have a dedicated instruction for it. It's shorter to write (I can't say for sure that it's faster), so let's use it.

color = lerp(color, unity_FogColor, lost);

Watch the order of the arguments. The one that grows as lost gets bigger is unity_FogColor, so that goes last. Then again, even if you get it wrong, you get the very obvious result that "nearby things turn fog-colored", so you'll notice straight away.

There we go: this is the basic fog shader. The whole code is here.

Basic fog that blends in the fog color

Getting rid of pow

The current code has an instruction called pow.

This is actually a compound instruction, and Unity generates code that breaks it down. By breaking it down by hand, we might be able to speed things up.

Also, pow doesn't play nicely with calculus. If you wanted to differentiate

pow(x, a)

with respect to x, what would you do?

The most basic derivative of an exponential function is that of ex. Let's write it code-style as exp(x). exp(x) has the wonderful property of staying exp(x) when you differentiate it, so whenever there's a whiff of calculus, you're better off switching all your powers and logarithms to base e, the natural logarithm's base. Once you get used to exp that way, you start feeling "why not just use it for everything?", and every time you see pow you want to turn it into exp.

So let's turn it into exp.

pow(a, b) = exp(log(a)*b)

That's the formula. It would be fine if you could just remember it, but I don't do mathematical work every day, and when you only use it now and then, you can never quite trust your memory of the formula, so I recommend deriving it each time.

a^b           # take the logarithm
log(a^b)      # a power inside log can be taken outside log as a multiplication. Take b outside.
log(a)*b      # we took the logarithm earlier, so undo it
exp(log(a)*b)

Like that. As long as you remember "a power inside log can be taken outside log as a multiplication", deriving it every time feels safer.

So we've converted

var lost = 1.0 - pow((1.0 - _Attenuation), distance);

into

var lost = 1.0 - exp(log(1.0 - _Attenuation) * distance);

After that, all you need is to compute log(1.0 - _Attenuation) on the C# side and put it into the Material. As for how big that is, for example when _Attenuation is 0.1 it's log(0.9), which is something like -0.1053... Having a gut feel for "the log of something smaller than 1 is negative" comes in handy for graphics work.

Incidentally, rather than computing this -0.1053... as log(1-0.1), you could let people specify it directly. It loses the meaning of "how much is lost per meter", but if it's set with a slider anyway, hardly anyone cares about the units. Even then the minus sign is in the way, so have them specify it as a positive number and handle just the minus in the shader. Negation is free in a shader. Besides, log(1-x) is close to -x. Here too, 0.1053 and 0.1 are barely different, right? (Try a Taylor expansion and cut it off at the first order.)

If we call this _Strength (since the bigger it is, the stronger the fog), we get

var lost = 1.0 - exp(-_Strength * distance);

and the code gets simpler.

Flipping lerp to get rid of the subtraction from 1

Now, we subtract from 1.0 to get lost, but we can actually do without that.

lerp(a, b, x) = lerp(b, a, 1-x)

That identity is what we use. If you swap the order of the arguments, you flip the interpolation factor by subtracting it from 1.

var a = exp(-_Strength, distance);
color = lerp(unity_FogColor, color, a);

I stopped subtracting from 1.0 and renamed it a (I can't think of a good name). Then I flipped the arguments of lerp. The code is shorter, which is nice. It might run faster too, but if the compiler is smart it may already be doing this much for us.

Making it depend on height

As the next step, let's make it affected by height.

The higher you go, that is, the bigger Y gets, the weaker the fog, but there are infinitely many ways to do that. Let's try a simple one first.

Say the fog disappears at a fixed height. Like this, for example.

The camera above the fog and an object inside it

The camera is above the fog, and the object is inside it. The length marked D in the figure is "how far the light travels through the fog". Replace distance in the code above with this and the calculation is done.

So how do we find D? It's pretty easy.

Finding D from similar triangles

We already have the distance from the camera to the object. The figure is drawn with v as the vector from the camera to the object. If we know its length |v| and its y component v.y, we can find D from similar triangles. With the y coordinate of the top of the fog as h and the object's position as p,

|v| / v.y = D / (h - p.y)

Solving for D,

D = |v| * (h - p.y) / v.y

Swap this in for distance and we're done.

Case analysis...

But actually it's not that simple. What we have now is the case "the camera is outside the fog and the object is in it", but that's not the only pattern.

  • The camera is outside the fog and the object is outside the fog too
    • No fog. D=0.
  • The camera is outside the fog and the object is in the fog
    • We just did this one.
  • The camera is in the fog and the object is outside the fog
    • A different expression from the one just now.
  • The camera is in the fog and the object is in the fog too
    • Everything is in the fog, so the distance between the camera and the object is D as it is.

These four calculations can't be unified, so there's no choice but to branch with if. In the sample it looks like this.

float calcFogHeightUniform(float3 objectPosition, float3 cameraPosition, float fogDensity, float fogEndHeight)
{
    float3 v = cameraPosition - objectPosition;
    float t;
    if (objectPosition.y < fogEndHeight) // the object is in the fog
    {
        if (cameraPosition.y > fogEndHeight) // the camera is outside the fog
        {
            t = (fogEndHeight - objectPosition.y) / v.y;
        }
        else // the camera is in the fog too
        {
            t = 1.0;
        }
    }
    else // the object is outside the fog
    {
        if (cameraPosition.y < fogEndHeight) // the camera is in the fog
        {
            t = (cameraPosition.y - fogEndHeight) / v.y;
        }
        else // the camera is outside the fog too
        {
            t = 0.0;
        }
    }
    float distance = length(v) * t;
    float fog = exp(-fogDensity * distance);
    return fog;
}

endFogHeight is the top of the fog. To keep the code tidy, it finds a t in the range 0 to 1 and multiplies the distance between the camera and the object by it to get the length that's inside the fog.

The result looks like this.

Fog that ends at a fixed height

You can see that only the part below a certain height is purple. It's set up so that there's no fog above 2 m. The fog vanishing suddenly is unnatural, but depending on the use, this may sometimes fit better.

As a general-purpose tool, though, it's not great. Fog that thins out gradually can be used in many more situations.

By the way, I had the impression that if statements are heavy, but this time I couldn't see that cost at all. The programming guide for the S2's GPU (Adreno) says that "branches where each pixel can take a different path are heavy", so it's worth at least keeping in mind that "it's better not to if you can avoid it".

Thinning out gradually with height

Now, at the start I showed this code.

color -= color * 0.1;

This was the code to "shave off 10%", for when 10% is shaved off for every meter traveled.

This time, that "10%" changes with height.

color -= color * calcFogDensity(y);

Something like that. I've interpreted 0.1 as "the density of the fog" and called the function that finds this 0.1 calcFogDensity. You pass it the height y of the current point. But if you try to run it like this, you need a loop. Since the density isn't constant, you can't "turn the loop into a power to speed it up".

for (...)
{
    color -= color * calcFogDensity(y);
}

Subtracting in a loop like this is, in the end, integration. If we can find the integrated expression beforehand, we can calculate it without a loop. Or rather, it becomes a matter of building an expression that integrates nicely so that we can do it without a loop.

What follows is explained elegantly using mathematical notation in Shitamachi no Napoleon - Implementing fog, so if you're comfortable with mathematical notation, I recommend that instead.

Making a function you can integrate

Now, when it comes to functions that are easy to integrate, there are polynomials like x^2+2x+4 and exponential functions like e^x. Exponential functions in particular are the best: they keep their shape whether you integrate or differentiate them, which makes things very easy. Also, in this case, unless the function has the property of "staying positive whatever the height", the fog density goes negative, which is a pain. On top of that, it needs to be guaranteed that "the higher, the thinner (= monotonically decreasing)". Given these conditions, polynomials are out.

So let's say "the fog density changes exponentially". Now, suppose the fog density d (short for density) can be expressed as

d = d0 * exp(-k*y)

d0 is the fog density at y=0. And k is some parameter; the bigger it is, the faster the fog thins out. If the inside of exp is negative, the result of exp is between 0 and 1, and the bigger k*y is, the closer the result gets to 0. So it thins out.

Now, the color being lost every meter traveled was written like this:

color -= color * calcFogDensity(y);

Since we're about to integrate, let's write it in more mathematical notation. One step looks something like

dc/ds = -c * d0 * exp(-k*y)

It's a derivative with respect to s, and this s is "the distance in the direction the light travels". If the distance is 100, suppose there's a variable s that is 0 at the camera and 100 at the object. We just need to integrate over this s from 0 to 100. Writing color as c, the change per step dc/ds is the current color c times the fog density at that height.

First, y is in the way

We're trying to integrate with respect to s, but there's a y on the right-hand side. y is "the height at that point", and of course it changes when s changes. So let's express y in terms of s.

y = y0 + (v.y / |v| * s)

Here y0 is the object's height, v is the vector from the camera to the object, |v| is its length and v.y is its y component. When s equals |v|, the numerator and denominator cancel and v.y remains; add that to y0 and you get the camera's height. In between, it's linear interpolation.

dc/ds = -c * d0 * exp(-k*(y0 + (v.y / |v| * s)))

Happily, it's now a function of s alone. It does have a "wait, we're integrating this?" feel to it. But fortunately, we can.

First, let's simplify the expression. The inside of exp is far too complicated, so we split it in two, using

exp(a+b) = exp(a) * exp(b)

It's the idea that 10 to the power (2+3)=5 is 100 thousand, which is the same as 10 squared = 100 times 10 cubed = 1000.

dc/ds = -c * d0 * exp(-k * y0) * exp(-k * v.y / |v| * s)

Now let's set

A = d0 * exp(-k * y0)
B = -k * v.y / |v|

These are constants.

dc/ds = -c * A * exp(B * s)

Much better. Now, there are two variables on the right-hand side, c and s, which is annoying. In cases like this you do what's called separation of variables: move c to the left-hand side and s to the right.

dc / c = -A * exp(B * s) * ds

dc/ds is a single symbol, and I don't yet understand well enough to explain to anyone why you're allowed to split it up like this. But if you sloppily interpret it as "a very small c divided by a very small s is dc/ds", then it seems fine to multiply both sides by ds. And apparently it actually is fine.

Now that they're separated, we integrate the left-hand side with respect to c and the right-hand side with respect to s. Why that's allowed, again, I don't understand well enough to explain.

The left-hand side is the integral of 1/c, which is log|c|. The right-hand side is the integral of an exponential function, and we use the fact that integrating exp(ax) gives exp(ax)/a. It comes out if you apply the product rule to integration, so it's easy to derive yourself. From the above,

log|c| = -A/B * exp(B * s) + constant of integration

That's the indefinite integral. What we want is c, not log|c|, so we'd like to put both sides into exp to remove the log, but let's get the definite integral before the expression gets long.

Subtract the value with s set to 0 from the value with s set to |v|.

-A/B * (exp(B * |v|) - exp(B * 0))

B was -k * v.y / |v|, so when s becomes |v| it cancels. And exp(0) is 1, so the right half becomes simple too:

-A/B * (exp(-k * v.y) - 1)

What we've found is the logarithm of c, log|c|, so wrapping it in exp,

|c| = exp(-A/B * (exp(-k * v.y) - 1))

We only need to deal with positive values here, so let's just drop the absolute value on c. Then put A and B back.

c = exp(d0 * |v| / (k * v.y) * exp(-k * y0) * (exp(-k * v.y) - 1))

And so we have the integrated result. With exp nested two deep, you get an "is this really OK?" feeling, but having come this far, just implement it, and if the picture looks right, it's OK.

float calcFogHeightExp(float3 objectPosition, float3 cameraPosition, float densityY0, float densityAttenuation)
{
    float3 v = cameraPosition - objectPosition;
    float l = length(v);
    float ret;
    float tmp = l * densityY0 * exp(-densityAttenuation * objectPosition.y);
    if (v.y == 0.0) // simple uniform fog
    {
        ret = exp(-tmp);
    }
    else
    {
        float kvy = densityAttenuation * v.y;
        ret = exp(tmp / kvy * (exp(-kvy) - 1.0));
    }
    return ret;
}

There's an if branch. It's for the case where the line of sight is horizontal, that is, where the camera and the object are at the same height. If v.y from the explanation above is 0, you get a division by zero, so it can't be calculated properly.

In fact, mathematically it's an unnecessary branch;

(exp(ax) - 1)/a

can be calculated fine even when a is 0. The Taylor expansion of exp is

exp(ax) = 1 + ax + (ax)^2/2 + ...

so once you subtract 1, all the remaining terms are divisible by a. But a shader has no room to compute a Taylor expansion, so you end up having to use the built-in exp and branch only when it fails.

You could also decide "the object's y at that pixel will hardly ever exactly match the camera's!", in which case you can remove the branch. Even if they did match exactly, only that pixel's calculation would go wrong. It would probably turn black. Not caring about the occasional black dot on screen is a valid option. If I measured the speed and it was slow enough to bother me, I'd probably do that too. But as I said above, it wasn't particularly slow, so I've left it as it is for now.

Closing

The integration in the second half used up four pages of my notebook. Honestly, I don't think I'm cut out for math.

And once things get this mathematical, I start to feel that writing it code-style has hit its limits, and that I should just use the integral sign like a normal person. What do you think? Then again, people who are fine with mathematical notation probably don't need an article like this.

By the way, this "fog that thins exponentially as you go higher" was apparently used in CryEngine. Knowing it already has a track record is a bit reassuring.

Bonus: making the parameters easier to set

In the sample, the fog density is given as "the distance at which the fog color is 50% mixed in". Set it to 300 and things 300 m away become gray, that sort of idea. It lets you put in a number with a physical meaning, which will appeal to those who like that sort of thing. But most people will ignore the theory completely and just fiddle with the slider, so whether it's worth doing is debatable.

Either way, though, as I said when talking about decibels, make the slider logarithmic. Entering 0.0001 or 0.001 with a non-logarithmic slider is impossible. And making people type a value they can't make sense of straight into a text box is even more out of the question, so I think you should always provide a slider.

Bonus: it can actually be made faster

This shader has a lot of exp() calls, but when you write exp() in Unity, the compiler converts it into another form. It gets expanded into

exp2(a * log2(e))

which increases the number of instructions. Let's take a peek at the compiled shader.

u_xlat0.x = u_xlat0.x * _FogStrength;
u_xlat0.x = u_xlat0.x * 1.44269502;
u_xlat0.x = exp2(u_xlat0.x);

What was originally written as exp(k*_FogStrength) has been split into three lines. 1.4426.. is log2(e). If you seriously want to speed it up, you need to rewrite the shader to use exp2. In other words, multiply by 1.4426.. at the stage where you set the constants on the material.

But this time it wasn't slow when I measured it, and it's a hassle, so I haven't gone that far. Especially for "the one where the fog thins with height", because of the integration, simply multiplying the constants by 1.4426.. doesn't work, so it gets quite fiddly. It may not be worth it.

Bonus: a few things unrelated to the main topic

The heights of the boxes in the sample are made with the log-normal distribution I introduced the other day. I wanted most buildings to be of similar height, with the occasional ridiculously tall one.

One more thing: the sample uses lightmaps. I wanted the shapes of things to be readable with as little processing as possible. As a sample of applying lightmaps in a home-made shader, the no-fog shader is short and handy, I think. I used [Unite Tokyo 2018] A fighting game with cutting-edge graphics even on mobile, using custom shaders! as a reference. Thank you very much.