Hello JGO,
I’ve been trying to solve this problem for several days, and can’t come with a working solution. Perhaps my math knowledge is lacking. Does anyone know how to calculate the normal vectors for a heightmap or a random terrain?
This is what I got now:
float[] vdata = new float[(width-1) * height * 6]; // The vertex data for the heightmap.
int i = 0;
for (int z = 0; z < data.length - 1; z++) {
for (int x = 0; x < data[z].length; x++) {
// Take a vertex from the current strip
vdata[i++] = x;
vdata[i++] = data[z][x];
vdata[i++] = z;
// Take a vertex from the next strip
vdata[i++] = x;
vdata[i++] = data[z + 1][x];
vdata[i++] = z + 1;
}
z++;
if(z < data.length - 1) {
for (int x = data[z].length - 1; x >= 0; x--) {
// Take a vertex from the current strip
vdata[i++] = x;
vdata[i++] = data[z][x];
vdata[i++] = z;
// Take a vertex from the next strip
vdata[i++] = x;
vdata[i++] = data[z + 1][x];
vdata[i++] = z + 1;
}
}
}
float[] ndata = new float[vdata.length]; // The normal data for the heightmap
i = 0;
for(int n = 0; n < vdata.length/3; n++) {
Vector3f v0 = new Vector3f(vdata[n], vdata[n+1], vdata[n+2]);
Vector3f v1;
if(n < vdata.length - 5) { // Prevent IndexOutOfBoundsException
v1 = new Vector3f(vdata[n+3], vdata[n+4], vdata[n+5]);
} else {
v1 = v0;
}
Vector3f v2;
if(n < vdata.length - 8) { // Prevent IndexOutOfBoundsException
v2 = new Vector3f(vdata[n+6], vdata[n+7], vdata[n+8]);
} else {
v2 = v0;
}
Vector3f dv1 = Vector3f.sub(v1, v0, new Vector3f());
Vector3f dv2 = Vector3f.sub(v2, v0, new Vector3f());
Vector3f nv = Vector3f.cross(dv1, dv2, new Vector3f());
ndata[i++] = nv.x;
ndata[i++] = nv.y;
ndata[i++] = nv.z;
}
setVertexData(vdata);
setNormalData(ndata);
setDrawType(GL_TRIANGLE_STRIP);
But the normals are totally wrong, as you can see in the image: