Walter
Walter

Reputation: 724

2D Shape Coordinates with Modern Opengl

I'm trying to render a series of 2D shapes (Rectangle, Circle) etc in modern opengl, hopefully without the use of any transformation matrices. I would like for me to be able to specify the coordinates for say a rectangle of 2 triangles like so:

float V[] = { 20.0, 20.0, 0.0, 
              40.0, 20.0, 0.0,
              40.0, 40.0, 0.0, 
              40.0, 40.0, 0.0,
              20.0, 40.0, 0.0,
              20.0, 20.0, 0.0 }

You can see that the vertex coordinates are specified in viewport? space (I believe thats what its called). Now, when this get rendered by opengl, it doesnt work because clip space goes from -1.0 to 1.0 with the origin in the center.

What would be the correct way for me to handle this? I initially thought adjusting glClipControl to upper left and 0 to 1 would work, but it didnt. With clip control set to upper left and 0 to 1, the origin was still at the center, but it did allow for the Y-Axis to increase as it moved downward (which is a start).

Ideally, I would love to get opengl to have 0.0,0.0 to be the top left and 1.0, 1.0 to be the bottom right, then I just normalise each vertex position, but I have no idea how to get opengl to use that type of coordinate system.

Upvotes: 1

Views: 642

Answers (1)

LJᛃ
LJᛃ

Reputation: 8143

One can easily do these transformation without matrices in the vertex shader:

// From pixels to 0-1 
vPos.xy /= vResolution.xy;

// Flip Y so that 0 is top 
vPos.y = (1.-vPos.y);

// Map to NDC -1,+1
vPos.xy = vPos.xy*2.-1.;

Upvotes: 1

Related Questions