1

我在 C++ 中使用 OpenGL 应用程序工作了几个月,以前从未遇到过这个问题。

在Visual Studio 2012中编码我可以在 IDE 中运行应用程序,也可以手动启动可执行文件。在这两种情况下,我都可以在调试和发布版本之间进行选择。以下问题仅在我自己启动发布构建可执行文件时出现。否则一切正常。

当我动态地向场景中添加新表单时,应用程序有时会崩溃。我的操作系统Windows 8 64bit让我Debug the program从崩溃对话框中退出,这确实没有太大帮助,因为它是一个发布版本,在运行时可用的调试信息较少,但它至少告诉我应用程序在 draw call 附近崩溃glDrawTriangles()。在我的代码中,循环内只有一个绘图调用。

崩溃只是不规则地发生,这让我发疯。有时应用程序在几分钟内运行良好,有时它立即崩溃,有时它运行几秒钟。但我认为重要的是要知道应用程序只会在新表单插入场景后立即崩溃,我首先在另一个线程中生成,然后在主线程中创建 OpenGL 缓冲区。

以下是 Windows 崩溃对话框中显示的问题详细信息。我的显卡ATI Radeon 7870的驱动程序似乎崩溃了。

问题签名:
  问题事件名称:APPCRASH
  应用程序名称:Application.exe 应用
  程序版本:0.0.0.0
  应用程序时间戳:50f1491a
  故障模块名称:atioglxx.dll
  故障模块版本:6.14.10.11931
  故障模块时间戳:50650037
  异常代码:c0000005
  异常偏移量: 001108ef
  操作系统版本:6.2.9200.2.0.0.256.27
  区域设置 ID:1031
  附加信息 1:5861
  附加信息 2:5861822e1919d7c014bbb064c64908b2
  附加信息 3:dac6
  附加信息 4:dac6c2650fa14dd558bd9f448e

在线阅读我们的隐私声明:http:
  //go.microsoft.com/fwlink/ ?linkid=190175

如果在线隐私声明不可用,请离线阅读我们的隐私声明:
  C:\Windows\system32\en-US\erofflps.txt

到目前为止,我所做的是更新我的视频卡驱动程序并调试我的应用程序,因为我注意到结果不可靠,因为崩溃是自发发生的。有很多源文件,老实说,我不确定哪个会影响这个错误。它可能是一个名为的文件,terrain.cpp因此我将代码粘贴到此处。

#pragma once

#include "system.h"
#include "debug.h"

#include <vector>
#include <cstdlib>
#include <future>
using namespace std;
#include <GLEW/glew.h>
#include <SFML/OpenGL.hpp>
#include <SFML/Graphics/Image.hpp>
using namespace sf;
#include <GLM/glm.hpp>
#include <GLM/gtc/noise.hpp>
using namespace glm;

#include "settings.h"
#include "camera.h"
#include "form.h"
#include "transform.h"
#include "terrain.h"
#include "shader.h"
#include "movement.h"


typedef detail::tvec3<int> vec3i;

class ComponentTerrain : public Component
{
    void Init()
    {
        auto wld = Global->Add<StorageTerrain>("terrain");

        tasking = false;

        Texture();

        Listeners();
    }

    void Update()
    {
        auto wld = Global->Get<StorageTerrain>("terrain");
        auto stg = Global->Get<StorageSettings>("settings");
        auto cam = Global->Get<StorageCamera>("camera");
        auto cks = Entity->Get<StorageChunk>();

        int Distance = (int)(.5f * stg->Viewdistance / CHUNK_X / 2);
        Debug::Info("Terrain chunk distance " + to_string(Distance));
        for(int X = -Distance; X <= Distance; ++X)
        for(int Z = -Distance; Z <= Distance; ++Z)
        {
            addChunk(X + (int)cam->Position.x / CHUNK_X, 0, Z + (int)cam->Position.z / CHUNK_Z);
        }
        for(auto chunk : wld->chunks)
        {
            auto chk = cks.find(chunk.second);
            float distance = (float)vec3(chunk.first[0] * CHUNK_X - cam->Position.x, chunk.first[1] * CHUNK_Y - cam->Position.y, chunk.first[2] * CHUNK_Z - cam->Position.z).length();
            if(distance > stg->Viewdistance)
                deleteChunk(chunk.first[0], chunk.first[1], chunk.first[2]);
        }

        if(tasking)
        {
            if(task.wait_for(chrono::milliseconds(0)) == future_status::ready)
            {
                tasking = false;
                Data data = task.get();
                Buffers(data);
            }
        }
        else
        {
            for(auto chunk : cks)
            if(chunk.second->changed)
            {
                tasking = true;
                chunk.second->changed = false;
                task = async(launch::async, &ComponentTerrain::Mesh, this, Data(chunk.first));
                break;
            }
        }
    }

