Thread: Multyple Keys in OpenGL - Freeglut

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    10

    Multyple Keys in OpenGL - Freeglut

    Sorry For My English. Anyone know how to process multyple key pressions in a game created with Freeglut??

    for example if i made a first person shooter, i have to process 2 arrows at the same time plus for example the spaceboard (if i'm jumping while fighting) and while i'm shooting enemies using the mouse + left or right mouse button.

    if it is not possibile doing this in freeglut. is it possibile with openGL commands without using glut intermediate??

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Dareltibus View Post
    if it is not possibile doing this in freeglut. is it possibile with openGL commands without using glut intermediate??
    It is not possible with glut, and openGL provides no user input handling at all.

    Pretty sure you will have to do some threaded, possibly system specific low level work for this. You have to deal with a key being down, but not yet up, in order to use it as a "modifier" for pressing the other key.

    Termcap may be the library you are looking for -- good luck.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Dec 2009
    Posts
    10
    but is Termcap related to key pressions?

    and it is available only in Linux Systems..

    there is in open GL or in glut something says

    KeyIsPressedDown =true/false?
    i need only to know if a key is down.
    Last edited by Dareltibus; 12-13-2009 at 04:34 PM.

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    IMO stay away from glut when dealing with opengl. Use SDL to setup the window and opengl, and use SDL to handle the input from keyboard/mouse aswell. You dont need to have threads running or any of that stuff. Use a buffer such as:
    bool keysDown[256]. Then when a key is pressed (detected through SDL) you set it to true, and when its not pressed any longer set it to false.

    In your UpdateGame you just check for the different keys and handle accordingly.

  5. #5
    Registered User
    Join Date
    Dec 2009
    Posts
    10
    Thanks. If i continue using "glut" graphics while using SDL to get keys there will be any error?

  6. #6
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    It may be possible, but I have never heard of it and IMO just use one or the other. OpenGL is very easy to get up and running under SDL (maybe not as easy as glut) so if you really want to get into it I suggest you move to SDL anyway.

  7. #7
    Registered User
    Join Date
    Dec 2009
    Posts
    10
    alternatively i have to found some way to read keyboard status... thanks.

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Dareltibus View Post
    Thanks. If i continue using "glut" graphics while using SDL to get keys there will be any error?
    You can't use glut and SDL at the same time. I have the opposite opinion from Shakti -- don't like SDL (it has too many ulterior priorities) and prefer glut, but SDL does handle keyboard events, whereas glut just has has the special keys.

    I did some quick digging and you can, in fact, use Xlib to handle keyboard events (key down, key up):

    Xlib Programming Manual: Event Handling Functions

    Unfortunately, Xlib is not for the faint of heart and suffers from an extreme lack of documentation and examples. It seems to have a ton of functions that would be very useful, except many of them require you to specify the window to work with, which makes sense. Only problem: I spent more than an hour online the other day trying to find out how you identify a given window, to no avail.

    However, it looks like you do not need to do that to use the event handling, since there is only one keyboard The "XCheckTypedEvent()" is probably a good place to start.

    You do need to establish a connection to the server, which is easy:
    Code:
    #include <stdio.h>
    #include <X11/Xlib.h>
    
    //compile -lX11
    
    int main() {
            Display *XDisplay = XOpenDisplay(NULL);
            if (!XDisplay) puts("no!");
            printf("%d %d\n", DisplayWidth(XDisplay,0), DisplayHeight(XDisplay,0));
    }
    Display *XDisplay, once open, is what you submit to the Xlib functions:
    Code:
    Bool XCheckTypedEvent(display, event_type, event_return);
    Looks like you will have to do some experimentation about what to use for "event_type" since these are not enumerated anywhere.

    You'll need to get comfy going thru /usr/include/X11 for this.

    There may be an easier way if there where a way to get the window. I'll post a question in the linux forum...hmm...I think it has to do with XQueryTree().

    If you're not up to all that, it is not too hard to switch over to SDL from glut. Remember, glu functions (such as gluLookAt) are part of GL. Only functions starting with glut (such as glutSolidSphere) are glut specific.
    Last edited by MK27; 12-13-2009 at 05:31 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    Registered User
    Join Date
    Dec 2009
    Posts
    10
    that seems much harder... but i will try this way.. thanks! ;-)

    Code:
     /*
       Simple Xlib application drawing a box in a window.
       gcc input.c -o output -lX11
     */
     
     #include <X11/Xlib.h>
     #include <stdio.h>
     #include <stdlib.h>
     #include <string.h>
     
     int main(void) {
       Display *d;
       Window w;
       XEvent e;
       char *msg = "Hello, World!";
       int s;
     
                            /* open connection with the server */
       d = XOpenDisplay(NULL);
       if (d == NULL) {
         fprintf(stderr, "Cannot open display\n");
         exit(1);
       }
     
       s = DefaultScreen(d);
     
                            /* create window */
       w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 200, 200, 1,
                               BlackPixel(d, s), WhitePixel(d, s));
     
                            /* select kind of events we are interested in */
       XSelectInput(d, w, ExposureMask | KeyPressMask);
     
                            /* map (show) the window */
       XMapWindow(d, w);
     
                            /* event loop */
       while (1) {
         XNextEvent(d, &e);
                            /* draw or redraw the window */
         if (e.type == Expose) {
           XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);
           XDrawString(d, w, DefaultGC(d, s), 50, 50, msg, strlen(msg));
         }
                            /* exit on key press */
         if (e.type == KeyPress)
           break;
       }
     
                            /* close connection to server */
       XCloseDisplay(d);
     
       return 0;
     }
    what i have to do is mind about

    Code:
    XSelectInput(d, w, ExposureMask | KeyPressMask);
    hoping that Xlib dont be in conflict with my glut program..

    it will work on windows vista?
    Last edited by Dareltibus; 12-13-2009 at 05:54 PM.

  10. #10
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Dareltibus View Post
    it will work on windows vista?
    Oh god no. Sorry -- Xlib is linux native. I always presume people who are using glut are on linux, which is silly.

    You are in luck tho. I just glanced at the Win API
    Keyboard Input
    and there are indeed functions for handling keyboard events, eg. GetKeyState.

    If you want to write something that is portable to both linux and windows doing this, you will have to use SDL -- that's one of it's major purposes (providing wide general cross-platform functionality).
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #11
    Registered User
    Join Date
    Oct 2006
    Posts
    250
    You can easily accomplish this using glut as follows:

    * Setup a variable which keeps track of whether a certain key has been pressed or not
    * Register callbacks for keypresses and keyreleases using 'glutKeyboardFunc', and 'glutKeyboardUpFunc'. In the callback registered through 'glutKeyboardFunc', you will set aforementioned variable to true. In the callback registered through 'glutKeyboardUpFunc', set the variable to false.
    * Somewhere in your application main loop you simply check the state of all the keys that you are interested in through the variables you created in the first step.

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by MWAAAHAAA View Post
    You can easily accomplish this using glut as follows:

    * Setup a variable which keeps track of whether a certain key has been pressed or not
    * Register callbacks for keypresses and keyreleases using 'glutKeyboardFunc', and 'glutKeyboardUpFunc'. In the callback registered through 'glutKeyboardFunc', you will set aforementioned variable to true. In the callback registered through 'glutKeyboardUpFunc', set the variable to false.
    * Somewhere in your application main loop you simply check the state of all the keys that you are interested in through the variables you created in the first step.
    Yeah, I was thinking about something like that. If you have the two keys pressed in the same frame, that's simultaneous. GLUT fires on key down, and it kill keep triggering as long as the key is down.

    Probably the easiest route.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #13
    Registered User
    Join Date
    Dec 2009
    Posts
    10
    So glut can manage multiple keypression cause it has a way to see if more than one key is Up or Down.

    Thanks to all now i'll have to try.

    EDIT. it seems very easy to use just looking the declaration in headers..

    Code:
    FGAPI void    FGAPIENTRY glutKeyboardUpFunc( void (* callback)( unsigned char, int, int ) );
    i expected that such func will work passing on "unsigend char" the code of key released..

    so i will set to 0 the var related to this key as MWAAAHAAA suggested...

    it seems a good way

    Code:
    #include <GL/glut.h>
    
    bool keystatus[256]={false};
    
    int main(){
    
        // code
        glutKeyboardFunc(keydown);
        glutKeyboardUpFunc(keyup);
        // code
    }
    Code:
    keydown(unsigned int k,int mx,int my){
    
        keysatus[k]=true;
    }
    
    
    keyup(unsigned int k,int mx,int my){
        keystatus[k]=false;
    
    }
    * Somewhere in your application main loop you simply check the state of all the keys that you are interested in through the variables you created in the first step.
    so in my rendering scene i put such control.. i don't know any other function called by MainLoop.


    I have to kiss someone..
    Last edited by Dareltibus; 12-17-2009 at 08:39 AM.

  14. #14
    Crazy Fool Perspective's Avatar
    Join Date
    Jan 2003
    Location
    Canada
    Posts
    2,640
    Quote Originally Posted by Dareltibus View Post
    So glut can manage multiple keypression cause it has a way


    i don't know any other function called by MainLoop.

    Have a look at this (inlined below).
    http://jeff.bagu.org/downloads/glut/EmptyGlut.cpp

    There's also a Makefile
    (*note, this website hasn't been updated in years.)

    Code:
    /*
     * This program is free software; you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation; either version 2 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     *
     *
     *
     * A Template for building OpenGL applications using GLUT
     *
     * Author: Perspective @ cprogramming.com
     * Date  : Jan, 2005
     *
     * Description: 
     *   This code initializes an OpenGL ready window
     * using GLUT.  Some of the most common callbacks
     * are registered to empty or minimal functions.
     *
     * This code is intended to be a quick starting point
     * when building GLUT applications.
     *
     ***********************************************************/
    
    //#include <windows.h>
    #include <iostream>
    #include <GL/glut.h>
    
    
    /* process menu option 'op' */
    void menu(int op) {
    
      switch(op) {
      case 'Q':
      case 'q':
        exit(0);
      }
    }
    
    /* executed when a regular key is pressed */
    void keyboardDown(unsigned char key, int x, int y) {
    
      switch(key) {
      case 'Q':
      case 'q':
      case  27:   // ESC
        exit(0);
      }
    }
    
    /* executed when a regular key is released */
    void keyboardUp(unsigned char key, int x, int y) {
    
    }
    
    /* executed when a special key is pressed */
    void keyboardSpecialDown(int k, int x, int y) {
    
    }
    
    /* executed when a special key is released */
    void keyboardSpecialUp(int k, int x, int y) {
    
    }
    
    /* reshaped window */
    void reshape(int width, int height) {
    
      GLfloat fieldOfView = 90.0f;
      glViewport (0, 0, (GLsizei) width, (GLsizei) height);
    
      glMatrixMode (GL_PROJECTION);
      glLoadIdentity();
      gluPerspective(fieldOfView, (GLfloat) width/(GLfloat) height, 0.1, 500.0);
    
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
    }
    
    /* executed when button 'button' is put into state 'state' at screen position ('x', 'y') */
    void mouseClick(int button, int state, int x, int y) {
    
    }
    
    /* executed when the mouse moves to position ('x', 'y') */
    void mouseMotion(int x, int y) {
    
    }
    
    /* render the scene */
    void draw() {
    
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
    
      /* render the scene here */
    
      glFlush();
      glutSwapBuffers();
    }
    
    /* executed when program is idle */
    void idle() { 
    
    }
    
    /* initialize OpenGL settings */
    void initGL(int width, int height) {
    
      reshape(width, height);
    
      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
      glClearDepth(1.0f);
    
      glEnable(GL_DEPTH_TEST);
      glDepthFunc(GL_LEQUAL);
    }
    
    /* initialize GLUT settings, register callbacks, enter main loop */
    int main(int argc, char** argv) {
      
      glutInit(&argc, argv);
    
      glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
      glutInitWindowSize(800, 600);
      glutInitWindowPosition(100, 100);
      glutCreateWindow("Perspective's GLUT Template");
    
      // register glut call backs
      glutKeyboardFunc(keyboardDown);
      glutKeyboardUpFunc(keyboardUp);
      glutSpecialFunc(keyboardSpecialDown);
      glutSpecialUpFunc(keyboardSpecialUp);
      glutMouseFunc(mouseClick);
      glutMotionFunc(mouseMotion);
      glutReshapeFunc(reshape);
      glutDisplayFunc(draw);  
      glutIdleFunc(idle);
      glutIgnoreKeyRepeat(true); // ignore keys held down
    
      // create a sub menu 
      int subMenu = glutCreateMenu(menu);
      glutAddMenuEntry("Do nothing", 0);
      glutAddMenuEntry("Really Quit", 'q');
    
      // create main "right click" menu
      glutCreateMenu(menu);
      glutAddSubMenu("Sub Menu", subMenu);
      glutAddMenuEntry("Quit", 'q');
      glutAttachMenu(GLUT_RIGHT_BUTTON);
    
      initGL(800, 600);
    
      glutMainLoop();
      return 0;
    }
    Formatted with CodeForm

  15. #15
    Registered User
    Join Date
    Dec 2009
    Posts
    10
    Quote Originally Posted by Perspective View Post
    Have a look at this (inlined below).
    http://jeff.bagu.org/downloads/glut/EmptyGlut.cpp

    There's also a Makefile
    (*note, this website hasn't been updated in years.)

    Code:
    /*
     * This program is free software; you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation; either version 2 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     *
     *
     *
     * A Template for building OpenGL applications using GLUT
     *
     * Author: Perspective @ cprogramming.com
     * Date  : Jan, 2005
     *
     * Description: 
     *   This code initializes an OpenGL ready window
     * using GLUT.  Some of the most common callbacks
     * are registered to empty or minimal functions.
     *
     * This code is intended to be a quick starting point
     * when building GLUT applications.
     *
     ***********************************************************/
    
    //#include <windows.h>
    #include <iostream>
    #include <GL/glut.h>
    
    
    /* process menu option 'op' */
    void menu(int op) {
    
      switch(op) {
      case 'Q':
      case 'q':
        exit(0);
      }
    }
    
    /* executed when a regular key is pressed */
    void keyboardDown(unsigned char key, int x, int y) {
    
      switch(key) {
      case 'Q':
      case 'q':
      case  27:   // ESC
        exit(0);
      }
    }
    
    /* executed when a regular key is released */
    void keyboardUp(unsigned char key, int x, int y) {
    
    }
    
    /* executed when a special key is pressed */
    void keyboardSpecialDown(int k, int x, int y) {
    
    }
    
    /* executed when a special key is released */
    void keyboardSpecialUp(int k, int x, int y) {
    
    }
    
    /* reshaped window */
    void reshape(int width, int height) {
    
      GLfloat fieldOfView = 90.0f;
      glViewport (0, 0, (GLsizei) width, (GLsizei) height);
    
      glMatrixMode (GL_PROJECTION);
      glLoadIdentity();
      gluPerspective(fieldOfView, (GLfloat) width/(GLfloat) height, 0.1, 500.0);
    
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
    }
    
    /* executed when button 'button' is put into state 'state' at screen position ('x', 'y') */
    void mouseClick(int button, int state, int x, int y) {
    
    }
    
    /* executed when the mouse moves to position ('x', 'y') */
    void mouseMotion(int x, int y) {
    
    }
    
    /* render the scene */
    void draw() {
    
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
    
      /* render the scene here */
    
      glFlush();
      glutSwapBuffers();
    }
    
    /* executed when program is idle */
    void idle() { 
    
    }
    
    /* initialize OpenGL settings */
    void initGL(int width, int height) {
    
      reshape(width, height);
    
      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
      glClearDepth(1.0f);
    
      glEnable(GL_DEPTH_TEST);
      glDepthFunc(GL_LEQUAL);
    }
    
    /* initialize GLUT settings, register callbacks, enter main loop */
    int main(int argc, char** argv) {
      
      glutInit(&argc, argv);
    
      glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
      glutInitWindowSize(800, 600);
      glutInitWindowPosition(100, 100);
      glutCreateWindow("Perspective's GLUT Template");
    
      // register glut call backs
      glutKeyboardFunc(keyboardDown);
      glutKeyboardUpFunc(keyboardUp);
      glutSpecialFunc(keyboardSpecialDown);
      glutSpecialUpFunc(keyboardSpecialUp);
      glutMouseFunc(mouseClick);
      glutMotionFunc(mouseMotion);
      glutReshapeFunc(reshape);
      glutDisplayFunc(draw);  
      glutIdleFunc(idle);
      glutIgnoreKeyRepeat(true); // ignore keys held down
    
      // create a sub menu 
      int subMenu = glutCreateMenu(menu);
      glutAddMenuEntry("Do nothing", 0);
      glutAddMenuEntry("Really Quit", 'q');
    
      // create main "right click" menu
      glutCreateMenu(menu);
      glutAddSubMenu("Sub Menu", subMenu);
      glutAddMenuEntry("Quit", 'q');
      glutAttachMenu(GLUT_RIGHT_BUTTON);
    
      initGL(800, 600);
    
      glutMainLoop();
      return 0;
    }
    Formatted with CodeForm
    seems interesting. these are all functions called by mainloop so..
    Last edited by Dareltibus; 12-18-2009 at 06:19 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linking OpenGL in Dev-C++
    By linkofazeroth in forum Game Programming
    Replies: 4
    Last Post: 09-13-2005, 10:17 AM
  2. OpenGL Window
    By Morgul in forum Game Programming
    Replies: 1
    Last Post: 05-15-2005, 12:34 PM
  3. Replies: 0
    Last Post: 12-08-2003, 11:40 PM
  4. OpenGL .dll vs video card dll
    By Silvercord in forum Game Programming
    Replies: 14
    Last Post: 02-12-2003, 07:57 PM
  5. opengl code not working
    By Unregistered in forum Windows Programming
    Replies: 4
    Last Post: 02-14-2002, 10:01 PM