glViewport偏移和正射投影

时间:2016-06-01 14:53:15

标签: c++ opengl viewport orthographic

在所有教程中,我发现基于视口大小创建投影矩阵,所有这些都假设视口的左下角坐标为(0,0)。

现在我想绘制到屏幕的不同部分,为此我想相应地切换视口:

glViewport(0,0,windowWidth/2, windowHeight/2); //left bottom
glViewport(0,windowHeight/2,windowWidth/2, windowHeight/2);//left top
glViewport(windowWidth/2,0,windowWidth/2, windowHeight/2);//right bottom
glViewport(windowWidth/2, windowHeight/2,windowWidth/2, windowHeight/2);//right top

现在我在定义投影矩阵方面遇到了问题。没有任何(x,y)offest我使用此代码来计算我的正投影矩阵:

if (m_WindowWidth > m_WindowHeight)
{
    auto viewportAspectRatio = (float)m_WindowWidth / (float)m_WindowHeight;

    m_ProjectionMatrix.m_fLeft = (-1.0f) * m_fWindowSize * viewportAspectRatio;
    m_ProjectionMatrix.m_fRight = m_fWindowSize * viewportAspectRatio;
    m_ProjectionMatrix.m_fBottom = (-1.0f)*m_fWindowSize;
    m_ProjectionMatrix.m_fTop = m_fWindowSize;
    m_ProjectionMatrix.m_fNear = -(10.0f)*m_fWindowSize;
    m_ProjectionMatrix.m_fFar = (10.0f)*m_fWindowSize;

    m_fMoveSpeed = static_cast<GLfloat>(m_fWindowSize * 2 / static_cast<float>(m_WindowHeight));
}
else
{
    auto viewportAspectRatio = (float)m_WindowHeight / (float)m_WindowWidth;

    m_ProjectionMatrix.m_fLeft = (-1.0f)*m_fWindowSize;
    m_ProjectionMatrix.m_fRight = m_fWindowSize;
    m_ProjectionMatrix.m_fBottom = (-1.0f)*m_fWindowSize * viewportAspectRatio;
    m_ProjectionMatrix.m_fTop = m_fWindowSize * viewportAspectRatio;
    m_ProjectionMatrix.m_fNear = -(10.0f)*m_fWindowSize;
    m_ProjectionMatrix.m_fFar = (10.0f)*m_fWindowSize;

    m_fMoveSpeed = static_cast<GLfloat>(m_fWindowSize * 2 / static_cast<float>(m_WindowWidth));
}

这样可以正常工作 UNTIL 我会在视口中添加任何(x,y)偏移量。使用glViewport(0, m_WindowHeight/2, m_WindowWidth/2, m_WindowHeight/2)后效果如下:

How to obtain the RevCommit or ObjectId from a SHA1 ID string with JGit?

使用glViewport(0, 0, m_WindowWidth/2, m_WindowHeight/2)glViewport(0, m_WindowHeight/2,  m_WindowWidth/2, m_WindowHeight/2)

如何让它发挥作用?

2 个答案:

答案 0 :(得分:0)

首先,宽高比始终是宽度/高度。

然后我认为你在寻找的是:

m_ProjectionMatrix.m_fLeft = x;
m_ProjectionMatrix.m_fRight = x + m_WindowWidth;
m_ProjectionMatrix.m_fBottom = y;
m_ProjectionMatrix.m_fTop = y + m_WindowHeight;
m_ProjectionMatrix.m_fNear = -(10.0f)*m_fWindowSize;
m_ProjectionMatrix.m_fFar = (10.0f)*m_fWindowSize;

看看这个wiki page

答案 1 :(得分:0)

我找到了解决这个问题的方法并将其发布在gamedev论坛上: https://gamedev.stackexchange.com/questions/122284/glviewport-offset-and-ortho-projection/122289#122289

简而言之: 我正在将整个场景绘制到帧缓冲区,然后我将生成的纹理渲染到屏幕上。此操作导致不需要的glViewport()转换累积。

解决这个问题的方法是将glViewport()设置为原始befrore渲染到帧缓冲区,然后在将纹理渲染到屏幕时设置偏移。