Render text in foreground - c++

I am trying to render some strings in the foreground in a OpenGL/GLUT application under MacOSX 10.7.2.
At the moment I am using this code to draw a few lines in the foreground and it works fine.
void drawForeground() {
int width = 10;
int height = 10;
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(-1, width, -1, height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glDepthMask(GL_FALSE);
glBegin(GL_LINES);
//Draw the lines
glEnd();
/*********************/
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glDepthMask(GL_TRUE);
}
Now I would like to draw also some text. In the previous function I added this piece of code in the line where I put the asterisks:
glRasterPos2d(2,2);
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, 'c');
but it didn't work. If I use the same two lines outside the drawForeground method the 'c' appears.
I already called glDisable(GL_TEXTURE_2D) and nothing changed.
May someone help me understanding my error?
Solution:
It turned out the solution to be disabling lighting using glDisable(GL_LIGHTING), reenabling it after rendering the text.
I would like to underline that the text is rendered always at the same dimension, independently from the parameters of the glOrtho call.

Nothing certain, but a couple of things to try if you haven't already:
What is the color set to before you call glutBitmapCharacter()? If the drawing color is set to something that doesn't show up against the background, it could simply look like nothing is being drawn.
Have you tried calling glDisable(GL_TEXTURE) in addition to glDisable(GL_TEXTURE_2D)?
Are there other things like lighting that you enable anywhere else in your code, and then don't disable before rendering the text that might affect things? When I've run into bugs like this in the past, it seems like they are often related to something in the OpenGL state being in a state I didn't expect, often because I made some change to the state elsewhere and forgot to undo it. I would recommend that you try systematically commenting out various OpenGL calls in your code, even if they don't seem directly related, and see if the characters ever show up. If they do, then you'll know which state change you need to make/undo.

Related

dll injection: drawing simple game overlay with opengl

