Reputation: 2300
I'm trying to pass data in the form of an array to a function that is called by glutDisplayFunc. Please let me know if/how this is possible or easy alternatives to achieve the same goal. Eventually I will want to pass a lot of values into the drawing function. Thank you!
#include "stdafx.h"
#include <ostream>
#include <iostream>
#include <Windows.h>
#include <ctime>
#include <vector>
using namespace std;
#include <glut.h>
void Draw(int passedArray[]) { // This is probably wrong but just to give you the idea
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_POINTS);
glVertex3f(passedArray[1], passedArray[2], 0.0); // A point is plotted based on passed data
glEnd();
glFlush();
}
void Initialize() {
glClearColor(0.0, 0.0, 0.0, 0.0); // Background color
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
int main(int iArgc, char** cppArgv) {
cout << "Start Main" << endl;
glutInit(&iArgc, cppArgv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(250, 250); // Control window size
glutInitWindowPosition(200, 200);
glutCreateWindow("GA");
Initialize();
int passedArray[2] = {10, 20}; // create array
glutDisplayFunc(Draw(passedArray)); // This is not how you do this, just to try to convey what I want
glutMainLoop();
return 0;
}
Upvotes: 3
Views: 1673
Reputation: 990
Main point is that only global variables make sense with glut.
Why?
There is no reason to use local variables, for glut itself is global.
glutInit
may be called only once per application. And so on.
Boiling out
For C++11 and higher. Pass lambda instead of a function pointer. The example below shows how to pass a lambda into the loop body. By having a lambda as a display function you may use the capture section to pass whatever you like.
// Include GLUT headers here as well
#include <functional>
typedef std::function<void()> loop_function_t;
struct GlutArgs {
loop_function_t loopFunction;
};
GlutArgs& getGlutArgs() {
static GlutArgs glutArgs;
return glutArgs;
}
void display() {
getGlutArgs().loopFunction();
}
void init(int argc, char** argv) {
// glutInit and friends goes here
glutDisplayFunc (display);
}
void loop(loop_function_t f) {
getGlutArgs().loopFunction = f;
glutMainLoop();
}
int main(int argc, char** argv) {
init(argc, argv);
int myVar = 1;
loop([myVar](){
glClear(...);
doSomething(myVar);
});
}
For old C++ standards, all the same but instead of lambda just fill GlutArgs
contents with your variables instead of lambda, and use them from display function directly.
Upvotes: 1