69
1 Introduction to OpenGL Prof. George Wolberg Dept. of Computer Science City College of New York 2 Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003 The Programmer’s Interface • Programmer sees the graphics system through an interface: the Application Programmer Interface (API) 3 Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003 API Contents • Functions that specify what we need to form an image - Objects - Viewer - Light Source(s) - Materials • Other information - Input from devices such as mouse and keyboard - Capabilities of system 4 Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003 Object Specification • Most APIs support a limited set of primitives including - Points (1D object) - Line segments (2D objects) - Polygons (3D objects) - Some curves and surfaces Quadrics Parametric polynomial • All are defined through locations in space or vertices 5 Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003 Example glBegin(GL_POLYGON) glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 1.0, 0.0); glVertex3f(0.0, 0.0, 1.0); glEnd( ); type of object location of vertex end of object definition 6 Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003 Camera Specification • Six degrees of freedom - Position of center of lens - Orientation • Lens • Film size • Orientation of film plane

The Programmer’s Interface Introduction to OpenGL ...wolberg/capstone/opengl/opengl.pdf · 1 Introduction to OpenGL Prof. George Wolberg Dept. of Computer Science City College of

  • Upload
    others

  • View
    12

  • Download
    0

Embed Size (px)

Citation preview

  • 1

    Introduction to OpenGL

    Prof. George WolbergDept. of Computer ScienceCity College of New York

    2Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The Programmer’s Interface

    •Programmer sees the graphics system through an interface: the Application Programmer Interface (API)

    3Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    API Contents

    •Functions that specify what we need to form an image

    - Objects- Viewer- Light Source(s)- Materials

    •Other information- Input from devices such as mouse and keyboard- Capabilities of system

    4Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Object Specification

    •Most APIs support a limited set of primitives including

    - Points (1D object)- Line segments (2D objects)- Polygons (3D objects)- Some curves and surfaces

    • Quadrics• Parametric polynomial

    •All are defined through locations in space or vertices

    5Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example

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

    glEnd( );

    type of objectlocation of vertex

    end of object definition

    6Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Camera Specification

    •Six degrees of freedom- Position of center of lens- Orientation

    •Lens•Film size•Orientation of film plane

  • 2

    7Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Lights and Materials

    •Types of lights- Point sources vs distributed sources- Spot lights- Near and far sources- Color properties

    •Material properties- Absorption: color properties- Scattering

    • Diffuse• Specular

    8Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Following the Pipeline:Transformations

    •Much of the work in the pipeline is in converting object representations from one coordinate system to another

    - World coordinates- Camera coordinates- Screen coordinates

    •Every change of coordinates is equivalent to a matrix transformation

    9Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Clipping

    • Just as a real camera cannot “see” the whole world, the virtual camera can only see part of the world space

    - Objects that are not within this volume are said to be clipped out of the scene

    10Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Projection

    •Must carry out the process that combines the 3D viewer with the 3D objects to produce the 2D image

    - Perspective projections: all projectors meet at the center of projection

    - Parallel projection: projectors are parallel, center of projection is replaced by a direction of projection

    11Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rasterization

    • If an object is visible in the image, the appropriate pixels in the frame buffer must be assigned colors

    - Vertices assembled into objects- Effects of lights and materials must be

    determined- Polygons filled with interior colors/shades- Must have also determined which objects are

    in front (hidden surface removal)

    Programming with OpenGLPart 1: Background

    Prof. George WolbergDept. of Computer ScienceCity College of New York

  • 3

    13Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    •Development of the OpenGL API•OpenGL Architecture

    - OpenGL as a state machine

    •Functions - Types- Formats

    •Simple program

    14Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Early History of APIs

    • IFIPS (1973) formed two committees to come up with a standard graphics API

    - Graphical Kernel System (GKS)• 2D but contained good workstation model

    - Core • Both 2D and 3D

    - GKS adopted as IS0 and later ANSI standard (1980s)

    •GKS not easily extended to 3D (GKS-3D)•Far behind hardware development

    15Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    PHIGS and X

    •Programmers Hierarchical Graphics System (PHIGS)

    - Arose from CAD community- Database model with retained graphics

    (structures)•X Window System

    - DEC/MIT effort- Client-server architecture with graphics

    •PEX combined the two- Not easy to use (all the defects of each)

    16Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    SGI and GL

    •Silicon Graphics (SGI) revolutionized the graphics workstation by implementing the pipeline in hardware (1982)

    •To use the system, application programmers used a library called GL

    •With GL, it was relatively simple to program three dimensional interactive applications

    17Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL

    •The success of GL lead to OpenGL in 1992, a platform-independent API that was

    - Easy to use- Close enough to the hardware to get excellent

    performance- Focused on rendering- Omitted windowing and input to avoid window

    system dependencies

    18Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL Evolution

    •Controlled by an Architectural Review Board (ARB)

    - Members include SGI, Microsoft, Nvidia, HP, 3DLabs,IBM,…….

    - Relatively stable (present version 1.4)• Evolution reflects new hardware capabilities

    – 3D texture mapping and texture objects– Vertex programs

    - Allows for platform specific features through extensions

    - See www.opengl.org for up-to-date info

  • 4

    19Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL Libraries

    •OpenGL core library- OpenGL32 on Windows- GL on most Unix/Linux systems

    •OpenGL Utility Library (GLU)- Provides functionality in OpenGL core but

    avoids having to rewrite code•Links with window system

    - GLX for X window systems- WGL for Windows- AGL for Macintosh

    20Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    GLUT

    •OpenGL Utility Toolkit (GLUT)- Provides functionality common to all window

    systems• Open a window• Get input from mouse and keyboard• Menus• Event-driven

    - Code is portable but GLUT lacks the functionality of a good toolkit for a specific platform

    • Slide bars

    21Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Software Organization

    GLUT

    GLU

    GL

    GLX, AGLor WGL

    X, Win32, Mac O/S

    software and/or hardware

    application program

    OpenGL Motifwidget or similar

    22Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL Architecture

    Immediate Mode

    DisplayList

    PolynomialEvaluator

    Per VertexOperations &

    PrimitiveAssembly

    Rasterization Per FragmentOperations

    TextureMemory

    CPU

    PixelOperations

    FrameBuffer

    Geometricpipeline

    23Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL Functions

    • Primitives- Points- Line Segments- Polygons

    • Attributes• Transformations

    - Viewing- Modeling

    • Control• Input (GLUT)

    24Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL State

    •OpenGL is a state machine•OpenGL functions are of two types

    - Primitive generating• Can cause output if primitive is visible• How vertices are processed and appearance of primitive

    are controlled by the state

    - State changing• Transformation functions• Attribute functions

  • 5

    25Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Lack of Object Orientation

    •OpenGL is not object oriented so that there are multiple functions for a given logical function, e.g. glVertex3f, glVertex2i, glVertex3dv,…..

    •Underlying storage mode is the same•Easy to create overloaded functions in C++ but issue is efficiency

    26Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL function format

    glVertex3f(x,y,z)

    belongs to GL library

    function name

    x,y,z are floats

    glVertex3fv(p)

    p is a pointer to an array

    27Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL #defines

    •Most constants are defined in the include files gl.h, glu.h and glut.h

    - Note #include should automatically include the others

    - Examples-glBegin(GL_POLYGON)-glClear(GL_COLOR_BUFFER_BIT)

    • include files also define OpenGL data types: Glfloat, Gldouble,….

    28Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    A Simple Program

    Generate a square on a solid background

    29Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    simple.c

    #include void mydisplay(){

    glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON);

    glVertex2f(-0.5,-0.5); glVertex2f(-0.5, 0.5); glVertex2f( 0.5, 0.5); glVertex2f( 0.5,-0.5);

    glEnd();glFlush();

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

    glutCreateWindow("simple"); glutDisplayFunc(mydisplay); glutMainLoop();

    }30Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Event Loop

    •Note that the program defines a display callback function named mydisplay

    - Every glut program must have a display callback

    - The display callback is executed whenever OpenGL decides the display must be refreshed, for example when the window is opened

    - The main function ends with the program entering an event loop

  • 6

    31Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Defaults

    •simple.c is too simple•Makes heavy use of state variable default values for

    - Viewing- Colors- Window parameters

    •Next version will make the defaults more explicit

    32Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Notes on compilation

    •See website and ftp for examples•Unix/Linux

    - Include files usually in …/include/GL- Compile with –lglut –lglu –lgl loader flags- May have to add –L flag for X libraries- Mesa implementation included with most linux

    distributions- Check web for latest versions of Mesa and glut

    33Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Compilation on Windows

    •Visual C++- Get glut.h, glut32.lib and glut32.dll from web- Create a console application- Add opengl32.lib, glut32.lib, glut32.lib to project

    settings (under link tab)

    •Borland C similar•Cygwin (linux under Windows)

    - Can use gcc and similar makefile to linux- Use –lopengl32 –lglu32 –lglut32 flags

    Programming with OpenGLPart 2: Complete Programs

    Prof. George WolbergDept. of Computer ScienceCity College of New York

    35Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    •Refine the first program- Alter the default values- Introduce a standard program structure

    •Simple viewing- Two-dimensional viewing as a special case of

    three-dimensional viewing

    •Fundamental OpenGL primitives•Attributes

    36Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Program Structure

    • Most OpenGL programs have a similar structure that consists of the following functions

    -main(): • defines the callback functions • opens one or more windows with the required properties• enters event loop (last executable statement)

    -init(): sets the state variables• viewing• Attributes

    - callbacks• Display function• Input and window functions

  • 7

    37Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Simple.c revisited

    • In this version, we will see the same output but have defined all the relevant state values through function calls with the default values

    • In particular, we set- Colors- Viewing conditions- Window properties

    38Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    main.c

    #include

    int main(int argc, char** argv){glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("simple"); glutDisplayFunc(mydisplay);

    init();

    glutMainLoop();}

    includes gl.h

    define window properties

    set OpenGL state

    enter event loop

    display callback

    39Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    GLUT functions

    •glutInit allows application to get command line arguments and initializes system

    •gluInitDisplayMode requests properties of the window (the rendering context)

    - RGB color- Single buffering- Properties logically ORed together

    •glutWindowSize in pixels•glutWindowPosition from top-left corner of

    display•glutCreateWindow create window with title

    “simple”•glutDisplayFunc display callback•glutMainLoop enter infinite event loop 40Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    init.c

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

    glColor3f(1.0, 1.0, 1.0);

    glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

    }

    black clear coloropaque window

    fill with white

    viewing volume

    41Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Coordinate Systems

    •The units of in glVertex are determined by the application and are called world or problem coordinates

    •The viewing specifications are also in world coordinates and it is the size of the viewing volume that determines what will appear in the image

    • Internally, OpenGL will convert to camera coordinates and later to screen coordinates

    42Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL Camera

    •OpenGL places a camera at the origin pointing in the negative z direction

    •The default viewing volumeis a box centered at theorigin with a side of length 2

  • 8

    43Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Orthographic Viewing

    z=0

    z=0

    In the default orthographic view, points are projected forward along the z axis onto theplane z=0

    44Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Transformations and Viewing

    • In OpenGL, the projection is carried out by a projection matrix (transformation)

    • There is only one set of transformation functions so we must set the matrix mode first glMatrixMode (GL_PROJECTION)

    • Transformation functions are incremental so we start with an identity matrix and alter it with a projection matrix that gives the view volumeglLoadIdentity (); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

    45Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Two- and three-dimensional viewing

    • In glOrtho(left, right, bottom, top, near, far) the near and far distances are measured from the camera

    • Two-dimensional vertex commands place all vertices in the plane z=0

    • If the application is in two dimensions, we can use the functiongluOrtho2D(left, right,bottom,top)

    • In two dimensions, the view or clipping volume becomes a clipping window

    46Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    mydisplay.c

    void mydisplay(){

    glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON);

    glVertex2f(-0.5,-0.5); glVertex2f(-0.5, 0.5); glVertex2f( 0.5, 0.5); glVertex2f( 0.5,-0.5);

    glEnd();glFlush();

    }

    47Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL Primitives

    GL_QUAD_STRIPGL_QUAD_STRIP

    GL_POLYGONGL_POLYGON

    GL_TRIANGLE_STRIPGL_TRIANGLE_STRIP GL_TRIANGLE_FANGL_TRIANGLE_FAN

    GL_POINTSGL_POINTS

    GL_LINESGL_LINES

    GL_LINE_LOOPGL_LINE_LOOP

    GL_LINE_STRIPGL_LINE_STRIP

    GL_TRIANGLESGL_TRIANGLES

    48Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example: Drawing an Arc

    •Given a circle with radius r, centered at (x,y), draw an arc of the circle that sweeps out an angle θ.

    .20for ),sin,cos(),( 00

    πθθθ

    ≤≤++= ryrxyx

  • 9

    49Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The Line Strip Primitive

    void drawArc(float x, float y, float r,float t0, float sweep)

    {float t, dt; /* angle */int n = 30; /* # of segments */int i;

    t = t0 * PI/180.0; /* radians */dt = sweep * PI/(180*n); /* increment */

    glBegin(GL_LINE_STRIP);for(i=0; i

  • 10

    55Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Smooth Color

    • Default is smooth shading- OpenGL interpolates vertex colors across

    visible polygons• Alternative is flat shading

    - Color of first vertex determines fill color

    •glShadeModel(GL_SMOOTH)or GL_FLAT

    56Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Viewports

    •Do not have use the entire window for the image: glViewport(x,y,w,h)

    •Values in pixels (screen coordinates)

    Programming with OpenGLPart 3: Three Dimensions

    Prof. George WolbergDept. of Computer ScienceCity College of New York

    58Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    •Develop a more sophisticated three-dimensional example

    - Sierpinski gasket: a fractal

    • Introduce hidden-surface removal

    59Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Three-dimensional Applications

    • In OpenGL, two-dimensional applications are a special case of three-dimensional graphics

    - Not much changes- Use glVertex3*( )- Have to worry about the order in which

    polygons are drawn or use hidden-surface removal

    - Polygons should be simple, convex, flat

    60Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Sierpinski Gasket (2D)

    • Start with a triangle

    • Connect bisectors of sides and remove central triangle

    • Repeat

  • 11

    61Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example

    •Five subdivisions

    62Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The gasket as a fractal

    •Consider the filled area (black) and the perimeter (the length of all the lines around the filled triangles)

    •As we continue subdividing- the area goes to zero- but the perimeter goes to infinity

    •This is not an ordinary geometric object- It is neither two- nor three-dimensional

    • It has a fractal (fractional dimension) object

    63Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Gasket Program

    #include

    /* a point data typetypedef GLfloat point2[2];

    /* initial triangle */

    point2 v[]={{-1.0, -0.58}, {1.0, -0.58}, {0.0, 1.15}};

    int n; /* number of recursive steps */

    64Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Draw a triangle

    /* display one triangle */void triangle( point2 a, point2 b, point2 c){

    glBegin(GL_TRIANGLES);glVertex2fv(a); glVertex2fv(b); glVertex2fv(c);

    glEnd();}

    65Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Triangle Subdivision

    /* triangle subdivision using vertex numbers */void divide_triangle(point2 a, point2 b, point2 c, int m)

    {point2 v0, v1, v2;int j;

    if(m > 0) {for(j=0; j

  • 12

    67Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    main Function

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

    n=4;glutInit(&argc, argv);glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);glutInitWindowSize(500, 500);glutCreateWindow(“2D Gasket");glutDisplayFunc(display);myinit();glutMainLoop();

    }

    68Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Moving to 3D

    •We can easily make the program three-dimensional by using typedef Glfloat point3[3]glVertex3fglOrtho

    •But that would not be very interesting• Instead, we can start with a tetrahedron

    69Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    3D Gasket

    •We can subdivide each of the four faces

    •Appears as if we remove a solid tetrahedron from the center leaving four smaller tetrahedtra

    70Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example

    after 5 iterations

    71Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    triangle code

    void triangle(point3 a, point3 b, point3 c){

    glBegin(GL_POLYGON);glVertex3fv(a);glVertex3fv(b);glVertex3fv(c);

    glEnd();}

    72Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    subdivision code

    void divide_triangle(point3 a, point3 b, point3 c, int m)

    {point3 v1, v2, v3;int j;

    if(m > 0) {for(j=0; j

  • 13

    73Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    tetrahedron code

    void tetrahedron(int m){

    glColor3f(1.0,0.0,0.0);divide_triangle(v[0], v[1], v[2], m);

    glColor3f(0.0,1.0,0.0);divide_triangle(v[3], v[2], v[1], m);

    glColor3f(0.0,0.0,1.0);divide_triangle(v[0], v[3], v[1], m);

    glColor3f(0.0,0.0,0.0);divide_triangle(v[0], v[2], v[3], m);

    }

    74Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Almost Correct

    • Because the triangles are drawn in the order they are defined in the program, the front triangles are not always rendered in front of triangles behind them

    get this

    want this

    75Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Hidden-Surface Removal

    • We want to see only those surfaces in front of other surfaces

    • OpenGL uses a hidden-surface method called the z-buffer algorithm that saves depth information as objects are rendered so that only the front objects appear in the image

    76Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Using the z-buffer algorithm

    • The algorithm uses an extra buffer, the z-buffer, to store depth information as geometry travels down the pipeline

    • It must be- Requested in main.c

    •glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH)

    - Enabled in init.c•glEnable(GL_DEPTH_TEST)

    - Cleared in the display callback•glClear(GL_COLOR_BUFFER_BIT |

    GL_DEPTH_BUFFER_BIT)

    77Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example: Drawing a Sphere

    • In this example, we draw a sphere using a combination of OpenGL primitives.

    •Locate points on the sphere by varying two parameters: longitude and latitude.

    φφθφθφθφθφθ

    cos),(coscos),(cossin),(

    ===

    zyx

    78Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    c = M_PI / 180.0; /* convert degrees to radians */for(p = -80.0; p

  • 14

    79Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    /* north pole */z = 1.0;glBegin(GL_TRIANGLE_FAN);glVertex3d(x, y, z);z = cos(c*80.0);for(t = -180.0; t

  • 15

    85Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Graphical Input

    •Devices can be described either by- Physical properties

    • Mouse• Keyboard• Trackball

    - Logical Properties• What is returned to program via API

    – A position– An object identifier

    •Modes- How and when input is obtained

    • Request or event

    86Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Physical Devices

    mouse trackball light pen

    data tablet joy stick space ball

    87Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Incremental (Relative) Devices

    •Devices such as the data tablet return a position directly to the operating system

    •Devices such as the mouse, trackball, and joy stick return incremental inputs (or velocities) to the operating system

    - Must integrate these inputs to obtain an absolute position

    • Rotation of wheels in mouse• Roll of trackball• Difficult to obtain absolute position• Can get variable sensitivity

    88Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Logical Devices

    •Consider the C and C++ code- C++: cin >> x;- C: scanf (“%d”, &x);

    •What is the input device?- Can’t tell from the code- Could be keyboard, file, output from another

    program•The code provides logical input

    - A number (an int) is returned to the program regardless of the physical device

    89Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Graphical Logical Devices

    • Graphical input is more varied than input to standard programs which is usually numbers, characters, or bits

    • Two older APIs (GKS, PHIGS) defined six types of logical input

    - Locator: return a position- Pick: return ID of an object- Keyboard: return strings of characters- Stroke: return array of positions- Valuator: return floating point number- Choice: return one of n items

    90Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    X Window Input

    • The X Window System introduced a client-server model for a network of workstations

    - Client: OpenGL program- Graphics Server: bitmap display with a pointing

    device and a keyboard

  • 16

    91Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Input Modes

    • Input devices contain a trigger which can be used to send a signal to the operating system

    - Button on mouse- Pressing or releasing a key

    •When triggered, input devices return information (their measure) to the system

    - Mouse returns position information- Keyboard returns ASCII code

    92Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Request Mode

    • Input provided to program only when user triggers the device

    •Typical of keyboard input- Can erase (backspace), edit, correct until enter

    (return) key (the trigger) is depressed

    93Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Event Mode

    •Most systems have more than one input device, each if which can be triggered at an arbitrary time by a user

    •Each trigger generates an event whose measure is put in an event queue which can be examined by the user program

    94Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Event Types

    •Window: resize, expose, iconify•Mouse: click one or more buttons•Motion: move mouse•Keyboard: press or release a key• Idle: nonevent

    - Define what should be done if no other event is in queue

    95Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Callbacks

    •Programming interface for event-driven input

    •Define a callback function for each type of event the graphics system recognizes

    •This user-supplied function is executed when the event occurs

    •GLUT example: glutMouseFunc(mymouse)

    mouse callback function96Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    GLUT callbacks

    GLUT recognizes a subset of the events recognized by any particular window system (Windows, X, Macintosh)

    -glutDisplayFunc-glutMouseFunc-glutReshapeFunc-glutKeyFunc-glutIdleFunc-glutMotionFunc, glutPassiveMotionFunc

  • 17

    97Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    GLUT Event Loop

    • Remember that the last line in main.c for a program using GLUT must beglutMainLoop();

    which puts the program in an infinite event loop• In each pass through the event loop, GLUT

    - looks at the events in the queue- for each event in the queue, GLUT executes the

    appropriate callback function if one is defined- if no callback is defined for the event, the event is

    ignored

    98Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The display callback

    • The display callback is executed whenever GLUT determines that the window should be refreshed, for example

    - When the window is first opened- When the window is reshaped- When a window is exposed- When the user program decides it wants to change the

    display• In main.c

    -glutDisplayFunc(mydisplay) identifies the function to be executed

    - Every GLUT program must have a display callback

    99Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Posting redisplays

    • Many events may invoke the display callback function

    - Can lead to multiple executions of the display callback on a single pass through the event loop

    • We can avoid this problem by instead usingglutPostRedisplay();

    which sets a flag. • GLUT checks to see if the flag is set at the end of the event loop

    • If set then the display callback function is executed

    100Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Animating a Display

    • When we redraw the display through the display callback, we usually start by clearing the window

    -glClear()

    then draw the altered display• Problem: the drawing of information in the frame buffer is decoupled from the display of its contents

    - Graphics systems use dual ported memory• Hence we can see partially drawn display

    - See the program single_double.c for an example with a rotating cube

    101Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Double Buffering

    • Instead of one color buffer, we use two- Front Buffer: one that is displayed but not written to- Back Buffer: one that is written to but not displayed

    • Program then requests a double buffer in main.c-glutInitDisplayMode(GL_RGB | GL_DOUBLE)- At the end of the display callback buffers are swapped

    void mydisplay(){

    glClear()./* draw graphics here */.

    glutSwapBuffers()}

    102Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Using the idle callback

    • The idle callback is executed whenever there are no events in the event queue

    -glutIdleFunc(myidle)- Useful for animations

    void myidle() {/* change something */t += dtglutPostRedisplay();

    }

    Void mydisplay() {glClear();/* draw something that depends on t */glutSwapBuffers();

    }

  • 18

    103Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Using globals

    • The form of all GLUT callbacks is fixed- void mydisplay()- void mymouse(GLint button, GLint state, GLint x, GLint y)

    • Must use globals to pass information to callbacksfloat t; /* global */

    void mydisplay(){

    /* draw something that depends on t}

    Working with Callbacks

    Prof. George WolbergDept. of Computer ScienceCity College of New York

    105Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    •Learn to build interactive programs using GLUT callbacks

    - Mouse- Keyboard- Reshape

    • Introduce menus in GLUT

    106Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The mouse callback

    •glutMouseFunc(mymouse)•void mymouse(GLint button, GLint state, GLint x, GLint y)

    •Returns - which button (GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, GLUT_RIGHT_BUTTON) caused event

    - state of that button (GLUT_UP, GLUT_DOWN)- Position in window

    107Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Positioning

    • The position in the screen window is usually measured in pixels with the origin at the top-left corner

    • Consequence of refresh done from top to bottom• OpenGL uses a world coordinate system with origin at

    the bottom left• Must invert y coordinate returned by callback by

    height of window• y = h – y;

    (0,0) h

    w 108Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Obtaining the window size

    •To invert the y position we need the window height

    - Height can change during program execution- Track with a global variable- New height returned to reshape callback that

    we will look at in detail soon- Can also use enquiry functions

    •glGetIntv•glGetFloatv

    to obtain any value that is part of the state

  • 19

    109Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Terminating a program

    • In our original programs, there was no way to terminate them through OpenGL

    •We can use the simple mouse callback

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

    if(btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN)exit(0);

    }

    110Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Using the mouse position

    • In the next example, we draw a small square at the location of the mouse each time the left mouse button is clicked

    •This example does not use the display callback but one is required by GLUT; We can use the empty display callback functionmydisplay(){}

    111Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Drawing squares at cursor location

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

    if(btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN)exit(0);

    if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN)drawSquare(x, y);

    }void drawSquare(int x, int y){

    y = h-y; /* invert y position */glColor3ub( (char) rand()%256, (char) rand )%256,

    (char) rand()%256); /* a random color */glBegin(GL_POLYGON);

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

    glEnd();}

    112Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Using the motion callback

    •We can draw squares (or anything else) continuously as long as a mouse button is depressed by using the motion callback

    - glutMotionFunc(drawSquare)

    •We can draw squares without depressing a button using the passive motion callback

    - glutPassiveMotionFunc(drawSquare)

    113Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Using the keyboard

    •glutKeyboardFunc(mykey)•Void mykey(unsigned char key,

    int x, int y)- Returns ASCII code of key depressed and mouse

    location- Note GLUT does not recognize key release as an event

    void mykey(){

    if(key == ‘Q’ | key == ‘q’) exit(0);

    }

    114Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Special and Modifier Keys

    • GLUT defines the special keys in glut.h- Function key 1: GLUT_KEY_F1- Up arrow key: GLUT_KEY_UP

    • if(key == ‘GLUT_KEY_F1’ ……

    • Can also check if one of the modifiers-GLUT_ACTIVE_SHIFT-GLUT_ACTIVE_CTRL-GLUT_ACTIVE_ALTis depressed byglutGetModifiers()

    - Allows emulation of three-button mouse with one- or two-button mice

  • 20

    115Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Reshaping the window

    •We can reshape and resize the OpenGL display window by pulling the corner of the window

    •What happens to the display?- Must redraw from application- Two possibilities

    • Display part of world• Display whole world but force to fit in new window

    – Can alter aspect ratio

    116Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Reshape possibilities

    original

    reshaped

    117Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The Reshape callback

    •glutReshapeFunc(myreshape)•void myreshape( int w, int h)

    - Returns width and height of new window (in pixels)- A redisplay is posted automatically at end of

    execution of the callback- GLUT has a default reshape callback but you

    probably want to define your own•The reshape callback is good place to put camera functions because it is invoked when the window is first opened

    118Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example Reshape

    • This reshape preserves shapes by making the viewport and world window have the same aspect ratio

    void myReshape(int w, int h){

    glViewport(0, 0, w, h);glMatrixMode(GL_PROJECTION); /* switch matrix mode */glLoadIdentity();if (w

  • 21

    121Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Defining a simple menu

    • In main.cmenu_id = glutCreateMenu(mymenu);glutAddmenuEntry(“clear Screen”, 1);

    gluAddMenuEntry(“exit”, 2);

    glutAttachMenu(GLUT_RIGHT_BUTTON);

    entries that appear whenright button depressed

    identifiers

    clear screen

    exit

    122Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Menu actions

    - Menu callback

    - Note each menu has an id that is returned when it is created

    - Add submenus byglutAddSubMenu(char *submenu_name, submenu id)

    void mymenu(int id){

    if(id == 1) glClear();if(id == 2) exit(0);

    }

    entry in parent menu

    123Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Other functions in GLUT

    •Dynamic Windows- Create and destroy during execution

    •Subwindows•Multiple Windows•Changing callbacks during execution•Timers•Portable fonts

    -glutBitmapCharacter-glutStrokeCharacter

    Better Interactive Programs

    Prof. George WolbergDept. of Computer ScienceCity College of New York

    125Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    •Learn to build more sophisticated interactive programs using

    - Picking• Select objects from the display• Three methods

    - Rubberbanding• Interactive drawing of lines and rectangles

    - Display Lists• Retained mode graphics

    126Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Picking

    • Identify a user-defined object on the display• In principle, it should be simple because the mouse gives the position and we should be able to determine to which object(s) a position corresponds

    • Practical difficulties- Pipeline architecture is feed forward, hard to go from

    screen back to world- Complicated by screen being 2D, world is 3D- How close do we have to come to object to say we

    selected it?

  • 22

    127Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Three Approaches

    •Hit list- Most general approach but most difficult to

    implement

    •Use back or some other buffer to store object ids as the objects are rendered

    •Rectangular maps - Easy to implement for many applications- See paint program in text

    128Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rendering Modes

    •OpenGL can render in one of three modes selected by glRenderMode(mode)

    -GL_RENDER: normal rendering to the frame buffer (default)

    -GL_FEEDBACK: provides list of primitives rendered but no output to the frame buffer

    -GL_SELECTION: Each primitive in the view volume generates a hit record that is placed in a name stack which can be examined later

    129Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Selection Mode Functions

    •glSelectBuffer(): specifies name buffer•glInitNames(): initializes name buffer•glPushName(id): push id on name buffer•glPopName(): pop top of name buffer•glLoadName(id): replace top name on buffer

    • id is set by application program to identify objects

    130Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Using Selection Mode

    • Initialize name buffer•Enter selection mode (using mouse)•Render scene with user-defined identifiers•Reenter normal render mode

    - This operation returns number of hits

    •Examine contents of name buffer (hit records)

    - Hit records include id and depth information

    131Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Selection Mode and Picking

    •As we just described it, selection mode won’t work for picking because every primitive in the view volume will generate a hit

    •Change the viewing parameters so that only those primitives near the cursor are in the altered view volume

    - Use gluPickMatrix (see text for details)

    132Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example: Picking

    • In this example, we use picking to select rectangles using the mouse.

  • 23

    133Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Assigning Object Names

    void drawSquares(GLenum mode) {GLuint i, j;

    for(i=0; i

  • 24

    139Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Writing Modes

    frame buffer

    application

    bitwise logical operation

    140Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    XOR write

    •Usual (default) mode: source replaces destination (d’ = s)

    - Cannot write temporary lines this way because we cannot recover what was “under” the line in a fast simple way

    •Exclusive OR mode (XOR) (d’ = d ⊕ s)- x ⊕ y ⊕ x =x- Hence, if we use XOR mode to write a line, we

    can draw it a second time and line is erased!

    141Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rubberbanding

    •Switch to XOR write mode•Draw object

    - For line can use first mouse click to fix one endpoint and then use motion callback to continuously update the second endpoint

    - Each time mouse is moved, redraw line which erases it and then draw line from fixed first position to to new second position

    - At end, switch back to normal drawing mode and draw line

    - Works for other objects: rectangles, circles

    142Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rubberband Lines

    initial displaydraw line with mouse

    in XOR mode

    mouse moved to new position

    first point

    second point

    original line redrawn with XOR

    new line drawn with XOR

    143Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    XOR in OpenGL

    •There are 16 possible logical operations between two bits

    •All are supported by OpenGL- Must first enable logical operations

    •glEnable(GL_COLOR_LOGIC_OP)

    - Choose logical operation•glLogicOp(GL_XOR)•glLogicOp(GL_COPY) (default)

    144Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example: Erasing Lines

    • In this example, we use the XOR drawing mode to draw erasable line segments.

    •The user selects the first endpoint using the mouse.

    /* global variables */float xm, ym, xmm, ymm;

    /* in mouse handler */xm = x/500.;ym = (500 - y)/500.;

  • 25

    145Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    XOR Drawing Mode

    xmm = x/500.;ymm = (500 - y)/500.;

    glLogicOp(GL_XOR);glBegin(GL_LINES);glVertex2f(xm, ym);glVertex2f(xmm, ymm);glEnd();glLogicOp(GL_COPY);glFlush();

    •When the user selects a second point, draw the line in XOR mode.

    146Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Erasing the Line

    glLogicOp(GL_XOR);glBegin(GL_LINES);glVertex2f(xm, ym);glVertex2f(xmm, ymm);glEnd();glFlush();xmm = x/500.;ymm = (500 - y)/500.;glBegin(GL_LINES);...glLogicOp(GL_COPY);

    •Redraw the old line in XOR mode before retrieving new coordinates.

    147Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Immediate and Retained Modes

    • Recall that in a standard OpenGL program, once an object is rendered there is no memory of it and to redisplay it, we must re-execute the code for it

    - Known as immediate mode graphics- Can be especially slow if the objects are complex and

    must be sent over a network

    • Alternative is define objects and keep them in some form that can be redisplayed easily

    - Retained mode graphics- Accomplished in OpenGL via display lists

    148Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Display Lists

    •Conceptually similar to a graphics file- Must define (name, create)- Add contents- Close

    • In client-server environment, display list is placed on server

    - Can be redisplayed without sending primitives over network each time

    149Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Display List Functions

    •Creating a display listGLuint id;

    void init( void ){

    id = glGenLists( 1 );glNewList( id, GL_COMPILE );/* other OpenGL routines */glEndList();

    }

    •Call a created listvoid display( void ){

    glCallList( id );}

    150Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Display Lists and State

    •Most OpenGL functions can be put in display lists

    •State changes made inside a display list persist after the display list is executed

    •Can avoid unexpected results by using glPushAttrib and glPushMatrix upon entering a display list and glPopAttriband glPopMatrix before exiting

  • 26

    151Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Hierarchy and Display Lists

    •Consider model of a car- Create display list for chassis- Create display list for wheel

    glNewList( CAR, GL_COMPILE );glCallList( CHASSIS );glTranslatef( … );glCallList( WHEEL );glTranslatef( … );glCallList( WHEEL );

    …glEndList();

    •Consider model of a car- Create display list for chassis- Create display list for wheel

    glNewList( CAR, GL_COMPILE );glCallList( CHASSIS );glTranslatef( … );glCallList( WHEEL );glTranslatef( … );glCallList( WHEEL );

    …glEndList();

    Geometry

    Prof. George WolbergDept. of Computer ScienceCity College of New York

    153Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    • Introduce the elements of geometry- Scalars- Vectors- Points

    •Develop mathematical operations among them in a coordinate-free manner

    •Define basic primitives- Line segments- Polygons

    154Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Basic Elements

    • Geometry is the study of the relationships among objects in an n-dimensional space

    - In computer graphics, we are interested in objects that exist in three dimensions

    • Want a minimum set of primitives from which we can build more sophisticated objects

    • We will need three basic elements- Scalars- Vectors- Points

    155Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Coordinate-Free Geometry

    • When we learned simple geometry, most of us started with a Cartesian approach

    - Points were at locations in space p=(x,y,z)- We derived results by algebraic manipulations

    involving these coordinates• This approach was nonphysical

    - Physically, points exist regardless of the location of an arbitrary coordinate system

    - Most geometric results are independent of the coordinate system

    - Euclidean geometry: two triangles are identical if two corresponding sides and the angle between them are identical

    156Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Scalars

    • Need three basic elements in geometry- Scalars, Vectors, Points

    • Scalars can be defined as members of sets which can be combined by two operations (addition and multiplication) obeying some fundamental axioms (associativity, commutivity, inverses)

    • Examples include the real and complex number under the ordinary rules with which we are familiar

    • Scalars alone have no geometric properties

  • 27

    157Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Vectors

    •Physical definition: a vector is a quantity with two attributes

    - Direction- Magnitude

    •Examples include- Force- Velocity- Directed line segments

    • Most important example for graphics• Can map to other types

    v

    158Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Vector Operations

    • Every vector has an inverse- Same magnitude but points in opposite direction

    • Every vector can be multiplied by a scalar• There is a zero vector

    - Zero magnitude, undefined orientation• The sum of any two vectors is a vector

    - Use head-to-tail axiom

    v -v αvv

    u

    w

    159Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Linear Vector Spaces

    •Mathematical system for manipulating vectors•Operations

    - Scalar-vector multiplication u=αv- Vector-vector addition: v=u+w

    •Expressions such as v=u+2w-3r

    Make sense in a vector space

    160Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Vectors Lack Position

    • These vectors are identical- Same length and magnitude

    • Vectors spaces insufficient for geometry- Need points

    161Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Points

    •Location in space•Operations allowed between points and vectors

    - Point-point subtraction yields a vector- Equivalent to point-vector addition

    P=v+Q

    v=P-Q

    162Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Affine Spaces

    •Point + a vector space•Operations

    - Vector-vector addition- Scalar-vector multiplication- Point-vector addition- Scalar-scalar operations

    • For any point define- 1 • P = P- 0 • P = 0 (zero vector)

  • 28

    163Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Lines

    •Consider all points of the form- P(α)=P0 + α d- Set of all points that pass through P0 in the

    direction of the vector d

    164Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Parametric Form

    •This form is known as the parametric form of the line

    - More robust and general than other forms- Extends to curves and surfaces

    •Two-dimensional forms- Explicit: y = mx +b- Implicit: ax + by +c =0- Parametric:

    x(α) = αx0 + (1-α)x1y(α) = αy0 + (1-α)y1

    165Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rays and Line Segments

    • If α >= 0, then P(α) is the ray leaving P0 in the direction dIf we use two points to define v, then

    P( α) = Q + α (R-Q)=Q+αv=αR + (1-α)QFor 0

  • 29

    169Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Curves and Surfaces

    •Curves are one parameter entities of the form P(α) where the function is nonlinear

    •Surfaces are formed from two-parameter functions P(α, β)

    - Linear functions give planes and polygons

    P(α) P(α, β)170Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Planes

    •A plane be determined by a point and two vectors or by three points

    P(α,β)=R+αu+βv P(α,β)=R+α(Q-R)+β(P-Q)

    171Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Triangles

    convex sum of P and Q

    convex sum of S(α) and R

    for 0

  • 30

    175Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Linear Independence

    •A set of vectors v1, v2, …, vn is linearly independent if

    v1+v2+..vn=0 iff α1=α2=…=0• If a set of vectors is linearly independent, we cannot represent one in terms of the others

    • If a set of vectors is linearly dependent, as least one can be written in terms of the others

    176Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Dimension

    • In a vector space, the maximum number of linearly independent vectors is fixed and is called the dimension of the space

    • In an n-dimensional space, any set of n linearly independent vectors form a basis for the space

    • Given a basis v1, v2,…., vn, any vector v can be written as

    v=α1v1+ α2v2 +….+αnvnwhere the {αi} are unique

    177Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Representation

    •Until now we have been able to work with geometric entities without using any frame of reference, such a coordinate system

    •Need a frame of reference to relate points and objects to our physical world.

    - For example, where is a point? Can’t answer without a reference system

    - World coordinates- Camera coordinates

    178Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Coordinate Systems

    • Consider a basis v1, v2,…., vn• A vector is written v=α1v1+ α2v2 +….+αnvn• The list of scalars {α1, α2, …. αn}is the representation of v with respect to the given basis

    • We can write the representation as a row or column array of scalars

    a=[α1 α2 …. αn]T=

    ⎥⎥⎥⎥⎥

    ⎢⎢⎢⎢⎢

    α

    αα

    n

    2

    1

    .

    179Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example

    •V=2v1+3v2-4v3•A=[2 3 –4]•Note that this representation is with respect to a particular basis

    •For example, in OpenGL we start by representing vectors using the world basis but later the system needs a representation in terms of the camera or eye basis

    180Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Coordinate Systems

    •Which is correct?

    •Both are correct because vectors have no fixed location

    vv

  • 31

    181Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Frames

    •Coordinate System is insufficient to present points

    • If we work in an affine space we can add a single point, the origin, to the basis vectors to form a frame

    P0v1

    v2

    v3

    182Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Frames II

    •Frame determined by (P0, v1, v2, v3)•Within this frame, every vector can be written as

    v=α1v1+ α2v2 +….+αnvn•Every point can be written as

    P = P0 + β1v1+ β2v2 +….+βnvn

    183Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Confusing Points and Vectors

    Consider the point and the vectorP = P0 + β1v1+ β2v2 +….+βnvnv=α1v1+ α2v2 +….+αnvn

    They appear to have the similar representationsp=[β1 β2 β3] v=[α1 α2 α3]which confuse the point with the vectorA vector has no position v

    pv

    can place anywherefixed

    184Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    A Single Representation

    If we define 0•P = 0 and 1•P =P then we can write

    v=α1v1+ α2v2 +α3v3 = [α1 α2 α3 0 ] [v1 v2 v3 P0] T

    P = P0 + β1v1+ β2v2 +β3v3= [β1 β2 β3 1 ] [v1 v2 v3 P0] T

    Thus we obtain the four-dimensional homogeneous coordinate representation

    v = [α1 α2 α3 0 ]T

    p = [β1 β2 β3 1 ]T

    185Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Homogeneous Coordinates

    The general form of four dimensional homogeneous coordinates is

    p=[x y z w] T

    We return to a three dimensional point (for w≠0) byx←x/wy←y/wz←z/wIf w=0, the representation is that of a vectorNote that homogeneous coordinates replaces points in

    three dimensions by lines through the origin in four dimensions

    186Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Homogeneous Coordinates and Computer Graphics

    •Homogeneous coordinates are key to all computer graphics systems

    - All standard transformations (rotation, translation, scaling) can be implemented by matrix multiplications with 4 x 4 matrices

    - Hardware pipeline works with 4 dimensional representations

    - For orthographic viewing, we can maintain w=0for vectors and w=1 for points

    - For perspective we need a perspective division

  • 32

    187Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Change of Coordinate Systems

    •Consider two representations of a the same vector with respect to two different bases. The representations are

    v=α1v1+ α2v2 +α3v3 = [α1 α2 α3] [v1 v2 v3] T

    =β1u1+ β2u2 +β3u3 = [β1 β2 β3] [u1 u2 u3] T

    a=[α1 α2 α3 ]b=[β1 β2 β3]

    where

    188Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Representing second basis in terms of first

    Each of the basis vectors, u1,u2, u3, are vectors that can be represented in terms of the first basis

    u1 = γ11v1+γ12v2+γ13v3u2 = γ21v1+γ22v2+γ23v3u3 = γ31v1+γ32v2+γ33v3

    v

    189Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Matrix Form

    The coefficients define a 3 x 3 matrix

    and the basis can be related by

    see text for numerical examples

    a=MTb

    ⎥⎥⎥

    ⎢⎢⎢

    γγγγγγγγγ

    3231

    232221

    131211

    33

    M =

    190Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Change of Frames

    • We can apply a similar process in homogeneous coordinates to the representations of both points and vectors

    • Consider two frames

    • Any point or vector can be represented in each

    (P0, v1, v2, v3)(Q0, u1, u2, u3) P0 v1

    v2

    v3

    Q0

    u1 u2

    u3

    191Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Representing One Frame in Terms of the Other

    u1 = γ11v1+γ12v2+γ13v3u2 = γ21v1+γ22v2+γ23v3u3 = γ31v1+γ32v2+γ33v3Q0 = γ41v1+γ42v2+γ43v3 +γ44P0

    Extending what we did with change of bases

    defining a 4 x 4 matrix

    ⎥⎥⎥⎥

    ⎢⎢⎢⎢

    1γγγ0γγγ0γγγ0γγγ

    434241

    333231

    232221

    131211

    M =

    192Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Working with Representations

    Within the two frames any point or vector has a representation of the same form

    a=[α1 α2 α3 α4 ] in the first frameb=[β1 β2 β3 β4 ] in the second frame

    where α4 = β4 = 1 for points and α4 = β4 = 0 for vectors and

    The matrix M is 4 x 4 and specifies an affine transformation in homogeneous coordinates

    a=MTb

  • 33

    193Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Affine Transformations

    •Every linear transformation is equivalent to a change in frames

    •Every affine transformation preserves lines

    •However, an affine transformation has only 12 degrees of freedom because 4 of the elements in the matrix are fixed and are a subset of all possible 4 x 4 linear transformations

    194Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The World and Camera Frames

    • When we work with representations, we work with n-tuples or arrays of scalars

    • Changes in frame are then defined by 4 x 4 matrices

    • In OpenGL, the base frame that we start with is the world frame

    • Eventually we represent entities in the camera frame by changing the world representation using the model-view matrix

    • Initially these frames are the same (M=I)

    195Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Moving the Camera

    If objects are on both sides of z=0, we must move camera frame

    ⎥⎥⎥⎥

    ⎢⎢⎢⎢

    −1000d100

    00100001

    M =

    Transformations

    Prof. George WolbergDept. of Computer ScienceCity College of New York

    197Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    • Introduce standard transformations- Rotations- Translation- Scaling- Shear

    •Derive homogeneous coordinate transformation matrices

    •Learn to build arbitrary transformation matrices from simple transformations

    198Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    General Transformations

    •A transformation maps points to other points and/or vectors to other vectors

    Q=T(P)

    v=T(u)

  • 34

    199Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Affine Transformations

    •Line preserving•Characteristic of many physically important transformations

    - Rigid body transformations: rotation, translation- Scaling, shear

    • Importance in graphics is that we need only transform endpoints of line segments and let implementation draw line segment between the transformed endpoints

    200Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Pipeline Implementation

    transformation rasterizer

    u

    v

    u

    v

    T

    T(u)

    T(v)

    T(u)T(u)

    T(v)

    T(v)

    vertices vertices pixels

    framebuffer

    (from application program)

    201Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Notation

    We will be working with both coordinate-free representations of transformations and representations within a particular frame

    P,Q, R: points in an affine spaceu, v, w: vectors in an affine spaceα, β, γ: scalarsp, q, r: representations of points-array of 4 scalars in homogeneous coordinates

    u, v, w: representations of points-array of 4 scalars in homogeneous coordinates 202Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Translation

    •Move (translate, displace) a point to a new location

    •Displacement determined by a vector d- Three degrees of freedom- P’=P+d

    P

    P’

    d

    203Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Object Translation

    Every point in object is displaced by same vector

    object Object translation

    204Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Translation Using Representations

    Using the homogeneous coordinate representation in some frame

    p=[ x y z 1]Tp’=[x’ y’ z’ 1]Td=[dx dy dz 0]T

    Hence p’ = p + d orx’=x+dxy’=y+dyz’=z+dz

    note that this expression is in four dimensions and expressesthat point = vector + point

  • 35

    205Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Translation Matrix

    We can also express translation using a 4 x 4 matrix T in homogeneous coordinatesp’=Tp where

    T = T(dx, dy, dz) =

    This form is better for implementation because all affine transformations can be expressed this way and multiple transformations can be concatenated together

    ⎥⎥⎥⎥

    ⎢⎢⎢⎢

    1000d100d010d001

    z

    y

    x

    206Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rotation (2D)

    • Consider rotation about the origin by θ degrees- radius stays the same, angle increases by θ

    x’ = x cos θ – y sin θy’ = x sin θ + y cos θ

    x = r cos φy = r sin φ

    x = r cos (φ + θ)y = r sin (φ + θ)

    207Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rotation about the z-axis

    • Rotation about z axis in three dimensions leaves all points with the same z

    - Equivalent to rotation in two dimensions in planes of constant z

    - or in homogeneous coordinatesp’=Rz(θ)p

    x’ = x cos θ – y sin θy’ = x sin θ + y cos θz’ = z

    208Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rotation Matrix

    ⎥⎥⎥⎥

    ⎢⎢⎢⎢

    ⎡θθθ−θ

    1000010000 cossin 00sin cos

    R = Rz(θ) =

    209Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rotation about x and y axes

    • Same argument as for rotation about z-axis- For rotation about x-axis, x is unchanged- For rotation about y-axis, y is unchanged

    R = Rx(θ) =

    R = Ry(θ) =

    ⎥⎥⎥⎥

    ⎢⎢⎢⎢

    θθθθ

    10000 cos sin00 sin- cos00001

    ⎥⎥⎥⎥

    ⎢⎢⎢⎢

    θθ

    θθ

    10000 cos0 sin-00100 sin0 cos

    210Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Scaling

    ⎥⎥⎥⎥

    ⎢⎢⎢⎢

    1000000000000

    z

    y

    x

    ss

    s

    S = S(sx, sy, sz) =

    x’=sxxy’=syyz’=szz

    p’=Sp

    Expand or contract along each axis (fixed point of origin)

  • 36

    211Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Reflection

    corresponds to negative scale factors

    originalsx = -1 sy = 1

    sx = -1 sy = -1 sx = 1 sy = -1

    212Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Inverses

    • Although we could compute inverse matrices by general formulas, we can use simple geometric observations

    - Translation: T-1(dx, dy, dz) = T(-dx, -dy, -dz) - Rotation: R -1(θ) = R(-θ)

    • Holds for any rotation matrix• Note that since cos(-θ) = cos(θ) and sin(-θ)=-sin(θ)R -1(θ) = R T(θ)

    - Scaling: S-1(sx, sy, sz) = S(1/sx, 1/sy, 1/sz)

    213Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Concatenation

    • We can form arbitrary affine transformation matrices by multiplying together rotation, translation, and scaling matrices

    • Because the same transformation is applied to many vertices, the cost of forming a matrix M=ABCD is not significant compared to the cost of computing Mp for many vertices p

    • The difficult part is how to form a desired transformation from the specifications in the application

    214Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Order of Transformations

    •Note that matrix on the right is the first applied

    •Mathematically, the following are equivalent

    p’ = ABCp = A(B(Cp))•Note many references use column matrices to present points. In terms of column matrices

    pT’ = pTCTBTAT

    215Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    General Rotation About the Origin

    θ

    x

    z

    yv

    A rotation by θ about an arbitrary axiscan be decomposed into the concatenationof rotations about the x, y, and z axes

    R(θ) = Rz(θz) Ry(θy) Rx(θx)

    θx θy θz are called the Euler angles

    Note that rotations do not commuteWe can use rotations in another order butwith different angles

    216Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rotation About a Fixed Point other than the Origin

    Move fixed point to originRotateMove fixed point backM = T(-pf) R(θ) T(pf)

  • 37

    217Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Instancing

    • In modeling, we often start with a simple object centered at the origin, oriented with the axis, and at a standard size

    •We apply an instance transformation to its vertices to

    Scale OrientLocate

    218Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Shear

    • Helpful to add one more basic transformation• Equivalent to pulling faces in opposite directions

    219Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Shear Matrix

    Consider simple shear along x axis

    x’ = x + y cot θy’ = yz’ = z

    ⎥⎥⎥⎥

    ⎢⎢⎢⎢

    ⎡ θ

    10000100001000cot 1

    H(θ) =

    220Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    •Draw a dot plot for the following function:

    Example: Plotting a Function

    .40for 2cos)( ≤≤= − xxexf x π

    221Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    •Use a linear transformation to fit the function in the window:

    •Translates the origin to the center of the window.

    •Scales the drawing to fit.

    Viewport Transformation

    .⎥⎦⎤

    ⎢⎣

    ⎡′′

    =⎥⎦

    ⎤⎢⎣

    ⎡⎥⎦

    ⎤⎢⎣

    ⎡yx

    yx

    DCBA

    222Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    A = screenWidth / 4.0;B = 0.0;C = screenHeight / 2.0;D = C;

    glBegin(GL_POINTS);for(x = 0.0; x

  • 38

    OpenGL Transformations

    Prof. George WolbergDept. of Computer ScienceCity College of New York

    224Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    •Learn how to carry out transformations in OpenGL

    - Rotation- Translation - Scaling

    • Introduce OpenGL matrix modes- Model-view- Projection

    225Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    OpenGL Matrices

    • In OpenGL matrices are part of the state•Three types

    - Model-View (GL_MODEL_VIEW)- Projection (GL_PROJECTION)- Texture (GL_TEXTURE) (ignore for now)

    •Single set of functions for manipulation•Select which to manipulated by

    -glMatrixMode(GL_MODEL_VIEW);-glMatrixMode(GL_PROJECTION);

    226Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Current Transformation Matrix (CTM)

    • Conceptually there is a 4 x 4 homogeneous coordinate matrix, the current transformation matrix (CTM) that is part of the state and is applied to all vertices that pass down the pipeline

    • The CTM is defined in the user program and loaded into a transformation unit

    CTMvertices verticesp p’=Cp

    C

    227Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    CTM operations

    • The CTM can be altered either by loading a new CTM or by postmultiplication

    Load an identity matrix: C ← ILoad an arbitrary matrix: C ← M

    Load a translation matrix: C ← TLoad a rotation matrix: C ← RLoad a scaling matrix: C ← S

    Postmultiply by an arbitrary matrix: C ← CMPostmultiply by a translation matrix: C ← CTPostmultiply by a rotation matrix: C ← C RPostmultiply by a scaling matrix: C ← C S

    228Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rotation about a Fixed Point

    Start with identity matrix: C ← IMove fixed point to origin: C ← CT -1Rotate: C ← CRMove fixed point back: C ← CT

    Result: C = T -1RT

    Each operation corresponds to one function call in the program.

    Note that the last operation specified is the first executed in the program

  • 39

    229Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    CTM in OpenGL

    •OpenGL has a model-view and a projection matrix in the pipeline which are concatenated together to form the CTM

    •Can manipulate each by first setting the matrix mode

    230Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Rotation, Translation, Scaling

    glRotatef(theta, vx, vy, vz)

    glTranslatef(dx, dy, dz)

    glScalef( sx, sy, sz)

    glLoadIdentity()

    Load an identity matrix:

    Multiply on right:

    theta in degrees, (vx, vy, vz) define axis of rotation

    Each has a float (f) and double (d) format (glScaled)

    231Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example

    •Rotation about z-axis by 30 degrees with a fixed point of (1.0, 2.0, 3.0)

    •Remember that last matrix specified in the program is the first applied

    glMatrixMode(GL_MODELVIEW);glLoadIdentity();glTranslatef(1.0, 2.0, 3.0);glRotatef(30.0, 0.0, 0.0, .10);glTranslatef(-1.0, -2.0, -3.0);

    232Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Arbitrary Matrices

    •Can load and multiply by matrices defined in the application program

    •The matrix m is a one dimension array of 16 elements which are the components of the desired 4 x 4 matrix stored by columns

    • In glMultMatrixf, m multiplies the existing matrix on the right

    glLoadMatrixf(m)glMultMatrixf(m)

    233Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Matrix Stacks

    • In many situations we want to save transformation matrices for use later

    - Traversing hierarchical data structures (Chapter 9)- Avoiding state changes when executing display lists

    •OpenGL maintains stacks for each type of matrix

    - Access present type (as set by glMatrixMode) by

    glPushMatrix()glPopMatrix()

    234Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Reading Back Matrices

    • Can also access matrices (and other parts of the state) by enquiry (query) functions

    • For matrices, we use as

    glGetIntegervglGetFloatvglGetBooleanvglGetDoublevglIsEnabled

    double m[16];glGetFloatv(GL_MODELVIEW, m);

  • 40

    235Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Using Transformations

    • Example: use idle function to rotate a cube and mouse function to change direction of rotation

    • Start with a program that draws a cube(colorcube.c) in a standard way

    - Centered at origin- Sides aligned with axes- Will discuss modeling in next lecture

    236Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    main.c

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

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

    }

    237Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Idle and Mouse callbacks

    void spinCube() {theta[axis] += 2.0;if( theta[axis] > 360.0 ) theta[axis] -= 360.0;glutPostRedisplay();

    }

    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;

    }238Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Display callback

    void display(){

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glLoadIdentity();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();glutSwapBuffers();

    }

    Note that because of fixed from of callbacks, variables such as theta and axis must be defined as globals

    Camera information is in standard reshape callback

    239Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Using the Model-View Matrix

    • In OpenGL the model-view matrix is used to- Position the camera

    • Can be done by rotations and translations but is often easier to use gluLookAt (Chapter 5)

    - Build models of objects • The projection matrix is used to define the view

    volume and to select a camera lens• Although both are manipulated by the same functions,

    we have to be careful because incremental changes are always made by postmultiplication

    - For example, rotating model-view and projection matrices by the same matrix are not equivalent operations. Postmultiplication of the model-view matrix is equivalent to premultiplication of the projection matrix

    240Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Example: Solar System

    •This example demonstrates how to combine transformations.

    •Planets rotate on their axes and also orbit the sun.

    •When issuing transformation commands, the order is significant.

  • 41

    241Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Motion Control

    • Use global variables to keep track of the planet's orbit.

    • Update the orbital state in response to events such as keyboard input.

    static int year = 0, day = 0;

    switch(key) {case 'd': day = (day + 10) % 360;

    glutPostRedisplay();break;

    case 'y': year = (year + 5) % 360;...

    242Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The Keyboard Handler

    void keyboard(unsigned char key, int x, int y) {switch(key) {case ‘d’: day = (day + 10) % 360;

    glutPostRedisplay();break;

    case ‘D’: day = (day – 10) % 360;glutPostRedisplay();break;

    case ‘y’: year = (year + 5) % 360;glutPostRedisplay();break;

    case ‘Y’: year = (year – 5) % 360;glutPostRedisplay();break;

    default: break;}

    }

    243Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Viewing Parameters

    • Set up a perspective projection in the reshape handler.

    • Since the camera is stationary, we can set up the model-view matrix here as well.

    glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION);glLoadIdentity();gluPerspective(60.0, (float) w/h, 1.0, 20.0);

    glMatrixMode(GL_MODELVIEW);glLoadIdentity();gluLookAt(0., 0., 5., 0., 0., 0., 0., 1., 0.);

    244Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The Reshape Handler

    void reshape(){

    glViewport(0, 0, w, h);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluPerspective(60.0, (float) w/h, 1.0, 20.0);glMatrixMode(GL_MODELVIEW); glLoadIdentity();gluLookAt(0., 0., 5., 0., 0., 0., 0., 1., 0.);

    }

    245Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Ordering the Transformations

    •An initial rotation around the sun is determined by the time of year.

    •Translation along the x-axis moves the planet to the correct spot along its orbit.

    •A second rotation based on the time of day rotates the local coordinate axis.

    246Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The Display Handler

    void display(void) {glClear (GL_COLOR_BUFFER_BIT);glColor3f(1.0, 1.0, 1.0);

    glPushMatrix ();glutWireSphere(1.0, 20, 16);glRotatef ((GLfloat) year, 0.0, 1.0, 0.0);glTranslatef (2.0, 0.0, 0.0);glRotatef ((GLfloat) day, 0.0, 1.0, 0.0);glutWireSphere(0.2, 10, 8);glPopMatrix ();

    glutSwapBuffers();}

    draw sun at origin

    draw planet afterapplying transformations

  • 42

    247Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Putting It All Together

    void init(void) {glClearColor(0., 0., 0., 0.);glShadeModel(GL_FLAT);

    }

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

    glutInit(&argc, argv);glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);glutInitWindowSize(500, 500);glutInitWindowPosition(100, 100);glutCreateWindow(argv[0]);init();glutDisplayFunc (display);glutReshapeFunc (reshape);glutKeyboardFunc(keyboard);glutMainLoop();return 0;

    }248Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Smooth Rotation

    • From a practical standpoint, we are often want to use transformations to move and reorient an object smoothly

    - Problem: find a sequence of model-view matrices M0,M1,…..,Mn so that when they are applied successively to one or more objects we see a smooth transition

    • For orientating an object, we can use the fact that every rotation corresponds to part of a great circle on a sphere

    - Find the axis of rotation and angle- Virtual trackball (see text)

    249Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Incremental Rotation

    • Consider the two approaches- For a sequence of rotation matrices

    R0,R1,…..,Rn , find the Euler angles for each and use Ri= Riz Riy Rix

    • Not very efficient

    - Use the final positions to determine the axis and angle of rotation, then increment only the angle

    • Quaternions can be more efficient than either

    250Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Quaternions

    • Extension of imaginary numbers from two to three dimensions

    • Requires one real and three imaginary components i, j, k

    • Quaternions can express rotations on sphere smoothly and efficiently. Process:

    - Model-view matrix → quaternion- Carry out operations with quaternions- Quaternion → Model-view matrix

    q=q0+q1i+q2j+q3k

    251Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Interfaces

    • One of the major problems in interactive computer graphics is how to use two-dimensional devices such as a mouse to interface with three dimensional objects

    • Example: how to form an instance matrix?• Some alternatives

    - Virtual trackball- 3D input devices such as the spaceball- Use areas of the screen

    • Distance from center controls angle, position, scale depending on mouse button depressed

    Building Models

    Prof. George WolbergDept. of Computer ScienceCity College of New York

  • 43

    253Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    • Introduce simple data structures for building polygonal models

    - Vertex lists- Edge lists

    •OpenGL vertex arrays

    254Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Representing a Mesh

    • Consider a mesh

    • There are 8 nodes and 12 edges- 5 interior polygons- 6 interior (shared) edges

    • Each vertex has a location vi = (xi yi zi)

    v1 v2

    v7

    v6v8

    v5

    v4

    v3

    e1e8

    e3

    e2

    e11

    e6

    e7e10

    e5

    e4

    e9

    e12

    255Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Simple Representation

    •List all polygons by their geometric locations

    •Leads to OpenGL code such as

    • Inefficient and unstructured- Consider moving a vertex to a new locations

    glBegin(GL_POLYGON);glVertex3f(x1, y1, z1);glVertex3f(x6, y6, z6);glVertex3f(x7, y7, z7);

    glEnd();

    256Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Inward and Outward Facing Polygons

    • The order {v0, v1, v2, v3} and {v1, v2, v3, v0} are equivalent in that the same polygon will be rendered by OpenGL but the order {v3, v2, v1, v0} is different

    • The first two describe inwardly facing polygons• Use the right-hand rule = counter-clockwise encirclement of outward-pointing normal • OpenGL treats inward and outward facing polygons differently

    257Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Geometry vs Topology

    •Generally it is a good idea to look for data structures that separate the geometry from the topology

    - Geometry: locations of the vertices- Topology: organization of the vertices and

    edges- Example: a polygon is an ordered list of

    vertices with an edge connecting successive pairs of vertices and the last to the first

    - Topology holds even if geometry changes

    258Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Vertex Lists

    • Put the geometry in an array• Use pointers from the vertices into this array• Introduce a polygon list

    x1 y1 z1x2 y2 z2x3 y3 z3x4 y4 z4x5 y5 z5.x6 y6 z6x7 y7 z7x8 y8 z8

    P1P2P3P4P5

    v1v7v6

    v8v5v6

    topology geometry

  • 44

    259Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Shared Edges

    •Vertex lists will draw filled polygons correctly but if we draw the polygon by its edges, shared edges are drawn twice

    •Can store mesh by edge list

    260Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Edge List

    v1 v2

    v7

    v6v8

    v5

    v3

    e1e8

    e3

    e2

    e11

    e6

    e7e10

    e5

    e4

    e9

    e12

    e1e2e3e4e5e6e7e8e9

    x1 y1 z1x2 y2 z2x3 y3 z3x4 y4 z4x5 y5 z5.x6 y6 z6x7 y7 z7x8 y8 z8

    v1v6

    Note polygons arenot represented

    261Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Modeling a Cube

    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 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}};

    Model a color cube for rotating cube program

    Define global arrays for vertices and colors

    262Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Drawing a polygon from a list of indices

    Draw a quadrilateral from a list of indices into the array vertices and use color corresponding to first index

    void polygon(int a, int b, int c, int d){

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

    glEnd();}

    263Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Draw cube from faces

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

    }

    0

    5 6

    2

    4 7

    1

    3Note that vertices are ordered so that we obtain correct outward facing normals

    264Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Efficiency

    •The weakness of our approach is that we are building the model in the application and must do many function calls to draw the cube

    •Drawing a cube by its faces in the most straight forward way requires

    - 6 glBegin, 6 glEnd- 6 glColor- 24 glVertex- More if we use texture and lighting

  • 45

    265Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Vertex Arrays

    • OpenGL provides a facility called vertex arraysthat allow us to store array data in the implementation

    • Six types of arrays supported- Vertices- Colors- Color indices- Normals- Texture coordinates- Edge flags

    • We will need only colors and vertices266Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Initialization

    • Using the same color and vertex data, first we enableglEnableClientState(GL_COLOR_ARRAY);glEnableClientState(GL_VERTEX_ARRAY);

    • Identify location of arraysglVertexPointer(3, GL_FLOAT, 0, vertices);

    glColorPointer(3, GL_FLOAT, 0, colors);

    3d arrays stored as floats data contiguousdata array

    267Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Mapping indices to faces

    •Form an array of face indices

    •Each successive four indices describe a face of the cube

    •Draw through glDrawElements which replaces all glVertex and glColor calls in the display callback

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

    268Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Drawing the cube

    • Method 1:

    • Method 2:

    for(i=0; i

  • 46

    Computer Viewing

    Prof. George WolbergDept. of Computer ScienceCity College of New York

    272Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Objectives

    • Introduce the mathematics of projection• Introduce OpenGL viewing functions•Look at alternate viewing APIs

    273Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Computer Viewing

    •There are three aspects of the viewing process, all of which are implemented in the pipeline,

    - Positioning the camera• Setting the model-view matrix

    - Selecting a lens• Setting the projection matrix

    - Clipping• Setting the view volume

    274Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    The OpenGL Camera

    • In OpenGL, initially the world and camera frames are the same

    - Default model-view matrix is an identity

    •The camera is located at origin and points in the negative z direction

    •OpenGL also specifies a default view volume that is a cube with sides of length 2 centered at the origin

    - Default projection matrix is an identity

    275Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Default Projection

    Default projection is orthogonal

    clipped out

    z=0

    2

    276Angel: Interactive Computer Graphics 3E © Addison-Wesley 2003

    Moving the Camera Frame

    • If