1

I have some questions about the screen set up. Originally when I would draw a triangle the x vector 1 would be all the way to the right and -1 would be all the way to the left. Now I have adjusted it to account for the different aspect ratio of the window. My new question how do I make the numbers which are used to render a 2d tri go along with the pixel values. If my window is 480 pixels wide and 320 tall I want to have to enter this to span the screen with a tri

glBegin(GL_TRIANGLES);
    glVertex2f(240, 320);
    glVertex2f(480, 0);
    glVertex2f(0, 0);
glEnd();

but instead it currently looks like this

glBegin(GL_TRIANGLES);
    glVertex2f(0, 1);
    glVertex2f(1, -1);
    glVertex2f(-1, -1);
glEnd();

Any ideas?

genpfault
  • 51,148
  • 11
  • 85
  • 139
King Popsicle
  • 465
  • 5
  • 17

2 Answers2

1

You need to use functions glViewport and glOrtho with correct values. Basically glViewport sets the part of your window capable of rendering 3D-Graphics using OpenGL. glOrtho establishes coordinate system within that part of a window using OpenGL's coordinates. So for your task you need to know exact width and height of your window. If you are saying they are 480 and 320 respectively then you need to call

glViewport(0, 0, 480, 320)
// or: glViewport ( 0,0,w,h)

somewhere, maybe in your SizeChanging-handler(if you are using WINAPI it is WM_SIZE message)

Next, when establishing OpenGL's scene you need to specify OpenGL's coordinates. For orthographic projection they will be the same as dimensions of a window so

glOrtho(-240, 240, -160, 160, -100, 100)
// or: glOrtho ( -w/2, w/2, -h/2, h/2, -100, 100 );

is siutable for your purppose. Not that here I'm using depth of 200 (z goes from -100 to 100). Next on your rendering routine you may draw your triangle

starmole
  • 4,974
  • 1
  • 28
  • 48
Blablablaster
  • 3,238
  • 3
  • 31
  • 33
0

Since the second piece of code is working for you, I assume your transformation matrices are all identity or you have a shader that bypasses them. Also your viewport is spanning the whole window.

In general if your viewport starts at (x0,y0) and has WxH size, the normalized coordinates (x,y) you feed to glVertex2f will be transformed to (vx,vy) as follows:

vx = x0 + (x * .5f + .5f) * W
vy = y0 + (y * .5f + .5f) * H

If you want to use pixel coordinates you can use the function

void vertex2(int x, int y)
{
    float vx = (float(x) + .5f) / 480.f;
    float vy = (float(y) + .5f) / 320.f;
    glVertex3f(vx, vy, -1.f);
}

The -1 z value is the closest depth to the viewer. It's negative because the z is assumed to be reflected after the transformation (which is identity in your case). The addition of .5f is because the rasterizer considers a pixel as a 1x1 quad and evaluates the coverage of your triangle in the middle of this quad.

a.lasram
  • 4,371
  • 1
  • 16
  • 24