PART ONE
codes.cpp
#include <stdio.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <iostream>
using namespace std;
#define width 222
#define height 207
#define num 3 //顶点计数器
struct Vector3f {
GLfloat x;
GLfloat y;
GLfloat z;
};
struct Color {
GLubyte r;
GLubyte g;
GLubyte b;
GLubyte a;
};
GLubyte image[height][width][4];
void initLines()
{
//定义NDC下的顶点数据
Vector3f points[num]{
{0.0f,0.0f,0.0f},
{0.5f,0.0f,0.0f},
{0.5f,0.5f,0.0f}
};
//定义颜色数据
Color color[num]{
{255,0,0,0},
{0,255,0,0},
{0,0,255,0}
};
//将NDC坐标转换成屏幕坐标
for (int i = 0; i < num; i++){
points[i].x = (points[i].x + 1.0f) * (width / 2 - 1);
points[i].y = (points[i].y + 1.0f) * (height / 2 - 1);
points[i].z = 0; //zbuffer统一设置为0
}
for (int i = 0; i < num-1; i++){
//定义线的起点
int start = i;
int start_x = (int)points[start].x;
int start_y = (int)points[start].y;
//定义线的终点 两两相邻取点
int end = i + 1;
int end_x = (int)points[end].x;
int end_y = (int)points[end].y;
//保证线起点的坐标(x,y)不大于终点的(x,y)
if (start_x > end_x) {
swap(start_x,end_x);
}
if (start_y > end_y) {
swap(start_y, end_y);
}
//斜率法画线
float delta_x = end_x - start_x;
float delta_y = end_y - start_y;
//便于算法的实现,将线宽设置为1
float lineWidth = 1.0f;
//采用起点的颜色画线
if (delta_x == 0 || delta_y == 0) {
for (int y = start_y; y <= end_y; y++) {
for (int x = start_x; x <= end_x; x++) {
image[y][x][0] = color[i].r;
image[y][x][1] = color[i].g;
image[y][x][2] = color[i].b;
image[y][x][3] = color[i].a;
}
}
}
else {
float gradient = (float)delta_y / delta_x;
for (int x = start_x; x <= end_x; x++) {
//直线斜率公式
int y = (int)(gradient * (x - start_x) + start_y);
image[y][x][0] = color[i].r;
image[y][x][1] = color[i].g;
image[y][x][2] = color[i].b;
image[y][x][3] = color[i].a;
}
}
}
}
void render()
{
glClear(GL_COLOR_BUFFER_BIT);
glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, image);
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(width, height);
glutInitWindowPosition(200, 100);
int id = glutCreateWindow("线的连接");
GLenum err = glewInit();
if (err != GLEW_OK) {
fprintf(stderr, "Error: '%s'\n", glewGetErrorString(err));
return 1;
}
initLines();
glutDisplayFunc(render);
glutMainLoop();
return 0;
}
部分二
代码分下
1、修改顶点计数器num的值为3,则可生成3个顶点。
2、在initPoints()中,初始化3个顶点属性:坐标、颜色(User-Defined:用户自定义)。将顶点按···{i-1:i},{i:i+1}···的方式构造成点对,{?:?+1}~{start:end}。对点对{start:end}利用“斜率法”构造的线的颜色为起点start.color的颜色。
3、render()函数实现绘制、显示功能。