Raymarching

From Shader Forge Wiki
Jump to: navigation, search
Render

The goal of this tutorial is to display a sphere using a very basic raymarcher, sadly SF doesn't allow us to use loops so we'll have to work inside a Code node for this one.

Before starting on this tutorial, you should know that everything that we are doing here happens for each pixel on your screen since this is a fragment shader, pretty basic stuff but it is essential to understand properly how raymarching works.

Here's how the tree looks like :

SFTreeRaymarching.png

And here's a visual explanation of the code :

RaymarcherVisu.png




I'll just run through the code directly since nothing particular is done outside of it.

So, at line one and two we are setting up the starting point for the ray, the starting point should be the closest point on the clipping plane since other geometry isn't rendered before that point.

Line three gives us the offset between each check, I'll explain it further below.

Four is just the output color, we'll assign the alpha below to tell us if the ray hit something.


Let's skip the for loop for now.


If(distance) tells us whether samplePos is inside the sphere, if it is then congratulation, we hit the sphere !

We can assign the color with, in this case, the position where it hit the sphere and set the alpha to 1.0 to show that pixel on screen.


The for loop and samplePos += sampleOffset pushes the position further along the ray to check again, on the following iteration, if we are inside the sphere.

So the third line tells the code how far we should push the position before each check.


Finally return color; sends that data to the rest of the shader to be used for other stuff,

in this case show the position and render transparent every pixels that didn't hit the sphere.




Just to clarify a few things:

- This is a very basic raymarcher, the gist of it is that you are pushing a position along a ray and check if we are inside or how close this position is compared to a function,

more useful raymarcher will do stuff like discard pixels before marching, move the sample position based on a whole bunch of factors to skip unnecessary parts,

precisely march inside a volume to avoid moire "cuts", etc.


- Line one isn't very useful in this code but it will be once you have to cull when stuff's in front of the sphere.


- This shader is intended to be rendered directly on screen or should be placed on a quad on your camera's near plane.


Now that you understand how this works, try to optimize it ! How could you find out before even marching wheter a ray will touch the sphere ?

How could you create a fog volume based on this sphere ? Avoid rendering parts of the sphere which is inside of behind other geometry ?

Try other shapes, maybe marching through an heightmap and create a terrain with it ?

Your GPU is the only limit in the world of raymarching !

Have fun !