Home My Page Projects Code Snippets Project Openings 3D graphics for Standard ML
 Summary Activity SCM

# SCM Repository

[sml3d] View of /trunk/sml3d/src/sml3d/base/vec3f.sml
 [sml3d] / trunk / sml3d / src / sml3d / base / vec3f.sml

# View of /trunk/sml3d/src/sml3d/base/vec3f.sml

Tue Jan 17 14:01:50 2012 UTC (7 years, 8 months ago) by jhr
File size: 2856 byte(s)
```  Working on new SML3d core library
```
```(* vec3f.sml
*
* COPYRIGHT (c) 2012 The SML3d Project (http://sml3d.cs.uchicago.edu)
*
* Operations on vectors in R^3 (float version).
*)

structure Vec3f :> VEC3 where type flt = Float.flt =
struct

structure Flt = Float

type flt = Flt.flt

val epsilon = Flt.epsilon
val slerpTolerance = 0.999

type vec3 = flt SML3dTypes.vec3
type vec4 = flt SML3dTypes.vec4

open Vec3

(* lift a 3D vector into homogeneous space *)
fun vector (x, y, z) : vec4 = (x, y, z, 0.0)
fun point (x, y, z) : vec4 = (x, y, z, 1.0)

val zero : vec3 = (0.0, 0.0, 0.0)

val e1 : vec3 = (1.0, 0.0, 0.0)
val e2 : vec3 = (0.0, 1.0, 0.0)
val e3 : vec3 = (0.0, 0.0, 1.0)

fun toString ((x, y, z) : vec3) = concat[
"<", Flt.toString x, ",", Flt.toString y, ",", Flt.toString z, ">"
]

fun neg ((x, y, z) : vec3) = (~x, ~y, ~z)

fun add ((x1, y1, z1) : vec3, (x2, y2, z2)) = (x1+x2, y1+y2, z1+z2)

fun sub ((x1, y1, z1) : vec3, (x2, y2, z2)) = (x1-x2, y1-y2, z1-z2)

fun mul ((x1, y1, z1) : vec3, (x2, y2, z2)) = (x1*x2, y1*y2, z1*z2)

fun scale (s, (x, y, z) : vec3) = (s*x, s*y, s*z)

fun abs (x, y, z) = (Flt.abs x, Flt.abs y, Flt.abs z)
fun min ((x1, y1, z1), (x2, y2, z2)) = (Flt.min(x1, x2), Flt.min(y1, y2), Flt.min(z1, z2))
fun max ((x1, y1, z1), (x2, y2, z2)) = (Flt.max(x1, x2), Flt.max(y1, y2), Flt.max(z1, z2))

fun dot ((x1, y1, z1) : vec3, (x2, y2, z2)) = (x1*x2 + y1*y2 +z1*z2)

fun lerp (v1, t, v2) = adds (scale(1.0-t, v1), t, v2)

(* spherical interpolation between unit vectors *)
fun slerp (v1, t, v2) = let
val cosAngle = dot(v1, v2)
in
if (cosAngle < slerpTolerance)
then let
val angle = Flt.acos cosAngle
val recipSinAngle = 1.0 / Flt.sin angle
val scale1 = recipSinAngle * Flt.sin((1.0 - t) * angle)
val scale2 = recipSinAngle * Flt.sin(t * angle)
in
end
else lerp(v1, t, v2)
end

fun cross ((x1, y1, z1) : vec3, (x2, y2, z2)) = (
y1*z2 - z1*y2,
z1*x2 - x1*z2,
x1*y2 - y1*x2
)

fun lengthSq v = dot(v, v)
fun length v = Flt.sqrt(lengthSq v)

fun distanceSq (u, v) = lengthSq (sub (u, v))
fun distance (u, v) = length (sub (u, v))

fun lengthAndDir v = let
val l = length v
in
if (l < epsilon)
then (0.0, zero)
else (l, scale(1.0 / l, v))
end

fun normalize v = #2(lengthAndDir v)

fun clipLength (v, maxLen) = let
val lenSq = lengthSq v
in
if (lenSq < maxLen*maxLen)
then v
else scale(maxLen / Flt.sqrt lenSq, v)
end

fun parallelComponent {basis, v} = scale(dot(basis, v), basis)

fun perpendicularComponent {basis, v} = sub(v, parallelComponent {basis=basis, v=v})

end
```