国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

第十三章 opengl之模型(導(dǎo)入3D模型)

這篇具有很好參考價值的文章主要介紹了第十三章 opengl之模型(導(dǎo)入3D模型)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

模型

使用Assimp并創(chuàng)建實際的加載和轉(zhuǎn)換代碼。Model類結(jié)構(gòu)如下:

class Model 
{
    public:
        /*  函數(shù)   */
        Model(char *path)
        {
            loadModel(path);
        }
        void Draw(Shader shader);   
    private:
        /*  模型數(shù)據(jù)  */
        vector<Mesh> meshes;
        string directory;
        /*  函數(shù)   */
        void loadModel(string path);
        void processNode(aiNode *node, const aiScene *scene);
        Mesh processMesh(aiMesh *mesh, const aiScene *scene);
        vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, 
                                             string typeName);
};

Model類包含一個Mesh對象的vector,構(gòu)造器參數(shù)需要一個文件路徑。
構(gòu)造器通過loadModel來加載文件。私有函數(shù)將會處理Assimp導(dǎo)入過程中的一部分,私有函數(shù)還存儲了 文件路徑的目錄,加載紋理時會用到。
Draw函數(shù)的作用:遍歷所有網(wǎng)格,調(diào)用網(wǎng)格 各自的Draw函數(shù):

void Draw(Shader shader)
{
    for(unsigned int i = 0; i < meshes.size(); i++)
        meshes[i].Draw(shader);
}

導(dǎo)入3D模型

導(dǎo)入一個模型,并將其轉(zhuǎn)換到自己的數(shù)據(jù)結(jié)構(gòu)中。則首先需要包含Assimp對應(yīng)的頭文件:

#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

首先調(diào)用函數(shù)loadModel,直接從構(gòu)造器中調(diào)用。在該函數(shù)匯總,使用Assimp加載模型到Assimp的一個叫做scene的數(shù)據(jù)結(jié)構(gòu)中。這個是場景對象,通過它可以訪問到加載后的模型中所有需要的數(shù)據(jù)。
Assimp抽象了加載不同文件格式的所有技術(shù)細節(jié),只需要一行代碼即可:

Assimp::Importer importer;
const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);

代碼解讀:聲明了Assimp命名空間內(nèi)的一個Importer,之后調(diào)用ReadFile函數(shù)。該函數(shù)需要一個文件路徑,第二個參數(shù)是后期處理的選項。除了加載文件外,Assimp允許設(shè)定一些選項來強制它對導(dǎo)入的數(shù)據(jù)做一些額外的計算
通過設(shè)定aiProcess_Triangulate ,能告訴Assimp,如果模型不是全部由三角形組成,那么需要將模型的所有圖元轉(zhuǎn)換成三角形。
aiProcess_FlipUVs,將在處理的時候翻轉(zhuǎn)y軸的紋理坐標,因為在OpenGL中大部分的圖像的y軸都是反的,所系這個后期處理選項可以修復(fù)該問題。
其他有用的選項還有:(https://assimp.sourceforge.net/lib_html/postprocess_8h.html)

  1. aiProcess_GenNormals:如果模型不包含法向量的話,就為每個頂點創(chuàng)建法線。
  2. aiProcess_SplitLargeMeshes:將比較大的網(wǎng)格分割成更小的子網(wǎng)格,如果你的渲染有最大頂點數(shù)限制,只能渲染較小的網(wǎng)格,那么它會非常有用。
  3. aiProcess_OptimizeMeshes:和上個選項相反,它會將多個小網(wǎng)格拼接為一個大的網(wǎng)格,減少繪制調(diào)用從而進行優(yōu)化。

可以看出使用Assimp加載模型是非常容易的。難的是之后使用返回的場景對象將加載的數(shù)據(jù)轉(zhuǎn)換到一個Mesh對象的數(shù)組。
完整的loadModel函數(shù)如下:

void loadModel(string path)
{
    Assimp::Importer import;
    const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);    

    if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) 
    {
        cout << "ERROR::ASSIMP::" << import.GetErrorString() << endl;
        return;
    }
    directory = path.substr(0, path.find_last_of('/'));

    processNode(scene->mRootNode, scene);
}

在我們加載了模型之后,我們會檢查場景和其根節(jié)點不為null,并且檢查了它的一個標記(Flag),來查看返回的數(shù)據(jù)是不是不完整的。如果遇到了任何錯誤,我們都會通過導(dǎo)入器的GetErrorString函數(shù)來報告錯誤并返回。我們也獲取了文件路徑的目錄路徑。
如果什么錯誤都沒有發(fā)生,我們希望處理場景中的所有節(jié)點,所以我們將第一個節(jié)點(根節(jié)點)傳入了遞歸的processNode函數(shù)。因為每個節(jié)點(可能)包含有多個子節(jié)點,我們希望首先處理參數(shù)中的節(jié)點,再繼續(xù)處理該節(jié)點所有的子節(jié)點,以此類推。這正符合一個遞歸結(jié)構(gòu),所以我們將定義一個遞歸函數(shù)。遞歸函數(shù)在做一些處理之后,使用不同的參數(shù)遞歸調(diào)用這個函數(shù)自身,直到某個條件被滿足停止遞歸。在我們的例子中退出條件(Exit Condition)是所有的節(jié)點都被處理完畢。

Assimp結(jié)構(gòu)中,每個節(jié)點包含一系列網(wǎng)格索引,每個索引指向場景對象中的那個特定網(wǎng)格。接下來需要去獲取這些網(wǎng)格索引,獲取每個網(wǎng)格,處理每個網(wǎng)格,接著對每個節(jié)點的子節(jié)點重復(fù)這個過程,則processNode函數(shù)如下:

void processNode(aiNode *node, const aiScene *scene)
{
    // 處理節(jié)點所有的網(wǎng)格(如果有的話)
    for(unsigned int i = 0; i < node->mNumMeshes; i++)
    {
        aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; 
        meshes.push_back(processMesh(mesh, scene));         
    }
    // 接下來對它的子節(jié)點重復(fù)這一過程
    for(unsigned int i = 0; i < node->mNumChildren; i++)
    {
        processNode(node->mChildren[i], scene);
    }
}

我們首先檢查每個節(jié)點的網(wǎng)格索引,并索引場景的mMeshes數(shù)組來獲取對應(yīng)的網(wǎng)格。返回的網(wǎng)格將會傳遞到processMesh函數(shù)中,它會返回一個Mesh對象,我們可以將它存儲在meshes列表/vector。

所有網(wǎng)格都被處理之后,我們會遍歷節(jié)點的所有子節(jié)點,并對它們調(diào)用相同的processMesh函數(shù)。當一個節(jié)點不再有任何子節(jié)點之后,這個函數(shù)將會停止執(zhí)行。

下一步是將Assimp的數(shù)據(jù)解析到Mesh類中。就是將一根aiMesh對象轉(zhuǎn)化為自己的網(wǎng)格對象。只需要訪問網(wǎng)格的相關(guān)屬性并將它們存儲到自己的對象中。processMesh函數(shù)如下:

Mesh processMesh(aiMesh *mesh, const aiScene *scene)
{
    vector<Vertex> vertices;
    vector<unsigned int> indices;
    vector<Texture> textures;

    for(unsigned int i = 0; i < mesh->mNumVertices; i++)
    {
        Vertex vertex;
        // 處理頂點位置、法線和紋理坐標
        ...
        vertices.push_back(vertex);
    }
    // 處理索引
    ...
    // 處理材質(zhì)
    if(mesh->mMaterialIndex >= 0)
    {
        ...
    }

    return Mesh(vertices, indices, textures);
}

處理網(wǎng)格的過程主要有三部分:獲取所有的頂點數(shù)據(jù),獲取它們的網(wǎng)格索引,并獲取相關(guān)的材質(zhì)數(shù)據(jù)。處理后的數(shù)據(jù)將會儲存在三個vector當中,我們會利用它們構(gòu)建一個Mesh對象,并返回它到函數(shù)的調(diào)用者那里。
1。獲取頂點數(shù)據(jù):定義了一個Vertex結(jié)構(gòu)體,將在每個迭代之后將它加入到vertices數(shù)組中。會遍歷網(wǎng)格中的所有頂點——使用mesh->mNumVertices來獲取。每個迭代中,使用所有的相關(guān)數(shù)據(jù)填充這個結(jié)構(gòu)體,頂點的位置如下:

