160
An Interactive Introduction to OpenGL Programming Dr. Mohammad Iqbal Based-on slide : Dave Shreiner, Ed Angel, Vicki Shreiner

An Interactive Introduction to OpenGL Programmingkarmila.staff.gunadarma.ac.id/Downloads/files/36466/mohiqbal+-+All... · zRegister fungsi input callback zrender zresize zinput: keyboard,

Embed Size (px)

Citation preview

An Interactive Introduction to OpenGL Programming

Dr. Mohammad IqbalBased-on slide : Dave Shreiner, Ed Angel, Vicki Shreiner

2

Agenda

General OpenGL IntroductionRendering PrimitivesRendering ModesLightingTexture MappingAdditional Rendering AttributesImaging

3

Goals for Today

Tujuan : mendemonstrasikan OpenGL dalam menghasilkan program grafik interaktif dalam

Membuat model 3D obyek atau imageryLighting - pencahayaantexture mapping

Mengenalkan topik lanjut untuk pendalaman berikutnya

OpenGL and GLUT Overview

5

OpenGL and GLUT Overview

Apakah OpenGL & apa manfaatnya?OpenGL dalam sistem windowMengapa GLUTTemplate program GLUT

6

Apakah OpenGL?

Graphics rendering API (Application Programming Interface)

citra warna high-quality yang terdiri darigeometric dan citra primitifIndependen window systemIndependen operating system

7

Arsitektur OpenGL

DisplayList

PolynomialEvaluator

Per VertexOperations &

PrimitiveAssembly

Rasterization Per FragmentOperations

FrameBuffer

TextureMemory

CPU

PixelOperations

8

OpenGL sebagai Renderer

Geometric primitiftitik, garis dan poligon

Image PrimitifCitra dan bitmapMemisahkan pipeline untuk citra dangeometry

linked ketika penerapan texture mapping

Rendering tergantung pada statuswarna, material, light sources, dll.

9

API yang Terkait OpenGL

AGL, GLX, WGLPerekat antara OpenGL dan sistem window

GLU (OpenGL Utility Library)Bagian OpenGLNURBS, tessellators, quadric shapes, dll.

GLUT (OpenGL Utility Toolkit)portable windowing APIBukan bagian OpenGL secara ofisial

10

API yang Terkait OpenGL

GLUT

GLU

GL

GLX, AGLor WGL

X, Win32, Mac O/S

software and/or hardware

application program

OpenGL Motifwidget or similar

11

Preliminaries

Headers Files#include <GL/gl.h>#include <GL/glu.h>#include <GL/glut.h>

LibrariesEnumerated Types

OpenGL defines numerous types for compatibility

GLfloat, GLint, GLenum, etc.

12

Dasar-dasar GLUT

Struktur AplikasiConfigure dan open windowInitialisasi status OpenGLRegister fungsi input callback

renderresizeinput: keyboard, mouse, dll.

Enter event processing loop

13

Contoh Program

void main( int argc, char** argv ){int mode = GLUT_RGB|GLUT_DOUBLE; glutInitDisplayMode( mode );glutCreateWindow( argv[0] );init();glutDisplayFunc( display );glutReshapeFunc( resize ); glutKeyboardFunc( key );glutIdleFunc( idle );glutMainLoop();

}

14

Inisialisasi OpenGL

Set up status yg ingin digunakanvoid init( void ){

glClearColor( 0.0, 0.0, 0.0, 1.0 );glClearDepth( 1.0 );

glEnable( GL_LIGHT0 );glEnable( GL_LIGHTING );glEnable( GL_DEPTH_TEST );

}

15

Fungsi input Callback GLUT

Rutin yang dipanggil ketika sesuatu terjadi

window resize atau redrawuser inputanimasi

Me-“register” callbacks pada GLUTglutDisplayFunc( display );glutIdleFunc( idle );glutKeyboardFunc( keyboard );

16

Rendering Callback

Lakukan penggambaran grafik pada bagian ini :

glutDisplayFunc( display );

void display( void ){

glClear( GL_COLOR_BUFFER_BIT );glBegin( GL_TRIANGLE_STRIP );

glVertex3fv( v[0] );glVertex3fv( v[1] );glVertex3fv( v[2] );glVertex3fv( v[3] );

glEnd();glutSwapBuffers();

}

17

Idle Callbacks

Gunakan untuk animasi dan update yang continyu

glutIdleFunc( idle );

void idle( void ){

t += dt;glutPostRedisplay();

}

18

User Input Callbacks

Untuk pemrosesan input dari userglutKeyboardFunc( keyboard );

void keyboard( unsigned char key, int x, int y ){

switch( key ) {case ‘q’ : case ‘Q’ :exit( EXIT_SUCCESS );break;

case ‘r’ : case ‘R’ :rotate = GL_TRUE;glutPostRedisplay();break;

}}

Elementary Rendering

20

Agenda Elementary Rendering

Geometric PrimitivesManaging OpenGL StateOpenGL Buffers

21

OpenGL Geometric Primitif

GL_QUAD_STRIPGL_QUAD_STRIP

GL_POLYGONGL_POLYGON

GL_TRIANGLE_STRIPGL_TRIANGLE_STRIP

GL_TRIANGLE_FANGL_TRIANGLE_FAN

GL_POINTSGL_POINTSGL_LINESGL_LINES

GL_LINE_LOOPGL_LINE_LOOPGL_LINE_STRIPGL_LINE_STRIP

GL_TRIANGLESGL_TRIANGLES

GL_QUADSGL_QUADS

Semua jenis geometric primitif dispesifikasikan oleh pipeline vertices

22

Contoh Sederhana

void drawRhombus( GLfloat color[] ){

glBegin( GL_QUADS );glColor3fv( color );glVertex2f( 0.0, 0.0 );glVertex2f( 1.0, 0.0 );glVertex2f( 1.5, 1.118 );glVertex2f( 0.5, 1.118 );glEnd();

}

23

Format Perintah OpenGL

glVertex3fv( glVertex3fv( vv ))

Number ofNumber ofcomponentscomponents

2 2 -- (x,y) (x,y) 3 3 -- (x,y,z)(x,y,z)4 4 -- (x,y,z,w)(x,y,z,w)

Data TypeData Typeb b -- bytebyteub ub -- unsigned byteunsigned bytes s -- shortshortus us -- unsigned shortunsigned shorti i -- intintui ui -- unsigned intunsigned intf f -- floatfloatd d -- doubledouble

VectorVector

omit omit ““vv”” forforscalar formscalar form

glVertex2f( x, y )glVertex2f( x, y )

24

Specifying Geometric Primitives

Primitif dispesifikasikan menggunakan :glBegin( glBegin( primType primType ););

glEnd();glEnd();

primType menentukan bagaimana verticedikombinasikan

GLfloat red, green, blue;Glfloat coords[3];glBegin( primType );for ( i = 0; i < nVerts; ++i ) {

glColor3f( red, green, blue );glVertex3fv( coords );

}glEnd();

25

Model Warna OpenGL

color index mode

Display12

48

16

Red Green Blue0123

242526

123 219 74

RGBA mode

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

RGBA atau Color Index

26

Shapes Tutorial

27

Mengendalikan tampilan Appearance (Rendering)

Dari Wireframemenjadi TextureMapped

28

Mesin Status OpenGL

Setiap atribut rendering di encapsulapsi dalam OpenGL State

rendering stylesshadinglightingtexture mapping

29

Manipulasi Status OpenGL

Tampilan dikendalikan oleh status terakhirfor each ( primitive to render ) {

update OpenGL staterender primitive

}

Manipulasi atribut vertex adalah cara umum untuk memanipulasi status

glColor*() / glIndex*()glNormal*()

glTexCoord*()

30

Mengendalikan Status terakhir

Setting StatusglPointSize( glPointSize( sizesize ););

glLineStipple( glLineStipple( repeatrepeat, , pattern pattern ););

glShadeModel( glShadeModel( GLGL__SMOOTHSMOOTH ););

Enabling FeaturesglEnable( glEnable( GLGL__LIGHTING LIGHTING ););

glDisable( glDisable( GL_TEXTURE_2D GL_TEXTURE_2D ););

Transformasi

32

Transformasi dalam OpenGL

ModelingViewing

orientasi kameraprojection

AnimasiMap to screen

33

Analogi Kamera

3D adalah seperti mengambil citra padafotografi (Banyak foto!)

camera

tripod model

viewingvolume

34

Analogi Kamera dan Transformasi

Projection transformationsMengatur lensa kamera

Viewing transformationsMengatur posisi tripod dan orientasi viewing suatu volume dalam dunia nyata (world)

Modeling transformationsmemindahkan model

Viewport transformationsMemperbesar atau mengurangi fotografi secara fisik

35

Sistem Koordinat dan Transformasi

Langkah dalam menyiapkan citraspesifikasikan geometri (world coordinates)spesifikasikan kamera (camera coordinates)proyeksi (window coordinates)Petakan ke viewport (screen coordinates)

Setiap langkah menggunakan transformasiSetiap transformasi adalah ekuivalen pada perubahan di sistem koordinat (frames)

36

Transformasi Affine

Transformasi yang mempertahankanbentuk geometri

garis, poligon, quadricAffine = mempertahankan garis (linepreserving)

Rotasi, translasi, skalaProyeksiKonkatnasi (komposisi)

37

Koordinat Homogen

Setiap vertex adalah vector kolom

w umumnya bernilai 1.0Semua operasi adalah perkalian matriksArah (directed line segments) direpresentasikan w = 0.0

⎥⎥⎥⎥

⎢⎢⎢⎢

=

wzyx

v

38

⎥⎥⎥⎥

⎢⎢⎢⎢

=

151173

141062

13951

12840

mmmmmmmmmmmmmmmm

M

3D Transformations

Vertex ditransformasikan oleh 4 x 4 matrikSemua operasi affine adalah perkalian matriksSemua matrik disimpan secara column-majordalam OpenGLmatriks selalu dalam kondisi post-multipliedProduk matrik dan vector adalah vM

39

Menspesifikasikan Transformasi

Programmer memiliki 2 styles untukmen-spesifikasikan transformasi

spesifikasikan matriks (glLoadMatrix, glLoadMatrix, glMultMatrixglMultMatrix)spesifikasikan operasi (glRotate, glRotate, glOrthoglOrtho)

