sistemas gráficos - PaperMint Designs

Transcripción

sistemas gráficos - PaperMint Designs
SISTEMAS GRÁFICOS
TMM: Tecnoloxia Multimedia. 2006
GRUPO DE PROCESADO DE IMAGEN Y REALIDAD VIRTUAL
ETSI Telecomunicación. Universidad de Vigo
Donde Estamos?
Generalidades
●
Gráficos Interactivos
–
Interfaces herramientas CAD
–
Interfaces herramientas de Modelado 3D
–
Entretenimiento
–
Interiores
–
etc...
Donde NO Estamos?
Generalidades
●
●
Imágen Fotorealista
–
Películas
–
Post Producción
Técnicas
–
Ray­Tracing (POV Ray)
Arquitectura Hardware I
Generalidades
●
CPU
●
RAM
●
BUS
●
VRAM
●
GPU
●
DAC
RAM
CPU
BUS (PCI, AGP, PCI Express)
Tarjeta Gráfica
Arquitectura Hardware II
Generalidades
RAM
CPU
●
Lee datos RAM
●
Escribe VRAM a través del Bus PCI
●
GPU lee VRAM
●
DAC genera señal de Video
BUS PCI/ISA/VESA LB
VRAM
GPU
DAC
VRAM Dual­Port Memory
Flicker – Retrazo Vertical
PCI : 133 MB/s
Arquitectura Hardware III
Generalidades
●
GPU accede directamente a la RAM del equipo
●
CPU
RAM
Tarjeta Gráfica tiene memoria local
●
Velocidades de bus
BUS AGP/PCI Express
VRAM
GPU
GPU procesador complejo
DAC
AGP x4 : 1 GB/s
AGP x8: 2.1 GB/s
PCI­Express (x16): 4GB/s
Arquitectura Hardware IV
Generalidades
●
MultiGPU
–
Permiten la conexión de varias tarjetas de video
Mejora del rendimiento
–
Dos Soluciones: ATI CrossFire y nVidia SLI
Arquitectura Hardware V
Generalidades
●
SLI: Scalable Link Interface
–
Require 2 PCI­Express x16
–
2 o 4 tarjetas (QUAD SLI)
–
Tarjetas idénticas conectadas por una PCB
–
Formas de trabajo:
●
SFR: Split Frame Rendering
●
AFR: Alternate Frame Rendering
Arquitectura Hardware IV
Generalidades
●
ATI Cross­Fire
–
Las tarjetas no tienen que ser idénticas
–
Master Card Composition chip
–
Modos de Funcionamiento:
●
Super Tiling
●
Scissor (SFR)
●
Alternate Frame Rendering (AFR)
●
CrossFire SuperAA
Arquitectura Hardware V
Generalidades
●
ATI Cross­Fire. Diagrama
Matemáticas I
Generalidades
●
Coordenadas Homogéneas
Coordenadas Homogéneas
(x, y, z) ­> (x, y, z, 1)
Transformación Afín
x ­> Ax +b
Matriz de Transformación
A b
0 1
–
Permiten representar transformaciones afines como operaciones con matrices
–
Transformaciones Afines: Transformación lineal + Traslación
●
Rotación, Escalado, Proyección...
–
Transformar un vector en coordenadas homogéneas =
= Multiplicarlo por la matriz
–
Composición de Transformaciones = = Producto de Matrices
Matemáticas II
Generalidades
●
Quaternion
v = a + b∙i + c∙j + d∙k = a + u
Propiedades
i*i = j*j = k*k = ­1
ij=k, jk=i, ki=j
ji=­k, kj=­i, ik=­j
Quaternions
–
Se pueden ver como una generalización de los números
complejos
–
Representan rotaciones respecto a un eje –
Utilizados para realizar rotaciones suaves:
●
Spherical Linear Interpolation (SLERP)
Introduccion
OpenGL
Notas
Desarrollado por SGI en 1992
Soportado en la mayoria
de plataformas existentes en
la actualidad
●
API de bajo nivel (primitivas gráficas sencillas)
●
Utilidades de mas alto nivel GLU, GLUT
–
●
No proporciona Widgets/Ventanas
–
●
Utility and Utility Toolkit
Se requiere un interfaz con el sistema de ventanas (glx/wglx, SDL, glut,...)
Alternativa: –
Microsoft DirectX (Direct3D) Introduccion
OpenGL
●
●
La especificacion la gestiona el Architecture Review Board (ARB)
Existen varias extensiones a la especificacion
–
●
ARB, NV, HP, SGI, etc...
Dos libros para empezar:
–
Libro Rojo (Redbook):
OpenGL Programming Guide
–
Libro Azul (BlueBook): OpenGL Reference Manual
Sitio Oficial
www.opengl.org
Aplicaciones Graficas
OpenGL
●
Estructura general de una aplicación Gráfica
–
INICIALIZACIÓN
–
BUCLE INFINITO PRINCIPAL
●
Lee Eventos
●
Procesa Eventos
●
Render Frame
●
Duerme Proceso
Matrices
OpenGL. Conceptos Generales
●
●
●
Trabajaremos con coordenadas homogéneas y matrices de transformación.
Matrices
–
PROJECTION_MATRIX: Prespectiva/ortonormal
–
MODELVIEW_MATRIX: Representación
–
TEXTURE_MATRIX: Manipulación de texturas
OpenGL permite la manipulación sencilla de las matrices:
glTranslatef (4.0f, 0.0f, ­10.0f); ­> Genera una traslación
Buffers
OpenGL Conceptos Generales
●
OpenGL gestiona diversos buffers necesarios para la representación de los gráficos:
–
COLOR_BUFFER: Imagen generada
–
Z_BUFFER: Información de profundidad de cada pixel de la imagen
–
STENCIL_BUFFER: Enmascarado de pixels
–
ACCUMULATION_BUFFER: Buffer de acumulación
Hola Mundo con GLUT I
OpenGL Programacion
●
Creando la ventana
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
int main (int argc, char *argv) {
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutCreateWindow (argv[0]);
init ();
...
Hola Mundo con GLUT II
OpenGL Programacion
●
Preparando Eventos
...
glutDisplayFunc (display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
void init(void){
glClearColor (0.0f, 0.0f, 0.0f);
glShadeMode (GL_FLAT);
}
Hola Mundo con GLUT III
OpenGL Programacion
●
Render. La funcion display
void display(void) { glClear (GL_COLOR_BUFFER_BIT); glColor3f (1.0, 1.0, 1.0); glLoadIdentity (); /* clear the matrix viewing transform*/ 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 (); }
Transformaciones
OpenGL Programacion
●
Tres transformaciones:
–
Translaciones
●
–
Rotaciones
●
–
glTranslatef (desp_x, desp_y, desp_z);
glRotatef (angulo, x, y, z);
Escalado
●
glScalef (escala_x, escala_y, escala_z);
Hola Mundo con GLUT III
OpenGL Programacion
●
Cambiando ViewPort. Funcion reshape
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); } MATRIX DE PROJECCION
glFrustum: Prespectiva
glOrtho: Ortografica
Hola Mundo con GLUT III
OpenGL Programacion
●
Proyeccion: Prespectiva y Ortografica
MATRIX DE PROJECCION
glFrustum: Prespectiva
glOrtho: Ortografica
Usando el Teclado I
OpenGL Programacion
●
Funcion de gestion de eventos de teclado
... /* En main */
glutKeyboardFunc (keyboard);
...
void keyboard (unsigned char key, int x, int y) {
switch (key) {
case 'a': rotX += 10.0f;
break;
case 's': rotX ­= 10.0f
break;
}
glutPostRedisplay();
}
Usando el Teclado II
OpenGL Programacion
●
Nueva funcion display
static GLfloat rotX;
void display(void) { glClear (GL_COLOR_BUFFER_BIT); glColor3f (1.0, 1.0, 1.0); glLoadIdentity (); 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); glRotatef (rotX, 1.0f, 0.0f, 0.0f);
glutWireCube (1.0); glFlush (); } Usando el Raton
OpenGL Programacion
●
Funcion de gestion de eventos de raton
... /* En main */
glutMouseFunc (mouse);
...
void mouse (int button, int state, int x, int y) {
switch (button) {
case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) rotX += 10.0f;
break;
case GLUT_RIGHT_BUTTON: (...)}
glutPostRedisplay();
}
Geometrias
OpenGL Programacion
●
Dibujando un Triangulo Rojo
void triangle(void)
{
glBegin (GL_TRIANGLES);
glColor3f (1.0, 0.0, 0.0);
glVertex2f (5.0, 5.0);
glVertex2f (25.0, 5.0);
glVertex2f (5.0, 25.0);
GL_POINTS
GL_LINES
GL_LINE_STRIP
GL_LINE_LOOP
GL_TRIANGLES
GL_TRIANGLES_STRIP
GL_TRIANGLES_FAN
GL_QUADS
GL_QUAD_STRIP
GL_POLYGON
glEnd();
}
void init(void) { glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
}
glVertex2{fd} (x, y)
glVertex3{fd} (x, y, z)
glVertex4{fd} (x, y, z, w)
Geometrias
OpenGL Programacion
●
Primitivas de Dibujo Geometrico
GL_POINTS
GL_LINES
GL_LINE_STRIP
GL_LINE_LOOP
GL_TRIANGLES
GL_TRIANGLES_STRIP
GL_TRIANGLES_FAN
GL_QUADS
GL_QUAD_STRIP
GL_POLYGON
Geometrias y Sombreado
OpenGL Programacion
●
Triangulo de color
void triangle(void)
{
glBegin (GL_TRIANGLES);
glColor3f (1.0, 0.0, 0.0);
glVertex2f (5.0, 5.0);
glColor3f (0.0, 1.0, 0.0);
glVertex2f (25.0, 5.0);
glColor3f (0.0, 0.0, 1.0);
glVertex2f (5.0, 25.0);
glEnd();
}
void init(void) { glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_SMOOTH);
}
Hidden-Surface Removal
OpenGL Programacion
●
Uso del Z­Buffer
int main (int argc, char* argv[]) {
...
glutInitDisplayMode (GLUT_DEPTH | GLUT_SINGLE | GLUT_RGB);
...
}
void display(void) {
glClear (GL_COLOR_BIT | GL_DEPTH_BUFFER_BIT);
/* Dibuja figuras solapadas */
...
}
Iluminacion I
OpenGL Programacion
●
●
Definicion de Luces
–
Ambiente: Luz ambiental proveniente de todas direcciones
–
Difusa: Luz que proviene de una direccion y rebota en una superficie en todas direcciones
–
Especular: Luz que proviene de una direccion y rebota en otra direccion definida
Materiales
–
Definen la reflectancia ambiental, difusa y especular de una superficie
Iluminacion II
OpenGL Programacion
●
Definiendo Luces y Materiales
Posicion luces
Direccional: w=0
Posicional: w=1
void init(void) {
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 50.0 };
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_SMOOTH);
GL_SHININESS
GL_AMBIENT
GL_DIFUSSE
GL_SPECULAR
GL_EMISSION
GL_AMBIENT_AND_DIFFUSSE
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
Iluminacion III
OpenGL Programacion
●
Definiendo Luces y Materiales 2
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
}
void display(void)
{
GL_POSITION
GL_AMBIENT
GL_DIFFUSE
GL_SPECULAR
GL_SPOT_DIRECTION
GL_SPOT_EXPONENT
GL_SPOT_CUTOFF
GL_CONSTANT_ATTENUATION
GL_LINEAR_ATTENUATION
GL_CUADRATIC_ATTENUATION
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glutSolidSphere (1.0, 20, 16);
glFlush ();
}
Iluminacion IV
OpenGL Programacion
●
Resultados
Transparencias
OpenGL Programacion
●
Usando Transparencias
–
Habilitarlo con glEnable
–
Seleccionar funcion para el mezclado de colores
–
El orden de dibujado importa
void init(void) {
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glShadeModel (GL_FLAT);
glClearColor (0.0, 0.0, 0.0, 0.0);
}
Transparencias
OpenGL Programacion
●
Usando Transparencias
static void drawLeftTriangle(void)
{
/* draw yellow triangle on LHS of screen */
glBegin (GL_TRIANGLES);
glColor4f(1.0, 1.0, 0.0, 0.75);
glVertex3f(0.1, 0.9, 0.0);
glVertex3f(0.1, 0.1, 0.0);
glVertex3f(0.7, 0.5, 0.0);
glEnd();
}
Display Lists I
OpenGL Programacion
●
●
Mejoran rendimiento cuando se dibuja una misma geometria repetidamente
Creacion y uso de Display Lists
void init (void) { geom1 = glGenLists (1); GL_COMPILE
GL_COMPILE_AND_EXECUTE
glNewList (geom1, GL_COMPILE); /* Comandos OpenGL para generar la geometria*/ glEndList(); ....
void display (void) {
.... glCallList (geom1);
Display Lists II
OpenGL Programacion
●
Ejecutando Multiples Display Lists
void init (void) { GLuint base;
base = glGenLists (128);
glListBase (base);
glNewList (base + 'A', GL_COMPILE); genera_letraA (); ...
glNewList (base + 'Z', GL_COMPILE); genera_letraZ ();
glEndList(); ....
void display (void) {
.... glCallLists (10, GL_BYTE, (GLbyte*) “HOLA MUNDO”);
Texturas I
OpenGL Programacion
●
Creacion de texturas
Gluint texName;
glGenTextures (1, &texName);
glBindTexture (GL_TEXTURE_2D, texName);
GL_REPEAT
GL_CLAMP
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage);
Texturas II
OpenGL Programacion
●
Mapeando texturas
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glBindTexture(GL_TEXTURE_2D, texName);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex3f(­2.0, ­1.0, 0.0);
glTexCoord2f(0.0, 1.0); glVertex3f(­2.0, 1.0, 0.0);
glTexCoord2f(1.0, 1.0); glVertex3f(0.0, 1.0, 0.0);
glTexCoord2f(1.0, 0.0); glVertex3f(0.0, ­1.0, 0.0);
....
Texturas III
OpenGL Programacion
●
Generacion de Texturas
void glTexImage2D( GLenum target,
GL_TEXTURE_2D
GL_PROXY_TEXTURE_2D
GLint level,
LoD
GLint internalFormat,
GLsizei width,
GLsizei height,
2m + 2b (en general potencias de 2)
GLint border,
GLenum format,
GLenum type,
const GLvoid *pixels )
0 o 1
Formato de pixels
RGB, BYTE...
Texturas IV
OpenGL Programacion
●
●
Otras operaciones con texturas
–
glCopyTexImage2D: Obtiene imagen del Framebuffer
–
glTexSubImage2D: Sustituye una parte de la textura
–
Render to Texture, Texturas animadas,...
Texturas 1D
–
glTexImage1D: Textura de una dimension (linea)
Texturas V
OpenGL Programacion
●
●
LoD (Level of Detail). Mip Mapping
–
Del latin (Multim im parvo)
–
Original, 1/4, 1/16, 1/64
–
OpenGL determina que textura utilizar dependiendo del tamaño del objeto (pixels) en el que se mapea
MipMapping
–
Hay que porporcionar todas las texturas, desde la original hasta 1x1 pixels
Texturas VI
OpenGL Programacion
●
Generando un Mipmap
GLubyte mipmapImage32[32][32][4];
....
GLubyte mipmapImage1[1][1][4];
....
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 32, 32, 0,
GL_RGBA, GL_UNSIGNED_BYTE, mipmapImage32);
glTexImage2D(GL_TEXTURE_2D, 1, GL_RGBA, 16, 16, 0,
GL_RGBA, GL_UNSIGNED_BYTE, mipmapImage16);
...
glTexImage2D(GL_TEXTURE_2D, 5, GL_RGBA, 1, 1, 0,
GL_RGBA, GL_UNSIGNED_BYTE, mipmapImage1);
Texturas VII
OpenGL Programacion
●
MipMap Render
glBindTexture(GL_TEXTURE_2D, texName);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex3f(­2.0, ­1.0, 0.0);
glTexCoord2f(0.0, 8.0); glVertex3f(­2.0, 1.0, 0.0);
glTexCoord2f(8.0, 8.0); glVertex3f(2000.0, 1.0, ­6000.0);
glTexCoord2f(8.0, 0.0); glVertex3f(2000.0, ­1.0, ­6000.0);
glEnd();
Texturas VIII
OpenGL Programacion
●
Filtrado de Texturas
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GL_TEXTURE_MAG_FILTER
GL_NEAREST
GL_LINEAR
GL_TEXTURE_MIN_FILTER
GL_NEAREST
GL_LINEAR
GL_NEAREST_MIPMAP_NEAREST
GL_NEAREST_MIPMAP_LINEAR
GL_LINEAR_MIPMAP_NEAREST
GL_LINEAR_MIPMAP_LINEAR
Otras Funcionalidades
OpenGL Programacion
●
Graficos 2D
–
●
Pixels, Bitmaps y Fonts. BitBliting
Tessellators y Quadrics (GLUT)
–
OpenGL no puede renderizar poligonos concavos rellenos
–
Tessellation : conversion a poligonos convexos
Otras Funcionalidades
OpenGL Programacion
●
Framebuffer
–
–
Color Buffer:
●
Front, Back, Front­left, Front­right, Back­left, Back­right,..
●
Right/Left depende de la implementacion OpenGL
●
Debe soportar GL_STEREO o GL_DOUBLEBUFFER
Depth Buffer
●
–
Ocultacion de Caras
Stencil Buffer
●
Enmascarado, contornos de objetos,...
Otras Funcionalidades
OpenGL Programacion
●
Framebuffer
–
Accumulation Buffer
●
Motion Blur, Depth of Field, etc...
●
En general es muy lento
Otras Funcionalidades
OpenGL Programacion
●
Evaluadores y NURBS
–
Evaluadores OpenGL para dibujar curvas 2D y 3D
–
GLUT soporte para generar superficies NURBS (Non­Uniform Rational B­Spline)
Otras Funcionalidades
OpenGL Programacion
●
Selección y Feedback
–
Modo selección: Permite seleccionar objetos en la escena a partir de coordenadas 2D (selección con raton)
●
●
●
–
Es necesario redibujar toda la escena. En modo selección no se generan pixels
Es necesario asignar “nombre” a los objetos seleccionables
Una vez definida el area de interes obtenemos una lista
de objetos en ella... Modo Feedback: Similar a selección pero devuelve las primitivas ejecutadas en el proceso de render
Otras Funcionalidades
OpenGL Programacion
●
Antialias glEnable (GL_POINT_SMOOTH); glEnable (GL_LINE_SMOOTH);
glEnable (GL_POLYGON_SMOOTH);
glHint (GL_LINE_SMOOTH, DONT_CARE);
glHint (GL_POINT_SMOOTH, GL_NICEST);
glHint (GL_POLYGON_SMOOTH, GL_FASTEST);
●
Activacion del blending con RGBA
glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc (GL_SRC_ALPHA, GL_ONE); Niebla
OpenGL Programacion
●
Efecto Niebla glEnable(GL_FOG); {
GLfloat fogColor[4] = {0.5, 0.5, 0.5, 1.0};
fogMode = GL_EXP;
glFogi (GL_FOG_MODE, fogMode);
glFogfv (GL_FOG_COLOR, fogColor);
glFogf (GL_FOG_DENSITY, 0.35);
glHint (GL_FOG_HINT, GL_DONT_CARE);
glFogf (GL_FOG_START, 1.0);
glFogf (GL_FOG_END, 5.0);
}
glClearColor(0.5, 0.5, 0.5, 1.0); /* fog color */
Sistema Graficos
TMM: Tecnoloxia Multimedia 2006

Documentos relacionados