Vertices changes sometimes

Im using this code to load a height map, but some times the quads changes… like this:

NORMAL:
/\ /
/ \ /
/ / \

FREAK:


/
/
/ \

CODE:

GLfloat Height(BYTE *pHeightMap, int X, int Y)
{

int x = X % MAP_SIZE;
int y = Y %MAP_SIZE;
if(!pHeightMap) return 0;
return pHeightMap[x + (y * MAP_SIZE)];
}

void RenderHeightMap(BYTE pHeightMap)
{
GLfloat x,y,z;
int X=0,Y=0;
if(!pHeightMap) return;
for ( X = 0; X < MAP_SIZE; X += STEP_SIZE )
for ( Y = 0; Y < MAP_SIZE; Y += STEP_SIZE )
{
x = X;
y = Height(pHeightMap, X, Y );
z = Y;
glTexCoord2f(0,0);
glVertex3f(x, y*ELEVATION, z);

  	x = X;
  	y = Height(pHeightMap, X, Y + STEP_SIZE );
  	z = Y + STEP_SIZE ;
  	glTexCoord2f(1,0);
  	glVertex3f(x,y*ELEVATION, z);

  	x = X + STEP_SIZE;
  	y = Height(pHeightMap, X + STEP_SIZE, Y + STEP_SIZE );
  	z = Y + STEP_SIZE ;
  	glTexCoord2f(1,1);
  	glVertex3f(x, y*ELEVATION, z);

  	x = X + STEP_SIZE;
  	y = Height(pHeightMap, X + STEP_SIZE, Y );
  	z = Y;
  	glTexCoord2f(0,1);
  	glVertex3f(x, y*ELEVATION, z);
  }

}

The code looks fine to me (assuming you are using GL_QUADS).

Perhaps it doesn’t look right because the quads are being split into triangles differently than you expect.

BTW, you will get a significant speed-up if you use GL_TRIANGLE_STRIP (or GL_QUAD_STRIP) because you will be calling glVertex half as many times.