Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Computer Graphics CSCI E 234

Similar presentations


Presentation on theme: "Intro to Computer Graphics CSCI E 234"— Presentation transcript:

1 Intro to Computer Graphics CSCI E 234
Jeff Parker, 2011 Based on lectures by Ed Angel © Ed Angel "Hardware: The parts of a computer system that can be kicked." - Jeff Pesis

2 Overview What is this course about? What should you know now?
What will you be expected to do? What will you know when you finish? Don't need to cover all topics in this lecture tonight

3 What Computer Graphics isn't
Let’s talk about what graphics isn’t. Image processing: taking an image and looking for features Red-eye removal: look for red dots, and change them Color correction Finding parts on assembly line Face detection and recognition Machine Vision: application of Image Processing to Robotics

4 What Computer Graphics isn't
Graphics User Interfaces: writing user interfaces Menus and widgets Take CS Software Design Xerox 8010 compound document en.wikipedia.org

5 What Computer Graphics isn't
Visualization: Can be used to Tracking a storm Show Gulf Stream currents Surface Temperature NASA NOAA

6 What Computer Graphics is
All aspects of creating an image with a computer Modelling the objects in a scene Modelling physics of the objects & interactions Capturing object’s geometry Lines, Points, … Picking a point of view Zooming… Rendering the image The Vertigo effect, from Hitchcock's Vertigo Copyright Pixar

7 What skills are important?
Mathematics Modelling the objects Following transformations from objects to points on screen Programming Writing programs to create objects Making the calls to the graphics system Creativity Create interesting stories. Draw memorable characters. Some of you will know more of one subject than the other. We will need to help each other out. Wolfram Math World Pixar

8 Expectations Let's talk about expectations and background Requisites
Academic Honesty Engagement Communication 9

9 Requisites (Preconditions)
It is often useful in programming to describe preconditions and postconditions What is assumed when you call this routine What will be true when it returns What are our assumptions about you? (what is equivalent to CS 119?) • You can program in a modern high level computer language • You are comfortable with mathematics • You can enter, run, and debug your programs • You know C++ or can learn it in the next 2 weeks You are comfortable with Abstraction, Callbacks, and Pointers • You have the time and the will to work hard for a semester to achieve a worthy goal • You will turn in your own work • You can turn off your cell phone and pager 9

10 Student Work Frequent small programming projects covering new material
Pen-and-paper problems addressing graphical algorithms We start with series of collision examples – first is 2 circles Graduate students write a final project that uses many of the ideas we cover 10

11 Academic Honesty A computer program written to satisfy a course requirement is, like a paper, expected to be the original work of the student submitting it. Copying a program from another student or from any other source is a form of academic dishonesty, as is deriving a program substantially from the work of another. At times in this course, we will provide the main idea or even text of a program that is to be completed as an exercise. We will also provide useful idioms in the form of short code fragments. You should have no more reservation about using this help than you would have about using standard formulas in a Physics course. If you are in doubt about any instance of reuse, be sure to credit your source in a comment at the head of your program. You should become familiar with the full set of rules and regulations about the rules at Harvard 9

12 Academic Misconduct All homework assignments, projects, lab reports, papers, and examinations submitted to a course are expected to be the student’s own work. Students should always take great care to distinguish their own ideas and knowledge from information derived from sources. The term "sources" includes not only primary and secondary material published in print or on-line, but also information and opinions gained directly from other people.

The responsibility for learning the proper forms of citation lies with the individual student. Quotations must be placed properly within quotation marks and must be cited fully. In addition, all paraphrased material must be acknowledged completely. Whenever ideas or facts are derived from a student’s reading and research or from a student’s own writings, the sources must be indicated (see also Submission of the Same Work to More than One Course) 

A computer program written to satisfy a course requirement is, like a paper, expected to be the original work of the student submitting it. Copying a program from another student or any other source is a form of academic dishonesty; so is deriving a program substantially from the work of another.. The amount of collaboration with others that is permitted in the completion of assignments can vary, depending upon the policy set by the head of the course. Students must assume that collaboration in the completion of assignments is prohibited unless explicitly permitted by the instructor. Students must acknowledge any collaboration and its extent in all submitted work.
 9

13 Postconditions: Course Goals
You will learn the important ideas of Computer Graphics You will learn a commonly-used API, OpenGL You will have seen some of the most interesting applications of mathematics to Computer Science Sampling Projective Geometry – into the 4th dimension… You can create some interesting programs You will be exposed to more interesting ideas than we have time to pursue in class 10

14 Postconditions: Course Goals
// You will be able to read a program like this by the end of the semester... public void init(GLDrawable drawable) { float[] mat_specular = {1.0f, 1.0f, 1.0f, 1.0f}; float[] mat_diffuse = {1.0f, 1.0f, 1.0f, 1.0f}; float[] mat_ambient = {1.0f, 1.0f, 1.0f, 1.0f}; float mat_shininess = 100.0f; float[] light_ambient = {0.0f, 0.0f, 0.0f, 1.0f}; float[] light_diffuse = {1.0f, 1.0f, 1.0f, 1.0f}; float[] light_specular = {1.0f, 1.0f, 1.0f, 1.0f}; GL gl = drawable.getGL(); /* set up ambient, diffuse, and specular components for light 0 */ gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, light_ambient); gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, light_diffuse); gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, light_specular); gl.glShadeModel(GL.GL_SMOOTH); /* enable smooth shading */ gl.glEnable(GL.GL_LIGHTING); /* enable lighting */ gl.glEnable(GL.GL_LIGHT0); /* enable light 0 */ gl.glEnable(GL.GL_DEPTH_TEST); /* enable z buffer */ gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); gl.glColor3f(0.0f, 0.0f, 0.0f); } 10

15 The Instructor Jeff Parker Ph.D. in Mathematics (1980)
Teaching since Williams, Amherst, Boston College Harvard Extension Present Middlebury College Merrimack Currently Research Advisor at Harvard Extension Helping students write Thesis Proposals and Theses Industry Experience Phoenix - Postscript Interpreter Prime Computer - Client Server group Sun Microsystems - System Administration Framework Agile Networks (later Lucent) - Layer-3 Switch Nexabit Networks (later Lucent)- Big Fast Router Axiowave Networks – Big Fast Router 12

16 Communication Be sure to check out the iSite – Check Recent Site Updates Post questions and comments to BBoard To reach me, send . If I think your question is of general interest, I may remove your name and forward your question Note user is Guest – not logged in 12

17 Communication You can subscribe Click on "my account" 12

18 Our Textbook A classic text, now in sixth edition
I have ordered copies from the bookstore Please purchase 6th Edition: new API I have placed several versions on reserve Course website has link to sample programs The bookstore will now rent books 12

19 OpenGL We will be writing our programs in C++, using the Application Programing Interface (API) Open GL OpenGL was developed by Silicon Graphics, and runs (with some adjustment) on Windows – Part of Vista and Windows 7– if you have XP or earlier, need to download GLUT from web. See links on website Linux Mac – may need to modify an include path in programs

20 Book Outline: Part 1 Introduction: Chapter 1
What is Computer Graphics? Applications Areas History Image formation Basic Architecture

21 Book Outline: Part 2 application program GLUT GLU GL X, Win32, Mac O/S
Basic OpenGL: Chapter 2 Architecture GLUT Simple programs in two and three dimensions Interaction application program OpenGL Motif widget or similar GLUT GLX, AGL or WGL GLU GL X, Win32, Mac O/S software and/or hardware

22 Book Outline: Part 3 Three-Dimensional Graphics: Chapters 3-5 Geometry
Transformations Homogeneous Coordinates Viewing Shading

23 Book Outline: Part 4 Implementation: Chapter 6
Approaches (object vs image space) Implementing the pipeline Clipping Line drawing Polygon Fill Display issues (color)

24 Book Outline: Part 5 Discrete Methods: Chapter 7 Buffers
Bitmaps and Pixel Maps Texture Mapping Compositing and Transparency Mark J. Kilgard

25 Book Outline: Part 6 Modeling – Chapters 8-9 Hierarchical Models
Algorithmic Models

26 Book Outline: Part 7 Curves and Surfaces: Chapter 10 Splines and NURBS

27 Book Outline: Part 8 Wikipedia Ray Tracing – Chapter 11
Ray Tracing and Ray Casting Wikipedia

28 Outline: Part 8 Gilles Tran

29 Assignment 1 Goals for the first project: Find the computers
Learn to write OpenGL calls Learn to link programs with OpenGL library Debug the project submission process Pen and Paper - Decide if two circles circumferences intersect Programming - Write an OpenGL program that draws a two dimensional scene using squares, triangles, and circles and multiple colors. At least one object should be clipped on frame Strive for something that is visually interesting. 12

