Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
277 views

Computer Graphics Lab Report

The document discusses implementing various 2D transformations like translation, rotation, scaling, reflection and shearing on shapes using Java. It provides algorithms and sample code to perform these transformations by applying the appropriate mathematical formulas to the coordinates of points on a shape.

Uploaded by

poshanbasnet10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
277 views

Computer Graphics Lab Report

The document discusses implementing various 2D transformations like translation, rotation, scaling, reflection and shearing on shapes using Java. It provides algorithms and sample code to perform these transformations by applying the appropriate mathematical formulas to the coordinates of points on a shape.

Uploaded by

poshanbasnet10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

SHREE YANTRA COLLEGE

DAMAK-9, JHAPA

BIM 5TH Semester


Computer Graphics
Lab Report

TRIBHUWAN UNIVERSITY
2023

Submitted By : Poshan Basnet


Exam Roll.no : 12725

Submitted To: Rabin Budathoki ( CG Professor )

4|Page
LIST OF EXPERIMENTS

EX.NO NAME OF EXPERIMENT

1 DDA LINE DRAWING ALGORITHM

2 BRESENHAM LINE DRAWING ALGORITHM

3 BRESENHAM CIRCLE DRAWING ALGORITHM

4 IMPLEMENTATION OF 2D TRANSFORMATION

5 LINE CLIPING USING COHEN-SUTHERLAND ALGORITHM

6 POLYGON CLIPPING USING COHEN-SUTHERLAND ALGORITHM

7 IMPLEMENTATION OF 3D TRANSFORMATION

8 IMPLEMENTATION OF COMPOSITE 2D TRANSFORMATION

9 IMPLEMENTATION OF 3D PROJECTIONS

10 WINDOW TO VIEWPORT MAPPING

5|Page
Ex .No - 1 DDA LINE DRAWING ALGORITHM

Question:

To write a JAVA program to implement DDA line drawing algorithm.

ALGORITHM:

Step 1:Start the program.

Step 2:Initialize the graphics mode using init graph function.

Step 3:Accept the end points of the line to be drawn x1,,y1,x2,y2.

Step 4:To determine the slope along find dy=y2-y1 ,dx=x2-x1 and slope =dy/dx.

Step 5:calculate the step value.

Step 6:Find the new intermediate points using xᵢ=dx/step and yᵢ=dy/step.

Step 7:Plot pixel using (xᵢ,yᵢ) and repeat this process by incrementing the points (xᵢ,yᵢ) at equal
slope intervals until the end points of the line to be drawn is encountered.

Step 8:Stop the program.

PROGRAM
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class DDALineDrawing extends JPanel {


private int x1, y1, x2, y2;

public DDALineDrawing(int x1, int y1, int x2, int y2) {


this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

int dx = x2 - x1;
int dy = y2 - y1;
int steps = Math.max(Math.abs(dx), Math.abs(dy));

float xIncrement = (float) dx / steps;


float yIncrement = (float) dy / steps;

6|Page
float x = x1;
float y = y1;

for (int i = 0; i <= steps; i++) {


g.drawRect(Math.round(x), Math.round(y), 1, 1);
x += xIncrement;
y += yIncrement;
}
}

public static void main(String[] args) {


int x1 = 50, y1 = 50, x2 = 300, y2 = 200;
JFrame frame = new JFrame("DDA Line Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

DDALineDrawing panel = new DDALineDrawing(x1, y1, x2, y2);


frame.add(panel);
frame.setVisible(true);
}
}

Output:

7|Page
Ex No.2 BRESENHAM LINE DRAWING ALGORITHM

AIM:

To write a JAVA program to create Bresenham line drawing algorithm.

ALGORITHM:

Step 1:Start the program.

Step 2:Initialize the graphics mode using init graph function.

Step 3:Accept the input at starting and endpoint of the line to be drawn.

Step 4: Load (xᵢ,yᵢ) into the frame buffer to be plotted as a first point.

Step 5:Calculate the constants ∆x,∆y,2∆y, 2∆y -2∆x and obtain the first decision parameter
P˳=2∆y -2∆x.

8|Page
Step 6:At each xk along the line starting at k=0 perform the following test

If pk<0,the next point is (xk+1,yK) and pk+1=pk+2∆y,otherwise next point to the plotted
is(xk+1,yk+1),

Otherwise the next point to be plotted is (xk+1,yk+1), and pk+1=pk+2∆y-2∆x.

Step 7 :Repeat the process until the end point of the line to be drawn is encountered.

Step 8: Stop the program.

PROGRAM

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class BresenhamLineDrawing extends JPanel {
private int x1, y1, x2, y2;
public BresenhamLineDrawing(int x1, int y1, int x2, int y2)
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;

this.y2 = y2;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int dx = Math.abs(x2 - x1);
int dy = Math.abs(y2 - y1);
int sx = x1 < x2 ? 1 : -1;
int sy = y1 < y2 ? 1 : -1;
int err = dx - dy;
int err2;
int x = x1;
int y = y1;
while (true) {
g.drawRect(x, y, 1, 1);
if (x == x2 && y == y2) break;
err2 = 2 * err;
if (err2 > -dy) {
err -= dy;
x += sx;
}
if (err2 < dx) {
err += dx;
y += sy;
}
}
}

9|Page
public static void main(String[] args) {
int x1 = 50, y1 = 50, x2 = 300, y2 = 200;
JFrame frame = new JFrame("Bresenham Line Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
BresenhamLineDrawing panel = new BresenhamLineDrawing(x1, y1, x2, y2);
frame.add(panel);
frame.setVisible(true);
}
}

Output:

10 | P a g e
Ex No.3 BRESENHAM CIRCLE DRAWING ALGORITHM

AIM:

To write a JAVA program to create bresenham circle drawing algorithm.

ALGORITHM:

Step 1: Start the program.

Step 2: Initialize the graphics mode using init graph function.

Step 3: Accept the input at radius and center of the circle.

Step 4: Obtain the first point to be plotted on th circumference of the circle centered on the
origin(o,r).

Step 5: Calculate the initial value of decision parameter P˳=5/4-r.

Step 6: At each xk along the line starting at k=0 perform the following test

If pk<0,the next point is (xk+1,yK) and pk+1=pk+2xk+1+1,otherwise next point to the plotted is

(xk+1,yk-1) and pk+1=pk+2xk+1+1-2yk-1.

Step 7 : Repeat the above steps until x>=y for this circle drawing one octant is generated and
copied for remaining octants.

PROGRAM

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class BresenhamCircleDrawing extends JPanel {
private int xCenter, yCenter, radius;
public BresenhamCircleDrawing(int xCenter, int yCenter, int radius) {
this.xCenter = xCenter;
this.yCenter = yCenter;
this.radius = radius;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
int y = radius;
int d = 3 - 2 * radius;
while (y >= x) {
drawSymmetricPoints(g, x, y);

11 | P a g e
if (d <= 0) {
d = d + 4 * x + 6;
} else {
d = d + 4 * (x - y) + 10;
y--;
}
x++;
}
}
private void drawSymmetricPoints(Graphics g, int x, int y) {
g.drawRect(xCenter + x, yCenter + y, 1, 1);
g.drawRect(xCenter - x, yCenter + y, 1, 1);
g.drawRect(xCenter + x, yCenter - y, 1, 1);
g.drawRect(xCenter - x, yCenter - y, 1, 1);
g.drawRect(xCenter + y, yCenter + x, 1, 1);
g.drawRect(xCenter - y, yCenter + x, 1, 1);
g.drawRect(xCenter + y, yCenter - x, 1, 1);
g.drawRect(xCenter - y, yCenter - x, 1, 1);
}
public static void main(String[] args) {
int xCenter = 200, yCenter = 200, radius = 100;
JFrame frame = new JFrame("Bresenham Circle Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
BresenhamCircleDrawing panel = new BresenhamCircleDrawing(xCenter, yCenter, radius);
frame.add(panel);
frame.setVisible(true);
}
}

Output :

12 | P a g e
Ex No.4 IMPLEMENTATION OF 2D TRANSFORMATION

AIM:

To create a JAVA program to implement 2D transformations such as translation, rotation,


scaling, reflection and shearing.

ALGORITHM:

Step 1: Start the program.

Step 2: Initialization the graphics mode using init graph().

Step 3: Declare all variables and draw the 2D .

Step 4: Translation

a) Accept the translation vector(tx,ty).

b) Add the translation vector to corresponding co-ordinates of the 2D object to obtain the
transaltion co-ordinates.

c) Draw the 2D object using translated co-ordinates x’=x+tx, y’=y+ty.

Step 5: Scaling

a) Accept the scaling factor(sx,sy).

b) Multiply the scaling factor to the corresponding co-ordinates of the 2D object to obtain
the scaling co ordinates.

c) Draw the 2D object using scaling co-ordinates x’=x*sx, y’=y*sy.

Step 6: Rotation to rotate the object using the formula

