Description:- In this algorithm, we are given 9 regions on the screen. Out of which one region is of the window and the rest 8 regions are around it given by 4 digit binary. The division of the regions are based on (x_max, y_max) and (x_min, y_min).
The central part is the viewing region or window, all the lines which lie within this region are completely visible. A region code is always assigned to the endpoints of the given line.
To check whether the line is visible or not.
Region CodesFormula to check binary digits:- TBRL which can be defined as top, bottom, right, and left accordingly.
TBRL RuleAlgorithm
Steps
1) Assign the region codes to both endpoints.
2) Perform OR operation on both of these endpoints.
3) if OR = 0000,
then it is completely visible (inside the window).
else
Perform AND operation on both these endpoints.
i) if AND ? 0000,
then the line is invisible and not inside the window. Also, it can't be considered for clipping.
ii) else
AND = 0000, the line is partially inside the window and considered for clipping.
4) After confirming that the line is partially inside the window, then we find the intersection with the boundary of the window. By using the following formula:-
Slope:- m= (y2-y1)/(x2-x1)
a) If the line passes through top or the line intersects with the top boundary of the window.
x = x + (y_wmax - y)/m
y = y_wmax
b) If the line passes through the bottom or the line intersects with the bottom boundary of the window.
x = x + (y_wmin - y)/m
y = y_wmin
c) If the line passes through the left region or the line intersects with the left boundary of the window.
y = y+ (x_wmin - x)*m
x = x_wmin
d) If the line passes through the right region or the line intersects with the right boundary of the window.
y = y + (x_wmax -x)*m
x = x_wmax
5) Now, overwrite the endpoints with a new one and update it.
6) Repeat the 4th step till your line doesn't get completely clipped
Given a set of lines and a rectangular area of interest, the task is to remove lines that are outside the area of interest and clip the lines which are partially inside the area.
Input : Rectangular area of interest (Defined by
below four values which are coordinates of
bottom left and top right)
x_min = 4, y_min = 4, x_max = 10, y_max = 8
A set of lines (Defined by two corner coordinates)
line 1 : x1 = 5, y1 = 5, x2 = 7, y2 = 7
Line 2 : x1 = 7, y1 = 9, x2 = 11, y2 = 4
Line 2 : x1 = 1, y1 = 5, x2 = 4, y2 = 1
Output : Line 1 : Accepted from (5, 5) to (7, 7)
Line 2 : Accepted from (7.8, 8) to (10, 5.25)
Line 3 : Rejected
Cohen-Sutherland algorithm divides a two-dimensional space into 9 regions and then efficiently determines the lines and portions of lines that are inside the given rectangular area.
The algorithm can be outlines as follows:-
Nine regions are created, eight "outside" regions and one
"inside" region.
For a given line extreme point (x, y), we can quickly
find its region's four bit code. Four bit code can
be computed by comparing x and y with four values
(x_min, x_max, y_min and y_max).
If x is less than x_min then bit number 1 is set.
If x is greater than x_max then bit number 2 is set.
If y is less than y_min then bit number 3 is set.
If y is greater than y_max then bit number 4 is set

There are three possible cases for any given line.
- Completely inside the given rectangle : Bitwise OR of region of two end points of line is 0 (Both points are inside the rectangle)
- Completely outside the given rectangle : Both endpoints share at least one outside region which implies that the line does not cross the visible region. (bitwise AND of endpoints != 0).
- Partially inside the window : Both endpoints are in different regions. In this case, the algorithm finds one of the two points that is outside the rectangular region. The intersection of the line from outside point and rectangular window becomes new corner point and the algorithm repeats

Pseudo Code:
Step 1 : Assign a region code for two endpoints of given line.
Step 2 : If both endpoints have a region code 0000
then given line is completely inside.
Step 3 : Else, perform the logical AND operation for both region codes.
Step 3.1 : If the result is not 0000, then given line is completely
outside.
Step 3.2 : Else line is partially inside.
Step 3.2.1 : Choose an endpoint of the line
that is outside the given rectangle.
Step 3.2.2 : Find the intersection point of the
rectangular boundary (based on region code).
Step 3.2.3 : Replace endpoint with the intersection point
and update the region code.
Step 3.2.4 : Repeat step 2 until we find a clipped line either
trivially accepted or trivially rejected.
Step 4 : Repeat step 1 for other lines
Below is implementation of above steps.
C++
// C++ program to implement Cohen Sutherland algorithm
// for line clipping.
#include <iostream>
using namespace std;
// Defining region codes
const int INSIDE = 0; // 0000
const int LEFT = 1; // 0001
const int RIGHT = 2; // 0010
const int BOTTOM = 4; // 0100
const int TOP = 8; // 1000
// Defining x_max, y_max and x_min, y_min for
// clipping rectangle. Since diagonal points are
// enough to define a rectangle
const int x_max = 10;
const int y_max = 8;
const int x_min = 4;
const int y_min = 4;
// Function to compute region code for a point(x, y)
int computeCode(double x, double y)
{
// initialized as being inside
int code = INSIDE;
if (x < x_min) // to the left of rectangle
code |= LEFT;
else if (x > x_max) // to the right of rectangle
code |= RIGHT;
if (y < y_min) // below the rectangle
code |= BOTTOM;
else if (y > y_max) // above the rectangle
code |= TOP;
return code;
}
// Implementing Cohen-Sutherland algorithm
// Clipping a line from P1 = (x2, y2) to P2 = (x2, y2)
void cohenSutherlandClip(double x1, double y1,
double x2, double y2)
{
// Compute region codes for P1, P2
int code1 = computeCode(x1, y1);
int code2 = computeCode(x2, y2);
// Initialize line as outside the rectangular window
bool accept = false;
while (true) {
if ((code1 == 0) && (code2 == 0)) {
// If both endpoints lie within rectangle
accept = true;
break;
}
else if (code1 & code2) {
// If both endpoints are outside rectangle,
// in same region
break;
}
else {
// Some segment of line lies within the
// rectangle
int code_out;
double x, y;
// At least one endpoint is outside the
// rectangle, pick it.
if (code1 != 0)
code_out = code1;
else
code_out = code2;
// Find intersection point;
// using formulas y = y1 + slope * (x - x1),
// x = x1 + (1 / slope) * (y - y1)
if (code_out & TOP) {
// point is above the clip rectangle
x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1);
y = y_max;
}
else if (code_out & BOTTOM) {
// point is below the rectangle
x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1);
y = y_min;
}
else if (code_out & RIGHT) {
// point is to the right of rectangle
y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1);
x = x_max;
}
else if (code_out & LEFT) {
// point is to the left of rectangle
y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1);
x = x_min;
}
// Now intersection point x, y is found
// We replace point outside rectangle
// by intersection point
if (code_out == code1) {
x1 = x;
y1 = y;
code1 = computeCode(x1, y1);
}
else {
x2 = x;
y2 = y;
code2 = computeCode(x2, y2);
}
}
}
if (accept) {
cout << "Line accepted from " << x1 << ", "
<< y1 << " to " << x2 << ", " << y2 << endl;
// Here the user can add code to display the rectangle
// along with the accepted (portion of) lines
}
else
cout << "Line rejected" << endl;
}
// Driver code
int main()
{
// First Line segment
// P11 = (5, 5), P12 = (7, 7)
cohenSutherlandClip(5, 5, 7, 7);
// Second Line segment
// P21 = (7, 9), P22 = (11, 4)
cohenSutherlandClip(7, 9, 11, 4);
// Third Line segment
// P31 = (1, 5), P32 = (4, 1)
cohenSutherlandClip(1, 5, 4, 1);
return 0;
}
Java
// Java program to implement Cohen Sutherland algorithm
// for line clipping.
import java.io.*;
class GFG {
// Defining region codes
static final int INSIDE = 0; // 0000
static final int LEFT = 1; // 0001
static final int RIGHT = 2; // 0010
static final int BOTTOM = 4; // 0100
static final int TOP = 8; // 1000
// Defining x_max, y_max and x_min, y_min for
// clipping rectangle. Since diagonal points are
// enough to define a rectangle
static final int x_max = 10;
static final int y_max = 8;
static final int x_min = 4;
static final int y_min = 4;
// Function to compute region code for a point(x, y)
static int computeCode(double x, double y)
{
// initialized as being inside
int code = INSIDE;
if (x < x_min) // to the left of rectangle
code |= LEFT;
else if (x > x_max) // to the right of rectangle
code |= RIGHT;
if (y < y_min) // below the rectangle
code |= BOTTOM;
else if (y > y_max) // above the rectangle
code |= TOP;
return code;
}
// Implementing Cohen-Sutherland algorithm
// Clipping a line from P1 = (x2, y2) to P2 = (x2, y2)
static void cohenSutherlandClip(double x1, double y1,
double x2, double y2)
{
// Compute region codes for P1, P2
int code1 = computeCode(x1, y1);
int code2 = computeCode(x2, y2);
// Initialize line as outside the rectangular window
boolean accept = false;
while (true) {
if ((code1 == 0) && (code2 == 0)) {
// If both endpoints lie within rectangle
accept = true;
break;
}
else if ((code1 & code2) != 0) {
// If both endpoints are outside rectangle,
// in same region
break;
}
else {
// Some segment of line lies within the
// rectangle
int code_out;
double x = 0, y = 0;
// At least one endpoint is outside the
// rectangle, pick it.
if (code1 != 0)
code_out = code1;
else
code_out = code2;
// Find intersection point;
// using formulas y = y1 + slope * (x - x1),
// x = x1 + (1 / slope) * (y - y1)
if ((code_out & TOP) != 0) {
// point is above the clip rectangle
x = x1
+ (x2 - x1) * (y_max - y1)
/ (y2 - y1);
y = y_max;
}
else if ((code_out & BOTTOM) != 0) {
// point is below the rectangle
x = x1
+ (x2 - x1) * (y_min - y1)
/ (y2 - y1);
y = y_min;
}
else if ((code_out & RIGHT) != 0) {
// point is to the right of rectangle
y = y1
+ (y2 - y1) * (x_max - x1)
/ (x2 - x1);
x = x_max;
}
else if ((code_out & LEFT) != 0) {
// point is to the left of rectangle
y = y1
+ (y2 - y1) * (x_min - x1)
/ (x2 - x1);
x = x_min;
}
// Now intersection point x, y is found
// We replace point outside rectangle
// by intersection point
if (code_out == code1) {
x1 = x;
y1 = y;
code1 = computeCode(x1, y1);
}
else {
x2 = x;
y2 = y;
code2 = computeCode(x2, y2);
}
}
}
if (accept) {
System.out.println("Line accepted from " + x1
+ ", " + y1 + " to " + x2
+ ", " + y2);
// Here the user can add code to display the
// rectangle along with the accepted (portion
// of) lines
}
else
System.out.println("Line rejected");
}
public static void main(String[] args)
{
// First Line segment
// P11 = (5, 5), P12 = (7, 7)
cohenSutherlandClip(5, 5, 7, 7);
// Second Line segment
// P21 = (7, 9), P22 = (11, 4)
cohenSutherlandClip(7, 9, 11, 4);
// Third Line segment
// P31 = (1, 5), P32 = (4, 1)
cohenSutherlandClip(1, 5, 4, 1);
}
}
// This code is contributed by jain_mudit.
C#
using System;
public class GFG{
// C# program to implement Cohen Sutherland algorithm
// for line clipping.
// Defining region codes
public const int INSIDE = 0; // 0000
public const int LEFT = 1; // 0001
public const int RIGHT = 2; // 0010
public const int BOTTOM = 4; // 0100
public const int TOP = 8; // 1000
// Defining x_max, y_max and x_min, y_min for
// clipping rectangle. Since diagonal points are
// enough to define a rectangle
public const int x_max = 10;
public const int y_max = 8;
public const int x_min = 4;
public const int y_min = 4;
// Function to compute region code for a point(x, y)
public static int computeCode(double x, double y)
{
// initialized as being inside
int code = INSIDE;
if (x < x_min) // to the left of rectangle
code |= LEFT;
else if (x > x_max) // to the right of rectangle
code |= RIGHT;
if (y < y_min) // below the rectangle
code |= BOTTOM;
else if (y > y_max) // above the rectangle
code |= TOP;
return code;
}
// Implementing Cohen-Sutherland algorithm
// Clipping a line from P1 = (x2, y2) to P2 = (x2, y2)
public static void cohenSutherlandClip(double x1, double y1,
double x2, double y2)
{
// Compute region codes for P1, P2
int code1 = computeCode(x1, y1);
int code2 = computeCode(x2, y2);
// Initialize line as outside the rectangular window
bool accept = false;
while (true) {
if ((code1 == 0) && (code2 == 0)) {
// If both endpoints lie within rectangle
accept = true;
break;
}
else if ((code1 & code2)!=0) {
// If both endpoints are outside rectangle,
// in same region
break;
}
else {
// Some segment of line lies within the
// rectangle
int code_out;
double x=0.0;
double y=0.0;
// At least one endpoint is outside the
// rectangle, pick it.
if (code1 != 0)
code_out = code1;
else
code_out = code2;
// Find intersection point;
// using formulas y = y1 + slope * (x - x1),
// x = x1 + (1 / slope) * (y - y1)
if ((code_out & TOP)!=0) {
// point is above the clip rectangle
x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1);
y = y_max;
}
else if ((code_out & BOTTOM)!=0) {
// point is below the rectangle
x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1);
y = y_min;
}
else if ((code_out & RIGHT)!=0) {
// point is to the right of rectangle
y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1);
x = x_max;
}
else if ((code_out & LEFT)!=0) {
// point is to the left of rectangle
y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1);
x = x_min;
}
// Now intersection point x, y is found
// We replace point outside rectangle
// by intersection point
if (code_out == code1) {
x1 = x;
y1 = y;
code1 = computeCode(x1, y1);
}
else {
x2 = x;
y2 = y;
code2 = computeCode(x2, y2);
}
}
}
if (accept) {
Console.WriteLine("Line accepted from "+x1+", "
+y1+" to "+x2+", "+y2);
// Here the user can add code to display the rectangle
// along with the accepted (portion of) lines
}
else
Console.WriteLine("Line rejected");
}
// Driver code
static public void Main (){
// First Line segment
// P11 = (5, 5), P12 = (7, 7)
cohenSutherlandClip(5, 5, 7, 7);
// Second Line segment
// P21 = (7, 9), P22 = (11, 4)
cohenSutherlandClip(7, 9, 11, 4);
// Third Line segment
// P31 = (1, 5), P32 = (4, 1)
cohenSutherlandClip(1, 5, 4, 1);
}
}
// This code is contributed by akashish__
JavaScript
// JavaScript program to implement Cohen Sutherland algorithm
// for line clipping.
// Defining region codes
const INSIDE = 0; // 0000
const LEFT = 1; // 0001
const RIGHT = 2; // 0010
const BOTTOM = 4; // 0100
const TOP = 8; // 1000
// Defining x_max, y_max and x_min, y_min for
// clipping rectangle. Since diagonal points are
// enough to define a rectangle
const x_max = 10;
const y_max = 8;
const x_min = 4;
const y_min = 4;
// Function to compute region code for a point(x, y)
function computeCode(x, y)
{
// initialized as being inside
let code = INSIDE;
if (x < x_min) // to the left of rectangle
code |= LEFT;
else if (x > x_max) // to the right of rectangle
code |= RIGHT;
if (y < y_min) // below the rectangle
code |= BOTTOM;
else if (y > y_max) // above the rectangle
code |= TOP;
return code;
}
// Implementing Cohen-Sutherland algorithm
// Clipping a line from P1 = (x2, y2) to P2 = (x2, y2)
function cohenSutherlandClip(x1, y1, x2, y2)
{
// Compute region codes for P1, P2
let code1 = computeCode(x1, y1);
let code2 = computeCode(x2, y2);
// Initialize line as outside the rectangular window
let accept = false;
while (true) {
if ((code1 == 0) && (code2 == 0)) {
// If both endpoints lie within rectangle
accept = true;
break;
}
else if (code1 & code2) {
// If both endpoints are outside rectangle,
// in same region
break;
}
else {
// Some segment of line lies within the
// rectangle
let code_out;
let x, y;
// At least one endpoint is outside the
// rectangle, pick it.
if (code1 != 0)
code_out = code1;
else
code_out = code2;
// Find intersection point;
// using formulas y = y1 + slope * (x - x1),
// x = x1 + (1 / slope) * (y - y1)
if (code_out & TOP) {
// point is above the clip rectangle
x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1);
y = y_max;
}
else if (code_out & BOTTOM) {
// point is below the rectangle
x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1);
y = y_min;
}
else if (code_out & RIGHT) {
// point is to the right of rectangle
y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1);
x = x_max;
}
else if (code_out & LEFT) {
// point is to the left of rectangle
y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1);
x = x_min;
}
// Now intersection point x, y is found
// We replace point outside rectangle
// by intersection point
if (code_out == code1) {
x1 = x;
y1 = y;
code1 = computeCode(x1, y1);
}
else {
x2 = x;
y2 = y;
code2 = computeCode(x2, y2);
}
}
}
if (accept) {
console.log("Line accepted from", x1, ",", y1, "to", x2, ",", y2);
// Here the user can add code to display the rectangle
// along with the accepted (portion of) lines
}
else
console.log("Line rejected");
}
// Driver code
// First Line segment
// P11 = (5, 5), P12 = (7, 7)
cohenSutherlandClip(5, 5, 7, 7);
// Second Line segment
// P21 = (7, 9), P22 = (11, 4)
cohenSutherlandClip(7, 9, 11, 4);
// Third Line segment
// P31 = (1, 5), P32 = (4, 1)
cohenSutherlandClip(1, 5, 4, 1);
// The code is contributed by Nidhi goel
Python3
# Python program to implement Cohen Sutherland algorithm
# for line clipping.
# Defining region codes
INSIDE = 0 # 0000
LEFT = 1 # 0001
RIGHT = 2 # 0010
BOTTOM = 4 # 0100
TOP = 8 # 1000
# Defining x_max, y_max and x_min, y_min for rectangle
# Since diagonal points are enough to define a rectangle
x_max = 10.0
y_max = 8.0
x_min = 4.0
y_min = 4.0
# Function to compute region code for a point(x, y)
def computeCode(x, y):
code = INSIDE
if x < x_min: # to the left of rectangle
code |= LEFT
elif x > x_max: # to the right of rectangle
code |= RIGHT
if y < y_min: # below the rectangle
code |= BOTTOM
elif y > y_max: # above the rectangle
code |= TOP
return code
# Implementing Cohen-Sutherland algorithm
# Clipping a line from P1 = (x1, y1) to P2 = (x2, y2)
# Implementing Cohen-Sutherland algorithm
# Clipping a line from P1 = (x1, y1) to P2 = (x2, y2)
def cohenSutherlandClip(x1, y1, x2, y2):
# Compute region codes for P1, P2
code1 = computeCode(x1, y1)
code2 = computeCode(x2, y2)
accept = False
while True:
# If both endpoints lie within rectangle
if code1 == 0 and code2 == 0:
accept = True
break
# If both endpoints are outside rectangle
elif (code1 & code2) != 0:
break
# Some segment lies within the rectangle
else:
# Line needs clipping
# At least one of the points is outside,
# select it
x = 1.0
y = 1.0
if code1 != 0:
code_out = code1
else:
code_out = code2
# Find intersection point
# using formulas y = y1 + slope * (x - x1),
# x = x1 + (1 / slope) * (y - y1)
if code_out & TOP:
# Point is above the clip rectangle
x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1)
y = y_max
elif code_out & BOTTOM:
# Point is below the clip rectangle
x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1)
y = y_min
elif code_out & RIGHT:
# Point is to the right of the clip rectangle
y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1)
x = x_max
elif code_out & LEFT:
# Point is to the left of the clip rectangle
y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1)
x = x_min
# Now intersection point (x, y) is found
# We replace point outside clipping rectangle
# by intersection point
if code_out == code1:
x1 = x
y1 = y
code1 = computeCode(x1, y1)
else:
x2 = x
y2 = y
code2 = computeCode(x2, y2)
if accept:
print("Line accepted from %.2f, %.2f to %.2f, %.2f" % (x1, y1, x2, y2))
# Here the user can add code to display the rectangle
# along with the accepted (portion of) lines
else:
print("Line rejected")
# Driver script
# First line segment
# P11 = (5, 5), P12 = (7, 7)
cohenSutherlandClip(5, 5, 7, 7)
# Second line segment
# P21 = (7, 9), P22 = (11, 4)
cohenSutherlandClip(7, 9, 11, 4)
# Third line segment
# P31 = (1, 5), P32 = (4, 1)
cohenSutherlandClip(1, 5, 4, 1)
Output:
Line accepted from 5.00, 5.00 to 7.00, 7.00
Line accepted from 7.80, 8.00 to 10.00, 5.25
Line rejected
Below is C++ code with Graphics using graphics.h
C++
// C++ program to implement Cohen Sutherland algorithm
// for line clipping.
// including libraries
#include <bits/stdc++.h>
#include <graphics.h>
using namespace std;
// Global Variables
int xmin, xmax, ymin, ymax;
// Lines where co-ordinates are (x1, y1) and (x2, y2)
struct lines {
int x1, y1, x2, y2;
};
// This will return the sign required.
int sign(int x)
{
if (x > 0)
return 1;
else
return 0;
}
// CohenSutherLand LineClipping Algorithm As Described in theory.
// This will clip the lines as per window boundaries.
void clip(struct lines mylines)
{
// arrays will store bits
// Here bits implies initial Point whereas byte implies end points
int bits[4], byte[4], i, var;
// setting color of graphics to be RED
setcolor(RED);
// Finding Bits
bits[0] = sign(xmin - mylines.x1);
byte[0] = sign(xmin - mylines.x2);
bits[1] = sign(mylines.x1 - xmax);
byte[1] = sign(mylines.x2 - xmax);
bits[2] = sign(ymin - mylines.y1);
byte[2] = sign(ymin - mylines.y2);
bits[3] = sign(mylines.y1 - ymax);
byte[3] = sign(mylines.y2 - ymax);
// initial will used for initial coordinates and end for final
string initial = "", end = "", temp = "";
// convert bits to string
for (i = 0; i < 4; i++) {
if (bits[i] == 0)
initial += '0';
else
initial += '1';
}
for (i = 0; i < 4; i++) {
if (byte[i] == 0)
end += '0';
else
end += '1';
}
// finding slope of line y=mx+c as (y-y1)=m(x-x1)+c
// where m is slope m=dy/dx;
float m = (mylines.y2 - mylines.y1) / (float)(mylines.x2 - mylines.x1);
float c = mylines.y1 - m * mylines.x1;
// if both points are inside the Accept the line and draw
if (initial == end && end == "0000") {
// inbuilt function to draw the line from(x1, y1) to (x2, y2)
line(mylines.x1, mylines.y1, mylines.x2, mylines.y2);
return;
}
// this will contain cases where line maybe totally outside for partially inside
else {
// taking bitwise end of every value
for (i = 0; i < 4; i++) {
int val = (bits[i] & byte[i]);
if (val == 0)
temp += '0';
else
temp += '1';
}
// as per algo if AND is not 0000 means line is completely outside hence draw nothing and return
if (temp != "0000")
return;
// Here contain cases of partial inside or outside
// So check for every boundary one by one
for (i = 0; i < 4; i++) {
// if both bit are same hence we cannot find any intersection with boundary so continue
if (bits[i] == byte[i])
continue;
// Otherwise there exist a intersection
// Case when initial point is in left xmin
if (i == 0 && bits[i] == 1) {
var = round(m * xmin + c);
mylines.y1 = var;
mylines.x1 = xmin;
}
// Case when final point is in left xmin
if (i == 0 && byte[i] == 1) {
var = round(m * xmin + c);
mylines.y2 = var;
mylines.x2 = xmin;
}
// Case when initial point is in right of xmax
if (i == 1 && bits[i] == 1) {
var = round(m * xmax + c);
mylines.y1 = var;
mylines.x1 = xmax;
}
// Case when final point is in right of xmax
if (i == 1 && byte[i] == 1) {
var = round(m * xmax + c);
mylines.y2 = var;
mylines.x2 = xmax;
}
// Case when initial point is in top of ymin
if (i == 2 && bits[i] == 1) {
var = round((float)(ymin - c) / m);
mylines.y1 = ymin;
mylines.x1 = var;
}
// Case when final point is in top of ymin
if (i == 2 && byte[i] == 1) {
var = round((float)(ymin - c) / m);
mylines.y2 = ymin;
mylines.x2 = var;
}
// Case when initial point is in bottom of ymax
if (i == 3 && bits[i] == 1) {
var = round((float)(ymax - c) / m);
mylines.y1 = ymax;
mylines.x1 = var;
}
// Case when final point is in bottom of ymax
if (i == 3 && byte[i] == 1) {
var = round((float)(ymax - c) / m);
mylines.y2 = ymax;
mylines.x2 = var;
}
// Updating Bits at every point
bits[0] = sign(xmin - mylines.x1);
byte[0] = sign(xmin - mylines.x2);
bits[1] = sign(mylines.x1 - xmax);
byte[1] = sign(mylines.x2 - xmax);
bits[2] = sign(ymin - mylines.y1);
byte[2] = sign(ymin - mylines.y2);
bits[3] = sign(mylines.y1 - ymax);
byte[3] = sign(mylines.y2 - ymax);
} // end of for loop
// Initialize initial and end to NULL
initial = "", end = "";
// Updating strings again by bit
for (i = 0; i < 4; i++) {
if (bits[i] == 0)
initial += '0';
else
initial += '1';
}
for (i = 0; i < 4; i++) {
if (byte[i] == 0)
end += '0';
else
end += '1';
}
// If now both points lie inside or on boundary then simply draw the updated line
if (initial == end && end == "0000") {
line(mylines.x1, mylines.y1, mylines.x2, mylines.y2);
return;
}
// else line was completely outside hence rejected
else
return;
}
}
// Driver Function
int main()
{
int gd = DETECT, gm;
// Setting values of Clipping window
xmin = 40;
xmax = 100;
ymin = 40;
ymax = 80;
// initialize the graph
initgraph(&gd, &gm, NULL);
// Drawing Window using Lines
line(xmin, ymin, xmax, ymin);
line(xmax, ymin, xmax, ymax);
line(xmax, ymax, xmin, ymax);
line(xmin, ymax, xmin, ymin);
// Assume 4 lines to be clipped
struct lines mylines[4];
// Setting the coordinated of 4 lines
mylines[0].x1 = 30;
mylines[0].y1 = 65;
mylines[0].x2 = 55;
mylines[0].y2 = 30;
mylines[1].x1 = 60;
mylines[1].y1 = 20;
mylines[1].x2 = 100;
mylines[1].y2 = 90;
mylines[2].x1 = 60;
mylines[2].y1 = 100;
mylines[2].x2 = 80;
mylines[2].y2 = 70;
mylines[3].x1 = 85;
mylines[3].y1 = 50;
mylines[3].x2 = 120;
mylines[3].y2 = 75;
// Drawing Initial Lines without clipping
for (int i = 0; i < 4; i++) {
line(mylines[i].x1, mylines[i].y1,
mylines[i].x2, mylines[i].y2);
delay(1000);
}
// Drawing clipped Line
for (int i = 0; i < 4; i++) {
// Calling clip() which in term clip the line as per window and draw it
clip(mylines[i]);
delay(1000);
}
delay(4000);
getch();
// For Closing the graph.
closegraph();
return 0;
}
Java
import java.util.ArrayList;
public class Main {
// Global Variables
static int xmin = 0, xmax = 0, ymin = 0, ymax = 0;
// Lines where co-ordinates are (x1, y1) and (x2, y2)
static class Lines {
int x1, y1, x2, y2;
public Lines(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
}
// This will return the sign required.
static int sign(int x) {
return x > 0 ? 1 : 0;
}
// CohenSutherLand LineClipping Algorithm As Described in theory.
// This will clip the lines as per window boundaries.
static void clip(Lines mylines) {
// arrays will store bits
// Here bits implies initial Point whereas byteArray implies end points
int[] bits = new int[4];
int[] byteArray = new int[4];
// Finding Bits
bits[0] = sign(xmin - mylines.x1);
byteArray[0] = sign(xmin - mylines.x2);
bits[1] = sign(mylines.x1 - xmax);
byteArray[1] = sign(mylines.x2 - xmax);
bits[2] = sign(ymin - mylines.y1);
byteArray[2] = sign(ymin - mylines.y2);
bits[3] = sign(mylines.y1 - ymax);
byteArray[3] = sign(mylines.y2 - ymax);
// initial will used for initial coordinates and end for final
String initial = "";
String end = "";
for (int bit : bits) {
initial += bit;
}
for (int b : byteArray) {
end += b;
}
String temp = "";
// finding slope of line y=mx+c as (y-y1)=m(x-x1)+c
// where m is slope m=dy/dx;
double m = (double)(mylines.y2 - mylines.y1) / (mylines.x2 - mylines.x1);
double c = mylines.y1 - m * mylines.x1;
// if both points are inside the Accept the line and draw
if (initial.equals(end) && end.equals("0000")) {
// plotting the line from (x1, y1) to (x2, y2)
System.out.println("Line from (" + mylines.x1 + ", " + mylines.y1 + ") to (" + mylines.x2 + ", " + mylines.y2 + ")");
return;
}
// this will contain cases where line maybe totally outside for partially inside
else {
// taking bitwise end of every value
for (int i = 0; i < 4; i++) {
int val = bits[i] & byteArray[i];
temp += val == 0 ? '0' : '1';
}
// as per algo if AND is not 0000 means line is completely outside hence draw nothing and return
if (!temp.equals("0000")) {
return;
}
// Here contain cases of partial inside or outside
// So check for every boundary one by one
for (int i = 0; i < 4; i++) {
// if both bit are same hence we cannot find any intersection with boundary so continue
if (bits[i] == byteArray[i]) {
continue;
}
// Otherwise there exist an intersection
// Case when initial point is in left xmin
if (i == 0 && bits[i] == 1) {
int tvar = (int)Math.round(m * xmin + c);
mylines.y1 = tvar;
mylines.x1 = xmin;
}
// Case when final point is in left xmin
if (i == 0 && byteArray[i] == 1) {
int tvar = (int)Math.round(m * xmin + c);
mylines.y2 = tvar;
mylines.x2 = xmin;
}
// Case when initial point is in right of xmax
if (i == 1 && bits[i] == 1) {
int tvar = (int)Math.round(m * xmax + c);
mylines.y1 = tvar;
mylines.x1 = xmax;
}
// Case when final point is in right of xmax
if (i == 1 && byteArray[i] == 1) {
int tvar = (int)Math.round(m * xmax + c);
mylines.y2 = tvar;
mylines.x2 = xmax;
}
// Case when initial point is in top of ymin
if (i == 2 && bits[i] == 1) {
int tvar = (int)Math.round((ymin - c) / m);
mylines.y1 = ymin;
mylines.x1 = tvar;
}
// Case when final point is in top of ymin
if (i == 2 && byteArray[i] == 1) {
int tvar = (int)Math.round((ymin - c) / m);
mylines.y2 = ymin;
mylines.x2 = tvar;
}
// Case when initial point is in bottom of ymax
if (i == 3 && bits[i] == 1) {
int tvar = (int)Math.round((ymax - c) / m);
mylines.y1 = ymax;
mylines.x1 = tvar;
}
// Case when final point is in bottom of ymax
if (i == 3 && byteArray[i] == 1) {
int tvar = (int)Math.round((ymax - c) / m);
mylines.y2 = ymax;
mylines.x2 = tvar;
}
// Updating Bits at every point
bits[0] = sign(xmin - mylines.x1);
byteArray[0] = sign(xmin - mylines.x2);
bits[1] = sign(mylines.x1 - xmax);
byteArray[1] = sign(mylines.x2 - xmax);
bits[2] = sign(ymin - mylines.y1);
byteArray[2] = sign(ymin - mylines.y2);
bits[3] = sign(mylines.y1 - ymax);
byteArray[3] = sign(mylines.y2 - ymax);
}
// If now both points lie inside or on boundary then simply draw the updated line
if (initial.equals(end) && end.equals("0000")) {
System.out.println("Line from (" + mylines.x1 + ", " + mylines.y1 + ") to (" + mylines.x2 + ", " + mylines.y2 + ")");
return;
}
// else line was completely outside hence rejected
else {
return;
}
}
}
// Driver Function
public static void main(String[] args) {
// Setting values of Clipping window
xmin = 40;
xmax = 100;
ymin = 40;
ymax = 80;
// Assume 4 lines to be clipped
ArrayList<Lines> mylines = new ArrayList<>();
// Setting the coordinates of 4 lines
mylines.add(new Lines(30, 65, 55, 30));
mylines.add(new Lines(60, 20, 100, 90));
mylines.add(new Lines(60, 100, 80, 70));
mylines.add(new Lines(85, 50, 120, 75));
// Drawing Initial Lines without clipping
for (Lines line : mylines) {
System.out.println("Line from (" + line.x1 + ", " + line.y1 + ") to (" + line.x2 + ", " + line.y2 + ")");
}
// Drawing clipped Line
for (Lines line : mylines) {
// Calling clip() which in term clip the line as per window and draw it
clip(line);
}
}
}
C#
using System;
// Class to represent a line with two points (x1, y1) and (x2, y2)
public class Lines
{
public double x1, y1, x2, y2;
public Lines(double x1, double y1, double x2, double y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
}
public class Program
{
// Define the window boundaries
static double xmin = 0, xmax = 0, ymin = 0, ymax = 0;
// Function to return 1 if x is greater than 0, and 0 otherwise
static int Sign(double x)
{
return x > 0 ? 1 : 0;
}
// Function to implement the Cohen-Sutherland algorithm
static void Clip(Lines mylines)
{
// Define the arrays to hold the bits for the initial and end points
int[] bits = new int[4];
int[] bytes = new int[4]; // Renamed 'byte' to 'bytes'
// Calculate the bits for the initial and end points
bits[0] = Sign(xmin - mylines.x1);
bytes[0] = Sign(xmin - mylines.x2);
bits[1] = Sign(mylines.x1 - xmax);
bytes[1] = Sign(mylines.x2 - xmax);
bits[2] = Sign(ymin - mylines.y1);
bytes[2] = Sign(ymin - mylines.y2);
bits[3] = Sign(mylines.y1 - ymax);
bytes[3] = Sign(mylines.y2 - ymax);
// Convert the bits to strings for comparison
string initial = string.Join("", bits);
string end = string.Join("", bytes);
string temp = "";
// Calculate the slope and y-intercept of the line
double m = (mylines.y2 - mylines.y1) / (mylines.x2 - mylines.x1);
double c = mylines.y1 - m * mylines.x1;
// If both points are inside the window, print the line
if (initial == end && end == "0000")
{
Console.WriteLine($"Line from ({mylines.x1}, {mylines.y1}) to ({mylines.x2}, {mylines.y2})");
return;
}
else
{
// Calculate the bitwise AND of the bits for the initial and end points
for (int i = 0; i < 4; i++)
{
int val = bits[i] & bytes[i]; // Changed '&&' to '&'
temp += val == 0 ? '0' : '1';
}
// If the line is completely outside the window, return
if (temp != "0000")
{
return;
}
// Check each boundary of the window
for (int i = 0; i < 4; i++)
{
// If the bit for the initial point is the same as the bit for the end point, continue
if (bits[i] == bytes[i])
{
continue;
}
// If the initial point is to the left of xmin, calculate the intersection with the left boundary
if (i == 0 && bits[i] == 1)
{
double tvar = Math.Round(m * xmin + c);
mylines.y1 = tvar;
mylines.x1 = xmin;
}
// If the end point is to the left of xmin, calculate the intersection with the left boundary
if (i == 0 && bytes[i] == 1)
{
double tvar = Math.Round(m * xmin + c);
mylines.y2 = tvar;
mylines.x2 = xmin;
}
// If the initial point is to the right of xmax, calculate the intersection with the right boundary
if (i == 1 && bits[i] == 1)
{
double tvar = Math.Round(m * xmax + c);
mylines.y1 = tvar;
mylines.x1 = xmax;
}
// If the end point is to the right of xmax, calculate the intersection with the right boundary
if (i == 1 && bytes[i] == 1)
{
double tvar = Math.Round(m * xmax + c);
mylines.y2 = tvar;
mylines.x2 = xmax;
}
// If the initial point is above ymin, calculate the intersection with the top boundary
if (i == 2 && bits[i] == 1)
{
double tvar = Math.Round((ymin - c) / m);
mylines.y1 = ymin;
mylines.x1 = tvar;
}
// If the end point is above ymin, calculate the intersection with the top boundary
if (i == 2 && bytes[i] == 1)
{
double tvar = Math.Round((ymin - c) / m);
mylines.y2 = ymin;
mylines.x2 = tvar;
}
// If the initial point is below ymax, calculate the intersection with the bottom boundary
if (i == 3 && bits[i] == 1)
{
double tvar = Math.Round((ymax - c) / m);
mylines.y1 = ymax;
mylines.x1 = tvar;
}
// If the end point is below ymax, calculate the intersection with the bottom boundary
if (i == 3 && bytes[i] == 1)
{
double tvar = Math.Round((ymax - c) / m);
mylines.y2 = ymax;
mylines.x2 = tvar;
}
// Update the bits for the initial and end points
bits[0] = Sign(xmin - mylines.x1);
bytes[0] = Sign(xmin - mylines.x2);
bits[1] = Sign(mylines.x1 - xmax);
bytes[1] = Sign(mylines.x2 - xmax);
bits[2] = Sign(ymin - mylines.y1);
bytes[2] = Sign(ymin - mylines.y2);
bits[3] = Sign(mylines.y1 - ymax);
bytes[3] = Sign(mylines.y2 - ymax);
}
// If both points are now inside the window, print the line
if (initial == end && end == "0000")
{
Console.WriteLine($"Line from ({mylines.x1}, {mylines.y1}) to ({mylines.x2}, {mylines.y2})");
return;
}
else
{
return;
}
}
}
static void Main()
{
// Set the window boundaries
xmin = 40;
xmax = 100;
ymin = 40;
ymax = 80;
// Create an array of Lines objects
Lines[] mylines = new Lines[4];
// Set the coordinates of the lines
mylines[0] = new Lines(30, 65, 55, 30);
mylines[1] = new Lines(60, 20, 100, 90);
mylines[2] = new Lines(60, 100, 80, 70);
mylines[3] = new Lines(85, 50, 120, 75);
// Print the initial lines
foreach (Lines line in mylines)
{
Console.WriteLine($"Line from ({line.x1}, {line.y1}) to ({line.x2}, {line.y2})");
}
// Clip each line and print the result
foreach (Lines line in mylines)
{
Clip(line);
}
}
}
JavaScript
// Global Variables
let xmin = 0, xmax = 0, ymin = 0, ymax = 0;
// Lines where co-ordinates are (x1, y1) and (x2, y2)
class Lines {
constructor(x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
}
// This will return the sign required.
function sign(x) {
return x > 0 ? 1 : 0;
}
// CohenSutherLand LineClipping Algorithm As Described in theory.
// This will clip the lines as per window boundaries.
function clip(mylines) {
// arrays will store bits
// Here bits implies initial Point whereas byte implies end points
let bits = Array(4).fill(0);
let byte = Array(4).fill(0);
// Finding Bits
bits[0] = sign(xmin - mylines.x1);
byte[0] = sign(xmin - mylines.x2);
bits[1] = sign(mylines.x1 - xmax);
byte[1] = sign(mylines.x2 - xmax);
bits[2] = sign(ymin - mylines.y1);
byte[2] = sign(ymin - mylines.y2);
bits[3] = sign(mylines.y1 - ymax);
byte[3] = sign(mylines.y2 - ymax);
// initial will used for initial coordinates and end for final
let initial = bits.join("");
let end = byte.join("");
let temp = "";
// finding slope of line y=mx+c as (y-y1)=m(x-x1)+c
// where m is slope m=dy/dx;
let m = (mylines.y2 - mylines.y1) / (mylines.x2 - mylines.x1);
let c = mylines.y1 - m * mylines.x1;
// if both points are inside the Accept the line and draw
if (initial === end && end === "0000") {
// plotting the line from (x1, y1) to (x2, y2)
console.log(`Line from (${mylines.x1}, ${mylines.y1}) to (${mylines.x2}, ${mylines.y2})`);
return;
}
// this will contain cases where line maybe totally outside for partially inside
else {
// taking bitwise end of every value
for (let i = 0; i < 4; i++) {
let val = bits[i] & byte[i];
temp += val === 0 ? '0' : '1';
}
// as per algo if AND is not 0000 means line is completely outside hence draw nothing and return
if (temp !== "0000") {
return;
}
// Here contain cases of partial inside or outside
// So check for every boundary one by one
for (let i = 0; i < 4; i++) {
// if both bit are same hence we cannot find any intersection with boundary so continue
if (bits[i] === byte[i]) {
continue;
}
// Otherwise there exist an intersection
// Case when initial point is in left xmin
if (i === 0 && bits[i] === 1) {
let tvar = Math.round(m * xmin + c);
mylines.y1 = tvar;
mylines.x1 = xmin;
}
// Case when final point is in left xmin
if (i === 0 && byte[i] === 1) {
let tvar = Math.round(m * xmin + c);
mylines.y2 = tvar;
mylines.x2 = xmin;
}
// Case when initial point is in right of xmax
if (i === 1 && bits[i] === 1) {
let tvar = Math.round(m * xmax + c);
mylines.y1 = tvar;
mylines.x1 = xmax;
}
// Case when final point is in right of xmax
if (i === 1 && byte[i] === 1) {
let tvar = Math.round(m * xmax + c);
mylines.y2 = tvar;
mylines.x2 = xmax;
}
// Case when initial point is in top of ymin
if (i === 2 && bits[i] === 1) {
let tvar = Math.round((ymin - c) / m);
mylines.y1 = ymin;
mylines.x1 = tvar;
}
// Case when final point is in top of ymin
if (i === 2 && byte[i] === 1) {
let tvar = Math.round((ymin - c) / m);
mylines.y2 = ymin;
mylines.x2 = tvar;
}
// Case when initial point is in bottom of ymax
if (i === 3 && bits[i] === 1) {
let tvar = Math.round((ymax - c) / m);
mylines.y1 = ymax;
mylines.x1 = tvar;
}
// Case when final point is in bottom of ymax
if (i === 3 && byte[i] === 1) {
let tvar = Math.round((ymax - c) / m);
mylines.y2 = ymax;
mylines.x2 = tvar;
}
// Updating Bits at every point
bits[0] = sign(xmin - mylines.x1);
byte[0] = sign(xmin - mylines.x2);
bits[1] = sign(mylines.x1 - xmax);
byte[1] = sign(mylines.x2 - xmax);
bits[2] = sign(ymin - mylines.y1);
byte[2] = sign(ymin - mylines.y2);
bits[3] = sign(mylines.y1 - ymax);
byte[3] = sign(mylines.y2 - ymax);
}
// If now both points lie inside or on boundary then simply draw the updated line
if (initial === end && end === "0000") {
console.log(`Line from (${mylines.x1}, ${mylines.y1}) to (${mylines.x2}, ${mylines.y2})`);
return;
}
// else line was completely outside hence rejected
else {
return;
}
}
}
// Driver Function
function main() {
// Setting values of Clipping window
xmin = 40;
xmax = 100;
ymin = 40;
ymax = 80;
// Assume 4 lines to be clipped
let mylines = [];
// Setting the coordinates of 4 lines
mylines.push(new Lines(30, 65, 55, 30));
mylines.push(new Lines(60, 20, 100, 90));
mylines.push(new Lines(60, 100, 80, 70));
mylines.push(new Lines(85, 50, 120, 75));
// Drawing Initial Lines without clipping
for (let line of mylines) {
console.log(`Line from (${line.x1}, ${line.y1}) to (${line.x2}, ${line.y2})`);
}
// Drawing clipped Line
for (let line of mylines) {
// Calling clip() which in term clip the line as per window and draw it
clip(line);
}
}
main();
Python3
import matplotlib.pyplot as plt
# Global Variables
xmin, xmax, ymin, ymax = 0, 0, 0, 0
# Lines where co-ordinates are (x1, y1) and (x2, y2)
class Lines:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
# This will return the sign required.
def sign(x):
if x > 0:
return 1
else:
return 0
# CohenSutherLand LineClipping Algorithm As Described in theory.
# This will clip the lines as per window boundaries.
def clip(mylines):
global xmin, xmax, ymin, ymax
# arrays will store bits
# Here bits implies initial Point whereas byte implies end points
bits = [0]*4
byte = [0]*4
# Finding Bits
bits[0] = sign(xmin - mylines.x1)
byte[0] = sign(xmin - mylines.x2)
bits[1] = sign(mylines.x1 - xmax)
byte[1] = sign(mylines.x2 - xmax)
bits[2] = sign(ymin - mylines.y1)
byte[2] = sign(ymin - mylines.y2)
bits[3] = sign(mylines.y1 - ymax)
byte[3] = sign(mylines.y2 - ymax)
# initial will used for initial coordinates and end for final
initial = "".join(map(str, bits))
end = "".join(map(str, byte))
temp = ""
# finding slope of line y=mx+c as (y-y1)=m(x-x1)+c
# where m is slope m=dy/dx;
m = (mylines.y2 - mylines.y1) / (mylines.x2 - mylines.x1)
c = mylines.y1 - m * mylines.x1
# if both points are inside the Accept the line and draw
if initial == end and end == "0000":
# plotting the line from (x1, y1) to (x2, y2)
plt.plot([mylines.x1, mylines.x2], [mylines.y1, mylines.y2], color='red')
return
# this will contain cases where line maybe totally outside for partially inside
else:
# taking bitwise end of every value
for i in range(4):
val = bits[i] & byte[i]
if val == 0:
temp += '0'
else:
temp += '1'
# as per algo if AND is not 0000 means line is completely outside hence draw nothing and return
if temp != "0000":
return
# Here contain cases of partial inside or outside
# So check for every boundary one by one
for i in range(4):
# if both bit are same hence we cannot find any intersection with boundary so continue
if bits[i] == byte[i]:
continue
# Otherwise there exist an intersection
# Case when initial point is in left xmin
if i == 0 and bits[i] == 1:
var = round(m * xmin + c)
mylines.y1 = var
mylines.x1 = xmin
# Case when final point is in left xmin
if i == 0 and byte[i] == 1:
var = round(m * xmin + c)
mylines.y2 = var
mylines.x2 = xmin
# Case when initial point is in right of xmax
if i == 1 and bits[i] == 1:
var = round(m * xmax + c)
mylines.y1 = var
mylines.x1 = xmax
# Case when final point is in right of xmax
if i == 1 and byte[i] == 1:
var = round(m * xmax + c)
mylines.y2 = var
mylines.x2 = xmax
# Case when initial point is in top of ymin
if i == 2 and bits[i] == 1:
var = round((ymin - c) / m)
mylines.y1 = ymin
mylines.x1 = var
# Case when final point is in top of ymin
if i == 2 and byte[i] == 1:
var = round((ymin - c) / m)
mylines.y2 = ymin
mylines.x2 = var
# Case when initial point is in bottom of ymax
if i == 3 and bits[i] == 1:
var = round((ymax - c) / m)
mylines.y1 = ymax
mylines.x1 = var
# Case when final point is in bottom of ymax
if i == 3 and byte[i] == 1:
var = round((ymax - c) / m)
mylines.y2 = ymax
mylines.x2 = var
# Updating Bits at every point
bits[0] = sign(xmin - mylines.x1)
byte[0] = sign(xmin - mylines.x2)
bits[1] = sign(mylines.x1 - xmax)
byte[1] = sign(mylines.x2 - xmax)
bits[2] = sign(ymin - mylines.y1)
byte[2] = sign(ymin - mylines.y2)
bits[3] = sign(mylines.y1 - ymax)
byte[3] = sign(mylines.y2 - ymax)
# If now both points lie inside or on boundary then simply draw the updated line
if initial == end and end == "0000":
plt.plot([mylines.x1, mylines.x2], [mylines.y1, mylines.y2], color='red')
return
# else line was completely outside hence rejected
else:
return
# Driver Function
def main():
global xmin, xmax, ymin, ymax
# Setting values of Clipping window
xmin = 40
xmax = 100
ymin = 40
ymax = 80
# Drawing Window using Lines
plt.plot([xmin, xmax, xmax, xmin, xmin], [ymin, ymin, ymax, ymax, ymin], color='black')
# Assume 4 lines to be clipped
mylines = []
# Setting the coordinates of 4 lines
mylines.append(Lines(30, 65, 55, 30))
mylines.append(Lines(60, 20, 100, 90))
mylines.append(Lines(60, 100, 80, 70))
mylines.append(Lines(85, 50, 120, 75))
# Drawing Initial Lines without clipping
for line in mylines:
plt.plot([line.x1, line.x2], [line.y1, line.y2], color='blue')
plt.pause(1)
# Drawing clipped Line
for line in mylines:
# Calling clip() which in term clip the line as per window and draw it
clip(line)
plt.pause(1)
plt.show()
if __name__ == "__main__":
main()
The Cohen–Sutherland algorithm can be used only on a rectangular clip window. For other convex polygon clipping windows, Cyrus–Beck algorithm is used. We will be discussing Cyrus–Beck Algorithm in next set.
Related Post :
Polygon Clipping | Sutherland–Hodgman Algorithm
Point Clipping Algorithm in Computer Graphics
Reference:
1) https://en.wikipedia.org/wiki/Cohen–Sutherland_algorithm
2)Book:- Computer Graphics: By Donald Hearn, M. Pauline Baker
3) College notes
Similar Reads
Computer Graphics Recent Articles on Computer GraphicsTable of Content Basics :Output Primitives :2-Dimensional Viewing :Visible Surface Detection :3-Dimension Object Representation :Open GL :Graphics function in C :Misc : Basics :Basic Graphic Programming in C++Vector vs Raster GraphicsSegments in Computer GraphicsI
2 min read
Basics
Basic Graphic Programming in C++Introduction So far we have been using C language for simple console output only.  Most of us are unaware that using C++, low level graphics program can also be made. This means we can incorporate shapes,colors and designer fonts in our program. This article deals with the steps to enable the DevC++
2 min read
Vector vs Raster GraphicsWhen it comes to digital images, two main types are commonly used: raster and vector graphics. Understanding the difference between these two can help you choose the right format for your project. Raster graphics, made up of tiny pixels, are ideal for detailed and colorful images like photographs. O
7 min read
Segments in Computer GraphicsIntroduction : Introduction segments are a fundamental concept in computer graphics, used to represent the basic building blocks of a graphical scene. They are commonly used in 2D graphics to represent lines or curves that connect two or more points. An introduction segment is defined by two endpoin
8 min read
Image FormatsImage formats are different types of file types used for saving pictures, graphics, and photos. Choosing the right image format is important because it affects how your images look, load, and perform on websites, social media, or in print. Common formats include JPEG, PNG, GIF, and SVG, each with it
5 min read
Output Primitives
DDA Line generation Algorithm in Computer GraphicsIntroduction : DDA (Digital Differential Analyzer) is a line drawing algorithm used in computer graphics to generate a line segment between two specified endpoints. It is a simple and efficient algorithm that works by using the incremental difference between the x-coordinates and y-coordinates of th
12 min read
Bresenhamâs Line Generation AlgorithmGiven the coordinate of two points A(x1, y1) and B(x2, y2). The task is to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates. Examples: Input : A(0,0), B(4,4)Output : (0,0), (1,1), (2,2), (3,3), (4,4) Input :
14 min read
Mid-Point Line Generation AlgorithmGiven coordinate of two points A(x1, y1) and B(x2, y2) such that x1 < x2 and y1 < y2. The task to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.We have discussed below algorithms for this task. DDA
11 min read
Program to find line passing through 2 PointsGiven two points P and Q in the coordinate plane, find the equation of the line passing through both points.This kind of conversion is very useful in many geometric algorithms like intersection of lines, finding the circumcenter of a triangle, finding the incenter of a triangle and many more... Exam
6 min read
Bresenhamâs circle drawing algorithmIt is not easy to display a continuous smooth arc on the computer screen as our computer screen is made of pixels organized in matrix form. So, to draw a circle on a computer screen we should always choose the nearest pixels from a printed pixel so as they could form an arc. There are two algorithm
4 min read
Anti-aliased Line | Xiaolin Wu's algorithmAnti-Aliased Line Drawing Below is the image showing line drawn with Bresenham's line algorithm (left) and Xiaolin Wu's line algorithm (right) which smooths the line. Which one looks better to you ? Anti Aliasing concept Suppose we want to draw a line from point(1 , 1) to point(8 , 4) with rectangul
10 min read
Neighbors of a point on a circle using Bresenham's algorithmGiven a center of a circle and its radius. our task is to find the neighbors of any point on the discrete circle. Examples: Input : Center = (0, 0), Radius = 3 Point for determining neighbors = (2, 2)Output : Neighbors of given point are : (1, 3), (3, 1)Input : Center = (2, 2) Radius 2 Point of det
15 min read
Mid-Point Circle Drawing AlgorithmThe mid-point circle drawing algorithm is an algorithm used to determine the points needed for rasterizing a circle. We use the mid-point algorithm to calculate all the perimeter points of the circle in the first octant and then print them along with their mirror points in the other octants. This wi
15+ min read
Boundary Fill AlgorithmPrerequisite : Flood fill algorithm, Scan-line polygon fillingIntroduction : Boundary Fill Algorithm starts at a pixel inside the polygon to be filled and paints the interior proceeding outwards towards the boundary. This algorithm works only if the color with which the region has to be filled and t
5 min read
Flood fill Algorithm - how to implement fill() in paint?Flood Fill is a classic algorithm used to change the color of an area in a 2D image where all pixels are connected and have the same initial color. Think of it like the paint bucket tool in graphic design software like MS Paint or Photoshopâwhen you click on a spot, it automatically fills that area
2 min read
Flood fill algorithm using C graphicsGiven a rectangle, your task to fill this rectangle using flood fill algorithm. Examples: Input : rectangle(left = 50, top = 50, right= 100, bottom = 100) flood( x = 55, y = 55, new_color = 12, old_color = 0) Output : Input : rectangle(left = 50, top = 50, right= 200, bottom = 400) flood( x = 51, y
2 min read
Draw a line in C++ graphicsgraphics.h library is used to include and facilitate graphical operations in program. graphics.h functions can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h you can make graphics programs, animations, projects and games.
2 min read
Draw Rectangle in C graphicsrectangle() is used to draw a rectangle. Coordinates of left top and right bottom corner are required to draw the rectangle. left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specifies the X-coordinate of right bottom corner, bottom specifie
2 min read
Draw circle in C graphicsThe header file graphics.h contains circle() function which draws a circle with center at (x, y) and given radius. Syntax : circle(x, y, radius); where, (x, y) is center of the circle. 'radius' is the Radius of the circle. Examples : Input : x = 250, y = 200, radius = 50 Output : Input : x = 300, y
1 min read
Draw a circle without floating point arithmeticGiven a radius of a circle, draw the circle without using floating point arithmetic.The following program uses a simple concept. Let the radius of the circle be r. Consider a square of size (2r+1)*(2r+1) around the circle to be drawn. Now walk through every point inside the square. For every point (
6 min read
Code to Generate the Map of India (With Explanation)Given an obfuscated code that generates the map of India, explain its working. The following code when executed generates the map of India. An obfuscated code is a code that has been deliberately made difficult to understand or difficult to read, typically for the purpose of hiding its logic or maki
8 min read
2-Dimensional Viewing
2D Transformation in Computer Graphics | Set 1 (Scaling of Objects)We can use a 2 Ã 2 matrix to change or transform, a 2D vector. This kind of operation, which takes in a 2-vector and produces another 2-vector by a simple matrix multiplication, is a linear transformation. By this simple formula, we can achieve a variety of useful transformations, depending on what
5 min read
2D Transformation | Rotation of objectsWe have to rotate an object by a given angle about a given pivot point and print the new co-ordinates.Examples: Input : {(100, 100), (150, 200), (200, 200), (200, 150)} is to be rotated about (0, 0) by 90 degrees Output : (-100, 100), (-200, 150), (-200, 200), (-150, 200) Input : {(100, 100), (100,
7 min read
Point Clipping Algorithm in Computer GraphicsThe Point Clipping Algorithm is a fundamental algorithm used in Computer Graphics to determine whether a point lies inside or outside a specific region or boundary. It is particularly useful when dealing with objects that have complex shapes or when displaying only a portion of an image. Clipping: I
10 min read
Line Clipping | Set 1 (CohenâSutherland Algorithm)Description:- In this algorithm, we are given 9 regions on the screen. Out of which one region is of the window and the rest 8 regions are around it given by 4 digit binary. Â The division of the regions are based on (x_max, y_max) and (x_min, y_min). The central part is the viewing region or window,
15+ min read
Polygon Clipping | SutherlandâHodgman AlgorithmA convex polygon and a convex clipping area are given. The task is to clip polygon edges using the SutherlandâHodgman Algorithm. Input is in the form of vertices of the polygon in clockwise order. Examples: Input : Polygon : (100,150), (200,250), (300,200) Clipping Area : (150,150), (150,200), (200,
15 min read
Implementation of a Falling MatrixSince the dawn of computers, Hollywood has greatly demonstrated a Hacker or a Programmer as someone sitting on a computer typing random keys on computer which ultimately compiles to a Falling matrix like simulation. Here, we will try to implement a similar falling matrix simulation on the console us
5 min read
Visible Surface Detection
3-Dimension Object Representation
Snowflakes Fractal using PythonTo create Snowflake fractals using Python programmingWhat are fractals A fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Driven by recu
3 min read
Koch Curve or Koch SnowflakeWhat is Koch Curve? The Koch snowflake (also known as the Koch curve, Koch star, or Koch island) is a mathematical curve and one of the earliest fractal curves to have been described. It is based on the Koch curve, which appeared in a 1904 paper titled "On a continuous curve without tangents, constr
4 min read
Klee's Algorithm (Length Of Union Of Segments of a line)Given starting and ending positions of segments on a line, the task is to take the union of all given segments and find length covered by these segments.Examples: Input : segments[] = {{2, 5}, {4, 8}, {9, 12}} Output : 9 Explanation: segment 1 = {2, 5} segment 2 = {4, 8} segment 3 = {9, 12} If we ta
9 min read
Cubic Bezier Curve Implementation in CWhat is a bezier curve? So a Bezier curve is a mathematically defined curve used in two-dimensional graphic applications like adobe Illustrator, Inkscape etc. The curve is defined by four points: the initial position and the terminating position i.e P0 and P3 respectively (which are called "anchors"
11 min read
Fractals in C/C++A Fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Mathematically fractals can be explained as follows. The location of a point on a scr
6 min read
Open GL
Scan-line Polygon filling using OPENGL in CFigures on a computer screen can be drawn using polygons. To fill those figures with color, we need to develop some algorithm.There are two famous algorithms for this purpose: Boundary fill and Scanline fill algorithms.Boundary filling requires a lot of processing and thus encounters few problems in
8 min read
Rendering a Triangle using OpenGL(using Shaders)In this article we'll see how to render a triangle using OpenGL. A triangle is probably the simplest shapes you can draw in OpenGL after points and lines and any complicated geometry that you make will me made up of number of triangles joined together.We'll be using the programmable pipeline, so we'
9 min read
Getting started with OpenGLOpen Graphics Library (OpenGL) is a cross-language (language independent), cross-platform (platform-independent) API for rendering 2D and 3D Vector Graphics(use of polygons to represent image). OpenGL API is designed mostly in hardware. Design : This API is defined as a set of functions which may be
4 min read
OpenGL program for Simple Ball GamePrerequisite - OpenGLOpenGL is a cross-language, cross-platform API for rendering 2D and 3D Vector Graphics. Using this, we can make a lot of design as well as animations. Below is a simple Game made using OpenGL.Description : In this, a ball is moving starting from middle and goes to up-left in sta
5 min read
OpenGL program for simple Animation (Revolution) in COpenGL is a cross-language, cross-platform API for rendering 2D and 3D Vector Graphics. Using this, we can make a lot of design as well as animations. Below is the simple animation made using OpenGL.Approach : To make a picture moving, we need to understand the working procedure of a function used t
6 min read
Translation of objects in computer graphicsIn computer graphics, we have seen how to draw some basic figures like line and circles. In this post we will discuss on basics of an important operation in computer graphics as well as 2-D geometry, which is transformation. In computer graphics, transformation of the coordinates consists of three m
7 min read
Graphics function in C
pieslice() function in Cpieslice() draws and fills a pie slice with center at (x, y) and given radius r. The slice travels from s_angle to e_angle which are starting and ending angles for the pie slice. The angles for pie-slice are given in degrees and are measured counterclockwise. Syntax : void pieslice(int x, int y, int
2 min read
outtextxy() function in CThe header file graphics.h contains outtextxy() function which displays the text or string at a specified point (x, y) on the screen. Syntax : void outtextxy(int x, int y, char *string); where, x, y are coordinates of the point and, third argument contains the address of string to be displayed. Exam
1 min read
settextstyle function in CThe header file graphics.h contains settextstyle() function which is used to change the way in which text appears. Using it we can modify the size of text, change direction of text and change the font of text. Syntax : void settextstyle(int font, int direction, int font_size); where, font argument s
2 min read
outtext() function in CThe header file graphics.h contains outtext() function which displays text at current position. Syntax : void outtext(char *string); Examples : Input : string = "Hello Geek, Have a good day !" Output : Input : string = "GeeksforGeeks is the best !" Output : Note : Do not use text mode functions like
1 min read
setlinestyle() function in CThe header file graphics.h contains setlinestyle() function which sets the style for all lines drawn by line, lineto, rectangle, drawpoly, and so on. Syntax : void setlinestyle(int linestyle, unsigned upattern, int thickness); Examples : Input : x = 200, y = 100 Output : x and y are initialized as (
2 min read
getx() function in CThe header file graphics.h contains getx() function which returns the X coordinate of the current position. Syntax : int getx(); Example : Explanation : Initially, the X coordinate of the current position is 0. On moving the coordinates using moveto() function, the X coordinate changes to 80. Below
2 min read
sector() function in CThe header file graphics.h contains sector() function which draws and fills an elliptical pie slice with (x, y) as center, (s_angle, e_angle) as starting and ending angle and (x_radius, y_radius) as x and y radius of sector. Syntax : void sector(int x, int y, int s_angle, int e_angle, int x_radius,
2 min read
moveto() function in CThe header file graphics.h contains moveto() function which changes the current position to (x, y) Syntax : void moveto(int x, int y); Examples : Input : x = 70, y = 40 Output : Input : x = 50, y = 80 Output : Below is the implementation of moveto() function: C // C Implementation for moveto() #incl
2 min read
gety() function in CThe header file graphics.h contains gety() function which returns the Y coordinate of the current position. Syntax : int gety(); Example : Explanation : Initially, the Y coordinate of the current position is 0. On moving the coordinates using moveto() function, the Y coordinate changes to 50. Below
2 min read
getmaxx() function in CThe header file graphics.h contains getmaxx() function which returns the maximum X coordinate for current graphics mode and driver. Syntax : int getmaxx(); Below is the implementation of getmaxx() function: C // C Implementation for getmaxx() #include <graphics.h> #include <stdio.h> // d
1 min read
lineto() function in CThe header file graphics.h contains lineto() function which draws a line from current position to the point(x,y). Note : Use getx() and gety() to get the current position. Syntax : lineto(int x, int y); where, (x, y) are the coordinates upto which the line will be drawn from previous point. CASE 1 :
2 min read
arc function in CThe header file graphics.h contains arc() function which draws an arc with center at (x, y) and given radius. start_angle is the starting point of angle and end_angle is the ending point of the angle. The value of the angle can vary from 0 to 360 degree. Syntax : void arc(int x, int y, int start_ang
2 min read
bar3d() function in C graphicsThe header file graphics.h contains bar3d() function which is used to draw a 2-dimensional, rectangular filled in bar . Coordinates of left top and right bottom corner of bar are required to draw the bar. Syntax : void bar3d(int left, int top, int right, int bottom, int depth, int topflag); where, l
2 min read
moverel() function in CThe header file graphics.h contains moverel() function which moves a point from the current position(x_pos1, y_pos1) to a point that is at a relative distance (x, y) from the Current Position and then advances the Current Position by (x, y). Note : getx and gety can be used to find the current posit
3 min read
cleardevice() function in CThe header file graphics.h contains cleardevice() function which clears the screen in graphics mode and sets the current position to (0,0). Clearing the screen consists of filling the screen with current background color. Syntax : void cleardevice(); Below is the implementation of cleardevice() in C
1 min read
closegraph() function in CThe header file graphics.h contains closegraph() function which closes the graphics mode, deallocates all memory allocated by graphics system and restores the screen to the mode it was in before you called initgraph. Syntax : void closegraph(); Below is the implementation of closegraph() in C. C //
1 min read
drawpoly() function in CThe header file graphics.h contains drawpoly() function which is used to draw polygons i.e. triangle, rectangle, pentagon, hexagon etc. Syntax : void drawpoly( int number, int *polypoints ); where, number indicates (n + 1) number of points where n is the number of vertices in a polygon. polypoints p
2 min read
putpixel() function in CThe header file graphics.h contains putpixel() function which plots a pixel at location (x, y) of specified color. Syntax : void putpixel(int x, int y, int color); where, (x, y) is the location at which pixel is to be put , and color specifies the color of the pixel. Explanation : A RED color pixel
2 min read
getarcoords() function in CThe header file graphics.h contains getarccoords() function which is used to get coordinates of arc which is drawn most recently. arccoordstype is a predefined structure which is defined as follows: Syntax : struct arccoordstype { // center point of arc int x, y; // start position int xstart, ystart
2 min read
getbkcolor() function in CThe header file graphics.h contains getbkcolor() function which returns the current background color. Syntax : int getbkcolor(); As getbkcolor() returns an integer value corresponding to the background color, so below is the table for Color values. Colors Table : COLOR INT VALUES -------------------
2 min read
getmaxcolor() function in CThe header file graphics.h contains getmaxcolor() function, which returns maximum color value for current graphics mode and driver. As color numbering starts from zero, total number of colors available for current graphics mode and driver are ( getmaxcolor() + 1 ) . Syntax : int getmaxcolor(); Below
2 min read
getpixel() function in CThe header file graphics.h contains getpixel() function which returns the color of pixel present at location (x, y). Syntax : int getpixel(int x, int y); Note : By default the screen is BLACK, therefore color of pixel at (0,0) is BLACK. Below is the implementation of getpixel() function. C // C Impl
2 min read
setcolor function in CThe header file graphics.h contains setcolor() function which is used to set the current drawing color to the new color. Syntax : void setcolor(int color); Explanation : In Graphics, each color is assigned a number. Total number of colors available are 16. Number of available colors depends on curre
2 min read
imagesize() function in CThe header file graphics.h contains imagesize() function which returns the number of bytes required to store a bit-image. Syntax : unsigned int imagesize(int left, int top, int right, int bottom); where, left, top, right, and bottom define the area of the screen in which image is stored. Below is th
2 min read
textheight() function in CThe header file graphics.h contains textheight() function which returns the height of input string in pixels. Syntax : int textheight(char *string); Example : Input : string = "Hello Geek ! Have a good day." Output : Below is the implementation of textheight() function. C // C Implementation for tex
1 min read
textwidth() function in CThe header file graphics.h contains textwidth () function which returns the width of input string in pixels. Syntax : int textwidth(char *string); Example : Input : string = "Hello Geek ! Have a good day." Output : Below is the implementation of textwidth() function. C // C Implementation for textwi
1 min read
grapherrormsg() function in CThe header file graphics.h contains grapherrormsg() function which returns an error message string. Syntax : char *grapherrormsg( int errorcode ); where, errorcode: code for the respective error Illustration of the grapherrormsg() : In the below program, gd = DETECT is not written and thus program m
1 min read
fillpoly() function in CThe header file graphics.h contains fillpoly() function which is used to draw and fill a polygon i.e. triangle, rectangle, pentagon, hexagon etc. It require same arguments as drawpoly(). Syntax : void fillpoly( int number, int *polypoints ); where, number indicates (n + 1) number of points where, n
3 min read
fillellipse() function in CThe header file graphics.h contains fillellipse() function which draws and fills an ellipse with center at (x, y) and (x_radius, y_radius) as x and y radius of ellipse. Syntax : void fillellipse(int x, int y, int x_radius, int y_radius); where, (x, y) is center of the ellipse. (x_radius, y_radius) a
1 min read
bar() function in C graphicsThe header file graphics.h contains bar() function which is used to draw a 2-dimensional, rectangular filled in bar. Syntax : void bar(int left, int top, int right, int bottom); where, left specifies the X-coordinate of top left corner, top specifies the Y-coordinate of top left corner, right specif
2 min read
Misc