我正在编写一个类来使用现代 OpenGL 技术从 32 位 bmp 渲染高度图。我让它在立即模式下工作,但想尝试将其转换为现代 OpenGL 上下文。我正在使用带有地图索引数据的元素数组缓冲区和具有顶点数据的 vbo,其中 y 分量取自位图的高度(像素颜色)。
现在,我在绘图调用中遇到了未处理的异常/访问冲突。这是我的代码:
void HeightMap::initHeightMap(const char* filePath, float size, float height){
SDL_Surface* image = SDL_LoadBMP(filePath);
if (!image)
{
smodgine::fatalError("Image could not be loaded!");
}
std::vector<float> tmp;
for (int y = 0; y< image->h; y++)
{
tmp.clear();
for (int x = 0; x < image->w; x++)
{
Uint32 pixel = ((Uint32*)image->pixels)[y * image->pitch/4 + x];
Uint8 r, g, b;
SDL_GetRGB(pixel, image->format, &r, &g, &b);
tmp.push_back((float)r / 255.0f);
}
heights.push_back(tmp);
}
for (int z = 0; z < heights.size(); z++)
{
for (int x = 0; x < heights[0].size(); x++)
{
vertices.push_back(x * size);
vertices.push_back(heights[z][x] * height);
vertices.push_back(z * size);
}
}
if (_vbo == 0) {
glGenBuffers(1, &_vbo);
}
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
_numRows = heights.size() - 1;
_numColumns = heights[0].size() - 1;
SDL_FreeSurface(image);
createElementBuffer();
}
void HeightMap::renderHeightMap()
{
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _eleBuffer);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, 0);
}
void HeightMap::createElementBuffer()
{
for (int z = 0; z < _numRows; z++)
{
for (int x = 0; x < _numColumns; x++)
{
//top left
indices.push_back(z * _numRows + x);
//bottom left
indices.push_back((z + 1) * _numRows + x);
//top right
indices.push_back(z * _numRows + (x + 1));
//top right
indices.push_back(z * _numRows + (x + 1));
//bottom left
indices.push_back((z + 1) * _numRows + x);
//bottom right
indices.push_back((z + 1) * _numRows + (x + 1));
}
}
if (_eleBuffer == 0){
glGenBuffers(1, &_eleBuffer);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _eleBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
我只使用现代 OpenGL 大约一个星期左右,任何帮助表示赞赏:D