stl2gltf/load.go

76 lines
1.5 KiB
Go
Raw Normal View History

2024-06-05 01:43:08 +08:00
package stl2gltf
import (
"encoding/binary"
"log"
"math"
"os"
)
func Load(filePath string) (stl STL) {
file, err := os.OpenFile(filePath, os.O_RDONLY, os.ModePerm)
if err != nil {
log.Panic("open file " + filePath + " error: " + err.Error())
}
2024-06-06 14:55:35 +08:00
// load 80 header
2024-06-05 01:43:08 +08:00
headerBuf := make([]byte, 80)
file.Read(headerBuf)
2024-06-06 14:55:35 +08:00
// int32
2024-06-05 01:43:08 +08:00
triangleNumBuf := make([]byte, 4)
file.Read(triangleNumBuf)
stl.Header = string(headerBuf)
stl.TriangleNum = int(binary.LittleEndian.Uint32(triangleNumBuf))
stl.Triangles = make([]Triangle, 0)
max := []float32{0, 0, 0}
min := []float32{0, 0, 0}
for range stl.TriangleNum {
normalBuf := make([]byte, 4*3)
file.Read(normalBuf)
positionBuf := make([]byte, 4*3*3)
file.Read(positionBuf)
2024-06-06 14:55:35 +08:00
// find max/min xyz
2024-06-05 01:43:08 +08:00
for r := range 3 {
x := math.Float32frombits(binary.LittleEndian.Uint32(positionBuf[:4+(r*4)]))
y := math.Float32frombits(binary.LittleEndian.Uint32(positionBuf[(r * 4) : (r*4)+4]))
z := math.Float32frombits(binary.LittleEndian.Uint32(positionBuf[(r*4)+4 : (r*4)+8]))
if max[0] < x {
max[0] = x
}
if max[1] < y {
max[1] = y
}
if max[2] < z {
max[2] = z
}
if min[0] > x {
min[0] = x
}
if min[1] > y {
min[1] = y
}
if min[2] > z {
min[2] = z
}
}
attributeBuf := make([]byte, 2)
file.Read(attributeBuf)
stl.Triangles = append(stl.Triangles, Triangle{
Normal: normalBuf,
Position: positionBuf,
Attribute: attributeBuf,
})
}
stl.Max = max
stl.Min = min
return stl
}