수업

컴퓨터그래픽스 - Bunny Model 회전 코드

eunslog 2023. 4. 5. 15:06

 

#include <glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "BunneyModel.h"
#include <stdio.h>

GLuint g_stanfordBunnyID = -1;

GLint xValue = 0;
GLint yValue = 0;
GLint zValue = 0;

GLint clickDown = 0;
GLint fixX = 0;
GLint fixY = 0;

GLint GenerateCallList()
{
	GLint lid = glGenLists(1);

	glNewList(lid, GL_COMPILE);
	glColor3f(1.0f, 0.0f, 0.0f);

	unsigned int i;

	for (int i = 0; i < (sizeof(face_indicies) / sizeof(face_indicies[0])); i++)
	{
		int vi;
		glBegin(GL_LINE_LOOP);

		vi = face_indicies[i][0];
		glVertex3f(vertices[vi][0], vertices[vi][1], vertices[vi][2]);
		//glVertex3fv(vertices[vi])와 같음. glVertex3fv(vertices[face_indicies[i][1]]);도 가능

		vi = face_indicies[i][1];
		glVertex3f(vertices[vi][0], vertices[vi][1], vertices[vi][2]);

		vi = face_indicies[i][2];
		glVertex3f(vertices[vi][0], vertices[vi][1], vertices[vi][2]);

		glEnd();
	}
	glEndList();

	return lid;
}

void MyDisplay()
{
	glClear(GL_COLOR_BUFFER_BIT);
	glColor3f(1.0, 0.0, 0.0);
	glLoadIdentity(); //초기화해야 정상적으로 회전함. 아니면 매우 빨리 회전함.
	

	// 위치에 따라 좌표축 회전
	glRotatef(xValue, 1.0, 0.0, 0.0);
	glRotatef(yValue, 0.0, 1.0, 0.0);
	glRotatef(zValue, 0, 0, 1.0);

	// Axis
	glLineWidth(2);
	glBegin(GL_LINES);
	glColor3f(1.0f, 0.0f, 0.0f);	glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f);
	glColor3f(0.0f, 1.0f, 0.0f);	glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f);
	glColor3f(0.0f, 0.0f, 1.0f);	glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f);
	glEnd();
	unsigned int i;

	glCallList(g_stanfordBunnyID);

	glFlush();
}


void MyKeyboard(unsigned char KeyPressed, int X, int Y)
{
	switch (KeyPressed)
	{
		case 'Q':
		case 'q':
			exit(0); break;
		case 'x':
		case 'X':
			xValue += 1; break;
			if (xValue > 360) xValue -= 360;
		case 'y':
		case 'Y':
			yValue += 1; break;
			if (yValue > 360) yValue -= 360;
		case 'z':
		case 'Z':
			zValue += 1; break;
			if (zValue > 360) zValue -= 360;
		case 32: //spacebar
			xValue = 0; yValue = 0; zValue = 0; break;

	}
	printf("%d\n", KeyPressed);
	glutPostRedisplay();
}

void MyMouseClick(GLint Button, GLint State, GLint X, GLint Y)
{
	if (Button == GLUT_LEFT_BUTTON && State == GLUT_DOWN)
	{
		xValue = X;
		yValue = Y;
		clickDown = 1;
	}

	if (Button == GLUT_LEFT_BUTTON && State == GLUT_UP)
	{
		clickDown = 0;
	}
}

void MyMouseMove(GLint X, GLint Y)
{
	if (clickDown == 1)
	{
		xValue = xValue + (fixX - X);
		yValue = yValue + (fixY - Y);
		fixX = X;
		fixY = Y;
	}
	glutPostRedisplay();
}



int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitWindowSize(700, 700);
	glutCreateWindow("OpenGL Example");

	g_stanfordBunnyID = GenerateCallList();

	glutDisplayFunc(MyDisplay);


	glutKeyboardFunc(MyKeyboard);
	glutMouseFunc(MyMouseClick);
	glutMotionFunc(MyMouseMove);

	glutMainLoop();
	return 0;
}