30 Assignment 1 Drop date is September 11
They strongly suggest that we give an assignment in the first week to give you an idea of what is ahead 12

31 Samples from Prior Year

32 Prior Year

33 Collision Problem bbc.co.uk
I am working on my Men In Tights Video Game In this scene, two players are fighting with swords The swords are represented as line segments We represent line segments by a pair of endpoints When the two swords cross, play the audio file "clang.au" Write an algorithm that decides if two line segments overlap. This is too hard, so our first problem is: Do two circles intersect? bbc.co.uk

34 Review Analytic Geometry
Points in 2-D space can be represented as pairs (x, y) Points in 3-D space can be represented as triple (x, y, z) Point in 4-D space can be … Lines in the plane can be represented as y = mx + b But we will see better ways How do we represent a line in 3-D space? Circles in the plane can be represented as r2 = (x – a)2 + (y – b)2 Points and Vectors Difference of two points is a vector We can add vectors – cannot add points We can multiply vectors – dot product and cross product Vectors have Length

35 Problem circumferences We want to know if two hoops touch each other.
What do we need to know? Any special cases? circumferences

36 Problem We want to know if two hoops touch each other.
What do we need to know? Centres and radius of each circle Special Cases?

37 Part II – the OpenGL API Development of the OpenGL API
OpenGL Architecture OpenGL as a state machine Functions Types Formats Simple program

38 SGI and GL There had been a number of companies making graphics hardware Tektronix, Calcomp, … Several of these had private APIs for their systems There had also been a number of efforts to produce an open API IFIPS GKS PHIGS & X Windows – PEX It is always difficult to get an API right the first few times Silicon Graphics Inc. (SGI) revolutionized the graphics workstation by implementing a rich graphics pipeline in hardware (1982) To access the system, application programmers used a library called GL Relatively simple to program 3D interactive applications

39 OpenGL The success of GL lead to OpenGL (1992), a platform- independent API Easy to use Close enough to hardware to get excellent performance Focused on rendering Omitted windowing & input to avoid system dependencies Compare to DirectX

40 OpenGL Evolution Controlled by an Architectural Review Board (ARB)
Members include SGI, Microsoft, Nvidia, HP, 3DLabs, IBM,……. Relatively stable (present version 3.x, Spring 2011) Evolution reflects new hardware capabilities 3D texture mapping and texture objects GL Shading Languages Allows for platform specific features through extensions

41 OpenGL Libraries OpenGL core library OpenGL32 on Windows
GL on most unix/linux systems (libGL.a) glVertex3f(x,y,z) OpenGL Utility Library (GLU) Provides some higher level functions based on the core. gluBuild2DMipmaps GLUT Toolkit (next slide) Provides functionality common to all window systems glutDisplayFunc( display ) Links with window system GLX for X window systems WGL for Windows AGL for Macintosh

42 GLUT OpenGL Utility Toolkit (GLUT)
Provides functionality common to all window systems Open a window Get input from mouse and keyboard Menus Event-driven /* Register callbacks */ glutDisplayFunc( display ); glutReshapeFunc( reshape ); glutKeyboardFunc( keyboard ); glutMouseFunc( mouse ); Code is portable but GLUT lacks the functionality of a good toolkit for a specific platform – e.g. No slide bars

43 Software Organization
GLUT GLU GL GLX, AGL or WGL X, Win32, Mac O/S software and/or hardware application program OpenGL Motif widget or similar

44 OpenGL Architecture geometry pipeline CPU Immediate Mode Per Vertex
Operations & Primitive Assembly Polynomial Evaluator Display List Per Fragment Operations Frame Buffer CPU Rasterization Texture Memory Pixel Operations

45 OpenGL Functions Primitives Points Line Segments Polygons Attributes
Transformations Viewing Modeling Control (GLUT) Input (GLUT) Query

46 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

47 Lack of Object Orientation
OpenGL is not object oriented so that there are multiple functions for a given logical function glVertex3f glVertex2i glVertex3dv Underlying storage mode is the same

48 OpenGL function format
function name dimensions glVertex3f(x,y,z) type - x,y,z are floats belongs to GL library glVertex3fv(p) vector – p is a pointer to an array

49 OpenGL #defines Most constants defined in the include files gl.h, glu.h and glut.h #include <GL/glut.h> should automatically include the others Sample constants: GL_POLYGON, GL_COLOR_BUFFER_BIT glBegin(GL_POLYGON) glClear(GL_COLOR_BUFFER_BIT) These include files also define OpenGL data types: GLfloat, GLdouble,….

