-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmcd.py
679 lines (560 loc) · 22.9 KB
/
mcd.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
import copy
import os, sys
import json
import ioUtils
import zlib
def hash_event_name(name):
return zlib.crc32(name.lower().encode("utf-8")) & ~0x80000000 # HAH gotem platinum
# https://github.com/synspawacza/nier_automata_localization
def calc_eager_padding(offset, mod):
return mod - (offset % mod)
def write_eager_padding(offset, mod):
return b"\0" * calc_eager_padding(offset, mod)
class Header:
struct_size = 40
def from_mcd(self, file):
self.messages_offset = ioUtils.read_int32(file)
self.messages_count = ioUtils.read_int32(file)
self.symbols_offset = ioUtils.read_int32(file)
self.symbols_count = ioUtils.read_int32(file)
self.glyphs_offset = ioUtils.read_int32(file)
self.glyphs_count = ioUtils.read_int32(file)
self.fonts_offset = ioUtils.read_int32(file)
self.fonts_count = ioUtils.read_int32(file)
self.events_offset = ioUtils.read_int32(file)
self.events_count = ioUtils.read_int32(file)
return self
def write_file(self, file):
ioUtils.write_Int32(file, self.messages_offset)
ioUtils.write_Int32(file, self.messages_count)
ioUtils.write_Int32(file, self.symbols_offset)
ioUtils.write_Int32(file, self.symbols_count)
ioUtils.write_Int32(file, self.glyphs_offset)
ioUtils.write_Int32(file, self.glyphs_count)
ioUtils.write_Int32(file, self.fonts_offset)
ioUtils.write_Int32(file, self.fonts_count)
ioUtils.write_Int32(file, self.events_offset)
ioUtils.write_Int32(file, self.events_count)
class Line:
struct_size = 24
def from_mcd(self, file):
content_offset = ioUtils.read_int32(file)
self.padding = ioUtils.read_int32(file)
content_length = ioUtils.read_int32(file)
ioUtils.read_int32(file)
self.below = ioUtils.read_float(file)
self.horiz = ioUtils.read_float(file)
last_pos = file.tell()
self.content = []
file.seek(content_offset)
for i in range(content_length):
val = ioUtils.read_int16(file)
if val < -32000:
val = val & 0xFFFF
self.content.append(val)
file.seek(last_pos)
return self
def to_string(self, symbols_glyph_Dict, font): # I stole this :) https://github.com/synspawacza/nier_automata_localization
result = ""
idx = 0
while idx < len(self.content) - 1:
char_id = self.content[idx]
if char_id < 0x8000:
result += symbols_glyph_Dict[char_id].char
if symbols_glyph_Dict[char_id].font_id != font.id:
raise Exception("Font mismatch")
idx += 2 # skip kerning
elif char_id == 0x8001:
result += " "
#result += f"[SET_FONT:{self.content[idx+1]}]"
idx += 2 # skip font id
elif char_id == 0x8000:
# text end
idx += 1
elif char_id == 0x8020:
result += "<special:" + str(self.content[idx + 1]) + ">"
idx += 2
else:
# using '<' and '>' for tagging - hopefully it doesn't break anything
result += "<unknown:" + str(char_id)
if idx + 1 < len(self.content):
result += ":" + str(self.content[idx + 1])
result += ">"
idx += 2 # skip kerning
return result
def from_string(self, string, symbols, font, kernings):
self.content = []
self.padding = 0
self.below = 0
self.horiz = 0
for i, char in enumerate(string):
if (char == " "):
self.content.append(0x8001)
self.content.append(font.id)
else:
for symbol in symbols:
if symbol.font_id != font.id:
continue
glyph_found = False
if symbol.char == char:
val = symbol.glyph_index
glyph_found = True
break
self.below = font.below
if not glyph_found:
raise Exception("Glyph not found in font " + str(font.id) + ": " + char)
self.content.append(val)
# Get next char
if i + 1 < len(string):
next_char = string[i + 1]
combined = char + next_char
if combined in kernings[font.id]:
self.content.append(round(kernings[font.id][combined]["kerning_num"]))
else:
self.content.append(0)
else:
self.content.append(0)
self.content.append(0x8000)
return self
class Text:
struct_size = 20
def from_mcd(self, file):
lines_offset = ioUtils.read_int32(file)
lines_count = ioUtils.read_int32(file)
self.vpos = ioUtils.read_int32(file)
self.hpos = ioUtils.read_int32(file)
self.font = ioUtils.read_int32(file)
last_pos = file.tell()
self.lines = []
file.seek(lines_offset)
for i in range(lines_count):
self.lines.append(Line().from_mcd(file))
file.seek(last_pos)
return self
def from_json(self, json, symbols, fonts_dict, kernings):
self.lines = []
self.vpos = json["vpos"]
self.hpos = json["hpos"]
self.font = json["font"]
split_lines = json["line"].split("\n")
for line in split_lines:
self.lines.append(Line().from_string(line, symbols, fonts_dict[self.font], kernings))
return self
def to_string(self, symbols_char_Dict, fonts_dict):
return "\n".join([line.to_string(symbols_char_Dict, fonts_dict[self.font]) for line in self.lines])
class Message:
struct_size = 16
def from_mcd(self, file):
texts_offset = ioUtils.read_int32(file)
texts_count = ioUtils.read_int32(file)
self.seq_number = ioUtils.read_int32(file)
self.event_id = ioUtils.read_int32(file)
return_pos = file.tell()
self.texts = []
file.seek(texts_offset)
for i in range(texts_count):
self.texts.append(Text().from_mcd(file))
file.seek(return_pos)
return self
def from_json(self, json, seq_number, symbols, fonts_dict, kernings):
self.seq_number = seq_number
self.event_name = json["event_name"]
self.event_id = hash_event_name(self.event_name)
self.texts = []
for text in json["texts"]:
self.texts.append(Text().from_json(text, symbols, fonts_dict, kernings))
return self
class Symbol:
struct_size = 8
def from_mcd(self, file):
self.font_id = ioUtils.read_int16(file)
self.char = file.read(2).decode("utf-16-le")
self.glyph_index = ioUtils.read_int32(file)
return self
def from_json(self, json, font_id):
self.font_id = font_id
self.char = json["char"]
self.glyph_index = json["glyph_index"]
return self
class Event:
struct_size = 40
def from_mcd(self, file):
self.id = ioUtils.read_int32(file)
self.idx = ioUtils.read_int32(file)
self.name = file.read(32).decode("utf-8").rstrip("\0")
return self
def from_message(self, name, message_idx):
self.id = hash_event_name(name)
self.idx = message_idx
self.name = name
return self
class Font:
struct_size = 20
def from_mcd(self, file):
self.id = ioUtils.read_int32(file)
self.width = ioUtils.read_float(file)
self.height = ioUtils.read_float(file)
self.below = ioUtils.read_float(file)
self.horiz = ioUtils.read_float(file)
return self
def from_json(self, json):
self.id = json["id"]
self.width = json["width"]
self.height = json["height"]
self.below = json["below"]
self.horiz = json["horiz"]
return self
class Glyph:
struct_size = 40
def from_mcd(self, file):
self.texture_id = ioUtils.read_uint32(file)
self.u1 = ioUtils.read_float(file)
self.v1 = ioUtils.read_float(file)
self.u2 = ioUtils.read_float(file)
self.v2 = ioUtils.read_float(file)
self.width = ioUtils.read_float(file)
self.height = ioUtils.read_float(file)
self.u_a = ioUtils.read_float(file)
self.below = ioUtils.read_float(file)
self.horiz = ioUtils.read_float(file)
return self
def from_json(self, json):
self.texture_id = json["texture_id"]
self.u1 = json["u1"]
self.v1 = json["v1"]
self.u2 = json["u2"]
self.v2 = json["v2"]
self.width = json["width"]
self.height = json["height"]
self.u_a = json["u_a"]
self.below = json["below"]
self.horiz = json["horiz"]
return self
class MCD:
def from_mcd(self, file):
self.header = Header().from_mcd(file)
file.seek(self.header.messages_offset)
self.messages = []
for i in range(self.header.messages_count):
self.messages.append(Message().from_mcd(file))
file.seek(self.header.symbols_offset)
self.symbols = []
for i in range(self.header.symbols_count):
self.symbols.append(Symbol().from_mcd(file))
file.seek(self.header.glyphs_offset)
self.glyphs = []
for i in range(self.header.glyphs_count):
self.glyphs.append(Glyph().from_mcd(file))
file.seek(self.header.fonts_offset)
self.fonts = []
for i in range(self.header.fonts_count):
self.fonts.append(Font().from_mcd(file))
file.seek(self.header.events_offset)
self.events = []
for i in range(self.header.events_count):
self.events.append(Event().from_mcd(file))
self.generate_events_Dict()
self.generate_fonts_Dict()
self.generate_symbols_char_Dict()
self.generate_symbols_glyph_Dict()
self.kernings = {}
self.generate_kernings()
return self
def generate_events_Dict(self):
self.events_Dict = {}
for event in self.events:
self.events_Dict[event.id] = event
def generate_symbols_char_Dict(self):
self.symbols_char_Dict = {}
for symbol in self.symbols:
self.symbols_char_Dict[symbol.char] = symbol
def generate_symbols_glyph_Dict(self):
self.symbols_glyph_Dict = {}
for symbol in self.symbols:
self.symbols_glyph_Dict[symbol.glyph_index] = symbol
def generate_fonts_Dict(self):
self.fonts_Dict = {}
for font in self.fonts:
self.fonts_Dict[font.id] = font
# This function is gonked, should probably not use for now
def generate_kernings(self):
for font in self.fonts:
self.kernings[font.id] = {}
for message in self.messages:
for text in message.texts:
font = self.fonts_Dict[text.font]
for line in text.lines:
idx = 0
while idx < len(line.content) - 1:
val = line.content[idx]
if val < 0x8000:
char = self.symbols_glyph_Dict[val].char
kerning = line.content[idx+1]
next_val = line.content[idx+2]
if next_val < 0x8000:
next_char = self.symbols_glyph_Dict[next_val].char
char_pair = char + next_char
if char_pair in self.kernings[font.id]:
self.kernings[font.id][char_pair]["kerning_num"] += kerning
self.kernings[font.id][char_pair]["count"] += 1
else:
self.kernings[font.id][char_pair] = {
"kerning_num": kerning,
"count": 1
}
idx += 2
elif val == 0x8001:
idx += 2
elif val == 0x8000:
idx += 2
for font in self.kernings.keys():
for kerning in self.kernings[font].keys():
self.kernings[font][kerning]["kerning_num"] /= self.kernings[font][kerning]["count"]
#with open("kernings.json", "w") as file:
# json.dump(self.kernings, file, indent=4)
def update_from_json(self, json):
# Fonts & Symbols
self.fonts = []
self.symbols = []
for font in json["fonts"]:
self.fonts.append(Font().from_json(font))
for symbol in font["symbols"]:
self.symbols.append(Symbol().from_json(symbol, font["id"]))
self.generate_fonts_Dict()
self.generate_kernings()
# Glyphs
self.glyphs = []
for glyph in json["glyphs"]:
self.glyphs.append(Glyph().from_json(glyph))
# Events
self.events = []
for i, message in enumerate(json["messages"]):
self.events.append(Event().from_message(message["event_name"], i))
self.events.sort(key=lambda x: x.id)
self.generate_events_Dict()
# Messages
self.messages = []
seq_number = json["starting_seq_number"]
for message in json["messages"]:
self.messages.append(Message().from_json(message, seq_number, self.symbols, self.fonts_Dict, self.kernings))
seq_number += 1
# Header
self.header.events_count = len(self.events)
self.header.messages_count = len(self.messages)
self.header.fonts_count = len(self.fonts)
self.header.symbols_count = len(self.symbols)
self.header.glyphs_count = len(self.glyphs)
def to_json(self):
json_data = {}
json_data["starting_seq_number"] = self.messages[0].seq_number
json_data["messages"] = []
for msg in self.messages:
json_data["messages"].append({
"event_name": self.events_Dict[msg.event_id].name,
"texts": []
})
for text in msg.texts:
json_data["messages"][-1]["texts"].append({
"vpos": text.vpos,
"hpos": text.hpos,
"font": text.font,
"line": text.to_string(self.symbols_glyph_Dict, self.fonts_Dict)
})
json_data["fonts"] = []
for font in self.fonts:
json_data["fonts"].append({
"id": font.id,
"width": font.width,
"height": font.height,
"below": font.below,
"horiz": font.horiz,
"symbols": []
})
for symbol in self.symbols:
if symbol.font_id == font.id:
json_data["fonts"][-1]["symbols"].append({
"char": symbol.char,
"glyph_index": symbol.glyph_index,
})
json_data["glyphs"] = []
for glyph in self.glyphs:
json_data["glyphs"].append({
"texture_id": glyph.texture_id,
"u1": glyph.u1,
"v1": glyph.v1,
"u2": glyph.u2,
"v2": glyph.v2,
"width": glyph.width,
"height": glyph.height,
"u_a": glyph.u_a,
"below": glyph.below,
"horiz": glyph.horiz
})
return json_data
def write_file(self, file): # https://github.com/synspawacza/nier_automata_localization
current_offset = Header.struct_size
strings = []
strings_offsets = []
texts = []
texts_offsets = []
lines = []
lines_offsets = []
for message in self.messages:
for text in message.texts:
texts.append(text)
for line in text.lines:
strings.append(line.content)
strings_offsets.append(current_offset)
current_offset += len(line.content) * 2
lines.append(line)
current_offset += calc_eager_padding(current_offset, 4)
# Update header offsets
self.header.messages_offset = current_offset
current_offset += self.header.messages_count * Message.struct_size
current_offset += calc_eager_padding(current_offset, 4)
for i in range(len(texts)):
texts_offsets.append(current_offset + i * Text.struct_size)
current_offset += len(texts) * Text.struct_size
current_offset += calc_eager_padding(current_offset, 4)
for i in range(len(lines)):
lines_offsets.append(current_offset + i * Line.struct_size)
current_offset += len(lines) * Line.struct_size
current_offset += calc_eager_padding(current_offset, 4)
self.header.symbols_offset = current_offset
self.header.symbols_count = len(self.symbols)
current_offset += self.header.symbols_count * Symbol.struct_size + 4
self.header.glyphs_offset = current_offset
self.header.glyphs_count = len(self.glyphs)
current_offset += self.header.glyphs_count * 40 + 4
self.header.fonts_offset = current_offset
self.header.fonts_count = len(self.fonts)
current_offset += self.header.fonts_count * Font.struct_size + 4
self.header.events_offset = current_offset
# Write header
self.header.write_file(file)
# Write strings
for string in strings:
for v in string:
val = v
if val < 0:
ioUtils.write_Int16(file, val)
else:
ioUtils.write_uInt16(file, val)
file.write(write_eager_padding(file.tell(), 4))
# Write messages
texts_offset_idx = 0
for message in self.messages:
texts_offset = texts_offsets[texts_offset_idx]
texts_offset_idx += len(message.texts)
ioUtils.write_uInt32(file, texts_offset)
ioUtils.write_uInt32(file, len(message.texts))
ioUtils.write_uInt32(file, message.seq_number)
ioUtils.write_uInt32(file, message.event_id)
file.write(write_eager_padding(file.tell(), 4))
# Write texts
lines_offset_idx = 0
for text in texts:
lines_offset = lines_offsets[lines_offset_idx]
lines_offset_idx += len(text.lines)
ioUtils.write_uInt32(file, lines_offset)
ioUtils.write_uInt32(file, len(text.lines))
ioUtils.write_uInt32(file, text.vpos)
ioUtils.write_uInt32(file, text.hpos)
ioUtils.write_uInt32(file, text.font)
file.write(write_eager_padding(file.tell(), 4))
# Write lines
strings_idx = 0
for line in lines:
strings_offset = strings_offsets[strings_idx]
strings_idx += 1
ioUtils.write_uInt32(file, strings_offset)
ioUtils.write_uInt32(file, line.padding)
ioUtils.write_uInt32(file, len(line.content))
ioUtils.write_uInt32(file, len(line.content))
ioUtils.write_float(file, line.below)
ioUtils.write_float(file, line.horiz)
file.write(write_eager_padding(file.tell(), 4))
# Write symbols
for symbol in self.symbols:
ioUtils.write_uInt16(file, symbol.font_id)
ioUtils.write_utf16(file, symbol.char, 2)
ioUtils.write_uInt32(file, symbol.glyph_index)
file.write(write_eager_padding(file.tell(), 4))
# Write glyphs
for glyph in self.glyphs:
ioUtils.write_uInt32(file, glyph.texture_id)
ioUtils.write_float(file, glyph.u1)
ioUtils.write_float(file, glyph.v1)
ioUtils.write_float(file, glyph.u2)
ioUtils.write_float(file, glyph.v2)
ioUtils.write_float(file, glyph.width)
ioUtils.write_float(file, glyph.height)
ioUtils.write_float(file, glyph.u_a)
ioUtils.write_float(file, glyph.below)
ioUtils.write_float(file, glyph.horiz)
file.write(write_eager_padding(file.tell(), 4))
# Write fonts
for font in self.fonts:
ioUtils.write_uInt32(file, font.id)
ioUtils.write_float(file, font.width)
ioUtils.write_float(file, font.height)
ioUtils.write_float(file, font.below)
ioUtils.write_float(file, font.horiz)
file.write(write_eager_padding(file.tell(), 4))
# Write events
for event in self.events:
ioUtils.write_uInt32(file, event.id)
ioUtils.write_uInt32(file, event.idx)
ioUtils.write_utf8(file, event.name, 32)
def mcd_to_json(mcd_file, out_file=None):
with open(mcd_file, 'rb') as file:
mcd = MCD().from_mcd(file)
if out_file is None:
out_file = os.path.splitext(mcd_file)[0] + ".json"
with open(out_file, "w", encoding="utf8") as f:
json_data = mcd.to_json()
json_str = json.dumps(json_data, indent=4, ensure_ascii=False)
f.write(json_str)
print("Wrote", out_file)
def json_to_mcd(json_file, mcd_file, out_file=None):
with open(mcd_file, 'rb') as file:
mcd = MCD().from_mcd(file)
#org_mcd = copy.deepcopy(mcd)
mcd.update_from_json(json.load(open(json_file, "r", encoding="utf8")))
if out_file is None:
out_file = os.path.splitext(json_file)[0] + ".mcd"
with open(out_file, "wb") as file:
mcd.write_file(file)
print("Wrote", out_file)
def print_usage():
print("Usage:\tmcd.py <mcd file> [output json file]"
"\n\tmcd.py <json file> <base mcd file> [output mcd file]"
"\nInfo:\t- If no output file is specified, the input file name will be used with the appropriate extension."
"\n\t- <base mcd file> is used as the base for fonts/glyphs used in the new mcd file.")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
print_usage()
if sys.argv[1] in ["-h", "--help"]:
print_usage()
in_file = sys.argv[1]
in_file = os.path.normpath(in_file)
in_file_ext = os.path.splitext(in_file)[1]
# MCD to JSON
if in_file_ext == ".mcd":
out_file = None
if len(sys.argv) > 2:
out_file = sys.argv[2]
out_file = os.path.normpath(out_file)
mcd_to_json(in_file, out_file)
# JSON to MCD
if in_file_ext == ".json":
if len(sys.argv) < 3:
print_usage()
mcd_file = sys.argv[2]
mcd_file = os.path.normpath(mcd_file)
out_file = None
if len(sys.argv) > 3:
out_file = sys.argv[3]
out_file = os.path.normpath(out_file)
json_to_mcd(in_file, mcd_file, out_file)