opengl - iowa state universityclass.ece.iastate.edu/cpre388/lecture/lecopengl.pdf · opengl •...
TRANSCRIPT
-
OpenGLOpenGL
CPRE388
-
OpenGLOpenGL
Open Graphics LibraryOpenGraphicsLibrary Developedin1992bySiliconGraphicsC ll i f 300 Collectionofover300APIs
HidesthedetailsofGPUs(hardwaregraphicsaccelerators).
-
Graphics PipelineGraphicsPipeline
-
OpenGLp basicoperationistoacceptprimitivessuchaspoints lines and polygons and convert thempoints,linesandpolygons,andconvertthemintopixels.
h d b h l k ThisisdonebyagraphicspipelineknownastheOpenGLStateMachine.
-
Some TermsSomeTerms
Pixel picture element is a single point in aPixel pictureelement isasinglepointinarasterimage.
pixel is the smallest addressable screen pixelisthesmallestaddressablescreenelement
l i i ll d b h f coloristypicallyrepresentedbythreeorfourcomponentintensitiessuchasred,greenandbl ll d bl kblue,orcyan,magenta,yellowandblack.
-
RasterizationRasterization
task of taking an image described in a vectortaskoftakinganimagedescribedinavectorgraphicsformat(shapes)andconvertingitintoa raster image (pixels or dots) for output on aarasterimage (pixels ordots)foroutputonavideodisplay orprinter,orforstorageinabitmap file formatbitmapfileformat.
-
OpenGLTransformationSupport Three matrices Threematrices
GL_MODELVIEW,GL_PROJECTION,GL_TEXTURE glMatrixMode(mode) specifiestheactivematrix
glLoadIdentity() Settheactivematrixtoidentity
glLoadMatrix{fd}(TYPE *m)glLoadMatrix{fd}(TYPE m) Setthe16valuesofthecurrentmatrixtothosespecifiedbym
m1 m5 m9 m13m2 m6 m10 m14m3 m7 m11 m15
m =
glMultMatrix{fd}(TYPE*m) Multipliesthecurrentactivematrixbym
m4 m8 m12 m16
-
TransformationExample
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();//matrix=I
lM ltM t i (N) // t i NglMultMatrix(N);//matrix=N
glMultmatrix(M);//matrix=NM
glMultMatrix(L); // matrix = NMLglMultMatrix(L);//matrix=NML
glBegin(GL_POINTS);
glVertex3f(v);//vwillbetransformed:NMLvg f( ); //
glEnd();
-
OpenGLTransformations
glTranslate{fd}(TYPEx,TYPEy,TYPEz) Multiplythecurrentmatrixbythetranslationmatrix
glRotate{fd}(TYPEangle,TYPEx,TYPEy,TYPEz) Multiplythecurrentmatrixbytherotationmatrixthatrotatesanobjectabouttheaxisfrom(0,0,0)to(x,y,z)
glScale{fd}(TYPEx,TYPEy,TYPEz) Multiplythecurrentmatrixbythescalematrix
-
ExamplesExamples
glMatrixMode(GL MODELVIEW);glMatrixMode(GL_MODELVIEW);
glRecti(50,100,200,150);
glTranslatef(200.0, 50.0, 0.0);glTranslatef( 200.0, 50.0,0.0);
glRecti(50,100,200,150);
glLoadIdentity();g y()
glRotatef(90.0,0.0,0.0,1.0);
glRecti(50,100,200,150);
glLoadIdentity();
glscalef(.5,1.0,1.0)
glRecti(50,100,200,150);
-
Viewingin3D World (3D) Screen (2D)World(3D) Screen(2D) OrientingEyecoordinatesysteminWorldcoordinate systemcoordinatesystem ViewOrientationMatrix
Specifyingviewingvolumeandprojectionparametersforn d(d
-
WorldtoEyeCoordinates
Weneedtotransformfromtheworldcoordinatestotheeyecoordinates
Theeyecoordinatesystemisspecifiedby: Viewreferencepoint(VRP)
(VRPx,VRPy,VRPz)
Directionoftheaxes:eyecoordinatesystem U =(ux,uy,uz)
V =(vx,vy,vz)
N ( ) N =(nx,ny,nz)
-
WorldtoEyeCoordinates
Therearetwostepsinthetransformation(in order)(inorder) Translation Rotation Rotation
-
WorldtoEyeCoordinates
TranslateWorldOrigintoVRP
1 0 0 VRP xa 1 0 0 -VRPx0 1 0 -VRPy0 0 1 -VRPz0 0 0 1
xyz1
abc1
=
0 0 0 1 11
-
WorldtoEyeCoordinates
RotateWorldX,Y,ZtotheEyecoordinatesystemu,v,n,alsoknownastheViewR f C diReferenceCoordinatesystem
ax u u u 0 abc1
xyz1
=
ux uy uz 0vx vy vz 0nx ny nz 00 0 0 1 11 0 0 0 1
-
DrawingDrawing
OpenGL primitives glVertex, glLine,OpenGLprimitives glVertex,glLine,glTriangle
glVertex2f(100.0f, 150.0f); defines a point at xglVertex2f(100.0f,150.0f);definesapointatx=100,y=150,z=0;thisfunctiontakesonly2parameters,zisalways0.
glVertex3f(100.0f,150.0f,25.0f);definesapointatx=100,y=150,z=25.0f;thisfunctiontakes3parameters,definingafully3Dpointinyourworld
-
glVertex alonewon'tdrawanythingonthescreenlB i (i t d ) d lE d( id ) glBegin(intmode);andglEnd(void );
TheparametermodeofthefunctionglBegin canbe one of the following:beoneofthefollowing:GL_POINTSGL LINESGL_LINESGL_LINE_STRIPGL_LINE_LOOPGL_TRIANGLESGL_TRIANGLE_STRIPGL TRIANGLE FANGL_TRIANGLE_FANGL_QUADSGL QUAD STRIPG _QU _SGL_POLYGON
-
//thiscodewilldrawapointlocatedat[100,100,25]
glBegin(GL_POINTS);
glVertex3f(100.0f,100.0f,25.0f);
glEnd( );glEnd();
-
// Thi d ill d li t t ti d//ThiscodewilldrawalineatstartingandendingcoordinatesspecifiedbyglVertex3f
glBegin(GL_LINES);glVertex3f(100.0f,100.0f,0.0f);//originoftheline
glVertex3f(200.0f,140.0f,5.0f);//endingpointoftheline
glEnd();
-
//thefollowingcodedrawsatriangle
l i ( )glBegin(GL_TRIANGLES);glVertex3f(100.0f,100.0f,0.0f);
glVertex3f(150.0f,100.0f,0.0f);
glVertex3f(125.0f,50.0f,0.0f);
glEnd();g ( );
-
//thiscodewilldrawtwolines"atatime"tosave//thetimeittakestocallglBegin andglEnd.glBegin(GL_LINES);glVertex3f(100.0f,100.0f,0.0f);//originoftheFIRSTlineglVertex3f(200.0f,140.0f,5.0f);//endingpointofh ltheFIRSTlineglVertex3f(120.0f,170.0f,10.0f);//originoftheSECOND liSECONDlineglVertex3f(240.0f,120.0f,5.0f);//endingpointofthe SECOND linetheSECONDline
glEnd();
-
OpenGL Viewer PerspectiveOpenGLViewerPerspective
-
ViewerViewer
when OpenGL is initialized and the projectionwhenOpenGLisinitializedandtheprojectionissetupweareinitiallylookingdownthenegative Z spacenegativeZspace
Thepointx=0,y=0,z=0isintheexactcenterof the screenofthescreen
-
voidRenderFrame (void){glClear(GL COLOR BUFFER BIT|GL DEPTglClear(GL_COLOR_BUFFER_BIT|GL_DEPT
H_BUFFER_BIT);glBegin(GL TRIANGLES);glBegin(GL_TRIANGLES);glVertex3f(1.0f,0.5f,4.0f);//lowerleftvertexvertexglVertex3f(1.0f,0.5f,4.0f);//lowerrightvertexvertexglVertex3f(0.0f,0.5f,4.0f);//uppervertexlE d()glEnd();}
-
glBegin(GL_TRIANGLES);
glVertex3f(1.0f,0.5f,4.0f);//lowerleftvertex
glVertex3f(1.0f,0.5f,4.0f);//lowerrightvertexvertex
glVertex3f(0.0f,0.5f,4.0f);//uppervertex
lV t 3f( 0 5f 1 5f 4 0f)glVertex3f(0.5f,1.5f,4.0f);
glVertex3f(0.5f,1.5f,4.0f);
glVertex3f(0.0f,1.0f,4.0f);
glEnd();glEnd();
-
StripsStrips
a call to glVertex takes some time to processacalltoglVertex takessometimetoprocess minimizethenumberofcallstoglVertex whiledrawing the same amount of primitives be it adrawingthesameamountofprimitivesbeitalineoratriangleoraquad
GL LINE STRIP GL_LINE_STRIPGL_TRIANGLE_STRIPGL QUAD STRIPGL_QUAD_STRIP
-
Triangle StripTriangleStrip
-
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(1.0f,0.5f,4.0f);//A
glVertex3f( 1.0f, 0.5f, 4.0f); // BglVertex3f(1.0f, 0.5f, 4.0f);//B
glVertex3f(0.0f,0.5f,4.0f);//C
lV t 3f(1 5f 0 0f 4 0f) // DglVertex3f(1.5f,0.0f,4.0f);//D
glVertex3f(2.0f,1.5f,4.0f);//E
glEnd();
-
Triangle FansTriangleFans
A triangle fan has one origin indicated by theAtrianglefanhasoneoriginindicatedbythefirstvertex,andaninitialtriangle,indicatedbythe first 3 vertices including the originthefirst3verticesincludingtheorigin.
Asyouaddthe4thand5thverticestoyoufan you continue it just like you did with afan,youcontinueitjustlikeyoudidwithatrianglestrip.
-
Triangle FanTriangleFan
-
glBegin(GL_TRIANGLE_FAN);
glVertex3f(1.0f,0.5f,4.0f);//A
glVertex3f(1.0f,0.5f,4.0f);//Bg ( , , );
glVertex3f(0.0f,0.5f,4.0f);//C
glVertex3f( 1 5f 0 0f 4 0f); // DglVertex3f(1.5f,0.0f,4.0f);//D
glVertex3f(1.8f,1.0f,4.0f);//E
glVertex3f(0.2f,1.5f,4.0f);//F
glVertex3f(1.0f,0.5f,4.0f);//Gg
glEnd();
-
OpenGLESOpenGL ES
OpenGL ES 1 1 implements the standardOpenGLES1.1implementsthestandardgraphicspipelinewithawelldefinedfixedfunction pipelinefunctionpipeline
OpenGLES2.0removesallfunctionsthatacton the fixed function pipeline replacing itonthefixedfunctionpipeline,replacingitwithageneralpurposeshaderbasedpipeline
A l ff h d h b h AppleoffershardwarethatsupportsbothOpenGLES1.1andOpenGLES2.0.
-
Core Animation is fundamental to the iOSCoreAnimationisfundamentaltotheiOSgraphicssubsystem,includingOpenGLES
Every UIView object in your application is EveryUIView objectinyourapplicationisbackedbyaCoreAnimationlayer
O GL ES i l d d yourOpenGLEScontentisalsorenderedtoaCoreAnimationlayersothatitcanbe
i d i h hcompositedwithothercontent
-
OpenGLESObjectsh b l d b h Atextureisanimagethatcanbesampledbythe
graphicspipeline.Thisistypicallyusedtomapacolor image onto your geometry but can also becolorimageontoyourgeometrybutcanalsobeusedtomapotherdataontothegeometry
AbufferisasetofmemoryownedbyOpenGLESth t li ti d it d t i tthatyourapplicationcanreadorwritedatainto.Themostcommonuseforabufferistoholdvertexdatathatyourapplicationwantstosubmity pptothegraphicshardware.
Shaders arealsoobjects.AnOpenGLES2.0application creates a shader compiles and linksapplicationcreatesashader,compilesandlinkscodeintoit,andthenassignsittoprocessvertexandfragmentdata.
-
A renderbuffer is a simple 2D graphics image Arenderbuffer isasimple2Dgraphicsimageinaspecifiedformat.Thisformatmaybedefinedascolordata,butitcouldalsobedepthorstencilinformation.Renderbuffersarenotusuallyusedalone,butareinsteadll d d d f f b ffcollectedandusedaspartofaframebuffer.
Framebuffers aretheultimatedestinationofh hi i li A f b ff bj ithegraphicspipeline.Aframebuffer objectisreallyjustacontainerthatattachestexturesand renderbuffers to itself to create aandrenderbuffers toitselftocreateacompletedestinationforrendering.
-
reducethecomplexityofyourgeometrybyusingsomeofthefollowingtechniques
Provide multiple versions of your geometry at Providemultipleversionsofyourgeometryatdifferentlevelsofdetail,andchooseanappropriatemodelbasedonthedistanceofpp ptheobjectfromthecamera.
-
UseInterleavedVertexData Interleaveddataprovidesbettermemorylocalitythanusingaseparatearrayforeachattribute.
UseTriangleStrips Usingtrianglestripssignificantlyreducesthenumberofvertexcalculations that OpenGL ES must perform oncalculationsthatOpenGLESmustperformonyourgeometry.Yourperformanceisbestifanobject (or even a group of objects) can beobject(orevenagroupofobjects)canbesubmittedinasingleunindexed trianglestripusingglDrawArrays.Thismayinvolveaddingdegeneratetrianglestomergemultiplesmallertrianglestripsintoasinglelargestrip.
-
UseVertexBuffers Bydefault,anapplicationmaintainsitsownvertexdataandsubmitsittothehardwaretoberendered.Whenyousubmitgeometry,itiscopiedtothehardwaretoberendered
-
typedef struct _vertexStruct{{
GLfloat position[2];GLubyte color[4];
} vertexStruct;}vertexStruct;voidDrawGeometry(){const vertexStruct vertices[] = { };constvertexStruct vertices[]={...};constGLubyte indices[]={...};
glEnableClientState(GL_VERTEX_ARRAY);lV t P i t (2 GL FLOAT i f( t St t)glVertexPointer(2,GL_FLOAT,sizeof(vertexStruct),&vertices[0].position);glEnableClientState(GL_COLOR_ARRAY);glColorPointer(4 GL UNSIGNED BYTE sizeof(vertexStruct)glColorPointer(4,GL_UNSIGNED_BYTE,sizeof(vertexStruct),
&vertices[0].color);glDrawElements(GL_TRIANGLE_STRIP,sizeof(indices)/sizeof(GLubyte),GL UNSIGNED BYTE indices);GL_UNSIGNED_BYTE,indices);
}
-
E h ti lD El t i ll d th d t EachtimeglDrawElements iscalled,thedataisretransmittedtothegraphicshardwaretob d dberendered
Ifthedatadidnotchange,thoseadditionalcopiesareunnecessary
-
CreatingVertexBufferstypedef struct vertexStructtypedef struct _vertexStruct{GLfloat position[2];p [ ];GLubyte color[4];
}vertexStruct;constvertexStruct vertices[]={...};constGLubyte indices[]={...};GLuint vertexBuffer;GLuint vertexBuffer;GLuint indexBuffer;voidCreateVertexBuffers(){glGenBuffers(1,&vertexBuffer);
-
glGenBuffers(1,&indexBuffer);glBindBuffer(GL_ARRAY_BUFFER,vertexBuffer);glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_STATIC_DRAW);glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,indexBuffer);glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_STATIC_DRAW);
}
-
DrawingusingVertexBuffersvoid DrawUsingVertexBuffers()voidDrawUsingVertexBuffers(){
glBindBuffer(GL_ARRAY_BUFFER,vertexBuffer);glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,indexBuffer);glEnableClientState(GL_VERTEX_ARRAY);glVertexPointer(2, GL FLOAT, sizeof(vertexStruct),glVertexPointer(2,GL_FLOAT,sizeof(vertexStruct),(void*)offsetof(vertexStruct,position));glEnableClientState(GL_COLOR_ARRAY);lC l P i t (4 GL UNSIGNED BYTE i f( t St t)glColorPointer(4,GL_UNSIGNED_BYTE,sizeof(vertexStruct),(void*)offsetof(vertexStruct,color));
glDrawElements(GL_TRIANGLE_STRIP,g ( _ _sizeof(indices)/sizeof(GLubyte),GL_UNSIGNED_BYTE,(void*)0);
}}