Sign in to follow this  
nippysaurus

OpenGL picking ... always nothing selected

Recommended Posts

nippysaurus    128
I have a simple opengl scene with some boxes ... I am using glut ... I have given the boxes names. I dont know what else you would need to know to help me, but I have implemented some picking code from various sites, never gives any errors but the items I have given names to, when clicked, still gives no results. I am going to just paste all my code just to make sure that nothing is missed. Any help would be greatly appreciated.
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h> // Header File For The GLUT Library 
#include <GL/gl.h>	 // Header File For The OpenGL32 Library
#include <GL/glu.h>	 // Header File For The GLu32 Library

#define DEBUG

#ifdef DEBUG
#define debugmsg(msg) {printf("DEBUG:%s\n",msg);}
#else
#define debugmsg(msg) {}
#endif

#define DEFAULT_WIDTH 800
#define DEFAULT_HEIGHT 600
#define LEFT (0-(WIDTH/2))
#define RIGHT (WIDTH/2)
#define TOP (HEIGHT/2)
#define BOTTOM (0-(HEIGHT/2))

//#define WIREFRAME

#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4
#define FIVE 5
#define SIX 6
#define SEVEN 7
#define EIGHT 8

float r = 0.0f;
float m = 0.0f;

bool MouseLeftDown = false;
bool MouseRightDown = false;

unsigned int width = DEFAULT_WIDTH;
unsigned int height = DEFAULT_HEIGHT;

#define BUFSIZE 512
GLuint selectBuf[BUFSIZE];

// =============================================================================
// Cube.
// =============================================================================
class Cube
{
    private:
        float _wl;  // Width/Length!
        float _left,_right,_top,_bottom,_front,_back;
    public:
        Cube(float wl)
        {
            _wl = wl;
            _right = _top = _front = _wl / 2;
            _left = _bottom = _back = -_right;
        }
        void Draw()
        {
            glColor3f(1.0f, 0.0f, 0.0f);
            glBegin(GL_QUADS);
            glVertex3f(_left, _top, _front);    // FRONT
            glVertex3f(_left, _bottom, _front);
            glVertex3f(_right, _bottom, _front);
            glVertex3f(_right, _top, _front);
            glVertex3f(_left, _top, _back);     // BACK
            glVertex3f(_right, _top, _back);
            glVertex3f(_right, _bottom, _back);
            glVertex3f(_left, _bottom, _back);
            glVertex3f(_left, _top, _front);    // TOP
            glVertex3f(_right, _top, _front);
            glVertex3f(_right, _top, _back);
            glVertex3f(_left, _top, _back);
            glVertex3f(_left, _bottom, _front); // BOTTOM
            glVertex3f(_left, _bottom, _back);
            glVertex3f(_right, _bottom, _back);
            glVertex3f(_right, _bottom, _front);
            glVertex3f(_left, _bottom, _back);  // LEFT
            glVertex3f(_left, _bottom, _front);
            glVertex3f(_left, _top, _front);
            glVertex3f(_left, _top, _back);
            glVertex3f(_right, _bottom, _front);  // RIGHT
            glVertex3f(_right, _bottom, _back);
            glVertex3f(_right, _top, _back);
            glVertex3f(_right, _top, _front);
            glEnd();
        }
};

// =============================================================================
// Drawaxis.
// =============================================================================
void DrawAxis()
{
    #define AXISLINELENGTH 0.25f

    // X
    glColor3f(1.0f, 0.0f, 0.0f);
    glBegin(GL_LINES);
    glVertex3f(0.0f, 0.0f, 0.0f);
    glVertex3f(AXISLINELENGTH, 0.0f, 0.0f);
    glEnd();
    glRasterPos3f(AXISLINELENGTH, 0.0f, 0.0f);
    glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, 'X');

    // Y
    glColor3f(0.0f, 1.0f, 0.0f);
    glBegin(GL_LINES);
    glVertex3f(0.0f, 0.0f, 0.0f);
    glVertex3f(0.0f, AXISLINELENGTH, 0.0f);
    glEnd();
    glRasterPos3f(0.0f, AXISLINELENGTH, 0.0f);
    glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, 'Y');

    // Z
    glColor3f(0.0f, 0.0f, 1.0f);
    glBegin(GL_LINES);
    glVertex3f(0.0f, 0.0f, 0.0f);
    glVertex3f(0.0f, 0.0f, AXISLINELENGTH);
    glEnd();
    glRasterPos3f(0.0f, 0.0f, AXISLINELENGTH);
    glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, 'Z');
}

// =============================================================================
// Start Ortho.
// =============================================================================
void StartOrtho(void)
{
	glMatrixMode(GL_PROJECTION);    // Select Projection
	glPushMatrix();                 // Push The Matrix
	glLoadIdentity();               // Reset The Matrix
	glOrtho(0,width,height,0,-1,1); // Select Ortho Mode
	glMatrixMode(GL_MODELVIEW);     // Select Modelview Matrix
	glPushMatrix();                 // Push The Matrix
	glLoadIdentity();               // Reset The Matrix
}

// =============================================================================
// End Ortho.
// =============================================================================
void EndOrtho(void)
{
	glMatrixMode(GL_PROJECTION);    // Select Projection
	glPopMatrix();                  // Pop The Matrix
	glMatrixMode(GL_MODELVIEW);     // Select Modelview
	glPopMatrix();                  // Pop The Matrix
}

// =============================================================================
// Process Hits.
// =============================================================================
void processHits(int hits, unsigned int buffer[])
{
    debugmsg("processing hits");
    //
}

// =============================================================================
// Select.
// =============================================================================
void select(int x, int y)
{
    debugmsg("checking for hits");

	GLint viewport[4];

	glSelectBuffer(BUFSIZE,selectBuf);
	glRenderMode(GL_SELECT);

	glInitNames();
    glPushName(0);

	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	glGetIntegerv(GL_VIEWPORT,viewport);
	gluPickMatrix(x,viewport[3]-y,5,5,viewport);
	gluPerspective(45,(1.0f*width/height),1.0f,100.0f);
	glMatrixMode(GL_MODELVIEW);

    int hits;
	
	// restoring the original projection matrix
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glFlush();
	
	// returning to normal rendering mode
	hits = glRenderMode(GL_RENDER);
	
	// if there are hits process them
	if (hits != 0)
		processHits(hits,selectBuf);

    debugmsg("finished checking for hits");
}

// =============================================================================
// Display.
// =============================================================================
void display(void)
{
    //glTranslatef(0.0f,0.0f,0.0f);
    //glRotatef(0.0f, 0.0f, 0.0f, 0.0f);
    //GL_POLYGON
    //GL_LINES
    //GL_QUADS

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glTranslatef(0.0f, 0.0f, -4.0f);

    {
        Cube* SmallCube = new Cube(0.3f);

        glPushMatrix();
        glTranslatef(0.5f, 0.5f, 0.5f);
        glPushName(ONE);
        SmallCube->Draw();
        glPopName();
        glPopMatrix();

        glPushMatrix();
        glTranslatef(0.5f, -0.5f, 0.5f);
        glPushName(TWO);
        SmallCube->Draw();
        glPopName();
        glPopMatrix();

        glPushMatrix();
        glTranslatef(-0.5f, -0.5f, 0.5f);
        glPushName(THREE);
        SmallCube->Draw();
        glPopName();
        glPopMatrix();

        glPushMatrix();
        glTranslatef(-0.5f, 0.5f, 0.5f);
        glPushName(FOUR);
        SmallCube->Draw();
        glPopName();
        glPopMatrix();

        glPushMatrix();
        glTranslatef(0.5f, 0.5f, -0.5f);
        glPushName(FIVE);
        SmallCube->Draw();
        glPopName();
        glPopMatrix();

        glPushMatrix();
        glTranslatef(0.5f, -0.5f, -0.5f);
        glPushName(SIX);
        SmallCube->Draw();
        glPopName();
        glPopMatrix();

        glPushMatrix();
        glTranslatef(-0.5f, -0.5f, -0.5f);
        glPushName(SEVEN);
        SmallCube->Draw();
        glPopName();
        glPopMatrix();

        glPushMatrix();
        glTranslatef(-0.5f, 0.5f, -0.5f);
        glPushName(EIGHT);
        SmallCube->Draw();
        glPopName();
        glPopMatrix();

        delete SmallCube;
    }

    DrawAxis();

    StartOrtho();

    glBegin(GL_QUADS);
    glVertex2f(10, 10);
    glVertex2f(10, height-10);
    glVertex2f(50, height-10);
    glVertex2f(50, 10);
    glEnd();

    EndOrtho();

    glutSwapBuffers();
}

// =============================================================================
// Keyboard.
// =============================================================================
void keyboard(unsigned char key, int x, int y)
{
    if( key == 'q' || key == 'Q') exit(0);
}

