Introduzione ad OpenGL
Cosa è OpenGL E una interfaccia so8ware all hardware grafico, rendering API Indipendente dal sistema di windowing Indipendente dal sistema operabvo
Evoluzione di OpenGL Viene gesbta da una Architectural Review Board (ARB) SGI, Microso8, Nvidia, Apple, HP, IBM Stabile e retrocompabbile (è nata nel 1992 e adesso siamo alla versione 4.3) Estensioni plauorm specific www.opengl.org
API di supporto AGL, GLX, WGL Interfaccia con i sistemi di windowing GLU (OpenGL UBlity Library) Parte di opengl NURBS, tesselators, quadric etc GLUT API di windowing e gesbone evenb cross- plauorm Non è parte ufficiale di OpenGL
OpenGL e API di supporto applica>on program OpenGL Mo>f widget or similar GLX, AGL or WGL X, Win32, Mac O/S GLUT GLU GL so7ware and/or hardware
Macchina a StaB Le funzioni OpenGL sono di due Bpi: Cambio di Stato Colore corrente, modalità di shading etc., Generazione di primibve Possono generare un output visuale se la primibva è visibile Le primibve vengono processate in accordo allo stato corrente
Macchina a StaB Macchina a stab con input e output L input è la geometria in ingresso, l output è un set di pixel La macchina a stab converte una collezione di oggea geometrici in 3D in una immagine. Questo processo è controllato dallo stato. Gli stab specificano come gli oggea sono proiedab sul piano immagine, come vengono colorab ecc.
Formato comandi OpenGL glvertex3fv( v ) Number of components 2 - (x,y) 3 - (x,y,z) 4 - (x,y,z,w) Data Type b - byte ub - unsigned byte s - short us - unsigned short i - int ui - unsigned int f - float d - double Vector omit v for scalar form glvertex2f( x, y )
PrimiBve OpenGL Rappresentazione poligonale GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP GL_POLYGON GL_TRIANGLES GL_TRIANGLE_STRIP GL_TRIANGLE_FAN GL_QUADS GL_QUAD_STRIP
Poligoni OpenGL renderizzerà correcamente solo poligoni che sono: Semplici (lab che non si intersecano) Convessi Piani Polygon Issues OpenGL will only display polygons correctly that are - Simple: edges cannot cross - Convex: All points on line segment between two points in a polygon are also in the polygon - Flat: all vertices are in the same plane OpenGL User program non controlla must check se if le above condizioni true sopraelencate sono verificate Triangles satisfy all conditions nonsimple polygon nonconvex polygon 20
Vector V V 1 SECTION 1.3 Shading Normals 9 Normali Figure 1.6 Computing a surface normal from edge cross-product. Vector U V 0 V 2 Vector V V 2 V 1 Vector V V 1 V 3 Vector U.6 Computing a surface normal from edge cross-product. 10 CHAPTER 1 Geometry Representation and Modeling V 0 Vector U V 0 Figure 1.7 Computing quadrilateral surface normal from vertex cross-product. V 2 poly 00 V 1 Vector V Vector U.7 Computing quadrilateral surface normal from vertex cross-product. r polygons with more than four vertices it canfigure be difficult 1.8 Splitting to choose normals the best for hard vertices edges. for the cross product. One method is to to choose vertices that are the furthest rom each other, or to average the result of several vertex cross products. V 0 V 3 poly 10 v 0 Spliang normals poly 11 v 1 poly 12 v 2 poly 01 For polygons with more than four vertices it can be difficult to choose the best verti to use poly02 for the cross product. One method is to to choose vertices that are the furth apart from each other, or to average the result of several vertex cross products. poly 03 Hard edge 1.3.1 Smooth Shading v 3 poly 04 To smoothly shade an object, a given vertex normal should be used by all polygo v poly 05 4 that share that vertex. Ideally, this vertex normal is the same as the surface normal the corresponding point on v 5 the original surface. However, if the true surface norm poly13 isn t available, the simplest way to approximate one is to add all (normalized) norm v from the common facets then renormalize 6 poly the result (Gouraud, 1971). This provid 14 reasonable results for surfaces that are fairly smooth, but does not look good for surfa with sharp edges. poly 15 In general, the polygonal nature of models can be hidden by smoothing the transiti between adjacent polygons. However, an object that should have hard edges, such a TEAM L
is straightforward to connect the triangles together into longer strips. Decide whether the first triangle should have a clockwise or counterclockwise winding, then ensure all subsequent triangles in the list alternate windings (as shown in Figure 1.10). Triangle fans 1 must also be started with the correct winding, but all subsequent triangles are wound in 3 5 the same direction (Figure 1.11). VerBci Since OpenGL does not have a way to specify generalized triangle strips, the user must choose between GL_TRIANGLE_STRIP and GL_TRIANGLE_FAN. In general, the triangle strip is the more (a.k.a. versatile primitive. While vertex triangle fans are winding ideal for large convex order) polygons that need to be converted to triangles or for triangulating geometry that is cone-shaped, most other cases are best converted to triangle strips. Ordinamento dell avvolgimento dei 7 SECTION 1.3 Shad 1 0 3 5 7 2 9 4 6 1 3 0 0 2 Figure 1.10 Triangle strip winding. 6 Figure 1.10 Triangle strip winding. In base a come sono ordinab I verbci, si capisce come è orientata una faccia. 0 E possibile infaa scartare ( cull ) dal processo di rasterizzazione le facce che sono viste da dietro. 5 3 8 0 4 6 Figure 1.9 Proper winding for shared edge of adjoining facets. correct 1 results. 2 5 0 1 2 2 For 6 an object such as a cube, three hard edges will share one comm case the edge-splitting algorithm needs to be repeated for the third ed 1.3.2 Vertex Winding Order Some 3D models come with polygons that are not 3 all wound in a cloc clockwise direction, but are a4 mixture of both. Since the polygon win 1 2
Semplice Esempio
Controllare lo stato corrente Sedare lo stato glpointsize( size ); gllinesbpple( repeat, padern ); glshademodel( GL_SMOOTH); Abilitare features glenable(gl_lighting); gldisable(gl_texture_2d);
Camera Analogy viewing volume camera tripod model
Stadi della Vertex TrasformaBon
Trasformazioni Semplici gltranslate{fd}(type x, TYPE y, TYPE z); glrotate{fd}(type angle, TYPE x, TYPE y, TYPE z); glscale{fd}(type, x, TYPE y, TYPE z);
glulookat void glulookat( GLdouble GLdouble GLdouble GLdouble GLdouble GLdouble GLdouble GLdouble GLdouble eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz);
Ordine delle Trasformazioni V = {vx,vy,vz,vw} Modelview M1 * M2*.Mn* V
Ordine delle trasformazioni Dato il seguente ordine gltranslate=mattrans glrotate=matrot glscale=matscale drawcube=v La matrice Modelview sarà IdenBty- >Trans- >Trans*Rot- >Trans*Rot*Scale Trans(Rot(Scale*v)))
Ordine delle trasformazioni Sistema di coordinate globali Le trasformazioni vengono applicate a parbre dall ulbma Sistema di coordinate locali Le trasformazioni vengono applicate a parbre dalla prima Non funziona per scalature non omogenee
Also let Scaling Matrici RisultanB S = Translation 0 z' y' z' 0 x' y' x' 0 and M = u The call glscale*(x, y, z) generates S, where gltranslate*(x, The call gltranslate*(x, y,z); glscale*(x, y, y,z); generates T, Then glrotate*(a,x,y,z) where 1 x 0 0 0 1 0 0 x x 010 00 x m 0 1 0 y T = and T 1 1 0 y S = = 0 y 0 0 and S 0 0 1 z 1 z 1 0 1 m m 0 m y m 0 0m 0 = R = 0 0 z 0 m m 0 1 m 0 0 0 0 0 0 1 0 0 0 1 z 0 1 0 1 0 0 0 1 Scaling Notice that S806 1 is defined Appendix only C: if Homogeneous x, y, and z are C Rotation The call glscale*(x, y, z) generates S, where The call glrotate*(a, 1 x, y, z) generates R as foll x 0 0 0 T T
Matrix Stack glpushmatrix(): aggiunge la matrice corrente nello stack glpopmatrix(): preleva la matrice corrente dallo stack glloadiden>ty(): seda la matrice corrente all idenbtà glloadmatrix{fd}(m): seda la matrice corrente ad m glloadtransposematrix{fd}(m):sosbtuisce la matrice corrente con la matrice m (ordinata per righe) glmultmatrix{fd}(m): molbplica la matrice corrente per la matrice m e carica il valore nella matrice corrente glmulttransposematrix{fd}(m):molbplica la matrice corrente per la matrice ordinata per righe m, e carica il valore nella matrice corrente glgetfloatv(gl_modelview_matrix,m): carica in m I 16 valori della matrice GL_MODELVIEW
//... gltranslatef(x,y,z); // 1) posi*on for drawing torso DrawTorso(); // 2) draw torso glpushmatrix(); // 3) save torso matrix gltranslatef(x,y,z); // 4) posi*on for drawing arm DrawArm(); // 5) draw arm glpushmatrix(); // 6) save arm matrix gltranslatef(x,y,z); // 7) posi*on for drawing hand DrawHand(); // 8) draw hand glpushmatrix(); // 9) save hand matrix gltranslatef(x,y,z); // 10) posi*on for drawing first finger DrawFinger(); // 11) draw first finger glpopmatrix(); // 12) load hand matrix glpushmatrix(); // 13) save hand matrix again gltranslatef(x,y,z); // 14) posi*on for drawing second finger DrawFinger(); // 15) draw second finger glpopmatrix(); // 16) load hand matrix glpushmatrix(); // 17) save hand matrix again gltranslatef(x,y,z); // 18) posi*on for drawing third finger DrawFinger(); // 19) draw third finger glpopmatrix(); // 20) load hand matrix glpopmatrix(); // 21) load arm matrix glpopmatrix(); // 22) load torso matrix
camera transformation, we take the camera s actor transform and fli camera backward is equivalent to moving the whole world forward Tipico Display Loop the left is equivalent to rotating the whole world to the right. To ren sually take the approach outlined in Figure 4.30. Loop Save Identity Matrix Apply camera transform Draw stuff that doesn t move Draw moving stuff (Actors) Save camera transform Loop Apply actor transform Draw actor geometry Restore camera transform Restore identity matrix 0 Typical rendering loop for a 3D environment.
or OpenGL represents the approach a 4 4 orientation matrix of the two-dimensional not (vectors as a here two-dimensional are array used (the to second represent array option of a flo in di glloadmatrixd(glfloat m); but as a single in array space. out of in For 16 a row-major most floating-point purposes, order. In values. these math terms, three This the vectors approach two orientations are always is diffea math libraries, which another. Most OpenGL implementations and are usually store do take and each manipulate the of two-dimensional unit pipeline length data as (unless floats array and you notapproach. are also app Fo doubles; consequently, using second variation may incur some performance penalty prefers the first mathematical of these two term examples: for this (in case you want to impress yo because 16 double-precision numbers must be converted into single-precision a 0 floats. a 4 a 8 a 12 the vectors are unit length, and orthogonal when they are n The GLfloat following matrix[16]; code shows an array being loaded // Nice with the OpenGL identity matrix friendly and a 1 then a 5 matrix abeing 9 a 13 loaded into the modelview transformation matrix stack. This matrix example with is equivalent the column to callingvectors highlighted GLfloat matrix[4][4]; // Popular, but not aas 2 aefficient 6 a 10 a 14 for O glloadidentity using the matrix higher-level is all functions: 0s with the exception of the very last elem // Load an identity matrix GLfloat OpenGL m[] = can { 1.0f, use 0.0f, the 0.0f, second 0.0f, variation, // X Column but the first is a more efficient FIGURE 4.27 Column-major matrix ordering. 0.0f, 1.0f, 0.0f, 0.0f, // Y Column reason for this will become clear in a moment. These 16 elements repr 0.0f, 0.0f, 1.0f, 0.0f, // Z Column matrix, as shown 0.0f, 0.0f, in The 0.0f, Figure real 1.0f magic 4.27. }; lies When // in Translation the the fact array that these elements 16 values traverse represent dow a columns one by one, and we an call orientation this column-major of the three axes matrix with respect ordering. to the In eye mem co glmatrixmode(gl_modelview); glloadmatrixf(m); glloadtransposematrix*(type* m); that fixed, unchanging coordinate system we talked about earl numbers is not hard at all. The four columns each represent a things simple for this book, we focus our attention on just the X vectors. The fourth column vector contains x Y the x Z x, x T y, and x z valu dinate system s origin. When you call gltranslate X y Y y Z y on T y the iden your values for x, y, and z in the 12th, 13th, X z Yand z Z z 14th T z position The first three elements of the first three 0columns 0 0 are 1 just dire sent the orientation (vectors here are used to represent a direct in space. For most purposes, these three vectors are always at 9 FIGURE 4.28 a 3 X axis direction a 7 Y axis direction a 11 Z axis direction a 15 Translation/location How a 4 4 matrix represents a position and o
Matrix Modes Matrix Mode(glMatrixMode) ModelView Matrix (GL_MODELVIEW) ProjecBon Matrix (GL_PROJECTION)
glfrustum void glfrustum ( GLdouble GLdouble GLdouble GLdouble GLdouble GLdouble le8, right, bodom, top, nearval, farval);
sion of the z-buffer is influenced by the values of z near and z fa too large, roundoff errors in the hidden surface algorithm can be et z near =0. nt projection matrix can be retrieved using the command loatv(gl PROJECTION MATRIX, GLfloat *params);. glfrustum matrix Figure 2: View Frustum () creates a transformation matrix M C that maps the view f [ 1, 1] [ 1, 1]: M C = 2 z near right left 0 0 2 z near top bottom right+left right left 0 top+bottom top bottom 0 2 z far z near z far z near 0 0 z far+z near z far z near 0 0 1 0.
gluperspecbve void gluperspecbve( GLdouble fovy, GLdouble aspect, GLdouble znear, GLdouble zfar);
glortho void glortho( GLdouble le8, GLdouble right, GLdouble bodom, GLdouble top, GLdouble nearval, GLdouble farval);
glorhto Matrix Orthographic Projection The call glortho(l, r, b, t, n, f ) generates R, where R 2 r --------- l 0 0 r+ l --------- r --------- l 0 r l 2 2 0 t --------- b 0 t + b t b ---------- 0 --------- = t b and R 1 = 2 2 0 0 ---------- f + n ---------- 0 0 f n f n 0 0 0 1 0 0 R is defined as long as l r, t b, and n f.
gluortho2d void gluortho2d( GLdouble GLdouble GLdouble GLdouble le8, right, bodom, top); Come glortho, con near = - 1 e far = +1
e thought of as a unit viewport; the final transformation that we e viewport in pixel coordinates. Assume that the trueviewport Viewport TransformaBon lf-widths V x,v y. Then one final matrix is needed to map to the V x 0 0 V cx 0 V y 0 V cy 0 0 1 0 0 0 0 1 el coordinates are now ( Px P w, P ) y P w C x C y C z C w = P x P y P z P w and the z value for the point, is P z P w. Points Vcx e Vcy on è il centro the della near viewport clipping plane end up with a z valu Vx = width/2 inate system, and points on the far clipping plane have z coord Vy = height/2 ate system. Il punto Think window of coordinates the z coordinate sarà (Px/Pw, Py/Pw) as a normalized distanc I punb con z minore saranno quelli che passeranno il test Z Buffer n doing z-buffering, you want to retain the color of points with th
glviewport void glviewport( GLint x, GLint y, GLsizei width, GLsizei height);
Architedura
GLUT Strudura della applicazione Configurare ed aprire una nuova finestra Inizializzare lo stato OpenGL Registrare le funzioni di callback Render Resize Input: keyboard, mouse, etc Idle Far parbre il main loop
Esempio 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(); }
OpenGL IniBalizaBon void init( void ) { glclearcolor( 0.0, 0.0, 0.0, 1.0 ); glcleardepth( 1.0 ); } glenable( GL_LIGHT0 ); glenable( GL_LIGHTING ); glenable( GL_DEPTH_TEST );
GLUT Callback FuncBons RouBne eseguite in base all evento Window resize o redraw User input AnimaBon Registrare le callback: glutdisplayfunc( cbdisplay ); glutdisplayfunc( cbidle); glutkeyboardfunc(cbkeyboard);
Display Callback 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(); }
Idle Callbacks Usata per le anmazioni e per l aggiornamento glutidlefunc(cbidle); void idle( void ) { t += dt; glutpostredisplay(); }
User Input Callback void keyboard( char key, int x, int y ) { switch( key ) { case q : case Q : exit( EXIT_SUCCESS ); break; case r : case R : rotate = GL_TRUE; break; } }
Reshape Callback void reshape (int w, int h) { glviewport (0, 0, (GLsizei) w, (GLsizei) h); glmatrixmode (GL_PROJECTION); glloadidenbty (); gluortho2d (0.0, 4, 0, 4); }