glm::vec3 vector; 
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z; 
vertex.Position = vector;

使用了vec3的臨時變量,是因為Assimp對向量,矩陣,字符串等都有自己的一套數(shù)據(jù)類型,并不能完美地轉(zhuǎn)換到GLM的數(shù)據(jù)類型中。
處理法線的過程類似:

vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.Normal = vector;

紋理坐標的處理也大體相似,但Assimp允許一個模型在一個頂點上有最多8個不同的紋理坐標,我們不會用到那么多,我們只關(guān)心第一組紋理坐標。我們同樣也想檢查網(wǎng)格是否真的包含了紋理坐標:

if(mesh->mTextureCoords[0]) // 網(wǎng)格是否有紋理坐標?
{
    glm::vec2 vec;
    vec.x = mesh->mTextureCoords[0][i].x; 
    vec.y = mesh->mTextureCoords[0][i].y;
    vertex.TexCoords = vec;
}
else
    vertex.TexCoords = glm::vec2(0.0f, 0.0f);

vertex結(jié)構(gòu)體現(xiàn)在已經(jīng)填充好了需要的頂點屬性,我們會在迭代的最后將它壓入vertices這個vector的尾部。這個過程會對每個網(wǎng)格的頂點都重復(fù)一遍。

Assimp的接口定義了每個網(wǎng)格都有一個面(Face)數(shù)組,每個面代表了一個圖元,在例子中(由于使用了aiProcess_Triangulate選項)它總是三角形。一個面包含了多個索引,它們定義了在每個圖元中,我們應(yīng)該繪制哪個頂點,并以什么順序繪制,所以如果我們遍歷了所有的面,并儲存了面的索引到indices這個vector中就可以了。

for(unsigned int i = 0; i < mesh->mNumFaces; i++)
{
    aiFace face = mesh->mFaces[i];
    for(unsigned int j = 0; j < face.mNumIndices; j++)
        indices.push_back(face.mIndices[j]);
}

到目前為止,有了一系列的頂點和索引數(shù)據(jù),可以通過glDrawElements函數(shù)來繪制網(wǎng)格。為了提供一些細節(jié),還需要處理網(wǎng)格的材質(zhì)。
一個網(wǎng)格只包含了一個指向材質(zhì)對象的索引。如果要獲取網(wǎng)格真正的材質(zhì),還需要索引場景的mMaterials數(shù)組。網(wǎng)格材質(zhì)索引位于其mMaterialIndex屬性,同樣可以用它來檢測一個網(wǎng)格是否包含有材質(zhì):

if(mesh->mMaterialIndex >= 0)
{
    aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
    vector<Texture> diffuseMaps = loadMaterialTextures(material, 
                                        aiTextureType_DIFFUSE, "texture_diffuse");
    textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
    vector<Texture> specularMaps = loadMaterialTextures(material, 
                                        aiTextureType_SPECULAR, "texture_specular");
    textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
}

我們首先從場景的mMaterials數(shù)組中獲取aiMaterial對象。接下來我們希望加載網(wǎng)格的漫反射和/或鏡面光貼圖。一個材質(zhì)對象的內(nèi)部對每種紋理類型都存儲了一個紋理位置數(shù)組。不同的紋理類型都以aiTextureType_為前綴。我們使用一個叫做loadMaterialTextures的工具函數(shù)來從材質(zhì)中獲取紋理。這個函數(shù)將會返回一個Texture結(jié)構(gòu)體的vector,我們將在模型的textures的尾部之后存儲它。

loadMaterialTextures函數(shù)遍歷了給定紋理類型的所有紋理位置,獲取了紋理的文件位置,并加載并和生成了紋理,將信息儲存在了一個Vertex結(jié)構(gòu)體中。loadMaterialTextures函數(shù)它看起來會像這樣:

vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
{
    vector<Texture> textures;
    for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
    {
        aiString str;
        mat->GetTexture(type, i, &str);
        Texture texture;
        texture.id = TextureFromFile(str.C_Str(), directory);
        texture.type = typeName;
        texture.path = str;
        textures.push_back(texture);
    }
    return textures;
}

我們首先通過GetTextureCount函數(shù)檢查儲存在材質(zhì)中紋理的數(shù)量,這個函數(shù)需要一個紋理類型。我們會使用GetTexture獲取每個紋理的文件位置,它會將結(jié)果儲存在一個aiString中。我們接下來使用另外一個叫做TextureFromFile的工具函數(shù),它將會(用stb_image.h)加載一個紋理并返回該紋理的ID。第二個參數(shù)是模型的文件路徑。

注意:我們假設(shè)了模型文件中紋理文件的路徑是相對于模型文件的本地(Local)路徑,比如說與模型文件處于同一目錄下。我們可以將紋理位置字符串拼接到之前獲取的目錄字符串上(TextureFromFile),來獲取完整的紋理路徑(這也是為什么GetTexture函數(shù)也需要一個目錄字符串)。

在網(wǎng)絡(luò)上找到的某些模型會對紋理位置使用絕對(Absolute)路徑,這就不能在每臺機器上都工作了。在這種情況下,你可能會需要手動修改這個文件,來讓它對紋理使用本地路徑(如果可能的話)。

綜上,是使用Assimp導(dǎo)入模型的全部。

優(yōu)化

優(yōu)化不是必須的,但是可以提高加載過程。
大多數(shù)場景都會在多個網(wǎng)絡(luò)中 重用部分紋理。比如:一個紋理不僅可以用到人身上,也能用到物體身上。當然就是用同一個紋理進行加載。但是同樣的紋理已經(jīng)被加載過了很多遍,對每個網(wǎng)格仍會加載并生成一個新的紋理。很快就會變成模型加載實現(xiàn)的性能瓶頸。
可以被模型的代碼進行調(diào)整,將所有加載過的紋理全局存儲。每當要加載一個紋理的時候,首先去檢查是否被加載過,如果有的話,直接使用那個紋理,并跳過整個加載流程。為了能夠比較紋理,還需要存儲它們的路徑:

struct Texture {
    unsigned int id;
    string type;
    aiString path;  // 我們儲存紋理的路徑用于與其它紋理進行比較
};

接下來我們將所有加載過的紋理儲存在另一個vector中,在模型類的頂部聲明為一個私有變量:

vector<Texture> textures_loaded;

在loadMaterialTextures函數(shù)中,我們希望將紋理的路徑與儲存在textures_loaded這個vector中的所有紋理進行比較,看看當前紋理的路徑是否與其中的一個相同。如果是的話,則跳過紋理加載/生成的部分,直接使用定位到的紋理結(jié)構(gòu)體為網(wǎng)格的紋理。更新后的函數(shù)如下:

vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
{
    vector<Texture> textures;
    for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
    {
        aiString str;
        mat->GetTexture(type, i, &str);
        bool skip = false;
        for(unsigned int j = 0; j < textures_loaded.size(); j++)
        {
            if(std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0)
            {
                textures.push_back(textures_loaded[j]);
                skip = true; 
                break;
            }
        }
        if(!skip)
        {   // 如果紋理還沒有被加載,則加載它
            Texture texture;
            texture.id = TextureFromFile(str.C_Str(), directory);
            texture.type = typeName;
            texture.path = str.C_Str();
            textures.push_back(texture);
            textures_loaded.push_back(texture); // 添加到已加載的紋理中
        }
    }
    return textures;
}

所以現(xiàn)在我們不僅有了個靈活的模型加載系統(tǒng),我們也獲得了一個加載對象很快的優(yōu)化版本。

綜上,完整代碼如下:

#ifndef MODEL_H
#define MODEL_H

#include <glad/glad.h> 

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <stb_image.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>

#include <learnopengl/mesh.h>
#include <learnopengl/shader.h>

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
using namespace std;

unsigned int TextureFromFile(const char *path, const string &directory, bool gamma = false);

class Model 
{
public:
    // model data 
    vector<Texture> textures_loaded;	// stores all the textures loaded so far, optimization to make sure textures aren't loaded more than once.
    vector<Mesh>    meshes;
    string directory;
    bool gammaCorrection;

    // constructor, expects a filepath to a 3D model.
    Model(string const &path, bool gamma = false) : gammaCorrection(gamma)
    {
        loadModel(path);
    }

    // draws the model, and thus all its meshes
    void Draw(Shader &shader)
    {
        for(unsigned int i = 0; i < meshes.size(); i++)
            meshes[i].Draw(shader);
    }
    
private:
    // loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector.
    void loadModel(string const &path)
    {
        // read file via ASSIMP
        Assimp::Importer importer;
        const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
        // check for errors
        if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
        {
            cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;
            return;
        }
        // retrieve the directory path of the filepath
        directory = path.substr(0, path.find_last_of('/'));

        // process ASSIMP's root node recursively
        processNode(scene->mRootNode, scene);
    }

    // processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any).
    void processNode(aiNode *node, const aiScene *scene)
    {
        // process each mesh located at the current node
        for(unsigned int i = 0; i < node->mNumMeshes; i++)
        {
            // the node object only contains indices to index the actual objects in the scene. 
            // the scene contains all the data, node is just to keep stuff organized (like relations between nodes).
            aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
            meshes.push_back(processMesh(mesh, scene));
        }
        // after we've processed all of the meshes (if any) we then recursively process each of the children nodes
        for(unsigned int i = 0; i < node->mNumChildren; i++)
        {
            processNode(node->mChildren[i], scene);
        }

    }

    Mesh processMesh(aiMesh *mesh, const aiScene *scene)
    {
        // data to fill
        vector<Vertex> vertices;
        vector<unsigned int> indices;
        vector<Texture> textures;

        // walk through each of the mesh's vertices
        for(unsigned int i = 0; i < mesh->mNumVertices; i++)
        {
            Vertex vertex;
            glm::vec3 vector; // we declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first.
            // positions
            vector.x = mesh->mVertices[i].x;
            vector.y = mesh->mVertices[i].y;
            vector.z = mesh->mVertices[i].z;
            vertex.Position = vector;
            // normals
            if (mesh->HasNormals())
            {
                vector.x = mesh->mNormals[i].x;
                vector.y = mesh->mNormals[i].y;
                vector.z = mesh->mNormals[i].z;
                vertex.Normal = vector;
            }
            // texture coordinates
            if(mesh->mTextureCoords[0]) // does the mesh contain texture coordinates?
            {
                glm::vec2 vec;
                // a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't 
                // use models where a vertex can have multiple texture coordinates so we always take the first set (0).
                vec.x = mesh->mTextureCoords[0][i].x; 
                vec.y = mesh->mTextureCoords[0][i].y;
                vertex.TexCoords = vec;
                // tangent
                vector.x = mesh->mTangents[i].x;
                vector.y = mesh->mTangents[i].y;
                vector.z = mesh->mTangents[i].z;
                vertex.Tangent = vector;
                // bitangent
                vector.x = mesh->mBitangents[i].x;
                vector.y = mesh->mBitangents[i].y;
                vector.z = mesh->mBitangents[i].z;
                vertex.Bitangent = vector;
            }
            else
                vertex.TexCoords = glm::vec2(0.0f, 0.0f);

            vertices.push_back(vertex);
        }
        // now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices.
        for(unsigned int i = 0; i < mesh->mNumFaces; i++)
        {
            aiFace face = mesh->mFaces[i];
            // retrieve all indices of the face and store them in the indices vector
            for(unsigned int j = 0; j < face.mNumIndices; j++)
                indices.push_back(face.mIndices[j]);        
        }
        // process materials
        aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];    
        // we assume a convention for sampler names in the shaders. Each diffuse texture should be named
        // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER. 
        // Same applies to other texture as the following list summarizes:
        // diffuse: texture_diffuseN
        // specular: texture_specularN
        // normal: texture_normalN

        // 1. diffuse maps
        vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
        textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
        // 2. specular maps
        vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
        textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
        // 3. normal maps
        std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
        textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
        // 4. height maps
        std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
        textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
        
