【问题标题】:Draw vertices with thread in opengl在opengl中用线程绘制顶点
【发布时间】:2016-02-18 00:42:25
【问题描述】:

我正在使用带有 opengl 的 glut 库并用它画圈。圆在框架上成功绘制,但我想要在线程中编译这些圆顶点。例如,我放入循环循环,2seconds 之后的每个顶点绘制都完成,而不是在运行时显示帧上的顶点经过了几秒钟。我正在使用sleep() 函数,但无法使用它。
代码:

#include <iostream>
#include <cstdlib>
#include <GL/glut.h>
#include<windows.h>
#include <cmath>
#define M_PI 3.14159265358979323846
using namespace std;

void init(void) {


    glClearColor(0.0f,0.0f,0.0f,0.0f);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

}



void keyboard(unsigned char key, int x, int y)
{
    switch (key)
    {
    case '\x1B':
        exit(EXIT_SUCCESS);
        break;
    }
}

void drawCircle(float pointX, float pointY, float Radius, int segment)
{




    glBegin(GL_LINE_LOOP);

    for (int i = 0; i < segment; i++)
    {
        float thetha= i * (2.0f * (float)M_PI / segment);
        float x = Radius * cos(thetha);
        float y = Radius * sin(thetha);
        Sleep(2000);
        glVertex2f(x + pointX, y + pointY);




    }
    glEnd();
}

void display()
{

    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0f,0.0f,0.0f);
    drawCircle(0.0f, 0.0f, 0.80f, 360);
    glFlush();
}


int main(int argc, char** argv)
{

    glutInit(&argc, argv);
    glutInitWindowSize(590, 590);
    glutInitWindowPosition(50,50);
    glutCreateWindow("Frame");
    init();
    glutKeyboardFunc(&keyboard);
    glutDisplayFunc(&display);
    glutMainLoop();

    return EXIT_SUCCESS;
}

【问题讨论】:

  • 如果我理解正确你想画一个圆圈然后等待 2 秒然后再画一次。如果那是你想要的,那你就睡错了地方。通过在循环段内休眠,您可以在每个顶点之间休眠,但是如果您想在连续绘制圆之间休眠,请将休眠移到 glEnd() 调用之后或您的主显示方法中。

标签: c++ opengl


【解决方案1】:

如果我正确理解了您的问题,您希望为圆圈绘制动画。 OpenGL 中的绘制命令不会立即发出——您需要绘制,然后将结果呈现给窗口。因此,在绘图函数中使用sleep 会延迟演示。使用您发布的代码,您在drawCircle 内的每次循环迭代都会休眠 2 秒。由于您传递的是segment=360,因此渲染您的圈子大约需要 12 分钟(在此期间您的应用程序似乎会挂起)。很可能,您应该在一个状态下绘制带有圆圈的帧 2 秒钟,然后再绘制下一个状态。

要实现这一点,您应该删除sleep,并在您的display 函数中设置一个计时器,它会随着时间的推移增加segment 参数。例如:

#include <ctime>
// ...
void display()
{
    static clock_t startTime = clock(); // NOTE: evaluated only once
    clock_t currentTime = clock();
    float timeLength = 2.0f * CLOCKS_PER_SEC;
    float circlePercentage = (currentTime - startTime) / timeLength;        
    circlePercentage = circlePercentage >= 1.0f ? 1.0f : circlePercentage; //clamp
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0f,0.0f,0.0f);
    drawCircle(0.0f, 0.0f, 0.80f, static_cast<int>(circlePercentage * 360));
    glFlush();
}

【讨论】:

  • currentTime,startTime,timeLength 如何初始化这些变量,这些都是红色下划线
  • 例如,您可以使用 ctime 初始化它们。 cplusplus.com/reference/ctime/time
  • 更新,时钟更适合计时,因为分辨率更高 - 但是,它不是“真正的”挂钟时间,但可能足以满足您的目的。
  • 但是你的代码在时间过去后会在框架上画圈。但是有没有办法,当框架显示出来时,我们可以立即看到每个顶点绘制并画一个完整的圆圈
  • 如果你想立即画出完整的圆圈,只需设置circlePercentage = 1.0f
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多