**Contents**

**News (August, 31)**: We are working on Scratchapixel 3.0 at the moment (current version of 2). The idea is to make the project open source by storing the content of the website on GitHub as Markdown files. In practice, that means you and the rest of the community will be able to edit the content of the pages if you want to contribute (typos and bug fixes, rewording sentences). You will also be able to contribute by translating pages to different languages if you want to. Then when we publish the site we will translate the Markdown files to HTML. That means new design as well.

That's what we are busy with right now and why there won't be a lot of updates in the weeks to come. More news about SaP 3.0 soon.

We are looking for native Engxish (yes we know there's a typo here) speakers that will be willing to readproof a few lessons. If you are interested please get in touch on Discord, in the #scratchapixel3-0 channel. Also looking for at least one experienced full dev stack dev that would be willing to give us a hand with the next design.

Feel free to send us your requests, suggestions, etc. (on Discord) to help us improve the website.

And you can also donate). Donations go directly back into the development of the project. The more donation we get the more content you will get and the quicker we will be able to deliver it to you.

So far we have only learned how to render homogeneous volumetric objects. Objects whose scattering and absorption coefficients are constant through space. That's fine but a bit boring and not really how things look in nature. If you look at clouds of smoke coming out of steam trains these volumes are heterogeneous. Some parts are more opaque than others. So how do we render heterogeneous volume objects?

In the real world, we would say that the absorption or scattering coefficients are varying through space. The higher the absorption coefficient, the more opaque the volume. And the scattering and absorption could vary through space independently of each other. We generally choose a more practical approach though, which is to use a constant value for both the scattering and absorption coefficients for a given volumetric object and use the density parameter instead to modulate the volume's appearance through space. Imagine that the density parameter (which is just a real number like a float or a double in programming terms) varies through space. We can then do something like this: $$ \sigma_s' = \sigma_s * density(p)\\ \sigma_t = (\sigma_s + \sigma_a) * density(p) $$

Where \(\sigma_s'\) here is just scattering coefficient modulated by the space varying density parameter. The extinction coefficients \(\sigma_t\) used in the Beer's Law equation, which is the sum of the absorption and scattering coefficients, are also modulated by the space varying density parameter. And \(density(p)\) is a kind of function that returns the density at point p in space. By doing so, we can produce images of volume objects such as the volcano smoke plume from the image above.

Now the question is how do we generate this density field? You can use two techniques:

- Procedural: you can use a
**3D texture**such as the Perlin noise function to procedurally create a space varying density field. - Simulation: you can use a fluid simulation program that simulates the motion of fluids (such as smoke) to generate a space varying density field too.

In this chapter, we will use the first approach. In the next chapter, we will learn how to render the result of a fluid simulation.

# Generating a density field using a noise function

In this lesson we will be using the Perlin noise function to generate a 3D density field procedurally. If you are unfamiliar with the concept of procedural noise generation we recommend that you read the following two lessons: Value Noise and Procedural Patterns (Part 1) and Perlin Noise (Part 2).

What is a procedural noise function (in this case the Perlin noise function)? It's a function (in the programmatic sense of the term) that procedurally generates a noise pattern through 3D space. We can use this pattern to generate a density field whose values vary through space. The noise function takes a point as an argument and returns the value of the 3D noise texture at that point (a real number like a float or a double). This value is bound to the range [-1,1]. Density can either be 0 (no volume) or positive so we will need to either clip or remap the values of the noise function to get positive values for the densities. In the following code snippet, we remap the values from [-1,1] to [0,1]:

Where pSample here is the position of a sample along the camera ray as we march through the volume.

For the noise function, we will be using the implementation of the improved Perlin noise provided by Ken Perlin himself (link). Again, you can learn how and why this code works in the lesson devoted to Perlin Noise (Part 2) if you are interested. But in this particular lesson, we will assume that you are familiar with the function. If you don't, don't worry too much. All you need to care about is that you pass to the function the position of the point in 3D space where you want the function to be evaluated, and it returns for that point a value in the range [-1,1]. Here is the code for reference (check the file provided in the source code section to get the full implementation):

And finally, here is how we will be using it in our ray-marching program:

This is a rather simple change as you can see compared to the program we've been using to render homogeneous volume objects in the previous chapter. We move the declaration of the density variable inside the ray-marching loop which is no longer a constant value but is now a space varying parameter. Figure 2 shows what's happening visually. We sample the density field as we march along the ray, where, once again, a noise function is used for the generation of that density field. For each sample along the ray, we evaluate the noise function using the sample position as the function input parameter and use the result as the value for the density at that point. Figure 3 shows the result applied to a volumetric sphere.

To be sure you understand what's going on here, we've plotted the noise function over some distance and the transmission value over the same distance using that same noise function for the density. The result is shown in the image below. We've also plotted how the Beer's Lambert law would look like if that volume had a constant density (in green) vs a space varying density. As you can see, the green curve (constant density) is perfectly smooth whereas the red curve (heterogeneous) is not. Note that transmission stays more or less constant where the noise function returns values closer to 0, whereas transmission drops sharply (the volume is denser) where the noise function is higher. All that is expected, but seeing it hopefully helps.

But there's a problem. This code works to compute the volume transmission value, but the code we've been using to calculate the in-scattering contribution (remember the Li term?) however will not as is. We will now explain why and what changes we need to make to get it to work with a heterogeneous participating medium.

# In-scattering for a heterogenous participating medium

Hopefully by looking at figure 4, you should get a sense of what the problem is. For homogeneous volume objects, all we had to do when it came to light rays was to find the distance from the sample point to the boundary of the object in the direction of the light. Then apply the Beer's Law using that distance (let's call it Dl) and the volume extinction coefficient (sigma_t = sigma_a + sigma_s) to find out how much light we are left with (how much is being transmitted) after it has traveled through the volume to the sample point. Easy:

The problem with heterogeneous volumes is that this is no longer valid since density varies along the light rays as well which is visible in figure 4. Be mindful: we are not solving the same problem as the problem we solved in chapter 2 with forward ray-marching. The reason why we used ray-marching so far, was to estimate the in-scattering term along the camera ray. Nothing else. However, the ray-marching technique will be useful here again to estimate the in-scattering term as well as estimating the camera and light rays transmission as they travel through a heterogeneous participating medium. Not the same problem (estimating the in-scattering vs estimating the transmission of the rays), though same technique (forward ray-marching in this particular case, which is a form of stochastic sampling method). We need to break the ray into a series of segments, and estimate the transmission of each one of the segments, assuming that over the segment's length (within the small volume element defined by step size), the density of the volume element is uniform, and then multiply the total transmission value by the sample's transmission as we move along the ray. In pseudo-code, this could be implemented as follows:

Compare this code with the code we used in the previous chapters to calculate the value of the camera ray transmission value as we march along the ray from t0 to t1.

The two code snippets are doing the same thing. There's one little mathematical trick we can take advantage of which we haven't spoken about until now (because precisely now is a good time to do so). Here it is:

$$e^a * e^b = e^{a + b}.$$If you look at the code, you can see that transmission value is essentially a series of exponentials multiplied by each other. If you unfold the ray-marching loop (snippet 2) you get something like:

If we re-write this code using the mathematical property of exponentials we just learned about, we get:

In other words, as we march along the light ray (exactly like we do for camera rays), all we need to do is accumulate the density values at each sample along the ray, then use this sum to calculate the light ray attenuation / transmission value in a single call to the exponential function (which is a bit of a time saver indeed). This concept is illustrated in the image below.

The name "tau" is not chosen by mistake. You will often see it being used in the literature to denote a quantity called the **optical depth**. Two Greek letters are often used for this quantity: either tau (\(\tau\)) or rho (\(\rho\)). We won't give a formal definition of what the optical depth is in this chapter, as this might be confusing at this point. But we do in the chapter Volume Rendering: Summary, Equations / Theory.

That's it! Now you have everything you need to render an accurate image of heterogeneous volume objects. This last figure shows what the transmission curve looks like for a given noise profile.

# Practical (and functional) implementation

Let's make the necessary adjustments to our program to demonstrate how this would work in practice. Remember that the algorithm now works as follows:

