使用三角形条带或四边形条在 OpenGL 中绘图

Drawing in OpenGL using triangle strips or quad strips

本文关键字:OpenGL 绘图 四边形 三角形      更新时间:2023-10-16

我已经导出了一个.obj文件,并将其中的信息解析为顶点,uvs和法线(C++)的向量。如何在 OpenGL 中绘制此数据。请注意,我正在运行旧版本的OpenGL,并且被迫使用三角形条带和四边形条带。下面的代码显示了我到目前为止所拥有的。

OpenGLObject::OpenGLObject(std::string& fileName) {
    std::ifstream inFile(fileName.c_str());
    if (!inFile.is_open()) {
        std::string err = "[Error] Unable to open file " + fileName + ".";
        throw(err);
    }
    std::vector<unsigned int> vertexIndices, uvIndices, normalIndices;
    std::vector<glm::vec3> vertices;
    std::vector<glm::vec2> uvs;
    std::vector<glm::vec3> normals;
    // Reading file contents
    while (inFile.good()) {
        std::string token;
        inFile >> token;
        // Parsing verticies
        if (token == "v") {
            glm::vec3 tempVect;
            inFile >> tempVect.x;
            inFile >> tempVect.y;
            inFile >> tempVect.z;
            vertices.push_back(tempVect);
        }
        // Parsing uvs
        else if (token == "vt") {
            glm::vec2 tempUv;
            inFile >> tempUv.x;
            inFile >> tempUv.y;
            uvs.push_back(tempUv);
        }
        // Parsing normals
        else if (token == "vn") {
            glm::vec3 tempNormal;
            inFile >> tempNormal.x;
            inFile >> tempNormal.y;
            inFile >> tempNormal.z;
            normals.push_back(tempNormal);
        }
        // Parsing faces (Note: not robust for all .obj files)
        else if (token == "f") {
            unsigned int vertexIndex[4], uvIndex[4], normalIndex[4];
            for (unsigned int i = 0; i < 4; ++i) {
                inFile >> vertexIndex[i];
                vertexIndices.push_back(vertexIndex[i]);
                inFile.ignore(1, '/');
                inFile >> uvIndex[i];
                uvIndices.push_back(uvIndex[i]);
                inFile.ignore(1, '/');
                inFile >> normalIndex[i];
                normalIndices.push_back(normalIndex[i]);
            }
        }
    }
    inFile.close();
    for (unsigned int i = 0; i < vertexIndices.size(); ++i) {
        unsigned int vertexIndex = vertexIndices[i];
        glm::vec3 vertex = vertices[vertexIndex - 1];
        vertices_.push_back(vertex);
    }
    for (unsigned int i = 0; i < uvIndices.size(); ++i) {
        unsigned int uvIndex = uvIndices[i];
        glm::vec2 uv = uvs[uvIndex - 1];
        uvs_.push_back(uv);
    }
    for (unsigned int i = 0; i < normalIndices.size(); ++i) {
        unsigned int normalIndex = normalIndices[i];
        glm::vec3 normal = normals[normalIndex - 1];
        normals_.push_back(normal);
    }
}

实际上,在旧版本的OpenGL中,使用比现代OpenGL有更多的原语可供选择。所以我真的看不出你的问题。为什么不简单地使用简单(索引)三角形进行绘制。您不仅限于…_STRIP基元。 GL_TRIANGLES(和GL_QUADS!)实际上在OpenGL-2.1及更早版本中可用。