Skip to content

Commit 766514c

Browse files
refactor: the decode method is split into several small functions, some logging info changed
renaming: the term cutting is replaced with rendering objects
1 parent 1ae7899 commit 766514c

File tree

15 files changed

+172
-183
lines changed

15 files changed

+172
-183
lines changed

.flake8

Lines changed: 0 additions & 6 deletions
This file was deleted.

.pre-commit-config.yaml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ repos:
1313
hooks:
1414
- id: black
1515
language_version: python3.10
16-
- repo: https://github.com/PyCQA/flake8
17-
rev: 6.0.0
16+
- repo: https://github.com/charliermarsh/ruff-pre-commit
17+
rev: 'v0.0.261'
1818
hooks:
19-
- id: flake8
19+
- id: ruff
20+
args: [--fix, --exit-non-zero-on-fix]

system/languages/en-EU.json

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,11 @@
4848
"clean_dirs_description": "Clear In and Out dirs",
4949

5050
"not_latest": "Not the latest version installed",
51-
"collecting_inf": "Collecting information...",
51+
"collecting_inf": "File: %s. Collecting information...",
5252
"about_sc": "About texture. Filename: %s (%d), Pixel type: %d, Size: %sx%s",
5353
"decompression_error": "Error while decompressing! Trying to decode as is...",
5454
"skip_not_installed": "%s isn't installed! Reinitialize",
55-
"detected_comp": "Detected %s compression!",
55+
"detected_comp": "%s compression detected",
5656
"unk_type": "Unknown pixel type: %s",
5757
"crt_pic": "Creating picture...",
5858
"join_pic": "Joining picture...",
@@ -73,7 +73,6 @@
7373
"cut_sprites_process": "Cutting sprites... (%d/%d)",
7474
"place_sprites_process": "Placing sprites... (%d/%d)",
7575
"not_implemented": "This feature will be added in future updates.\nYou can follow XCoder updates here: github.com/Vorono4ka/XCoder",
76-
"dec_sc": "Decoding .sc file...",
7776
"error": "ERROR! (%s.%s: %s)",
7877
"e1sc1": "Overwrite SC sprites",
7978
"cgl": "Changelog:\n%s",
@@ -88,4 +87,4 @@
8887
"disabled": "Disabled",
8988

9089
"install_to_unlock": "Install '%s' to unlock more functions!"
91-
}
90+
}

system/languages/ru-RU.json

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,11 @@
4848
"clean_dirs_description": "Очистить In и Out папки",
4949

5050
"not_latest": "Установлена не последняя версия",
51-
"collecting_inf": "Сбор информации...",
51+
"collecting_inf": "Файл: %s. Сбор информации...",
5252
"about_sc": "О текстуре. Файл: %s (%d), Тип пикселя: %d, Размеры: %dx%d",
5353
"decompression_error": "Ошибка распаковки! Проведите повторную инициализацию!",
5454
"skip_not_installed": "%s не установлен! Пропускаем...",
55-
"detected_comp": "Обнаружено %s сжатие!",
55+
"detected_comp": "Обнаружено сжатие: %s",
5656
"unk_type": "Неизвестный подтип: %s",
5757
"crt_pic": "Создаём картинку...",
5858
"join_pic": "Соединяем картинку...",
@@ -73,7 +73,6 @@
7373
"cut_sprites_process": "Вырезаем спрайты... (%d/%d)",
7474
"place_sprites_process": "Ставим спрайты на место... (%d/%d)",
7575
"not_implemented": "Данная возможность будет добавлена в будущих обновлениях.\nЗа обновлениями XCoder вы можете следить здесь: github.com/Vorono4ka/XCoder",
76-
"dec_sc": "Декодируем SC...",
7776
"error": "ОШИБКА! (%s.%s: %s)",
7877
"e1sc1": "Перезапись спрайтов",
7978
"cgl": "Список изменений: \n%s",
@@ -88,4 +87,4 @@
8887
"disabled": "Выключено",
8988

9089
"install_to_unlock": "Установите '%s' чтобы открыть больше функций!"
91-
}
90+
}

system/languages/ua-UA.json

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,11 @@
4848
"clean_dirs_description": "Очистити папки і файли в них",
4949

5050
"not_latest": "Встановлена не остання версія",
51-
"collecting_inf": "Збираємо інформацію...",
51+
"collecting_inf": "Файл: %s. Збираємо інформацію...",
5252
"about_sc": "Про текстуру. Назва файлу: %s (%d), Тип пікселів: %d, Величина: %sx%s",
5353
"decompression_error": "Помилка при розпакуванні! Намагаємся розпакувати як є...",
5454
"skip_not_installed": "%s не встановлений, повторіть налаштування",
55-
"detected_comp": "Виявлено %s компресію!",
55+
"detected_comp": "Виявлено компресію: %s",
5656
"unk_type": "Невідомий вид пікселів: %s",
5757
"crt_pic": "Створюємо зоображеня...",
5858
"join_pic": "З'єднуємо зоображення...",
@@ -73,7 +73,6 @@
7373
"cut_sprites_process": "Обрізаємо спрайти... (%d/%d)",
7474
"place_sprites_process": "Вставляємо спрайти... (%d/%d)",
7575
"not_implemented": "Ця функція буде додана у наступних оновленнях.\nТи можеш сладкувати за оновленнями тут: github.com/Vorono4ka/XCoder",
76-
"dec_sc": "Розпаковуємо .sc файл...",
7776
"error": "Помилка! (%s.%s: %s)",
7877
"e1sc1": "Переписати SC спрайти",
7978
"cgl": "Список змін:\n%s",
@@ -88,4 +87,4 @@
8887
"disabled": "Виключено",
8988

9089
"install_to_unlock": "Встанови '%s' щоб розблокувати більше функції!"
91-
}
90+
}

system/lib/__init__.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
import sys
22
import time
33

4+
from loguru import logger
5+
46
from system import clear
57
from system.lib.config import config
68
from system.lib.console import Console
79
from system.lib.features.directories import clear_directories
810
from system.lib.features.initialization import initialize
9-
from system.lib.features.update.check import check_update, check_for_outdated, get_tags
10-
from system.lib.menu import menu, Menu
11+
from system.lib.features.update.check import check_for_outdated, check_update, get_tags
12+
from system.lib.menu import Menu, menu
1113
from system.localization import locale
1214

13-
from loguru import logger
14-
1515
logger.remove()
1616
logger.add(
1717
"./logs/info/{time:YYYY-MM-DD}.log",
@@ -73,14 +73,20 @@ def refill_menu():
7373

7474
del PIL
7575

76-
from system.lib.features.sc.decode import sc_decode
76+
from system.lib.features.sc.assembly_encode import (
77+
collect_objects_and_encode,
78+
)
79+
from system.lib.features.sc.decode import (
80+
decode_and_render_objects,
81+
decode_textures_only,
82+
)
7783
from system.lib.features.sc.encode import sc_encode
78-
from system.lib.features.sc.decode_and_cut import decode_and_cut
79-
from system.lib.features.sc.assembly_encode import sc1_encode
8084

8185
sc_category = Menu.Category(0, locale.sc_label)
8286
sc_category.add(
83-
Menu.Item(locale.decode_sc, locale.decode_sc_description, sc_decode)
87+
Menu.Item(
88+
locale.decode_sc, locale.decode_sc_description, decode_textures_only
89+
)
8490
)
8591
sc_category.add(
8692
Menu.Item(locale.encode_sc, locale.encode_sc_description, sc_encode)
@@ -89,21 +95,21 @@ def refill_menu():
8995
Menu.Item(
9096
locale.decode_by_parts,
9197
locale.decode_by_parts_description,
92-
decode_and_cut,
98+
decode_and_render_objects,
9399
)
94100
)
95101
sc_category.add(
96102
Menu.Item(
97103
locale.encode_by_parts,
98104
locale.encode_by_parts_description,
99-
sc1_encode,
105+
collect_objects_and_encode,
100106
)
101107
)
102108
sc_category.add(
103109
Menu.Item(
104110
locale.overwrite_by_parts,
105111
locale.overwrite_by_parts_description,
106-
lambda: sc1_encode(True),
112+
lambda: collect_objects_and_encode(True),
107113
)
108114
)
109115
menu.add_category(sc_category)

system/lib/features/cut_sprites.py

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,39 @@
11
import os
2+
from pathlib import Path
23

34
from system.lib.console import Console
45
from system.lib.swf import SupercellSWF
56
from system.localization import locale
67

78

8-
def cut_sprites(swf: SupercellSWF, export_folder: str):
9-
os.makedirs(f"{export_folder}/overwrite", exist_ok=True)
10-
os.makedirs(f"{export_folder}/shapes", exist_ok=True)
11-
os.makedirs(f"{export_folder}/movie_clips", exist_ok=True)
9+
def render_objects(swf: SupercellSWF, output_folder: Path):
10+
os.makedirs(output_folder / "overwrite", exist_ok=True)
11+
os.makedirs(output_folder / "shapes", exist_ok=True)
12+
os.makedirs(output_folder / "movie_clips", exist_ok=True)
1213

1314
# TODO: Too slow, fix it
14-
movie_clips_skipped = 0
15-
movie_clip_count = len(swf.movie_clips)
16-
for movie_clip_index in range(movie_clip_count):
17-
movie_clip = swf.movie_clips[movie_clip_index]
18-
19-
rendered_movie_clip = movie_clip.render(swf)
20-
if sum(rendered_movie_clip.size) >= 2:
21-
clip_name = movie_clip.export_name or movie_clip.id
22-
rendered_movie_clip.save(f"{export_folder}/movie_clips/{clip_name}.png")
23-
else:
24-
# For debug:
25-
# logger.warning(f'MovieClip {movie_clip.id} cannot be rendered.')
26-
movie_clips_skipped += 1
27-
28-
Console.progress_bar(
29-
"Rendering movie clips (%d/%d). Skipped count: %d"
30-
% (movie_clip_index + 1, movie_clip_count, movie_clips_skipped),
31-
movie_clip_index,
32-
movie_clip_count,
33-
)
15+
# movie_clips_skipped = 0
16+
# movie_clip_count = len(swf.movie_clips)
17+
# for movie_clip_index in range(movie_clip_count):
18+
# movie_clip = swf.movie_clips[movie_clip_index]
19+
#
20+
# rendered_movie_clip = movie_clip.render(swf)
21+
# if sum(rendered_movie_clip.size) >= 2:
22+
# clip_name = movie_clip.export_name or movie_clip.id
23+
# rendered_movie_clip.save(f"{export_folder}/movie_clips/{clip_name}.png")
24+
# else:
25+
# # For debug:
26+
# # logger.warning(f'MovieClip {movie_clip.id} cannot be rendered.')
27+
# movie_clips_skipped += 1
28+
#
29+
# Console.progress_bar(
30+
# "Rendering movie clips (%d/%d). Skipped count: %d"
31+
# % (movie_clip_index + 1, movie_clip_count, movie_clips_skipped),
32+
# movie_clip_index,
33+
# movie_clip_count,
34+
# )
35+
36+
print()
3437

3538
shapes_count = len(swf.shapes)
3639
swf.xcod_writer.write_uint16(shapes_count)
@@ -45,14 +48,14 @@ def cut_sprites(swf: SupercellSWF, export_folder: str):
4548
)
4649

4750
rendered_shape = shape.render()
48-
rendered_shape.save(f"{export_folder}/shapes/{shape.id}.png")
51+
rendered_shape.save(f"{output_folder}/shapes/{shape.id}.png")
4952

5053
regions_count = len(shape.regions)
5154
for region_index in range(regions_count):
5255
region = shape.regions[region_index]
5356

5457
rendered_region = region.render(use_original_size=True)
55-
rendered_region.save(f"{export_folder}/shape_{shape.id}_{region_index}.png")
58+
rendered_region.save(f"{output_folder}/shape_{shape.id}_{region_index}.png")
5659

5760
for shape_index in range(shapes_count):
5861
shape = swf.shapes[shape_index]

system/lib/features/files.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
import struct
2-
31
from loguru import logger
4-
from sc_compression import decompress, compress
2+
from sc_compression import compress, decompress
53
from sc_compression.signatures import Signatures
64

75
from system.localization import locale
@@ -13,7 +11,8 @@ def write_sc(output_filename: str, buffer: bytes, use_lzham: bool):
1311

1412
if use_lzham:
1513
logger.info(locale.compressing_with % "LZHAM")
16-
file_out.write(struct.pack("<4sBI", b"SCLZ", 18, len(buffer)))
14+
# Why is this here? It's included in the compression module
15+
# file_out.write(struct.pack("<4sBI", b"SCLZ", 18, len(buffer)))
1716
compressed = compress(buffer, Signatures.SCLZ)
1817

1918
file_out.write(compressed)
@@ -24,11 +23,9 @@ def write_sc(output_filename: str, buffer: bytes, use_lzham: bool):
2423
logger.info(locale.compression_done)
2524

2625

27-
def open_sc(input_filename: str):
28-
decompressed_data = None
26+
def open_sc(input_filename: str) -> tuple[bytes, bool]:
2927
use_lzham = False
3028

31-
logger.info(locale.collecting_inf)
3229
with open(input_filename, "rb") as f:
3330
file_data = f.read()
3431
f.close()
@@ -37,9 +34,10 @@ def open_sc(input_filename: str):
3734
if b"START" in file_data:
3835
file_data = file_data[: file_data.index(b"START")]
3936
decompressed_data, signature = decompress(file_data)
40-
#
41-
# logger.info(locale.detected_comp % signature.upper())
42-
#
37+
38+
if signature.name != Signatures.NONE:
39+
logger.info(locale.detected_comp % signature.name.upper())
40+
4341
if signature == Signatures.SCLZ:
4442
use_lzham = True
4543
except TypeError:

system/lib/features/sc/__init__.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,11 @@ def compile_sc(
3131
return logger.info(locale.dir_empty % _dir.split("/")[-2])
3232
files = [Image.open(f"{_dir}{i}") for i in files]
3333

34-
logger.info(locale.collecting_inf)
3534
sc = Writer()
3635

37-
use_lzham = file_info.use_lzham
38-
3936
for picture_index in range(len(files)):
4037
sheet_info = file_info.sheets[picture_index]
4138
img = files[picture_index]
42-
print()
4339

4440
file_type = sheet_info.file_type
4541
pixel_type = sheet_info.pixel_type
@@ -67,8 +63,8 @@ def compile_sc(
6763
split_image(img)
6864

6965
save_texture(sc, img, pixel_type)
66+
print()
7067

7168
sc.write(bytes(5))
72-
print()
7369

74-
write_sc(f"{output_folder}/{name}.sc", sc.getvalue(), use_lzham)
70+
write_sc(f"{output_folder}/{name}.sc", sc.getvalue(), file_info.use_lzham)

system/lib/features/sc/assembly_encode.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from system.localization import locale
88

99

10-
def sc1_encode(overwrite: bool = False):
10+
def collect_objects_and_encode(overwrite: bool = False):
1111
folder = "./SC/In-Sprites/"
1212
output_folder = "./SC/Out-Compressed/"
1313
files = os.listdir(folder)
@@ -18,11 +18,10 @@ def sc1_encode(overwrite: bool = False):
1818
logger.error(locale.not_found % xcod)
1919
else:
2020
try:
21-
logger.info(locale.dec_sc)
21+
logger.info(locale.collecting_inf % file)
2222
sheets, file_info = place_sprites(
2323
f"{folder}{file}/{xcod}", f"{folder}{file}", overwrite
2424
)
25-
logger.info(locale.dec_sc)
2625
compile_sc(f"{folder}{file}/", file_info, sheets, output_folder)
2726
except Exception as exception:
2827
logger.exception(

0 commit comments

Comments
 (0)