使用 OpenGL 绘制任意线(即轴范围没有限制)

draw an arbitrary line with OpenGL(i.e. no limit on axis range)

我想用用户定义的参数画一条二维线。但是x轴和y轴的范围是[-1,1].

怎样才能画出能完整显示在window中的线?我使用了 gluOrtho2D(-10.0, 10.0, -10.0, 10.0) 但它似乎不是一个好的选择,因为范围根据参数是动态的。

例如,该行是y=ax^3+bx^2+cx+d。 x 的范围是 [1, 100].

我的代码是:

#include "pch.h"
#include<windows.h>

#include <gl/glut.h>

#include <iostream>
using namespace std;

double a, b, c, d;
void init(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(-10.0, 10.0, -10.0, 10.0);
}

double power(double x, int p) {
    double y = 1.0;
    for (int i = 0; i < p; ++i) {
        y *= x;
    }
    return y;
}

void linesegment(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1, 0, 0);
    glPointSize(1);

    glBegin(GL_POINTS);
    for (int i = 1; i <= 10; ++i) {
        double y = a * power(i, 3) + b * power(i, 2) + c * i + d;
        glVertex2f(i, y);
    }
    glEnd();

    glFlush();
}

int main(int argc, char**argv)

{
    if (argc < 4) {
        cout << "should input 4 numbers" << endl;
        return 0;
    }

    a = atof(argv[1]);
    b = atof(argv[2]);
    c = atof(argv[3]);
    d = atof(argv[4]);

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowPosition(50, 100);
    glutInitWindowSize(400, 300);
    glutCreateWindow("AnExample");

    init();

    glutDisplayFunc(linesegment);
    glutMainLoop();

    return 0;
}

设置投影矩阵不是一次性操作。您可以随时更改它。事实上,强烈反对您 init 的做法。只需在绘图函数中设置投影参数即可。也使用标准库函数,不要自己动手。无需自己实施 power。只需使用 pow 标准库函数即可。最后但同样重要的是,使用双缓冲;因为它提供了更好的性能,并且具有更好的兼容性。

#include "pch.h"
#include <windows.h>

#include <gl/glut.h>

#include <iostream>
#include <cmath>
using namespace std;

double a, b, c, d;
double x_min, x_max, y_min, y_max; // <<<<---- fill these per your needs

void linesegment(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(x_min, x_max, y_min, y_max, -1, 1);

    glColor3f(1, 0, 0);
    glPointSize(1);

    glBegin(GL_POINTS);
    for (int i = 1; i <= 10; ++i) {
        double y = a * pow(i, 3) + b * pow(i, 2) + c * i + d;
        glVertex2f(i, y);
    }
    glEnd();

    glFlush();
}