Building Worlds With Distance Functions in GLSL (Raymarching)

Article index:

3 – Raymarching: Floor + Sphere

Build Worlds With Distance Functions in GLSL, GLSL Hacker
Raymarching: floor + sphere

The new functions to generate this scene: obj_union() and obj_sphere():

vec2 obj_union(in vec2 obj0, in vec2 obj1)
  if (obj0.x < obj1.x)
  	return obj0;
  	return obj1;

The obj_union() function will be used with all other primitives to combine the floor and a primitive. This function can be seen as the depth test.

Now the function to generate a sphere. This function returns the distance between a position p and a sphere with a radius of 1.9. The vec2 used to return the result holds the distance in x and the material index in y. If material == 0, we have the floor. If material == 1 we have a primitive.

vec2 obj_sphere(in vec3 p)
  float d = length(p)-1.9;
  return vec2(d,1);

Now let’s see where to use both functions in our GLSL framework: we just need to modify the distance_to_obj() function like this:

vec2 distance_to_obj(in vec3 p)
  return obj_union(obj_floor(p), obj_sphere(p));

Article index: