c++ - 将值传递给 glutDisplayFunc 函数

标签 c++ glut

我正在尝试将数组形式的数据传递给由 glutDisplayFunc 调用的函数。请让我知道这是否/如何实现相同目标的可能或简单的替代方法。最终我会想要将很多值传递到绘图函数中。谢谢!

#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;
}

最佳答案

要点是只有全局变量才有意义过剩。

为什么?

没有理由使用局部变量,因为过剩本身是全局的。 glutInit 每个应用程序只能调用一次。等等。

沸腾

对于 C++11 及更高版本。 传递 lambda 而不是函数指针。 下面的示例显示了如何将 lambda 传递到循环体中。通过将 lambda 作为显示函数,您可以使用捕获部分来传递您喜欢的任何内容。

    // 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);
        });
    }

对于旧的 C++ 标准,一切都一样,只是用您的变量而不是 lambda 填充 GlutArgs 内容,而不是 lambda,并直接从 display 函数中使用它们。

关于c++ - 将值传递给 glutDisplayFunc 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11149807/

相关文章:

c++ - 更新返回 0 即使表中没有此 id

c++ - 未定义的行为和顺序点

c++ - 如何使 Visual Studio 2017 C++ 项目在计算机之间更具可移植性?

c++ - OpenGL Fog不出现

c - 旋转肩膀和肘部的 OpenGL Arm

c++ - 需要使用glRasterPos3f(openGL)的帮助

opengl - 如何让鼠标光标在 opengl/glut 中消失?

c++ - 在 macOS 上编译 GLEW 和 GLUT?

c++ - C++中的字典库

c++ - MFC : Fix a console on a GUI