简体   繁体   中英

Passing SRTM *.hgt file as texture to OpenGL shader results in skewed image

I am writing terrain renderer that interprets NASA SRTM *.hgt files to get height data. I implemented LOD technique described here: http://www.pheelicks.com/2014/03/rendering-large-terrains/ .

My terrain mesh has 1024 width and height. The height map is 1201 x 1201. I load the height map into memory and the send it to shader as a texture. Then I sample it in vertex shader using current vertex position which x and z component is in range [-512, 512]. Next I divide it by 1024 which gives me vector with x and z in range [-0.5, 0.5]. The upper left corner of the mesh is at (-0.5, -0.5) so I add vec2(0.5, 0.5) to "normalize" it.

When sampling a jpeg file with the calculated co-ordinates it all looks as expected, but when I'm sampling the heightmap it looks like this: 在此处输入图片说明

with this strange diagonal line. After thinkig for a while what's wrong with this image I discovered that the heightmap is actually just skewed (or my sampling is somehow skewed...) and on the left you can see the part that should be on the right, like here: 在此处输入图片说明

I have no idea what's going on here. Considering the fact that the jpeg image was laying perfectly on the mesh with the same sampling code I thought that it cannot be something wrong with the sampling method.

All the code is available on the github repository: https://github.com/0ctothorp/terrain_rendering/tree/lod2 in the "lod2" branch.

The most interesting part is probably the sampling code:

sample_ = texture(heightmap, (position.xz / meshSize) + vec2(0.5f, 0.5f)).r;
position.y = sample_ / 50.0f;

and how I pass heightmap to shader:

GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, GL_R16I, 1201, 1201, 0, GL_RED_INTEGER, GL_SHORT, 
                      hmData->data()));

Apparently your data is tightly packed, whereas OpenGL expects it to be 4-byte aligned by default. You can override the expected alignment with the following prior to the glTexImage2D call:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM