QT+OpenGL模型加载 - Assimp

QT+OpenGL模型加载 - Assimp

本篇完整工程见gitee:OpenGL 对应点的tag,由turbolove提供技术支持,您可以关注博主或者私信博主

模型加载

先来张图:

在这里插入图片描述

我们不大可能手工定义房子、汽车或者人形角色这种复杂形状所有的顶点、法线和纹理坐标。我们想要的是将这些模型导入到程序当中。

但是不同种类的文件格式中,它们之间通常没有一个通用的结构,因此我们将使用到模型加载库Assimp

Assimp

  • 一个非常流行的模型导入库
  • 将所有的模型数据加载到Assimp的通用数据结构中

这里不介绍对应的编译,如果你熟悉CMake的话编译起来是非常简单的,项目中提供的是使用vs2019编译的64位的动态库和lib。如果您不好运行,可以将对应的开发环境更换成跟我一致的环境。或者您自己编译对应的库文件。

介绍:

  • 场景(Scene): 所有场景/模型数据(材质和网格)都包含在场景对象中。场景对象也包含了场景根节点的引用。

  • 根节点(Root Node): 场景根节点可能包含子节点(和其他节点一样),他会有一系列指向场景对象中的mMeshes数组中存储的网格数据索引。

    ​ Scene下 的mMeshes数组存储了真正的Mesh对象,节点中的mMeshes数组保存的知识场景中网格数组的索引

  • Mesh对象: 一个Mesh对象本身包含了渲染所需要的所有相关数据,像是顶点位置,法向向量、纹理坐标、面和物体的材质。

  • 面(Face): 一个网格包含了多个面。面代表的是物体的渲染图元(三角形、方形、点)。一个面包含了组成图元的顶点的索引

  • 材料(Material):一个网格也包含了一个Material对象,他包含了一些函数能让我们获取物体的材质属性,比如颜色和纹理贴图(比如漫反射和镜面光贴图)。

封装Mesh:

一个网格至少需要:

  • 顶点数据:至少包含一个位置向量、一个法向量和一个纹理坐标向量
  • 材质数据:漫反射/镜面反射
  • 索引数据:

mesh.h

#ifndef QTOPENGL_MESH_H
#define QTOPENGL_MESH_H

#include <QOpenGLFunctions_4_5_Core>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>

struct Vertex
{
    QVector3D position;
    QVector3D normal;
    QVector2D tex_coords;
};

struct Texture
{
    QOpenGLTexture *texture;
    std::string path;
    std::string type;
};

class Mesh
{
public:
    Mesh(QOpenGLFunctions_4_5_Core *glFn, const QVector<Vertex> &vertices,
         const QVector<unsigned int> &indices, const QVector<Texture> &textures);
    ~Mesh();
    void draw(QOpenGLShaderProgram &shader);

protected:
    void setupMesh();

private:
    unsigned int VAO,VBO,EBO;
    QOpenGLFunctions_4_5_Core *gl_fn_;
    QVector<Vertex> vertices_;
    QVector<unsigned int> indices_;
    QVector<Texture> textures_;
};

#endif //QTOPENGL_MESH_H

mesh.cpp

#include "mesh.h"
Mesh::Mesh(QOpenGLFunctions_4_5_Core *glFn, const QVector<Vertex> &vertices, const QVector<unsigned int> &indices,
           const QVector<Texture> &textures)
{
    gl_fn_ = glFn;
    vertices_ = vertices;
    indices_ = indices;
    textures_ = textures;
    setupMesh();
}

Mesh::~Mesh()
{

}

void Mesh::setupMesh()
{
    //创建VBO和VAO对象,并赋予ID
    gl_fn_->glGenVertexArrays(1, &VAO);
    gl_fn_->glGenBuffers(1, &VBO);
    gl_fn_->glGenBuffers(1,&EBO);
    //绑定VBO和VAO对象
    gl_fn_->glBindVertexArray(VAO);
    gl_fn_->glBindBuffer(GL_ARRAY_BUFFER, VBO);
    //为当前绑定到target的缓冲区对象创建一个新的数据存储。
    //如果data不是NULL,则使用来自此指针的数据初始化数据存储
    gl_fn_->glBufferData(GL_ARRAY_BUFFER, vertices_.size()*sizeof(Vertex),
                           &vertices_[0], GL_STATIC_DRAW);
    gl_fn_->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    gl_fn_->glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                           indices_.size() * sizeof(unsigned int),&indices_[0], GL_STATIC_DRAW);
    //告知显卡如何解析缓冲里的属性值
    gl_fn_->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    gl_fn_->glEnableVertexAttribArray(0);
    gl_fn_->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
                                    (void*)offsetof(Vertex, normal));

    gl_fn_->glEnableVertexAttribArray(1);
    gl_fn_->glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
                                    (void*)offsetof(Vertex, tex_coords));
    gl_fn_->glEnableVertexAttribArray(2);
}

void Mesh::draw(QOpenGLShaderProgram &shader)
{
    unsigned int diffuseNum = 1;
    unsigned int specularNum = 1;
    for(int i = 0; i < textures_.size(); i++)
    {
        std::string name = textures_[i].type;
        shader.setUniformValue(("material." + name).c_str(), i);
        textures_[i].texture->bind(i);
    }

    gl_fn_->glBindVertexArray(VAO);
    gl_fn_->glDrawArrays(GL_TRIANGLES,0,36);
}

封装Model:

我们需要通过Assimp加载模型,并且将其转换成多个网格数据

Assimp里的结构: 每个节点包含一组网格索引,每个索引指向场景对象中的特定网络。

model.h

#ifndef QTOPENGL_MODEL_H
#define QTOPENGL_MODEL_H

#include "assimp/scene.h"
#include "assimp/postprocess.h"
#include "mesh.h"

class Model
{
public:
    Model(QOpenGLFunctions_4_5_Core *glFn, const std::string &path);
    ~Model();

    void draw(QOpenGLShaderProgram &shader)
    {
        for(unsigned int i = 0; i < meshes_.size(); i++)
        {
            meshes_[i].draw(shader);
        }
    }

protected:
    void loadModel(const std::string &path);
    void processNode(aiNode *node, const aiScene *scene);
    Mesh processMesh(aiMesh *mesh, const aiScene *scene);
    QVector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, std::string typeName);
    QOpenGLTexture *textureFromFile(const std::string &file);

private:
    QOpenGLFunctions_4_5_Core *gl_fn_;
    QVector<Texture> texture_loaded_;
    QVector<Mesh>    meshes_;
    std::string      directory_;
};


#endif //QTOPENGL_MODEL_H

model.cpp

#include "model.h"
#include "assimp/Importer.hpp"
#include <iostream>
using namespace std;
Model::Model(QOpenGLFunctions_4_5_Core *glFn, const std::string &path)
{
    gl_fn_ = glFn;
    loadModel(path);
}

Model::~Model()
{

}

void Model::loadModel(const std::string &path)
{
    Assimp::Importer importer;
    const aiScene *scene = importer.ReadFile(path.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs);
    if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
    {
        cout << "ERROR::ASSIMP::" << importer.GetErrorString() <<endl;
        return;
    }
    directory_ = path.substr(0, path.find_last_of('/'));
    processNode(scene->mRootNode, scene);
}

void Model::processNode(aiNode *node, const aiScene *scene)
{
    for(unsigned int i = 0; i < node->mNumMeshes; i++)
    {
        aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
        meshes_.push_back(processMesh(mesh, scene));
    }
    for(unsigned int i = 0; i < node->mNumChildren; i++)
    {
        processNode(node->mChildren[i], scene);
    }
}

