chiark / gitweb /
Merge pull request #601 from CapnBry/reloadscene
[cura.git] / Cura / util / meshLoaders / obj.py
1 """
2 OBJ file reader.
3 OBJ are wavefront object files. These are quite common and can be exported from a lot of 3D tools.
4 Only vertex information is read from the OBJ file, information about textures and normals is ignored.
5
6 http://en.wikipedia.org/wiki/Wavefront_.obj_file
7 """
8 __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License"
9
10 import os
11 from Cura.util import printableObject
12
13 def loadScene(filename):
14         obj = printableObject.printableObject(filename)
15         m = obj._addMesh()
16
17         vertexList = []
18         faceList = []
19
20         f = open(filename, "r")
21         for line in f:
22                 parts = line.split()
23                 if len(parts) < 1:
24                         continue
25                 if parts[0] == 'v':
26                         vertexList.append([float(parts[1]), float(parts[2]), float(parts[3])])
27                 if parts[0] == 'f':
28                         parts = map(lambda p: p.split('/')[0], parts)
29                         for idx in xrange(1, len(parts)-2):
30                                 faceList.append([int(parts[1]), int(parts[idx+1]), int(parts[idx+2])])
31         f.close()
32
33         m._prepareFaceCount(len(faceList))
34         for f in faceList:
35                 i = f[0] - 1
36                 j = f[1] - 1
37                 k = f[2] - 1
38                 if i < 0 or i >= len(vertexList):
39                         i = 0
40                 if j < 0 or j >= len(vertexList):
41                         j = 0
42                 if k < 0 or k >= len(vertexList):
43                         k = 0
44                 m._addFace(vertexList[i][0], vertexList[i][1], vertexList[i][2], vertexList[j][0], vertexList[j][1], vertexList[j][2], vertexList[k][0], vertexList[k][1], vertexList[k][2])
45
46         obj._postProcessAfterLoad()
47         return [obj]