2017年10月19日 星期四

蒲立年的學習筆記 Week 06

打光 (Linghting)
#include <GL/glut.h>
#include "glm.h"
GLMmodel* pmodel = NULL;
void
drawmodel(void)
{
    if (!pmodel)
    {
        pmodel = glmReadOBJ("data/al.obj");
        if (!pmodel) exit(0);
        glmUnitize(pmodel);
        glmFacetNormals(pmodel);
        glmVertexNormals(pmodel, 90.0);
    }

    glmDraw(pmodel, GLM_SMOOTH | GLM_MATERIAL);
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    drawmodel();
    glutSwapBuffers();
}
 GLfloat light_pos[] = { 0.0, 0.0,-1.0, 0.0 }; //打光的方向,此參數時為背後打光
int main(int argc, char**argv)
{

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("week05");

    glutDisplayFunc(display);
    glEnable(GL_DEPTH_TEST); //深度測試
    glEnable(GL_LIGHTING); //打光(1)
    glEnable(GL_LIGHT0); //打光(1)
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
    glutMainLoop();
}
藍字為打光程式碼
綠字為深度程式碼




加入KeyBoard、Mouse和Motion

#include <GL/glut.h>
#include <stdio.h>
#include "glm.h"
GLMmodel* pmodel=NULL;
int rotateX=0,rotateY=0,rotateZ=0;
int oldX=0, oldY=0, oldZ=0;
void keyboard(unsigned char key, int x, int y)
{
    printf("Now:%c (%d %d)\n", key, x, y);
    if (key=='1') rotateX++;
    if (key=='2') rotateY++;
    if (key=='3') rotateZ++;
    glutPostRedisplay();
}
void mouse(int button, int state, int x, int y)
{
    printf("Button:%d State:%d (%d %d)\n",button, state, x, y);
    if(state==GLUT_DOWN)
    {
        oldX=x;
        oldY=y;
    }
}
void motion(int x, int y)
{
    rotateY += -(x-oldX);
    rotateX += -(y-oldY);
    oldX=x;
    oldY=y;
    glutPostRedisplay(); //貼出公告,請電腦有空時,把畫面重新redisplay
}
drawmodel(void)
{
    if (!pmodel)
    {
        pmodel = glmReadOBJ("data/al.obj");
        if (!pmodel) exit(0);
        glmUnitize(pmodel);
        glmFacetNormals(pmodel);
        glmVertexNormals(pmodel, 90.0);
    }

    glmDraw(pmodel, GLM_SMOOTH | GLM_MATERIAL);
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glRotatef(rotateX, 1, 0, 0);  //設定旋轉角度
    glRotatef(rotateY, 0, 1, 0);
    glRotatef(rotateZ, 0, 0, 1);
    drawmodel();
    glPopMatrix();
    glutSwapBuffers();
}
GLfloat light_pos[] = { 0.0, 0.0,-1.0, 0.0 };
int main(int argc, char**argv)
{

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("week05");

    glutDisplayFunc(display);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHT0);
    glEnable(GL_LIGHTING);
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
    glutMotionFunc(motion);
    glutMouseFunc(mouse);
    glutKeyboardFunc(keyboard);
    glutMainLoop();
}





沒有留言:

張貼留言