Date post: | 22-Dec-2015 |
Category: |
Documents |
View: | 216 times |
Download: | 0 times |
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?
http://isites.harvard.edu/k81300
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
http://en.wikipedia.org/wiki/Red-eye_effect
4
What Computer Graphics isn't
Graphics User Interfaces: writing user interfaces
Menus and widgets
Take CS 247 - Software Design
Xerox 8010 compound documenten.wikipedia.org
5
What Computer Graphics isn't
Visualization: Can be used to
Tracking a storm
Show Gulf Stream currents
Surface TemperatureNASANOAA
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 imageThe Vertigo effect, from Hitchcock's Vertigohttp://www.youtube.com/watch?v=je0NhvAQ6fM
Copyright Pixar
7
What skills are important?
MathematicsModelling the objectsFollowing transformations from objects to points on screen
ProgrammingWriting programs to create objectsMaking the calls to the graphics system
CreativityCreate 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
Requisites (Preconditions)
It is often useful in programming to describe preconditions and postconditionsWhat is assumed when you call this routineWhat 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
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
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
12
Academic MisconductAll 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.
http://www.extension.harvard.edu/exams-grades-policies/student-responsibilities
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
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);
}
15
The InstructorJeff Parker Ph.D. in Mathematics (1980)Teaching since 1980 -
Williams, Amherst, Boston College 1980-1989Harvard Extension 1989 - PresentMiddlebury College 2004 - 2006Merrimack 2006 - 2008
Currently Research Advisor at Harvard ExtensionHelping students write Thesis Proposals and Theses
Industry ExperiencePhoenix - Postscript InterpreterPrime Computer - Client Server groupSun Microsystems - System Administration FrameworkAgile Networks (later Lucent) - Layer-3 SwitchNexabit Networks (later Lucent)- Big Fast RouterAxiowave Networks – Big Fast Router
16
CommunicationBe sure to check out the iSite – Check Recent Site Updates
Post questions and comments to BBoard
To reach me, send e-mail. 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
17
Communication
You can subscribe
Click on
"my account"
18
Our TextbookA classic text, now in sixth editionI have ordered copies from the bookstorePlease purchase 6th Edition: new APII have placed several versions on reserveCourse website has link to sample programs
The bookstore will now rent books
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 2Basic OpenGL: Chapter 2
Architecture
GLUT
Simple programs in two and three dimensions
Interaction
GLUT
GLU
GL
GLX, AGLor WGL
X, Win32, Mac O/S
software and/or hardware
application program
OpenGL Motifwidget or similar
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
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.
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
31
Samples from Prior Year
32
Prior Year
33
Collision Problem
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
But we will see better ways
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
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 LibrariesOpenGL core library
OpenGL32 on WindowsGL 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 systemsWGL for WindowsAGL 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, AGLor WGL
X, Win32, Mac O/S
software and/or hardware
application program
OpenGL Motifwidget or similar
44
OpenGL ArchitectureImmediate Mode
DisplayList
PolynomialEvaluator
Per VertexOperations &
PrimitiveAssembly
RasterizationPer Fragment
Operations
TextureMemory
CPU
PixelOperations
FrameBuffer
geometry pipeline
45
OpenGL Functions
PrimitivesPointsLine SegmentsPolygons
AttributesTransformations
ViewingModeling
Control (GLUT)Input (GLUT)Query
46
OpenGL State
OpenGL is a state machineOpenGL functions are of two types
Primitive generatingCan cause output if primitive is visibleHow vertices are processed and appearance
of primitive are controlled by the stateState changing
Transformation functionsAttribute 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
glVertex3f(x,y,z)
belongs to GL library
function name
type - x,y,z are floats
glVertex3fv(p)
vector – p is a pointer to an array
dimensions
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
Alternativemain() # 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
Alternativemain() # 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 codevoid 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 Gamevoid 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
Chaos Game
Chaos Game is due to Michael BarnsleyGiven a starting dot and a goal triangle (green)
Goal is to move dot into triangle in fewest number of moves
http://math.bu.edu/DYSYS/applets/chaos-game.htmlJohanna Voolich and Robert L. Devaney
56
Chaos Gamehttp://math.bu.edu/DYSYS/applets/chaos-game.html
57
Chaos Gamevoid 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 backgroundHow we create a window to hold the imageWhere the image appears within the windowThe size of the imageHow 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 3.14159265358979323846#endif
#ifndef __APPLE__# include <OpenGL/OpenGL.h>#endif#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) 321-4567
64
Emergency
In case of an emergency, call my wife at (617) 321-4567If 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-4567If I die, my will is in left hand drawer of my deskIf the sink backs up, call the plumber at (617) 969-7170
66
Event HandlerIf the sink backs up, call the plumber at (617) 969-7170Often we wish to prepare for an eventuality
We might like to define a routine to do the workHowever, we might not be around to call the routine ourselvesWe leave instructions:
If this happens, take that actionIn programming, we can define an Event Handler for some events
Also called a CallbackThen 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 handledHow to register for each type of event: the name and signature
67
Callbacksvoid 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 LoopNote that the program defines a callback function named display()
Every glut program must have a display() callbackDoes 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 openedCallback must have correct signature – not checked in CWe register the display() callback by calling glutDisplayFunc()
void display(void){ ...}
int main( int argc, char **argv ){ ... glutDisplayFunc( display );
69
Keyboard Callbackvoid 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 yvoid 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 yvoid 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 glutKeyboardFunchttp://www.opengl.org/resources/libraries/glut/spec3/node49.html
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
mainint 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
mainvoid 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
mainvoid 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
mainvoid 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 drawWe 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 drawglClearColor( 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.glslattribute 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
http://www.mesa3d.org/
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
MacOS XTo build the examples, we need the OpenGL libraries and FrameworkMinimal 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.cppAngle puts header files in an include directoryRather than type this in each time, I use a makefile and say
% make gasket
Makefile# Try one of these two options as a starting point# You must have the OpenGL libraries installed# See http://www.opengl.org/ for details# # GCC_OPTIONS=-Wall -pedantic -lglut -lGLU -lGL -lmGCC_OPTIONS=-Wall -pedantic -I ../includeGL_OPTIONS=-framework OpenGL -framework GLUT OPTIONS=$(GCC_OPTIONS) $(GL_OPTIONS)
.cpp: g++ [email protected] ../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 clickvoid 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*3.14159*2)/NUM_CHORDS;
glVertex2i((int)(radius*sin(theta)) + cx, (int)(radius*cos(theta)) + cy);
}
glEnd();
}
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;
}
}
Why Study Computer Graphics?
Widely used in two major sectors of the US economyVideo Games Motion Pictures
Used in many other areas, such as VisualizationAn interesting application of ideas
Some very clever algorithms, cutting edge hardwareCan help you understand why it takes so long to refresh an
image
It is fun!
What did we do tonight?
Introduced some ideas we will seeStepped all the way through a program that uses GPU
programming.Did not discuss why it looks like Sierpinski's
gasketTalked about initial assignment
Credits
Non-credited images are from Ed Angel's book or are my creation