使用实例渲染时在着色器中旋转

时间:2019-03-01 13:07:53

标签: c++ opengl shader

我建立了实例渲染系统,在其中我在不同位置渲染同一对象。我现在正在尝试对每个对象实施单个旋转(每个对象在特定位置将具有自己的旋转度),我无法使其正常工作。

这是我的初始化代码:

//Init translation VBO
glBindBuffer(GL_ARRAY_BUFFER, m_translationVBO);
glBufferData(GL_ARRAY_BUFFER, m_size * sizeof(glm::vec3), &translations[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);


//Init rotation VBO
glm::mat4 rot = glm::mat4(1.0f);
rot = glm::rotate(rot, glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f));
vector<glm::mat4> rotations(m_size, rot);
glBindBuffer(GL_ARRAY_BUFFER, m_rotationVBO);
glBufferData(GL_ARRAY_BUFFER, m_size * sizeof(glm::vec4), &rotations[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

//Send vertex attrib to VAO
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_translationVBO);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, m_rotationVBO);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0);
glEnableVertexAttribArray(3);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);

这是我的渲染代码:

m_shader0.use();
glBindTexture(GL_TEXTURE_2D, m_texture);   

glBindVertexArray(m_VAO);

glm::mat4 modelview = getModelview();
glm::mat4 modelviewProjection = getProjection() * modelview;

m_shader0.setMat4("modelviewProjection", modelviewProjection);

unsigned long indicesSize = m_indices.size();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO);
glDrawElementsInstanced(GL_TRIANGLES, indicesSize, GL_UNSIGNED_INT, 0, m_size);

glBindVertexArray(0);
glUseProgram(0);

这是我的顶点着色器:

#version 330 core

layout (location = 0) in vec3 in_Vertex;
layout (location = 1) in vec2 in_texCoord;
layout (location = 2) in vec3 in_Offset;
layout (location = 3) in vec4 in_Rot;

uniform mat4 modelviewProjection;

out vec2 texCoord;

void main()
{
    gl_Position = modelviewProjection * in_Rot * vec4(in_Vertex + in_Offset, 1.0);
    texCoord = in_texCoord;
}

这是对每个实例化对象进行旋转的正确方法吗?

0 个答案:

没有答案