Как я могу пофиксить загрузку моделей через Assimp в моём движке на OpenGL?
Это мой код:
int init() {
GLFWwindow* window = Window::createWindow(800, 600, "OpenGL");
if (!window) return -1;
if (!Window::initGLAD()) {
Window::terminate();
return -1;
}
Window::setFramebufferSizeCallback(window, framebuffer_size_callback);
Window::setScrollCallback(window, scroll_callback);
Window::setInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
Input input(window);
glfwSetWindowUserPointer(window, &input);
#ifdef __APPLE__
Shader modelShader("resources/shaders/shader.vert", "resources/shaders/shader.frag");
#else
Shader modelShader("resources/shaders/shader.vert", "resources/shaders/shader.frag");
#endif
// Загружаем 3D модель
#ifdef __APPLE__
Model ourModel("resources/models/backpack/backpack.obj");
#else
Model ourModel("resources/models/backpack/backpack.obj");
#endif
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window)) {
float currentFrame = static_cast<float>(glfwGetTime());
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
input.update();
if (input.isKeyHeld(GLFW_KEY_W)) camera.ProcessKeyboard(FORWARD, deltaTime);
if (input.isKeyHeld(GLFW_KEY_S)) camera.ProcessKeyboard(BACKWARD, deltaTime);
if (input.isKeyHeld(GLFW_KEY_A)) camera.ProcessKeyboard(LEFT, deltaTime);
if (input.isKeyHeld(GLFW_KEY_D)) camera.ProcessKeyboard(RIGHT, deltaTime);
double dx, dy;
input.getMouseDelta(dx, dy);
camera.ProcessMouseMovement(dx, dy);
if (input.getScrollOffset() != 0.0) {
camera.ProcessMouseScroll(input.getScrollOffset());
}
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Преобразования для модели
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), 800.0f / 600.0f, 0.1f, 100.0f);
glm::mat4 view = camera.GetViewMatrix();
modelShader.use();
modelShader.setMat4("projection", projection);
modelShader.setMat4("view", view);
// Рендерим модель
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.0f)); // Позиция модели
model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f)); // Масштаб модели
model = glm::rotate(model, (float)glfwGetTime(), glm::vec3(0.0f, 1.0f, 0.0f)); // Вращение модели
modelShader.setMat4("model", model);
ourModel.Draw(modelShader);
glfwSwapBuffers(window);
glfwPollEvents();
}
Window::terminate();
return 0;
}
-init.cpp
#ifndef MESH_H
#define MESH_H
#include <glad/glad.h> // holds all OpenGL type declarations
#include "libs/glm/glm.hpp"
#include "libs/glm/gtc/matrix_transform.hpp"
#include "scr/Visual/shader.h"
#include <string>
#include <vector>
using namespace std;
#define MAX_BONE_INFLUENCE 4
struct Vertex {
// position
glm::vec3 Position;
// normal
glm::vec3 Normal;
// texCoords
glm::vec2 TexCoords;
// tangent
glm::vec3 Tangent;
// bitangent
glm::vec3 Bitangent;
//bone indexes which will influence this vertex
int m_BoneIDs[MAX_BONE_INFLUENCE];
//weights from each bone
float m_Weights[MAX_BONE_INFLUENCE];
};
struct MeshTexture {
unsigned int id;
string type;
string path;
};
class Mesh {
public:
// mesh Data
vector<Vertex> vertices;
vector<unsigned int> indices;
vector<MeshTexture> textures;
unsigned int VAO;
// constructor
Mesh(vector<Vertex> vertices, vector<unsigned int> indices, vector<MeshTexture> textures)
{
this->vertices = vertices;
this->indices = indices;
this->textures = textures;
// now that we have all the required data, set the vertex buffers and its attribute pointers.
setupMesh();
}
// render the mesh
void Draw(Shader &shader)
{
// bind appropriate textures
unsigned int diffuseNr = 1;
unsigned int specularNr = 1;
unsigned int normalNr = 1;
unsigned int heightNr = 1;
for (unsigned int i = 0; i < textures.size(); i++) {
glActiveTexture(GL_TEXTURE0 + i);
std::string number;
std::string name = textures[i].type;
if (name == "texture_diffuse")
number = std::to_string(diffuseNr++);
else if (name == "texture_specular")
number = std::to_string(specularNr++);
else if (name == "texture_normal")
number = std::to_string(normalNr++);
else if (name == "texture_height")
number = std::to_string(heightNr++);
glUniform1i(glGetUniformLocation(shader.ID, (name + number).c_str()), i);
glBindTexture(GL_TEXTURE_2D, textures[i].id);
}
// draw mesh
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, static_cast<unsigned int>(indices.size()), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// always good practice to set everything back to defaults once configured.
glActiveTexture(GL_TEXTURE0);
}
private:
// render data
unsigned int VBO, EBO;
// initializes all the buffer objects/arrays
void setupMesh()
{
// create buffers/arrays
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
// load data into vertex buffers
glBindBuffer(GL_ARRAY_BUFFER, VBO);
// A great thing about structs is that their memory layout is sequential for all its items.
// The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which
// again translates to 3/2 floats which translates to a byte array.
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);
// set the vertex attribute pointers
// vertex Positions
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
// vertex normals
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
// vertex texture coords
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
// vertex tangent
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
// vertex bitangent
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent));
// ids
glEnableVertexAttribArray(5);
glVertexAttribIPointer(5, 4, GL_INT, sizeof(Vertex), (void*)offsetof(Vertex, m_BoneIDs));
// weights
glEnableVertexAttribArray(6);
glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_Weights));
glBindVertexArray(0);
}
};
#endif
-mesh.h
#ifndef MODEL_H
#define MODEL_H
#include <glad/glad.h>
#include "libs/glm/glm.hpp"
#include "libs/glm/gtc/matrix_transform.hpp"
#include "libs/stb_image/stb_image.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "mesh.h"
#include <scr/Visual/shader.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#ifndef RESOURCE_DIR
#error "RESOURCE_DIR is not defined! Set it in CMakeLists.txt"
#endif
using namespace std;
unsigned int TextureFromFile(const char *path, const string &directory, bool gamma = false);
static std::string normalizePath(std::string path) {
std::replace(path.begin(), path.end(), '\\', '/');
return path;
}
class Model {
public:
vector<MeshTexture> textures_loaded;
vector<Mesh> meshes;
string directory;
bool gammaCorrection;
Model(string const &path, bool gamma = false) : gammaCorrection(gamma) {
loadModel(path);
}
void Draw(Shader &shader) {
for (unsigned int i = 0; i < meshes.size(); i++)
meshes[i].Draw(shader);
}
private:
void loadModel(string const &path) {
std::string fullPath = getFullPath(path);
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(fullPath, aiProcess_Triangulate | aiProcess_GenSmoothNormals |
aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;
cout << "Tried path: " << fullPath << endl;
return;
}
directory = getDirectory(fullPath);
processNode(scene->mRootNode, scene);
}
std::string getFullPath(const std::string& path) {
std::string fullPath = std::string(RESOURCE_DIR) + "/" + path;
if (std::ifstream(fullPath).good()) {
return fullPath;
}
return path;
}
std::string getDirectory(const std::string& path) {
size_t lastSlash = path.find_last_of("/\\");
if (lastSlash != std::string::npos) {
return path.substr(0, lastSlash);
}
return ".";
}
void 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 processMesh(aiMesh *mesh, const aiScene *scene) {
vector<Vertex> vertices;
vector<unsigned int> indices;
vector<MeshTexture> textures;
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
Vertex vertex{};
glm::vec3 vector;
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;
vertex.Position = vector;
if (mesh->HasNormals()) {
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.Normal = vector;
}
if (mesh->mTextureCoords[0]) {
glm::vec2 vec;
vec.x = mesh->mTextureCoords[0][i].x;
vec.y = mesh->mTextureCoords[0][i].y;
vertex.TexCoords = vec;
vector.x = mesh->mTangents[i].x;
vector.y = mesh->mTangents[i].y;
vector.z = mesh->mTangents[i].z;
vertex.Tangent = vector;
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);
}
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]);
}
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
vector<MeshTexture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
vector<MeshTexture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
vector<MeshTexture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
vector<MeshTexture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
return Mesh(vertices, indices, textures);
}
vector<MeshTexture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName) {
vector<MeshTexture> textures;
for (unsigned int i = 0; i < mat->GetTextureCount(type); i++) {
aiString str;
mat->GetTexture(type, i, &str);
std::string texturePath = normalizePath(std::string(str.C_Str()));
bool skip = false;
for (const auto &loadedTex : textures_loaded) {
if (loadedTex.path == texturePath) {
textures.push_back(loadedTex);
skip = true;
break;
}
}
if (!skip) {
MeshTexture texture;
texture.id = TextureFromFile(texturePath.c_str(), this->directory);
texture.type = typeName;
texture.path = texturePath;
textures.push_back(texture);
textures_loaded.push_back(texture);
}
}
return textures;
}
};
unsigned int TextureFromFile(const char *path, const string &directory, bool gamma) {
std::string filename = normalizePath(std::string(path));
if (filename.find("resources/") != 0) {
filename = directory + '/' + filename;
}
filename = normalizePath(filename);
std::string fullPath = std::string(RESOURCE_DIR) + "/" + filename;
if (!std::ifstream(fullPath).good()) {
std::cerr << "Texture not found: " << fullPath << std::endl;
return 0;
}
unsigned int textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char *data = stbi_load(fullPath.c_str(), &width, &height, &nrComponents, 0);
if (data) {
GLenum format = (nrComponents == 1) ? GL_RED :
(nrComponents == 3) ? GL_RGB : 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::cerr << "Texture failed to load at path: " << fullPath << std::endl;
stbi_image_free(data);
}
return textureID;
}
#endif
-model.h
cmake_minimum_required(VERSION 3.10)
project(OpenGLWindow)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(APPLE)
set(CMAKE_MACOSX_RPATH ON)
endif()
find_package(glfw3 REQUIRED)
find_package(OpenGL REQUIRED)
find_package(assimp REQUIRED)
set(GLM_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/libs/glm)
include_directories(
${GLM_INCLUDE_DIR}
${CMAKE_SOURCE_DIR}/libs/glad/include
${CMAKE_SOURCE_DIR}
)
add_library(glad STATIC ${CMAKE_SOURCE_DIR}/libs/glad/src/glad.c)
set_target_properties(glad PROPERTIES
C_STANDARD 11
C_STANDARD_REQUIRED ON
)
if(APPLE)
set(RESOURCES_DEST "${CMAKE_BINARY_DIR}")
else()
set(RESOURCES_DEST "${CMAKE_BINARY_DIR}/resources")
endif()
add_custom_target(copy_resources ALL
COMMAND ${CMAKE_COMMAND} -E make_directory "${RESOURCES_DEST}/shaders"
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_SOURCE_DIR}/resources/shaders/shader.vert
"${RESOURCES_DEST}/shaders/"
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_SOURCE_DIR}/resources/shaders/shader.frag
"${RESOURCES_DEST}/shaders/"
COMMAND ${CMAKE_COMMAND} -E make_directory "${RESOURCES_DEST}/models/backpack"
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_SOURCE_DIR}/resources/models/backpack
"${RESOURCES_DEST}/models/backpack"
COMMENT "Copying resources to build directory"
)
add_executable(opengl_window
main.cpp
scr/Visual/texture.cpp
scr/Meshes/object2d.cpp
scr/Meshes/object3d.cpp
scr/Visual/shader.h
scr/Accessories/camera.h
scr/Accessories/window.cpp
scr/Input/input.cpp
scr/init.cpp
scr/init.h
scr/Meshes/mesh.h
scr/Meshes/model.h
)
add_dependencies(opengl_window glad copy_resources)
target_link_libraries(opengl_window
glad
glfw
OpenGL::GL
assimp::assimp
)
# ✅ Передаём путь ресурсов в код
target_compile_definitions(opengl_window PRIVATE
RESOURCE_DIR="${RESOURCES_DEST}"
)
# Копирование ресурсов
if(APPLE)
# Для macOS копируем в Resources внутри app bundle
set(RESOURCES_DEST "${CMAKE_BINARY_DIR}/opengl_window.app/Contents/Resources")
else()
# Для других платформ копируем в build directory
set(RESOURCES_DEST "${CMAKE_BINARY_DIR}/resources")
endif()
-CMake
Я получаю такую ошибку, когда вы запускаете программу через консоль (и macos также вешает меня о фатальной ошибке при запуске программы):
opengl_window(11588,0x1f353e0c0) malloc: *** error for object 0x11ff12e38: pointer being freed was not allocated
opengl_window(11588,0x1f353e0c0) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort ./opengl_window
Я уже пытался что-то с этим сделать, я пытался добавить настройки под macos, но я не смог это исправить - кто-нибудь знает, что делать?
Источник: Stack Overflow на русском