0% found this document useful (0 votes)
2 views446 pages

Lecture1-Introduction To Computer Graphics

This document outlines a course on Computer Graphics, focusing on techniques for creating 2D and 3D graphics using OpenGL, covering topics like rendering, transformations, and lighting. It includes course logistics, prerequisites, assessment methods, and policies regarding attendance and academic integrity. Additionally, it discusses the importance of computer graphics in various applications, including virtual reality, CAD, and scientific visualization.

Uploaded by

anas293salim
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views446 pages

Lecture1-Introduction To Computer Graphics

This document outlines a course on Computer Graphics, focusing on techniques for creating 2D and 3D graphics using OpenGL, covering topics like rendering, transformations, and lighting. It includes course logistics, prerequisites, assessment methods, and policies regarding attendance and academic integrity. Additionally, it discusses the importance of computer graphics in various applications, including virtual reality, CAD, and scientific visualization.

Uploaded by

anas293salim
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPUTER GRAPHICS

501472-3
Lecture 1: Introduction to Computer Graphics
Logistics

• Instructor: Dr. Mohammad Mirza


• Email: mmmirza@[Link]
• Office Hours: Monday, Tuesday. Otherwise, online on Teams or by appointment
• Course Slides: Blackboard
• Communication channels: Teams (most preferred), or email.

2
Course Description:

■ This course introduces techniques for constructing 2D and 3D Graphics using OpenGL.
■ The topics include the rendering pipeline, primitive drawings, geometric
transformations, clipping, lighting and illumination, color models texture mapping, and
ray-tracing animation.
Course Content:
1. Overview of computer graphics concepts
2. Cathode Ray Tube (CRT), spots and lights, raster and random scan displays, color models
3. Color CRT monitors, color models, flat CRT and Video controller systems Raster and vector
graphics.
4. OpenGl program and structures, Windows, points, coordinate system
5. Primitive objects and fill colors in OpenGL
6. Line drawing: DDA algorithm, Brasenham’s algorithm
7. Circle and midpoint circle algorithms, Brasenham’s algorithm
8. 2D/3D transformation such as translation, scaling, shearing, rotation, and affine
transformations
9. 2D/3D deformation such as shearing, tapering, twisting, bending
10. Model view
11. Light and Shadow
Prerequisites

■ Install C++, OpenGL, GLUT (freeglut – latest version is v3.8.0)


■ Basic linear algebra and analytic geometry
Assessment

■ Quiz 10% (Week 4: 9–10 February), (Week 10: 20-21 April)


■ Course Project 25% (Week 14: 2 Jun) - Presentation (8-9 June)
■ Assignments and Participation 5%
■ Midterm 20% (Week 6: 6-7 April)
■ Final 40%
Course Material

■ Textbook (Required):
o Computer Graphics with OpenGL by Donald D. Hearn, M. Pauline Baker, 4th Edition
■ Recommended References (Not obligatory):
o Computer Graphics Through OpenGL: From Theory to Experiments , 4th edition,
published in 2022
■ Software: C++ with FreeGlut library
■ Others: Lecture slides

■ All the course contents will be covered in class.

7
Policies

• Attendance: Students are allowed up to 20% absence, including sick leave, which still
counts towards this limit.
• Homework and Tests: Must be submitted by the due date. Late submissions will receive a
zero.
• Honor Code: Plagiarism and cheating are strictly prohibited. Violations result in a zero for
the assignment and may be subject to university disciplinary actions. Final exams will
adhere to university regulations.
• Generative AI Policy: If you use generative AI, you must cite it and explain its role in your
work. Using AI to complete entire assignments is not allowed.
• Phone Policy: Phones must be kept on silent during class. Taking pictures without prior
permission is not allowed.

9
Policies

■ Quizzes: Students will be informed of quiz dates in advance. There will be 2 quizzes,
contributing 10 points to the final grade.

■ Test Absence: Absence from tests is only allowed with a valid sick leave from a
public hospital or in the event of a first-degree relative's death. For any other
reasons, students must seek permission prior to missing the test.

10
OVERVIEW OF COMPUTER
GRAPHICS CONCEPTS
What is an image?

■ An image is a combination of objects,


lights, and a viewer (or camera).
■ It represents visual information, stored
in photographic films, canvas/paint or
digitally.
■ There are many ways of acquiring digital
images: Scanner, Digital cameras,
computer graphics and Others.
Image Synthesis
■ Image synthesis or image generation refers more to the construction of
images from scratch, rather than processing of existing images.
■ Synthesis of a 2D image from a 3D scene description is more commonly
called rendering.
■ Rendering is a specific type of image synthesis:
– It refers to the process of generating a 2D image from a 3D model. In
this context, a 3D scene description – which includes information about
geometry, viewpoint, texture, lighting, and shading – is converted into a
2D image.
– This is commonly used in video games and computer-animated films
where complex 3D models and environments need to be presented in a
way that is visually comprehensible from a certain viewpoint.
What is Computer Graphics (CG)?

■ Computer graphics generally means creation, storage and manipulation of


models and images by a computer.

■ Generating 2D images of a 3D world represented in a computer.

■ Use of computer to define, store, manipulate, interrogate and present


pictorial output.
What is Computer Graphics (CG)?
■ Different things in different contexts:
– Pictures, scenes that are generated by a computer.
– Tools used to make such pictures (digital images), software and
hardware, input/output devices.
– Field of study that involves these tools and the pictures they produce.
■ Computer Graphics involves:
– How pictures are represented in computer graphics.
– How pictures are prepared for presentation.
– How interaction within the picture is accomplished.
The difference between 2D and 3D are:

■ 2D: flat images, Objects has no notion of distance from viewer and only (x,y)
color values on screen.
■ 3D: Objects have distances from viewer with (x,y,z) values on screen.
Why Computer Graphics are important?

■ Computers have become powerful for the rapid and economical


production of pictures.
■ Computer graphic has a wide range of applications, including graphics
presentation, User Interface, image processing, simulation, virtual
reality, games and entertainment.
■ Graphical User Interfaces (GUI) Now all software applications provide
GUI environments which helps user easily to handle the software
using the help of interactive pointing devices.
Computer Graphics Applications
■ Data Visualization
– Visual techniques are used as aid in the understanding and
analysis of complex processes and mathematical functions.
– Used in scientific, business and medical visualization to study the
behaviour of complex process.
■ Graphs and charts
– To draw simple graphs, data plotting, to generate highly complex
data relationships.
– Used to summarize financial, statistical, mathematical, scientific,
engineering, economic data reports etc.,
Computer Graphics Applications
Computer-aided design (CAD)
– Used in design processes, particularly for engineering and
architectural systems.
– Generally referred to as CAD, computer-aided design methods are
now used in the design of buildings, automobiles, aircraft,
watercraft, spacecraft, computers, textiles, home appliances etc.,
VIRTUAL REALITY (VR)

Creation of VR environments in
which user interact with objects
in a 3D scene.
Educational and
Training
■ For training applications,
special hardware systems are
designed, such as training ship
Designing Effective Step-By-Step Assembly Instructions
(Maneesh Agrawala et. al)
captains, aircraft pilots.

View from the ship’s bridge in the virtual environment at


Dalian Maritime University.(Courtesy Xie Cui )
Pixar: Monster’s Inc.
ENTERTAINMENT
(MOVIES)

A Bug’s Life (Pixar)


Square: Final Fantasy
Entertainment
(Games)

GT Racer 3

Polyphony Digital: Gran Turismo 3, A Spec


Medical Visualization

The Visible Human Project


MIT: Image-Guided Surgery Project
Scientific Visualization
Airflow around a Harrier Jet (NASA Ames)
■ Scientific visualization refers to
the process of representing raw,
scientific data as images,
providing an external aid to
improve scientists’ interpretations
of large data sets and to gain
insights.

Airflow around a Harrier Jet (NASA Ames)


COMPUTER
ART
Image Processing
■ The modification or interpretation of existing pictures.
Everyday use

Window system and large-screen interaction metaphors (François Guimbretière)


Computer Graphics vs Computer Vision
■ Computer vision is sometimes considered as a separate discipline
from computer graphics, although they share many things in common.
■ Computer Vision (CV) is the science that allows computers to extract
useful information from images and analyse it.
■ The information extracted through CV can be used to assist in
decision-making or tasks, such as medical image analysis,
autonomous driving etc.
Computer Graphics vs Computer Vision

■ A central goal in computer vision is to take a set of 2D images (usually


from a video or set of photos) and infer from that a 3D description of
what is being viewed. This is a very different process than rendering and
is more of a form of artificial intelligence. (3D construction)
■ Computer Vision involves analysis and understanding images and
scenes.
■ Computer Graphics deals with synthesizing images, objects (2D/3D) by
employing algorithms and techniques.
■ CG uses mathematical models and computer algorithms to generate
images.
Computer Graphics vs Computer Vision
Computer Vision (CV) Computer Graphics (CG)
Definition Extracts useful information from Creates and synthesizes images, objects
images and analyzes them. (2D/3D) using algorithms.
Main Goal Understanding and interpreting Generating and rendering realistic or
images and scenes. stylized images.
Process Type Data extraction and analysis from Image and object synthesis from
existing images/videos. mathematical models.
Applications Medical image analysis, auto driving, Video game graphics, 3D animation,
face recognition. visual effects, virtual reality.
Data Input Real-world images or video data. Geometric models and textures.
Data Output Structured information (e.g., Images or visual scenes.
classifications).
Computer Graphics vs Computer Vision
Interactive vs. Non-Interactive Computer
Graphics
Interactive CG Non-Interactive CG
User input Allows real-time user Graphics do not respond to user
interaction with the graphics. input after initial creation.

Examples Video games, virtual reality Animated films, images, graphs,


simulations, CAD programs. and diagrams in presentations.

Requirements Requires systems capable of Requires significant computational


quick response to maintain resources to render high-quality
immersion. images in advanced.
Applications Education, training simulators, Media, advertising, architectural
gaming, real-time data visualization, storytelling.
visualization.
Conceptual Framework for Interactive
Graphics
• Application model is where the data or the application model is
stored, include the 3D models, textures, and other related data that
graphics application will render.
• Application program maps application objects to view (images) of
those objects by calling on graphics library. Application model may
contain lots of non-graphical data.
• Graphics library/package is intermediary between application and
display hardware (Graphics System).

software hardware
Conceptual Framework for Interactive
Graphics
• Graphics System is the actual hardware that renders the graphics.
The Graphics Processing Unit takes instructions from the graphics
library and uses them to process the application model data and
generate the final image or frame.
• The GPU is specialized hardware optimized for tasks such as shading,
texturing, and rendering 3D models.
• User interaction results in modification of image and/or model

software hardware
Graphics Library
■ Graphics Library are functions to draw line, circle, image, etc.
■ They are cross-platform, device-independent libraries. Examples:
OpenGL, Vulkan, DirectXTM, Windows Presentation Foundation (WPF),
and RenderManTM.
Graphics Library

■ Elements of a graphical library are:


– Primitives are the basic elements that form images (points, lines,
polygons)
– Attributes or material properties (Color, line style, material
properties for 3D)
– Light sources have location, strength, color, … etc.
– Transformations
– Immediate mode vs. retained mode
Graphics Library

■ Immediate mode vs. retained mode


– Immediate mode: no stored representation, package holds only
attribute state, and application must completely draw each frame.
– Retained mode: library compiles and displays from scene graph
that it maintains. It is a display-centered extract of the Application
Model.
Exercise 1:

Question1: What is the primary purpose of Computer-Aided Design


(CAD)?
A) To enhance photographs
B) To create visual effects in movies
C) To aid in the creation, modification, analysis, or optimization of a
design
D) To interpret and understand visual data from the world
Exercise 1:

Question 2: Which of the following best describes 'rendering' in the


context of computer graphics?
A. Converting text to HTML
B. Generating a 2D image from a 3D model
C. Compressing image files to reduce their size
D. Generating visual effects
Exercise 1:

Question 3: What does a primitive in computer graphics refer to?


A) A complex algorithm for image processing
B) A basic element from which images are created
C) An outdated graphics card
D) A tool used for digital painting
Exercise 1:

Question 4: In the context of interactive computer graphics, what does


'immediate mode' refer to?
A) Storing the entire scene and redrawing it for each change
B) Rendering objects directly to the screen without storing them
C) Immediately updating graphics upon user input
D) A mode that prioritizes speed over quality
BASIC COMPONENTS OF
A GRAPHICS SYSTEM
Basic Components of a Graphics
System
There are six major elements in a computer graphics system :
1. Input devices
2. Central Processing Unit
3. Graphics Processing Unit
4. Memory
5. Frame buffer
6. Output devices
1 Input Devices
■ Two types of input devices: physical and logical input devices.
■ Physical input devices are hardware peripherals that allow users to input
data into a computer system.
– The keyboard device is almost always a physical keyboard but can be
generalized to include any device that returns character codes
(ASCII)
■ The pointing device allows the user to indicate a position on the screen.
■ Each provides positional information to the system, and each usually is
equipped with one or more buttons to provide signals to the processor.
1 Input Devices
■ The Relative-positioning device changes in the position of the ball
yield a position in the user program; the absolute location of the ball
(or the mouse) is not used by the application.
– Touch sensitive screen such as ATMs
– Light Pens pencil shaped devices are used by detecting the light
coming from points on the sceen.
– Digitizers (e.g., graphic tablet) common device for drawing,
painting, or interactively selecting coordinate positions on an
object.
1 Input Devices
– Data Glove - used to grasp a "virtual" object. It is constructed with
sensors to detect hand and finger motions.
– Paddle Control, mouse operate by converting the motion of the
ball into signals sent to the computer through pairs of encoders.
two orthogonal directions.
– Joystick also known as the control column, is the principal control
devi
– Image Scanners - Drawings, graphs, color and black-and-white
photos, or text can be stored for computer processing with an
image scanner.
Physical
Input
Devices
1 Input Devices

Logical input devices: Two major characteristics: the measurements that the device
returns to the user program and the time when the device returns those measurements.
■ String device: the use of character input through scanf or cin.
■ Locator: it can provide a position to the application in either a device-independent
coordinate system, or in screen coordinates
■ Logical pick device returns the identifier of an object on the display to the
application program.
■ Widget is a graphical interactive device, provided by either the window system or a
toolkit. Such as menus, scrollbars, and graphical buttons.
■ Logical valuator provides analog input to the user program, usually through a widget
such as a slidebar, or a physical keyboard
2 Central processing unit (CPU)
■ The CPU, often called the "brain" of the computer, is a general-purpose
processor designed for sequential task execution and system
management.
■ General-purpose processing: Optimized for logic, math, and I/O
operations, not specialized for graphics.
– Sequential execution: Handles tasks one at a time with high
precision, unlike GPUs, which excel in parallel tasks.
– Managing operating systems and running diverse applications.
– Handling logical operations and decision-making processes.
– Performing tasks like browsing, word processing, and system control.
3 Graphics Processing Unit (GPU)

■ The main graphical function of the processor is to take specifications


of graphical primitives (such as lines, circles, and polygons) generated
by application programs and to assign values to the pixels in the
frame buffer that best represent these entities.
■ For example, a triangle is specified by its three vertices, but to display
its outline by the three-line segments connecting the vertices, the
graphics system must generate a set of pixels that appear as line
segments to the viewer.
3 Graphics Processing Unit (GPU)

■ A specialized electronic circuit designed to rapidly manipulate and


alter memory to accelerate the creation of images in a frame buffer
intended for output to a display device.
■ The GPU located either on PC motherboard (Intel) or Separate
graphics card (Nvidia or ATI).
The roles of GPU and CPU in graphical
system
Aspect GPU CPU
Primary Function Renders and processes graphics, Manages general-purpose tasks and
including images and videos. controls overall system operations.
Specialization Highly specialized for parallel Optimized for general-purpose tasks and
processing of graphics-related tasks. sequential processing.
Role in Graphics Performs image rendering, texture Coordinates high-level operations and sends
mapping, shading, and handling of commands to the GPU for rendering.
complex visual data.
Task Examples Rendering 3D scenes, applying Executing operating system processes,
shaders, encoding video, ray tracing. running applications, managing system
resources.
Interaction with Directly writes to and reads from the May access frame buffer for image
Frame Buffer frame buffer to generate images. manipulation or updates but does not
perform rendering.
4 Frame Buffer

■ This is a place where images and pictures are stored as a 2D array (matrix of 0 & 1,
0 represents darkness and 1 represents image or picture).
■ In today’s term frame buffer is called V-RAM (video RAM) and it helps to store the
image in bit form.
■ Frame buffer accessible to CPU of the main computer. This allowing repaid update of
the stored image.
5 Output devices

■ A display device is a device for visual or tactile presentation of images (including


text) acquired, stored, or transmitted in various forms.
■ Also known as an information display.
■ The display systems are often referred to as Video Monitor or Video Display Unit
(VDU).
■ The primary output device in a graphical system is the video monitor. Example :
Computer monitor, TV screen.
DISPLAY HARDWARE
How are images displayed?
Related Terminologies
■ Pixel: Picture Element

■ Resolution: No. of pixels per unit video display


■ Display Size: Measured as distance from one corner
to the diagonally opposite corner (inches).

■ Persistence: How long a phosphor continue to emit light. Lower


persistence phosphors require higher refresh rate to maintain a picture
on the screen without flicker. (The time it takes the emitted light from
the screen to decay to one-tenth of its original intensity.)

■ Viewing Angle: It is angle from which the screen can be seen from side.
Related Terminologies

■ Response time: The minimum time necessary to change a pixel’s color or


brightness.

■ Brightness: The amount of light emitted from the display.


■ Aspect Ratio: This number gives the ratio of vertical points to horizontal points to
produce equal-length lines in both directions on the screen.
Display (Video Display Device)
■ The primary CG output device is a video monitor (VDU).
■ Other popular display types:
– Old but still present: CRT (Cathode Ray Tube)
– Plasma display
– Light Emitting Diodes (LED)
– Organic Light-Emitting Diode (OLED)
– 3D display devices (hologram or VR headset)
■ Display methods determine how images are rendered on a screen,
with the two main types being raster scan and random scan (vector
display).
RASTER SCAN DISPLAYS
Raster Scan Display
■ The term "raster display" refers to a method of displaying images.
■ It is used in various types of display technologies, (e.g., CRT, LCD, and
LED)
■ Raster: A rectangular array of points or dots.
■ Screen is a regular grid of samples called pixels (picture element).
■ In raster display, screen is refreshed line by line.
■ Picture definition is stored in a memory area called the refresh buffer
or frame buffer.
Raster Scan Display
■ The electron beam is swept across the
screen, one row at a time from top to
bottom.
■ As the electron beam moves across each
row, the beam intensity is turned on and off
to create a pattern of illuminated spots.
■ Picture definition is stored in memory area
called the Refresh Buffer or Frame Buffer.
■ This memory area holds the set of values for
all the screen points and then retrieved from
the refresh buffer and “painted” on the
screen one row (scan line) at a time.
Raster Scan Display

■ Interlacing: An effective technique for avoiding flickering affect for


small refresh rates .
■ Explanation of Interlacing: On an older, 30 frame per-second,
noninterlaced display, some flicker is noticeable.
■ But with interlacing, each of the two passes can be accomplished in 1/6th
of a second, which brings the refresh rate nearer to 60 frames per
second.
non-interlaced interlaced, cycle 1 interlaced, cycle 2 interlaced, 2 cycles
Raster Image

■ The quality of a raster image is determined by the total number pixels


(resolution), and the amount of information in each pixel (color depth).
■ Raster graphics cannot be scaled to a higher resolution without loss of
apparent quality.
RANDOM SCAN DISPLAYS
Random Scan Displays
Random Scan Displays

■ Random scan display is the use of geometrical primitives such as


points, lines, curves, and polygons, which are all based upon
mathematical equation.
■ Raster Scan is the representation of images as a collection of pixels
(dots)
■ Random scan monitors draw a picture one line at a time (Vector
display or calligraphic display).
■ Refresh rate depends on the number of lines to be displayed.
Random Scan Displays

■ The electron beam is directed only to the part of the screen where the
picture is to be drawn rather than scanning from left to right and top
to bottom as in raster scan.
■ Picture definition is stored as a set of line-drawing commands in an
area of memory referred to as the refresh display file.
■ To display a specified picture, the system cycles through the set of
commands in the display file, drawing each component line in turn.
Random Scan Displays
■ Picture definition is now stored as a line-drawing commands an area
of memory referred to as refresh display file (display list).
■ Random scan displays have higher resolution than raster systems.
■ Random scan displays are designed for line-drawing applications and
cannot display realistic shaded scenes.
Exercise 2:
1. What are the two main types of display methods in computer
graphics?
2. Which display method is better suited for rendering complex images
with shading and colors?
3. In which type of display system would you expect to find a frame
buffer?
4. Which type of display can directly draw lines between any two points
without concerning about pixel resolution.
CATHODE RAY TUBE (CRT)
Cathode Ray Tube (CRT)
Cathode Ray Tube (CRT) related terms
■ A Cathode Ray Tube (CRT) is a vacuum tube once widely used in older computer
monitors and TVs.
■ In computing, it served as the primary display technology before LCDs and LEDs.
■ The CRT beam transfers energy to the phosphor coating on the screen, producing
visible light.
■ CRT displays relied on raster scanning techniques, forming images by rapidly moving
the electron beam across the screen, a process managed by the computer’s
graphics hardware and software.
Cathode Ray Tube (CRT) related terms
● Refresh rate: # of complete images (frames)
drawn on the screen in 1 second. Frames/sec.
● Frame time: the time elapsed between two
consecutive frames, divided by the refresh rate.
sec/frame.
● Intensity Distribution: The intensity is
greatest at the center of the spot and decrease
with Gaussian distribution out to the edges of
the spot.

Intensity Distribution
Cathode Ray Tube (CRT) related terms
● Resolution: a 2D term, maximum number of points that can be
displayed without overlap on a CRT
● Resolution of a CRT is dependent on:

● The type of phosphor


● The intensity to be displayed

● The focusing and deflection systems.

Overlap
Color CRT Monitors
■ A CRT monitor displays color pictures by using a combination of phosphors that emit
different color lights.
■ Methods:
– Beam Penetration: Two layers of phosphor (red and green) are coated onto the
inside of the CRT screen.
FYI ■ Used with random scan monitors
■ Only four colors are possible (red, green, orange, and yellow).
■ Quality of pictures is not as good as with other methods.
– Shadow Mask: Three color phosphor dots (red, green and blue) at each point
on the screen.
■ Used in raster scan system (including color TV)
■ Designed as RGB monitors.
FYI
Flat CRT

■ Electron beams are accelerated parallel to the screen, then deflected 90º to the
screen.
Color Models

■ The RGB Color Model: R, G, and B represent the colors produced by red, green
and blue phosphors, respectively.
Color Models

■ CMY Color Model: CMY (short for Cyan, Magenta, Yellow, and key) is a
subtractive color model.
■ .
Liquid Crystal Display (LCD)
■ Thinner and lighter. No tube or electron beams. requires a backlight to illuminate the
screen.
■ Blocking/unblocking light through polarized crystals. Crystals liquefy when excited
by heat or E field.
Polarizer
■ A matrix of LC cells one for each pixel.
■ No refresh unless the screen changes. Color filtering

■ Color 3 cells per pixel. Liquid Crystal Layer


Polarizer

Light
Plasma Displays
■ Plasma display panels
– Similar in principle to fluorescent light tubes
– Small gas-filled capsules are excited by electric
field, emits UV light
– UV excites phosphor
– Phosphor relaxes, emits some other color
Plasma Displays
■ Plasma Display Panel Pros
– Large viewing angle
– Good for large-format displays
– Fairly bright
■ Cons
– Expensive
– Large pixels (~1 mm versus ~0.2 mm)
– Phosphors gradually deplete
– Less bright than CRTs, using more power
Display Technology: DMD / DLP
■ Digital Micromirror Devices (projectors) or Digital Light Processing
■ Microelectromechanical (MEM) devices, fabricated with VLSI techniques
Display Technologies: LED
■ A Light Emitting Diode (LED) screen is a display technology that
uses LEDs as backlight to illuminate pixels in an LCD (Liquid Crystal
Display) panel
■ A type of LCD screen that uses LEDs as the backlight instead of older
CCFL (Cold Cathode Fluorescent Lamp) backlights.
Display Technologies: Organic LED
Arrays
■ Organic Light-Emitting Diode (OLED) Arrays
– OLEDs function like regular semiconductor LEDs
– But they emit light
■ They are made by putting a very thin layer of special materials that glow
when electricity goes through them, onto the screen in a vacuum.
■ To make different colors, they add some glowy substances to these layers
with fluorescent molecules.
■ Can emit true black color compared to LCD and LED.
Exercise 3:

1. Which type of screen technology utilizes a vacuum tube and electron


beams to create images?
2. In which display technology do the pixels themselves emit light,
eliminating the need for a backlight?
3. Which screen technology is known for its thickness and ability to
produce true blacks by turning off individual pixels?
4. Which technology is characterized by the use of two glass plates and
a liquid crystal material sandwiched in between?
Computer Graphics Software
● Rendering Primitives
– Models are composed of, or can be converted to, a large
number of geometric primitives.
– Typical rendering primitives directly supported in hardware
include:
● Points (single pixels)
● Line segments
● Polygons (perhaps simple, triangle, rectangle)
Algorithms
■ A number of basic algorithms are needed:
– Transformation: Convert representations of models/primitives from one coordinate
system to another
– Clipping/Hidden surface removal: remove primitives and part of primitives that are
not visible on the display
– Rasterization: Convert a projected screen space primitive to a set of pixels.
■ Advanced algorithms:
– Picking: select a 3D object by clicking an input device over a pixel location.
– Shading and illumination: Simulate the interaction of light with a scene.
– Animation: Simulate movement by rendering a sequence of frames.
FYI Application Programming Interfaces
■ X11: 2D rasterization in the context of X11 involves converting vector
graphics (like fonts and GUI elements) into pixels to be displayed on
the screen.
■ Postscript, PDF: Both support 2D transformations, which include
operations like scaling, rotating, and translating objects within a
document. They also involve 2D rasterization, especially when
preparing documents for printing or display on digital screens.
■ Phigs+, GL, OpenGL, Direct3D: Support 3D pipeline by providing a set
of functions for describing and manipulating 3D objects and scenes
FYI Application Programming Interfaces
■ APIs provide access to rendering hardware via conceptual model.
■ APIs abstract the hardware implementations and algorithms in
standard software calls.
■ For 3D interactive applications, we might modify the scene, or a model
directly or just change the attributes like viewing information.
■ We need interface to input devices in an event-driven, asynchronous
and device independent fashion. APIs and toolkits are also defined for
this task. GLUT, Qt, GTK, MFC, DirectX, Motif, Tcl/Tk.
RENDERING,
ANIMATION, MODELING
What is Computer Graphics (CG)?
■ Main tasks of CG:
– Modeling → (shape) creating and
representing the geometry of
objects in the 3D world.
– Rendering → (light, perspective)
generating 2D images of the
objects.
– Animation → (movement)
describing how objects change in
time.
Computer Graphics
■ Rendering:
– Photoreal (indistinguishable from real-life photographs)
– Non-Photorealistic Rendering (NPR): a wide range of expressive
styles for digital art.
■ Animation:
– Physics-Based Animation: simulate realistic movements and
interactions.
– Character Animation: Focuses on bringing characters to life
through movement
Computer Graphics
■ Modeling:
– Computational Geometry: algorithms and their implementations to
manipulate geometrical objects.
– Procedural Modeling: creating models or scenes based on sets of
rules or algorithms rather than manually sculpting or modeling
them.
– Data Acquisition: gathering information about real-world objects to
create digital models.
Photoreal Rendering
◼ Photoreal rendering refers to rendering a 3D scene in a realistic way
◼ Modern photoreal rendering algorithms are essentially a physically
based simulation of light propagation and scattering throughout a 3D
environment
◼ In a sense, this means that there is a ‘correct’ image that should be
generated, given an input data set. This allows the subject of
photoreal rendering to have a strong theoretical basis (namely, the
science of optics)
◼ Most modern photoreal rendering algorithms are based on the
classic ray tracing algorithm, that traces the path of individual light
rays starting from the eye and working backwards to the light sources
Non-Photoreal Rendering
◼ Non-photoreal rendering (NPR) refers to rendering images in
other ways…

◼ Sometimes, this is done to achieve aesthetic goals such as


artificial watercolors, pencil sketches, paint brushstrokes…

◼ Other times, the goal is to maximize the communication of visual


information, as in scientific and medical visualization
NPR
Animation
◼ An animation is just a sequence of individual images
◼ Basically, the subject of computer animation focuses on
how things change over time. Usually, this refers to motion,
but can also refer to other properties changing over time.
◼ Physical simulation is a very powerful tool in computer
animation and can be used to generate believable
animations of objects, gasses, liquids, fracture, particle
effects, and even explosions and fire.
◼ Computer animation also includes a large number of
techniques specifically developed to manipulate virtual
characters
Physics Simulation

A physics simulation starts with a mathematical model whose variables define


the state of the system at a given time. Each variable represents the position or
velocity of some part of the system. The heart of a physics simulation is the set
of differential equations that describe how the variables evolve over time.
Character Animation

Character animation is a
type of animation that uses
movement, speech and tone
to bring a character to life.
Animators can shape
characters to take on a
desired personality,
experience specific
emotions, or embark on a
physical or mental journey.
Modeling
■ Modeling refers to the techniques involved with creating, scanning,
editing, and manipulating 3D geometric data.
■ Modeling is often done by a human user with an interactive editing
program but complex objects, such as trees, can be constructed with
automatic procedural modeling algorithms
■ 3D models are also often acquired from real world objects using laser
scanning or computer vision techniques
Modeling
■ Modeling also includes the use of curved surfaces and other higher
order primitives, which are often converted into triangles using various
tessellation algorithms.
■ Another important area of modeling includes mesh reconstruction for
surface simplification
■ Modeling makes heavy use of computational geometry

tessellation algorithms
Modeling
Before the next lecture:

■ Prepare your CG development environment


■ Install OpenGL and GLUT, freeglut
■ You may use standard C/C++ compilers like gcc/g++ to compile and link your
programs.
■ Revise the basics of C++ (use the following slides)
C++ OVERVIEW
Self-Study
C++ Overview

• C++ is a high-level object-oriented programming language.


• The structure of the C++ language is:

#include <iostream>
// This is a comment line.
int main() {
return 1; // return EXIT_SUCCESS;
}
C++ Overview

■ Every sentence in C++ ends with a semicolon.


■ Every variable in C++ has a name, a type and probably an initial value. For
example: int a = 5 ;
■ Types can be: int, float, double, bool, string, char, struct, class
■ C++ code is case sensitive: INT is different than int, it is not the same as Int.
■ The code is written in a file with .cpp file extension: e.g. [Link]
■ // signify comments and are ignored by the C++ compiler.
C++ Overview

■ C++ operators include: Assignment (=), Addition (+),


subtraction (-), multiplication (*), division (/), modulo (%).
■ Example: a = 5+3;
■ C++ logical operator are operators that return true or false:
comparison (==, >=, <=, >, <, !=, &&, ||, ~).
■ Example:
– 5 == 3 && 5>3 this is false statement.
– 5 == 3 || 5>3 this is a true statement.
C++ Overview

• Example:
int a = 5, b = 3;
int c = a; // c = 5
b = a*c; // b = 25
c = b/2; // c = 12 (trucated)
a = 7; // a = 7
c = a % 2; // c = 1 (remainder 7/2 = 3 ½.

• Be careful of order of operations (priority), use brackets (and) Combined operators: ++a means a=a+1,
--a means a = a-1
a +=b means a=a+b a *=b means a=a*b
a /=3 means a=a/3 a -= 5 means a=a-5
C++ Overview

• Libraries that are mostly used in c++ are:


<iostream>: for input and output
<string>: for string manipulation
<cmath>: for math functions
<fstream>: for input/output files.
• Loops: for, while, do-while
for (int i=1; i<10; i++) {
std::cout << i << std::endl;
}
C++ Overview

• Example on while-loop
i=1;
while (i<10) {
std::cout << i++ << std::endl;
}
• Example on do-while loop:
i=1;
do {
std::cout << i++ << std::endl;
} while (i<10);
C++ Overview

■ Scope of variables means define where a variable is visible in a program.


■ Declare variables as you need them – not at the top of functions of program.
■ Example:
#include <iostream>
int a=2; // variable visible everywhere in the program
int main() {
int b=5; // variable visible only in main.
std::cout << a << "\t" << b << std::endl;
return 0
}
C++ Overview
#include <iostream>
int a=2; // visible everywhere in program
int foo(int s) { // visible only in function foo.
s = a;
return s;
}
int main() {
int b=5; // visible only in main function.
for (int i=0; i<n; i++) { // visible only in the for loop
int c = i+a; // visible only in the for loop
std::cout << c << std::endl;
}
a = c; // error -- c is not visible outside for loop
s=b; // error – s is not visible outside function foo.
return 0;
C++ Introduction

Additional resources:
■ [Link]/doc/tutorial
■ [Link]
■ [Link]
Computer Graphics
501472-3
Lecture 2- OpenGL Introduction
What is OpenGL
• OpenGL is a computer graphics rendering API
• With it, you can generate high-quality color images by rendering with
geometric primitives.
• Objects in OpenGL are built by assembly vertices into primitives. Example:
A triangle is a primitive with 3 vertices.
What is OpenGL
• By using OpenGL, the graphics part of your application can be
• operating system independent
• Window system independent

The interface consists of about 120 distinct commands, which we use to


specify the objects and operations needed to produce interactive 3D
applications.
Learning OpenGL with GLUT
• GLUT (OpenGL Utility Toolkit) is a Window Manager (handles window
creation, user interaction, callbacks, etc)
• Makes it easy to learn and write OpenGL programs without being
distracted by your environment
• Not “final” code (Not meant for commercial products)
• Go to [Link] download files
• Follow the Setup instruction to configure proper path
OpenGL Library
• OpenGL library has functions with the following form:
• Start with gl or glu or glut.
• Each word after that starts with a capital letter
• Examples:
• glBegin, glEnd, glLoadIdentity,
• glutInit, glutCreateWindow
• gluMailLoop, gluDisplayFunc
• OpenGL constants:
• All constants are all in capital letters
• All constants begin with GL_
• Underscore is used as a separator between words in a constant
• Examples: GL_2D, GL_RGB, GL_POLYGON
Callback Functions
• A callback function is a function that runs when a specific event happens, such as
a window resize, screen redraw, or user input
• Callback functions are used to handle events automatically.
• You just need to set up the callbacks in your program.
……
glutDisplayFunc ( display ); // display callback
glutReshapeFunc ( resize ); // window resize callback
glutKeyboardFunc ( key ); // keyboard (Key Pressed) callback
……
• How It Works?
• You define the function (e.g., display()), then link it to an event using GLUT
functions (e.g., glutDisplayFunc(display); ).
Setting up a Window to Draw in OpenGL
• OpenGL is not object oriented so that there are multiple functions for a
given logical function
• After including OpenGL header
#include <GL/gl.h> // required
#include <GL/glu.h>
#include <GL/glut.h>
• We should define a function that is going to draw the objects on the
screen. Let us call this function "draw"; you can name it whatever you
want.
void draw() {
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
Setting up a Window to Draw in OpenGL
Currently there is no drawing in "draw" function. The Two lines in the "draw"
function are:
• glClear(GL_COLOR_BUFFER_BIT)used to clean the window from any old
drawing done before.
• GL_COLOR_BUFFER_BIT is where the color information of each pixel in the
framebuffer is stored.
• glFlush()used to send the content of the drawing to the display monitor, so
you can see the drawing results.
Setting up a Window to Draw in OpenGL
• After that, we need to define a function responsible of defining the window background
and coordinates that we are going to draw in.
void init() {
glClearColor(1,1,1,0); // Sets background color to white
gluOrtho2D(-20, 20,-20, 20); // Defines a 2D coordinate system
}
• The glClearColor(red, green, blue, transparent) sets the background color of the window.
• The RGB values (1,1,1) means that red, green, and blue are all at their maximum
intensity, which combines to form white.
• The last zero means the transparent value (0 → Fully transparent (invisible).1 → Fully
opaque (solid).)
Setting up a Window to
Draw in OpenGL

• Window coordinate is defined by the user using the


function "gluOrtho2D" which accepts 4-parameters:
(xmin, xmax, ymin, ymax).
• Therefore, writing the function:
gluOrtho2D(-20, 20,-20, 20);
Setting up a Window to Draw in OpenGL
• When we define a pixel we define the x-coordinate first then the y-
coordinate as we use in mathematics. For example, the pixel (10,
7) is shown below:
Setting up a Window to Draw in OpenGL
• Next, is the "main" function, which should include some OpenGL setup and
defining the window position on the screen and the size of the window. In
addition, we need to tell OpenGL that the drawing function is called "draw".

• First let us define the header of the function "main":


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

• The first sentence in the "main" function is setting up the OpenGL library:
(&argc, argv);
Setting up a Window to Draw in OpenGL
• Then we should initialize the display frame buffer, we are going to use a single
buffer (other option is double buffer for animation) and a colored RGB monitor.
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
• After that, we define the window size in pixels:
glutInitWindowSize(600, 600); //physical window size in pixels

• Next, we define the window position in pixels on the monitor:


glutInitWindowPosition(100, 100);
• Then, we will create the window and set its title:
glutCreateWindow("Opengl Test")
Setting up a Window to Draw in OpenGL
• The display coordinate is from (0,0) to (screen_width,
screen_height).
• The (0, 0) is at the left-top corner of the display and the
(screen_width, screen_height) is at the right bottom of the display.
Setting up a Window to Draw in OpenGL
• After that, we need to tell OpenGL that the drawing function is named "draw".
• The function "draw" is called a callback function because it is not called from
our program, but it is going to be called from the OpenGL library programs.
glutDisplayFunc(draw);
• Next, a call to the "init" function defined previously to set the background color
and coordinate of the window.
init();
• Finally, we enter a loop, so that OpenGL can look at the events occurring
during the program execution (more on this later).
glutMainLoop();
#include <GL\glut.h>
void draw() {
glClear(GL_COLOR_BUFFER_BIT);
glFlush(); }

void init() {
glClearColor(1,1,1,0);
gluOrtho2D(-20,20, -20,20); }

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


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(600, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow("OpenDL Testing");
glutDisplayFunc(draw);
init();
glutMainLoop();
return 0;}
Drawing in
OpenGL
• In OpenGL, an object is made
up of geometric primitives
such as triangle, quad, line
segment and point.
• A primitive is made up of one
or more vertices.
• OpenGL supports the
following primitives:

Source: [Link]
Drawing in OpenGL
• There are several methods to draw in OpenGL.
• The simplest method to draw primitives is to use the OpenGL begin and
end calls.
• Attributes (e.g., GL_POINT) are set within a glBegin/glEnd block.
• Each vertex is defined using glVertex, along with its attributes.
• A vertex is a location in the form (x, y) for 2D or (x, y, z) for 3D.
• Using glBegin/glEnd, we can draw points (or pixels), lines, triangles, or
polygons.
OpenGL Command Notation
glVertexDTv( ... )

Number of Data Type Vector


dimentions b - byte the function expects
ub - unsigned byte its arguments to be
2 - (x,y) s - short
3 - (x,y,z) passed as an array
us - unsigned short
4 - (x,y,z,w) i - int omit “v” for scalar form
ui - unsigned int glVertex2f( x, y )
f - float
d - double
OpenGL glVertexDTv
• glVertexDTv:
• D : 2 or 3 dimension.
• T : type: integer (i), short (s), float (f), double (d)
• v : optional for vector points.
• Examples:
• glVertex2i(5,5): 2D-point, integer coordinates (5,5)
• glVertex2f(5.5, 6.3): 2D-point, float coordinates (5.5, 6.3).
• glVertex3i(5,2,6): 3D-point, integer coordinates (5,2,6).
• glVertex2iv(a): 2D-point, integer coordinates in vector formats.
glVertex2iv
• Assume we want to draw a triangle that consists of 3-vertices: (0,0), (1, 1), (0,
2). We can store the three points in an array and call the glVertex2iv, as follows:

Point a[3]; Another implementation:


a[0] = Point(0, 0); glBegin(GL_LINE_LOOP);
a[1] = Point(1, 1); glVertex2i(0, 0);
a[2] = Point(2, 2); glVertex2i(1, 1);
glBegin(GL_LINE_LOOP); glVertex2i(0, 2);
glVertex2iv(a);
glEnd();
glEnd();
The result is the same triangle.
Specifying colors
To draw any of the primitive geometries, we need to set the color:
1. glColor3f(red, green, blue)
• This function takes three GLfloat arguments assigned to the basic colors: red, green and
blue respectively.
• The range of values for each basic color is between 0 and 1.
• For example: glColor3f(1.0, 0.0, 0.0)
2. glColor3ub(red, green, blue)
• This function takes three GLubyte arguments for the red, green, and blue colors.
• The values are ranging from 0 to 255.
• For example: glColor3ub(20, 150, 170).
Specifying colors
• The set of colors and their values are shown in:
Specifying colors
• The glColor3ub(255,0,0) is similar to
glColor3f(1.0,0.0,0.0), this is color red.
• glColor3ub(0,255,0) is similar to glColor3f(0.0,1.0,0.0),
this is the color green.
• The function glColor3ub or glColor3f is called before start drawing
the object. It is used to draw and fill the object with the specified
color.
• It will take effect until another call of glColor3ub or glColor3f that
changes the drawing or filling color.
Geometric Primitives
• In OpenGL, Geometric primitives are: pixels, lines, triangles, quads and
polygons.
• Pixels are one point, lines are two points, triangles consists of three
points, quads consists of four points and finally polygons are closed
object of any number of points.
• Set the color of drawing or filling using either glColor3f or glColor3ub
before drawing.
• Points and line do not have fill color, they have only drawing colors.
• Triangles, quads, and polygons have drawing and filling colors by default.
Draw a Point or Pixel
• We use the following code to draw a pixel in red color:

glColor3ub(255, 0, 0);
glBegin(GL_POINTS);
glVertex2i(2, 2);
glVertex2i(5, 5);
glVertex2i(6, 6);
glEnd();

• The above code will draw three pixels at locations (2,2), (5,5) and (6,6) in red color.
You can use glPointSize(5.0) to increase the size of the pixel.
Draw a Point or Pixel
// The full body of the draw function
void display() {
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer
glPointSize(5.0); // Set the point size to 5 pixels
// Draw three points in red color
glColor3ub(255, 0, 0); // Set the color to red
glBegin(GL_POINTS);

glVertex2i(2, 2);
glVertex2i(5, 5);
glVertex2i(6, 6);
glEnd

glFlush(); // Ensure all OpenGL commands are executed


}
Draw a line
• There are three types of lines in OpenGL: normal lines, line strips and line loop.
• Normal line is used to draw disconnected lines
• Strip lines are used to draw lines in a special order.
• Line loop are used to draw a closed object using lines.
Normal Lines
• Lines require two points to draw them.
• Every 2-points in the list of points are grouped.
• If the last points left from the list of points are less than two then it will be
discarded.
• Every group is drawn separately. Every group will construct a line.
glBegin(GL_LINES);
glVertex2i(…);

glEnd();
Normal Lines Example
glColor3ub(255, 0, 0);
glBegin(GL_LINES);
glVertex2i(0, -20);
glVertex2i(0, 20);
glVertex2i(-20, 0);
glVertex2i( 20, 0);
glVertex2i(0, 0);
glEnd();
• We assume the coordinate of the screen is (20, -20) for the x-axis and (20,-20)
for the y-axis.
• You can use glLineWidth(3.0) to increase the width of the line.
Normal Lines Example
• We will write a function that draws axes and their markings.
void draw_axis() {
glLineWidth(3.0);
glColor3f(0, 0, 0); //Set color black
glBegin(GL_LINES);
glVertex2i(-20, 0); glVertex2i(20, 0);//Horizontal
glVertex2i(0,-20); glVertex2i(0, 20); //Vertical
// Draw small lines for the axes
for (int i=-20; i<=20; i++) {
glVertex2i(i, -0.2); glVeretex2i(i, 0.2);
glVertex2i(-0.2, i); glVeretex2i(0.2, i);}
glEnd();
}
Line Attributes
• Color, thickness, stippling.
• glColor3f(); // sets color.
• glLineWidth(4.0); // sets thickness. The default thickness is 1.0.
• glEnable(GL_LINE_STIPPLE); // enable stippled lines
glLineStipple(1, 0x00FF); // 1-> pattern repeat, 0x00FF -> Dashed

a) thin lines b) thick lines c) stippled lines


Line Strip
• The first 2-points from the list of points will construct a line.
• The last point from the last line with the point from the list of points will form a
line.

glBegin(GL_LINE_STRIP);
glVertex*(…);

glEnd();
Lines Strip Example
glBegin(GL_LINES_STRIP);
glVertex2i( 0,-20);
glVertex2i( 0, 20);
glVertex2i(-20, 0);
glVertex2i( 20, 0);
glVertex2i( 0, 20);
glEnd();
Line Loop
• The first 2-points from the list of points will construct a line.
• The last point from the last line with the point from the list of points
will form a line.
• The last point from the list of points with the first point from the list
of points will form a line.
glBegin(GL_LINE_LOOP);
glVertex*(…);

glEnd();
Lines Loop Example
glBegin(GL_LINES_LOOP);
glVertex2i( 0,-20);
glVertex2i( 0, 20);
glVertex2i(-20, 0);
glVertex2i( 20, 0);
glEnd();
• Compare the above code with the one in the line strip. You can see
the last glVertex is removed from the line loop code.
glBegin(GL_LINE_ST
RIP);
glVertix2iv(p1);
glVertix2iv(p2);
glVertix2iv(p3);
glVertix2iv(p4);
glVertix2iv(p5);
glEnd();

glBegin(GL_LINES);
glVertix2iv(p1);
glVertix2iv(p2);
glBegin(GL_LINE_LO glVertix2iv(p3);
OP); glVertix2iv(p4);
glVertix2iv(p1); glVertix2iv(p5);
glVertix2iv(p2);
glVertix2iv(p3); glEnd();
glVertix2iv(p4);
glVertix2iv(p5);
glEnd();
Understanding Check 1
• How many vertices should we determine to draw
this shape using GL_LINES?
• How many vertices should we determine to draw
this shape using GL_LINE_STRIP?
• Write the code that draws this shape using
GL_LINE_STRIP
Draw Triangles
• There are three ways to draw triangles: normal triangles ,triangle
strip, triangle fan.
• A triangle has 3-vertices (corners).
• Set the color3ub or color3f before drawing the triangle.
• The triangles drawn are filled by default with the drawing color.
Draw Triangles
• Triangles are drawn filled by default. However, one can choose to use
glPolygonMode(face, fill_mode); where:
• face can be either GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK. It
indicates the drawing of the polygon is front faced or back faced. This used
in 3D drawing.
• fill_mode can be either GL_FILL, GL_LINE, GL_POINT. It indicate the filling
color of a triangle.
• GL_FILL is the default which fill the polygon with solid color.
• GL_LINE is drawing the polygon with border lines (outline or wireframe).
• GL_POINT is drawing the triangle with points.
• Remember a triangle is a polygon.
Normal Triangles
• Every 3-points from the list of points are grouped.
• Last points that are less than 3-points from the list of points are
discarded.
• Every group is drawn separately.
• Every group will construct a color filled triangle. Use glColor3f or
glColor3ub to fill the triangle color.

glBegin (GL_TRIANGLES);
glVertex*(…);
...
glEnd();
Normal Triangles
glColor3f(0, 1, 0);
glBegin(GL_TRIANGLES);
glVertex2i(0, 0);
glVertex2i(10, 10);
glVertex2i(19, 0);
glVertex2i(4, 4);
glEnd();

• Note, the drawing is using the default GL_FILL.


Normal Triangles
glColor3f(0, 1, 0);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glLineWidth(4.0);
glBegin(GL_TRIANGLES);
glVertex2i(0, 0);
glVertex2i(10, 10);
glVertex2i(19, 0);
glVertex2i(4, 4);
glEnd();
• Using the glLineWidth(4.0) to increase the line thickness.
• Using glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); to color the drawing line
Normal Triangles
glColor3f(0, 1, 0);
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
glPointSize(15.0);
glBegin(GL_TRIANGLES);
glVertex2i(0, 0);
glVertex2i(10, 10);
glVertex2i(19, 0);
glVertex2i(4, 4);
glEnd();
• Using the glPointSize(15.0) to increase the size of pixels.
• Using glPolygonMode(GL_FRONT_AND_BACK, GL_ POINT); to color the points
Strip Triangles
• The first 3-points from the list of points will construct a triangle.
• The last two points from the last triangle with the next point in the
list of points will construct a triangle.
• Use glColor3f of glColor3ub to fill the triangle with a specified color.

glBegin (GL_TRIANGLE_STRIP);
glVertex*(…);
...
glEnd();
Strip Triangles

glColor3f(0, 1, 0);
glBegin(GL_TRIANGLE_STRIP);
glVertex2i(-10, 0);
glVertex2i(0, 10);
glVertex2i(10, 0);
glColor3f(0, 0, 1); // shading
glVertex2i(15, 10);
glEnd();
To avoid shading, we need to draw two triangles within separate glBegin/glEnd blocks.
Strip Triangles
glColor3f(0, 0, 0);
glBegin(GL_LINES);
glVertex2i(-20, 0); glVertex2i(20, 0);
glVertex2i(0,-20); glVertex2i(0, 20);
glEnd();
glColor3f(0, 0, 1);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_TRIANGLE_STRIP);
glVertex2i(-3,0); glVertex2i(-5,-10);
glVertex2i(-3,-8); glVertex2i(5,-10);
glVertex2i(3,-8); glVertex2i(5,2);
glVertex2i(3,0); glVertex2i(-5,2);
glVertex2i(-3,0); glVertex2i(-5,10);
glEnd();
Triangle Fans
The first three points create the first triangle.
Each new point forms a triangle with the previous point and the
first point.
• Use glColor3f or glColor3ub to fill the triangle with a specified color.
Triangle Fans
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColor3f(0, 0, 1);
glBegin(GL_TRIANGLE_FAN);
glVertex2i(0, 0);
glVertex2i(10, 0);
glVertex2i(7, 7);
(-7,7) (7,7)

glVertex2i(-7, 7); 2
glVertex2i(-10, 0); (-10,0)
3 1
(10,0)

glVertex2i(-7, -7); 4 (0,0)


6
5
glVertex2i(7, -7); (-7,-7) (7,-7)

glVertex2i(10, 0);
glEnd();
Quads
• There are two ways to draw quads: normal quads and quad strips. A
quad has four vertices (corners).
• Set the color using glColor3ub or glColor3f before drawing the quad.
Quads are filled by default with the assigned drawing color.
Normal Quads
• Every 4 points from the list of points are grouped.
• Any remaining points less than 4 are discarded.
• Each group is drawn separately.
• Each group forms a filled quad using the assigned color.
• Use glColor3f or glColor3ub to set the quad color.

glBegin(GL_QUADS);
glVertex*(...);
...
glEnd();
Quad Example
glColor3ub(255, 0, 0);
glBegin(GL_QUADS);
glVertex2i(0, 0);
(0,6) (6,6)
glVertex2i(6, 0);
glVertex2i(6, 6); (0,0) (6,0)

glVertex2i(0, 6);
glVertex2i(-6, 0);
glVertex2i(-6, -6);
glEnd();

• We can use the same glPolygonMode(face, fill_color) as we did in the triangle,


where fill_color is either GL_FILL (default), GL_LINE, or GL_POINT as explained
before.
Drawing a Rectangle
Drawing Aligned Rectangles
• Later rectangles are drawn on top of previous ones
Understanding Check 2
• Draw the previous red rectangle using glRectf function.

10,10

0,0
Polygon
• A polygon is any shape with more than 2-sides (i.e. 3-points).
• Same as Line Loop but filled with color.
• However, when drawing a polygon, one must be careful in ensuring
that it is a plane convex figure, i.e., it lies on one plane and has no
'bays' or 'inlets’.
Polygon
A polygon is called convex if the line joining any two interior points of
the polygon lies completely inside the polygon. A non-convex polygon
is said to be concave.

Every polygon is either convex or


concave. The difference between convex
and concave (non-convex) polygons lies
in the measures of their angles. For a
polygon to be convex, all of its interior
angles must be less than 180 degrees.
Otherwise, the polygon is concave.
Understanding Check 3
• Which of the following is convex?
Polygon

Polygon is filled with the current drawing color


Polygon
• glPolygon and glRectf are not recommended to use, because we
can get the same result using triangle strip. The triangle strip is more
efficient and does not require the object to be in plane convex form.
Therefore, any closed object with vertices can be divided
into triangles and drawn using triangle strip.
• However, it is not easy to draw objects on a triangle strip and
requires some experience.
Understanding Check 4
• What is the best method for drawing this
star? Lines, triangles, quads,… etc.
• Would you change your answer if you
want to fill the star with a solid colour?
• If you were asked to draw it using
triangles, which method will you be
using: normal triangles ,triangle strip,
triangle fan?
Understanding Check 5 (10,10)

(7,7)

• Draw the following shape.


(3,3)
• Four groups:
• Group1, draw it using Lines (No filling) (0,0)

• Group2, draw it using Quads (Filling)


• Group3: draw it using glRectf (Filling).
• Group4: draw it using Polygon (Filling).
Simple User Interaction with Mouse and Keyboard

• In OpenGL using GLUT, we can capture user input from the mouse and
keyboard by registering callback functions.
• Register functions:
glutMouseFunc (myMouse); // the mouse callback function
glutKeyboardFunc (myKeyboard); // the keyboard callback function
• Write the function(s)
• NOTE that any drawing you do when you use these functions must be done
IN the mouse or keyboard function (or in a function called from within
mouse or keyboard callback functions).
Example Mouse Function
void myMouse(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
cout << "Left Mouse Button Pressed";
}
• Button: Identifies which button was clicked GLUT_LEFT_BUTTON,
GLUT_MIDDLE_BUTTON, or GLUT_RIGHT_BUTTON.
• State: Tells if the button was pressed (GLUT_DOWN) or released
(GLUT_UP).
• x, y: Mouse cursor position (in pixels) at the time of the event
Example Mouse Function (2)

• The x value is the number of pixels from the left of the window.
• The y value is the number of pixels down from the top of the window.
• In order to see the effects of some activity of the mouse or keyboard,
the mouse or keyboard handler must call either myDisplay() or
glutPostRedisplay().
• Code for an example myMouse() is in the next slide
Code for Mouse-controlled Polyline (LINE_STRIP)
void myMouse(int button, int state, int x, int y){
#define NUM 20 // maximum of 20 points
static GLintPoint List[NUM]; // Stores the points
static int last = -1; // last point used so far
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && last < (NUM -1)){
List[++last].x = x; // add new point to list
List[ last].y = screenHeight - y; // GLUT (top-left)
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_LINE_STRIP); // redraw the polyline
for(int i = 0; i <= last; i++)
glVertex2i(List[i].x, List[i].y);
glEnd(); visualization of the polyline based on
sequential mouse clicks. Each blue dot
glFlush();} represents a mouse click, and
else if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) the lines connect these points to form
the polyline.
last = -1; // reset the list to empty
}
Example of the click events

• The function is called once per Action


Points Stored in
What is Drawn?
List[]
mouse button click.
Left Click #1 at
• The number of times it runs (50, 200)
(50,200) Single point

depends on how often the user A line


clicks. Left Click #2 at (50,200) → connecting
(100, 250) (100,250) (50,200) to
• It is limited to 20 left clicks before (100,250)
requiring a reset via right-click. Left Click #3 at
(50,200) → A polyline
(100,250) → connecting all
• Every time the user left-clicks, the (150, 150)
(150,150) three points
entire polyline redraws from the Right Click Reset last = -1 Screen clears
first point up to the latest point Left Click #4 at Starts fresh with
(80,300)
(80, 300) one point
Using Mouse Motion Functions

• GLUT provides two types of mouse motion functions to track mouse


movement in an OpenGL window.
• glutMotionFunc(myMovedMouse); // moved with button held down (Dragging)
• glutPassiveMotionFunc(myMovedMouse); // moved with buttons up

• myMovedMouse(int x, int y); // Callback function


• x and y are the current mouse position (in pixels) when the event occurred.
• Origin (0,0) is at the top-left in GLUT
Understanding Check 6
Write a code snippet to define a mouse callback function named handleMouse. The function should draw a
point where the user clicked (hint: Store x, y position and draw a point.
Example Keyboard Function
// receives the ASCII value of the key pressed and the mouse posttion (x,y)
void myKeyboard(unsigned char theKey, int mouseX, int mouseY){
GLint x = mouseX;
GLint y = screenHeight - mouseY; // Correct y value (GLUT to OpenGL
switch(theKey){
case 'p': drawDot(x, y); break; // Draw dot at mouse position ( drawDot is user defined)
case 'E': exit(0); //terminate the program
default: break; // do nothing
}
}
Example Keyboard Function (2)

• Parameters to the function will always be (unsigned char key, int


mouseX, int mouseY).
• The y coordinate needs to be flipped by subtracting it from
screenHeight.
• Body is a switch with cases to handle active keys (key value is ASCII
code).
• Remember to end each case with a break!
Understanding Check 7
Write a code snippet to define a mouse callback function named handleMouse. The function should draw a
point where the user clicked (hint: Store x, y position and draw a point.
Using Menus

• Both GLUT and GLUI make menus available.


• GLUT menus are simple, and GLUI menus are more powerful.
• We will build a single menu that will allow the user to change the
color of a triangle, which is undulating back and forth as the
application proceeds.
• GLUT allows creating right-click menus in OpenGL applications.
• Menus can contain options (entries) and submenus (nested options).
• They are useful for UI interaction without needing GUI libraries.
GLUT Menu Callback Function

• int glutCreateMenu(myMenu);
//Creates a menu and returns a menu ID
• void myMenu(int num);
// Call back, num is which menu item was selected
• void glutAddMenuEntry(char* name, int value);
// Adds an option (item) to the menu with a name and a
value.
• void glutAttachMenu(int button);
// Attach menu to one of (GLUT_RIGHT_BUTTON,
GLUT_MIDDLE_BUTTON, or GLUT_LEFT_BUTTON)
GLUT Menu-Example

void myMenu(int num) { // Menu function to handle user choices


switch(num) {
case 1: cout << "Option 1 selected\n"; break;
case 2: cout << "Option 2 selected\n"; break;}
}
void createMenu() { // Function to create and attach the menu
int menuID = glutCreateMenu(myMenu); // Create menu
glutAddMenuEntry("Option 1", 1); // Add menu items
glutAddMenuEntry("Option 2", 2);
glutAttachMenu(GLUT_RIGHT_BUTTON); // Attach to right-click
}
GLUT subMenus

• A submenu groups related options under a main menu category.


• It is created separately and then linked to the main menu.
• glutAddSubMenu (char* name, int menuID);
• glutAddSubMenu("Submenu Name", submenuID);
• "Submenu Name" → What appears in the main menu.
• submenuID → The ID of the submenu created
GLUT Menu-Example Main Menu (Right Click)
├── Messages → [abc, ABC]
├── Colors → [Green, Red, White]
└── Exit (Closes the program)
// Create Submenus
int submenu1 = glutCreateMenu(myMenu); // Create message sub menu
glutAddMenuEntry("abc", 1); glutAddMenuEntry("ABC", 2);
int submenu2 = glutCreateMenu(selectColor); // Create color submenu
glutAddMenuEntry("Green", 1); glutAddMenuEntry("Red", 2); glutAddMenuEntry("White", 3);
glutCreateMenu(myMenu); // Create Main Menu
glutAddSubMenu("Messages", submenu1); glutAddSubMenu("Colors", submenu2);
glutAddMenuEntry("Exit", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON); // Attach Menu to Right Mouse Click
}
COMPUTER GRAPHICS
501472-3
Lecture 3- Line Drawing
Next week group
Assignment :
Write the code that creates
the menu on the left
■ Write OpenGL program that draws a triangle and
allows the user to change its color using a right-click
menu. The menu provides options to select different
colors (Red, Green, Blue, and Orange).
Drawing a line:

■ Digital Differential Analyzer (DDA) Algorithm


■ Bresenham Algorithm
Line Equation

■ The equation of a straight line is


– y = mx + b
– m is the slope or gradient
– b is the y-intercept (y value when x=0)

y=2x+3
•Slope m=2 → The line rises by 2 for every 1 step right.
•Y-intercept b=3 → The line crosses the y-axis at (0,3).
Line Equation

■ Slope (m):

y
y2

y1

b x1 x2 x

6
Example
x y
0 2(0)+1 = 1

1 2(1)+1 = 3

2 2(2)+1 = 5

3 2(3)+1 = 7

4 2(4)+1 = 9
DDA ALGORITHM
DDA

❖ DDA stands for Digital Differential Analyzer.


❖ It is an incremental method of scan conversion of line.
❖ In this method calculation is performed at each step but by using results of previous
steps.

Mar-26 9
DDA

❖ Input: (x1,y1) and (x2,y2).


❖ Calculate the slope of the line.
❖ Set the initial point of the line as (x1,y1).
❖ Loop through the x-coordinates of the line, incrementing by one each time, and
calculate the corresponding y-coordinate using the equation y = y1 + m(x – x1).
❖ Plot the pixel at the calculated (x,y) coordinate.
❖ Repeat until the endpoint (x2,y2) is reached.

Mar-26 10
DDA Algorithm for Drawing a Line

■ If m =1: y m=1
y2-y1 = x2-x1 y2
y2-y1
y2-y1 m= x2-x1
y1

45
x1 x2 x

x2-x1
DDA Algorithm for Drawing a Line
y m=1
• If |m|<1 (Left-to-right)
y2-y1
• ∆x = 1 m= x2-x1
• 𝑦𝑘+1 = 𝑦𝑘 + 𝑚; y2
y2-y1 y1
• For (k=0; k< 𝑥2 − 𝑥1 ; k++) {
𝑥𝑘+1 = 𝑥𝑘 + 1; x1 x2 x
𝑦𝑘+1 = 𝑦𝑘 + 𝑚;
x2-x1
plot(𝑥𝑘+1 , 𝑦𝑘+1 );
}
DDA Algorithm for Drawing a Line
FYI
y m=1
• if |m|<1 (right-to-left)
y2-y1
• ∆x = -1 m= x2-x1
• 𝑦𝑘+1 = 𝑦𝑘 − 𝑚; y2
y2-y1 y1
• For (k=0; k< 𝑥2 − 𝑥1 ; k++) {
𝑥𝑘+1 = 𝑥𝑘 − 1; x1 x2 x
𝑦𝑘+1 = 𝑦𝑘 − 𝑚;
x2-x1
plot(𝑥𝑘+1 , 𝑦𝑘+1 );
}
DDA Algorithm for Drawing a Line
y2-y1
y m= m=1
x2-x1
■ |m|>1 (left to right)
– ∆y=1 y2
1
– 𝑥𝑘+1 = 𝑥𝑘 + ; y2-y1
𝑚
y1

◦ For (k=0; k< 𝑥2 − 𝑥1 ; k++) { x1 x2 x


y𝑘+1 = 𝑦𝑘 + 1;
x2-x1
𝑥𝑘+1 = 𝑥𝑘 + 1/𝑚;
plot(𝑥𝑘+1 , 𝑦𝑘+1 );
}
DDA Algorithm for Drawing a Line
FYI y2-y1
y m= m=1
x2-x1
■ |m|>1 (right to left)
– ∆y=-1 y2
– 𝑥𝑘+1 = 𝑥𝑘 − 1/𝑚; y2-y1
y1

◦ For (k=0; k< 𝑥2 − 𝑥1 ; k++) { x1 x2 x


y𝑘+1 = 𝑦𝑘 − 1;
𝑥𝑘+1 = 𝑥𝑘 − 1/𝑚; x2-x1

plot(𝑥𝑘+1 , 𝑦𝑘+1 );
}
DDA Algorithm for Drawinga Line

|m|<1 |m|>1

Left to right xk+1 = xk + 1 yk+1 = yk + 1


yk+1 = yk + m xk+1 = xk + 1/m

Right to left xk+1 = xk - 1 yk+1 = yk - 1


yk+1 = yk – m xk+1 = xk - 1/m

Mar-26 16
Example 1

Draw a line from (2,1) to (8,5) using DDA:


■ X1 = 2, x2=8, y1=1, and y2=5
■ Calculating the slope:
■ m=(5-1)/(8-2) = 2/3 = 0.6667
■ m<1 → we need to increment x value by 1. and add the slope to y to get the
corresponding y value.

Mar-26 17
Example 1

𝑥1 = 2, 𝑦 =1,
m = 0.6667
𝑥𝑘+1 = 𝑥𝑘 + 1;
𝑦𝑘+1 = 𝑦𝑘 + 𝑚;

Mar-26 18
Example 2

Draw a line from (3,2) to (7,8) using DDA:


■ X1 = 3, x2=7, y1=2, and y2=8
■ Calculating the slope: m=(8-2)/(7-3) = 3/2 = 1.5
■ |m| >1
y𝑘+1 = 𝑦𝑘 + 1;
𝑥𝑘+1 = 𝑥𝑘 + 1/𝑚;
Example 3

Draw a line from (20, 10) to (30, 18) using DDA:


Advantages and Disadvantages of DDA

Advantages: Disadvantages:
• Faster than direct use of line • Less suited for hardware
equation. implementation due to multiplication
and division operation.
• Does not use multiplication
theorem. • Involvement of round-off functionality
(consumes a lot of time) and
• Simple and easier to calculate since accumulations of rounding off values
each step has only two additions. cause accumulation error.
• Slower than Bresenham’s algorithm
because it uses real arithmetic
(Floating Point operation)
BRESENHAM’S
ALGORITHM
Bresenham’s Line Algorithm

■ In Bresenham’s algorithm, we move


across the x-axis in unit intervals.
■ The idea of Bresenham’s algorithm is to
avoid floating point multiplication and
addition to compute mx + c, and then
compute the round value of (mx + c) in
every step.
Bresenham’s Line Algorithm
Input endpoints: (x0 , y0 ) – (xn , yn )
|m| >1
Calculate: ∆x, ∆y, 2∆y, 2∆y-2∆x Yk+1 Yk+1
d2
1. p0 = 2∆x- ∆y y
2. Plot(x0 , y0 ) d1
yk yk
3. For k=0 to n:
If pk ≥ 0:
plot (xk + 1, yk + 1) xk Xk+1 xk Xk+1
pk+1 = pk + 2∆x−2∆y
Else if pk < 0:
plot (xk , yk + 1)
pk+1 = pk + 2∆x
Example
Draw the line with endpoints (20,10), (30,18).
Advantages and Disadvantages of Bresenham

Advantages Disadvantage:
■ Faster than DDA because it does not ■ This algorithm is meant for basic line
involve floating point calculations like drawing only Initializing is not a part
DDA Algorithm of Bresenham's line algorithm. So, to
draw smooth lines, you should want
■ Involves only integer arithmetic.
to look into a different algorithm.
■ It can be implemented using
hardware because it does not use
multiplication and division.
COMPUTER GRAPHICS
501472-3
Lecture 4- Circle and midpoint circle algorithms
Cartesian Coordinates

• Circle properties:
• Center (xc , yc)
• Radius r
• Equation of circle:
• Cartesian Coordinates: A point in this system is represented by a
pair of numerical coordinates, (x,y)
• r = (x − x )2 + ( y − y )2
c c
Cartesian Coordinates

• We can use r to find the other points:

• Time consuming computation:


• Float numbers
• Require square root and multiplication calculation.

Computer Graphics 3
Polar coordinates
◦ Polar coordinates: A point is represented by (r,θ), where r is the distance from
the origin (radius), and θ is the angle from the reference direction to the line
connecting the origin to the point.
◦ [Link]
◦ r = xc .cos
◦ x = xc + [Link]
◦ y = yc + [Link] 
◦  =  r
• Time consuming computation.
• Float numbers
• Require trigonometric and multiplication calculation.
Circles Symmetry

• Quadrant circle symmetry: A circle divided into four equal parts by its horizontal and
vertical diameters exhibits quadrant symmetry.

(-x,y) (x,y)

(-x,-y) (x,-y)
Circles Symmetry

• Octant circle symmetry: Further


dividing each quadrant of a circle by
the lines gives us eight equal sections,
each called an octant.
• This division results in finer symmetry,
with the circle now exhibiting octant
symmetry.
• We can draw an octant of a circle
from the previous equations then
we find the symmetrical points.
Drawing Circles – Midpointcircle Algorithm

• We are going to assume that the center of the circle is (0,0).


• This is not a restriction because for any point (x,y) calculated on the
boundary of the circle, we can shift the point by:
• x = x + xc
• y = y + yc
• (xc, yc) is the original center of the circle.

Computer Graphics 7
Midpoint Drawing Circles Algorithm

• Given the center point and radius of circle, Mid Point Circle Drawing Algorithm
attempts to generate the points of one octant.
• The points for other octants are generated using the octant symmetry property.
Procedure-

Given:
•Centre point of Circle = (X0, Y0)
•Radius of Circle = R

The points generation using Mid Point Circle Drawing Algorithm involves the following steps-

Step-01:

Assign the starting point coordinates (X0, Y0) as-


•X0 = 0
•Y0 = R

Step-02:

Calculate the value of initial decision parameter P0 as P0 = 1 – R

Computer Graphics 9
Step-03:

• Suppose the current point is (Xk, Yk) and the next point is (Xk+1, Yk+1).
• Find the next point of the first octant depending on the value of decision parameter P k.
Follow the below two cases:

xk+1 = xk+1
pk <0 yk+1 = yk
pk+1 = pk + 2xk+1+1

Two cases

xk+1 = xk + 1
pk >0 yk+1 = yk - 1
pk+1 = pk + 2xk+1+1 – 2yk+1
Step-04:
If the given center point (X0, Y0) is not (0, 0), then do the following and plot the
point:
•Xplot = Xcurrent + X0
•Yplot = Ycurrent + Y0

Here, (Xcurrent, Ycurrent) denotes the current value of X and Y coordinates.

Step-05:
Keep repeating Step-03 and Step-04 until Xplot >= Yplot.

Step-06:
• Step-05 generates all the points for one octant.
• To find the points for other seven octants, follow the eight-symmetry property
of circle.
Input r and (xc, yc).
First point: (x0, y0) = (0, r).
Compute: p0 = 1 – r
Set k=0: While (xk< yk)
xk+1 = xk+1
If (pk<0) {
yk+1 = yk
pk+1 = pk + 2xk+1+1
Draw (xc+xk+1, yc+yk+1) }
else {
yk+1 = yk-1
pk+1 = pk + 2xk+1+1 – 2yk+1
Draw (xc+xk+1,yc+ yk+1) }
k=k+1 This figure help you complete the circle using the eight-
symmetry property of circle.

Computer Graphics 12
Drawing CirclesAlgorithm (octant)
Draw a circle r=10, (xc, yc)=(0, 0)
First point: (x0, y0) = (0, r).
Compute: p0 = 1 – r
Set k=0: While (xk< yk) k X Y P
xk+1 = xk+1 0
If (pk<0) { 1

Yk+1 = yk 2

pk+1 = pk + 2xk+1+1 3

Draw (xc+xk+1, yc+yk+1) } 4

else { 5
6
yk+1 = yk-1
7
pk+1 = pk + 2xk+1+1 – 2yk+1
Draw (xc+xk+1,yc+ yk+1) } Algorithm Terminates
These are all points for Octant-1.
k=k+1
Drawing CirclesAlgorithm (octant)
Draw a circle r=10, (xc, yc)=(0, 0)
First point: (x0, y0) = (0, r).
Compute: p0 = 1 – r
Set k=0: While (xk< yk) k X Y P
xk+1 = xk+1 0 0 10 -9
If (pk<0) { 1 1 10 -6

Yk+1 = yk 2 2 10 -1

pk+1 = pk + 2xk+1+1 3 3 10 6

Draw (xc+xk+1, yc+yk+1) } 4 4 9 -3

else { 5 5 9 8
6 6 8 5
yk+1 = yk-1
7 7 7 6
pk+1 = pk + 2xk+1+1 – 2yk+1
Draw (xc+xk+1,yc+ yk+1) } Algorithm Terminates
These are all points for Octant-1.
k=k+1
Drawing CirclesAlgorithm (octant)
■ Algorithm calculates all the points of octant-1
and terminates. Octant-1 Octant-2
Points Points
■ Now, the points of octant-2 are obtained using
(0, 10) (7,7)
the mirror effect by swapping X and Y
coordinates (i.e., (1, 10) (8, 6)
(2, 10) (9, 5)
(3, 10) (9, 4)
(4, 9) (10, 3)
(5, 9) (10, 2)
(6, 8) (10, 1)
(7,7) (10, 0)
These are all points for
Quadrant-1 and 2. Do the same
with Octan 3-8
Drawing Circles Algorithm (Quadrant)
■ Here, all the points have been generated with respect to quadrant-1-
Q-1 (X,Y) Q-2 (-X,Y) Q-3(-X,-Y) Q-4 (X,-Y)
(0, 10) (0, 10) (0, -10) (0, -10)
(1, 10) (-1, 10) (-1, -10) (1, -10)
(2, 10) (-2, 10) (-2, -10) (2, -10)
(3, 10) (-3, 10) (-3, -10) (3, -10)
(4, 9) (-4, 9) (-4, -9) (4, -9)
(5, 9) (-5, 9) (-5, -9) (5, -9)
(6, 8) (-6, 8) (-6, -8) (6, -8)
(7,7) (7,7) (7,7) (7,7)
(8, 6) (-8, 6) (-8, -6) (8, -6)
(9, 5) (-9, 5) (-9, -5) (9, -5)
(9, 4) (-9, 4) (-9, -4) (9, -4)
(10, 3) (-10, 3) (-10, -3) (10, -3)
(10, 2) (-10, 2) (-10, -2) (10, -2)
(10, 1) (-10, 1) (-10, -1) (10, -1)
(10, 0) (-10, 0) (-10, 0) (10, 0) Computer Graphics 16
Drawing Circle using C++ functions
const int MAX_POINTS = 20; // Maximum number of points int // Function 2: Draw symmetric points using OpenGL
circlePointsX[MAX_POINTS]; void drawCirclePoints(int x, int y) {
int circlePointsY[MAX_POINTS]; glBegin(GL_POINTS);
int pointCount = 0; // Track the number of points glVertex2i(xc+x, yc+y); glVertex2i(xc-x, yc+y);
int xc = 0, yc = 0, r = 3; glVertex2i(xc+x, yc-y); glVertex2i(xc-x, yc-y);
glVertex2i(xc+y, yc+x); glVertex2i(xc-y, yc+x);
// Function 1: Midpoint Circle Algorithm for One Octant glVertex2i(xc+y, yc-x); glVertex2i(xc-y, yc-x);
void midpointCircleAlgorithm(int r, int xc, int yc) { glEnd();
int x = 0; int y = r; int p = 1 - r; }
circlePointsX[pointCount] = x;
circlePointsY[pointCount] = y; // Function 3: Draw all octants using computed points void drawCircle() {
pointCount++; glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
while (x < y && pointCount < MAX_POINTS) { for (int i = 0; i < pointCount; i++) {
x++; drawCirclePoints(circlePointsX[i], circlePointsY[i]);
if (p < 0) { }
p = p + 2 * x + 1; glFlush();
} else { }
y--; // Display function
p = p + 2 * x + 1 - 2 * y; void display() {
} midpointCircleAlgorithm(r, xc, yc);
circlePointsX[pointCount] = x; drawCircle();
circlePointsY[pointCount] = y; }
pointCount++;
}
}
HW: Drawing CirclesAlgorithm

Draw a circle r=3, (xc, yc)=(0, 0)


First point: (0, r). k xk yk pk
p0 = 1 – r; k=0;
0
While (xk< yk)
xk+1 = xk+1 1
If (pk<0) { 2
yk+1 = yk
4
pk+1 = pk + 2xk+1+1
Draw (xk+1, yk+1) } 5
else {
yk+1 = yk-1
pk+1 = pk + 2xk+1+1 – 2yk+1
Draw (xk+1, yk+1) }
k=k+1

Computer Graphics 18
COMPUTER GRAPHICS
501472-3
Lecture 5- Model Viewing
Windowing I

■ A scene is made up of a collection


of objects specified in world
coordinates.

World
Coordinates
Windowing II

■ When we display a
Window
scene only those objects wymax
within a particular window
are displayed

wymin

wxmin wxmax
World Coordinates
Windowing III

■ Because drawing things to wyma


Window

a display takes time, we clip x

everything outside the


window
wymin

wxmin wxma

World Coordinates x
TWO-DIMENSIONAL
VIEWING
Introduction To Windowing

■ Graphics software allows user to select which part of the picture to show on the display
device and where that part to be placed on the display device
■ A Cartesian coordinate system (world coordinate system) is used to define the picture
■ In a two-dimensional picture , a view is selected by deciding a subarea of total picture
■ A user can select single area or multiple areas for display
■ The picture part within the selected areas are then mapped (converted) onto the
specific areas of the device coordinates
Introduction To Windowing

■ Transformations from cartesian coordinates to device coordinates involves


translation, rotation and scaling operations.
■ This involves also deleting those parts of the picture that are outside the
boundaries of selected display area
– Window - A world coordinate area selected for display
– Viewport - An area on the display device to which a window is mapped
Introduction To Windowing

■ Windowing: mapping a part of a world coordinate scene to device coordinates


is referred to as windowing transformation
■ Windowing transformation is also called as viewing transformation or window-
to-viewport transformation
■ Window is also considered as an area of picture that is selected for viewing
(display)
2D Viewing

■ Window defines what part of the 2D world you want to view.


■ The viewport specifies where and how this view will be displayed on the
output device.
Different window same viewport
wymax wymax

wymin wymin

wxmin wxmax wxmin wxmax

wymax wymax

wymin wymin

wxmin wxmax wxmin wxmax


Same window different viewport
wymax wymax

wymin wymin

wxmin wxmax wxmin wxmax

wymax

wymin

wxmin wxmax
Understanding Check 1

1. What happens if a part of an object lies outside the selected window?


A) It is clipped and not shown
B) It is stretched into the viewport
C) It appears with reduced brightness
D) It overlaps into other scenes
2. A designer selects a very large window but maps it to a small viewport. What is the
likely result?
A) Only part of the window will be visible
B) The scene will appear zoomed-in
C) The scene will look very small and squeezed
D) The scene will not display at all
Understanding Check 1

3. If two users select different windows from the same scene, what changes?
A) The display device
B) The actual objects in the file
C) The part of the scene each user sees
D) The entire scene content
4. If two windows show different parts of the world coordinate scene but map to the
same viewport, what does the user experience?
A) They switch between scenes rapidly
B) They see different content in the same screen area
C) They see the full scene together
D) They get an error
THREE-DIMENSIONAL
VIEWING
Graphics Rendering Pipeline
● Rendering: conversion from scene to image

3D
2D Image
Scene

● Scene is represented as a model composed of primitives. Model is generated by a


program or input by a user.
● Image is drawn on an output device: monitor, printer, memory, file, video frame. Device
independence.
Graphics Rendering Pipeline

■ Typically rendering process is divided into steps called the graphics


pipeline.
■ Some steps are implemented by graphics hardware.
■ Programmable graphics accelerator, GPU: Modern GPUs can
be programmed to control how these steps are done.
Graphics Pipeline

■ A conceptual model that describes what steps a graphics system


needs to render a 3D scene to a 2D screen.
■ Once a 3D model has been created, for instance in a video game or
any other 3D computer animation, the graphics pipeline is the process
of turning that 3D model into what the computer displays.
■ A graphics pipeline can be divided into three main parts: Application,
Geometry and Rasterization.
Graphics Pipeline

▪ Application (Handled by the CPU):


▪ During the application step, changes are made to the scene as
required.
▪ For example, by user interaction by means of input devices or
during an animation.
▪ The new scene with all its primitives, usually triangles, lines and
points, is then passed on to the next step in the pipeline.
Graphics Pipeline
▪ Geometry
▪ The geometry stage’s main responsibilities are per-polygon and per-vertex
operations and can be divided to the following functional stages:

Model & camera Window, viewport


Lighting Projection Clipping
transformation transformation

Object Coordinates Camera Coordinates Clipping Coordinates Device Coordinates

■ Model & Camera Transformation → Places objects in the world and sets the camera
viewpoint (place the model in the world and the camera view)
■ Lighting → Calculates how light hits the objects.
Graphics Pipeline

Model & camera Window, viewport


Lighting Projection Clipping
transformation transformation

Object Coordinates Camera Coordinates Clipping Coordinates Device Coordinates

■ Projection → Converts 3D scene into 2D view (like taking a picture).


■ Clipping → Removes parts outside the camera’s view (we won’t render them).
■ Window/Viewport Transformation → Maps the visible part of the scene to the screen.
Graphics Pipeline (detailed breakdown)
Modeling Viewing
Transformations Transformations
Model
M1
MCS 3D World V 3D View
model Model Scene Scene
coordinate M2
system
Model
M3
WCS
World
coordinate
VCS
View coordinate
system
system

2D/3D Device Rasterization


P Clip Normalize
Scene

Projection NDCS
Normalized DCS
2D Image
Device
Coordinate
SCS
System
Three-Dimensional Viewing

Viewing in 3D involves the following considerations:


• Our eyes collapse the 3D world into a 2D retinal image.
• We can view an object from any spatial position, for example: In front of the
object, behind the object, in the middle of a group of objects, inside the object,
etc.
• In computer graphics (CG), this process occurs through projection: 3D
descriptions of objects must be projected onto the flat viewing surface of the
output device.
• Clipping boundaries define a volume of space that determines what will be
visible in the final view.
Understanding Check 2

1. In computer graphics, what process is used to display 3D objects on a 2D screen?


A) Shading
B) Projection
C) Clipping
D) Scanning
2. Which of the following is not a valid viewpoint in 3D viewing?
A) In front of the object
B) Behind the object
C) Inside the object
D) Under the screen
Projections

■ There are 2 basic projection methods:


1. Parallel Projection transforms object positions to
the view plane along parallel lines.
• Preserves relative proportions of objects.
• Accurate views of the various sides of an object
are obtained with a parallel projection. But not
a realistic representation.
• However, it's super useful when you need to
keep the correct sizes and proportions
(blueprint or CAD)
Projections

2. Perspective Projection transforms object positions to the view plane while converging to a
center point of projection.
• Produces realistic views but does not preserve relative proportions. Projections of distant
objects are smaller than the projections of objects of the same size that are closer to the
projection plane.
Parallel Projection

■ Classification:
Orthographic Parallel Projection and Oblique Projection:

■ Orthographic parallel projections are done by projecting points along parallel lines
that are perpendicular to the projection plane.
■ Oblique projections are obtained by projecting along parallel lines that are NOT
perpendicular to the projection plane.
Parallel Projection

■ Some special Orthographic Parallel Projections involve Plan View (Top


projection), Side Elevations, and Isometric Projection:
Parallel Projection

■ The following results can be obtained from oblique projections of a cube:


Understanding Check 3

1. What type of projection is most likely used in this drawing?


A) Orthographic Projection
B) Oblique Projection
C) Perspective Projection

2. What type of projection is most likely used in this drawing?


A) Orthographic Projection
B) Oblique Projection
C) Perspective Projection
CLIPPING
Clipping

• Goal: Cut off parts of objects outside the view volume to save rendering effort.
• Any procedure that identifies which portion of a picture is inside or outside of a
specified region (area) is called as 'clipping algorithm)
• The region (area) which is used to clip an object is called as 'clip window'
Clipping

■ Clipping is used in many ways, such as:


– extracting part of a scene
– Building objects in 3D modelling
– Displaying multiple windows
– Drawing or painting within a certain area
– Choosing a part of a picture to copy
Clipping
Clipping

■ For the image below consider which lines and points should be kept and which ones
should be clipped
P4

Window P2
wymax
P6
P3
P1
P7 P5

P9
P8
wymin
P10

wxmin wxmax
Point Clipping

• Easy - a point (x,y) is not clipped if:


• wxmin ≤ x ≤ wxmax AND wymin ≤ y ≤ wymax
P4 Clipped
• otherwise, it is clipped. Clipped

Window
• Example: wymax
P2

Clipped
• P5 is not clipped because: P5
P1
P7 Points Within the Window
• wxmin ≤ x ≤ wxmax AND wymin ≤ y ≤ wymax are Not Clipped
P9 P8
wymin
Clipped P10

wxmin wxmax
Understanding Check 3

Is the point (4,3) clipped or not?

Window
Is the point (2,6) clipped or not? 7

3 10
Line Clipping
Harder - examine the end-points of each line to see if they are in the window or not

Situation Solution Example

Both end-points inside


Don’t clip
the window

One end-point inside


the window, one Must clip
outside

Both end-points
Don’t know!
outside the window
Brute Force Line Clipping

■ Brute force line clipping can be performed


as follows:
– Don’t clip lines with both end-points
within the window
– For lines with one end-point inside the
window and one end-point outside,
calculate the intersection point (using
the equation of the line) and clip from
this point out
Brute Force Line Clipping

– For lines with both end-points outside


the window test the line for intersection
with all of the window boundaries, and
clip appropriately
■ However, calculating line intersections is
computationally expensive.
■ Because a scene can contain so many
lines, the brute force approach to clipping
is much too slow
Line Clipping
11
of

Cohen-Sutherland Clipping Algorithm


30

• An efficient line clipping algorithm


• The key advantage of the algorithm is that it greatly reduces the number of line
intersections that must be calculated.
• In the Cohen–Sutherland line clipping algorithm, a four-digit binary code is
assigned to both endpoints of each line.
• This four-digit binary code is called a region code (e.g., 1010).
• The region code identifies the location of a point relative to the rectangular
clipping window.
• Each bit gives information about the point's position with respect to the clipping
window.
Cohen-Sutherland: World Division

■ World space is divided into regions based on the window boundaries


– Each region has a unique four-bit region code
– Region codes indicate the position of the regions with respect to the
window

1001 1000 1010


3 2 1 0 0000
0001 0010
above below right left Window
Region Code Legend
0101 0100 0110
Cohen-Sutherland: World Division

■ If a point is on the left side of the window, then


its first bit is 1, or when X < XWmin
■ If a point is on the right side of the window, then
its second bit is 1, or when XWmax < X
■ If a point is below the window, then its third bit is
1, or when Y < YWmin
■ If a point is above the window, then its fourth bit
is 1, or when YWmax < Y
■ If a point is inside the window, then all four
bits of that point are 0
[Link]
[Link]
Cohen-Sutherland: World Division

■ Cohen–Sutherland line clipping algorithm can be divided into two parts.


■ PART-1: we decide the category of lines as below:
– Category 1: Lines which are completely inside the window
– Category 2: Lines which are completely outside the window
– Category 3: Lines which are partially inside and partially outside the window
■ We give a four-bit code (region code) to each endpoint of all the lines.
■ If a point is on the left side of the window or when X < XWmin, then set the first bit to
1
Cohen-Sutherland: World Division

In Part 2: We calculate the intersection points of lines that fall into category 3 (partially
inside and partially outside the window).
Bit-Based Calculations:
• If first bit is 1: Line intersects the left vertical boundary.
Intersection point Y=Y1+m(XWmin−X1)
• If second bit is 1: Line intersects the right vertical boundary.
Intersection point Y=Y1+m(XWmax−X1)
• If third bit is 1: Line intersects the bottom horizontal boundary.
Intersection point X = X1+(YWmin−Y1)/m
• If fourth bit is 1: Line intersects the top horizontal boundary.
Intersection point X=X1+(YWmax−Y1)/m
Cohen–Sutherland Line Clipping
Algorithm (Steps)
■ Step 1: Read the two end points of a line P1(X1,Y1) and P2(X2,Y2)
■ Step 2: Read the lower-left and upper-right coordinates of the clipping window.
■ Step 3: Assign 4-bit region codes to P1 and P2.
■ Step 4: Check the category of the line based on region codes:
• Category 1: Line is completely inside the window, accept and display the line.
• Category 2: Line is completely outside the window, reject the line
• Category 3: Line is partially inside and partially outside the window, continue to
next steps.
■ Step 6: Find the intersection boundaries of the clipping window and proceed with
calculating intersection points.
Cohen–Sutherland Example

Window
Consider the line P₉ to P₁₀ below: wymax
• Start at P₁₀
• From the region codes of the two end-
points, we know the line doesn’t cross the P9 [0000]
left or right boundary wymin
P10’ [0000]

• Calculate the intersection of the line with P10 [0100]


the bottom boundary to generate point P₁₀′
→ X = X1+(YWmin−Y1)/m wxmin wxmax

• The line P₉ to P₁₀′ is completely inside the


window, so it is retained
Cohen–Sutherland Example

Consider the line P7 to P8 below: Window


wymax
• Start at P7: From the two region codes of
the two end-points we know the line
crosses the left boundary so calculate P7’ [0000]
the intersection point to generate P7’ P7 [0001] P8 [0010]
P8’ [0000]
• Start at P8: Calculate the intersection wymin
with the right boundary to generate P8’
• P7’ to P8’ is inside the window so is
retained. wxmin wxmax
Understanding Check 4

Given:
Window
• Clipping Window boundaries: 30
• WXmin=10
(5,15)
• WXmax=40
• WYmin=10
• WYmax=30 10

Line Segment: (30,5)

• Point A: (5,15) 10 40
• Point B: (30,5)
Polygon Clipping
■ Collection of connected lines is considered as Polygon.
■ A polygon clipper takes as input the vertices of a polygon and returns one(or more)
polygons.
■ A closed Polygon when clipped then we may get one or more open polygon or lines.
– After clipping the resulting polygon should be closed.
– It requires that lines ab & cd be added to make it closed polygon.
– Hence it is difficult to find out which pieces of sections should be joined to
make the clipped polygon closed.
C
d c
D
a
A
b
B
Polygon Clipping

■ Another problem occurs when clipping a closed polygon into several distinct smaller
polygons as shown:

Clipping
Window

Concave
Polygon
Polygon Clipping

By convention, a polygon with vertices p1..pn is said to be positively oriented if it


produces a anticlockwise direction. And if produces clockwise it will be negative
oriented.

C D
D C
L R

E
L R

E B B
A
A
SUTHERLAND-HODGMAN ALGORITHM
Each edge of the polygon must be tested
against each edge of the clip rectangle; new
edges must be added, and existing edges must
be discarded, retained, or divided. Multiple
polygons may result from clipping a single
polygon. We need an organized way to deal
with all these cases.
Steps of Sutherland-Hodgman's polygon
clipping algorithm
■ Polygons can be clipped against each edge of the window one at a
time.
■ Vertices which are kept after clipping against one window edge are
saved for clipping against the remaining edges.
■ Note that the number of vertices usually changes and will often
increases.

The original polygon


and the clip
rectangle.
After clipped by the
right clip boundary.

After clipped by the


right and bottom
clip boundaries.
After clipped by the
right, bottom, and
left clip boundaries.

After clipped by all


four boundaries.
Four Cases of polygon clipping against one
Edge:
The clip boundary determines a visible and
Invisible region. The edges from vertex can be
one of four types:
■ Case 1 : Wholly inside visible region - save endpoint
■ Case 2 : Exit visible region - save the intersection
■ Case 3 : Wholly outside visible region - save nothing
■ Case 4 : Enter visible region - save intersection and endpoint

V1
V2 V1
V1’

V2

Out → in in → in
Save V1’,V2 Save V2
V2

V1
V1’
V2 V1

in → out out → out


Save V1’ Save none
COMPUTER GRAPHICS
501472-3
Lecture 7- 3D in OpenGL
External Links

• [Link]
• [Link]
Coordinate Systems

■ In 3D we have XYZ-coordinates.
■ The three axes are perpendicular to each other.
■ The point of intersection is called the origin which is (0,0,0).
■ To define a point in space, we give 3-numbers (X,Y, Z).
Coordinate Systems
Range of view
• In OpenGL, negative Z axis is inside the
screen. (i.e. moving object toward Your eyes
negative Z-axis will move the object Negative z-axis
deeper into the scene, away from the
viewer.
Imaginary line
• OpenGL simulate your eyes.
• Your eyes is looking into the negative z-
axis.
Coordinate Systems
Range of view

• To draw a point: Your eyes


Negative z-axis
• The intersection of the
imaginary line from the point
to be drawn and the range of Imaginary line
view rectangle (the
boundaries of the screen or
Point to be drawn
viewport) is the point drawn. Point drawn
3D Functions:

• glEnable(GL_DEPTH_TEST); Enable testing the depth of objects.


• This means that the object behind another object will not appear on the
screen (it is hidden).
When GL_DEPTH_TEST is enabled,
then the blue triangle is above the red
triangle. Part of the red triangle is
hidden behind the blue triangle.

• To disable the depth test we use: glDisable(GL_DEPTH_TEST);


3D Functions:

• Before drawing, you need to clear the depth buffer:


– glClear(GL_DEPTH_BUFFER_BIT);
• The depth buffer, also known as the Z-buffer, stores the depth of each
pixel to handle objects.
3D Functions:

• gluLookAt(eyex, eyey, eyez, ax, ay, az,


upx, upy, upz);
• It is used to set up a camera in a 3D world (or eye)
• eyex, eyey ,eyez are location of the camera or eye.
• ax, ay, az are aim of the camera (the main subject
you want to capture).
• upx, upy, upz are the up-vector of the camera
(ensures the camera is looking up).

gluLookAt(0.0, 0.0, 0.0, 0.0, 0.0, -100.0, 0.0, 1.0, 0.0);


Example of gluLookAt:

gluLookAt(4.0, 2.0, 1.0, 2.0, 4.0, -3.0, 2.0, 2.0, -1.0);


■ The 'up' vector is non-standard. This
vector does not have to be normalized
(having a length of 1), as OpenGL will
normalize it for you.
3D Functions:

■ To produce a perspective projection, we use gluPerspective or


glFrustum.
■ The primary difference between the two is:
– gluPerspective()only produces symmetrical (on-axis)
projections-- a straightforward, balanced view.
– while glFrustum() is more general and allows symmetrical and
asymmetrical projections.
3D Functions:

glFrustum(left, right, top, bottom,


near, far)

• This is a perspective projection: it


means as object go to the far plane,
then the object gets smaller.

Object exist outside


this frustum is not
drawn
3D Functions:

• gluPerspective(angle, aspect, near,


far)
• Angle (fovy): view angle how wide.
• Aspect: width/height (x/y).
• This is a perspective projection: it means
as object go to the far plane, then the
object gets smaller.
3D Functions:

• glOrtho(left, right, top,


bottom, near, far)
• gluOrtho2D(left, right, top, bottom, 1, -1)
• This is called parallel projection: it
means that object are in the same size
in the far or near to the camera.
#include <GL/glut.h>
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Define the frustum
double left = -1.0, right = 1.0, bottom = -1.0, top = 1.0, near = 1.0, far = 10.0;
glFrustum(left, right, bottom, top, near, far); // Set up the perspective projection using
glFrustum
glutSwapBuffers();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("glFrustum Example");
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST); // Enable depth testing for 3D rendering
glutMainLoop();
Understanding Check 1
Q1: If you use gluPerspective(45.0, 1.0, 0.1, 100.0), what does the
parameter 45.0 represent?
A) Camera position
B) Field of view angle
C) Near clipping plane
D) Aspect ratio

Q2: Which projection would you choose for accurately displaying an architectural
blueprint?
A) gluPerspective
B) glFrustum
C) glOrtho
D) gluLookAt
3D SHAPES
3D Functions:

• glutSolidSphere(radius, slice, stack):


• Slice: number of subdivision around the z-axis (More slices result in a
smoother appearance.)
• Stack: number of subdivision along the z-axis (More stacks result in a
more detailed sphere.)

• glutWireSphere(radius, slice, stack):


3D Functions:

• glutSolidCone(base radius, height, subdiv1, subdiv2)

• glutWireCone(base radius, height, subdiv1, subdiv2)


3D Functions:

• glutSolidCube(side)
• glutWireCube(side)
3D Functions:

A ring-shaped object:
• glutSolidTorus(thickness, radius, subdiv1, subdiv2)
• glutWireTorus(thickness, radius, subdiv1, subdiv2):
3D Functions:

• glutSolidTeapot(size)
• glutWireTeapot(size)
Understanding Check 2

■ Draw a cube with each side measuring 4 cm


Understanding Check 2

void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glFrustum(-2.0, 2.0, -2.0, 2.0, 5.0, 100.0);
gluLookAt(5.0, 5.0, 10.0, // Camera position
0.0, 0.0, 0.0, // Look-at point (center of cube)
0.0, 1.0, 0.0); // Up vector
glColor3f(0.8f, 0.1f, 0.1f); // Dice red
glutSolidCube(4) // Call the cube drawing function
glutSwapBuffers();
}
ANIMATION
Animations

Animation is the art of making drawings move or the method of photographing successive
drawings, models, and puppets and manipulating them to appear as moving images.
Double buffer

• We created a simple animation, but the methodology that we used


does not produce smooth animations. Since it uses a single buffer for
drawing, that method will often produce flicker animations.
• Moreover, the lack of timing control means that such animations will
not run consistently across different machines.
• In fact, that method will typically produce jerky animations of varying
speed as the computer running it changes processor usage.
Double buffer

• To fix the flickering problems, we add double buffering to the previous


single buffer animation.
• With double buffer, we use an additional back buffer for drawing our
next frame.
• When we are finished drawing, the back buffer is switched to be the
front buffer where it is used to update the screen.
• Doing this, prevents our drawing from being shown before it is
complete.
Double buffer Example

3D_LecTorus
Double buffer

• We can make two simple changes to add double buffering to


our animation.
• First, we change the display mode by replacing "GLUT_SINGLE"
with "GLUT_DOUBLE" to enable double buffering.
• Then, we need to add the buffer switching. To do this, change
"glFlush();" to "glutSwapBuffers();" to swap buffers when
Draw() is called.
• Note that glutSwapBuffers() also calls glFlush(), so we
can make this simple replacement.
Timer Function

• We move on to add in a timed delay to make our rendering consistent.


• For this, we can use the function glutTimerFunc() to set a function
to be called after a specified time. It takes three arguments:
1. Time in milliseconds,
2. The function that will be called, and
3. An integer value that is passed into the function when it is called.
• Example: glutTimerFunc(25, update, 0);
• Function update will be called in 25 millisecond with argument to
update of 0.
Timer Function

Example:
void update(int value) {

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

glutTimerFunc(30, update, 0);

}
#include <GL/glut.h>
float posX = 0.0f; // Initial x position of the square

void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glTranslatef(posX, 0.0f, 0.0f); // Translate the square along the x-axis
glColor3f(1.0, 1.0, 1.0); // Set color to white
glBegin(GL_QUADS);
glVertex2f(-0.2, -0.2); glVertex2f(0.2, -0.2); glVertex2f(0.2, 0.2); glVertex2f(-
0.2, 0.2);
glEnd();
glutSwapBuffers();
}
void update(int value) {
posX += 0.01f; // Increment x position
if (posX > 1.0) {

posX = -1.0; // Reset x position when reaching the right edge of the screen
}
glutPostRedisplay(); // Request redisplay to animate continuously
glutTimerFunc(16, update, 0); // Call update function again after 16 milliseconds
}
int main(int argc, char** argv) {

glutInit(&argc, argv);

glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);

glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Animation Example");

glutDisplayFunc(display);

glEnable(GL_DEPTH_TEST); // Enable depth testing for 3D rendering

glutTimerFunc(16, update, 0); // Call update function every 16 milliseconds for


animation

glutMainLoop();
return 0;

}
Understanding Check 3

Q1: Why is glutSwapBuffers() preferred over glFlush() in an animation loop using double
buffering?
A) It improves color rendering
B) It allows drawing in both front and back buffers simultaneously
C) It avoids the need for a depth buffer
D) It swaps the completed frame to the screen for smooth rendering
Q2: An animation appears choppy and inconsistent in speed. Which of the following is the
most likely cause?
A) The field of view is too wide
B) glutSwapBuffers() is not used
C) The viewport is not resized properly
D) No timer function is the frame rate
Understanding Check 3

Q3: In a double-buffered OpenGL animation, what could cause screen flickering?


A) Updating animations directly on the front buffer
B) Forgetting to call glFlush()
B) Drawing too few frames per second
C) Using glutIdleFunc() instead of glutTimerFunc()
Q4: You need to animate a car moving left to right continuously. What is the best approach?
A) Change the camera with gluLookAt() every frame
B) Use a sine wave to update car position in the Z-axis
C) Use glTranslatef() inside a timed update with glutTimerFunc()
D) Redraw the car in the same position every time
Types Of Animation
■ There are four main types of animation:

1. 2D animation
2. 3D animation
3. Stop motion animation
4. Motion graphics

There is an additional type of animation called traditional animation.


However, since traditional animation is the first type of 2D animation
Types Of Animation
■ TRADITIONAL ANIMATION
Traditional animation is also called hand-drawing animation, classical
animation, or cel animation. It consisted of drawing everything frame
by frame, be it a character, a background, and everything in between.

These drawings were made on sheets of transparent paper and then


photographed on an animation camera.

After that, the final photographs were used to create movement in a


two-dimensional space, animated on 12 frames per second (fps).
Sometimes they were animated on 24fps for smoother movements and
faster action.
Types Of Animation

■ 2D ANIMATION
With traditional animation, animators were required to keep drawing
the same characters over and over again.
■ That is not needed with vector-based 2D animation since the
motion is controlled by vectors.
■ With vectors, every creation can be reused as many times as the
animator wishes, without having to re-create the same
backgrounds, characters, and so on.
■ Moreover, the movement of the characters is controlled by
vectors.
Types Of Animation

■ 3D ANIMATION

Also called CGI or Computer Animation, 3D animation is one of


the most popular types of animation. 3D animation is used not
only for feature films but also for short films, video games,
ads, and more.
3D Animation vs. 2D Animation
■ Technical skillsets:
– excellent drawing skills to become a 3D designer.
However, you will need to have a clear understanding
of animating in 3D.

■ Moving instead of drawing:


– Compared to 2D animation, 3D animation will mainly
consist of moving the character in a 3D program
rather than drawing for different frames.
Stop Motion Animation

■ Stop motion animation is similar to traditional animation since it also combines a


series of images that document slight movements.
■ However, stop motion animation uses photographs of real objects and not drawings
or vector animations.
■ Artists take pictures of real-life objects and scenes. After each object they move in
the scene they have set up, they take a picture before making the next move or the
next moves.
Stop Motion Animation

■ They continue this process until they have a photo for each frame they want to use
for their animation.
■ Similar to traditional 2D animation, when all frames are shown in a sequence right
after the other, the objects seem like they are moving on their own. That’s how the
illusion of movement is created with stop motion animation.
■ Before CGI animation, stop motion animation was the only animation type that gave
viewers that “special effects” feeling.
Motion Graphics
■ Motion graphics can be 2D and 3D and are mainly used to animate text, logos, and
video clips. Motion graphics are called all digital graphics that create the illusion of
motion.

■ Unlike 2D animation and 3D animation, you do not need to follow a particular


storyline or focus on key characters with motion graphics.
COMPUTER GRAPHICS
501472-3
Lecture 6- 2D/3D transformation
Current Transformation Matrix (CTM) in
OpenGL
■ The CTM (Current Transformation Matrix) is 4X4 matrix used by OpenGL to
transform every vertex before it's rendered.
■ Always exists — even without transformations (initialized to the identity matrix).
■ It accumulates modelling and viewing transformations, such as:
– Translation
– Rotation
– Scaling
– Composite transformations (combined effects)
■ Every change to the CTM affects how subsequent geometry appears on screen.
Working with Transformation Matrices
in OpenGL
■ How the CTM Works:
■ Each transformation (like glTranslatef, glRotatef) generates a matrix.
■ The CTM can be set/reset/modify (by post- multiplication) by a matrix, example:
– C <= M // set to matrix M
– C <= CT // post-multiply by T
– C <= CS // post-multiply by S
– C <= CR // post-multiply by R
■ The final CTM is a cumulative result of all applied transformations. Example
Sequence:
– CTM = M × T × R × S
Managing Transformation Matrices

■ Define matrix types: modeling, viewing, projection, viewport.


■ Use glLoadIdentity() to reset the CTM... Removes previous transformations
■ Apply transformations with glTranslatef(), glRotatef(), glScalef().
■ Save/restore state using glPushMatrix() and glPopMatrix().
■ Combine transformations to form a single effect (order matters).
Transformation
• Transformation means changing some graphics into
something else by applying rules.
• We can have various types of transformations such as
translation, scaling up or down, rotation, shearing, etc.
• Transformations play an important role in computer
graphics to reposition the graphics on the screen and
change their size or orientation.

Computer Graphics 5
Why use transformations?

• Position objects in a scene (modeling)


• Change the shape of objects
• Create multiple copies of objects
• Projection for virtual cameras
• Animations

Computer Graphics 6
Why Transformations?

■ In graphics, once we have an object described, transformations are used to move


that objects, scale it and rotate it.

Computer Graphics 7
ObjectsTransformation
• 5-type of object Transformation:
• Translation or Shifting: moving objects
• Scaling: change size.
• Rotation: moving about a point by an angle.
• Reflection: mirror of an object.
• Shearing: distort the object (deformation).

Reflect Translate Scale Rotate Shear


Ways to Specify Transformations
■ In OpenGL, we usually have two styles of
■ specifying transformations:
– Specify matrices ( glLoadMatrix, glMultMatrix )
– Specify operations ( glRotate, glTranslate )

Using Pre-defined functions Using glMultMatrixf


glLoadIdentity(); GLfloat myMatrix[16] = {
glTranslatef(2.0, 0.0, 0.0); 1.0, 0.0, 0.0, 0.0, // Scaling X
drawObject(); 0.0, 1.0, 0.0, 0.0, // Scaling Y
0.0, 0.0, 1.0, 0.0, // Scaling Z
2.0, 0.0, 0.0, 1.0 // Translation (X=2.0)
};
glLoadIdentity(); glMultMatrixf(myMatrix);
Transformation Matrices

1 0 0 𝑑𝑥 1 0 0 0
𝑑𝑦 0 cos 𝜃 − sin 𝜃 0
Translation: 0 1 0 Rotation Rx 𝜃 :
0 sin 𝜃 cos 𝜃 0
0 0 1 𝑑𝑧
0 0 0 1 0 0 0 1

𝑠𝑥 0 0 0 cos 𝜃 0 sin 𝜃 0
0 𝑆𝑦 0 0 Rotation Ry 𝜃 : 0 1 0 0
Scale: 0 − sin 𝜃 0 cos 𝜃 0
0 𝑆𝑧 0
0 0 0 1 0 0 0 1
TRANSLATION
Translation

■ Simply moves an object from position to another

Computer Graphics 12
Translation

• The object is shifted or moved to a new coordinates.


• The shift is by (dx, dy).
• x’ = x + dx
• y’ = y + dy.
• In matrix forms:  x'  x  dx
 y' =  y  + dy
     
Translation

• To translate a line, translate its end points.


• To translate a polygon, translate its vertices.
• To translate a circle or ellipse, its center coordinates are
transformed, then the object is drawn (boundary points)
using new coordinates.

Computer Graphics 14
Translation Example 1

• Draw a square of length 2. One side of the square vertices'


coordinates are (0,0), (2,0), (2,2), (0,2), then translate it toward y-
axis by 1.
• Solution: x’=x, y’=y+1

• dx=0, dy=1. Old New


(0,3)
Coordinates Coordinates (2,3)
(0,0) (0,1)
(0,2) (2,2)
(2,0) (2,1)
(2,2) (2,3) (0,1) (2,1)
(0,2) (0,3)
(0,0)
(2,0)

Computer Graphics 15
Translation Example 2:

■ A triangle with vertices coordinates: (1,0), (3,0), (2,2). What its new coordinates
after shifting it by 1 in the x-axis and y-axis.
■ Solution:
(3,3)
– x’= x + 1 and y’ = y+1.
(2,2)

Old New
Coordinate Coordinate (4,1)
(2,1)
s s
(1,0) (2,1) (1,0) (3,0)
(3,0) (4,1)
(2,2) (3,3)

Computer Graphics 16
Translation In OpenGL
glTranslate[fd](Tx, Ty, Tz): It will shift the whole coordinates by Tx, Ty, Tz.
■ glTranslated() takes double-precision floating-point values.
■ glTranslatef() takes single-precision floating-point values.

glColor3ub(255, 0, 0);
glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(2,0); glVertex2i(2,2);
glVertex2i(0,2);
glEnd();
glColor3ub(0, 0, 255);
glTranslatef(1.0,1.0,0); // Translate the coordinate system by
(1.0, 1.0, 0)
glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(2,0); glVertex2i(2,2);
glVertex2i(0,2);
glEnd();
Computer Graphics 17
Understanding Check 1

■ Draw the Triangle with the coordinates:


■ (1,0), (5,0), (3,4)
■ Then translate it using the function:
■ glTranslatef(1,3,0);
SCALING
Scaling

• Scaling: increase/decrease size of object


• To scale an object, we do the following:
1. Shift object to point (0,0).
2. Scale by (sx, sy) using the equations: x’ = x*sx; y’ = y*sy;
3. Shift object back to its original location.

• In general, scaling equations are:


• x’ = xf + (x-xf)*sx; y’ = yf + (y-yf)*sy;
• Where (xf, yf) is the reference point.
Computer Graphics 20
Scaling

• Scaling is called uniform if sx=sy, otherwise it is called differential.


• In matrix form:
x′ Sx 0 x
=
y′ 0 Sy y
■ To apply the scaling transformation to a point (x,y,1), we use matrix multiplication

Computer Graphics 21
Scaling Example:

• A rectangle with coordinates (0,0), (4,0), (4,3), (0,3) what it is the


new coordinates if:
• Sx=Sy=2
• Sx=Sy=0.5 Old New
Coordinates Coordinates (8,6)
• Solution: (0,6)
(0,0) (0,0)
• Sx=Sy=2:
(4,0) (8,0) (4,3)
(0,3)
(4,3) (8,6)
(0,3) (0,6)

(0,0) (4,0) (8,0)


Scaling Example:

■ Sx=Sy=0.5:

Old New
Coordinates Coordinates
(0,0) (0,0)
(4,0) (2,0) (4,3)
(0,4)
(4,3) (2,1.5)
(0,1.5) (2,1.5)
(0,3) (0,1.5)

(0,0) (2,0) (4,0)

Computer Graphics 23
Scaling Example 2

■ A square with coordinates: (1,1), (2,1), (2,2) ,(1,2).


■ Scale it by Sx=Sy=2, with (xf,yf)=(1,1).

■ Solution:
Old New
◦ Sx=Sy=2: Coordi Coordin
◦ Shift point (1,1) to (0,0) nates ates
■ (Xf,yf) = (1,1). (1,1) (1,1)
◦ x’ = xf + (x-xf)*sx; (2,1) (3,1)
◦ y’ = yf + (y-yf)*sy (2,2) (3,3)
(1,2) (1,3)

Computer Graphics 24
Scaling Example 2

(1,3) (3,3)
(1,2) (2,2) (1,2)
(2,2)

(1,1) (2,1) (3,1)


(1,1) (2,1)

Computer Graphics 25
OpenGL Scaling

glScale[fd](Sx, Sy, Sz)

glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(4,0); glVertex2i(4,4); glVertex2i(0,4);
glEnd();

glScaled(2,2,1); // Apply scaling with scaling factors (2, 2, 1)


glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(4,0); glVertex2i(4,4); glVertex2i(0,4);
glEnd();

Computer Graphics 26
OpenGL Scaling:
Example .. What is the output of this code?
#include <GL/glut.h> void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
void drawTriangle() {

glBegin(GL_TRIANGLES); drawTriangle(); // Draw the original triangle


drawScaledTriangle(); // Draw the scaled triangle
glVertex2f(2, 2);

glVertex2f(2, 4); glutSwapBuffers();


}
glVertex2f(5, 2);

glEnd();

void drawScaledTriangle() {

glPushMatrix();

glScalef(2, 2, 1); //Scale by a factor of 2

drawTriangle();

glPopMatrix();

}
Understanding Check
Draw a rectangle then apply a scaling transformation to make the width half its
size and keep the height the same. Draw the scaled rectangle.
ROTATION
Rotation
• In linear algebra, a rotation matrix is used to perform
a rotation in Euclidean space.

• For example, rotating points in the xy plane


counterclockwise through an angle θ with respect to
the positive x axis about the origin of a 2D Cartesian
coordinate system.
• By means of the following matrix multiplication,

Computer Graphics 33
Rotation

• Thus, the new coordinates (x′, y′) of a point (x, y) after a 2D rotation
around the origin (0,0) by an angle θ in the counterclockwise
direction is:
• x' = x cos θ - y sin θ ; y' = x sin θ + y cos θ

• The equation for rotation about a reference point (xf,yf) is:


(x’,y’)

• x' = x f + (x − x f ) cos − ( y − y f ) sin (x,y)



• y' = y f + (x − x f ) sin + ( y − y f ) cos
(xf,yf)
Rotation Example

• Consider a rectangle with coordinates (1,1), (3,1), (3,5), (1,5).


Rotate it 45o about the point (1,1).
Old Coordinates New Coordinates
(1,1) (1,1)
(3,1) (2.4142, 2.4142)
• Solution: (3,5) (-0.4142 5.2426)
• (xf,yf)=(1,1),  = 45o. (1,5) (-1.828, 3.828)
• cos 45 = 0.71, sin 45 = 0.71,
• So, x’ = xf + (x-xf) * cos  - (y-yf)sin 
• And y’ = yf + (x-xf) * sin  + (y-yf)*cos

Computer Graphics 35
Rotation In Opengl

• glRotatef(angle, x, y, z).
• The last three parameters (x, y, z) are clamped to the range of [0, 1].

Rotation 45o about the z-axis:


• glRotatef(45, 0.0, 0.0, 1.0); //red
Rotation 45o about the x-axis:
• glRotatef(45, 1.0, 0.0, 0.0); //blue
Rotation 45o about the y-axis:
• glRotatef(45, 0.0, 1.0, 0.0); //green

Computer Graphics 36
Rotation In Opengl

glRotatef(theta, 0, 1, 0); glRotatef(theta, 1, 0, 0); glRotatef(theta, 0, 0, 1);

Source: [Link]

Computer Graphics 37
Rotation In Opengl

glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(4,0); glVertex2i(4,4); glVertex2i(0,4);
glEnd();
glRotatef(45, 0.0, 0.0, 1.0);
glBegin(GL_LINE_LOOP);
glVertex2i(0,0); glVertex2i(4,0); glVertex2i(4,4); glVertex2i(0,4);
glEnd();

Computer Graphics 38
Rotation In Opengl

Computer Graphics 39
REFLECTION
Reflection

• The equation for reflection with respect to x-axis


• For each point (x, y)
• New point (x, -y).

Computer Graphics 41
Reflection

• The equation for reflection with respect to y-axis


• For each point (x, y)
• New point (-x, y).

Computer Graphics 42
Reflection

• The equation for reflection with respect to origin


• For each point (x, y)
• New point (-x, -y).

Computer Graphics 43
Reflection Example

 Consider a rectangle with coordinates (1,1), (3,1), (3,5), (1,5). Reflect it with
respect to x-axis

 Solution:
Old Coordinates New Coordinates
(1,1) (1, -1)
(3,1) (3, -1)
(3,5) (3, -5)
(1,5) (1, -5)

Computer Graphics 44
Reflection Example

 Consider a rectangle with coordinates (1,1), (3,1), (3,5), (1,5). Reflect it with
respect to y-axis

 Solution:
Old Coordinates New Coordinates
(1,1) (-1, 1)
(3,1) (-3, 1)
(3,5) (-3, 5)
(1,5) (-1, 5)

Computer Graphics 45
Reflection Example

 Consider a rectangle with coordinates (1,1), (3,1), (3,5), (1,5). Reflect it with
respect to origin

 Solution: Old Coordinates New Coordinates


(1,1) (-1, -1)
(3,1) (-3, -1)
(3,5) (-3, -5)
(1,5) (-1, -5)

Computer Graphics 46
Reflection in OpenGL

■ In OpenCL, we can reflect an object By using glScal[fd]


– To reflect an object across the y-axis we use “glScalef(-1, 1, 1)”.
– To reflect an object across the x-axis we use “glScalef( 1,-1, 1)”.
– To reflect an object across the origin we use “glScalef(-1, -1, 1)”.
Example .. What is the output of this code?
#include <GL/glut.h>
void drawTriangle(float x_axes, float y_axes) {
glBegin(GL_TRIANGLES);
glVertex2f(2 * x_axes, 2 * y_axes);
glVertex2f(2 * x_axes, 7 * y_axes);
glVertex2f(5 * x_axes, 2 * y_axes);
glEnd();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
drawTriangle (1, 1)
drawTriangle(-1, 1); // Reflect along -x and +y
drawTriangle(-1, -1); // Reflect along -x and -y
drawTriangle(1, -1); // Reflect along +x and -y
glutSwapBuffers();
}
Example .. What is the output of this code?
void display() {
glClear(GL_COLOR_BUFFER_BIT);
drawTriangle(); // Original Triangle

glPushMatrix();
glScalef(-1.0, 1.0, 1.0); // across Y-axis
drawTriangle();
glPopMatrix();

glPushMatrix();
glScalef(-1.0, -1.0, 1.0); // across origin
drawTriangle();
glPopMatrix();

glPushMatrix();
glScalef(1.0, -1.0, 1.0); // across X-axis
drawTriangle();
glPopMatrix();
glFlush();
}
Order of transformation

■ Generally, do not expect different orders of transforms to produce the same result, because
matrix multiplication is not commutative.
■ Another way to think about transforms.
– Move a local coordinate system.
– Each object has a local coordinate system
– Transforms happen relative to this coordinate system.
– Unfortunately, breaks down when scale is involved.
Rotation About an Arbitrary Point

1. Translate object through vector –V. • glMatrixMode (GL_MODEVIEW);


T(-4.0, -5.0, -6.0)
• glLoadIdentity ();
2. Rotate about the origin.
• glTranslatef (4.0, 5.0, 6.0);
R(45.0, 1.0, 2.0, 3.0)
• glRotatef (45.0, 1.0, 2.0, 3.0);
3. Translate back through vector V
• glTranslatef (-40.0, -5.0, -6.0);
4. T(4.0, 5.0, 6.0)

Note: The order in the code appears reversed compared to the written explanation because OpenGL
applies transformations in reverse order (matrix multiplication is done from the right).
Order of Transformations

■ The transformation matrices appear in reverse order to that in which the transformations
are applied.
■ In OpenGL, the transformation specified most recently is the one applied first.
■ In each step:
– C <= I
– C <= CT(4.0, 5.0, 6.0)
– C <= CR(45, 1.0, 2.0, 3.0)
– C < = CT(-4.0, -5.0, -6.0)
■ Finally
– C = T(4.0, 5.0, 6.0) CR(45, 1.0, 2.0, 3.0) CT(-4.0, -5.0, -6.0)
COMPUTER GRAPHICS
501472-3
Lecture 7- 2D/3D deformation
Deformation

• Deformation means transformation that do not preserve the original


shape. Deformation such as:
• Shearing

• Other 3D deformations are:


• Tapering
• Twisting
• Bending
Deformation

■ A transformation that slants the shape of an object is called the shear


transformation.
■ Primarily, there are two shear transformations X-Shear and Y-Shear.
■ One shifts X coordinates values and other shifts Y coordinate values.
■ However; in both cases only one coordinate changes its coordinates and other
preserves its values. Shearing is also termed as Skewing.
Shearing

■ X-Shear
■ The X-Shear preserves the Y coordinate, and changes are made to X
coordinates, which causes the vertical lines to tilt right or left as shown in
below figure.
Shearing

The transformation matrix for X-Shear can be represented as in 2D:

X’ = X + Shx . Y
Y’ = Y

For 3D, X-Shear is represented as :


1 𝑠ℎ𝑥 0 0
0 1 0 0
𝑋𝑠ℎ =
0 0 1 0
0 0 0 1
Shearing

■ Y-Shear
■ Similarly, the Y-Shear preserves the X coordinate and changes are made to Y
coordinates, which causes the horizontal lines to tilt up or down as shown in
below figure.
1 0 0 0
𝑠ℎ𝑦 1 0 0
𝑌𝑠ℎ =
0 0 1 0
0 0 0 1

X’ = X
Y’ = Y + Shy . X
Deformation - Shearing

■ Example: Consider the following square:

0, 2 2, 2

0, 0 2, 0

■ Draw the square after a shearing in the x-direction with a factor of 3.


Deformation - Shearing

■ The vertices are: (0, 0), (2, 0), (8, 2), 6, 2):
■ The new vertices are:
– X= x + shx.Y
– Y= y
■ (0,2) → x =6, y=2
■ (2,2) → x=8, y=2
■ (0,0) → remains unchanged (bottom-left).
■ (2,0) → remains unchanged (bottom-right).
Deformation - Shearing

• In Opengl, there is no function to do shearing.


• However, Opengl, provide some functions that we can use to do shearing.
• We follow these steps for shearing:
• Define the Shearing Matrix: A basic example of a shearing matrix in 2D (ignoring the
Z-axis) that would shear along the x-axis would look like this:

1 𝑠ℎ𝑥 0 0
0 1 0 0
𝑋𝑠ℎ =
0 0 1 0
0 0 0 1
Deformation - Shearing

• glMultMatrixf(m): This function multiply the current transformation matrix with


shearMatrix. We can define shearMatrix as follows:
• shearMatrix[16] = { 1, 0, 0, 0,
shx, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
Deformation - Shearing

■ Another thing about OpenGL, is that it will consider the matrix in column-major order.
So, OpenGL stores matrices as (in transpose form):

m[0] m[4] m[8] m[12]


m[1] m[5] m[9] m[13]

m[2] m[6] m[10] m[14]
 
m[7] m[11] m[15]
m[3]
Deformation - Shearing

■ The transformation matrix for the shearing, is stored in OpenGl in a transpose form.
Therefore, shearing in the x- direction as:

T
1 a 0 0 1 0 0 0
0 
1 0 0 a 1 0 0
 =
0 0 1 0 0 0 1 0
0  0 
 0 0 1  0 0 1
Deformation - Shearing
GLfloat shearMatrix[16] = { 1, 0, 0, 0,
3, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 };
glPushMatrix(); // Save the current matrix on the stack
// Multiply the current matrix(by the shearing matrix
glMultMatrixf(shearMatrix);
// Draw a square that will be sheared along the x-axis
glBegin(GL_QUADS);
glVertex2f(-2, -2);
glVertex2f(2, -2);
glVertex2f(2, 2);
glVertex2f(-2, 2);
glEnd(); // Restore the original matrix
glPopMatrix();
COMPUTER GRAPHICS
501472-3
Lecture 9- Light
Lighting Models and Shading
■ For visual realism, lighting models
Ambient lighting :
have been developed to illuminate
the surfaces of solid models
■ These models incorporate
– ambient lighting and illumination
incident reflected light
– diffuse reflection of directional
light
lighting
– specular reflection of directional
lighting
incident reflected light
light

2
Light Source
Ray Tracing Shadow Ray
Eye
Object
Eye Ray

Shadow Ray
Object
Light Source
■ Ray tracing traces a ray of
light from the eye to a light
source
■ Ray tracing realistically
renders scenes with shiny
and transparent objects

3
Radiosity
■ Diffuse illumination
results from the
absorption and reflection
of diffuse light from many
objects in the scene
■ Radiosity uses thermal
models of emission and
reflection of radiation to Radiosity is very good at rendering
accurately calculate architectural interiors
diffuse lighting

4
Light source Light
Object
sun
Light
rays
• Light source can be either:
– A light at some specified position (Positional light)

– Sun which is considered as a light source at an infinite position (Directional light)

• Light source has a color, in Opengl it is called: diffuse color.

• In Opengl, you can define 8‐light sources, they are called: GL_LIGHT0, GL_LIGHT1,
GL_LIGHT2, …, GL_LIGHT7
Enable light in Opengl

• In order to work with light in Opengl, we should enable the lighting, this is
done by writing:
– glEnable(GL_LIGHTING).

• Then we need to enable the light source. For example, to enable light
source zero, we write:
– glEnable(GL_LIGHT0)
Different light source

• Each light can be configured with different parameters, such as:


– Diffuse light: The color of the light that comes directly from the light
source.
– Ambient light: The general color of the light that is present in all directions
in a scene (source is unknown).
– Specular light: which is the shininess of the light source on the object.
Diffuse Light

■ Diffuse light: which is the color of the light that is directly falling on objects.
Ambient Light

■ Ambient light: is the light that is reflected many times such that its source is
unknown, then fall on objects.
Specular Light

■ Specular light: which is the shininess of the light source on the object.
Shading

■ Flat Shading
– Calculate one lighting calculation (pick a vertex) per triangle
– Color the entire triangle the same color
■ Gouraud Shading
– Calculate three lighting calculations (the vertices) per triangle
– Linearly interpolate the colors as you scan convert
■ Phong Shading
– While do scan convert, linearly interpolate the normals.
– With the interpolated normal at each pixel, calculate the lighting at each
pixel
Opengl functions forlight

• Opengl uses the following function to set the light:


– glLightfv(light_source, property_name, property_value);

• Example:
• To set the position of the light source light0, we write:
GLfloat light_position[] = {1.0, 1.0, 1.0} \\ white
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
• This will set the light source GL_LIGHT0 to be at position (1, 1, 1).
Opengl functions forlight

• To set the specular color of light0:

GLfloat light_specular_color[] = {1, 1, 1, 1}


glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular_color);

– This will set the specular light color to white.


Opengl functions forlight

• To set the color of light0:


GLfloat light_diffuse_color[] = {1, 0, 0, 0}
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse_color);
– This will set the light color to red.

• To set the ambient light color, we write:


GLfloat light_ambient_color[] = {1, 0, 0, 0}
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient_color);
– This will set the ambient light color to red.
Opengl functions formaterial

• In addition to the light color, we have material color for the object.
• We have the following for materials:
– Material color is called diffuse color.
– Material shininess color is called specular color

• To set the material color, we write:


glMaterial(front_face, material_property, material_value);
Opengl functions formaterial

• Example: To set the color of the material object, we write:


GLfloat mat_color[] = {1, 0, 0, 0}
glMaterial(GL_FRONT, GL_DIFFUSE, mat_color);
– This will set the material color to red.
Absorption & Reflection Of Color

• Let's say you're looking at a red car. The sun emits a ray of white light.

• The ray bounces off the car and goes into your eye. Your eye detects that the
ray only contains red light, which is why you see a red car instead of a white
car.

• We know that white light contains all colors, so what happened to the green
and blue? The green and blue light was absorbed by the surface, and the
red light was reflected.
Absorption & Reflection Of Color

• When a light source with a color (such as red) illuminates a material with a different
color (like blue), the resulting color seen by the viewer is determined by the
interaction between the two colors.
• This interaction typically involves a component-wise multiplication of the light's color
with the material's color, a process known as "color blending.
• Resulting Diffuse Color:
• Red Component: 1 (light) * 0 (material) = 0
• Green Component: 0 (light) * 0 (material) = 0
• Blue Component: 0 (light) * 1 (material) = 0
• So, the resulting color will be (0, 0, 0) in RGB, which is black.
Absorption & Reflection OfColor

•Red Component: 1 (light) * 1 (material) = 1


•Green Component: 1 (light) * 0 (material) = 0
•Blue Component: 1 (light) * 0 (material) = 0
Absorption & Reflection OfColor

• What if we were to shine a pure cyan (blue + green) light on the red car? If
the car was pure red, it would look black, because it would absorb 100% of
the light.
Absorption & Reflection OfColor

• What about a cyan (blue + green) (0,1,1) light on a magenta (red + blue)
surface? Magenta color is (1, 0, 1). So green is absorbed and blue is
reflected.
Steps to Set the Light inOpengl

• Enable light and light source:


glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
• Enable depth test to test the objects at the front and the object at the back of a
scene:
glEnable(GL_DEPTH_TEST);
• Set the light color:
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse_color);
• Set the ambient color (optional):
glLightfv(GL_LIGHT0, GL_AMBIENT, ambient_color);
Steps to Set the Light inOpengl

• Set the specular color (optional):


glLightfv(GL_LIGHT0, GL_SPECULAR, specular_color);
• Set the material color:
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_color);
• Set the material sepcular color, optional:
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
• Set the material ambient color, optional:
glMaterial(GL_FRONT, GL_AMBIENT, mat_ambient);
Steps to Set the Light inOpengl

Assume we have the following colors setting:

GLfloat cyan[] = {0, 0.8f, 0.8f, 1};


GLfloat red[] = {1.0f, 0.0f, 0.0f, 1};
GLfloat green[] = {0.0f, 1.0f, 0.0f, 1};
GLfloat blue[] = {0.0f, 0.0f, 1.0f, 1};
GLfloat yellow[] = {1.0f, 0.0f, 1.0f, 1};
GLfloat white[] = {1.0f, 1.0f, 1.0f, 1};
GLfloat black[] = {0.0f, 0.0f, 0.0f, 1};
GLfloat shininess[] = {50.0};
Code Example: white lightsource

Now, consider the following OpenGL code:


// material color is blue
glMaterialfv(GL_FRONT, GL_DIFFUSE, blue);
//light source position is (1, 1, 1) (space not direction)
GLfloat position[] = { 1.0, 1.0, 1.0, 1.0 };
glLightfv(GL_LIGHT0, GL_POSITION, position);
// light source color is white:
glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
glutSolidSphere(1, 30, 30);
glFlush ();
Adding white ambientlight

Now, consider the following OpenGL code:


// material color is blue
glMaterialfv(GL_FRONT, GL_DIFFUSE, blue);
//light source position is (1, 1, 1) (space not direction)
GLfloat position[] = { 1.0, 1.0, 1.0, 1.0 };
glLightfv(GL_LIGHT0, GL_POSITION, position);
// light source color is white:
glLightfv(GL_LIGHT0, GL_DIFFUSE, white);

glLightfv(GL_LIGHT0, GL_AMBIENT, white);


glutSolidSphere(1, 30, 30);
glFlush ();
Adding white ambientlight

Now, consider the following openglcode:

// material color is blue:

glMaterialfv(GL_FRONT, GL_DIFFUSE, blue);


glMaterialfv(GL_FRONT, GL_SPECULAR, white);
glMaterialfv(GL_FRONT, GL_SHININESS, shininess);

//light source position is (1, 1, 1)

GLfloat position[] = { 1.0, 1.0, 1.0, 1.0 };

glLightfv(GL_LIGHT0, GL_POSITION, position);


// light source and ambient color is white:

glLightfv(GL_LIGHT0, GL_DIFFUSE, white);

glLightfv(GL_LIGHT0, GL_AMBIENT, white);


glutSolidSphere(1, 30, 30);
glFlush ();
Texture Mapping
■ For realism, photographic textures are “mapped” onto the surfaces of objects
■ Example textures:
– woodgrain
– concrete texture
– grass mapping
– marble
■ Texture mapping is very computationally intensive
reflections

shadows

37
Example of Shading

Wireframe Flat Shaded

Smooth Shaded Shadows

38
Texture Mapping in OpenGL

■ Steps in Texture Mapping


– Create a texture object and specify a texture for that object.
– Indicate how the texture is to be applied to each pixel.
– Enable texture mapping.
– Draw the scene, supplying both texture and geometric coordinates.
■ Keep in mind that texture mapping works only in RGBA mode. Texture mapping
results in color-index mode are undefined.
Specifying the Texture

■ GLubyte image[rows][cols]
void glTexImage2D (GLenum target, GLint level, GLint
internalFormat, GLsizei width, GLsizei height, GLint
border, GLenum format, GLenum type, const GLvoid
*pixels)
■ Note: both width and height must have the form 2m+2b, where m is
nonnegative integer, and b is the value of board.
Texture Object

■ Texture objects are an important new feature since OpenGL 1.1. A texture object
stores data and makes it readily available.
■ To use texture objects for your texture data, take these steps:
– Generate texture names.
– Initially bind (create) texture objects to texture data, including the image
arrays and texture properties.
– Bind and rebind texture objects, making their data currently available for
rendering texture models.
Naming a Texture Object

■ Any nonzero unsigned integer may be used as a texture name. To avoid


accidentally resulting names, consistently use glGenTexture() to provide unused
texture names.

void glGenTextures (Glsizei n, GLuint *textureNames)


Creating and Using Texture Object

■ The same routine, glBindTexture(), both creates and uses texture objects.
void glBindTexture (GLenum target, GLuint textureName)
■ When using it first time, a new texture object is created. When binding to
previously created texture object, that texture object becomes active.
■ Example:
glBindTexture(GL_TEXTURE_2D, name);
Cleaning Up Texture Object

void glDeleteTexture (GLsizei n, const GLuint textureNames)

Delete n texture object, named by elements in the array textureNames. The


freed texture names may now be reused.
Texture Mapping Process
Rendering the Texture

■ Rendering texture is similar to shading: It proceeds across the surface pixel-by pixel.
For each pixel, it must determine the corresponding texture coordinates (s, t), access
the texture, and set the pixel to the proper texture color.
Combining Lighting and Texturing

■ There is no lighting involved with texture Mapping


■ They are independent operations, which may be combined
■ It all depends on how to “apply” the texture to the underlying triangle
■ Set the current texturing function.
void glTexEnv (GLenum target, GLenum pname, TYPE param)
■ We can use directly the texture colors to paint the object, or use the texture values
to modulate or blend the color in the texture map with the original color of object.
■ Example:
glTexEnv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND)
Assigning Texture Coordinates

void glTexCoord* (TYPE coords)


■ Sets the current texture coordinates. Subsequent calls to glVertex*() result in
those vertices being assigning the current texture coordinates.
glBegin(GL_QUAN) {
glTexCoord2f (0, 0); glVertex2f (0, 0, 5);
glTexCoord2f (1, 0); glVertex2f (10, 0, 5);
glTexCoord2f (1, 1); glVertex2f (10, 10, 5);
glTexCoord2f (0, 1); glVertex2f (0, 10, 5);
}
Remember to Enable Texture

■ glEnable (GL_TEXTURE_2D)
■ glDisable (GL_TEXTURE_2D)
■ Enable/disable texture mapping
Automatic Texture-Coordinate Generation

■ OpenGL can automatically generate texture coordinate for you.


■ void glTexGen* (GLenum coord, GLenum pname, TYPE param)
■ Specifies the function for automatically generating texture coordinates.
■ coord: GL_S, GL_T, GL_R, GL_Q
Summary

■ Objects within a scene must be clipped to display the scene in a window


■ Because there are can be so many objects clipping must be extremely efficient
■ The Cohen-Sutherland algorithm can be used for line clipping
■ The Sutherland-hodgman Algorithm can be used for polygon clipping

You might also like