Create obj module for scene objects

This commit is contained in:
Camden Dixie O'Brien
2025-09-23 15:35:26 +01:00
parent 0ea0c1edd2
commit 08f1a2a4dc
5 changed files with 85 additions and 26 deletions

36
demo.c
View File

@@ -1,4 +1,6 @@
#include "ff.h"
#include "obj.h"
#include "ray.h"
#include "vec3.h"
#include <limits.h>
@@ -14,9 +16,7 @@
#define FOCLEN 1.0
typedef struct {
vec3_t orig, dir;
} ray_t;
#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))
typedef struct {
vec3_t centre;
@@ -34,35 +34,19 @@ static const vec3_t vp_v = { 0, -VP_H, 0 };
static const vec3_t pix_x_step = { VP_W / W, 0, 0 };
static const vec3_t pix_y_step = { 0, -VP_H / H, 0 };
static const sphere_t obj = {
.centre = { 1.0, 0.0, -3.0 },
.rad = 1.0,
static const obj_t scene[] = {
SPHERE(1.0, 0.0, -3.0, 1.0),
SPHERE(-2.0, 0.0, -5.0, 1.0),
};
static pix_t pix[W * H];
static double intersect(sphere_t sphere, ray_t ray)
{
const vec3_t disp = vec3_sub(sphere.centre, ray.orig);
const double a = vec3_dot(ray.dir, ray.dir);
const double b = -2.0 * vec3_dot(ray.dir, disp);
const double c = vec3_dot(disp, disp) - sphere.rad * sphere.rad;
const double discriminant = b * b - 4 * a * c;
if (discriminant < 0)
return -1.0;
else
return (-b - sqrt(discriminant)) / (2.0 * a);
}
static vec3_t raycol(ray_t ray)
{
const double t = intersect(obj, ray);
if (t > 0.0) {
const vec3_t p = vec3_add(ray.orig, vec3_scale(ray.dir, t));
const vec3_t normal = vec3_unit(vec3_sub(p, obj.centre));
return vec3_scale(vec3_add(normal, white), 0.5);
hit_t hit;
for (unsigned i = 0; i < NELEMS(scene); ++i) {
if (scene[i].intersect(scene[i].params, ray, &hit))
return vec3_scale(vec3_add(hit.normal, white), 0.5);
}
const double a = (ray.dir.y + 1.0) / 2.0;