#include <iostream>
#include <cmath>
using namespace std;
// Structure for a 3D vector
struct Vec3 {
float x, y, z;
// Constructor to initialize vector
Vec3(float x = 0, float y = 0, float z = 0) : x(x), y(y), z(z) {}
// Vector addition
Vec3 operator+(const Vec3& v) const {
return Vec3(x + v.x, y + v.y, z + v.z);
}
// Vector subtraction
Vec3 operator-(const Vec3& v) const {
return Vec3(x - v.x, y - v.y, z - v.z);
}
// Scalar multiplication
Vec3 operator*(float t) const {
return Vec3(x * t, y * t, z * t);
}
// Dot product
float dot(const Vec3& v) const {
return x * v.x + y * v.y + z * v.z;
}
// Length of the vector (magnitude)
float length() const {
return sqrt(x * x + y * y + z * z);
}
// Normalize the vector
Vec3 normalize() const {
float len = length();
return Vec3(x / len, y / len, z / len);
}
};
// Structure for a ray
struct Ray {
Vec3 origin;
Vec3 direction;
// Constructor to initialize ray
Ray(const Vec3& origin, const Vec3& direction) : origin(origin), direction(direction.normalize()) {}
// Get point at distance t along the ray
Vec3 pointAtParameter(float t) const {
return origin + direction * t;
}
};
// Structure for a sphere
struct Sphere {
Vec3 center;
float radius;
// Constructor to initialize sphere
Sphere(const Vec3& center, float radius) : center(center), radius(radius) {}
// Check if a ray intersects with the sphere
bool intersect(const Ray& ray, float& t) const {
Vec3 oc = ray.origin - center;
float a = ray.direction.dot(ray.direction);
float b = 2.0f * oc.dot(ray.direction);
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.0f * a);
return true;
}
}
};
int main() {
// Define a sphere at position (0, 0, -5) with radius 1
Sphere sphere(Vec3(0, 0, -5), 1);
// Define a ray originating at the camera position (0, 0, 0) and pointing in the z direction
Ray ray(Vec3(0, 0, 0), Vec3(0, 0, -1));
float t;
if (sphere.intersect(ray, t)) {
Vec3 hitPoint = ray.pointAtParameter(t);
cout << "Ray intersects the sphere at point (" << hitPoint.x << ", " << hitPoint.y << ", " << hitPoint.z << ")" << endl;
} else {
cout << "Ray does not intersect the sphere." << endl;
}
return 0;
}