diff --git a/lab1/2.cpp b/lab1/2.cpp new file mode 100644 index 0000000..01f7c91 --- /dev/null +++ b/lab1/2.cpp @@ -0,0 +1,80 @@ +#include +#include +#include + +// 窗口宽度和高度 +const int WIDTH = 640; +const int HEIGHT = 480; + +void drawDDALine(int x1, int y1, int x2, int y2) { + float x = x1; + float y = y1; + + // 计算差值 + int dx = x2 - x1; + int dy = y2 - y1; + + // 确定步数,取 dx 和 dy 中绝对值较大的那个 + int steps = std::abs(dx) > std::abs(dy) ? std::abs(dx) : std::abs(dy); + + // 计算每一步的增量 + float xIncrement = (float)dx / steps; + float yIncrement = (float)dy / steps; + + // 开始绘制点 + glBegin(GL_POINTS); + glVertex2i((int)round(x), (int)round(y)); // 绘制起点 + + for (int k = 0; k < steps; k++) { + x += xIncrement; + y += yIncrement; + // 将浮点坐标四舍五入转换为整数像素坐标 + std::cout << (int)round(x) << ", " << (int)round(y)<<"\n"; + glVertex2i((int)round(x), (int)round(y)); + } + glEnd(); +} + +// 显示回调函数 +void display() { + drawDDALine(0, 0, 50, 20); + glFlush(); +} + +// 初始化 OpenGL 设置 +void init() { + // 设置背景颜色为白色 + glClearColor(1.0f, 1.0f, 1.0f, 1.0f); + + // 设置投影矩阵为 2D 正交投影 + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + // 定义可视区域,左下角(0,0),右上角(WIDTH, HEIGHT) + gluOrtho2D(0.0, WIDTH, 0.0, HEIGHT); +} + +int main(int argc, char** argv) { + // 初始化 GLUT + glutInit(&argc, argv); + + // 设置显示模式:单缓冲、RGB 颜色模式 + glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); + + // 设置窗口大小和位置 + glutInitWindowSize(WIDTH, HEIGHT); + glutInitWindowPosition(100, 100); + + // 创建窗口 + glutCreateWindow("DDA算法"); + + // 注册回调函数 + glutDisplayFunc(display); + + // 初始化设置 + init(); + + // 进入主循环 + glutMainLoop(); + + return 0; +} \ No newline at end of file diff --git a/lab1/2.exe b/lab1/2.exe new file mode 100644 index 0000000..e6348df Binary files /dev/null and b/lab1/2.exe differ