I need to use a heightmap (.png) to modify a terrain (2D plane) but I just can’t make it work.
I am trying to make a new texture using the .png, then in vertex shader ( I need to work with vertex shader ) I have to modify the vertexes depending on the texture.
channels = 1 // I think this is for grey
Creating the texture :
heightPixels = stbi_load((textureLoc + "heightmap.png").c_str(), &width, &height, &channels, STBI_grey);
GLuint textureID = 6;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
//Send heightPixels to gpu
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, (void*)heightPixels);
Texture2D* texture = new Texture2D();
texture->Init(textureID, width, height, channels);
mapTextures["heightMap"] = texture;
Vertex Shader:
#version 330
layout(location = 0) in vec3 v_position;
layout(location = 1) in vec3 v_normal;
layout(location = 2) in vec2 v_texture_coord;
layout(location = 3) in vec3 v_color;
// Uniform properties
uniform mat4 Model;
uniform mat4 View;
uniform mat4 Projection;
uniform sampler2D texture_1;
uniform int heightMapSize;
uniform float time;
out vec2 texcoord;
void main()
{
// TODO : pass v_texture_coord as output to Fragment Shader
texcoord = v_texture_coord;
float u = v_texture_coord.x;
float v = v_texture_coord.y;
float height = texture2D(texture_1, vec2(u,v)).r;
//normalization for lighting
vec2 texelSize = vec2(1.0/heightMapSize,1.0/heightMapSize);
float heightRight = texture2D(texture_1, vec2(u + texelSize.x,v)).r;
float heightUp = texture2D(texture_1, vec2(u,v + texelSize.y)).r;
float Hx = height - heightRight;
float Hz = height - heightUp;
vec3 normal = normalize(vec3(Hz,1,Hz));
//Calculating new position
vec3 new_pos = v_position + vec3(0,0,height * 10);
gl_Position = Projection * View * Model * vec4(new_pos, 1.0);
}
Fragment Shader:
#version 330
uniform sampler2D texture_1;
uniform sampler2D texture_2;
uniform int mixer;
in vec2 texcoord;
layout(location = 0) out vec4 out_color;
void main()
{
// TODO : calculate the out_color using the texture2D() function
vec4 color1 = texture2D(texture_1, texcoord);
vec4 color2 = texture2D(texture_2, texcoord);
vec4 color;
if(mixer == 1)
color = mix(color1, color2, 0.5f);
else
color = color1;
if(color.a < 0.5f)
discard;
out_color = color;
}
The problem is that the texture is invisible (nothing appears), if I use other textures (random ones) they appear but the plane is white and there is no deformity.