30
S TUDY G UIDE Computer Graphics Rimvydas KRASAUSKAS Vilnius University 2012

Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

  • Upload
    dotuyen

  • View
    220

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

STUDY GUIDE

Computer Graphics

Rimvydas KRASAUSKAS

Vilnius University2012

Page 2: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Computer GraphicsStudy Guide

Cycle: FirstStudy program: Information TechnologiesCourse unit code:ITKOGAwarding institution: Department of Computer Science II, Faculty of Mathematics and Informatics

Preparation of the study guide was supported bythe project „Increasing Internationality in Study Programs of the Department of ComputerScience II“, project number VP1–2.2–ŠMM-07-K-02-070, funded by The European SocialFund Agency and the Government of Lithuania.

Studiju vadovo medžiagos rengima remeprojektas „Kompiuterijos katedros studiju programu tarptautiškumo didinimas“, projekto ko-das VP1–2.2–ŠMM-07-K-02-070, finansuojamas iš Europos socialinio fondo ir Lietuvosvalstybes biudžeto lešu.

c© Rimvydas Krasauskas, 2012c© Vilnius University, 2012

Page 3: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Contents1 Reading Guide 6

1.1 Reading list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.2 Reading references by lectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2 Homework assignments 82.1 Line drawing algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2 2D affine fractals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.2.1 2D affine transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2.2 Fractals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.3 3D rotations and quaternions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172.3.1 Algebra of quaternions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172.3.2 Reflections in space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.3.3 Rotations in space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

2.4 Bézier Curves and surfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3 Test 233.1 Examples of questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233.2 Answers and solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

4 Exam 264.1 Examples of assignments: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.2 Assessment rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

References 29

3

Page 4: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

4

Page 5: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Abstract

This is a study guide to the introductory course on computer graphics. This module teachessome graphics hardware devices, reviews the relevant mathematics, and discusses the fundamentalareas of computer graphics. After completing the course, students are expected to know theoreticalprinciples of computer graphics and to be able to apply these methods in practice, i.e. to be able todesign and implement simple 3D interactive computer graphics related programs.

5

Page 6: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

1 Reading Guide

1.1 Reading listRequired literature:

[2] S.R. Buss, 3-D Computer graphics. A Mathematical introduction with OpenGL Cambridge Uni-versity Press, 2003.

[4] OpenGL Programming Guide, The official guide for learning OpenGL, Addison Wesley, Release1, 1994. http://fly.cc.fer.hr/~unreal/theredbook/

Optional literature:

[1] E. Angel, Interactive Computer Graphics: a Top-Down Approach with Shader Based OpenGL,Addison Wesley, 2011.

[3] R.J. Rost et al., OpenGL Shading Language, Addison Wesley, 2009.

1.2 Reading references by lecturesLecture 1 Introduction to computer graphics:

• problem domain and applications,

• overview of history of computer graphics.

Lecture 2 Drawing with OpenGL [2, Chapter I, p. 1–16]:

• the simplest OpenGL program [2, Exercises I.1, I.2, p. 8],

• 2D primitives and their attributes [2, Chapter I.2, p. 4–15],

• interaction via keyboard and mousehttp://www.lighthouse3d.com/tutorials/glut-tutorial/

Lecture 3 Geometrical transformations I [2, Chapter II.1.1-II.1.3, p. 17–26]:

• 2D transformations: translation, scaling, rotation, reflection,

Lecture 4 Geometrical transformations I (continued):

• affine fractals on the plane [1, Chapter 11.7]

Lectures 5-6 Geometrical transformations II:

• matrices and homogeneous coordinates [2, Chapter II.1.1-II.1.3, p. 17–26] ,

• 3D transformations [2, Chapter II.2, p. 34–46],

• viewing transformations and perspective [2, Chapter II.3, p. 46–57].

Lecture 7 Geometric modeling:

• 3D data sources and acquisition,

• representation schemes, hierarchy.

6

Page 7: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Lectures 8-9 Geometric models:

• primitive 3D shapes,

• indexed face sets,

• 3D modeling packages: wings3d, SketchUp.

Lectures 10-11 Lighting and shading [2, Chapter III.1]:

• Phong lighting model, illumination and materials,

• Phong and Gouroud shading methods.

Lectures 12-13 Texturing [2, Chapter V]:

• parametrization of primitive surfaces (cylinder, cone, sphere, torus),

• texture space and coordinates, automatic texture generation,

• mipmapping, filtering, bumpmapping.

Lectures 14-15 Advanced geometric models [2, Chapter VII]:

• Bezier curves and surfaces, De Casteljau algorithm,

• splines, NURBS,

• subdivision surfaces.

7

Page 8: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

2 Homework assignments

2.1 Line drawing algorithmIt is impossible to draw the exact line on the raster grid. Hence, we need to approximate the true

line. The first and most famous algorithm for line drawing was developed by Jack E. Bresenham in1962 at IBM. Here we consider this Bresenham line drawing algorithm in details.

The goal is to draw a line between two points (x0, y0) and (x1, y1) on a raster grid, as it is shown inFig. 2.1.

Figure 2.1: A line segment on the raster grid.

It is easy to derive the equation of the line

y = k(x− x0) + y0, k =y1 − y0x1 − x0

.

