c++ - 在 Open GL 中计算曲面的法线

标签 c++ opengl graphics

我正在尝试为我的地形生成器添加阴影/光照。但出于某种原因,即使在我计算了表面法线之后,我的输出看起来仍然是 block 状的。

set<pair<int,int> >::const_iterator it;

for ( it = mRandomPoints.begin(); it != mRandomPoints.end(); ++it )
{
    for ( int i = 0; i < GetXSize(); ++i )
    {
        for ( int j = 0; j < GetZSize(); ++j )
        {
            float pd = sqrt(pow((*it).first - i,2) + pow((*it).second - j,2))*2 / mCircleSize;
            if(fabs(pd) <= 1.0)
            {
                mMap[i][j][2] += mCircleHeight/2 + cos(pd*3.14)*mCircleHeight/2; ;
            }

        }
    }
}

/*
    The three points being considered to compute normals are 
    (i,j)
    (i+1,j)
    (i, j+1)
*/

for ( int i = 0; i < GetXSize() -1 ; ++i )
{
    for ( int j = 0; j < GetZSize() - 1; ++j )
    {
        float b[] = {mMap[i+1][j][0]-mMap[i][j][0], mMap[i+1][j][1]-mMap[i][j][1], mMap[i+1][j][2]-mMap[i][j][2] };
        float c[] = {mMap[i][j+1][0]-mMap[i][j][0], mMap[i][j+1][1]-mMap[i][j][1], mMap[i][j+1][2]-mMap[i][j][2] };
        float a[] = {b[1]*c[2] - b[2]*c[1], b[2]*c[0]-b[0]*c[2], b[0]*c[1]-b[1]*c[0]};

        float Vnorm = sqrt(pow(a[0],2) + pow(a[1],2) + pow(a[2],2));

        mNormalMap[i][j][0] = a[0]/Vnorm;
        mNormalMap[i][j][1] = a[1]/Vnorm;
        mNormalMap[i][j][2] = a[2]/Vnorm;

    }
}

然后在绘制时我使用以下内容

float*** normal = map->GetNormalMap();

for (int i = 0 ; i < map->GetXSize() - 1; ++i)
{
    glBegin(GL_TRIANGLE_STRIP);

    for (int j = 0; j < map->GetZSize() - 1; ++j)
    {

        glNormal3fv(normal[i][j]);


        float color = 1 - (terrain[i][j][2]/height);
        glColor3f(color,color, color);
        glVertex3f(terrain[i][j][0], terrain[i][j][2], terrain[i][j][1]);
        glVertex3f(terrain[i+1][j][0], terrain[i+1][j][2], terrain[i+1][j][1]);
        glVertex3f(terrain[i][j+1][0], terrain[i][j+1][2], terrain[i][j+1][1]);
        glVertex3f(terrain[i+1][j+1][0], terrain[i+1][j+1][2], terrain[i+1][j+1][1]);
    }

    glEnd();
}

编辑:初始化代码

glFrontFace(GL_CCW);
glCullFace(GL_FRONT); // glCullFace(GL_BACK); 
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glEnable(GL_POLYGON_SMOOTH);
glMatrixMode(GL_PROJECTION);

我是否正确计算了法线?

最佳答案

除了 Bovinedragon 建议的内容,即 glShadeModel(GL_SMOOTH);,您可能应该使用逐顶点法线。这意味着每个 glVertex3f 之前都会有一个 glNormal3fv 调用,这将定义所有相邻面的平均法线。要获得它,您可以简单地将这些相邻的法 vector 相加并对结果进行归一化。

enter image description here

引用这个问题:Techniques to smooth face edges in OpenGL

关于c++ - 在 Open GL 中计算曲面的法线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13392995/

相关文章:

c++ - 如何设置 QVariant 结构?

c++ - class type info MACRO 可以用模板代替吗?

c++ - 未读行中的最后一个字

c++ - 转换透明 png 会使 SDL/OpenGL 崩溃

ios - 在 Metal 中访问 Mipmap 级别

c++ - 轴对齐矩形测试中的点?

OpenGL 4.1 和 3.1+,主要区别是什么?

opengl - 在 OpenGL 中存储和加载矩阵

python - 注释并将图例放在轴的一侧,多轴的特殊情况:

python - 填充颜​​色Python图形(印度国旗)