    struct Data
    {
        Data() {}
        Data(unsigned int id) : id(id) {}
        unsigned int id;
        vector<float> Vertices, Normals, Texcoords;
        vector<int> Elements;
    };

    future<Data> task;
    bool tasking;
    Image texture;

    void Listeners()
    {
        Event->Listen("SystemInitialized", [=]{
            auto cam = Global->Get<StorageCamera>("camera");
            cam->Position = vec3(0, CHUNK_Y, 0);
            cam->Angles = vec2(0.75, -0.25);
        });

        Event->Listen("InputBindChunk", [=]{
            addChunk(rand() % 5, 0, rand() % 5);
            addChunk(rand() % 5, 0, rand() % 5);
            addChunk(rand() % 5, 0, rand() % 5);
        });
    }

    unsigned int getChunk(int X, int Y, int Z)
    {
        auto wld = Global->Get<StorageTerrain>("terrain");
        array<int, 3> key = {X, Y, Z};
        auto i = wld->chunks.find(key);
        return (i != wld->chunks.end()) ? i->second : 0;
    }

    int addChunk(int X, int Y, int Z)
    {
        auto wld = Global->Get<StorageTerrain>("terrain");
        auto shd = Global->Get<StorageShader>("shader"); // moved this line

        unsigned int id = getChunk(X, Y, Z);
        if(!id)
        {
            id = Entity->New();
            Entity->Add<StorageChunk>(id);
            auto frm = Entity->Add<StorageForm>(id); // moved this line
            auto tsf = Entity->Add<StorageTransform>(id);

            frm->Program = shd->Program; // moved this line
            tsf->Position = vec3(X * CHUNK_X, Y * CHUNK_Y, Z * CHUNK_Z);

            Generate(id, X, Y, Z);

            array<int, 3> key = {X, Y, Z};
            wld->chunks.insert(make_pair(key, id));
        }
        return id;
    }

    void deleteChunk(int X, int Y, int Z)
    {
        auto wld = Global->Get<StorageTerrain>("terrain");

        unsigned int id = getChunk(X, Y, Z);
        if(id < 1) return;

        array<int, 3> key = {X, Y, Z};
        wld->chunks.erase(key);

        Entity->Delete<StorageChunk>(id);
        Entity->Delete<StorageForm>(id);
        Entity->Delete<StorageTransform>(id);

        // free buffers
    }

    void Generate(unsigned int id, int X, int Y, int Z)
    {
        auto cnk = Entity->Get<StorageChunk>(id);
        cnk->changed = true;

        for(int x = 0; x < CHUNK_X; ++x) {
        const float i = X + (float)x / CHUNK_X;
        for(int z = 0; z < CHUNK_Z; ++z) {
        const float j = Z + (float)z / CHUNK_Z;
                double height_bias = 0.30;
                double height_base = 0.50 * (simplex(0.2f * vec2(i, j)) + 1) / 2;
                double height_fine = 0.20 * (simplex(1.5f * vec2(i, j)) + 1) / 2;
                int height = (int)((height_bias + height_base + height_fine) * CHUNK_Y);
                for(int y = 0; y < height; ++y) cnk->blocks[x][y][z] = true;
        } }
    }

    #define TILES_U 4
    #define TILES_V 4

