Post on 14-Dec-2015
transcript
Pemrograman Pemrograman OpenGL DasarOpenGL Dasar
Materi 03Materi 03
Grafik Komputer 1Grafik Komputer 1
The Programmer’s The Programmer’s InterfaceInterface
Programmer sees the graphics Programmer sees the graphics system through a software interface: system through a software interface: the Application Programmer the Application Programmer Interface (API)Interface (API)
API ContentsAPI Contents
Functions that specify what we need Functions that specify what we need to form an imageto form an imageObjectsObjectsViewerViewerLight Source(s)Light Source(s)MaterialsMaterials
Other informationOther informationInput from devices such as mouse and Input from devices such as mouse and keyboardkeyboard
Capabilities of systemCapabilities of system
Object SpecificationObject Specification
Most APIs support a limited set of Most APIs support a limited set of primitives includingprimitives includingPoints (0D object)Points (0D object)Line segments (1D objects)Line segments (1D objects)Polygons (2D objects)Polygons (2D objects)Some curves and surfacesSome curves and surfaces
QuadricsQuadricsParametric polynomialsParametric polynomials
All areAll are defined through locations in defined through locations in space or space or verticesvertices
OpenGLOpenGL
The success of GL lead to OpenGL The success of GL lead to OpenGL (1992), a platform-independent API (1992), a platform-independent API that was that was Easy to useEasy to useClose enough to the hardware to get Close enough to the hardware to get excellent performanceexcellent performance
Focus on renderingFocus on renderingOmitted windowing and input to avoid Omitted windowing and input to avoid window system dependencies window system dependencies
OpenGL LibrariesOpenGL Libraries
OpenGL core libraryOpenGL core libraryOpenGL32 on WindowsOpenGL32 on WindowsGL on most unix/linux systems (libGL.a)GL on most unix/linux systems (libGL.a)
OpenGL Utility Library (GLU)OpenGL Utility Library (GLU)Provides functionality in OpenGL core but Provides functionality in OpenGL core but avoids having to rewrite codeavoids having to rewrite code
Links with window systemLinks with window systemGLX for X window systemsGLX for X window systemsWGL for WindowsWGL for WindowsAGL for MacintoshAGL for Macintosh
GLUTGLUTOpenGL Utility Toolkit (GLUT)OpenGL Utility Toolkit (GLUT)
Provides functionality common to all window Provides functionality common to all window systemssystems
Open a windowOpen a window Get input from mouse and keyboardGet input from mouse and keyboard MenusMenus Event-drivenEvent-driven
Code is portable but GLUT lacks the Code is portable but GLUT lacks the functionality of a good toolkit for a specific functionality of a good toolkit for a specific platformplatform
No slide barsNo slide bars
Software OrganizationSoftware Organization
GLUT
GLU
GL
GLX, AGLor WGL
X, Win32, Mac O/S
software and/or hardware
application program
OpenGL Motifwidget or similar
OpenGL function formatOpenGL function format
glVertex3f(x,y,z)
belongs to GL library
function name
x,y,z are floats
glVertex3fv(p)
p is a pointer to an array
dimensions
ExampleExample
glBegin(GL_POLYGON)glBegin(GL_POLYGON)glVertex3f(0.0, 0.0, 0.0);glVertex3f(0.0, 0.0, 0.0);glVertex3f(0.0, 1.0, 0.0);glVertex3f(0.0, 1.0, 0.0);glVertex3f(0.0, 0.0, 1.0);glVertex3f(0.0, 0.0, 1.0);glEnd( );glEnd( );
type of object
location of vertex
end of object definition
OpenGL PrimitivesOpenGL Primitives
GL_QUAD_STRIPGL_QUAD_STRIP
GL_POLYGONGL_POLYGON
GL_TRIANGLE_STRIPGL_TRIANGLE_STRIP GL_TRIANGLE_FANGL_TRIANGLE_FAN
GL_POINTSGL_POINTS
GL_LINESGL_LINES
GL_LINE_LOOPGL_LINE_LOOP
GL_LINE_STRIPGL_LINE_STRIP
GL_TRIANGLESGL_TRIANGLES
A Simple ProgramA Simple Program
Generate a square on a solid Generate a square on a solid backgroundbackground
simple.csimple.c#include <GL/glut.h>void mydisplay(){ glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5);
glEnd();glFlush();
}int main(int argc, char** argv){
glutCreateWindow("simple"); glutDisplayFunc(mydisplay); glutMainLoop();
}
OpenGL #definesOpenGL #defines
Most constants are defined in the Most constants are defined in the include files include files gl.hgl.h, , glu.hglu.h and and glut.hglut.hNote Note #include <GL/glut.h>#include <GL/glut.h> should should automatically include the othersautomatically include the others
ExamplesExamplesglBegin(GL_POLYGON)glBegin(GL_POLYGON)glClear(GL_COLOR_BUFFER_BIT)glClear(GL_COLOR_BUFFER_BIT)
include files also define OpenGL data include files also define OpenGL data types: types: GLfloatGLfloat, , GLdoubleGLdouble,….,….
Event LoopEvent Loop
Note that the program defines a Note that the program defines a display display callbackcallback function named function named mydisplaymydisplayEvery glut program must have a display Every glut program must have a display callbackcallback
The display callback is executed whenever The display callback is executed whenever OpenGL decides the display must be OpenGL decides the display must be refreshed, for example when the window is refreshed, for example when the window is openedopened
The The mainmain function ends with the program function ends with the program entering an event loopentering an event loop
DefaultsDefaults
simple.csimple.c is too simple is too simpleMakes heavy use of state variable Makes heavy use of state variable default values fordefault values forViewingViewingColorsColorsWindow parametersWindow parameters
Next version will make the defaults Next version will make the defaults more explicitmore explicit
Program StructureProgram Structure Most OpenGL programs have a similar structure Most OpenGL programs have a similar structure
that consists of the following functionsthat consists of the following functions main()main(): :
defines the callback functions defines the callback functions opens one or more windows with the required propertiesopens one or more windows with the required properties enters event loop (last executable statement)enters event loop (last executable statement)
init()init(): sets the state variables: sets the state variables ViewingViewing AttributesAttributes
callbackscallbacks Display functionDisplay function Input and window functionsInput and window functions
simple.c revisitedsimple.c revisited
In this version, we shall see the In this version, we shall see the same output but we have defined all same output but we have defined all the relevant state values through the relevant state values through function calls using the default function calls using the default valuesvalues
In particular, we setIn particular, we set ColorsColors Viewing conditionsViewing conditions Window propertiesWindow properties
main.cmain.c
#include <GL/glut.h>#include <GL/glut.h>
int main(int argc, char** argv)int main(int argc, char** argv){{
glutInit(&argc,argv); glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutInitWindowPosition(0,0); glutCreateWindow("simple"); glutCreateWindow("simple"); glutDisplayFunc(mydisplay); glutDisplayFunc(mydisplay);
init(); init();
glutMainLoop();glutMainLoop();
}}
includes gl.h
define window properties
set OpenGL state
enter event loop
display callback
GLUT functionsGLUT functions glutInit glutInit allows application to get command line allows application to get command line
arguments and initializes systemarguments and initializes system gluInitDisplayMode gluInitDisplayMode requests properties for the window requests properties for the window
(the (the rendering contextrendering context)) RGB colorRGB color Single bufferingSingle buffering Properties logically ORed togetherProperties logically ORed together
glutWindowSize glutWindowSize in pixelsin pixels glutWindowPosition glutWindowPosition from top-left corner of displayfrom top-left corner of display glutCreateWindow glutCreateWindow create window with title “simple”create window with title “simple” glutDisplayFunc glutDisplayFunc display callbackdisplay callback glutMainLoop glutMainLoop enter infinite event loopenter infinite event loop
init.cinit.c
void init()void init(){{
glClearColor (0.0, 0.0, 0.0, 1.0);glClearColor (0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, 1.0, 1.0); glColor3f(1.0, 1.0, 1.0);
glMatrixMode (GL_PROJECTION); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glLoadIdentity (); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}}
black clear coloropaque window
fill/draw with white
viewing volume
RGB colorRGB color
Each color component is stored separately Each color component is stored separately in the frame bufferin the frame buffer
Usually 8 bits per component in bufferUsually 8 bits per component in buffer Note in Note in glColor3fglColor3f the color values range the color values range
from 0.0 (none) to 1.0 (all), whereas in from 0.0 (none) to 1.0 (all), whereas in glColor3ubglColor3ub the values range from 0 to the values range from 0 to 255255
Indexed ColorIndexed Color
Colors are indices into tables of RGB valuesColors are indices into tables of RGB values Requires less memoryRequires less memory
indices usually 8 bitsindices usually 8 bits not as important nownot as important now
Memory inexpensiveMemory inexpensive Need more colors for shadingNeed more colors for shading
Color and StateColor and State
The color as set by The color as set by glColorglColor becomes part of becomes part of the state and will be used until changedthe state and will be used until changed Colors and other attributes are not part of Colors and other attributes are not part of
the object but are assigned when the the object but are assigned when the object is renderedobject is rendered
We can create conceptual We can create conceptual vertex colorsvertex colors by by code such ascode such as
glColorglColor glVertexglVertex glColorglColor glVertexglVertex
Smooth ColorSmooth Color
Default is Default is smoothsmooth shading shading OpenGL interpolates vertex colors OpenGL interpolates vertex colors
across visible polygonsacross visible polygons Alternative is Alternative is flat shadingflat shading
Color of first vertex Color of first vertex
determines fill colordetermines fill color glShadeModelglShadeModel
(GL_SMOOTH)(GL_SMOOTH)
or or GL_FLATGL_FLAT
RangkumanRangkuman
API berfungsi sebagai perantara API berfungsi sebagai perantara antara aplikasi dengan hardwareantara aplikasi dengan hardware
Membuat tampilan 2 dimensi Membuat tampilan 2 dimensi sederhana menggunakan OpenGLsederhana menggunakan OpenGL
Penjelasan Fungsi-fungsi dasar Penjelasan Fungsi-fungsi dasar pembentuk program OpenGLpembentuk program OpenGL
Contoh SoalContoh Soal
Buat tampilan sebagai berikut:Buat tampilan sebagai berikut:
JawabanJawaban#include "stdafx.h"#include "stdafx.h"#include <GL/glut.h>#include <GL/glut.h>
void display()void display(){{
glClear(GL_COLOR_BUFFER_BIT);glClear(GL_COLOR_BUFFER_BIT);glBegin(GL_TRIANGLES);glBegin(GL_TRIANGLES);
glClearColor(1.0,1.0,1.0,1.0);glClearColor(1.0,1.0,1.0,1.0);glColor3f(1.0,0.0,0.0);glColor3f(1.0,0.0,0.0);glVertex3f(-2.0,-2.0,0.0);glVertex3f(-2.0,-2.0,0.0);glClearColor(1.0,1.0,1.0,1.0);glClearColor(1.0,1.0,1.0,1.0);glColor3f(0.0,1.0,0.0);glColor3f(0.0,1.0,0.0);glVertex3f(0.0,2.0,0.0);glVertex3f(0.0,2.0,0.0);glClearColor(1.0,1.0,1.0,1.0);glClearColor(1.0,1.0,1.0,1.0);glColor3f(0.0,0.0,1.0);glColor3f(0.0,0.0,1.0);glVertex3f(2.0,-2.0,0.0);glVertex3f(2.0,-2.0,0.0);
glEnd();glEnd();glFlush();glFlush();
}}
void myinit()void myinit(){{
glMatrixMode(GL_PROJECTION);glMatrixMode(GL_PROJECTION);glLoadIdentity();glLoadIdentity();gluOrtho2D(-2.0,2.0,-2.0,2.0);gluOrtho2D(-2.0,2.0,-2.0,2.0);glMatrixMode(GL_MODELVIEW);glMatrixMode(GL_MODELVIEW);glClearColor(1.0,1.0,1.0,1.0);glClearColor(1.0,1.0,1.0,1.0);glColor3f(0.0,0.0,0.0);glColor3f(0.0,0.0,0.0);
}}
int main(int argc, char* argv[])int main(int argc, char* argv[]){{
if (argv[1] != NULL) if (argv[1] != NULL) {{ n=atoi(argv[1]);n=atoi(argv[1]);}}else n=5;else n=5;glutInit(&argc,argv);glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowSize(500,500);glutInitWindowPosition(100,100);glutInitWindowPosition(100,100);glutCreateWindow("Segitiga Warna");glutCreateWindow("Segitiga Warna");glutDisplayFunc(display);glutDisplayFunc(display);myinit();myinit();glutMainLoop();glutMainLoop();
return 0;return 0;}}
Contoh SoalContoh SoalBuatlah tampilan program Buatlah tampilan program Sierpinski GasketSierpinski Gasket
ReferensiReferensi
Edward Angel, “Interactive Edward Angel, “Interactive Computer Graphics Fourth Computer Graphics Fourth Edition”, Pearson, 2006, ch 2, p 46 Edition”, Pearson, 2006, ch 2, p 46 – 84– 84
F. S. Hill, Jr., “Computer Graphics F. S. Hill, Jr., “Computer Graphics Using OpenGL Second Edition”, Using OpenGL Second Edition”, Prentice Hall, 2001, ch 2, p 39 - 63 Prentice Hall, 2001, ch 2, p 39 - 63