Programmer tidak perlu mengingat jenis matriksnya secara tepat

cek lampiran buku Red Book (Programming Guide)

40

Programming Transformations

Sebelum proses rendering, view, locate, dan orientasi :

Posisi mata/kamera3D geometri

Mengatur matriksTermasuk matriks stack

Kombinasikan (composite) transformasi

41

vertex

ModelviewMatrix

ProjectionMatrix

PerspectiveDivision

ViewportTransform

Modelview

Modelview

Projection

object eye clip normalizeddevice

window

Bbrp kalkulasi tambahan :material colorshade model (flat)polygon rendering modepolygon cullingclipping

Pipeline Transformasi CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

42

Operasi Matriks

Spesifikasikan Matriks Stack terkiniglMatrixMode( GL_MODELVIEW atau GL_PROJECTION )

Matriks atau operasi Stack lainglLoadIdentity() glPushMatrix()glLoadIdentity() glPushMatrix()glPopMatrix()glPopMatrix()

ViewportBiasanya sama dengan ukuran window sizeaspek rasio viewport harus sama dengan transformasi proyeksi atau citra hasilnya akan terdistorsiglViewport( x, y, width, height )

43

Transformasi Proyeksi

Bentuk untuk menampilkan (viewing) frustum :

Perspective projectiongluPerspective( fovy, aspect, zNear, zFar )glFrustum( left, right, bottom, top, zNear, zFar )

Orthographic parallel projectionglOrtho( left, right, bottom, top, zNear, zFar )

gluOrtho2D( left, right, bottom, top )

Gunakan glOrtho dengan nilai z mendekati nol

44

Mengaplikasikan Transformasi Proyeksi

Pengunaan Umum (orthographic projection)glMatrixMode( GL_PROJECTION );glMatrixMode( GL_PROJECTION );

glLoadIdentity();glLoadIdentity();

glOrtho( left, right, bottom, top, zNear, zFar glOrtho( left, right, bottom, top, zNear, zFar ););

45

Viewing Transformations

Posisi Kamera/mata dalam scenePosisikan tripod (eye) ; persiapkan (aim) Kamera

Untuk Scene “fly through”Ubah transformasi viewing danre-draw scenegluLookAt( eyex, eyey, eyez,

aimx, aimy, aimz,upx, upy, upz )

up vector menghasilkan orientasi unikBerhati-hati dalam de-generate posisi

tripod

46

Projection Tutorial

47

Modeling Transformations

Memindahkan obyekglTranslate{fd}( glTranslate{fd}( x, y, zx, y, z ))

Rotasi obyek di sekitar sumbu utamaglRotateglRotate{{fdfd}( }( angle, x, y, zangle, x, y, z ))

angle dalam derajatDilasi (stretch atau shrink) atau mirror objectglScale{fd}( glScale{fd}( x, y, zx, y, z ))

( )zyx

48

Transformation Tutorial

49

Connection: Viewing dan Modeling

Memindahkan kamera equivalentdengan memindahkan setiap obyek di dunia nyata di depan kamera diamViewing transformation equivalent dengan transformasi modelinggluLookAt() memiliki perintah tersendiriyaitu polar view atau pilot view

50

Proyeksi dengan kaidah tangan kiri

Projection transformations (gluPerspective, glOrtho) berdasarkan kaidah tangan kiri

bayangkan zNear dan zFar sebagai jarak tertentu dari view point

Setiap hal selain itu adalah kaidah tangan kanan, termasuk vertex yang dirender

xx

yy

z+

z+

left handed right handed

51

Penggunaan Umum Transformasi

3 contoh rutin resize()Re-status proyeksi & viewing transformations

Umumnya dipanggil ketika window resizeDi-register sebagai callback untuk glutReshapeFunc()

52

resize(): Perspective & LookAt

void resize( int w, int h ){

glViewport( 0, 0, (GLsizei) w, (GLsizei) h );glMatrixMode( GL_PROJECTION );glLoadIdentity();gluPerspective( 65.0, (GLdouble) w / h,

1.0, 100.0 );glMatrixMode( GL_MODELVIEW );glLoadIdentity();gluLookAt( 0.0, 0.0, 5.0,

0.0, 0.0, 0.0, 0.0, 1.0, 0.0 );

}

53

resize(): Perspective & Translate

Efek yang sama dengan LookAt :

void resize( int w, int h ){

glViewport( 0, 0, (GLsizei) w, (GLsizei) h );glMatrixMode( GL_PROJECTION );glLoadIdentity();gluPerspective( 65.0, (GLdouble) w/h,

1.0, 100.0 );glMatrixMode( GL_MODELVIEW );glLoadIdentity();glTranslatef( 0.0, 0.0, -5.0 );

}

54

resize(): Ortho (bagian 1)

void resize( int width, int height ){

GLdouble aspect = (GLdouble) width / height;GLdouble left = -2.5, right = 2.5;GLdouble bottom = -2.5, top = 2.5;glViewport( 0, 0, (GLsizei) w,

(GLsizei) h );glMatrixMode( GL_PROJECTION );glLoadIdentity();… continued …

55

if ( aspect < 1.0 ) {left /= aspect;right /= aspect;

} else {bottom *= aspect;top *= aspect;

}glOrtho( left, right, bottom, top,

near, far );glMatrixMode( GL_MODELVIEW );glLoadIdentity();

}

resize(): Ortho (bagian 2)

56

Membangun Modeling Transformations

Masalah 1: hirarki obyekSuatu posisi tergantung pada posisi sebelumnyaLengan robot atau tangan ; sub-assemblies

Solusi 1: memindahkan sistem koordinat lokalmodeling transformation untuk memindahkan sistem koordinatpost-multiply column-major matrices OpenGL post-multiplies matrices

57

Membangun Modeling Transformations

Masalah 2 : obyek berpindah secara relatifpada absolute world origin

Obyek berotasi di area yang salah pada originMembuat obyek spin di sekitar center atau suatu area

Solusi 2: fixed coordinate systemmodeling transformations akan memindahkan obyek disekitar fixed coordinate systempre-multiply column-major matricesOpenGL post-multiplies matricesharus me-reverse order operasi untuk mendapatkan efek yang diinginkan

58

Area Clipping Tambahan

Paling tidak ada 6 atau lebih area clippingBaik untuk perhitungan cross-sectionsModelview matrix memindahkan area clipping

clipped

glEnable( GL_CLIP_PLANEi )glClipPlane( GL_CLIP_PLANEi, GLdouble* coeff )

0<+++ DCzByAx

59

Reversing Koordinat Proyeksi

Screen space kembali ke world spaceglGetIntegerv( GL_VIEWPORT, GLint viewport[4] )glGetDoublev( GL_MODELVIEW_MATRIX, GLdouble

mvmatrix[16] )glGetDoublev( GL_PROJECTION_MATRIX,

GLdouble projmatrix[16] )gluUnProject( GLdouble winx, winy, winz,

mvmatrix[16], projmatrix[16],GLint viewport[4],GLdouble *objx, *objy, *objz )

gluProject untuk memindahkanworld space ke screen space

Pencahayaan (Lighting)

61

Prinsip Pencahayaan

Pencahayaan mensimulasikan bagaimana obyek memantulkan cahaya

Komposisi material obyekWarna cahaya dan posisiParameter global pencahayaan

Cahaya ambienPencahayaan dua sisi

Terdapat pada color index dan mode RGBA

62

Bagaimana OpenGL Mensimulasikan Cahaya

Model Pencahayaan PhongPerhitungan pada vertices

Kontributor PencahayaanProperti permukaan materialProperti cahayaProperti Model pencahayaan

63

SurfaceNormals

Normal mendefinisikan bagaimana pemukaan memantulkan cahaya

glNormal3f( glNormal3f( x, y, zx, y, z ))

Current normal digunakan untuk menghitung warna vertexGunakan unit normals untuk pencahayaan yang tepat

Skalakan efek pada panjang normalglEnable( GL_NORMALIZE )

orglEnable( GL_RESCALE_NORMAL )

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

64

Material Properties

Definisikan properti permukaan obyek primitifglMaterialfv( face, property, value );

Pisahkan material antara bagian front dan back

GL_DIFFUSE Base color

GL_SPECULAR Highlight Color

GL_AMBIENT Low-light Color

GL_EMISSION Glow Color

GL_SHININESS Surface Smoothness

65

Properti Cahaya

glLightfv( light, property, value );

light menspesifikasikan jenis cahayamultiple lights, mulai dari GL_LIGHT0glGetIntegerv( GL_MAX_LIGHTS, &n );

propertiesWarnaposisi dan typeAttenuation (metode perambatan)

66

Sumber cahaya

Light color propertiesGL_AMBIENTGL_DIFFUSEGL_SPECULAR

67

Tipe Cahaya

OpenGL mendukung 2 tipe Cahaya :Local (Point) light sourcesInfinite (Directional) light sources

Tipe cahaya dikendalikan oleh koordinatw

( )( )w

zw

yw

xwzyxw

at positioned Light Local along directed LightInfinite

00

≠=

68

Menyalakan (Turning on) Cahaya

Flip setiap “switch” cahayaglEnable( GL_LIGHTn );

Turn on the powerglEnable( GL_LIGHTING );

69

Light Material Tutorial

70

Mengendalikan Posisi Cahaya

Modelview matrix berpengaruh padaposisi cahaya:

Perbedaan efek berdasarkan kapan posisi cahaya dispesifikasikan

eye coordinatesworld coordinatesmodel coordinates

Matrik Push dan pop untuk pengendali unik posisi cahaya

71

Light Position Tutorial

72

Fitur Pencahayaan Lanjut

SpotlightMelokalisasi efek cahaya

GL_SPOT_DIRECTIONGL_SPOT_CUTOFFGL_SPOT_EXPONENT

73

Fitur Pencahayaan Lanjut

Perambatan cahaya (Light attenuation)decrease light intensity with distance

GL_CONSTANT_ATTENUATIONGL_LINEAR_ATTENUATIONGL_QUADRATIC_ATTENUATION

2

1dkdkk

fqlc

i ++=

74

Properti Model Cahaya

glLightModelfv( property, value );

Enabling two sided lightingGL_LIGHT_MODEL_TWO_SIDE

Global ambient colorGL_LIGHT_MODEL_AMBIENT

