-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrender_intersects.c
More file actions
79 lines (73 loc) · 2.67 KB
/
Copy pathrender_intersects.c
File metadata and controls
79 lines (73 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* render_intersects.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: khlavaty <khlavaty@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/06 14:14:27 by fvonsovs #+# #+# */
/* Updated: 2024/09/12 21:31:01 by khlavaty ### ########.fr */
/* */
/* ************************************************************************** */
#include "minirt.h"
int intersect(t_ray ray, t_obj *obj, float *t)
{
if (obj->type == SPHERE)
return (sphere_intersect(ray, obj->object, t));
if (obj->type == PLANE)
return (plane_intersect(ray, obj->object, t));
if (obj->type == CYLINDER)
return (cylinder_intersect(ray, obj->object, t));
else
return (0);
}
// calculate vector from ray origin to sphere center
// calculate quadratic equation coeffivarsents
// calculates vars.disc to see if intersects
// calculates two possible solutions intersection points
// finds the correct intersection point (smallest distance *t)
int sphere_intersect(t_ray ray, t_sp *sphere, float *t)
{
t_cyl_intersect vars;
float radius;
radius = sphere->dia / 2.0;
vars.oc = vec_sub(ray.orig, sphere->pos);
vars.a = vec_dot(ray.dir, ray.dir);
vars.b = 2.0 * vec_dot(vars.oc, ray.dir);
vars.c = vec_dot(vars.oc, vars.oc) - (radius * radius);
vars.disc = (vars.b * vars.b) - (4 * vars.a * vars.c);
if (vars.disc < 0)
return (0);
vars.t0 = (-vars.b - sqrt(vars.disc)) / (2.0 * vars.a);
vars.t1 = (-vars.b + sqrt(vars.disc)) / (2.0 * vars.a);
if (vars.t0 > 1e-6 || vars.t1 > 1e-6)
{
if (vars.t0 > 1e-6)
*t = vars.t0;
else
*t = vars.t1;
return (1);
}
return (0);
}
// calculates dot product between ray direction and plane normal
// if denom is close to 0, it is parallel = no intersection
// if not, calculate vector from ray origin to a point on the plane
// calculate numerator of intersection formula
// calculate intersection distance, if > 0 we hit
int plane_intersect(t_ray ray, t_pl *plane, float *t)
{
t_float_3 vec;
float denom;
float num;
denom = vec_dot(ray.dir, plane->vec);
if (fabs(denom) > 1e-6)
{
vec = vec_sub(plane->pos, ray.orig);
num = vec_dot(vec, plane->vec);
*t = num / denom;
if (*t >= 1e-6)
return (1);
}
return (0);
}