forked from fogleman/fauxgl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
114 lines (100 loc) · 1.94 KB
/
util.go
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package fauxgl
import (
"fmt"
"image"
_ "image/jpeg"
"image/png"
"math"
"os"
"path/filepath"
"strconv"
"strings"
)
func Radians(degrees float64) float64 {
return degrees * math.Pi / 180
}
func Degrees(radians float64) float64 {
return radians * 180 / math.Pi
}
func LatLngToXYZ(lat, lng float64) Vector {
lat, lng = Radians(lat), Radians(lng)
x := math.Cos(lat) * math.Cos(lng)
y := math.Cos(lat) * math.Sin(lng)
z := math.Sin(lat)
return Vector{x, y, z}
}
func LoadMesh(path string) (*Mesh, error) {
ext := strings.ToLower(filepath.Ext(path))
switch ext {
case ".stl":
return LoadSTL(path)
case ".obj":
return LoadOBJ(path)
case ".ply":
return LoadPLY(path)
case ".3ds":
return Load3DS(path)
}
return nil, fmt.Errorf("unrecognized mesh extension: %s", ext)
}
func LoadImage(path string) (image.Image, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
im, _, err := image.Decode(file)
return im, err
}
func SavePNG(path string, im image.Image) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
return png.Encode(file, im)
}
func ParseFloats(items []string) []float64 {
result := make([]float64, len(items))
for i, item := range items {
f, _ := strconv.ParseFloat(item, 64)
result[i] = f
}
return result
}
func Clamp(x, lo, hi float64) float64 {
if x < lo {
return lo
}
if x > hi {
return hi
}
return x
}
func ClampInt(x, lo, hi int) int {
if x < lo {
return lo
}
if x > hi {
return hi
}
return x
}
func AbsInt(x int) int {
if x < 0 {
return -x
}
return x
}
func Round(a float64) int {
if a < 0 {
return int(math.Ceil(a - 0.5))
} else {
return int(math.Floor(a + 0.5))
}
}
func RoundPlaces(a float64, places int) float64 {
shift := powersOfTen[places]
return float64(Round(a*shift)) / shift
}
var powersOfTen = []float64{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16}