Local viewer modeGL_LIGHT_MODEL_LOCAL_VIEWER

Separate specular colorGL_LIGHT_MODEL_COLOR_CONTROL

75

Tips untuk pencahayaan yg baik

Pemanggilan Pencahayaan dikomputasi hanya pada vertices

Pemanggilan pada model tessellation memang menghasilkan kualitas pencahayaan yang lebih baik tapi proses geometrinya lebih kompleks

Gunakan cahaya tunggal infinite untuk perhitungan pencahayaan cepat

Karena komputasi minimal untuk setiap vertex-nya

Animasi dan Depth Buffering

77

Animation dan Depth Buffering

Mendikusikan double buffering dananimasiMendiskusikan hidden surface removalmenggunakan depth buffer

78

DoubleBuffering

12

48

16

12

48

16FrontBuffer

BackBuffer

Display

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

79

Animasi menggunakan Double Buffering

Defenisikan double buffered pada color bufferglutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE );

Clear color bufferglClear( GL_COLOR_BUFFER_BIT );

Render sceneDefinisikan swap untuk front dan back buffers

glutSwapBuffers();

Ulangi langkah 2 - 4 untuk animasi

80

Depth Buffering danHidden Surface Removal

12

48

16

12

48

16ColorBuffer

DepthBuffer

Display

81

Depth Buffering menggunakan OpenGL

Defenisikan depth bufferglutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );

Enable depth bufferingglEnable( GL_DEPTH_TEST );

Clear color dan depth buffersglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

Render sceneSwap color buffers

82

An Updated Program Template

void main( int argc, char** argv ){

glutInit( &argc, argv );glutInitDisplayMode( GLUT_RGB |

GLUT_DOUBLE | GLUT_DEPTH );glutCreateWindow( “Tetrahedron” );init();glutIdleFunc( idle );glutDisplayFunc( display );glutMainLoop();

}

83

An Updated Program Template (Lanjutan)void init( void ){

glClearColor( 0.0, 0.0, 1.0, 1.0 );}

void idle( void ){

glutPostRedisplay();}

84

An Updated Program Template (Lanjutan)

void drawScene( void ){

GLfloat vertices[] = { … };GLfloat colors[] = { … };glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

glBegin( GL_TRIANGLE_STRIP );/* calls to glColor*() and glVertex*() */glEnd();glutSwapBuffers();

}

Texture Mapping

86

TextureMapping CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

mengaplikasikan citra 1D, 2D, atau 3D ke geometrik primitifHal yang digunakan untuk proses Texturing

simulasi materialMengurangi kompleksitas geometrikimage warpingrefleksi

87

Texture Mapping

s

t

x

y

z

image

geometry screen

88

Texture Mapping dan OpenGLPipeline

geometry pipelinevertices

pixel pipelineimagerasterizer

Citra dan geometri mengalir dalam pipeline yang terpisah pada proses dirasterizer

“kompleks” textures tidak berpengaruh pada kompleksitas geometrik

89

Contoh Tekstur

Tekstur ini adalah citra256 x 256 yang di gabung(mapped) dengan poligonpersegi panjang yang ditampilkan pada perspektif

90

Cara mengaplikasikan Tekstur I

Three stepsspecify texture

read or generate imageassign to textureenable texturing

assign texture coordinates to verticesspecify texture parameters

wrapping, filtering

91

Tekstur Obyek

Like display lists for texture imagesone image per texture objectmay be shared by several graphics contexts

Generate texture namesglGenTextures( n, *texIds );

92

Cara mengaplikasikan Tekstur II

specify textures in texture objectsset texture filter set texture function set texture wrap modeset optional perspective correction hintbind texture object enable texturingsupply texture coordinates for vertex

coordinates can also be generated

93

Tekstur Obyek (lanjutan)

Create texture objects with texture data and stateglBindTexture( target, id );

Bind textures before usingglBindTexture( target, id );

94

Define a texture image from an array of texels in CPU memory

glTexImage2D( target, level, components,w, h, border, format, type, *texels );

dimensions of image must be powers of 2Texel colors are processed by pixel pipeline

pixel scales, biases and lookups can bedone

Memilih citrauntuk Tekstur CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

95

Konversikan citra Tekstur

If dimensions of image are not power of 2gluScaleImage( format, w_in, h_in,

type_in, *data_in, w_out, h_out,type_out, *data_out );

*_in is for source image*_out is for destination image

Image interpolated and filtered during scaling

96

Memilih Tekstur: Methode Lainnya

Use frame buffer as source of texture imageuses current buffer as source image

glCopyTexImage1D(...)glCopyTexImage1D(...)glCopyTexImage2D(...)glCopyTexImage2D(...)

Modify part of a defined textureglTexSubImage1D(...)glTexSubImage1D(...)glTexSubImage2D(...)glTexSubImage2D(...)glTexSubImage3D(...)glTexSubImage3D(...)

Do both with glCopyTexSubImage2D(...), etc.

97

Based on parametric texture coordinatesglTexCoord*() specified at each vertex

s

t 1, 10, 1

0, 0 1, 0

(s, t) = (0.2, 0.8)

(0.4, 0.2)

(0.8, 0.4)

A

B C

a

bc

Texture Space Object Space

Memetakan(Mapping) Tekstur

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

98

Membuat Koordinat Tekstur

Automatically generate texture coordsglTexGen{ifd}[v]()

specify a planegenerate texture coordinates based upon distance from plane

generation modesGL_OBJECT_LINEARGL_EYE_LINEARGL_SPHERE_MAP

0=+++ DCzByAx

99

Tutorial: Texture

100

Filter Modesminification or magnificationspecial mipmap minification filters

Wrap Modesclamping or repeating

Texture Functionshow to mix primitive’s color with texture’s color

blend, modulate or replace texels

Metode Aplikasi Tekstur

101

Filter Modes

Texture PolygonMagnification Minification

PolygonTexture

Example:glTexParameteri( glTexParameteri( target, type, modetarget, type, mode ););

102

Tekstur Mipmapped

Mipmap allows for prefiltered texture maps of decreasing resolutionsLessens interpolation errors for smaller textured objectsDeclare mipmap level during texture definitionglTexImage*D( glTexImage*D( GL_TEXTURE_*D, level, GL_TEXTURE_*D, level, …… ))

GLU mipmap builder routinesgluBuild*DMipmaps( gluBuild*DMipmaps( …… ))

OpenGL 1.2 introduces advanced LOD controls

103

Mode Wrapping

Example:glTexParameteri( GL_TEXTURE_2D,

GL_TEXTURE_WRAP_S, GL_CLAMP )glTexParameteri( GL_TEXTURE_2D,

GL_TEXTURE_WRAP_T, GL_REPEAT )

texture

s

t

GL_CLAMPwrapping

GL_REPEATwrapping

104

Fungsi berkaitan dengan Tekstur

Controls how texture is appliedglTexEnv{fi}[v]( GL_TEXTURE_ENV, prop,

param )

GL_TEXTURE_ENV_MODE modesGL_MODULATEGL_BLENDGL_REPLACE

Set blend color with GL_TEXTURE_ENV_COLOR

105

Tips untuk Koreksi Perspektif

Texture coordinate and color interpolationeither linearly in screen spaceor using depth/perspective values (slower)

Noticeable for polygons “on edge”glHint( GL_PERSPECTIVE_CORRECTION_HINT,

hint )where hint is one of

GL_DONT_CAREGL_NICESTGL_FASTEST

106

Adakah tempat untuk Tekstur?

Query largest dimension of texture imagetypically largest square texturedoesn’t consider internal format size

glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size )

Texture proxywill memory accommodate requested texture size? no image specified; placeholderif texture won’t fit, texture state variables set to 0

doesn’t know about other texturesonly considers whether this one texture will fit all of memory

107

Texture Residency

Working set of textureshigh-performance, usually hardware acceleratedtextures must be in texture objectsa texture in the working set is residentfor residency of current texture, check GL_TEXTURE_RESIDENT state

If too many textures, not all are residentcan set priority to have some kicked out firstestablish 0.0 to 1.0 priorities for texture objects

Imaging and Raster Primitives

109

Imaging and Raster Primitives

Describe OpenGL’s raster primitives: bitmaps and image rectanglesDemonstrate how to get OpenGL to read and render pixel rectangles

110

Pixel-based primitives

Bitmaps2D array of bit masks for pixels

update pixel color based on current color

Images2D array of pixel color information

complete color information for each pixel

OpenGL doesn’t understand image formats

FrameBuffer

Rasterization(including

Pixel Zoom)

Per FragmentOperations

TextureMemory

Pixel-TransferOperations

(and Pixel Map)CPU

PixelStorageModes

glReadPixels(), glCopyPixels()

glBitmap(), glDrawPixels()

glCopyTex*Image();

Pixel Pipeline

Programmable pixel storageand transfer operations

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

112

Positioning Image Primitives

glRasterPos3f( x, y, z )raster position transformed like geometrydiscarded if raster positionis outside of viewport

may need to fine tuneviewport for desiredresults

Raster Position

113

Rendering Bitmaps

glBitmap( width, height, xorig, yorig, xmove, ymove, bitmap )

render bitmap in current colorat advance raster position by

after rendering

⎣ ⎦ ⎣ ⎦( )yorigyxorigx −−

( )ymovexmove

width

heig

ht

xorig

yorig

xmove

114

Rendering Fonts using Bitmaps

OpenGL uses bitmaps for font renderingeach character is stored in a display list containing a bitmapwindow system specific routines to access system fonts

glXUseXFont()wglUseFontBitmaps()

115

Rendering Images

glDrawPixels( width, height, format, type, pixels )

render pixels with lower left ofimage at current raster positionnumerous formats and data typesfor specifying storage in memory

best performance by using format and type that matches hardware

116

Reading Pixels

glReadPixels( x, y, width, height, format, type, pixels )

read pixels from specified (x,y) position in framebufferpixels automatically converted from framebuffer format into requested format and type

Framebuffer pixel copyglCopyPixels( x, y, width, height,

type )

117

RasterPosition

glPixelZoom(1.0, -1.0);

Pixel Zoom

glPixelZoom( x, y )expand, shrink or reflect pixelsaround current raster positionfractional zoom supported

118

Storage and Transfer Modes

Storage modes control accessing memory

byte alignment in host memoryextracting a subimage

