Skip to content

Commit

Permalink
Merge pull request #21 from xcoder-tool/pvr-tex-tool-refactoring
Browse files Browse the repository at this point in the history
refactor(pvr tex tool): first search for cli in the system
  • Loading branch information
danila-schelkov authored Aug 12, 2024
2 parents ab416fe + fa3a5ed commit 8967305
Show file tree
Hide file tree
Showing 10 changed files with 46 additions and 25 deletions.
2 changes: 1 addition & 1 deletion system/languages/en-EU.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
"not_found": "File '%s' not found!",
"cut_sprites_process": "Cutting sprites... (%d/%d)",
"place_sprites_process": "Placing sprites... (%d/%d)",
"not_implemented": "This feature will be added in future updates.\nYou can follow XCoder updates here: github.com/Vorono4ka/XCoder",
"not_implemented": "This feature will be added in future updates.\nYou can follow XCoder updates here: https://github.com/Vorono4ka/XCoder",
"error": "ERROR! (%s.%s: %s)",
"e1sc1": "Overwrite SC sprites",
"cgl": "Changelog:\n%s",
Expand Down
2 changes: 1 addition & 1 deletion system/languages/ru-RU.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
"not_found": "Файл '%s' не найден!",
"cut_sprites_process": "Вырезаем спрайты... (%d/%d)",
"place_sprites_process": "Ставим спрайты на место... (%d/%d)",
"not_implemented": "Данная возможность будет добавлена в будущих обновлениях.\nЗа обновлениями XCoder вы можете следить здесь: github.com/Vorono4ka/XCoder",
"not_implemented": "Данная возможность будет добавлена в будущих обновлениях.\nЗа обновлениями XCoder вы можете следить здесь: https://github.com/Vorono4ka/XCoder",
"error": "ОШИБКА! (%s.%s: %s)",
"e1sc1": "Перезапись спрайтов",
"cgl": "Список изменений: \n%s",
Expand Down
2 changes: 1 addition & 1 deletion system/languages/ua-UA.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
"not_found": "Файл '%s' не знайдено!",
"cut_sprites_process": "Обрізаємо спрайти... (%d/%d)",
"place_sprites_process": "Вставляємо спрайти... (%d/%d)",
"not_implemented": "Ця функція буде додана у наступних оновленнях.\nТи можеш сладкувати за оновленнями тут: github.com/Vorono4ka/XCoder",
"not_implemented": "Ця функція буде додана у наступних оновленнях.\nТи можеш сладкувати за оновленнями тут: https://github.com/Vorono4ka/XCoder",
"error": "Помилка! (%s.%s: %s)",
"e1sc1": "Переписати SC спрайти",
"cgl": "Список змін:\n%s",
Expand Down
5 changes: 5 additions & 0 deletions system/lib/features/ktx.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import os
from pathlib import Path

from loguru import logger

from system.lib.pvr_tex_tool import convert_ktx_to_png, convert_png_to_ktx
from system.localization import locale

IN_PNG_PATH = Path("./TEX/In-PNG")
IN_KTX_PATH = Path("./TEX/In-KTX")
Expand All @@ -21,6 +24,7 @@ def convert_png_textures_to_ktx():
if not os.path.isfile(png_filepath):
continue

logger.info(locale.collecting_inf % file)
convert_png_to_ktx(png_filepath, output_folder=output_folder)


Expand All @@ -36,4 +40,5 @@ def convert_ktx_textures_to_png():
if not os.path.isfile(ktx_filepath):
continue

logger.info(locale.collecting_inf % file)
convert_ktx_to_png(ktx_filepath, output_folder=output_folder)
4 changes: 2 additions & 2 deletions system/lib/features/place_sprites.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ def place_sprites(
f'{folder}{"/overwrite" if overwrite else ""}/{filename}'
).convert("RGBA")
if region_info.is_mirrored:
tmp_region = tmp_region.transpose(Image.FLIP_LEFT_RIGHT)
tmp_region = tmp_region.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
tmp_region = tmp_region.rotate(region_info.rotation, expand=True)
tmp_region = tmp_region.resize((width, height), Image.ANTIALIAS)
tmp_region = tmp_region.resize((width, height), Image.Resampling.LANCZOS)

sheets[region_info.texture_id].paste(
Image.new("RGBA", (width, height)), (left, top), img_mask.crop(bbox)
Expand Down
2 changes: 1 addition & 1 deletion system/lib/features/sc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def compile_sc(

if Console.question(locale.resize_qu):
logger.info(locale.resizing)
sheet = sheet.resize(sheet_info.size, Image.ANTIALIAS)
sheet = sheet.resize(sheet_info.size, Image.Resampling.LANCZOS)

width, height = sheet.size
pixel_size = get_byte_count_by_pixel_type(pixel_type)
Expand Down
2 changes: 1 addition & 1 deletion system/lib/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def choice(self):
+ colorama.Style.RESET_ALL
).center(console_width + 12)
)
print("github.com/Vorono4ka/XCoder".center(console_width - 1))
print("https://github.com/Vorono4ka/XCoder".center(console_width - 1))
self._print_divider_line(console_width)

for category in self.categories:
Expand Down
8 changes: 5 additions & 3 deletions system/lib/objects/movie_clip.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from math import ceil
from typing import TYPE_CHECKING, List, Tuple

Expand Down Expand Up @@ -53,7 +55,7 @@ def __init__(self):
self.binds: List[int] = []
self.matrix_bank_index: int = 0

def load(self, swf: "SupercellSWF", tag: int):
def load(self, swf: SupercellSWF, tag: int):
self.id = swf.reader.read_ushort()

self.fps = swf.reader.read_char()
Expand Down Expand Up @@ -115,7 +117,7 @@ def load(self, swf: "SupercellSWF", tag: int):
else:
swf.reader.read(frame_length)

def render(self, swf: "SupercellSWF", matrix=None) -> Image.Image:
def render(self, swf: SupercellSWF, matrix=None) -> Image.Image:
if self in CACHE:
return CACHE[self].copy()

Expand Down Expand Up @@ -150,7 +152,7 @@ def render(self, swf: "SupercellSWF", matrix=None) -> Image.Image:

return image

def get_sides(self, swf: "SupercellSWF") -> Tuple[float, float, float, float]:
def get_sides(self, swf: SupercellSWF) -> Tuple[float, float, float, float]:
matrix_bank: MatrixBank = swf.get_matrix_bank(self.matrix_bank_index)

left = 0
Expand Down
10 changes: 6 additions & 4 deletions system/lib/objects/shape.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from math import atan2, ceil, degrees
from typing import TYPE_CHECKING, List, Optional, Tuple

Expand All @@ -17,7 +19,7 @@ def __init__(self):
self.id = 0
self.regions: List[Region] = []

def load(self, swf: "SupercellSWF", tag: int):
def load(self, swf: SupercellSWF, tag: int):
self.id = swf.reader.read_ushort()

swf.reader.read_ushort() # regions_count
Expand Down Expand Up @@ -101,7 +103,7 @@ def __init__(self):

self.texture: SWFTexture

def load(self, swf: "SupercellSWF", tag: int):
def load(self, swf: SupercellSWF, tag: int):
self.texture_index = swf.reader.read_uchar()

self.texture = swf.textures[self.texture_index]
Expand Down Expand Up @@ -161,10 +163,10 @@ def render(self, use_original_size: bool = False) -> Image.Image:

rendered_region = rendered_region.rotate(-self.rotation, expand=True)
if self.is_mirrored:
rendered_region = rendered_region.transpose(Image.FLIP_LEFT_RIGHT)
rendered_region = rendered_region.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
if use_original_size:
return rendered_region
return rendered_region.resize((width, height), Image.ANTIALIAS)
return rendered_region.resize((width, height), Image.Resampling.LANCZOS)

def get_image(self) -> Image.Image:
left, top, right, bottom = get_sides(self._uv_points)
Expand Down
34 changes: 23 additions & 11 deletions system/lib/pvr_tex_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,31 @@
from system import run
from system.exceptions.tool_not_found import ToolNotFoundException

TOOL_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
COLOR_SPACE = "sRGB"
KTX_FORMAT = "ETC1,UBN,lRGB"
QUALITY = "etcfast"
CLI_PATH = f"{TOOL_DIR}/system/bin/PVRTexToolCLI"
_main_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
_color_space = "sRGB"
_format = "ETC1,UBN,lRGB"
_quality = "etcfast"


# Note: a solution from
# https://stackoverflow.com/questions/11210104/check-if-a-program-exists-from-a-python-script
def can_use_pvr_tex_tool() -> bool:
def _get_executable_path(*paths: str) -> str | None:
from distutils.spawn import find_executable

executable_path = find_executable(CLI_PATH)
return executable_path is not None
for path in paths:
executable_path = find_executable(path)
if executable_path is not None:
return path

return None


_cli_name = "PVRTexToolCLI"
_cli_path = _get_executable_path(_cli_name, f"{_main_dir}/system/bin/{_cli_name}")


def can_use_pvr_tex_tool() -> bool:
return _cli_path is not None


def get_image_from_ktx_data(data: bytes) -> Image.Image:
Expand Down Expand Up @@ -52,7 +63,9 @@ def convert_ktx_to_png(filepath: Path, output_folder: Path | None = None) -> Pat
if output_folder is not None:
output_filepath = output_folder / output_filepath.name

run(f"{CLI_PATH} -noout -ics {COLOR_SPACE} -i {filepath!s} -d {output_filepath!s}")
run(
f"{_cli_path} -noout -ics {_color_space} -i {filepath!s} -d {output_filepath!s}"
)

return output_filepath

Expand All @@ -65,8 +78,7 @@ def convert_png_to_ktx(filepath: Path, output_folder: Path | None = None) -> Pat
output_filepath = output_folder / output_filepath.name

run(
f"{CLI_PATH} -f {KTX_FORMAT} -q {QUALITY} "
f"-i {filepath!s} -o {output_filepath!s}"
f"{_cli_path} -f {_format} -q {_quality} -i {filepath!s} -o {output_filepath!s}"
)

return output_filepath
Expand Down

0 comments on commit 8967305

Please sign in to comment.