示例#1
0
OsdHbrMesh * 
ConvertToHBR( int nVertices,
              std::vector<int>   const & faceVertCounts,
              std::vector<int>   const & faceIndices,
              std::vector<int>   const & vtxCreaseIndices,
              std::vector<double> const & vtxCreases,
              std::vector<int>   const & edgeCrease1Indices,  // face index, local edge index
              std::vector<float> const & edgeCreases1,
              std::vector<int>   const & edgeCrease2Indices,  // 2 vertex indices (Maya friendly)
              std::vector<double> const & edgeCreases2,
              OsdHbrMesh::InterpolateBoundaryMethod interpBoundary,
              HbrMeshUtil::SchemeType scheme,
              bool usingPtex,
              FVarDataDesc const * fvarDesc,
              std::vector<float> const * fvarData
            )
{

    static OpenSubdiv::HbrBilinearSubdivision<OpenSubdiv::OsdVertex> _bilinear;
    static OpenSubdiv::HbrLoopSubdivision<OpenSubdiv::OsdVertex> _loop;
    static OpenSubdiv::HbrCatmarkSubdivision<OpenSubdiv::OsdVertex> _catmark;

    // Build HBR mesh with/without face varying data, according to input data.
    // If a face-varying descriptor is passed in its memory needs to stay 
    // alive as long as this hbrMesh is alive (for indices and widths arrays). 
    OsdHbrMesh *hbrMesh;
    if ( fvarDesc )
    {
        if (scheme == HbrMeshUtil::kCatmark)
            hbrMesh = new OsdHbrMesh(&_catmark,  fvarDesc->getCount(), 
                                                 fvarDesc->getIndices(), 
                                                 fvarDesc->getWidths(), 
                                                 fvarDesc->getTotalWidth());
        else if (scheme == HbrMeshUtil::kLoop)
            hbrMesh = new OsdHbrMesh(&_loop,     fvarDesc->getCount(), 
                                                 fvarDesc->getIndices(), 
                                                 fvarDesc->getWidths(), 
                                                 fvarDesc->getTotalWidth());
        else 
            hbrMesh = new OsdHbrMesh(&_bilinear, fvarDesc->getCount(),
                                                 fvarDesc->getIndices(), 
                                                 fvarDesc->getWidths(), 
                                                 fvarDesc->getTotalWidth());
    }
    else
    {
        if (scheme == HbrMeshUtil::kCatmark)
            hbrMesh = new OsdHbrMesh(&_catmark);
        else if (scheme == HbrMeshUtil::kLoop)
            hbrMesh = new OsdHbrMesh(&_loop);
        else
            hbrMesh = new OsdHbrMesh(&_bilinear);
    }


    // create empty verts: actual vertices initialized in UpdatePoints();
    OpenSubdiv::OsdVertex v;
    for (int i = 0; i < nVertices; ++i) {
        hbrMesh->NewVertex(i, v);
    }

    std::vector<int> vIndex;
    int nFaces = (int)faceVertCounts.size();
    int fvcOffset = 0;          // face-vertex count offset
    int ptxIdx = 0;

    for (int fi = 0; fi < nFaces; ++fi) 
    {
        int nFaceVerts = faceVertCounts[fi];
        vIndex.resize(nFaceVerts);

        bool valid = true;
        for (int fvi = 0; fvi < nFaceVerts; ++fvi) 
        {
            vIndex[fvi] = faceIndices[fvi + fvcOffset];
            int vNextIndex = faceIndices[(fvi+1) % nFaceVerts + fvcOffset];

            // check for non-manifold face
            OsdHbrVertex * origin = hbrMesh->GetVertex(vIndex[fvi]);
            OsdHbrVertex * destination = hbrMesh->GetVertex(vNextIndex);
            if (!origin || !destination) {
                OSD_ERROR("ERROR : An edge was specified that connected a nonexistent vertex");
                valid = false;
            }

            if (origin == destination) {
                OSD_ERROR("ERROR : An edge was specified that connected a vertex to itself");
                valid = false;
            }

            OsdHbrHalfedge * opposite = destination->GetEdge(origin);
            if (opposite && opposite->GetOpposite()) {
                OSD_ERROR("ERROR : A non-manifold edge incident to more than 2 faces was found");
                valid = false;
            }

            if (origin->GetEdge(destination)) {
                OSD_ERROR("ERROR : An edge connecting two vertices was specified more than once. "
                          "It's likely that an incident face was flipped");
                valid = false;
            }
        }

        if ( valid ) 
        {
            if (scheme == HbrMeshUtil::kLoop) {
                // triangulate
                int triangle[3];
                triangle[0] = vIndex[0];
                for (int fvi = 2; fvi < nFaceVerts; ++fvi) {
                    triangle[1] = vIndex[fvi-1];
                    triangle[2] = vIndex[fvi];
                    hbrMesh->NewFace(3, triangle, 0);
                }
                // ptex not fully implemented for loop, yet
                // fvar not fully implemented for loop, yet

            } else {

                // bilinear not entirely implemented

                OsdHbrFace *face = hbrMesh->NewFace(nFaceVerts, &(vIndex[0]), 0);

                if (usingPtex) {
                    face->SetPtexIndex(ptxIdx);
                    ptxIdx += (nFaceVerts == 4) ? 1 : nFaceVerts;
                }

                if (fvarData) {
                    int fvarWidth = hbrMesh->GetTotalFVarWidth();
                    const float *faceData = &(*fvarData)[ fvcOffset*fvarWidth ];
                    for(int fvi=0; fvi<nFaceVerts; ++fvi)
                    {
                        OsdHbrVertex *v = hbrMesh->GetVertex( vIndex[fvi] );
                        OsdHbrFVarData& fvarData = v->GetFVarData(face);
                        if ( ! fvarData.IsInitialized() )
                        {
                            fvarData.SetAllData( fvarWidth, faceData );
                        }
                        else if (!fvarData.CompareAll(fvarWidth, faceData))
                        {
                            OsdHbrFVarData& fvarData = v->NewFVarData(face);
                            fvarData.SetAllData( fvarWidth, faceData );
                        }

                        // advance pointer to next set of face-varying data
                        faceData += fvarWidth;
                    }
                }
            }
        } else {
            OSD_ERROR("Face %d will be ignored\n", fi);
        }

        fvcOffset += nFaceVerts;
    }

    // Assign boundary interpolation methods
    hbrMesh->SetInterpolateBoundaryMethod(interpBoundary);
    if ( fvarDesc ) 
        hbrMesh->SetFVarInterpolateBoundaryMethod(fvarDesc->getInterpBoundary());

    // XXX hbr behavior doesn't match naming of k_Interpolate constants
    // hbrMesh->SetFVarInterpolateBoundaryMethod(OsdHbrMesh::k_InterpolateBoundaryEdgeAndCorner);   // no for cube
    // hbrMesh->SetFVarInterpolateBoundaryMethod(OsdHbrMesh::k_InterpolateBoundaryNone);            // yes for cube
    // hbrMesh->SetFVarInterpolateBoundaryMethod(OsdHbrMesh::k_InterpolateBoundaryEdgeOnly);


    // set edge crease in two different indexing way
    size_t nEdgeCreases = edgeCreases1.size();
    for (size_t i = 0; i < nEdgeCreases; ++i) {
        if (edgeCreases1[i] <= 0.0)
            continue;

        OsdHbrHalfedge * e = hbrMesh->
            GetFace(edgeCrease1Indices[i*2])->
            GetEdge(edgeCrease1Indices[i*2+1]);

        if (!e) {
            OSD_ERROR("Can't find edge (face %d edge %d)\n",
                      edgeCrease1Indices[i*2], edgeCrease1Indices[i*2+1]);
            continue;
        }
        e->SetSharpness(static_cast<float>(edgeCreases1[i]));
    }
    nEdgeCreases = edgeCreases2.size();
    for (size_t i = 0; i < nEdgeCreases; ++i) {
        if (edgeCreases2[i] <= 0.0)
            continue;

        OsdHbrVertex * v0 = hbrMesh->GetVertex(edgeCrease2Indices[i*2]);
        OsdHbrVertex * v1 = hbrMesh->GetVertex(edgeCrease2Indices[i*2+1]);
        OsdHbrHalfedge * e = NULL;

        if (v0 && v1)
            if (!(e = v0->GetEdge(v1)))
                e = v1->GetEdge(v0);
        if (!e) {
            OSD_ERROR("ERROR can't find edge");
            continue;
        }
        e->SetSharpness(static_cast<float>(edgeCreases2[i]));
    }

    // set corner
    {
        size_t nVertexCreases = vtxCreases.size();
        for (size_t i = 0; i < nVertexCreases; ++i) {
            if (vtxCreases[i] <= 0.0)
                continue;
            OsdHbrVertex * v = hbrMesh->GetVertex(vtxCreaseIndices[i]);
            if (!v) {
                OSD_ERROR("Can't find vertex %d\n", vtxCreaseIndices[i]);
                continue;
            }
            v->SetSharpness(static_cast<float>(vtxCreases[i]));
        }
    }

    hbrMesh->Finish();
    return hbrMesh;
}
// Here is where the real meat of the OSD setup happens. The mesh topology is 
// created and stored for later use. Actual subdivision happens in updateGeom 
// which gets called at the end of this function and on frame change.
//
void
createOsdContext(int level)
{
    // 
    // Setup an OsdHbr mesh based on the desired subdivision scheme
    //
    static OpenSubdiv::HbrCatmarkSubdivision<OpenSubdiv::OsdVertex>  _catmark;
    OsdHbrMesh *hmesh(new OsdHbrMesh(&_catmark));

    //
    // Now that we have a mesh, we need to add verticies and define the topology.
    // Here, we've declared the raw vertex data in-line, for simplicity
    //
    float verts[] = {    0.000000f, -1.414214f, 1.000000f,
                        1.414214f, 0.000000f, 1.000000f,
                        -1.414214f, 0.000000f, 1.000000f,
                        0.000000f, 1.414214f, 1.000000f,
                        -1.414214f, 0.000000f, -1.000000f,
                        0.000000f, 1.414214f, -1.000000f,
                        0.000000f, -1.414214f, -1.000000f,
                        1.414214f, 0.000000f, -1.000000f
                        };

    //
    // The cube faces are also in-lined, here they are specified as quads
    //
    int faces[] = {
                        0,1,3,2,
                        2,3,5,4,
                        4,5,7,6,
                        6,7,1,0,
                        1,7,5,3,
                        6,0,2,4
                        };
    //
    // Record the original vertex positions and add verts to the mesh.
    //
    // OsdVertex is really just a place holder, it doesn't care what the 
    // position of the vertex is, it's just being used here as a means of
    // defining the mesh topology.
    //
    for (unsigned i = 0; i < sizeof(verts)/sizeof(float); i += 3) {
        g_orgPositions.push_back(verts[i+0]);
        g_orgPositions.push_back(verts[i+1]);
        g_orgPositions.push_back(verts[i+2]);
        
        OpenSubdiv::OsdVertex vert;
        hmesh->NewVertex(i/3, vert);
    }

    //
    // Now specify the actual mesh topology by processing the faces array 
    //
    const unsigned VERTS_PER_FACE = 4;
    for (unsigned i = 0; i < sizeof(faces)/sizeof(int); i += VERTS_PER_FACE) {
        //
        // Do some sanity checking. It is a good idea to keep this in your 
        // code for your personal sanity as well.
        //
        // Note that this loop is not changing the HbrMesh, it's purely validating
        // the topology that is about to be created below.
        //
        for (unsigned j = 0; j < VERTS_PER_FACE; j++) {
            OsdHbrVertex * origin      = hmesh->GetVertex(faces[i+j]);
            OsdHbrVertex * destination = hmesh->GetVertex(faces[i+((j+1)%VERTS_PER_FACE)]);
            OsdHbrHalfedge * opposite  = destination->GetEdge(origin);

            if(origin==NULL || destination==NULL) {
                std::cerr << 
                    " An edge was specified that connected a nonexistent vertex"
                    << std::endl;
                exit(1);
            }

            if(origin == destination) {
                std::cerr << 
                    " An edge was specified that connected a vertex to itself" 
                    << std::endl;
                exit(1);
            }

            if(opposite && opposite->GetOpposite() ) {
                std::cerr << 
                    " A non-manifold edge incident to more than 2 faces was found" 
                    << std::endl;
                exit(1);
            }

            if(origin->GetEdge(destination)) {
                std::cerr << 
                    " An edge connecting two vertices was specified more than once."
                    " It's likely that an incident face was flipped" 
                    << std::endl;
                exit(1);
            }
        }
        // 
        // Now, create current face given the number of verts per face and the 
        // face index data.
        //
        /* OsdHbrFace * face = */ hmesh->NewFace(VERTS_PER_FACE, faces+i, 0);

        //
        // If you had ptex data, you would set it here, for example
        //
        /* face->SetPtexIndex(ptexIndex) */

    }

    //
    // Apply some tags to drive the subdivision algorithm. Here we set the 
    // default boundary interpolation mode along with a corner sharpness. See 
    // the API and the renderman spec for the full list of available operations.
    //
    hmesh->SetInterpolateBoundaryMethod( OsdHbrMesh::k_InterpolateBoundaryEdgeOnly );
    
    OsdHbrVertex * v = hmesh->GetVertex(0);
    v->SetSharpness(2.7f);

    //
    // Finalize the mesh object. The Finish() call is a signal to the internals 
    // that optimizations can be made on the mesh data. 
    //
    hmesh->Finish();

    //
    // Setup some raw vectors of data. Remember that the actual point values were
    // not stored in the OsdVertex, so we keep track of them here instead
    //
    g_normals.resize(g_orgPositions.size(),0.0f);
    calcNormals( hmesh, g_orgPositions, g_normals );

    // 
    // At this point, we no longer need the topological structure of the mesh, 
    // so we bake it down into subdivision tables by converting the HBR mesh 
    // into an OSD mesh. Note that this is just storing the initial subdivision
    // tables, which will be used later during the actual subdivision process.
    //
    // Again, no vertex positions are being stored here, the point data will be 
    // sent to the mesh in updateGeom().
    //
    OpenSubdiv::FarMeshFactory<OpenSubdiv::OsdVertex> meshFactory(hmesh, level);

    g_farmesh = meshFactory.Create();

    g_osdComputeContext = OpenSubdiv::OsdCpuComputeContext::Create(g_farmesh);

    delete hmesh;

    // 
    // Initialize draw context and vertex buffer
    //
    g_vertexBuffer = 
        OpenSubdiv::OsdCpuGLVertexBuffer::Create(6,  /* 3 floats for position, 
                                                            +
                                                            3 floats for normal*/
                                                 g_farmesh->GetNumVertices());

    g_drawContext =
        OpenSubdiv::OsdGLDrawContext::Create(g_farmesh->GetPatchTables(), false);
    g_drawContext->UpdateVertexTexture(g_vertexBuffer);

    // 
    // Setup camera positioning based on object bounds. This really has nothing
    // to do with OSD.
    //
    computeCenterAndSize(g_orgPositions, g_center, &g_size);

    //
    // Finally, make an explicit call to updateGeom() to force creation of the 
    // initial buffer objects for the first draw call.
    //
    updateGeom();

    //
    // The OsdVertexBuffer provides GL identifiers which can be bound in the 
    // standard way. Here we setup a single VAO and enable points and normals 
    // as attributes on the vertex buffer and set the index buffer.
    //
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, g_vertexBuffer->BindVBO());
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof (GLfloat) * 6, 0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof (GLfloat) * 6, (float*)12);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_drawContext->GetPatchIndexBuffer());
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}