3d terrain heightmap not working

Recently I have been working on some 3d terrain which takes a model and stores the heights of each point in an array. The model loading works correctly and when I assign the heights to a 2d array it works, but for some reason after the for loop most of the values get set two zero. It seems random too. Here is my code:

public HeightMap(Model terrain) {
		width = 202;
		height = 202;
		heightMap = new float[width][height];

		for (int i=0; i<width; i++) {
			for (int j=0; j<height; j++) {
				heightMap[i][j] = 0;
			}
		}		
		for (int i=0; i<terrain.vertices.size(); i++) {
			Vector3f vec = terrain.vertices.get(i);
			heightMap[(int)(vec.x+((float)width/2f))]
					[(int)(vec.z+((float)height/2f))] = vec.y;
		}
	}

It’s probably just something stupid but I can’t figure it out.

Without seeing the Model class it’s quite hard to see what’s going on here. Can you post that code as well? or at least a fragment of what the data looks like.

However there’s a couple of things in there that look suspicious to me:

public HeightMap(Model terrain) {
		width = 202;
		height = 202;
		...

Why 202? Seems a bit of a random size. Why not 200, or maybe even 201?


		for (int i=0; i<terrain.vertices.size(); i++) {
			Vector3f vec = terrain.vertices.get(i);
			heightMap[(int)(vec.x+((float)width/2f))]
					[(int)(vec.z+((float)height/2f))] = vec.y;
		}

What is the reason for including the width/height divided by two in this loop? Again seems a rather odd way of deriving the 2D height-map from the vertices.

Assuming the model is a one-dimensional array of the same width-height size as the height-map then surely this is simpler:


		int idx = 0;
		for (int x=0; x<width; x++) {
			for (int z=0; z<height; z++) {
				Vector3f vec = terrain.vertices.get(idx);
				heightMap[x][z] = vec.y;
				++idx;
			}
		}		

Also, I would change the loop that initialises the height-map data to zero to set it to something else (say -1 or 256 or whatever your maximum height is) which might help to diagnose the problem. In any case, assuming the model is the same size as the height-map (and why would you make it any different?) then what’s the point in initialising the height-map at all?

Finally, I’m surprised you are attempting to ‘extract’ the height-map from the model, generally it happens the other way round. i.e. load or create a height-map (from a grey-scale image or some noise function) and then generate a 3D model from that data. Usually the height-map (and image) can then be discarded, the only time the height-map usually needs to remain in memory is if you’re implementing some sort of terrain following or collision system that doesn’t use the model itself.

Not meant to be criticisms, just some pointers that hopefully might help?

  • stride