commit 62e284866b3f4e472e48556d410af4e8a7a60951 Author: sthkm3 Date: Thu Oct 22 21:07:47 2026 +0800 upload diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bb4d3ed --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.venv/ +__pycache__/ +.pytest_cache/ +*.pyc +*.zip +!examples/*.zip diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3ef98d1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 sthkm3 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..0eda67e --- /dev/null +++ b/README.md @@ -0,0 +1,208 @@ +# Rhyculator Maker + +小遊戲 [Rhyculator](https://github.com/Sthkm3/Rhyculator) 的簡易譜面製作器。 | A simple chart editor for game [Rhyculator](https://github.com/Sthkm3/Rhyculator). + +## 製譜流程 + +該遊戲非傳統下落式音遊,直接使用遊玩的顯示方式製譜不夠直覺,且該遊戲預設為兩指遊玩設計,本製作器會採用兩階段製譜。 + +- **第一階段**:將遊戲的 5x6 格子拆分成左手專用的 2x6、左右手皆可使用的 1x6 以及右手專用的 2x6,渲染成三條下落式軌道,用來設計敲擊手感。 + + ![譜面第一階段](docs/chart.png) + +- **第二階段**:把三條軌道上的音符個別配置到 5x6 格子上,最後輸出成曲包(`.zip`)。 + + ![譜面第二階段](docs/position.png) + +## 額外功能 + +- **手動微調**:點音符、點格子即可改位置,改過的音符會鎖定,重新自動配置時保留 +- **與遊戲一致的預覽**:5x6 預覽的出現時間、縮放動畫與遊戲相同 +- **精確播放**:以音訊取樣計算播放位置並扣除輸出延遲;可 0.5x/0.75x 慢速播放、開關打擊音效 +- **錄製模式**:邊聽邊按 F/空白/J 打點,停止時自動吸附到格線 +- **檢查**:未配置、區域違規、同格重疊、同一隻手同時要按兩個,都會即時標紅 +- **匯入 osu! 當參考**:taiko 與 mania 4K 譜面可匯入當作參考 + +## 安裝 + +需要 Python 3.10 以上。 + +``` +git clone https://github.com/sthkm3/RhyculatorMaker.git +cd RhyculatorMaker +python -m venv .venv +.venv\Scripts\pip install -r requirements.txt +``` + +macOS/Linux 把 `.venv\Scripts\` 換成 `.venv/bin/`。 + +## 快速開始 + +開啟示範曲包 FREEDOM DiVE (tpz Overcute Remix)(也可以把 `examples/FREEDOM DiVE (tpz Overcute Remix).zip` 拖進啟動視窗): + +``` +.venv\Scripts\python maker.py "examples\FREEDOM DiVE (tpz Overcute Remix).zip" +``` + +> 示範曲包內的音樂〈FREEDOM DiVE (tpz Overcute Remix)〉原曲為 xi 的〈FREEDOM DiVE↓〉,Remix 為 tpz,版權屬於原作者,僅供示範用途,不在本專案的 MIT 授權範圍內。 + +不帶參數啟動時會先出現啟動視窗(Windows 也可以直接執行 `run.bat`): + +``` +.venv\Scripts\python maker.py +``` + +- **開啟曲包**:把 `.zip` 拖進視窗(或按「選擇檔案…」),按「確定」。曲包會解壓到暫存區編輯, + 每次 `Ctrl+S` 都直接重新打包並覆蓋原本的 zip +- **建立新曲包**:路徑留空按「確定」,填好存放位置、ID、曲名、曲師、BPM、音訊或影片、封面, + 並勾選要有的難度與難度數字,按「建立」後會立刻存出一個空曲包並進入編輯器 + +## 操作說明 + +### 1. 譜面分頁:決定節奏與分手 + +| 操作 | 說明 | +|---|---| +| 左鍵點軌道 | 放 tap | +| 拖曳 | 放 hold | +| `Shift` + 拖曳 | 放 slide | +| 右鍵 | 刪除 | +| `↑` `↓` | 選取的音符移動一格線 | +| `1` `2` `3` | 選取的音符改到 L/M/R 軌 | +| `R` | 錄製模式:播放中按 `F`(左)`空白`(中)`J`(右) | +| `[` `]` | 格線細分(1/1 ~ 1/16 拍) | +| `B`/`O` | 設定 BPM/第一拍時間 | + +### 2. 座標分頁:配置到 5x6 + +| 操作 | 說明 | +|---|---| +| `A` | 自動配置所有未鎖定的音符 | +| `Shift` + `A` | 只配置還沒有座標的音符 | +| 點音符 → 點格子 | 指定座標並鎖定(只能點該手可用的區域) | +| slide:點格子/`Shift` + 點格子 | 重畫路徑/延伸路徑 | +| `U` | 解除鎖定 | + +各軌可用的欄位(x = 0 在最左,y = 0 在最下): + +| 軌 | tap/hold | slide 路徑 | +|---|---|---| +| L(左手) | x = 0, 1 | x = 0, 1, 2 | +| R(右手) | x = 3, 4 | x = 2, 3, 4 | +| M(中間,任一隻手) | x = 2 | x = 2 | + +### 共用操作 + +| 操作 | 說明 | +|---|---| +| `空白` | 播放/暫停(錄製模式時改用 `Enter`) | +| 滾輪/`Ctrl` + 滾輪 | 捲動/縮放時間軸 | +| `F1` `F2` `F3` | 播放速度 0.5x/0.75x/1x | +| `K` | 打擊音效開關 | +| 左上下拉選單 | 切換難度 | +| 右上「難度」勾選 | 決定曲包有哪些難度(例如只要 normal、hard);點 `Lv` 修改難度數字 | +| `I` | 編輯曲包資訊 | +| `Tab` | 切換分頁 | +| `Ctrl+O` | 回到啟動視窗(開啟其他曲包/建立新曲包) | +| `Ctrl+S`/`Ctrl+Shift+S` | 存檔/另存 | +| `Ctrl+I` | 匯入 osu! 譜面到目前難度 | +| `Ctrl+Z` | 復原 | +| `H` | 顯示/隱藏說明 | + +## 曲包格式 + +``` +.zip +├─ config.json 必要 +├─ easy.json / normal.json / hard.json 至少一個(檔案存在 = 有這個難度,可以是空譜面) +├─ music.wav | .ogg | .mp3 / video.mp4 音訊與影片至少一個(只有影片時,Maker 會自動抽出 music.wav) +└─ image.png 必要,正方形(匯入時自動置中裁切為 512x512) +``` + +### config.json + +```json +{ + "format": 1, + "id": "my-song", + "name": "曲名", + "artist": "曲師", + "charter": "譜師", + "bpm": 174.0, + "beat_offset": 1216, + "offset": 0, + "preview_start": 60000, + "preview_length": 15000, + "easy_num": 4, + "normal_num": 9, + "hard_num": 15 +} +``` + +| 欄位 | 說明 | +|---|---| +| `id` | 曲包唯一 ID,小寫英數字與 `-` | +| `name`/`artist`/`charter` | 曲名/曲師/譜師 | +| `bpm`/`beat_offset` | Maker 格線用:BPM 與第一拍時間(ms) | +| `offset` | 遊戲判定時間微調(ms) | +| `preview_start`/`preview_length` | 選歌試聽片段(ms) | +| `easy_num`/`normal_num`/`hard_num` | 難度數字;有該難度譜面時必填 | + +### 譜面(easy.json 等) + +```json +{ + "format": 1, + "divisor": 4, + "notes": [ + {"t": 1216, "lane": "L", "type": "tap", "pos": {"x": 0, "y": 3}}, + {"t": 2000, "lane": "R", "type": "hold", "end": 2500, "pos": {"x": 3, "y": 1}, "locked": true}, + {"t": 3000, "lane": "L", "type": "slide", "end": 3500, + "path": [{"x": 0, "y": 0}, {"x": 1, "y": 1}, {"x": 2, "y": 2}]} + ] +} +``` + +- `t`/`end`:判定時間與結束時間(ms) +- `lane`:L/M/R,`locked`:手動指定過座標 +- slide 的路徑格子平均分布在 `t` ~ `end`,第一格在 `t`、最後一格在 `end` + +遊戲讀取時忽略 `lane` 與 `locked`。 + +## 檢查譜面 + +``` +.venv\Scripts\python validate.py my-song.zip +``` + +會檢查曲包本身與每個難度的譜面;有問題時列出並以非 0 結束碼結束(可用在 CI)。 + +Maker 存檔前也會檢查曲包:必要檔案、config 欄位、`id` 格式、封面是否為正方形;有問題時不會存檔,並在狀態列列出原因。 + +## 開發 + +``` +.venv\Scripts\python -m pytest tests +``` + +| 檔案 | 內容 | +|---|---| +| `maker.py` | 主程式(pygame) | +| `chart.py` | 譜面資料模型、格線吸附、匯出 | +| `pack.py` | 曲包讀寫與驗證、封面裁切、影片抽音軌 | +| `placer.py` | 依手分區的自動配置 | +| `validate.py` | 譜面檢查 | +| `zones.py` | 手的區域規則與遊戲共用常數 | +| `audio.py` | 播放、變速、打擊音效、波形 | +| `importers.py`/`osu_parse.py` | osu! 匯入 | +| `examples/make_demo_pack.py` | 產生示範曲包 | + +`maker.py --screenshot out.png` 可在不開視窗的情況下輸出畫面(測試用)。 + +## 關於 Rhyculator + +Rhyculator 是一款以雙指為主的 Android 節奏遊戲,在 5x6 的格子上按下出現的音符,有 tap、hold、slide 三種音符。 + +## 授權 + +[MIT](LICENSE) diff --git a/audio.py b/audio.py new file mode 100644 index 0000000..c82aae4 --- /dev/null +++ b/audio.py @@ -0,0 +1,123 @@ +"""音訊播放:以送出的取樣數計算播放位置(比 pygame.mixer 準),支援變速與打擊音效""" +import threading + +import numpy as np + +try: + import sounddevice as sd +except Exception: # 沒有音訊裝置(例如 CI)時仍可載入、計算波形 + sd = None + +SAMPLE_RATE = 44100 + + +def load_audio(path): + """讀 wav/mp3/flac/ogg → float32 stereo ndarray (n, 2)""" + import miniaudio + dec = miniaudio.decode_file(path, output_format=miniaudio.SampleFormat.FLOAT32, + nchannels=2, sample_rate=SAMPLE_RATE) + return np.frombuffer(dec.samples, dtype=np.float32).reshape(-1, 2).copy() + + +def make_click(freq=1800.0, ms=30): + n = int(SAMPLE_RATE * ms / 1000) + t = np.arange(n) / SAMPLE_RATE + return (np.sin(2 * np.pi * freq * t) * np.exp(-t * 180) * 0.6).astype(np.float32) + + +class Player: + def __init__(self, samples): + self.samples = samples + self.pos = 0.0 # 播放位置(取樣,可為小數:變速時) + self.speed = 1.0 + self.playing = False + self.hit_times = [] # 打擊音效時間點(ms,已排序) + self.hitsound = True + self._click = make_click() + self._clicks = [] # 進行中的打擊音效 [(offset_in_click)] + self._lock = threading.Lock() + self._stream = None + self.latency = 0.0 + if sd is not None: + try: + self._stream = sd.OutputStream(samplerate=SAMPLE_RATE, channels=2, dtype="float32", + callback=self._callback, latency="low") + self._stream.start() + self.latency = self._stream.latency + except Exception: + self._stream = None + + @property + def length_ms(self): + return len(self.samples) / SAMPLE_RATE * 1000 + + def position_ms(self): + """目前「聽到」的位置:扣掉輸出延遲""" + with self._lock: + p = self.pos + heard = p / SAMPLE_RATE * 1000 - (self.latency * 1000 * self.speed if self.playing else 0) + return max(0.0, heard) + + def seek(self, ms): + with self._lock: + self.pos = max(0.0, min(len(self.samples) - 1, ms / 1000 * SAMPLE_RATE)) + self._clicks.clear() + + def toggle(self): + self.playing = not self.playing + + def set_hit_times(self, times): + with self._lock: + self.hit_times = sorted(times) + + def close(self): + if self._stream is not None: + self._stream.stop() + self._stream.close() + + def _callback(self, out, frames, time_info, status): + out.fill(0) + if not self.playing: + return + with self._lock: + start = self.pos + idx = start + np.arange(frames) * self.speed + i0 = idx.astype(np.int64) + valid = i0 < len(self.samples) - 1 + if valid.any(): + i0v = i0[valid] + frac = (idx[valid] - i0v)[:, None] + out[valid] = self.samples[i0v] * (1 - frac) + self.samples[i0v + 1] * frac + self.pos = start + frames * self.speed + if self.pos >= len(self.samples) - 1: + self.pos = len(self.samples) - 1 + self.playing = False + + if self.hitsound and self.hit_times: + t0 = start / SAMPLE_RATE * 1000 + t1 = self.pos / SAMPLE_RATE * 1000 + lo = np.searchsorted(self.hit_times, t0) + hi = np.searchsorted(self.hit_times, t1) + for ht in self.hit_times[lo:hi]: + at = int((ht - t0) / 1000 * SAMPLE_RATE / self.speed) + self._clicks.append(-at) + alive = [] + for off in self._clicks: + a = max(0, -off) + c0 = max(0, off) + n = min(frames - a, len(self._click) - c0) + if n > 0: + out[a:a + n] += self._click[c0:c0 + n, None] + if off + frames < len(self._click): + alive.append(off + frames) + self._clicks = alive + + +def waveform(samples, bin_ms=10): + """每 bin_ms 一個峰值(0~1),用於畫波形""" + mono = np.abs(samples).max(axis=1) + step = int(SAMPLE_RATE * bin_ms / 1000) + n = len(mono) // step + peaks = mono[: n * step].reshape(n, step).max(axis=1) + m = peaks.max() or 1.0 + return peaks / m diff --git a/chart.py b/chart.py new file mode 100644 index 0000000..9c71767 --- /dev/null +++ b/chart.py @@ -0,0 +1,162 @@ +"""譜面資料模型:三軌(L/M/R)中間檔 *.lanes.json 與遊戲譜面匯出""" +from __future__ import annotations + +import copy +import json +from dataclasses import dataclass, field, asdict +from typing import Optional + +NOTE_TYPES = ("tap", "hold", "slide") + + +@dataclass(eq=False) # 以物件身分比較:選取、刪除都針對「這一顆」 +class Note: + t: int # 判定時間(ms) + lane: str # "L" / "M" / "R" + type: str = "tap" # tap / hold / slide + end: Optional[int] = None # hold / slide 結束時間(ms) + pos: Optional[tuple] = None # tap / hold 的格子 (x, y) + path: Optional[list] = None # slide 路徑 [(x, y), ...] + locked: bool = False # 手動指定過座標,自動配置時保留 + + @property + def end_time(self): + return self.end if self.end is not None else self.t + + def placed(self): + return bool(self.path) if self.type == "slide" else self.pos is not None + + def to_json(self): + d = {"t": self.t, "lane": self.lane, "type": self.type} + if self.end is not None: + d["end"] = self.end + if self.pos is not None: + d["pos"] = {"x": self.pos[0], "y": self.pos[1]} + if self.path: + d["path"] = [{"x": x, "y": y} for x, y in self.path] + if self.locked: + d["locked"] = True + return d + + @staticmethod + def from_json(d): + pos = (d["pos"]["x"], d["pos"]["y"]) if "pos" in d else None + path = [(p["x"], p["y"]) for p in d["path"]] if "path" in d else None + return Note(int(d["t"]), d["lane"], d.get("type", "tap"), d.get("end"), pos, path, d.get("locked", False)) + + +@dataclass +class Chart: + audio: str = "" + bpm: float = 120.0 + offset: int = 0 # 第一拍的時間(ms) + divisor: int = 4 # 吸附細分:1/divisor 拍 + notes: list = field(default_factory=list) + + # ---------- 節拍格線 ---------- + @property + def beat_ms(self): + return 60000.0 / self.bpm + + def snap(self, t, divisor=None): + step = self.beat_ms / (divisor or self.divisor) + return int(round(self.offset + round((t - self.offset) / step) * step)) + + def grid_lines(self, t0, t1, divisor=None): + """回傳 [(time, is_beat, is_bar)]""" + div = divisor or self.divisor + step = self.beat_ms / div + k = int((t0 - self.offset) // step) + out = [] + while True: + t = self.offset + k * step + if t > t1: + break + if t >= t0: + out.append((t, k % div == 0, k % (div * 4) == 0)) + k += 1 + return out + + # ---------- 音符 ---------- + def sort(self): + self.notes.sort(key=lambda n: (n.t, "LMR".index(n.lane))) + + def add(self, note): + self.notes.append(note) + self.sort() + return note + + def note_at(self, lane, t, tolerance): + best = None + for n in self.notes: + if n.lane != lane: + continue + if n.t - tolerance <= t <= n.end_time + tolerance: + if best is None or abs(n.t - t) < abs(best.t - t): + best = n + return best + + def snapshot(self): + return copy.deepcopy(self.notes) + + # ---------- 曲包內的譜面(統一格式;bpm 等曲目資訊在 config.json)---------- + CHART_FORMAT = 1 + + def chart_json(self): + return {"format": self.CHART_FORMAT, "divisor": self.divisor, + "notes": [n.to_json() for n in self.notes]} + + @staticmethod + def from_chart_json(d, bpm, beat_offset, audio=""): + c = Chart(audio, float(bpm), int(beat_offset), int(d.get("divisor", 4)), + [Note.from_json(n) for n in d.get("notes", [])]) + c.sort() + return c + + # ---------- 舊版 *.lanes.json ---------- + def to_json(self): + return {"audio": self.audio, "bpm": self.bpm, "offset": self.offset, "divisor": self.divisor, + "notes": [n.to_json() for n in self.notes]} + + def save(self, path): + with open(path, "w", encoding="utf-8", newline="\n") as f: + json.dump(self.to_json(), f, ensure_ascii=False, indent=1) + + @staticmethod + def load(path): + d = json.load(open(path, encoding="utf-8")) + c = Chart(d.get("audio", ""), float(d.get("bpm", 120)), int(d.get("offset", 0)), int(d.get("divisor", 4)), + [Note.from_json(n) for n in d.get("notes", [])]) + c.sort() + return c + + # ---------- 匯出遊戲譜面 ---------- + def export_sheet(self): + """轉成遊戲 MusicPlayer 讀取的格式;未配置座標的音符會被略過""" + out = [] + for n in self.notes: + if not n.placed(): + continue + if n.type == "slide": + # 遊戲把路徑格子平均分配在 [startTime, endTime):第 i 格在 start + i * (end-start)/len + # 這裡讓最後一格剛好落在 n.end + k = len(n.path) + end = n.end if k == 1 else int(round(n.t + (n.end - n.t) * k / (k - 1))) + out.append({"type": "slide", "startTime": n.t, "endTime": end, + "path": [{"x": x, "y": y} for x, y in n.path]}) + elif n.type == "hold": + out.append({"type": "hold", "startTime": n.t, "endTime": n.end, + "pos": {"x": n.pos[0], "y": n.pos[1]}}) + else: + out.append({"type": "tap", "startTime": n.t, "pos": {"x": n.pos[0], "y": n.pos[1]}}) + return out + + def export_sheet_file(self, path): + with open(path, "w", encoding="utf-8", newline="\n") as f: + json.dump(self.export_sheet(), f, ensure_ascii=False, indent=2) + + +def slide_steps(chart, note): + """slide 路徑的格子數:每 1/divisor 拍一格,至少 2 格""" + step = chart.beat_ms / chart.divisor + return max(2, int(round((note.end_time - note.t) / step)) + 1) diff --git a/docs/chart.png b/docs/chart.png new file mode 100644 index 0000000..780cba2 Binary files /dev/null and b/docs/chart.png differ diff --git a/docs/position.png b/docs/position.png new file mode 100644 index 0000000..c57168e Binary files /dev/null and b/docs/position.png differ diff --git a/examples/FREEDOM DiVE (tpz Overcute Remix).zip b/examples/FREEDOM DiVE (tpz Overcute Remix).zip new file mode 100644 index 0000000..b98d3a3 Binary files /dev/null and b/examples/FREEDOM DiVE (tpz Overcute Remix).zip differ diff --git a/examples/make_demo_pack.py b/examples/make_demo_pack.py new file mode 100644 index 0000000..bca09c2 --- /dev/null +++ b/examples/make_demo_pack.py @@ -0,0 +1,87 @@ +"""產生示範曲包 demo.zip(節拍音軌 + 漸層封面 + 三種音符的範例譜面),全部由程式產生、無版權疑慮 + +用法:python examples/make_demo_pack.py [輸出路徑] +""" +import os +import sys +import tempfile +import wave + +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "..")) + +from chart import Note # noqa: E402 +from pack import SongPack, default_config, save_pack # noqa: E402 +from placer import auto_place # noqa: E402 + +BPM = 120 +FIRST_BEAT = 1000 +BEATS = 64 +SR = 44100 + + +def click_track(path): + beat = 60.0 / BPM + length = FIRST_BEAT / 1000 + BEATS * beat + 1.0 + data = np.zeros(int(SR * length), dtype=np.float32) + n = int(SR * 0.05) + t = np.arange(n) / SR + for b in range(BEATS): + freq = 1760 if b % 4 == 0 else 1320 + start = int((FIRST_BEAT / 1000 + b * beat) * SR) + data[start:start + n] += np.sin(2 * np.pi * freq * t) * np.exp(-t * 60) * 0.6 + pcm = (np.clip(data, -1, 1) * 32767).astype(np.int16) + with wave.open(path, "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(SR) + w.writeframes(pcm.tobytes()) + + +def cover(path): + from PIL import Image + x = np.linspace(0, 1, 512) + r = (40 + 180 * x)[None, :].repeat(512, 0) + g = np.full((512, 512), 60.0) + b = (200 - 120 * x)[:, None].repeat(512, 1) + Image.fromarray(np.stack([r, g, b], -1).astype(np.uint8)).save(path) + + +def demo_notes(): + beat = 60000 / BPM + notes = [] + for i in range(48): # 前 48 拍:左右交替,每 4 拍一顆中間 + t = int(FIRST_BEAT + i * beat) + notes.append(Note(t, "M" if i % 4 == 3 else ("L" if i % 2 == 0 else "R"), "tap")) + t = int(FIRST_BEAT + 48 * beat) + notes.append(Note(t, "L", "hold", int(t + 2 * beat))) + notes.append(Note(int(t + 2 * beat), "R", "hold", int(t + 4 * beat))) + notes.append(Note(int(t + 6 * beat), "L", "slide", int(t + 8 * beat))) + notes.append(Note(int(t + 10 * beat), "R", "slide", int(t + 12 * beat))) + return notes + + +def main(): + out = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "demo.zip") + tmp = tempfile.mkdtemp() + music, image = os.path.join(tmp, "music.wav"), os.path.join(tmp, "cover.png") + click_track(music) + cover(image) + + pack = SongPack(default_config(id="demo", name="Maker Demo", artist="Rhyculator Maker", + charter="Rhyculator Maker", bpm=BPM, beat_offset=FIRST_BEAT, + normal_num=1)) + pack.set_music(music) + pack.set_image(image) + chart = pack.chart("normal", create=True) + chart.notes = demo_notes() + auto_place(chart) + save_pack(pack, out) + pack.close() + print(f"已產生 {out}(normal {len(chart.notes)} 顆)") + + +if __name__ == "__main__": + main() diff --git a/importers.py b/importers.py new file mode 100644 index 0000000..c6b5d88 --- /dev/null +++ b/importers.py @@ -0,0 +1,113 @@ +"""從 osu 譜面匯入成三軌(L/M/R)譜面,作為製譜起點 + +- taiko:don → L、ka → R、大音符 → M;同色快速連打改為左右交替,避免單手連打; + 轉盤 → M 的 hold、連打條 → slide +- mania 4K:1-2 軌 → L、3-4 軌 → R、長條 → hold;同手和弦時其中一顆移到 M +""" +from chart import Chart, Note +from osu_parse import parse_osu + +# 同一隻手連續兩下的最短間隔,比這更快就換手(ms) +ALTERNATE_BELOW = 150 + + +def read_sections(path): + sections, cur = {}, None + for raw in open(path, encoding="utf-8"): + line = raw.strip() + if not line or line.startswith("//"): + continue + if line.startswith("[") and line.endswith("]"): + cur = line[1:-1] + sections[cur] = [] + elif cur: + sections[cur].append(line) + return sections + + +def timing_info(sections): + """第一個非繼承 timing point 的 BPM 與時間""" + for l in sections.get("TimingPoints", []): + p = l.split(",") + uninherited = p[6] == "1" if len(p) > 6 else True + if uninherited and float(p[1]) > 0: + return 60000.0 / float(p[1]), int(float(p[0])) + return 120.0, 0 + + +def general(sections, key, default=""): + for l in sections.get("General", []): + if l.startswith(key + ":"): + return l.split(":", 1)[1].strip() + return default + + +def import_taiko(path): + sec = read_sections(path) + bpm, offset = timing_info(sec) + chart = Chart(general(sec, "AudioFilename"), round(bpm, 3), offset, 4) + + last = {"L": -10**9, "R": -10**9} + prev_lane = None + for o in parse_osu(path): + t = o["time"] + if o["kind"] == "spinner": + chart.notes.append(Note(t, "M", "hold", o["end"])) + continue + if o["kind"] == "drumroll": + lane = "R" if prev_lane == "L" else "L" + chart.notes.append(Note(t, lane, "slide", o["end"])) + last[lane] = o["end"] + prev_lane = lane + continue + if o["big"]: + chart.notes.append(Note(t, "M", "tap")) + last["L"] = last["R"] = t + prev_lane = None + continue + + lane = "R" if o["kat"] else "L" + other = "L" if lane == "R" else "R" + # 同一隻手太快 → 換另一隻手 + if t - last[lane] < ALTERNATE_BELOW and t - last[other] >= ALTERNATE_BELOW: + lane = other + chart.notes.append(Note(t, lane, "tap")) + last[lane] = t + prev_lane = lane + + chart.sort() + return chart + + +def import_mania4k(path): + sec = read_sections(path) + bpm, offset = timing_info(sec) + chart = Chart(general(sec, "AudioFilename"), round(bpm, 3), offset, 4) + + busy_until = {"L": -10**9, "R": -10**9, "M": -10**9} + for l in sec["HitObjects"]: + p = l.split(",") + col = min(3, int(int(p[0]) * 4 / 512)) + t, typ = int(p[2]), int(p[3]) + end = int(p[5].split(":")[0]) if typ & 128 else None + lane = "L" if col <= 1 else "R" + # 同手已被佔用(和弦或長條中)→ 移到中間欄,再不行就略過 + if busy_until[lane] >= t: + lane = "M" if busy_until["M"] < t else None + if lane is None: + continue + chart.notes.append(Note(t, lane, "hold" if end else "tap", end)) + busy_until[lane] = end if end else t + + chart.sort() + return chart + + +def import_osu(path): + sec = read_sections(path) + mode = general(sec, "Mode", "0") + if mode == "1": + return import_taiko(path) + if mode == "3": + return import_mania4k(path) + raise ValueError("目前只支援 osu!taiko 與 osu!mania 4K 譜面") diff --git a/install.bat b/install.bat new file mode 100644 index 0000000..84ed222 --- /dev/null +++ b/install.bat @@ -0,0 +1,2 @@ +python -m venv .venv +.venv\Scripts\pip install -r requirements.txt \ No newline at end of file diff --git a/launcher.py b/launcher.py new file mode 100644 index 0000000..b1121b5 --- /dev/null +++ b/launcher.py @@ -0,0 +1,241 @@ +"""啟動視窗:選擇(或拖入)曲包 zip 開啟;留空按確定則建立新曲包 + +run_launcher() 回傳: + ("open", zip 路徑) + ("new", SongPack) 已建立並存檔的新曲包 + None 取消 +""" +import os +import zipfile + +from pack import DIFFS, ID_RE, create_pack + +AUDIO_TYPES = [("音訊或影片", "*.wav *.ogg *.mp3 *.mp4")] +IMAGE_TYPES = [("圖片", "*.png *.jpg *.jpeg *.webp")] + + +def check_open_path(path): + """回傳錯誤訊息,沒問題回傳 None""" + if not path.lower().endswith(".zip"): + return "請選擇 .zip 曲包" + if not os.path.isfile(path): + return "找不到這個檔案" + if not zipfile.is_zipfile(path): + return "這不是有效的 zip 檔" + return None + + +def new_pack_errors(v): + """新曲包表單的檢查(v 為各欄位字串與勾選狀態),回傳錯誤清單""" + errors = [] + if not v.get("save_path", "").strip(): + errors.append("請選擇曲包存放位置") + elif not v["save_path"].lower().endswith(".zip"): + errors.append("存放位置需為 .zip") + if not ID_RE.match(v.get("id", "").strip()): + errors.append("ID 只能用小寫英數字與 -(2~64 字)") + for k, label in (("name", "曲名"), ("artist", "曲師")): + if not v.get(k, "").strip(): + errors.append(f"請填{label}") + try: + if float(v.get("bpm", "")) <= 0: + errors.append("BPM 必須大於 0") + except ValueError: + errors.append("BPM 必須是數字") + try: + int(v.get("beat_offset", "") or 0) + except ValueError: + errors.append("第一拍時間必須是整數(ms)") + media = v.get("media", "").strip() + if not media: + errors.append("請選擇音訊或影片") + elif not os.path.isfile(media): + errors.append("找不到音訊/影片檔") + image = v.get("image", "").strip() + if not image: + errors.append("請選擇封面圖片") + elif not os.path.isfile(image): + errors.append("找不到封面圖片") + chosen = [d for d in DIFFS if v.get(f"use_{d}")] + if not chosen: + errors.append("至少勾選一個難度") + for d in chosen: + try: + n = int(v.get(f"{d}_num", "")) + if not 1 <= n <= 99: + raise ValueError + except ValueError: + errors.append(f"{d} 的難度數字需為 1~99") + return errors + + +def _tk_root(): + try: + from tkinterdnd2 import TkinterDnD + return TkinterDnD.Tk(), True + except Exception: + import tkinter as tk + return tk.Tk(), False + + +def run_launcher(): + import tkinter as tk + from tkinter import filedialog, messagebox + + root, dnd = _tk_root() + root.title("Rhyculator Maker") + root.resizable(False, False) + result = {"value": None} + + # ---------- 開啟畫面 ---------- + open_frame = tk.Frame(root, padx=16, pady=14) + path_var = tk.StringVar() + + tk.Label(open_frame, text="開啟曲包", font=("Microsoft JhengHei", 14, "bold")).grid(row=0, column=0, columnspan=2, sticky="w") + drop = tk.Label(open_frame, text=("把曲包 .zip 拖到這裡" if dnd else "按「選擇檔案…」選擇曲包 .zip") + + "\n留空按「確定」可建立新曲包", + width=48, height=4, relief="groove", fg="#666") + drop.grid(row=1, column=0, columnspan=2, pady=(8, 8), sticky="we") + entry = tk.Entry(open_frame, textvariable=path_var, width=46) + entry.grid(row=2, column=0, sticky="we") + + def browse_open(): + p = filedialog.askopenfilename(parent=root, filetypes=[("Rhyculator 曲包", "*.zip")]) + if p: + path_var.set(p) + + tk.Button(open_frame, text="選擇檔案…", command=browse_open).grid(row=2, column=1, padx=(6, 0)) + open_err = tk.Label(open_frame, text="", fg="#c33") + open_err.grid(row=3, column=0, columnspan=2, sticky="w") + + if dnd: + from tkinterdnd2 import DND_FILES + + def on_drop(e): + files = root.tk.splitlist(e.data) + if files: + path_var.set(files[0]) + for w in (drop, entry): + w.drop_target_register(DND_FILES) + w.dnd_bind("<>", on_drop) + + def confirm_open(): + p = path_var.get().strip().strip('"') + if not p: + open_frame.pack_forget() + new_frame.pack() + refresh_new() + return + err = check_open_path(p) + if err: + open_err.config(text=err) + return + result["value"] = ("open", os.path.abspath(p)) + root.quit() + + btns = tk.Frame(open_frame) + btns.grid(row=4, column=0, columnspan=2, sticky="e", pady=(8, 0)) + tk.Button(btns, text="取消", width=10, command=root.quit).pack(side="right", padx=(6, 0)) + tk.Button(btns, text="確定", width=10, command=confirm_open).pack(side="right") + open_frame.pack() + + # ---------- 新曲包畫面 ---------- + new_frame = tk.Frame(root, padx=16, pady=14) + tk.Label(new_frame, text="建立新曲包", font=("Microsoft JhengHei", 14, "bold")).grid(row=0, column=0, columnspan=3, sticky="w") + vars_ = {} + + def add_row(r, key, label, default="", browse=None): + tk.Label(new_frame, text=label).grid(row=r, column=0, sticky="e", padx=(0, 6), pady=2) + var = tk.StringVar(value=default) + tk.Entry(new_frame, textvariable=var, width=40).grid(row=r, column=1, sticky="we", pady=2) + if browse: + tk.Button(new_frame, text="…", width=3, command=lambda: browse(var)).grid(row=r, column=2, padx=(4, 0)) + vars_[key] = var + + def browse_save(var): + p = filedialog.asksaveasfilename(parent=root, defaultextension=".zip", filetypes=[("Rhyculator 曲包", "*.zip")], + initialfile=(vars_["id"].get().strip() or "song") + ".zip") + if p: + var.set(p) + + def browse_file(types): + def f(var): + p = filedialog.askopenfilename(parent=root, filetypes=types) + if p: + var.set(p) + return f + + add_row(1, "save_path", "存放位置", browse=browse_save) + add_row(2, "id", "曲包 ID") + add_row(3, "name", "曲名") + add_row(4, "artist", "曲師") + add_row(5, "charter", "譜師") + add_row(6, "bpm", "BPM", "120") + add_row(7, "beat_offset", "第一拍 (ms)", "0") + add_row(8, "media", "音訊或影片", browse=browse_file(AUDIO_TYPES)) + add_row(9, "image", "封面圖片", browse=browse_file(IMAGE_TYPES)) + + tk.Label(new_frame, text="難度").grid(row=10, column=0, sticky="ne", padx=(0, 6), pady=(6, 0)) + diff_box = tk.Frame(new_frame) + diff_box.grid(row=10, column=1, columnspan=2, sticky="w", pady=(6, 0)) + for i, d in enumerate(DIFFS): + use = tk.BooleanVar(value=(d == "normal")) + num = tk.StringVar() + tk.Checkbutton(diff_box, text=d, variable=use, width=7, anchor="w").grid(row=0, column=i * 2) + tk.Entry(diff_box, textvariable=num, width=4).grid(row=0, column=i * 2 + 1, padx=(0, 12)) + vars_[f"use_{d}"] = use + vars_[f"{d}_num"] = num + tk.Label(diff_box, text="(勾選要有的難度並填難度數字)", fg="#666").grid(row=1, column=0, columnspan=6, sticky="w") + + new_err = tk.Label(new_frame, text="", fg="#c33", justify="left", wraplength=380) + new_err.grid(row=11, column=0, columnspan=3, sticky="w", pady=(6, 0)) + + def values(): + return {k: v.get() for k, v in vars_.items()} + + def refresh_new(*_): + errs = new_pack_errors(values()) + new_err.config(text="\n".join("・" + e for e in errs[:4])) + create_btn.config(state="disabled" if errs else "normal") + + def back(): + new_frame.pack_forget() + open_frame.pack() + + def create(): + v = values() + if new_pack_errors(v): + return + config = {"id": v["id"].strip(), "name": v["name"].strip(), "artist": v["artist"].strip(), + "charter": v["charter"].strip(), "bpm": float(v["bpm"]), "beat_offset": int(v["beat_offset"] or 0)} + diffs = {d: int(v[f"{d}_num"]) for d in DIFFS if v[f"use_{d}"]} + try: + root.config(cursor="watch") + root.update() + pack = create_pack(os.path.abspath(v["save_path"].strip()), config, v["media"].strip(), + v["image"].strip(), diffs) + except Exception as e: + root.config(cursor="") + messagebox.showerror("建立失敗", str(e), parent=root) + return + result["value"] = ("new", pack) + root.quit() + + nb = tk.Frame(new_frame) + nb.grid(row=12, column=0, columnspan=3, sticky="e", pady=(8, 0)) + create_btn = tk.Button(nb, text="建立", width=10, command=create) + create_btn.pack(side="right", padx=(6, 0)) + tk.Button(nb, text="返回", width=10, command=back).pack(side="right") + for var in vars_.values(): + var.trace_add("write", refresh_new) + + root.protocol("WM_DELETE_WINDOW", root.quit) + root.bind("", lambda e: confirm_open() if open_frame.winfo_ismapped() else create()) + entry.focus_set() + root.mainloop() + root.destroy() + return result["value"] + + +if __name__ == "__main__": + print(run_launcher()) diff --git a/maker.py b/maker.py new file mode 100644 index 0000000..d4e369c --- /dev/null +++ b/maker.py @@ -0,0 +1,1023 @@ +"""Rhyculator Maker(譜面製作器) + +第一階段(譜面分頁):L / M / R 三軌下落式時間軸做譜 +第二階段(座標分頁):依手的區域把音符配置到 5x6 格子(自動 + 手動) + +執行:python maker.py [chart.lanes.json] +按 H 顯示所有快捷鍵。 +""" +import argparse +import os +import sys + +import pygame + +from chart import Chart, Note, slide_steps +from pack import DIFFS, SongPack, default_config, open_pack, save_pack, validate_pack +from placer import auto_place +from validate import validate +from zones import COLS, ROWS, APPEAR_MS, EXPIRE_MS, allowed_cols, cell_allowed, lane_of_column + +W, H = 1280, 820 +TOP = 44 +JUDGE_Y = 720 +WAVE_X, WAVE_W = 16, 60 +LANE_X0, LANE_W = 90, 120 +LANE_ORDER = ("L", "M", "R") +PANEL_X = 480 +TAB_X = 420 # 分頁按鈕起點 +DD_RECT = (8, 6, 132, 32) # 難度下拉按鈕 + +GRID_CELL, GRID_GAP = 86, 10 +GRID_X = PANEL_X + 120 +GRID_Y = TOP + 110 +DIFF_BAR_Y = TOP + 14 # 右側「難度」勾選列 + +C_BG = (18, 18, 22) +C_PANEL = (28, 28, 34) +C_TEXT = (225, 225, 230) +C_DIM = (130, 130, 140) +C_LINE_BAR = (120, 120, 130) +C_LINE_BEAT = (70, 70, 80) +C_LINE_SUB = (40, 40, 48) +C_JUDGE = (255, 107, 204) +C_NOTE = {"tap": (110, 180, 255), "hold": (255, 107, 204), "slide": (255, 220, 90)} +C_ZONE = {"L": (34, 46, 70), "M": (52, 40, 62), "R": (70, 44, 40)} +C_ERR = (255, 70, 70) +C_SEL = (255, 255, 255) + +HELP = [ + "空白 播放/暫停(錄製時:Enter) 滾輪 捲動 Ctrl+滾輪 縮放", + "[ ] 格線細分 F1/F2/F3 速度 0.5/0.75/1x K 打擊音效開關", + "譜面分頁:左鍵點軌道=tap 拖曳=hold Shift+拖曳=slide 右鍵=刪除", + " 選取後:↑↓ 移動一格線 1/2/3 改到 L/M/R 軌 Delete 刪除", + " R 錄製模式:播放中按 F=L 空白=M J=R,停止時自動吸附格線", + "座標分頁:點音符選取 → 點格子指定座標(自動鎖定)", + " slide:點格子重畫路徑,Shift+點格子延伸路徑 U 解除鎖定", + " A 自動配置全部未鎖定 Shift+A 只配置未配置的", + "左上下拉選單切換難度 I 編輯曲包資訊(config)", + "B 設定 BPM O 設定第一拍時間 Tab 切換分頁", + "右上「難度」勾選要有哪些難度,點 Lv 修改難度數字", + "Ctrl+O 回到啟動視窗(開啟其他曲包 / 建立新曲包) Ctrl+I 匯入 osu 到目前難度", + "Ctrl+S 存檔(直接覆蓋原 zip) Ctrl+Shift+S 另存 Ctrl+E 匯出現行遊戲格式 sheet_N.json", + "Ctrl+Z 復原 H 顯示/隱藏說明", +] + + +def lane_x(lane): + return LANE_X0 + LANE_ORDER.index(lane) * LANE_W + + +def cell_rect(x, y): + # y=0 在最下面(與遊戲一致) + px = GRID_X + x * (GRID_CELL + GRID_GAP) + py = GRID_Y + (ROWS - 1 - y) * (GRID_CELL + GRID_GAP) + return pygame.Rect(px, py, GRID_CELL, GRID_CELL) + + +class Editor: + def __init__(self, chart_path=None, audio_enabled=True): + pygame.init() + self.screen = pygame.display.set_mode((W, H)) + pygame.display.set_caption("Rhyculator Maker") + self.font = self._font(18) + self.font_small = self._font(14) + self.font_big = self._font(24) + self.clock = pygame.time.Clock() + + self.audio_enabled = audio_enabled + self.pack = None # SongPack;None = 舊版 *.lanes.json 模式 + self.diff = "normal" # 目前編輯的難度 + self.chart = Chart() + self.chart_path = None # 舊版 lanes 檔路徑 + self.player = None + self.wave = None + self.audio_loaded = None + self.time_ms = 0.0 + self.zoom = 0.25 # px / ms + self.tab = "chart" + self.selected = None + self.undo_stacks = {} # 難度 → undo 堆疊(切換難度不會混在一起) + self.drag = None # (lane, start_t, shift) + self.recording = False + self.recorded = [] + self.show_help = True + self.issues = [] + self.message = "" + self.dirty = False + self.dropdown_open = False + + if chart_path: + self.open_path(chart_path) + + @property + def undo_stack(self): + return self.undo_stacks.setdefault(self.diff if self.pack else "_lanes", []) + + # ---------- 基本 ---------- + @staticmethod + def _font(size): + for name in ("microsoftjhenghei", "microsoftyahei", "notosanscjktc", "simhei", "pingfangtc"): + path = pygame.font.match_font(name) + if path: + return pygame.font.Font(path, size) + return pygame.font.Font(None, size + 6) + + def say(self, msg): + self.message = msg + + def push_undo(self): + self.undo_stack.append(self.chart.snapshot()) + if len(self.undo_stack) > 200: + self.undo_stack.pop(0) + self.dirty = True + + def undo(self): + if self.undo_stack: + self.chart.notes = self.undo_stack.pop() + self.selected = None + self.changed() + self.say("已復原") + + def changed(self): + self.chart.sort() + self.issues = validate(self.chart) + if self.player: + self.player.set_hit_times([n.t for n in self.chart.notes]) + + def now(self): + if self.player and self.player.playing: + self.time_ms = self.player.position_ms() + return self.time_ms + + def seek(self, ms): + length = self.player.length_ms if self.player else 10**7 + self.time_ms = max(0.0, min(length, ms)) + if self.player: + self.player.seek(self.time_ms) + + # ---------- 對話框 ---------- + def _dialog(self): + import tkinter + from tkinter import filedialog, simpledialog + root = tkinter.Tk() + root.withdraw() + root.attributes("-topmost", True) + return root, filedialog, simpledialog + + def ask_file(self, title, types, save=False, initial=""): + root, fd, _ = self._dialog() + if save: + path = fd.asksaveasfilename(title=title, filetypes=types, initialfile=initial, + defaultextension=types[0][1].split()[0][1:]) + else: + path = fd.askopenfilename(title=title, filetypes=types) + root.destroy() + return path or None + + def dialog_number(self, title, prompt, initial, is_float): + root, _, sd = self._dialog() + v = (sd.askfloat if is_float else sd.askinteger)(title, prompt, initialvalue=initial, parent=root) + root.destroy() + return v + + def form(self, title, fields, values): + """簡易表單:fields = [(key, 標籤, 型別)];回傳 dict 或 None(取消)。空白的數字欄位回傳 None""" + import tkinter as tk + from tkinter import messagebox + root = tk.Tk() + root.title(title) + root.attributes("-topmost", True) + entries = {} + for i, (k, label, _) in enumerate(fields): + tk.Label(root, text=label).grid(row=i, column=0, sticky="e", padx=8, pady=3) + e = tk.Entry(root, width=44) + v = values.get(k) + e.insert(0, "" if v is None else str(v)) + e.grid(row=i, column=1, padx=8, pady=3) + entries[k] = e + result = {} + done = {"ok": False} + + def ok(): + out = {} + for k, label, typ in fields: + s = entries[k].get().strip() + if s == "": + out[k] = "" if typ is str else None + continue + try: + out[k] = typ(s) + except ValueError: + messagebox.showerror(title, f"「{label}」格式不正確", parent=root) + return + result.update(out) + done["ok"] = True + root.quit() + + row = len(fields) + tk.Button(root, text="確定", width=10, command=ok).grid(row=row, column=1, sticky="e", padx=8, pady=8) + tk.Button(root, text="取消", width=10, command=root.quit).grid(row=row, column=0, padx=8, pady=8) + root.protocol("WM_DELETE_WINDOW", root.quit) + root.mainloop() + root.destroy() + return result if done["ok"] else None + + CONFIG_FIELDS = [ + ("id", "曲包 ID(小寫英數與 -)", str), + ("name", "曲名", str), + ("artist", "曲師", str), + ("charter", "譜師", str), + ("bpm", "BPM", float), + ("beat_offset", "第一拍時間 (ms)", int), + ("offset", "判定時間微調 (ms)", int), + ("preview_start", "試聽開始 (ms)", int), + ("preview_length", "試聽長度 (ms)", int), + ("easy_num", "Easy 難度數字", int), + ("normal_num", "Normal 難度數字", int), + ("hard_num", "Hard 難度數字", int), + ] + + def edit_config(self, title="曲包資訊"): + if not self.pack: + self.say("目前不是曲包(Ctrl+S 可轉成曲包)") + return False + v = self.form(title, self.CONFIG_FIELDS, self.pack.config) + if v is None: + return False + for k, val in v.items(): + if val is None: + self.pack.config.pop(k, None) + else: + self.pack.config[k] = val + self.pack.sync_timing() + self.dirty = True + self.say("已更新曲包資訊") + return True + + # ---------- 音訊 ---------- + def load_audio(self, path): + if not path or not os.path.exists(path): + self.say(f"找不到音檔:{path}") + return + if path == self.audio_loaded and self.player: + return + from audio import load_audio, waveform, Player + samples = load_audio(path) + self.wave = waveform(samples) + if self.player: + self.player.close() + self.player = Player(samples) if self.audio_enabled else None + if self.player is None: + # 無音訊模式仍需要長度 + class _Len: + length_ms = len(samples) / 44.1 + playing = False + def seek(self, ms): pass + def position_ms(self): return 0 + def set_hit_times(self, t): pass + def close(self): pass + self.player = _Len() + self.audio_loaded = path + + # ---------- 曲包 / 難度 ---------- + def set_pack(self, pack, diff=None): + if self.pack and self.pack is not pack: + self.pack.close() + self.pack = pack + self.chart_path = None + self.undo_stacks.clear() + existing = [d for d in DIFFS if d in pack.charts] + self.switch_diff(diff or (existing[0] if existing else "normal")) + self.load_audio(pack.music) + self.dirty = False + + def switch_diff(self, diff): + if not self.pack: + return + self.diff = diff + self.chart = self.pack.chart(diff, create=True) + self.selected = None + self.changed() + self.say(f"編輯 {diff}({len(self.chart.notes)} 顆)") + + def title(self): + if self.pack: + return self.pack.config.get("name") or self.pack.config.get("id") or "(未命名曲包)" + return os.path.basename(self.chart_path) if self.chart_path else "(未存檔)" + + # ---------- 開啟 / 存檔 ---------- + def open_path(self, path): + if path.lower().endswith(".zip"): + self.set_pack(open_pack(path)) + self.say(f"已開啟曲包 {os.path.basename(path)}:" + + "、".join(f"{d} {len(c.notes)} 顆" for d, c in self.pack.charts.items())) + else: + self.open_lanes(path) + + def open_lanes(self, path): + """舊版 *.lanes.json:可編輯,Ctrl+S 時轉成曲包""" + if self.pack: + self.pack.close() + self.pack = None + self.chart = Chart.load(path) + self.chart_path = path + a = self.chart.audio + if a and not os.path.isabs(a): + a = os.path.join(os.path.dirname(path), a) + self.chart.audio = a + self.load_audio(a) + self.undo_stacks.clear() + self.selected = None + self.dirty = False + self.changed() + self.say(f"已開啟舊版譜面 {os.path.basename(path)},Ctrl+S 會轉成曲包") + + def dialog_open(self): + path = self.ask_file("開啟曲包", [("Rhyculator 曲包", "*.zip"), ("舊版譜面", "*.lanes.json")]) + if path: + self.open_path(path) + + def save(self, ask=False): + if not self.pack: + self.convert_to_pack() + return + self.pack.sync_timing() + errors = validate_pack(self.pack) + if errors: + self.say("無法存檔:" + ";".join(errors[:3]) + ("…" if len(errors) > 3 else "") + "(I 編輯曲包資訊)") + return + path = self.pack.path + if ask or not path: + path = self.ask_file("儲存曲包", [("Rhyculator 曲包", "*.zip")], save=True, + initial=f"{self.pack.config.get('id') or 'song'}.zip") + if not path: + return + try: + save_pack(self.pack, path) + except Exception as e: + self.say(f"存檔失敗:{e}") + return + self.dirty = False + self.say(f"已儲存 {os.path.basename(path)}") + + def convert_to_pack(self): + """舊版 lanes / 匯入的譜面 → 曲包:補上封面與 config""" + image = self.ask_file("選擇封面圖片(會裁成正方形)", [("Image", "*.png *.jpg *.jpeg *.webp")]) + if not image: + return + pack = SongPack(default_config(bpm=self.chart.bpm, beat_offset=self.chart.offset)) + pack.set_music(self.chart.audio) + pack.set_image(image) + pack.charts[self.diff] = self.chart + self.set_pack(pack, self.diff) + if self.edit_config("新曲包資訊"): + self.save(ask=True) + + def update_caption(self): + where = self.pack.path if self.pack and self.pack.path else (self.chart_path or "") + pygame.display.set_caption(("* " if self.dirty else "") + "Rhyculator Maker" + (f" — {where}" if where else "")) + + def confirm_discard(self): + """有未存檔的修改時詢問;回傳 True 表示可以繼續(已存檔或放棄修改)""" + if not self.dirty: + return True + from tkinter import messagebox + root, _, _ = self._dialog() + ans = messagebox.askyesnocancel("尚未存檔", "有尚未存檔的修改,要先存檔嗎?", parent=root) + root.destroy() + if ans is None: + return False + if ans: + self.save() + return not self.dirty + return True + + def reopen_launcher(self): + """回到啟動視窗:開啟其他曲包或建立新曲包""" + if not self.confirm_discard(): + return + from launcher import run_launcher + res = run_launcher() + if not res: + return + kind, value = res + if kind == "open": + self.open_path(value) + else: + self.set_pack(value) + self.say(f"已建立新曲包 {os.path.basename(value.path)}") + + def dialog_import(self): + path = self.ask_file("匯入 osu 譜面", [("osu!", "*.osu")]) + if not path: + return + from importers import import_osu + try: + chart = import_osu(path) + except Exception as e: + self.say(f"匯入失敗:{e}") + return + if self.pack: + # 匯入到目前難度,沿用曲包的 BPM / 第一拍 + self.push_undo() + self.chart.notes = chart.notes + self.changed() + self.say(f"已匯入 {len(chart.notes)} 顆到 {self.diff}") + return + chart.audio = os.path.join(os.path.dirname(path), chart.audio) + self.pack = None + self.chart = chart + self.chart_path = None + self.load_audio(chart.audio) + self.undo_stacks.clear() + self.changed() + self.say(f"已匯入 {len(chart.notes)} 顆,Ctrl+S 會建立曲包") + + def dialog_export(self): + unplaced = sum(1 for n in self.chart.notes if not n.placed()) + if unplaced: + self.say(f"還有 {unplaced} 顆未配置座標,請先到座標分頁按 Shift+A") + return + path = self.ask_file("匯出遊戲譜面(現行格式)", [("Rhyculator sheet", "*.json")], save=True, + initial=f"sheet_{DIFFS.index(self.diff) + 1}.json" if self.pack else "sheet.json") + if path: + self.chart.export_sheet_file(path) + self.say(f"已匯出 {len(self.chart.notes)} 顆 → {os.path.basename(path)}" + + (f"(注意:{len(self.issues)} 個問題)" if self.issues else "")) + + def set_bpm(self, bpm): + self.chart.bpm = bpm + if self.pack: + self.pack.config["bpm"] = bpm + self.pack.sync_timing() + self.dirty = True + + def set_beat_offset(self, ms): + self.chart.offset = ms + if self.pack: + self.pack.config["beat_offset"] = ms + self.pack.sync_timing() + self.dirty = True + + # ---------- 座標換算 ---------- + def y_of(self, t): + return JUDGE_Y - (t - self.now()) * self.zoom + + def t_of(self, y): + return self.now() + (JUDGE_Y - y) / self.zoom + + def lane_at(self, x): + for lane in LANE_ORDER: + if lane_x(lane) <= x < lane_x(lane) + LANE_W: + return lane + return None + + def note_at_mouse(self, x, y): + lane = self.lane_at(x) + if not lane: + return None + return self.chart.note_at(lane, self.t_of(y), 10 / self.zoom) + + # ---------- 編輯 ---------- + def add_note(self, lane, t0, t1, shift): + t0, t1 = self.chart.snap(t0), self.chart.snap(t1) + if t1 < t0: + t0, t1 = t1, t0 + self.push_undo() + if t1 - t0 >= self.chart.beat_ms / self.chart.divisor * 0.9: + note = Note(t0, lane, "slide" if shift else "hold", t1) + else: + note = Note(t0, lane, "tap") + self.chart.add(note) + self.selected = note + self.changed() + + def delete(self, note): + if note in self.chart.notes: + self.push_undo() + self.chart.notes.remove(note) + if self.selected is note: + self.selected = None + self.changed() + + def move_selected(self, steps): + n = self.selected + if not n: + return + self.push_undo() + d = self.chart.beat_ms / self.chart.divisor * steps + n.t = self.chart.snap(n.t + d) + if n.end is not None: + n.end = self.chart.snap(n.end + d) + self.changed() + + def set_lane(self, lane): + n = self.selected + if not n or n.lane == lane: + return + self.push_undo() + n.lane = lane + # 原座標若不在新區域就清掉 + cells = n.path if n.type == "slide" else ([n.pos] if n.pos else []) + if any(not cell_allowed(lane, n.type, x, y) for x, y in cells): + n.pos, n.path, n.locked = None, None, False + self.changed() + + def click_cell(self, x, y, shift): + n = self.selected + if not n: + self.say("先在左邊時間軸點選一顆音符") + return + if not cell_allowed(n.lane, n.type, x, y): + self.say(f"({x},{y}) 不在 {n.lane} 軌可用的區域") + return + self.push_undo() + if n.type == "slide": + if shift and n.path: + n.path = n.path + [(x, y)] + else: + n.path = [(x, y)] + else: + n.pos = (x, y) + n.locked = True + self.changed() + + def auto(self, only_unplaced): + self.push_undo() + auto_place(self.chart, seed=1, only_unplaced=only_unplaced) + self.changed() + self.say(f"自動配置完成,{len(self.issues)} 個問題") + + def finish_recording(self): + if not self.recorded: + return + self.push_undo() + added = 0 + for lane, t in self.recorded: + st = self.chart.snap(t) + if not any(n.lane == lane and n.t == st for n in self.chart.notes): + self.chart.notes.append(Note(st, lane, "tap")) + added += 1 + self.recorded = [] + self.changed() + self.say(f"錄製完成:新增 {added} 顆(已吸附到 1/{self.chart.divisor} 拍)") + + def toggle_play(self): + if not self.player: + return + if self.player.playing: + self.player.toggle() + self.time_ms = self.player.position_ms() + if self.recording: + self.finish_recording() + else: + self.player.seek(self.time_ms) + self.player.toggle() + + # ---------- 事件 ---------- + def handle(self, e): + mods = pygame.key.get_mods() + ctrl = mods & pygame.KMOD_CTRL + shift = mods & pygame.KMOD_SHIFT + + if e.type == pygame.MOUSEWHEEL: + if ctrl: + self.zoom = max(0.05, min(1.5, self.zoom * (1.15 if e.y > 0 else 1 / 1.15))) + else: + step = self.chart.beat_ms / self.chart.divisor + self.seek(self.chart.snap(self.now() + e.y * step * 2)) + return + + if e.type == pygame.KEYDOWN: + k = e.key + if ctrl: + if k == pygame.K_z: self.undo() + elif k == pygame.K_s: self.save(ask=bool(shift)) + elif k == pygame.K_o: self.reopen_launcher() + elif k == pygame.K_i: self.dialog_import() + elif k == pygame.K_e: self.dialog_export() + return + if self.recording and self.player and self.player.playing and k in (pygame.K_f, pygame.K_j, pygame.K_SPACE): + lane = {pygame.K_f: "L", pygame.K_j: "R", pygame.K_SPACE: "M"}[k] + self.recorded.append((lane, self.player.position_ms())) + return + if k in (pygame.K_SPACE, pygame.K_RETURN): self.toggle_play() + elif k == pygame.K_TAB: self.tab = "pos" if self.tab == "chart" else "chart" + elif k == pygame.K_h: self.show_help = not self.show_help + elif k == pygame.K_i: self.edit_config() + elif k == pygame.K_LEFTBRACKET: self.chart.divisor = max(1, self.chart.divisor // 2) + elif k == pygame.K_RIGHTBRACKET: self.chart.divisor = min(16, self.chart.divisor * 2) + elif k in (pygame.K_F1, pygame.K_F2, pygame.K_F3) and self.player and hasattr(self.player, "speed"): + self.player.speed = {pygame.K_F1: 0.5, pygame.K_F2: 0.75, pygame.K_F3: 1.0}[k] + elif k == pygame.K_k and self.player and hasattr(self.player, "hitsound"): + self.player.hitsound = not self.player.hitsound + elif k == pygame.K_r: + self.recording = not self.recording + if not self.recording: + self.finish_recording() + self.say("錄製模式:播放後按 F / 空白 / J" if self.recording else "錄製模式關閉") + elif k == pygame.K_b: + v = self.dialog_number("BPM", "BPM:", self.chart.bpm, True) + if v: self.set_bpm(v) + elif k == pygame.K_o: + v = self.dialog_number("第一拍", "第一拍時間(ms):", self.chart.offset, False) + if v is not None: self.set_beat_offset(v) + elif k == pygame.K_UP: self.move_selected(1) + elif k == pygame.K_DOWN: self.move_selected(-1) + elif k in (pygame.K_1, pygame.K_2, pygame.K_3): + self.set_lane({pygame.K_1: "L", pygame.K_2: "M", pygame.K_3: "R"}[k]) + elif k in (pygame.K_DELETE, pygame.K_BACKSPACE) and self.selected: + self.delete(self.selected) + elif k == pygame.K_a and self.tab == "pos": + self.auto(only_unplaced=bool(shift)) + elif k == pygame.K_u and self.selected: + self.push_undo() + self.selected.locked = False + self.changed() + return + + if e.type == pygame.MOUSEBUTTONDOWN and e.button in (1, 3): + x, y = e.pos + # 難度下拉(只列啟用的難度) + if self.pack and self.dropdown_open: + self.dropdown_open = False + for d, r in zip(self.pack.enabled(), self.dropdown_items()): + if r.collidepoint(x, y): + self.switch_diff(d) + return + if self.pack and pygame.Rect(DD_RECT).collidepoint(x, y): + self.dropdown_open = True + return + # 右側難度勾選列 + if self.pack and e.button == 1: + for d, box, lv in self.diff_bar_rects(): + if box.collidepoint(x, y): + self.toggle_diff(d) + return + if lv.collidepoint(x, y) and d in self.pack.charts: + self.edit_diff_num(d) + return + # 分頁按鈕 + if y < TOP: + if TAB_X <= x < TAB_X + 96: self.tab = "chart" + elif TAB_X + 96 <= x < TAB_X + 192: self.tab = "pos" + return + if self.tab == "pos" and x >= PANEL_X: + for cx in range(COLS): + for cy in range(ROWS): + if cell_rect(cx, cy).collidepoint(x, y) and e.button == 1: + self.click_cell(cx, cy, bool(shift)) + return + lane = self.lane_at(x) + if not lane: + return + hit = self.note_at_mouse(x, y) + if e.button == 3: + if hit and self.tab == "chart": + self.delete(hit) + return + if hit: + self.selected = hit + return + if self.tab == "chart": + self.drag = (lane, self.t_of(y), bool(shift)) + return + + if e.type == pygame.MOUSEBUTTONUP and e.button == 1 and self.drag: + lane, t0, sh = self.drag + self.drag = None + self.add_note(lane, t0, self.t_of(e.pos[1]), sh) + + # ---------- 繪製 ---------- + def text(self, s, pos, color=C_TEXT, font=None): + img = (font or self.font).render(s, True, color) + self.screen.blit(img, pos) + return img.get_width() + + def dropdown_items(self): + return [pygame.Rect(DD_RECT[0], TOP + i * 36, 220, 34) for i in range(len(self.pack.enabled()))] + + def diff_bar_rects(self): + """[(難度, 勾選框, Lv 文字區)]""" + out = [] + for i, d in enumerate(DIFFS): + x = PANEL_X + 80 + i * 200 + out.append((d, pygame.Rect(x, DIFF_BAR_Y, 110, 28), pygame.Rect(x + 112, DIFF_BAR_Y, 70, 28))) + return out + + def draw_diff_bar(self): + if not self.pack: + return + self.text("難度", (PANEL_X + 20, DIFF_BAR_Y + 3), C_DIM) + for d, box, lv in self.diff_bar_rects(): + on = d in self.pack.charts + mark = pygame.Rect(box.x, box.y + 4, 20, 20) + pygame.draw.rect(self.screen, C_JUDGE if on else (90, 90, 100), mark, 0 if on else 2, border_radius=4) + if on: + pygame.draw.lines(self.screen, (30, 30, 36), False, + [(mark.x + 4, mark.y + 10), (mark.x + 8, mark.y + 15), (mark.x + 16, mark.y + 5)], 3) + self.text(d, (box.x + 28, box.y + 3), C_TEXT if on else C_DIM) + if on: + num = self.pack.config.get(f"{d}_num") + pygame.draw.rect(self.screen, (48, 48, 60), lv, border_radius=6) + self.text(f"Lv.{num}" if num else "Lv.?", (lv.x + 10, lv.y + 3), C_TEXT if num else C_ERR) + pygame.draw.line(self.screen, (60, 60, 70), (PANEL_X + 10, DIFF_BAR_Y + 38), (W - 10, DIFF_BAR_Y + 38)) + + def toggle_diff(self, d): + p = self.pack + if d in p.charts: + if len(p.enabled()) == 1: + self.say("至少要保留一個難度") + return + n = len(p.charts[d].notes) + if n and not self.confirm("停用難度", f"{d} 有 {n} 顆音符,停用後存檔就會刪除這個難度。確定要停用嗎?"): + return + p.disable(d) + self.undo_stacks.pop(d, None) + if self.diff == d: + self.switch_diff(p.enabled()[0]) + self.dirty = True + self.say(f"已停用 {d}(存檔後生效)") + else: + num = self.dialog_number("難度數字", f"{d} 的難度數字(1~99):", None, False) + if num is None: + return + if not 1 <= num <= 99: + self.say("難度數字需為 1~99") + return + p.enable(d, num) + self.dirty = True + self.switch_diff(d) + + def edit_diff_num(self, d): + num = self.dialog_number("難度數字", f"{d} 的難度數字(1~99):", self.pack.config.get(f"{d}_num"), False) + if num is not None and 1 <= num <= 99: + self.pack.config[f"{d}_num"] = num + self.dirty = True + + def confirm(self, title, msg): + from tkinter import messagebox + root, _, _ = self._dialog() + ok = messagebox.askyesno(title, msg, parent=root) + root.destroy() + return ok + + def draw_topbar(self): + pygame.draw.rect(self.screen, C_PANEL, (0, 0, W, TOP)) + x = 12 + if self.pack: + r = pygame.Rect(DD_RECT) + pygame.draw.rect(self.screen, (60, 60, 75), r, border_radius=6) + self.text(self.diff, (r.x + 12, r.y + 5)) + self.text("▼", (r.right - 26, r.y + 5), C_DIM) + x = r.right + 10 + title = ("* " if self.dirty else "") + self.title() + while self.font.size(title)[0] > TAB_X - x - 10 and len(title) > 4: + title = title[:-2] + "…" + self.text(title, (x, 11)) + for i, (key, label) in enumerate((("chart", "譜面"), ("pos", "座標"))): + r = pygame.Rect(TAB_X + i * 96, 6, 88, 32) + pygame.draw.rect(self.screen, (70, 70, 85) if self.tab == key else (40, 40, 50), r, border_radius=6) + self.text(label, (r.x + 26, r.y + 5)) + t = self.now() + info = (f"BPM {self.chart.bpm:g} 第一拍 {self.chart.offset}ms 1/{self.chart.divisor} " + f"{int(t // 60000)}:{(t % 60000) / 1000:06.3f}") + if self.player and hasattr(self.player, "speed"): + info += f" {self.player.speed:g}x" + self.text(info, (TAB_X + 200, 11)) + if self.recording: + pygame.draw.circle(self.screen, C_ERR, (W - 90, 22), 8) + self.text("REC", (W - 76, 11), C_ERR) + + def draw_dropdown(self): + if not (self.pack and self.dropdown_open): + return + for d, r in zip(self.pack.enabled(), self.dropdown_items()): + pygame.draw.rect(self.screen, (70, 70, 88) if d == self.diff else (48, 48, 60), r, border_radius=6) + num = self.pack.config.get(f"{d}_num") + self.text(f"{d} {len(self.pack.charts[d].notes)} 顆" + (f" Lv.{num}" if num else ""), (r.x + 12, r.y + 6)) + + def draw_timeline(self): + top, bottom = TOP, H - 30 + t_bottom, t_top = self.t_of(bottom), self.t_of(top) + + # 波形 + if self.wave is not None: + for py in range(top, bottom, 2): + idx = int(self.t_of(py) / 10) + if 0 <= idx < len(self.wave): + w = float(self.wave[idx]) * WAVE_W + pygame.draw.line(self.screen, (60, 90, 110), (WAVE_X + WAVE_W / 2 - w / 2, py), (WAVE_X + WAVE_W / 2 + w / 2, py)) + + # 軌道 + for lane in LANE_ORDER: + pygame.draw.rect(self.screen, C_ZONE[lane], (lane_x(lane), top, LANE_W - 4, bottom - top)) + self.text({"L": "左手", "M": "中", "R": "右手"}[lane], (lane_x(lane) + 40, bottom + 4), C_DIM, self.font_small) + + # 格線 + x0, x1 = LANE_X0, LANE_X0 + 3 * LANE_W - 4 + for t, beat, bar in self.chart.grid_lines(t_bottom, t_top): + y = self.y_of(t) + color = C_LINE_BAR if bar else C_LINE_BEAT if beat else C_LINE_SUB + pygame.draw.line(self.screen, color, (x0, y), (x1, y), 2 if bar else 1) + + # 音符 + problem = {self.chart.notes[i] for i, _ in self.issues} + for n in self.chart.notes: + if n.end_time < t_bottom - 100 or n.t > t_top + 100: + continue + lx = lane_x(n.lane) + 8 + w = LANE_W - 20 + y0, y1 = self.y_of(n.t), self.y_of(n.end_time) + col = C_NOTE[n.type] + if n.type != "tap": + pygame.draw.rect(self.screen, tuple(c // 2 for c in col), (lx + 20, y1, w - 40, y0 - y1), border_radius=6) + pygame.draw.rect(self.screen, col, (lx, y0 - 8, w, 16), border_radius=5) + if n in problem: + pygame.draw.rect(self.screen, C_ERR, (lx - 3, y0 - 11, w + 6, 22), 2, border_radius=6) + if n is self.selected: + pygame.draw.rect(self.screen, C_SEL, (lx - 4, min(y0, y1) - 12, w + 8, abs(y0 - y1) + 24), 2, border_radius=6) + if self.tab == "pos" and not n.placed(): + self.text("?", (lx + w + 2, y0 - 9), C_ERR, self.font_small) + elif self.tab == "pos" and n.locked: + self.text("鎖", (lx + w + 1, y0 - 9), C_DIM, self.font_small) + + # 錄製中的點 + for lane, t in self.recorded: + pygame.draw.circle(self.screen, C_JUDGE, (lane_x(lane) + LANE_W // 2, int(self.y_of(t))), 6) + + # 拖曳預覽 + if self.drag: + lane, t0, sh = self.drag + my = pygame.mouse.get_pos()[1] + y0, y1 = self.y_of(self.chart.snap(t0)), self.y_of(self.chart.snap(self.t_of(my))) + pygame.draw.rect(self.screen, C_SEL, (lane_x(lane) + 8, min(y0, y1) - 8, LANE_W - 20, abs(y0 - y1) + 16), 1) + + pygame.draw.line(self.screen, C_JUDGE, (WAVE_X, JUDGE_Y), (x1, JUDGE_Y), 3) + + def grid_events(self): + """與遊戲相同展開:(hit_time, x, y, note, end_time)""" + for n in self.chart.notes: + if n.type == "slide" and n.path: + iv = (n.end_time - n.t) / max(1, len(n.path) - 1) + for j, (x, y) in enumerate(n.path): + yield n.t + iv * j, x, y, n, n.t + iv * j + elif n.pos: + yield n.t, n.pos[0], n.pos[1], n, n.end_time + + def draw_grid(self): + self.text("5x6 預覽(與遊戲相同的出現時間)", (GRID_X, GRID_Y - 32), C_DIM) + for x in range(COLS): + for y in range(ROWS): + r = cell_rect(x, y) + pygame.draw.rect(self.screen, C_ZONE[lane_of_column(x)], r, border_radius=12) + pygame.draw.rect(self.screen, (90, 90, 100), r, 3, border_radius=12) + + now = self.now() + playing = self.player and getattr(self.player, "playing", False) + sel = self.selected + + # 選取音符可用的區域 + if sel: + for x in allowed_cols(sel.lane, sel.type): + for y in range(ROWS): + pygame.draw.rect(self.screen, (200, 200, 210), cell_rect(x, y), 1, border_radius=12) + + for t, x, y, n, end in self.grid_events(): + if not (t - APPEAR_MS <= now <= end + EXPIRE_MS): + continue + d = now - t + scale = 0.5 if d < -200 else min(1.5, 1 + d / 400) + if n.type == "hold" and t <= now <= end: + scale = 1.0 + r = cell_rect(x, y) + size = int(GRID_CELL * scale) + rr = pygame.Rect(0, 0, size, size) + rr.center = r.center + pygame.draw.rect(self.screen, C_NOTE[n.type], rr, 6, border_radius=12) + + # 選取的音符(暫停時一律顯示) + if sel and not playing: + cells = sel.path if sel.type == "slide" and sel.path else ([sel.pos] if sel.pos else []) + for i, (x, y) in enumerate(cells): + r = cell_rect(x, y) + pygame.draw.rect(self.screen, C_SEL, r.inflate(-14, -14), 4, border_radius=10) + if sel.type == "slide": + self.text(str(i + 1), (r.x + 8, r.y + 4), C_SEL, self.font_small) + for (ax, ay), (bx, by) in zip(cells, cells[1:]): + pygame.draw.line(self.screen, C_NOTE["slide"], cell_rect(ax, ay).center, cell_rect(bx, by).center, 3) + + info_y = GRID_Y + ROWS * (GRID_CELL + GRID_GAP) + 6 + if sel: + where = sel.path if sel.type == "slide" else sel.pos + self.text(f"選取:{sel.lane} 軌 {sel.type} t={sel.t}" + (f"~{sel.end}" if sel.end else "") + + f" 座標 {where}" + (" (已鎖定,U 解除)" if sel.locked else ""), (PANEL_X + 20, info_y), C_TEXT, self.font_small) + + def draw_panel(self): + x = PANEL_X + 20 + y = TOP + 16 + if self.pack: + self.draw_diff_bar() + y = DIFF_BAR_Y + 50 + if self.tab == "pos": + self.draw_grid() + y = GRID_Y + ROWS * (GRID_CELL + GRID_GAP) + 34 + elif self.show_help: + self.text("說明(H 隱藏)", (x, y), C_DIM) + y += 30 + for line in HELP: + self.text(line, (x, y), C_TEXT, self.font_small) + y += 24 + y += 16 + + placed = sum(1 for n in self.chart.notes if n.placed()) + self.text(f"音符 {len(self.chart.notes)}(L {sum(n.lane == 'L' for n in self.chart.notes)} / " + f"M {sum(n.lane == 'M' for n in self.chart.notes)} / R {sum(n.lane == 'R' for n in self.chart.notes)})" + f" 已配置 {placed} 問題 {len(self.issues)}", (x, y), C_ERR if self.issues else C_TEXT) + y += 26 + if self.tab == "chart": + for i, msg in self.issues[:8]: + n = self.chart.notes[i] + self.text(f"t={n.t} {n.lane} {n.type}:{msg}", (x, y), C_ERR, self.font_small) + y += 20 + + def draw(self): + self.screen.fill(C_BG) + self.draw_timeline() + pygame.draw.rect(self.screen, C_PANEL, (PANEL_X, TOP, W - PANEL_X, H - TOP)) + self.draw_panel() + self.draw_topbar() + self.draw_dropdown() + pygame.draw.rect(self.screen, C_PANEL, (0, H - 26, W, 26)) + self.text(self.message, (12, H - 24), C_TEXT, self.font_small) + + def run(self): + running = True + while running: + for e in pygame.event.get(): + if e.type == pygame.QUIT: + running = not self.confirm_discard() + else: + self.handle(e) + self.draw() + pygame.display.flip() + caption = (self.dirty, self.pack.path if self.pack else self.chart_path) + if caption != getattr(self, "_caption", None): + self._caption = caption + self.update_caption() + self.clock.tick(120) + if self.player: + self.player.close() + pygame.quit() + + +def main(): + ap = argparse.ArgumentParser(description="Rhyculator Maker") + ap.add_argument("chart", nargs="?", help="曲包 .zip 或舊版 *.lanes.json") + ap.add_argument("--diff", choices=("easy", "normal", "hard"), help="開啟時的難度(截圖用)") + ap.add_argument("--dropdown", action="store_true", help="截圖時展開難度選單") + ap.add_argument("--no-audio", action="store_true", help="不開音訊裝置") + ap.add_argument("--screenshot", help="不開視窗,輸出一張截圖後結束(測試用)") + ap.add_argument("--tab", default="chart", choices=("chart", "pos")) + ap.add_argument("--time", type=float, default=0, help="截圖時的時間(ms)") + ap.add_argument("--select", type=int, default=-1, help="截圖時選取第幾顆音符") + a = ap.parse_args() + + if a.screenshot: + os.environ["SDL_VIDEODRIVER"] = "dummy" + + # 沒有指定檔案時先開啟動視窗(拖入 / 選擇 zip,或建立新曲包) + new_pack = None + if not a.chart and not a.screenshot: + from launcher import run_launcher + res = run_launcher() + if not res: + return + kind, value = res + if kind == "open": + a.chart = value + else: + new_pack = value + + ed = Editor(a.chart, audio_enabled=not (a.no_audio or a.screenshot)) + if new_pack: + ed.set_pack(new_pack) + ed.say(f"已建立新曲包 {os.path.basename(new_pack.path)},開始製譜吧") + if a.screenshot: + ed.tab = a.tab + if a.diff and ed.pack: + ed.switch_diff(a.diff) + ed.dropdown_open = a.dropdown + ed.seek(a.time) + if 0 <= a.select < len(ed.chart.notes): + ed.selected = ed.chart.notes[a.select] + ed.draw() + pygame.image.save(ed.screen, a.screenshot) + print("saved", a.screenshot) + return + ed.run() + + +if __name__ == "__main__": + main() diff --git a/osu_parse.py b/osu_parse.py new file mode 100644 index 0000000..631b997 --- /dev/null +++ b/osu_parse.py @@ -0,0 +1,52 @@ +"""osu! 譜面(.osu)解析:回傳打擊物件清單,供 importers 使用""" + + +def parse_osu(path): + sections, cur = {}, None + for raw in open(path, encoding="utf-8"): + line = raw.strip() + if not line or line.startswith("//"): + continue + if line.startswith("[") and line.endswith("]"): + cur = line[1:-1] + sections[cur] = [] + elif cur: + sections[cur].append(line) + + diff = dict(l.split(":", 1) for l in sections["Difficulty"]) + slider_mult = float(diff["SliderMultiplier"]) + + timing = [] + for l in sections["TimingPoints"]: + p = l.split(",") + timing.append((float(p[0]), float(p[1]), p[6] == "1" if len(p) > 6 else True)) + + objs = [] + for l in sections["HitObjects"]: + p = l.split(",") + t, typ, sound = int(p[2]), int(p[3]), int(p[4]) + o = {"time": t, "kat": bool(sound & (2 | 8)), "big": bool(sound & 4)} + if typ & 8: # spinner / denden + o["kind"] = "spinner" + o["end"] = int(p[5]) + elif typ & 2: # slider / drumroll + beat, sv = beat_at(timing, t) + length, slides = float(p[7]), int(p[6]) + o["kind"] = "drumroll" + o["end"] = int(t + length / (slider_mult * 100 * sv) * beat * slides) + else: + o["kind"] = "hit" + objs.append(o) + return objs + + +def beat_at(timing, t): + beat, sv = 500.0, 1.0 + for time, val, uninherited in timing: + if time > t: + break + if uninherited: + beat, sv = val, 1.0 + else: + sv = -100.0 / val + return beat, sv diff --git a/pack.py b/pack.py new file mode 100644 index 0000000..93de5f7 --- /dev/null +++ b/pack.py @@ -0,0 +1,269 @@ +"""曲包(.zip)讀寫與驗證 + +.zip +├─ config.json 必要 +├─ easy.json / normal.json / hard.json 至少一個(統一格式:Chart.chart_json) +├─ music.wav|.ogg|.mp3 / video.mp4 至少一個;只有影片時會從影片抽出 music.wav +└─ image.png 必要,正方形 +""" +import json +import os +import re +import shutil +import subprocess +import tempfile +import zipfile + +from chart import Chart + +PACK_FORMAT = 1 +DIFFS = ("easy", "normal", "hard") +MUSIC_NAMES = ("music.wav", "music.ogg", "music.mp3") +VIDEO_NAME = "video.mp4" +IMAGE_NAME = "image.png" +CONFIG_NAME = "config.json" +IMAGE_SIZE = 512 +ALLOWED = {CONFIG_NAME, IMAGE_NAME, VIDEO_NAME, *MUSIC_NAMES, *(f"{d}.json" for d in DIFFS)} + +ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,63}$") +REQUIRED_TEXT = ("id", "name", "artist") +REQUIRED_NUM = ("bpm", "beat_offset", "offset") + + +def default_config(**over): + c = {"format": PACK_FORMAT, "id": "", "name": "", "artist": "", "charter": "", + "bpm": 120.0, "beat_offset": 0, "offset": 0, "preview_start": 0, "preview_length": 15000} + c.update(over) + return c + + +class SongPack: + def __init__(self, config=None): + self.workdir = tempfile.mkdtemp(prefix="rhypack_") + self.config = config or default_config() + self.charts = {} # 難度 → Chart + self.path = None # 對應的 .zip + + # ---------- 檔案位置 ---------- + def file(self, name): + return os.path.join(self.workdir, name) + + @property + def music(self): + for n in MUSIC_NAMES: + if os.path.exists(self.file(n)): + return self.file(n) + return None + + @property + def video(self): + return self.file(VIDEO_NAME) if os.path.exists(self.file(VIDEO_NAME)) else None + + @property + def image(self): + return self.file(IMAGE_NAME) if os.path.exists(self.file(IMAGE_NAME)) else None + + def close(self): + shutil.rmtree(self.workdir, ignore_errors=True) + + # ---------- 難度 ---------- + # 「難度存在」= charts 裡有這個 key(曲包內有該檔案,可以是空譜面) + def enabled(self): + return [d for d in DIFFS if d in self.charts] + + def enable(self, diff, num=None): + self.chart(diff, create=True) + if num is not None: + self.config[f"{diff}_num"] = int(num) + + def disable(self, diff): + self.charts.pop(diff, None) + self.config.pop(f"{diff}_num", None) + + # ---------- 內容 ---------- + def chart(self, diff, create=False): + if diff not in self.charts and create: + self.charts[diff] = Chart(self.music or "", float(self.config["bpm"]), + int(self.config["beat_offset"]), 4, []) + return self.charts.get(diff) + + def sync_timing(self): + """config 的 bpm / beat_offset 套用到各難度(Maker 格線用)""" + for c in self.charts.values(): + c.bpm = float(self.config["bpm"]) + c.offset = int(self.config["beat_offset"]) + c.audio = self.music or "" + + def set_music(self, src): + ext = os.path.splitext(src)[1].lower() + name = f"music{ext}" + if name not in MUSIC_NAMES: + raise ValueError("音訊只支援 wav / ogg / mp3") + for n in MUSIC_NAMES: + if os.path.exists(self.file(n)): + os.remove(self.file(n)) + shutil.copyfile(src, self.file(name)) + self.sync_timing() + + def set_video(self, src): + shutil.copyfile(src, self.file(VIDEO_NAME)) + # 時間以音訊為準:沒有音訊時從影片抽出 + if self.music is None: + extract_audio(self.file(VIDEO_NAME), self.file("music.wav")) + self.sync_timing() + + def set_image(self, src): + import_image(src, self.file(IMAGE_NAME)) + + +# ---------- 讀寫 ---------- + +def open_pack(zip_path): + pack = SongPack() + with zipfile.ZipFile(zip_path) as z: + for info in z.infolist(): + name = info.filename + # 只接受白名單檔名(防止 zip 內的路徑寫到別處) + if name not in ALLOWED: + continue + with z.open(info) as src, open(pack.file(name), "wb") as dst: + shutil.copyfileobj(src, dst) + + if os.path.exists(pack.file(CONFIG_NAME)): + pack.config = default_config(**json.load(open(pack.file(CONFIG_NAME), encoding="utf-8"))) + for d in DIFFS: + p = pack.file(f"{d}.json") + if os.path.exists(p): + pack.charts[d] = Chart.from_chart_json(json.load(open(p, encoding="utf-8")), + pack.config["bpm"], pack.config["beat_offset"], + pack.music or "") + pack.path = zip_path + return pack + + +def save_pack(pack, zip_path): + """驗證通過才寫入;先寫暫存檔再取代,失敗不會弄壞原本的曲包""" + errors = validate_pack(pack) + if errors: + raise ValueError(";".join(errors)) + + pack.config["format"] = PACK_FORMAT + tmp = zip_path + ".tmp" + with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr(CONFIG_NAME, json.dumps(pack.config, ensure_ascii=False, indent=2)) + # 啟用的難度全部寫入(空譜面也寫,代表這個難度存在) + for d in pack.enabled(): + z.writestr(f"{d}.json", json.dumps(pack.charts[d].chart_json(), ensure_ascii=False, indent=1)) + # 音訊 / 影片本身已壓縮或很大,不再壓縮 + for path in (pack.music, pack.video): + if path: + z.write(path, os.path.basename(path), compress_type=zipfile.ZIP_STORED) + z.write(pack.image, IMAGE_NAME, compress_type=zipfile.ZIP_STORED) + os.replace(tmp, zip_path) + pack.path = zip_path + + +def validate_pack(pack): + errors = [] + cfg = pack.config + + for k in REQUIRED_TEXT: + if not str(cfg.get(k, "")).strip(): + errors.append(f"config 缺少 {k}") + if cfg.get("id") and not ID_RE.match(cfg["id"]): + errors.append("id 只能用小寫英數字與 -(2~64 字)") + for k in REQUIRED_NUM: + try: + float(cfg.get(k)) + except (TypeError, ValueError): + errors.append(f"config 的 {k} 必須是數字") + try: + if float(cfg.get("bpm", 0)) <= 0: + errors.append("bpm 必須大於 0") + except (TypeError, ValueError): + pass + + present = pack.enabled() + if not present: + errors.append("至少需要啟用一個難度") + for d in present: + v = cfg.get(f"{d}_num") + if not isinstance(v, int) or not (1 <= v <= 99): + errors.append(f"{d} 有譜面,config 需要 {d}_num(1~99 的整數)") + + if pack.music is None and pack.video is None: + errors.append("至少需要 music 或 video") + if pack.image is None: + errors.append("缺少 image.png") + else: + from PIL import Image + with Image.open(pack.image) as im: + if im.width != im.height: + errors.append(f"image.png 必須是正方形(目前 {im.width}x{im.height})") + return errors + + +# ---------- 媒體 ---------- + +def import_image(src, dst, size=IMAGE_SIZE): + """置中裁成正方形並縮放""" + from PIL import Image + with Image.open(src) as im: + im = im.convert("RGBA") + side = min(im.size) + left, top = (im.width - side) // 2, (im.height - side) // 2 + im = im.crop((left, top, left + side, top + side)).resize((size, size), Image.LANCZOS) + im.save(dst, "PNG") + + +def convert_audio(src, dst, quality=6): + """轉成 Ogg Vorbis(quality 0~10,6 約 192kbps),44.1kHz 雙聲道""" + import imageio_ffmpeg + ffmpeg = imageio_ffmpeg.get_ffmpeg_exe() + subprocess.run([ffmpeg, "-y", "-loglevel", "error", "-i", src, "-vn", "-ac", "2", "-ar", "44100", + "-c:a", "libvorbis", "-q:a", str(quality), dst], check=True) + + +def extract_audio(video, dst): + """用 imageio-ffmpeg 內附的 ffmpeg 抽出 44.1kHz 雙聲道 wav""" + import imageio_ffmpeg + ffmpeg = imageio_ffmpeg.get_ffmpeg_exe() + subprocess.run([ffmpeg, "-y", "-loglevel", "error", "-i", video, "-vn", "-ac", "2", "-ar", "44100", + "-f", "wav", dst], check=True) + + +def create_pack(zip_path, config, media, image, diffs): + """建立新曲包並立即存檔(譜面可為空);diffs = {難度: 難度數字}。回傳已開啟的 SongPack""" + pack = SongPack(default_config(**config)) + try: + if media.lower().endswith(".mp4"): + pack.set_video(media) + else: + pack.set_music(media) + pack.set_image(image) + for d, num in diffs.items(): + pack.enable(d, num) + save_pack(pack, zip_path) + except Exception: + pack.close() + raise + return pack + + +# ---------- 遷移 ---------- + +def pack_from_lanes(lanes_by_diff, image_src, **config): + """把舊的 *.lanes.json(每難度一份)轉成曲包;音訊取第一份的 audio""" + pack = SongPack() + first = None + for d, path in lanes_by_diff.items(): + c = Chart.load(path) + if first is None: + first = (c, path) + pack.charts[d] = c + c0, p0 = first + audio = c0.audio if os.path.isabs(c0.audio) else os.path.join(os.path.dirname(p0), c0.audio) + pack.config = default_config(bpm=c0.bpm, beat_offset=c0.offset, **config) + pack.set_music(audio) + pack.set_image(image_src) + return pack diff --git a/placer.py b/placer.py new file mode 100644 index 0000000..79265e7 --- /dev/null +++ b/placer.py @@ -0,0 +1,123 @@ +"""第二階段:依手的區域把音符自動配置到 5x6 格子 + +規則 +- L 軌只用左手區、R 軌只用右手區、M 軌只用中間欄;slide 可進中間欄但不跨到另一手 +- 每隻手記住自己上一格;間隔越短,下一格只能離上一格越近(同一隻手連打不用大跳) +- 同一格在音符顯示期間(判定前 APPEAR_MS ~ 判定後 EXPIRE_MS)不重複使用 +- M 軌交給「目前空著、且最久沒按」的那隻手 +- locked 的音符保留座標,但仍計入格子與手的佔用 +- 固定亂數種子,結果可重現 +""" +import random + +from zones import COLS, ROWS, APPEAR_MS, EXPIRE_MS, TAP_COLS, SLIDE_COLS +from chart import slide_steps + +CELL_MARGIN = 50 # 格子釋放後再多留一點緩衝(ms),避免掉幀時同格重疊 + + +class HandState: + def __init__(self, start): + self.cell = start + self.last_time = -10**9 # 上一次按下的時間 + self.busy_until = -10**9 # hold / slide 進行中 + + +def assign_hand(note, hands): + """回傳負責這顆音符的手('L' / 'R'),M 軌選空著且最久沒按的手""" + if note.lane in ("L", "R"): + return note.lane + free = [h for h in ("L", "R") if hands[h].busy_until < note.t] + pool = free or ["L", "R"] + return min(pool, key=lambda h: hands[h].last_time) + + +def reach_for(gap): + return 1 if gap < 140 else 2 if gap < 300 else max(COLS, ROWS) + + +class ZonePlacer: + def __init__(self, seed=1): + self.rng = random.Random(seed) + self.cell_free_at = {(x, y): -10**9 for x in range(COLS) for y in range(ROWS)} + self.hands = {"L": HandState((1, 2)), "R": HandState((3, 2))} + + def _free(self, cell, t): + return self.cell_free_at[cell] <= t - APPEAR_MS + + def _occupy(self, cell, t_end): + self.cell_free_at[cell] = t_end + EXPIRE_MS + CELL_MARGIN + + def _pick(self, t, cols, hand): + h = self.hands[hand] + reach = reach_for(t - h.last_time) + lx, ly = h.cell + cells = [(x, y) for x in cols for y in range(ROWS)] + cands = [c for c in cells if c != h.cell and self._free(c, t) + and max(abs(c[0] - lx), abs(c[1] - ly)) <= reach] + if not cands: + cands = [c for c in cells if self._free(c, t)] + if not cands: + cands = [min(cells, key=lambda c: self.cell_free_at[c])] + return self.rng.choice(cands) + + def _path(self, t0, t1, steps, cols, hand): + h = self.hands[hand] + interval = (t1 - t0) / max(1, steps - 1) + start = self._pick(t0, cols, hand) + path = [start] + cur = start + for i in range(1, steps): + t = t0 + interval * i + x, y = cur + nbrs = [(x + dx, y + dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1) + if (dx or dy) and (x + dx) in cols and 0 <= y + dy < ROWS + and (x + dx, y + dy) not in path and self._free((x + dx, y + dy), t)] + # 傾向直線前進,看起來像一筆畫 + if len(path) >= 2: + d = (path[-1][0] - path[-2][0], path[-1][1] - path[-2][1]) + straight = (x + d[0], y + d[1]) + if straight in nbrs and self.rng.random() < 0.6: + nbrs = [straight] + if not nbrs: + break + cur = self.rng.choice(nbrs) + path.append(cur) + return path + + def _commit(self, note, hand): + h = self.hands[hand] + if note.type == "slide": + k = len(note.path) + interval = (note.end_time - note.t) / max(1, k - 1) + for i, c in enumerate(note.path): + self._occupy(c, note.t + interval * i) + h.cell = note.path[-1] + else: + self._occupy(note.pos, note.end_time) + h.cell = note.pos + h.last_time = note.end_time if note.type != "tap" else note.t + if note.type != "tap": + h.busy_until = note.end_time + + def place(self, chart, only_unplaced=False): + """配置 chart 內所有未鎖定的音符(only_unplaced=True 時只配置還沒有座標的)""" + chart.sort() + for note in chart.notes: + hand = assign_hand(note, self.hands) + keep = note.locked or (only_unplaced and note.placed()) + if not keep: + if note.type == "slide": + steps = slide_steps(chart, note) + note.path = self._path(note.t, note.end_time, steps, SLIDE_COLS[note.lane], hand) + note.pos = None + else: + note.pos = self._pick(note.t, TAP_COLS[note.lane], hand) + note.path = None + if note.placed(): + self._commit(note, hand) + return chart + + +def auto_place(chart, seed=1, only_unplaced=False): + return ZonePlacer(seed).place(chart, only_unplaced) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..5f91c31 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +pygame-ce>=2.4 +numpy +miniaudio +sounddevice +Pillow +imageio-ffmpeg +tkinterdnd2 +pytest diff --git a/run.bat b/run.bat new file mode 100644 index 0000000..69b197d --- /dev/null +++ b/run.bat @@ -0,0 +1 @@ +.venv\Scripts\python maker.py %* diff --git a/tests/test_maker.py b/tests/test_maker.py new file mode 100644 index 0000000..9f1a604 --- /dev/null +++ b/tests/test_maker.py @@ -0,0 +1,224 @@ +import os +import sys + +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "..")) + +from chart import Chart, Note, slide_steps # noqa: E402 +from placer import auto_place # noqa: E402 +from validate import validate # noqa: E402 +from zones import TAP_COLS, SLIDE_COLS # noqa: E402 + +BPM = 120.0 # 1 拍 = 500 ms + + +def make(notes, divisor=4): + c = Chart("", BPM, 1000, divisor, notes) + c.sort() + return c + + +# ---------- 格線 ---------- + +def test_snap_to_grid(): + c = make([]) + assert c.snap(1000) == 1000 + assert c.snap(1120) == 1125 # 1/4 拍 = 125 ms + assert c.snap(1060) == 1000 + assert c.snap(1063, divisor=8) == 1062 or c.snap(1063, divisor=8) == 1063 + + +def test_grid_lines_mark_beats_and_bars(): + c = make([]) + lines = c.grid_lines(1000, 3000) + assert lines[0] == (1000, True, True) + assert sum(1 for _, beat, _ in lines if beat) == 5 # 1000..3000 每 500ms + assert sum(1 for _, _, bar in lines if bar) == 2 # 1000、3000 + + +# ---------- 自動配置的區域限制 ---------- + +def dense_chart(): + notes = [] + t = 1000 + for i in range(200): + notes.append(Note(t, "LRM"[i % 3], "tap")) + t += 125 + notes.append(Note(t + 500, "L", "hold", t + 1500)) + notes.append(Note(t + 2000, "R", "slide", t + 3000)) + notes.append(Note(t + 4000, "L", "slide", t + 5000)) + return make(notes) + + +def test_auto_place_respects_zones(): + c = auto_place(dense_chart()) + for n in c.notes: + if n.type == "slide": + assert all(x in SLIDE_COLS[n.lane] for x, _ in n.path) + assert len(n.path) >= 2 + else: + assert n.pos[0] in TAP_COLS[n.lane] + assert validate(c) == [] + + +def test_slide_never_crosses_to_other_hand(): + c = auto_place(dense_chart()) + for n in c.notes: + if n.type == "slide" and n.lane == "L": + assert max(x for x, _ in n.path) <= 2 + if n.type == "slide" and n.lane == "R": + assert min(x for x, _ in n.path) >= 2 + + +def test_auto_place_is_deterministic_and_keeps_locked(): + a = auto_place(dense_chart(), seed=7) + b = dense_chart() + b.notes[10].pos, b.notes[10].locked = (0, 5) if b.notes[10].lane == "L" else (2, 5) if b.notes[10].lane == "M" else (4, 5), True + locked = b.notes[10].pos + auto_place(b, seed=7) + assert b.notes[10].pos == locked + assert [n.pos for n in auto_place(dense_chart(), seed=7).notes] == [n.pos for n in a.notes] + + +# ---------- 檢查 ---------- + +def test_validate_zone_violation_and_overlap(): + c = make([Note(1000, "L", "tap", pos=(4, 0)), # 左手放到右手區 + Note(2000, "R", "tap", pos=(3, 0)), + Note(2300, "R", "tap", pos=(3, 0))]) # 同格 300ms 內重複 + msgs = [m for _, m in validate(c)] + assert any("不在 L 軌" in m for m in msgs) + assert any("重疊" in m for m in msgs) + + +def test_validate_same_hand_simultaneous(): + c = make([Note(1000, "L", "hold", 2000, pos=(0, 0)), + Note(1500, "L", "tap", pos=(1, 5))]) # 左手 hold 中又按 + assert any("左手同時" in m for _, m in validate(c)) + + c2 = make([Note(1000, "L", "hold", 2000, pos=(0, 0)), + Note(1000, "R", "hold", 2000, pos=(4, 0)), + Note(1500, "M", "tap", pos=(2, 3))]) # 兩手都忙 + assert any("沒有空著的手" in m for _, m in validate(c2)) + + c3 = make([Note(1000, "L", "hold", 2000, pos=(0, 0)), + Note(1500, "M", "tap", pos=(2, 3))]) # 右手空著 → 合法 + assert validate(c3) == [] + + +# ---------- 匯出 ---------- + +def test_export_sheet_matches_game_format(): + c = make([Note(1000, "L", "tap", pos=(1, 2)), + Note(2000, "R", "hold", 2500, pos=(3, 1)), + Note(3000, "L", "slide", 3500, path=[(0, 0), (1, 1), (2, 2)])]) + sheet = c.export_sheet() + assert sheet[0] == {"type": "tap", "startTime": 1000, "pos": {"x": 1, "y": 2}} + assert sheet[1] == {"type": "hold", "startTime": 2000, "endTime": 2500, "pos": {"x": 3, "y": 1}} + s = sheet[2] + # 遊戲把第 i 格放在 start + i*(end-start)/len:最後一格應落在 3500 + last_hit = s["startTime"] + (s["endTime"] - s["startTime"]) / len(s["path"]) * (len(s["path"]) - 1) + assert last_hit == pytest.approx(3500) + + +def test_save_load_roundtrip(tmp_path): + c = auto_place(dense_chart()) + c.notes[0].locked = True + p = tmp_path / "x.lanes.json" + c.save(p) + d = Chart.load(p) + assert d.bpm == c.bpm and d.offset == c.offset and len(d.notes) == len(c.notes) + assert [(n.t, n.lane, n.type, n.pos, n.path, n.locked) for n in d.notes] == \ + [(n.t, n.lane, n.type, n.pos, n.path, n.locked) for n in c.notes] + + +def test_slide_steps_follow_divisor(): + c = make([]) + assert slide_steps(c, Note(1000, "L", "slide", 1500)) == 5 # 500ms / 125ms + 1 + + +# ---------- osu 匯入(有 osu 檔時才跑)---------- + +OSU_DIR = os.environ.get("RHY_OSU_DIR") + + +@pytest.mark.skipif(not OSU_DIR, reason="設定 RHY_OSU_DIR 指向解壓的 osu 譜面資料夾") +def test_import_taiko_keeps_all_objects(): + import glob + from importers import import_osu + from osu_parse import parse_osu + for f in glob.glob(os.path.join(OSU_DIR, "*.osu")): + c = import_osu(f) + assert len(c.notes) == len(parse_osu(f)) + auto_place(c) + assert validate(c) == [], f + + +# ---------- 編輯器操作(無視窗)---------- + +@pytest.fixture +def editor(): + os.environ["SDL_VIDEODRIVER"] = "dummy" + import pygame + from maker import Editor + ed = Editor(audio_enabled=False) + ed.chart = Chart("", BPM, 0, 4, []) + yield ed + pygame.quit() + + +def _click(ed, x, y, button=1, up_y=None, shift=False): + import pygame + pygame.key.set_mods(pygame.KMOD_SHIFT if shift else 0) + ed.handle(pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos=(x, y), button=button)) + if button == 1: + ed.handle(pygame.event.Event(pygame.MOUSEBUTTONUP, pos=(x, up_y if up_y is not None else y), button=1)) + pygame.key.set_mods(0) + + +def test_editor_place_tap_hold_slide_and_undo(editor): + from maker import lane_x, JUDGE_Y, LANE_W + ed = editor + ed.time_ms = 0 + # 判定線上方 125ms 處點一下 → L 軌 tap + y = JUDGE_Y - 125 * ed.zoom + _click(ed, lane_x("L") + LANE_W // 2, y) + assert [(n.lane, n.type, n.t) for n in ed.chart.notes] == [("L", "tap", 125)] + + # R 軌往上拖 500ms → hold + _click(ed, lane_x("R") + LANE_W // 2, JUDGE_Y - 500 * ed.zoom, up_y=JUDGE_Y - 1000 * ed.zoom) + hold = [n for n in ed.chart.notes if n.lane == "R"][0] + assert (hold.type, hold.t, hold.end) == ("hold", 500, 1000) + + # Shift + 拖曳 → slide + _click(ed, lane_x("M") + LANE_W // 2, JUDGE_Y - 1500 * ed.zoom, up_y=JUDGE_Y - 2000 * ed.zoom, shift=True) + assert any(n.type == "slide" and n.lane == "M" for n in ed.chart.notes) + + # 右鍵刪除 tap,再復原 + _click(ed, lane_x("L") + LANE_W // 2, y, button=3) + assert not any(n.lane == "L" for n in ed.chart.notes) + ed.undo() + assert any(n.lane == "L" for n in ed.chart.notes) + + +def test_editor_assign_cell_respects_zone(editor): + from maker import cell_rect + ed = editor + note = ed.chart.add(Note(1000, "L", "tap")) + ed.tab = "pos" + ed.selected = note + r = cell_rect(4, 0) # 右手區 → 拒絕 + _click(ed, r.centerx, r.centery) + assert note.pos is None + r = cell_rect(1, 3) + _click(ed, r.centerx, r.centery) + assert note.pos == (1, 3) and note.locked + + +def test_editor_recording_snaps(editor): + ed = editor + ed.recorded = [("L", 1010), ("R", 1490), ("M", 2130)] + ed.finish_recording() + assert [(n.lane, n.t) for n in ed.chart.notes] == [("L", 1000), ("R", 1500), ("M", 2125)] diff --git a/tests/test_pack.py b/tests/test_pack.py new file mode 100644 index 0000000..212c6fb --- /dev/null +++ b/tests/test_pack.py @@ -0,0 +1,289 @@ +import json +import os +import subprocess +import sys +import wave +import zipfile + +import numpy as np +import pytest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "..")) + +from chart import Note # noqa: E402 +from pack import (SongPack, default_config, open_pack, save_pack, # noqa: E402 + validate_pack, import_image, extract_audio) + + +# ---------- 測試素材 ---------- + +def write_wav(path, seconds=1.0): + sr = 44100 + t = np.arange(int(sr * seconds)) / sr + data = (np.sin(2 * np.pi * 440 * t) * 8000).astype(np.int16) + with wave.open(str(path), "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(sr) + w.writeframes(data.tobytes()) + return str(path) + + +def write_image(path, size=(800, 600)): + from PIL import Image + Image.new("RGB", size, (200, 80, 120)).save(path) + return str(path) + + +def make_pack(tmp_path): + p = SongPack(default_config(id="test-song", name="Test", artist="Someone", charter="Me", + bpm=120.0, beat_offset=100, easy_num=3, hard_num=12)) + p.set_music(write_wav(tmp_path / "a.wav")) + p.set_image(write_image(tmp_path / "cover.jpg")) + e = p.chart("easy", create=True) + e.notes = [Note(100, "L", "tap", pos=(0, 1)), Note(600, "R", "hold", 900, pos=(4, 2), locked=True)] + h = p.chart("hard", create=True) + h.notes = [Note(100, "M", "tap", pos=(2, 0)), + Note(400, "L", "slide", 800, path=[(0, 0), (1, 1), (2, 2)])] + return p + + +# ---------- 往返 ---------- + +def test_save_open_roundtrip(tmp_path): + p = make_pack(tmp_path) + z = str(tmp_path / "test-song.zip") + save_pack(p, z) + + names = set(zipfile.ZipFile(z).namelist()) + assert names == {"config.json", "easy.json", "hard.json", "music.wav", "image.png"} # 沒有 normal + + q = open_pack(z) + assert q.config["id"] == "test-song" and q.config["easy_num"] == 3 + assert set(q.charts) == {"easy", "hard"} + + def dump(pack, d): + return [(n.t, n.lane, n.type, n.end, n.pos, n.path, n.locked) for n in pack.charts[d].notes] + for d in ("easy", "hard"): + assert dump(q, d) == dump(p, d) + # 曲目層級的 BPM / 第一拍來自 config + assert q.charts["easy"].bpm == 120.0 and q.charts["easy"].offset == 100 + + +def test_chart_file_is_unified_format(tmp_path): + p = make_pack(tmp_path) + z = str(tmp_path / "x.zip") + save_pack(p, z) + d = json.loads(zipfile.ZipFile(z).read("easy.json")) + assert d["format"] == 1 and d["divisor"] == 4 + assert d["notes"][1] == {"t": 600, "lane": "R", "type": "hold", "end": 900, + "pos": {"x": 4, "y": 2}, "locked": True} + assert "bpm" not in d + + +def test_save_failure_keeps_old_zip(tmp_path): + p = make_pack(tmp_path) + z = str(tmp_path / "x.zip") + save_pack(p, z) + before = open(z, "rb").read() + p.config["name"] = "" + with pytest.raises(ValueError): + save_pack(p, z) + assert open(z, "rb").read() == before + + +def test_open_ignores_unexpected_paths(tmp_path): + z = tmp_path / "evil.zip" + with zipfile.ZipFile(z, "w") as f: + f.writestr("config.json", json.dumps(default_config(id="x1", name="n", artist="a"))) + f.writestr("../escape.txt", "nope") + f.writestr("sub/easy.json", "{}") + q = open_pack(str(z)) + assert not os.path.exists(os.path.join(os.path.dirname(q.workdir), "escape.txt")) + assert q.charts == {} + + +# ---------- 驗證 ---------- + +def test_validate_reports_each_problem(tmp_path): + p = make_pack(tmp_path) + assert validate_pack(p) == [] + + p.config["id"] = "Bad ID" + p.config.pop("hard_num") + p.config["bpm"] = "fast" + errs = " ".join(validate_pack(p)) + assert "id 只能用" in errs and "hard_num" in errs and "bpm" in errs + + q = SongPack(default_config(id="empty", name="n", artist="a")) + errs = " ".join(validate_pack(q)) + assert "至少需要啟用一個難度" in errs and "music 或 video" in errs and "image.png" in errs + + +def test_validate_rejects_non_square_image(tmp_path): + p = make_pack(tmp_path) + from PIL import Image + Image.new("RGB", (300, 200)).save(p.file("image.png")) + assert any("正方形" in e for e in validate_pack(p)) + + +def test_import_image_center_crop(tmp_path): + from PIL import Image + src = tmp_path / "wide.png" + im = Image.new("RGB", (900, 300), (0, 0, 255)) + for x in range(300, 600): # 中間 300x300 為紅色 + for y in range(300): + im.putpixel((x, y), (255, 0, 0)) + im.save(src) + dst = tmp_path / "out.png" + import_image(str(src), str(dst)) + out = Image.open(dst).convert("RGB") + assert out.size == (512, 512) + assert out.getpixel((10, 256)) == (255, 0, 0) and out.getpixel((500, 256)) == (255, 0, 0) + + +# ---------- 只有影片 ---------- + +def test_video_only_extracts_audio(tmp_path): + import imageio_ffmpeg + ff = imageio_ffmpeg.get_ffmpeg_exe() + video = str(tmp_path / "clip.mp4") + subprocess.run([ff, "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=black:s=64x64:d=2", + "-f", "lavfi", "-i", "sine=frequency=440:duration=2", "-shortest", + "-c:v", "libx264", "-c:a", "aac", video], check=True) + + p = SongPack(default_config(id="video-song", name="v", artist="a", normal_num=5)) + p.set_video(video) + assert p.video and p.music and p.music.endswith("music.wav") + with wave.open(p.music) as w: + assert w.getframerate() == 44100 and w.getnchannels() == 2 + assert abs(w.getnframes() / 44100 - 2.0) < 0.1 + + p.set_image(write_image(tmp_path / "c.png", (256, 256))) + p.chart("normal", create=True).notes = [Note(500, "M", "tap", pos=(2, 2))] + z = str(tmp_path / "v.zip") + save_pack(p, z) + assert {"video.mp4", "music.wav"} <= set(zipfile.ZipFile(z).namelist()) + + +# ---------- Maker:難度切換 ---------- + +def test_maker_switch_difficulty_keeps_edits_and_undo(tmp_path): + os.environ["SDL_VIDEODRIVER"] = "dummy" + import pygame + from maker import Editor + p = make_pack(tmp_path) + ed = Editor(audio_enabled=False) + try: + ed.set_pack(p, "easy") + ed.push_undo() + ed.chart.add(Note(1500, "L", "tap")) + ed.switch_diff("normal") # 不存在 → 建立空譜面 + assert ed.chart.notes == [] and "normal" in p.charts + assert ed.undo_stack == [] # undo 各難度獨立 + ed.switch_diff("easy") + assert len(ed.chart.notes) == 3 # 剛剛的編輯還在 + ed.undo() + assert len(ed.chart.notes) == 2 + finally: + pygame.quit() + + +# ---------- 啟用 / 停用難度、空曲包 ---------- + +def test_empty_pack_can_be_saved_and_opened(tmp_path): + from pack import create_pack + z = str(tmp_path / "new.zip") + p = create_pack(z, {"id": "new-song", "name": "N", "artist": "A", "bpm": 150.0, "beat_offset": 0}, + write_wav(tmp_path / "m.wav"), write_image(tmp_path / "c.png"), {"normal": 5, "hard": 11}) + assert p.path == z + names = set(zipfile.ZipFile(z).namelist()) + assert {"normal.json", "hard.json"} <= names and "easy.json" not in names + q = open_pack(z) + assert q.enabled() == ["normal", "hard"] + assert q.charts["normal"].notes == [] and q.config["hard_num"] == 11 + + +def test_disable_removes_difficulty_on_save(tmp_path): + p = make_pack(tmp_path) + z = str(tmp_path / "x.zip") + save_pack(p, z) + p.disable("easy") + save_pack(p, z) # 同一路徑直接覆蓋 + q = open_pack(z) + assert q.enabled() == ["hard"] + assert "easy.json" not in zipfile.ZipFile(z).namelist() and "easy_num" not in q.config + + +def test_at_least_one_difficulty_required(tmp_path): + p = make_pack(tmp_path) + p.disable("easy") + p.disable("hard") + assert any("至少需要啟用一個難度" in e for e in validate_pack(p)) + + +def test_enabled_difficulty_needs_number(tmp_path): + p = make_pack(tmp_path) + p.enable("normal") # 沒給難度數字 + assert any("normal_num" in e for e in validate_pack(p)) + p.enable("normal", 7) + assert validate_pack(p) == [] + + +def test_convert_audio_to_ogg_keeps_length(tmp_path): + from pack import convert_audio + from audio import load_audio + src = write_wav(tmp_path / "a.wav", seconds=3.0) + dst = str(tmp_path / "a.ogg") + convert_audio(src, dst) + assert os.path.getsize(dst) < os.path.getsize(src) + assert abs(len(load_audio(dst)) / 44100 - 3.0) < 0.05 + + +# ---------- 啟動視窗的檢查 ---------- + +def test_launcher_checks(tmp_path): + from launcher import check_open_path, new_pack_errors + assert check_open_path(str(tmp_path / "nope.zip")) == "找不到這個檔案" + assert check_open_path("song.txt") == "請選擇 .zip 曲包" + bad = tmp_path / "bad.zip" + bad.write_text("not a zip") + assert check_open_path(str(bad)) == "這不是有效的 zip 檔" + + ok = {"save_path": str(tmp_path / "s.zip"), "id": "my-song", "name": "N", "artist": "A", "charter": "", + "bpm": "120", "beat_offset": "0", "media": write_wav(tmp_path / "m.wav"), + "image": write_image(tmp_path / "c.png"), "use_easy": False, "use_normal": True, "use_hard": False, + "easy_num": "", "normal_num": "6", "hard_num": ""} + assert new_pack_errors(ok) == [] + errs = new_pack_errors(dict(ok, id="My Song", bpm="x", use_normal=False)) + assert any("ID" in e for e in errs) and any("BPM" in e for e in errs) and any("至少勾選" in e for e in errs) + assert any("normal 的難度數字" in e for e in new_pack_errors(dict(ok, normal_num="0"))) + + +# ---------- Maker:難度勾選列 ---------- + +def test_maker_diff_toggle(tmp_path, monkeypatch): + os.environ["SDL_VIDEODRIVER"] = "dummy" + import pygame + from maker import Editor + p = make_pack(tmp_path) + ed = Editor(audio_enabled=False) + try: + ed.set_pack(p, "hard") + monkeypatch.setattr(ed, "dialog_number", lambda *a: 8) + monkeypatch.setattr(ed, "confirm", lambda *a: True) + ed.toggle_diff("normal") # 啟用 normal → 切過去 + assert ed.diff == "normal" and p.config["normal_num"] == 8 + ed.toggle_diff("hard") # 停用目前以外的難度 + assert "hard" not in p.charts + ed.toggle_diff("normal") # 停用目前難度 → 自動切到 easy + assert ed.diff == "easy" and p.enabled() == ["easy"] + ed.toggle_diff("easy") # 最後一個不能停用 + assert p.enabled() == ["easy"] + # 點擊勾選列也能操作 + d, box, lv = ed.diff_bar_rects()[2] + ed.handle(pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos=box.center, button=1)) + assert "hard" in p.charts + finally: + pygame.quit() diff --git a/validate.py b/validate.py new file mode 100644 index 0000000..6b5fa45 --- /dev/null +++ b/validate.py @@ -0,0 +1,101 @@ +"""譜面檢查:未配置、區域違規、越界、同格顯示重疊、同一隻手同時按壓 + +用法(CLI):python validate.py chart.lanes.json +""" +import sys + +from zones import COLS, ROWS, APPEAR_MS, EXPIRE_MS, cell_allowed + + +def _events(chart): + """與遊戲 MusicPlayer 相同的展開方式:(hit_time, x, y, 結束時間, 音符 index)""" + ev = [] + for i, n in enumerate(chart.notes): + if n.type == "slide" and n.path: + k = len(n.path) + iv = (n.end_time - n.t) / max(1, k - 1) + ev += [(n.t + iv * j, x, y, n.t + iv * j, i) for j, (x, y) in enumerate(n.path)] + elif n.pos is not None: + ev.append((n.t, n.pos[0], n.pos[1], n.end_time, i)) + ev.sort() + return ev + + +def validate(chart): + """回傳 [(音符 index, 訊息)],空串列表示沒有問題""" + issues = [] + chart.sort() + + for i, n in enumerate(chart.notes): + if not n.placed(): + issues.append((i, "尚未配置座標")) + continue + cells = n.path if n.type == "slide" else [n.pos] + for x, y in cells: + if not (0 <= x < COLS and 0 <= y < ROWS): + issues.append((i, f"座標超出範圍 ({x},{y})")) + elif not cell_allowed(n.lane, n.type, x, y): + issues.append((i, f"({x},{y}) 不在 {n.lane} 軌可用的區域")) + if n.type in ("hold", "slide") and (n.end is None or n.end <= n.t): + issues.append((i, "結束時間必須晚於開始時間")) + if n.type == "slide" and n.path: + for (ax, ay), (bx, by) in zip(n.path, n.path[1:]): + if max(abs(ax - bx), abs(ay - by)) != 1: + issues.append((i, "slide 路徑必須走相鄰格")) + break + + # 同格在顯示期間重疊 + free_at = {} + for t, x, y, end, i in _events(chart): + if (x, y) in free_at and t - APPEAR_MS < free_at[(x, y)]: + issues.append((i, f"({x},{y}) 與前一顆音符顯示重疊")) + free_at[(x, y)] = end + EXPIRE_MS + + # 同一隻手同時按壓(M 交給空著的手) + busy = {"L": [], "R": []} # 每隻手的 (start, end) + + def overlaps(hand, s, e): + return any(not (e < bs or s > be) for bs, be in busy[hand]) + + for i, n in enumerate(chart.notes): + s, e = n.t, n.end_time + if n.lane in ("L", "R"): + if overlaps(n.lane, s, e): + issues.append((i, f"{'左' if n.lane == 'L' else '右'}手同時有兩個按壓")) + busy[n.lane].append((s, e)) + else: + free = [h for h in ("L", "R") if not overlaps(h, s, e)] + if not free: + issues.append((i, "中間欄的音符沒有空著的手")) + else: + busy[free[0]].append((s, e)) + + issues.sort() + return issues + + +def _report(label, c): + found = validate(c) + print(f"{label}: {len(c.notes)} notes, {len(found)} issues") + for i, msg in found[:50]: + print(f" #{i} t={c.notes[i].t} {c.notes[i].lane} {c.notes[i].type}: {msg}") + return len(found) + + +if __name__ == "__main__": + # 用法:python validate.py 曲包.zip | 舊版.lanes.json ... + from chart import Chart + total = 0 + for p in sys.argv[1:]: + if p.lower().endswith(".zip"): + from pack import open_pack, validate_pack + pack = open_pack(p) + for msg in validate_pack(pack): + print(f"{p}: {msg}") + total += 1 + for d, c in pack.charts.items(): + total += _report(f"{p} [{d}]", c) + pack.close() + else: + total += _report(p, Chart.load(p)) + sys.exit(1 if total else 0) diff --git a/zones.py b/zones.py new file mode 100644 index 0000000..824c3ac --- /dev/null +++ b/zones.py @@ -0,0 +1,27 @@ +"""手的區域規則與遊戲共用常數""" + +COLS, ROWS = 5, 6 + +# 與遊戲一致:GridDisplay.AppearLead / NoteJudge.BadWindow +APPEAR_MS = 500 +EXPIRE_MS = 200 + +LANES = ("L", "M", "R") + +# tap / hold 可用欄 +TAP_COLS = {"L": (0, 1), "M": (2,), "R": (3, 4)} +# slide 路徑可用欄:可進中間欄,但不跨到另一隻手的區域 +SLIDE_COLS = {"L": (0, 1, 2), "M": (2,), "R": (2, 3, 4)} + + +def allowed_cols(lane, note_type): + return SLIDE_COLS[lane] if note_type == "slide" else TAP_COLS[lane] + + +def cell_allowed(lane, note_type, x, y): + return 0 <= y < ROWS and x in allowed_cols(lane, note_type) + + +def lane_of_column(x): + """格子屬於哪一軌(用於預覽上色)""" + return "L" if x <= 1 else "R" if x >= 3 else "M"