views:

196

answers:

4

Hey,

I have a simple OpenGL drawing. When the user changes the window's size, I want the drawing to maintain it's aspect ration. I accomplished that by setting the glViewport to the maximum rectangle with the appropriate aspect ration whenever the reshape method is called.

My problem is that I want to draw a square that will always remain in the top right corner of the window, no matter what the size or shape of the window is. Right now, that square moves around the screen whenever the window is reshaped.

Can anyone please explain how to do this?

Thank you,

+1  A: 

You need to move/size the square when the screen is re-sized. You can fix a square to the top left by using device coordinates but it won't necessarily be square of the aspect ratio changes. Therefore you need to resize the square to keep it square.

Goz
+1  A: 

One way of doing this would be to create a new ortho matrix that maps to pixel coordinates (left = 0, bottom = 0, right = window-width, top = window-height) and set the gl-viewport to cover the entire window whenever the window changes. That way, you can draw a square by specifying pixel coordinates, if you make sure you have an identity model-view matrix set up.

It's not the only way, though. No matter what non-singular transformation you have, you should be able to come up with a way of hitting the correct pixels as long as the gl-viewport covers those, it's just easier this way.

kusma
A: 

To draw a square in the top-right corner of the window, you need the viewport to cover this area. Having a viewport smaller than the window won't allow drawing in the corner.

You want your viewport to cover all the window (as done usually), and your square coordinates should be mapped to something like:

X0 = 1-2*s/width
X1 = 1
Y0 = 1-2*s/height
Y1 = 1

where s is the side of the square (pix), and width, height the dimensions of the window (pix).

Eric Bainville
A: 

If I understand correctly, you wish to draw a square at the top right corner of the window, regardless of where your scene viewport is positioned.

The easiest way to do this is to, after having rendered your normal scene with desired aspect, change the gl viewport to the square you want to draw in the top corner. Then draw a "full-screen" quad to fill the square, with full-screen in-fact becoming full-viewport in this case.

Untested semi-pseudo code would go something like this:

// Draw normal scene
glViewport(x, y, w, h);
drawScene();

// Draw top-right red square
glViewport( windowWidth - squareWidth, windowHeight - squareHeight,
            squareWidth, squareHeight );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glColor3f(1.f, 0.f, 0.f);
glRectf(-1.f, -1.f, 1.f, 1.f);

Making sure that the winding of the glRectf matches your current gl cull face configuration. Alternatively, just temporarily disable culling by glDisable(GL_CULL_FACE) / glEnable(GL_CULL_FACE).

tbone