Introducción a OpenGL

Download Report

Transcript Introducción a OpenGL

Introducción a OpenGL
LINK
http://www.sc.ehu.es/ccwgamoa/docencia/Material/Presentaciones
OpenGL
A. García-Alonso
1
Antecedentes
• CORE Graphics standard (SIGGRAPH 1977)
• IGL-Plot 10 (Tektronix)
– Interactive Graphic Library
• HP-GL “plotting language” (Hewlett Packard)
– Hewlett Packard Graphic Language
• Starbase (Hewlett Packard)
• PHIGS (standard ANSI, ISO)
– Programmer's Hierarchical Interactive Graphics System
• GKS, GKS-3D (standard ANSI, ISO)
– Graphic Kernel System
• GL (Silicon Graphics)
 OpenGL
– Graphic Library
OpenGL
A. García-Alonso
2
Clasificar-distinguir
“sistemas gráficos”
• Sintaxis y semántica de ficheros
– Estándar (ISO, ANSI, ...) : VRML, X3D
– Estándar industrial “de facto standard” : DXF, 3ds, obj, …
• Librerías, APIs, Toolkits, ...
–
–
–
–
–
OpenGL, Direct 3D
Java 3D
Open Inventor
Performer
[ Fahrenheit ]
(low level)
(scene graph, nodes)
(scene graph, nodes)
(large-scale visualization model)
(three levels)
• Motores
OpenGL
A. García-Alonso
3
Librerías en OpenGL
• Librería de funciones para generar imágenes a partir de modelos
3D, más otras librerías auxiliares
– gl la librería OpenGL relacionada directamente con el H/W
– glu librería de mayor nivel construida sobre OpenGL
– glaux librería fuera de uso
– glut librería para crear interfaces de usuario transportables (Linux,
Windows)
• En Visual C++ falta (están en el web de la asignatura)
– glut.dll  windows\system(32)
– glut.lib  …\lib
– glut.h  …\include\gl
OpenGL
A. García-Alonso
4
Entorno de programación
• Visual C++ (versión 6.0)
• Trabajamos en C, es decir sin crear clases de C++
• Añadir las librerías opengl32.lib glu32.lib glut32.lib
– Project : settings : link : Object/Library Modules
• Ficheros a incluir
– #include <GL/gl.h>
– #include <GL/glu.h>
– If you are using GLUT for managing your window manager
• #include <GL/glut.h>
• Note that glut.h includes gl.h, glu.h, and glx.h automatically,
so including all three files is redundant.
OpenGL
A. García-Alonso
5
Estados
• Máquina de estados
–
–
–
–
–
Color de fondo
Intensidad de luz
Material de dibujo
Luz encendida o apagada
etc
• Valor o estado
– glColor*(), glGetFloatv()
– glEnable(), glDisable(), glIsEnabled()
OpenGL
A. García-Alonso
6
Command syntax (functions)
•
glVertex3fv( ... )
–
–
–
–
•
Number Of Arguments: 2, 3, or 4
–
–
–
•
gl tells that this function belongs to the “gl” s/w package
3 is used to indicate three arguments
f is used to indicate that the arguments are floating point
v indicates that the arguments are in vector format
Bi-dimensional version of the command
3D or rgb
Homogeneous coordinates or rgb+alpha
Formats
–
–
OpenGL
absence of v indicates scalar format
v indicates vector format
A. García-Alonso
7
Tipos variables y constantes
• Las equivalencias más habituales aparecen en la tabla
– Se recomienda definir los argumentos que se pasan a las
funciones de OpenGL usando sus tipos predefinidos
• Para Glint unos sistemas pueden usar short, otros long
• Para Glfloat unos sistemas float otros double
Typical Corresponding
C-Language Type
b 8-bit integer
C-Language Type
s 16-bit integer
OpenGL Type
i 32-bit integer
int or long
f 32-bit floating-point
float
d 64-bit floating-point
double
ub 8-bit unsigned integer unsigned char
us 16-bit unsigned integer unsigned short
unsigned int
or
ui 32-bit unsigned integer
unsigned long
Data type
OpenGL
A. García-Alonso
OpenGL
Type Definition
GLbyte
GLshort
Glint GLsizei
Glfloat GLclampf
Gldouble GLclampd
Glubyte GLboolean
GLushort
Gluint Glenum
GLbitfield
8
Constants & “defined names”
• Ejemplos :
–
–
–
–
#define GL_COLOR_BUFFER_BIT
#define GL_POINTS
#define GL_LINE_LOOP
#define GL_POLYGON
0x00004000
0x0000
0x0002
0x0009
• Defined names (for constants)
– Begin with GL_
– Use all capital letters
– Use underscores to separate words
• Operaciones “bitwise inclusive or operator”
– glutInitDisplayMode( GLUT_RGB | GLUT_SINGLE )
OpenGL
A. García-Alonso
9
Sistema gobernado por eventos
• Event (evento) : teclado, ratón, pasar por, etc.
• Callback : nombre, tipo, interfaz
• Bind : a callback to an event (asociar función y evento)
• Main( )
– Inicialización
– Loop (bucle) dispatch events (proceso eventos)
•
Post an event
OpenGL
A. García-Alonso
10
Ejemplo 010 : Dibuja 3 segmentos
• Cfr. OpenGLPrimer 010
– Dibuja tres líneas
• OpenGL functions and (concepts)
– gl
– glut
• Sistema gobernado por eventos : estructura “main”
– Inicialización
•
•
•
•
Creación ventana contenga el drawingarea de soporte
Asociar función (callback) a un evento (teclado, ratón, etc.)
Evento “drawingarea exposed”
Ajustar algún estado de “gl”
– Bucle proceso eventos
OpenGL
A. García-Alonso
11
... (gl)
• pure "output", but lacks connection with display
–
–
–
–
–
–
–
–
–
–
OpenGL
glClear
glClearColor
glBegin glEnd
glVertex*
glColor*
glFlush, glFinish
(command)
(state)
(geometry)
(attribute, state)
(command stack & processing)
(debbuging)
(aspect ratio)
(mapping from modelling coord. to display coordinates)
(need for a transformation management system)
A. García-Alonso
12
... (glut)
• Window system independent management
– “window” management
•
•
•
•
glutInitDisplayModel( GLUT_RGB | GLUT_SINGLE );
glutInitWindowSize( WIDTH, HEIGHT );
glutInitWindowPosition ( 550, 350 );
glutCreateWindow(“Basic Draw");
– “input” : event handling
• similar to : The X Window system, MOTIF, MFF, ...
•
(event)
• void Display(void);
(callback function)
• glutDisplayFunc( Display );
(binding event & callback)
– void Display ( void )
• glutMainLoop();
(dispatching events)
OpenGL
A. García-Alonso
13
Ejemplo 011 : Teclado
• Exit from an application
• Profundizar en el concepto de CallBack
• gl
– glLineWidth
• glut
– glutPostRedisplay()
– glutKeyboardFunc( DoIt )
• void DoIt (unsigned char key, int x, int y)
• DoIt puede tomar cualquier nombre
• Sin embargo, al declarar y definir la función, su tipo y el de sus
parámetros debe ser forzosamente el que se indica
OpenGL
A. García-Alonso
14
Diferenciar estos tres métodos
glutPostRedisplay
posts
OpenGL
glutDisplayFunc
Display
binds
draws
A. García-Alonso
15
Primitivas
GL_POINTS
GL_LINES
GL_LINE_LOOP
GL_LINE_STRIP
GL_TRIANGLES
GL_TRIANGLE_STRIP
GL_TRIANGLE_FAN
GL_QUADS
GL_QUAD_STRIP
GL_POLYGON
OpenGL
A. García-Alonso
16
...
• Otras primitivas disponibles (glu library)
– Polígonos : cóncavos, múltiplemente conexos
– Objetos (uso auxiliar, no para crear modelos)
– Evaluators, NURBS, etc
• Vertex arrays (veremos después de los atributos)
• Display lists (veremos después de los atributos)
• Texto
– No existe primitiva
– Usar texturas, problema aliasing
OpenGL
A. García-Alonso
17
Atributos
• glPointSize(GLfloat)
• glLineWidth(GLfloat)
• glLineStipple(GLint factor, GLushort pattern)
– glEnable( GL_LINE_STIPPLE )
• glPolygonMode( face, mode )
– GL_FRONT GL_BACK GL_FRONT_AND_BACK
– GL_POINT GL_LINE GL_FILL
•
•
•
•
glPolygonStipple (enable)
“transparency”
glEdgeFlag*
mode Line, splitted concave polygons
glColor*
glMaterial*
OpenGL
A. García-Alonso
18
Variables de estado
• Valor de defecto
• Valor actual
• Gestión en una aplicación o en un módulo reutilizable
– Valor de defecto en una aplicación dada
– Política de cambios de estado en un módulo de software
• glPushAttrib( ored mask ) / glPopAttrib()
– Permiten salvar grupos de atributos
OpenGL
A. García-Alonso
19
Grupos de
atributos
OpenGL
GL_ACCUM_BUFFER_BIT
accum-buffer
GL_ALL_ATTRIB_BITS
--
GL_COLOR_BUFFER_BIT
color-buffer
GL_CURRENT_BIT
current
GL_DEPTH_BUFFER_BIT
depth-buffer
GL_ENABLE_BIT
enable
GL_EVAL_BIT
eval
GL_FOG_BIT
fog
GL_HINT_BIT
hint
GL_LIGHTING_BIT
lighting
GL_LINE_BIT
line
GL_LIST_BIT
list
GL_PIXEL_MODE_BIT
pixel
GL_POINT_BIT
point
GL_POLYGON_BIT
polygon
GL_POLYGON_STIPPLE_BIT
polygon-stipple
GL_SCISSOR_BIT
scissor
GL_STENCIL_BUFFER_BIT
stencil-buffer
GL_TEXTURE_BIT
texture
GL_TRANSFORM_BIT
transform
A. García-Alonso
GL_VIEWPORT_BIT
viewport
20
Agrupamiento
• Vertex arrays
– Evitar pérdidas de tiempo en llamadas a funciones
• Display Lists
– Ídem
– La información puede estar ya más procesada
– Almacenar en el procesador gráfico para aliviar el bus
• Workstations
• PCs
OpenGL
A. García-Alonso
21
Comandos entre : glBegin-glEnd
Command
OpenGL
Purpose of Command
Reference
glVertex*()
set vertex coordinates
Chapter 2
glColor*()
set current color
Chapter 5
glIndex*()
set current color index
Chapter 5
glNormal*()
set normal vector coordinates
Chapter 2
glEvalCoord*()
generate coordinates
Chapter 11
glCallList(), glCallLists()
execute display list(s)
Chapter 4
glTexCoord*()
set texture coordinates
Chapter 9
glEdgeFlag*()
control drawing of edges
Chapter 2
glMaterial*()
set material properties
A. García-Alonso
Chapter 6
22
Ejemplo 020 : Window to viewport
• Exit from an application
• gl
–
–
–
–
–
glMatrixMode
glLoadIdentity
viewport
glOrtho
glGetIntegerv
• glut
– glutReshapeFunc( myNewSize )
• void myNewSize( int w, int h )
OpenGL
A. García-Alonso
23
Implementación en OpenGL
•
•
•
•
•
•
Materiales
Fuentes de luz
Parámetros de control
Texturas
Bucle de visualización interactiva
Aspectos prácticos estructuras de datos
– Modelos geométricos
– Materiales
– Luces
OpenGL
A. García-Alonso
24
Materiales
OpenGL
A. García-Alonso
25
Fuentes de luz
OpenGL
A. García-Alonso
26
Parámetros de control
OpenGL
A. García-Alonso
27
Texturas
• Textura superficies
• Reducir detalles geométricos
• Iluminación precalculada (texturas, texturas animadas)
OpenGL
A. García-Alonso
28
Bucle de visualización
OpenGL
A. García-Alonso
29
Estructuras geométricas
OpenGL
A. García-Alonso
30
Estructuras materiales
OpenGL
A. García-Alonso
31
Estructuras luces
•
•
•
•
Limitadas (8)
Coste de las luces
Luz en la cabeza
VRML : radio de acción de las luces posicionales y
focos
OpenGL
A. García-Alonso
32
Materiales (parámetros)
• Definir las constantes usadas para distintos materiales:
hierro, acero, plata, oro
OpenGL
A. García-Alonso
33