From a654eccc414d57ef6af6d62bba5cbc06e6901282 Mon Sep 17 00:00:00 2001 From: neviyn Date: Sun, 8 Nov 2020 22:44:48 +0000 Subject: [PATCH] Added Ray type --- src/ray.nim | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/ray.nim diff --git a/src/ray.nim b/src/ray.nim new file mode 100644 index 0000000..ae1299c --- /dev/null +++ b/src/ray.nim @@ -0,0 +1,34 @@ +from "./tuple" import Tuple4, isPoint, isVector, `+`, `*` + +type + Ray* = object + origin: Tuple4 + direction: Tuple4 + RayCreationError = object of CatchableError + +proc ray(origin, direction: Tuple4): Ray = + if(not origin.isPoint() or not direction.isVector()): + raise newException(RayCreationError, "origin must be a point and direction must be a vector") + result.origin = origin + result.direction = direction + +proc position(ray: Ray, t: float): Tuple4 = + ray.origin + ray.direction * t + +when isMainModule: + import unittest + from "./tuple" import point, vector, `==` + suite "ray": + test "Ray creation": + let origin = point(1.0, 2.0, 3.0) + let direction = vector(4.0, 5.0, 6.0) + let ray = ray(origin, direction) + check(ray.origin == origin) + check(ray.direction == direction) + + test "Computing a point from a distance": + let ray = ray(point(2.0, 3.0, 4.0), vector(1.0, 0.0, 0.0)) + check(ray.position(0.0) == point(2.0, 3.0, 4.0)) + check(ray.position(1.0) == point(3.0, 3.0, 4.0)) + check(ray.position(-1.0) == point(1.0, 3.0, 4.0)) + check(ray.position(2.5) == point(4.5, 3.0, 4.0)) \ No newline at end of file