-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathprepare_assets.py
731 lines (600 loc) · 28 KB
/
prepare_assets.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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# How to use
# ==========
# pip install pipenv
# pipenv install -d
# pipenv run python prepare_assets.py
# Quelle https://thepythoncorner.com/posts/2019-01-13-how-to-create-a-watchdog-in-python-to-look-for-filesystem-changes/
# We need python 3.10 for cross platform newline
# Export to exe on windows via
# pyinstaller --onefile .\prepare_assets.py
from __future__ import annotations
import contextlib
import hashlib
import json
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass, field
from multiprocessing import Pool, freeze_support
from os import cpu_count, walk
from pathlib import Path
from stat import S_IREAD, S_IRGRP, S_IROTH, S_IWUSR
from typing import Any, Literal
import requests
from termcolor import colored
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
SCHNACKER_FOLDER = "data/dialog/"
RHUBARB_OUT = "data/rhubarb/"
SPINE_THREADS = cpu_count()
set_read_only = True
# could be "linux", "linux2", "linux3", ...
if sys.platform.startswith("linux"):
RHUBARB = None
SPINE = "/usr/bin/spine"
LUA = "luac"
elif sys.platform == "darwin":
RHUBARB = "/Applications/Rhubarb-Lip-Sync-1.13.0-macOS/rhubarb"
SPINE = "/Applications/Spine.app/Contents/MacOS/Spine"
LUA = "luac"
elif sys.platform == "win32":
# Windows
SPINE = "C:\\Program Files\\Spine\\Spine.exe"
if getattr(sys, "frozen", False):
mod_path = Path(sys.executable).resolve().parent
elif __file__:
mod_path = Path(__file__).parent
RHUBARB = (mod_path / "windows_bin\\rhubarb.exe").resolve()
LUA = (mod_path / "windows_bin\\luac.exe").resolve()
set_read_only = False
spine_objects: dict[str, set[str]] = {"Player": {"internal"}, "Background": {"internal"}}
spine_animations: dict[str, set[str]] = {}
spine_skins: dict[str, set[str]] = {}
spine_points: dict[str, set[str]] = {}
all_dialogs: dict[str, set[str]] = {}
all_scenes: dict[str, set[str]] = {}
all_audio: dict[str, set[str]] = {}
all_language: dict[str, set[str]] = {}
scene_files = [] # Temp list to prevent infinite loop
class Progress:
def __init__(self: Progress,
initialCount: int,
maxCount: int,
maxTitleLength: int = 26,
barLength: int = 46) -> None:
self._initialCount = initialCount
self._currentCount = initialCount
self._maxCount = maxCount
self._title = ""
self._maxTitleLength = maxTitleLength
self._barLength = barLength
self._errors = []
def updateTitle(self: Progress, title: str) -> None:
self._title = title
self.print_status()
def advance(self: Progress, count: int = 1) -> None:
self._currentCount += count
self.print_status()
def print_status(self: Progress) -> None:
if self._maxCount == 0:
return
percent = float(self._currentCount) / self._maxCount
printedTitle = (self._title if len(self._title) <= self._maxTitleLength
else "[...]" + self._title[len(self._title) - self._maxTitleLength - 5:])
filledCount = int(self._barLength * percent)
filled = "█" * filledCount
unfilled = "-" * (self._barLength - filledCount)
percentage = "%3.1f" % (percent * 100)
print(colored(f"\r{printedTitle} |{filled}{unfilled}| {percentage}%",
"red" if len(self._errors) > 0
else "blue"), end="\r")
def finish(self: Progress) -> None:
print("\n")
def addError(self: Progress, errorMsg: str) -> None:
self._errors.append(errorMsg)
self.print_status()
def rhubarb_export(node_info: list[tuple[str, str]]) -> list[Any]:
node_id = node_info[0]
errors = []
if not RHUBARB:
return errors
rhubarb_out = Path(f"{RHUBARB_OUT}{node_id}.json")
with contextlib.suppress(FileNotFoundError):
if set_read_only:
rhubarb_out.chmod(S_IREAD | S_IRGRP | S_IROTH | S_IWUSR)
command = [RHUBARB, f"data/audio/{node_id}.ogg", "-r", "phonetic", "-f", "json", "-o", str(rhubarb_out)]
p = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate()[0]
if p.returncode != 0:
errors.append(output.decode())
with contextlib.suppress(FileNotFoundError):
if set_read_only:
rhubarb_out.chmod(S_IREAD | S_IRGRP | S_IROTH)
return errors
def rhubarb_reexport() -> None:
nodes = get_notes()
progress = Progress(0, len(nodes))
progress.updateTitle(" Re-Exporting Rhubarb Files")
results = []
Path(RHUBARB_OUT).mkdir(parents=True, exist_ok=True)
with Pool(SPINE_THREADS) as p:
for i, (errors) in enumerate(p.imap_unordered(rhubarb_export, nodes), 0):
progress.advance()
if len(errors) > 0:
results.append({
"file": nodes[i],
"errors": errors,
})
progress.finish()
def apply_rhubarb(character=None) -> None:
nodes = get_notes(character)
for node_info in nodes:
node_id = node_info[0]
character_name = node_info[1]
rhubarb_out = Path(f"{RHUBARB_OUT}{node_id}.json")
# read rhubarb output
with rhubarb_out.open() as rhubarb_outfile:
# Add animation to character
character_path = Path(f"data/{character_name}/{character_name}.json")
if not character_path.exists():
print("Can not write into: ", character_path)
continue
if set_read_only:
character_path.chmod(S_IREAD | S_IRGRP | S_IROTH | S_IWUSR)
with character_path.open("r+") as character_file:
mouthCues = json.load(rhubarb_outfile)
character = json.load(character_file)
if "animations" not in character:
character["animations"] = {}
character["animations"][f"say_{node_id}"] = {}
character["animations"][f"say_{node_id}"]["slots"] = {}
skins = [skin["name"] for skin in character["skins"]]
for skin in skins:
animation = [{"time": cues["start"], "name": f"{skin}/mouth-{str(cues['value']).lower()}"}
for cues in mouthCues["mouthCues"]]
character["animations"][f"say_{node_id}"]["slots"][f"{skin}-mouth"] = {}
character["animations"][f"say_{node_id}"]["slots"][f"{skin}-mouth"]["attachment"] = animation
character_file.seek(0)
character_file.write(json.dumps(character, indent=4))
if set_read_only:
character_path.chmod(S_IREAD | S_IRGRP | S_IROTH)
def get_notes(character=None) -> list[Any]:
nodes = []
for _root, _dirs, files in walk(SCHNACKER_FOLDER):
for file in files:
if file.endswith(".schnack"):
with Path(_root + file).open(encoding="utf-8") as dialog_file:
dialogs = json.load(dialog_file)
for dialog in dialogs["dialogs"]:
for node in dialog["nodes"]:
if "character" not in node or (character and node["character"] != character):
continue
character_name = node["character"]
if "character" not in node or node["character"] in ["Player"]:
character_name = "joy"
if dialogs["localization"].get(str(node["id"])):
node_id = str(node["id"]).zfill(3)
for lang_code in dialogs["locales"]:
if not Path(f"data/audio/{lang_code}_{node_id}.ogg").exists():
print(colored(f"Can not load: data/audio/{lang_code}_{node_id}.ogg", "red"))
continue
nodes.append((f"{lang_code}_{node_id}", character_name))
return nodes
def spine_reexport(directorys: list[str]) -> None:
spinefiles = []
for folder in directorys:
for root, _dirs, files in walk(folder):
for file in files:
if file.endswith(".spine"):
spinefiles.append(root + "/" + file)
progress = Progress(0, len(spinefiles))
progress.updateTitle(" Re-Exporting Spine Files")
results = []
with Pool(SPINE_THREADS) as p:
for i, (errors, spine_object, spine_file) in enumerate(p.imap_unordered(spine_export, spinefiles), 0):
progress.advance()
spine_objects.update(spine_object)
if not errors:
parse_spine_json(spine_file=spine_file)
if len(errors) > 0:
results.append({
"file": spinefiles[i],
"errors": errors,
})
progress.finish()
for result in results:
printErrors(
result["file"], result["errors"])
def printErrors(fileName: str, errors: list[str]) -> None:
color: Literal["red", "yellow"] = "red" if len(errors) > 0 else "yellow"
print(colored(f" {fileName}", color))
for error in errors:
print(colored(f" ERROR: {error}", "red"))
print()
def parse_spine_json(spine_file: str) -> None:
# read spine json to check for missing scripts
with Path(spine_file).open() as spine_json:
spine_object = json.load(spine_json)
if "animations" in spine_object:
for animation in spine_object["animations"]:
if animation in spine_animations:
spine_animations[animation].add(spine_file)
else:
spine_animations[animation] = {spine_file}
if "skins" in spine_object:
for skin in spine_object["skins"]:
if skin["name"] in spine_skins:
spine_skins[skin["name"]].add(spine_file)
else:
spine_skins[skin["name"]] = {spine_file}
if "attachments" not in skin:
continue
for attachment in skin["attachments"]:
for subattachment in skin["attachments"][attachment]:
if ("type" in skin["attachments"][attachment][subattachment] and
skin["attachments"][attachment][subattachment]["type"] == "point"):
point_name = subattachment
if point_name in spine_points:
spine_points[point_name].add(spine_file)
else:
spine_points[point_name] = {spine_file}
for i, _skin in enumerate(spine_object["skins"]):
if "attachments" not in spine_object["skins"][i]:
continue
attachment_obj = spine_object["skins"][i]["attachments"]
for attachment in attachment_obj:
for subattachment in attachment_obj[attachment]:
if "name" in attachment_obj[attachment][subattachment]:
bbname = attachment_obj[attachment][subattachment]["name"]
else:
bbname = subattachment
if "type" in attachment_obj[attachment][subattachment] \
and attachment_obj[attachment][subattachment]["type"] == "boundingbox":
if bbname == "walkable_area" or bbname == "non_walkable_area": # No scripts for navmeshes
continue
if (not bbname.startswith("dlg:") and not bbname.startswith("anim:") and
not Path(f"./data-src/scripts/{bbname}.lua").exists()):
if not Path("./data-src/scripts/").exists():
Path("./data-src/scripts/").mkdir(parents=True, exist_ok=True)
with Path(f"./data-src/scripts/{bbname}.lua").open("w") as f:
f.write(f'print("{bbname}")')
print(colored(f"Script {bbname}.lua was created automatically!", "blue"))
if bbname.startswith("dlg:") and bbname[4:] not in all_dialogs:
print(colored(f"Dialog {bbname[4:]} is missing!", "red"))
# there is no print allowed in this function, since this would destroy the progress bar
def spine_export(file: str) -> tuple[list[str], dict[Any, Any], Literal[""]] | tuple[list[Any],
dict[str, set[str]], str]:
errors = []
if not file.endswith(".spine"):
errors.append("invalid spine file " + file)
return errors, {}, ""
if not Path(SPINE).exists():
errors.append("spine executable '" + SPINE + "' could not be found!")
return errors, {}, ""
name = Path(file).stem
command: list[str] = [SPINE, "-i", file, "-m", "-o",
f"./data/{name}/", "-e", "./data-src/spine_export_template.export.json"]
with contextlib.suppress(Exception):
shutil.rmtree(f"./data/{name}/", ignore_errors=True)
if set_read_only:
Path(f"./data/{name}/{name}.json").chmod(S_IREAD | S_IRGRP | S_IROTH | S_IWUSR)
Path(f"./data/{name}/{name}.atlas").chmod(S_IREAD | S_IRGRP | S_IROTH | S_IWUSR)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate()[0]
if p.returncode != 0:
print(colored(output.decode(), "red"))
sys.exit(p.returncode)
if not Path(f"./data/{name}/{name}.json").exists():
errors.append(
f"Spine export of {name} failed. No file ./data/{name}/{name}.json was created. \n"
f"Is the sceleton of {name}.spine named {name}?")
return errors, {}, ""
if (Path(file).parent / Path("zBufferMap")).exists():
copy_folder(str(Path(file).parent / Path("zBufferMap")), f"./data/{name}/")
if set_read_only:
with contextlib.suppress(Exception):
Path(f"./data/{name}/{name}.json").chmod(S_IREAD | S_IRGRP | S_IROTH)
Path(f"./data/{name}/{name}.atlas").chmod(S_IREAD | S_IRGRP | S_IROTH)
return errors, {name: {file}}, f"./data/{name}/{name}.json"
def scripts_recopy(directorys: list[str]) -> None:
for folder in directorys:
for root, _dirs, files in walk(folder):
for file in files:
if file.endswith(".lua"):
copy_script(file=root + "/" + file)
def rehash_scenes(directorys: str) -> None:
for root, _dirs, files in walk(directorys):
for file in files:
if file.endswith(".json"):
if file in all_scenes:
all_scenes[file.rstrip(".json")].add("data-src")
else:
all_scenes[file.rstrip(".json")] = {"data-src"}
src_path = root + "/" + file
try:
with Path(src_path).open() as f:
data = f.read()
parsed = json.loads(data)
for item in parsed["items"]:
if "id" in item:
spine_objects.update({item["id"]: file})
parsed["hash"] = ""
parsed["hash"] = hashlib.sha1(str(parsed).encode()).hexdigest()
with Path(src_path).open("w") as f:
scene_files.append(src_path)
f.write(json.dumps(parsed, indent=4))
except Exception:
print(colored(f"data-src file '{src_path}' has errors", "red"))
def copy_script(file: str) -> None:
if file.endswith("ALPACA.lua"):
return
if file.endswith(".lua"):
command = [LUA, "-p", file]
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate()[0]
if p.returncode != 0:
print(colored(output.decode(), "red"))
name = Path(file).name
Path("./data/scripts").mkdir(parents=True, exist_ok=True)
if set_read_only:
with contextlib.suppress(Exception):
Path(f"./data/scripts/{name}").chmod(S_IREAD | S_IRGRP | S_IROTH | S_IWUSR)
shutil.copyfile(file, f"./data/scripts/{name}")
if set_read_only:
Path(f"./data/scripts/{name}").chmod(S_IREAD | S_IRGRP | S_IROTH)
def copy_folder(src: str, des: str) -> None:
for root, _dirs, files in walk(src):
for file in files:
copy_file(src=root + "/" + file, des=Path(des))
if ".schnack" in file:
fill_all_dialogs(Path(root + "/" + file), file)
def copy_file(src: str, des: Path) -> None:
src = src.replace("\\", "/")
name = Path(src).name
Path(des).mkdir(parents=True, exist_ok=True)
if set_read_only:
with contextlib.suppress(Exception):
Path(f"{des}/{name}").chmod(S_IREAD | S_IRGRP | S_IROTH | S_IWUSR)
with contextlib.suppress(FileNotFoundError):
shutil.copyfile(src, f"{des}/{name}")
if set_read_only:
Path(f"{des}/{name}").chmod(S_IREAD | S_IRGRP | S_IROTH)
def on_created(event) -> None:
print(colored(f"{event.src_path} has been created!", "green"))
def on_deleted(event) -> None:
print(colored(f"{event.src_path} was deleted! Please delete it manually from data.", "red"))
def on_data_src_modified(event) -> None:
time.sleep(.5)
print(colored(f"data-src file '{event.src_path}' has been modified", "green"))
if event.src_path.endswith(".spine"):
(errors, spine_object, spine_file) = spine_export(event.src_path)
spine_objects.update(spine_object)
if not errors:
parse_spine_json(spine_file=spine_file)
if len(errors) > 0:
printErrors(event.src_path, errors)
apply_rhubarb(list(spine_object.keys())[0])
if event.src_path.endswith(".ogg"):
(errors) = rhubarb_export(event.src_path)
if len(errors) > 0:
printErrors(event.src_path, errors)
if event.src_path.endswith(".lua"):
copy_script(event.src_path)
if event.src_path.endswith(".json") and "scenes" in event.src_path:
file = Path(event.src_path).name
if event.src_path in scene_files:
scene_files.remove(event.src_path)
copy_file(f"./data-src/scenes/{file}", Path("./data/scenes"))
scene = file.rstrip(".json")
if not Path(f"./data-src/scripts/{scene}.lua").exists():
if not Path("./data-src/scripts/").exists():
Path("./data-src/scripts/").mkdir(parents=True, exist_ok=True)
with Path(f"./data-src/scripts/{scene}.lua").open("w") as f:
f.write(f'print("{scene}")')
print(colored(f"Script {scene}.lua was created automatically!"), "blue")
if file in all_scenes:
all_scenes[file.rstrip(".json")].add("data-src")
else:
all_scenes[file.rstrip(".json")] = {"data-src"}
return
parsed = None
try:
with Path(event.src_path).open() as f:
data = f.read()
parsed = json.loads(data)
parsed["hash"] = ""
parsed["hash"] = hashlib.sha1(str(parsed).encode()).hexdigest()
with Path(event.src_path).open("w") as f:
scene_files.append(event.src_path)
f.write(json.dumps(parsed, indent=4))
except Exception:
print(colored(f"data-src file '{event.src_path}' has errors", "red"))
if event.src_path.endswith(".json") and "config" in event.src_path:
file = Path(event.src_path).name
copy_file(f"./data-src/config/{file}", Path("./data/config"))
if event.src_path.endswith(".schnack") and "dialog" in event.src_path:
file = Path(event.src_path).name
copy_file(f"./data-src/dialog/{file}", Path("./data/dialog"))
fill_all_dialogs(Path(f"./data-src/dialog/{file}"), file)
if "ALPACA.lua" not in event.src_path:
LuaDocsGen().render("lua.cpp")
def fill_all_dialogs(path: Path, file: str) -> None:
with Path.open(path, encoding='utf-8') as f:
dialogs = json.load(f)
for dialog in dialogs["dialogs"]:
if dialog["name"] in all_dialogs:
all_dialogs[dialog["name"]].add(file)
else:
all_dialogs[dialog["name"]] = {file}
def on_moved(event) -> None:
print(colored(
f"ok ok ok, someone moved {event.src_path} to {event.dest_path}", "green"))
@dataclass
class DocFunction:
"""Class for keeping track of an item in inventory."""
name: str = ""
docs: list[str] = field(default_factory=list)
parameters: str = ""
copy_parameters: str = ""
returns: str = ""
class LuaDocsGen:
"""The PAC's Lua handler class."""
def collect(self: LuaDocsGen, identifier: str) -> str:
return identifier
def get_name(self: LuaDocsGen, name: str) -> str:
result = name.replace('lua_state->set_function("', "")
result = result.replace('"', "")
result = result.replace(",", "")
return result.strip()
def get_parameters(self: LuaDocsGen, parameters: str) -> str:
result = parameters.replace("[](", "").replace(")", "")
result = result.replace("[this](", "").replace(")", "")
result = result.replace("const ", "")
result = result.replace("std::string ", "string ")
result = result.replace("&", "")
result = result.replace("\tint ", "number ")
result = result.replace(", int ", ", number ")
result = result.replace("float ", "number ")
result = result.replace("bool ", "boolean ")
result = result.replace("sol::function ", "function ")
result = result.replace("std::optional<sol::function> ", "function? ")
return result.strip()
def get_copy_parameters(self: LuaDocsGen, parameters: str) -> str:
result = self.get_parameters(parameters)
result = result.replace("string ", "")
result = result.replace("number ", "")
result = result.replace("function ", "")
result = result.replace("function? ", "")
result = result.replace("boolean ", "")
result = result.replace("LuaSpineObject ", "")
result = result.replace("LuaSpineAnimation ", "")
result = result.replace("LuaSpineSkin ", "")
result = result.replace("LuaSpinePoint ", "")
result = result.replace("LuaDialog ", "")
result = result.replace("LuaScene ", "")
result = result.replace("LuaAudio ", "")
result = result.replace("LuaLanguage ", "")
return result.strip()
def get_docs(self: LuaDocsGen, code: list[str], index: int) -> list[str]:
result = []
index -= 1
while "///" in code[index]:
if "returns:" in code[index]:
index -= 1
continue
result.append(code[index].replace("///", "").strip())
index -= 1
if result == []:
return ["Cool Documentation"]
result.reverse()
return result
def get_returns(self: LuaDocsGen, code: list[str], index: int) -> str:
result = ""
index -= 1
while "///" in code[index]:
if "return" in code[index]:
result += code[index].replace("///", "").strip()
index -= 1
if result == "":
return "void"
return result.strip()
def render(self: LuaDocsGen, data: str) -> str:
template = ""
result = []
code = None
code_file = Path("subprojects/ALPACA/src/" + data).absolute()
if code_file.exists():
with code_file.open() as f:
code = f.readlines()
if code is None:
code = requests.get("https://raw.githubusercontent.com/pinguin999/ALPACA/main/src/lua.cpp", timeout=30).text
code = code.split("\n")
for i, line in enumerate(code):
if "set_function" in line:
doc_obj = DocFunction()
doc_obj.name = self.get_name(code[i])
doc_obj.docs = self.get_docs(code, i)
doc_obj.parameters = self.get_parameters(code[i + 1])
doc_obj.copy_parameters = self.get_copy_parameters(code[i + 1])
doc_obj.returns = self.get_returns(code, i)
result.append(doc_obj)
alpaca_lua = Path("data-src/scripts/ALPACA.lua")
if not alpaca_lua.exists():
alpaca_lua.touch(exist_ok=True)
with alpaca_lua.open("w") as output:
output.write("") # Clear file
def write_alias(alias: str, entries: dict[str, set[str]]) -> None:
with alpaca_lua.open("+a") as output:
output.write(f"\n\n---@alias {alias}")
for spine_object in entries.items():
output.write(f"""\n---| '"{spine_object[0]}"' # Found in {spine_object[1]}""")
write_alias("LuaSpineObject", spine_objects)
write_alias("LuaSpineAnimation", spine_animations)
write_alias("LuaSpineSkin", spine_skins)
write_alias("LuaSpinePoint", spine_points)
write_alias("LuaDialog", all_dialogs)
write_alias("LuaScene", all_scenes)
write_alias("LuaAudio", all_audio)
write_alias("LuaLanguage", all_language)
with Path("data-src/scripts/ALPACA.lua").open("+a") as output:
for func in result:
docs = f"--- {func.docs[0]}"
for doc in func.docs[1:]:
docs += f"\n-- {doc}"
parameters = func.parameters.split(",")
for parameter in parameters:
parameter_striped = parameter.strip()
if parameter_striped == "":
continue
parameter_striped = parameter_striped.split(" ")
if parameter_striped[0] == "function?":
parameter_striped[0] = "function"
parameter_striped[1] = parameter_striped[1] + "?"
docs += f"\n---@param {parameter_striped[1]} {parameter_striped[0]}"
output.write(f"""
{docs}
function {func.name}({func.copy_parameters})
end
""")
return template
if __name__ == "__main__":
freeze_support()
print(colored("Start convert", "green"))
scripts_recopy(["./data-src/scripts/"])
copy_folder("./data-src/config", "./data/config")
copy_folder("./data-src/fonts", "./data/fonts")
copy_folder("./data-src/scenes", "./data/scenes")
copy_folder("./data-src/audio", "./data/audio")
copy_folder("./data-src/icons", "./data/icons")
copy_folder("./data-src/dialog", "./data/dialog")
spine_reexport(["./data-src"])
rehash_scenes("./data-src/scenes")
rhubarb_reexport()
apply_rhubarb()
LuaDocsGen().render("lua.cpp")
print(colored("Convert sucess", "green"))
patterns_src = ["*.spine", "*.lua", "*.json", "*.schnack", "*.ogg"]
ignore_patterns = None
ignore_directories = False
case_sensitive = True
go_recursively = True
data_src_event_handler = PatternMatchingEventHandler(
patterns_src, ignore_patterns, ignore_directories, case_sensitive)
data_src_event_handler.on_created = on_created
data_src_event_handler.on_deleted = on_deleted
data_src_event_handler.on_modified = on_data_src_modified
data_src_event_handler.on_moved = on_moved
data_src_path = "./data-src/"
data_src_observer = Observer()
data_src_observer.schedule(
data_src_event_handler, data_src_path, recursive=go_recursively)
data_src_observer.start()
print(colored("Observer Started", "green"))
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
data_src_observer.stop()
data_src_observer.join()