My 3D world draws perfectly every time but the 2D text never draws. The code below features my latest effort using a tutorial from lighthouse3D. I get the feeling its something stupidly simple and im just not seeing it.
Rendering code :
void ScreenGame::draw(SDL_Window * window)
{
glClearColor(0.5f,0.5f,0.5f,1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Set up projection matrix
glm::mat4 projection(1.0);
projection = glm::perspective(60.0f,800.0f/600.0f,1.0f,150.0f);
rt3d::setUniformMatrix4fv(shaderProgram, "projection", glm::value_ptr(projection));
GLfloat scale(1.0f); // just to allow easy scaling of complete scene
glm::mat4 modelview(1.0); // set base position for scene
mvStack.push(modelview);
mvStack.top() = glm::lookAt(camera->getEye(),camera->getAt(),camera->getUp());
glm::vec4 tmp = mvStack.top()*lightPos;
light0.position[0] = tmp.x;
light0.position[1] = tmp.y;
light0.position[2] = tmp.z;
rt3d::setLightPos(shaderProgram, glm::value_ptr(tmp));
glUseProgram(skyBoxShader); // Switch shaders, reset uniforms for skybox
rt3d::setUniformMatrix4fv(skyBoxShader, "projection", glm::value_ptr(projection));
glDepthMask(GL_FALSE); // make sure depth test is off
glm::mat3 mvRotOnlyMat3 = glm::mat3(mvStack.top());
mvStack.push( glm::mat4(mvRotOnlyMat3) );
skyBox->draw(mvStack); // drawing skybox
mvStack.pop();
glDepthMask(GL_TRUE); // make sure depth test is on
mvStack.top() = glm::lookAt(camera->getEye(),camera->getAt(),camera->getUp());
glUseProgram(shaderProgram); // Switch back to normal shader program
rt3d::setUniformMatrix4fv(shaderProgram, "projection", glm::value_ptr(projection));
rt3d::setLightPos(shaderProgram, glm::value_ptr(tmp));
rt3d::setLight(shaderProgram, light0);
// Draw all visible objects...
Ball->draw(mvStack);
ground->draw(mvStack);
building1->draw(mvStack);
building2->draw(mvStack);
setOrthographicProjection();
glPushMatrix();
glLoadIdentity();
renderBitmapString(5,30,1,GLUT_BITMAP_HELVETICA_18,"Text Test");
glPopMatrix();
restorePerspectiveProjection();
SDL_GL_SwapWindow(window); // swap buffers
}
using the following methods :
void setOrthographicProjection() {
// switch to projection mode
glMatrixMode(GL_PROJECTION);
// save previous matrix which contains the
//settings for the perspective projection
glPushMatrix();
// reset matrix
glLoadIdentity();
// set a 2D orthographic projection
glOrtho(0.0F, 800, 600, 0.0F, -1.0F, 1.0F);
// switch back to modelview mode
glMatrixMode(GL_MODELVIEW);
}
void restorePerspectiveProjection() {
glMatrixMode(GL_PROJECTION);
// restore previous projection matrix
glPopMatrix();
// get back to modelview mode
glMatrixMode(GL_MODELVIEW);
}
void renderBitmapString(
float x,
float y,
int spacing,
void *font,
char *string) {
char *c;
int x1=x;
for (c=string; *c != '\0'; c++) {
glRasterPos2f(x1,y);
glutBitmapCharacter(font, *c);
x1 = x1 + glutBitmapWidth(font,*c) + spacing;
}
}
Related
Need to get global absolute scale of object to display it with OpenGL.
When I just multiply scale vectors of parents and children, I get absolute scale for world axes space. When I rotate object, it scales along global axes, not local.
I decided that I need to rotate scale vector too. But:
When I am trying to rotate it with direction vector - it values sometimes are going to 0, and scale too.
{ scale.x * forward.x , scale.y * forward.y , scale.z * forward.z }
When I am trying to rotate it with glm::rotate, it makes unexpected results, like infinite rotating/scaling, wrench and other effects on meshes.
auto globalScale = glm::vec3(scale.x, scale.y, scale.z);
globalScale = glm::rotate(globalScale, rotation.x, {1,0,0});
globalScale = glm::rotate(globalScale, rotation.y, {0,1,0});
globalScale = glm::rotate(globalScale, rotation.z, {0,0,1});
My rendering code:
void Render(Material *mat, Transform* tr){
glEnable(GL_COLOR_MATERIAL);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
// Get object transformations
Vector3 pos = tr->globalPosition();
Vector3 rot = tr->globalRotation();
Vector3 scale = (tr->globalScale());
auto globalScale = glm::vec3(scale.x, scale.y, scale.z);
// First, scaling, then rotating, then translating in world space
// ( Initially all objects rendering starts at (0,0,0) )
glScaled(globalScale.x, globalScale.y, globalScale.z);
glRotatef(rot.x, 1.0, 0.0, 0.0);
glRotatef(rot.y, 0.0, 1.0, 0.0);
glRotatef(rot.z, 0.0, 0.0, 1.0);
glTranslated(pos.x, pos.y, pos.z);
// Rendering
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3,GL_FLOAT,0,vertexArray);
glNormalPointer(GL_FLOAT,0,normalArray);
glClientActiveTexture(GL_TEXTURE0_ARB);
glTexCoordPointer(2,GL_FLOAT,0,uvArray);
glDrawArrays(GL_TRIANGLES,0,numVerts);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// Rolling transformations back
glTranslated(-pos.x, -pos.y, -pos.z);
glRotated(-rot.z, 0.0, 0.0, 1.0);
glRotated(-rot.y, 0.0, 1.0, 0.0);
glRotated(-rot.x, 1.0, 0.0, 0.0);
glScaled(1/globalScale.x, 1/globalScale.y, 1/globalScale.z);
}
Rendering call:
void RenderObject(GameObject* go){
for(auto goc : go->children)
goc->Update<MeshRenderer>();//RenderObject(goc);
}
void RenderScene(){
auto scene = EditorInstance::GetSingleton()->currentScene;
for(auto go : scene->hierarchy){
RenderObject(go);
if(auto mr = (go->GetComponent<Camera>())){
mr->Update();
}
}
}
... render->setOnRender(RenderScene); ...
Main rendering method:
int render()
{
#ifdef EDITOR
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); // Bind our frame buffer for rendering
glPushAttrib(GL_VIEWPORT_BIT | GL_ENABLE_BIT); // Push our glEnable and glViewport states
DrawGrid(100);
#else
if(NukeOGL::getSingleton() != this){
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); // Bind our frame buffer for rendering
glPushAttrib(GL_VIEWPORT_BIT | GL_ENABLE_BIT); // Push our glEnable and glViewport states
}
#endif
//glClearColor(0, 0, 0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity ();
gluLookAt(transform->position.x,
transform->position.y,
transform->position.z,
transform->position.x + transform->direction().x,
transform->position.y + transform->direction().y,
transform->position.z + transform->direction().z,
0.0,
1.0,
0.0);
if(_onRender.size() > 0)
for(auto _rn : _onRender){
_rn();
}
#ifdef EDITOR
glPopAttrib(); // Restore our glEnable and glViewport states
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // Unbind our texture
#else
if(NukeOGL::getSingleton() != this){
glPopAttrib(); // Restore our glEnable and glViewport states
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // Unbind our texture
}
#endif
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if(_onGUI.size() > 0)
for(auto _rn : _onGUI){
_rn();
}
glutSwapBuffers();
//glutPostRedisplay();
return 0;
}
What I am doing wrong? What I should do to make it right scale from local to world space?
Scale and rotation are linear transformations, their effects are relative to distance to origin of coordinates system. You must apply them in a proper order and with a proper origin each.
I explain in 2D so it's easier to understand.
Say you have a rectangle of size axb, whose center is at {cx,cy} and you want to scale and rotate (in this order). Then you first translate to {0,0} then scale, then rotate, then translate it back to {cx,cy}. Since each transformation is defined by a matrix, and usually OpenGL matrices are defined in column-mayor order, the composed matrix for this object may be:
MObj_i = MObj_i_trans(cx,cy) * MObj_i_rot(cangle, caxis) * MObj_i_sca(cfactor) * MObj_i_trans(-cx,-cy)
After you do those transformations for each object (with its own center/scale/rotation each) you want a "global" scale and rotation. Again you need a center of scale/rotation:
MGlobal = MGlo_trans(gx,gy) * MGlo_rot(gangle, gaxis) * MGlo_sca(gfactor) * MGlo_trans(-gx,-gy)
Usually the world center is `{0,0}' so you can avoid translations:
MGlobal = MGlo_rot(gangle, gaxis) * MGlo_sca(gfactor)
The good news is that the transformations can be combined into an only matrix. So, for each object, you apply the matrix:
MObjec_i = MGlobal * MObj_i
If you use glm for these maths, don't forget to inializate an Identity matrix:
glm::mat4 objScale(1.0);
objScale(objScale, vec3(fx, fy, fz));
glm::mat4 objRotate(1.0);
objRotate(objRotate, angle, vec3(axis.x, axis.y, axis.z));
etc.
hello I am using glut and opengl with c++ , I have home I want to draw blue QUADS in it my problem when I draw the QUADS all the sense color in blue , so how I can to color only QUADS in blue color and Prevents to color all sense in blue color what I do wrong how to remove the blue color from all the sense and color only my QUAD?
my try:
void drawSquare1()
{
glBegin(GL_QUADS);
glColor3d(1,0,0);
glVertex3f(-0.5,-0.5,-0.5);
glColor3d(1,1,0);
glVertex3f(0.5,-0.5,-0.5);
glColor3d(1,1,1);
glVertex3f(0.5,0.5,-0.5);
glColor3d(0,1,1);
glVertex3f(-0.5,0.5,-0.5);
glEnd();
}
void render(void) // Our Rendering Is Done Here
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity(); // Reset The View
GLfloat xtrans = -g_xpos;
GLfloat ztrans = -g_zpos;
GLfloat ytrans = -g_ypos;
if(g_yrot > 360)
g_yrot -= 360;
else if(g_yrot < 0)
g_yrot += 360;
GLfloat sceneroty = (360.0f - g_yrot);
int numpolygons;
glRotatef(g_lookupdown,1.0f,0,0);
glRotatef(sceneroty,0,1.0f,0);
glTranslatef(xtrans, ytrans, ztrans);
numpolygons = g_sector1.numpolygons;
for (int loop_m = 0; loop_m < numpolygons; loop_m++)
texture_object(loop_m);
gluQuadricDrawStyle(my_shape[0],GLU_FILL);
glBindTexture(GL_TEXTURE_2D, textures[1].texID);
glScalef(0.1,0.1,0.1);
glTranslatef(0.78,14.3,-4.2);
gluSphere(my_shape[0], 1.0,50,50);
gluQuadricDrawStyle(my_shape[1],GLU_FILL);
glBindTexture(GL_TEXTURE_2D, textures[8].texID);
glTranslatef(-20,0,0);
gluSphere(my_shape[1], 1.0,50,50);
gluQuadricDrawStyle(my_shape[2],GLU_FILL);
glBindTexture(GL_TEXTURE_2D, textures[22].texID);
glTranslatef(40,0,0);
gluSphere(my_shape[2], 1.0,50,50);
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glPushMatrix(); // Store The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
glOrtho(-10,window_width,0,window_height,-10,10); // Set Up An Ortho Screen
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
drawSquare1();
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glPopMatrix(); // Restore The Old Projection Matrix
//glPushMatrix();
drawSquare1();
//glPopMatrix();
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glutSwapBuffers ( );
}
int main(int argc, char** argv) // Main Function For Bringing It All Together.
{
//cout << "Hello World!" << endl;
//cin.get();
glutInit(&argc, argv); // GLUT Initializtion
glutInitDisplayMode(GLUT_DEPTH | GLUT_RGBA | GLUT_DOUBLE); // (CHANGED)
if (g_gamemode)
{
glutGameModeString("640x480:16"); // Select The 640x480 In 16bpp Mode
if (glutGameModeGet(GLUT_GAME_MODE_POSSIBLE))
glutEnterGameMode(); // Enter Full Screen
else g_gamemode = false; // Cannot Enter Game Mode, Switch To Windowed
}
screen_width = glutGet(GLUT_SCREEN_WIDTH);
screen_height = glutGet(GLUT_SCREEN_HEIGHT);
window_width = screen_width/1.4;
window_height = screen_height/1.4;
if (!g_gamemode)
{
glutInitWindowSize(window_width,window_height); // Window Size If We Start In Windowed Mode
glutInitWindowPosition((screen_width-window_width)/2,(screen_height-window_height)/2);
glutCreateWindow("Frank's 3-D House"); // Window Title
}
init();
glutIgnoreKeyRepeat(true); // Disable Auto Repeat (NEW)
// glutKeyboardFunc(myKey); // register the key handler.
glutDisplayFunc(render); // Register The Display Function
glutReshapeFunc(reshape); // Register The Reshape Handler
glutKeyboardFunc(keyboard); // Register The Keyboard Handler
//glRasterPos2f(lineMargin, currentHight); // set the cursor to the initial position.
glutSpecialFunc(special_keys); // Register Special Keys Handler
glutSpecialUpFunc(special_keys_up); // Called When A Special Key Released (NEW)
glutIdleFunc(game_function); // Process User Input And Does Rendering (CHANGED)
glutMouseFunc(mouse) ;
glutMainLoop(); // Go To GLUT Main Loop
return 0;
}
and this picture of run my code:
By default the texture environment mode (GL_TEXTURE_ENV_MODE) is GL_MODULATE. See glTexEnv.
This means if texturing is enabled (glEnable(GL_TEXTURE_2D)), then the color from the texture is multiplied by the color which is currently set by glColor.
To fix your issue, I recommend to set glColor4f(1.0f,1.0f,1.0f,1.0f); before the geometry is drawn:
void render(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
.....
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
for (int loop_m = 0; loop_m < numpolygons; loop_m++)
texture_object(loop_m);
.....
}
Note, the current color is changed in the function drawSquare1 and keeps its state.
Here's the vertex buffer information of the quad I'm drawing:
static const GLfloat pv_quad[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
-1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
};
This quad is used to draw 2D frames on the screen as part of the graphical user interface. The class I use to do this is Mage::Interface::Frame. I'll spare you the header definition and instead give you the class's implementation, as it's small. There's some test code in here, so ignore the fact the shader is part of the class. I know it shouldn't be there.
#include <Mage/Root.h>
#include <Mage/Interface/Frame.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
using Mage::Interface::Frame;
Frame::Frame()
: width(300), height(200), position(0, 0), color(1.0, 1.0, 1.0), model(1.0), rotation(0) {
prog.compileFile("Data/Shaders/FrameVertex.glsl", Mage::ShaderType::VERTEX);
prog.compileFile("Data/Shaders/FrameFragment.glsl", Mage::ShaderType::FRAGMENT);
prog.link();
this->calcTransform();
}
void Frame::setSize(int w, int h) {
this->width = w;
this->height = h;
this->calcTransform();
}
void Frame::setColor(int r, int g, int b) {
this->color = glm::vec3(float(r) / 256, float(g) / 256, float(b) / 256);
}
void Frame::setRotation(float degrees) {
this->rotation = glm::radians(degrees);
this->calcTransform();
}
void Frame::calcTransform() {
this->model = glm::mat4(1.0f); // reset model to origin.
// 1280 and 720 are the viewport's size. This is only hard coded for tests.
this->model = glm::scale(this->model, glm::vec3(float(width) / 1280, float(height) / 720, 1.0f));
this->model = glm::rotate(this->model, this->rotation, glm::vec3(0.0f, 0.0f, 1.0f));
this->model = glm::translate(this->model, glm::vec3(position.x, position.y, 0.0f));
}
void Frame::draw() {
Mage::VertexObject obj = ROOT.getRenderWindow()->getVertexBufferObject()->getObject("PrimitiveQuad");
prog.use();
prog.setUniform("mvp", this->model);
prog.setUniform("fColor", this->color);
glEnableVertexAttribArray(0);
ROOT.getRenderWindow()->getVertexBufferObject()->bind();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)obj.begin);
glDrawArrays(GL_TRIANGLE_STRIP, 0, obj.size);
glDisableVertexAttribArray(0);
}
Here's the drawing function that's called every frame:
void RenderWindow::render() {
Mage::Interface::Frame F;
F.setSize(400, 200);
F.setRotation(0);
while (glfwWindowShouldClose(this->win) == 0) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
F.draw();
glfwSwapBuffers(this->win);
glfwPollEvents();
}
}
When I have setRotation(0), the resulting quad is indeed, 400 pixels wide and 200 pixels high, right in the centre of my screen as you would expect.
However, if I set the rotation to (90), well, this happens:
As you can see, that's not at all close to a 90 degrees turn. It should be 400px high and 200px wide.
Anyone care to explain what's going on here?
EDIT: Some playing around has shown me that the problem is with the scale, not the rotation. When I comment out the scale, the rotation appears to be correct.
The angle argument to glm::rotate() is in radians, not degrees:
m: Input matrix multiplied by this rotation matrix.
angle: Rotation angle expressed in radians.
axis: Rotation axis, recommanded [sic] to be normalized.
Use this:
void Frame::setRotation(float degrees) {
this->rotation = glm::radians( degrees );
this->calcTransform();
}
I am assuming that this game is supposed to be a 3D game with a 2D GUI, although this was not specified in the question, though not entirely necessary, as my answer will be the same.
When rendering with a 3D matrix, using a perspective view (Field of View taken into account), as opposed to using an orthographic view, the shapes will bend to their position depending on the fov.
So with that, I propose that you use a simple solution, and initialize a 2D viewing matrix (or orthographic matrix) for your 2D interface. If you are just looking for a simple way to render a 2D quad onto the screen freeGLUT(free Graphics Library Utility Toolkit) is there for you. There are plenty of docs out there to help install freeglut, so once you finish that, initialize a 2D rendering matrix, then render the quad using glVertex2i/f or glVertex3i/f, like so:
void setView2d()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, *SCREEN_WIDTH, *SCREEN_HEIGHT, 0);
glMatrixMode( GL_MODELVIEW );
glDisable(GL_DEPTH_TEST);
glLoadIdentity();
}
void setView3d()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(70, (GL_FLOAT)*SCREEN_WIDTH / *SCREEN_HEIGHT, 0.1, 100);
glEnable(GL_DEPTH_TEST);
glLoadIdentity();
}
void render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_TEST);
setView2d(); //Render 2D objects
glPushMatrix();
{
//glTranslatef() and glRotatef() still work for 2D
//if using rotate, rotate on z axis, like so:
glRotatef(90, 0, 0, 1);
glBegin(GL_TRIANGLES);
{
glVertex2i(0, 0);
glVertex2i(100, 0);
glVertex2i(0, 100);
/*
glVertex2i is replacable with glVertex2f, glVertex3i, and glVertex3f
if using a glVertex3, set the z value to 0
*/
}
glEnd();
}
glPopMatrix();
setView3d(); //Render 3D objects
glPushMatrix();
{
//render 3D stuff
}
glPopMatrix();
glutSwapBuffers();
}
I should also mention that when using the gluOrtho2D, coordinates used in vertex x,y are based on pixels, instead of the 3D blocks.
Hope this helped,
-Nick
I need to draw a cube and project it with the default projection matrix. Also, I want to draw a hud controlling the orientation of the sphere. The hud is projected with another projection matrix.
render()
{
DrawGUI(); // project GUI with another projection matrix
glPushMatrix();
glutSolidCube(); // project the cube with the default projection matrix
glPopMatrix();
glutSwapBuffers();
}
reshape()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(...);
...
}
DrawGUI()
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(...); // project the GUI with this matrix
glMatrixMode(GL_MODELVEIW);
glPushMatrix();
glLoadIdentity();
glBegin();
//... drawing GUI
glEnd();
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
#define BUFFER_LENGTH 64
void processSelection(int xPos, int yPos)
{
static GLuint selectBuff[BUFFER_LENGTH];
GLint hits, viewport[4];
glSelectBuffer(BUFFER_LENGTH, selectBuff);
glGetIntegerv(GL_VIEWPORT, viewport);
// Switch to projection and save the matrix
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glRenderMode(GL_SELECT);
glLoadIdentity();
gluPickMatrix(xPos, viewport[3] - yPos, 2,2, viewport);
glOrtho (-100, 100, -100, 100, -100, 100); // this line of code is the most
glMatrixMode(GL_MODELVIEW);
render();
hits = glRenderMode(GL_RENDER);
//...process hits
// Restore the projection matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
The render part works well. Both the GUI and the cube are drawn without problem. However, the selection does not work as intended.
My question is: Since I project 3D models with different projection matrix, how should I deal with selection? I try to implement the typical selection buffer approach, but every time I click in the window, the selection buffer always contains the GUI even if I do not click on the GUI. Also, if I click on the cube, the selection buffer ends up with both the cube and the GUI.
If you use the selection buffer approach, you render with mixed projections as you do when doing the usual render. The only difference, is, that you apply that pick matrix as well. Also don't try to be too clever with the matrix pushing / poping. It rarely makes sense to use that in the projection matrix stack (hence it requires to have only 2 push levels, instead of the 32 for the modelview). Also don't use the reshape function to define the projection matrix.
DrawCube()
{
glMatrixMode(GL_MODELVEIW);
glLoadIdentity();
glutSolidCube();
}
DrawGUI()
{
glMatrixMode(GL_MODELVEIW);
glLoadIdentity();
glBegin();
//... drawing GUI
glEnd();
}
void render()
{
// base the projection on whats already in the projection
// matrix stack. For normal render this is identity, for
// selection it is a pick matrix.
glMatrixMode(GL_PROJECTION);
glPushMatrix();
gluOrtho2D(...); // project the GUI with this matrix
DrawGUI();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
gluPerspective(...);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
void display()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
render();
glutSwapBuffers();
}
#define BUFFER_LENGTH 64
void select(int xPos, int yPos)
{
static GLuint selectBuff[BUFFER_LENGTH];
GLint hits, viewport[4];
glSelectBuffer(BUFFER_LENGTH, selectBuff);
glGetIntegerv(GL_VIEWPORT, viewport);
// Switch to projection and augment it with a picking matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPickMatrix(xPos, viewport[3] - yPos, 2,2, viewport);
glRenderMode(GL_SELECT);
render();
hits = glRenderMode(GL_RENDER);
//...process hits
}
Note that OpenGL selection mode is usually not GPU accelerated and hence very slow. Also it's been deprecated and removed from modern OpenGL versions. It's highly recommended to use either index buffer selection (i.e. render each object with a dedicated index "color") or perform manual ray-intersection picking into the scene data.
I'm going to show FPS on the screen with the freeglut function glutBitmapString,but it shows nothing. Here is my code. Is there anyone can figure where the problem is?
void PrintFPS()
{
frame++;
time=glutGet(GLUT_ELAPSED_TIME);
if (time - timebase > 100) {
cout << "FPS:\t"<<frame*1000.0/(time-timebase)<<endl;
char* out = new char[30];
sprintf(out,"FPS:%4.2f",frame*1000.0f/(time-timebase));
glColor3f(1.0f,1.0f,1.0f);
glRasterPos2f(20,20);
glutBitmapString(GLUT_BITMAP_TIMES_ROMAN_24,(unsigned char* )out);
timebase = time;
frame = 0;
}
}
void RenderScene(void)
{
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
GLfloat vRed[] = { 1.0f, 0.0f, 0.0f, 0.5f };
GLfloat vYellow[] = {1.0f,1.0f,0.0f,1.0f};
shaderManager.UseStockShader(GLT_SHADER_IDENTITY, vYellow);
//triangleBatch.Draw();
squareBatch.Draw();
PrintFPS();
glutSwapBuffers();
}
it supposed to show the FPS on the top left of the screen
The position that's provided by glRasterPos is treated just like a vertex, and transformed by the current model-view and projection matrices. In you example, you specify the text to be position at (20,20), which I'm guessing is supposed to be screen (viewport, really) coordinates.
If it's the case that you're rendering 3D geometry, particularly with a perspective projection, your text may be clipped out. However, there are (at least) two simple solutions (presented in order of code simplicity):
use one of the glWindowPos functions instead of glRasterPos. This function bypasses the model-view and projection transformations.
use glMatrixMode, glPushMatrix, and glPopMatrix to temporarily switch to window coordinates for rendering:
// Switch to window coordinates to render
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glLoadIdentity();
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
gluOrtho2D( 0, windowWidth, 0, windowHeight );
glRasterPos2i( 20, 20 ); // or wherever in window coordinates
glutBitmapString( ... );
glPopMatrix();
glMatrixMode( GL_MODELVIEW );
glPopMatrix();