122
M.S.RAMAIAH INSTITUTE OF TECHNOLOGY, BANGALORE-54 (Autonomous Institute, Affiliated to VTU) DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING CS712 Graphics & Visualization LABORATORY MANUAL Version: 1.0 Prepared by: Jayalakshmi D S

CGLab Manual 2012

Embed Size (px)

DESCRIPTION

cg

Citation preview

Page 1: CGLab Manual 2012

M.S.RAMAIAH INSTITUTE OF TECHNOLOGY, BANGALORE-54(Autonomous Institute, Affiliated to VTU)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

CS712 Graphics & Visualization

LABORATORY MANUALVersion: 1.0

Prepared by: Jayalakshmi D S Associate Professor Dept. of CSE, MSRIT

August – December 2012

Page 2: CGLab Manual 2012

Content

s

Lab Work Details for Term: Aug-Dec 2012....................................................................................5

List of Suggested Programming Exercises..................................................................................5

Instructions for Mini Project........................................................................................................7

Assessment..................................................................................................................................7

Installing OpenGL on Windows......................................................................................................8

Installation/verification:...............................................................................................................8

Compiling OpenGL Programs Using Visual Studio...................................................................9

Introduction to OpenGL................................................................................................................12

Software Organization...........................................................................................................12

OpenGL Utility Toolkit (GLUT)...........................................................................................12

OpenGL Pipeline Architecture..............................................................................................13

A Simplified Model of the OpenGL Pipeline........................................................................13

Primitives and Attributes.......................................................................................................14

Clipping and Projection.........................................................................................................15

Rasterization..........................................................................................................................16

Frame Buffer..........................................................................................................................16

Per-fragment Operations........................................................................................................17

Evaluators..............................................................................................................................17

Display Lists..........................................................................................................................17

Feedback and Selection.........................................................................................................17

OpenGL State........................................................................................................................18

Commonly Required OpenGL Functions......................................................................................19

SPECIFYING SIMPLE GEOMETRY..................................................................................19

ATTRIBUTES.......................................................................................................................20

WORKING WITH WINDOW SYSTEM.............................................................................22

INTERACTION....................................................................................................................25

ENABLING FEATURES......................................................................................................27

TRANSFORMATIONS........................................................................................................28

VIEWING..............................................................................................................................29

Page 3: CGLab Manual 2012

3

DISPLAY LISTS...................................................................................................................30

PICKING...............................................................................................................................31

LIGHTING............................................................................................................................33

VERTEX ARRAYS..............................................................................................................34

Sample Code for Suggested Programming Exercises...................................................................37

Lab 1..........................................................................................................................................37

Create a simple house with windows and door open. Write the reshape function so that the house is not distorted when the display window is resized...................................................37

Create a chessboard...............................................................................................................38

Create a gingerbread man using iterated function system. Use the equations q.x = M(1 + 2L) - p.y + |p.x –LM| and q.y = p.x..........................................................................39

Lab 2..........................................................................................................................................42

Create 2D Sierpinski gasket by plotting points (IFS)............................................................42

Create 2D Sierpinski gasket by recursive subdivision of triangle.........................................43

Create 3D Sierpinski gasket by recursive subdivision of tetrahedron...................................45

Lab 3..........................................................................................................................................48

fish swimming.......................................................................................................................48

kite flying...............................................................................................................................48

rotating wheel........................................................................................................................49

Lab 4..........................................................................................................................................50

Write a program to handle mouse events. Plot points in random colors by pressing the mouse left button. The display window must be cleared when you press the mouse right button. Also write the reshape callback function which changes the clipping rectangle when window is resized..................................................................................................................50

Write a program to handle mouse events. Draw rectangles using 2 points, at top left and bottom right on mouse left-button clicks. On right click, clear window. Use reshape callback to avoid distortion on window resize......................................................................51

Write a program to simulate free hand drawing using a fat brush. The brush size must be randomly variable in the range 3-10. The drawing should be multicolored..........................53

Lab 5..........................................................................................................................................56

Write a program to handle mouse events Create a polyline using mouse left-button clicks. The polyline must be redisplayed on window resize.............................................................56

Write a program to create a font for the letter C .................................................................58

Write a program to create a font for the letter D..................................................................59

Write a program to create a font for the letter O..................................................................60

Write a program to create a font for the letter S...................................................................62

Lab 6..........................................................................................................................................64

Page 4: CGLab Manual 2012

4

Write a program to display a hierarchical menu as below using popup menu. When an option is selected, display the option on output window.......................................................64

Write a program to draw a square. Use popup menu with options to quit or resize the square. The resize option has submenu with increase size and decrease size as options. The increase size must double the size of the square and the decrease size option must reduce the size by 2. (half size) . Min size is 1.......................................................................................66

Lab 7..........................................................................................................................................69

Write a program to rotate a square using both single and double buffering..........................69

Write a program to demonstrate picking using selection mode............................................71

Write a program to perform rotation of a cube using color interpolation.............................74

Write a program to perform rotation of a cube using vertex arrays......................................75

Write a program that generates approximations to a sphere by recursive subdivision generation..............................................................................................................................77

Write a program to draw a line using Bresenham’s algorithm..............................................79

Lab 9..........................................................................................................................................81

Write a program to implement the Cohen Sutherland line clipping algorithm in 2D. Make provision to specify the input line, window for clipping and view port for displaying the clipped image.........................................................................................................................81

Write a program to draw a color cube and allow the user to move the camera suitably to experiment with perspective viewing. Use OpenGL functions.............................................84

Write a program to fill any given polygon using scan-line area filling algorithm. (Use appropriate data structures.)...................................................................................................87

Page 5: CGLab Manual 2012

5

M.S.RAMAIAH INSTITUTE OF TECHNOLOGY, BANGALORE-54

(Autonomous Institute, Affiliated to VTU)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Lab Work Details for Term: Aug-Dec 2012

Subject Code: CS712

Subject Name: Graphics and Visualization Course Credits: 3:0:1

Teaching Faculty: D S Jayalakshmi, S Seema

Total lab sessions required : 14 (2Hrs each)

List of Experiments: The Lab work consists of a set of programming exercises using OpenGL and a mini-project to be implemented using OpenGL in groups of two students each.

List of Suggested Programming Exercises

Lab 1:

1) Create a simple house with windows and door open. Write the reshape function so that the house is not distorted when the display window is resized.

2) Create a chessboard. 3) Create a gingerbread man using iterated function system. Use the equations q.x

= M(1 + 2L) - p.y + |p.x –LM| and q.y = p.x.

Lab 2:

4) Create 2D Sierpinski gasket by plotting points (IFS)5) Create 2D Sierpinski gasket by recursive subdivision of triangle.6) Create 3D Sierpinski gasket by recursive subdivision of tetrahedron.

Lab 3:

7) Create a scene of fish swimming.8) Create a scene of flying kite.9) Create a scene of rotating wheel.

Lab 4:

10) Write a program to handle mouse events. Plot points in random colors by pressing the mouse left button. The display window must be cleared when you press the mouse right button. Also write the reshape callback function which changes the clipping rectangle when window is resized.

Page 6: CGLab Manual 2012

6

11) Write a program to handle mouse events. Draw rectangles using 2 points, at top left and bottom right on mouse left-button clicks. On right click, clear window. Use reshape callback to avoid distortion on window resize.

12) Write a program to simulate free hand drawing using a fat brush. The brush size must be randomly variable in the range 3-10. The drawing should be multicolored.

Lab 5:

13) Write a program to handle mouse events Create a polyline using mouse left-button clicks. The polyline must be redisplayed on window resize.

14) Write a program to create a font for the letter C of user input thickness.15) Write a program to create a font for the letter D of user input thickness16) Write a program to create a font for the letter O of user input thickness17) Write a program to create a font for the letter S of user input thickness

Lab 6:

18) Write a program to display a hierarchical menu as below using popup menu. When an option is selected, display the option on output window.

View _______ normal| _print|_web

Edit_________cut|_ copy|_paste

19) Write a program to draw a square. Use popup menu with options to quit or resize the square. The resize option has submenu with increase size and decrease size as options. The increase size must double the size of the square and the decrease size option must reduce the size by 2. (half size) . Min size is 1.

Lab 7:

20) Write a program to rotate a square using both single and double buffering.21) Write a program to demonstrate picking using selection mode.22) Write a program to perform rotation of a cube using color interpolation.23) Write a program to perform rotation of a cube using vertex arrays.

Lab 8:

24) Write a program that generates approximations to a sphere by recursive subdivision generation.

25) Write a program to draw a line using Bresenham’s algorithm.26) Write a program to demo the usage of viewports. The program should define a

viewport in the left half of the display window and the original triangle is displayed in blue color. Define another viewport for the right half of the window. The color of the triangle is changed to red and the triangle is rotated about its centroid and displayed in the second viewport.

Page 7: CGLab Manual 2012

7

Lab 9:

27) Write a program to implement the Cohen Sutherland line clipping algorithm in 2D. Make provision to specify the input line, window for clipping and view port for displaying the clipped image.

28) Program to draw a color cube and allow the user to move the camera suitably to experiment with perspective viewing. Use OpenGL functions.

29) Program to fill any given polygon using scan-line area filling algorithm. (Use appropriate data structures.)

Instructions for Mini Project

The mini project is to be carried out in 3 weeks duration. The students will form the batches of two and need to develop a mini project demonstrating either the concepts they have learnt in the theory, or need to build a graphics application using OpenGL. The aim is to check the expertise the students would have gained in OpenGL and the concepts of 2D and 3D graphics.

Sample topics include: Dynamic Maze Demonstrating 3D operations Bouncing Ball game Any 3D games.

The deliverables are

A working demonstration of the project work A complete project report including source code and screen shots

Assessment

The lab work carries total 25 CIE marks. The assessment consists of

1. Lab Test : 15 Marks (Write- up and program execution: 10M + Viva 5 M)2. Project work : 10 Marks (Demonstration 5 M + report 3 M + Viva 2 M)

Page 8: CGLab Manual 2012

8

Installing OpenGL on Windows

Windows versions:7 Enterprise, Vista x64 Enterprise Edition SP2 (Build 6002), Vista Enterprise Edition SP2 (Build 6002), XP Professional Edition SP3 5.1 (Build 2600)

Visual Studio 2010 version 10.0.420219.1 SP1Rel .NET Framework version 4.0.30319 SP1 Rel2008 version 9.0.21022.8.RTM .NET Framework version 3.5 SP1

Installation/verification:

OpenGL comes with the OS and Visual Studio 2010/2008 installations, to verify:o runtime libraries:

C:\Windows\System32\{opengl,glu}32.dll on 64-bit Windows: C:\Windows\SysWOW64\{opengl,glu}32.dll

o header files: C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\GL\{GL,GLU}.h ["Program Files (x86)" for 64-bit Windows; VS2008: v6.0A]

o linker library: C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib\OpenGL32.Lib ["Program Files (x86)" for 64-bit Windows; VS2008: v6.0A]

Windows does not include GLUT standard. If it is not already installed follow the following steps.

1. Download GLUT from http://www.xmission.com/~nate/glut/glut-3.7.6-bin.zip2. Unzip the file.3. Put the file "glut32.dll" into the system path.

o This can be in the same directory as your executable file.o On Windows XP or earlier, this can be in "C:\WINDOWS\system32"o Or you can create a directory like "C:\DLLs", put the file in this directory and

change your system path to include this new directory. Do this by opening Control Panel -> System, clicking on "Advanced

System Settings", followed by "Environment Variables", and editing the "Path" variable.

4. Put the file "glut.h" into the standard Visual C++ include directoyo (For Visual Studio 2010, this should be:

"C:\Program Files\Microsoft SDKs\Windows\v7.0A\include\gl")

Page 9: CGLab Manual 2012

9

o (For Visual Studio 2008, this should be: "C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\gl")

o (For Visual Studio 2005, this should be: "C:\Program Files\Microsoft Visual Studio.NET\Vc7\PlatformSDK\Include\gl")

o You've got the right directory if you see a copy of "gl.h"

5. Put the file "glut32.lib" into the standard Visual C++ library directoryo (For Visual Studio 2010, this should be:

"C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib")o (For Visual Studio 2008, this should be:

"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib")o (For Visual Studio 2005, this should be:

"C:\Program Files\Microsoft Visual Studio.NET\Vc7\PlatformSDK\lib")o There should be lots of .lib files here, including "opengl32.lib" and "glu32.lib".

6. Make sure your Visual C++ project links in the GLUT/gl/glu libraries (see also this page). This is located in:

o Menu: "Project -> (your-project-name) Properties"o Tab: "Configuration Properties -> Linker -> Input"o Under "Additional Dependancies", add "glut32.lib glu32.lib opengl32.lib"

7. #include < GL/glut.h > in your program.o Note: This needs to come after you #include < stdio.h > and < stdlib.h >.o Note: This needs to come before you #include < GL/gl.h >.o Also note that glut.h includes gl.h for you (so you need not explicitly #include <

GL/gl.h >).8. You should not include windows.h or any other Windows-specific header files.9. If you get compilation errors because of multiple conflicting definitions of "exit()", then

"stdio.h" and "glut.h" have been #include'd in the wrong order. You may fix this by:o Reordering your #include files (see step #7). This is the "right" way.o Add "#define GLUT_DISABLE_ATEXIT_HACK" to glut.h on the line immediately

after the first "#if defined(_WIN32)".10. If you happen to have a 64-bit version of Windows and Visual Studio, make sure you

compile a 32-bit executable.

Compiling OpenGL Programs Using Visual Studio

The key things you need to do are: Tell Visual Studio where your code resides (or will reside). Tell Visual Studio which code files to compile. Tell Visual Studio what libraries you need. Tell Visual Studio where to find those libraries.

These instructions work for Visual Studio 2008, though they are mostly similar for other versions:

Page 10: CGLab Manual 2012

10

1. Open Visual Studio 2008.o If this is your first time, select "Visual C++" as the default configuration.

2. Once it has completely opened, select from the menu "File" followed by "New" followed by "Project".

3. In the New Project dialog box:o Type a name for your project and a location where you want your project

directory.o For the project type, select "Visual C++" then "Win32" then "Win32 Console

Application"o Click "Ok"

4. In the Win32 Application Wizard dialog box:o Click "Application Settings"o De-select "precompiled header" (unless you know what they are)o Select "empty project"o Keep the application type as "Console application"o Click "Finish"

5. You will now return to the main Visual Studio window, where a subwindow entitled "Solution Explorer" will appear. This contains information about "Solution < myTestProject >" (where < myTestProject > is whatever you named your project). Visual Studio should also have created a project directory where it will store the files. Open up the directory "< myTestProject >" and its subdirectory (also called "< myTestProject >"). There you should see a file called < myTestProject >.vcproj (or labeled "VC++ Project"). Copy any code you would like to use into this subdirectory.

6. Back in the Visual Studio subwindow (the "Solution Explorer"), you should see folders labeled "Header Files" and "Source Files."

o Right click on "Source Files," select "Add," select "Existing File" and then select the C/C++ file you wish to use (e.g., my "glut_template.c" file). Alternately, create a new file and start typing in code from scratch.

o Right click on "Header Files," select "Add," select "Existing File" and then select the header file you wish to use (e.g., my "glut_template.h" file).

o If you find it easier, you can drag and drop files directly onto the solution explorer.

7. Right click on the BOLD name of your project in the "Solution Explorer."o Select "Properties" (all the way at the bottom of the pop-up menu)o Click the plus (+) next to "Linker" to see more linker options

Click on "Input" and add an entry to "Additional Dependencies." This entry should be "opengl32.lib glu32.lib glut32.lib" (without the quotes).

o Click "OK" to confirm your changes and close the properties dialog.8. Double click on any of the listed code files to open them and begin editing.9. Once you have finished coding, press "F7" to compile (or build) your project.10. Your executable will be in the "Debug" subdirectory of the project's directory. If your

executable requires no command-line parameters, you can run it directly from inside Visual Studio by pressing "F5."

Page 11: CGLab Manual 2012

11

Acknowledgement: These instructions are compiled from [1] http://web.eecs.umich.edu/~sugih/courses/eecs487/glut-howto/#win[2] http://homepage.cs.uiowa.edu/~cwyman/classes/common/howto/winGLUT.html[3] http://homepage.cs.uiowa.edu/~cwyman/classes/common/howto/compileVS.html

Page 12: CGLab Manual 2012

12

Introduction to OpenGL

OpenGL is a library of function calls for doing computer graphics. With it, one can create interactive applications that render high-quality color images composed of 3D geometric objects and images. The current version of OpenGL is 4.3, released on August 6, 2012, and is the fifteenth revision since the original version 1.0.

The OpenGL API is window and operating system independent. That means that the part of the application that draws can be platform independent. However, in order for OpenGL to be able to render, it needs a window to draw into. Generally, this is controlled by the windowing system on whatever platform you are working on.

Software Organization

The OpenGL Interface consists of functions in three libraries. 1. OpenGL core library: OpenGL32 on Windows and GL on most unix/linux systems

(libGL.a)2. OpenGL Utility Library (GLU): Provides functionality in OpenGL core but avoids having to

rewrite code3. Links with window system: GLX for X window systems, WGL for Windows, AGL for

Macintosh

OpenGL Utility Toolkit (GLUT)

GLUT provides functionality common to all window systems such as opening a window, getting input from mouse and keyboard, menus. GLUT is event-driven and its code is portable. GLUT is designed for constructing small to medium sized OpenGL programs. But GLUT lacks the functionality of a good toolkit for a specific platform. For example, it does not provide slide bars. So, large applications requiring sophisticated user interfaces are better off using native window system toolkits.

Page 13: CGLab Manual 2012

13

The GLUT library has C, C++ (same as C), FORTRAN, and Ada programming bindings. The GLUT source code distribution is portable to nearly all OpenGL implementations and platforms. The current version is 3.7.

The toolkit supports multiple windows for OpenGL rendering, callback driven event processing, sophisticated input devices, an 'idle' routine and timers, a simple, cascading pop-up menu facility, utility routines to generate various solid and wire frame objects, support for bitmap and stroke fonts.

OpenGL Pipeline Architecture

A Simplified Model of the OpenGL Pipeline

Page 14: CGLab Manual 2012

14

Generally data flows from an application through the GPU to generate an image in the frame buffer. The application will provide vertices, which are collections of data that are composed to form geometric objects, to the OpenGL pipeline. The vertex processing stage uses a vertex shader to process each vertex, doing any computations necessary to determine where in the frame buffer each piece of geometry should go. The other shading stages like tessellation and geometry shading are also used for vertex processing.

After all the vertices for a piece of geometry are processed, the rasterizer determines which pixels in the frame buffer are affected by the geometry, and for each pixel, the fragment processing stage is employed, where the fragment shader runs to determine the final color of the pixel.

Primitives and Attributes

In OpenGL, as in other graphics libraries, objects in the scene are composed of geometric primitives, which themselves are described by vertices. A vertex in modern OpenGL is a collection of data values associated with a location in space. Vertices may be specified in 2D, 3D, or 4D. 2D coordinates are promoted to 3D by assigning a Z value of zero. 4D homogeneous coordinates are reduced to 3D by dividing x, y, and z by the w coordinate (if non-zero).

Optional vertex attributes are picked up from state if not specified per-vertex. The normal is a 3D vector perpendicular to the surface being described, and is used during lighting calculations. The color may be an RGBA value, or a Color Index, depending on the visual type of the window. Texture coordinates determine the mapping of a texture onto the vertex, and may be specified with 1, 2, 3, or 4 parameters. Edge flags are used to specify if the vertex is on a boundary of a surface. Material properties specify such things as reflectance, ambience, etc, and are used for lighting calculations. These vertex and attribute commands, as well as many other OpenGL commands, accept arguments either explicitly or through pointers. They also accept a variety of data types as arguments, such as ints, floats, doubles, bytes, unsigned ints and bytes, etc. Commands not associated with primitives are not allowed within Begin/End blocks. This allows increased optimization of primitive processing.

The model-view matrix, texture matrix, and projection matrix each affect the vertex and its attributes, and may be easily manipulated via transformations such as rotation, scaling, and translation. Lighting parameters, such as material properties, light source properties, and lighting model parameters affect lighting on a per-vertex basis.

Geometric primitives are defined in the problem domain and can be rotated, translated and scaled. OpenGL also supports image or raster primitives. These like an array of pixels lack geometric properties.

OpenGL only knows how to draw three things: points, lines, and triangles, but can use collections of the same type of primitive to optimize rendering.

Page 15: CGLab Manual 2012

15

OpenGL Primitive

Description Total Vertices for n Primitives

GL_POINTS Render a single point per vertex (points may be larger than a single pixel)

n

GL_LINES Connect each pair of vertices with a single line segment.

2n

GL_LINE_STRIP Connect each successive vertex to the previous one with a line segment.

n+1

GL_LINE_LOOP Connect all vertices in a loop of line segments. n

GL_TRIANGLES Render a triangle for each triple of vertices. 3n

GL_TRIANGLE_STRIP

Render a triangle from the first three vertices in the list, and then create a new triangle with the last two rendered vertices, and the new vertex.

n+2

GL_TRIANGLE_FAN Create triangles by using the first vertex in the list, and pairs of successive vertices. n+2

Clipping and ProjectionOnce a primitive has been assembled, it is subject to arbitrary clipping via user definable

clip planes. An OpenGL implementation must provide at least six, and they may be turned on and off independently by the user.

Points are either clipped in our out, depending on whether they fall inside or outside the half-space defined by the clip planes. Lines and polygons, however, may either be 100% clipped, 100% unclipped, or they may fall partially within the clip space. In this latter case, new vertices are automatically place on the clip boundary between pre-existing vertices. Vertex attributes are interpolated.

Page 16: CGLab Manual 2012

16

After clipping, vertices are transformed by the projection matrix (either perspective or orthogonal), and then clipped to the frustum (view space), following the same process as above. Finally, the vertices are mapped to the viewport (screen space).

RasterizationRasterization converts the above viewport-mapped primitives into fragments.

Fragments consist of pixel location in frame buffer, color, texture coordinates, and depth (z buffer). Depending on the shading mode, vertex attributes are either interpolated across the primitive to all fragments (smooth shading), or all fragments are assigned the same values based on one vertex's attributes (flat shading).

Rasterization is affected by the point and line widths, the line stipple sequence, and the polygon stipple pattern. Anti-aliasing may be enabled or disabled for each primitive type. If enabled, the alpha color value (if in RGBA mode) or color index (if in CI mode) are modified to reflect sub-pixel coverage.

Pixel rectangles and bitmaps are also rasterized, but they bypass the lighting and geometrical transformations. They are groups of values heading for the frame buffer. They can be scaled, offset, and mapped via lookup tables. The rasterization process produces a rectangle of fragments at a location controlled by the current raster position state variable. The size may be affected by the pixel zoom setting.

Bitmaps are similar to pixel rectangles, but the data is binary, only producing fragments when on. This is useful for drawing text in 3D space as part of a scene.

Frame BufferFragments produced by rasterization go to the frame buffer where they may be

displayed. The frame buffer is a rectangular array of n bit planes. The bit planes are organized into several logical buffers -- Color, Depth, Stencil, and Accumulation.

The color buffer contains the fragment's color info. The depth buffer contains the fragment's depth info, typically used for z-buffering

hidden surface removal. The stencil buffer can be associated with fragments that pass the conditional tests

described below and make it into the frame buffer. It can be useful for multiple-pass algorithms.

The accumulation buffer is also used for multiple-pass algorithms. It can average the values stored in the color buffer. Full-screen anti aliasing can be achieved by jittering the viewpoint. Depth of Field can be achieved by jittering the view angle. Motion blur can be achieved by stepping the scene in time.

Stereo and double-buffering may be supported under OpenGL, depending on the implementation. These would further divide the frame buffer into up to 4 sections -- front and back buffer, left and right. Other auxiliary buffers may be available on some implementations.

Page 17: CGLab Manual 2012

17

Per-fragment OperationsBefore being placed into the framebuffer, each fragment may be subjected to a series of

tests and modifications, each of which may be individually enabled, disabled, and controlled. These include stencil test, depth test, and blending.

The stencil test compares the value in the stencil buffer associated with the fragment with a reference value. If successful, the stencil value may be updated and the fragment proceeds to the next test. If it fails, the fragment is discarded, and the stencil value may be updated with another value.

The depth test is similar. It compares the fragment's depth with that currently in the depth buffer. If successful, the depth buffer is updated and the fragment proceeds to the next test. Otherwise, the fragment is discarded and the depth buffer is unchanged.

Blending mixes the fragment's color with the color already in the color buffer based on some blend function. This is used for anti aliasing and transparency.

EvaluatorsEvaluators allow the specification of polynomial functions of 1 or 2 variables which may

be used to determine a primitive's vertex coordinates, normal coordinates, texture coordinates, and/or color. A polynomial map based on a Bezier basis may be specified for any of these attributes individually.

Evaluators may either be used within primitives (generating individual vertices) or outside of primitives (generating entire primitives).

Display ListsDisplay lists encapsulate a group of commands so that they may be later issued as many

times as desired simply by calling the list by name. This allows increased optimization, server-side command caching, and simplified user programming. Display lists may be redefined, but may not be edited. They can be nested, however.

Feedback and SelectionThe default OpenGL mode is render mode, by which primitives are rendered to the

frame buffer. There are two other modes -- feedback and selection.

In feedback mode, primitives are intercepted after processing but before rasterization. It returns info about the primitives, such as vertex coordinates, texture coordinates, and color. This is useful for rendering to vector devices, such as pen plotters.

In selection mode, OpenGL returns a "hit" whenever a clipped primitive lies within the view frustum. This can be useful for picking primitives via the cursor.

OpenGL StateOpenGL can be viewed as a state–machine. “Setting state” is the process of initializing

the internal data that OpenGL uses to render the primitives. It can be as simple as setting up

Page 18: CGLab Manual 2012

18

the size of points and color that you want a vertex to be, to initializing multiple mipmap levels for texture mapping. The state can be changed using OpenGL functions which are of two types.

1. Primitive generating functions: These can cause the machine to produce a visible output. The state controls how vertices are processed and primitives appear.

2. State changing functions: These either change state inside the machine or return state information. Eg. Transformation functions, attribute functions.

Page 19: CGLab Manual 2012

19

Commonly Required OpenGL Functions

SPECIFYING SIMPLE GEOMETRY

void glVertex[234][sifd] (TYPE xcoordinate, TYPE ycoordinate, …)void glVertex[234]v (TYPE *coordinates)

Specifies the position of a vertex in 2,3, or 4 dimensions. The coordinates can be specified as short s, int i, float f, or double d. If the v is present, the argument is a pointer to n array containing the coordinates. glVertex commands are used within glBegin/glEnd pairs to specify point, line, and polygon vertices. The current color, normal, texture coordinates, and fog coordinate are associated with the vertex when glVertex is called.When only x and y are specified, z defaults to 0 and w defaults to 1. When x, y, and z are specified, w defaults to 1.

void glBegin(GLenum mode); Delimits the vertices of a primitive or a group of like primitives. mode: Specifies the primitive or primitives that will be created from vertices presented between glBegin and the subsequent glEnd. Ten symbolic constants are accepted. GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS, GL_QUAD_STRIP, andGL_POLYGON

void glEnd() terminates a list of vertices

void glutStrokeCharacter(void *font, int character); renders a stroke character using OpenGL.

font : Stroke font to use.character: Character to render (not confined to 8 bits).

The available fonts are:GLUT_STROKE_ROMAN

A proportionally spaced Roman Simplex font for ASCII characters 32 through 127. GLUT_STROKE_MONO_ROMANA mono-spaced spaced Roman Simplex font for ASCII characters 32 through 127.

void glRect[sifd] (TYPE x1, TYPE y1, TYPE x2, TYPE y2)void glRect[sifd]v(TYPE *v1, TYPE *v2)

Page 20: CGLab Manual 2012

20

Specify a two dimensional axis-aligned rectangle by the x, y coordinates of the diagonally opposite vertices (or pointers to the vertices) using the standard data types.

void glutSolidTeapot(GLdouble size);void glutWireTeapot(GLdouble size);size : Relative size of the teapot.

glutSolidTeapot and glutWireTeapot render a solid or wireframe teapot respectively. Both surface normals and texture coordinates for the teapot are generated. The teapot is generated with OpenGL evaluators.

ATTRIBUTES

void glPolygonMode(GLenum face, GLenum

mode);

select a polygon rasterization mode face

Specifies the polygons that mode applies to. Must be GL_FRONT for front-facing polygons, GL_BACK for back-facing polygons, or GL_FRONT_AND_BACK for front- and back-facing polygons.

modeSpecifies how polygons will be rasterized. Accepted values are GL_POINT, GL_LINE, and GL_FILL. The initial value is GL_FILL for both front- and back-facing polygons. The polygon mode affects only the final rasterization of polygons. In particular, a polygon's vertices are lit and the polygon is clipped and possibly culled before these modes are applied. Three modes are defined and can be specified in mode:

1. GL_POINT: Polygon vertices that are marked as the start of a boundary edge are drawn as points. Point attributes such as GL_POINT_SIZE and GL_POINT_SMOOTH control the rasterization of the points. Polygon rasterization attributes other than GL_POLYGON_MODE have no effect.

2. GL_LINE: Boundary edges of the polygon are drawn as line segments. They are treated as connected line segments for line stippling; the line stipple counter and pattern are not reset between segments.Line attributes such as GL_LINE_WIDTH and GL_LINE_SMOOTH control the rasterization of the lines. Polygon rasterization attributes other than GL_POLYGON_MODE have no effect.

3. GL_FILL: The interior of the polygon is filled. Polygon attributes such as GL_POLYGON_STIPPLE and GL_POLYGON_SMOOTH control the rasterization of the polygon.

Notes: Vertices are marked as boundary or nonboundary with an edge flag. Edge flags are generated internally by the GL when it decomposes polygons; they can be set explicitly using glEdgeFlag.

Page 21: CGLab Manual 2012

21

void glColor[34][b i f d ub us ui] (TYPE red,TYPE green,TYPE blue,TYPE alpha)void glColor[34][b I f d ub us ui]v (TYPE *color)

red, green, blue:Specify new red, green, and blue values for the current colorAlpha: Specifies a new alpha value for the current color. Included only in the four

argument glColor4 commands.v: Specifies a pointer to an array that contains red, green, blue, and (sometimes) alpha values.The initial value for the current color is (1, 1, 1, 1). The current color can be updated at any time. In particular, glColor can be called between a call to glBegin and the corresponding call to glEnd.

void glClearColor(GLClampf r, GLClampf g, GLClampf b, GLClampf a)

specifies the red, green, blue, and alpha values used by glClear to clear the color buffers. The initial values are all 0. Values specified by glClearColor are clamped to the range [0, 1].

void glIndexi[s i f d ub] (TYPE index)

set the current color index. index : Specifies a pointer to a one-element array that contains the new value for the current color index.

void glutSetColor(int cell,GLfloat red, GLfloat green, GLfloat blue);

cell: Color cell index (starting at zero).Sets the cell color index colormap entry of the current window's logical colormap for the layer in use with the color specified by red, green, and blue. The layer in use of the current window should be a color index window. cell should be zero or greater and less than the total number of colormap entries for the window. If the layer in use's colormap was copied by reference, a glutSetColor call will force the duplication of the colormap.

void glPointSize(GLfloat size);

Size: Specifies the diameter of rasterized points. The initial value is 1.glPointSize specifies the rasterized diameter of both aliased and antialiased points. Using a point size other than 1 has different effects, depending on whether point antialiasing is enabled. To enable and disable point antialiasing, call glEnable and glDisable with argument GL_POINT_SMOOTH. Point antialiasing is initially disabled.

void glPushAttrib(GLbitfield mask);

Mask: Specifies a mask that indicates which attributes to save. Values for mask are listed below.

glPushAttrib takes one argument, a mask that indicates which groups of state variables to save on the attribute stack. Symbolic constants are used to set bits in the mask.mask is typically

Page 22: CGLab Manual 2012

22

constructed by specifying the bitwise-or of several of these constants together. The special mask GL_ALL_ATTRIB_BITS can be used to save all stackable states.

void glPopAttrib(void);

glPopAttrib restores the values of the state variables saved with the last glPushAttrib command. Those not saved are left unchanged.It is an error to push attributes onto a full stack or to pop attributes off an empty stack. In either case, the error flag is set and no other change is made to GL state. Initially, the attribute stack is empty. The depth of the attribute stack depends on the implementation, but it must be at least 16.Notes: Not all values for GL state can be saved on the attribute stack. For example, render mode state, and select and feedback state cannot be saved. Client state must be saved with glPushClientAttrib.

WORKING WITH WINDOW SYSTEM

void glFlush(void);Different GL implementations buffer commands in several different locations, including network buffers and the graphics accelerator itself. glFlush empties all of these buffers, causing all issued commands to be executed as quickly as they are accepted by the actual rendering engine. Though this execution may not be completed in any particular time period, it does complete in finite time.

void glutInit(int *argcp, char **argv); glutInit is used to initialize the GLUT library.argcp

A pointer to the program's unmodified argc variable from main. Upon return, the value pointed to by argcp will be updated, because glutInit extracts any command line options intended for the GLUT library.

argvThe program's unmodified argv variable from main. Like argcp, the data for argv will be updated because glutInit extracts any command line options understood by the GLUT library.

glutInit will initialize the GLUT library and negotiate a session with the window system. During this process, glutInit may cause the termination of the GLUT program with an error message to the user if GLUT cannot be properly initialized. Examples of this situation include the failure to connect to the window system, the lack of window system support for OpenGL, and invalid command line options.glutInit also processes command line options, but the specific options parse are window system dependent.

Page 23: CGLab Manual 2012

23

int glutCreateWindow(char *name);name: ASCII character string for use as window name.glutCreateWindow creates a top-level window. The name will be provided to the window system as the window's name. The intent is that the window system will label the window with the name. Implicitly, the current window is set to the newly created window.Each created window has a unique associated OpenGL context. State changes to a window's associated OpenGL context can be done immediately after the window is created. The display state of a window is initially for the window to be shown. Until glutMainLoop is called, rendering to a created window is ineffective because the window can not yet be displayed.The value returned is a unique small integer identifier for the window. The range of allocated identifiers starts at one. This window identifier can be used when calling glutSetWindow.

void glutInitDisplayMode(unsigned int mode);

glutInitDisplayMode sets the initial display mode.

mode: Display mode, normally the bitwise OR-ing of GLUT display mode bit masks below:

GLUT_RGBA: Bit mask to select an RGBA mode window. This is the default if either GLUT_RGBA nor GLUT_INDEX are specified.GLUT_RGB: An alias for GLUT_RGBA.GLUT_INDEX: Bit mask to select a color index mode window. This overrides GLUT_RGBA if it is also specified.GLUT_SINGLE: Bit mask to select a single buffered window. This is the default if neither GLUT_DOUBLE or GLUT_SINGLE are specified.GLUT_DOUBLE: Bit mask to select a double buffered window. This overrides GLUT_SINGLE if it is also specified.GLUT_ACCUM: Bit mask to select a window with an accumulation buffer.GLUT_ALPHA: Bit mask to select a window with an alpha component to the color buffer(s).GLUT_DEPTH: Bit mask to select a window with a depth buffer.GLUT_STENCIL: Bit mask to select a window with a stencil buffer.Also used are GLUT_MULTISAMPLE, GLUT_STEREO, GLUT_LUMINANCE

void glutInitWindowSize(int width, int height);void glutInitWindowPosition(int x, int y);

glutInitWindowPosition and glutInitWindowSize set the initial position and size respectively.Width: Width in pixels.Height: Height in pixels.X: Window X location in pixels.Y: Window Y location in pixels.

Page 24: CGLab Manual 2012

24

Windows created by glutCreateWindow will be requested to be created with the current initial window position and size. The initial value of the initial window position GLUT state is -1 and -1. If either the X or Y component to the initial window position is negative, the actual window position is left to the window system to determine. The initial value of the initial window size GLUT state is 300 by 300. The initial window size components must be greater than zero.

void glViewport(Glint x, GLint y, GLsizei width, GLsizei height);

Sets the viewport.

x, y:Specify the lower left corner of the viewport rectangle, in pixels. The initial value is (0,0).

width, height: Specify the width and height of the viewport. When a GL context is first attached to a window, width and height are set to the dimensions of that window.

void glutMainLoop(void);glutMainLoop enters the GLUT event processing loop. This routine should be called at most once in a GLUT program. Once called, this routine will never return. It will call as necessary any callbacks that have been registered.

void glutDisplayFunc(void (*func)(void));

func: The new display callback function.

glutDisplayFunc sets the display callback for the current window. GLUT determines when the display callback should be triggered based on the window's redisplay state. The redisplay state for a window can be either set explicitly by calling glutPostRedisplay or implicitly as the result of window damage reported by the window system. Multiple posted redisplays for a window are coalesced by GLUT to minimize the number of display callbacks called.

void glutPostRedisplay(void);

Mark the normal plane of current window as needing to be redisplayed. The next iteration through glutMainLoop, the window's display callback will be called to redisplay the window's normal plane. Multiple calls to glutPostRedisplay before the next display callback opportunity generates only a single redisplay callback.

void glutSwapBuffers(void);

glutSwapBuffers swaps the buffers of the current window if double buffered. Specifically, glutSwapBuffers promotes the contents of the back buffer of the layer in use of the current window to become the contents of the front buffer. The contents of the back buffer then become undefined.

void glutSetWindow(int win);int glutGetWindow(void);

Page 25: CGLab Manual 2012

25

win: Identifier of GLUT window to make the current window.glutSetWindow sets the current window; glutGetWindow returns the identifier of the current window.If no windows exist or the previously current window was destroyed, glutGetWindow returns zero.

INTERACTION

void glutMouseFunc(void (*func)(int button, int state, int x, int y));func:The new mouse callback function.

glutMouseFunc sets the mouse callback for the current window. When a user presses and releases mouse buttons in the window, each press and each release generates a mouse callback. The button parameter is one of GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, or GLUT_RIGHT_BUTTON. The state parameter is either GLUT_UP or GLUT_DOWN indicating whether the callback was due to a release or press respectively. The x and y callback parameters indicate the window relative coordinates when the mouse button state changed. Passing NULL to glutMouseFunc disables the generation of mouse callbacks.

void glutReshapeFunc(void (*func)(int width, int height));

glutReshapeFunc sets the reshape callback for the current window. The reshape callback is triggered when a window is reshaped, immediately before a window's first display callback after a window is created. The width and height parameters of the callback specify the new window size in pixels. Before the callback, the current windowis set to the window that has been reshaped.If a reshape callback is not registered for a window or NULL is passed to glutReshapeFunc (to deregister a previously registered callback), the default reshape callback is used. This default callback will simply call glViewport(0,0,width,height) on the normal plane (and on the overlay if one exists).

void glutKeyboardFunc(void (*func)(unsigned char key, int x, int y));

glutKeyboardFunc sets the keyboard callback for the current window. When a user types into the window, each key press generating an ASCII character will generate a keyboard callback. The x and y callback parameters indicate the mouse location in window relative coordinates when the key was pressed. When a new window is created, no keyboard callback is initially registered, and ASCII key strokes in the window are ignored. During a keyboard callback, glutGetModifiers may be called to determine the state of modifier keys when the keystroke generating the callback occurred.

Page 26: CGLab Manual 2012

26

void glutIdleFunc(void (*func)(void));glutIdleFunc sets the global idle callback to be func so a GLUT program can perform background processing tasks or continuous animation when window system events are not being received.

int glutCreateMenu(void (*func)(int value));glutCreateMenu creates a new pop-up menu and returns a unique small integer identifier starting from 1. Implicitly, the current menu is set to the newly created menu. This menu identifier can be used when calling glutSetMenu.

void glutSetMenu(int menu);int glutGetMenu(void);menu: The identifier of the menu to make the current menu.glutSetMenu sets the current menu; glutGetMenu returns the identifier of the current menu. If no menus exist or the previous current menu was destroyed, glutGetMenu returns zero.

void glutAddMenuEntry(char *name, int value);name:ASCII character string to display in the menu entry.value:Value to return to the menu's callback function if the menu entry is selected.glutAddMenuEntry adds a menu entry to the bottom of the current menu. The string name will be displayed for the newly added menu entry. If the menu entry is selected by the user, the menu's callback will be called passing value as the callback's parameter.

void glutAddSubMenu(char *name, int menu);name: ASCII character string to display in the menu item from which to cascade the sub-menu.Menu: Identifier of the menu to cascade from this sub-menu menu item.glutAddSubMenu adds a sub-menu trigger to the bottom of the current menu. The string name will be displayed for the newly added sub-menu trigger. If the sub-menu trigger is entered, the sub-menu numbered menu will be cascaded, allowing sub-menu menu items to be selected.

void glutAttachMenu(int button);void glutDetachMenu(int button);button:The button to attach a menu or detach a menu,glutAttachMenu attaches a mouse button for the current window to the identifier of the current menu; glutDetachMenu detaches an attached mouse button from the current window. By attaching a menu identifier to a button, the named menu will be popped up when the user presses the specified button. Button should be one of GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, and GLUT_RIGHT_BUTTON.

Page 27: CGLab Manual 2012

27

______________________________________________________________________________

void glutTimerFunc(unsigned int msecs, void (*func)(int value), value);glutTimerFunc registers the timer callback func to be triggered in at least msecs milliseconds. The value parameter to the timer callback will be the value of the value parameter to glutTimerFunc. GLUT attempts to deliver the timer callback as soon as possible after the expiration of the callback's time interval.

void glutMotionFunc(void (*func)(int x, int y));void glutPassiveMotionFunc(void (*func)(int x, int y));glutMotionFunc and glutPassiveMotionFunc set the motion and passive motion callback respectively for the current window. The motion callback for a window is called when the mouse moves within the window while one or more mouse buttons are pressed. The passive motion callback for a window is called when the mouse moves within the window while no mouse buttons are pressed.The x and y callback parameters indicate the mouse location in window relative coordinates.

ENABLING FEATURES

void glEnable(GLenum cap);void glDisable(GLenum cap);cap: Specifies a symbolic constant indicating a GL capability.glEnable and glDisable enable and disable various capabilities. Both glEnable and glDisable take a single argument, cap, which can assume one of the following values, among many others:GL_BLEND: If enabled, blend the computed fragment color values with the values in the color buffers. GL_CLIP_PLANEi: If enabled, clip geometry against user-defined clipping plane i. GL_COLOR_LOGIC_OP: If enabled, apply the currently selected logical operation to the computed fragment color and color buffer values..GL_COLOR_MATERIAL: If enabled, have one or more material parameters track the current color. GL_COLOR_SUM: If enabled and no fragment shader is active, add the secondary color value to the computed fragment color. GL_COLOR_TABLE: If enabled, perform a color table lookup on the incoming RGBA color values.GL_CULL_FACE: If enabled, cull polygons based on their winding in window coordinates. GL_DEPTH_TEST: If enabled, do depth comparisons and update the depth buffer. Note that even if the depth buffer exists and the depth mask is non-zero, the depth buffer is not updated if the depth test is disabled.GL_DITHER: If enabled, dither color components or indices before they are written to the color buffer.

Page 28: CGLab Manual 2012

28

GL_FOG: If enabled and no fragment shader is active, blend a fog color into the post-texturing color. GL_LIGHTING: If enabled and no vertex shader is active, use the current lighting parameters to compute the vertex color or index. Otherwise, simply associate the current color or index with each vertex.GL_LINE_SMOOTH: If enabled, draw lines with correct filtering. Otherwise, draw aliased lines.GL_LINE_STIPPLE: If enabled, use the current line stipple pattern when drawing lines. GL_POLYGON_SMOOTH: If enabled, draw polygons with proper filtering. Otherwise, draw aliased polygons. For correct antialiased polygons, an alpha buffer is needed and the polygons must be sorted ront to back.GL_POLYGON_STIPPLE: If enabled, use the current polygon stipple pattern when rendering polygons.

TRANSFORMATIONS

void glMatrixMode(GLenum mode);

mode: Specifies which matrix stack is the target for subsequent matrix operations. Three values are accepted: GL_MODELVIEW, GL_PROJECTION, and GL_TEXTURE. The initial value is GL_MODELVIEW. glMatrixMode sets the current matrix mode. mode can assume one of four values: GL_MODELVIEW, GL_PROJECTION, GL_TEXTURE, GL_COLOR. To find out which matrix stack is currently the target of all matrix operations, call glGet with argument GL_MATRIX_MODE. The initial value is GL_MODELVIEW.

void glLoadIdentity(void):

glLoadIdentity replaces the current matrix with the identity matrix. It is semantically equivalent to calling glLoadMatrix with the identity matrix but in some cases it is more efficient.

void glPushMatrix (void); void glPopmatrix(void);

Push and pop the current matrix. There is a stack of matrices for each of the matrix modes. In GL_MODELVIEW mode, the stack depth is at least 32. In the other modes, GL_COLOR, GL_PROJECTION, and GL_TEXTURE, the depth is at least 2. The current matrix in any mode is the matrix on the top of the stack for that mode. Initially, each of the stacks contains one matrix, an identity matrix.

void glRotate[df] (GLDouble angle, GLDouble x, GLDouble y, GLDouble z);

multiply the current matrix by a rotation matrix

Page 29: CGLab Manual 2012

29

angle - Specifies the angle of rotation, in degrees.x, y, z- Specify the x, y, and z coordinates of a vector, respectively.

glRotate produces a rotation of angle degrees around the vector x y z .

void glScale[df] ( GLDouble x, GLDouble y, GLDouble z);

glScale multiply the current matrix by a general scaling matrix

x, y, z Specify scale factors along the x, y, and z axes, respectively. glScale produces a nonuniform scaling along the x, y, and z axes. The three parameters indicate the desired scale factor along each of the three axes.

void glTranslate[df] ( GLDouble x, GLDouble y, GLDouble z);

glTranslate multiply the current matrix by a translation matrix. x, y, z: Specify the x, y, and z coordinates of a translation vector.

void glMultMatrixd(const GLdouble m);void glMultMatrixf(const GLfloat m);

glMultMatrix multiplies the current matrix with the one specified using m, and replaces the current matrix with the product.

void glLoadMatrixd(const GLdouble m);void glLoadMatrixf(const GLfloat m);

glLoadMatrix replace the current matrix with the specified matrix. m specifies a pointer to 16 consecutive values, which are used as the elements of a 4 x 4 column-major matrix. The current matrix is the projection matrix, modelview matrix, or texture matrix, depending on the current matrix mode.

VIEWINGvoid glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble nearVal, GLdouble farVal);

glOrtho describes a transformation that produces a parallel projection. It multiplies the current matrix with an orthographic matrix. left, right specify the coordinates for the left and right vertical clipping planes. bottom, top specify the coordinates for the bottom and top horizontal clipping planes. nearVal, farVal specify the distances to the nearer and farther depth clipping planes. These values are negative if the plane is to be behind the viewer.

Page 30: CGLab Manual 2012

30

void gluOrtho2D (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top);

define a 2D orthographic projection matrix. left, right - Specify the coordinates for the left and right vertical clipping planes. bottom, top - Specify the coordinates for the bottom and top horizontal clipping planes. gluOrtho2D sets up a two-dimensional orthographic viewing region. This is equivalent to calling glOrtho with near = -1 and far = 1.

void gluLookAt(GLdouble eyeX, eyeY,eyeZ, centerX, centerY, centerZ, upX, upY, upZ);

eyeX, eyeY, eyeZ - Specifies the position of the eye point.centerX, centerY, centerZ - Specifies the position of the reference point.upX, upY, upZ - Specifies the direction of the up vector.

gluLookAt creates a viewing matrix derived from an eye point, a reference point indicating the center of the scene, and an UP vector.

void glFrustum(GLdouble left,, GLdouble right, GLdouble bottom, GLdouble top, GLdouble nearVal, GLdouble farVal);

glFrustum describes a perspective matrix that produces a perspective projection by multiplying the current matrix by a perspective matrix. left, right - Specify the coordinates for the left and right vertical clipping planes. bottom, top - Specify the coordinates for the bottom and top horizontal clipping planes. nearVal, farVal - Specify the distances to the near and far depth clipping planes. Both distances must be positive.

void gluPerspective(GLDouble fovy, GLDouble aspect, GLDouble zNear, GLDouble zFar);

gluPerspective specifies a viewing frustum into the world coordinate system and sets up a perspective projection matrix. Fovy specifies the field of view angle, in degrees, in the y direction. Aspect specifies the aspect ratio that determines the field of view in the x direction. The aspect ratio is the ratio of x (width) to y (height). zNear specifies the distance from the viewer to the near clipping plane (always positive). zFar specifies the distance from the viewer to the far clipping plane (always positive).

DISPLAY LISTS

glNewList(GLuint list, GLenum mode); void glEndList( void);

Create or replace a display list. List specifies the display-list name. mode Specifies the compilation mode, which can be GL_COMPILE or GL_COMPILE_AND_EXECUTE. Display lists are groups of GL commands that have been stored for subsequent execution list, in the order issued, until glEndList is called. glNewList has two arguments. The first argument, list, is a positive integer that becomes the unique name for the display list. Names can be created and

Page 31: CGLab Manual 2012

31

reserved withglGenLists and tested for uniqueness with glIsList. The second argument, mode, is a symbolic constant that can assume one of two values: GL_COMPILE - Commands are merely compiled. GL_COMPILE_AND_EXECUTE - Commands are executed as they are compiled into the display list.

void glCallList(GLuint list);

glCallList causes the named display list to be executed. The commands saved in the display list are executed in order, just as if they were called without using a display list. If list has not been defined as a display list, glCallList is ignored. Use glPushAttrib, glPopAttrib, glPushMatrix, and glPopMatrix to preserve GL state across glCallList calls.

void glCallLists(Glsizei n, GLenum type, const GLvoid *lists);

execute a list of display lists, n specifies the number of display lists to be executed, type specifies the type of values in lists. Symbolic constants GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT, GL_FLOAT, GL_2_BYTES, GL_3_BYTES, and GL_4_BYTESare accepted. Lists specifies the address of an array of name offsets in the display list. The pointer type is void because the offsets can be bytes, shorts, ints, or floats, depending on the value of type.

GLuint glGenLists( GLsizei range);

generate a contiguous set of empty display lists. Range specifies the number of contiguous empty display lists to be generated.

PICKING

GLint glRenderMode(GLenum mode);

set rasterization mode. Mode specifies the rasterization mode. Three values are accepted: GL_RENDER, GL_SELECT, and GL_FEEDBACK. The initial value is GL_RENDER.

GL_RENDER: Render mode. Primitives are rasterized, producing pixel fragments, which are written into the frame buffer. This is the normal mode and also the default mode.

GL_SELECT: Selection mode. No pixel fragments are produced, and no change to the frame buffer contents is made. Instead, a record of the names of primitives that would have been drawn if the render mode had been GL_RENDER is returned in a select buffer, which must be created before selection mode is entered.

GL_FEEDBACK: Feedback mode. No pixel fragments are produced, and no change to the frame buffer contents is made. Instead, the coordinates and attributes of vertices that would have been drawn if the render mode had been GL_RENDER is returned in a feedback buffer, which must be created feedback mode is entered.

Page 32: CGLab Manual 2012

32

The return value of glRenderMode is determined by the render mode at the time glRenderMode is called, rather than by mode. The values returned for the three render modes are as follows:GL_RENDER: 0.GL_SELECT: The number of hit records transferred to the select buffer.GL_FEEDBACK: The number of values (not vertices) transferred to the feedback buffer.

void glSelectBuffer(GLsizei size, GLuint buffer)

establish a buffer for selection mode values. Size - specifies the size of buffer. Buffer- returns the selection data. glSelectBuffer has two arguments: buffer is a pointer to an array of unsigned integers, and size indicates the size of the array. buffer returns values from the name stack when the rendering mode is GL_SELECT. glSelectBuffer must be issued before selection mode is enabled, and it must not be issued while the rendering mode is GL_SELECT.

A programmer can use selection to determine which primitives are drawn into some region of a window. The region is defined by the current modelview and perspective matrices. In selection mode, no pixel fragments are produced from rasterization. Instead, if a primitive or a raster position intersects the clipping volume defined by the viewing frustum and the user-defined clipping planes, this primitive causes a selection hit. (With polygons, no hit occurs if the polygon is culled.) When a change is made to the name stack, or when glRenderMode is called, a hit record is copied to buffer if any hits have occurred since the last such event (name stack change or glRenderMode call). The hit record consists of the number of names in the name stack at the time of the event, followed by the minimum and maximum depth values of all vertices that hit since the previous event, followed by the name stack contents, bottom name first.

An internal index into buffer is reset to 0 whenever selection mode is entered. Each time a hit record is copied into buffer, the index is incremented to point to the cell just past the end of the block of names\(emthat is, to the next available cell If the hit record is larger than the number of remaining locations in buffer, as much data as can fit is copied, and the overflow flag is set. If the name stack is empty when a hit record is copied, that record consists of 0 followed by the minimum and maximum depth values.

glBegin/glEnd primitives and calls to glRasterPos can result in hits. glWindowPos will always generate a selection hit.

void glInitNames(void);

initialize the name stack. The name stack is used during selection mode to allow sets of rendering commands to be uniquely identified. It consists of an ordered set of unsigned integers. glInitNames causes the name stack to be initialized to its default empty state. The name stack is always empty while the render mode is not GL_SELECT. Calls to glInitNames while the render mode is not GL_SELECT are ignored.

Page 33: CGLab Manual 2012

33

void glPushName(GLuint name); void glPopName(void);

push and pop the name stackname- Specifies a name that will be pushed onto the name stack.

void glLoadName(GLuint name); load a name onto the name stackname - specifies a name that will replace the top value on the name stack.

void gluPickMatrix(GLdouble x, GLdouble y, GLdouble del, GLdouble delY, Glint viewport);

define a picking region, x, y - specify the center of a picking region in window coordinates. delX, delY - specify the width and height, respectively, of the picking region in window coordinates. Viewport specifies the current viewport.

gluPickMatrix creates a projection matrix that can be used to restrict drawing to a small region of the viewport. Use gluPickMatrix to restrict drawing to a small region around the cursor. Then, enter selection mode (with glRenderMode) and rerender the scene. All primitives that would have been drawn near the cursor are identified and stored in the selection buffer.

LIGHTING

void glLight[fi](GLenum light, GLenum pnmae, GL[float] [int] param);

set light source parameters

light : Specifies a light. The number of lights depends on the implementation, but at least eight lights are supported. They are identified by symbolic names of the form GL_LIGHTi, where i ranges from 0 to the value of GL_MAX_LIGHTS - 1.Pname: Specifies a single-valued light source parameter for light. GL_SPOT_EXPONENT, GL_SPOT_CUTOFF, GL_CONSTANT_ATTENUATION, GL_LINEAR_ATTENUATION, and GL_QUADRATIC_ATTENUATION are accepted.Param: Specifies the value that parameter pname of light source light will be set to.

void glLight[fi]v(GLenum light, GLenum pname, const [GLfloat Glint] *params);

light : Specifies a light. The number of lights depends on the implementation, but at least eight lights are supported. They are identified by symbolic names of the form GL_LIGHTi, where i ranges from 0 to the value of GL_MAX_LIGHTS - 1.Pname: Specifies a light source parameter for light. GL_AMBIENT, GL_DIFFUSE, GL_SPECULAR, GL_POSITION, GL_SPOT_CUTOFF, GL_SPOT_DIRECTION, GL_SPOT_EXPONENT, GL_CONSTANT_ATTENUATION, GL_LINEAR_ATTENUATION, and GL_QUADRATIC_ATTENUATION are accepted.

Page 34: CGLab Manual 2012

34

Params: Specifies a pointer to the value or values that parameter pname of light source light will be set to.

void glLightModelf(GLenum pname, GLfloat param);void glLightModeli(GLenum pnmae, Glint param);

void glLightModelfv(GLenum pname, const GLfloat *params);void glLightModeliv(GLenum pnmae, const Glint *params);

set the lighting model parameterspname: Specifies a single-valued lighting model parameter. GL_LIGHT_MODEL_LOCAL_VIEWER, GL_LIGHT_MODEL_COLOR_CONTROL, and GL_LIGHT_MODEL_TWO_SIDEare accepted.Param: Specifies the value that param will be set to.Params: specifies a pointer to the value or values that params will be set to.

void glMaterialf(GLenum face, GLenum pname, GLfloat param); void glMateriali(GLenum face, GLenum pnmae, Glint param);

void glMaterialfv(GLenum face, GLenum pname, const GLfloat *params); void glMaterialiv(GLenum face, GLenum pnmae, Glint* params);

-specify material parameters for the lighting modelFace: Specifies which face or faces are being updated. Must be one of GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK.Pname: Specifies the single-valued material parameter of the face or faces that is being updated. Must be GL_SHININESS.Param: Specifies the value that parameter GL_SHININESS will be set to.

VERTEX ARRAYSvoid glEnableClientState(GLenum cap); void glDisableClientState(GLenum cap);

enable or disable client-side capability. Cap: Specifies the capability to enable. Symbolic constants GL_COLOR_ARRAY, GL_EDGE_FLAG_ARRAY, GL_FOG_COORD_ARRAY, GL_INDEX_ARRAY, GL_NORMAL_ARRAY, GL_SECONDARY_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY, and GL_VERTEX_ARRAY are accepted.

void glColorPointer(Glint size, GLenum type, GLsizei stride, const GLvoid *pointer);

Define an array of colorsSize: Specifies the number of components per color. Must be 3 or 4. The initial value is 4.

Page 35: CGLab Manual 2012

35

Type: Specifies the data type of each color component in the array. Symbolic constants GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT, GL_FLOAT, and GL_DOUBLE are accepted. The initial value is GL_FLOAT.Stride: Specifies the byte offset between consecutive colors. If stride is 0, the colors are understood to be tightly packed in the array. The initial value is 0.Pointer: Specifies a pointer to the first component of the first color element in the array. The initial value is 0.

void glVertexPointer Glint size, GLenum type, GLsizei stride, const GLvoid *pointer);

define an array of vertex data

size: Specifies the number of coordinates per vertex. Must be 2, 3, or 4. The initial value is 4.Type: Specifies the data type of each coordinate in the array. Symbolic constants GL_SHORT, GL_INT, GL_FLOAT, or GL_DOUBLE are accepted. The initial value is GL_FLOAT.Stride: Specifies the byte offset between consecutive vertices. If stride is 0, the vertices are understood to be tightly packed in the array. The initial value is 0.Pointer: Specifies a pointer to the first coordinate of the first vertex in the array. The initial value is 0.

void glTexCoordPointer(Glint size, GLenum type, GLsizei stride, const GLvoid *pointer);

define an array of texture coordinates

size: Specifies the number of coordinates per array element. Must be 1, 2, 3, or 4. The initial value is 4.Type: Specifies the data type of each texture coordinate. Symbolic constants GL_SHORT, GL_INT, GL_FLOAT, or GL_DOUBLE are accepted. The initial value is GL_FLOAT.Stride: Specifies the byte offset between consecutive texture coordinate sets. If stride is 0, the array elements are understood to be tightly packed. The initial value is 0.Pointer: Specifies a pointer to the first coordinate of the first texture coordinate set in the array. The initial value is 0.

void glNormalPointer(GLenum type, GLsizei stride, const GLvoid *pointer);

define an array of normals

void glNormal3b(GLbyte nx, GLbyte ny, GLbyte nz);

set the current normal vector, also available for GLdouble, GLfloat, GLshort, GLint

nx, ny, nz: Specify the x, y, and z coordinates of the new current normal. The initial value of the current normal is the unit vector, (0, 0, 1).void glNormal3bv(const GLbyte *v);

Page 36: CGLab Manual 2012

36

void glNormal3dv( const GLdouble *v);void glNormal3fv(const GLfloat * v);void glNormal3iv(const GLint *v);void glNormal3sv(const GLshort *v);

v: Specifies a pointer to an array of three elements: the x, y, and z coordinates of the new current normal.

glDrawElements - render primitives from array data

void glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);

mode: Specifies what kind of primitives to render. Symbolic constants GL_POINTS, GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_TRIANGLES, GL_QUAD_STRIP, GL_QUADS, and GL_POLYGON are accepted.Count: Specifies the number of elements to be rendered.Type: Specifies the type of the values in indices. Must be one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, or GL_UNSIGNED_INT.Indices: Specifies a pointer to the location where the indices are stored.

Page 37: CGLab Manual 2012

37

Sample Code for Suggested Programming Exercises

Lab 1

Create a simple house with windows and door open. Write the reshape function so that the house is not distorted when the display window is resized.

Program Code:

#include<stdlib.h>#include<GL/glut.h>#include<stdio.h>void myinit(){

glClearColor(1.0,1.0,1.0,1.0);}void drawhouse(){

glColor3f(1.0,0.0,0.0);glBegin(GL_POLYGON);

glVertex2f(0.0,0.0);glVertex2f(0.0,10.0);glVertex2f(10.0,10.0);glVertex2f(10.0,0.0);

glEnd();glColor3f(0.0,1.0,0.0);glBegin(GL_POLYGON);

glVertex2f(0.0,10.0);glVertex2f(10.0,10.0);glVertex2f(5.0,15.0);

glEnd();glColor3f(0.0,0.0,1.0);glBegin(GL_POLYGON);

glVertex2f(2.5,0.0);glVertex2f(7.5,0.0);glVertex2f(7.5,2.5);glVertex2f(2.5,2.5);

glEnd();glutSwapBuffers();

}

void resizeHandler( int w, int h ){if( h==0 ) h=1;float aspecRatio = (float)w / (float)h;

glViewport( 0, 0, w, h );

glMatrixMode( GL_PROJECTION );glLoadIdentity( );

gluPerspective( 30.0, aspecRatio, 3.0, 8888.0 );

Page 38: CGLab Manual 2012

38

gluLookAt( 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 );

return;}

void display(){

glClear(GL_COLOR_BUFFER_BIT);drawhouse();

}

void main(int argc, char *argv[]){

glutInit(&argc,argv);glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(0,0);glutCreateWindow("House");glutDisplayFunc(display);glutReshapeFunc(resizeHandler);myinit();glutMainLoop();

}

Output:

Create a chessboard.

#include<stdio.h>#include<stdafx.h>#include<GL/glut.h>

void display(void){

int i,j;glClear(GL_COLOR_BUFFER_BIT);glBegin(GL_QUADS);for(i=0;i<8;i++){

for(j=0;j<8;j++){if((i+j)%2==0)

glColor3f(0.0,0.0,0.0);else

glColor3f(1.0,1.0,1.0);

Page 39: CGLab Manual 2012

39

glVertex2f(i*5,j*5);glVertex2f((i+1)*5,j*5);glVertex2f((i+1)*5,(j+1)*5);glVertex2f(i*5,(j+1)*5);}

}glEnd();glFlush();

}void myinit(){

glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0, 40.0, 0.0, 40.0);glClearColor (1.0, 1.0, 1.0,1.0);glColor3f(0.0,0.0,0.0);

}int main(int argc, char **argv){

glutInit(&argc, argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500, 500);glutCreateWindow("Chess");glutDisplayFunc(display);myinit();

glutMainLoop();}

Output:

Create a gingerbread man using iterated function system. Use the equations q.x = M(1 + 2L) - p.y + |p.x –LM| and q.y = p.x.

#include<stdlib.h>#include <GL/glut.h>#include <stdio.h>

void myinit(){

/* attributes */

Page 40: CGLab Manual 2012

40

glClearColor(1.0, 1.0, 1.0, 1.0); /* white background */glColor3f(1.0, 1.0, 0.0); /* draw in red */

/* set up viewing *//* 500 x 500 window with origin lower left */

glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(600,0,600,0);glMatrixMode(GL_MODELVIEW);

}int mold(int a){

if(a>0)return a;

elsereturn (-a);

}

void func(int *p,int k){

int m=40,l=3;int q[2];if(k==0){

return;}q[0]=m*(1+2*l)-p[1]+mold((p[0]-l*m));q[1]=p[0];

//int rand(); /* standard random number generator *///GLfloat p[2] ={7.5,5.0}; /* An arbitrary initial point inside traingle */

/*clear the window */ /* compute and plots 5000 new points */

glPointSize(4.0);glColor3f(1,0,0);glBegin(GL_POINTS);glVertex2iv(q);glEnd();glFlush();func(q,k-1);

}

void display( void ){

int p[2]={115,121};glClear(GL_COLOR_BUFFER_BIT);func(p,3000);

}

void main(int argc, char** argv){

/* Standard GLUT initialization */

glutInit(&argc,argv);

Page 41: CGLab Manual 2012

41

glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); /* default, not needed */glutInitWindowSize(600,600); /* 500 x 500 pixel window */glutInitWindowPosition(0,0); /* place window top left on display */glutCreateWindow("Ginger breadman"); /* window title */glutDisplayFunc(display); /* display callback invoked when window opened */myinit(); /* set attributes */glutMainLoop(); /* enter event loop */

}

Output:

Page 42: CGLab Manual 2012

42

Lab 2

Create 2D Sierpinski gasket by plotting points (IFS)

/* gasket.c */#include<stdio.h>#include<stdlib.h>#include <GL/glut.h>

void myinit(void){

glClearColor(1.0, 1.0, 1.0, 1.0); /* white background */glColor3f(0.5, 0.5, 0.0); /* draw in red */

/* set up viewing *//* 500 x 500 window with origin lower left */

glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0, 500.0, 0.0, 500.0);glMatrixMode(GL_MODELVIEW);

}

void display( void ){

/* define a point data type */

typedef GLfloat point2[2]; point2 vertices[3]={{0.0,0.0},{250.0,500.0},{500.0,0.0}}; int i, j, k;int rand(); point2 p ={75.0,50.0};

glClear(GL_COLOR_BUFFER_BIT); /*clear the window */

/* compute and plots 5000 new points */for( k=0; k<5000; k++){

j=rand()%3; /* pick a vertex at random */

/* Compute point halfway between selected vertex and old point */

p[0] = (p[0]+vertices[j][0])/2.0; p[1] = (p[1]+vertices[j][1])/2.0;

/* plot new point */

glBegin(GL_POINTS);glVertex2fv(p); glEnd();

}glFlush(); /* clear buffers */}

Page 43: CGLab Manual 2012

43

void main(int argc, char** argv){

/* Standard GLUT initialization */

glutInit(&argc,argv);glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("Sierpinski Gasket"); glutDisplayFunc(display); myinit(); glutMainLoop(); }

Output

Create 2D Sierpinski gasket by recursive subdivision of triangle.

#include<stdlib.h>#include <GL/glut.h>#include <stdio.h>

/* initial triangle */

GLfloat v[3][2]={{-1.0, -0.58}, {1.0, -0.58}, {0.0, 1.15}};

int n;

void triangle( GLfloat *a, GLfloat *b, GLfloat *c){

Page 44: CGLab Manual 2012

44

glVertex2fv(a);glVertex2fv(b);glVertex2fv(c);

}

void divide_triangle(GLfloat *a, GLfloat *b, GLfloat *c, int m){

/* triangle subdivision using vertex numbers */

GLfloat v0[2], v1[2], v2[2];int j;if(m>0){

for(j=0; j<2; j++) v0[j]=(a[j]+b[j])/2;for(j=0; j<2; j++) v1[j]=(a[j]+c[j])/2;for(j=0; j<2; j++) v2[j]=(b[j]+c[j])/2;divide_triangle(a, v0, v1, m-1);divide_triangle(c, v1, v2, m-1);divide_triangle(b, v2, v0, m-1);

}else triangle(a,b,c); /* draw triangle at end of recursion */}

void display(){glClear(GL_COLOR_BUFFER_BIT);glBegin(GL_TRIANGLES);divide_triangle(v[0], v[1], v[2], n);glEnd();glFlush();}

void myinit(){glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(-2.0, 2.0, -2.0, 2.0);glMatrixMode(GL_MODELVIEW);glClearColor (1.0, 1.0, 1.0, 1.0);glColor3f(0.0,0.0,0.0);}

int main(int argc, char **argv){//n=atoi(argv[1]); /* or set number of subdivision steps here */

glutInit(&argc, argv);printf("Enter the number of divisions : ");

scanf("%d",&n);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

glutInitWindowSize(500, 500);glutCreateWindow("Sierpinski Gasket");glutDisplayFunc(display);myinit();glutMainLoop();

return 0;

Page 45: CGLab Manual 2012

45

}

Output

Create 3D Sierpinski gasket by recursive subdivision of tetrahedron.

/* recursive subdivision of a tetrahedron to form 3D Sierpinski gasket *//* number of recursive steps given on command line */

#include <stdlib.h>#include <GL/glut.h>

/* initial tetrahedron */

GLfloat v[4][3]={{0.0, 0.0, 1.0}, {0.0, 0.942809, -0.33333},{-0.816497, -0.471405, -0.333333}, {0.816497, -0.471405, -0.333333}};

GLfloat colors[4][3] = {{1.0, 0.0, 0.0}, {0.0, 1.0, 0.0},{0.0, 0.0, 1.0}, {0.0, 0.0, 0.0}};

int n;

void triangle(GLfloat *va, GLfloat *vb, GLfloat *vc){

glVertex3fv(va);glVertex3fv(vb);glVertex3fv(vc);

}

void tetra(GLfloat *a, GLfloat *b, GLfloat *c, GLfloat *d){

glColor3fv(colors[0]);triangle(a, b, c);

Page 46: CGLab Manual 2012

46

glColor3fv(colors[1]);triangle(a, c, d);glColor3fv(colors[2]);triangle(a, d, b);glColor3fv(colors[3]);triangle(b, d, c);

}

void divide_tetra(GLfloat *a, GLfloat *b, GLfloat *c, GLfloat *d, int m){

GLfloat mid[6][3];int j;if(m>0){

/* compute six midpoints */

for(j=0; j<3; j++) mid[0][j]=(a[j]+b[j])/2;for(j=0; j<3; j++) mid[1][j]=(a[j]+c[j])/2;for(j=0; j<3; j++) mid[2][j]=(a[j]+d[j])/2;for(j=0; j<3; j++) mid[3][j]=(b[j]+c[j])/2;for(j=0; j<3; j++) mid[4][j]=(c[j]+d[j])/2;for(j=0; j<3; j++) mid[5][j]=(b[j]+d[j])/2;

/* create 4 tetrahedrons by subdivision */

divide_tetra(a, mid[0], mid[1], mid[2], m-1);divide_tetra(mid[0], b, mid[3], mid[5], m-1);divide_tetra(mid[1], mid[3], c, mid[4], m-1);divide_tetra(mid[2], mid[4], d, mid[5], m-1);

}else(tetra(a,b,c,d)); /* draw tetrahedron at end of recursion */

}

void display(){

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glBegin(GL_TRIANGLES);divide_tetra(v[0], v[1], v[2], v[3], n);glEnd();glFlush();

}

void myReshape(int w, int h){

glViewport(0, 0, w, h);glMatrixMode(GL_PROJECTION);glLoadIdentity();if (w <= h)

glOrtho(-2.0, 2.0, -2.0 * (GLfloat) h / (GLfloat) w,2.0 * (GLfloat) h / (GLfloat) w, -10.0, 10.0);

elseglOrtho(-2.0 * (GLfloat) w / (GLfloat) h,

2.0 * (GLfloat) w / (GLfloat) h, -2.0, 2.0, -10.0, 10.0);

Page 47: CGLab Manual 2012

47

glMatrixMode(GL_MODELVIEW);glutPostRedisplay();

}

int main(int argc, char **argv){

n=3; /* atoi(argv[1]); or enter number of subdivision steps here */glutInit(&argc, argv);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);glutInitWindowSize(500, 500);glutCreateWindow("3D Gasket");glutReshapeFunc(myReshape);glutDisplayFunc(display);glEnable(GL_DEPTH_TEST);glClearColor (1.0, 1.0, 1.0, 1.0);glutMainLoop();

}

Output

Page 48: CGLab Manual 2012

48

Lab 3

fish swimming#include<stdlib.h>#include<stdio.h>#include<time.h>#include "stdafx.h"#include<GL/glut.h> void fish(void);int c=0;int i=0,singleb;int _tmain(int argc, _TCHAR* argv[]){ return 0;}

void init (void){ // glClear (GL_COLOR_BUFFER_BIT); glClearColor (0.118, 0.126, 0.355, 1.0); // Set display-window color to white. glColor3f(0.5,0.0,0.0); //glMatrixMode (GL_PROJECTION); // Set projection parameters. gluOrtho2D (0.0, 150.0, 0.0, 150.0);}void displays(){ glClear (GL_COLOR_BUFFER_BIT);

fish();

glFlush();}

void spinDisplay (void){ //spin = spin + 2.0; if (i > 200) i =-50; //x= 25.0*cos(DEGREES_TO_RADIANS * spin); //y= 25.0*sin(DEGREES_TO_RADIANS * spin); i=i+1; for(int j=0;j<1000000;j++); for(int j=0;j<1000000;j++); for(int j=0;j<1000000;j++); for(int j=0;j<1000000;j++); glutSetWindow(singleb); glutPostRedisplay(); //glutSetWindow(doubleb); //glutPostRedisplay();}void fish(){ //glClearColor (1.0, 1.0, 1.0, 0.0);

Page 49: CGLab Manual 2012

49

//glClear (GL_COLOR_BUFFER_BIT); glBegin(GL_TRIANGLES); glVertex2i(50+i,50); glVertex2i(35+i,65); glVertex2i(35+i,35); glEnd(); glBegin(GL_TRIANGLES); glVertex2i(35+i,50); glVertex2i(25+i,60); glVertex2i(25+i,40); glEnd(); glFlush ( ); // Process all OpenGL routines as quickly as possible.

}

void main (int argc, char** argv){ glutInit (&argc, argv); // Initialize GLUT. glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // Set display mode. glutInitWindowPosition (200, 200); // Set top-left display-window position. glutInitWindowSize (500, 500); // Set display-window width and height. singleb=glutCreateWindow ("Swimming fish"); // Create display window.

init ( ); // Execute initialization procedure. glutDisplayFunc (displays); // Send graphics to display window. glutIdleFunc (spinDisplay); glutMainLoop ( ); // Display everything and wait.

}

Page 50: CGLab Manual 2012

50

kite flying

#include<stdafx.h>#include<stdlib.h>#include<time.h>#include<GL/glut.h>#include<stdio.h>GLsizei wh=500,ww=500;void init(){

glViewport(0,0,ww,wh);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,(GLdouble)ww,0.0,(GLdouble)wh);glMatrixMode(GL_MODELVIEW);//glColor3f(1.0,0.0,1.0);

}void delay(){ int i,j,r;

for(i=0;i<1000;i++)for(j=0;j<60000;j++)

r=i*j*10;}

void drawkite(float x,float y){

glColor3f(1.0,1.0,0.0);glBegin(GL_POLYGON);

glVertex2f(x-20,y+10);glVertex2f(x-20,y-40);glVertex2f(x+20,y-10);glVertex2f(x+20,y+40);

glEnd();glColor3f(0.0,0.0,0.0);glBegin(GL_LINES);

glVertex2f(x-20,y+10);glVertex2f(x+20,y-10);

glVertex2f(x-20,y-40);glVertex2f(x+20,y+40);

glEnd();glFlush();

}

void drawstring(float x,float y){

glColor3f(1.0,0.0,1.0);glBegin(GL_LINES);

glVertex2f(x-20,y-40);glVertex2f(x-30,y-80);glVertex2f(x-30,y-80);glVertex2f(x-50,y-120);glVertex2f(x-50,y-120);glVertex2f(x-80,y-150);

Page 51: CGLab Manual 2012

51

glEnd();glFlush();

}

void display(){

glClear(GL_COLOR_BUFFER_BIT);float i=50.0,j=50.0;

while(j<=450.0){ i=50.0;

while(i<400.0){

drawkite(i,j);drawstring(i,j);glClear(GL_COLOR_BUFFER_BIT);delay();i=i+5.0;j=j+1.0;

}while(i>100.0){

drawkite(i,j);drawstring(i,j);glClear(GL_COLOR_BUFFER_BIT);delay();i=i-5.0;j=j+1.0;

}//j=j+30.0;}

}int main(int argc, char ** argv){

glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(50,50);glutCreateWindow("Click");glutDisplayFunc(display);init();glutMainLoop();

}

Page 52: CGLab Manual 2012

52

rotating wheel #include<stdafx.h> #include <stdlib.h> #include <math.h> #include <GL/glut.h>

static int angle=0; static double *spoke_pts = NULL; static double *rim_pts; // Creates an array of 2*n doubles representing n points evenly // spaced around a circle of radius 1. Point i on the // circumference will be at coordinates (array[2*i], array[2*i+1]). static double* createCircumferencePoints(int n) { double *ret; int i; double theta; ret = (double*) malloc(2 * n * sizeof(double)); for(i = 0; i < n; i++) { theta = 2 * 3.14 * i / n; ret[2 * i] = cos(theta); ret[2 * i + 1] = sin(theta); } return ret; } // Initializes data necessary for drawing a wagon wheel. void wheelInit() { if(spoke_pts == NULL) { spoke_pts = createCircumferencePoints(12); rim_pts = createCircumferencePoints(24); } }

Page 53: CGLab Manual 2012

53

// Draws wagon wheel of radius 1, centered at origin. void wheelDraw() { int i; glBegin(GL_LINES); // Draw spokes. for(i = 0; i < 12; i++) { glVertex2f(0.0, 0.0); glVertex2f(spoke_pts[2 * i], spoke_pts[2 * i + 1]); } glEnd(); glBegin(GL_LINE_LOOP); // Draw rim. for(i = 0; i < 24; i++) { glVertex2f(rim_pts[2 * i], rim_pts[2 * i + 1]); } glEnd(); }

// Initializes information for drawing within OpenGL. void init() { glClearColor(1.0, 1.0, 1.0, 0.0); // Set window color to white. glMatrixMode(GL_PROJECTION); // Set projection parameters. gluOrtho2D(-1.5, 1.5, -1.5, 1.5); // Set viewable coordinates wheelInit(); } // Draws the picture. void draw() { glClear(GL_COLOR_BUFFER_BIT); // Clear display window. glColor3f(0.0, 0.0, 0.0); // Set line segment color to black. wheelDraw(); glFlush(); // Process all OpenGL routines as quickly as possible. } void mouse(int b,int st,int x, int y) {

if(b==GLUT_LEFT_BUTTON &&st==GLUT_DOWN) glutIdleFunc(NULL);

} void spin() {double i;

angle+=10; if(angle>360)angle=0;

glutPostRedisplay(); for(i=0;i<10000;i++);

} int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition(50, 100); // Set up display window. glutInitWindowSize(200, 200);

Page 54: CGLab Manual 2012

54

glutCreateWindow("Wagon Wheel"); init(); glutDisplayFunc(draw);

glutMouseFunc(mouse); glutIdleFunc(spin);

glutMainLoop(); return 0; }

Page 55: CGLab Manual 2012

55

Lab 4

Write a program to handle mouse events. Plot points in random colors by pressing the mouse left button. The display window must be cleared when you press the mouse right button. Also write the reshape callback function which changes the clipping rectangle when window is resized.

//#include"windows.h"#include"stdio.h"#include<stdafx.h>#include"GL/glut.h"

GLsizei wh=500,ww=500;GLfloat size=3.0;int flag=0;

void myDisp(){ glClear(GL_COLOR_BUFFER_BIT); glFlush(); }

void drawSquare(int x,int y){if(flag){

y=wh-y;glBegin(GL_POLYGON);glVertex2f(x+size,y+size);glVertex2f(x-size,y+size);glVertex2f(x-size,y-size);glVertex2f(x+size,y-size);glEnd();glFlush();

}}

void myMouse(int b,int s,int x,int y){if(b==GLUT_LEFT_BUTTON && s==GLUT_DOWN) { flag=1; drawSquare(x,y); }if(b==GLUT_LEFT_BUTTON && s==GLUT_UP) flag=0;if(b==GLUT_RIGHT_BUTTON && s==GLUT_DOWN){

glClearColor(0.0,0.0,0.0,1.0);glClear(GL_COLOR_BUFFER_BIT);glFlush();}

}

void myReshape(int w,int h){

Page 56: CGLab Manual 2012

56

glMatrixMode(GL_PROJECTION);glLoadIdentity();glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,-1.0,1.0);glMatrixMode(GL_MODELVIEW);glLoadIdentity();glViewport(0,0,w,h);

glutPostRedisplay();ww=w; wh=h;

}

void myInit(){glViewport(0,0,ww,wh);glMatrixMode(GL_PROJECTION);glLoadIdentity();glOrtho(0.0,(GLdouble)ww,0.0,(GLdouble)wh,-1.0,1.0);glMatrixMode(GL_MODELVIEW);glClearColor(0.0,0.0,0.0,1.0);glClear(GL_COLOR_BUFFER_BIT);glColor3f(1.0,0.0,0.0);

}

int main(int argc,char** argv){glutInit(&argc,argv);glutInitWindowSize(ww,wh);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutCreateWindow("Square");myInit();glutReshapeFunc(myReshape);glutMouseFunc(myMouse);glutMotionFunc(drawSquare);glutDisplayFunc(myDisp);glutMainLoop();

}

Output:

Page 57: CGLab Manual 2012

57

Write a program to handle mouse events. Draw rectangles using 2 points, at top left and bottom right on mouse left-button clicks. On right click, clear window. Use reshape callback to avoid distortion on window resize.

#include<stdafx.h>#include<stdlib.h>#include<GL/glut.h>#include<stdio.h>

GLsizei wh=500,ww=500;float ax,ay,bx,by,initx,inity;int flag;

void refresh(){ ax=bx=ay=by=0.0; flag=0;}void myReshape(int w,int h){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,-1.0,1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0,0,w,h);

glutPostRedisplay(); ww=w; wh=h;}

void init(){

refresh();glViewport(0,0,ww,wh);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,(GLdouble)ww,0.0,(GLdouble)wh);glMatrixMode(GL_MODELVIEW);glColor3f(1.0,0.0,1.0);

}

void draw(int x,int y) //rectangle is drawn{

y=wh-y;if(flag==0) { ax=(float)x; ay=(float)y; flag++; glClear(GL_COLOR_BUFFER_BIT); }else if(flag==1){ bx=(float)x; by=(float)y; glBegin(GL_POLYGON); glColor3f(1.0,1.0,0.0);

Page 58: CGLab Manual 2012

58

glVertex2f(ax,ay); glVertex2f(bx,ay); glVertex2f(bx,by); glVertex2f(ax,by); glEnd(); glFlush(); refresh();}

glFlush();}

void mouse(int button,int state, int x, int y) {glColor3f(1.0,0.0,1.0);if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN) draw(x,y);if(button==GLUT_RIGHT_BUTTON)

{glClearColor(0.0,0.0,0.0,1.0); glClear(GL_COLOR_BUFFER_BIT);glFlush();}

}void display(){

glClear(GL_COLOR_BUFFER_BIT);}

int main(int argc,char** argv){ glutInit(&argc,argv); glutInitWindowSize(ww,wh); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutCreateWindow("Square"); init(); glutReshapeFunc(myReshape); glutMouseFunc(mouse); glutDisplayFunc(display); glutMainLoop();}

Output:

Page 59: CGLab Manual 2012

59

Write a program to simulate free hand drawing using a fat brush. The brush size must be randomly variable in the range 3-10. The drawing should be multicolored.

#include<stdafx.h>#include<stdlib.h>#include<GL/glut.h>#include<stdio.h>#include<time.h>GLsizei wh=500,ww=500;float ax,ay,bx,by,initx,inity;int flag;void refresh(){ ax=bx=ay=by=0.0; flag=0;

}

void myReshape(int w,int h){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,-1.0,1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0,0,w,h); glutPostRedisplay(); ww=w; wh=h;

}

void init(){

refresh();glViewport(0,0,ww,wh);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,(GLdouble)ww,0.0,(GLdouble)wh);glMatrixMode(GL_MODELVIEW);glColor3f(1.0,0.0,1.0);

}

void drawLine(int x,int y){

y=wh-y;if(flag==0) { ax=(float)x; ay=(float)y; flag++;}else if(flag==1){

GLfloat thick; srand( time( NULL ) );

thick=rand()%10+3;bx=(float)x;

by=(float)y; glBegin(GL_LINES); glColor3f(1.0,1.0,0.0);

Page 60: CGLab Manual 2012

60

glLineWidth(thick); glVertex2f(ax,ay); glVertex2f(bx,by); glEnd(); glFlush(); ax=bx; ay=by; //refresh();

}glFlush();

}

void temp(int button,int state, int x, int y){

glColor3f(1.0,0.0,1.0);if(button==GLUT_LEFT_BUTTON && state!=GLUT_DOWN) refresh();

}

void move(int x, int y){

glColor3f(0.0,1.0,0.0);drawLine(x,y);}

void display(){

glClear(GL_COLOR_BUFFER_BIT);}

int main(int argc, char ** argv){ glutInit(&argc,argv);

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(50,50);glutCreateWindow("Click");init();glutReshapeFunc(myReshape);glutDisplayFunc(display);glutMouseFunc(temp);glutMotionFunc(move);

glutMainLoop();}

Output:

Page 61: CGLab Manual 2012

61

Page 62: CGLab Manual 2012

62

Lab 5

Write a program to handle mouse events Create a polyline using mouse left-button clicks. The polyline must be redisplayed on window resize.

#include<stdafx.h>#include<stdlib.h>#include<GL/glut.h>#include<stdio.h>GLsizei wh=500,ww=500;float ax,ay,bx,by,initx,inity;int flag;void refresh(){ ax=bx=ay=by=0.0; flag=0;

}void init(){

refresh();glViewport(0,0,ww,wh);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,(GLdouble)ww,0.0,(GLdouble)wh);glMatrixMode(GL_MODELVIEW);glColor3f(1.0,0.0,1.0);

}void myReshape(int w,int h){

glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,-1.0,1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glViewport(0,0,w,h); glutPostRedisplay(); ww=w; wh=h;

}

void drawLineLoop(int x,int y){

y=wh-y;if(flag==0){

initx=inity=ax=ay=bx=by=0.0; ax=(float)x; ay=(float)y; initx=ax; inity=ay; flag++; glClear(GL_COLOR_BUFFER_BIT); }else if(flag==1){ bx=(float)x;

Page 63: CGLab Manual 2012

63

by=(float)y; glBegin(GL_LINES); glColor3f(1.0,1.0,0.0); glVertex2f(ax,ay); glVertex2f(bx,by);

glEnd(); glFlush(); ax=bx; ay=by; }

glFlush();}void drawfinal(int x,int y){ y=wh-y; glBegin(GL_LINES); glColor3f(1.0,1.0,0.0); glVertex2f(bx,by); glVertex2f(initx,inity); glEnd(); glFlush();

flag=0;}void lineloop(int button,int state, int x, int y){

glColor3f(1.0,0.0,1.0);if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN) drawLineLoop(x,y);if(button==GLUT_RIGHT_BUTTON) drawfinal(x,y);

}void display(){

glClear(GL_COLOR_BUFFER_BIT);}

int main(int argc,char** argv){glutInit(&argc,argv);

glutInitWindowSize(ww,wh); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutCreateWindow("Square"); init(); glutReshapeFunc(myReshape); glutMouseFunc(lineloop); glutDisplayFunc(display); glutMainLoop();

}Output:

Page 64: CGLab Manual 2012

64

Write a program to create a font for the letter C .#include<stdafx.h>#include<stdlib.h>#include<GL/glut.h>#include<math.h>

void letter_c(int i,int j){ int k; float angle; glBegin(GL_QUAD_STRIP); for(k=2;k<=10;k++) { angle = 3.14159 / 6.0 * k; glVertex2f(7*cos(angle)+i+10 , 7*sin(angle)+j+10); glVertex2f(12*cos(angle)+i+10 , 12*sin(angle)+j+10); } glEnd();}

void display(){ glClear(GL_COLOR_BUFFER_BIT); letter_c(62,250); glFlush();}

void init(){ glClearColor (0.7, 0.7, 0.7, 0.0);}

void myReshape(int w,int h){ glViewport(0,0,w,h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); if(w<=h) glOrtho(0.0, 700.0, 0.0, 700.0 * (GLfloat)h/(GLfloat)w, -100.0, 100.0); else glOrtho(0.0, 700.0 * (GLfloat)w/(GLfloat)h, 0.0, 700.0, -100.0, 100.0); glMatrixMode(GL_MODELVIEW); glutPostRedisplay();}

Page 65: CGLab Manual 2012

65

int main(int argc, char** argv){

glutInit(&argc,argv);glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);glutInitWindowSize(700,700);glutInitWindowPosition(0,0);glutCreateWindow("simple");glutReshapeFunc(myReshape);glutDisplayFunc(display);init();glutMainLoop();

}

Output:

Write a program to create a font for the letter D #include<stdafx.h>#include<stdlib.h>#include<GL/glut.h>#include<math.h>

void letter_d(int i,int j){ int k; float angle,a; glBegin(GL_QUAD_STRIP); for(k=9;k<=12;k++) { angle = 3.14159 / 6.0 * k; glVertex2f(7*cos(angle)+i+10 , 7*sin(angle)+j+10); glVertex2f(12*cos(angle)+i+10 , 12*sin(angle)+j+10); } glEnd(); glBegin(GL_QUAD_STRIP); for(k=0;k<=3;k++) { angle = 3.14159 / 6.0 * k; glVertex2f(7*cos(angle)+i+10 , 7*sin(angle)+j+10); glVertex2f(12*cos(angle)+i+10 , 12*sin(angle)+j+10); } glEnd(); glBegin(GL_POLYGON); glVertex2f(i,j-2); glVertex2f(i,j+22); glVertex2f(i+4,j+22); glVertex2f(i+4,j-2); glEnd(); glBegin(GL_POLYGON); glVertex2f(i+4,j-2);

Page 66: CGLab Manual 2012

66

glVertex2f(i+4,j+2); glVertex2f(i+10,j+2); glVertex2f(i+10,j-2); glEnd(); glBegin(GL_POLYGON); glVertex2f(i+4,j+18); glVertex2f(i+4,j+22); glVertex2f(i+10,j+22); glVertex2f(i+10,j+18); glEnd();}

void display(){ glClear(GL_COLOR_BUFFER_BIT);

letter_d(86,250); glFlush();}

void init(){ glClearColor (0.7, 0.7, 0.7, 0.0);}

void myReshape(int w,int h){ glViewport(0,0,w,h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); if(w<=h) glOrtho(0.0, 700.0, 0.0, 700.0 * (GLfloat)h/(GLfloat)w, -100.0, 100.0); else glOrtho(0.0, 700.0 * (GLfloat)w/(GLfloat)h, 0.0, 700.0, -100.0, 100.0); glMatrixMode(GL_MODELVIEW); glutPostRedisplay();}

int main(int argc, char** argv){

glutInit(&argc,argv);glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);glutInitWindowSize(700,700);glutInitWindowPosition(0,0);glutCreateWindow("simple");glutReshapeFunc(myReshape);glutDisplayFunc(display);init();glutMainLoop();

}

Output:

Page 67: CGLab Manual 2012

67

Write a program to create a font for the letter O

#include<stdafx.h>#include<stdlib.h>#include<math.h>#include<GL/glut.h>void myInit(){

glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,500.0,0.0,500.0);glMatrixMode(GL_MODELVIEW);glClearColor(1.0,0.0,0.0,0.0);glColor3f(1.0,0.0,0.0);

}void myDisplay(void){

float angle;int i;glTranslatef(250.0,250.0,0.0);glBegin(GL_QUAD_STRIP);for(i=0;i<=16;i++){

angle = 3.1415 / 6.0 * i+(3.1415/2);;glVertex2f(40*cos(angle), 40*sin(angle)); //change the angle forglVertex2f(50*cos(angle), 50*sin(angle)); //different thickness of

// letter ‘O’

}glEnd();glFlush();

}int main(int argc,char **argv){

glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);glutCreateWindow("Letter O");glutDisplayFunc(myDisplay);myInit();glutMainLoop();

}

Page 68: CGLab Manual 2012

68

Output:

Write a program to create a font for the letter S #include<stdafx.h>#include<windows.h>#include <stdlib.h>#include<stdio.h>#include <GL/glut.h>#include<math.h>

void OurFont(char c){ int i; float angle; glColor3f(1.0,0.0,0.0);

glTranslatef(0.0,0.0,0.0); glBegin(GL_QUAD_STRIP);

for(i=2; i<=9;i++) { angle = 3.14159/6.0*i; glVertex2f(0.4*cos(angle)+0.5,0.4*sin(angle)+0.5); glVertex2f(0.5*cos(angle)+0.5,0.5*sin(angle)+0.5); } glEnd();

glTranslatef(-0.1,0.12,0.0);glBegin(GL_QUAD_STRIP); for(i=9; i!=4;i++) { angle = 3.14159/6.0*i; glVertex2f(0.4*cos(angle)+0.5,-(0.4*sin(angle)+0.5)); glVertex2f(0.5*cos(angle)+0.5,-(0.5*sin(angle)+0.5));

if(i==12) i=0; }glEnd();

}

void display(void){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); OurFont('S'); glFlush();}

void myReshape(int w, int h){

Page 69: CGLab Manual 2012

69

glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho(-2.0, 2.0, -2.0 * (GLfloat) h / (GLfloat) w, 2.0 * (GLfloat) h / (GLfloat) w, -10.0, 10.0); else glOrtho(-2.0 * (GLfloat) w / (GLfloat) h, 2.0 * (GLfloat) w / (GLfloat) h, -2.0, 2.0, -10.0, 10.0); glMatrixMode(GL_MODELVIEW); glutPostRedisplay();}

int main(int argc, char **argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 500); glutCreateWindow("LetterS"); glutReshapeFunc(myReshape); glutDisplayFunc(display); glEnable(GL_DEPTH_TEST); glClearColor (1.0, 1.0, 1.0, 1.0); glutMainLoop();}

Output:

Page 70: CGLab Manual 2012

70

Lab 6

Write a program to display a hierarchical menu as below using popup menu. When an option is selected, display the option on output window.

View _______ normal

| _print

|_web

Edit_________cut

|_ copy

|_paste

#include<stdafx.h>#include<stdlib.h>#include<GL/glut.h>#include<stdio.h>

#include<math.h>int flag=0;float size=0.2;void mydisplay(){ glClear(GL_COLOR_BUFFER_BIT)l glFlush();}

void init(){ glClearColor(0.0,0.0,0.0,1); glColor3f(1.0,0.0,0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,500,0,500); glMatrixMode(GL_MODELVIEW);}

void demo_menu(int id){

switch(id){ case 1:exit(0);break;}

}

void edit_menu(int id){

switch(id){

case 5: printf("cut");break;case 6: printf("copy");break;case 7: printf("paste");break;

}

Page 71: CGLab Manual 2012

71

}

void size_menu(int id){

switch(id){case 2: printf("normal");break;case 3: printf("print");break;case 4:printf("web");break;

}}

void myReshape(int w, int h){

/* adjust clipping box */glViewport(0,0,w,h);glMatrixMode(GL_PROJECTION);glLoadIdentity();if(w<=h) glOrtho(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w, 2.0*(GLfloat)h/(GLfloat)w,-10.0,10.0);else

glOrtho(-2.0*(GLfloat)w/(GLfloat)h, 2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0,-10.0,10.0);glMatrixMode(GL_MODELVIEW);

}

int main(int argc, char** argv){

int sub_menu1, sub_menu2;glutInit(&argc,argv);

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(20,20); glutCreateWindow("menu");

sub_menu1=glutCreateMenu(size_menu);glutAddMenuEntry("normal",2);glutAddMenuEntry("print",3);glutAddMenuEntry("web",4);

sub_menu2=glutCreateMenu(edit_menu);glutAddMenuEntry("cut",5);glutAddMenuEntry("copy",6);glutAddMenuEntry("paste",7);

glutCreateMenu(demo_menu);glutAddMenuEntry("quit",1);glutAddSubMenu("view",sub_menu1);glutAddSubMenu("edit",sub_menu2);glutAttachMenu(GLUT_RIGHT_BUTTON);

glutDisplayFunc(mydisplay);init();glutReshapeFunc(myReshape);glutMainLoop();

Page 72: CGLab Manual 2012

72

}Output:

Write a program to draw a square. Use popup menu with options to quit or resize the square. The resize option has submenu with increase size and decrease size as options. The increase size must double the size of the square and the decrease size option must reduce the size by 2. (half size) . Min size is 1.

#include<stdafx.h>#include<stdlib.h>#include<GL/glut.h>#include<stdio.h>

#include<math.h>int flag=0; float size=0.2;void mydisplay(){

glClear(GL_COLOR_BUFFER_BIT);glBegin(GL_POLYGON);

glVertex2f(-1.0*size, -1.0*size); glVertex2f(1.0*size, -1.0*size); glVertex2f(1.0*size, 1.0*size); glVertex2f(-1.0*size,1.0*size); glEnd(); glFlush();}

Page 73: CGLab Manual 2012

73

void init(){ glClearColor(0.0,0.0,0.0,1); glColor3f(1.0,0.0,0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,500,0,500); glMatrixMode(GL_MODELVIEW);}

void demo_menu(int id){

switch(id){

case 1:exit(0);break;}glutPostRedisplay();

}

void size_menu(int id){

switch(id){

case 2: size=2*size;break;case 3: size=size/2;break;

}glutPostRedisplay();

}void myReshape(int w, int h){

/* adjust clipping box */glViewport(0,0,w,h);glMatrixMode(GL_PROJECTION);glLoadIdentity();if(w<=h) glOrtho(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w, 2.0*(GLfloat)h/(GLfloat)w,-10.0,10.0);else

glOrtho(-2.0*(GLfloat)w/(GLfloat)h, 2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0,-10.0,10.0);glMatrixMode(GL_MODELVIEW);

}int main(int argc, char** argv){

int sub_menu;glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(20,20);

glutCreateWindow("menu");sub_menu=glutCreateMenu(size_menu);glutAddMenuEntry("increase size",2);glutAddMenuEntry("decrease size",3);

Page 74: CGLab Manual 2012

74

glutCreateMenu(demo_menu);glutAddMenuEntry("quit",1);glutAddSubMenu("resize",sub_menu);

glutAttachMenu(GLUT_RIGHT_BUTTON);

glutDisplayFunc(mydisplay); init();

glutReshapeFunc(myReshape); glutMainLoop();}Output:

Page 75: CGLab Manual 2012

75

Lab 7

Write a program to rotate a square using both single and double buffering.

#include<stdafx.h>#include <stdlib.h>

#include <GL/glut.h>#include <math.h>

#define DEGREES_TO_RADIANS 3.14159/180.0

static GLfloat spin = 0.0;GLfloat x, y;int singleb, doubleb;

void square(){ glBegin(GL_QUADS);

glVertex2f(x,y); glVertex2f(-y,x);

glVertex2f(-x,-y); glVertex2f(y,-x);glEnd();

}

void displayd(){ glClear (GL_COLOR_BUFFER_BIT);

square();

glutSwapBuffers ();}

void displays(){ glClear (GL_COLOR_BUFFER_BIT);

square();

glFlush();}

void spinDisplay (void){ spin = spin + 2.0; if (spin > 360.0) spin = spin - 360.0;

x= 25.0*cos(DEGREES_TO_RADIANS * spin); y= 25.0*sin(DEGREES_TO_RADIANS * spin);

glutSetWindow(singleb); glutPostRedisplay();

Page 76: CGLab Manual 2012

76

glutSetWindow(doubleb); glutPostRedisplay();}

void myinit (){ glClearColor (0.0, 0.0, 0.0, 1.0); glColor3f (1.0, 1.0, 1.0); glShadeModel (GL_FLAT);}

void mouse(int btn, int state, int x, int y){if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN) glutIdleFunc(spinDisplay);if(btn==GLUT_MIDDLE_BUTTON && state==GLUT_DOWN) glutIdleFunc(NULL);}

void myReshape(int w, int h){ glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h)

glOrtho (-50.0, 50.0, -50.0*(GLfloat)h/(GLfloat)w, 50.0*(GLfloat)h/(GLfloat)w, -1.0, 1.0);

else glOrtho (-50.0*(GLfloat)w/(GLfloat)h, 50.0*(GLfloat)w/(GLfloat)h, -50.0, 50.0, -1.0, 1.0);

glMatrixMode(GL_MODELVIEW); glLoadIdentity ();

}

/* Main Loop * Open window with initial window size, title bar, * RGBA display mode, and handle input events. */int main(int argc, char** argv){

glutInit(&argc,argv);glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);singleb=glutCreateWindow("single buffered");

myinit ();glutDisplayFunc(displays);

glutReshapeFunc (myReshape); glutIdleFunc (spinDisplay); glutMouseFunc (mouse);

glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowPosition(500,0);

doubleb=glutCreateWindow("double buffered"); myinit ();

glutDisplayFunc(displayd); glutReshapeFunc (myReshape); glutIdleFunc (spinDisplay); glutMouseFunc (mouse);

Page 77: CGLab Manual 2012

77

glutMainLoop();

}

Write a program to demonstrate picking using selection mode.

#include <stdlib.h>#include <stdio.h>#include <GL/glut.h>

void init(){ glClearColor (0.0, 0.0, 0.0, 0.0);}

void drawObjects(GLenum mode){ if(mode == GL_SELECT) glLoadName(1); glColor3f(1.0, 0.0, 0.0); glRectf(-0.5, -0.5, 1.0, 1.0); if(mode == GL_SELECT) glLoadName(2); glColor3f(0.0, 0.0, 1.0); glRectf(-1.0, -1.0, 0.5, 0.5);}

void display(){ glClear(GL_COLOR_BUFFER_BIT); drawObjects(GL_RENDER); glFlush();}

/* processHits prints out the contents of the * selection array */void processHits (GLint hits, GLuint buffer[]){ unsigned int i, j; GLuint names, *ptr;

printf ("hits = %d\n", hits); ptr = (GLuint *) buffer; for (i = 0; i < hits; i++) { /* for each hit */

Page 78: CGLab Manual 2012

78

names = *ptr; ptr+=3; for (j = 0; j < names; j++) { /* for each name */ if(*ptr==1) printf ("red rectangle\n"); else printf ("blue rectangle\n"); ptr++; } printf ("\n"); }}

#define SIZE 512

void mouse(int button, int state, int x, int y){ GLuint selectBuf[SIZE]; GLint hits; GLint viewport[4];

if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { glGetIntegerv (GL_VIEWPORT, viewport);

glSelectBuffer (SIZE, selectBuf); glRenderMode(GL_SELECT);

glInitNames(); glPushName(0);

glMatrixMode (GL_PROJECTION); glPushMatrix (); glLoadIdentity ();/* create 5x5 pixel picking region near cursor location */ gluPickMatrix ((GLdouble) x, (GLdouble) (viewport[3] - y), 5.0, 5.0, viewport); gluOrtho2D (-2.0, 2.0, -2.0, 2.0); drawObjects(GL_SELECT);

glMatrixMode (GL_PROJECTION); glPopMatrix (); glFlush ();

hits = glRenderMode (GL_RENDER); processHits (hits, selectBuf);

glutPostRedisplay(); }}

void reshape(int w, int h){ glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D (-2.0, 2.0, -2.0, 2.0);

Page 79: CGLab Manual 2012

79

glMatrixMode(GL_MODELVIEW); glLoadIdentity();}

void keyboard(unsigned char key,int x, int y){ switch (key) { case 27: exit(0); break; }}

/* main loop */ int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (500, 500); glutInitWindowPosition (100, 100); glutCreateWindow (argv[0]); init (); glutReshapeFunc (reshape); glutDisplayFunc(display); glutMouseFunc (mouse); glutKeyboardFunc (keyboard); glutMainLoop(); return 0;}

Output:

Page 80: CGLab Manual 2012

80

Write a program to perform rotation of a cube using color interpolation.

#include<stdlib.h>#include<gl/GLUT.h>#define THETA 0.2int flag=0;void display(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor3f(1.0,0.0,0.0);

glutSolidCube(1.0); glutSwapBuffers();}

void redisplay(){ if (flag==1) { glRotatef(THETA,1.0,0.0,0.0); glutPostRedisplay(); } if (flag==2) { glRotatef(THETA,0.0,1.0,0.0); glutPostRedisplay(); } if (flag==3) { glRotatef(THETA,0.0,0.0,1.0); glutPostRedisplay(); } display();}void mymouse (int button,int state,int x,int y){ if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { flag=1;

glLoadIdentity(); redisplay(); } if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) { flag=2;

glLoadIdentity(); redisplay(); } if(button == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) { flag=3; glLoadIdentity();

redisplay(); }}

void mykeyboard(unsigned char key,int x,int y)

Page 81: CGLab Manual 2012

81

{ if (key=='ESC') exit(0);}

void myinit(){ glEnable( GL_DEPTH_TEST ); glClearColor(0.0,0.0,0.0,0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-3.0,3.0,-3.0,3.0); glMatrixMode(GL_MODELVIEW);}

int main(int argc, char *argv){ glutInitWindowPosition(0.0,0.0); glutInitWindowSize(500,500); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutCreateWindow("Cube"); myinit(); glutDisplayFunc(redisplay); glutMouseFunc(mymouse); glutKeyboardFunc(mykeyboard); glutMainLoop();)Output:

Write a program to perform rotation of a cube using vertex arrays.

#include <stdlib.h>#include <GL/glut.h>

GLfloat vertices[] = {-1.0,-1.0,-1.0,1.0,-1.0,-1.0,1.0,1.0,-1.0, -1.0,1.0,-1.0, -1.0,-1.0,1.0, 1.0,-1.0,1.0, 1.0,1.0,1.0, -1.0,1.0,1.0};

GLfloat colors[] = {0.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0, 0.0,1.0,0.0, 0.0,0.0,1.0, 1.0,0.0,1.0, 1.0,1.0,1.0, 0.0,1.0,1.0};

GLubyte cubeIndices[]={0,3,2,1,2,3,7,6,0,4,7,3,1,2,6,5,4,5,6,7,0,1,5,4};

static GLfloat theta[] = {0.0,0.0,0.0};

Page 82: CGLab Manual 2012

82

static GLint axis = 2;

void display(void){

/* display callback, clear frame buffer and z buffer, rotate cube and draw, swap buffers */

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glLoadIdentity();gluLookAt(1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0);glTranslatef(0.0, 3.0, 0.0);glRotatef(theta[0], 1.0, 0.0, 0.0);glRotatef(theta[1], 0.0, 1.0, 0.0);glRotatef(theta[2], 0.0, 0.0, 1.0);

glColorPointer(3,GL_FLOAT, 0, colors); glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, cubeIndices);

glutSwapBuffers(); }

void spinCube(){

/* Idle callback, spin cube 2 degrees about selected axis */theta[axis] += 2.0;if( theta[axis] > 360.0 ) theta[axis] -= 360.0;glutPostRedisplay();

}

void mouse(int btn, int state, int x, int y){

/* mouse callback, selects an axis about which to rotate */

if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis = 0;if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis = 1;if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis = 2;

}

void myReshape(int w, int h){ glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho(-4.0, 4.0, -3.0 * (GLfloat) h / (GLfloat) w, 5.0 * (GLfloat) h / (GLfloat) w, -10.0, 10.0); else glOrtho(-4.0 * (GLfloat) w / (GLfloat) h, 4.0 * (GLfloat) w / (GLfloat) h, -3.0, 5.0, -10.0, 10.0); glMatrixMode(GL_MODELVIEW);}

voidmain(int argc, char **argv){

Page 83: CGLab Manual 2012

83

/* need both double buffering and z buffer */

glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 500); glutCreateWindow("colorcube"); glutReshapeFunc(myReshape); glutDisplayFunc(display); glutIdleFunc(spinCube); glutMouseFunc(mouse); glEnable(GL_DEPTH_TEST); /* Enable hidden--surface--removal */ glEnableClientState(GL_COLOR_ARRAY);

glEnableClientState(GL_VERTEX_ARRAY);glVertexPointer(3, GL_FLOAT, 0, vertices);

glColorPointer(3,GL_FLOAT, 0, colors); glClearColor(1.0,1.0,1.0,1.0);glColor3f(1.0,1.0,1.0);

glutMainLoop();}Output:

Lab 8:

Page 84: CGLab Manual 2012

84

Lab 8

Write a program that generates approximations to a sphere by recursive subdivision generation.

#include<windows.h>#include<GL/glut.h>#include<math.h>void mydisplay(){ glClear(GL_COLOR_BUFFER_BIT); double c = 3.14/180.0,theta,thetar,phi,phir,c80,x,y,z,phir20; for(phi=-80.0;phi<=80.0;phi+=20.0) { phir = c*phi; phir20 = c*(phi+20); glBegin(GL_QUAD_STRIP); for(theta=-180.0;theta<=180.0;theta+=20.0) { thetar= c*theta; x=sin(thetar)*cos(phir); y=cos(thetar)*cos(phir); z=sin(phir); //glColor3f(0.0,1.0,0.0); glVertex3d(x,y,z); x=sin(thetar)*cos(phir20); y=cos(thetar)*cos(phir20); z=sin(phir20); //glColor3f(0.0,0.0,1.0); glVertex3d(x,y,z); } glEnd(); } glFlush(); glBegin(GL_TRIANGLE_FAN); //glColor3f(1.0,1.0,0.0); glVertex3d(0.0,0.0,1.0); c80=c*80.0; z=sin(c80); for(theta= -180.0;theta<=180.0;theta+=20.0) { thetar=c*theta; x=sin(thetar)*cos(c80); y=cos(thetar)*cos(c80); //glColor3f(0.0,1.0,1.0); glVertex3d(x,y,z); } glEnd(); glFlush(); glBegin(GL_TRIANGLE_FAN); //glColor3f(1.0,0.0,1.0); glVertex3d(0.0,0.0,-1.0); z=-sin(c80); for(theta= -180.0;theta<=180.0;theta+=20.0)

Page 85: CGLab Manual 2012

85

{ thetar=c*theta; x=sin(thetar)*cos(c80); y=cos(thetar)*cos(c80); //glColor3f(1.0,1.0,1.0); glVertex3d(x,y,z); } glEnd(); glFlush();

}

void init(){ glClearColor(0.0,0.0,0.0,1); glColor3f(1.0,0.0,0.0); //glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1.0,1.0,-1.0,1.0,-1.0,1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(45.0,1.0,0.0,0.0); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); //glShadeModel(GL_FLAT);}

int main(int argc, char** argv){ glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(20,20); glutCreateWindow("Sphere"); glutDisplayFunc(mydisplay); init(); glutMainLoop();}

Output:

Page 86: CGLab Manual 2012

86

Write a program to draw a line using Bresenham’s algorithm.

#include <stdafx.h>#include <stdlib.h>#include <stdio.h>

#include <GL/glut.h>

void init(){ glClearColor (0.0, 0.0, 0.0, 0.0);}void myDrawLine(int x1, int y1, int x2, int y2) { // Bresenham's algorithmint xTemp, yTemp;int m; // slope of linefloat x, y; // float versions of x and yfloat e; // error between line and pixel rowfloat sign; // shows if line goes up or down, mod(m) < 1float step; // line goes up / down mod(m) > 1

if(x2 < x1) { // Swap p1 and p2, draw other direction

xTemp = x1; yTemp = y1;x1 = x2; y1 = y2;x2 = xTemp; y2 = yTemp;

}

x = x1; y = y1; e = 0.0f;if(x1 == x2 && y1 > y2) {

m = -63000; // stop division b 0} else if (x1 == x2 && y1 <= y2) {

m = 63000;} else m = (y2 - y1)/(x2 - x1);

glVertex2f(x, y); // plot this pointif( abs(m) < 1.0f) {

if( m > 0) { // Step on xsign = 1.0f; // 1, y increases

} else {sign = -1.0f; // 8, y decreases

}while ( x < x2) {

x = x + 1;e = e + m;if(abs(e) > 0.5) {

y = y + sign;e = e - sign;

} // Non-IntegerglVertex2f(x, y); // plot this point

} // First Octant} else {

if (m > 0.0f) {step = +1;

Page 87: CGLab Manual 2012

87

} else {step = -1;

}while ( (y - y2) * step < 0) {

y = y + step; // + or -e = e + 1.0f / m;if (abs(e) > 0.5) {

x = x + 1;e = e - step;

}glVertex2f(x, y); // plot this point

}}

}