int MouseX = -1;
int MouseY = -1;

// =============================================================================
// Mousemove.
// =============================================================================
void mousemove(int x, int y)
{
    //int DiffX = x - MouseX;
    //int DiffY = y - MouseY;

    if (MouseLeftDown && MouseRightDown)
    {
        //
    }
    else if (MouseLeftDown)
    {
        //
    }
    else if (MouseRightDown)
    {
        //
    }

    MouseX = x;
    MouseY = y;
}

// =============================================================================
// Mouseclick.
// =============================================================================
void mouseclick(int button, int state, int x, int y)
{
    // button can be:
    // GLUT_LEFT_BUTTON
    // GLUT_MIDDLE_BUTTON
    // GLUT_RIGHT_BUTTON

    // state can be:
    // GLUT_DOWN
    // GLUT_UP

    // compatibility with original GLUT
    #if !defined(GLUT_WHEEL_UP)
    #  define GLUT_WHEEL_UP   3
    #  define GLUT_WHEEL_DOWN 4
    #endif

    if (state == GLUT_DOWN)
        select(x,y);

    switch(button) {
        case GLUT_LEFT_BUTTON:
            MouseLeftDown = ((state==GLUT_DOWN) ? true : false);
            break;
        case GLUT_MIDDLE_BUTTON:
            break;
        case GLUT_RIGHT_BUTTON:
            MouseRightDown = ((state==GLUT_DOWN) ? true : false);
            break;
        case GLUT_WHEEL_UP:
            break;
        case GLUT_WHEEL_DOWN:
            break;
    }

    MouseX = x;
    MouseY = y;
}

// =============================================================================
// Init.
// =============================================================================
void  init(void)
{
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
    glEnable(GL_CULL_FACE);

	glClearDepth(1.0f);

    #ifdef WIREFRAME
        glPolygonMode(GL_FRONT,GL_LINE);
    #else
        glPolygonMode(GL_FRONT,GL_FILL);
    #endif

    glInitNames();
}

// =============================================================================
// Resize.
// =============================================================================
void resize(int w, int h)

{
    width = w;
    height = h;


	glMatrixMode(GL_PROJECTION);

	glLoadIdentity();

	glViewport(0, 0, width, height);

	gluPerspective(45.0f, 1.0f * width / height, 1.0f, 100.0f);


	glMatrixMode(GL_MODELVIEW);

	glLoadIdentity();

}

// =============================================================================
// Entry.
// =============================================================================
int main(int argc, char* argv[])
{
    debugmsg("creating window");

    // Create window.
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowSize(width, height);
    glutCreateWindow("Seen");

    debugmsg("doing init");

    init();

    debugmsg("event loop functions");

    // Event loop functions.
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutKeyboardFunc(keyboard);
    glutReshapeFunc(resize);
    glutMotionFunc(mousemove);
    glutMouseFunc(mouseclick);

    debugmsg("starting main loop");

    // Start event loop.
    glutMainLoop();

    return 0;
}

Share this post


Link to post
Share on other sites
Brother Bob    10344
You're not getting any hits because you're not drawing anything in your select function. You enter selection mode, set up the matrices, restore them and go back to render mode. The missing third step should be to draw everything so the selection mechanism actually gets something to perform selection on.

Share this post


Link to post
Share on other sites
nippysaurus    128
Thanks Brother Bob :)

It works now ... but it is not well implemented because in my display function I switch to ortho mode to display some UI stuff ... and I am sure that because of that there is ALWAYS one item in the picking list. I need to split the functions up so that the pickable objects can be drawn in a single function :)

