CG Lab PV Assignment
CG Lab PV Assignment
Assignment 2
CG LAB
Student Name: Lakshay Baskotra UID: 22BCS15016
Branch: BE-CSE Section/Group: IOT-605 ‘B’
Semester: 6th Date of Performance: 10/04/2025
Subject Name: Computer Graphics with Lab Subject Code:22CSH-352
Code :
# Ray class
class Ray:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
# Sphere class
class Sphere:
def init (self, center, radius, color, reflection=0.5):
self.center, self.radius, self.color, self.reflection = center, radius,
color, reflection
# Light
light_pos = Vec3(5, 5, -10)
# Scene setup
scene = [
Sphere(Vec3(0, -1, 3), 1, (255, 0, 0)), # Red Sphere
Sphere(Vec3(2, 0, 4), 1, (0, 0, 255)), # Blue Sphere
Sphere(Vec3(-2, 0, 4), 1, (0, 255, 0)), # Green Sphere
Sphere(Vec3(0, -5001, 0), 5000, (255, 255, 0)) # Ground
]
if hit_obj:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
# Shadow check
shadow_ray = Ray(hit_point + normal * 0.001, to_light)
in_shadow = any(obj.intersect(shadow_ray) for obj in scene if obj !=
hit_obj)
# Diffuse
intensity = max(normal.dot(to_light), 0) * (0.2 if in_shadow else 1.0)
local_color = tuple(min(int(c * intensity), 255) for c in hit_obj.color)
# Reflection
if depth < MAX_DEPTH and hit_obj.reflection > 0:
reflect_dir = ray.direction - normal * 2 * ray.direction.dot(normal)
reflect_ray = Ray(hit_point + normal * 0.001, reflect_dir)
reflect_color = trace(reflect_ray, depth + 1)
color = tuple(
int(local_color[i] * (1 - hit_obj.reflection) + reflect_color[i]
* hit_obj.reflection)
for i in range(3)
)
else:
color = local_color
return color
# Create image
img = Image.new("RGB", (WIDTH, HEIGHT))
pixels = img.load()
img.save("raytracing_output.png")
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Ques 2:
Problem Statements: Write a program to model and render a 3D fractal object such as the
Mandelbrot set or a 3D Koch snowflake.
Objective: Learn iterative fractal generation techniques and visualize self-similarity properties in
3D.
Code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Line3DCollection
def divide(points):
new_points = []
for i in range(len(points) - 1):
a = points[i]
b = points[i + 1]
vec = (b - a) / 3
p1 = a + vec
p3 = a + 2 * vec
angle = np.pi / 3
rotation = np.array([
[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]
])
p2 = p1 + rotation.dot(vec)
new_points += [a, p1, p2, p3]
new_points.append(points[-1])
return new_points
for _ in range(order):
points = divide(points)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
return np.array(points)
return faces
# Generate fractal
order = 3
points = koch_snowflake(order)
faces = extrude_to_3d(points)
# Plot
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
OUTPUT:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Ques 3:
Problem Statements: Create an interactive simulation of celestial mechanics for planets orbiting
a star system with gravity effects.
Objective: Apply physics formulas for gravitational forces and simulate realistic orbital paths in
2D or 3D.
Code:
import pygame
import math
# Constants
G = 6.67430e-11 # Gravitational constant
SCALE = 1e-9 # Scale to draw pixels
TIMESTEP = 3600 # One hour per frame
class Body:
def init (self, x, y, radius, color, mass, name="Planet"):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.mass = mass
self.name = name
self.orbit = []
self.x_vel = 0
self.y_vel = 0
if len(self.orbit) > 2:
updated_points = [
(px * SCALE + WIDTH / 2, py * SCALE + HEIGHT / 2)
for px, py in self.orbit
]
pygame.draw.lines(win, self.color, False, updated_points, 2)
def main():
pygame.init()
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Celestial Simulation")
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
win.fill((0, 0, 0))
pygame.display.update()
pygame.quit()
Output:
Ques4:
Problem Statement: Develop a cloth simulation that reacts to user inputs and simulates realistic
fabric behavior.
Aim: To simulate flexible materials using physics- based techniques.
Objective: Learn to model forces like tension, shear, and gravity to create realistic cloth
simulations.
Code:
import pygame
import math
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Cloth Simulation")
class Point:
def init (self, x, y, pinned=False):
self.x = x
self.y = y
self.old_x = x
self.old_y = y
self.pinned = pinned
self.constraints = []
def update(self):
if self.pinned:
return
dx = (self.x - self.old_x) * FRICTION
dy = (self.y - self.old_y) * FRICTION
self.old_x = self.x
self.old_y = self.y
self.x += dx
self.y += dy + GRAVITY
def constrain(self):
for c in self.constraints:
c.solve()
class Constraint:
def init (self, p1, p2):
self.p1 = p1
self.p2 = p2
self.length = math.dist((p1.x, p1.y), (p2.x, p2.y))
def solve(self):
dx = self.p2.x - self.p1.x
dy = self.p2.y - self.p1.y
dist = math.sqrt(dx**2 + dy**2)
diff = (self.length - dist) / dist
if not self.p1.pinned:
self.p1.x -= offset_x
self.p1.y -= offset_y
if not self.p2.pinned:
self.p2.x += offset_x
self.p2.y += offset_y
points = []
def draw_lines(surface):
for row in points:
for point in row:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
for c in point.constraints:
pygame.draw.line(surface, (100, 255, 100),
(int(c.p1.x), int(c.p1.y)),
(int(c.p2.x), int(c.p2.y)), 1)
def update_cloth():
for row in points:
for point in row:
point.update()
for _ in range(CONSTRAINT_ITERATIONS):
for row in points:
for point in row:
point.constrain()
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
screen.fill((30, 30, 30))
update_cloth()
draw_lines(screen)
for row in points:
for point in row:
point.draw(screen)
pygame.display.flip()
pygame.quit()
Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Ques 5:
Problem Statements : Build a dynamic water simulation system that uses particle or grid-based
methods to depict fluid motion.
Aim: To simulate realistic water motion using computational techniques.
Objective: Understand fluid dynamics principles and their implementation in real-time
simulations.
Code:
import pygame
import random
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
import math
# Initialize Pygame
pygame.init()
# Window settings
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("💧 Water Simulation - Particle Based")
# Colors
BLUE = (0, 120, 255)
BLACK = (0, 0, 0)
# Physics constants
GRAVITY = 0.3
FRICTION = 0.98
NUM_PARTICLES = 300
class Particle:
def init (self, x, y):
self.x = x
self.y = y
self.radius = 3
self.color = BLUE
self.vx = random.uniform(-1, 1)
self.vy = random.uniform(-1, 0)
def move(self):
self.vy += GRAVITY
self.vx *= FRICTION
self.vy *= FRICTION
self.x += self.vx
self.y += self.vy
# Bounce on edges
if self.x <= 0 or self.x >= WIDTH:
self.vx *= -1
if self.y >= HEIGHT - self.radius:
self.vy *= -0.6
self.y = HEIGHT - self.radius
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
# Create particles
particles = [Particle(random.randint(300, 500), random.randint(100, 200)) for _
in range(NUM_PARTICLES)]
# Main loop
running = True
clock = pygame.time.Clock()
while running:
screen.fill(BLACK)
for p in particles:
p.move()
p.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Output: