OpenGL,Texture输出为纯色

问题描述 投票:0回答:1

我试图纹理我的地形但似乎要么采取从纹理中挑选一种颜色并在任何地方使用它的纹理的平均颜色。我看过其他解决方案,但他们没有帮助我。我是新人,所以这可能是一个简单的错误

纹理由SOIL2生成

生成纹理

int texID = SOIL_load_OGL_texture(
    filename.c_str(),
    SOIL_LOAD_AUTO,
    SOIL_CREATE_NEW_ID,
    SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
    );

生成UV坐标(删除了我的问题不重要的东西)

int i=0;
for (int z = 0; z < m_Size; z++) // loop through columns
{
    for (int x = 0; x < m_Size; x++) // loop through rows
    {
        model.mesh.uvs[i] = Math::Vector2(x / m_Size, z / m_Size); //Terrain is square
        i++;
    }

}

创建纹理缓冲区

if (model->mesh.numOfUVs != 0)
{
    glGenBuffers(1, &model->textureBufferID);
    glBindBuffer(GL_ARRAY_BUFFER, model->textureBufferID);
    glBufferData(GL_ARRAY_BUFFER, model->mesh.numOfUVs * sizeof(Math::Vector2), model->mesh.uvs, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Math::Vector2), (void*)(0));     
}

绘制地形(不是完整代码)

            glBindVertexArray(ID);

            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, model->textureID1);
            unsigned int textureLocation = glGetUniformLocation(shaderID, "grassTex");
            glUniform1i(textureLocation, 0);

            glUniformMatrix4fv(glGetUniformLocation(shaderID, "MVP"), 1, false, &newMVP.mat[0][0]);

            glDrawElements(GL_TRIANGLES, model->mesh.numOfIndices, GL_UNSIGNED_INT, (void*)0);


            glBindVertexArray(0);

Vert Shader

#version 330 core

layout(location = 0) in vec2 texturecoord;

uniform mat4 MVP;

out vec2 texcoord;

void main(){
    texcoord = texturecoord;
    gl_Position = MVP * vec4(in_position, 1);
}

问Shader

#version 330 core

layout(location = 0) out vec4 out_colour;

in vec2 texcoord;
uniform sampler2D grassTex;

void main()
{
    out_colour = texture2D(grassTex, texcoord);
}

如果某些事情没有意义,那可能是因为我删除了大量代码以尝试减少我发布的代码量

它看起来像什么(图片中的3个纹理,但我删除了这篇文章中的代码,因为我不认为它与我使用的纹理数量有任何关系)https://imgur.com/a/rSPp7Ru

c++ opengl textures terrain
1个回答
1
投票

问题是整数除法。除分整数后,得到一个整数。这是您生成UV坐标的位置。

for (int z = 0; z < m_Size; z++) // loop through columns
{
    for (int x = 0; x < m_Size; x++) // loop through rows
    {
        model.mesh.uvs[i] = Math::Vector2(x / m_Size, z / m_Size); //Terrain is square
        i++;
    }
}

xz总是小于m_Size。这意味着x / m_Sizez / m_Size总是0,因为你不能将0.2存储在int中。由于你所有的UV坐标都是0, 0,你只是看到整个三角形的纹理的一个角(我认为它是左下角)。

要解决这个问题,请将其中一个操作数转换为floatdouble

model.mesh.uvs[i] = Math::Vector2(
  static_cast<float>(x) / m_Size, 
  static_cast<float>(z) / m_Size
);

如果你将float除以int,那么int将被提升为float,因此将进行float分裂。

© www.soinside.com 2019 - 2024. All rights reserved.