Computer Graphics Lab.

parakeetincurableSoftware and s/w Development

Dec 13, 2013 (3 years and 8 months ago)

128 views

Computer Graphics Lab.

Fall 2011

Hyunki Hong

Dept. of Imaging Science & Arts, GSAIM

Chung
-
Ang Univ.

Ch.2 Getting Started: Drawing Figures


2.1 Getting started making pictures

∙ environment


-

H/W

to display pictures (the “screen”)


-

a library of S/W

tools to perform the actual drawing of graphics


primitives

∙ Every graphics program begins with some initializations.


-

establish the desired display mode


-

set up a coordinate system for specifying


points, lines, etc.



:
x

&
y

are measured in pixels

∙ examples


-

setPixel(x, y, color)


-

line(x1, y1, x2, y2)


= moveto(x1, y1) & lineto(x2, y2)


cf
. pen plotter having some current position

∙ Every environment has a different collection of tools for producing


the graphics primitives.




difficulty porting a program



3/29


device
-
independent graphics


programming !!

∙ examples


-

setPixel(x, y, color)


-

line(x1, y1, x2, y2)


= moveto(x1, y1) & lineto(x2, y2)


cf
. pen plotter having some current position

∙ Every environment has a different collection of tools for producing


the graphics primitives.




difficulty porting a program

∙ OpenGL


-

application programming interface (API)


1. a collection of routines that the programmer can call, along with


a model of how the routines work together to produce graphics


2. The programmer “sees” only the interface.




cf
. What is OpenGL?

∙ a software interface to graphics hardware

∙ a hardware independent interface to be implemented on many


different hardware platform

∙ a library for 3D CG & modeling, open (portable), high speed

∙ no commands for performing windowing tasks or obtaining user input

∙ no high
-
level commands for describing models of 3D objects


→ build up your desired models with the set of
primitives


: points, lines, polygons

∙ OpenGL Utility Library (GLU)


→ quadric surfaces, NURBS curves & surfaces

4/29

2.1.2 Windows
-
based Programming

∙ Event
-
driven programming


: The program responds to various events, such as a mouse click,


the press of a keyboard key, or the resizing of the screen window


-

an event queue


1. receive messages stating that certain events have occurred


2. deal with them on a first
-
come, first
-
served, basis.


-

a collection of callback functions that are executed when events occurs



-

"do nothing until an event occurs, and then do the specified thing"



event loop


wherein the system waits patiently in a repeating loop until it


receives an even trigger

∙ OpenGL Utility Toolkit (GLUT) for event management


5/29

∙ registering the callback function


: to associate each type of event with the desired callback function


ex
. glutMouseFunc (myMouse)



→ register the function myMouse ( ) as the function to be


executed when a mouse event occurs.

“glut”: OpenGL Utility Toolkit

6/29

∙ registering the callback function


: to associate each type of event with the desired callback function


ex
. glutMouseFunc (myMouse)



→ register the function myMouse ( ) as the function to be


executed when a mouse event occurs.



-

OpenGL drawing commands are limited in

simple geometric


primitives (points, lines, and polygons) generation, but GLUT


includes several routines for more complicated 3D objects


(a sphere, a torus, and a teapot).

∙ pseudocode for callback functions registering


: glutDIsplayFunc (myDisplay), glutReshapeFunc (myReshape)


glutMouseFunc (myMouse), glutKeyboardFunc (myKeyboard)


-

glutMainLoop ( )
→ draw the initial picture & enter an unending loop

#include <windows.h>
//
모든

Windows application


필요
. WIN32
함수

프로토타입

대부분

포함

#include <gl/glut.h>
// windows.h
파일을

포함
. gl.h(OpenGL
라이브러리

함수

정의
),


// glu.h(GLU)
파일도

포함



void RenderScene(void)
// Called to draw scene

{


// Clear the window with current clearing color


glClear(GL_COLOR_BUFFER_BIT);


glFlush();
// Flush drawing commands

}

void SetupRC(void)
// Setup the rendering state

{


glClearColor(0.0f, 0.0f, 1.0f, 1.0f);

}

void main(void)
// Main program entry point

{


glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);


glutCreateWindow("Simple");


glutDisplayFunc(RenderScene);


SetupRC();


glutMainLoop();

}

싱글

버퍼

윈도우

사용

RG䉁
컬러모드

사용

타이틀


Simple”
윈도우

생성

R敮摥牓捥湥e
함수를

디스플레이

콜백함수


사용
(r敳e穥z 浯癥
등의

e癥vt


함수

호출
)

GLUT


메인

이벤트

핸들링

루프

시작

키보드

마우스

등의

윈도우

메시지

처리

float


⡒( G, 䈬 Al灨愩p
컬러

설정


윈도우를

클리어할



사용할

컬러


현재

설정된

捬敡e
컬러로

윈도우



화면을

捬敡e
작업

지금까지의

OpenGL
명령

실행
/
처리

렌더링



초기화

2.1.3 Opening a Window for drawing

∙ The first task in making pictures is to open a screen window for
drawing.

∙ pseudocode (Fig. 2.5)


-

glutInitDIsplayMode (GLUT_SINGLE | GLUT_RGB)


-

glutInitWindowSize (640, 480)


-

glutInitWindowPosition (100, 480)


-

glutCreateWindow ("my first attempt")


+ register the callback functions ..



cf
. Until glutMainLoop() is called, the window is not yet displayed.


2.2 Drawing Basic Graphics Primitives

∙ establish the coordinate system. (Fig. 2.6)

∙ OpenGL provides tools for drawing many output primitives.


ex
. points, lines, polylines, and polygons, by one or more vertices


8/29

∙ Drawing three dots (Fig. 2.7)


-

The argument of glBegin ( ) determines which object is drawn.


ex
. GL_LINES, GL_POLYGON, etc.

∙ Format of a OpenGL commands.






∙ Fig. 2.9: Command suffixes and argument data types

glBegin(GL_PONTS);


glVertex2i(100, 50);


glVertex2i(100, 130);


glVertex2i(150, 130);

glEnd( );

9/29

∙ Encapsulating OpenGL details in the generic function drawDot ().





· OpenGL “State”


-

keep track of many state variables


-

the current size of a point


ex
. glPointSize ()


-

the current color of a drawing


ex
. glColor3f (red, green, blue)


-

the current background color, etc.

∙ Establishing the Coordinate System


-

glMatrixMode() : determine matrix mode (GL_MODELVIEW,


GL_PROJECTION: define clipping space, GL_TEXTURE:


define texture coordinates)


-

glLoadIdentity : convert current matrix into a unit matrix


-

glOrtho : define parallel clipping space.
cf
. Perspective.

10/29

∙ Fig. 2.7 & 11: a complete OpenGL program to draw three dots


-

The initialization in myInit ( ) function sets up


1. the coordinate system 2. the point size


3. the background color 4. the drawing color


-

glFlush( ) is called to ensure that all data are completely


processed and sent to the display.

11/29

#include <windows.h>
// use as needed for your system

#include <gl/Gl.h>

#include <gl/glut.h>

void myInit(void)

{


glClearColor(1.0,1.0,1.0,0.0);
// set white background color


glColor3f(0.0f, 0.0f, 0.0f);
// set the drawing color



glPointSize(4.0);


// a ‘dot’ is 4 by 4 pixels


glMatrixMode(GL_PROJECTION);


glLoadIdentity();


gluOrtho2D(0.0, 640.0, 0.0, 480.0);

}

void myDisplay(void)

{


glClear(GL_COLOR_BUFFER_BIT);
// clear the screen



glBegin(GL_POINTS);


glVertex2i(100, 50);
// draw three points


glVertex2i(100, 130);


glVertex2i(150, 130);


glEnd();



glFlush();


// send all output to display

}

void glOrtho2D(GLdouble left,


GLdouble right, GLdouble bottom,


GLdouble top);

일련의

정점들의

시작점

표시


g汅湤
함께

사용
ⰠG䱟偏乔匬N

G䱟䱉久匬⁇䱟呒T䅎A䱅匠



12⼲9

void main(int argc, char** argv)

{


glutInit(&argc, argv);
// initialize the toolkit


glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
// set display mode


glutInitWindowSize(640,480);
// set window size


glutInitWindowPosition(100, 150);
// set window position on screen


glutCreateWindow("my first attempt");
// open the screen window


glutDisplayFunc(myDisplay);
// register redraw function


myInit();


glutMainLoop();



// go into a perpetual loop

}

13/29

2.2.1 Drawing Dot constellations

∙ glutDIsplayFunc (myDisplay): the callback function for the redraw event

∙ Ex. Drawing the Sierpinski gasket (iterated function system)


-

Choose three fixed points
T
0
,
T
1
,
T
2

to form some triangles.


-

Choose the initial point
p
0

to be drawn by selecting one of the points


T
0
,
T
1
,
T
2

at random.


-

Now iterate the following steps until the pattern is satisfyingly filled in:



1. Choose one of the three points
T
0
,
T
1
,
T
2

at random; call it
T
.



2. Construct the next point
p
k

as the midpoint between
T

and the previously


found point
p
k
-
1
.



3. Draw
p
k

using drawDot ( ).

#include <iostream.h>

#include <stdlib.h>

#include <gl/glut.h>


int random (int m)

{


return rand()%m;

}

class GLintPoint{

public :


GLint x, y;

};


void myInit(void)

{


glClearColor(1.0,1.0,1.0,0.0);


// set white background color


glColor3f(0.0f, 0.0f, 0.0f);


// set the drawing color



glPointSize(3.0);




// a dot is 4 by 4 pixels


glMatrixMode(GL_PROJECTION);


glLoadIdentity();


gluOrtho2D(0.0, 640.0, 0.0, 480.0);

}


void drawDot(GLint x, GLint y)

{
// draw initial point



glBegin(GL_POINTS);


glVertex2i(x, y);


glEnd();

}


void Sierpinski(void)

{


glClear(GL_COLOR_BUFFER_BIT);




// clear the screen



GLintPoint T[3]= {{10,10},{300,30},{200, 300}};


// defines the vertices of the triangle


int index = random(3);


// choose the initial vertex randomly



GLintPoint point = T[index];

// initial point



drawDot(point.x, point.y);




// draw initial point


for(int i = 0; i < 20000; i++)

// draw 1000 dots


{


index = random(3);



point.x = (point.x + T[index].x) / 2;


point.y = (point.y + T[index].y) / 2;


drawDot(point.x, point.y);


}

glFlush();
// flushes all unfinished drawing commands


}



기본

데이터

捬慳a

15/29




//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>

void main(int argc, char** argv)

{


glutInit(&argc, argv);
// initialize the toolkit


glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
// set display mode


glutInitWindowSize(640,480);
// set window size


glutInitWindowPosition(100, 150);
// set window position on screen


glutCreateWindow("my first attempt");
// open the screen window


glutDisplayFunc(Sierpinski);
// register redraw function


myInit();


glutMainLoop();



// go into a perpetual loop

}


∙ the dot constellation is generated procedurally, which means


that each successive dot is determined by a procedural rule.

16/29

Ex 2.2.3 Simple "Dot Plots"(scale & position) & Fig. 2.16:
정규화




2.3 Line Drawings in OpenGL

∙ Use GL_LINES as the argument to glBegin(), and pass it two


endpoints as vertices.


ex
. glBegin(GL_LINES);



glVertex2i(40, 100);




glVertex2i(202, 96); //draw a line between (40, 100)



glEnd(); // & (202, 96)

∙ setting the attributes of lines
ex
. color, width, etc.

2.3.1 Drawing polylines & polygons

∙ polyline



a. a collection of line segments jointed end to end


→ line strip



b. described by an ordered list of points




→ glBegin(GL_LINE_STRIP) & glEnd()


Ex 2.3.2 Drawing polylines stored in a file



Ex 2.3.3 Parameterizing figures

void drawLine(GLint x1, GLint y1, GLint x2,

GLint y2)

{ glBgin(GL_LINES);


glVertex2i(x1, y1);


glVertex2i(x2, y2);


glEnd( ); }

17/29

#include <iostream.h>

#include <fstream.h>

#include <gl/glut.h>

void drawPolyLineFile()

{


fstream inStream;


inStream.open("dino.dat", ios ::in);


// open the file


if(inStream.fail()) return;


glClear(GL_COLOR_BUFFER_BIT);
// clear the screen



GLint numpolys, numLines, x ,y;


inStream >> numpolys;



// read the number of polylines


for(int j = 0; j < numpolys; j++)
// read each polyline


{


inStream >> numLines;


glBegin(GL_LINE_STRIP);


// draw the next polyline


for (int i = 0; i < numLines; i++) {


inStream >> x >> y;
// read the next x, y pair


glVertex2i(x, y);


}


glEnd();


}


glFlush();


inStream.close();

}

첫번째

정점이

명시된




다음

정점들은

선분에

사용

18/29

void myInit(void)


{


glClearColor(1.0,1.0,1.0,0.0);
// set white background color


glColor3f(0.0f, 0.0f, 0.0f);
// set the drawing color



glPointSize(3.0);



// a dot is 4 by 4 pixels


glMatrixMode(GL_PROJECTION);


glLoadIdentity();


gluOrtho2D(0.0, 640.0, 0.0, 480.0);

}

void main(int argc, char** argv)

{


glutInit(&argc, argv);
// initialize the toolkit


glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
// set display mode


glutInitWindowSize(640,480);
// set window size


glutInitWindowPosition(100, 150);
// set window position on screen


glutCreateWindow("my first attempt");
// open the screen window


glutDisplayFunc(drawPolyLineFile);
// register redraw function


myInit();


glutMainLoop();



// go into a perpetual loop

}



19/29

#include <iostream.h>

#include <gl/glut.h>

void myInit(void)


{


glClearColor(1.0,1.0,1.0,0.0);


glColor3f(0.0f, 0.0f, 0.0f);


glPointSize(3.0);




glMatrixMode(GL_PROJECTION);


glLoadIdentity();


gluOrtho2D(0.0, 640.0, 0.0, 480.0);

}

void drawDot(GLint x, GLint y)

{


glBegin(GL_POINTS);


glVertex2i(x, y);


glEnd();

}

void hardwiredHouse(void)

{


glClear(GL_COLOR_BUFFER_BIT);


glBegin(GL_LINE_LOOP);


glVertex2i(40, 40);
// draw the shell of house



glVertex2i(40, 90);


glVertex2i(70, 120);


glVertex2i(100, 90);


glVertex2i(100, 40);


glEnd();



glBegin(GL_LINE_STRIP);


glVertex2i(50, 100);
// draw the chimney



glVertex2i(50, 120);


glVertex2i(60, 120);


glVertex2i(60, 110);


glEnd();



// draw the door



// draw the window



glFlush();

}


void main(int argc, char** argv)

{


glutInit(&argc, argv);


glutInitDisplayMode


(GLUT_SINGLE | GLUT_RGB);


glutInitWindowSize(640,480);


glutInitWindowPosition(100, 150);


glutCreateWindow("my first attempt");


glutDisplayFunc(hardwiredHouse);



myInit();


glutMainLoop();




}



20/29

2.3.2 Line drawing using moveto ( ) & lineto ( )

∙ moveto(x, y): set CP(current position) to (x, y)

∙ lineto(x, y): draw a line from CP to (x, y), and then update CP to (x, y)


2.3.3 Drawing Aligned rectangles

∙ the aligned rectangle


: glRecti(GLint x1, GLint y1, GLint x2, GLint y2);


→ draw a rectangle with opposite corners (x1, y1) and (x2, y2)


→ fill the rectangle with the current color

∙ Fig. 2.32, 33



#
Line
-
Drawing Algorithms

∙ the Cartesian slope
-
intercept equation for a straight line


:
y

=
m


x

+
b


∙ Given the two endpoints of line segment at (
x
1
,
y
1
) & (
x
2
,
y
2
),


-

the slope :
m

= (
y
2



y
1
)/(x
2



x
1
)


-

the intercept :
b

=
y
1



m


x
1


-

For any given
x

interval
Δ
x

along a line

Δ
y

=
m

Δ
x


· We must “sample” a line at discrete positions and determine


the nearest pixel to the line at each sampled position.


ex
. mspaint.exe

22/29

Line
-
Drawing Algorithms

1
x
2
x
2
y
1
y
x

y

x
y
x
x
y
y
m
mx
y
b
b
mx
y










1
2
1
2
1
1
x
m
y




-

Assumptions

0
2
1


m
x
x


Cartesian slope
-
intercept equation

23/29


∙ Digital Differential Analyzer (DDA)


-

based on calculating either
Δ
y

or
Δ
x



-

sample the line at unit intervals in one coordinate & determine


integer values nearest the line path for the other coordinate.

24/29

DDA Algorithm



Digital Differential Analyzer


-

a scan
-
conversion line algorithm based on calculating either


Δ
y

or Δ
x



-

sample the line at unit intervals in


one coordinate and determine


corresponding integer values nearest


the line path for the other coordinate.


-

0 < Slope


1


sample at unit
x

intervals Δ
x

= 1

x1

y1

x2

y2

m
y
y
k
k



1
25/29



-

slope > 1


sample at unit
y

intervals Δ
y

= 1

∙ If the starting point is at the right,



-

unit
x

intervals Δ
x

=
-
1


-

|slope| > 1, Δ
y

=
-
1

x1

y1

x2

y2

m
x
x
k
k
1
1



DDA Algorithm

m
y
y
k
k



1
x1

y2

x2

y1

m
x
x
k
k
1
1



x1

y1

x2

y2

26/29

2.3.4 On the aspect ratio of an aligned rectangle

∙ size, position, color, shape, aspect ratio (=width/height: Fig. 2.34)

∙ alternative ways to specify a rectangle



-

its center point, height, & width : drawRectangleCenter()



-

its upper left corner, width, & aspect ratio


: drawRectangleCornerSize()



27/29

2.3.5 Filling polygons

∙ convex polygon


: A polygon is convex if a line connecting any two points of


the polygon lies entirely within it.



cf
. "bend inward" at some point (Fig. 2.37 B & C)


-

glBegin(GL_POLYGON), glVertex2f(x0, y0), & glEnd()









2.3.6 other gaphics primitives in OpenGL

A is not simple.

28/29

2.4 Simple Interaction with the Mouse and Keyboard

∙ Using the OpenGL Utility Toolkit (GLUT) the programmer can


register a callback function with each of these events.



-

glutMouseFunc(myMouse)



-

glutMotionFunc(myMovedMouse)



-

glutKeyboardFunc(myKeyboard)


2.4.1 Mouse interaction

∙ void myMouse(int button, int state, int x, int y);


-

Ex 2.4.1, 2, 3, 4

∙ Mouse motion


-

glutMotionFunc(myMovedMouse);


-

void myMovedMouse(int x, int y);


2.4.2 Keyboard interaction



∙ glutKeyboardFunc(myKeyboard)



∙ void myKeyboard(unsigned int key, int x, int y);

myMouse() with the event that

occurs when the mouse button

is pressed or released

29/29

숙제
:

1. 18
-
19
페이지

예제를

이용해

자신이



좋아하는

간단한

캐릭터를

만드시오
.



)
미키

마우스
,
도날드
,
아이언





2. 20
페이지

예제를

이용해

교재

그림

2.28




완성하시오
: parameterizedHouse()