For simplicity, let us first restrict the allowable slopes of the line 0 ≤ k ≤ 1.Suppose, the line-drawing routine so always increments x as it plots. When the routine plots a point

at (x, y), there are only two possibilities for the next point on the line: either the point (x+ 1, y) or thepoint (x + 1, y + 1). The idea is to keep track of error, i.e. difference between the true line and thecorresponding point on the raster grid.

Listing 1: drawLine (float-point version).

1 void drawLine ( i n t x0 , i n t y0 , i n t x1 , i n t y1 )2 {3 i n t dx = x1 – x0 ;4 i n t dy = y1 – y0 ;5 i n t y = y0 ;6 f l o a t e = 0 . 0 ;7 f o r ( i n t x = x0 ; x < x1 ; x ++) / / −0.5 <= e < 0 . 58 {9 d r a w P o i n t ( x , y ) ;

10 e = e + dy / dx ;11 i f ( e >= 0 . 5 ) { y = y +1; e = e − 1 . 0 ; }12 }13 }

8

Page 9: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Here we use floating point operations, that should be avoided in order to increase the speed ofdrawing. So we multiply the error e by 2dx and shift the resulting range of e from [−dx, dx) to [0, 2dx)(only lines from 6 to 12 are changed):

Listing 2: drawLine (integer version).

6 i n t e = dx ;7 f o r ( i n t x = x0 ; x < x1 ; x ++) / / 0 <= e < 2∗dx8 {9 d r a w P o i n t ( x , y ) ;

10 e = e + 2∗dy ;11 i f ( e >= 2∗dx ) { y = y +1; e = e − 2∗dx ; }12 }

The Bresenham algorithm results from then moving the update of the error to after the comparison,shifting the initial value of e, and using a zero test in the ’if’ statement (only lines from 6 to 12 arechanged):

Listing 3: drawLine (Bresenham algorithm).

6 i n t e = 2∗dy − dx ;7 f o r ( i n t x = x0 ; x < x1 ; x ++) / / 2∗dy − dx <= e < 2∗dy + dx8 {9 d r a w P o i n t ( x , y ) ;

10 i f ( e >= 0) { y = y +1; e = e − 2∗dx ; }11 e = e + 2∗dy ;12 }

Homework assignment 1: - Bresenham’s line algorithm

Writte a code of OpenGL programm visualizing line drawing:

• draw a line segment between two points onto a square-shaped window consisting of 32×32 equalsmall squares;

• user interface (mouse, keyboard, menu) should allow to choose endpoints of the line; convenienceof the user interface is important!

• the true line segment (shown, e.g. in red) should be approximated by nearest squares;

• switching endpoints of the segment should produce the same result! (see Fig. 2.2, where wereare two different possibilities to draw the same line - two pixels are in equal distance from thetrue line).

Figure 2.2: Two possibilities to draw the same line.

9

Page 10: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

• compare float point and integer versions of the algorithm by their computational speed (by draw-ing accidental lines many times); think about how to estimate pure time of computation notincluding drawing time;

• (additional points): check if your code draws the same lines as the standard OpenGL functions.

RemarkFor graphical windows and user interface use the GLUT library, see e.g.http://www.lighthouse3d.com/tutorials/glut-tutorial/

2.2 2D affine fractals2.2.1 2D affine transformations

How to represent points and vectors on a plane? We will begin by considering vectors, lineartransformations (i.e. elements of linear algebra) and then generalize them to affine case. We knowfrom linear algebra that if we have a basis (i.e. 2 linearly independent vectors) (~e1, ~e2) then we canrepresent any other vector on the plane uniquely as a linear combination, which can be expressed in theformal matrix notations

~v = x1~e1 + x2~e2 =(~e1 ~e2

)( x1x2

)for some scalars x1 and x2.

For any other basis (~e ′1, ~e′2) we can express its vectors in the former basis: ~e ′1 = a11~e1 + a21~e2 and

~e ′2 = a12~e1 + a22~e2, or in the matrix form:(~e ′1 ~e ′2

)=(~e1 ~e2

)( a11 a12a21 a22

)(1)

Then denoting by x′1 and x′2 coordinates of the same vector ~v in the new basis we have

~v = x′1~e′1 + x′2~e

′2 =

(~e ′1 ~e ′2

)( x′1x′2

)=(~e1 ~e2

)( a11 a12a21 a22

)(x′1x′2

).

Therefore, transformation of coordinates are defined by the inverse of matrix that transformation of thecoordinate systems:(

x1x2

)=

(a11 a12a21 a22

)(x′1x′2

),

(x′1x′2

)=

(a11 a12a21 a22

)−1(x1x2

).

The simplest examples are:

• scaling with factors λ1, λ2

S(λ1,λ2) =

(λ1 00 λ2

),

in particular, S(−1,1) is the reflection with respect to x2-axis, and S(−1,−1) is the central symmetry(coinciding with the rotation by angle α = π, see below);

• rotation by the angle α (counter clock-wise)

Rα =

(cos α − sin αsin α cos α

).

10

Page 11: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Affine plane contains points. Vectors appear as differences of points (see e.g. ...). We will treatpoints and vectors as objects of different type. To define coordinates for an affine plane we would liketo find some way to represent any object (point or vector) as a sequence of scalars. Thus it seemsnatural to generalize the notion of a basis in linear algebra to define a basis in affine plane. Note thattwo vectors alone are not enough to define a point since we cannot define a point by any combinationof vector operations. Indeed, to specify position we will designate an arbitrary a point denoted O toserve as the origin of our coordinate frame. We see that for any point P , P −O is just some vector ~v.Such a vector can be expressed uniquely as a linear combination of basis vectors. Therefore, given theorigin pointO and a couple of basis vectors (~e1, ~e2) any point P can be expressed uniquely as a sum ofO and some linear combination of the basis vectors

P = x1~e1 + x2~e2 +O =(~e1 ~e2 O

) x1x21

.

Now we have a possibility to consider transformations between coordinate systems that can have dif-ferent origins. Similarly to transformation of vector basis (1), we can describe transformations of affineframes (~e1, ~e2,O) and (~e ′1, ~e

′2,O′):

(~e ′1 ~e ′2 O′

)=(~e1 ~e2 O

) a11 a12 a13a21 a22 a230 0 1

. (2)

The matrix A on the right in (2) corresponds to most general affine transformation. The simplestexamples include earlier described linear transformations and translations:

• scaling with factors λ1, λ2

S(λ1,λ2) =

λ1 0 00 λ2 00 0 1

;

• rotation by the angle α (counter clock-wise)

Rα =

cos α − sin α 0sin α cos α 0

0 0 1

;

• translation by a vector ~u = u1~e1 + u2~e2

T~u =

1 0 u10 1 u20 0 1

;

The general affine matrix A can be decomposed into the product of two simple ones A = T~uL, i.e.translation by vector ~u = a13~e1 + a23~e2 and the general linear transformation L: a11 a12 a13

a21 a22 a230 0 1

=

1 0 a130 1 a230 0 1

a11 a12 0a21 a22 00 0 1

. (3)

11

Page 12: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

2.2.2 Fractals

Fractals can be shortly defined as geometric objects with two properties:

• self-similarity, i.e. the whole object is similar to its smaller parts;

• having fractal dimension.

Let us informally discuss dimensions by considering three simple examples: a unit line segment I , aunit square S, and a unit cube C. We expect that these objects are 1-, 2-, and 3-dimensional, respec-tively. Suppose we try to measure them with the smallest unit ε = 1/n, for a certain integer n. Bydividing each of the objects into similar parts of that size, we see that the line segment I will haveN = n parts, the unit square S will have N = n2 parts, and the unit cube C will have N = n3 parts. Ineach case we have generated new objects by scaling the original object by a factor of ε and replicatingit k times. In all cases k = nd, where d is dimension of the considered object. Hence, solving for d weget

lnN = ln(nd) = d lnn, d =lnN

lnn.

Therefore, the formula d = lnN/ lnn can be treated as approximate dimension formula, when n goesto infinity. Hence, the fractal dimension of an object is determined by how many similar objects wecreate by subdivision.

Consider one more example – the Sierpinski triangle (also called gasket). We start from a triangle,subdivide it in 4 equal parts, and erase the middle part. For the three remaining triangles we apply thesame procedure and repeat this infinite number of times. The figure that will remain in limit is calledthe Sierpinski triangle (see Fig. 2.3). Let us count dimension: after k iteration steps the side of triangle

Figure 2.3: The Sierpinski triangle generation by subdivision.

is subdivided into n = 2k parts, but the Sierpinski triangle itself will have N = 3k similar parts. Hence

d = limn→∞

lnN

lnn= lim

k→∞

ln 3k

ln 2k= lim

k→∞

k ln 3

k ln 2=

ln 3

ln 2≈ 1.58496

This is a particular case of 2D affine fractals which we are going to study below.This kind of fractals can be defined using iterated function system (IFS) approach. For a collection

of affine transformations {f1, . . . , fr : R2 → R2} of a plane, define the Hutchinson operator

H(X) =r⋃i=1

fi(X), X ⊂ R2,

12

Page 13: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

acting on subsets in the plane R2. If all transformations fi are similarities (i.e. they preserve angles andchange all distances in the same ratio) with scaling coefficient less than 1 then for every compact set ∆(e.g. ∆ can be finite number of points and/or polygons in R2)

F = limn→∞

H◦n(∆), H◦n = H ◦H ◦ · · · ◦H︸ ︷︷ ︸n times

,

exists and is called a fractal generated by IFS {f1, . . . , fr}. Actually, the existence and uniqueness of Fis a consequence of the contraction mapping principle, where F plays a role of a fixed point (i.e. set inthis case) of the Hutchinson operator: F = H(F ). The interesting consequence: the limit figure F doesnot depend on the initial figure ∆! The resulting fractal F depends only on the list of IFS {f1, . . . , fr}.

Let all IFS transformations {f1, . . . , fr} are similarities with scaling coefficients {λ1, . . . , λr}. Thenthere is a simple formula for the dimension d of the fractal:

λd1 + · · ·+ λdr = 1. (4)

See derivation in: http://classes.yale.edu/fractals/fracanddim/Moran/Moran.htmlConsider a simple case of affine fractal – the Sierpinski triangle (see Fig. 2.3). The generating IFS

has three transformations:

f1 = S0.5, f2 = T0.5~e1S0.5, f3 = T0.5~e2S0.5,

