1

我正在使用 GLUtesselator 来填充一些非凸多边形。

它工作得很好,但是对于一些多边形,它抱怨它需要一个组合函数,所以我提供了一个非常简单的 GLU_TESS_COMBINE 回调,它分配一个新顶点并只复制坐标(它是纯色的 2D,所以我不需要插值RGB值或任何东西):

void CALLBACK tessCombine( GLdouble coords[3], GLdouble * vertex_data[4], GLfloat weight[4], GLdouble **outData )
{
    GLdouble *vertex = new GLdouble[3];
    vertex[0] = coords[0];
    vertex[1] = coords[1];
    vertex[2] = coords[2];
    *outData = vertex;
}

现在一切都按预期呈现,但它显然泄漏了内存。文档说:

分配另一个顶点,[...] 在调用 gluTessEndPolygon 后的某个时间释放内存。

但是在我发现的所有示例中,它们都没有显示如何处理内存。回调是免费函数,没有办法释放那里分配的内存,是吗?

我能想到的唯一方法是将它们存储在某个地方,然后自己删除它们。这是正确的方法吗?

4

1 回答 1

3

看看这个 OpenGL Tessellation 教程

关键是不要在回调中分配任何内存(否则你会得到内存泄漏)。相反,您应该将顶点数据复制到回调中的内存位置(就像在示例中所做的那样。从哪里复制顶点数据,由您决定。

这是回调函数在他们的示例中的样子:

void CALLBACK tessCombineCB(const GLdouble newVertex[3], const GLdouble *neighborVertex[4],
                            const GLfloat neighborWeight[4], GLdouble **outData)
{
    // copy new intersect vertex to local array
    // Because newVertex is temporal and cannot be hold by tessellator until next
    // vertex callback called, it must be copied to the safe place in the app.
    // Once gluTessEndPolygon() called, then you can safly deallocate the array.
    vertices[vertexIndex][0] = newVertex[0];
    vertices[vertexIndex][1] = newVertex[1];
    vertices[vertexIndex][2] = newVertex[2];

    // compute vertex color with given weights and colors of 4 neighbors
    // the neighborVertex[4] must hold required info, in this case, color.
    // neighborVertex was actually the third param of gluTessVertex() and is
    // passed into here to compute the color of the intersect vertex.
    vertices[vertexIndex][3] = neighborWeight[0] * neighborVertex[0][3] +   // red
                               neighborWeight[1] * neighborVertex[1][3] +
                               neighborWeight[2] * neighborVertex[2][3] +
                               neighborWeight[3] * neighborVertex[3][3];
    vertices[vertexIndex][4] = neighborWeight[0] * neighborVertex[0][4] +   // green
                               neighborWeight[1] * neighborVertex[1][4] +
                               neighborWeight[2] * neighborVertex[2][4] +
                               neighborWeight[3] * neighborVertex[3][4];
    vertices[vertexIndex][5] = neighborWeight[0] * neighborVertex[0][5] +   // blue
                               neighborWeight[1] * neighborVertex[1][5] +
                               neighborWeight[2] * neighborVertex[2][5] +
                               neighborWeight[3] * neighborVertex[3][5];


    // return output data (vertex coords and others)
    *outData = vertices[vertexIndex];   // assign the address of new intersect vertex

    ++vertexIndex;  // increase index for next vertex
}
于 2012-09-04T07:26:39.470 回答