Presentation is loading. Please wait.

Presentation is loading. Please wait.

OpenGL 1 Angel: Chapter 2 OpenGL Programming and Reference Guides, Angel, other sources. CSCI 6360.

Similar presentations


Presentation on theme: "OpenGL 1 Angel: Chapter 2 OpenGL Programming and Reference Guides, Angel, other sources. CSCI 6360."— Presentation transcript:

1 OpenGL 1 Angel: Chapter 2 OpenGL Programming and Reference Guides, Angel, other sources. CSCI 6360

2 Introduction Angel’s (and others) “top down” approach … vs. the “old school” approach OpenGL is pretty complicated … –Especially, in that programmer has access to “inner workings” of (graphics) system Rather in contrast to pedagogic, and limited access, environments –Below is single engine aircraft, next, look out for the ejection button …

3 ..

4 Overview The world of computer graphics …which you’ve just seen … Development of the OpenGL API –… and why things are not as easy these days, OGL (free) resources OpenGL Architecture –OpenGL as a state machine and geometry processing machine Functions –Types –Formats Simple viewing –Coordinate systems, orthographic viewing Practical things: –Color, Viewports A first program –Event loop, compiler things, first assignment

5 Early History of Graphics APIs (pre-OpenGL pre-history) IFIPS (1973) formed two committees to come up with a standard graphics API –Graphical Kernel System (GKS) - 2D but contained good workstation model –Core - Both 2D and 3D –GKS adopted as IS0 and later ANSI standard (1980s) GKS not easily extended to 3D (GKS-3D) –Far behind hardware development Programmers Hierarchical Graphics System (PHIGS) –Arose from CAD community –Database model with retained graphics (structures) X Window System –DEC/MIT effort –Client-server architecture with graphics PEX combined the two –Not easy to use (all the defects of each)

6 SGI, GL and OpenGL Silicon Graphics (SGI) revolutionized graphics workstation by implementing the pipeline in hardware (1982) –Had to be able to program it! To access system, application programmers used a library called “GL” –Relatively simple to program 3d interactive applications Success of GL lead to OpenGL (1992), a platform-independent API –Easy to use –Close enough to the hardware to get excellent performance –Focus on rendering –Omitted windowing and input to avoid window system dependencies

7 OpenGL Evolution Controlled by an Architectural Review Board (ARB) –(see opengl.org for all you could want) –Members include Microsoft, Nvidia, HP, 3DLabs, IBM,……. –Relatively stable (present version 4.3) Evolution reflects new hardware capabilities –3D texture mapping and texture objects –Vertex shader programs –Allows for platform specific features through extensions –OpenGL continues to evolve –Reflects, in large part, hardware evolution … see below: “Software migrates to hardware …” –E.g., for cg, from routines in main memory to firmware on graphics controller Now, “hardware (or firmware) migrates to software !” –E.g., cg programmable shaders – now firmware not firm! –I.e., it’s all programmable

8 OpenGL Evolution “Software migrates to hardware …” –Cg, from routines in main memory to firmware on graphics controller Now, “hardware (or firmware) migrates to software !” –Cg programmable shaders – now firmware not firm! –I.e., it’s all programmable

9 Recall, Programmable Pipelines … and OpenGL Recall, “in hardware” means in “in firmware” … And with current gpu’s, graphics routines, formerly only in firmware, are now accessible to programmer –Current graphics systems have ability to change algorithms that implement low level algorithms E.g., changing shading algorithm … or anything Indeed, current versions of OpenGL require program to supply low level algorithms for the graphics pipeline: –Defaults available for all … for now –Text requires from 1 st program! –We will use a “middle ground”

10 Recall, The Graphics Pipeline Programmable Pipeline Rasterization Application Commands Geometry Fragment Display “Application Program” Logic and processes Networking User input events Etc. … Send OpenGL commands OpenGL driver: Process GL command stream, talk to GPU GPU CPU Vertex transformations Vertex lighting Clipping Primitive assembly Convert triangles to fragments Tex coordinate interpolation Color interpolation Color blending Texturing Depth test Programmable vertex units Programmable fragment units Hence, the term “shaders” From Pfister, 2006, Harvard E-234 notes