I'm trying to draw a custom opengl overlay (steam does that for example) in a 3d desktop game.
This overlay should basically be able to show the status of some variables which the user
can affect by pressing some keys. Think about it like a game trainer.
The goal is in the first place to draw a few primitives at a specific point on the screen. Later I want to have a little nice looking "gui" component in the game window.
The game uses the "SwapBuffers" method from the GDI32.dll.
Currently I'm able to inject a custom DLL file into the game and hook the "SwapBuffers" method.
My first idea was to insert the drawing of the overlay into that function. This could be done by switching the 3d drawing mode from the game into 2d, then draw the 2d overlay on the screen and switch it back again, like this:
//SwapBuffers_HOOK (HDC)
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glOrtho(0.0, 640, 480, 0.0, 1.0, -1.0);
//"OVERLAY"
glBegin(GL_QUADS);
glColor3f(1.0f, 1.0f, 1.0f);
glVertex2f(0, 0);
glVertex2f(0.5f, 0);
glVertex2f(0.5f, 0.5f);
glVertex2f(0.0f, 0.5f);
glEnd();
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
SwapBuffers_OLD(HDC);
However, this does not have any effect on the game at all.
Is my approach correct and reasonable (also considering my 3d to 2d switching code)?
I would like to know what the best way is to design and display a custom overlay in the hooked function. (should I use something like windows forms or should I assemble my component with opengl functions - lines, quads
...?)
Is the SwapBuffers method the best place to draw my overlay?
Any hint, source code or tutorial to something similiar is appreciated too.
The game by the way is counterstrike 1.6 and I don't intend to cheat online.
Thanks.
EDIT:
I could manage to draw a simple rectangle into the game's window by using a new opengl context as proposed by 'derHass'. Here is what I did:
//1. At the beginning of the hooked gdiSwapBuffers(HDC hdc) method save the old context
GLboolean gdiSwapBuffersHOOKED(HDC hdc) {
HGLRC oldContext = wglGetCurrentContext();
//2. If the new context has not been already created - create it
//(we need the "hdc" parameter for the current window, so the initialition
//process is happening in this method - anyone has a better solution?)
//Then set the new context to the current one.
if (!contextCreated) {
thisContext = wglCreateContext(hdc);
wglMakeCurrent(hdc, thisContext);
initContext();
}
else {
wglMakeCurrent(hdc, thisContext);
}
//Draw the quad in the new context and switch back to the old one.
drawContext();
wglMakeCurrent(hdc, oldContext);
return gdiSwapBuffersOLD(hdc);
}
GLvoid drawContext() {
glColor3f(1.0f, 0, 0);
glBegin(GL_QUADS);
glVertex2f(0,190.0f);
glVertex2f(100.0f, 190.0f);
glVertex2f(100.0f,290.0f);
glVertex2f(0, 290.0f);
glEnd();
}
GLvoid initContext() {
contextCreated = true;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 640, 480, 0.0, 1.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0, 0, 0, 1.0);
}
Here is the result:
cs overlay example
It is still very simple but I will try to add some more details, text etc. to it.
Thanks.
If the game is using OpenGL, then hooking into SwapBuffers is the way to go, in principle. In theory, there might be sevaral different drawables, and you might have to decide in your swap buffer function which one(s) are the right ones to modify.
There are a couple of issues with such kind of OpenGL interceptions, though:
OpenGL is a state machine. The application might have modified any GL state variable there is. The code you provided is far from complete to guarantee that something is draw. For example, if the application happens to have shaders enabled, all your matrix setup might be without effect, and what really would appear on the screen depends on the shaders.
If depth testing is on, your fragments might lie behind what already was drawn. If polygon culling is on, your primitive might be incorrectly winded for the currect culling mode. If the color masks are set to GL_FALSE or the draw buffer is not set to where you expect it, nothing will appear.
Also note that your attempt to "reset" the matrices is also wrong. You seem to assume that the current matrix mode is GL_MODELVIEW. But this doesn't have to be the case. It could as well be GL_PROJECTION or GL_TEXTURE. You also apply glOrtho to the current projection matrix without loading identity first, so this alone is a good reason for nothing to appear on the screen.
As OpenGL is a state machine, you also must restore all the state you touched. You already try this with the matrix stack push/pop. But you for example failed to restore the exact matrix mode. As you have seen in 1, a lot more state changes will be required, so restoring it will be more comples. Since you use legacy OpenGL, glPushAttrib() might come handy here.
SwapBuffers is not a GL function, but one of the operating system's API. It gets a drawable as parameter, and does only indirectly refer to any GL context. It might be called while another GL context is bound to the thread, or with none at all. If you want to play it safe, you'll also have to intercept the GL context creation function as well as MakeCurrent. In the worst (though very unlikely) case, the application has the GL context bound to another thread while it is calling the SwapBuffers, so there is no change for you in the hooked function to get to the context.
Putting this all together opens up another alternative: You can create your own GL context, bind it temporarily during the hooked SwapBuffers call and restore the original binding again. That way, you don't interfere with the GL state of the application at all. You still can augment the image content the application has rendered, since the framebuffer is part of the drawable, not the GL context. Doing so might have a negative impact on performance, but it might be so small that you never would even notice it.
Since you want to do this only for a single specific application, another approach would be to find out the minimal state changes which are necessary by observing what GL state the application actually set during the SwapBuffers call. A tool like apitrace can help you with that.

Drawing model from c++ header file

I am using xcode with glut, OpenGL and c++ and I am trying to import and draw a model. I have used an obj to .h file conversion and this is a small part of the header so you can see the structure.
unsigned int M4GunNumVerts = 37812;
GLfloat M4GunVerts [] = {
// f 1/1/1 1582/2/1 4733/3/1
{0.266494348503772, 0.0252334302709736, -0.000725898139236535},
{0.265592372987502, 0.0157389511523397, -0.000725898139236535},
{0.264890836474847, 0.0182004476109518, -0.00775888079925833},
I have tried to draw this in my main with this code.
glVertexPointer(3, GL_FLOAT, 0, M4GunVerts);
glNormalPointer(GL_FLOAT, 0, M4GunNormals);
glTexCoordPointer(2, GL_FLOAT, 0, M4GunTexCoords);
glDrawArrays(GL_TRIANGLES, 0, M4GunNumVerts);
When I run I cant see the model. I have set up a glut window and have made a triangle to see if shapes were being drawn and the triangle showed up. I don't know how fix this so I can see the model.
Here is the reshape function
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
gluPerspective(45, ratio, 0.01, 1000);
glMatrixMode(GL_MODELVIEW);
Can anybody help?
Either you:
do not enable arrays correctly
and or your camera view is in wrong direction to your object
and or your camera is inside the object. (while CULL_FACE is enabled)
and or wrongly or none at all glColor !!! (can not see black on black)
and or forget to bind texture (while enabled)
and or wrong glTexCoord (while enabled)
and or wrongly set lights (while enabled)
and or wrong perspective respect to object distance and size (view angle,znear,zfar)
if object is planar and you are looking on the thin side ...
Some hints:
Try to rotate camera around the scene (ideal with some keys like arrows and see if the object is behind... or mouse drag...). Also try to move your camera forward/backward (also can use keys but my favorite is mouse wheel).
Use glBegin() glVertex() glEnd() first to avoid problems with wrongly enabled arrays and start without lighting,textures,CULL_FACEing (have them disabled!!!). When you see your model then enable all incrementally so you see what is wrong. After all is OK then try arrays.
If your object seems the wrong way about while CULL_FACE enabled then your winding rule is wrong (CW/CCW) can be seen mostly while rotating object
here is simple OpenGL scene app in BDS2006 you can use it as test of your window and camera/model matrix settings

How to make a step by step display animation in openGL?

How to make a step by step display animation in openGL??
I'M doing a reprap printer project to read a GCode file and interpret it into graphic.
now i have difficulty make a step by step animation of drawing the whole object.
i need to draw many short lines to make up a whole object.
for example:
|-----|
| |
| |
|-----|
the square is made up of many short lines, and each line is generated by code like:
glPushMatrix();
.....
for(int i=0; i< instruction[i].size(),i++)
{ ....
glBegin(GL_LINES);
glVertex3f(oldx, oldy, oldz);
glVertex3f(x, y, z);
glEnd();
}
glPopMatrix();
now i want to make a step animation to display how this square is made. I tried to refresh the screen each time a new line is drawn, but it doesn't work, the whole square just come out at once. anyone know how to make this?
Typical OpenGL implementations will queue up large number of calls to batch them together into bursts of activity to make optimal use of available communication bandwidth and GPU time resources.
What you want to do is basically the opposite of double buffered rendering, i.e. rendering where each drawing step is immediately visible. One way to do this is by rendering to a single buffered window and call glFinish() after each step. Major drawback: It's likely to not work well on modern systems, which use compositing window managers and similar.
Another approach, which I recommend, is using a separate buffer for incremental drawing, and constantly refreshing the main framebuffer from this one. The key subjects are Frame Buffer Object and Render To Texture.
First you create a FBO (tons of tutorials out there and as answers on StackOverflow). A FBO is basically an abstraction to which you can connect target buffers, like textures or renderbuffers, and which can be bound as the destination of drawing calls.
So how to solve your problem with them? First you should not do the animation by delaying a drawing loop. This has several reasons, but the main issue is, that you loose program interactivity by this. Instead you maintain a (global) counter at which step in your animation you are. Let's call it step:
int step = 0;
Then in your drawing function you have to phases: 1) Texture update 2) Screen refresh
Phase one consists of binding your framebuffer object as render target. For this to work the target texture must be unbound
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, animFBO);
glViewport(0, 0, fbo.width, fbo.height);
set_animFBO_projection();
the trick now is, that you clear the animFBO only once, namely after creation, and then never again. Now you draw your lines according to the animation step
draw_lines_for_step(step);
and increment the step counter (could do this as a compound statement, but this is more explicit)
step++;
After updating the animation FBO it's time to update the screen. First unbind the animFBO
glBindFramebuffer(GL_FRAMEBUFFER, 0);
We're now on the main, on-screen framebuffer
glViewport(0, 0, window.width, window.height);
set_window_projection(); //most likely a glMatrixMode(GL_PROJECTION); glOrtho(0, 1, 0, 1, -1, 1);
Now bind the FBO attached texture and draw it to a full viewport quad
glBindTexture(GL_TEXTURE_2D, animFBOTexture);
draw_full_viewport_textured_quad();
Finally do the buffer swap to show the animation step iteration
SwapBuffers();
You should have the SwapBuffer method called after each draw call.
Be sure you don't screw the matrix stack and you'll probably need something to "pause" the rendering like a breakpoint.
If you only want the Lines to appear one after another and you dont have to be nit-picking about efficiency or good programming style try something like:
(in your drawing routine)
if (timer > 100)
{
//draw the next line
timer = 0;
}
else
timer++;
//draw all the other lines (you have to remember wich one already appeared)
//for example using a boolean array "lineDrawn[10]"
The timer is an integer that tells you, how often you have drawn the scene. If you make it larger, stuff happens more slowly on the screen when you run your program.
Of course this only works if you have a draw routine. If not, I strongly suggest using one.
->plenty tutorials pretty everywhere, e.g.
http://nehe.gamedev.net/tutorial/creating_an_opengl_window_%28win32%29/13001/
Goor luck to you!
PS: I think you have done nearly the same, but without a timer. thats why everything was drawn so fast that you thought it appeared all at the same time.

