aboutsummaryrefslogtreecommitdiff
path: root/vec3d.go
blob: 9e4ced0d221c55e3c3e82640add1c7f72fa92001 (plain) (blame)
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

package main

import (
	"math"
	"math/rand"
)

type Vec3D struct {
	x, y, z float64
}

func (vec Vec3D) Invert() Vec3D {
	return Vec3D{-vec.x, -vec.y, -vec.z}
}

func (vec Vec3D) Length() float64 {
	return math.Sqrt(DotProduct(vec, vec))
}

func (vec Vec3D) Unit() Vec3D {
	length := vec.Length()
	if length == 0 {
		return vec
	}
	return ScalarProduct(1.0/length, vec)
}

func (vec Vec3D) Reflect(normal Vec3D) Vec3D {
	return SubVec3D(vec, ScalarProduct(2*DotProduct(vec, normal), normal))
}

func AddVec3D(vec1 Vec3D, vec2 Vec3D) Vec3D {
	return Vec3D{vec1.x + vec2.x, vec1.y + vec2.y, vec1.z + vec2.z}
}

func SubVec3D(vec1 Vec3D, vec2 Vec3D) Vec3D {
	return AddVec3D(vec1, vec2.Invert())
}

func ScalarProduct(scalar float64, vec Vec3D) Vec3D {
	return Vec3D{scalar * vec.x, scalar * vec.y, scalar * vec.z}
}

func DotProduct(vec1 Vec3D, vec2 Vec3D) float64 {
	return vec1.x*vec2.x + vec1.y*vec2.y + vec1.z*vec2.z
}

func CrossProduct(vec1 Vec3D, vec2 Vec3D) Vec3D {
	return Vec3D{
		vec1.y*vec2.z - vec1.z*vec2.y,
		vec1.z*vec2.x - vec1.x*vec2.z,
		vec1.x*vec2.y - vec1.y*vec2.x,
	}
}

func RandomInUnitSphere() Vec3D {
	for {
		point := Vec3D{2*rand.Float64() - 1, 2*rand.Float64() - 1, 2*rand.Float64() - 1}
		if point.Length() < 1.0 {
			return point
		}
	}
}