2024年3月7日 星期四

電腦圖學 Week03 🥴

Mose滑鼠畫圖:week03_mouse

1. moodle下載 freeglut 拖到桌面

2. 把桌面\freglut\lib\libfreeglut.a 複製成 libglut32.a

3. CodeBlocks開GLUT專案, 目錄選桌面, 專案名取week03_mouse

4. GLUT要選桌面的 freeglut

5. 複製第一周10行程式

6. 另外加3行, 點茶壺就顯示一行Hello Mouse!
#include <stdio.h>
void mouse(int button, int state, int x, int y){
    printf("Hello Mouse!\n");
}    
glutMouseFunc(mouse);

7. 再加上一行程式碼, 滑鼠點視窗顯示座標
printf("%d %d %d %d\n", button, state, x, y);

8. 再加一行, 滑鼠點視窗產生座標程式碼 
if(state==GLUT_DOWN) printf("glVertex2f((%d-150)/150.0, -(%d-150)/150.0);\n", x, y);


移動:week03_mouse_glTranslatef

1. 下載課本的範例 https://jsyeh.org/3dcg10 windows.zip(win32) 及 data.zip(data)

2. windows.zip 解壓縮, data.zip 解壓縮拉到windows資料夾

3. 執行 Transformation.exe

移動:glTranslatef(x,y,z)
旋轉:glRotatef(角度,x,y,z)
縮放比例:glScalef ( ) 
備分矩陣:glPushMatrix();
還原矩陣:glPopMatrix();

4. CodeBlocks開GLUT專案, 目錄選桌面, 專案名取week03_mouse

5. GLUT要選桌面的 freeglut

6. 複製上一個程式碼

7. 修改並加上幾行程式碼讓茶壺跟著滑鼠移動
float teapotX = 0, teapotY = 0;
void mouse(int button, int state, int x, int y){
    teapotX = (x-150)/150.0;
    teapotY = -(y-150)/150.0;
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
        glTranslatef(teapotX, teapotY, 0);
        glutSolidTeapot( 0.3 );
    glPopMatrix();
    glutSwapBuffers();
}

旋轉:week03_mouse_glRotatef

1. 用右手比「讚」來理解glRotatef(角度,x,y,z)
    轉動軸是拇指, 其他手指代表旋轉方向
    X軸:平的讚glRotatef(角度,1,0,0)
    Y軸:正常的讚glRotatef(角度,0,1,0)
    Z軸:拇指比向自己的讚glRotatef(角度,0,0,1)

2. CodeBlocks開GLUT專案, 目錄選桌面, 專案名取week03_mouse_Rotatef

3. 複製上一個程式碼

4. 修改並加上幾行程式碼讓茶壺跟著滑鼠轉動
    float angle = 0;
  glRotatef(angle, 0, 0, 1);
  void motion(int x, int y)
  {
    angle = x;
    display();
  }
  glutMotionFunc(motion);

用鍵盤W, E移動加旋轉:week03_mouse_translate_rotate

1. CodeBlocks開GLUT專案, 目錄選桌面, 專案名取week03_mouse_translate_rotate

2. 複製上一個程式碼

3. 修改並加上幾行程式碼讓茶壺跟著滑鼠轉動+移動
int method = 1;
int oldX = 0, oldY = 0;
void mouse(int button, int state, int x, int y){
    oldX = x;//teapotX = (x-150)/150.0;
    oldY = y;//teapotY = -(y-150)/150.0;
}
void motion(int x, int y)
{
    if(method==1) {
        angle += x-oldX;
    }
    else if(method==2) {
        teapotX += (x - oldX)/150.0;
        teapotY -= (y - oldY)/150.0;
    }
    oldX = x;
    oldY = y;
    display();
}
void keyboard(unsigned char key, int x, int y)
{
    if(key=='e') method=1; ///旋轉Rotate
    if(key=='w') method=2; ///移動Translate
}
glutKeyboardFunc(keyboard);

沒有留言:

張貼留言