summaryrefslogtreecommitdiff
path: root/stl.go
diff options
context:
space:
mode:
Diffstat (limited to 'stl.go')
-rw-r--r--stl.go53
1 files changed, 49 insertions, 4 deletions
diff --git a/stl.go b/stl.go
index 35e69eb..60ada3e 100644
--- a/stl.go
+++ b/stl.go
@@ -20,6 +20,8 @@ type StlModel struct {
surface Surface
}
+type Vector3 [3]float32
+
// read and parse a given binary STL file
func ReadBinaryStlFile(filePath string) (StlModel, error) {
@@ -75,9 +77,12 @@ func ParseBinaryStlTriangle(data []byte) *Triangle { // FIXME: This function sh
return triangle
}
-func (stl StlModel) toVertices() []float32 {
+func (stl StlModel) toVertices() (vertex_position []float32, vertex_normal []float32) {
+
+ vertex_position = make([]float32, stl.numberOfTriangles * 9)
+ vertex_normal = make([]float32, stl.numberOfTriangles * 9)
- retval := make([]float32, stl.numberOfTriangles * 9)
+ var point0,point1,point2,edge0,edge1,normal Vector3;
for triangleIndex,triangle := range(stl.surface.triangles) {
@@ -85,13 +90,53 @@ func (stl StlModel) toVertices() []float32 {
for scalarIndex,scalar := range(point.scalars) {
- retval[triangleIndex*9+pointIndex*3+scalarIndex] = scalar
+ vertex_position[triangleIndex*9+pointIndex*3+scalarIndex] = scalar
}
}
+ // calculate normal
+ point0 = Vector3{triangle.points[0].scalars[0], triangle.points[0].scalars[1], triangle.points[0].scalars[2]}
+ point1 = Vector3{triangle.points[1].scalars[0], triangle.points[1].scalars[1], triangle.points[1].scalars[2]}
+ point2 = Vector3{triangle.points[2].scalars[0], triangle.points[2].scalars[1], triangle.points[2].scalars[2]}
+ edge0 = point1.subtract(point0)
+ edge1 = point2.subtract(point1)
+ normal = edge0.crossProduct(edge1)
+ normal.divideScalar(2.0) // length of normal vector corresponds to triangle area
+
+ // save normal to each vertex of the triangle
+ for i := 0; i<3; i++ {
+ vertex_normal[triangleIndex*9+i*3+0] = normal[0]
+ vertex_normal[triangleIndex*9+i*3+1] = normal[1]
+ vertex_normal[triangleIndex*9+i*3+2] = normal[2]
+ }
+
}
- return retval
+ return vertex_position, vertex_normal
+}
+
+func (vector *Vector3) divideScalar(scalar float32) {
+ vector[0] = vector[0] / scalar
+ vector[1] = vector[1] / scalar
+ vector[2] = vector[2] / scalar
+}
+
+func (vectorA Vector3) subtract(vectorB Vector3) (vectorC Vector3) {
+
+ vectorC[0] = vectorA[0] - vectorB[0]
+ vectorC[1] = vectorA[1] - vectorB[1]
+ vectorC[2] = vectorA[2] - vectorB[2]
+
+ return vectorC
+}
+
+func (vectorA Vector3) crossProduct(vectorB Vector3) (vectorC Vector3) {
+
+ vectorC[0] = vectorA[1] * vectorB[2] - vectorA[2] * vectorB[1]
+ vectorC[1] = vectorA[2] * vectorB[0] - vectorA[0] * vectorB[2]
+ vectorC[2] = vectorA[0] * vectorB[1] - vectorA[1] * vectorB[0]
+
+ return vectorC
}