1 / 64

IE352 CAD/CAM 개론 Chap.3 Graphic programming - Using OpenGL, Part 2

IE352 CAD/CAM 개론 Chap.3 Graphic programming - Using OpenGL, Part 2. KAIST 산업공학과 신하용. Stock Price. World Coordinates. Stock Price. NDC. Stock Price. Date. Date. Date. Viewport Coordinates. 2D Case : Viewing transform is trivial. ModelView Matrix. Projection Matrix. Viewport.

otto
Download Presentation

IE352 CAD/CAM 개론 Chap.3 Graphic programming - Using OpenGL, Part 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. IE352 CAD/CAM개론Chap.3 Graphic programming - Using OpenGL, Part 2 KAIST 산업공학과 신하용

  2. Stock Price World Coordinates Stock Price NDC Stock Price Date Date Date Viewport Coordinates 2D Case : Viewing transform is trivial

  3. ModelView Matrix Projection Matrix Viewport Local coord. Object coord. Modeling coord. (xo, yo , zo) Viewing coord. Eye coord. Camera coord. (xv, yv , zv) Normalized Device Coord. (NDC) VDC (xd, yd , zd) Projected Coord. (xd, yd) Viewport coord. Screen coord. (xs, ys) World coord. (xw, yw , zw) Graphic transformation pipeline

  4. Modeling transformation • glVertex ( …)에 넣을 좌표값을 World coord.에서 넣는 대신 • Local-to-World coord. transformation matrix를 주고 • Local coord. 상에서의 좌표값을 입력 Local coord. World coord.

  5. Modeling transformation in OpenGL • Translate object : Trans (x, y, z) glTranslate{fd}( x, y, z ) • Rotate object around arbitrary axis : Rot (k(x,y,z), angle) glRotate{fd}( angle, x, y, z ) • angle is in degrees • Dilate (stretch or shrink) or mirror object : Scale (x, y, z) glScale{fd}( x, y, z )

  6. Viewing coord. up World coord. at eye Viewing transformation • World coord.상의 좌표값을 Camera의 위치에서 보는 Viewing coord.로 변환 • Modeling transformation + Viewing transformation  ModelView matrix in OpenGL • Modeling transformation을 안하고, world coord.로 값을 주기로 하면  ModelView matrix represents viewing transformation glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( eyex, eyey, eyez, atx, aty, atz, upx, upy, upz )

  7. (1,1,1) (-1,-1, 0) Standard NDC cube in OpenGL Projection transformation • Define viewing volume • Transform viewing volume onto Standard NDC cube • (-1, -1, 0) ~ (1,1,1) • Perspective projection glMatrixMode( GL_PROJECTION ); glLoadIdentity(); // zNear에서의 left, right, bottom, top glFrustum( left, right, bottom, top, zNear, zFar ); // or gluPerspective(fovy, aspect, zNear, zFar ); • Orthographic(parallel) projection glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( left, right, bottom, top, zNear, zFar );

  8. Near plane Far plane Viewing volume right Near plane top Far plane bottom left Viewing volume Perspective vs Orthographic(parallel) projection

  9. aspect = w/h w  h View point fovy zNear zFar gluPerspective • gluPerspective(fovy, aspect, zNear, zFar ); • fovy : 상하 방향의 시각 (degree) • aspect = w/h == glFrustum( left, right, bottom, top, zNear, zFar ); w/ top = zNear * tan (fovy / 2); bottom = -top and right = top * aspect; left = -right

  10. Viewport mapping • gluViewport(int x, int y, int width, int height); • Map NDC cube to the view port • x, y • Specify the lower left corner of the viewport rectangle, in pixels. • Defines the origin of viewport • The initial value is (0, 0). • width, height • Specify the width and height of the viewport in pixels. • When a GL context is first attached to a window, width and height are set to the dimensions of that window. • Define the size of the viewport • Window resize시 주로 불리움

  11. A simple example int main(int argc, char **argv) { glutInit(&argc, argv); // initialize window glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutCreateWindow(“Simple"); init (); initMenu (); registerCallbacks (); glutMainLoop (); return 0; } void init() { setLight (); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glOrtho (-3.0, 3.0, -3.0, 3.0, 1.0, 20.0); glMatrixMode(GL_MODELVIEW); gluLookAt(3.0, 4.0, 5.0, // eye position 0.0, 0.0, 0.0, // center (target) 0.0, 0.0, 1.0); // up vector } void setLight () { // Enable a single OpenGL light // Red diffuse light. GLfloat light_diffuse[] = {1.0, 0.0, 0.0, 1.0}; // Infinite light location. GLfloat light_position[] = {1.0,1.0,5.0,0.0}; glLightfv(GL_LIGHT0, GL_DIFFUSE,light_diffuse); glLightfv(GL_LIGHT0, GL_POSITION,light_position); glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); }

  12. A simple example - cont void registerCallbacks () { // register call back func glutDisplayFunc(displayBox); glutReshapeFunc(resize); glutMouseFunc(mouseButton); glutMotionFunc(mouseMove); } void drawBox() { glutSolidCube (2.0); } void drawBox2 () { glMatrixMode (GL_MODELVIEW); glPushMatrix (); // draw 1st cube drawBox (); // draw 2nd cube glTranslatef (0.0, 0.0, 2.0); glScalef (0.5, 0.5, 1.0); drawBox (); glPopMatrix (); } void displayBox() { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); drawBox2 (); glutSwapBuffers (); } void resize (int w, int h) { glViewport (0, 0, w, h); } void mouseButton (int button, int state, int x, int y) { } void mouseMove (int x, int y) { }

  13. A simple example - cont void menuFunc (int select) { switch (select) { case 1 : // box glutDisplayFunc (displayBox); break; case 2 : // sphere glutDisplayFunc (displaySphere); break; case 3: // flat glShadeModel (GL_FLAT); break; case 4: // smooth glShadeModel (GL_SMOOTH); break; case 0 : // quit menu exit(0); break; default : ; // do something } glutPostRedisplay(); } void initMenu () { glutCreateMenu(menuFunc); glutAddMenuEntry ("Box", 1); glutAddMenuEntry ("Sphere", 2); glutAddMenuEntry ("Flat", 3); glutAddMenuEntry ("Smooth", 4); glutAddMenuEntry("Quit", 0); glutAttachMenu(GLUT_RIGHT_BUTTON); } void displaySphere () { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glutSolidSphere (2.0, 20, 20); glutSwapBuffers (); }

  14. Shading model : Flat & Smooth glShadeModel (GL_SMOOTH) glShadeModel (GL_FLAT)

  15. ModelView Matrix Viewing Matrix Eye coord. World coord. = ModelView Matrix Viewing Matrix Modeling Matrix Modeling Matrix Eye coord. Local coord. = … Local coord. World coord.

  16. Matrix Stack xyz’ World coord. • glPushMatrix (); • glPopMatrix (); Viewing Matrix V Modeling Matrix M1 Modeling Matrix M2 Eye coord. xyz = V V M1 V M1M2 V V M1 V

  17. frame buffer CPU pixels display list client Display lists • What’s for display processor? • CPU does everything. • Display processor(GPU) : a separate processor on a graphic card frame buffer GPU CPU primitives pixels server

  18. pixels objects CPU GPU Frame buffer objects display display command Display List re-display Immediate mode vs. Retained mode • Immediate mode pixels objects CPU GPU Frame buffer display GPU does not “remember” any of graphic objects. clear display • Retained mode • cons • requires memory on the server. • overhead of creating a display list. • pros • reduce traffic between client and server. • utilize any special hardware available on the server

  19. Display list in OpenGL • To define a new display list, glNewList (BOX, GL_COMPILE); // drawing commands, here glEndList (BOX); • To display the display list, glCallList (BOX); • Do not display now. • (c.f. GL_COMPILE_AND_EXECUTE)

  20. 은선 제거, 은면 제거 (Hidden-line/surface removal) • Back-face removal algorithm • Depth-sorting, or Painter’s algorithm • Hidden-line removal algorithm • Z-buffer method

  21. Face, Normal vector N Vertex Face Edge N Polyhedron

  22. Back-face removal algorithm (1) • A face of an object is visible if its normal vector in the direction of the outside of the object is pointing toward the viewer. MN > 0  Visible MN = 0  Line MN < 0  Invisible • 적용가능 경우 • planar face • Convex solid

  23. ? Back-face removal algorithm (2) • 적용이 어려운 경우 • 여러 개 물체, • 오목한 형상, • 곡면의 경우 • 곡면의 경우 • 실루엣 곡선 (Silhouette curve) 이용 • Curve along which M  N=0 • 계산이 복잡하고, 시점에 따라 다시 계산되어야 하므로 실용성?

  24. Edge와 face간의 위치 관계 Hidden-line removal algorithm • Back-face removal algorithm의 단점 보완 필요. • 그려질 부위만 미리 계산 • Algorithm 복잡하고, 계산시간 많이 필요

  25. Depth-sorting, or Painter’s algorithm • Hidden-surface removal • 물체의 면 (surface)을 관찰자와의 거리에 따라 정렬 (sorting)한 후, 가장 먼 거리에 있는 면부터 색깔을 채워 그린다. • 관찰자와 면간의 거리는 viewing 좌표계의 Z값 (Zv)을 기준으로 한다. 따라서 Z값이 더 크면 더 가깝다. • 여러 개의 면이 있을 경우 Zv값의 범위가 겹치는 경우가 발생함. • 면을 다시 작은 조각으로 쪼개어 Zv값의 범위가 겹치지 않도록 한다 (예: 삼각형 조각). • Triangulation (facet conversion)

  26. A D E Viewer C View Plane B Depth Sort Depth Sort • Painter’s Algorithm: • Sort surfaces in order of decreasing maximum depth • Draw surfaces in order starting with ones of greatest depth • Order : View point dependent

  27. Z-buffer method • 그리는 순서와 무관 • 스크린 상의 pixel은 관찰자와 가장 가까운 entity가 차지한다. • Z-buffer (depth buffer) : viewport pixel수만큼, 투영된 물체의 Zv값을 저장하는 HW memory • Color value for each pixel : color buffer z=3 • 각 polygon에 대해, 해당 pixel의 Zv 계산 • Zv가 저장된 Z값보다 작을 경우 • - color buffer의 해당 pixel update • (현재 polygon의 color값으로) • - z-buffer의 해당 pixel update w/ Zv z=1 z=2 z=4

  28. BSP(Binary Space Partition) Trees • BSP tree: organize all of space (hence partition)into a binary tree • Preprocess: overlay a binary tree on objects in the scene • Runtime: correctly traversing this tree enumerates objects from back to front • Idea: divide space recursively into half-spaces by choosing splitting planes • Splitting planes can be arbitrarily oriented • Notice: nodes are always convex • Ref. A Watt, F Policarpo, 3D Games : real-time rendering and software technology, Addison-Wesley, 2001, Chap.9

  29. BSP Trees: Objects

  30. BSP Trees: Objects

  31. BSP Trees: Objects

  32. BSP Trees: Objects

  33. BSP Trees: Objects

  34. Rendering BSP Trees renderBSP(BSPtree *T) BSPtree *near, *far; if (eye on left side of T->plane) near = T->left; far = T->right; else near = T->right; far = T->left; renderBSP(far); if (T is a leaf node) renderObject(T) renderBSP(near);

  35. Rendering BSP Trees renderBSP(BSPtree *T) BSPtree *near, *far; if (eye on left side of T->plane) near = T->left; far = T->right; else near = T->right; far = T->left; renderBSP(far); if (T is a leaf node) renderObject(T) renderBSP(near);

  36. Rendering BSP Trees

  37. Ouch Discussion: BSP Tree Cons • No bunnies were harmed in my example • But what if a splitting plane passes through an object? • Split the object; give half to each node: • Worst case: can create up to O(n3) objects!

  38. Plates (1-1) Wire-frame Ref : Foley et al, Computer Graphics Principles and Practice, 2nd edition, 1990, Addison-Wesley

  39. Plates (1-2) 은선 제거

  40. Plates (1-3) 은면 제거

  41. Rendering • 현실적인 느낌을 주기 위해서는 물체에 대한 빛의 효과를 나타냄. • Rendering: 색깔 + 빛의 세기 (intensity) 고려. • Rendering 기법 • Shading: 은면 제거와 유사, 단일 물체 • Ray tracing: 여러 개 물체

  42. Light modeling • Light source: 광원 • Direct illumination: 광원에 의한 직접조명 • Ambient illumination: 주변의 간접조명 • Reflected light: 반사광 • ambient + direct illumination

  43. Phong light intensity model • I = Ra + Rd + Rs • I : 눈에 들어오는 빛의 세기 • Ra : 주변광(Ambient illumination)이 반사된 빛의 세기 • Rd : 직접조명이 난반사된 반사된 빛의 세기 • Rd : 직접조명이 정반사된 반사된 빛의 세기

  44. 간접조명에 의해 반사된 빛의 세기 • Ambient illumination으로 반사된 빛의 세기 • Ra = KdIa • Ia: intensity of the ambient light • Kd: 물체 표면의 난반사율 (Diffuse reflectance coefficient) • 빛의 세기는 관찰자 위치와 무관. • 모든 위치에서 동일한 강도를 느낀다고 봄.

  45. 빛이 사방으로 방사됨.(거친 면) - 빛의 세기는 관찰자 위치와 무관함. 면에서 바로 반사됨. - 빛의 세기는 관찰자 위치에 따라 달라지게 됨. 직접조명 (광원)에 의한 반사 • 광원은 점 광원 (point light source)만을 고려. • 난반사 (diffuse reflection), 정반사 (specular reflection) • 반사광 세기 = 난반사 된 빛의 세기 + 정반사 된 빛의 세기 • Ip (반사광의 세기) = Ep(광원의 세기) / (D + D0) • D : 물체와 눈의 거리 • Do : constant added to prevent dividing by 0

  46. N L 난반사 된 빛의 세기 (Rd) • 입사각 (angle of incidence)의 cosine에 비례 • Lambert’s cosine 법칙 • Rd = Ip Kd (N•L) • Ip : 직접조명의 세기 • Kd : 물체 표면의 난반사율 (Diffuse reflectance coefficient) • N : 물체의 Normal vector • L : 입사광 방향

  47. L V H N 정반사 된 빛의 세기 • 입사 하는 빛의 방향은 L, 반사 된 빛의 방향은 R. • 관찰자가 느끼는 반사광의 세기는, R과 벗어 날수록 약해짐. • V: 관찰자가 보는 방향벡터. • Rs = Ip Ks (V•R)n • (V•R)n = (cos)n • 면이 밝을수록 n값은 커짐. 즉, 에 민감해짐. (예: 금속 n = 150, 종이 n = 1) • V•R = H•N, H=(L+V)/2 • H•N : 계산이 쉽다.

  48. Putting it together • 반사된 빛의 색깔 (color)을 고려한다면, Red, Green, Blue에 대해 식 (3.22)를 별도로 적용함 - Ir, Ig, Ib: 식 (3.23). • 이때 Ks (specular reflectance)는 일반적으로 색에 따라 달라지는 효과가 거의 없기에 분리하지 않음. • 일반적인 자유곡면에 대해서는 삼각형 등으로 잘게 쪼개어 각각의 삼각형 면의 법선 벡터 (N)을 구하여 상기 식을 적용하는 것이 일반적임. 식 (3.22)

  49. Approximations for Speed • The viewer direction, V, and the light direction, L, depend on the surface position being considered, x • Distant light approximation: • Assume L is constant for all x • Good approximation if light is distant, such as sun • Distant viewer approximation • Assume V is constant for all x • Rarely good, but only affects specularities

  50. Phong shading, Gouraud shading • 곡면을 삼각형으로 잘게 쪼개어 반사광 세기를 계산할 때, 삼각형 경계에서 법선벡터 (N)의 변화가 심하기 때문에 꺽인듯이 보임. • 법선벡터를 부드럽게 변화 시킴으로써 해결하고자 하는 노력 • Phong, Gouraud shading. • Phong shading • 삼각형 꼭지점의 법선벡터는 이웃한 삼각형의 평균법선벡터. • 삼각형 내부에서 법선벡터는 3 꼭지점 법선벡터를 조합하여 부드럽게 변화되도록 계산함. • Gouraud shading • 삼각형 꼭지점의 빛의 세기를 보간 (interpolating)하여 투영된 삼각형 내부에 들어오는 pixel에서 빛의 세기를 계산함.

More Related