CG Lab Assignement
CG Lab Assignement
PROBLEM-1
1. Problem Statement: Implement a ray-tracing renderer to simulate realistic
lighting effects, including shadows and reflections.
2. Aim: To simulate realistic light behavior in computer graphics.
3. Objective: Understand ray tracing concepts, including intersections, light
reflection, and refraction for photorealistic rendering.
4. Code:
#include <graphics.h>
#include <cmath>
#include <iostream>
#include <conio.h>
using namespace std;
struct Vec3 {
float x, y, z;
Vec3(float x_=0, float y_=0, float z_=0) : x(x_), y(y_), z(z_) {}
Vec3 operator + (const Vec3& v) const { return Vec3(x + v.x, y + v.y, z + v.z); }
Vec3 operator - (const Vec3& v) const { return Vec3(x - v.x, y - v.y, z - v.z); }
Vec3 operator * (float s) const { return Vec3(x * s, y * s, z * s); }
Vec3 operator / (float s) const { return Vec3(x / s, y / s, z / s); }
};
struct Sphere {
Vec3 center;
float radius;
int color;
Sphere(Vec3 c, float r, int col) : center(c), radius(r), color(col) {}
bool intersect(const Vec3& rayOrig, const Vec3& rayDir, float &t) {
Vec3 oc = rayOrig - center;
float a = rayDir.dot(rayDir);
float b = 2.0 * oc.dot(rayDir);
float c = oc.dot(oc) - radius * radius;
float discriminant = b*b - 4*a*c;
if (discriminant < 0) return false;
else {
t = (-b - sqrt(discriminant)) / (2*a);
return t > 0;
}}
};
int applyLighting(int color, float intensity) {
int r = min(255, int((color >> 16 & 255) * intensity));
int g = min(255, int((color >> 8 & 255) * intensity));
int b = min(255, int((color & 255) * intensity));
return COLOR(r, g, b);
}
void drawRayTracedScene() {
Vec3 camPos(0, 0, 0);
float viewportSize = 1.0;
float projectionPlaneZ = 1.0;
PROBLEM-2
1.Problem Statement: Create a 3D maze generator and solver, visualized using
perspective transformations and real-time rendering.
struct Cell {
int x, y;
bool visited;
bool walls[4]; // top, right, bottom, left
Cell(int x_=0, int y_=0) {
x = x_;
y = y_;
visited = false;
for (int i = 0; i < 4; i++) walls[i] = true;
}
int index(int x, int y) {
if (x < 0 || y < 0 || x >= cols || y >= rows) return -1;
return x + y * cols;
}
void draw(int offsetX, int offsetY, bool fillCell = false) {
int x1 = x * cellSize + offsetX;
int y1 = y * cellSize + offsetY;
int x2 = x1 + cellSize;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
int y2 = y1 + cellSize;
setcolor(WHITE);
if (walls[0]) line(x1, y1, x2, y1); // top
if (walls[1]) line(x2, y1, x2, y2); // right
if (walls[2]) line(x2, y2, x1, y2); // bottom
if (walls[3]) line(x1, y2, x1, y1); // left
if (fillCell) {
setfillstyle(SOLID_FILL, LIGHTBLUE);
bar(x1+1, y1+1, x2-1, y2-1);
}}
};
std::vector<Cell> grid;
std::stack<Cell*> stack;
Cell* current;
Cell* getNeighbor(Cell* cell) {
std::vector<Cell*> neighbors;
int x = cell->x;
int y = cell->y;
int indices[] = {
cell->index(x, y-1), // top
cell->index(x+1, y), // right
cell->index(x, y+1), // bottom
cell->index(x-1, y) // left
};
for (int i = 0; i < 4; i++) {
int idx = indices[i];
if (idx != -1 && !grid[idx].visited)
neighbors.push_back(&grid[idx]);
}
if (!neighbors.empty()) {
int r = rand() % neighbors.size();
return neighbors[r];
}
return NULL;
}
void removeWalls(Cell* a, Cell* b) {
int dx = a->x - b->x;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
current = &grid[0];
int offsetX = 50;
int offsetY = 50;
// Generate maze
while (true) {
cleardevice();
generateMaze(offsetX, offsetY);
delay(20);
if (stack.empty()) break;
}
// Final Maze Display
for (int i = 0; i < grid.size(); i++)
grid[i].draw(offsetX, offsetY);
getch();
closegraph();
return 0;
5.Output
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
PROBLEM-3
1.Problem Statement: Create an interactive simulation of celestial mechanics for
planets orbiting a star system with gravity effects.
2.Aim: To visualize gravitational force interactions in a dynamic celestial system.
3.Objective: Apply physics formulas for gravitational forces and simulate realistic
orbital paths in 2D or 3D.
4.Code:
#include <graphics.h>
#include <cmath>
#include <vector>
#include <ctime>
#include <cstdlib>
#define G 0.1 // Gravitational constant (scaled for screen simulation)
#define NUM_PLANETS 3
#define TIME_STEP 1
struct Body {
double x, y; // Position
double vx, vy; // Velocity
double mass;
int radius;
int color;
void updatePosition() {
x += vx * TIME_STEP;
y += vy * TIME_STEP;
}
void draw() {
setcolor(color);
setfillstyle(SOLID_FILL, color);
fillellipse(x, y, radius, radius);
}
};
int main() {
int gd = DETECT, gm;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
PROBLEM-4
1.Problem Statement: Develop a cloth simulation that reacts to user inputs and
simulates realistic fabric behavior.
2.Aim: To simulate flexible materials using physics-based techniques.
3.Objective: Learn to model forces like tension, shear, and gravity to create
realistic cloth simulations.
4.Code:
#include <graphics.h>
#include <vector>
#include <math.h>
#include <conio.h>
struct Point {
float x, y;
float oldx, oldy;
bool pinned;
Point(float _x, float _y, bool pin = false) {
x = _x;
y = _y;
oldx = _x;
oldy = _y;
pinned = pin;
}
void update() {
if (pinned) return;
float vx = (x - oldx) * damping;
float vy = (y - oldy) * damping;
oldx = x;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
oldy = y;
x += vx;
y += vy + gravity;
}
void draw() {
circle(x, y, 2);
floodfill(x, y, WHITE);
}
void constrain(float minX, float maxX, float minY, float maxY) {
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
}};
struct Stick {
Point *p1, *p2;
float length;
Stick(Point *a, Point *b) {
p1 = a;
p2 = b;
float dx = p2->x - p1->x;
float dy = p2->y - p1->y;
length = sqrt(dx * dx + dy * dy);
}
void update() {
float dx = p2->x - p1->x;
float dy = p2->y - p1->y;
float dist = sqrt(dx * dx + dy * dy);
float diff = length - dist;
float percent = diff / dist / 2;
float offsetX = dx * percent;
float offsetY = dy * percent;
if (!p1->pinned) {
p1->x -= offsetX;
p1->y -= offsetY;
}
if (!p2->pinned) {
p2->x += offsetX;
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
p2->y += offsetY;
}}
void draw() {
line(p1->x, p1->y, p2->x, p2->y);
}
};
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
std::vector<Point> points;
std::vector<Stick> sticks;
// Constraint solving
for (int it = 0; it < iterations; it++) {
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
5.Output:
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
PROBLEM-5
1.Problem Statement: Build a 3D game engine with basic physics, lighting, and
camera movement.
2.Aim: To integrate multiple computer graphics concepts into a functional game
engine.
3.Objective: Combine graphics, physics, and interactivity to create a versatile game
development framework.
4.Code:
#include <graphics.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
// Target structure
struct Target {
int x, y, radius;
int speed;
};
// Global variables
int shooterX = 300, shooterY = 400;
int bulletX = -1, bulletY = -1;
int bulletSpeed = 10;
bool bulletFired = false;
Target target = {50, 100, 20, 5};
// Function to draw the shooter
void drawShooter() {
setcolor(WHITE);
rectangle(shooterX - 20, shooterY, shooterX + 20, shooterY + 10);
rectangle(shooterX - 5, shooterY - 20, shooterX + 5, shooterY);
}
// Function to draw the bullet
void drawBullet() {
if (bulletFired) {
setcolor(RED);
circle(bulletX, bulletY, 3);
}}
// Function to draw the moving target
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
void drawTarget() {
setcolor(GREEN);
circle(target.x, target.y, target.radius);
}
// Function to move the target horizontally
void moveTarget() {
target.x += target.speed;
if (target.x >= getmaxx() - target.radius || target.x <= target.radius) {
target.speed = -target.speed;
}}
// Function to move the bullet
void moveBullet() {
if (bulletFired) {
bulletY -= bulletSpeed;
if (bulletY < 0) bulletFired = false;
}}
// Check if bullet hits the target
bool checkCollision() {
if (!bulletFired) return false;
int dx = bulletX - target.x;
int dy = bulletY - target.y;
int distance = sqrt(dx * dx + dy * dy);
return distance < target.radius;
}
// Game rendering loop
void gameLoop() {
cleardevice();
drawShooter();
drawTarget();
drawBullet();
moveTarget();
moveBullet();
if (checkCollision()) {
outtextxy(250, 200, "Target Hit!");
bulletFired = false;
target.x = rand() % (getmaxx() - 40) + 20;
}
delay(30);
}
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
outtextxy(10, 10, "Use Left/Right Arrow Keys to Move | SPACE to Shoot | ESC to Exit");
while (1) {
if (kbhit()) {
char ch = getch();
if (ch == 27) break; // ESC to exit
if (ch == 75 && shooterX > 30) shooterX -= 10; // Left Arrow
if (ch == 77 && shooterX < getmaxx() - 30) shooterX += 10; // Right Arrow
if (ch == ' ' && !bulletFired) {
bulletFired = true;
bulletX = shooterX;
bulletY = shooterY - 20;
} }
gameLoop();
}
closegraph();
return 0;
}
5.Output: