-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.py
370 lines (296 loc) · 9.11 KB
/
parse.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import yaml
from PIL import Image, ImageOps
import os
from shapely.geometry import Polygon, mapping
from shapely.geometry import MultiPoint
from shapely.ops import triangulate
# CHANGE THIS WITH YOUR FILE
# Image name (auto-prefixed with image_)
anima2d_name = "hasumiFront"
# Save extracted sprites to "unpack" folder
save_img = False
# USAGE: RUN then copy generated JSON to Stage2 "SceneParser"
if not os.path.isdir("unpack"):
os.mkdir("unpack")
def generate_edges(vertices: list) -> list:
points = [(x, y) for x, y in zip(vertices[::2], vertices[1::2])]
poly = Polygon(points)
coords = poly.exterior.coords[:]
out = sum(
[
[
points.index(coords[i]),
points.index(coords[i+1]),
]
for i in range(len(coords)-1)],
[])
return out
def generate_triangles(vertices: list) -> list:
points = [(x, y) for x, y in zip(vertices[::2], vertices[1::2])]
poly = Polygon(points)
triangles = triangulate(poly)
triangles_list = []
for triangle in triangles:
coords = triangle.exterior.coords[:]
coords_out = []
for coord in coords:
if coord in points:
i = points.index(coord)
if i not in coords_out:
coords_out.append(i)
if len(coords_out) == 3:
triangles_list.append(coords_out)
return triangles_list
def generate_uvs(outline: list, width: int, height: int) -> list:
"""
Generate UVS from outline
:param height: Base height
:param width: Base width
:param outline: list of x,y for each node
:return: list of uv
"""
"""
Translate
Base : To:
y
+ +--^--+ +-----> x +
| | | | | | |
height | <--+--> x | | | 1
| | | | | | |
+ +--v--+ v-----+ +
y
+-----+ +-----+
width 1
Translate a point :
x= x+w/2
y= y-h/2
Revert y axis:
y= -1*y
Scale from (h,w) to (1,1)
x= x/w
y= y/h
"""
points = []
# FIXME: bug, textures are flipped upside down !
for coords in outline:
c_x = coords['x']
c_y = coords['y']
x = c_x + width/2
y = c_y + height/2
# y = -1*(c_y - height / 2)
o_x = round(x / width, 5)
o_y = round(1-(y / height), 5)
points.append(o_x)
points.append(o_y)
# return sum(
# [[
# round((-1 * (-i['y'] - height / 2)) / height, 5), # y
# round((i['x'] + width / 2) / width, 5), # x
#
# ] for i in outline],
# [])
return points
def anima2d_to_dragon_bones():
data = {
"frameRate": 24,
"name": f"{anima2d_name}",
"version": "5.5",
"compatibleVersion": "5.5",
"armature": [
{
"type": "Armature",
"frameRate": 24,
"name": "hair",
"aabb": {
"x": -32.5,
"y": -150.51,
"width": 219.3,
"height": 250
},
"bone": [
{
"name": "root"
}
],
"slot": [
# {
# "name": "name",
# "parent": "root"
# }
],
"skin": [
{
"slot": [
]
}
],
"animation": [
{
"duration": 0,
"playTimes": 0,
"name": "animtion0"
}
],
"defaultActions": [
{
"gotoAndPlay": "animtion0"
}
]
}
]
}
im = Image.open(f"image_{anima2d_name}.png")
Iwidth, Iheight = im.size
with open(f'image_{anima2d_name}.png.meta', 'r') as file:
image_hasumi = yaml.safe_load(file)
spriteSheet = image_hasumi['TextureImporter']['spriteSheet']
for sprite in spriteSheet['sprites']:
width = sprite['rect']['width']
height = sprite['rect']['height']
x = sprite['rect']['x']
y = Iheight - height - sprite['rect']['y']
name = sprite['name']
pivot = sprite['pivot'] if 'pivot' in sprite else {'x': 0.50, 'y': 0.50}
rotate = None
outline = sprite['outline'] if 'outline' in sprite else []
physics_shape = sprite['physicsShape'] if 'physicsShape' in sprite else []
print(name)
# print(sprite['border'])
# print(sprite['outline'])
# print(sprite['physicsShape'])
#
# bones = sprite['bones']
# print(bones)
im1 = im.crop((x, y, x + width, y + height))
filename = "unpack/" + name
# data['armature'][0]['bone'].append({
# 'name': name,
# "parent": "root"
# })
data['armature'][0]['slot'].append({
'name': name,
"parent": "root"
})
vertices = sum(
[[i['x'], -i['y']] for i in outline[0]],
[]
)
data['armature'][0]['skin'][0]['slot'].append({
'name': name,
'display': [
{
'name': name,
"transform": {
"x": round(x, 3),
"y": round(y, 3)
},
'pivot': pivot,
"type": "mesh",
"width": int(width),
"height": int(height),
# "vertices": [],
# "uvs": [],
# "triangles": [],
# "edges": [],
# "userEdges": []
"vertices": vertices,
# "vertices": [
# -round(width/2, 3), -round(height/2, 3),
# round(width/2, 3), -round(height/2, 3),
# -round(width/2, 3), round(height/2, 3),
# round(width/2, 3), round(height/2, 3)
# ],
"uvs": generate_uvs(outline[0], width, height),
# "triangles": [
# 0, 1, 2,
# 1, 3, 2
# ],
"triangles": sum(generate_triangles(vertices), []),
# "edges": [
# 0, 1,
# 1, 3,
# 3, 2,
# 2, 0
# ],
"edges": generate_edges(vertices),
"userEdges": []
}
]
})
if len(physics_shape) > 0:
data['armature'][0]['slot'].append({
'name': f'{name}_boundingBox',
"parent": name
})
transform = {
"x": round(x, 3),
"y": round(y, 3),
}
if rotate:
transform.update({
"skX": round(rotate['x'] * 100, 3),
"skY": round(rotate['y'] * 100, 3)
})
data['armature'][0]['skin'][0]['slot'].append({
'name': f'{name}_boundingBox',
'display': [
{
'name': f'{name}_boundingBox',
'type': "boundingBox",
'subType': "polygon",
'pivot': pivot,
"vertices": sum(
[[i['x'], -i['y']] for i in physics_shape[0]],
[]),
"transform": transform
}
]
})
# Hack cause I'm terrible with UV
# im1 = ImageOps.flip(im1)
if save_img:
im1.save(filename + ".png", "PNG")
with open(f"{anima2d_name}_ske.json", "w+") as out:
import json
json.dump(data, out, indent=2)
def do_tests():
width = 65
height = 104
vertices = [
-108, -63.5,
-43, -63.5,
-108, 40.5,
-43, 40.5
]
outline = [[
{'x': -108, 'y': 63.5},
{'x': -43, 'y': 63.5},
{'x': -108, 'y': -40.5},
{'x': -43, 'y': -40.5},
]]
expected_uvs = [
0, 0,
1, 0,
0, 1,
1, 1
]
expected_triangles = [
1, 0, 3,
0, 2, 3
]
expected_edges = [
0, 1,
1, 3,
3, 2,
2, 0
]
uvs = generate_uvs(outline[0], width, height)
edges = generate_edges(vertices)
triangles = generate_triangles(vertices)
print(uvs)
if __name__ == '__main__':
import sys
if len(sys.argv) > 1 and 'test' in sys.argv[1:]:
do_tests()
else:
anima2d_to_dragon_bones()