Transfer modes allow modify pixel values

scale and bias pixel component valuesreplace colors using pixel maps

Advanced OpenGL Topics

120

Advanced OpenGL Topics

Display Lists and Vertex ArraysAlpha Blending and AntialiasingUsing the Accumulation BufferFogFeedback & SelectionFragment Tests and OperationsUsing the Stencil Buffer

121

Immediate Mode versus Display Listed Rendering

Immediate Mode GraphicsPrimitives are sent to pipeline and display right awayNo memory of graphical entities

Display Listed GraphicsPrimitives placed in display listsDisplay lists kept on graphics serverCan be redisplayed with different stateCan be shared among OpenGL graphics contexts

122

Immediate Mode versus Display Lists

Immediate Mode

Display Listed

DisplayList

PolynomialEvaluator

Per VertexOperations &

PrimitiveAssembly

Rasterization Per FragmentOperations

TextureMemory

CPU

PixelOperations

FrameBuffer

123

Display Lists

Creating a display listGLuint id;void init( void ){

id = glGenLists( 1 );glNewList( id, GL_COMPILE );/* other OpenGL routines */glEndList();

}

Call a created listvoid display( void ){

glCallList( id );}

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

124

Display Lists

Not all OpenGL routines can be stored in display listsState changes persist, even after a display list is finishedDisplay lists can call other display listsDisplay lists are not editable, but you can fake it

make a list (A) which calls other lists (B, C, and D)delete and replace B, C, and D, as needed

125

Display Lists and Hierarchy

Consider model of a carCreate display list for chassisCreate display list for wheel

glNewList( CAR, GL_COMPILE );glCallList( CHASSIS );glTranslatef( … );glCallList( WHEEL );glTranslatef( … );glCallList( WHEEL );

…glEndList();

126

Advanced Primitives

Vertex ArraysBernstein Polynomial Evaluators

basis for GLU NURBSNURBS (Non-Uniform Rational B-Splines)

GLU Quadric Objectsspherecylinder (or cone)disk (circle)

127

Vertex Arrays

Colordata

Vertexdata

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

Pass arrays of vertices, colors, etc. to OpenGL in a large chunk

glVertexPointer( 3, GL_FLOAT, 0, coords )glColorPointer( 4, GL_FLOAT, 0, colors )glEnableClientState( GL_VERTEX_ARRAY )glEnableClientState( GL_COLOR_ARRAY )glDrawArrays( GL_TRIANGLE_STRIP, 0,

numVerts );All active arrays are used in rendering

128

Why use Display Lists or Vertex Arrays?

May provide better performance than immediate mode renderingDisplay lists can be shared between multiple OpenGL context

reduce memory usage for multi-context applications

Vertex arrays may format data for better memory access

129

Alpha: the 4th Color Component

Measure of Opacitysimulate translucent objects

glass, water, etc.composite imagesantialiasingignored if blending is not enabled

glEnable( GL_BLEND )

130

Blending

Combine pixels with what’s in alreadyin the framebuffer

glBlendFunc( src, dst )

FramebufferFramebufferPixelPixel((dstdst))

BlendingEquation

BlendingEquation

FragmentFragment((srcsrc))

BlendedBlendedPixelPixel

pfr CdstCsrcC +=

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

131

Multi-pass Rendering

Blending allows results from multiple drawing passes to be combined together

enables more complex rendering algorithms

Example of bump-mappingdone with a multi-pass

OpenGL algorithm

132

Antialiasing

Removing the JaggiesglEnable( mode )

GL_POINT_SMOOTHGL_LINE_SMOOTHGL_POLYGON_SMOOTH

alpha value computed by computingsub-pixel coverageavailable in both RGBA and colormap modes

133

Accumulation Buffer

Problems of compositing into color buffers

limited color resolutionclampingloss of accuracy

Accumulation buffer acts as a “floating point” color buffer

accumulate into accumulation buffertransfer results to frame buffer

134

Accessing Accumulation Buffer

glAccum( op, value )operations

within the accumulation buffer: GL_ADD, GL_MULTfrom read buffer: GL_ACCUM, GL_LOADtransfer back to write buffer: GL_RETURN

glAccum(GL_ACCUM, 0.5) multiplies each value in write buffer by 0.5 and adds to accumulation buffer

135

Accumulation Buffer Applications

CompositingFull Scene AntialiasingDepth of FieldFilteringMotion Blur

136

Full Scene Antialiasing : Jittering the view

Each time we move the viewer, the image shifts

Different aliasing artifacts in each imageAveraging images using accumulationbuffer averages outthese artifacts

137

Depth of Focus : Keeping a Plane in Focus

Jitter the viewer to keep one plane unchanged

Front Plane

Back Plane

Focal Plane

eye pos1 eye pos2

138

Fog

glFog{if}( property, value )

Depth CueingSpecify a range for a linear fog ramp

GL_FOG_LINEAR

Environmental effectsSimulate more realistic fog

GL_FOG_EXPGL_FOG_EXP2

139

Fog Tutorial

140

Feedback Mode

Transformed vertex data is returned to the application, not rendered

useful to determine which primitives will make it to the screen

Need to specify a feedback bufferglFeedbackBuffer( size, type, buffer )

Select feedback mode for renderingglRenderMode( GL_FEEDBACK )

