Question background:
I need to align two images with the same resolution and display the alignment on an OpenGL canvas. So I prepared the vertices like so:
float vertices[] = {
// positions
0.0f, 0.0f, // bottom left
width, 0.0f, // bottom right
0.0f, height, // top left
width, 0.0f, // bottom right
0.0f, height, // top left
width, height, // top right
};
This way I can draw any number of images on top the other using the same shader, I just send the texture and a transformation matrix to the shader per each aligned image.
With the following vertex and fragment shader, the effect is working as expected:
Vertex shader:
#version 330 core
layout (location = 0) in vec3 vertex_in;
out vec2 TexCoord;
uniform mat3 cvAffine; // OpenCV affine transformation matrix
const vec2 texture_coord[] = {
vec2( 0.0, 0.0),
vec2( 1.0, 0.0),
vec2( 0.0, 1.0),
vec2( 1.0, 0.0),
vec2( 0.0, 1.0),
vec2( 1.0, 1.0)
};
void main(){
vec3 cvCoord = vec3(vertex_in.xy,1.0f); //Create homogenous 2D vector for 3x3 mat mult.
vec3 transformedCoord = cvAffine*cvCoord; //Transform the image
gl_Position = vec4((transformedCoord.xy*0.0002), 0.0, transformedCoord.z); //Scale it down for us to see it
TexCoord = texture_coord[gl_VertexID]; //Send a texture coordinate to the frag. shader
};
Fragment shader
#version 330 core
in vec2 TexCoord;
out vec4 FragColor;
uniform sampler2D texture;
void main(){
FragColor = texture(texture, TexCoord);
}
The effect:
The actual question:
When I modify this line in the vertex shader:
gl_Position = vec4((transformedCoord.xy*0.0002), 0.0, transformedCoord.z);
with supposedly equivalent line:
gl_Position = vec4(((transformedCoord.xy/transformedCoord.z)*0.0002), 0.0, 1.0);
the alignment breaks:
And there is this common problem with many names:
- Affine Texture mapping
- Perspective correct Texture mapping
- Projective Texture mapping
- Trapezoid texture mapping
How is it possible that Vector(xW,yW,z*W,W) is not equal to Vector(x,y,z,1)? Or at least the fragment shader does not agree with that? I need to have 1 in gl_Position.w component as it allows me to further transform pictures around the canvas while preserving the alignment. I have touched the w component of the uv texture space and project it in some way but I was not successful. How to properly transform the texture coordinates so that the texture is sampled uniformly across the whole distorted two-triangle rectangle?
The geometry itself does not change between the modification, only the texture is drawn differently.