a) Θ=(float)(3.14xra)/180.
b) X1=x2+abs(x1-x2)cosθ-abs(y1-y2)sinθ
c) Y1=y2+abs(x1-x2)sinθ+abs(y1-y2)cosθ
d) X3=x2+abs(x3-x1)cosθ-abs(y3-y1)sinθ
e) Y3=y2+abs(x3-x1)sinθ+abs(y3-y1)cosθ

Step 7 : Shearing

To shear the object using the formula

a) Along x-direction

x=x1+sx*y1, y=y1

13 | P a g e
b) Along y-direction

x=x1, y=y1+sy*x1

Step 8: Reflection

To reflect a object using formula

a) Along x-axis

theta=(90*ra)/180

b) Along y-axis

theta=(270*ra)/180

c) Along z-axis

theta=(180*ra)/180

Step 9: Generate the output.

Step 10: Stop the program.

PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Transformations2D extends JPanel implements ActionListener {


private int[] originalX = {50, 150, 100}; // Example polygon coordinates
private int[] originalY = {50, 50, 150};
private int numPoints = 3;

private int[] x = new int[numPoints];


private int[] y = new int[numPoints];

private double[][] transformationMatrix = new double[3][3];

private JButton translateButton, rotateButton, scaleButton, reflectButton, shearButton;

public Transformations2D() {
setPreferredSize(new Dimension(400, 400));

translateButton = new JButton("Translate");


rotateButton = new JButton("Rotate");
scaleButton = new JButton("Scale");
reflectButton = new JButton("Reflect");

14 | P a g e
shearButton = new JButton("Shear");

translateButton.addActionListener(this);
rotateButton.addActionListener(this);
scaleButton.addActionListener(this);
reflectButton.addActionListener(this);
shearButton.addActionListener(this);

add(translateButton);
add(rotateButton);
add(scaleButton);
add(reflectButton);
add(shearButton);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

g.setColor(Color.BLACK);
g.drawPolygon(x, y, numPoints);
}

private void applyTransformation(double[][] matrix) {


for (int i = 0; i < numPoints; i++) {
double tempX = x[i] * matrix[0][0] + y[i] * matrix[0][1] + matrix[0][2];
double tempY = x[i] * matrix[1][0] + y[i] * matrix[1][1] + matrix[1][2];
x[i] = (int) Math.round(tempX);
y[i] = (int) Math.round(tempY);
}
repaint();
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == translateButton) {
double tx = 30; // Translate by 30 units in x-direction
double ty = 30; // Translate by 30 units in y-direction
transformationMatrix = new double[][]{{1, 0, tx}, {0, 1, ty}, {0, 0, 1}};
} else if (e.getSource() == rotateButton) {
double angle = Math.toRadians(45); // Rotate by 45 degrees
transformationMatrix = new double[][]{{Math.cos(angle), -Math.sin(angle), 0},
{Math.sin(angle), Math.cos(angle), 0},
{0, 0, 1}};
} else if (e.getSource() == scaleButton) {
double sx = 1.5; // Scale by a factor of 1.5 in x-direction
double sy = 1.5; // Scale by a factor of 1.5 in y-direction
transformationMatrix = new double[][]{{sx, 0, 0}, {0, sy, 0}, {0, 0, 1}};

15 | P a g e
} else if (e.getSource() == reflectButton) {
transformationMatrix = new double[][]{{-1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
} else if (e.getSource() == shearButton) {
double shx = 0.5; // Shear in x-direction by a factor of 0.5
transformationMatrix = new double[][]{{1, shx, 0}, {0, 1, 0}, {0, 0, 1}};
}

applyTransformation(transformationMatrix);
}

public static void main(String[] args) {


JFrame frame = new JFrame("2D Transformations");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);

Transformations2D panel = new Transformations2D();


frame.add(panel);
frame.setVisible(true);
}
}
Output :

16 | P a g e
Ex No.5 LINE CLIPING USING COHEN-SUTHERLAND ALGORITHM

AIM:

To write a JAVA program to clip a line using the line clipping algorithm.

ALGORITHM:

Step 1: Start the program.

Step 2: Initialize the graphic mode using initgraph.

Step 3: Declare the variables and draw a window and a line using rectangle an line function.

Step 4: Using the values of x1,y1,x2,y2.Check whether the line is within the rectangle
coordinates xmin,ymin,xmax,ymax and clip it.

Step 5: Draw the clipped line in the window.

Step 6: Stop the program.

PROGRAM

import java.awt.*;
import javax.swing.*;

