【发布时间】:2023-04-09 06:39:02
【问题描述】:
我目前正在使用 OpenGL 构建高度图地形生成器。这是一个简单的程序,可以加载高度图图像,迭代图像数据并生成顶点、索引和法线。在当前状态下,它可以基于法线使用单一颜色渲染高度图。
我的问题是为漫反射贴图生成正确的 UV 坐标。结果就是错了:
这是我要加载的漫反射贴图:
这是我目前拥有的:
生成顶点、法线和索引
// Generate Vertices and texture coordinates
for (int row = 0; row <= this->imageHeight; row++)
{
for (int column = 0; column <= this->imageWidth; column++)
{
float x = (float)column / (float)this->imageWidth;
float y = (float)row / (float)this->imageHeight;
float pixel = this->imageData[this->imageWidth * row + column];
float z;
if (row == this->imageHeight || column == this->imageWidth || row == 0 || column == 0)
{
z = 0.0f;
}
else
{
z = float(pixel / 256.0)*this->scale;
}
MeshV3 mesh;
mesh.position = glm::vec3(x, y, z);
mesh.normal = glm::vec3(0.0, 0.0, 0.0);
mesh.texture = glm::vec2(x, y);
this->mesh.push_back(mesh);
}
}
// Generate indices
for (int row = 0; row < this->imageHeight; row++)
{
for (int column = 0; column < this->imageWidth; column++)
{
int row1 = row * (this->imageWidth + 1);
int row2 = (row + 1) * (this->imageWidth + 1);
// triangle 1
this->indices.push_back(glm::uvec3(row1 + column, row1 + column + 1, row2 + column + 1));
// triangle 2
this->indices.push_back(glm::uvec3(row1 + column, row2 + column + 1, row2 + column));
}
}
// Generate normals
for (int i = 0; i < this->indices.size(); i++)
{
glm::vec3 v1 = this->mesh[this->indices[i].x].position;
glm::vec3 v2 = this->mesh[this->indices[i].y].position;
glm::vec3 v3 = this->mesh[this->indices[i].z].position;
glm::vec3 edge1 = v1 - v2;
glm::vec3 edge2 = v1 - v3;
glm::vec3 normal = glm::normalize(glm::cross(edge1, edge2));
this->mesh[this->indices[i].x].normal += normal;
this->mesh[this->indices[i].y].normal += normal;
this->mesh[this->indices[i].z].normal += normal;
}
我用下面的方法加载漫反射贴图
void Terrein::getDIffuseMap()
{
glGenTextures(1, &this->texture);
glBindTexture(GL_TEXTURE_2D, this->texture); // all upcoming GL_TEXTURE_2D operations now have effect on this texture object
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
int width, height, nrChannels;
std::string path = "assets/diffuse.jpg";
this->diffuseData = stbi_load(path.c_str(), &width, &height, &nrChannels, 0);
if (this->diffuseData)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->diffuseData);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load diffuse texture" << std::endl;
}
}
我似乎无法弄清楚这里可能出了什么问题。我如何加载图像有问题吗?还是我没有正确计算纹理坐标?如果还有什么我应该提供的,请告诉我。我已经坚持了几天了。谢谢!
【问题讨论】:
-
不是您的问题,而是您对
float pixel的计算可能超出了imageData的范围。由于pixel仅用于以下if的else部分,因此将pixel移动到else的正文中。 -
你的着色器在哪里?
-
@1201ProgramAlarm 谢谢,我在 imageData 上遇到了越界错误。我犯了一个愚蠢的错误,在采纳您的建议后它已修复。