dar varias propiedades a los primitivos de opengl curso: graficación prof. gueorgi khatchatourov

28
Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Upload: benito-barbero-avila

Post on 24-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Dar varias propiedades a los Primitivos de OpenGL

Curso: Graficación

Prof. Gueorgi Khatchatourov

Page 2: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Contenido

• Cómo ver un polígono?• Con qué color ver un objeto?• Como llenar Polígonos, o re-visitando

“Stippling” (ver “Other Primitives” de Chapter III “Drawing in Space” de “OpenGL SuperBible”)

• Cómo tratar los polígonos no convexos• Cómo tratar los polígonos no planos• Usar “Stencil Buffer” (plantilla para pintar)• Usar “Scissors” (tijeras)

Page 3: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar al indice Cómo ver un polígono?(I de II)

• Ver lo interior de un polígono? Ver ambos lados de un polígono? Ver un polígono desde ambos lados? Ver los bordes de un polígono ?

• -----------------------------------------------------------------------------------------------------------------------

• Polygons as Points, Outlines, or Solids• A polygon has two sides - front and back - and might be rendered differently depending on which

side is facing the viewer. By default, both front and back faces are drawn in the same way. To change this, or to draw only outlines or vertices, use glPolygonMode().

• void glPolygonMode(GLenum face, GLenum mode);

_ Controls the drawing mode for a polygon's front and back faces. The parameter face can be GL_FRONT_AND_BACK, GL_FRONT, or GL_BACK; mode can be GL_POINT, GL_LINE, or GL_FILL to indicate whether the polygon should be drawn as points, outlined, or filled.

• By default, both the front and back faces are drawn filled.

• For example, you can have the front faces filled and the back faces outlined with two calls to this routine:

glPolygonMode(GL_FRONT, GL_FILL);glPolygonMode(GL_BACK, GL_LINE);

Page 4: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar al indice Cómo ver un polígono?(II de II):

Ver ambos lados de un polígono? Los controles para cambiar manera de ver diferentes lados de un

polígono son:

– Prender/apagar eliminación de las superficies ocultas () glCullFace

void glCullFace(GLenum mode);Indica cuales polígonos deben ser eliminados (culled) antes que se convierten en

las coordenadas de pantalla. El mode es uno de GL_FRONT, GL_BACK, o GL_FRONT_AND_BACK para indicar el lado anverso, reverso o todos los polígonos.

To take effect, culling must be enabled using glEnable() with GL_CULL_FACE; it can be disabled with glDisable() and the same argument.

– Cambia el sentido de los lados frontales y traseras glFrontFace(GL_CW);

Page 5: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar al índice Con qué color ver un objeto?

Con que color ver lo interior de un objeto? Cómo el color interior de un polígono depende de los vértices? Cómo lo depende de propiedades de luz, de material?

-----------------------------------------------------------------------------

• Mecanísmos de formación de color de un pixel

Page 6: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al índice Cómo tratar los polígonos no convexos (I de II)

• Figure 2-12 : Subdividing a Nonconvex Polygon

you can manually control the setting of the edge flag with the commandglEdgeFlag*(). It is used between glBegin() and glEnd() pairs, and it affects all the vertices specified after it until the next glEdgeFlag() call is made. It applies only to vertices specified for polygons, triangles, and quads, not to those specified for strips of triangles or quads.

void glEdgeFlag(GLboolean flag);void glEdgeFlagv(const GLboolean *flag);Indicates whether a vertex should be considered as initializing a boundary edge of a polygon. If flag is GL_TRUE, the edge flag is set to TRUE (the default), and any vertices created are considered to precede boundary edges until this function is called again with flag being GL_FALSE.

Page 7: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al índice Cómo tratar los polígonos no convexos (II de II)

Example 2-7 draws the outline shown in Figure 2-13. Figure 2-13 : Outlined Polygon Drawn Using Edge Flags

Example 2-7 : Marking Polygon Boundary Edges

glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);glBegin(GL_POLYGON);

