summaryrefslogtreecommitdiff
path: root/stl.py
blob: 7989d433c937b324350e72dbff1698be5de64aba (plain)
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
import numpy as np
import string
import struct

def read_stl(filename):
    f = open(filename)
    buf = f.read(200)
    f.close()

    for char in buf:
        if char not in string.printable:
            return read_binary_stl(filename)

    return read_ascii_stl(filename)

def read_ascii_stl(filename):
    f = open(filename)

    vertex = []
    for line in f:
        if not line.strip().startswith('vertex'):
            continue
        vertex.append([float(s) for s in line.strip().split()[1:]])

    f.close()
    return np.array(vertex)

def read_binary_stl(filename):
    f = open(filename)

    f.read(80)
    triangles = struct.unpack('<I', f.read(4))[0]

    vertex = []
    for i in range(triangles):
        f.read(12)
        for j in range(3):
            vertex.append(struct.unpack('<fff', f.read(12)))
        f.read(2)

    f.close()
    return np.array(vertex)