Prev: The Material3D Class Next: Postscript: Isn't There a Better Way?

10. A Sample Material

In this chapter, we will implement a sample Material. This Material creates the effect of patchy fog by adding together three octaves of Perlin noise, and using the result to adjust the transparency. It includes a number of adjustable parameters: the color and thickness of the fog, how strongly it scatters light, and whether it casts shadows.

The full source code is found in PatchyFog.java. Here is the getMaterialSpec() method:

public void getMaterialSpec(MaterialSpec spec, double x, double y, double z, double xsize, double ysize, double zsize, double t)
{
  double size = 1.0, scale = 1.0;
  float d = 0.0f;

  for (int i = 0; i < 3 && xsize < size && ysize < size && zsize < size; i++)
    {
      d += (float) (size*Noise.value(x*scale+123.456, y*scale+123.456, z*scale+123.456));
      size *= 0.5;
      scale *= 2.0;
    }
  d = 0.5f*d + 1.0f - thickness;
  if (d > 1.0f)
    d = 1.0f;
  else if (d < 0.0f)
    d = 0.0f;
  spec.transparency.setRGB(d, d, d);
  spec.color.copy(color);
  if (scattering > 0.0f)
    {
      d = scattering*(1.0f-d);
      spec.scattering.setRGB(d, d, d);
      spec.eccentricity = 0.0;
    }
}
There are a number of important things to notice about this method: Here is what the PatchyFog Material looks like when rendered:

Prev: The Material3D Class Next: Postscript: Isn't There a Better Way?