public class LineClipping extends JPanel {


private int x1, y1, x2, y2;
private int xmin, ymin, xmax, ymax;

public LineClipping(int x1, int y1, int x2, int y2, int xmin, int ymin, int xmax, int ymax) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.xmin = xmin;
this.ymin = ymin;
this.xmax = xmax;
this.ymax = ymax;
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

g.setColor(Color.BLACK);
g.drawRect(xmin, ymin, xmax - xmin, ymax - ymin);

17 | P a g e
int outCode1 = computeOutCode(x1, y1);
int outCode2 = computeOutCode(x2, y2);

boolean accept = false;

while (true) {
if ((outCode1 & outCode2) != 0) {
break;
}

if ((outCode1 | outCode2) == 0) {
accept = true;
break;
}

int x, y;
int outCode = (outCode1 != 0) ? outCode1 : outCode2;

if ((outCode & 8) != 0) {
x = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1);
y = ymax;
} else if ((outCode & 4) != 0) {
x = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1);
y = ymin;
} else if ((outCode & 2) != 0) {
y = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1);
x = xmax;
} else {
y = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1);
x = xmin;
}

if (outCode == outCode1) {
x1 = x;
y1 = y;
outCode1 = computeOutCode(x1, y1);
} else {
x2 = x;
y2 = y;
outCode2 = computeOutCode(x2, y2);
}
}

if (accept) {
g.setColor(Color.RED);
g.drawLine(x1, y1, x2, y2);
}
}

18 | P a g e
private int computeOutCode(int x, int y) {
int code = 0;
if (x < xmin) code |= 1; // to the left of clip window
if (x > xmax) code |= 2; // to the right of clip window
if (y < ymin) code |= 4; // below clip window
if (y > ymax) code |= 8; // above clip window
return code;
}

public static void main(String[] args) {


int x1 = 50, y1 = 50, x2 = 300, y2 = 200;
int xmin = 100, ymin = 100, xmax = 200, ymax = 150;

JFrame frame = new JFrame("Line Clipping");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

LineClipping panel = new LineClipping(x1, y1, x2, y2, xmin, ymin, xmax, ymax);
frame.add(panel);
frame.setVisible(true);
}
}

Output :

19 | P a g e
Ex No. 6 POLYGON CLIPPING USING COHEN-SUTHERLAND ALGORITHM

AIM:

To write a JAVA program to clip a polygon using the line clipping algorithm.

ALGORITHM:

Step 1: Start the program

Step 2: Initialize the graphic mode using initgraph.

Step 3: Declare the variables and draw a window and a polygon shape of based on five lines
using window and line function.

Step 4: Using the clipping function,the values of the lines are checked whether the line is within
the rectangle coordinates xmin,ymin,xmax,ymax and clip it.

Step 5: Draw the clipped line in the window.

Step 6: Stop the program.

PROGRAM

Define the Polygon Class:


import java.awt.*;
import java.util.ArrayList;

public class Polygon {


private ArrayList<Point> vertices;

public Polygon() {
vertices = new ArrayList<>();
}

public void addVertex(int x, int y) {


vertices.add(new Point(x, y));
}

public ArrayList<Point> getVertices() {


return vertices;
}
}

Define the Clipping Window Class:


public class ClippingWindow {
private int xmin, ymin, xmax, ymax;

20 | P a g e
public ClippingWindow(int xmin, int ymin, int xmax, int ymax) {
this.xmin = xmin;
this.ymin = ymin;
this.xmax = xmax;
this.ymax = ymax;
}

public int getXmin() {


return xmin;
}

public int getYmin() {


return ymin;
}

public int getXmax() {


return xmax;
}

public int getYmax() {


return ymax;
}
}
Define the PolygonClipping Class:
import java.awt.*;
import java.util.ArrayList;

public class PolygonClipping {


private Polygon polygon;
private ClippingWindow window;

public PolygonClipping(Polygon polygon, ClippingWindow window) {


this.polygon = polygon;
this.window = window;
}

private ArrayList<Point> clipEdge(ArrayList<Point> inputVertices, int edge) {


ArrayList<Point> outputVertices = new ArrayList<>();
int size = inputVertices.size();

Point S = inputVertices.get(size - 1); // Start with the last point


for (Point E : inputVertices) {
if (inside(S, edge)) {
if (inside(E, edge)) {
outputVertices.add(E);
} else {
outputVertices.add(computeIntersection(S, E, edge));
}

21 | P a g e
} else if (inside(E, edge)) {
outputVertices.add(computeIntersection(S, E, edge));
outputVertices.add(E);
}

S = E;
}

return outputVertices;
}

private boolean inside(Point P, int edge) {


int x = P.x;
int y = P.y;

switch (edge) {
case 1: return x >= window.getXmin();
case 2: return y >= window.getYmin();
case 3: return x <= window.getXmax();
case 4: return y <= window.getYmax();
default: return false;
}
}

private Point computeIntersection(Point S, Point E, int edge) {


int x1 = S.x, y1 = S.y, x2 = E.x, y2 = E.y;
int xi = 0, yi = 0;

switch (edge) {
case 1: // Left Edge (x = xmin)
xi = window.getXmin();
yi = y1 + (x1 - xi) * (y2 - y1) / (x2 - x1);
break;
case 2: // Bottom Edge (y = ymin)
yi = window.getYmin();
xi = x1 + (y1 - yi) * (x2 - x1) / (y2 - y1);
break;
case 3: // Right Edge (x = xmax)
xi = window.getXmax();
yi = y1 + (x1 - xi) * (y2 - y1) / (x2 - x1);
break;
case 4: // Top Edge (y = ymax)
yi = window.getYmax();
xi = x1 + (y1 - yi) * (x2 - x1) / (y2 - y1);
break;
}

return new Point(xi, yi);

22 | P a g e
}

public ArrayList<Point> clipPolygon() {


ArrayList<Point> clippedVertices = new ArrayList<>(polygon.getVertices());
for (int edge = 1; edge <= 4; edge++) {
clippedVertices = clipEdge(clippedVertices, edge);
}

return clippedVertices;
}
}

Using the Classes:


import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;

public class Main extends JPanel {


private Polygon polygon;
private ClippingWindow window;

public Main() {
polygon = new Polygon();
polygon.addVertex(50, 50);
polygon.addVertex(150, 50);
polygon.addVertex(100, 150);

window = new ClippingWindow(100, 100, 200, 200);


}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

ArrayList<Point> clippedVertices = new PolygonClipping(polygon, window).clipPolygon();

int[] xPoints = new int[clippedVertices.size()];


int[] yPoints = new int[clippedVertices.size()];

for (int i = 0; i < clippedVertices.size(); i++) {


Point vertex = clippedVertices.get(i);
xPoints[i] = vertex.x;
yPoints[i] = vertex.y;
}

g.drawPolygon(xPoints, yPoints, clippedVertices.size());

// Draw the clipping window

23 | P a g e
g.drawRect(window.getXmin(), window.getYmin(), window.getXmax() - window.getXmin(),
window.getYmax() - window.getYmin());
}

public static void main(String[] args) {


JFrame frame = new JFrame("Polygon Clipping");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

Main panel = new Main();


frame.add(panel);
frame.setVisible(true);
}
}

24 | P a g e
Ex No. 7 3D TRANSFORMATION

AIM:

To write a JAVA program for the implementation of 3D transformation such as translation,


scaling, rotation.

ALGORITHM:

Step 1: Start the program.

Step 2: Initialize the graphic mode and declare the variables.

Step 3: Translation

a) Accept the translation vector(x,y).


b) Add the translation vector to the corresponding coordinates of the 3d object to obtain the
translation coordinates
c) Draw the 3d object.

Step 4: Scaling

a) Accept the scaling factor (x,y,z).


b) Multiply the scaling factor with the corresponding coordinates of the 3d object to obtain
scaling coordinates.
c) Draw the 3d objects.

Step 5: Rotation

a) Accept the rotation angle()


b) Using the angle calculate x1,y1,x2,y2,
c) Using that to draw 3d object x,y,z axis rotation.

Step 6: Stop the program

PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ThreeDTransformations extends JPanel implements ActionListener {


private int[] originalX = {50, 150, 150, 50, 50, 150, 150, 50}; // Example cube vertices x-coordinates
private int[] originalY = {50, 50, 150, 150, 50, 50, 150, 150}; // Example cube vertices y-coordinates
private int[] originalZ = {0, 0, 0, 0, 100, 100, 100, 100}; // Example cube vertices z-coordinates

private int numVertices = 8;

25 | P a g e
private int[] x = new int[numVertices];
private int[] y = new int[numVertices];
private int[] z = new int[numVertices];

private JButton translateButton, scaleButton, rotateButton;

private double[][] transformationMatrix = new double[4][4];

public ThreeDTransformations() {
setPreferredSize(new Dimension(400, 400));

translateButton = new JButton("Translate");


scaleButton = new JButton("Scale");
rotateButton = new JButton("Rotate");

translateButton.addActionListener(this);
scaleButton.addActionListener(this);
rotateButton.addActionListener(this);

add(translateButton);
add(scaleButton);
add(rotateButton);

System.arraycopy(originalX, 0, x, 0, numVertices);
System.arraycopy(originalY, 0, y, 0, numVertices);
System.arraycopy(originalZ, 0, z, 0, numVertices);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

g.setColor(Color.BLACK);

// Draw the original cube


for (int i = 0; i < 4; i++) {
int next = (i + 1) % 4;
int next2 = i + 4;
int next2Next = next2 + 1;

g.drawLine(x[i], y[i], x[next], y[next]);


g.drawLine(x[next], y[next], x[next2Next], y[next2Next]);
g.drawLine(x[next2Next], y[next2Next], x[next2], y[next2]);
g.drawLine(x[next2], y[next2], x[i], y[i]);

g.drawLine(x[i], y[i], x[next2], y[next2]);


g.drawLine(x[next], y[next], x[next2Next], y[next2Next]);

26 | P a g e
}

// Draw the transformed cube


for (int i = 0; i < 4; i++) {
int next = (i + 1) % 4;
int next2 = i + 4;
int next2Next = next2 + 1;

g.drawLine(x[i] + 200, y[i], x[next] + 200, y[next]);


g.drawLine(x[next] + 200, y[next], x[next2Next] + 200, y[next2Next]);
g.drawLine(x[next2Next] + 200, y[next2Next], x[next2] + 200, y[next2]);
g.drawLine(x[next2] + 200, y[next2], x[i] + 200, y[i]);

g.drawLine(x[i] + 200, y[i], x[next2] + 200, y[next2]);


g.drawLine(x[next] + 200, y[next], x[next2Next] + 200, y[next2Next]);
}
}

private void applyTransformation(double[][] matrix) {


double[] tempX = new double[numVertices];
double[] tempY = new double[numVertices];
double[] tempZ = new double[numVertices];

for (int i = 0; i < numVertices; i++) {


tempX[i] = x[i] * matrix[0][0] + y[i] * matrix[0][1] + z[i] * matrix[0][2] + matrix[0][3];
tempY[i] = x[i] * matrix[1][0] + y[i] * matrix[1][1] + z[i] * matrix[1][2] + matrix[1][3];
tempZ[i] = x[i] * matrix[2][0] + y[i] * matrix[2][1] + z[i] * matrix[2][2] + matrix[2][3];
}

System.arraycopy(tempX, 0, x, 0, numVertices);
System.arraycopy(tempY, 0, y, 0, numVertices);
System.arraycopy(tempZ, 0, z, 0, numVertices);

repaint();
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == translateButton) {
double tx = 50; // Translate by 50 units in x-direction
double ty = 50; // Translate by 50 units in y-direction
double tz = 50; // Translate by 50 units in z-direction
transformationMatrix = new double[][]{{1, 0, 0, tx}, {0, 1, 0, ty}, {0, 0, 1, tz}, {0, 0, 0, 1}};
} else if (e.getSource() == scaleButton) {
double sx = 1.5; // Scale by a factor of 1.5 in x-direction
double sy = 1.5; // Scale by a factor of 1.5 in y-direction
double sz = 1.5; // Scale by a factor of 1.5 in z-direction
transformationMatrix = new double[][]{{sx, 0, 0, 0}, {0, sy, 0, 0}, {0, 0, sz, 0}, {0, 0, 0, 1}};

27 | P a g e
} else if (e.getSource() == rotateButton) {
double angle = Math.toRadians(45); // Rotate by 45 degrees around z-axis
transformationMatrix = new double[][]{{Math.cos(angle), -Math.sin(angle), 0, 0},
{Math.sin(angle), Math.cos(angle), 0, 0},
{0, 0, 1, 0}, {0, 0, 0, 1}};
}

applyTransformation(transformationMatrix);
}

public static void main(String[] args) {


JFrame frame = new JFrame("3D Transformations");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 400);

ThreeDTransformations panel = new ThreeDTransformations();


frame.add(panel);
frame.setVisible(true);
}
}
Output :

28 | P a g e
Ex No. 8 COMPOSITE 2D TRANSFORMATION

AIM:

To write a JAVA program to implement composite 2D transformation

ALGORITHM:

Step 1: Start the program.

Step 2: Input the object coordinates.

Step 3: Translation

a) Enter the translation factors tx and ty


b) Move the original coordinate position (x,y,az,w) ,(x,y,p,q) and (az,w,p,q).

Step 6: Rotation

a) Enter the radian value ra.


b) Using the ra calculate theta value Θ=(float)(3.14xra)/180.
c) From the theta value calculate the x,y,p,q values.
d) Rotate the original coordinate position (x,y,az,w),( x,y,p,q) and (az,w,p,q).

Step 5: Scaling

a) Input the scaled factors sx and sy.

b) Transform the coordinates by x’=x*sx, y’=y*sy,az=az*sx, w=w*sy,p=p*sx,q=q*sy.

Step 6: Reflection

a) Along x-axis

theta=(float)(90*(3.14/180));

b) Along y-axis

theta=(float)(270*(3.14/180));

c) Along both-axis

theta=(float)(180*(3.14/180));

Using the theta value accordingly find the x,y,p,q values

Step 7 : Shearing

To shear the object using the formula


29 | P a g e
a) Along x-direction

y=y, x=x+(xls*y),

w=w; az=az+(xls*w),

q=q,p=p+(xls*q).

b) Along y-direction

x=x, y=y+(yls*x),

az=az,w=w+(yls*az),

p=p,q=q+(yls*p)

Step 8: Generate the output.

Step 9: Stop the program.

PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Composite2DTransformations extends JPanel implements ActionListener {


private int[] originalX = {50, 150, 150, 50}; // Example square vertices x-coordinates
private int[] originalY = {50, 50, 150, 150}; // Example square vertices y-coordinates

private int numVertices = 4;

private int[] x = new int[numVertices];


private int[] y = new int[numVertices];

private JButton transformButton;

public Composite2DTransformations() {
setPreferredSize(new Dimension(400, 400));

transformButton = new JButton("Transform");


transformButton.addActionListener(this);

add(transformButton);

System.arraycopy(originalX, 0, x, 0, numVertices);
System.arraycopy(originalY, 0, y, 0, numVertices);

30 | P a g e
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

g.setColor(Color.BLACK);

// Draw the original square


g.drawPolygon(x, y, numVertices);

// Draw the transformed square


g.drawPolygon(x, y, numVertices);

// Draw the lines connecting corresponding vertices of the original and transformed squares
for (int i = 0; i < numVertices; i++) {
g.drawLine(x[i], y[i], x[i] + 200, y[i]);
}
}

private void applyTransformation(double[][] matrix) {


double[] tempX = new double[numVertices];
double[] tempY = new double[numVertices];

for (int i = 0; i < numVertices; i++) {


tempX[i] = x[i] * matrix[0][0] + y[i] * matrix[0][1] + matrix[0][2];
tempY[i] = x[i] * matrix[1][0] + y[i] * matrix[1][1] + matrix[1][2];
}

System.arraycopy(tempX, 0, x, 0, numVertices);
System.arraycopy(tempY, 0, y, 0, numVertices);

repaint();
}

@Override
public void actionPerformed(ActionEvent e) {
double[][] translationMatrix = {{1, 0, 50}, {0, 1, 50}, {0, 0, 1}};
double[][] rotationMatrix = {{Math.cos(Math.toRadians(45)), -Math.sin(Math.toRadians(45)), 0},
{Math.sin(Math.toRadians(45)), Math.cos(Math.toRadians(45)), 0},
{0, 0, 1}};
double[][] scalingMatrix = {{1.5, 0, 0}, {0, 1.5, 0}, {0, 0, 1}};

// Apply transformations sequentially: translation, rotation, scaling


applyTransformation(translationMatrix);
applyTransformation(rotationMatrix);
applyTransformation(scalingMatrix);
}

31 | P a g e
public static void main(String[] args) {
JFrame frame = new JFrame("Composite 2D Transformations");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);

Composite2DTransformations panel = new Composite2DTransformations();


frame.add(panel);
frame.setVisible(true);
}
} Output :

32 | P a g e
Ex No.9 3D PROJECTIONS

AIM:

To write a JAVA program to implement 3D projection

ALGORITHM:

Step 1: Start the program.

Step 2: Initialize the variables.

Step 3: Get the number of sides ‘s’ using the calculate the coordinate points.

Step 4: Get the depth value ‘d’ uing the print the 3d object by draw3d function.

Step 5: Print the top view,side view and bottom view of the 3d object.

Step 6: Stop the program

PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ThreeDProjection extends JPanel implements ActionListener {


private int[] originalX = {-50, 50, 50, -50, -50, 50, 50, -50}; // Example cube vertices x-coordinates
private int[] originalY = {-50, -50, 50, 50, -50, -50, 50, 50}; // Example cube vertices y-coordinates
private int[] originalZ = {-50, -50, -50, -50, 50, 50, 50, 50}; // Example cube vertices z-coordinates

private int numVertices = 8;

private int[] x = new int[numVertices];


private int[] y = new int[numVertices];

private JButton projectButton;

public ThreeDProjection() {
setPreferredSize(new Dimension(400, 400));

projectButton = new JButton("Project");


projectButton.addActionListener(this);

add(projectButton);

System.arraycopy(originalX, 0, x, 0, numVertices);
System.arraycopy(originalY, 0, y, 0, numVertices);
}

33 | P a g e
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

g.setColor(Color.BLACK);

// Draw the original cube


for (int i = 0; i < 4; i++) {
int next = (i + 1) % 4;
int next2 = i + 4;
int next2Next = next2 + 1;

g.drawLine(x[i], y[i], x[next], y[next]);


g.drawLine(x[next], y[next], x[next2Next], y[next2Next]);
g.drawLine(x[next2Next], y[next2Next], x[next2], y[next2]);
g.drawLine(x[next2], y[next2], x[i], y[i]);
}

// Draw the lines connecting corresponding vertices of the original and projected cubes
for (int i = 0; i < 4; i++) {
int next = (i + 1) % 4;
int next2 = i + 4;
int next2Next = next2 + 1;

g.drawLine(x[i], y[i], x[next], y[next]);


g.drawLine(x[next], y[next], x[next2Next], y[next2Next]);
g.drawLine(x[next2Next], y[next2Next], x[next2], y[next2]);
g.drawLine(x[next2], y[next2], x[i], y[i]);
}
}

private void applyProjection() {


double perspective = 100; // Distance from the viewer to the projection plane

for (int i = 0; i < numVertices; i++) {


x[i] = (int) (x[i] * perspective / (perspective + originalZ[i]));
y[i] = (int) (y[i] * perspective / (perspective + originalZ[i]));
}

repaint();
}

@Override
public void actionPerformed(ActionEvent e) {
applyProjection();
}

34 | P a g e
public static void main(String[] args) {
JFrame frame = new JFrame("3D Projection");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 400);

ThreeDProjection panel = new ThreeDProjection();


frame.add(panel);
frame.setVisible(true);
}
}
Output :

35 | P a g e
Ex No.10 WINDOW TO VIEWPORT MAPPING

AIM:

To write a JAVA program to clip a window to viewport mapping.

ALGORITHM:

Step 1: Start the program

Step 2: Get the maximum and minimum coordinates of the window.

Step 3: Get the maximum and minimum coordinates of the viewport.

Step 4: Get the vertices of the triangles.

Step 5: Display the output by fiiting window in viewport.

Step 6: Stop the program.

PROGRAM

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class WindowToViewportMapping extends JPanel implements ActionListener {


private int[] originalX = {50, 150, 150, 50}; // Example square vertices x-coordinates
private int[] originalY = {50, 50, 150, 150}; // Example square vertices y-coordinates

private int numVertices = 4;

private int[] x = new int[numVertices];


private int[] y = new int[numVertices];

private JButton mapButton;

private int xmin = 0; // Viewport coordinates


private int ymin = 0;
private int xmax = 300;
private int ymax = 300;

private int windowXmin = -50; // Window coordinates


private int windowYmin = -50;
private int windowXmax = 50;
private int windowYmax = 50;

public WindowToViewportMapping() {
setPreferredSize(new Dimension(400, 400));

36 | P a g e
mapButton = new JButton("Map");
mapButton.addActionListener(this);

add(mapButton);

System.arraycopy(originalX, 0, x, 0, numVertices);
System.arraycopy(originalY, 0, y, 0, numVertices);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

g.setColor(Color.BLACK);

// Draw the original square


g.drawPolygon(x, y, numVertices);

// Draw the viewport


g.drawRect(xmin, ymin, xmax - xmin, ymax - ymin);
}

private void applyMapping() {


for (int i = 0; i < numVertices; i++) {
x[i] = (x[i] - windowXmin) * (xmax - xmin) / (windowXmax - windowXmin) + xmin;
y[i] = (y[i] - windowYmin) * (ymax - ymin) / (windowYmax - windowYmin) + ymin;
}

repaint();
}

@Override
public void actionPerformed(ActionEvent e) {
applyMapping();
}

public static void main(String[] args) {


JFrame frame = new JFrame("Window to Viewport Mapping");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);

WindowToViewportMapping panel = new WindowToViewportMapping();


frame.add(panel);
frame.setVisible(true);
}
}

37 | P a g e
Output :

38 | P a g e

You might also like