- Ray-march along the camera ray. At each sample along the camera ray, estimate the density at the sample location to calculate the sample transmission and estimate the in-scattering contribution.
- Ray-march along light rays: whereas before we only marched along camera rays, we now need to ray-march along light rays too. For homogeneous volume objects, we only needed to march along the camera rays to estimate the in-scattering term. Whereas for heterogeneous, we need to do so along the camera rays to estimate the in-scattering term (this doesn't change) but now also to evaluate the density term along the ray. And we need to ray-march along the light rays to evaluate the density function along these rays as well.

In other words, we need to ray march along both the camera and the light rays now, and evaluate at each sample along these rays a density function. Currently the Perlin noise function. This is a lot of operations, and as you will see rendering our sphere as a heterogeneous medium will take significantly longer than its homogeneous counterpart.

In this implementation, the step size used for the camera and the light rays is the same. This doesn't need to be. To speed things up you can use a bigger step size to estimate the light rays transmission values. Also, now that we use a procedural texture we may encounter some filtering issues. If the frequency at which you sample the noise function is too low, you may miss some details from the procedural texture and you will eventually get aliasing issues. Again this is a filtering issue that we won't be digging into now but be aware that the step size, the noise frequency, and your image resolution are somehow interconnected (from a sampling point of view).

You might be surprised that the program output (right) doesn't look more like a cloud already. However, as you can see with an image of the noise pattern (left), the "lumps" making up the noise pattern are rather smooth by default which is why the volume has a smooth appearance as well. The art of making cloud-looking procedural noise requires tweaking the result of the noise function in different ways to get visually more interesting results (as we will show further down).

Here are a couple of simple variations you can already try: removing the negative values from the noise function (left) and taking the noise function absolute value (right). The falloff parameter is explained further down.

However unspectacular, this is exactly the technique that was used to create the spectacular volumetric effects of the movie Contact's opening sequence (1997). These images were rendered using Pixar's renderer and created by Sony Picture Imageworks. This sequence was a huge technical undertaking at the time. As mentioned before, they used the same technique as the one provided in this lesson. The difference is that they used some geometry (and not basic spheres) to define the shape of the volumetric objects and some fractal patterns to give the nebulas a cloud-like texture. We will touch on the former technique in the last chapter of this lesson (volume rendering in production). As for a cloud-like texture, let's now see what we can do...

# Playing with the density function (to create more interesting looks & animations)

Writing a ray-marcher is one thing. Creating a cloud-like procedural texture is another. Whereas the former is a science, the latter is more a matter of art: using a series of mathematical tools to shape the procedural texture and spending a lot of time tweaking the parameters until you eventually get something you are satisfied with. Our goal here is not to create convincing and wow images, but to give you the tools or bricks that first help you understand how things work and second, that you can eventually recombine yourself into more complex systems to make some "wow" images if you want to. But we will leave that up to you... Share them with us though if you create something cool!

Now here are a few tricks that you can use to create more interesting cloud-like "spheres". This is just a short selection of some of these tools.

## Smoothstep

The smoothstep function is a function you are familiar with as we've been using it already for several things, including for the noise function. It creates a "smooth" transition between two values. Here is one possible implementation of the function:

We can use this function to create a falloff near the sphere boundary. To do so, we will make some changes to the eval_density function to pass as parameters to the function, the sphere center and radius. By doing so, we can compute a normalized distance from the sample position to the center of the sphere, and use this value to adjust the density of the sphere-like so:

Again this technique is useful for fading out the volume before it reaches the boundary of the sphere. We use the smoothstep function to control how far from the edge or side the falloff begins (and eventually ends, but for a falloff effect, it should be kept to 1).

## fBm

fBm (also known as plasma or "chaos" texture in the good old times) stands for Fractal Brownian Motion. In the field of computer graphics, it has a different meaning than in mathematics. We will be considering what it means for us, graphics engineers and artists. It's a kind of fractal pattern that is made out of a sum of procedural noise layers, whose frequency and amplitude vary from layer to layer. You can find some information on this pattern in the lessons from the Procedural Generation section.

The code of a typical fBm procedural texture can be constructed as follows:

Building a fBm pattern takes two lines of code (looping over the layers). Many variations can be built from this basic version such as taking the noise function absolute value (a pattern known as turbulence) etc. Again check the procedural generation section if you want to learn more on this topic (and learn how to filter this pattern properly).

## Bias

Bias shifts where the center (0.5) value will be while leaving 0 and 1 the same.

## Rotate the noise pattern using the primitive local frame

Another technique was used a lot in the good old times (before fluid simulations became mainstream, thanks to an increase in computational power) to animate the noise pattern within the volume primitives (sphere, cubes, etc.). The sample position we pass to the density function is defined in world space, but we can define this point position within a system of reference that's attached to the sphere. In other words, we transform our sample point from world to object space. To define the sample point within the sphere reference system all we need to do is:

A more generic solution would consist of transforming the sphere primitive using matrices. Then we would be using the inverse of the object-to-world matrix to transform our sample point from world space to the sphere local reference system. However, we are not using matrices in our sample program for simplicity. But you can do this yourself easily with the information provided on Scratchapixel.

This technique is useful for the following reason: if we move the sphere, the coordinates of the point defined in the sphere local frame of reference will not. And that can be used to insure that the noise pattern sticks with the sphere regardless of its transformation. Similarly to the veins of a glass marble that you roll between your fingers. In the example we chose to illustrate this idea (even though it's a little different from what we just explained but the concept and the results are the same): we will be rotating the point in object space around the primitive sphere y-axis (a better solution would be to rate the sphere using an object-to-world matrix, and then transform the sample point from world space to object space using the world-to-object matrix, but we were too lazy to do it here, so we decided to rotate the point in object space instead). As a result, we can see the fractal pattern rotating as well, again a little bit as if we were looking at a glass marble spinning. More sophisticated deformations (linear or not) can be applied using this method.

Note how we can now clearly see the 3D structure of the fractal pattern.

## And many more...

The list of "procedural" tricks can go on and on: displacement (we displace the edges of the volume using a noise function), different types of noise (billow, space-time which is an animated type of noise, etc.). We will eventually expand this list in a future revision of the lesson.

# What did we learn so far?

See the last chapter for a summary of the techniques studied in this lesson.

Though what you can do now is use ray-marching to render single-scattering heterogeneous volumetric objects. And this is already a big accomplishment. Another thing that should be clear by now, is that with ray-marching, we break the volume object into smaller volume elements defined by the step size. This technique works because we assume that these tiny volume elements or samples are small enough to be homogeneous themselves. In short, you break down heterogeneous objects into small "bricks" which you can see as being "homogeneous". Though the bricks themselves can be different from one another. A little bit like when you build an object using Lego bricks.

# Source code

The source code of a fully functional program implementing this technique is available in the source code section of this lesson. Feel free to play with the eval_density() function to create different looks.