add binary stl writer
@@ -89,11 +89,43 @@ def write(
assert len(cells.keys()) == 1 and list(cells.keys())[0] == 'triangle', \
'STL can only write triangle cells.'
- pts = points[cells['triangle']]
- # compute normals
+ if write_binary:
+ _write_binary(filename, points, cells)
+ else:
+ _write_ascii(filename, points, cells)
+
+ return
+
+
+def _compute_normals(pts):
normals = numpy.cross(pts[:, 1] - pts[:, 0], pts[:, 2] - pts[:, 0])
nrm = numpy.sqrt(numpy.einsum('ij,ij->i', normals, normals))
normals = (normals.T / nrm).T
+ return normals
+
+
+def _write_binary(filename, points, cells):
+ pts = points[cells['triangle']]
+ normals = _compute_normals(pts)
+
+ with open(filename, 'wb') as fh:
+ # 80 character header data
+ msg = 'This file was generated by meshio.'
+ msg += (80 - len(msg)) * 'X'
+ msg += '\n'
+ fh.write(msg.encode('utf-8'))
+ fh.write(numpy.uint32(len(cells['triangle'])))
+ for pt, normal in zip(pts, normals):
+ fh.write(normal.astype(numpy.float32))
+ fh.write(pt.astype(numpy.float32))
+ fh.write(numpy.uint16(0))
+
+ return
+
+
+def _write_ascii(filename, points, cells):
+ pts = points[cells['triangle']]
+ normals = _compute_normals(pts)
with open(filename, 'wb') as fh:
fh.write('solid\n'.encode('utf-8'))
