1 import sys, math, re, os, struct, time
6 class stlModel(mesh.mesh):
8 super(stlModel, self).__init__()
10 def load(self, filename):
11 f = open(filename, "rb")
12 if f.read(5).lower() == "solid":
14 if len(self.faces) < 1:
15 f.seek(6, os.SEEK_SET)
21 self._postProcessAfterLoad()
24 def _loadAscii(self, f):
30 v0 = util3d.Vector3(float(data[1]), float(data[2]), float(data[3]))
33 v1 = util3d.Vector3(float(data[1]), float(data[2]), float(data[3]))
36 v2 = util3d.Vector3(float(data[1]), float(data[2]), float(data[3]))
37 self.addFace(v0, v1, v2)
40 def _loadBinary(self, f):
43 faceCount = struct.unpack('<I', f.read(4))[0]
44 for idx in xrange(0, faceCount):
45 data = struct.unpack("<ffffffffffffH", f.read(50))
46 v0 = util3d.Vector3(data[3], data[4], data[5])
47 v1 = util3d.Vector3(data[6], data[7], data[8])
48 v2 = util3d.Vector3(data[9], data[10], data[11])
49 self.addFace(v0, v1, v2)
51 def saveAsSTL(mesh, filename):
52 f = open(filename, 'wb')
53 #Write the STL binary header. This can contain any info, except for "SOLID" at the start.
54 f.write(("CURA BINARY STL EXPORT. " + time.strftime('%a %d %b %Y %H:%M:%S')).ljust(80, '\000'))
55 #Next follow 4 binary bytes containing the amount of faces, and then the face information.
56 f.write(struct.pack("<I", len(mesh.faces)))
57 for face in mesh.faces:
61 normal = (v2 - v1).cross(v3 - v1)
63 f.write(struct.pack("<fff", normal.x, normal.y, normal.z))
64 f.write(struct.pack("<fff", v1.x, v1.y, v1.z))
65 f.write(struct.pack("<fff", v2.x, v2.y, v2.z))
66 f.write(struct.pack("<fff", v3.x, v3.y, v3.z))
67 f.write(struct.pack("<H", 0))
70 if __name__ == '__main__':
71 for filename in sys.argv[1:]:
72 m = stlModel().load(filename)
73 print("Loaded %d faces" % (len(m.faces)))
74 parts = m.splitToParts()
76 saveAsSTL(p, "export_%i.stl" % parts.index(p))