Create material abstraction

This commit is contained in:
2025-09-23 15:36:08 +01:00
parent b15edd1906
commit ce45c57662
8 changed files with 84 additions and 26 deletions

View File

@@ -30,32 +30,29 @@ static const vec3_t lightblue = { 0.4, 0.6, 1.0 };
static const vec3_t white = { 1.0, 1.0, 1.0 };
static const vec3_t black = { 0.0, 0.0, 0.0 };
static ray_t scatter(hit_t hit, rng_t *rng)
{
return (ray_t) {
.orig = hit.point,
.dir = vec3_add(hit.normal, rng_vec3(rng)),
};
}
static vec3_t
trace(ray_t ray, const obj_t *scene, unsigned scene_count, rng_t *rng)
{
double coeff = 1.0;
vec3_t colour = white;
for (unsigned i = 0; i < MAX_ITER; ++i) {
hit_t hit = { .t = DBL_MAX };
for (unsigned j = 0; j < scene_count; ++j)
scene[j].intersect(scene[j].params, ray, &hit, MIN_T, hit.t);
material_t material = {};
for (unsigned j = 0; j < scene_count; ++j) {
if (scene[j].intersect(scene[j].params, ray, &hit, MIN_T, hit.t))
material = scene[j].material;
}
if (hit.t == DBL_MAX) {
const double a = (ray.dir.y + 1.0) / 2.0;
return vec3_scale(
vec3_add(vec3_scale(lightblue, a), vec3_scale(white, 1 - a)),
coeff);
const vec3_t bg = vec3_add(
vec3_scale(lightblue, a), vec3_scale(white, 1 - a));
return vec3_hadamard(colour, bg);
}
ray = scatter(hit, rng);
coeff *= 0.3;
vec3_t atten;
if (!material.scatter(material.params, hit, rng, &ray, &atten))
break;
colour = vec3_hadamard(colour, atten);
}
return black;

12
src/material.c Normal file
View File

@@ -0,0 +1,12 @@
#include "material.h"
bool scatter_lambertian(
material_params_t params, hit_t hit, rng_t *rng, ray_t *ray,
vec3_t *atten_out)
{
const vec3_t dir = vec3_unit(vec3_add(hit.normal, rng_vec3(rng)));
ray->orig = hit.point;
ray->dir = vec3_len(dir) == 0 ? hit.normal : dir;
*atten_out = params.lambertian.albedo;
return true;
}

View File

@@ -40,6 +40,15 @@ vec3_t vec3_cross(vec3_t v, vec3_t u)
};
}
vec3_t vec3_hadamard(vec3_t v, vec3_t u)
{
return (vec3_t) {
.x = v.x * u.x,
.y = v.y * u.y,
.z = v.z * u.z,
};
}
double vec3_len(vec3_t v)
{
return sqrt(v.x * v.x + v.y * v.y + v.z * v.z);