디지털 그래픽스

[openGL] 광원 회전 / 조명 종류 변환

gom1n 2021. 5. 16. 00:39
#include <iostream>
#include <math.h>
#include <gl/glut.h>
using namespace std;

int w = 500, h = 500;

void init() {
	glViewport(0, 0, w, h);
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glEnable(GL_DEPTH_TEST);

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
}

float spin = 0;
int ltype = 1;
float ZPos = 0;
float angle = 45;

void display() {
	float zdist = 1;
	GLfloat position[] = { 0.0, 0.0, zdist, 1.0 };
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1.0, 1.0, -1.0, 1.0, 1, 30.0);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(0, 0, 2.0f, 0, 0, 0, 0, 1, 0);
	
	//LIGHT y축 회전
	glPushMatrix();
	glRotated((GLdouble)spin, 0.0, 1.0, 0.0);
	spin += 1.0;
	glLightfv(GL_LIGHT0, GL_POSITION, position);
	//Draw cube for light display
	glTranslated(0.0, 0.0, zdist);
	glDisable(GL_LIGHTING);
	glColor3f(1.0, 0.0, 0.0);
	glutWireCube(0.05);
	glEnable(GL_LIGHTING);

	//LIGHT type 변경
	switch (ltype) {
	case 1:		//Point Light
		position[3] = 1;
		glLightfv(GL_LIGHT0, GL_POSITION, position);
		glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0.0);
		break;
	case 2:		//Directional Light
		position[3] = 0;
		glLightfv(GL_LIGHT0, GL_POSITION, position);
		break;
	case 3:		//SpotLight
		position[3] = 1;
		glLightfv(GL_LIGHT0, GL_POSITION, position);
		GLfloat sd[] = { 0.0, 0.0, -1.0 };
		glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, sd);
		glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45);
		glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 10.0);
		break;
	}
	glPopMatrix();
	//TORUS
	glColor3f(0.7, 0.7, 0.7);
	glutSolidTorus(0.1, 0.4, 100, 100);
	glutSwapBuffers();
}
int count = 0;
void keyboard(unsigned char key, int x, int y) {
	switch (key) {
	case '1':
		ltype = 1; glutPostRedisplay(); break;
	case '2':
		ltype = 2; glutPostRedisplay(); break;
	case '3':
		ltype = 3; glutPostRedisplay(); break;
	default: break;
	}
}
int main(int argc, char** argv) {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowSize(w, h);
	glutInitWindowPosition(100, 100);
	glutCreateWindow("light");
	init();

	glutDisplayFunc(display);
	glutIdleFunc(display);
	glutKeyboardFunc(keyboard);
	glutMainLoop();

	return 0;
}

결과물)