Perspective correct texturing of trapezoid in OpenGL ES 2.0

前端 未结 3 912
执念已碎
执念已碎 2020-11-27 05:00

I have drawn a textured trapezoid, however the result does not appear as I had intended.

Instead of appearing as a single unbroken quadrilateral, a discontinuity occ

3条回答
  •  温柔的废话
    2020-11-27 05:39

    The accepted answer gives the correct solution and explanation but for those looking for a bit more help on the OpenGL (ES) 2.0 pipeline...

    const GLfloat L = 2.0;
    const GLfloat Z = -2.0;
    const GLfloat W0 = 0.01;
    const GLfloat W1 = 0.10;
    
    /** Trapezoid shape as two triangles. */
    static const GLKVector3 VERTEX_DATA[] = {
        {{-W0,    0,  Z}},
        {{+W0,    0,  Z}},
        {{-W1,    L,  Z}},
    
        {{+W0,    0,  Z}},
        {{+W1,    L,  Z}},
        {{-W1,    L,  Z}},
    };
    
    /** Add a 3rd coord to your texture data.  This is the perspective divisor needed in frag shader */
    static const GLKVector3 TEXTURE_DATA[] = {
        {{0, 0, 0}},
        {{W0, 0, W0}},
        {{0, W1, W1}},
    
        {{W0, 0, W0}},
        {{W1, W1, W1}},
        {{0, W1, W1}},
    };
    
    ////////////////////////////////////////////////////////////////////////////////////
    
    // frag.glsl
    
    varying vec3 v_texPos;
    uniform sampler2D u_texture;
    
    void main(void) 
    {
        // Divide the 2D texture coords by the third projection divisor
        gl_FragColor = texture2D(u_texture, v_texPos.st / v_texPos.p);
    }
    

    Alternatively, in the shader, as per @maverick9888's answer, You can use texture2Dproj though for iOS / OpenGLES2 it still only supports a vec3 input...

    void main(void) 
    {
        gl_FragColor = texture2DProj(u_texture, v_texPos);
    }
    

    I haven't really benchmarked it properly but for my very simple case (a 1d texture really) the division version seems a bit snappier.

提交回复
热议问题