Pausing a c++ GLUT program with keyboard entry - c++

I am trying to pause my GLUT program during its execution by pressing a key on the keyboard. It seems to not recognize my entry. Here are the relevant sections of my code:
static bool paused = false;
void handleKeypress(unsigned char key, //The key that was pressed
int x, int y) { //The current mouse coordinates
switch (key) {
case 27: //Escape key
exit(0); //Exit the program
case 'p':
paused = !paused;
break;
}
}
int main(int argc, char** argv) {
//Initialize GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(600, 400); //Set the window size
//Create the window
glutCreateWindow("Fractals in Motion");
initRendering(); //Initialize rendering
//Set handler functions for drawing, keypresses, and window resizes
if(!paused)
{
glutDisplayFunc(drawScene); //drawScene draws everything does the real work
glutTimerFunc(10, update, 0); //Add a timer
}
//glutKeyboardFunc(handleKeypress);
glutReshapeFunc(handleResize);
glutMainLoop(); //Start the main loop. glutMainLoop doesn't return.
return 0; //This line is never reached
}
I actually got the skeleton of this code from this very will written tutorial:
http://www.videotutorialsrock.com/opengl_tutorial/basic_shapes/home.php
However, I cannot seem to get the program to pause when I press the 'p' key. If you have better methods please let me know!

its not working because glutKeyboardFunc(handleKeypress) is commented out for some reason. uncomment and it should work.

Your program runs in two stages:
Initialization
Main loop
Everything before glutMainLoop is initialization, telling GLUT all the different settings and callbacks you want to use. During the main loop, GLUT will call all your callbacks and you can draw.
The problem is that you're setting paused during the main loop and checking it during the initialization. Since initialization always happens before the main loop, setting paused won't actually do anything.
The solution is to not rely on checking paused during initialization, but instead modify your callbacks to immediately return if paused is true.

# include<GL/glut.h>
void keys(unsigned char key, int x, int y)
{
if (key == 'a') paused = 1;
if (key == 'A') paused = 0;
glutPostRedisplay();
}
add this function in your program for keyboard function and wherever u are using glutPostRedisplay() in program
add
if(paused == 0)
above it

Related

SDL_MOUSEBUTTONUP occurring even before releasing mouse button?

