OpenGL绘制三角形
三角形的平移和旋转
对三角形的三个坐标矩阵化,之后乘相应操作的矩阵得到平
移/旋转后的三角形矩阵,并用Opengl函数库进行绘制。
注意:并未使用Opengl中自带的平移与旋转函数。而是根据原理理解后写出的具体操作。
// An highlighted block
// sanJiaoxing.cpp: 定义控制台应用程序的入口点。
//
#include<GL/glut.h>
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
float dx, dy, dj;
float sanjiao_chu[3][3] = { 50,25,1,150,25,1,100,100,1 };//原来的三角形
float sanjiao_zhong_ping[3][3] = { 0 };
float sanjiao_zhong_zhuan[3][3] = { 0 };
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_SMOOTH);
}
void draw_triangle(float sanjiao[][3])//画三角形
{
glColor3f(0.2, 0.7, 0.30);
glBegin(GL_TRIANGLES);//画出三角形,为混合色填充方式
glShadeModel(GL_SMOOTH);
glVertex2f(sanjiao[0][0], sanjiao[0][1]);
glColor3f(0.4, 0.5, 0.60);
glVertex2f(sanjiao[1][0], sanjiao[1][1]);
glColor3f(0.9, 0.7, 0.8);
glVertex2f(sanjiao[2][0], sanjiao[2][1]);
glEnd();
}
void chengfa(float sanjiao1[][3], float sanjiao2[][3], float sanjiao3[][3])//矩阵相乘,结果放到sanjiao3中,sanjiao3为全局变量中的结果
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
sanjiao3[i][j] += sanjiao1[i][k] * sanjiao2[k][j];
}
}
}
}
void pingyi(void)
{
glClear(GL_COLOR_BUFFER_BIT);
float ping[3][3] = { 1,0,0,0,1,0,dx,dy,1 };
chengfa(sanjiao_chu, ping, sanjiao_zhong_ping);
draw_triangle(sanjiao_chu);
draw_triangle(sanjiao_zhong_ping);
glFlush();
}
void xuanzhuan(void)
{
glClear(GL_COLOR_BUFFER_BIT);
float jiaodu;
jiaodu = dj / 180 * 3.14;
float zhuan[3][3] = { cos(jiaodu),sin(jiaodu),0,-sin(jiaodu),cos(jiaodu),0,0,0,1 };
chengfa(sanjiao_chu, zhuan, sanjiao_zhong_zhuan);
draw_triangle(sanjiao_chu);
draw_triangle(sanjiao_zhong_zhuan);
glFlush();
}
void mulu()
{
int choose;
cout << "1.平移" << endl << "2.旋转" << endl;
cin >> choose;
switch (choose)
{
case 1:
cout << "输入平移距离dx,dy:" << endl;
cin >> dx >> dy;
glutDisplayFunc(pingyi);
break;
case 2:
cout << "输入旋转角度:" << endl;
cin >> dj;
glutDisplayFunc(xuanzhuan);
break;
default:
cout << "输入错误" << endl;
break;
}
}
void main(int argc, char** argv)
{
glutInit(&argc, argv); //初始化glut
glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE | GLUT_RGBA); //设置窗口的模式-深度缓存,单缓存,颜色模型
glutInitWindowPosition(100, 100); //设置窗口的位置
glutInitWindowSize(500, 500); //设置窗口的大小
init();
glutCreateWindow("3D Tech- GLUT Tutorial"); //创建窗口并赋予title
glMatrixMode(GL_PROJECTION);
gluOrtho2D(-250, 250, -250, 250);
glMatrixMode(GL_PROJECTION);
mulu();
glutMainLoop(); //进入循环等待
}
版权声明:本文为weixin_42654581原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。