-
Notifications
You must be signed in to change notification settings - Fork 7
/
JAAseImport.py
354 lines (305 loc) · 15 KB
/
JAAseImport.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
from .mod_reload import reload_modules
reload_modules(locals(), __package__, [], [".casts"]) # nopep8
from .casts import bpy_generic_cast
from typing import List
import bpy
### The new operator ###
class Operator(bpy.types.Operator):
bl_idname = "import_scene.ja_ase"
bl_label = "Import JA ASE (.ase)"
# gets set by the file select window - internal Blender Magic or whatever.
filepath: bpy.props.StringProperty(
name="File Path", description="File path used for importing the ASE file", maxlen=1024, default="") # type: ignore
def execute(self, context): # pyright: ignore [reportIncompatibleMethodOverride]
self.ImportStart()
return {'FINISHED'}
def invoke(self, context, event): # pyright: ignore [reportIncompatibleMethodOverride]
windowMan = context.window_manager
# sets self.properties.filename and runs self.execute()
windowMan.fileselect_add(self)
return {'RUNNING_MODAL'}
def ImportStart(self):
whitespace = set(" \t\n")
def error(msg):
self.report({'ERROR'}, msg)
def skipWhitespace(file):
prevPos = file.tell()
c = file.read(1)
while c in whitespace:
prevPos = file.tell()
c = file.read(1)
if c != "":
file.seek(prevPos)
# reads everything up to (and excluding) the next whitespace or {, } or *, returns that, cursor is before the whitespace
# or, if the next token starts with {, } or * returns just that
def readToken(file):
skipWhitespace(file)
token = ""
isString = False
while True:
prevPos = file.tell()
c = file.read(1)
if c == "\"":
if isString:
return token
else:
if token == "":
isString = True
continue
else: # treat " in mid-token as token's end
file.seek(prevPos)
return token
if c in whitespace and not isString:
file.seek(prevPos)
return token
if c in ["{", "}", "*"] and not isString:
if token == "":
return c
else:
file.seek(prevPos)
return token
elif c == "":
if isString:
print("Warning: Unterminated String!")
return token
else:
token = token + c
class Block:
def __init__(self):
self.name = ""
self.parameters = []
self.children = []
class ASESyntaxError(RuntimeError):
def __init__(self, msg):
self.message = msg
def __str__(self):
return repr(self.message)
# Gets blocks - or should the be called Nodes? Basically stuff like this:
# *MATERIAL_REF 0
# and this:
# *GEOMOBJECT { ... }
# returns all of them on the same level, and recursively fills the "children" part of those
def getBlocks(file):
blocks = []
while True:
prevPos = file.tell()
token = readToken(file)
if token == "":
return blocks
elif token == "}":
file.seek(prevPos)
return blocks
elif token != "*":
raise ASESyntaxError(
"Invalid File: * expected, got {}".format(token))
# else: Token == *
# read block name
block = Block()
blocks.append(block)
block.name = readToken(file)
if block.name == "":
raise ASESyntaxError(
"Invalid File: Unexpected end of file!")
elif block.name in ["{", "}", "*"]:
raise ASESyntaxError(
"Invalid File: Unexpected {}!".format(block.name))
# read block parameters, i.e. stuff that follows, and children, if any
parametersOver = False
while not parametersOver:
prevPos = file.tell()
nextToken = readToken(file)
if nextToken == "": # EOF
return blocks
elif nextToken in ["}", "*"]: # end of block
file.seek(prevPos)
parametersOver = True
elif nextToken == "{": # children follow
block.children = getBlocks(file)
nextToken = readToken(file)
if nextToken != "}":
raise ASESyntaxError(
"Invalid File: Block not properly closed!")
else:
block.parameters.append(nextToken)
# open file
filename = self.properties.filepath
file = open(filename)
# read file
try:
blocks = getBlocks(file)
except ASESyntaxError as err:
error(err.message)
return
# interpret read blocks:
# check filetype/version:
if len(blocks) == 0:
error("No valid ASE file, should start with *3DSMAX_ASCIIEXPORT!")
return
if blocks[0].name.lower() != "3dsmax_asciiexport":
error(
"No valid ASE file, should start with *3DSMAX_ASCIIEXPORT, starts with {}!".format(blocks[0].name))
return
if len(blocks[0].parameters) == 0 or blocks[0].parameters[0] != "200":
error("Invalid ASE file, wrong version number, must be 200!")
return
# remove filetype block
blocks = blocks[1:]
# find material list
material_lists = [
block for block in blocks if block.name.lower() == "material_list"]
if len(material_lists) == 0:
error("No *MATERIAL_LIST!")
return
elif len(material_lists) > 1:
error("More than one *MATERIAL_LIST!")
return
# else len == 1
material_list = material_lists[0]
material_blocks = [
block for block in material_list.children if block.name.lower() == "material"]
try:
if not all([(len(block.parameters) > 0 and block.parameters[0] == str(index)) for index, block in enumerate(material_blocks)]):
error("Materials out of order")
return
except IndexError:
error("Invalid file: *MATERIAL with too few arguments!")
# create materials based on material list
material_names = []
try:
for material_block in material_blocks:
names = [child.parameters[0]
for child in material_block.children if child.name.lower() == "material_name"]
if len(names) == 0:
error("*MATERIAL without *MATERIAL_NAME!")
return
elif len(names) > 1:
print("Warning: *MATERIAL with multiple *MATERIAL_NAMEs!")
material_names.append(names[0])
except IndexError:
error("Invalid file: *MATERIAL_NAME with too few arguments!")
# find objects with meshes
class Object:
def __init__(self, index):
self.mat_ref = -1
self.vertices = [] # flat list of coordinates
self.faces = [] # flat list of indices
self.tvertices = [] # list of uv pairs
self.tfaces = [] # list of tvertex index triples
self.index = index # index of this object's GEOMOBJECT entry
def toBlender(self, materials: List[bpy.types.Material]):
# create mesh
mesh = bpy.data.meshes.new("ASEMesh")
# add material
mat = materials[self.mat_ref]
mesh.materials.append(mat)
# add vertices
numVerts = len(self.vertices) // 3
mesh.vertices.add(numVerts)
mesh.vertices.foreach_set("co", self.vertices)
# add faces
numTris = len(self.faces) // 3
mesh.polygons.add(numTris)
# loops are the per-face-vertex-settings in one long flat list
mesh.loops.add(numTris * 3)
# so we need to set where in that list a face's settings start...
mesh.polygons.foreach_set(
"loop_start", range(0, numTris * 3, 3))
# ... and how many there are.
mesh.polygons.foreach_set("loop_total", (3,) * numTris)
mesh.loops.foreach_set("vertex_index", self.faces)
mesh.uv_layers.new() # creates a new uv_layer
# FIXME "Argument of type "slice" cannot be assigned to parameter "key" of type" -> I should probably drop the [:]?
uv_loops = mesh.uv_layers.active.data[:]
for poly, tface in zip(mesh.polygons, self.tfaces):
poly = bpy_generic_cast(bpy.types.MeshPolygon, poly)
for ofs, tvertIndex in enumerate(tface):
tvert = None
try:
tvert = self.tvertices[tvertIndex]
except IndexError:
error(
"Invalid file: TFACELIST references non-existing TVERT {} in GEOMOBJECT {}".format(tvertIndex, self.index))
return
try:
uv_loops[poly.loop_start + ofs].uv = tvert
except IndexError:
error(
"Invalid file: TFACELIST of GEOMOBJECT {} too long.".format(self.index))
return
mesh.update()
mesh.validate()
# add object
obj = bpy.data.objects.new("ASEObject", mesh)
bpy.context.scene.collection.objects.link(
obj) # remember scene.update() later!
objects: List[Object] = []
# if the last index is 0, blender assumes that to be the end...
# or does it? Maybe it does, but changing the order screws UV up and that
def fixOrder(face):
if face[-1] == 0:
print(
"There might be a missing face on this model. If that's the case, tell me to fix the importer, it's my fault.")
return face # do nothing for now...
face.insert(0, face[-1])
del face[-1]
return face
objIndex = -1
for block in blocks:
if block.name.lower() == "geomobject":
objIndex = objIndex + 1
try:
meshes = [
child for child in block.children if child.name.lower() == "mesh"]
mat_refs = [
child for child in block.children if child.name.lower() == "material_ref"]
if len(meshes) != 1 or len(mat_refs) != 1:
error("*GEOMOBJECT with no/multiple *MESH and/or *MAT_REF")
return
mesh = meshes[0]
vertex_lists = [
child for child in mesh.children if child.name.lower() == "mesh_vertex_list"]
face_lists = [
child for child in mesh.children if child.name.lower() == "mesh_face_list"]
tvert_lists = [
child for child in mesh.children if child.name.lower() == "mesh_tvertlist"]
tface_lists = [
child for child in mesh.children if child.name.lower() == "mesh_tfacelist"]
if len(vertex_lists) != 1 or len(face_lists) != 1 or len(tvert_lists) != 1 or len(tface_lists) != 1:
error(
"Invalid *MESH with no/multiple *MESH_VERTEX_LIST/*MESH_FACE_LIST/*MESH_TVERTLIST/*MESH_TFACELIST")
return
print("TVerts:", len(tvert_lists[0].children))
object = Object(objIndex)
object.mat_ref = int(mat_refs[0].parameters[0])
# list comprehension yay!
# get vertices
# basically: [ float(vertex_lists[0].children[n].parameters[1]), float(vertex_lists[0].children[n].parameters[2]), float(vertex_lists[0].children[n].parameters[3]), float(vertex_lists[0].children[n+1].parameters[1]), ... ] for those n... where children[n].name == "MESH_VERTEX"
object.vertices = [float(vert.parameters[i]) for vert in vertex_lists[0].children if vert.name.lower(
) == "mesh_vertex" for i in [1, 2, 3]]
# get faces (one flat list of indices)
faces = [fixOrder([int(face.parameters[2]), int(face.parameters[4]), int(
face.parameters[6])]) for face in face_lists[0].children if face.name.lower() == "mesh_face"]
# flatten
object.faces = [face[i]
for face in faces for i in range(3)]
# get tvertices (list of uv-pairs)
# object.tvertices = [ float( vert.parameters[ i ] ) for vert in tvert_lists[0].children if vert.name.lower() == "mesh_tvert" for i in [ 1, 2 ] ]
object.tvertices = [[float(vert.parameters[i]) for i in [
1, 2]] for vert in tvert_lists[0].children if vert.name.lower() == "mesh_tvert"]
# get tfaces (list of index-triples)
# object.tfaces = [ fixOrder( [ int( face.parameters[ 1 ] ), int( face.parameters[ 2 ] ), int( face.parameters[ 3 ] ) ] ) for face in tface_lists[0].children if face.name.lower() == "mesh_tface" ]
object.tfaces = [[int(face.parameters[1]), int(face.parameters[2]), int(
face.parameters[3])] for face in tface_lists[0].children if face.name.lower() == "mesh_tface"]
objects.append(object)
except IndexError as err:
print(err)
error("Invalid file: Node with too few arguments!")
materials = [bpy.data.materials.new(
material_name) for material_name in material_names]
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode='OBJECT')
for object in objects:
object.toBlender(materials)
bpy.context.scene.update() # since new objects have been linked
def menu_func(self, context):
self.layout.operator(Operator.bl_idname, text="JA ASE (.ase)")