50 A Simple Program in pseudocode
main() # Draw a sequence of points { initialize_system(); p = initial_point)_; for (some number of points) q = generate_a_point_based_on(p); display_point(q); p = q; } cleanup();

51 Alternative main() # Draw a sequence of points { initialize_system();
p = initial_point)_; for (some number of points) q = generate_a_point_based_on(p); store_point(q); p = q; } display_all_points(); cleanup();

52 Alternative main() # Draw a sequence of points { initialize_system();
p = initial_point)_; for (some number of points) q = generate_a_point_based_on(p); store_point(q); p = q; } send_all_points_to_GPU(); display_points_on_GPU(); cleanup();

53 Solution // Real code void init( void ) { vec2 points[NumPoints];
// Specify the vertices for a triangle vec2 vertices[3] = { vec2( -1.0, -1.0 ), vec2( 0.0, 1.0 ), vec2( 1.0, -1.0 ) }; // Select an initial point inside triangle points[0] = vec2( 0.25, 0.50 );

54 Chaos Game void init( void ) { ... // compute and store N-1 new points
for ( int i = 1; i < NumPoints; ++i ) { int j = rand() % 3; // pick random vertex // Compute the point halfway between // selected vertex and previous point points[i] = (points[i-1] + vertices[j]) / 2.0; } Chaos game is due to Michael Barnsley

55 Johanna Voolich and Robert L. Devaney
Chaos Game Chaos Game is due to Michael Barnsley Given a starting dot and a goal triangle (green) Goal is to move dot into triangle in fewest number of moves Johanna Voolich and Robert L. Devaney

56 Chaos Game

57 Chaos Game void init( void ) { ... // compute and store N-1 new points
for ( int i = 1; i < NumPoints; ++i ) { int j = rand() % 3; // pick random vertex // Compute the point halfway between // selected vertex and previous point points[i] = (points[i-1] + vertices[j]) / 2.0; }

58 What is left? We have not described
The colors we are using to draw, the background How we create a window to hold the image Where the image appears within the window The size of the image How much of the (infinite) image do we display? How long will we show the image?

59 Include Files // Two-Dimensional Sierpinski Gasket
// Generated using randomly selected vertices and bisection #include "Angel.h" const int NumPoints = 5000;

60 Angel.h #ifndef __ANGEL_H__ #define __ANGEL_H__ #include <cmath>
#include <iostream> #ifndef M_PI # define M_PI #endif #ifndef __APPLE__ # include <OpenGL/OpenGL.h> #include <GLUT/glut.h>

61 Angel.h // Define a macro for handling offsets into buffers
#define BUFFER_OFFSET( offset ) ((GLvoid*) (offset)) // --- Include our class libraries and constants --- namespace Angel { // Function to load vertex and fragment shader files GLuint InitShader( const char* vertexShaderFile, const char* fragmentShaderFile ); const GLfloat DivideByZeroTolerance = GLfloat(1.0e-07); // Degrees-to-radians constant const GLfloat DegreesToRadians = M_PI / 180.0; } // namespace Angel

62 Angel.h ... } // namespace Angel #include "vec.h" #include "mat.h"
#include "CheckError.h" #define Print(x) do { std::cerr << #x " = " << (x) << std::endl; } while(0) // Globally use our namespace in our example programs. using namespace Angel; #endif // __ANGEL_H__

63 Emergency In case of an emergency, call my wife at (617)

64 Emergency In case of an emergency, call my wife at (617) 321-4567
If I die, my will is in left hand drawer of my desk

65 Emergency In case of an emergency, call my wife at (617) 321-4567
If I die, my will is in left hand drawer of my desk If the sink backs up, call the plumber at (617)

66 Event Handler If the sink backs up, call the plumber at (617) 969-7170
Often we wish to prepare for an eventuality We might like to define a routine to do the work However, we might not be around to call the routine ourselves We leave instructions: If this happens, take that action In programming, we can define an Event Handler for some events Also called a Callback Then we register a handler for the event glutMouseFunc ( mouse ); /* Registration */ Mouse events will be handled by the function mouse() The Framework we are using defines two things Which events are handled How to register for each type of event: the name and signature

67 Callbacks We register a handler for an event void display( void ) {
glClear( GL_COLOR_BUFFER_BIT ); // clear window glDrawArrays( GL_POINTS, 0, NumPoints ); glFlush(); } int main( int argc, char **argv ) ... glutDisplayFunc( display ); glutKeyboardFunc( keyboard ); glutMainLoop(); return 0; We register a handler for an event

68 Event Loop Note that the program defines a callback function named display() Every glut program must have a display() callback Does not need to be called display() The display()function that was registered is executed whenever OpenGL decides the window must be refreshed For example when the window is opened Callback must have correct signature – not checked in C We register the display() callback by calling glutDisplayFunc() void display(void){ ... } int main( int argc, char **argv ) { glutDisplayFunc( display );

69 Keyboard Callback void keyboard( unsigned char key, int x, int y ) {
switch ( key ) { case 033: exit( EXIT_SUCCESS ); break; } // Your main function should end by entering an event loop int main( int argc, char **argv ) ... glutDisplayFunc( display ); glutKeyboardFunc( keyboard ); glutMainLoop(); // Event Loop return 0;

70 int x, int y void keyboard( unsigned char key, int x, int y )
I understand why you need the parameter key. But what are x and y doing here?

71 int x, int y void keyboard( unsigned char key, int x, int y )
I understand why you need the parameter key. But what are x and y doing here? Search for glutKeyboardFunc 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 key callback parameter is the generated ASCII character. The state of modifier keys such as Shift cannot be determined directly; their only effect will be on the returned ASCII data. The x and y callback parameters indicate the mouse location in window relative coordinates when the key was pressed. …

72 main int main( int argc, char **argv ) { glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA ); glutInitWindowSize( 512, 512 ); glutCreateWindow( "Sierpinski Gasket" ); init(); glutDisplayFunc( display ); glutKeyboardFunc( keyboard ); glutMainLoop(); return 0; }

73 main void init( void ) { ... // Create a vertex array object
GLuint vao; glGenVertexArraysAPPLE( 1, &vao ); glBindVertexArrayAPPLE( vao ); // Create and initialize a buffer object GLuint buffer; glGenBuffers( 1, &buffer ); glBindBuffer( GL_ARRAY_BUFFER, buffer ); glBufferData( GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW ); // Load shaders and use the resulting shader program

74 main void init( void ) { ... // Load shaders and use the resulting shader program GLuint program = InitShader( "vshader21.glsl", "fshader21.glsl" ); glUseProgram( program ); // Initialize vertex position attribute in vertex shader GLuint loc = glGetAttribLocation(program, "vPosition" ); glEnableVertexAttribArray( loc ); glVertexAttribPointer( loc, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) ); glClearColor( 1.0, 1.0, 1.0, 1.0 ); // white background }

75 main void init( void ) { ... // Load shaders and use the resulting shader program GLuint program = InitShader( "vshader21.glsl", "fshader21.glsl" ); glUseProgram( program ); // Initialize vertex position attribute in vertex shader GLuint loc = glGetAttribLocation(program, "vPosition" ); glEnableVertexAttribArray( loc ); glVertexAttribPointer( loc, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) ); glClearColor( 1.0, 1.0, 0.5, 1.0 ); // - jdp }

76 What is left? We have not described The colors we are using to draw
We set the background here glClearColor( 1.0, 1.0, 1.0, 1.0 ); // white background But where do we set the drawing color? fshader21.glsl void main() { gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); }

77 What is left? We have not described The colors we are using to draw
glClearColor( 1.0, 1.0, 1.0, 1.0 ); // white background Change the drawing color… fshader21.glsl void main() { gl_FragColor = vec4( 0.0, 1.0, 0.0, 1.0 ); }

78 What is left? How we create a window to hold the image?
The size of the image int main( int argc, char **argv ) { glutInit( &argc, argv ); glutInitDisplayMode( GLUT_RGBA ); glutInitWindowSize( 512, 512 );

79 What is left? How long will we show the image? Loop until exit()
void keyboard( unsigned char key, int x, int y ) { switch ( key ) { case 033: exit( EXIT_SUCCESS ); break; } int main( int argc, char **argv ) { ... glutMainLoop();

80 What is left? Where the image appears within the window?
GLuint loc = glGetAttribLocation( program, "vPosition" ); glEnableVertexAttribArray( loc ); glVertexAttribPointer( loc, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) ); vshader21.glsl attribute vec4 vPosition; void main() { gl_Position = vPosition; }

81 Notes on compilation See book's website for examples Unix/linux
OpenGL nclude files usually in …/include/GL Compile with –lglut –lglu –lgl loader flags May have to add –L flag for X libraries Mesa is an open source library that implements OpenGL Mesa implementation is included with most linux distributions Check web for latest versions of Mesa and glut

82 Compilation on Windows XP
OpenGL is included with Vista and Windows 7 With XP, you needed to take more steps 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

83 MacOS X To build the examples, we need the OpenGL libraries and Framework Minimal compile line for self-contained problem % gcc gasket.c -framework OpenGL -framework GLUT -framework Foundation I want to see all warnings (-Wall -pedantic ) I like to name the executable gasket, not a.out (-o …) % gcc gasket.c -Wall –pedantic -framework OpenGL -framework GLUT -framework Foundation -o gasket Angle splits out the shader initialization code into initShader.cpp Angle puts header files in an include directory Rather than type this in each time, I use a makefile and say % make gasket

84 Makefile # Try one of these two options as a starting point
# You must have the OpenGL libraries installed # See for details # # GCC_OPTIONS=-Wall -pedantic -lglut -lGLU -lGL -lm GCC_OPTIONS=-Wall -pedantic -I ../include GL_OPTIONS=-framework OpenGL -framework GLUT OPTIONS=$(GCC_OPTIONS) $(GL_OPTIONS) .cpp: g++ ../Common/initShader.o $(OPTIONS) -o

85 circle.h #ifndef _CIRCLE_H_ #define _CIRCLE_H_H #include "Shape.h"
class Circle: public Shape { public: Circle(int x, int y, int r, int color); void draw(); bool intersects(Shape* s); bool intersects(Circle* c); private: int cx, cy, radius; }; #endif

86 mouse click void mouse (int button, int state, int x, int y ) {
if ( button==GLUT_LEFT_BUTTON && state==GLUT_DOWN ) { int xPos = x; int yPos = height - y; /* Flip y */ c2 = new Circle(xPos, yPos, SIZE, BLUE); numPoints = 1; glutPostRedisplay(); if (c1->intersects(c2)) cout << "Ouch!\n"; else cout << "Missed again!\n"; }

87 Fill in the Blanks // Dispatch to correct routine
bool Circle::intersects(Shape *s) { if (dynamic_cast<Circle *>(s)) return intersects((Circle *)s); else cout << "Not prepared for this shape\n"; return false; }

88 Fill in the Blanks / Put the real work here
bool Circle::intersects(Circle *other) { cout << "checkCollision called – place logic here"; // You may use this->radius, other->radius, // this->cx, this->cy, etc. return false; // Replace with your logic }

89 Drawing a circle with lines
void Circle::draw() { setColor(); /* Draw Center */ glBegin(GL_POINTS); glVertex2i( cx, cy ); glEnd(); /* Draw Circle Rim */ glBegin( GL_LINE_STRIP ); for (int i = 0; i <= NUM_CHORDS; i++) float theta = (float)(i* *2)/NUM_CHORDS; glVertex2i((int)(radius*sin(theta)) + cx, (int)(radius*cos(theta)) + cy); }

90 Set Color void Shape::setColor() { // Color is stored as int
unsigned int color = (unsigned)getColor(); // Break the color into RGB components glColor3ub((0x0FF0000 & color) >> 16, (0x0FF00 & color) >> 8, 0x0FF & color); } Think Geek

91 Display Routine /* Paint the background circle, and perhaps a second circle */ void display(void) { glClear(GL_COLOR_BUFFER_BIT); c1->draw(); /* Draw background circle */ /* Should we draw a circle? */ if (numPoints > 0) /* Did the user make a selection? */ c2->draw(); /* Draw circle around the cursor */ glFlush(); }

92 Ending Program /* Take input from the keyboard */
void keyboard (unsigned char key, int x, int y) { switch (key) { case 27: /* escape */ exit(0); break; }

93 Why Study Computer Graphics?
Widely used in two major sectors of the US economy Video Games Motion Pictures Used in many other areas, such as Visualization An interesting application of ideas Some very clever algorithms, cutting edge hardware Can help you understand why it takes so long to refresh an image It is fun!

94 What did we do tonight? Introduced some ideas we will see
Stepped all the way through a program that uses GPU programming. Did not discuss why it looks like Sierpinski's gasket Talked about initial assignment

95 Credits Non-credited images are from Ed Angel's book or are my creation


Download ppt "Intro to Computer Graphics CSCI E 234"

Similar presentations


Ads by Google