在Open GL中计算曲面的法线

时间:2012-11-15 07:16:11

标签: c++ opengl graphics

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

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);

我是否正确计算法线?

2 个答案:

答案 0 :(得分:8)

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

enter image description here

参考此问题:Techniques to smooth face edges in OpenGL

答案 1 :(得分:2)

您是否已将glShadeModel设置为GL_SMOOTH?

请参阅:http://www.khronos.org/opengles/documentation/opengles1_0/html/glShadeModel.html

此设置除了照明外,还会影响顶点颜色。你似乎说它甚至在光照之前都是块状的,这让我觉得这是个问题。