        // return a mesh object created from the extracted mesh data
        return Mesh(vertices, indices, textures);
    }

    // checks all material textures of a given type and loads the textures if they're not loaded yet.
    // the required info is returned as a Texture struct.
    vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
    {
        vector<Texture> textures;
        for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
        {
            aiString str;
            mat->GetTexture(type, i, &str);
            // check if texture was loaded before and if so, continue to next iteration: skip loading a new texture
            bool skip = false;
            for(unsigned int j = 0; j < textures_loaded.size(); j++)
            {
                if(std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0)
                {
                    textures.push_back(textures_loaded[j]);
                    skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization)
                    break;
                }
            }
            if(!skip)
            {   // if texture hasn't been loaded already, load it
                Texture texture;
                texture.id = TextureFromFile(str.C_Str(), this->directory);
                texture.type = typeName;
                texture.path = str.C_Str();
                textures.push_back(texture);
                textures_loaded.push_back(texture);  // store it as texture loaded for entire model, to ensure we won't unnecessary load duplicate textures.
            }
        }
        return textures;
    }
};


unsigned int TextureFromFile(const char *path, const string &directory, bool gamma)
{
    string filename = string(path);
    filename = directory + '/' + filename;

    unsigned int textureID;
    glGenTextures(1, &textureID);

    int width, height, nrComponents;
    unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
    if (data)
    {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << path << std::endl;
        stbi_image_free(data);
    }

    return textureID;
}
#endif

使用3D模型

加載一個3D模型,這個模型被輸出為一個.obj文件和一個.mtl文件,.mtl文件包含了模型的漫反射,鏡面光,法線貼圖。
注意:所有的紋理和模型文件應(yīng)該位于同一個目錄下,以供加載紋理。
在代碼中,聲明一個Model對象,將模型的文件位置傳入。接下來模型會自動加載并在渲染循環(huán)中使用它的Draw函數(shù)來繪制物體。不再需要緩沖分配、屬性指針和渲染指令,只需要一行代碼就可以了。文章來源地址http://www.zghlxwxcb.cn/news/detail-451316.html

到了這里,關(guān)于第十三章 opengl之模型(導(dǎo)入3D模型)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 第十三章 接口測試(筆記)

    一、接口測試分類 ? ? 內(nèi)部接口:測試被測系統(tǒng)各個子模塊之間的接口,或者被測系統(tǒng)提供給內(nèi)部系統(tǒng)使用的接口 ? ? 外部接口: ? ? ? ? 1.被測系統(tǒng)調(diào)用外部的接口 ? ? ? ? ?2.系統(tǒng)對外提供的接口 接口測試重點:檢查接口參數(shù)傳遞的正確性,接口功能的正確性,輸出結(jié)

    2024年02月02日
    瀏覽(29)
  • NodeJs第十三章 cookie

    NodeJs第十三章 cookie

    假設(shè)服務(wù)器有一個接口,通過請求這個接口,可以添加一個管理員 但是,不是任何人都有權(quán)力做這種操作的 那么服務(wù)器如何知道請求接口的人是有權(quán)力的呢? 答案是:只有登錄過的管理員才能做這種操作 可問題是,客戶端和服務(wù)器的傳輸使用的是http協(xié)議,http協(xié)議是無狀態(tài)

    2024年01月19日
    瀏覽(25)
  • [C國演義] 第十三章

    [C國演義] 第十三章

    力扣鏈接 根據(jù)題目要求: 返回的數(shù)對應(yīng)的下標各不相同 三個數(shù)之和等于0 不可包含重復(fù)的三元組 – – 即 順序是不做要求的 如: [-1 0 1] 和 [0, 1, -1] 是同一個三元組 輸出答案順序不做要求 暴力解法: 排序 + 3個for循環(huán) + 去重 — — N^3, 肯定超時 優(yōu)化: 排序 + 雙指針 + 去重 — —

    2024年02月08日
    瀏覽(29)
  • 第十三章 python之爬蟲

    Python基礎(chǔ)、函數(shù)、模塊、面向?qū)ο蟆⒕W(wǎng)絡(luò)和并發(fā)編程、數(shù)據(jù)庫和緩存、 前端、django、Flask、tornado、api、git、爬蟲、算法和數(shù)據(jù)結(jié)構(gòu)、Linux、設(shè)計題、客觀題、其他

    2024年02月04日
    瀏覽(37)
  • 《微服務(wù)實戰(zhàn)》 第十三章 JWT

    《微服務(wù)實戰(zhàn)》 第十三章 JWT

    【項目實戰(zhàn)】Spring boot整合JWT、Vue案例展示用戶鑒權(quán) 【微服務(wù)實戰(zhàn)】JWT JSON Web Token(JWT)是目前最流行的跨域身份驗證解決方案。 基于JSON的開發(fā)標準 用戶信息加密到token里,服務(wù)器不保存任何用戶信息 在傳統(tǒng)的用戶登錄認證中,因為http是無狀態(tài)的,所以都是采用session方式

    2024年02月06日
    瀏覽(53)
  • 第十三章,枚舉與泛型例題

    第十三章,枚舉與泛型例題

    例題1 結(jié)果 ? 例題2 結(jié)果 ? 例題3 結(jié)果? ? ?例題4 結(jié)果 例題5 ?結(jié)果 例題6 ?結(jié)果 例題7 ?結(jié)果 例題8 ?結(jié)果

    2024年02月06日
    瀏覽(31)
  • 第十三章 Unity 移動和旋轉(zhuǎn)(上)

    第十三章 Unity 移動和旋轉(zhuǎn)(上)

    移動和旋轉(zhuǎn)是游戲?qū)ο笞铑l繁地操作。我們上個章節(jié)簡單介紹了Cube的移動和旋轉(zhuǎn)。移動是修改transform的position屬性,旋轉(zhuǎn)是修改transform的eulerAngles(歐拉角)屬性,兩者屬性值均可以使用Vector3向量來實現(xiàn)。需要大家注意的是,transform.forward和Vector3.forward的區(qū)別(參考坐標系是

    2024年02月05日
    瀏覽(38)
  • 精讀《圖解密碼技術(shù)》——第十三章 PGP

    精讀《圖解密碼技術(shù)》——第十三章 PGP

    ??PGP是一款由個人編寫的密碼軟件,PGP是為了保護處于極端狀況下的人們的隱私而開發(fā)的,如果這些人的信息被竊聽,那么可能是性命攸關(guān)的大事件。 ??OpenPGP是對密文和數(shù)字簽名格式進行定義的標準規(guī)格。 ??GNU Privacy Guard ( GnuPG、GPG)是一款基于OpenPGP標準開發(fā)的密碼學(xué)

    2024年02月05日
    瀏覽(34)
  • 第十三章_Redis中的BigKey

    第十三章_Redis中的BigKey

    MoreKey案例 大批量往redis里面插入2000W測試數(shù)據(jù)key? Linux?Bash下面執(zhí)行,插入100W # 生成100W條redis批量設(shè)置kv的語句(key=kn,value=vn)寫入到/tmp目錄下的redisTest.txt文件中 for((i=1;i=100*10000;i++)); do echo \\\"set k$i v$i\\\" /tmp/redisTest.txt ;done; 通過redis提供的管道--pipe命令插入100W大批量數(shù)據(jù) 結(jié)合自己

    2024年02月03日
    瀏覽(30)
  • 【正點原子STM32連載】第十三章 串口通信實驗 摘自【正點原子】APM32E103最小系統(tǒng)板使用指南

    【正點原子STM32連載】第十三章 串口通信實驗 摘自【正點原子】APM32E103最小系統(tǒng)板使用指南

    1)實驗平臺:正點原子APM32E103最小系統(tǒng)板 2)平臺購買地址:https://detail.tmall.com/item.htm?id=609294757420 3)全套實驗源碼+手冊+視頻下載地址: http://www.openedv.com/docs/boards/xiaoxitongban 本章將介紹使用串口進行數(shù)據(jù)的收發(fā)操作,具體實現(xiàn)APM32E103與上位機軟件的數(shù)據(jù)通信,APM32E103將接受

    2024年02月21日
    瀏覽(16)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包