Thank you for your help :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By markshaw001
      Hi i am new to this forum  i wanted to ask for help from all of you i want to generate real time terrain using a 32 bit heightmap i am good at c++ and have started learning Opengl as i am very interested in making landscapes in opengl i have looked around the internet for help about this topic but i am not getting the hang of the concepts and what they are doing can some here suggests me some good resources for making terrain engine please for example like tutorials,books etc so that i can understand the whole concept of terrain generation.
       
    • By KarimIO
      Hey guys. I'm trying to get my application to work on my Nvidia GTX 970 desktop. It currently works on my Intel HD 3000 laptop, but on the desktop, every bind textures specifically from framebuffers, I get half a second of lag. This is done 4 times as I have three RGBA textures and one depth 32F buffer. I tried to use debugging software for the first time - RenderDoc only shows SwapBuffers() and no OGL calls, while Nvidia Nsight crashes upon execution, so neither are helpful. Without binding it runs regularly. This does not happen with non-framebuffer binds.
      GLFramebuffer::GLFramebuffer(FramebufferCreateInfo createInfo) { glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); textures = new GLuint[createInfo.numColorTargets]; glGenTextures(createInfo.numColorTargets, textures); GLenum *DrawBuffers = new GLenum[createInfo.numColorTargets]; for (uint32_t i = 0; i < createInfo.numColorTargets; i++) { glBindTexture(GL_TEXTURE_2D, textures[i]); GLint internalFormat; GLenum format; TranslateFormats(createInfo.colorFormats[i], format, internalFormat); // returns GL_RGBA and GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, createInfo.width, createInfo.height, 0, format, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); DrawBuffers[i] = GL_COLOR_ATTACHMENT0 + i; glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, textures[i], 0); } if (createInfo.depthFormat != FORMAT_DEPTH_NONE) { GLenum depthFormat; switch (createInfo.depthFormat) { case FORMAT_DEPTH_16: depthFormat = GL_DEPTH_COMPONENT16; break; case FORMAT_DEPTH_24: depthFormat = GL_DEPTH_COMPONENT24; break; case FORMAT_DEPTH_32: depthFormat = GL_DEPTH_COMPONENT32; break; case FORMAT_DEPTH_24_STENCIL_8: depthFormat = GL_DEPTH24_STENCIL8; break; case FORMAT_DEPTH_32_STENCIL_8: depthFormat = GL_DEPTH32F_STENCIL8; break; } glGenTextures(1, &depthrenderbuffer); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); glTexImage2D(GL_TEXTURE_2D, 0, depthFormat, createInfo.width, createInfo.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthrenderbuffer, 0); } if (createInfo.numColorTargets > 0) glDrawBuffers(createInfo.numColorTargets, DrawBuffers); else glDrawBuffer(GL_NONE); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer Incomplete\n"; glBindFramebuffer(GL_FRAMEBUFFER, 0); width = createInfo.width; height = createInfo.height; } // ... // FBO Creation FramebufferCreateInfo gbufferCI; gbufferCI.colorFormats = gbufferCFs.data(); gbufferCI.depthFormat = FORMAT_DEPTH_32; gbufferCI.numColorTargets = gbufferCFs.size(); gbufferCI.width = engine.settings.resolutionX; gbufferCI.height = engine.settings.resolutionY; gbufferCI.renderPass = nullptr; gbuffer = graphicsWrapper->CreateFramebuffer(gbufferCI); // Bind glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); // Draw here... // Bind to textures glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textures[2]); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); Here is an extract of my code. I can't think of anything else to include. I've really been butting my head into a wall trying to think of a reason but I can think of none and all my research yields nothing. Thanks in advance!
    • By Adrianensis
      Hi everyone, I've shared my 2D Game Engine source code. It's the result of 4 years working on it (and I still continue improving features ) and I want to share with the community. You can see some videos on youtube and some demo gifs on my twitter account.
      This Engine has been developed as End-of-Degree Project and it is coded in Javascript, WebGL and GLSL. The engine is written from scratch.
      This is not a professional engine but it's for learning purposes, so anyone can review the code an learn basis about graphics, physics or game engine architecture. Source code on this GitHub repository.
      I'm available for a good conversation about Game Engine / Graphics Programming
    • By C0dR
      I would like to introduce the first version of my physically based camera rendering library, written in C++, called PhysiCam.
      Physicam is an open source OpenGL C++ library, which provides physically based camera rendering and parameters. It is based on OpenGL and designed to be used as either static library or dynamic library and can be integrated in existing applications.
       
      The following features are implemented:
      Physically based sensor and focal length calculation Autoexposure Manual exposure Lense distortion Bloom (influenced by ISO, Shutter Speed, Sensor type etc.) Bokeh (influenced by Aperture, Sensor type and focal length) Tonemapping  
      You can find the repository at https://github.com/0x2A/physicam
       
      I would be happy about feedback, suggestions or contributions.

    • By altay
      Hi folks,
      Imagine we have 8 different light sources in our scene and want dynamic shadow map for each of them. The question is how do we generate shadow maps? Do we render the scene for each to get the depth data? If so, how about performance? Do we deal with the performance issues just by applying general methods (e.g. frustum culling)?
      Thanks,
       
  • Popular Now