    Data Mesh(Data data)
    {
        auto cnk = Entity->Get<StorageChunk>(data.id);
        auto *Vertices = &data.Vertices, *Normals = &data.Normals, *Texcoords = &data.Texcoords;
        auto *Elements = &data.Elements;

        const vec2 grid(1.f / TILES_U, 1.f / TILES_V);

        int n = 0;
        for(int X = 0; X < CHUNK_X; ++X)
        for(int Y = 0; Y < CHUNK_Y; ++Y)
        for(int Z = 0; Z < CHUNK_Z; ++Z)
            if(cnk->blocks[X][Y][Z])
            {
                int Tile = Clamp(rand() % 2 + 1, 0, TILES_U * TILES_V - 1);

                for(int dim = 0; dim < 3; ++dim) { int dir = -1; do {
                    vec3i neigh = Shift(dim, vec3i(dir, 0, 0)) + vec3i(X, Y, Z);

                    if(Inside(neigh, vec3i(0), vec3i(CHUNK_X, CHUNK_Y, CHUNK_Z) - 1))
                        if(cnk->blocks[neigh.x][neigh.y][neigh.z])
                            { dir *= -1; continue; }

                    for(float i = 0; i <= 1; ++i)
                    for(float j = 0; j <= 1; ++j)
                    {
                        vec3 vertex = vec3(X, Y, Z) + floatify(Shift(dim, vec3i((dir+1)/2, i, j)));
                        Vertices->push_back(vertex.x); Vertices->push_back(vertex.y); Vertices->push_back(vertex.z);
                    }

                    vec3 normal = normalize(floatify(Shift(dim, vec3i(dir, 0, 0))));
                    for(int i = 0; i < 4; ++i)
                    {
                        Normals->push_back(normal.x); Normals->push_back(normal.y); Normals->push_back(normal.z);
                    }

                    vec2 position = (vec2(Tile % TILES_U, Tile / TILES_U) + .25f) * grid;
                    Texcoords->push_back(position.x);            Texcoords->push_back(position.y);
                    Texcoords->push_back(position.x + grid.x/2); Texcoords->push_back(position.y);
                    Texcoords->push_back(position.x);            Texcoords->push_back(position.y + grid.y/2);
                    Texcoords->push_back(position.x + grid.x/2); Texcoords->push_back(position.y + grid.y/2);

                    if(dir == -1) {
                        Elements->push_back(n+0); Elements->push_back(n+1); Elements->push_back(n+2);
                        Elements->push_back(n+1); Elements->push_back(n+3); Elements->push_back(n+2);
                    } else {
                        Elements->push_back(n+0); Elements->push_back(n+2); Elements->push_back(n+1);
                        Elements->push_back(n+1); Elements->push_back(n+2); Elements->push_back(n+3);
                    }
                    n += 4;

                dir *= -1; } while(dir > 0); }
            }

        return data;
    }

    void Buffers(Data data)
    {
        auto frm = Entity->Get<StorageForm>(data.id);

        glGenBuffers(1, &frm->Positions);
        glBindBuffer(GL_ARRAY_BUFFER, frm->Positions);
        glBufferData(GL_ARRAY_BUFFER, data.Vertices.size() * sizeof(float), &(data.Vertices[0]), GL_STATIC_DRAW);

        glGenBuffers(1, &frm->Normals);
        glBindBuffer(GL_ARRAY_BUFFER, frm->Normals);
        glBufferData(GL_ARRAY_BUFFER, data.Normals.size() * sizeof(float), &(data.Normals[0]), GL_STATIC_DRAW);

        glGenBuffers(1, &frm->Texcoords);
        glBindBuffer(GL_ARRAY_BUFFER, frm->Texcoords);
        glBufferData(GL_ARRAY_BUFFER, data.Texcoords.size() * sizeof(float), &(data.Texcoords[0]), GL_STATIC_DRAW);

        glGenBuffers(1, &frm->Elements);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, frm->Elements);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, data.Elements.size() * sizeof(int), &data.Elements[0], GL_STATIC_DRAW);

        glGenTextures(1, &frm->Texture);
        glBindTexture(GL_TEXTURE_2D, frm->Texture);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture.getSize().x, texture.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.getPixelsPtr());
        glGenerateMipmap(GL_TEXTURE_2D);
    }

    void Texture()
    {
        Image image;
        bool result = image.loadFromFile("forms/textures/terrain.png");
        if(!result){ Debug::Fail("Terrain texture loading fail"); return; }

        Vector2u size = Vector2u(image.getSize().x / TILES_U, image.getSize().y / TILES_V);
        texture.create(image.getSize().x * 2, image.getSize().y * 2, Color());
        for(int u = 0; u < TILES_U; ++u)
        for(int v = 0; v < TILES_V; ++v)
        {
            Image tile, quarter;
            tile.create(size.x, size.y, Color());
            tile.copy(image, 0, 0, IntRect(size.x * u, size.y * v, size.x, size.y), true);
            quarter.create(size.x, size.y, Color());
            quarter.copy(tile, 0,          0,          IntRect(size.x / 2, size.y / 2, size.x / 2, size.y / 2), true);
            quarter.copy(tile, size.x / 2, 0,          IntRect(0,          size.y / 2, size.x / 2, size.y / 2), true);
            quarter.copy(tile, 0,          size.y / 2, IntRect(size.x / 2, 0,          size.x / 2, size.y / 2), true);
            quarter.copy(tile, size.x / 2, size.y / 2, IntRect(0,          0,          size.x / 2, size.y / 2), true);
            texture.copy(quarter, (u * 2    ) * size.x, (v * 2    ) * size.y, IntRect(0, 0, 0, 0), true);
            texture.copy(quarter, (u * 2 + 1) * size.x, (v * 2    ) * size.y, IntRect(0, 0, 0, 0), true);
            texture.copy(quarter, (u * 2    ) * size.x, (v * 2 + 1) * size.y, IntRect(0, 0, 0, 0), true);
            texture.copy(quarter, (u * 2 + 1) * size.x, (v * 2 + 1) * size.y, IntRect(0, 0, 0, 0), true);
        }
    }

    template <typename T>
    inline T Clamp(T Value, T Min, T Max)
    {
        if(Value < Min) return Min;
        if(Value > Max) return Max;
        return Value;
    }

    bool Inside(vec3i Position, vec3i Min, vec3i Max)
    {
        if(Position.x < Min.x || Position.y < Min.y || Position.z < Min.z) return false;
        if(Position.x > Max.x || Position.y > Max.y || Position.z > Max.z) return false;
        return true;
    }

    inline vec3i Shift(int Dimension, vec3i Vector)
    {
        if      (Dimension % 3 == 1) return vec3i(Vector.z, Vector.x, Vector.y);
        else if (Dimension % 3 == 2) return vec3i(Vector.y, Vector.z, Vector.x);
        else                         return Vector;
    }

    vec3 floatify(vec3i Value)
    {
        return vec3(Value.x, Value.y, Value.z);
    }
};

但是,您可以在 Github 上找到整个代码

您知道什么可能导致崩溃或如何找到错误吗?如果您需要更多信息以及哪种信息,请告诉我。

感谢@doomster,我现在可以找到并修复错误。

渲染器组件循环遍历表单向量以绘制它们。异步线程向该向量添加了新形式,但它们的缓冲区稍后在返回生成的顶点后在主线程中创建。这意味着绘图和表单添加是并行运行的。当渲染器尝试渲染没有任何已创建缓冲区的表单时发生崩溃。

addChunk()我在上面的代码中插入了注释,以突出显示我为解决问题而移至的三行Buffers()。我不知道为什么只有发布构建可执行文件崩溃了,但这不再重要了。

4

1 回答 1

4

我要在这里验证两件事:

  • 您正在使用future<T>. 我不确定,但如果它在不同的线程中运行,可能会对 OpenGL 产生负面影响,我听说它对多线程使用很敏感。尽管将其视为谣言,我不太确定,但尝试转换为单线程代码是值得一试的。
  • 您也可以在发布版本中激活调试符号。这至少应该在崩溃发生时为您提供可用的回溯。实际上,VS 的 Debug/Release 设置只是默认设置,没有任何内在意义,因此您可以逐步修改 Debug 设置,直到与 Release 设置匹配。这应该会给你一个失败的变体,但仍然可以在调试器中使用。
于 2013-01-12T12:14:03.610 回答