opengl
Transkript
opengl
OPENGL
Y. Doç. Dr. Aybars UĞUR
Ocak 2006
OpenGL Nedir?
OpenGL (Open Graphics Library),
grafik donanımını kullanmak için hazırlanmış
bir yazılım arayüzüdür.
Bu kütüphane yardımıyla, 2B (Boyutlu) ve 3B Grafiksel
nesneler ve işlemler, kolaylıkla tanımlanabilmektedir.
Programlama dillerindeki önemli bir eksikliği
gidermektedir.
İki ve üç boyutlu etkileşimli grafikler içeren yazılımlar
geliştirmek için kullanılan 250 farklı komutu (200’ü
OpenGL’in kendi içinde, 50’si de OpenGL Utility
Library yani glut içinde olmak üzere) içermektedir.
Grafik donanımlarının gücünden yararlanmaktadır.
Ocak 2006
Dr. Aybars UĞUR
2
OpenGL : Bazı Özellikler
İşletim Sistemi bağımsızdır (Windows 95/98/NT/2000...,
Linux, Unix, MacOS, BeOS). Windows’ta standart
olarak gelir.
Programlama Dili bağımsızdır. Kütüphane, C, C++, C#,
Java, Visual Basic, Delphi, Fortran, Perl gibi dillerden
kullanılabilmektedir.
Pencere yöneticilerinden bağımsızdır. Sisteme özgü ekler
yapılmazsa, programlar, Win32, X-Window gibi tüm
pencere yöneticileri ile sorunsuz çalışır.
Pencere, fare ve klavye işlemlerinden bağımsız hale
getirmek için kullanılan glut, birçok işletim sistemine
aktarılmıştır.
Ocak 2006
Dr. Aybars UĞUR
3
OpenGL Temelleri
Red Book’tan yararlanınız…
OpenGL bir “durum makinesidir” :
Çokgenler, etkin (current) renk,
dönüşüm, çizim modu vs. etkilenir.
OpenGL Spesifikasyonundaki herşey,
tüm gerçekleştirimlerinde desteklenir.
Ocak 2006
Dr. Aybars UĞUR
4
OpenGL RedBook - II
Chapter 1, "Introduction to
OpenGL,"
Chapter 2, "State Management and
Drawing Geometric Objects,"
Chapter 3, "Viewing,"
Chapter 4, "Color,"
Chapter 5, "Lighting,"
Ocak 2006
Dr. Aybars UĞUR
5
OpenGL RedBook - II
Chapter 6, "Blending, Antialiasing,
Fog, and Polygon Offset,"
Chapter 7, "Display Lists,"
Chapter 8, "Drawing Pixels,
Bitmaps, Fonts, and Images,"
Chapter 9, "Texture Mapping,"
Chapter 10, "The Framebuffer,"
Ocak 2006
Dr. Aybars UĞUR
6
OpenGL RedBook - III
Chapter 11, "Tessellators and
Quadrics,"
Chapter 12, "Evaluators and
NURBS,"
Chapter 13, "Selection and
Feedback,"
Chapter 14, "Now That You Know,"
Ocak 2006
Dr. Aybars UĞUR
7
OpenGL ve
Visual C++ 6.0
Bu ders notları, basit olarak Visual C’de OpenGL
kullanımını anlatmak üzere hazırlanmıştır. OpenGL’in
diğer programlama dillerinden kullanımı benzer
şekildedir.
Örnek programlar hazırlandıktan sonra, Visual C++ 6.0
kullanılarak çalıştırılmış ve test edilmiştir. Örnekleri
çalıştırabilmek için VC++ 6.0 yüklendikten sonra
GLUT’un eklenmesi gerekmektedir.
Glut’un güncel sürümü, aşağıda belirtilen adresten
indirilebilmektedir :
http://www.xmission.com/~nate/opengl.html
Ocak 2006
Dr. Aybars UĞUR
8
Glut’un Kurulumu
Visual C++ 6.0 yüklendikten sonra, GLUT’un kurulması :
GLUT Version 3.7.6 (117 KB) içindeki
“GLUT32.DLL“, \Windows\System klasörüne (NT tabanlı ise
WINNT\System)
“GLUT.H“, \Program Files\Microsoft Visual
Studio\VC98\Include\GL klasörüne
“GLUT.LIB“, \Program Files\Microsoft Visual Studio\VC98\Lib
klasörüne kopyalanır.
Proje ayarları
Project-Settings-Link-Object/Library Modules’de başa :
opengl32.lib glut32.lib eklenir.
Ocak 2006
Dr. Aybars UĞUR
9
Using OpenGL & GLUT in
Visual Studio .NET 2003
GLUT.H
C:\Program Files\Microsoft Visual Studio
.NET 2003\Vc7\PlatformSDK\Include\gl
GLUT.LIB
C:\Program Files\Microsoft Visual Studio
.NET 2003\Vc7\PlatformSDK\Lib
Ocak 2006
Dr. Aybars UĞUR
10
Glut : Başlangıç
int main (int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DEPTH | GLUT_DOUBLE |
GLUT_RGBA);
glutInitWindowSize (windowWidth, windowHeight);
glutInitWindowPosition (0, 0);
glutCreateWindow (“248 Video Game!");
SetStates();
RegisterCallbacks();
glutMainLoop();
return 0;
// Initialize rendering states*
// Set event callbacks*
// Start GLUT
}
Ocak 2006
Dr. Aybars UĞUR
11
İlk OpenGL Programı :
Pencere Açmak
#include <GL/glut.h>
void init(void)
{
glClearColor(1.0,1.0,1.0,0.0);
glShadeModel(GL_FLAT);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glutSwapBuffers();
}
Ocak 2006
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(400,100);
glutInitWindowPosition(100,100);
glutCreateWindow("Merhaba");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Dr. Aybars UĞUR
12
OpenGL Double Buffering
Double buffering:
– Draw on back buffer while front
buffer is being displayed.
– When finished drawing, swap the
two, and begin work on the new
back buffer.
– glutSwapBuffers();
Primary purpose: eliminate flicker
Ocak 2006
Dr. Aybars UĞUR
13
VC++ Programının
İşletimi
File-New-Workspaces’den yeni bir
Workspace açılır.
File-New-Files-C++ Source File ile
C++ Kaynak Kodu sayfası açılır.
Program yazılır veya belgeden
kopyalanır.
Derlenip çalıştırılır.
Ocak 2006
Dr. Aybars UĞUR
14
OpenGL Komut Yapısı
glColor3f
OpenGL
komutu
öneki
Ocak 2006
parametre
veri tipi
(float)
OpenGL Komutun
üç
komutu
parametre
Komutu
alan tipi
oluşturan
kelimeler
büyük
harfle
başlar
Dr. Aybars UĞUR
15
OpenGL Sabit Yapısı
GL_COLOR_BUFFER_BIT
Sabitler GL_ ile başlar
Tümü büyük harftir
Kelimeleri ayırmada alt çizgi kullanılır
Ocak 2006
Dr. Aybars UĞUR
16
Nesne Köşelerini Belirtme
Nesneler köşeleri ile belirtilir :
– glVertex3f (2.0, 4.1, 6.0);
– glVertex2i (4, 5);
Etkin Renk köşeleri etkiler :
– glColor3f (0.0, 0.5, 1.0);
Ocak 2006
Dr. Aybars UĞUR
17
Üçgen Oluşturma
Şeklin köşeleri, glBegin(mode) ve
glEnd() bloğu içinde ve saat yönü
(counter-clockwise) sırasında yazılır.
glBegin (GL_TRIANGLES);
glVertex2i (0, 0);
glVertex2i (2, 0);
glVertex2i (1, 1);
glEnd();
Ocak 2006
Dr. Aybars UĞUR
18
Şekil Oluşturma
Ocak 2006
Dr. Aybars UĞUR
19
Primitive (İlkel) Türleri
glBegin için
Points
Lines
GL_POINTS
GL_LINES,
GL_LINE_STRIP,
GL_LINE_LOOP
Triangles GL_TRIANGLES,
GL_TRIANGLE_STRIP,
GL_TRIANGLE_FAN
Quads
GL_QUADS,
GL_QUAD_STRIP
Polygons GL_POLYGON
Ocak 2006
Dr. Aybars UĞUR
20
Temel Geometrik Tipler
GL_POINTS individual points
GL_LINES pairs of vertices interpreted as individual line segments
GL_LINE_STRIP series of connected line segments
GL_LINE_LOOP same as above, with a segment added between last
and first vertices
GL_TRIANGLES triples of vertices interpreted as triangles
GL_TRIANGLE_STRIP linked strip of triangles
GL_TRIANGLE_FAN linked fan of triangles
GL_QUADS quadruples of vertices interpreted as four-sided polygons
GL_QUAD_STRIP linked strip of quadrilaterals
GL_POLYGON boundary of a simple, convex polygon
Ocak 2006
Dr. Aybars UĞUR
21
İki Boyut ve
Koordinat Sistemi
OpenGL, iki boyutlu grafikler için birçok
alternatif içermektedir. Basit bir dikdörtgen
çizmek için aşağıdaki kod bloğu kullanılır :
glBegin( GL_QUADS );
glColor3f( 1.0, 0.0, 0.0 );
glVertex2f( 0.0, 0.0 );
glVertex2f( 0.9, 0.0 ); (-1,-1)
glVertex2f( 1.0, 1.0 );
glVertex2f( 0.0, 0.5 );
glEnd();
Ocak 2006
Dr. Aybars UĞUR
(1,1)
22
Renkler
Kırmızı Yeşil Mavi
glColor3f(0.0, 0.0, 0.0);
black
glColor3f(1.0, 0.0, 0.0);
red
glColor3f(0.0, 1.0, 0.0);
green
glColor3f(1.0, 1.0, 0.0);
yellow
glColor3f(0.0, 0.0, 1.0);
blue
glColor3f(1.0, 0.0, 1.0);
magenta
glColor3f(0.0, 1.0, 1.0);
cyan
glColor3f(1.0, 1.0, 1.0);
white
glColor3f(0.9, 0.9, 0.9);
light gray
glColor3f(0.3, 0.3, 0.3);
dark gray
Tüm renkler, üç ana rengin (r, g, b) bileşiminden oluşur.
Ocak 2006
Dr. Aybars UĞUR
23
Örnek 2 :
Mavi Dikdörtgen Çizmek
#include <gl/glut.h>
void init(void)
{
glClearColor(1.0,1.0,1.0,0.0);
glShadeModel(GL_FLAT);
}
void Draw_A_Rectangle(void)
{
glBegin(GL_QUADS);
glColor3f(0.0,1.0,0.0);
glVertex2f(0.25,0.25);
glColor3f(1.0,1.0,0.0);
glVertex2f(0.25,0.75);
glColor3f(1.0,0.0,0.0);
glVertex2f(0.75,0.75);
glColor3f(0.0,0.0,1.0);
glVertex2f(0.75,0.25);
glEnd();
}
Ocak 2006
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
Draw_A_Rectangle();
glutSwapBuffers();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE |
GLUT_RGB);
glutInitWindowSize(400,100);
glutInitWindowPosition(100,100);
glutCreateWindow(" Rectangle ");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Dr. Aybars UĞUR
24
Çokgen Üzerinde
Renk Geçişi
glShadeModel(GL_SMOOTH);
void Draw_A_Rectangle(void)
{
glBegin(GL_QUADS);
glColor3f(0.0,1.0,0.0);
glVertex2f(0.25,0.25);
glColor3f(1.0,1.0,0.0);
glVertex2f(0.25,0.75);
glColor3f(1.0,0.0,0.0);
glVertex2f(0.75,0.75);
glColor3f(0.0,0.0,1.0);
glVertex2f(0.75,0.25);
glEnd();
}
Ocak 2006
Dr. Aybars UĞUR
GL_FLAT
25
OpenGL: Shading
OpenGL supports 2 basic shading
models: flat and smooth.
glShadeModel(GL_FLAT);
glShadeModel(GL_SMOOTH);
Ocak 2006
Dr. Aybars UĞUR
26
Örnek 3 :
Döngü ile Çokgen Oluşturma
#include <gl/
gl/glut.h>
glut.h>
#include <math.h>
math.h>
void init(
init(void)
void)
{
glClearColor(1.0,1.0,1.0,0.0);
glClearColor(1.0,1.0,1.0,0.0);
glShadeModel(GL_FLAT);
glShadeModel(GL_FLAT);
}
void Draw_
Draw_Polygon(
Polygon(void)
void)
{
double M_PI = 3.1415, angle;
angle;
glColor3f(0.0,1.0,0.0);
glBegin (GL_LINE_LOOP);
for (int j=0; j<10; j++) {
angle = 2*M_PI*j/10;
glVertex2f (cos
(cos((angle),
angle),
sin(angle
));
sin(angle));
}
Ocak 2006
glEnd();
glEnd();
}
void display(
display(void)
void)
{
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_COLOR_BUFFER_BIT);
Draw_
Draw_Polygon();
Polygon();
glutSwapBuffers();
glutSwapBuffers();
}
int main(
main(int argc,
argc,char **argv
**argv))
{
glutInit(&
argc,,argv);
glutInit(&argc
argv);
glutInitDisplayMode(GLUT_DOUBLE
glutInitDisplayMode(GLUT_DOUBLE |
GLUT_RGB);
glutInitWindowSize(400,100);
glutInitWindowSize(400,100);
glutInitWindowPosition(100,100);
glutInitWindowPosition(100,100);
glutCreateWindow("
glutCreateWindow(" Polygon ");
init();
init();
glutDisplayFunc(
glutDisplayFunc(display);
display);
glutMainLoop();
glutMainLoop();
return 0;
Dr. Aybars }UĞUR
27
GLUT Event Callbacks
Register functions that are called when certain
events occur.
Examples:
glutDisplayFunc( Display );
glutKeyboardFunc( Keyboard );
glutReshapeFunc( Reshape );
glutMouseFunc( Mouse );
glutPassiveMotionFunc( PassiveFunc );
glutMotionFunc( MouseDraggedFunc );
glutIdleFunc( Idle );
Ocak 2006
Dr. Aybars UĞUR
28
Etkileşim : Klavye
void keyboard(unsigned char key, int x, int y)
{
switch(key)
{
case 'x' :
axis = X;
Main’e Eklenmesi gereken :
spin();
glutPostRedisplay();
break;
case 'y' :
glutKeyboardFunc(keyboard);
axis = Y;
spin();
glutPostRedisplay();
break;
default :
break;
}
Dr. Aybars UĞUR
29
} Ocak 2006
Etkileşim : Fare
void mouse(int button, int state, int x, int y)
{
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(spinDisplay);
Main’e Eklenmesi gereken:
break;
case GLUT_MIDDLE_BUTTON:
glutMouseFunc(mouse);
if (state == GLUT_DOWN)
glutIdleFunc(NULL);
break;
default:
break;
}
}
Ocak 2006
Dr. Aybars UĞUR
30
OPENGL : 3D CONCEPTS
The camera initially
points down the
negative z-axis.
(You're seeing the
back of the camera.)
Ocak 2006
Dr. Aybars UĞUR
31
Summary of 3D
Transformation
3D Object Coordinates
P(x, y, z)
Modeling
Modeling
Transformation
Transformation
3D World Coordinates
Viewing
Viewing
Transformation
Transformation
3D Viewing Coordinates
Projection
Projection
Transformation
Transformation
2D Projection Coordinates
Window-to-Viewport
Window-to-Viewport
Transformation
Transformation
2D Device Coordinates
Ocak 2006
P(x, y)Dr. Aybars UĞUR
32
The Camera
Analogy
To take a photograph with a
camera, steps might be
• Set up your tripod and pointing the
camera at the scene (viewing trans.)
• Arrange the scene to be
photographed into the desired
composition (modoling trans.)
• Choose a camera lens or adjust the
zoom (projection trans.)
• Determine how large you want the
final photograph to be - for example,
you might want it enlarged (viewport
trans.)
• After these steps are performed, the
picture can be snapped or the scene
can be drawn.
Ocak 2006
Dr. Aybars UĞUR
33
Stages of Vertex Transform
• Modelview matrix: orients the model and the camera relative to
each other.
• Projection matrix: specifies the shape and orietation of the viewing
volume.
• Viewport transformation: controls the conversion of 3D model
coordinates to screen coordinates.
Ocak 2006
Dr. Aybars UĞUR
34
Example: Drawing Cube 1
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glLoadIdentity ();
/* clear the matrix */
/* viewing transformation */
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glScalef (1.0, 2.0, 1.0);
/* modeling transformation */
glutWireCube (1.0);
glFlush ();
}
Ocak 2006
Dr. Aybars UĞUR
35
Example: Drawing Cube 2
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
glMatrixMode (GL_MODELVIEW);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
Ocak 2006
Dr. Aybars UĞUR
36
Example: Drawing Cube 3
Viewing Transformation
• Analogus to positioning and aiming the camera.
• Usage: gluLookAt()
• Arguments indicate where the camera (eye position) is placed,
where it is aimed, and which way is up.
• In the example, we place the camera at (0, 0, 5), aim the camera
lens toward (0, 0, 0) and specify the up-vector as (0, 1, 0)
• By default the camera is at the origin (0, 0, 0), points down the
negative z-axis and has an up-vector of (0, 0, 1)
Modeling Transformation
• Analogous to positioning and orienting the model.
• Uasge: glScalef()
• Arguments specify how scaling should occur along the 3 axes.
• In the example, the cube is drawn twice as large in the y
direction
Ocak 2006
Dr. Aybars UĞUR
37
Example: Drawing Cube 4
Projection Transformation
• Similar to choosing a lens for a camera as determining what the
field of view (FOV) or viewing volume is.
• In addition, it determines how objects are projected onto screen.
• Usage: glFrustum()
• Arguments describe values of left, right, bottom, top, near and
far for a viewing volume.
• Before calling glFrustum(), glMatrixMode() with the argument
GL_PROJECTION must be called.
• After calling glFrustum(), the matrix stack must be set back to
GL_MODELVIEW
• Take care the current matrix with glLoadIdentity()
Note: Default matrix stack is GL_MODELVIEW
Ocak 2006
Dr. Aybars UĞUR
38
Example: Drawing Cube 5
Viewport Transformation
• Indicates the region of available screen area into which the scene
is mapped.
• Usage: glViewport()
• The arguments describe the origin, the width and height of the
region within the window.
What does OpenGL do when all transformations have been
specified?
• Transforms each vertex of every object in the scene by the
modeling and viewing transformations.
• Transforms the vertices and clips the objects by the projection
transformations
• Divides the remaining transformed vertices with w and maps
them onto the viewport.
Ocak 2006
Dr. Aybars UĞUR
39
Let’s Think About Transformations
In general, the order of transformation is critical
• If oyu do transformation A and then transformation B, you almost
always get something different than you do them the the
opposite order.
Ocak 2006
Dr. Aybars UĞUR
40
Transformations
and Viewing
OpenGL has 3 different matrix
modes:
– GL_MODELVIEW
– GL_PROJECTION
– GL_TEXTURE
Choose the matrix with:
glMatrixMode(…);
Ocak 2006
Dr. Aybars UĞUR
41
Modelview matrix
Transforms objects within the scene.
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(10.5, 0, 0);
glRotatef(45, 0, 0, 1);
DrawCube();
Remember that the operations are right
multiplied, so the transformation just
before DrawCube() takes effect first.
Ocak 2006
Dr. Aybars UĞUR
42
Modeling
Transformations
void glTranslate{fd}(TYPE x,
TYPE y, TYPE z);
Multiplies the current matrix
by a matrix that moves
(translates) an object by
the given x, y, and z values
(or moves the local
coordinate system by the
same amounts).
Ocak 2006
Dr. Aybars UĞUR
43
Üç Boyutlu Dönüşümler
glRotate produces a rotation of angle degrees
around the vector (x,y,z).
– void glRotated( GLdouble angle, GLdouble x, GLdouble y,
GLdouble z)
– void glRotatef( GLfloat angle, GLfloat x, GLfloat y, GLfloat z )
glScale produces a nonuniform scaling along the x,
y, and z axes.
void glScaled( GLdouble x, GLdouble y, GLdouble z )
void glScalef( GLfloat x, GLfloat y, GLfloat z )
glTranslate produces a translation by (x,y,z).
void glTranslated( GLdouble x, GLdouble y, GLdouble z )
void glTranslatef( GLfloat x, GLfloat y, GLfloat z )
Ocak 2006
Dr. Aybars UĞUR
44
OpenGL Matrix Stacks
glLoadIdentity(void);
Clears the currently modifiable matrix for future
transformation instructions.
Typically we call this instruction before specifying
modeling, viewing or projection transformations.
Ocak 2006
Dr. Aybars UĞUR
45
OpenGL Matrix Stacks
Manipulating stacks: the OpenGL calls to push, pop,
or multiply top of stack
glLoadMatrix(void);
glMultMatrix(void);
glPushMatrix(void); the topmost matrix is copied
glPopMatrix(void); the topmost matrix is destroyed
All vertices of the object are multiplied by the matrix.
Ocak 2006
Dr. Aybars UĞUR
46
OpenGL Matrix Stacks
Manipulating stacks: the OpenGL calls to push, pop,
or multiply top of stack
glLoadMatrix(const type *m);
glMultMatrix(const type *m);
m1 m5
m9 m13
m2 m6 m10 m14
m3 m7 m11 m15
m4 m8 m12 m16
Ocak 2006
Dr. Aybars UĞUR
47
Matrix Stacks
OpenGL supports two stacks of matrices
– Modelview matrix stack (4x4 matrices)
– Projection matrix stack (4x4 matrices)
These stacks are useful for constructing
hierarchical models. For example a car
made of its body and the four wheels:
Rotate wheels
+ Rotate body
Rotate wheels
Ocak 2006
Dr. Aybars UĞUR
48
Matrix Stacks
glPushMatrix(void) - Pushes
all matrices in the current stack
down one level.
glPopMatrix(void) - Pops the
top matrix off the current stack,
losing the topmost matrix!
(The current stack is determined
by glMatrixMode).
Current
matrix
level
M4
M3
M2
M4
Push
M1
M4
M3
M2
M1
M5
Current
matrix
level
M4
M5
M4
M3
M2
Pop
M3
M2
M1
M1
Ocak 2006
Dr. Aybars UĞUR
49
Matrix Stacks
Example code:
void drawCar() {
glMatrixMode(GL_MODELVIEW) ;
glTranslatef(x,y,z) ;
/*/
glRotatef(car_ang, 0, 1, 0) ;
/*/
draw_car_body() ;
glPushMatrix() ;
glTranslate(-1,0,1) ;
glRotatef(wheels_ang, 0, 1, 0) ;
draw_car_wheel() ;
glPopMatrix() ;
glPushMatrix() ;
glTranslate(1,0,1) ;
glRotatef(wheels_ang, 0, 1, 0) ;
draw_car_wheel() ;
glPopMatrix() ;
}
Ocak 2006
Dr. Aybars UĞUR
First we move and rotate
the car (body + wheels) as it is the top level in the
hierarchy.
Next we push the stack and therefore store a
copy.
Then we draw the right
and left wheels in their
appropriate position and
orientation. Note that on
each wheel the
transformation /*/ will
operate.
The last pop will retrieve
the matrix containing only
the /*/ transformations.50
3D GLUT predefined
shapes
Ocak 2006
Dr. Aybars UĞUR
51
Üç Boyutlu Hazır Nesneler
I
glutSolidSphere, glutWireSphere
glutSolidCube, glutWireCube
glutSolidCone, glutWireCone
glutSolidTorus, glutWireTorus
glutSolidDodecahedron, glutWireDodecahedron
glutSolidOctahedron, glutWireOctahedron
glutSolidTetrahedron, glutWireTetrahedron
glutSolidIcosahedron, glutWireIcosahedron
glutSolidTeapot, glutWireTeapot
Ocak 2006
Dr. Aybars UĞUR
52
Üç Boyutlu Hazır Nesneler
II
glutSolidCone - render a solid or wireframe cone respectively.
glutWireCone
glutSolidCube - render a solid or wireframe cube respectively.
glutSolidDodecahedron - render a solid or wireframe
dodecahedron (12-sided regular solid) respectively.
glutSolidIcosahedron - render a solid or wireframe
icosahedron (20-sided regular solid) respectively.
glutSolidOctahedron - render a solid or wireframe
octahedron (8-sided regular solid) respectively.
glutSolidSphere - render a solid or wireframe sphere
respectively.
glutSolidTeapot - render a solid or wireframe teapot
respectively.
glutSolidTetrahedron - render a solid or wireframe
tetrahedron (4-sided regular solid) respectively.
glutSolidTorus - render a solid or wireframe torus
(doughnut) respectively.
Ocak 2006
Dr. Aybars UĞUR
53
Projection Matrix – I
Sets up a perspective projection.
– glFrustrum (...);
– gluPerspective (fovy,
aspect, near, far);
– glOrtho (...);
– gluLookAt (...);
(often applied to modelview matrix)
Ocak 2006
Dr. Aybars UĞUR
54
Projection Matrix - II
Example:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(64, (float)windowWidth /
(float)windowHeight, 4, 4096);
gluLookAt(0.0, 0.0, 2.0, // camera position
0.0, 0.0, 0.0, // target position
0.0, 0.0, 2.0);// up vector
Ocak 2006
Dr. Aybars UĞUR
55
Perspective Viewing Volume
Specified by gluPerspective()
Ocak 2006
Dr. Aybars UĞUR
56
Viewing Transformations
Default camera position
Ocak 2006
gluLookAt(4.0, 2.0, 1.0, 2.0, 4.0, -3.0, 2.0, 2.0, -1.0);
Dr. Aybars UĞUR
57
Viewport Transformation
The viewport transformation specifies the rectangular
region of the window where the model is drawn.
void glViewport(GLint x, GLint y, GLsizei width, GLsizei
height);
Defines a pixel rectangle in the window into which the final
image is mapped. The (x, y) parameter specifies the lowerleft corner of the viewport, and width and height are the
size of the viewport rectangle. By default, the initial
viewport values are (0, 0, winWidth, winHeight), where
winWidth and winHeight are the size of the window.
Ocak 2006
Dr. Aybars UĞUR
58
Viewport Transformation
The aspect ratio of a viewport should generally equal to the
aspect ratio of the viewing volume.
gluPerspective(fovy, 1.0, near, far);
glViewport(0, 0, 400, 400);
Ocak 2006
gluPerspective(fovy, 1.0, near, far);
glViewport (0, 0, 400, 200);
Dr. Aybars UĞUR
59
Sample Viewport
Application
// top left: top view
glViewport(0, win_height/2, win_width/2, win_height/2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-3.0, 3.0, -3.0, 3.0, 1.0, 50.0);
gluLookAt(0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glCallList(object);
// top right: right view
glViewport(win_width/2, win_height/2, win_width/2, win_height/2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-3.0, 3.0, -3.0, 3.0, 1.0, 50.0);
gluLookAt(5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glCallList(object);
// bottom left: front view
glViewport(0, 0, win_width/2, win_height/2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-3.0, 3.0, -3.0, 3.0, 1.0, 50.0);
gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glCallList(object);
Ocak 2006
// bottom right: rotating perspective view
glViewport(win_width/2, 0, win_width/2, win_height/2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(70.0, 1.0, 1, 50);
gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(30.0, 1.0, 0.0, 0.0);
glRotatef(Angle, 0.0, 1.0, 0.0);
glCallList(object);
Dr. Aybars UĞUR
60
OpenGL : Setting Up
Rendering States
OpenGL is a state machine: polygons are affected
by the current color, transformation, drawing
mode, etc.
Enable and disable features such as lighting,
texturing, and alpha blending.
– glEnable (GL_LIGHTING);
– glDisable (GL_FOG);
Forgetting to enable something is a common
source of bugs!
Ocak 2006
Dr. Aybars UĞUR
61
OpenGL:
Normals and Lighting
OpenGL can do lighting computations for you
Normal vectors should be of unit length
(normalized) in most cases.
Normal vector kept as state – each vertex is
assigned the most recently set normal vector
...
glNormal3fv
glVertex3fv
glVertex3fv
glVertex3fv
...
Ocak 2006
(n0);
(v0);
(v1);
(v2);
Dr. Aybars UĞUR
62
OpenGL: Lighting
glEnable (GL_LIGHTING);
OpenGL supports a minimum of 8 lights.
glEnable (GL_LIGHT0);
(GL_LIGHT7);
...
glEnable
Lights have a position, type, and color,
among other things (more details in text).
Types of lights are point light, directional
light, and spotlight.
Ocak 2006
Dr. Aybars UĞUR
63
Lighting in OpenGL
GLfloat amb0[] = {0.2, 0.4, 0.6, 1.0};
GLfloat diff0[] = {0.8, 0.9, 0.5, 1.0};
GLfloat spec0[] = {1.0, 0.8, 1.0, 1.0};
glLightfv(GL_LIGHT0, GL_AMBIENT, amb0);
//attach them to LIGHT0
glLightfv(GL_LIGHT0, GL_DIFFUSE, diff0);
glLightfv(GL_LIGHT0, GL_SPECULAR, spec0);
Ocak 2006
Dr. Aybars UĞUR
64
OpenGL:
Material Properties
Material properties are associated with each
polygon (corresponding light properties)
– glMaterial*(GLenum face, GLenum
pname, TYPE param);
Some properties (pname) :
–
–
–
–
Ocak 2006
GL_AMBIENT: Ambient color of material
GL_DIFFUSE: Diffuse color of material
GL_SPECULAR: Specular component (for highlights)
GL_SHININESS: Specular exponent (intensity of
highlight)
Dr. Aybars UĞUR
65
OpenGL: Texturing
Mapping the texture to the polygon
– specify (s,t) texture coordinates for
(x,y,z) polygon vertices
– texture coordinates (s,t)are from 0,1:
glTexCoord2f(s,t);
(x3,y3,z3) (x1,y1,z1)
0,1
1,1
t
1,1
+
0,0
Ocak 2006
s
0,0
1,0
(x0,y0,z0) (x2,y2,z2)
Dr. Aybars UĞUR
66
OpenGL: Alpha Blending
When enabled, OpenGL uses the alpha
channel to blend a new fragment’s color
value with a color in the framebuffer
+
=
New color
(r1,g1,b1,a1)
Color in framebuffer
(r0,g0,b0,a0)
“source”
“destination”
?
(r’,g’,b’,a’)
Useful for overlaying textures or other effects
Ocak 2006
Dr. Aybars UĞUR
67
OpenGL: Fog
Simulate atmospheric effects
•glFog ():
Sets fog parameters
•glEnable (GL_FOG);
Ocak 2006
Dr. Aybars UĞUR
68
Rendering Pipeline
Ocak 2006
Dr. Aybars UĞUR
69
OpenGL: Other Features
Display Lists (ch 7): Speed up your
game!
Quadrics (ch 11): Pre-made objects
– Also look at GLUT’s objects
Evaluators (ch 12): Bezier curves and
surfaces
Selection (ch 13): Clicking on game
objects with a mouse
Ocak 2006
Dr. Aybars UĞUR
70
CSGL
C Sharp Graphics Library
CSGL
OpenGL’in .NET ortamında kullanımını
sağlayan grafik kütüphanesidir.
Adresler :
– http://sourceforge.net/projects/csgl
– http://csgl.sourceforge.net/
• .NET üzerinde csgl.1.4.1.dll.zip install
dosyasından kurularak program
geliştirmeye başlanabilir.
Ocak 2006
Dr. Aybars UĞUR
72
Dikdörtgen Çizdiren CSGL
Kodu (1)
using System;
using System.Drawing;
using System.Windows.Forms;
using CsGL.OpenGL;
public class RectDemo : Form
{
MyView view = new MyView();
public static void Main()
{
RectDemo di = new
RectDemo();
Application.Run( di );
}
}
public RectDemo()
{
Text = "Rect demo !";
view.Dock = DockStyle.Fill;
Controls.Add( view );
}
Ocak 2006
Dr. Aybars UĞUR
73
Dikdörtgen Çizdiren CSGL
Kodu (2)
class MyView : OpenGLControl
{
public override void glDraw()
{
GL.glClear( GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT );
// Clear Screen And Depth Buffer
GL.glBegin( GL.GL_QUADS );
GL.glVertex2i( 10, 10 );
GL.glVertex2i( 10, 50 );
GL.glVertex2i( 100, 50 );
GL.glVertex2i( 100, 10 );
GL.glEnd();
GL.glFlush();
}
protected override void InitGLContext()
{
GL.glClearColor( 1.0f, 1.0f, 1.0f, 0.0f );
GL.glColor3f( 0.0f, 0.0f, 0.0f );
GL.glPointSize( 4.0f );
Ocak
Dr. Aybars UĞUR
} 2006
74
Dikdörtgen Çizdiren CSGL
Kodu (3)
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
GL.glMatrixMode(GL.GL_PROJECTION);
GL.glLoadIdentity();
GL.gluOrtho2D( 0.0, Size.Width, 0.0, Size.Height );
}
}
Ocak 2006
Dr. Aybars UĞUR
75
KAYNAKLAR
Bilgisayar Grafikleri ders notları,
Aybars UĞUR, Ege Üniversitesi
OpenGL Red Book
Sean Walker ve Ian Buck ders slaytları,
Stanford University
Ocak 2006
Dr. Aybars UĞUR
76