NDC坐标中的OpenGL转换而不是屏幕坐标(2D)

时间:2015-08-23 22:27:50

标签: c++ opengl glm-math

我无法弄清楚如何使用屏幕坐标在我的场景中定位2D对象。目前我有一些工作(下面的代码),但它想要NDC坐标,这是不容易使用的。我无法弄清楚它出了什么问题。我想我已经习惯了应有的一切,所以我觉得我忘了什么。

这是处理场景中对象绘制的代码:

getContext().getResources()

其中colorProgram是我的精灵使用的着色器,glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // RENDERING HERE colorProgram.bind(); for (size_t t = 0; t < objectsWithGraphicsComponentInThisScene.size(); ++t) { // set texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, objectsWithGraphicsComponentInThisScene[t]->getComponent<GraphicsComponent>()->getTexture()); GLint texLocation = colorProgram.getUniformLocation("texSampler"); glUniform1i(texLocation, 0); glm::mat4 trans; trans = glm::translate(glm::mat4x4(1.0f), glm::vec3(objectsWithGraphicsComponentInThisScene[t]->getPosition().x, objectsWithGraphicsComponentInThisScene[t]->getPosition().y, 0)); GLint transMatLocation = colorProgram.getUniformLocation("transformMatrix"); glUniformMatrix4fv(transMatLocation, 1, GL_FALSE, glm::value_ptr(trans)); // set camera Matrix GLint projMatLocation = colorProgram.getUniformLocation("projectionMatrix"); glm::mat4 cameraMatrix = camera->getCameraMatrix(); glUniformMatrix4fv(projMatLocation, 1, GL_FALSE, glm::value_ptr(cameraMatrix)); objectsWithGraphicsComponentInThisScene[t]->getComponent<GraphicsComponent>()->getSprite()->draw(); // unbind all glBindTexture(GL_TEXTURE_2D, 0); } colorProgram.unbind(); 只返回我设置的值。 (其中x y和z值应作为屏幕坐标给出)。例如,getPosition可能会返回[100,50,0],但这会将对象渲染到屏幕之外(屏幕为1280x720)。

现在呈现精灵的代码(objectsWithGraphicsComponentInThisScene [t] - &gt; getComponent() - &gt; getSprite() - &gt; draw();):

getPosition()

以下是着色器中的代码(colorProgram): VERTEX SHADER:

void Sprite::draw()
{
glBindBuffer(GL_ARRAY_BUFFER, vboID);

glEnableVertexAttribArray(0);

// position
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));

//color
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (void*)offsetof(Vertex, color));

// uv
glVertexAttribPointer(2, 2, GL_FLOAT, GL_TRUE, sizeof(Vertex), (void*)offsetof(Vertex, uv));

glDrawArrays(GL_TRIANGLES, 0, 6);

glDisableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
}

FRAGMENT SHADER

#version 130
// per vertex

// input data from VBO
in vec2 vertexPosition;
in vec4 vertexColor;
in vec2 vertexUV;

// output to fragment shader
out vec4 fragmentColor;
out vec2 fragmentUV;

uniform mat4 projectionMatrix;
uniform mat4 transformMatrix;

void main()
{
mat4 resultMatrix = transformMatrix * projectionMatrix;
gl_Position.xy = (resultMatrix * vec4(vertexPosition, 0.0, 1.0)).xy;
gl_Position.z = 0.0;

// Indicate that the coordinates are normalized
gl_Position.w = 1.0;

fragmentColor = vertexColor;
fragmentUV = vec2(vertexUV.x, 1.0 - vertexUV.y);
}

如果您需要更多代码,我很乐意添加更多代码,尽管我认为这是所需的一切。

0 个答案:

没有答案