我试图使用 c 来使用 opengl。我写的代码在线条内留下了空隙,即画虚线,而我在网上找到的那个画得很好。我不明白,如果我写的代码和我在网上找到的代码没有区别,为什么会发生这种情况?
我尝试浏览这些网站。我还阅读了DDA Line Drawing Algoruthm have errors 但是,找不到解决方案
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//comment the following line when not on windows
//#include <windows.h>
#include <GL/gl.h>
#include <GL/glut.h>
void Init(void); //used to initialize the stuff such as ortho2D and matrix mode;
void renderFunction(void); //this function is called in the glutDisplayFunc
void drawAxes(void); //used to draw the axes
void dda(const float, const float, const float, const float); //the actual implementation of the algorithm
main(argc, argv)
char** argv;
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(300,300);
glutInitWindowPosition(100,100);
glutCreateWindow(argv[1]);
Init();
glutDisplayFunc(renderFunction);
glutMainLoop();
return EXIT_FAILURE;
}
void Init(void) {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-500, 500, -500, 500);
}
void renderFunction(void) {
drawAxes();
int x0, y0, x1, y1;
while(1) {
printf("ENTER THE CO-ORDINATES OF THE FIRST POINT: ");
scanf("%d %d",&x0 ,&y0);
printf("ENTER THE CO-ORDINATES OF THE SECOND POINT: ");
scanf("%d %d",&x1 ,&y1);
dda(x0, y0, x1, y1);
}
}
void drawAxes(void) {
dda(-500, 0, 500, 0);
dda(0, -500, 0, 500);
}
void dda(x0, y0, x1, y1)
const float x0, y0, x1, y1;
{
float dx = x1 - x0;
float dy = y1 - y0;
int steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
float xInc = dx/(float)steps;
float yInc = dy/(float)steps;
float x = x0;
float y = y0;
glBegin(GL_LINES);
int i = 0;
for(i = 0; i < steps; i++) {
glVertex2i((int)x, (int)y);
x += xInc;
y += yInc;
}
glEnd();
glFlush();
}
我在网上找到的代码:
#include<stdio.h>
#include<math.h>
#include<GL/freeglut.h>
#include<GL/gl.h>
void dda(int x0, int y0, int x1, int y1){
int steps;
float Xinc; float Yinc; float X,Y;
//DDA Calculation start
int dx = x1-x0;
int dy = y1-y0;
steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
Xinc = dx/(float)steps;
Yinc = dy/(float)steps;
X=x0;
Y=y0;
//DDA Calculation end
int i;
glColor3f(0.0, 0.0, 0.0);
// glOrtho(-1.0,1.0,-1.0, 1.0,1.0,-1.0);
glBegin(GL_POINTS);
for(i=0 ; i<steps ; i++){
glVertex2i((int)X,(int)Y);
X+=Xinc;
Y+=Yinc;
}
glEnd();
}
void axis(){
dda(-750,0,750,0);
dda(0,-750,0,750);
}
void renderF(void){
gluOrtho2D(750,-750,750,-750);
axis();
//Diagonal Vertex 1
int x1 = 500;
int y1 = 500;
//Diagonal Vertex 2
int x2 = -500;
int y2 = -500;
int v = x1;
int u = v/2;
dda(-v,v,-v,-v);
glFlush();
}
int main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutCreateWindow("Hello");
glClearColor(1.0, 1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glutDisplayFunc(renderF);
glutMainLoop();
return 0;
}