-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport_foam.py
More file actions
204 lines (161 loc) · 6.71 KB
/
import_foam.py
File metadata and controls
204 lines (161 loc) · 6.71 KB
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
import math
import os
import struct
import time
import bmesh
import bpy
import mathutils
from bpy.props import BoolProperty, EnumProperty, StringProperty
from bpy.types import Operator
from bpy_extras.io_utils import ImportHelper, axis_conversion
bl_info = {
"name": "SeaDogs island foam import",
"description": "Import Foam files",
"author": "Wazar",
"version": (2, 2, 0),
"blender": (3, 6, 0),
"location": "File > Import",
"warning": "",
"support": "COMMUNITY",
"category": "Import",
}
correction_matrix = axis_conversion(
from_forward='X', from_up='Y', to_forward='Y', to_up='Z')
class Point:
def __init__(self, idx, matrix, links):
self.matrix = matrix
self.idx = idx
self.links = links
class Foam:
def __init__(self):
self.points = {}
self.links = []
pass
def parse(self, file_path='', report_func=None):
state = 'init'
self.depth_file = None
self.v_box_center = None
self.v_box_size = None
with open(file_path, mode='r') as file:
for line in file:
line = line.strip()
if state == 'init':
if line.startswith('[Main]'):
state = 'main'
elif state == 'main':
if line.startswith('DepthFile'):
parts = line.split(sep=';')[0].split(sep='=')
parts[1] = parts[1].strip()
self.depth_file = parts[1]
elif line.startswith('vBoxCenter'):
parts = line.split(sep=';')[0].split(sep='=')
parts[1] = parts[1].strip()
self.v_box_center = parts[1]
elif line.startswith('vBoxSize'):
parts = line.split(sep=';')[0].split(sep='=')
parts[1] = parts[1].strip()
self.v_box_size = parts[1]
elif line.startswith('[GraphPoints]'):
state = 'points'
elif state == 'points':
if line.startswith('pnt'):
line = line.split(sep=';')[0]
parts = line.split(sep='=')
num = parts[0].strip()[3:]
num = int(num)
data = parts[1].split(sep=',')
coords = [float(v.strip()) for v in data[:2]]
matrix = mathutils.Matrix.Translation((coords[0], 0, coords[1]))
matrix.translation *= mathutils.Vector([-1, 1, 1])
matrix = correction_matrix.to_4x4() @ matrix
if data[-1] == '':
data.pop()
count = int(data[2])
links = [int(v.strip()) for v in data[3:]]
if len(links) % 2 == 1:
report_func({'ERROR'}, 'point links should be even for pnt{}'.format(num))
return {'CANCELLED'}
if len(links) // 2 != count:
report_func({'ERROR'}, 'point links count should be {}, not {} for pnt{}'.format(count, len(links) // 2))
return {'CANCELLED'}
links_paired = []
for i in range(len(links) // 2):
links_paired.append((links[2*i], links[2*i + 1]))
self.points[num] = Point(num, matrix, links_paired)
else:
report_func({'ERROR'}, 'Unknown state')
return None
def parse_sp(file_path="", report_func=None):
sp = Foam()
ret = sp.parse(file_path, report_func)
if ret is not None:
return {'CANCELLED'}
return sp
def import_foam(
context,
file_path="",
report_func=None
):
file_name = os.path.basename(file_path)[:-4]
data = parse_sp(file_path, report_func)
if data == {'CANCELLED'}:
return {'CANCELLED'}
collection = bpy.data.collections.new(file_name)
bpy.context.scene.collection.children.link(collection)
root = bpy.data.objects.new("root", None)
root['ExportType'] = 'FoamIsland'
collection.objects.link(root)
blender_objects = []
points_locator_name = 'points'
points_locator = bpy.data.objects.new(points_locator_name, None)
collection.objects.link(points_locator)
points_locator.parent = root
points_locator['DepthFile'] = data.depth_file
points_locator['vBoxCenter'] = data.v_box_center
points_locator['vBoxSize'] = data.v_box_size
for idx in data.points:
locator_name = 'pnt{:04d}'.format(data.points[idx].idx)
locator = bpy.data.objects.new(locator_name, None)
collection.objects.link(locator)
locator.parent = points_locator
locator.empty_display_type = 'ARROWS'
locator.empty_display_size = 0.5
locator.matrix_basis = data.points[idx].matrix
data.points[idx].locator = locator
for idx in data.points:
i = 0
for p1, p2 in data.points[idx].links:
first_point = data.points[p1]
second_point = data.points[p2]
if first_point.idx == second_point.idx:
continue
constraint = first_point.locator.constraints.new(type='TRACK_TO')
constraint.target = second_point.locator
constraint.name = 'pnt{:04d}_{:04d}'.format(idx, i)
i += 1
#print('pnt{}_{}| first_point: "{}" second_point: "{}"'.format(idx, i, first_point.locator.name, second_point.locator.name))
return {'FINISHED'}
class ImportFoam(Operator, ImportHelper):
"""This appears in the tooltip of the operator and in the generated docs"""
bl_idname = "import.foam"
bl_label = "Island foam import"
# ImportHelper mixin class uses this
filename_ext = ".ini"
filter_glob: StringProperty(
default="*.ini",
options={'HIDDEN'},
maxlen=255, # Max internal buffer length, longer would be clamped.
)
def execute(self, context):
return import_foam(context, self.filepath, report_func=self.report)
def menu_func_import_foam(self, context):
self.layout.operator(ImportFoam.bl_idname,
text="Island foam import (.ini)")
def register():
bpy.utils.register_class(ImportFoam)
bpy.types.TOPBAR_MT_file_import.append(menu_func_import_foam)
def unregister():
bpy.utils.unregister_class(ImportFoam)
bpy.types.TOPBAR_MT_file_import.remove(menu_func_import_foam)
if __name__ == "__main__":
register()