void display(){ glClear(GL_COLOR_BUFFER_BIT); // clear the drawing area

glColor3f(1.0, 1.0, 1.0); // draw white linesglPointSize(1); // set one point to 1 pixel sizeglBegin(GL_POINTS); // start drawing pointsmyDrawLine(100, 1000, 200, 0); // draw the lineglEnd(); // end drawing pointsglFlush();

}

/* processHits prints out the contents of the * selection array */

void reshape(int w, int h){ glViewport(0, 0, (GLsizei) w, (GLsizei) h); // set viewport to fill window

glMatrixMode(GL_PROJECTION); // Select The Projection Matrix

glLoadIdentity();gluOrtho2D(0.0, (GLdouble) w, 0.0, (GLdouble) h);

// use orthographics projectionglClearColor(0.0, 0.0, 0.0, 0.0); // colour to clear

viewport toglClear(GL_COLOR_BUFFER_BIT); // clear viewport RGB

bitsglMatrixMode(GL_MODELVIEW); // Select model MatrixglLoadIdentity();

}

/* main loop */ int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);

Page 88: CGLab Manual 2012

88

glutInitWindowSize (500, 500); glutInitWindowPosition (100, 100); glutCreateWindow (argv[0]); init (); glutReshapeFunc (reshape); glutDisplayFunc(display); glutMainLoop(); return 0;}

Write a program to demo the usage of viewports. The program should define a viewport in the left half of the display window and the original triangle is displayed in blue color. Define another viewport for the right half of the window. The color of the triangle is changed to red and the triangle is rotated about its centroid and displayed in the second viewport.

#include<stdafx.h>#include <stdlib.h>#include <GL/glut.h>#include <math.h>

static int width;static int height;static int wh;static int hw;

void Tri(void){ glBegin(GL_TRIANGLES); glVertex3f(0,0,0); glVertex3f(0.5,0,0); glVertex3f(0.25,0.5,0); glEnd();

}

void DisplayFunc(void){ glClear(GL_COLOR_BUFFER_BIT);

Page 89: CGLab Manual 2012

89

glViewport(0, height / 2 + 1, width / 2 + 1, height / 2); glPushMatrix(); glColor3f(0,0,1); Tri(); glPopMatrix();

glViewport(width / 2 + 1, height / 2 + 1, width / 2, height / 2); glPushMatrix(); glColor3f(1,0,0);glTranslatef(.25, 0.1666, 0);glRotatef(180, 0, 0, 1.0); Tri(); glTranslatef(-0.25,-0.1666,0); glPopMatrix();

/* End */ glFlush(); glutSwapBuffers();}

void ReshapeFunc(int new_width, int new_height){ width = new_width; height = new_height;

hw = height / (float) width; wh = width / (float) height;

glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (height > width) glOrtho(-1.2, 1.2, -1.2 * hw, 1.2 * hw, -1.2, 1.2); else glOrtho(-1.2 * wh, 1.2 * wh, -1.2, 1.2, -1.2, 1.2); glMatrixMode(GL_MODELVIEW);

glutPostRedisplay();}

int main(int argc, char **argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE); glutInitWindowSize(500, 500); glutCreateWindow("Viewport"); glutDisplayFunc(&DisplayFunc); glutReshapeFunc(&ReshapeFunc); glutMainLoop();

Page 90: CGLab Manual 2012

90

return 0;}

/* ========================================================================= */

Page 91: CGLab Manual 2012

91

Lab 9

Write a program to implement the Cohen Sutherland line clipping algorithm in 2D. Make provision to specify the input line, window for clipping and view port for displaying the clipped image.

// Cohen-Suderland Line Clipping Algorithm with Window to viewport Mapping */#include <stdio.h>#include <GL/glut.h>#define outcode intdouble xmin=50,ymin=50, xmax=100,ymax=100; // Window boundariesdouble xvmin=200,yvmin=200,xvmax=300,yvmax=300; // Viewport boundaries//bit codes for the right, left, top, & bottomconst int RIGHT = 8;const int LEFT = 2;const int TOP = 4;const int BOTTOM = 1;//used to compute bit codes of a pointoutcode ComputeOutCode (double x, double y);//Cohen-Sutherland clipping algorithm clips a line from//P0 = (x0, y0) to P1 = (x1, y1) against a rectangle with//diagonal from (xmin, ymin) to (xmax, ymax).void CohenSutherlandLineClipAndDraw (double x0, double y0,double x1, double y1){//Outcodes for P0, P1, and whatever point lies outside the clip rectangle

outcode outcode0, outcode1, outcodeOut;bool accept = false, done = false;

//compute outcodesoutcode0 = ComputeOutCode (x0, y0);outcode1 = ComputeOutCode (x1, y1);do{

if (!(outcode0 | outcode1)) //logical or is 0 Trivially accept & exit

{accept = true;done = true;

}else if (outcode0 & outcode1) //logical and is not 0. Trivially

reject and exitdone = true;

else{

//failed both tests, so calculate the line segment to clip//from an outside point to an intersection with clip edge

double x, y;//At least one endpoint is outside the clip rectangle; pick

it.outcodeOut = outcode0? outcode0: outcode1;//Now find the intersection point;//use formulas y = y0 + slope * (x - x0), x = x0 +

(1/slope)* (y - y0)

Page 92: CGLab Manual 2012

92

if (outcodeOut & TOP) //point is above the clip rectangle{

x = x0 + (x1 - x0) * (ymax - y0)/(y1 - y0);y = ymax;

}else if (outcodeOut & BOTTOM) //point is below the clip

rectangle{

x = x0 + (x1 - x0) * (ymin - y0)/(y1 - y0);y = ymin;

}else if (outcodeOut & RIGHT) //point is to the right of clip

rectangle{

y = y0 + (y1 - y0) * (xmax - x0)/(x1 - x0);x = xmax;

}else //point is to the left of clip rectangle{

y = y0 + (y1 - y0) * (xmin - x0)/(x1 - x0);x = xmin;

}//Now we move outside point to intersection point to clip

//and get ready for next pass. if (outcodeOut == outcode0)

{x0 = x; y0 = y;

outcode0 = ComputeOutCode (x0, y0); }

else{

x1 = x; y1 = y;outcode1 = ComputeOutCode (x1, y1);

}}

}while (!done);if (accept){ // Window to viewport mappings

double sx=(xvmax-xvmin)/(xmax-xmin); // Scale parametersdouble sy=(yvmax-yvmin)/(ymax-ymin);double vx0=xvmin+(x0-xmin)*sx;double vy0=yvmin+(y0-ymin)*sy;double vx1=xvmin+(x1-xmin)*sx;double vy1=yvmin+(y1-ymin)*sy;//draw a red colored viewportglColor3f(1.0, 0.0, 0.0);glBegin(GL_LINE_LOOP);

glVertex2f(xvmin, yvmin);glVertex2f(xvmax, yvmin);glVertex2f(xvmax, yvmax);glVertex2f(xvmin, yvmax);

glEnd();glColor3f(0.0,0.0,1.0); // draw blue colored clipped lineglBegin(GL_LINES);

glVertex2d (vx0, vy0);glVertex2d (vx1, vy1);

glEnd();

Page 93: CGLab Manual 2012

93

}}

//Compute the bit code for a point (x, y) using the clip rectangle//bounded diagonally by (xmin, ymin), and (xmax, ymax)

outcode ComputeOutCode (double x, double y){

outcode code = 0;if (y > ymax) //above the clip window

code |= TOP;else if (y < ymin) //below the clip window

code |= BOTTOM;if (x > xmax) //to the right of clip window

code |= RIGHT;else if (x < xmin) //to the left of clip window

code |= LEFT;return code;

}

void display(){

double x0=120,y0=10,x1=40,y1=130;glClear(GL_COLOR_BUFFER_BIT);//draw the line with red colorglColor3f(1.0,0.0,0.0);//bres(120,20,340,250);glBegin(GL_LINES);

glVertex2d (x0, y0);glVertex2d (x1, y1);glVertex2d (60,20);glVertex2d (80,120);

glEnd();//draw a blue colored windowglColor3f(0.0, 0.0, 1.0);glBegin(GL_LINE_LOOP);

glVertex2f(xmin, ymin);glVertex2f(xmax, ymin);glVertex2f(xmax, ymax);glVertex2f(xmin, ymax);

glEnd();CohenSutherlandLineClipAndDraw(x0,y0,x1,y1);CohenSutherlandLineClipAndDraw(60,20,80,120);glFlush();

}void myinit(){

glClearColor(1.0,1.0,1.0,1.0);glColor3f(1.0,0.0,0.0);glPointSize(1.0);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,499.0,0.0,499.0);

}void main(int argc, char** argv){

Page 94: CGLab Manual 2012

94

//int x1, x2, y1, y2;//printf("Enter End points:");//scanf("%d%d%d%d", &x1,&x2,&y1,&y2);glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(0,0);glutCreateWindow("Cohen Suderland Line Clipping Algorithm");glutDisplayFunc(display);myinit();glutMainLoop();

}

Output:

Write a program to draw a color cube and allow the user to move the camera suitably to experiment with perspective viewing. Use OpenGL functions.

/* We use the Lookat function in the display callback to point the viewer, whose position can be altered by the x,X,y,Y,z, and Z keys.The perspective view is set in the reshape callback */#include <stdlib.h>#include <GL/glut.h>

GLfloat vertices[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0}, {1.0,1.0,-1.0}, {-1.0,1.0,-1.0}, {-1.0,-1.0,1.0}, {1.0,-1.0,1.0}, {1.0,1.0,1.0}, {-1.0,1.0,1.0}};GLfloat normals[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0}, {1.0,1.0,-1.0}, {-1.0,1.0,-1.0}, {-1.0,-1.0,1.0}, {1.0,-1.0,1.0}, {1.0,1.0,1.0}, {-1.0,1.0,1.0}};GLfloat colors[][3] = {{0.0,0.0,0.0},{1.0,0.0,0.0},{1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}, {1.0,0.0,1.0}, {1.0,1.0,1.0}, {0.0,1.0,1.0}};void polygon(int a, int b, int c , int d){

Page 95: CGLab Manual 2012

95

glBegin(GL_POLYGON);glColor3fv(colors[a]);glNormal3fv(normals[a]);glVertex3fv(vertices[a]);glColor3fv(colors[b]);glNormal3fv(normals[b]);glVertex3fv(vertices[b]);glColor3fv(colors[c]);glNormal3fv(normals[c]);glVertex3fv(vertices[c]);glColor3fv(colors[d]);glNormal3fv(normals[d]);glVertex3fv(vertices[d]);

glEnd();}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);

}static GLfloat theta[] = {0.0,0.0,0.0};static GLint axis = 2;static GLdouble viewer[]= {0.0, 0.0, 5.0}; /* initial viewer location */void display(void){

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);/* Update viewer position in modelview matrix */glLoadIdentity();

gluLookAt(viewer[0],viewer[1],viewer[2], 0.0, 0.0, 0.0, 0.0, 1.0,0.0);/* rotate cube */glRotatef(theta[0], 1.0, 0.0, 0.0);glRotatef(theta[1], 0.0, 1.0, 0.0);glRotatef(theta[2], 0.0, 0.0, 1.0);colorcube();glFlush();glutSwapBuffers();

}void mouse(int btn, int state, int x, int y){

if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) axis = 0;if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) axis = 1;if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN) axis = 2;theta[axis] += 2.0;if( theta[axis] > 360.0 ) theta[axis] -= 360.0;display();

}void keys(unsigned char key, int x, int y){

/* Use x, X, y, Y, z, and Z keys to move viewer */if(key == 'x') viewer[0]-= 1.0;if(key == 'X') viewer[0]+= 1.0;if(key == 'y') viewer[1]-= 1.0;

Page 96: CGLab Manual 2012

96

if(key == 'Y') viewer[1]+= 1.0;if(key == 'z') viewer[2]-= 1.0;if(key == 'Z') viewer[2]+= 1.0;display();

}void myReshape(int w, int h){

glViewport(0, 0, w, h);/* Use a perspective view */glMatrixMode(GL_PROJECTION);glLoadIdentity();if(w<=h)

glFrustum(-2.0, 2.0, -2.0 * (GLfloat) h/ (GLfloat) w,2.0* (GLfloat) h / (GLfloat) w, 2.0, 20.0);

else glFrustum(-2.0, 2.0, -2.0 * (GLfloat) w/ (GLfloat) h, 2.0*

(GLfloat) w / (GLfloat) h, 2.0, 20.0);/* Or we can use gluPerspective *//* gluPerspective(45.0, w/h, -10.0, 10.0); */glMatrixMode(GL_MODELVIEW);

}void main(int argc, char **argv){

glutInit(&argc, argv);glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);glutInitWindowSize(500, 500);glutCreateWindow("Colorcube Viewer");glutReshapeFunc(myReshape);glutDisplayFunc(display);glutMouseFunc(mouse);glutKeyboardFunc(keys);glEnable(GL_DEPTH_TEST);glutMainLoop();

}

Output:

Page 97: CGLab Manual 2012

97

Write a program to fill any given polygon using scan-line area filling algorithm. (Use appropriate data structures.)

// Scan-Line algorithm for filling a polygon#define BLACK 0#include <stdlib.h>#include <stdio.h>#include <GL/glut.h>float x1,x2,x3,x4,y1,y2,y3,y4;void edgedetect(float x1,float y1,float x2,float y2,int *le,int *re){

float mx,x,temp;int i;if((y2-y1)<0){

temp=y1;y1=y2;y2=temp;temp=x1;x1=x2;x2=temp;

}if((y2-y1)!=0)

mx=(x2-x1)/(y2-y1);else

mx=x2-x1;x=x1;

for(i=y1;i<=y2;i++){

if(x<(float)le[i])le[i]=(int)x;if(x>(float)re[i])re[i]=(int)x;x+=mx;

}}void draw_pixel(int x,int y,int value)

Page 98: CGLab Manual 2012

98

{glColor3f(1.0,1.0,0.0);glBegin(GL_POINTS);glVertex2i(x,y);glEnd();

}void scanfill(float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4){

int le[500],re[500];int i,y;for(i=0;i<500;i++){

le[i]=500;re[i]=0;

}edgedetect(x1,y1,x2,y2,le,re);edgedetect(x2,y2,x3,y3,le,re);edgedetect(x3,y3,x4,y4,le,re);edgedetect(x4,y4,x1,y1,le,re);for(y=0;y<500;y++){

if(le[y]<=re[y])for(i=(int)le[y];i<(int)re[y];i++)

draw_pixel(i,y,BLACK);}

}void display(){

x1=200.0;y1=200.0;x2=100.0;y2=300.0;x3=200.0;y3=400.0;x4=300.0;y4=300.0;glClear(GL_COLOR_BUFFER_BIT);glColor3f(0.0, 0.0, 1.0);

glBegin(GL_LINE_LOOP);glVertex2f(x1,y1);glVertex2f(x2,y2);glVertex2f(x3,y3);glVertex2f(x4,y4);

glEnd();scanfill(x1,y1,x2,y2,x3,y3,x4,y4);glFlush();

}void myinit(){

glClearColor(1.0,1.0,1.0,1.0);glColor3f(1.0,0.0,0.0);glPointSize(1.0);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D(0.0,499.0,0.0,499.0);

}void main(int argc, char** argv){

glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500,500);

Page 99: CGLab Manual 2012

99

glutInitWindowPosition(0,0);glutCreateWindow("Filling a Polygon using Scan-line Algorithm");glutDisplayFunc(display);myinit();glutMainLoop();

}

Output: