这是一个作业,我需要使用 OpenGL 来渲染一条线,但只使用 GL_POINTS。
我正在用 P1(-1,-1) 到 P2(1,-1) 的水平线对其进行测试。
我的函数使用直线函数 y=mx+c:
void line2(double x1, double y1, double x2, double y2, double precision, int r, int g, int b){
double m = 0.0; // slope
double c = (y1 - m*x1); // constant
double j = y1; // starting y value
// check division by 0
if (x2-x1 == 0)
m = 0;
else
m = (y2-y1)/(x2-x1);
glColor3f(r,g,b);
glBegin(GL_POINTS);
for (double i = x1; i < x2; i+=precision){
j = m*i + c; // result of y from line function
glVertex2f(i,j);
}
glEnd();
调用方式:
line2(-1,-1,1,-1,0.000001, 102, 102, 255);
给我一条水平虚线。它不是连续的。如果我增加更多的精度,我的程序可能会因内存而挂起。
更新:我现在注意到渲染多行,第一行是虚线!因此,如果我多次调用 line(),无论参数如何,第一行始终是虚线,其他都是完美的。
是否有更好的方法(公式或循环)来渲染一条线?
谢谢!
最佳答案
double m = 0.0; // slope
double c = (y1 - m*x1); // constant
double j = y1; // starting y value
// check division by 0
if (x2-x1 == 0)
m = 0;
else
m = (y2-y1)/(x2-x1);
您正在使用 m==0
计算 c
,因此 c
始终等于 j
。尝试将 c
的计算移动到 m
计算之后的一行。
此外,当 x2-x1 == 0
时,斜率应该是正无穷大或负无穷大,而不是 0。由于 inf
很难处理,您可能需要特殊情况才能画竖线。
至于从像素绘制线条的其他方法,Bresenham 线条不会出错:https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
关于c++ - OpenGL:仅使用 GL_POINTS 渲染一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39760837/