Search code examples
c#openglglslopentk

Two images side by side - OpenGL


I want to display two images side by side using opengl (one image on left of the screen and other on right of screen). I have used below shader code for it. It shows two images in full screen. But only a part of both images are seen. Where should I correct the code to show full image on both side?

private void CreateShaders()
{
    /***********Vert Shader********************/
    vertShader = GL.CreateShader(ShaderType.VertexShader);
    GL.ShaderSource(vertShader, @"attribute vec3 a_position;
                                varying vec2 vTexCoord;
                                void main()
                                {
                                    vTexCoord = (a_position.xy + 1) / 2;
                                    gl_Position = vec4(a_position, 1);
                                }");
    GL.CompileShader(vertShader);

    /***********Frag Shader ****************/
    fragShader = GL.CreateShader(ShaderType.FragmentShader);
    GL.ShaderSource(fragShader, @"precision highp float;
                                uniform sampler2D sTexture;uniform sampler2D sTexture1;
                                uniform int screenwidth;
                                varying vec2 vTexCoord;
                                void main ()
                                {
                                    vec4 color = texture2D (sTexture, vTexCoord);  //image 1                            
                                    vec4 color1=texture2D (sTexture1, vTexCoord); //image2
                                    if(vTexCoord.x<0.5)
                                        gl_FragColor = color;
                                    else
                                        gl_FragColor    = color1;
                                }");
    GL.CompileShader(fragShader);
}

Solution

  • You have to scale and translate the x component of the texture coordinates in the fragment shader,

    For the left side the texture coordinate vec2(vTexCoord.x*2.0, vTexCoord.y), for the right side it is vec2(vTexCoord.x*2.0-1.0, vTexCoord.y)):

    varying vec2 vTexCoord;
    
    void main ()
    {
        vec4 color1 = texture2D(sTexture, vec2(vTexCoord.x*2.0, vTexCoord.y));
        vec4 color2 = texture2D(sTexture, vec2(vTexCoord.x*2.0-1.0, vTexCoord.y));
        gl_FragColor = vTexCoord.x < 0.5 ? color1 : color2;
    }