47
Chapter 10 Chapter 10 Bresenham’s Algorithm Bresenham’s Algorithm Data Structures and Data Structures and Graphics or Graphics or Working with Models Working with Models

Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Embed Size (px)

Citation preview

Page 1: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Chapter 10Chapter 10

Bresenham’s AlgorithmBresenham’s Algorithm

Data Structures and Graphics orData Structures and Graphics or

Working with ModelsWorking with Models

Page 2: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

What is a model?What is a model?

representation of some (not necessarily representation of some (not necessarily all) features of a concrete or abstract all) features of a concrete or abstract entityentity

Page 3: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Bohr ModelBohr Model

model of the atom model of the atom name honors of Niels Bohr who proposed name honors of Niels Bohr who proposed

the structure in 1913. the structure in 1913. Bohr atom consists of a central nucleus Bohr atom consists of a central nucleus

composed of neutrons and protons, composed of neutrons and protons, which is surrounded by electrons which which is surrounded by electrons which “orbit” around the nucleus. “orbit” around the nucleus.

Page 4: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

What models use What models use Graphics?Graphics?

Qualitative ModelsQualitative Models expressed as system expressed as system

of equationsof equations can be experimented can be experimented

with by modifying with by modifying independent variablesindependent variables

depicted by graphs or depicted by graphs or plotsplots

Page 5: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

What models use What models use Graphics?Graphics?

Organizational Organizational ModelsModels hierarchieshierarchies examplesexamples

library classificationlibrary classification org. chartorg. chart

Page 6: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models
Page 7: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

What models use What models use Graphics?Graphics?

Geometric ModelsGeometric Models block diagramsblock diagrams pseudo realistic pseudo realistic

photographsphotographs

Page 8: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models
Page 9: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Why use models?Why use models?

Visualize structure or behaviorVisualize structure or behavior Provide a vehicle for experimentationProvide a vehicle for experimentation SimulationsSimulations

new pharmaceuticalsnew pharmaceuticals engineeringengineering flight trainingflight training disaster recoverydisaster recovery

Page 10: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Chemical EngineeringChemical Engineering

A three-dimensional A three-dimensional model for the beta-2 model for the beta-2 adrenergic receptor, adrenergic receptor, with an epinephrine with an epinephrine molecule docked in the molecule docked in the proposed binding pocket proposed binding pocket (shown in cyan). (shown in cyan).

Page 11: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Flight TrainingFlight Training

Pilots learn to flyPilots learn to fly Aviation attendants Aviation attendants

learn to park planeslearn to park planes

Page 12: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Automotive EngineeringAutomotive Engineering Crash simulationsCrash simulations Structural AnalysisStructural Analysis

Page 13: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

The following The following slidesslidesare from:are from:Ed AngelEd Angel

Professor of Computer Science, Professor of Computer Science, Electrical and Computer Electrical and Computer Engineering, and Media ArtsEngineering, and Media Arts

University of New MexicoUniversity of New Mexico

Page 14: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

ObjectivesObjectives

Build a tree-structured model of a Build a tree-structured model of a humanoid figurehumanoid figure

Examine various traversal strategiesExamine various traversal strategies Build a generalized tree-model structure Build a generalized tree-model structure

that is independent of the particular that is independent of the particular modelmodel

Page 15: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Humanoid FigureHumanoid Figure

Page 16: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Building the ModelBuilding the Model

Can build a simple implementation using Can build a simple implementation using quadrics: ellipsoids and cylindersquadrics: ellipsoids and cylinders

Access parts through functionsAccess parts through functions torso()torso() left_upper_arm()left_upper_arm()

Matrices describe position of node with Matrices describe position of node with respect to its parentrespect to its parent MMllalla positions left lower leg with respect to positions left lower leg with respect to

left upper armleft upper arm

Page 17: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Tree with MatricesTree with Matrices

Page 18: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Display and TraversalDisplay and Traversal

The position of the figure is determined The position of the figure is determined by 11 joint angles (two for the head and by 11 joint angles (two for the head and one for each other part)one for each other part)

Display of the tree requires a Display of the tree requires a graph graph traversaltraversal Visit each node onceVisit each node once Display function at each node that describes Display function at each node that describes

the part associated with the node, applying the part associated with the node, applying the correct transformation matrix for position the correct transformation matrix for position and orientationand orientation

Page 19: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Transformation MatricesTransformation Matrices

There are 10 relevant matricesThere are 10 relevant matrices MM positions and orients entire figure through positions and orients entire figure through

the torso which is the root nodethe torso which is the root node MMhh positions head with respect to torso positions head with respect to torso

MMlualua, , MMruarua, , MMlullul, , MMrulrul position arms and legs position arms and legs

with respect to torsowith respect to torso MMllalla, , MMrlarla, , MMllllll, , MMrllrll position lower parts of limbs position lower parts of limbs

with respect to corresponding upper limbswith respect to corresponding upper limbs

Page 20: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Stack-based TraversalStack-based Traversal Set model-view matrix to Set model-view matrix to MM and draw and draw

torsotorso Set model-view matrix to Set model-view matrix to MMMMhh and draw and draw

headhead For left-upper arm need For left-upper arm need MMMMlua lua and so onand so on

Rather than recomputing Rather than recomputing MMMMlualua from from

scratch or using an inverse matrix, we scratch or using an inverse matrix, we can use the matrix stack to store can use the matrix stack to store M M and and other matrices as we traverse the treeother matrices as we traverse the tree

Page 21: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Traversal CodeTraversal Code

figure() {figure() { glPushMatrix()glPushMatrix() torso();torso(); glRotate3f(…);glRotate3f(…); head();head(); glPopMatrix();glPopMatrix(); glPushMatrix();glPushMatrix(); glTranslate3f(…);glTranslate3f(…); glRotate3f(…);glRotate3f(…); left_upper_arm();left_upper_arm(); glPopMatrix();glPopMatrix(); glPushMatrix();glPushMatrix();

save present model-view matrix

update model-view matrix for head

recover original model-view matrix

save it again

update model-view matrix for left upper arm

recover and save original model-view matrix again

rest of code

Page 22: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

AnalysisAnalysis

The code describes a particular tree and a The code describes a particular tree and a particular traversal strategyparticular traversal strategy Can we develop a more general approach?Can we develop a more general approach?

Note that the sample code does not include Note that the sample code does not include state changes, such as changes to colorsstate changes, such as changes to colors May also want to use May also want to use glPushAttribglPushAttrib and and glPopAttribglPopAttrib to protect against unexpected state to protect against unexpected state changes affecting later parts of the codechanges affecting later parts of the code

Page 23: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

General Tree Data StructureGeneral Tree Data Structure

Need a data structure to represent tree Need a data structure to represent tree and an algorithm to traverse the treeand an algorithm to traverse the tree

We will use a We will use a left-child right siblingleft-child right sibling structurestructure Uses linked listsUses linked lists Each node in data structure is two pointersEach node in data structure is two pointers Left: next nodeLeft: next node Right: linked list of childrenRight: linked list of children

Page 24: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Left-Child Right-Left-Child Right-Sibling TreeSibling Tree

Page 25: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Tree node StructureTree node Structure

At each node we need to store At each node we need to store Pointer to siblingPointer to sibling Pointer to childPointer to child Pointer to a function that draws the object Pointer to a function that draws the object

represented by the noderepresented by the node Homogeneous coordinate matrix to multiply on the Homogeneous coordinate matrix to multiply on the

right of the current model-view matrixright of the current model-view matrix Represents changes going from parent to nodeRepresents changes going from parent to node In OpenGL this matrix is a 1D array storing In OpenGL this matrix is a 1D array storing

matrix by columns matrix by columns

Page 26: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

C Definition of treenodeC Definition of treenode

typedef struct treenodetypedef struct treenode

{{

Glfloat m[16];Glfloat m[16];

void (*f)();void (*f)();

struct treenode *sibling;struct treenode *sibling;

struct treenode *child;struct treenode *child;

} treenode;} treenode;

Page 27: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Defining the torso nodeDefining the torso nodetreenode torso_node, head_node, lua_node, … ;treenode torso_node, head_node, lua_node, … ; /* use OpenGL functions to form matrix *//* use OpenGL functions to form matrix */glLoadIdentity();glLoadIdentity();glRotatef(theta[0], 0.0, 1.0, 0.0);glRotatef(theta[0], 0.0, 1.0, 0.0); /* move model-view matrix to m *//* move model-view matrix to m */glGetFloatv(GL_MODELVIEW_MATRIX, glGetFloatv(GL_MODELVIEW_MATRIX, torso_node.m)torso_node.m)

torso_node.f = torso; /* torso() draws torso torso_node.f = torso; /* torso() draws torso */*/

Torso_node.sibling = NULL;Torso_node.sibling = NULL;Torso_node.child = &head_node;Torso_node.child = &head_node;

Page 28: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Dynamic TreesDynamic Trees

If we use pointers, the structure can be dynamicIf we use pointers, the structure can be dynamic

typedef treenode *tree_ptr;typedef treenode *tree_ptr;

tree_ptr torso_ptr;tree_ptr torso_ptr;

torso_ptr = malloc(sizeof(treenode));torso_ptr = malloc(sizeof(treenode));

Definition of nodes and traversal are Definition of nodes and traversal are essentially the same as before but we can add essentially the same as before but we can add and delete nodes during executionand delete nodes during execution

Page 29: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

ObjectivesObjectives

Introduce graphical objectsIntroduce graphical objects Generalize the notion of objects to Generalize the notion of objects to

include lights, cameras, attributesinclude lights, cameras, attributes Introduce scene graphs Introduce scene graphs

Page 30: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Limitations of Immediate Limitations of Immediate Mode GraphicsMode Graphics

When we define a geometric object in an When we define a geometric object in an application, upon execution of the code application, upon execution of the code the object is passed through the pipeline the object is passed through the pipeline

It then disappears from the graphical It then disappears from the graphical systemsystem

To redraw the object, either changed or To redraw the object, either changed or the same, we must reexecute the codethe same, we must reexecute the code

Display lists provide only a partial Display lists provide only a partial solution to this problemsolution to this problem

Page 31: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

OpenGL and ObjectsOpenGL and Objects OpenGL lacks an object orientationOpenGL lacks an object orientation Consider, for example, a green sphereConsider, for example, a green sphere

We can model the sphere with polygons or We can model the sphere with polygons or use OpenGL quadricsuse OpenGL quadrics

Its color is determined by the OpenGL state Its color is determined by the OpenGL state and is not a property of the objectand is not a property of the object

Defies our notion of a physical objectDefies our notion of a physical object We can try to build better objects in code We can try to build better objects in code

using object-oriented using object-oriented languages/techniqueslanguages/techniques

Page 32: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Imperative Programming Imperative Programming ModelModel

Example: rotate a cubeExample: rotate a cube

The rotation function must know how the The rotation function must know how the cube is representedcube is representedVertex listVertex listEdge listEdge list

Application glRotate

cube data

results

Page 33: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Object-Oriented Object-Oriented Programming ModelProgramming Model

Application Cube Object

• In this model, the representation is stored In this model, the representation is stored with the object with the object

• The application sends a The application sends a messagemessage to the to the objectobject

• The object contains functions (The object contains functions (methodsmethods) ) which allow it to transform itselfwhich allow it to transform itself

message

Page 34: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

C/C++C/C++

Can try to use C structs to build objects Can try to use C structs to build objects C++ provides better supportC++ provides better support

Use class constructUse class construct Can hide implementation using public, Can hide implementation using public,

private, and protected members in a classprivate, and protected members in a class Can also use friend designation to allow Can also use friend designation to allow

classes to access each otherclasses to access each other

Page 35: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Cube ObjectCube Object

Suppose that we want to create a simple Suppose that we want to create a simple cube object that we can scale, orient, cube object that we can scale, orient, position and set its color directly through position and set its color directly through code such ascode such as

cube mycube;cube mycube;

mycube.color[0]=1.0;mycube.color[0]=1.0;

mycube.color[1]=mycube.color[2]=0.0;mycube.color[1]=mycube.color[2]=0.0;

mycube.matrix[0][0]=………mycube.matrix[0][0]=………

Page 36: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Cube Object FunctionsCube Object Functions We would also like to have functions that We would also like to have functions that

act on the cube such as act on the cube such as mycube.translate(1.0, 0.0,0.0);mycube.translate(1.0, 0.0,0.0); mycube.rotate(theta, 1.0, 0.0, mycube.rotate(theta, 1.0, 0.0, 0.0);0.0);

setcolor(mycube, 1.0, 0.0, 0.0);setcolor(mycube, 1.0, 0.0, 0.0);

We also need a way of displaying the We also need a way of displaying the cubecube mycube.render();mycube.render();

Page 37: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Building the Cube ObjectBuilding the Cube Object

class cube {class cube {

public:public:

float color[3];float color[3];

float matrix[4][4];float matrix[4][4];

// public methods// public methods

private:private:

// implementation// implementation

}}

Page 38: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

The ImplementationThe Implementation

Can use any implementation in the Can use any implementation in the private part such as a vertex listprivate part such as a vertex list

The private part has access to public The private part has access to public members and the implementation of members and the implementation of class methods can use any class methods can use any implementation without making it visibleimplementation without making it visible

Render method is tricky but it will invoke Render method is tricky but it will invoke the standard OpenGL drawing functions the standard OpenGL drawing functions such as such as glVertexglVertex

Page 39: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Other ObjectsOther Objects

Other objects have geometric aspectsOther objects have geometric aspects CamerasCameras Light sourcesLight sources

But we should be able to have But we should be able to have nongeometric objects toonongeometric objects too MaterialsMaterials ColorsColors Transformations (matrices)Transformations (matrices)

Page 40: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Application CodeApplication Code

cube mycube;cube mycube;

material plastic;material plastic;

mycube.setMaterial(plastic);mycube.setMaterial(plastic);

camera frontView;camera frontView;

frontView.position(x ,y, z);frontView.position(x ,y, z);

Page 41: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Light ObjectLight Objectclass light { // match Phong modelclass light { // match Phong model public:public: boolean type; //ortho or boolean type; //ortho or perspectiveperspective boolean near;boolean near; float position[3];float position[3]; float orientation[3];float orientation[3]; float specular[3];float specular[3]; float diffuse[3];float diffuse[3]; float ambient[3];float ambient[3];}}

Page 42: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Scene DescriptionsScene Descriptions

If we recall figure model, we saw that If we recall figure model, we saw that We could describe model either by tree or by We could describe model either by tree or by

equivalent codeequivalent code We could write a generic traversal to displayWe could write a generic traversal to display

If we can represent all the elements of a If we can represent all the elements of a scene (cameras, lights,materials, scene (cameras, lights,materials, geometry) as C++ objects, we should be geometry) as C++ objects, we should be able to show them in a treeable to show them in a tree Render scene by traversing this treeRender scene by traversing this tree

Page 43: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Scene GraphScene Graph

Page 44: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Preorder TraversalPreorder Traversal

glPushAttribglPushAttrib

glPushMatrix glPushMatrix

glColorglColor

glTranslateglTranslate

glRotateglRotate

Object1Object1

glTranslateglTranslate

Object2Object2

glPopMatrixglPopMatrix

glPopAttribglPopAttrib

……

Page 45: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Separator NodesSeparator Nodes

Necessary to isolate state chagesNecessary to isolate state chages Equivalent to OpenGL Push/PopEquivalent to OpenGL Push/Pop

Note that as with the figure modelNote that as with the figure model We can write a universal traversal algorithmWe can write a universal traversal algorithm The order of traversal can matter The order of traversal can matter

If we do not use the separator node, state If we do not use the separator node, state changes can propagatechanges can propagate

Page 46: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

Inventor and Java3DInventor and Java3D

Inventor and Java3D provide a scene graph API Inventor and Java3D provide a scene graph API Scene graphs can also be described by a file Scene graphs can also be described by a file

(text or binary)(text or binary) Implementation independent way of Implementation independent way of

transporting scenestransporting scenesSupported by scene graph APIsSupported by scene graph APIs

However, primitives supported should match However, primitives supported should match capabilities of graphics systemscapabilities of graphics systemsHence most scene graph APIs are built on Hence most scene graph APIs are built on

top of OpenGL or DirectX (for PCs)top of OpenGL or DirectX (for PCs)

Page 47: Chapter 10 Bresenham’s Algorithm Data Structures and Graphics or Working with Models

VRMLVRML

Want to have a scene graph that can be Want to have a scene graph that can be used over the World Wide Webused over the World Wide Web

Need links to other sites to support Need links to other sites to support distributed data basesdistributed data bases

VVirtual irtual RReality eality MMarkup arkup LLanguageanguage Based on Inventor data baseBased on Inventor data base Implemented with OpenGLImplemented with OpenGL