I'm trying to make a video player using SDL and ffmpeg in C++. I've created two separate threads, one that renders the video on the SDL window and one that handles window events. When the user clicks and releases on the video I want it to toggle playback/pause. However, it fires multiple times and the event occurs even before I release the mouse which results in unpredictable behavior.
My code:
SDL_Event event;
while (1)
{
SDL_PollEvent(&event);
switch (event.type)
{
case SDL_QUIT:
SDL_DestroyWindow(screen);
SDL_Quit();
break;
case SDL_MOUSEBUTTONUP:
if (event.button.state == SDL_RELEASED)
{
printf("Mouse released\n");
}
break;
}
}
When I click the window and hold down I would expect it wouldn't print Mouse released until I release the button. However, it prints Mouse released the entire time I hold down the mouse button. I don't know if maybe this has to do with me using a touchpad on my laptop.
SDL_PollEvent has a return value, you are ignoring.
[It] returns 1 if there are any pending events, or 0 if there are none available.
Given your code logic, whenever there is no pending event, you keep handling the previous event over and over again, until a new event arrives. This leads to the observed behavior.
The easiest fix would be to wrap the entire event handling inside an if (SDL_PollEvent(&event)) { /* Event handling */ } conditional.
EDIT: My answer is wrong, check IInspectable's answer.
Your error is that you're not checking all the pending events given by pollEvent, just one. Try this code and tell me how many button ups you get.
#include <SDL2/SDL.h>
#include <iostream>
int main(int argc, char *argv[]) {
if(SDL_Init(SDL_INIT_VIDEO) != 0) {
throw std::runtime_error("SDL failed to initialize.\n");
}
SDL_Window *window = SDL_CreateWindow("App", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, NULL);
bool done = false;
while(!done) {
SDL_Event event;
while(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT) {
done = true;
}
if (event.type == SDL_MOUSEBUTTONUP) {
if (event.button.state == SDL_RELEASED) {
printf("Mouse released\n");
}
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}

eclipse c++ debug: no source available for gl_draw

The code is designed to load a .obj file, draw, rotate camera around mesh (this is ongoing) and display rotation value when the mouse button is clicked. I am using eclipse C++ IDE with FLTK. When the mouse button is clicked the window crashes. The error message when debugging is "no source available for gl_draw".
The code is as follows:
void onMouseButton(int button, int state, int x, int y)
{
switch(button){
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN){
// Print value on object
char s[40];
sprintf(s, "ROT=%.2f", g_rotation);
glRasterPos2f(60,40);
gl_draw(s, strlen(s));
}
}
}
The main code:
int main(int argc, char **argv)
{
Fl_Window win(WIDTH,HEIGHT, "Wavefront");
win.resizable(win);
win.show(argc, argv);
// Docs say to add glut subwindow /after/ calling win.show()
win.begin();
// initialize and run program
//glutInit(&argc, argv); // GLUT initialization
glutInitWindowSize(WIDTH-20, HEIGHT-20);
glutInitWindowPosition(10,10); // place inside parent window
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_MULTISAMPLE);
glutCreateWindow("Ear");
glutDisplayFunc(display); // register Display Function
glutIdleFunc( display ); // register Idle Function
glutMouseFunc( onMouseButton );
glutKeyboardFunc( keyboard ); // register Keyboard Handler
initialize();
obj.Load("Ear_obj.obj");
//gl_draw(s, strlen(s));
glutMainLoop();
win.end();// run GLUT mainloop
return 0;
}
If gl_draw(s, strlen(s)); is removed code run as expected , therefore loads the mesh, draws it, displays the mesh as the camera is rotated but would do nothing if the mouse is clicked.
Is the a way to display any text when the mouse is clicked or is there a step I am missing that is causing the error?

Automatic change of background color using OpenGL [duplicate]

I have a real robot that is ordering my virtual robot in open gl. I want show every movement of my master robot(real robot) in slave (virtual one in open gl) online, so i need to update my glut window continuously, actually as long as real robot moves my virtual one moves too, and all these movement should be online.
I get data from master always with get data function, but I dont know how I should update the window.
Here is my code:
********************************************/
void OnIdle(void){
initSocket();
printf("\n Defining Step Time Parameters and Initial Conditions for solving Dynamic equations\n");
xi=0;
xf=0.1;
printf("\n end value x : %f ",xf);
i=0; yi[i]=0;
i++;yi[i]=-1.570796;
i++;yi[i]=-1.570796;
i++;yi[i]=0;
i++;yi[i]=0;
i++;yi[i]=0;
ndata=2; fi=1;
double counter=0.1;
Eqdifp(v1,v2,v3,v4,v5,v6,xi,xf,yi,ndata,p,fi);
for(int i=0;i<50;i++)
//while(1)
{
getData();
printf("\n");
for(int i=0;i<6; i++)
{
printf("%d = %.3f\n", i,drecvbuf[i]);
}
printf("\n");
yi[0]=v1[ndata];
yi[1]=v2[ndata];
yi[2]=v3[ndata];
yi[3]=v4[ndata];
yi[4]=v5[ndata];
yi[5]=v6[ndata];
printf("my nadata %f\n",v1[ndata]);
counter=counter+0.1;
Eqdifp(v1,v2,v3,v4,v5,v6,xi,xf,yi,ndata,p,fi);
glutPostRedisplay();
}
}
/////////////////////////////////////////////////////
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(900,500);
int u=glutCreateWindow("3DOF robot");
myinit();
createMenu();
glutIdleFunc (OnIdle);
glutDisplayFunc(Display);
glutReshapeFunc(reshape);
glutKeyboardFunc(KeyDown);
glutMainLoop();
System::Timers::Timer^ aTimer = gcnew System::Timers::Timer( 100 );
// Hook up the Elapsed event for the timer.
aTimer->Elapsed += gcnew System::Timers::ElapsedEventHandler( OnTimedEvent );
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer->Enabled = true;
return 0;
}
You can call glutPostRedisplay after the update, which schedules the window to be redrawn (using GLUT's display func, of course) as soon as it returns to the message queue, I think.
But this won't work if you are continously polling the robot data in an infinite loop as this continously blocks the program. What you should do is use a timer to schedule the robot update in short intervals, so that between these updates the program can return to the main event loop and redraw the window. Or you can call some function, which tells the framework to visit the event loop. Your code sample doesn't really explain how you do it at the moment (or I'm just not familiar with the functions you call).
GLUT offers you a idle callback (void (*)(void) signature), set through glutIdleFunc. Retrieve the robot input data in the idle handler. Or use a separate thread polling the data, filling data structures; use a semaphore to unlock idle after new data arrived, use a locking with timeout so that your program remains interactive. Pseudocode:
Semaphore robot_data_semaphore;
void wait_for_data(void)
{
SemaphoreLockStatus lock_status =
semaphore_raise_timeout(robot_data_semaphore, RobotDataTimeout);
if( lock_status == SEMAPHORE_RAISED ) {
update_scene_with_robot_data();
semaphore_lower(robot_data_semaphore);
glutPostRedisplay();
}
}
void main(int argc, char *argv[])
{
/* ... */
semaphore_init(robot_data_semaphore);
Thread thread_robot_data_poller = thread_create(robot_data_poller);
glutIdleFunc(wait_for_data);
/* ... */
thread_start(thread_robot_data_poller);
glutMainLoop();
}
I would do the following. Treat glutMainLoop() as your loop and every time you process one getData() you draw it, it will be faster than you think.
What needs to happen for you to get a 'continuous' update is to:
Process data (getData() then your calculations)
Redraw (Display() glut calls this every time it loops)
Other functions defined using glut_____Func()
Back to 1
Glut keeps going until the program is exited.
//called every time glutMainLoop
//do data processing
void OnIdle(void)
{
getData();
printf("\n");
for(int i=0;i<6; i++)
{
printf("%d = %.3f\n", i,drecvbuf[i]);
}
printf("\n");
yi[0]=v1[ndata];
yi[1]=v2[ndata];
yi[2]=v3[ndata];
yi[3]=v4[ndata];
yi[4]=v5[ndata];
yi[5]=v6[ndata];
printf("my nadata %f\n",v1[ndata]);
Eqdifp(v1,v2,v3,v4,v5,v6,xi,xf,yi,ndata,p,fi);
}
//also called every loop of glutMainLoop
void Display()
{
...
//Your previous Display() function just add this:
glutPostRedisplay(); //everytime you are done
// drawing you put it on the screen
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(900,500);
int u=glutCreateWindow("3DOF robot");
myinit();
createMenu();
glutIdleFunc (OnIdle);
glutDisplayFunc(Display);
glutReshapeFunc(reshape);
glutKeyboardFunc(KeyDown);
///////////////
// SETUP YOUR INITIAL DATA
System::Timers::Timer^ aTimer = gcnew System::Timers::Timer( 100 );
// Hook up the Elapsed event for the timer.
aTimer->Elapsed += gcnew System::Timers::ElapsedEventHandler( OnTimedEvent );
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer->Enabled = true;
initSocket();
printf("\n Defining Step Time Parameters and Initial Conditions for solving Dynamic equations\n");
xi=0;
xf=0.1;
printf("\n end value x : %f ",xf);
i=0; yi[i]=0;
i++;yi[i]=-1.570796;
i++;yi[i]=-1.570796;
i++;yi[i]=0;
i++;yi[i]=0;
i++;yi[i]=0;
ndata=2; fi=1;
Eqdifp(v1,v2,v3,v4,v5,v6,xi,xf,yi,ndata,p,fi);
//////////////
//Start the Main Loop
glutMainLoop(); //This statement blocks, meaning that until you exit the
// glut main loop no statments past this point will be executed.
return 0;
}

'X' button doesn't kill the process

I have a small game made in visual studio 2013, written in c++. It creates a window in which it draws several things and pops up the console I used to debug. The problem is: if I click on the "exit" button from the menu I introduced, all things good, the process is terminated as it should be; if I press the 'X' (close) button on top of the window, it closes the window, but the console still remains. As it should be excepted, not having the console enabled doesn't fix anything: there are no windows associated with the game, but the sound still plays and the process still exists in task manager. I've searched a lot about this and I couldn't find a solution for this issue.
I've tried with atexit, but the program doesn't go to the function written for atexit. Maybe I'm placing it wrong, I can't tell. This is what I've tried.
void close_win() {
if (engine)
engine->drop();
/*if (SC_CLOSE) {
cout << "sc_close";
_exit(0);
}*/
cout << "Ceva ";
exit(0);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow("Aarghhh! O ramaaa !");
createMenu();
glClearColor(0.0, 0.0, 0.0, 0.0);
init();
glutReshapeFunc(reshape);
glutDisplayFunc(dreptunghi);
glutSpecialFunc(player);
glutMainLoop();
atexit(close_win);
return 0;
}
or
BOOL WINAPI ConsoleHandler(DWORD CEvent)
{
if (CEvent == CTRL_CLOSE_EVENT)
{
cout << "You are closing my program.";
}
return TRUE;
} if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE) == FALSE)
{
cout << "The handler is not going to work.";
}
or
if (glutGetWindow == 0)
exit(0);
The game was made without classes, using OpenGL and GLUT libraries, if it matters for anything.
Also, when I set a breakpoint to atexit and use step over, after 2 steps the debug stops with "sehprolg4.asm not found". Does any of this has to do with the fact that the function doesn't call close_win()?

How to update glut window continuously?

I have a real robot that is ordering my virtual robot in open gl. I want show every movement of my master robot(real robot) in slave (virtual one in open gl) online, so i need to update my glut window continuously, actually as long as real robot moves my virtual one moves too, and all these movement should be online.
I get data from master always with get data function, but I dont know how I should update the window.
Here is my code:
********************************************/
void OnIdle(void){
initSocket();
printf("\n Defining Step Time Parameters and Initial Conditions for solving Dynamic equations\n");
xi=0;
xf=0.1;
printf("\n end value x : %f ",xf);
i=0; yi[i]=0;
i++;yi[i]=-1.570796;
i++;yi[i]=-1.570796;
i++;yi[i]=0;
i++;yi[i]=0;
i++;yi[i]=0;
ndata=2; fi=1;
double counter=0.1;
Eqdifp(v1,v2,v3,v4,v5,v6,xi,xf,yi,ndata,p,fi);
for(int i=0;i<50;i++)
//while(1)
{
getData();
printf("\n");
for(int i=0;i<6; i++)
{
printf("%d = %.3f\n", i,drecvbuf[i]);
}
printf("\n");
yi[0]=v1[ndata];
yi[1]=v2[ndata];
yi[2]=v3[ndata];
yi[3]=v4[ndata];
yi[4]=v5[ndata];
yi[5]=v6[ndata];
printf("my nadata %f\n",v1[ndata]);
counter=counter+0.1;
Eqdifp(v1,v2,v3,v4,v5,v6,xi,xf,yi,ndata,p,fi);
glutPostRedisplay();
}
}
/////////////////////////////////////////////////////
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(900,500);
int u=glutCreateWindow("3DOF robot");
myinit();
createMenu();
glutIdleFunc (OnIdle);
glutDisplayFunc(Display);
glutReshapeFunc(reshape);
glutKeyboardFunc(KeyDown);
glutMainLoop();
System::Timers::Timer^ aTimer = gcnew System::Timers::Timer( 100 );
// Hook up the Elapsed event for the timer.
aTimer->Elapsed += gcnew System::Timers::ElapsedEventHandler( OnTimedEvent );
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer->Enabled = true;
return 0;
}
You can call glutPostRedisplay after the update, which schedules the window to be redrawn (using GLUT's display func, of course) as soon as it returns to the message queue, I think.
But this won't work if you are continously polling the robot data in an infinite loop as this continously blocks the program. What you should do is use a timer to schedule the robot update in short intervals, so that between these updates the program can return to the main event loop and redraw the window. Or you can call some function, which tells the framework to visit the event loop. Your code sample doesn't really explain how you do it at the moment (or I'm just not familiar with the functions you call).
GLUT offers you a idle callback (void (*)(void) signature), set through glutIdleFunc. Retrieve the robot input data in the idle handler. Or use a separate thread polling the data, filling data structures; use a semaphore to unlock idle after new data arrived, use a locking with timeout so that your program remains interactive. Pseudocode:
Semaphore robot_data_semaphore;
void wait_for_data(void)
{
SemaphoreLockStatus lock_status =
semaphore_raise_timeout(robot_data_semaphore, RobotDataTimeout);
if( lock_status == SEMAPHORE_RAISED ) {
update_scene_with_robot_data();
semaphore_lower(robot_data_semaphore);
glutPostRedisplay();
}
}
void main(int argc, char *argv[])
{
/* ... */
semaphore_init(robot_data_semaphore);
Thread thread_robot_data_poller = thread_create(robot_data_poller);
glutIdleFunc(wait_for_data);
/* ... */
thread_start(thread_robot_data_poller);
glutMainLoop();
}
I would do the following. Treat glutMainLoop() as your loop and every time you process one getData() you draw it, it will be faster than you think.
What needs to happen for you to get a 'continuous' update is to:
Process data (getData() then your calculations)
Redraw (Display() glut calls this every time it loops)
Other functions defined using glut_____Func()
Back to 1
Glut keeps going until the program is exited.
//called every time glutMainLoop
//do data processing
void OnIdle(void)
{
getData();
printf("\n");
for(int i=0;i<6; i++)
{
printf("%d = %.3f\n", i,drecvbuf[i]);
}
printf("\n");
yi[0]=v1[ndata];
yi[1]=v2[ndata];
yi[2]=v3[ndata];
yi[3]=v4[ndata];
yi[4]=v5[ndata];
yi[5]=v6[ndata];
printf("my nadata %f\n",v1[ndata]);
Eqdifp(v1,v2,v3,v4,v5,v6,xi,xf,yi,ndata,p,fi);
}
//also called every loop of glutMainLoop
void Display()
{
...
//Your previous Display() function just add this:
glutPostRedisplay(); //everytime you are done
// drawing you put it on the screen
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(900,500);
int u=glutCreateWindow("3DOF robot");
myinit();
createMenu();
glutIdleFunc (OnIdle);
glutDisplayFunc(Display);
glutReshapeFunc(reshape);
glutKeyboardFunc(KeyDown);
///////////////
// SETUP YOUR INITIAL DATA
System::Timers::Timer^ aTimer = gcnew System::Timers::Timer( 100 );
// Hook up the Elapsed event for the timer.
aTimer->Elapsed += gcnew System::Timers::ElapsedEventHandler( OnTimedEvent );
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer->Enabled = true;
initSocket();
printf("\n Defining Step Time Parameters and Initial Conditions for solving Dynamic equations\n");
xi=0;
xf=0.1;
printf("\n end value x : %f ",xf);
i=0; yi[i]=0;
i++;yi[i]=-1.570796;
i++;yi[i]=-1.570796;
i++;yi[i]=0;
i++;yi[i]=0;
i++;yi[i]=0;
ndata=2; fi=1;
Eqdifp(v1,v2,v3,v4,v5,v6,xi,xf,yi,ndata,p,fi);
//////////////
//Start the Main Loop
glutMainLoop(); //This statement blocks, meaning that until you exit the
// glut main loop no statments past this point will be executed.
return 0;
}