141

Selection Mode

Method to determine which primitives are inside the viewing volumeNeed to set up a buffer to have results returned to you

glSelectBuffer( glSelectBuffer( size, buffersize, buffer ))

Select selection mode for renderingglRenderMode( GL_SELECT )

142

Selection Mode (cont.)

To identify a primitive, give it a name“names” are just integer values, not strings

Names are stack basedallows for hierarchies of primitives

Selection Name Routines

glLoadName( name ) glPushName( name )glInitNames()

143

Picking

Picking is a special case of selectionProgramming steps

restrict “drawing” to small region near pointer

use gluPickMatrix() on projection matrix

enter selection mode; re-render sceneprimitives drawn near cursor cause hitsexit selection; analyze hit records

144

Picking Template

glutMouseFunc( pickMe );

void pickMe( int button, int state, int x, int y ){GLuint nameBuffer[256];GLint hits;GLint myViewport[4];if (button != GLUT_LEFT_BUTTON ||

state != GLUT_DOWN) return;glGetIntegerv( GL_VIEWPORT, myViewport );glSelectBuffer( 256, nameBuffer );(void) glRenderMode( GL_SELECT );glInitNames();

145

Picking Template (cont.)

glMatrixMode( GL_PROJECTION );glPushMatrix();glLoadIdentity();gluPickMatrix( (GLdouble) x, (GLdouble)

(myViewport[3]-y), 5.0, 5.0, myViewport );/* gluPerspective or glOrtho or other

projection */glPushName( 1 );

/* draw something */glLoadName( 2 );

/* draw something else … continue … */

146

Picking Template (cont.)

glMatrixMode( GL_PROJECTION );glPopMatrix();hits = glRenderMode( GL_RENDER );

/* process nameBuffer */}

147

Picking Ideas

For OpenGL Picking Mechanismonly render what is pickable (e.g., don’t clear screen!)use an “invisible” filled rectangle, instead of textif several primitives drawn in picking region, hard to use z values to distinguish which primitive is “on top”

Alternatives to Standard Mechanismcolor or stencil tricks (for example, use glReadPixels() to obtain pixel value from back buffer)

148

Getting to the Framebuffer

BlendingBlendingDepthTest

DepthTest DitheringDithering Logical

OperationsLogical

Operations

ScissorTest

ScissorTest

StencilTest

StencilTest

AlphaTest

AlphaTest

Frag

men

t

Fram

ebuf

fer

149

Scissor Box

Additional Clipping TestglScissor( x, y, w, h )

any fragments outside of box are clippeduseful for updating a small section of a viewport

affects glClear() operations

150

Alpha Test

Reject pixels based on their alpha valueglAlphaFunc( func, value )glEnable( GL_ALPHA_TEST )

use alpha as a mask in textures

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

151

Stencil Buffer

Used to control drawing based on values in the stencil buffer

Fragments that fail the stencil test are not drawnExample: create a mask in stencil buffer and draw only objects not in mask area

CPUCPU DLDL

Poly.Poly. PerVertex

PerVertex

RasterRaster FragFrag FBFB

PixelPixelTextureTexture

152

Controlling Stencil Buffer

glStencilFunc( func, ref, mask )compare value in buffer with ref using funconly applied for bits in mask which are 1func is one of standard comparison functions

glStencilOp( fail, zfail, zpass )Allows changes in stencil buffer based on passing or failing stencil and depth tests: GL_KEEP, GL_INCR

153

Creating a Mask

glInitDisplayMode( …|GLUT_STENCIL|… );glEnable( GL_STENCIL_TEST );glClearStencil( 0x0 );

glStencilFunc( GL_ALWAYS, 0x1, 0x1 );glStencilOp( GL_REPLACE, GL_REPLACE,

GL_REPLACE );

draw mask

154

Using Stencil Mask

Draw objects where stencil = 1glStencilFunc( GL_EQUAL, 0x1, 0x1

)

Draw objects where stencil != 1glStencilFunc( GL_NOTEQUAL, 0x1,

0x1 );glStencilOp( GL_KEEP, GL_KEEP,

GL_KEEP );

155

Dithering

glEnable( GL_DITHER )

Dither colors for better looking resultsUsed to simulate more available colors

156

Logical Operations on Pixels

Combine pixels using bitwise logical operations

glLogicOp( mode )Common modes

GL_XORGL_AND

157

Advanced Imaging

Imaging SubsetOnly available if GL_ARB_imaging defined

Color matrixConvolutionsColor tablesHistogramMinMaxAdvanced Blending

Ringkasan dan Penutup

159

On-Line Resources

http://www.opengl.orgstart here; up to date specification and lots of sample code

news:comp.graphics.api.openglhttp://www.sgi.com/software/openglhttp://www.mesa3d.org/

Brian Paul’s Mesa 3Dhttp://www.cs.utah.edu/~narobins/opengl.html

very special thanks to Nate Robins for the OpenGL Tutorssource code for tutors available here!

160

Buku

OpenGL Programming Guide, 3rd EditionOpenGL Reference Manual, 3rd EditionOpenGL Programming for the X Window System

includes many GLUT examplesInteractive Computer Graphics: A top-down approach with OpenGL, 2nd Edition