-
Notifications
You must be signed in to change notification settings - Fork 1
/
write_ascii.go
69 lines (59 loc) · 1.83 KB
/
write_ascii.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
package stl
import (
"bufio"
"fmt"
"io"
"math"
"os"
"strings"
)
// ToASCII writes the Solid out in ASCII form
func (s *Solid) ToASCII(w io.Writer) error {
bw := bufio.NewWriter(w)
defer bw.Flush()
_, err := bw.WriteString("solid " + s.Header + "\n")
if err != nil {
return fmt.Errorf("did not write header: %v", err)
}
for _, t := range s.Triangles {
if _, err := bw.WriteString(triangleASCII(t)); err != nil {
return fmt.Errorf("did not write triangle: %v", err)
}
}
_, err = bw.WriteString("endsolid " + s.Header + "\n")
if err != nil {
return fmt.Errorf("did not write footer: %v", err)
}
return nil
}
// ToASCIIFile writes the Solid to a file in ASCII format
// See stl.ToASCII for more info
func (s *Solid) ToASCIIFile(filename string) error {
file, err := os.OpenFile(strings.TrimSpace(filename), os.O_WRONLY|os.O_CREATE, 0700)
if err != nil {
return err
}
defer file.Close()
return s.ToASCII(file)
}
func triangleASCII(t Triangle) string {
return fmt.Sprintf(" facet normal %s %s %s\n", shortFloat(t.Normal.Ni), shortFloat(t.Normal.Nj), shortFloat(t.Normal.Nk)) +
" outer loop\n" +
fmt.Sprintf(" vertex %s %s %s\n", shortFloat(t.Vertices[0].X), shortFloat(t.Vertices[0].Y), shortFloat(t.Vertices[0].Z)) +
fmt.Sprintf(" vertex %s %s %s\n", shortFloat(t.Vertices[1].X), shortFloat(t.Vertices[1].Y), shortFloat(t.Vertices[1].Z)) +
fmt.Sprintf(" vertex %s %s %s\n", shortFloat(t.Vertices[2].X), shortFloat(t.Vertices[2].Y), shortFloat(t.Vertices[2].Z)) +
" endloop\n" +
" endfacet\n"
}
func shortFloat(f float32) string {
// Scientific notation
sn := fmt.Sprintf("%g", f)
// If f is an integer, and its shorter than scientific notation form, return an integer
if float64(f) == math.Floor(float64(f)) {
in := fmt.Sprintf("%d", int64(f))
if len(sn) > len(in) {
return in
}
}
return sn
}