11 OpenGL Evolution (Version History – Focus on Shaders – and this matters for you …) 1.0, 1992, “ Pioneers” – now, didn’t have to buy SGI’s to use! –1995, Microsoft DirectX competes, only recently OpenGL support in MS Windows 2.0, 2004, first version for shader programming 3.0, 2008, objects not bound to states –No new functionality for “old” (graphics) object system Old = immediate mode + fixed functionality (non-shader mode) –Left old functionality there, but as deprecated (supported, but by context) All fixed-function vertex and fragment processing Direct-mode rendering, using glBegin and glEnd Display lists Indexed-color rendering targets –Angel examples require 3.2 Will see what version your computer supports! 4.0, 2010, nothing major, supported on latest Intel laptop CPU/GPU IC –H 4000 -- 4 cores, 100+ pipelines –4.1, 2010, and 4.2, 2011, add geometry shaders and tessellator

12 OpenGL Evolution (Version History – Focus on Shaders – and this matters for you …) So, you find yourself at the “time of change” for computer graphics programming –From “old” immediate mode OpenGL to “new” shader based E.g., as noted this 6 th edition of Angel, is the first to provide it –AND, the programs in the text require OpenGL version 3.2 to execute! –So, first class assignment asks that you use a utility (provided with other programs through class and various site) to query the version of OpenGL available on your personal system (or whatever you use to do homework) E.g., recent versions of OpenGL are also shader based (next slide) More, as we progress in the next couple of weeks

13 Other Versions of OpenGL, Direct X OpenGL ES –Embedded systems, e.g., phones, e.g., http://developer.android.com/guide/topics/graphics/opengl.html http://developer.android.com/guide/topics/graphics/opengl.html –Version 1.0 simplified OpenGL 2.1 –Version 2.0 simplified OpenGL 3.1 Shader based WebGL –Javascript implementation of ES 2.0 –Supported on newer browsers Direct X –Windows only –Advantages: Better control of resources, Access to high level functionality –Disadvantages: New versions not backward compatible, Windows only –Recent advances in shaders leading to convergence with OpenGL

14 OpenGL, Resources Below contains much useful, and free information –www.opengl.orgwww.opengl.org Tutorials –Many available online –Note that most are “old” OpenGL, vs. shader based … though both should ultimately be mastered “OpenGL Documentation Overview”: OpenGL is the industry's most widely used, supported and best documented 2D/3D graphics API making it inexpensive & easy to obtain information on implementing OpenGL in hardware and software. There are numerous books, tutorials, online coding examples, coding seminars, and classes that document the API, Extensions, Utility Libraries, and Platform Specific Implementations. At opengl.org there are free books – details follow –The OpenGL Reference ManualThe OpenGL Reference Manual –The OpenGL Programming GuideThe OpenGL Programming Guide

15 Books, etc., OpenGL.org and elsewhere The “Red Book” –The OpenGL Programming Guide 4th Edition: The Official Guide to Learning OpenGL Version 4.3, 8 th Ed. All the new stuff, $38.21 from Amazon – 2/2/15 Many others at http://www.opengl.org/http://www.opengl.org/ –Top level menu: Documentation – OpenGl …. Guide Earlier versions (v. 1.1) available online: –“limited, but useful” … –Pointers change over time –Current pointers: The OpenGL "Redbook" v1.1 HTML format –http://www.glprogramming.com/red/ Sample Programs for the OpenGL "Redbook" v1.1 –http://www.opengl.org/resources/code/samples/redbook/

16 Books, etc. The “Blue Book” –The OpenGL Reference Manual 4th Edition The Official Reference Document to OpenGL, Version 1.4 –Old, 2004, but useful for non-shader programming Earlier versions available online: –Pointers change … http://www.glprogramming.com/blue/

17 OpenGl.org Many resources Standards, etc. –E.g., OpenGL 4.5 news and feedback thread, WebGL –See ad for OpenCL book See GLEW 1.12.0 released at right –Jan 28, 2015 –So, … that’s an example of why there may not be a quick answer to why something in your install (or program) does not (or does) work!

18 OpenGL … finally Libraries and other “support” elements –Overview, see class install notes for details and current versions for class OpenGL Commands and syntax Yet more about pipelines and software architecture

19 Recall, CG Software Architecture, APIs Both window system and graphics system api’s Graphics API OpenGl (no win sys func) DirectX Window system API MS windows X tools CPU GPU Graphics Processing Unit

20 Software Arch., Window System “The familiar” – No Graphics API Use “Application Progs” E.g., student programs MS Excel, etc. Tools: UI Program. MFC, Swing, Qt (widget toolkit and more) Graphics API OpenGl (no win sys func) DirectX Window system API MS windows X tools CPU GPU Graphics Processing Unit

21 Software Arch., Graphics – 1 “Simple” Use of Graphics API “Application Progs” E.g., student programs MS Excel, etc. Graphics API OpenGl (no win sys func) DirectX GLUT OpenGL Utility Toolkit Window system API MS windows X tools CPU GPU Graphics Processing Unit

22 Software Arch., Graphics – 2 Tool/package Use of Graphics API “Application Progs” E.g., student programs MS Excel, etc. Graphics API OpenGl (no win sys func) DirectX Window system API MS windows X tools CPU GPU Graphics Processing Unit Tools: Vis. Program. VTK s3s

23 Software Arch., Graphics – 3 Graphics API Use “Application Progs” E.g., student programs MS Excel, etc. Graphics API OpenGl (no win sys func) DirectX GLUT OpenGL Utility Toolkit Window system API MS windows X tools CPU GPU Graphics Processing Unit Tools: Vis. Program. VTK

24 Software Architecture, All “Application Progs” E.g., student programs MS Excel, etc. Tools: Graphic Maya, 3ds Tools: UI Program. MFC, Swing, Qt (widget toolkit and more) Graphics API OpenGl (no win sys func) DirectX GLUT OpenGL Utility Toolkit Window system API MS windows X tools CPU GPU Graphics Processing Unit Tools: Vis. Program. VTK

25 Software Organization Focus on GL, GLU, GLUT Below shows relationship among libraries –GLU “on top of” GL, –GLUT uses GLU and GL for graphics (as does GLEW, used in class) Controls operating and window systems primarily through GLX –Application program can call GLUT, GLU, GL GLUT GLU GL GLX, AGL or WGL X, Win32, Mac O/S software and/or hardware application program OpenGL Motif widget or similar

26 OpenGL Libraries Overview, see class install notes for details To call the functions that are the OpenGL API, use libraries –Will need to put on computer, and access (#include), to develop programs OpenGL core library –#include, e.g., gl.h OpenGL Utility Library (GLU) –Provides functionality in OpenGL core but avoids having to rewrite code OpenGL Utility Toolkit (GLUT) –Interfaces with window system …. GLX for X window systems WGL for Windows AGL for Macintosh –Provides window system independent implementation –For class, freeglut and GLEW (OpenGL extension Wrangler) … “wrangler” … not too reassuring … –Have instructions for use with compiler on class web site

27 OpenGL: “Software Interface to Graphics Hardware” OpenGL is a software interface to graphics hardware – more so, now Software layer with API: –Excellent synopsis in Angel’s Appendix D –~200 core functions - next slide specify objects and operations – again, at any point in the pipeline –~50 in library (auxiliary) commands – next slide glu, glut make life simple –also, can use ogl with straight Windows (the windowing system) –… and build your own shaders, …

28 OpenGL: “Software Interface to Graphics Hardware” … more detail, more later OpenGL is a software interface to graphics hardware – at any point! Software layer with API: –Excellent synopsis in Angel’s Appendix D –~200 core functions - next slide specify objects and operations – again, at any point in the pipeline –~50 in library (auxiliary) commands – next slide glu, glut make life simple –also, can use ogl with straight Windows (the windowing system) –… and build your own shaders, …

29 FYI - OpenGL: “Software Interface to Graphics Hardware”, same as last one Immediate Mode Display List Polynomial Evaluator Per Vertex Operations & Primitive Assembly Rasterization Per Fragment Operations Texture Memory CPU Pixel Operations Frame Buffer Another view, showing pipeline (more later)

30 GL Commands

31

32 From online Reference www.glprogramming.com/blue/ http://www.glprogramming.com/blue/

33 GL Commands

34 Commands

35 GLUT – OpenGL Utility Toolkit Again, GLEW (OpenGL Extension Wrangler) for class OpenGL Utility Toolkit (GLUT) –Provides functionality common to all window systems Open a window Get input from mouse and keyboard Menus Event-driven –Code is portable but GLUT lacks the functionality of a good toolkit for a specific platform E.g., no scroll bars But, it will work for us –Lots of tutorials online –Much more next time Will also look at qt

36 “Types” of OpenGL Functions Again, OGL API implemented as functions (below after Angel): Primitives –Points –Line Segments –Polygons Attributes Viewing Transformations –Viewing –Modeling Input (GLUT) Control (GLUT) Query

37 OpenGL: Primitives and States Older, pre - 2.0 and 3.0 OpenGL is a “state machine” –Some “state”, e.g., color is set and remains in that state until changed –Everything drawn is in the color set –When program starts, default values are set for everything Color, camera position and orientation, projection type, etc. OpenGL functions are of two types: 1.Primitive generating E.g., vertex, line Can cause output if primitive is visible How vertices are processed and appearance of primitive are controlled by the state 2. State changing Transformation functions –E.g, viewing, projections Attribute functions –E.g., color

38 Note: Lack of Object Orientation BTW, OpenGL is not object oriented –So there are multiple functions for a given logical function –Below differ in 2d vs. 3d and type of arguments, integer vs. fp (example next slides) glVertex3f glVertex2i glVertex3dv Underlying storage mode is the same Easy to create overloaded functions in C++, but issue is efficiency As usual, alternative software layers exist

39 OpenGL Function Format 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/vector n dimensions

40 “OGLese” – Naming Conventions E.g., as seen, glVertex3f (x, y, z) Suffixes and types (like MS Windows API): – Suffix Data Type Typical C TypeOpenGL Type – b 8-bit integer signed char GLbyte – s 16-bit integer short GLshort – i 32-bit integer long GLint, GLsizei – f 32-bit floating-point float GLfloat, GLclampf – d 64-bit floating-point double GLdouble,GLclampd – ub 8-bit unsigned integer unsigned char GLubyte, GLboolean – us 16-bit unsigned integer unsigned short GLushort – ui 32-bit unsigned integer unsigned long GLuint, GLenum Argument expectation convention (name of function gives args): –glVertex2i(1, 3); –glVertex2f(1.0, 3.0); Also, vector arguments common: –glColor3f(1.0, 0.0, 0.0); –float color_array[] = {1.0, 0.0, 0.0}; –glColor3fv(color_array);

41 OpenGL Include Files: “#defines” Well, this is C, so lexics and semantics conflated Most constants are defined in include files – gl.h, glu.h and glut.h Note #include glut.h automatically includes the others –Do have a look at the *.h files, quite easy in MS compiler Examples – glBegin(GL_POLYGON) – glClear(GL_COLOR_BUFFER_BIT) include files also define OpenGL data types: – GLfloat, GLdouble,….

42 Coordinate Systems

43 Units in glVertex are determined by application –called object or problem or model coordinates Viewing specifications are also in object coordinates –Size of viewing volume that determines what will appear in the image Internally, OpenGL will convert to camera (eye) coordinates and later to screen coordinates OpenGL also uses some internal representations that usually not visible to application – next slide

44 Coordinate Systems in Viewing Coordinate Systems in the Graphics Pipeline –OCS – object coordinate system –WCS – world coordinate system –VCS – viewing coordinate system –CCS – clipping coordinate system –NDCS - normalized device coordinate system –DCS – device coordinate system And images are formed on the image plane

45 Placing & Aiming the OpenGL (synthetic) Camera Natural to position camera in world space as if real camera 1. Identify the eye point where the camera is located 2. Identify the look-at point that we wish to appear in the center of our view 3. Identify an up-vector vector oriented upwards in our final image Specify camera configuration with: –gluLookAt (ex, ey, ez, ax, ay, az, ux, uy, uz) –3 camera vectors: lookFrom (ex, ey, ez), lookAt (ax, ay, az), vUp (ux, uy, uz)

46 OpenGL Viewing: The Camera Analogy (and, briefly, transformations to create coordinate systems) Synthetic camera in OGL 1. Setting up tripod & pointing camera at scene: viewing transformation 2. Arranging scene viewed into desired composition: modeling transformation 3. Choosing camera lens or adjusting zoom: projection transformation 4. Determining how large and what part final view: viewport transformation

47 Again, Viewing – gluLookAt gluLookAt (ex, ey, ez, ax, ay, az, ux, uy, uz) Real handy (about as useful as anything): –gluLookAt (x, y, z,//cop – where the camera is, center of projection x, y, z// any pt - where camera looking, viewpoint z, y, z);// up vector (camera twist) Most Simply: –Center of projection: just x, y, z –Viewpoint is specified by eyex, eyey, and eyez. –“Where looking” is specified as atx, aty, and atz, any point along line of sight –Up vector: upx, upy, and upz indicate which direction is up

48 Example - gluLookAt gluLookAt (GLdouble eyex, GLdouble eyey, Gldouble eyez, //cop GLdouble atx, GLdouble aty,GLdouble atz, // pt on los GLdouble upx,GLdouble upy,GLdouble upz);// up vec. gluLookAt (4.0, 2.0, 1.0, 2.0, 4.0, -3.0, 2.0, 2.0, -1.0) –Shows camera twist

49 BTW, OpenGL Camera Defaults … who would know … First examples do not move camera, so default/ “opening state” –Need to know, lest may not see anything! –E.g., object placed “on” camera –Need to move object or camera! OpenGL places a camera at origin in world/object space pointing in negative z direction Default view volume is a box centered at the origin with a side of length 2

50 Also, Orthographic Viewing is Default Orthographic vs. Perspective Viewing –Later will examine projection on view plane for differing distances –Angel suggests thinking of orthographic view as camera at infinite/far distance w/telephoto lens –Or, no vanishing point –Or, …. In the default orthographic view, points are projected forward along the z axis onto the plane z=0 z=0

51 Viewports More later Do not have use the entire window for the image –E.g., glViewport(x,y,w,h) Values in pixels (window coordinates)

52 It’s (almost) all about Polygons

53 It’s (almost) all about Polygons (recall, modeling topics last week) Have discussed tractability, interactivity and selection of image models –Not physical –Leads to using “good enough” (for the task) representation –Much of challenge of cg lies in representing the analog world on a digital device E.g., approximation of circle as series of straight lines Though some surfaces and objects can be described mathematically, e.g., sphere, most cannot, e.g., crocodile Approximation for objects is typically polygon mesh Polygons – Flat shading Ray tracing Wireframe Polygons - Smooth shading

54 Polygon Representations More is always better (for polygon count and photorealism) –Below, 20, 80, 320 polygons for sphere –Sampling vs. discrete –Tesselation Fair amount of detail in using meshes, etc. –Usually, library routines or tools create

55 Polygon Mesh – More is Better Maya ( en.9jcg.com/comm_pages/blog_content-art-51.htm ) en.9jcg.com/comm_pages/blog_content-art-51.htm 940 and ~1m polygons –But they are still polygons!

56 Example: Draw cube from faces (quick look) void colorcube( ) { polygon(0,3,2,1); polygon(2,3,7,6); polygon(0,4,7,3); polygon(1,2,6,5); polygon(4,5,6,7); polygon(0,1,5,4); } Vertices are ordered to obtain correct outward facing normals 0 56 2 4 7 1 3

57 Representing a Mesh (quick look) Consider a simple “mesh” Already 8 nodes and 12 edges –5 interior polygons –6 interior (shared) edges Each vertex has location v i = (x i y i z i ) How to efficiently store for use is a significant data structure question –Hence, the large number of representations in OpenGL v1v1 v2v2 v7v7 v6v6 v8v8 v5v5 v4v4 v3v3 e1e1 e8e8 e3e3 e2e2 e 11 e6e6 e7e7 e 10 e5e5 e4e4 e9e9 e 12

58 OpenGL Primitives (quick look) Can Specify individual vertices and polygons, as below, or a zillion other ways In fact “it’s all about polygons”, so efficient representations needed 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(); }

59 Polygons and OpenGL OpenGL will only display polygons correctly that are: –Simple: edges cannot cross – a, not b –Convex: All points on line segment between two points in a polygon are also in the polygon – not b –Flat: all vertices are in same plane User program checks if above true –Program vs. OpenGL checks for efficiency –OpenGL will produce output if these conditions are violated, … but it may not be what is desired All triangles satisfy all conditions … used extensively

60 Attributes Attributes are part of the OpenGL state and determine the appearance of objects –Color (points, lines, polygons) –Size and width (points, lines) –Stipple pattern (lines, polygons) –Polygon mode Display as filled: solid color or stipple pattern Display edges Display vertices

61 Color

62 More later … Additive and subtractive color –Additive: Monitors, etc. –Subtractive: Printers, etc. RGB color –Color cube –Indexed color Gamuts –Will later see some more things, e.g., gamuts

63 RGB color Basic color specification is straightforward Each color component is stored separately in frame buffer Usually 8 bits per component in buffer OpenGL – multiple ways to specify color, e.g.: –In glColor3f the color values range from 0.0 (none) to 1.0 (all), –Whereas in glColor3ub the values range from 0 to 255

64 About Color – More Later Colorimetry –Any color can be (perceptually) matched with a mixture of <=3 lights (primaries) C =  rR + gG + bB –Where C is color to be matched, R, G, B are primary sources, and r, g, b amounts –E.g., at right cyan = R + G yellow = R + G Also, negative amts (subtractive) –As shining light through colored glass –“removing” color of glass In fact, primaries other than R, G, and B can be used –E.g., R,Y,B (paint) –However, will produce different gamuts

65 Color Gamut – More Later Gamut is the set of all colors that a device can produce, or a receptor can sense –E.g., Film gamut Monitor gamut Human eye gamut –E.g, color printer cannot reproduce all the colors visible on a color monitor CIE standard

66 Color Space Example: RGB Color Cube Again, can specify color with 3 –Will see other way RGB Color Cube –Neutral Gradient Line –Edge of Saturated Hues –ppt example http://graphics.csail.mit.edu/classes/6.837/F01/Lecture02/ http://www.photo.net/photo/edscott/vis00020.htm

67 Recall, Indexed Color Colors are indices into tables of RGB values –Recall (actually we skipped it in class), CLUT Requires less memory –indices usually 8 bits –not as important now Memory inexpensive Need more colors for shading

68 Color and State Color, as set by glColor, becomes part of state and will be used until changed Colors and other attributes are not part of object –But are assigned when object is rendered Can create conceptual vertex colors, e.g., glColor glVertex glColor glVertex BTW, from OpenGL Reference: http://www.cs.utk.edu/~vose/c-stuff/opengl/ glColor NAME glColor3b, glColor3d, glColor3f… C SPECIFICATION void glColor3b(GLbyte red, GLbyte green, GLbyte blue) void glColor3d(GLdouble red, GLdle green, GLdouble blue) void glColor3f(GLfloat red, GLfloat green, GLfloat blue) … PARAMETERS red, green, blue Specify new red, green, and blue values for the current color. … DESCRIPTION The GL stores both a current single-valued color index and a current four-valued RGBA color. glColor sets a new four- valued RGBA color. glColor has two major variants: glColor3 and glColor4 …

69 Smooth Color (quick look) Will later look closely at shading models later, for now, “how to program” Default is smooth shading –OpenGL interpolates vertex colors across visible polygons Alternative is flat shading –Color of first vertex determines fill color glShadeModel (GL_SMOOTH) or GL_FLAT

70 Projection: Essential Definitions

71 Projectors View plane (or film plane) Direction of projection Center of projection –Eye, projection reference point

72 Projection: Perspective vs. Parallel Fundamental distinction is whether projection is perspective or parallel –Even though mathematically parallel viewing is the limit of perspective viewing –Is just as simple as whether projectors Converge, or are Parallel Can (probably) see in squares in figure Computer graphics treats all projections same –implements them with a single pipeline –Will see … “just a matter of setting a single matrix value” Classical viewing developed different techniques for drawing each type of projection Parallel projection Perspective projection, smaller as f(distance cop)

73 Parallel Projections Simplest form of parallel projection is simply along lines parallel to z-axis onto xy-plane –So, parallel projectors –Called “direction of projection” (DOP) –Vs. center of projection (COP) –Though could consider COP at infinity This form of projection called orthographic

74 Perspective Projections Artists during renaissance discovered importance of perspective for making images appear realistic –Parallel lines intersect at a point “Diminution of size” –Objects farther away are smaller –This makes sense, considering way projectors intersect view plane

75 Getting Close to a Program …

76 Text … OpenGL (actually) GLUT and GLEW) have it –Stroke vs. bitmap (raster) Stroke-text attributes example Will be easy to figure out how to use –Basic paradigm for your learning –Encourages (actually, requires) “self directed learning”

77 OpenGL Viewports and Screen Recall, GLUT and GLEW handles much of window system detail An OpenGL viewport is displayed in a screen window –Lots of things one can do both with image and screen, e.g., multiple viewports –Simple is fine, as below Do not have to use entire window for the image, for example: –Note: Values in pixels (screen coordinates) –glutCreateWindow (char *title); –glutInitDisplayMode (GLUT_RGB | GLUT_DEPTH); –glutInitWindowSize (640,480); –// display OpenGL at top left – uses screen coordinates –GlutInitWindowPostion (0,0); Most generally: – glViewport(x,y,w,h)

78 BTW, Hidden-Surface Removal Want to see only surfaces “in front of” (closer to viewer than) other surfaces –Classic cg problem – hidden surface removal OpenGL uses z-buffer algorithm –Saves depth information as objects are rendered so only front objects appear in image Use extra buffer, z-buffer, to store depth information as geometry travels down pipeline To enable hidden surface removal: –Requested in main.c glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH) –Enabled in init.c glEnable(GL_DEPTH_TEST) –Cleared in the display callback glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

