incoming update

This commit is contained in:
Anthony Samms
2025-12-19 19:43:16 -05:00
parent 252c3c3e0b
commit 986ab1baaf
4 changed files with 352 additions and 52 deletions

View File

@@ -4,6 +4,8 @@ import logging
from pathlib import Path
import random
from typing import Optional, Union
from raylib import SHADER_UNIFORM_FLOAT, SHADER_UNIFORM_VEC3
from libs.audio import audio
from libs.animation import Animation, MoveAnimation
from libs.global_data import Crown, Difficulty
@@ -18,6 +20,45 @@ BOX_CENTER = 594 * tex.screen_scale
logger = logging.getLogger(__name__)
def rgb_to_hue(r, g, b):
rf = r / 255.0
gf = g / 255.0
bf = b / 255.0
max_val = max(rf, gf, bf)
min_val = min(rf, gf, bf)
delta = max_val - min_val
if delta == 0:
return 0 # Gray/white, no hue
if max_val == rf:
hue = 60.0 * (((gf - bf) / delta) % 6)
elif max_val == gf:
hue = 60.0 * ((bf - rf) / delta + 2.0)
else:
hue = 60.0 * ((rf - gf) / delta + 4.0)
if hue < 0:
hue += 360.0
return hue
def calculate_hue_shift(source_rgb, target_rgb):
source_hue = rgb_to_hue(*source_rgb)
target_hue = rgb_to_hue(*target_rgb)
shift = (target_hue - source_hue) / 360.0
# Normalize to 0.0-1.0 range
while shift < 0:
shift += 1.0
while shift >= 1.0:
shift -= 1.0
return shift
class BaseBox():
OUTLINE_MAP = {
1: ray.Color(0, 77, 104, 255),
@@ -69,6 +110,17 @@ class BaseBox():
def load_text(self):
self.name = OutlinedText(self.text_name, tex.skin_config["song_box_name"].font_size, ray.WHITE, outline_thickness=5, vertical=True)
'''
self.shader = ray.load_shader('', 'shader/colortransform.fs')
source_rgb = (142, 212, 30)
target_rgb = (209, 162, 19)
source_color = ray.ffi.new('float[3]', [source_rgb[0]/255.0, source_rgb[1]/255.0, source_rgb[2]/255.0])
target_color = ray.ffi.new('float[3]', [target_rgb[0]/255.0, target_rgb[1]/255.0, target_rgb[2]/255.0])
source_loc = ray.get_shader_location(self.shader, 'sourceColor')
target_loc = ray.get_shader_location(self.shader, 'targetColor')
ray.set_shader_value(self.shader, source_loc, source_color, SHADER_UNIFORM_VEC3)
ray.set_shader_value(self.shader, target_loc, target_color, SHADER_UNIFORM_VEC3)
'''
def move_box(self, current_time: float):
if self.position != self.target_position and self.move is None:
@@ -96,10 +148,12 @@ class BaseBox():
self.open_fade.update(current_time)
def _draw_closed(self, x: float, y: float, outer_fade_override: float):
#ray.begin_shader_mode(self.shader)
tex.draw_texture('box', 'folder_texture_left', frame=self.texture_index, x=x, fade=outer_fade_override)
offset = 1 * tex.screen_scale if self.texture_index == 3 or self.texture_index >= 9 and self.texture_index not in {10,11,12} else 0
tex.draw_texture('box', 'folder_texture', frame=self.texture_index, x=x, x2=tex.skin_config["song_box_bg"].width, y=offset, fade=outer_fade_override)
tex.draw_texture('box', 'folder_texture_right', frame=self.texture_index, x=x, fade=outer_fade_override)
#ray.end_shader_mode()
if self.texture_index == BaseBox.DEFAULT_INDEX:
tex.draw_texture('box', 'genre_overlay', x=x, y=y, fade=outer_fade_override)
elif self.texture_index == BaseBox.DIFFICULTY_SORT_INDEX:
@@ -938,20 +992,27 @@ class DanCourse(FileSystemItem):
self.charts: list[tuple[TJAParser, int, int, int]] = []
for chart in data["charts"]:
hash = chart["hash"]
#chart_title = chart["title"]
#chart_subtitle = chart["subtitle"]
chart_title = chart["title"]
chart_subtitle = chart["subtitle"]
difficulty = chart["difficulty"]
if hash in global_data.song_hashes:
path = Path(global_data.song_hashes[hash][0]["file_path"])
if (path.parent.parent / "box.def").exists():
_, genre_index, _ = parse_box_def(path.parent.parent)
else:
genre_index = 9
tja = TJAParser(path)
self.charts.append((tja, genre_index, difficulty, tja.metadata.course_data[difficulty].level))
else:
pass
#do something with song_title, song_subtitle
for key, value in global_data.song_hashes.items():
for i in range(len(value)):
song = value[i]
if (song["title"]["en"].strip() == chart_title and
song["subtitle"]["en"].strip() == chart_subtitle.removeprefix('--') and
Path(song["file_path"]).exists()):
hash_val = key
path = Path(global_data.song_hashes[hash_val][i]["file_path"])
break
if (path.parent.parent / "box.def").exists():
_, genre_index, _ = parse_box_def(path.parent.parent)
else:
genre_index = 9
tja = TJAParser(path)
self.charts.append((tja, genre_index, difficulty, tja.metadata.course_data[difficulty].level))
self.exams = []
for exam in data["exams"]:
self.exams.append(Exam(exam["type"], exam["value"][0], exam["value"][1], exam["range"]))
@@ -1037,7 +1098,7 @@ class FileNavigator:
self._generate_objects_recursive(root_path)
if self.favorite_folder is not None:
if self.favorite_folder is not None and self.favorite_folder.path.exists():
song_list = self._read_song_list(self.favorite_folder.path)
for song_obj in song_list:
if str(song_obj) in self.all_song_files:
@@ -1121,16 +1182,8 @@ class FileNavigator:
for tja_path in sorted(tja_files):
song_key = str(tja_path)
if song_key not in self.all_song_files and tja_path.name == "dan.json":
valid_dan = True
with open(tja_path, 'r', encoding='utf-8') as file:
dan_data = json.load(file)
for chart in dan_data["charts"]:
hash = chart["hash"]
if hash not in global_data.song_hashes:
valid_dan = False
if valid_dan:
song_obj = DanCourse(tja_path, tja_path.name)
self.all_song_files[song_key] = song_obj
song_obj = DanCourse(tja_path, tja_path.name)
self.all_song_files[song_key] = song_obj
elif song_key not in self.all_song_files and tja_path in global_data.song_paths:
song_obj = SongFile(tja_path, tja_path.name, texture_index)
song_obj.box.get_scores()

View File

@@ -62,14 +62,23 @@ class TextureWrapper:
self.animations: dict[int, BaseAnimation] = dict()
self.skin_config: dict[str, SkinInfo] = dict()
self.graphics_path = Path(get_config()['paths']['graphics_path'])
if (self.graphics_path / "skin_config.json").exists():
data = json.loads((self.graphics_path / "skin_config.json").read_text())
self.skin_config: dict[str, SkinInfo] = {
k: SkinInfo(v.get('x', 0), v.get('y', 0), v.get('font_size', 0), v.get('width', 0), v.get('height', 0)) for k, v in data.items()
}
self.parent_graphics_path = Path(get_config()['paths']['graphics_path'])
if not (self.graphics_path / "skin_config.json").exists():
raise Exception("skin is missing a skin_config.json")
data = json.loads((self.graphics_path / "skin_config.json").read_text())
self.skin_config: dict[str, SkinInfo] = {
k: SkinInfo(v.get('x', 0), v.get('y', 0), v.get('font_size', 0), v.get('width', 0), v.get('height', 0)) for k, v in data.items()
}
self.screen_width = int(self.skin_config["screen"].width)
self.screen_height = int(self.skin_config["screen"].height)
self.screen_scale = self.screen_width / 1280
if "parent" in data["screen"]:
parent = data["screen"]["parent"]
self.parent_graphics_path = Path("Graphics") / parent
parent_data = json.loads((self.parent_graphics_path / "skin_config.json").read_text())
for k, v in parent_data.items():
self.skin_config[k] = SkinInfo(v.get('x', 0) * self.screen_scale, v.get('y', 0) * self.screen_scale, v.get('font_size', 0) * self.screen_scale, v.get('width', 0) * self.screen_scale, v.get('height', 0) * self.screen_scale)
def unload_textures(self):
"""Unload all textures and animations."""
@@ -133,26 +142,62 @@ class TextureWrapper:
tex_object.controllable = [tex_mapping.get("controllable", False)]
def load_animations(self, screen_name: str):
"""Load animations for a screen."""
"""Load animations for a screen, falling back to parent if not found."""
screen_path = self.graphics_path / screen_name
parent_screen_path = self.parent_graphics_path / screen_name
if (screen_path / 'animation.json').exists():
with open(screen_path / 'animation.json') as json_file:
self.animations = parse_animations(json.loads(json_file.read()))
logger.info(f"Animations loaded for screen: {screen_name}")
elif self.parent_graphics_path != self.graphics_path and (parent_screen_path / 'animation.json').exists():
with open(parent_screen_path / 'animation.json') as json_file:
anim_json = json.loads(json_file.read())
for anim in anim_json:
if "total_distance" in anim and not isinstance(anim["total_distance"], dict):
anim["total_distance"] = anim["total_distance"] * self.screen_scale
self.animations = parse_animations(anim_json)
logger.info(f"Animations loaded for screen: {screen_name} (from parent)")
def load_zip(self, screen_name: str, subset: str):
"""Load textures from a zip file."""
zip = (self.graphics_path / screen_name / subset).with_suffix('.zip')
"""Load textures from child zip, using parent texture.json if child doesn't have one."""
zip_path = (self.graphics_path / screen_name / subset).with_suffix('.zip')
parent_zip_path = (self.parent_graphics_path / screen_name / subset).with_suffix('.zip')
if screen_name in self.textures and subset in self.textures[screen_name]:
return
try:
with zipfile.ZipFile(zip, 'r') as zip_ref:
if 'texture.json' not in zip_ref.namelist():
raise Exception(f"texture.json file missing from {zip}")
with zip_ref.open('texture.json') as json_file:
tex_mapping_data: dict[str, dict] = json.loads(json_file.read().decode('utf-8'))
self.textures[zip.stem] = dict()
# Child zip must exist
if not zip_path.exists():
logger.warning(f"Zip file not found: {subset} for screen {screen_name}")
return
try:
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
# Try to get texture.json from child first, then parent
tex_mapping_data = None
texture_json_source = "child"
if 'texture.json' in zip_ref.namelist():
with zip_ref.open('texture.json') as json_file:
tex_mapping_data = json.loads(json_file.read().decode('utf-8'))
elif self.parent_graphics_path != self.graphics_path and parent_zip_path.exists():
# Fall back to parent's texture.json
with zipfile.ZipFile(parent_zip_path, 'r') as parent_zip_ref:
if 'texture.json' in parent_zip_ref.namelist():
with parent_zip_ref.open('texture.json') as json_file:
tex_mapping_data = json.loads(json_file.read().decode('utf-8'))
for tex_map in tex_mapping_data:
for key in tex_mapping_data[tex_map]:
if key in ["x", "y", "x2", "y2"]:
tex_mapping_data[tex_map][key] = tex_mapping_data[tex_map][key] * self.screen_scale
texture_json_source = "parent"
else:
raise Exception(f"texture.json file missing from both {zip_path} and {parent_zip_path}")
else:
raise Exception(f"texture.json file missing from {zip_path}")
self.textures[zip_path.stem] = dict()
encoding = sys.getfilesystemencoding()
for tex_name in tex_mapping_data:
@@ -166,11 +211,11 @@ class TextureWrapper:
extracted_path = Path(temp_dir) / tex_name
if extracted_path.is_dir():
frames = [ray.LoadTexture(str(frame).encode(encoding)) for frame in sorted(extracted_path.iterdir(),
key=lambda x: int(x.stem)) if frame.is_file()]
key=lambda x: int(x.stem)) if frame.is_file()]
else:
frames = [ray.LoadTexture(str(extracted_path).encode(encoding))]
self.textures[zip.stem][tex_name] = Texture(tex_name, frames, tex_mapping)
self._read_tex_obj_data(tex_mapping, self.textures[zip.stem][tex_name])
self.textures[zip_path.stem][tex_name] = Texture(tex_name, frames, tex_mapping)
self._read_tex_obj_data(tex_mapping, self.textures[zip_path.stem][tex_name])
elif f"{tex_name}.png" in zip_ref.namelist():
tex_mapping = tex_mapping_data[tex_name]
@@ -181,30 +226,34 @@ class TextureWrapper:
try:
tex = ray.LoadTexture(temp_path.encode(encoding))
self.textures[zip.stem][tex_name] = Texture(tex_name, tex, tex_mapping)
self._read_tex_obj_data(tex_mapping, self.textures[zip.stem][tex_name])
self.textures[zip_path.stem][tex_name] = Texture(tex_name, tex, tex_mapping)
self._read_tex_obj_data(tex_mapping, self.textures[zip_path.stem][tex_name])
finally:
os.unlink(temp_path)
else:
logger.error(f"Texture {tex_name} was not found in {zip}")
logger.info(f"Textures loaded from zip: {zip}")
logger.error(f"Texture {tex_name} was not found in {zip_path}")
json_note = f" (texture.json from {texture_json_source})" if texture_json_source == "parent" else ""
logger.info(f"Textures loaded from zip: {zip_path}{json_note}")
except Exception as e:
logger.error(f"Failed to load textures from zip {zip}: {e}")
logger.error(f"Failed to load textures from zip {zip_path}: {e}")
def load_screen_textures(self, screen_name: str) -> None:
"""Load textures for a screen."""
screen_path = self.graphics_path / screen_name
if not screen_path.exists():
logger.warning(f"Textures for Screen {screen_name} do not exist")
return
if (screen_path / 'animation.json').exists():
with open(screen_path / 'animation.json') as json_file:
self.animations = parse_animations(json.loads(json_file.read()))
logger.info(f"Animations loaded for screen: {screen_name}")
for zip in screen_path.iterdir():
if zip.is_dir() or zip.suffix != ".zip":
continue
self.load_zip(screen_name, zip.name)
# Load animations
self.load_animations(screen_name)
# Load zip files from child screen path only
for zip_file in screen_path.iterdir():
if zip_file.is_file() and zip_file.suffix == ".zip":
self.load_zip(screen_name, zip_file.stem)
logger.info(f"Screen textures loaded for: {screen_name}")
def control(self, tex_object: Texture, index: int = 0):