Added the intervals struct

This commit is contained in:
Luxdragon 2024-02-27 19:01:28 +01:00
parent 0371842a00
commit c1a66dd653

45
main.go
View file

@ -159,6 +159,37 @@ func (r *Ray) At(t float32) Vec3 {
}
}
// =============== INTERVAL =================
type Interval struct {
min, max float32
}
func NewInterval(borders ...float32) *Interval {
if (len(borders) == 2) {
return &Interval{
min: borders[0],
max: borders[1],
}
} else {
return &Interval{
min: float32(math.Inf(1)),
max: float32(math.Inf(-1)),
}
}
}
func (i *Interval) Contains(x float32) bool {
return i.min <= x && x <= i.max
}
func (i *Interval) Surrounds(x float32) bool {
return i.min < x && x < i.max
}
var Empty *Interval = NewInterval()
var Universe *Interval = NewInterval(float32(math.Inf(-1)), float32(math.Inf(1)))
// =============== HIT ======================
@ -187,7 +218,7 @@ type Sphere struct {
radius float32
}
func (s Sphere) Hit_sphere(r *Ray, ray_tmin float32, ray_tmax float32, rec *Hit_record) bool {
func (s Sphere) Hit_sphere(r *Ray, ray_t *Interval, rec *Hit_record) bool {
oc := r.Origin().Sub(s.center)
a := r.Direction().Length_squared()
half_b := Dot(oc, r.Direction())
@ -201,9 +232,9 @@ func (s Sphere) Hit_sphere(r *Ray, ray_tmin float32, ray_tmax float32, rec *Hit_
// find the nearest root that lies in the acceptable range
root := (-half_b - sqrtd) / a
if (root <= ray_tmin || ray_tmax<= root) {
if (!ray_t.Surrounds(root)) {
root = (sqrtd-half_b) / a
if (root <= ray_tmin || ray_tmax <= root) {
if (!ray_t.Surrounds(root)) {
return false
}
}
@ -231,13 +262,13 @@ func (hl *Hittable) Clear() {
hl.spheres = []Sphere{}
}
func (hl Hittable) Hit(r *Ray, ray_tmin float32, ray_tmax float32, rec *Hit_record) bool {
func (hl Hittable) Hit(r *Ray, ray_t Interval, rec *Hit_record) bool {
var temp_rec Hit_record
var hit_anything bool = false
var closest_so_far float32 = ray_tmax
var closest_so_far float32 = ray_t.max
for _, sphere := range hl.spheres {
if (sphere.Hit_sphere(r, ray_tmin, closest_so_far, &temp_rec)) {
if (sphere.Hit_sphere(r, NewInterval(ray_t.min, closest_so_far), &temp_rec)) {
hit_anything = true
closest_so_far = temp_rec.t
*rec = temp_rec
@ -248,7 +279,7 @@ func (hl Hittable) Hit(r *Ray, ray_tmin float32, ray_tmax float32, rec *Hit_reco
func Ray_color(r Ray, world *Hittable) Vec3 {
var rec Hit_record
if (world.Hit(&r, 0, float32(math.Inf(1)), &rec)) {
if (world.Hit(&r, *NewInterval(0, float32(math.Inf(1))), &rec)) {
return rec.normal.Add(NewColor(1,1,1)).Mult(0.5)
}
unit_direction := Unit_vector(r.Direction())