IVIS Lab, Changwon National University

Download Report

Transcript IVIS Lab, Changwon National University

2장 Initial Steps in Drawing Figures
창원대학교 정보통신공학과
박동규
2.1 To get started making pictures
• Writing and testing programs that produces a variety
of pictures
– Display layout
IVIS Lab, Changwon National University
What is OpenGL
• A low level graphics rendering and imaging library
• A layer of abstraction between graphics hardware and
an application program
• Window system and OS independent
– Use with Unix, Microsoft Windows, IBM OS/2, Mac
OS
• 3차원 그래픽을 이용하기 위한 API
IVIS Lab, Changwon National University
OpenGL의 역사
• IRIS GL에서 시작
– SGI의 워크스테이션 IRIS에서 구현된 그래픽 라이브러리인 IRIS
GL에서 시작
– 이식성을 위해 기계에 종속적인 부분을 제거
• OpenGL 1.0
– 속도를 위해 IRIS GL의 기능을 일부 축소하여 1992년 7월
OpenGL 1.0을 발표
– 개방형+그래픽 라이브러리
IVIS Lab, Changwon National University
OpenGL 1.1
• OpenGL ARB(Architecture Review Board)
– SGI, DEC, IBM, 인텔, 마이크로 소프트
– 3D 그래픽 라이브러리의 표준으로
• OpenGL 1.1(1995년 12월)
– 텍스쳐 매핑을 개선
– RGBA 모드에서 논리연산 가능
– 윈도우용 오픈 GL
IVIS Lab, Changwon National University
OpenGL의 특징
• 윈도우 제어와 관련된 기능을 포함하지 않는다
• 객체 지향적이지 않다
• 클라이언트/ 서버 구조이다
• State Machine 구조이다
• 절차적이다
IVIS Lab, Changwon National University
OpenGL 구성
• OpenGL(GL)
– Fundamental OpenGL library
• OpenGL Utility(Glu)
– OpenGL Utility library
– 높은 수준의 그리기 기능 제공
• Glut
– OpenGL Utility toolkit
– Window 시스템에 독립적인 OpenGL 프로그램을 작성하도록 도
와주는 도구
• OpenGL User Interface Library(GLUI)
– Button, checkbox, radio button, spinner등과 같은 사용자 인테
페이스를 제공하는 C++ library
– Glut에 기반하고 있슴
IVIS Lab, Changwon National University
OpenGL(GL)
• OpenGL의 핵심
– 2D, 3D 컴퓨터 그래픽스를 위한 기본적인 함수들의 집합체
– 모델링, 렌더링과 관련된 기능들을 제공
IVIS Lab, Changwon National University
OpenGL and Libraries
• OpenGL’s main library
– Gl.h, opengl32.lib, opengl32.dll
• OpenGL’s utility library
– Glu.h, glu32.lib, glu32.dll
IVIS Lab, Changwon National University
OpenGL 환경 설정(visual c++)
• Microsoft Visual Studio
– Compiler가 제일 먼저 필요
– Visual c++에서는 openGL의 기본적인 library들이 default로 설치
됨
• 추가적인 library 설치
• OpenGL wizard 설치
IVIS Lab, Changwon National University
Visual C++을 이용한 OpenGL 프로그램 작성
• 필요한 파일들
– 라이브러리
• opengl32.lib, glu32.lib는 Visual C++에서 제공됨
• glut32.lib를 내려 받고 컴파일러에 경로 지정
– DLL 파일
• opengl32.dll, glu32.dll 파일을 시스템에서 기본 제공
• glut32.dll 파일을 내려 받아 C: \WINNT\system32 디렉토리에
복사
– 헤더 파일
• gl.h, glu.h
• glut.h를 내려 받고 컴파일러에 경로 지정
IVIS Lab, Changwon National University
glut 라이브러리 설치
• 강의자료실에서 glut-3.7.6.zip 파일 다운로드
– http://www.youtube.com/watch?v=BOHpAUmFa7Q
• Visual Studio 6.0(다음 위치에 파일을 복사함)
glut32.dll  X:\WINDOWS\System32\glut32.dll
glut32.lib  X:\…\VisualStudio\VC98\Lib\glut32.lib
glut.h  X:\…\VisualStudio\VC98\Include\GL\glut.h
• Visual Studio 2008에서 설치
glut32.dll  X:\WINDOWS\System32\glut32.dll
glut32.lib  X:\Program FileFiles\Microsoft Visual Studio
9.0\VC\lib\glut32.lib
glut.h  C:\Program Files\Microsoft Visual Studio
9.0\VC\include\GL\glut.h
IVIS Lab, Changwon National University
Visual Studio실행
• Microsoft Visual C++ 6.0
실행
• File  New 실행
• Project Tab의 Win32
Console Application을
선택함
– Location: 파일 프로젝트를
생성할 위치를 지정함
– Project name
: 프로젝트 이름을 정함
IVIS Lab, Changwon National University
프로젝트 생성
IVIS Lab, Changwon National University
IVIS Lab, Changwon National University
텍스트 파일 생성
• File 메뉴 아래의 New
Text File 단축 아이콘을
선택하여 빈 텍스트 파일
을 생성
• 소스코드를 입력
IVIS Lab, Changwon National University
New Text File
단축 아이콘
저 장
• 프로그램을 .cpp 또는 .c
확장자를 가지는 파일로
저장함
• 작업영역에서 오른쪽 버튼
을 선택 Insert File Into
Project를 선택하여 파일
을 프로젝트에 추가함
IVIS Lab, Changwon National University
링 크
• 라이브러리를 링크함
– Project 메뉴의 Settings 부메뉴의 Link 탭 선택
– opengl32.lib, glu32.lib, glut32.lib가 포함되도록
IVIS Lab, Changwon National University
컴파일 방법
• 책의 예제 프로그램
– 소스 파일을 더블클릭
– Build 메뉴에서 Rebuild All을 선택
 *.dsw, *.dsp 등 프로젝트 파일을 자동으로 생성
– 예상되는 에러들
• 헤더 파일 또는 라이브러리 찾기 오류
– 경로 지정 : Tools 메뉴의 Directories 탭에서 Include Files 항목과
Library Files 항목 확인
IVIS Lab, Changwon National University
2.1.2 Window-based Programming
void main(int argc, char** argv)
{
초기화 기능
스크린 윈도우 생성
glutDisplayFunc(myDisplay);
// register redraw function
glutReshapeFunc(myReshape);
glutMouseFunc(myMouse);
glutKeyboardFunc(myKeyboard);
기타 초기화기능
glutMainLoop();
}
콜백 함수 정의
IVIS Lab, Changwon National University
// go into a perpetual loop
OpenGL Utility(Glu)
• GL 사용시 발생하는 많은 반복작업 간소화
– 예) 구, 실린더, 디스크 등의 기본 오브젝트 생성
• 꼭지점을 일일이 계산하여 각 점을 glVertex() 함수
로 하나하나 찍어야 함
GLUquadricObj *pObj;
pObj = gluNewQuadric();
gluSphere(pObj, 30.0, 10, 10);
gluDeleteQuadric(pObj); //객체를 삭제
IVIS Lab, Changwon National University
기하학적 객체의 정의
• 선분
glBegin(GL_LINES);
glVertex2f(x1, y1);
glVertex2f(x2,y2);
glEnd();
• 한쌍의 점
glBegin(GL_POINTS);
glVertex2f(100, 50);
glVertex2f(100, 130);
glVertex2f(150, 130);
glEnd();
IVIS Lab, Changwon National University
OpenGL에서 정점의 표현
• glVertex*()
– * = nt 또는 ntv 형태
• n : 차원
• t : 데이터 형 ( 정수 : i, 실수 : f, double : d )
• v: 배열에 대한 포인터
• 예)
– glVertex2i(GLint xi, GLint yi)
– glVertex3f(GLfloat x, GLfloat y, GLfloat z)
– GLfloat vertex[3];
glVertex3fv(vertex)
IVIS Lab, Changwon National University
OpenGL 명령어
• OpenGL 명령어 형식
IVIS Lab, Changwon National University
명령어 첨자
IVIS Lab, Changwon National University
OpenGL as a State Machine
• 다양한 state(mode) 삽입
• 사용자가 바꾸기 전까지 활성화된 상태
– (예) current color (state variable)
• color를 바꾸면, 그 이후의 모든 object는 바뀐 color로 색칠됨.
• Current color를 다른 색으로 바꿀 때까지 계속 유지됨.
• other state variables
– current viewing and projection transformation, polygon
drawing modes, positions and characteristics of light 등
IVIS Lab, Changwon National University
Establishing the Coordinate System
• 좌표계 초기화를 담당하는 함수를 만든다
– 좌표계의 크기, 투영 방법을 정의함
IVIS Lab, Changwon National University
Putting it All Together
#include <windows.h>
// use as needed for your system
#include <gl/Gl.h>
#include <gl/glut.h>
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0);
glColor3f(0.0f, 0.0f, 0.0f);
// set white background color
// set the drawing color
glPointSize(4.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
IVIS Lab, Changwon National University
// a 멶ot?is 4 by 4 pixels
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
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
}
//<<<<<<<<<<<<<<<<<<<<<<<< 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(myDisplay);
// register redraw function
myInit();
glutMainLoop();
// go into a perpetual loop
}
실행 결과
IVIS Lab, Changwon National University
Drawing Dot Constellations
• Example 2.1.1 북두칠성
– Figure 2.5를 참조하여 다음과 같은 북두칠성을 그리시오
IVIS Lab, Changwon National University
Example 2.2.2 시어핀스키 가스켓
• Sierpinski라는 수학자가 만듬
• 시어핀스키 삼각형이라고도 함
• 프랙탈 기하학의 한 예
– 자기 유사성을 가짐
IVIS Lab, Changwon National University
알고리즘
1)
2)
3)
4)
5)
6)
삼각형 내부에서 임의의 시작점 선택
세 정점 중 임의의 한 점 선택
시작점과 선택된 정점의 중간점 계산
중간점에 점을 찍음
이 새로운 점을 시작점으로 대치
단계 2로 돌아감
IVIS Lab, Changwon National University
프로그램 형식
main()
{
initialize_the_system();
for (some_number_of_points)
{
generate_a_point();
display_the_point();
}
cleanup();
}
IVIS Lab, Changwon National University
Source
void Sierpinski_render(void)
{
glClear(GL_COLOR_BUFFER_BIT);
GLintPoint T[3]= {{10,10},{600,10},{300, 600}};
int index = rand () % 3;
// 0, 1, or 2 equally likely
GLintPoint point = T[index];
// initial point
drawDot(point.x, point.y);
// draw initial point
for(int i = 0; i < 55000; i++) // draw 1000 dots
{
index = = rand () % 3;
point.x = (point.x + T[index].x) / 2;
point.y = (point.y + T[index].y) / 2;
drawDot(point.x,point.y);
}
glFlush();
}
IVIS Lab, Changwon National University
과제
• 배포한 예제를 참고하여 시어핀스키 가스켓 프로그램을
작성하시오
– 필요한 함수로 DrawDot, random()을 교재를 참고하여 만드시오
IVIS Lab, Changwon National University
Example 2.2.3 Simple “Dot Plots”
• 수학 함수 f(x)
– f(x)=e-xcos(2πx)
– x값의 간격을 0.005로 하여
glVertex2d(x,f(x))를 화면에
출력
• 문제점
– 0에서 4사이의 작은 점을 출
력
– 코사인 함수의 특징으로 인
하여 음수값을 가짐
• 해결
– scale과 shift 연산을 이용
IVIS Lab, Changwon National University
과제
• shift & Scale 을 이용하여 그림 2.16과 같은 함수
plotting을 완성하여라
IVIS Lab, Changwon National University
2.3 Line Drawings in OpenGL
• 직선 그리기는 그래픽스의 가장 기본적인 기능
glBegin(GL_LINES);
glVertex2i(x1, y1);
glVertex2i(x2,y2);
glEnd();
• 그리기 함수
void drawLine(GLint x1, GLint y1, GLint x2, GLint y2)
{
glBegin(GL_LINES);
glVertex2i(x1, y1);
glVertex2i(x2,y2);
glEnd();
}
IVIS Lab, Changwon National University
직선 그리기
glBegin(GL_LINES);
glVertex2i(10, 20);
glVertex2i(40, 20);
glVertex2i(20, 10);
glVertex2i(20, 40);
four more calls ...
glEnd();
IVIS Lab, Changwon National University
glLineWidth(4.0) 함수로 조절
2.3.1 Drawing Polylines and Polygons
glBegin(GL_LINE_STRIP);
glVertex2i(20, 10);
glVertex2i(50, 10);
glVertex2i(20, 80);
glVertex2i(50, 80);
glEnd();
IVIS Lab, Changwon National University
GL_LINE_LOOP 사용
기본 요소
• 점과 선분형
IVIS Lab, Changwon National University
2.3.2 저장된 파일로부터 그리기
21
29
32 435
10 439
4 438
2 433
4 428
6 425
10 420
15 416
21 413
IVIS Lab, Changwon National University
다중선분 그리기
void drawPolyLineFile(char * fileName)
{
fstream inStream;
inStream.open(fileName, ios::in);
//
if(inStream.fail())
return;
glClear(GL_COLOR_BUFFER_BIT); //
GLint numpolys, numLines, x ,y;
inStream >> numpolys;
//
for(int j = 0; j < numpolys; j++)
//
{
inStream >> numLines;
glBegin(GL_LINE_STRIP);
for (int i = 0; i < numLines; i++)
{
inStream >> x >> y;
glVertex2i(x, y);
}
glEnd();
}
glFlush();
inStream.close();
}
IVIS Lab, Changwon National University
open the file
clear the screen
read the number of polylines
read each polyline
// draw the next polyline
// read the next x, y pair
hardwired coding
void hardwiredHouse(void)
{
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
}
IVIS Lab, Changwon National University
결과
• 고정된 위치의 고정된
크기의 집
IVIS Lab, Changwon National University
매개변수화 된 코딩
void parameterizedHouse(GLintPoint peak, GLint width, GLint height)
// the top of house is at the peak; the size of house is given
// by height and width
{
glBegin(GL_LINE_LOOP);
glVertex2i(peak.x,
peak.y); // draw shell of house
glVertex2i(peak.x + width / 2, peak.y - 3 * height /8);
glVertex2i(peak.x + width / 2 peak.y height);
glVertex2i(peak.x - width / 2, peak.y height);
glVertex2i(peak.x - width / 2, peak.y - 3 * height /8);
glEnd();
draw chimney in the same fashion
draw the door
draw the window
}
IVIS Lab, Changwon National University
매개변수를 이용한 다양한 모양
• 다양한 매개변수를 활용한 “village(촌락)”
IVIS Lab, Changwon National University
Building a polyline drawer
struct GLintPoint{
public :
GLint x,y;
}
class GLintPointArray{
const int MAX_NUM = 10000;
public:
int num;
GLintPoint pt[MAX_NUM];
};
IVIS Lab, Changwon National University
drawing
void drawPolyLine(GlintPointArray poly, int closed)
{
if(closed)
glBegin(GL_LINE_LOOP);
else
glBegin(GL_LINE_STRIP);
for(int i = 0; i < poly.num; i++)
glVertex2i(poly.pt[i].x, poly.pt[i].y);
glEnd();
glFlush();
}
IVIS Lab, Changwon National University
2.3.3 Line drawing
• moveto()와 lineto()를 이용한 그리기
– moveto(x,y); 현재 위치(CP)를 x,y로 설정
– lineto(x,y); 이전 CP에서 x,y까지 직선을 그리고 CP를 x,y 로 이동
– GLintPoint CP;
// global current position
IVIS Lab, Changwon National University
GLintPoint CP;
// global current position
//<<<<<<<<<<<<< moveto >>>>>>>>>>>>>>
void moveto(GLint x, GLint y)
{
CP.x = x; CP.y = y; // update the CP
}
//<<<<<<<<<<<< lineTo >>>>>>>>>>>>>>>>>
void lineto(GLint x, GLint y)
{
glBegin(GL_LINES); // draw the line
glVertex2i(CP.x, CP.y);
glVertex2i(x, y);
glEnd();
glFlush();
CP.x = x; CP.y = y; // update the CP
}
2.3.4 Drawing Aligned Rectangles
• 좌표축에 정렬된 직사각형 그리기
• glRecti(GLint x1, GLint y1, GLint x2, GLint y2) 사용
glClearColor(1.0,1.0,1.0,0.0); // white background
glClear(GL_COLOR_BUFFER_BIT); // clear the window
glColor3f(0.6,0.6,0.6);
// bright gray
glRecti(20,20,100,70);
glColor3f(0.2,0.2,0.2);
// dark gray
glRecti(70, 50, 150, 130);
glFlush();
IVIS Lab, Changwon National University
drawFlurry
void drawFlurry(int num, int numColors, int Width, int Height)
// draw num random rectangles in a Width by Height rectangle
{
for (int i = 0; i < num; i++)
{
GLint x1 = random(Width);
// place corner randomly
GLint y1 = random(Height);
GLint x2 = random(Width);
// pick the size so it fits
GLint y2 = random(Height);
GLfloat lev = random(10)/10.0; // random value, in range 0 to 1
glColor3f(lev,lev,lev);
// set the gray level
glRecti(x1, y1, x2, y2);
// draw the rectangle
}
glFlush();
}
IVIS Lab, Changwon National University
과제
• 예제 프로그램을 참고하여 서로 다른 색상을 가진 50개
이상의 사각형을 그리도록 하여라
– drawFlurry를 참고하시오
IVIS Lab, Changwon National University
2.3.5 On the Aspect Ratio of an Aligned
Rectangle
• aspect ratio = width/height
• 그림과 같이 다양한 종류의
종횡비가 존재함
– a의 종횡비 1.294
– c에서 ф = 1.618034
– e의 종횡비 .7727
IVIS Lab, Changwon National University
example
• 체크판 그리기
if(( i+j) %2 == 0)
glColor3f(r1, g1, b1);
else
glColor3f(r2, g2, b2);
• 사각형을 그리는 다른 방식
– 중심점과 너비, 높이를 기술
– 좌상단 좌표와 너비, 종횡비로 기술
• 디스플레이의 크기에 적합한 종횡비로 사각형 만들기
• 매개변수로 표현된 집그리기
• 다이아몬드꼴 그리기 등
IVIS Lab, Changwon National University
2.3.6 Filling Polygons
• Convex polygon의 정의
– A polygon is convex if a line connecting any two points of the
polygon lies entirely within it
• Convex polygon을 찾아라
IVIS Lab, Changwon National University
polygon
• 다각형 그리기
glBegin(GL_POLYGON)
glVertex2f(x0, y0);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
...
glVertex2f(xn, yn);
glEnd()
IVIS Lab, Changwon National University
2.3.7 other graphics primitives
• OpenGL에 표현할 수 있는 그래픽 프리미티브
– glBegin( ) 의 괄호안에 사용할 수 있는 상수값
IVIS Lab, Changwon National University
2.4 마우스와 키보드를 이용한 상호작용
• GLUT의 callback 함수를 사용하여 대화식 프로그래밍을
할 수 있음
• glutMouseFunc(myMouse)
– myMouse() 함수가 마우스의 클릭과 놓음에 대한 이벤트 처리
• glutMotionFunc(myMovedMouse)
– myMovedMouse() 함수가 마우스가 클릭된 상태에서의 움직임 이
벤트를 처리
• glutKeyboardFunc(myKeyboard)
– myKeyboard() 함수가 키보드 입력에 대한 이벤트를 처리함
IVIS Lab, Changwon National University
이벤트-구동 입력의 프로그래밍
• 이벤트 종류
– 이동이벤트
• 버튼중 하나가 눌린 채로 이동 시
• 답신 함수 : glutMotionFunc(callback_func)
– 비활성 미동이벤트
• 버튼을 누르지 않고 이동 시
• 답신함수 : glutPassiveMotionFunc(callback_func)
– 마우스 이벤트
• 버튼 중 하나가 눌려지거나 떼어졌을 때
• 답신 함수 : glutMouseFunc(callback_func)
IVIS Lab, Changwon National University
2.4.1 Mouse Interaction
• void myMouse(int button, int state, int x, int y)
– 마우스 이벤트가 발생하면 등록된 함수가 호출됨
• button 값
– GLUT_LEFT_BUTTON
– GLUT_MIDDLE_BUTTON
– GLUT_RIGHT_BUTTON
• state 값
– GLUT_UP
– GLUT_DOWN
IVIS Lab, Changwon National University
예 2.4.1 마우스로 점 찍기
void myMouse(int button, int state, int x, int y)
{
if(state == GLUT_DOWN) {
if( button == GLUT_LEFT_BUTTON){
drawDots(x, screenHeight – y);
glFlush();
}
else if( button == GLUT_RIGHT_BUTTON){
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
}
}
IVIS Lab, Changwon National University
예 2.4.3 사각형 그리기
void myMouse(int button, int state, int x, int y)
{
static GLintPoint corner[2];
static int numCorners = 0;
// initial value is 0
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
corner[numCorners].x = x;
corner[numCorners].y = screenHeight - y; // flip y coordinate
if(++numCorners == 2) // have another point
{
glRecti(corner[0].x, corner[0].y, corner[1].x, corner[1].y);
numCorners = 0;
// back to 0 corners
}
}
else if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
glClear(GL_COLOR_BUFFER_BIT);
// clear the window
glFlush();
}
IVIS Lab, Changwon National University
예 2.4.3 시어핀스키 가스킷
• Sierpinski gasket 루틴에서 필요한 세 점을 마우스를 이
용하여 얻는 방법
– 세 점을 corners[] 에 저장
– p 65
IVIS Lab, Changwon National University
예 2.4.4 마우스를 이용한 다중선분
void myMouse(int button, int state, int x, int y)
{
#define NUM 20
static GLintPoint List[NUM];
static int last = -1;
// last index used so far
// test for mouse button as well as for a full array
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && last < NUM -1)
{
List[++last].x = x;
// add new point to list
List[ last].y = screenHeight - y; // window height is 480
glClear(GL_COLOR_BUFFER_BIT);
// clear the screen
glBegin(GL_LINE_STRIP);
// redraw the polyline
for(int i = 0; i <= last; i++)
glVertex2i(List[i].x, List[i].y);
glEnd();
glFlush();
}
else if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
last = -1;
// reset the list to empty
}
IVIS Lab, Changwon National University
실행
IVIS Lab, Changwon National University
2.4.2 Keyboard Interaction
• 키보드 콜백함수 myKeyboard의 예
void myKeyboard(unsigned char theKey, int mouseX, int mouseY)
{
GLint x = mouseX;
GLint y = screenHeight - mouseY; // flip the y value as always
switch(theKey)
{
case ‘p’:
drawDot(x, y);
// draw a dot at the mouse position
break;
case GLUT_KEY_LEFT:
List[++last].x = x; // add a point
List[ last].y = y;
break;
case ‘E’:
exit(-1);
//terminate the program
default:
break;
// do nothing
}
}
IVIS Lab, Changwon National University
2.6 case studies
• Level of Effort
– I: A simple exercise
– II: An intermediate exercise
– III: An Advanced exercise
• Pseudorandom clouds of dots
– II : random-number generator(RNG)
• 난수는 시뮬레이션, 분석, 벤치마킹을 위해서 널리 사용된다.
• 우리는 난수를 무작위로 만들어진 수를 말하지만 난수란 수학적으
로 이야기해서 모든 수가 나타날 가능성이 동일한 경우를 말한다
• 오늘날의 컴퓨터를 이용해서 진정한 의미의 난수를 생성하는 것은
불가능하다.
IVIS Lab, Changwon National University
random number
• 난수 생성
– 난수를 생성하는 프로그램이 있을 경우, 컴퓨터가 생성하는 숫자
들은 추론이 가능할 것이다. 따라서 이 숫자들은 랜덤하다고 할 수
없다.
– 최선의 방법은 난수가 가지는 특징들을 가능한 많이 보유한 숫자
의 열을 생성하는 방법을 만드는 일이다(의사 난수)
– 난수를 생성하기 위한 가장 유명한 방법은 선형 일치 방법으로 D.
Lehmer가 1951년에 최초로 소개하였다.
– 종자(seed)값이 임의의 수를 포함하고 있다면 이 방법을 사용해서
N개의 난수를 가진 배열을 만들 수 있다.
a[0] = seed;
for(i=1; i<= N; i++)
a[i] = (a[i-1]*b+1) %m;
– ni=[ni-1A+B] mod N,
• A=1,103,515,245, B=12,345 N=32,767
IVIS Lab, Changwon National University
난수의 특성
• 흩어진 점들의 분포를 이용하여 난수화의 정도를 측정
for(int i=0; i<num; i++)
drawDot(random(N), random(N));
한 값과 다음 값 사이의 상관 관계가
없음
IVIS Lab, Changwon National University
scatter plots(과제)
서로 다른 A, B, N 값을 사용하여 random plot를 구성하도록 한 결과를
제출하라
즉 그림 a) 그림 b) 그림 c)와 같은 모양을 만드는 A,B,N값의 쌍을 구하여
제출하고 그 결과를 캡쳐하여라(다른 사람의 값을 베끼지 말고 본인이 구할것 )
IVIS Lab, Changwon National University
IFS: iterated function system
• iterated function system(IFS)
– 한 함수의 입력값으로 이전의 출력값을 사용하여 새로운 값을 얻
는 시스템
– 프랙털 이론등에서 활용
– 시어핀스키 가스킷이 대표적인 IFS
IVIS Lab, Changwon National University
Gingerbread Man(생강빵 인간?)
• 다음의 함수를 사용함
q.x = M(1+2L) – p.y + |p.x – LM|;
q.y = p.x;
• M=40, L=3 초기값 p는(115,121)등을 사용
– 초기값에 따라 다른 모양 생성
IVIS Lab, Changwon National University
source code
void myDisplay(void)
{
int px=115, py=121, cx, cy;
int M = 42, L=3;
glClear(GL_COLOR_BUFFER_BIT);
// clear the screen
for(int i=0; i<1500; i++){
cx = M*(1+2*L) - py + abs(px-L*M);
cy = px;
drawDot(cx, cy);
px = cx; py = cy;
}
glFlush();
// send all output to display
}
IVIS Lab, Changwon National University
사례연구 2.3 황금비
• golden rectangle
– 너무 좁거나 너무 뚱뚱해 보이지 않는 사각형
– 사각형 중에서 가장 이쁜(?) 사각형
• 모나리자
• 그리스 파르테논 신전의 가로세로비
IVIS Lab, Changwon National University
황금비
• Φ = 1+ 1/φ
– Φ = 1.614...
IVIS Lab, Changwon National University
IVIS Lab, Changwon National University
과제 1
• 대화식 Sierpinski gasket 프로그램 작성
– 화면에 마우스로 세 점을 입력한 후 이를 화면에 붉은색 점으로 보
여주고, 키보드로부터 ‘d’ 키를 입력받아 Sierpinski Gasket을 그
리는 프로그램을 작성하여라
– 이 때 제일 마지막에 입력된 세 점을 이용하여 화면에 Sierpinski
Gasket을 그리도록 한다.
– ‘q’ 키가 들어오면 프로그램을 중지하고 프로그램을 닫도록 하여
라
– 프로그램 소스에 comment를 충분히 달아서 source 프로그램과
실행결과를 과제를 제출하도록 한다.
IVIS Lab, Changwon National University
과제 2
• 대화식 에디터
– 대화식 polyline editor 프로그램을 작성하여라
– 이 프로그램은 키보드로 부터 b,d,a,r,q를 입력 받아서 시작(b),
점의 삭제(d), 추가(a), refresh(r), 종료(q)등을 수행하도록 되어
있다.
– 프로그램 소스에 comment를 충분히 달아서 source 프로그램과
실행결과를 과제를 제출하도록 한다.
IVIS Lab, Changwon National University
끝