79 Finally, A Real OpenGL Program!!!

80 A (realllllly) Simple Program Simple is good … –In fact, only simple because OGL sets defaults for all! –If all uninitialized, or to say 0’s, then could be 50-100 lines of code Generate a square on a solid background:

81 simple.c Quick look Just draws it: #include “glut.h” // uses lots of defaults // see class ex. programs for glew details here int main(int argc, char** argv) { glutCreateWindow("simple"); glutDisplayFunc(mydisplay); // callback function glutMainLoop(); } 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(); }

82 Callback Functions & Event Loop Quick look More about Glut, glew, callbacks, … next time Program defines a display callback function –Here, named mydisplay Every glut program must have a display callback –Executed whenever OpenGL decides display must be refreshed, E.g., when window opened –The main function ends with program entering an event loop #include // see class examples 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(); }

83 Defaults and OpenGL Again, simple.c is really simple –But, it runs Makes heavy use of state variable default values for –Viewing Camera location, direction orthographic vs. perspective –Colors White –Window parameters Size, etc. Next version will make defaults more explicit #include // see class example programs for details 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(); }

84 Next simple.c Version Refine the first program: Alter default values, standard program structure Simple viewing: 2D viewing as a special case of 3Dviewing Fundamental OpenGL primitives and attributes Most OpenGL programs have a similar structure that consists of: 1. main() : defines the callback functions opens one or more windows with the required properties enters event loop (last executable statement) 2. init() : sets the state variables Viewing Attributes 3. Callbacks, e.g., mydisplay () Display function Input and window functions

85 simple.c Revisited In this version, –same output –But defined some of the relevant state values through function calls using the default values Set: –Colors –Viewing conditions –Window properties #include //now, use glut int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500);// define win prop glutInitWindowPosition(0,0); glutCreateWindow("simple"); glutDisplayFunc(mydisplay); // display callback init(); // set OpenGl state glutMainLoop();// enter event loop }

86 simple.c revisited, GLUT functions GLUT library calls glutInit –allows application to get command line arguments and initializes system gluInitDisplayMode –requests properties for window –rendering context RGB color Single buffering Properties logically ORed together glutWindowSize (pixels) glutWindowPosition –from top-left corner of display glutCreateWindow –Window has title “simple” glutDisplayFunc –display callback glutMainLoop –enter infinite event loop #include //now, use glut, glew void init() { // black clear color - 1.0 – opaque window glClearColor (0.0, 0.0, 0.0, 1.0); // fill/draw with white glColor3f(1.0, 1.0, 1.0); glMatrixMode (GL_PROJECTION); // more later glLoadIdentity (); // view volume glOrtho(-1.0,1.0,-1.0,1.0,-1.0,1.0); } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500);// win prop glutInitWindowPosition(0,0); glutCreateWindow("simple"); glutDisplayFunc(mydisplay); // display callback init(); // set OpenGl state glutMainLoop();// enter event loop }

87 BTW, glu - Sphere All kinds of objects can be created easily using glu

88 Program 1, a In this first programming assignment in Open GL you will 1) create a really simple “scene” in which there are a few polygons and 2) use a utility program from the GLEW download to find out the version of OpenGL supported on the system you use. A primary goal of the assignment is to make sure all is set up for program compilation on the system on which you will be programming. 1) Angel’s program simple.c is from his book OpenGL: A Primer and is available on the class web site, as well as his site at http://www.cs.unm.edu/~angel/BOOK/. http://www.cs.unm.edu/~angel/BOOK/ Also available at that site are the usual “book support” elements for Angel’s text (all editions), e.g., code, book figures, solutions to exercises, errata (in case you’re sure there’s a mistake in the book!).

89 Program 1, b For the assignment the program should display at least three polygons, all of which are visible. In the simplest implementation, simply create the polygons one at a time, as in the program simple.c discussed in the lecture. Make each polygon a different color. Note that the camera has a default position and the location of the polygons must be “in front of” the camera, which we will talk about more in the next weeks. For extra credit, make an interesting, cool or complex scene. For even more extra credit, make something move. Any extra credit with respect to grade will not be large, and your feeling of accomplishment is likely the larger reward. Never simply copy code and expect good things to happen. The CS Department’s Academic Integrity Policy will be strictly enforced, and it’s more fun to make it all up anyway.

90 Program 1, c 2) When you download the “OpenGL Extension Library” (GLEW) you will find couple of utility files, found in the \bin directory, glewinfo.exe and visualinfo.exe. Executing visualinfo provides a wealth of information about the capabilities of the graphics system on the computer. After the program is executed this information is located in a file visualinfo.txt. The first part of the file has information about the version of OpenGL that your system has, e.g. below is the first part when executed on my desktop machine: –OpenGL vendor string: Microsoft Corporation –OpenGL renderer string: GDI Generic –OpenGL version string: 1.1.0 –OpenGL extensions (GL_): – GL_WIN_swap_hint, GL_EXT_bgra, GL_EXT_paletted_texture. –GLU version string: 1.2.2.0 Microsoft Corporation –GLU extensions (GLU_): – GL_EXT_bgra.

91 Program 1, d What to submit. When complete, please send for this figure drawing program: a screen capture, the source code, and the OpenGL support information provided by visualinfo (just paste it in). The format for this should be a Word document with 1) a short description (100-200 words) of what the program does, followed by 2) a screen capture of the program’s output on the same page, and finally 3) the OpenGL capabilities from visualinfo (just cut and paste). This should all fit on one page. Following this first page, please include 4) the program’s source code, uploading all to Blackboard.

92 Program 1, e Submit to blackboard No program will be accepted past the due date and time. Both the Teaching Assistant and instructor are in general glad to help, … but we are a lot more glad to help in the days well before the assignment is due, i.e., Wednesday, Thursday, or Friday, than the 36 hours prior to the assignment due date, i.e., Monday and Tuesday, especially “How to get started” questions. But, whatever.

93 Compiler Stuff … for the experienced (see class web site “Installation Instructions” for more detail) Get and unzip freeglut and GLEW –http://www.transmissionzero.co.uk/software/freeglut-devel/http://www.transmissionzero.co.uk/software/freeglut-devel/ –http://glew.sourceforge.net/ (1/26/15 latest version)http://glew.sourceforge.net/ Need to determine whether 32-bit or 64-bit version of Windows –Start -> Control Panel -> System, then, says there which version Put files where system and compiler can find them –*. h files in “include directory”, e.g., C:\Program Files\Microsoft SDKs\Windows\v7.0A\include\gl –*.dll in “system directory”, e.g., C:\Windows\System32 or C:\Windows\SystemWOW64 –*.lib files, e.g., C:\Program Files\Microsoft SDKs\Windows\v7.0A\lib Create console C project, …, add sample code (item) Set C project linking dependencies –Project – Properties – Linker – Input, - then Add dependencies

94 Questions?.


Download ppt "OpenGL 1 Angel: Chapter 2 OpenGL Programming and Reference Guides, Angel, other sources. CSCI 6360."

Similar presentations


Ads by Google