-
Notifications
You must be signed in to change notification settings - Fork 29
/
import_off.py
324 lines (284 loc) · 9.32 KB
/
import_off.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#####
#
# Copyright 2014 Alex Tsui
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#####
#
# http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Guidelines/Addons
#
import os
import bpy
import mathutils
from bpy.props import (BoolProperty,
FloatProperty,
StringProperty,
EnumProperty,
)
from bpy_extras.io_utils import (ImportHelper,
ExportHelper,
unpack_list,
unpack_face_list,
axis_conversion,
)
#if "bpy" in locals():
# import imp
# if "import_off" in
bl_info = {
"name": "OFF format",
"description": "Import-Export OFF, Import/export simple OFF mesh.",
"author": "Alex Tsui, Mateusz Kłoczko",
"version": (0, 4, 0),
"blender": (2, 82, 7),
"location": "File > Import-Export",
"warning": "", # used for warning icon and text in addons panel
"wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/"
"Scripts/My_Script",
"category": "Import-Export"}
class ImportOFF(bpy.types.Operator, ImportHelper):
"""Load an OFF Mesh file"""
bl_idname = "import_mesh.off"
bl_label = "Import OFF Mesh"
filename_ext = ".off"
filter_glob = StringProperty(
default="*.off",
options={'HIDDEN'},
)
axis_forward = EnumProperty(
name="Forward",
items=(('X', "X Forward", ""),
('Y', "Y Forward", ""),
('Z', "Z Forward", ""),
('-X', "-X Forward", ""),
('-Y', "-Y Forward", ""),
('-Z', "-Z Forward", ""),
),
default='Y',
)
axis_up = EnumProperty(
name="Up",
items=(('X', "X Up", ""),
('Y', "Y Up", ""),
('Z', "Z Up", ""),
('-X', "-X Up", ""),
('-Y', "-Y Up", ""),
('-Z', "-Z Up", ""),
),
default='Z',
)
def execute(self, context):
#from . import import_off
keywords = self.as_keywords(ignore=('axis_forward',
'axis_up',
'filter_glob',
))
global_matrix = axis_conversion(from_forward=self.axis_forward,
from_up=self.axis_up,
).to_4x4()
mesh = load(self, context, **keywords)
if not mesh:
return {'CANCELLED'}
scene = bpy.context.scene
obj = bpy.data.objects.new(mesh.name, mesh)
scene.collection.objects.link(obj)
obj.matrix_world = global_matrix
layer = bpy.context.view_layer
layer.update()
return {'FINISHED'}
class ExportOFF(bpy.types.Operator, ExportHelper):
"""Save an OFF Mesh file"""
bl_idname = "export_mesh.off"
bl_label = "Export OFF Mesh"
filter_glob = StringProperty(
default="*.off",
options={'HIDDEN'},
)
check_extension = True
filename_ext = ".off"
axis_forward = EnumProperty(
name="Forward",
items=(('X', "X Forward", ""),
('Y', "Y Forward", ""),
('Z', "Z Forward", ""),
('-X', "-X Forward", ""),
('-Y', "-Y Forward", ""),
('-Z', "-Z Forward", ""),
),
default='Y',
)
axis_up = EnumProperty(
name="Up",
items=(('X', "X Up", ""),
('Y', "Y Up", ""),
('Z', "Z Up", ""),
('-X', "-X Up", ""),
('-Y', "-Y Up", ""),
('-Z', "-Z Up", ""),
),
default='Z',
)
use_colors = BoolProperty(
name="Vertex Colors",
description="Export the active vertex color layer",
default=False,
)
def execute(self, context):
keywords = self.as_keywords(ignore=('axis_forward',
'axis_up',
'filter_glob',
'check_existing',
))
global_matrix = axis_conversion(to_forward=self.axis_forward,
to_up=self.axis_up,
).to_4x4()
keywords['global_matrix'] = global_matrix
return save(self, context, **keywords)
def menu_func_import(self, context):
self.layout.operator(ImportOFF.bl_idname, text="OFF Mesh (.off)")
def menu_func_export(self, context):
self.layout.operator(ExportOFF.bl_idname, text="OFF Mesh (.off)")
classes = (
ImportOFF,
ExportOFF,
)
def register():
for c in classes:
bpy.utils.register_class(c)
bpy.types.TOPBAR_MT_file_export.append(menu_func_export)
bpy.types.TOPBAR_MT_file_import.append(menu_func_import)
def unregister():
for c in reversed(classes):
bpy.utils.unregister_class(c)
bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)
bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)
def load(operator, context, filepath):
# Parse mesh from OFF file
# TODO: Add support for NOFF and COFF
filepath = os.fsencode(filepath)
file = open(filepath, 'r')
first_line = file.readline().rstrip()
use_colors = (first_line == 'COFF')
colors = []
# handle blank and comment lines after the first line
line = file.readline()
while line.isspace() or line[0]=='#':
line = file.readline()
vcount, fcount, ecount = [int(x) for x in line.split()]
verts = []
facets = []
edges = []
i=0;
while i<vcount:
line = file.readline()
if line.isspace():
continue # skip empty lines
try:
bits = [float(x) for x in line.split()]
px = bits[0]
py = bits[1]
pz = bits[2]
if use_colors:
colors.append([float(bits[3]) / 255, float(bits[4]) / 255, float(bits[5]) / 255])
except ValueError:
i=i+1
continue
verts.append((px, py, pz))
i=i+1
i=0;
while i<fcount:
line = file.readline()
if line.isspace():
continue # skip empty lines
try:
splitted = line.split()
ids = list(map(int, splitted))
if len(ids) > 3:
facets.append(tuple(ids[1:]))
elif len(ids) == 3:
edges.append(tuple(ids[1:]))
except ValueError:
i=i+1
continue
i=i+1
# Assemble mesh
off_name = bpy.path.display_name_from_filepath(filepath)
mesh = bpy.data.meshes.new(name=off_name)
mesh.from_pydata(verts,edges,facets)
# mesh.vertices.add(len(verts))
# mesh.vertices.foreach_set("co", unpack_list(verts))
# mesh.faces.add(len(facets))
# mesh.faces.foreach_set("vertices", unpack_face_list(facets))
mesh.validate()
mesh.update()
if use_colors:
color_data = mesh.vertex_colors.new()
for i, facet in enumerate(mesh.polygons):
for j, vidx in enumerate(facet.vertices):
color_data.data[3*i + j].color = colors[vidx]
return mesh
def save(operator, context, filepath,
global_matrix = None,
use_colors = False):
# Export the selected mesh
if global_matrix is None:
global_matrix = mathutils.Matrix()
scene = context.scene
obj = bpy.context.view_layer.objects.active
mesh = obj.to_mesh()
# Apply the inverse transformation
obj_mat = obj.matrix_world
mesh.transform(global_matrix @ obj_mat)
verts = mesh.vertices[:]
facets = [ f for f in mesh.polygons ]
# Collect colors by vertex id
colors = False
vertex_colors = None
if use_colors:
colors = mesh.tessface_vertex_colors.active
if colors:
colors = colors.data
vertex_colors = {}
for i, facet in enumerate(mesh.polygons):
color = colors[i]
color = color.color1[:], color.color2[:], color.color3[:], color.color4[:]
for j, vidx in enumerate(facet.vertices):
if vidx not in vertex_colors:
vertex_colors[vidx] = (int(color[j][0] * 255.0),
int(color[j][1] * 255.0),
int(color[j][2] * 255.0))
else:
use_colors = False
# Write geometry to file
filepath = os.fsencode(filepath)
fp = open(filepath, 'w')
if use_colors:
fp.write('COFF\n')
else:
fp.write('OFF\n')
fp.write('%d %d 0\n' % (len(verts), len(facets)))
for i, vert in enumerate(mesh.vertices):
fp.write('%.16f %.16f %.16f' % vert.co[:])
if use_colors:
fp.write(' %d %d %d 255' % vertex_colors[i])
fp.write('\n')
#for facet in facets:
for i, facet in enumerate(mesh.polygons):
fp.write('%d' % len(facet.vertices))
for vid in facet.vertices:
fp.write(' %d' % vid)
fp.write('\n')
fp.close()
return {'FINISHED'}
if __name__ == "__main__":
register()