在opengl es 2中渲染时拉伸的圆

mcdcgff0  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(407)

我已经在我的设备上渲染了一个纯白色的圆圈,但是它根据屏幕尺寸成比例地在我的设备上延伸。翻阅2d的例子和可能的答案,我没有能够正确的缩放它。
我的渲染器类:

@Override
public void onSurfaceChanged(GL10 gl, int width, int height)
{
    float scaleX = (float) width / Screen.getScreenWidthPx();
    float scaleY = (float) height / Screen.getScreenHeightPx();
    final int vpWidth = (int)(Screen.getScreenWidthPx() * scaleX);
    final int vpHeight = (int)(Screen.getScreenHeightPx() * scaleY);

    GLES20.glViewport(0, 0, vpWidth, vpHeight);

    mCam.setProjection(Screen.getScreenWidthPx(), Screen.getScreenHeightPx());
}

我的相机课:

public void setProjection(float width, float height)
{        
    final float ratio = width / height;
    Matrix.orthoM(mProjection, 0, 0, width, height, 0, -1, 1);
}

顶点着色器:

private String mVSCode =
        "attribute vec4 vPosition;" +
                "uniform float sWidth;" +
                "uniform float sHeight;" +
                "void main() {" +
                "gl_Position = vPosition;" +                  
                "}";

结果:

4nkexdtk

4nkexdtk1#

你必须决定你想做什么。如果要将顶点坐标1:1绘制为窗口坐标(像素),则正交投影是正确的。
但是如果你只想考虑纵横比,那么投影必须是:

public void setProjection(float width, float height)
{        
    final float ratio = width / height;
    Matrix.orthoM(mProjection, 0, -1, 1, 1/ratio, -1/ratio, -1, 1);
}

无论如何,必须通过顶点着色器中的正交投影矩阵变换顶点坐标。
添加矩阵均匀( mat4 uProjection )到顶点着色器。把制服穿上 mProjection . 将顶点坐标乘以 uProjection 在顶点着色器中:

attribute vec4 vPosition;

uniform uProjection;

void main() {
    gl_Position = uProjection* vPosition;
}

或者,可以在顶点着色器中手动设置正交投影矩阵:
(当然你得把制服穿好 sWidth 分别 sHeight )

attribute vec4 vPosition;

uniform float sWidth;
uniform float sHeight;

void main() {

    mat4 projection = mat4(1.0);
    projection[1][1] = -sHeight/sWidth;

    gl_Position = projection * vPosition;            
};

或者如果要使用窗口坐标:

attribute vec4 vPosition;

uniform float sWidth;
uniform float sHeight;

void main() {

    mat4 projection = mat4(
        vec4( 2.0/sWidth,  0.0,         0.0, 0.0),
        vec4( 0.0,        -2.0/sHeight, 0.0, 0.0),
        vec4( 0.0,         0.0,         1.0, 0.0),
        vec4(-1.0,         1.0,         0.0, 1.0));

    gl_Position = projection * vPosition;            
};

相关问题