where S0.5 = S(0.5,0.5) is a uniform scaling by factor 1/2.We present an OpenGL code that shows several initial figures that eventually converges to this

fractal. Listing 4 the function drawFractal() that actually draws a triangle on the step 0, andproceeds recursively applying three transformations f1, f2, f3.

Listing 4: Function drawFractal().

1 void d r a w F r a c t a l ( i n t s t e p )2 {3 sw i t ch ( s t e p ) {4 case 0 :5 g l B e g i n ( GL_TRIANGLES ) ;6 g l V e r t e x 3 f ( 1 . 0 , 0 . 0 , 0 . 0 ) ;7 g l V e r t e x 3 f ( 0 . 0 , 1 . 0 , 0 . 0 ) ;8 g l V e r t e x 3 f ( 0 . 0 , 0 . 0 , 0 . 0 ) ;9 glEnd ( ) ;

10 break ;11 d e f a u l t :12 g l P u s h M a t r i x ( ) ;13 g l P u s h M a t r i x ( ) ;14 g l S c a l e f ( 0 . 5 , 0 . 5 , 1 . 0 ) ;15 d r a w F r a c t a l ( s t e p −1) ;16 g l P o p M a t r i x ( ) ;17 g l T r a n s l a t e f ( 0 . 5 , 0 . 0 , 0 . 0 ) ;18 g l S c a l e f ( 0 . 5 , 0 . 5 , 1 . 0 ) ;19 d r a w F r a c t a l ( s t e p −1) ;20 g l P o p M a t r i x ( ) ;21 g l T r a n s l a t e f ( 0 . 0 , 0 . 5 , 0 . 0 ) ;22 g l S c a l e f ( 0 . 5 , 0 . 5 , 1 . 0 ) ;23 d r a w F r a c t a l ( s t e p −1) ;24 break ;25 }26 }

13

Page 14: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Listing 5 contains the full code that uses the function drawFractal(). Interactivity is sim-ple: by pressing space bar one goes to the next step, ’escape’ button ends the program. The functionresizeWindow() is relatively sophisticated because it takes into account non-square shaped win-dows (the fractal picture is not deformed - can be only uniformly scaled).

Listing 5: Recursive Sierpinski Triangle.

1 # i n c l u d e < s t d l i b . h>2 # i n c l u d e < s t d i o . h>3 # i n c l u d e <GL/ g l u t . h>45 i n t C u r r e n t S t e p = 0 ;6 c o n s t i n t MaxStep = 1 0 ;7 c o n s t double Xmin = −0.1 , Xmax = 1 . 1 ;8 c o n s t double Ymin = −0.1 , Ymax = 1 . 1 ;9

10 void myKeyboardFunc ( u n s i g n e d char key , i n t x , i n t y )11 {12 sw i t ch ( key ) {13 case ’ ’ :14 C u r r e n t S t e p = ( C u r r e n t S t e p +1)%MaxStep ;15 g l u t P o s t R e d i s p l a y ( ) ;16 break ;17 case 2 7 :18 e x i t ( 1 ) ;19 }20 }2122 void d r a w F r a c t a l ( i n t s t e p ) { . . . }2324 void drawScene ( void )25 {26 g l C l e a r (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ;27 g l C o l o r 3 f ( 1 . 0 , 1 . 0 , 1 . 0 ) ;28 glMatr ixMode (GL_MODELVIEW) ;29 g l L o a d I d e n t i t y ( ) ;30 d r a w F r a c t a l ( C u r r e n t S t e p ) ;31 g l F l u s h ( ) ;32 }3334 void i n i t R e n d e r i n g ( )35 {36 g l E n a b l e ( GL_DEPTH_TEST ) ;37 }3839 void res izeWindow ( i n t w, i n t h )40 {41 double s c a l e , c e n t e r ;42 double windowXmin , windowXmax , windowYmin , windowYmax ;43 g l V i e w p o r t ( 0 , 0 , w, h ) ;44 w = (w==0) ? 1 : w;45 h = ( h ==0) ? 1 : h ;46 i f ( ( Xmax−Xmin ) /w < ( Ymax−Ymin ) / h ) {47 s c a l e = ( ( Ymax−Ymin ) / h ) / ( ( Xmax−Xmin ) /w) ;48 c e n t e r = (Xmax+Xmin ) / 2 ;49 windowXmin = c e n t e r − ( c e n t e r−Xmin ) ∗ s c a l e ;50 windowXmax = c e n t e r + ( Xmax−c e n t e r ) ∗ s c a l e ;

14

Page 15: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

51 windowYmin = Ymin ;52 windowYmax = Ymax ;53 }54 e l s e {55 s c a l e = ( ( Xmax−Xmin ) /w) / ( ( Ymax−Ymin ) / h ) ;56 c e n t e r = (Ymax+Ymin ) / 2 ;57 windowYmin = c e n t e r − ( c e n t e r−Ymin ) ∗ s c a l e ;58 windowYmax = c e n t e r + ( Ymax−c e n t e r ) ∗ s c a l e ;59 windowXmin = Xmin ;60 windowXmax = Xmax ;61 }62 glMatr ixMode ( GL_PROJECTION ) ;63 g l L o a d I d e n t i t y ( ) ;64 g l O r t h o ( windowXmin , windowXmax , windowYmin , windowYmax , −1, 1 ) ;65 }6667 i n t main ( i n t argc , char ∗∗ a rgv )68 {69 g l u t I n i t (& argc , a rgv ) ;70 g l u t I n i t D i s p l a y M o d e (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH ) ;71 g l u t I n i t W i n d o w P o s i t i o n ( 20 , 60 ) ;72 g l u t I n i t W i n d o w S i z e ( 500 , 500 ) ;73 g lu tCrea teWindow ( " S i e r p i n s k i t r i a n g l e " ) ;74 i n i t R e n d e r i n g ( ) ;75 g lu tKeyboa rdFunc ( myKeyboardFunc ) ;76 g l u t R e s h a p e F u n c ( res izeWindow ) ;77 g l u t D i s p l a y F u n c ( drawScene ) ;78 f p r i n t f ( s t d o u t , " P r e s s s p a c e b a r −> t h e n e x t s t e p ; e s c −> t o q u i t . \ n " ) ;79 glu tMainLoop ( ) ;80 re turn ( 0 ) ;81 }

15

Page 16: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Figure 2.4: The example of 2D affine fractal.

Homework assignment 2: - Draw 2D fractal

For a given picture of 2D affine fractal in a square (e.g. see Fig. 2.4) write an OpenGL program thatrecreates this picture:

• find main 4 transformations that define IFS (iterated functional system) of the given fractal, andcalculate its dimension;

• write an OpenGL program that recreates the picture, where different 4 parts (that correspond to4 transformations) are colored differently; use Listings 5 and 4 as initial example;

• present an alternative code that uses probability approach.

16

Page 17: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

2.3 3D rotations and quaternions

2.3.1 Algebra of quaternions

Complex numbers are an extension of the real number system and can be written in the form a+ bi,where a and b are both real numbers and i is called an imaginary unit with the property i2 = −1. Thequaternions are just a further extension of these complex numbers. A quaternion is usually written as

q = a+ bi + cj + dk,

where a, b, and c are scalar values, and i, j and k are the special quaternions satisfying conditions

i2 = −1, j2 = −1, k2 = −1

andij = k, jk = i, ki = j, ji = −k, kj = −i, ik = −j.

Addition of quaternions is defined as addition of vectors. Hence for the two quaternions

q1 = a1 + b1i + c1j + d1k, q2 = a2 + b2i + c2j + d2k,

their sum of the two quaternions is

q1 + q2 = (a1 + a2) + (b1 + b2)i + (c1 + c2)j + (d1 + d2)k.

Multiplication is more complicated: first we have to multiply component-wise, and then use the productformulas for i, j, and k to simplify the resulting expression. Hence the product of q1 and q2 is

q1q2 = (a1 + b1i + c1j + d1k)(a2 + b2i + c2j + d2k)

= a1a2 + a1b2i + a1c2j + a1d2k + b1a2i + b1b2i2 + b1c2ij + b1d2ik

+ c1a2j + c1b2ji + c1c2j2 + c1d2jk + d1a2k + d1b2ki + d1c2kj + d1d2k

2

= (a1a2 − b1b2 − c1c2 − d1d2) + (a1b2 + a2b1 + c1d2 − d1c2)i+ (a1c2 + a2c1 + d1b2 − b1d2)j + (a1d2 + a2d1 + b1c2 − c1b2)k.

It will be convenient to use the following alternative representation of quaternions. Any quaternionqcan be represented as a sum of its scalar (real) part and its vector (imaginary) part:

q = r + v = r1 + v1i + v2j + v3k, r = Re(q), v = Im(q).

The product of quaternions in these notations has the following compact formula:

qq′ = (r + v)(r′ + v′) = (rr′ − v · v′) + (rv′ + r′v + v × v′),

where v · v′ and v × v′ are dot and vector products of vectors in R3. If q = r + v then q = r − v iscalled a conjugate quaternion. The norm of a quaternion (or its length) is |q| =

√qq. If q is a non-zero

quaternion the it has the inverse q−1 = q/|q|2. Indeed,

q−1q = qq−1 = qq/|q|2 = 1.

17

Page 18: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

2.3.2 Reflections in space

If q ∈ ImH then it is a vector q = v = v1i + v2j + v3k. We will identify vectors in 3D space R3

with imaginary quaternions ImH. Therefore, we can multiply vectors (as quaternions):

vv′ = −v · v′ + v × v′, (5)

Also conjugation and inverse operations are defined:

v = −v, v−1 = −v/|v|2. (6)

Let v and n are vectors, |n| = 1, then operation

Anv = nvn

defines a reflection about the plane perpendicular to n (and passing through the origin).Indeed, using the identity for the cross product

(a× b)× c = (a · c)b− (b · c)a

one can derivenvn = (n× v)× n− (n · v)n = v − 2(n · v)n.

The vector v − 2(n · v)n is exactly the reflection of v with respect to n.

2.3.3 Rotations in space

Recall that any rotation in space is a composition of two reflections, and the rotation angle is twicebigger than the angle between the planes of reflections. In terms of quaternions this can be expressedas

Rv = An2An1v = n2n1vn1n2 = qvq−1,

where q = n2n1 (see (6)). Using (5) we get

q = n2n1 = −n2 · n1 + n2 × n1.

Suppose the rotational angle is θ and the rotational axis is defined by the unit vector u (in the directionof n1 × n2). Then

n2 · n1 = − cosθ

2, n2 × n1 = − sin

(θ2

)u.

Finally the quaternion q is expressed via θ and u:

q = ± cosθ

2± sin

(θ2

)u. (7)

Now we are ready to derive matrix representation of the rotation, which is given by a unit quaternionq. That is, we are looking for the matrix that affects a rotation about an axis u by angle θ in R3. Assumeq = q0 + q, q = q1i + q2j + q3k, is a unit quaternion, i.e. |q|2 = q20 + |q|2 = 1. Then, from v′ = qvqwe can determine the matrix that transforms the components of a given vector v to those of v′. Wecalculate the first product

v′ = (q0 + q)v(q0 − q) = (−q · v + q0v + q× v)(q0 − q).

18

Page 19: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Since (q× v) · q = 0, the real part is zero:

Rev′ = −q0(q · v) + (q0v + q× v) · q = 0.

Therefore, using (q× v)× q = (q · q)v − (v · q)q we get

v′ = Imv′ = (q · v)q + q20v + q0(q× v)− q0(v × q)− (q× v)× q

= (q20 − q · q)v + 2q(q · v) + 2q0q× v.

Hence, the matrix R, such that v′ = Rv, can be extracted

R = (q20 − q · q)I + 2qqT + 2q0

0 −q3 q2q3 0 −q1−q2 q1 0

Finally the rotational matrix R corresponding to the quaternion q = q0 + q1i + q2j + q3k is

R =

q20 + q21 − q22 − q23 q1q2 − q0q3 q1q3 + q0q2q1q2 + q0q3 q20 − q21 + q22 − q23 q2q3 − q0q1q1q3 − q0q2 q2q3 + q0q1 q20 − q21 − q22 + q23

(8)

The same matrix R in terms of angle θ and rotational axis u = u1i + u2j + u3k is

R = (cos θ)I + (1− cos θ)

u21 u1u2 u1u3u2u1 u22 u2u3u3u1 u3u2 u23

+ sin θ

0 −u3 u2u3 0 −u1−u2 u1 0

.

Denoting c = cos θ and s = sin θ we get

R =

(1− c)u21 + c (1− c)u1u2 − su3 (1− c)u1u3 + su2(1− c)u2u1 + su3 (1− c)u22 + c (1− c)u2u3 − su1(1− c)u3u1 − su2 (1− c)u3u2 + su1 (1− c)u23 + c

. (9)

Homework assignment 3: - Draw 3D fractal

For a given text file with a ’cloud’ of points (i.e. their coordinates) representing a 3D affine fractalin a unit cube write an OpenGL program:

• that interactively demonstrates this cloud of points;

• find main 4 transformations that define IFS of the given fractal;

• the program should iteratively recreate the 3D fractal as polyhedral shape with the possibility tolook at it from all directions with minimal shading;

• animate each of 4 transformations as a composition of translation, rotation, and scaling.

19

Page 20: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

2.4 Bézier Curves and surfacesA Bézier curve of degree 1 is a line segment with endpoints p0 and p1 parametrized as usual

p10(t) = (1− t)p0 + tp1.

The first non-trivial case is a Bézier curve of degree 2, also called a quadratic Bézier curve. This curveis built using repeated linear interpolations. Let p0,p1,p2 be three given points and let 0 ≤ t ≤ 1. Wecalculate:

p10(t) = (1− t)p0 + tp1

p11(t) = (1− t)p1 + tp2

p20(t) = (1− t)p1

0(t) + tp11(t).

Inserting the first two equations into the third one, we get

p20(t) = (1− t)2p0 + 2(1− t)tp1 + t2p2. (10)

This formula is quadratic in t and defines the quadratic Bézier curve. The point p20 traces out the curve,

if t varies in the interval [0, 1]. In Fig. 2.5 the geometric construction of the curve point p20 for t = 1/3

is shown.

Figure 2.5: De Casteljau algorithm for quadratic and cubic Bézier curve.

For 0 ≤ t ≤ 1 the curve lies in the triangle formed by p0,p1,p2. This is called the convex hullproperty. As special points we have p2(0) = p0 and p2(1) = p2. The construction also shows thefollowing property:

ratio(p0,p10,p1) = ratio(p1,p

11,p2) = ratio(p1

0,p20,p

11) =

t

1− t. (11)

All ratios are equal, this proves the affine invariance of the curve construction. If you look at Fig. 2.5,you see that for t = 0 the curve is tangent to the line p0p1 and for t = 1 it is tangent to the line p1p2.Similarly a cubic Bézier curve (i.e. of degree 3) is defined by four control points see Fig. 2.5(right):

p30(t) = (1− t)3p0 + 3(1− t)2tp1 + 3(1− t)t2p2 + t3p3. (12)

20

Page 21: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

In order to represent other curves of degree 2 (e.g. circles) we need to generalize the introducedformulas. Let us start from the description of a rational quadratic Bézier curve:

p(t) =(1− t)2w0p0 + 2(1− t)tw1p1 + t2w2p2

(1− t)2w0 + 2(1− t)tw1 + t2w2

. (13)

As you can see, every point is associated with it’s own weight. This is the general form of a rationalquadratic Bézier curve. With some more involved math it can be translated into a simpler form, whichis called the standard form and it looks like this:

p(t) =(1− t)2p0 + 2(1− t)twp1 + t2p2

(1− t)2 + 2(1− t)tw + t2. (14)

The outer weights w0 and w2 are gone (their value is 1) and the central inner weight is transformed tow. The term rational simply reflects the fact, that every rational Bézier curve is build from a rationalexpression, which is much more complicated then the expression for integral curves.

Figure 2.6: The middle weight variation of a rational quadratic Bézier curve.

Using rational Bézier surfaces one can represent patches of straight circular cylinders, spheres andtorus patches (see Fig. 2.7). Details can be found in [2, Chapter VII.13-14].

Figure 2.7: Representing a 1/16 of a torus as a rational bi-quadratic Bézier surface.

21

Page 22: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

Homework assignments 4-5: - Render 3D object using various CG techniques

Create a scene on the horizontal square with two vertical walls in one corner and one object in thecenter.

• The user interface – the menu invoked by RMB click.

• The object is a 3D solid made of cubes wings3d formate several distinguished edges that shouldbe rounded according to the example on Fig. 2.8 (use Bézier surfaces for rounding!); the roundingradius is controlled by keys “R” (increase) and “r” (decrease).

• Navigation: at least two types – “walk” (use arrow-keys), “examine”, or “game like”.

• Collisions are computed in the “walk” mode with the walls and with the bounding box of theobject (sliding – additional scores).

• Adjustable light sources: directional, point and spot light.

• The object shadow on the horizontal square and vertical walls.

• Camera control: at least 5 different viewpoints, orthogonal and perspective projections, ad-justable fov (fiels of view).

• Textures on the object that is compatible with textures on Bézier surfaces.

Figure 2.8: The ’cubical’ object with distinguished edges and its rounding.

22

Page 23: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

3 Test

3.1 Examples of questionsHere are examples of questions in the test.

1. Sketch a picture, that will be drawn by OpenGL code below, if a function drawTriangle() drawsa triangle with vertices (0, 0, 0), (1, 0, 0), (0, 2, 0):

Listing 6: Fragment of OpenGL code.

1 glMatr ixMode (GL_MODELVIEW) ;2 g l L o a d I d e n t i t y ( ) ;3 g l R o t a t e f ( 4 5 . 0 , 0 . 0 , 0 . 0 , 1 . 0 ) ;4 g l T r a n s l a t e f ( 2 . 0 , 0 . 0 , 0 . 0 ) ;5 g l P u s h M a t r i x ( ) ;6 g l T r a n s l a t e f ( 0 . 0 , − 2 . 0 , 0 . 0 ) ;7 d r a w T r i a n g l e ( ) ;8 g l P o p M a t r i x ( ) ;9 g l R o t a t e f ( 1 8 0 . 0 , 0 . 0 , 0 . 0 , 1 . 0 ) ;

10 g l T r a n s l a t e f ( 0 . 0 , − 2 . 0 , 0 . 0 ) ;11 d r a w T r i a n g l e ( ) ;

2. Express a given affine transformation matrix of as a product of three matrices, that correspond toscale, rotation and translation: −2 −1 2

−2 1 −10 0 1

.

3. For a given picture of affine fractal find matrices of the main 4 transformations (its iterated func-tional system), and calculate its dimension:

Figure 3.1: The picture of 2D affine fractal.

23

Page 24: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

4. First we apply rotation by −90 degrees about y axis, then we rotate by 180 degrees about x axis.Find the angle and axis of the composite rotation:

(a) using matrix approach;(b) using quaternions.

3.2 Answers and solutions1. See Fig. 3.2.

Figure 3.2: The triangle drawn by triangleDraw(), and the final picture.

2. Here is decomposition into product of scaling, rotation, and translation (from right to left): −2 −1 2−2 1 −10 0 1

=

1 0 20 1 −10 0 1

1√2− 1√

20

1√2

1√2

0

0 0 1

−2√

2 0 0

0√

2 00 0 1

.

3. The main 4 transformations of our iterated functional system have following matrices (visuallycorresponding to the four quadrants of the square that contains the picture) 0.5 0 0

0 0.5 0.50 0 1

0.25 0 0.750 0.25 0.750 0 1

0 −0.5 0.5

0.5 0 00 0 1

0.5 0 0.50 0.5 00 0 1

The fractional dimension can be computed using Moran formula (4). since all transformationsare similarities (where d is dimension of the fractal):

λd1 + λd2 + λd3 + λd4 = 1, λ1 = 1/4, λ2 = λ3 = λ4 = 1/2

Denoting x = 1/2d we get the quadratic equation x2 + 3x − 1 = 0 with the positive rootx = (

√13− 3)/2. Finally

d = log2

1

x= log2

2√13− 3

= log2

3 +√

13

2≈ 1.723678968

24

Page 25: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

4. Answer: 180 degrees, axis (1/√

2, 0,−1/√

2).

(a) Solution by matrix approachwe represent rotations by their matrices and then multiply them (note right-to-left order) 1 0 0

0 −1 00 0 −1

0 0 −10 1 01 0 0

=

0 0 −10 −1 0−1 0 0

= M.

Since the matrix M = (mij) is a rotational matrix, from (9) follows

cosα = (m11 +m22 +m33 − 1)/2 = −1, sinα = 0.

Hence the rotational angle is θ = π (i.e. 180 degrees) and we have the following equationof matrices: 0 0 −1

0 −1 0−1 0 0

=

2u21 − 1 2u1u2 2u1u32u2u1 2u22 − 1 2u2u32u3u1 2u3u2 2u23 − 1

.

Thus −1 = 2u22 − 1, u2 = 0, and 1 = 2u21 = 2u23, i.e. u1 = ±1/√

2, u3 = ±1/√

2. On theother hand, 2u1u3 = −1. Therefore, the rotational axis is u = ±(1/

√2, 0,−1/

√2). Here

the sign is not unique because of the exceptional case θ = π.

(b) Solution using quaternionsAccording to the formula (7), the rotation by−90 degrees about y axis is represented by thequaternion

q1 = cos(−π/4) + sin(−π/4)j = (1− j)/√

2,

and the rotation by 180 degrees about x axis is represented by the quaternion

q2 = cos(π/2) + sin(π/2)i = i.

Hence the composition of these rotations is represented by the product of our quaternions

q2q1 = i(1− j)/√

2 = (i− k)/√

2 = cos(π/2) + sin(π/2)u,

where u = ±(i− k)/√

2. This is exactly the same answer.

25

Page 26: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

4 ExamExam has 4 groups of assignments:

1. viewing in OpenGL;

2. lighting and shading;

3. texturing;

4. Bézier curves and surfaces.

4.1 Examples of assignments:1. Viewing in OpenGL:

We are looking from a position (0, 2,−1) at a sphere with a center point (1, 4, 1) and radius 1.Fill empty space in the following code in such a way that the image of the sphere will be 2/3height and 1/2 width of the window, and exactly one half of the sphere will be visible.

1 glMatr ixMode ( ) ;2 g l L o a d I d e n t i t y ( ) ;3 gluLookAt ( ) ;4 glMatr ixMode ( ) ;5 g l L o a d I d e n t i t y ( ) ;6 g l u P e r s p e c t i v e ( ) ;

2. Lighting and shading:

• Mark features of ambient (respectively: diffuse, specular) reflection in the Phong lightingmodel:

© Models rough surfaces – where light scatters equally in all directions© Approximates the effect of inter-reflections© Models highlights from smooth, shiny surfaces© Has a point or directional source© Sourceless – constant over entire surface© Depends on surface normal© Does not depend on surface normal© Depends on viewpoint© Does not vary based on viewpoint

• Given three vertices A0 = (3, 1, 2), A1 = (3,−1, 3), A2 = (4,−1, 4) of a triangle computea normal of the plane that the points lie in. Explain relation between the normal directionand orientation of the triangle.

3. Texturing

• The brick texture is applied to the rectangular wall. We would like to reduce the width ofevery brick 4 times. Fill empty spaces in the following code:

26

Page 27: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

1 g l B e g i n (GL_POLYGON) ;2 g lTexCoord2f ( 0 . 0 , 0 . 0 ) ; g l V e r t e x 3 f ( − 1 . 0 , 0 . 0 , 0 . 0 ) ;3 g lTexCoord2f ( , ) ; g l V e r t e x 3 f ( 3 . 0 , 0 . 0 , 0 . 0 ) ;4 g lTexCoord2f ( , ) ; g l V e r t e x 3 f ( 3 . 0 , 2 . 0 , 0 . 0 ) ;5 g lTexCoord2f ( , ) ; g l V e r t e x 3 f ( − 1 . 0 , 2 . 0 , 0 . 0 ) ;6 glEnd ( ) ;

• Consider the torus given by the parametric equations:

x = (R + r cos θ) sinφ,

y = r sin θ,

z = (R + r cos θ) cosφ.

Find formulas for texture coordinates (s, t), 0 ≤ s, t ≤ 1, such that the center of the texturemap (0.5, 0.5) appear at the front of the torus.

4. Bézier curves and surfaces

• Represent an arc of a unit circle x2 + y2 ≤ 0 defined by the angle 0 ≤ α ≤ 2π/3 as arational Bézier curve.

• Represent a curvilinear triangle on the plane defined by x2 + y2 ≥ 0, x ≤ 1, y ≤ 1, z = 0,as a rational Bézier surface of bi-degree (1, 2).

• Find control points and weights of 1/16 of the torus (see the parametrization formulasabove) defined by inequalities: x ≥ 0, y ≤ 0, z ≥ 0.

4.2 Assessment rules1 score for each group of assignments: 0 – incorrect, 0.5 – partially correct, 1 – correct answer.

27

Page 28: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack
Page 29: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

References[1] E. Angel. Interactive Computer Graphics: a Top-Down Approach with Shader Based OpenGL.

Addison Wesley, 2011.

[2] S.R. Buss. 3-D Computer graphics. A Mathematical introduction with OpenGL. Cambridge Uni-versity Press, 2003.

[3] R.J. Rost et al. OpenGL Shading Language. Addison Wesley, 2009.

[4] T. Davis J. Neider and M. Woo. OpenGL Programming Guide, The official guide for learningOpenGL. Addison Wesley, 1994.

29

Page 30: Computer Graphics - Pradžiarimask/wp-content/uploads/study_guide_RK.pdf · Computer Graphics Study ... The first and most famous algorithm for line drawing was developed by Jack

30