glEdgeFlag(GL_TRUE);glVertex3fv(V0);glEdgeFlag(GL_FALSE);glVertex3fv(V1);glEdgeFlag(GL_TRUE);glVertex3fv(V2);

glEnd();

Page 8: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Cómo tratar los polígonos no planos

Page 9: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar al índice Usar “Stencil Buffer” (plantilla para pintar)

Frequently, we want to mask out an irregularly shaped area using a stencil pattern. In the real world, a stencil is a flat piece of cardboard or other material that has a pattern cut out of it. Painters use the stencil to apply paint to a surface using the pattern in the stencil. Figure shows how this process works.

The stencil test takes place only if there is a stencil buffer. (If there is no stencil buffer, the stencil test always passes.) Stenciling applies a test that compares a reference value with the value stored at a pixel in the stencil buffer. Depending on the result of the test, the value in the stencil buffer is modified.

El stencil test modifica contenido

del pixel en stencil buffer basandose

en el resultado de una comparición del

valor de referencia con el valor en el stencil buffer

Page 10: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar al índice Usar “Stencil Buffer” (II) ir al inicio del stencil buffer

• void init (void)

{ …. glClearStencil(0x0);/*specifica el valor del

vacio para el

"stencil buffer"*/

glEnable(GL_STENCIL_TEST);

}

Page 11: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Ir a lamina anterior Usar “Stencil Buffer” (III):lógica del uso ir al inicio del stencil buffer

• glStencilFunc ( // establece la función y el valor de referencia para “stencil test”

GLenum func, // especifica tipo de comparición para “stencil test”

GLint ref, // valor de referencia;

GLuint mask // máscara. );

Por ejemplo, si

func=GL_EQUAL Entonces, el pixel pasa satisfactoriamente la prueba (stencil test)

siempre y cuando se cumple(ref&mask)=(stencil&mask)

}

Page 12: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar al índice Usar “Stencil Buffer” (IV) ir al inicio del stencil buffer

• void display(void){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

/* draw blue sphere where the stencil is 1 */ glStencilFunc (GL_EQUAL, 0x1, 0x1 ); //Ver un ejemplo de lógica de uso de los parametros

glStencilOp (GL_KEEP, GL_KEEP, GL_KEEP); //define la acción del stencil test glCallList (BLUEMAT); glutSolidSphere (0.5, 15, 15);

/* draw the tori where the stencil is not 1 */ glStencilFunc (GL_NOTEQUAL, 0x1, 0x1); glPushMatrix(); glRotatef (45.0, 0.0, 0.0, 1.0); glRotatef (45.0, 0.0, 1.0, 0.0); glCallList (YELLOWMAT); glutSolidTorus (0.275, 0.85, 15, 15); glPushMatrix(); glRotatef (90.0, 1.0, 0.0, 0.0); glutSolidTorus (0.275, 0.85, 15, 15); glPopMatrix(); glPopMatrix();}

Page 13: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar al índice Usar “Stencil Buffer” (V) ir al inicio del stencil buffer

void reshape(int w, int h){….

glMatrixMode(GL_MODELVIEW); glLoadIdentity();

glClear(GL_STENCIL_BUFFER_BIT); glStencilFunc (GL_ALWAYS, 0x1, 0x1); glStencilOp (GL_REPLACE, GL_REPLACE, GL_REPLACE); glBegin(GL_QUADS); glVertex2f (-1.0, 0.0); glVertex2f (0.0, 1.0); glVertex2f (1.0, 0.0); glVertex2f (0.0, -1.0); glEnd();

glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, (GLfloat) w/(GLfloat) h, 3.0, 7.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -5.0);

}

Page 14: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al indice de la presentacion Usar “Scissors” (tijeras) (I de III)

• One way to improve rendering performance is to update only the portion of the screen that has changed. You may also need to restrict OpenGL rendering to a smaller rectangular region inside the window. OpenGL allows you to specify a scissor rectangle within your window where rendering can take place. By default, the scissor rectangle is the size of the window, and no scissor test takes place. You turn on the scissor test with:

•glEnable(GL_SCISSOR_TEST);

• You can turn off the scissor test again with the corresponding glDisable function call.

Page 15: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al indice de la presentacion Usar “Scissors” (tijeras) (II de III)

• Listing 3.13. Using the Scissor Box to Render a Series of Rectangles

void RenderScene(void) { // Clear blue window

glClearColor(0.0f, 0.0f, 1.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT);

// Now set scissor to smaller red sub region glClearColor(1.0f, 0.0f, 0.0f, 0.0f); glScissor(100, 100, 600, 400); glEnable(GL_SCISSOR_TEST); glClear(GL_COLOR_BUFFER_BIT);

// Finally, an even smaller green rectangle glClearColor(0.0f, 1.0f, 0.0f, 0.0f); glScissor(200, 200, 400, 200); glClear(GL_COLOR_BUFFER_BIT);

// Turn scissor back off for next render glDisable(GL_SCISSOR_TEST); glutSwapBuffers();

}

Page 16: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al indice de la presentacion Usar “Scissors” (tijeras): salida del programa (III de

III)

Page 17: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar a Cómo ver un polígono Orientación de polígonos (I de II)

• OpenGL, by default, considers polygons that have counterclockwise winding to be front facing. This means that the triangle on the left in Figure 3.15 shows the front of the triangle, and the one on the right shows the back side of the triangle.

Page 18: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar a “Cómo ver un polígono” Orientación de polígonos (II de II) regresar a I de II

• you will often want to give the front and back of a polygon different physical characteristics. You can hide the back of a polygon altogether or give it a different color and reflective property (see SuperBibliaOPenGL Chapter 5, "Color, Materials, and Lighting: The Basics"). It's important to keep the winding of all polygons in a scene consistent, using front-facing polygons to draw the outside surface of any solid objects.

• If you need to reverse the default behavior of OpenGL, you can do so by calling the following function: glFrontFace(GL_CW);

• The GL_CW parameter tells OpenGL that clockwise-wound polygons are to be considered front facing. To change back to counterclockwise winding for the front face, use GL_CCW.

Page 19: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al indice de la presentacion Mecanísmos de formación de color de un pixel ir al Con

que color…

• Limpiar el buffer de color y dar un color para todos los píxeles desocupados

• Lógica de coloración de OpenGL Color solido (GL_FLAT) o interpolado (GL_SMOOTH)

• Los factores geométricos y físicos que influyen a la percepción de luz y generación del color final de un píxel

Page 20: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al indice de la presentacion Mecanísmos de formación de color

de un pixel: Limpiar el buffer de color y dar un

color para los pixeles desocupados ir al indice de

mecanísmos de coloracion

// limpia el buffer de color

• glClear(GL_COLOR_BUFFER_BIT);

// dar color a los pixeles desocupados• glClearColor (…);

Page 21: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al indice de la presentacion Mecanísmos de formación de color

de un pixel: Lógica de coloración de OpenGLir al indice de mecanísmos de coloracion

Podemos considerar la coloración de un objeto como dar una pintura al objeto sin tomar en cuenta cómo lo se verá en una posición especifica respecto a una camara, o de que material se ha hecho o cuanto y cuales luces se tienen en el entorno.

En este sentido hay dos opciones (dos modelos de “SHADING”) de pintura: • con un color sólido (GL_FLAT) • con lo interpolado (GL_SMOOTH)-------------------------------------------------------------------------------------------------------In general, an OpenGL programmer first sets the color or coloring scheme and then draws the objects. Until the color

or coloring scheme is changed, all objects are drawn in that color or using that coloring scheme. This method helps OpenGL achieve higher drawing performance than would result if it didn't keep track of the current color.

For example, the pseudocode

set_current_color(red);draw_object(A);draw_object(B);set_current_color(green);set_current_color(blue);draw_object(C);

draws objects A and B in red, and object C in blue. The command on the fourth line that sets the current color to green is wasted.

Page 22: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al indice Lógica de coloración de OpenGL (II de ) : Color solido o interpolado:

lamina II.1: Color solido (GL_FLAT) ir al

indice de mecanísmos de coloracion

Por omisión se supone que el modelo de coloración es como después del comando

glShadeModel (GL_FLAT);

glColor3f (1.0, 0.0, 0.0); /* the current RGB color is red: */

/* full red, no green, no blue. */ glBegin (GL_POINTS); glVertex3fv (point_array); glEnd ();

Page 23: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al indice Lógica de coloración de OpenGL (II de ) : Color solido o interpolado:

lamina II.2: Color interpolado (GL_SMOOTH); ir al indice de mecanísmos de coloracion

• #include <GL/glut.h>void init(void){ glClearColor (0.0, 0.0, 0.0, 0.0);

glShadeModel (GL_SMOOTH);}void display(void){ glClear (GL_COLOR_BUFFER_BIT);

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();glFlush ();

}

Page 24: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al indice Lógica de coloración de OpenGL (II de ) : Color solido o interpolado:

lamina II.2': Color interpolado (GL_SMOOTH); ir al indice de mecanísmos de coloracion

void reshape (int w, int h){ glViewport (0, 0, (GLsizei) w, (GLsizei) h);

glMatrixMode (GL_PROJECTION);glLoadIdentity ();if (w <= h)gluOrtho2D (0.0, 30.0, 0.0, 30.0*(GLfloat) h/(GLfloat) w);elsegluOrtho2D (0.0, 30.0*(GLfloat) w/(GLfloat) h, 0.0, 30.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;

}

Page 25: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

ir al índice Los factores geométricosgeométricos y físicos que influyen a la percepción de luz y la generación del

color final de un píxel ir al índice de mecanísmos de coloracion

• Los factores geometricos incluyen posicion y orientacion espacial del objeto y de la cámara, posición(es) del(as) fuentes de luz. – Para mejorar rendiminto, tomando en cuenta esos factores, el

paradigma de OpenGL supone procesamiento de color final no para los puntos individuales, sino para polígonos enteros. En su vez, para evitar varios efectos de mal interpretación, cómo los polígonos se usan los triángulostriángulos a los cuales previamente se calculan y se adjuntan vectores normalesvectores normales

• Los factores físicos incluyen color del objeto, propiedades de reflexión del material, propiedades (de transparencia y de iluminación) del medio ambiente

Page 26: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regla I de Construcción de Polígonos regresar a “factores

geométricosgeométricos y físicos que influyen…” When you are using many polygons to construct a complex surface, you need

to remember two important rules.• The first rule is that all polygons must be planar. That is, all the vertices of

the polygon must lie in a single plane, as illustrated in Figure 3.31. The polygon cannot twist or bend in space.

• Figure 3.31. Planar versus nonplanar polygons.

Page 27: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regla II de Construcción de Polígonos regresar a “factores geométricosgeométricos y físicos que influyen…”

• The second rule of polygon construction is that the polygon's edges must not intersect, and the polygon must be convex. If any given line enters and leaves the polygon more than once, the polygon is not convex. Figure 3.32 gives examples of good and bad polygons.

• Figure 3.32. Some valid and invalid primitive polygons.

Page 28: Dar varias propiedades a los Primitivos de OpenGL Curso: Graficación Prof. Gueorgi Khatchatourov

Regresar al índice Usar “Stencil Buffer” (IV’): la acción del stencil test

ir atras

• void glStencilOp(GLenum fail, GLenum zfail, GLenum zpass

);• The value of any of fail, zfail, and zpass can be GL_KEEP,

GL_ZERO, GL_REPLACE, GL_INCR, GL_DECR, or GL_INVERT.

• The fail function is applied if the fragment fails the stencil test; if it passes, then zfail is applied if the depth test fails and zpass if the depth test passes, or if no depth test is performed.

• By default, all three stencil operations are GL_KEEP.