Computer Graphics - Chapter 4 - 10
Computer Graphics - Chapter 4 - 10
Computer Graphics - Chapter 4 - 10
COMPUTER GRAPHICS
COURSE NUMBER: COSC3072
PREREQUISITE: COMPUTER PROGRAMMING (COSC 1012)
1. Draw the Core Line: Use Bresenham’s or any other line algorithm to plot the central line.
2. For each point on the central line, plot additional pixels above and below or to the left and right.
3. For steep lines, the displacement is vertical (above/below); for shallow lines, the displacement is horizontal
(left/right).
Parallel Line Algorithm 22
1. Determine Dash Length and Gap: Decide on the length of each dash
and the gap between dashes.
2. Draw the Line in Segments: Use a line drawing algorithm to draw a
segment (dash), then skip a corresponding gap before drawing the next
segment. function DashedLine(x1, y1, x2, y2, dashLength, gapLength):
currentLength = 0
while currentLength < totalLength(x1, y1, x2, y2):
drawLineSegment(x1, y1, x2, y2, dashLength)
skipLineSegment(x1, y1, x2, y2, gapLength)
currentLength += dashLength + gapLength
Dotted Line Algorithm 24
The dotSpacing parameter defines how frequently the points are plotted. For
example, if dotSpacing = 3, every third point will be plotted.
1. Function: y = x^2
2. Domain: All real numbers
3. Range: y ≥ 0
4. Select a set of x-values, such as: -3, -2, -1, 0, 1, 2, 3.
5. Calculate the corresponding y-values: 9, 4, 1, 0, 1, 4, 9.
6. Connect the points using a smooth curve.
27
Example2 Polyline 28
Circle Drawing Algorithms 29
A circle is a closed two-dimensional figure in which the set of all the
points in the plane is equidistant from a given point called “centre”.
Circumference (C) = πd = 2 π r
Area of a circle = πr2 We know that Area is the
space occupied by the circle.
Circle Drawing Algorithms 31
1. Initialization: The algorithm starts at the circle's radius (i.e., (0, r)) and
iteratively steps along the perimeter of the circle.
2. Decision Parameter: determine whether the next point should move
horizontally or diagonally.
3. Since circles are symmetric, the algorithm only calculates points for
one-eighth of the circle and reflects these points across all octants.
4. The process continues until the point reaches the x > y diagonal.
Midpoint Circle Drawing Algorithm 37
p1 = p0 + 2 x1 + 1 = −9 + 3 = −6
OpenGL Circle Example 40
41
Polygon Plotting 42
Input: A set of vertices [(x1, y1), (x2, y2), ..., (xn, yn)]
defining the polygon.
1. Start with the first vertex (x1, y1).
2. For i = 1 to n-1: - Draw a line from (xi, yi) to (xi+1, yi+1).
3. Connect the last vertex (xn, yn) back to the first vertex
(x1, y1) to close the polygon.
4. Optionally fill the polygon if needed.
Filling 44
Input: A polygon defined by vertices [(x1, y1), (x2, y2), ..., (xn, yn)].
1. Sort the vertices of the polygon by their y-coordinates.
2. Initialize the Edge Table and fill it with the polygon’s edges.
3. For each scanline from the bottom y-coordinate to the top y-
coordinate:
Find the intersection points of the scanline with the polygon edges.
Sort the intersection points by their x-coordinates.
Fill the pixels between each pair of intersection points.
4. Repeat for all scanlines to fill the polygon.
Polygon Examples 46
Text and Characters in Computer 47
Graphics
Text and characters play This means that the
characters are rendered directly from a pixel grid
instead of vector graphics, making them useful
for applications that require fixed-size fonts or
low-resolution displays a significant role in
computer graphics, especially in user interfaces,
digital art, games, and other visual media.
They provide essential information and enhance
the visual experience.
Text Representation 48
Bitmap Fonts:
Vector Fonts:
Unicode:
Rasterization Process:
Converting vector text into a bitmap image suitable for display
on a raster device. Techniques: Font Smoothing: Techniques like
anti-aliasing to improve the appearance of text edges.
TextShading: Adding shadows or gradients to enhance
readability.
Texture Mapping:
Applying a bitmap font as a texture to a surface in 3D
OpenGL Text Rendering 52
53
54
End of Chapter 4
55
COMPUTER GRAPHICS
COURSE NUMBER: COSC3072
PREREQUISITE: COMPUTER PROGRAMMING (COSC 1012)
Introduction
Mathematical Foundations
Transformation
Transformation in Practice (OpenGL)
Introduction 57
Homogenous Coordinates 59
Cartesian coordinates, you can divide the
first three components by the last
component 𝑤.
Where:
• The upper-left 3x3 part represents rotation and scaling.
• The right-most column represents translation.
• The bottom row handles perspective transformations
(usually 0, 0, 0, 1 for standard transformations).
Types of Transformations 70
x cos − sin 0 x
2D Rotation y = sin cos 0 y , P = R ( ) P
1 0 0 1 1
x S x 0 0 x
2D Scaling y = 0 Sy 0 y , P = S ( S x , S y ) P
1 0 0 1 1
Why Matrix Multiplication? 72
April 2010
y y t y
y P = P + T
P
P x
Sx
x = x s x , y = y s y Sy
x s x 0 x
y = 0 s y y
P = S P
2D Rotation 76
y
yr
x
xr
x = xr + ( x − xr ) cos − ( y − yr ) sin
y
( x, y)
y = yr + ( x − xr ) sin + ( y − yr ) cos
P = Pr + R ( P − Pr )
( x, y ) Rotation in angle about a
cos − sin
( xr , yr ) x R= pivot (rotation) point ( xr , yr ) .
sin cos
Rotationsin3D y
Viewlookingdown-xaxis:
y
x z
xcoordinateisunchangedby
z rotationaboutx
z
y
x
zcoordinateisunchangedby
rotationaboutz
z
78
Reflection 79
(left) Original Image (right)
Image after horizontal
reflection.
Reflection is a vital geometric
transformation in both 2D and 3D space,
allowing for the mirroring of points over
specific lines or planes.
The reflection of a point (x, y) over the x-axis
results in the point (x,−y).
The reflection of a point (𝑥,𝑦) over the y-axis
results in the point (−𝑥,𝑦).
The reflection of a point (𝑥,𝑦) over the line 𝑦=𝑥
results in the point (𝑦,𝑥).
Reflection in 3D 80
Parameters:
• eyeX, eyeY, eyeZ: The position of the camera or the
viewer in 3D space (the eye point).
• centerX, centerY, centerZ: The point in 3D space that
the camera is looking at (the target point or center).
• upX, upY, upZ: The direction that defines "up" for the
camera. This is typically the positive Y-axis (0, 1, 0) but
can vary depending on the desired orientation.
Transforms in Professional Software 84
● Godot: https://godotengine.org/
● Unity: https://unity.com/
● Unreal: https://www.unrealengine.com/en-US
● Blender: https://www.blender.org/
● GLM: https://github.com/g-truc/glm
Classroom Exercise 85
• GL_FRONT_AND_BACK,
• GL_FRONT, or
• GL_BACK;
Mode can be GL_POINT, GL_LINE, or GL_FILL to
Important Considerations:
indicate whether the polygon should be drawn as Performance: Wireframe and point modes can improve rendering
performance, particularly when testing or visualizing complex models.
points, outlined, or filled. By default, both the front
Shader Compatibility: If you are using shaders, ensure the shader
and back faces are drawn filled. handles line and point modes properly, as some shader programs may
assume solid fills by default.
Control the Display of Polygons 115
Normalize N:
Vertex Arrays 122
Advantages
❑ It can be used to model almost any object.
❑ They are easy to represent as a collection of vertices.
❑ They are easy to transform.
❑ They are easy to draw on computer screen.
Disadvantages
❑ Curved surfaces can only be approximately described.
❑ It is difficult to simulate some type of objects like hair or liquid.
146
Modelling 147
Techniques
Box Modeling
Start with a simple box (or cube)
and refine its shape by adding
detail and manipulating its
vertices, edges, and faces.
Use Case: Ideal for creating
complex shapes from a basic
form, commonly used in
character modeling.
Modelling Techniques 148
Subdivision Surface
Modeling:
Increasesthe number of polygons
by subdividing faces, creating a
smoother surface.
Averages vertex positions for a
more natural, organic shape.
Popular in character modeling
and other organic shapes.
150
GLUT 3D Models 151
GLUT (OpenGL Utility Toolkit) provides a set of
predefined geometric shapes that you can
render in either solid or wireframe forms.
Two main categories
❑ Wireframe Models
❑ Solid Models
Basic Shapes
❑ Cube: glutWireCube( ), glutSolidCube( )
❑ Cone: glutWireCone( ), glutSolidCone( )
❑ Sphere, Torus, Tetrahedron
More advanced shapes
❑ Octahedron (8), Dodecahedron (12),
Icosahedron (20)
❑ Teapot (symbolic)
Predefined Geometric Shapes
152
Solid: glutSolidTeapot(GLdouble size) Solid: glutSolidCube(GLdouble size)
Wireframe: glutWireTeapot(GLdouble size) Wireframe: glutWireCube(GLdouble size)
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
int main(int argc, char** argv) {
// Draw a solid teapot
glColor3f(0.0, 0.5, 0.0); glutInit(&argc, argv);
glutSolidTeapot(1.0); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
World Space Positions the object in a larger Translation, Rotation, glTranslatef(2.0f, 0.0f, 0.0f);
scene, transforming from local Scaling
space to its place in the world.
View (Camera) Adjusts the scene to the camera’s gluLookAt or equivalent gluLookAt(0.0, 0.0, 3.0, 0.0, 0.0, 0.0,
Space perspective, simulating the rotation 0.0, 1.0, 0.0);
viewpoint of the viewer.
Clip Space Transforms coordinates into the Projection glOrtho(-1.0, 1.0, -1.0, 1.0, 1.0, -1.0);
canonical viewing volume for Transformation
visibility determination (range [-1,
1]).
Normalized Device Scales clip space to fit the device Perspective Division Internally handled by OpenGL
Coordinates (NDC) screen, mapping coordinates to
[-1, 1] in each axis.
Screen Space Maps NDC to pixel positions on Viewport glViewport(0, 0, width, height);
the screen. This is what is actually Transformation
rendered.
Projection Types: Perspective and 157
Orthographic
Perspective Projection
❑ Mimics human vision, where objects appear smaller as they get farther
from the viewer.
❑ Mathematics: Objects are scaled based on distance from the viewpoint.
❑ Usage: Applied in realistic scenes (e.g., video games, simulations).
❑ gluPerspective( fieldOfViewAngle, aspect, near, far );
glLoadIdentity(); // Resets the projection matrix to an identity matrix. This clears any previous
transformations, so the following projection transformations start fresh.
gluPerspective: This function defines a perspective projection glMatrixMode(GL_MODELVIEW); // Switches to the
matrix. In this context, it sets the viewing volume parameters: model-view matrix, which controls object
• 45.0: Field of view angle in the y-direction (vertical FOV) in transformations (translations, rotations, scaling) and
degrees. Here, it’s set to 45 degrees, meaning the viewer can camera positioning.
see 45 degrees above and below the center of the view.
• 1.0: Aspect ratio (width/height) of the viewing volume. Here, 1.0 gluLookAt(
sets a square aspect ratio. 0.0, 1.5, 5.0, // Camera Position
• 1.0: Near clipping plane. Objects closer than this distance from 0.0, 1.0, 0.0, // Look-at Point (Target)
the camera are not visible. 0.0, 1.0, 0.0 // Up Vector
• 100.0: Far clipping plane. Objects farther than this distance from );
(x, y, z) = (0.0, 1.0, 0.0) means that the positive y-axis is
the camera are also not visible. considered "up" for the camera. This is used to orient
the camera properly in 3D space.
In computer graphics, cameras
are the windows through which
we view 3D scenes.
164
Non-Polygonal Representations 165
”
a 3D volume and blending layers to achieve a smooth, volumetric
appearance.
Ambient Light
Represents indirect light scattered from the environment.
Creates a base level of brightness and does not have a specific direction.
Point Light
Emits light equally in all directions from a single point (e.g., light bulbs).
Light intensity decreases with distance.
Directional Light
Light rays are parallel and consistent, simulating a distant light source (e.g., sunlight).
Position is effectively "at infinity," so intensity does not change with distance.
Spotlight
Emits light within a cone shape, with intensity fading toward the edge of the cone.
Useful for focused lighting (e.g., stage lights).
void glLightfv(GLenum light, GLenum 169
pname, const GLfloat *params);
The glLightfv function in OpenGL is used to define
various properties of a light source.
Each light in OpenGL can have parameters for
position, direction, ambient intensity, diffuse
intensity, specular intensity, and more.
light: Specifies which light source you're setting properties for. OpenGL supports multiple lights, labeled
GL_LIGHT0 to GL_LIGHT7.
pname: Specifies the property of the light source to set (e.g., position, ambient, diffuse, specular, etc.).
params: An array containing the values for the specified property. The number of elements required
depends on pname.
Parameter Name: GL_POSITION 170
GLfloat diffuse[] = {0.8f, 0.8f, 0.8f, 1.0f}; // Bright, white diffuse light
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
Parameter - GL_SPECULAR 175
GLfloat mat_diffuse[] = {1.0, 0.5, 0.31, 1.0}; // Orange color for the
material
GLfloat light_diffuse[] = {1.0, 1.0, 1.0, 1.0}; // White diffuse light
glutSwapBuffers();
}
3. Add Light Parameters: int main(int argc, char** argv) {
glutInit(&argc, argv);
GLfloat light_position[] = {1.0f, 1.0f, 1.0f, 0.0f}; glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("Lighting and Shading");
glLightfv(GL_LIGHT0, GL_POSITION, light_position); glEnable(GL_DEPTH_TEST);
initLighting();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
189
190
Facts About Colour 191
Complementary Monochromatic
180 Degree
WEBSITE & APP
LOGO - Attention DESIGN
Triadic
Analogous
EDUCATION
INTERIOR DESIGN
What is colour Model? 195
In Photoshop, you’ll be able to see how HSL get calculated. In the main
color picker, if you move the color point from left to right, you’ll see that
the Saturation value gets updated, then if you move the color point from
top to bottom, it’s the Lightness (Brightness) value that gets updated.
Finally, if you select a different base color to the right of the vertical color
picker, the hue gets updated.
201
202
CYAN (GREEN +
BLUE)
CMYK 203
MAGENTA (RED
CMYK is a subtractive color model used in + BLUE)
printing.
Unlike RGB, which is based on light, CMYK works
by subtracting light from white paper using ink.
YELLOW (RED +
Colors are created by mixing the four primary GREEN)
Use Cases
Games: Applying textures to make objects appear as stone, metal, or wood
without adding extra polygons.
Simulations and VR: Enhancing realism for objects like terrain, skies, and
characters.
ArchitecturalVisualization: Adding textures like brick, wood, and metal to make
structures more lifelike.
Benefits of Texture Mapping
Realism: Adds complex details without extra geometry.
Efficiency: Reduces the number of polygons needed by using detailed images.
Flexibility:
Easily change textures to modify an object's appearance without
changing its structure.
Texture Mapping 216
1. Load Image Data: stbi_load reads image data and stores its dimensions.
2. Generate Texture ID: glGenTextures creates a unique texture identifier.
3. Bind Texture: glBindTexture makes the texture active.
4. Generate Mipmaps: gluBuild2DMipmaps creates scaled-down versions of the
texture.
5. Set Wrapping Options: glTexParameteri for GL_TEXTURE_WRAP_S and
GL_TEXTURE_WRAP_T defines how the texture should behave when wrapping.
6. Set Filtering Options: glTexParameteri for GL_TEXTURE_MIN_FILTER and
GL_TEXTURE_MAG_FILTER sets filtering for scaling.
7. Free Image Data: stbi_image_free releases memory allocated for the image.
Texture Mapping 217
// Create scaled-down versions of the texture (Texture type, Store Format (RGB), W, H, Color, Type, Pointe
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, width, height, GL_RGB, GL_UNSIGNED_BYTE, data);
// Set texture wrapping and filtering options S-Horizontal, T –Vertical, Smooth Transition, Smooth Scaling
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
void initGL() {
glEnable(GL_TEXTURE_2D); // Enable 2D texture mapping
loadTexture("path_to_image.jpg"); // Load your texture here
return 0;
}
224
COMPUTER GRAPHICS
COURSE NUMBER: COSC3072
PREREQUISITE: COMPUTER PROGRAMMING (COSC 1012)