2014年5月16日 星期五

叮叮噹噹木頭人

WEEK 13 複習

專案選項>參數> 加入-lcv -lcxcore -lhighgui

#include <GL/glut.h>
#include <opencv/highgui.h>
#include <opencv/cv.h>
float angleX =0, angle0=0, angle1=0, angle2=0, angle3=0;
GLuint id[4];//技巧2: 使用陣列, 讓變數 變 簡單 simple
IplImage * img[4];
char filename[4][100]={"imgBody.png", "imgHand0.png", "imgLeg0.png", "imgLeg1.png"};
void myTexture()
{
 glEnable(GL_TEXTURE_2D);
 for(int i=0; i<4; i++){//技巧3: 迴圈, 可以讓程式碼, 做重覆的事可以很爽 清爽
  img[i] = cvLoadImage( filename[i] );
  cvCvtColor(img[i], img[i], CV_BGR2RGB);
  glGenTextures(1, &id[i]);
  glBindTexture(GL_TEXTURE_2D, id[i]);//head
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_LINEAR);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img[i]->width, img[i]->height, 0, GL_RGB, GL_UNSIGNED_BYTE, img[i]->imageData);
 }
}
void myRect()//技巧1: 重覆的程式碼, 用函式拉出來, 就不用一直copy啦
{//函式就是 黑盒子 幫你做事情!
 glPushMatrix();
  glScalef(0.2, 0.5, 0.5);
  glBegin(GL_POLYGON);
   glTexCoord2f(0,0);  glVertex3f(-0.5, 0.5,0);
   glTexCoord2f(0,1);  glVertex3f(-0.5,-0.5,0);
   glTexCoord2f(1,1);  glVertex3f( 0.5,-0.5,0);
   glTexCoord2f(1,0);  glVertex3f( 0.5, 0.5,0);
  glEnd();
 glPopMatrix();
}
void display()
{
 glEnable(GL_DEPTH_TEST);
 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 glPushMatrix();
  glBindTexture(GL_TEXTURE_2D, id[0]);
  myRect();//body//技巧1: 用函式, 哥就是帥!
  glPushMatrix();//left hand
   glTranslatef(-0.1, 0.15, 0);
   glRotatef(angleX, 0,0,1);
   glTranslatef(0, -0.25, 0);
   glBindTexture(GL_TEXTURE_2D, id[1]);
   myRect();//技巧1: 用函式, 哥就是帥!
  glPopMatrix();
  glPushMatrix();//right hand
   glTranslatef(0.1, 0.15, 0);
   glRotatef(-angleX, 0,0,1);
   glTranslatef(0, -0.25, 0);
   glBindTexture(GL_TEXTURE_2D, id[1]);
   myRect();//技巧1: 用函式, 哥就是帥!
  glPopMatrix();
  glPushMatrix();//left leg
   glTranslatef( -0.05, -0.25, 0);
   glRotatef(180-angleX, 0,0,1);
   glTranslatef(0, 0.25, 0);
   glBindTexture(GL_TEXTURE_2D, id[2]);
   myRect();
   glPushMatrix();//left foot
    glTranslatef( 0, 0.25, 0);
    glRotatef(30, 0,0,1);
    glTranslatef(0, 0.15, 0);
    glBindTexture(GL_TEXTURE_2D, id[3]);
    myRect();
   glPopMatrix();  
  glPopMatrix();
  glPushMatrix();//right leg
   glTranslatef( 0.05, -0.25, 0);
   glRotatef(-(180-angleX), 0,0,1);
   glTranslatef(0, 0.25, 0);
   glBindTexture(GL_TEXTURE_2D, id[2]);
   myRect();
  glPopMatrix();
 glPopMatrix();
 glutSwapBuffers();
}
void keyboard(unsigned char key, int x, int y)
{
 if(key=='1') angleX+=5;
 if(key=='2') angleX-=5;
 glutPostRedisplay();//請電腦重新畫一次畫面
}
int main()
{
 glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
 glutCreateWindow("week11");
 glutDisplayFunc(display);
 glutKeyboardFunc(keyboard);
 myTexture();

 glutMainLoop();
}

沒有留言:

張貼留言