Mesh Model::processMesh(aiMesh *mesh, const aiScene *scene)
{
    QVector<Vertex> vertices;
    QVector<unsigned int> indices;
    QVector<Texture> textures;
    // 顶点数据
    for(unsigned int i = 0; i < mesh->mNumVertices; i++)
    {
        Vertex vertex;
        QVector3D vector;
        vector.setX(mesh->mVertices[i].x);
        vector.setY(mesh->mVertices[i].y);
        vector.setZ(mesh->mVertices[i].z);
        vertex.position = vector;

        vector.setX(mesh->mNormals[i].x);
        vector.setY(mesh->mNormals[i].y);
        vector.setZ(mesh->mNormals[i].z);
        vertex.normal = vector;

        if(mesh->mTextureCoords[0])
        {
            QVector2D tex;
            tex.setX(mesh->mTextureCoords[0][i].x);
            tex.setY(mesh->mTextureCoords[0][i].y);
            vertex.tex_coords = tex;
        }
        else
        {
            vertex.tex_coords = QVector2D(0.0, 0.0);
        }
        vertices.push_back(vertex);
    }
    // 索引数据
    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]);
        }
    }
    // 纹理数据
    if(mesh->mMaterialIndex >= 0)
    {
        aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
        QVector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "diffuse");
        textures.append(diffuseMaps);
        QVector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "specular");
        textures.append(specularMaps);
    }
    return Mesh(gl_fn_, vertices, indices, textures);
}

QVector<Texture> Model::loadMaterialTextures(aiMaterial *mat, aiTextureType type, std::string typeName)
{
    QVector<Texture> textures;
    for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
    {
        aiString str;
        mat->GetTexture(type, i, &str);
        bool skip = false;
        for(int j = 0; j < texture_loaded_.size(); j++)
        {
            if(std::strcmp(texture_loaded_[j].path.data(), str.C_Str()) == 0)
            {
                textures.push_back(texture_loaded_[j]);
                skip = true;
                break;
            }
        }
        if(!skip)
        {
            Texture texture;
            texture.texture = textureFromFile(directory_ + "/" + str.C_Str());
            texture.type = typeName;
            texture.path = str.C_Str();
            textures.push_back(texture);
            texture_loaded_.push_back(texture);
        }
    }
    return textures;
}

QOpenGLTexture *Model::textureFromFile(const std::string &file)
{
    QOpenGLTexture *texture = new QOpenGLTexture(QImage(file.c_str()).mirrored());
    if(!texture->isCreated())
    {
        cout << "texture load failed!" << endl;
    }
    return texture;
}

之后我们可以使用QT加载模型,该部分代码已经上传到gitee,请在gitee中使用。

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论
要在Qt中使用OpenGL和Assimp加载骨骼动画,需要进行以下步骤: 1. 在Qt中使用OpenGL:首先,需要使用QtOpenGL模块来创建OpenGL窗口和上下文。可以使用Qt自带的QGLWidget类或者QOpenGLWidget类来创建OpenGL窗口。然后,需要在OpenGL上下文中加载Assimp导入的模型和动画数据。 2. 加载Assimp导入的模型:使用Assimp库导入模型文件,并将所有顶点数据存储在内存中。Assimp库还提供了一些函数来访问模型的骨骼和动画数据。 3. 加载骨骼动画:使用Assimp库提供的函数来加载骨骼动画数据。这些数据通常包括关键帧和骨骼层次结构。可以使用这些数据来计算每个骨骼在每个时间步长中的变换矩阵。 4. 动画播放:将每个骨骼的变换矩阵应用于每个顶点,以在每个时间步长中更新动画。可以使用OpenGL的顶点着色器来执行此操作。 以下是一些代码示例,演示如何在Qt加载Assimp导入的模型和动画数据,并将其渲染到OpenGL窗口中: ```cpp #include <QOpenGLWidget> #include <QOpenGLFunctions> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> class MyOpenGLWidget : public QOpenGLWidget, protected QOpenGLFunctions { public: MyOpenGLWidget(QWidget *parent = nullptr) : QOpenGLWidget(parent) { } void initializeGL() override { initializeOpenGLFunctions(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); Assimp::Importer importer; const aiScene* scene = importer.ReadFile("model.dae", aiProcess_Triangulate | aiProcess_FlipUVs); // Load mesh data into VBOs ... // Load bone data into VBOs ... // Load animation data into VBOs ... } void paintGL() override { glClear(GL_COLOR_BUFFER_BIT); // Update animation ... // Render mesh ... } }; ``` 在上面的示例中,`initializeGL()`函数将加载模型和动画数据,并将它们存储在OpenGL缓冲区中。`paintGL()`函数将更新动画并呈现模型。这些步骤的具体实现将取决于您的应用程序需求和Assimp库的版本。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

turbolove

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值