I currently have a terrain mesh that I’m successfully rendering, generated from digital elevation data. Now I need to render a line over that terrain such that the line is “draped” over the contours of the terrain.

My approach has been to render the full height and width of the terrain to a heightmap texture using an orthographic projection. Then, when I’m drawing the line, I can sample the heightmap for the correct height.

My problem is I’m having difficulty calculating the correct UV coordinates to look up the height in the texture. My line will have height variations, but they are all over the place and do not follow the terrain in the slightest. Often going into the terrain itself.

Currently I’m calculating the UV coordinates in the vertex shader for the line. I’ve tried using a separate UV buffer as well but I get the same results.

Here is my vertex shader where I’m calculating the UV and interpolating the height stored in the red channel.

```
#version 120
uniform mat4 Model;
uniform mat4 View;
uniform mat4 Projection;
attribute vec2 Vertex;
uniform sampler2D terraintexture;
void main()
{
vec2 pos;
// Map vertex to -1 -> 1 range
pos.x = (Vertex.x) / (HalfSquareSize);
pos.y = (Vertex.y) / (HalfSquareSize);
// Then convert to 0 -> 1 for texture
pos += 1.0;
pos /= 2.0;
vec4 tex = texture2D(terraintexture, pos);
// Convert 0 -> 1 back to MinHeight -> MaxHeight
float altitude = (tex.r * (2 * MaxHeight)) - MaxHeight;
// Apply model with vertex at 0 height
vec4 x = Model * vec4(Vertex.x, 0.0, Vertex.y, 1.0);
// Apply our offset
x.y += altitude;
gl_Position = Projection * View * x;
}
```

I’ve thought that maybe my heightmap and terrain mesh were possibly rotated differently, but I’ve tried rotating the heightmap multiple ways with no results. Any help is greatly appreciated, thank you.