Visualizing the Trilinear Interpolant

WebGL + Ray Casting

July 12, 2015



Isosurfaces induced by the trilinear interpolant can be very complicated. This WebGL app shows the geometry and topology of the trilinear interpolant.


f(x,y,z) = 0.30 xyz + 0.40 xy + 1.00 yz + 0.10 xz + 0.20 x + -0.70 y + 0.50 z + -0.40 = 0.00
Your browser does not support WebGL

The trilinear interpolant can be built from a sequence of linear interpolations along the edges of a cube (see Wikipedia's page trilinear interpolation). Because it is "just" a combination of linear interpolants, one may feel tempted to think that the geometry and topology of the isosurfaces induced by the interpolant are straightforward. Alas, that's not the case. Since the early 90s, several papers showed how complex these cases can be. For example, an isosurface defined on a single voxel may have multiple sheets of surface and surfaces with holes. In 2003, Gregory Nielson published On marching cubes, the first paper providing a comprehensive description of all possible Marching Cubes cases induced by the trilinear interpolant. In order to help understand those cases, Nielson used an app to visualize the shape of the interpolants.

Previously, I explored the shape of the trilinear interpolant using WebGL. The main idea was to project particles placed at random positions within a cube onto the isosurfaces of the trilinear interpolant. The app can be found here. Although the particles provided a good idea of the surface topology and geometry, the result was a poor-quality isosurface rendering. To improve the rendering quality, more particles are needed, which in turn makes the app very slow.

This is my second attempt at visualizing the trilinear interpolant. Instead of projecting particles onto an isosurface, a fragment shader is used to intersect rays with the isosurface, making the whole app faster and providing superior visual quality. The idea is to shoot rays from each pixel, find the intersection point with the isosurface, and color the pixel when it hits the surface. The fragment shader used in this app is shown below. This code was adapted from lightbits' Raymarching Distance Fields.


Fragment shader:
precision mediump float;

//
// Input grid (a single voxel)
// 
struct grid_t {
	float s000, s001, s010, s011, s100, s101, s110, s111;	
};

//
// Trilinear surface defined as:
// f(x,y,z) = axyz + bxy + cxz + dyz + ex + fy + gz + h
//
// An isosurface is defined as:
// f(x,y,x) = c
// where c is a constant value
//
struct trilinear_t {
	float a, b, c, d, e, f, g, h;
};

//
// The interpolated quad coordinates from [-1, 1] on the x and y axis
//
varying vec2 uv;

//
// Camera
//
uniform vec2 g_resolution;
uniform vec3 g_camUp;
uniform vec3 g_camRight;
uniform vec3 g_camForward;
uniform vec3 g_eye;
uniform mat3 g_coefficients;

//
// Light
//
uniform vec3 g_light0Position;
uniform vec4 g_light0Color;

//
// Constants
//
const float g_zNear = 0.0001; // Near clip depth
const float g_zFar = 10.0; // Far clip depth
const int g_rmSteps = 5000; // Max raymarch steps
const vec4 g_skyColor = vec4(248.0/255.0,247.0/255.0,243.0/255.0, 1.0); //sky
const vec4 g_ambient = vec4(0.15, 0.2, 0.32, 1.0); 
const float delta = 0.08; // Step size
trilinear_t g_trilinear; // Trilinear interpolant

//
// Return a trilinear function
//
trilinear_t makeTrilinear() {
	trilinear_t l;
	l.a = g_coefficients[ 0 ][ 0 ];
	l.b = g_coefficients[ 0 ][ 1 ];
	l.c = g_coefficients[ 0 ][ 2 ];
	l.d = g_coefficients[ 1 ][ 0 ];
	l.e = g_coefficients[ 1 ][ 1 ];
	l.f = g_coefficients[ 1 ][ 2 ];
	l.g = g_coefficients[ 2 ][ 0 ];
	l.h = g_coefficients[ 2 ][ 1 ];
	return l;
}

//
// Provide the scalar value of a point located at (x, y, z)
//
float f( trilinear_t l, float x, float y, float z ) {
	return l.a * x * y * z + 
	       l.b * x * y     + 
	       l.c *     y * z + 
	       l.d * x     * z + 
	       l.e * x         + 
	       l.f     * y     + 
	       l.g         * z + 
	       l.h; 
}

//
// Provide the gradient of f at (x, y, z)
//
vec3 grad_f( trilinear_t l, float x, float y, float z ) {
		return vec3( l.a * y * z + l.b * y + l.d * z + l.e, 
								 l.a * x * z + l.b * x + l.c * z + l.f, 
								 l.a * x * y + l.c * y + l.d * x + l.g );
}

//
// Calculate the light intensity with soft shadows
// p: point on surface
// normal: surface normal vector
// lightPos: position of the light source
// lightColor: the radiance of the light source
// returns: the color of the point
//
vec4 getShading(vec3 p, vec3 normal, vec3 lightPos, vec4 lightColor)
{
	float lightIntensity = 0.0;
	float shadow = 0.5;
	if(shadow > 0.0) // If we are at all visible
	{
		vec3 lightDir = normalize( lightPos - p );
		lightIntensity = shadow * clamp( dot( normal, lightDir ), 0.0, 1.0 );
	}
	
	return lightColor * lightIntensity + g_ambient * (1.0 - lightIntensity);
}

vec3 getNormal(vec3 p)
{
	return normalize( grad_f( g_trilinear, p.x, p.y, p.z ) );
}

struct Ray {
    vec3 Origin;
    vec3 Dir;
};

struct AABB {
    vec3 Min;
    vec3 Max;
};

bool intersectBox(Ray r, AABB aabb, out float t0, out float t1)
{
    vec3 invR = 1.0 / r.Dir;
    vec3 tbot = invR * (aabb.Min-r.Origin);
    vec3 ttop = invR * (aabb.Max-r.Origin);
    vec3 tmin = min(ttop, tbot);
    vec3 tmax = max(ttop, tbot);
    vec2 t = max(tmin.xx, tmin.yz);
    t0 = max(t.x, t.y);
    t  = min(tmax.xx, tmax.yz);
    t1 = min(t.x, t.y);
    return t0 <= t1;
}

//
// Marches along a ray using the distance field, until an intersection is found
// i: iteration count
// t: distance traveled along ray
//
void raymarch(vec3 ro, vec3 rd, out int i, out float t)
{
	AABB aabb;
	Ray r;

	float t_start;
	float t_end;
	float t_mid;

	aabb.Min = vec3( -10.0, -10.0, -10.0 );
	aabb.Max = vec3( +10.0, +10.0, +10.0 );

	r.Origin = ro;
	r.Dir = rd;

	if( intersectBox( r, aabb, t_start, t_end ) == false ) {
		i = g_rmSteps;
		return;
	}
	
	vec3 p_s = ro + t_start * rd;
	vec3 p_e = ro + t_end   * rd;
	float f_s = f( g_trilinear, p_s.x, p_s.y, p_s.z );
	float f_e = f( g_trilinear, p_e.x, p_e.y, p_e.z );

	// Check ray box intersction

	i = g_rmSteps;
	for( int j = 0; j < g_rmSteps; ++j )
	{
		vec3 p = ro + rd * t_start;	

		//
		// Checking traversal
		//	
		if( f_s * f( g_trilinear, p.x, p.y, p.z ) < 0.0 )
		{
			i = j;
			t = t_start;
			break;
		}

		//
		// Update block
		//
		t_start += delta;

		//
		// Early exit
		//
		if( t_start >= t_end ) 
		{
			break;
		}
	}
}

//
// Computes the color corresponding to the ray intersection point (if any)
//
vec4 computeColor(vec3 ro, vec3 rd)
{
	float t0;
	int i;
	raymarch(ro, rd, i, t0);

	vec3 p; // Surface point
	vec3 normal; // Surface normal
	float t; // Distance traveled by ray from eye
	vec4 texture = vec4(1.0); // Surface texture

	if(i < g_rmSteps) // Raymarching hit a surface
	{
		t = t0;
		p = ro + rd * t0;
		normal = getNormal(p);
	}
	else
	{
		return g_skyColor;
	}

	vec4 color;

	// Diffuse lighting
	if( dot( normal, rd ) >= 0.0 ) {
		color = texture * (
			getShading(p, normal, g_light0Position, g_light0Color) +
			getShading(p, normal, vec3(2.0, 3.0, 0.0), vec4(1.0, 0.5, 0.5, 1.0))
			) / 2.0;	
	} else {
		color = texture * (
			getShading(p, normal, g_light0Position, g_light0Color) +
			vec4(1.0, 1.0, 0.0, 0.8 ) ) / 2.0;	
	}
	
	return color;
}

void main(void) {
	float aspectRatio = g_resolution.x / g_resolution.y;
	vec3 ro = g_eye + g_camRight * uv.x * 25.0 + g_camUp * uv.y * 25.0;
	vec3 rd = normalize(g_camForward);
	g_trilinear = makeTrilinear();
	vec4 color = computeColor(ro, rd);
	gl_FragColor = vec4(color.xyz, 1.0);
}