OpenGL: Limiting changes to object only

I'm making a basic game in openGL with GLUT, and I've come across a small hitch.
When I attempt to draw an object from a class into my world, it gives everything a tint of colour which was last created with the function makeMaterial (see below).
Does anyone know how I could restrict these changes to being applied to the object only?
I've tried push/pop, but it doesn't seem to limit anything.
Additionally, if the last colour drawn is black, I see nothing at all, except for my snowman.
Here are the relevant code:
makeMaterial :-
makeMaterial( float r,float g,float b,float a,float s )
{
float color[4];
float white[4];
GLfloat surfshine[1] ;
surfshine[0]=s*128.0 ;
color[0]=r;color[1]=g;color[2]=b;color[3]=a;
white[0]=0.5;white[1]=0.5;white[2]=0.5;white[3]=1.0;
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT,color);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE,color);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR,white);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS,surfshine);
}
makeMaterial in use :-
makeMaterial(0.05f,0.05f,0.05f,1.00f, 0.4f);
glPushMatrix();
glutSolidCube(10.0);
glPopMatrix();
my draw function :-
void drawToScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
uniformFPS.setStartTime(glutGet(GLUT_ELAPSED_TIME));
camera.updateCamera();
lvl1.drawLevel();
enemy.drawSnowman(350.0f,6.0f, 200.0f);
crosshair.show();
glutSwapBuffers();
uniformFPS.enforceChecks();
}
If you really want to ensure you are restricting changes to a specific section, you should be able to use glPushAttrib(GL_LIGHTING_BIT) before you do your makeMaterial call, and glPopAttrib after your drawing of the object is done. The reference for glPushAttrib here shows what properties are push'd by each of the possible bits you can supply. I don't know that this is a particularly well regarded way to handle your state however.
A more general solution would be to make a call to makeMaterial with appropriate values before each set of drawing commands, i.e. assuming you have just one material for your snowman and one material for your world:
//...
makeMaterial(1.0f,1.0f,1.0f,1.0f,1.0f);
lvl1.drawLevel();
makeMaterial(0.5f,0.5f,0.5f,0.5f,0.5f);
enemy.drawSnowman(350.0f,6.0f,200.0f);
//...
OpenGL behaves like a state machine when it comes to properties like current color, current material properties, current line width, etc. The values provided are preserved unless they are changed with calls to setter methods explicity.
A proper way to handle your problem would be to have all such properties, be properties of the object being drawn and call appropriate methods before rendering the objects.

Why does my colored cube not work with GL_BLEND?

My cube isn't rendering as expected when I use GL_BLEND.
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
I'm also having a similar problem with drawing some semi-opaque vertices in front, which could well be related.
Related: Why do my semi-opaque vertices make background objects brighter in OpenGL?
Here's what it's supposed to look like:
Normal cube http://img408.imageshack.us/img408/2853/normalcube.png
And here's what it actually looks like:
Dark cube http://img7.imageshack.us/img7/7133/darkcube.png
Please see the code used to create the colored cube, and the code used to actually draw the cube.
The cube is being drawn like so:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glLoadIdentity();
// ... do some translation, rotation, etc ...
drawCube();
glPopMatrix();
// ... swap the buffers ...
You could try disabling all lighting before drawing the cube:
glDisable(GL_LIGHTING);
It looks like you have lighting enabled on the second one,
try with a glShadeModel( GL_FLAT ) before drawing,
This has me stomped. What it looks like is that some vertices have some alpha values that are non-opaque. However the code you posted has all 1. for alpha. So... in order to debug more, did you try to change your clear color to something non-black ? Say green ?
From the code, I doubt lighting is turned on, since no normals were specified.
Last comment, offtopic... You should really not use glBegin/glEnd (2 function calls per vertex + 2 per primitive is really not a good usage of the recent developments in OpenGL). Try glDrawElements with QUAD_LIST, or even better, TRIANGLE_LIST. You already have the data nicely laid out for that.