How to get Terrain height from Pixel Buffer.

How do you implement the code to get the height for the Terrain from a Pixel buffer?

  1. Assume that you have a pixel buffer with your image data in it. The code for this can be found on the resources page on the web site.
  2. Assume that you have your tanks x and z position in World coordinates. This can be extracted from your eyepos vec3 variable.
Now we implement the code to extract the height:

// assume we have a global variable Gpixel with the image data.
// assume we have a global variable Gimage with width and height information

// this function returns the height of the terrain for a given, x,z position.
// x and z are in the range [-1,1]. 
function getTerHeight(x,z)
{
    //First you need to scale x,z from [-1,1] to [0,Gimage.width]
    // adjust range of x and z to texture size
    i = ...ScaleX... * Gimage.width);
    j = ...ScaleZ... * Gimage.height);
    if (i >= Gimage.width) i = Gimage.width; // bounds check
    if (j >= Gimage.height) j = Gimage.height; // bounds check
    

    // calculate the index offset into the Pixel Array
    // standard array offset arithmetic
    var aoffset = Math.round(i * 4 + j*Gimage.width*4);
    var r = Gpixels[0 + aoffset];  //get red value
    var g = Gpixels[1 + aoffset];  // get green value
    var b = Gpixels[2 + aoffset];  // get blue value
    
    // now calculate the length of  as a vector and scale to 0 to 1.0
    var aval = Math.sqrt(r* r + g * g + b * b)/441.673;
    return aval;  // return the height
}

When you first visit the web page your texture may not be loaded yet and your Pixel buffer may not be valid. You need to add a test on some variable in this code to check if your Pixel has been loaded. When it has not been loaded you can just have this function return 0.0