Rebuild the game as a single code-driven scene with a package-folder pack source
- One empty scene; App builds the canvas, safe-area layout and a shared 5x6 Grid in code. Pages (Intro, Main, Choose, Play, Account, Settings) replace 5 scenes, 5 prefabs and the per-cell spawner/display components. - Packs: the game reads Rhyculator/package/ (with All files access) or the app folder, like a plugged-in USB stick. Zips stay where they are and are extracted to a cache keyed by name/size/mtime; folders are read directly. Scans run every second on a background thread. Old songs/ imports and inbox zips are migrated automatically. - Download packs by 8-char code from the new pack website, or via rhyculator://pack/<code> links; opened/shared zips go into the package folder. - Play: pause/resume/retry, auto-pause on background, combo and progress bar; judging and scoring unchanged. Choose page fits 9:16 screens; empty state, pack delete. Android back key handled everywhere. - Slimming: removed TextMesh Pro, unused 2D/Timeline/VisualScripting/etc. packages and modules, scene template, unused sprites; menu theme wav (20MB) -> ogg (2.3MB). Build profile replaced by explicit settings in BuildAndroid. - Tests: PackLibrary/PackReader/migration/serializer tests (39 passing). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
6d5f66ac6a
commit
ddd5fdc28b
295 files changed
+3854
-82126
No files matched your search
@@ -0,0 +1,25 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
// 延遲校正的計算(純函式,方便測試)
|
||||
public static class CalibrationMath
|
||||
{
|
||||
// 點擊時間對最近一拍的偏差;超出半拍或屬於暖身拍則回傳 false
|
||||
public static bool TryBeatDelta(double tapTime, double firstBeat, double interval, int beatCount, int warmupBeats, out double delta)
|
||||
{
|
||||
delta = 0;
|
||||
int i = (int)System.Math.Round((tapTime - firstBeat) / interval);
|
||||
if (i < warmupBeats || i >= beatCount) return false;
|
||||
delta = tapTime - (firstBeat + i * interval);
|
||||
return System.Math.Abs(delta) < interval / 2;
|
||||
}
|
||||
|
||||
// 中位數(比平均值不受誤觸影響)
|
||||
public static double Median(List<double> values)
|
||||
{
|
||||
if (values == null || values.Count == 0) return 0;
|
||||
var sorted = new List<double>(values);
|
||||
sorted.Sort();
|
||||
int n = sorted.Count;
|
||||
return n % 2 == 1 ? sorted[n / 2] : (sorted[n / 2 - 1] + sorted[n / 2]) / 2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 21855371daac8a148b883bb46c4b43ce
|
||||
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
// 譜面展開後的一個事件(slide 的每一格各是一個事件)
|
||||
public struct ChartEvent
|
||||
{
|
||||
public double hitTime; // 判定時間(秒,已含曲包的 offset)
|
||||
public string type; // tap / hold / slide
|
||||
public int x, y;
|
||||
public int holdMs;
|
||||
}
|
||||
|
||||
// 讀取 Maker 統一格式的譜面:
|
||||
// {"format":1,"divisor":4,"notes":[{"t":1216,"lane":"L","type":"tap","pos":{"x":0,"y":3}}, ...]}
|
||||
// lane / locked 是製譜用的欄位,遊戲忽略;沒有座標、座標超出格子、型別不認識的音符略過並計入 skipped
|
||||
public static class ChartLoader
|
||||
{
|
||||
public const int Columns = 5;
|
||||
public const int Rows = 6;
|
||||
|
||||
public static List<ChartEvent> LoadFile(string path, int offsetMs, out int skipped)
|
||||
=> Parse(File.ReadAllText(path), offsetMs, out skipped);
|
||||
|
||||
public static List<ChartEvent> Parse(string json, int offsetMs, out int skipped)
|
||||
{
|
||||
skipped = 0;
|
||||
var events = new List<ChartEvent>();
|
||||
object root = MiniJson.Parse(json);
|
||||
// 也接受只有 notes 陣列的檔案
|
||||
var notes = MiniJson.AsList(root) ?? MiniJson.AsList(MiniJson.Get(MiniJson.AsObject(root), "notes"));
|
||||
if (notes == null) throw new FormatException("譜面缺少 notes 陣列");
|
||||
double offset = offsetMs / 1000.0;
|
||||
|
||||
foreach (var item in notes)
|
||||
{
|
||||
var n = MiniJson.AsObject(item);
|
||||
if (n == null || !MiniJson.TryGetNumber(n, "t", out double tMs)) { skipped++; continue; }
|
||||
string type = MiniJson.GetString(n, "type", "tap");
|
||||
double t = tMs / 1000.0 + offset;
|
||||
bool hasEnd = MiniJson.TryGetNumber(n, "end", out double endMs);
|
||||
|
||||
if (type == "slide")
|
||||
{
|
||||
var cells = new List<(int x, int y)>();
|
||||
var path = MiniJson.AsList(MiniJson.Get(n, "path"));
|
||||
if (path != null)
|
||||
foreach (var p in path)
|
||||
if (TryCell(MiniJson.AsObject(p), out int cx, out int cy)) cells.Add((cx, cy));
|
||||
if (cells.Count == 0) { skipped++; continue; }
|
||||
|
||||
// 路徑的格子平均分布在 t ~ end:第一格在 t、最後一格在 end
|
||||
double end = hasEnd ? endMs / 1000.0 + offset : t;
|
||||
double interval = cells.Count > 1 ? (end - t) / (cells.Count - 1) : 0;
|
||||
for (int i = 0; i < cells.Count; i++)
|
||||
events.Add(new ChartEvent { hitTime = t + interval * i, type = "slide", x = cells[i].x, y = cells[i].y });
|
||||
}
|
||||
else if (type == "tap" || type == "hold")
|
||||
{
|
||||
if (!TryCell(MiniJson.AsObject(MiniJson.Get(n, "pos")), out int x, out int y)) { skipped++; continue; }
|
||||
int holdMs = type == "hold" && hasEnd ? (int)Math.Max(0, endMs - tMs) : 0;
|
||||
events.Add(new ChartEvent { hitTime = t, type = type, x = x, y = y, holdMs = holdMs });
|
||||
}
|
||||
else skipped++;
|
||||
}
|
||||
|
||||
events.Sort((a, b) => a.hitTime.CompareTo(b.hitTime));
|
||||
return events;
|
||||
}
|
||||
|
||||
private static bool TryCell(Dictionary<string, object> pos, out int x, out int y)
|
||||
{
|
||||
x = y = 0;
|
||||
if (pos == null) return false;
|
||||
if (!MiniJson.TryGetNumber(pos, "x", out double dx) || !MiniJson.TryGetNumber(pos, "y", out double dy)) return false;
|
||||
x = (int)dx;
|
||||
y = (int)dy;
|
||||
return x >= 0 && x < Columns && y >= 0 && y < Rows;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a41b742a3c95c084a8044f32b0692b89
|
||||
@@ -0,0 +1,239 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
// 精簡 JSON 讀取器:物件 → Dictionary<string, object>、陣列 → List<object>、
|
||||
// 數字 → double、字串 → string、true/false → bool、null → null
|
||||
// 曲包譜面的 pos / path / end / locked 都是「可有可無」的欄位,JsonUtility 會把缺少的巢狀物件
|
||||
// 填成預設值,分不出「沒有座標」和「座標 (0,0)」,所以自己解析
|
||||
public static class MiniJson
|
||||
{
|
||||
public static object Parse(string json)
|
||||
{
|
||||
if (json == null) throw new FormatException("JSON 為空");
|
||||
var p = new Parser(json);
|
||||
p.SkipWhitespace();
|
||||
object v = p.ParseValue();
|
||||
p.SkipWhitespace();
|
||||
if (!p.AtEnd) throw p.Error("結尾有多餘的內容");
|
||||
return v;
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> AsObject(object v) => v as Dictionary<string, object>;
|
||||
public static List<object> AsList(object v) => v as List<object>;
|
||||
|
||||
public static object Get(Dictionary<string, object> obj, string key)
|
||||
=> obj != null && obj.TryGetValue(key, out var v) ? v : null;
|
||||
|
||||
public static string GetString(Dictionary<string, object> obj, string key, string fallback = null)
|
||||
=> Get(obj, key) is string s ? s : fallback;
|
||||
|
||||
public static bool TryGetNumber(Dictionary<string, object> obj, string key, out double value)
|
||||
{
|
||||
if (Get(obj, key) is double d) { value = d; return true; }
|
||||
value = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static double GetNumber(Dictionary<string, object> obj, string key, double fallback = 0)
|
||||
=> TryGetNumber(obj, key, out var d) ? d : fallback;
|
||||
|
||||
public static int GetInt(Dictionary<string, object> obj, string key, int fallback = 0)
|
||||
=> TryGetNumber(obj, key, out var d) ? (int)Math.Round(d) : fallback;
|
||||
|
||||
public static bool GetBool(Dictionary<string, object> obj, string key, bool fallback = false)
|
||||
=> Get(obj, key) is bool b ? b : fallback;
|
||||
|
||||
// 輸出 JSON(伺服器請求用):支援 Dictionary、IList、字串、數字、bool、null
|
||||
public static string Serialize(object value)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
Write(sb, value);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static void Write(StringBuilder sb, object v)
|
||||
{
|
||||
switch (v)
|
||||
{
|
||||
case null: sb.Append("null"); break;
|
||||
case string s: WriteString(sb, s); break;
|
||||
case bool b: sb.Append(b ? "true" : "false"); break;
|
||||
case int or long or short: sb.Append(Convert.ToInt64(v).ToString(CultureInfo.InvariantCulture)); break;
|
||||
case float or double: sb.Append(Convert.ToDouble(v).ToString("R", CultureInfo.InvariantCulture)); break;
|
||||
case IDictionary<string, object> d:
|
||||
sb.Append('{');
|
||||
bool first = true;
|
||||
foreach (var kv in d)
|
||||
{
|
||||
if (!first) sb.Append(',');
|
||||
first = false;
|
||||
WriteString(sb, kv.Key);
|
||||
sb.Append(':');
|
||||
Write(sb, kv.Value);
|
||||
}
|
||||
sb.Append('}');
|
||||
break;
|
||||
case System.Collections.IList list:
|
||||
sb.Append('[');
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(',');
|
||||
Write(sb, list[i]);
|
||||
}
|
||||
sb.Append(']');
|
||||
break;
|
||||
default: WriteString(sb, v.ToString()); break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteString(StringBuilder sb, string s)
|
||||
{
|
||||
sb.Append('"');
|
||||
foreach (char c in s)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case '"': sb.Append("\\\""); break;
|
||||
case '\\': sb.Append("\\\\"); break;
|
||||
case '\n': sb.Append("\\n"); break;
|
||||
case '\r': sb.Append("\\r"); break;
|
||||
case '\t': sb.Append("\\t"); break;
|
||||
default:
|
||||
if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4"));
|
||||
else sb.Append(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
sb.Append('"');
|
||||
}
|
||||
|
||||
private class Parser
|
||||
{
|
||||
private readonly string s;
|
||||
private int i;
|
||||
|
||||
public Parser(string s) { this.s = s; }
|
||||
|
||||
public bool AtEnd => i >= s.Length;
|
||||
public FormatException Error(string msg) => new FormatException($"JSON 第 {i} 個字元:{msg}");
|
||||
|
||||
public void SkipWhitespace()
|
||||
{
|
||||
while (i < s.Length && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) i++;
|
||||
}
|
||||
|
||||
public object ParseValue()
|
||||
{
|
||||
if (AtEnd) throw Error("內容不完整");
|
||||
char c = s[i];
|
||||
switch (c)
|
||||
{
|
||||
case '{': return ParseObject();
|
||||
case '[': return ParseArray();
|
||||
case '"': return ParseString();
|
||||
case 't': Expect("true"); return true;
|
||||
case 'f': Expect("false"); return false;
|
||||
case 'n': Expect("null"); return null;
|
||||
default:
|
||||
if (c == '-' || (c >= '0' && c <= '9')) return ParseNumber();
|
||||
throw Error($"無法解析 '{c}'");
|
||||
}
|
||||
}
|
||||
|
||||
private void Expect(string word)
|
||||
{
|
||||
if (string.CompareOrdinal(s, i, word, 0, word.Length) != 0) throw Error($"預期 {word}");
|
||||
i += word.Length;
|
||||
}
|
||||
|
||||
private Dictionary<string, object> ParseObject()
|
||||
{
|
||||
var obj = new Dictionary<string, object>();
|
||||
i++; // {
|
||||
SkipWhitespace();
|
||||
if (i < s.Length && s[i] == '}') { i++; return obj; }
|
||||
while (true)
|
||||
{
|
||||
SkipWhitespace();
|
||||
if (AtEnd || s[i] != '"') throw Error("物件的鍵必須是字串");
|
||||
string key = ParseString();
|
||||
SkipWhitespace();
|
||||
if (AtEnd || s[i] != ':') throw Error("缺少 ':'");
|
||||
i++;
|
||||
SkipWhitespace();
|
||||
obj[key] = ParseValue();
|
||||
SkipWhitespace();
|
||||
if (AtEnd) throw Error("物件未結束");
|
||||
if (s[i] == ',') { i++; continue; }
|
||||
if (s[i] == '}') { i++; return obj; }
|
||||
throw Error("物件內預期 ',' 或 '}'");
|
||||
}
|
||||
}
|
||||
|
||||
private List<object> ParseArray()
|
||||
{
|
||||
var list = new List<object>();
|
||||
i++; // [
|
||||
SkipWhitespace();
|
||||
if (i < s.Length && s[i] == ']') { i++; return list; }
|
||||
while (true)
|
||||
{
|
||||
SkipWhitespace();
|
||||
list.Add(ParseValue());
|
||||
SkipWhitespace();
|
||||
if (AtEnd) throw Error("陣列未結束");
|
||||
if (s[i] == ',') { i++; continue; }
|
||||
if (s[i] == ']') { i++; return list; }
|
||||
throw Error("陣列內預期 ',' 或 ']'");
|
||||
}
|
||||
}
|
||||
|
||||
private string ParseString()
|
||||
{
|
||||
i++; // 開頭的引號
|
||||
var sb = new StringBuilder();
|
||||
while (true)
|
||||
{
|
||||
if (AtEnd) throw Error("字串未結束");
|
||||
char c = s[i++];
|
||||
if (c == '"') return sb.ToString();
|
||||
if (c != '\\') { sb.Append(c); continue; }
|
||||
if (AtEnd) throw Error("字串未結束");
|
||||
char e = s[i++];
|
||||
switch (e)
|
||||
{
|
||||
case '"': sb.Append('"'); break;
|
||||
case '\\': sb.Append('\\'); break;
|
||||
case '/': sb.Append('/'); break;
|
||||
case 'b': sb.Append('\b'); break;
|
||||
case 'f': sb.Append('\f'); break;
|
||||
case 'n': sb.Append('\n'); break;
|
||||
case 'r': sb.Append('\r'); break;
|
||||
case 't': sb.Append('\t'); break;
|
||||
case 'u':
|
||||
if (i + 4 > s.Length) throw Error("\\u 跳脫不完整");
|
||||
sb.Append((char)int.Parse(s.Substring(i, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
|
||||
i += 4;
|
||||
break;
|
||||
default: throw Error($"不支援的跳脫 \\{e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private double ParseNumber()
|
||||
{
|
||||
int start = i;
|
||||
if (s[i] == '-') i++;
|
||||
while (i < s.Length && IsNumberChar(s[i])) i++;
|
||||
string token = s.Substring(start, i - start);
|
||||
if (!double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out double d))
|
||||
throw Error($"數字格式錯誤 '{token}'");
|
||||
return d;
|
||||
}
|
||||
|
||||
private static bool IsNumberChar(char c)
|
||||
=> (c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 756aef3f2685f5641bfea1d649343619
|
||||
@@ -0,0 +1,39 @@
|
||||
// 判定:以「按下時間 - 音符時間」決定結果(秒)
|
||||
// 時間窗沿用舊版以動畫縮放判定時的手感:Perfect ±50ms、Fast/Slow ±130ms、Bad ±200ms
|
||||
public enum Judgement
|
||||
{
|
||||
None, // 不在判定範圍內(太早),不處理
|
||||
Perfect,
|
||||
Fast,
|
||||
Slow,
|
||||
Bad,
|
||||
Miss // 音符過期沒按到
|
||||
}
|
||||
|
||||
public static class NoteJudge
|
||||
{
|
||||
public const double PerfectWindow = 0.050;
|
||||
public const double GreatWindow = 0.130;
|
||||
public const double BadWindow = 0.200;
|
||||
|
||||
public static Judgement Evaluate(double delta)
|
||||
{
|
||||
double abs = System.Math.Abs(delta);
|
||||
if (abs <= PerfectWindow) return Judgement.Perfect;
|
||||
if (abs <= GreatWindow) return delta < 0 ? Judgement.Fast : Judgement.Slow;
|
||||
if (abs <= BadWindow) return Judgement.Bad;
|
||||
return delta > 0 ? Judgement.Miss : Judgement.None;
|
||||
}
|
||||
|
||||
public static int Score(Judgement j)
|
||||
{
|
||||
switch (j)
|
||||
{
|
||||
case Judgement.Perfect: return 212;
|
||||
case Judgement.Fast:
|
||||
case Judgement.Slow: return 159;
|
||||
case Judgement.Bad: return 53;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f85fc10a56e03644bb72ae9bbecbc66d
|
||||
@@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
// 曲包來源:package 資料夾(像插上的隨身碟一樣,裡面有什麼就玩什麼)
|
||||
// package/*.zip 曲包 zip:解壓到快取資料夾再讀取,zip 本身不動
|
||||
// package/<資料夾>/ 已解開的曲包(資料夾內直接有 config.json),直接讀取
|
||||
// 快取以「檔名 + 大小 + 修改時間」區分,zip 被換掉或刪掉時快取跟著更新 / 清除
|
||||
// 不使用 UnityEngine,可在背景執行緒與 EditMode 測試中使用
|
||||
public static class PackLibrary
|
||||
{
|
||||
public class ScanResult
|
||||
{
|
||||
public readonly List<SongInfo> songs = new List<SongInfo>();
|
||||
public readonly List<string> errors = new List<string>(); // 這次新發現的錯誤(同一個檔案只回報一次)
|
||||
public readonly List<SongInfo> added = new List<SongInfo>(); // 和上次相比新出現的曲包
|
||||
public bool changed; // 曲包清單有變
|
||||
public bool pending; // 有檔案還在寫入,晚點再掃
|
||||
}
|
||||
|
||||
// 剛修改過的 zip 可能還在複製中(USB、瀏覽器下載),先跳過
|
||||
public static TimeSpan SettleTime = TimeSpan.FromSeconds(2);
|
||||
|
||||
private static readonly HashSet<string> reported = new HashSet<string>();
|
||||
private static string lastSignature = "";
|
||||
private static HashSet<string> lastSources = null;
|
||||
|
||||
public static ScanResult Scan(string packageDir, string cacheDir)
|
||||
{
|
||||
var r = new ScanResult();
|
||||
Directory.CreateDirectory(packageDir);
|
||||
Directory.CreateDirectory(cacheDir);
|
||||
|
||||
var found = new List<SongInfo>();
|
||||
var usedCache = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var nowReported = new HashSet<string>();
|
||||
|
||||
foreach (var zip in Directory.GetFiles(packageDir, "*.zip"))
|
||||
{
|
||||
var fi = new FileInfo(zip);
|
||||
if (DateTime.UtcNow - fi.LastWriteTimeUtc < SettleTime) { r.pending = true; continue; }
|
||||
|
||||
string key = CacheKey(fi);
|
||||
string dir = Path.Combine(cacheDir, key);
|
||||
usedCache.Add(key);
|
||||
try
|
||||
{
|
||||
SongInfo s = File.Exists(Path.Combine(dir, SongInfo.ConfigName))
|
||||
? SongInfo.FromDir(dir)
|
||||
: PackReader.Extract(zip, dir);
|
||||
s.source = zip;
|
||||
found.Add(s);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Report(r, nowReported, key, $"{fi.Name}:{PackReader.Describe(e)}");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var dir in Directory.GetDirectories(packageDir))
|
||||
{
|
||||
if (!File.Exists(Path.Combine(dir, SongInfo.ConfigName))) continue;
|
||||
string name = Path.GetFileName(dir);
|
||||
try
|
||||
{
|
||||
var s = SongInfo.FromDir(dir);
|
||||
if (s.MusicPath == null) throw new PackReader.PackException("缺少音樂");
|
||||
if (s.FirstLevel() == 0) throw new PackReader.PackException("沒有任何難度的譜面");
|
||||
s.source = dir;
|
||||
found.Add(s);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Report(r, nowReported, "dir:" + dir + Directory.GetLastWriteTimeUtc(dir).Ticks, $"{name}:{PackReader.Describe(e)}");
|
||||
}
|
||||
}
|
||||
|
||||
// 同一個 id 只留最新的來源
|
||||
found.Sort((a, b) => LastWrite(b.source).CompareTo(LastWrite(a.source)));
|
||||
var ids = new Dictionary<string, SongInfo>();
|
||||
foreach (var s in found)
|
||||
{
|
||||
if (ids.TryGetValue(s.id, out var kept))
|
||||
{
|
||||
Report(r, nowReported, "dup:" + s.source, $"{Path.GetFileName(s.source)} 和 {Path.GetFileName(kept.source)} 的 id 相同({s.id}),只使用較新的");
|
||||
continue;
|
||||
}
|
||||
ids[s.id] = s;
|
||||
r.songs.Add(s);
|
||||
}
|
||||
r.songs.Sort((a, b) => string.Compare(a.name, b.name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
// 只保留仍有錯誤的紀錄:檔案修好或刪掉後再壞掉會再回報一次
|
||||
reported.IntersectWith(nowReported);
|
||||
|
||||
// 清掉沒用到的快取
|
||||
foreach (var dir in Directory.GetDirectories(cacheDir))
|
||||
{
|
||||
string name = Path.GetFileName(dir);
|
||||
if (name.EndsWith(".tmp") || !usedCache.Contains(name))
|
||||
{
|
||||
try { Directory.Delete(dir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
var sources = new HashSet<string>();
|
||||
var sig = new System.Text.StringBuilder();
|
||||
foreach (var s in r.songs)
|
||||
{
|
||||
sources.Add(s.source);
|
||||
sig.Append(s.source).Append('|').Append(s.dir).Append('\n');
|
||||
}
|
||||
r.changed = sig.ToString() != lastSignature;
|
||||
if (lastSources != null)
|
||||
foreach (var s in r.songs)
|
||||
if (!lastSources.Contains(s.source)) r.added.Add(s);
|
||||
lastSignature = sig.ToString();
|
||||
lastSources = sources;
|
||||
return r;
|
||||
}
|
||||
|
||||
// 重設「上次掃描」的紀錄(換了 package 資料夾、測試用)
|
||||
public static void ResetState()
|
||||
{
|
||||
reported.Clear();
|
||||
lastSignature = "";
|
||||
lastSources = null;
|
||||
}
|
||||
|
||||
private static void Report(ScanResult r, HashSet<string> nowReported, string key, string message)
|
||||
{
|
||||
nowReported.Add(key);
|
||||
if (reported.Add(key)) r.errors.Add(message);
|
||||
}
|
||||
|
||||
private static DateTime LastWrite(string path)
|
||||
=> File.Exists(path) ? File.GetLastWriteTimeUtc(path) : Directory.GetLastWriteTimeUtc(path);
|
||||
|
||||
// 快取資料夾名稱:檔名(去掉不安全字元)+ 大小與修改時間的雜湊
|
||||
public static string CacheKey(FileInfo fi)
|
||||
{
|
||||
string name = Path.GetFileNameWithoutExtension(fi.Name);
|
||||
var safe = new System.Text.StringBuilder();
|
||||
foreach (char c in name)
|
||||
safe.Append(char.IsLetterOrDigit(c) && c < 128 ? char.ToLowerInvariant(c) : '-');
|
||||
string s = safe.ToString();
|
||||
if (s.Length > 32) s = s.Substring(0, 32);
|
||||
|
||||
ulong h = 14695981039346656037UL; // FNV-1a
|
||||
foreach (char c in $"{fi.Name}|{fi.Length}|{fi.LastWriteTimeUtc.Ticks}")
|
||||
{
|
||||
h ^= c;
|
||||
h *= 1099511628211UL;
|
||||
}
|
||||
return $"{s}-{h:x16}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7ff7d094ad9b04649a25edb101c020e3
|
||||
@@ -0,0 +1,107 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
// 曲包(.zip)檢查與解壓。曲包格式見 RhyculatorMaker 的 README
|
||||
// 不使用 UnityEngine,可在背景執行緒與 EditMode 測試中使用
|
||||
public static class PackReader
|
||||
{
|
||||
public class PackException : Exception
|
||||
{
|
||||
public PackException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
// 只解出這些檔名;zip 內其他東西一律忽略(也避免 zip 內的路徑寫到別處)
|
||||
private static readonly HashSet<string> Allowed = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
SongInfo.ConfigName, SongInfo.ImageName, SongInfo.VideoName,
|
||||
"easy.json", "normal.json", "hard.json",
|
||||
"music.ogg", "music.wav", "music.mp3",
|
||||
};
|
||||
private const long MaxEntryBytes = 512L * 1024 * 1024;
|
||||
|
||||
// 檢查 zip 並解壓到 destDir(先解到暫存資料夾,全部成功才取代 destDir)
|
||||
public static SongInfo Extract(string zipPath, string destDir)
|
||||
{
|
||||
using var fs = File.OpenRead(zipPath);
|
||||
return Extract(fs, destDir);
|
||||
}
|
||||
|
||||
public static SongInfo Extract(Stream zipStream, string destDir)
|
||||
{
|
||||
using var zip = new ZipArchive(zipStream, ZipArchiveMode.Read, leaveOpen: true);
|
||||
var files = Collect(zip, out string configText);
|
||||
|
||||
SongInfo info;
|
||||
try { info = SongInfo.FromConfig(configText, null); }
|
||||
catch (FormatException e) { throw new PackException(e.Message); }
|
||||
|
||||
bool hasChart = false;
|
||||
foreach (var n in SongInfo.LevelNames) if (files.ContainsKey(n + ".json")) hasChart = true;
|
||||
if (!hasChart) throw new PackException("曲包沒有任何難度的譜面");
|
||||
bool hasMusic = false;
|
||||
foreach (var n in SongInfo.MusicNames) if (files.ContainsKey(n)) hasMusic = true;
|
||||
if (!hasMusic) throw new PackException("曲包沒有音樂(music.ogg / wav / mp3)");
|
||||
if (!files.ContainsKey(SongInfo.ImageName)) throw new PackException("曲包沒有封面 image.png");
|
||||
|
||||
string temp = destDir.TrimEnd('/', '\\') + ".tmp";
|
||||
if (Directory.Exists(temp)) Directory.Delete(temp, true);
|
||||
Directory.CreateDirectory(temp);
|
||||
try
|
||||
{
|
||||
foreach (var kv in files)
|
||||
{
|
||||
using var src = kv.Value.Open();
|
||||
using var dst = File.Create(Path.Combine(temp, kv.Key));
|
||||
src.CopyTo(dst);
|
||||
}
|
||||
if (Directory.Exists(destDir)) Directory.Delete(destDir, true);
|
||||
Directory.Move(temp, destDir);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (Directory.Exists(temp)) Directory.Delete(temp, true);
|
||||
throw;
|
||||
}
|
||||
return SongInfo.FromDir(destDir);
|
||||
}
|
||||
|
||||
// 白名單內的檔案(檔名小寫 → entry);允許整個資料夾被壓進去:以最淺的 config.json 所在位置為根
|
||||
private static Dictionary<string, ZipArchiveEntry> Collect(ZipArchive zip, out string configText)
|
||||
{
|
||||
ZipArchiveEntry config = null;
|
||||
foreach (var e in zip.Entries)
|
||||
{
|
||||
if (!string.Equals(e.Name, SongInfo.ConfigName, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (config == null || e.FullName.Length < config.FullName.Length) config = e;
|
||||
}
|
||||
if (config == null) throw new PackException("zip 裡沒有 config.json,不是曲包");
|
||||
string prefix = config.FullName.Substring(0, config.FullName.Length - config.Name.Length);
|
||||
|
||||
var files = new Dictionary<string, ZipArchiveEntry>();
|
||||
foreach (var e in zip.Entries)
|
||||
{
|
||||
if (!e.FullName.StartsWith(prefix, StringComparison.Ordinal)) continue;
|
||||
string rel = e.FullName.Substring(prefix.Length);
|
||||
if (rel.Length == 0 || rel.IndexOf('/') >= 0 || rel.IndexOf('\\') >= 0) continue; // 目錄項目、子資料夾
|
||||
if (!Allowed.Contains(rel)) continue;
|
||||
if (e.Length > MaxEntryBytes) throw new PackException($"{rel} 太大");
|
||||
files[rel.ToLowerInvariant()] = e;
|
||||
}
|
||||
|
||||
using var reader = new StreamReader(config.Open(), System.Text.Encoding.UTF8);
|
||||
configText = reader.ReadToEnd();
|
||||
return files;
|
||||
}
|
||||
|
||||
// 給玩家看的錯誤訊息
|
||||
public static string Describe(Exception e)
|
||||
{
|
||||
if (e is PackException || e is FormatException) return e.Message;
|
||||
if (e is InvalidDataException) return "不是有效的 zip 檔";
|
||||
if (e is IOException) return "檔案讀取失敗(可能還在複製中)";
|
||||
if (e is UnauthorizedAccessException) return "沒有讀取權限";
|
||||
return e.GetType().Name + ": " + e.Message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c0876d2a8cc58b346b9007f5ca830a23
|
||||
@@ -0,0 +1,30 @@
|
||||
// 一次遊玩的統計,給結算/上傳使用
|
||||
public class PlayResult
|
||||
{
|
||||
public int score;
|
||||
public int perfect, fast, slow, bad, miss;
|
||||
public int maxCombo;
|
||||
public int combo;
|
||||
|
||||
public static PlayResult Last { get; set; }
|
||||
|
||||
public void Add(Judgement j, int points)
|
||||
{
|
||||
score += points;
|
||||
switch (j)
|
||||
{
|
||||
case Judgement.Perfect: perfect++; break;
|
||||
case Judgement.Fast: fast++; break;
|
||||
case Judgement.Slow: slow++; break;
|
||||
case Judgement.Bad: bad++; break;
|
||||
case Judgement.Miss: miss++; break;
|
||||
}
|
||||
|
||||
if (j == Judgement.Miss) combo = 0;
|
||||
else if (j != Judgement.None) combo++;
|
||||
if (combo > maxCombo) maxCombo = combo;
|
||||
}
|
||||
|
||||
public override string ToString() =>
|
||||
$"score={score} P={perfect} F={fast} S={slow} B={bad} M={miss} maxCombo={maxCombo}";
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 48d770f32e4d63d48ac02109441a84af
|
||||
@@ -0,0 +1,36 @@
|
||||
using UnityEngine;
|
||||
|
||||
// 所有 PlayerPrefs 的鍵集中在這裡(沿用舊版的鍵名,更新後登入狀態與設定不會消失)
|
||||
public static class Prefs
|
||||
{
|
||||
public const string Uid = "UID";
|
||||
public const string Token = "Token";
|
||||
public const string LegacyPassword = "Password"; // 舊版存的密碼,登入成功後刪除
|
||||
public const string Name = "Name";
|
||||
public const string Email = "Email";
|
||||
public const string AccountType = "Type";
|
||||
public const string CreateTime = "CreateTime";
|
||||
public const string EmailVerified = "EmailVerified";
|
||||
|
||||
public const string Song = "NowPlayingSong";
|
||||
public const string Level = "NowPlayingLevel";
|
||||
public const string AudioOffsetMs = "AudioOffsetMs";
|
||||
public const string VideoBackground = "VideoBackground";
|
||||
public const string StorageAsked = "StorageAsked";
|
||||
|
||||
public static int UserId => PlayerPrefs.GetInt(Uid, 0);
|
||||
public static bool LoggedIn => UserId != 0 && (PlayerPrefs.HasKey(Token) || PlayerPrefs.HasKey(LegacyPassword));
|
||||
|
||||
// UID 顯示格式:帳號類型字元 + x + 8 位十六進位
|
||||
public static string UidText()
|
||||
{
|
||||
int uid = UserId;
|
||||
string type = PlayerPrefs.GetString(AccountType, "");
|
||||
if (uid == 0 || type == "") return "0x00000000";
|
||||
char c = type switch { "R" => '0', "A" => 'a', "B" => 'b', "D" => 'f', _ => '?' };
|
||||
return $"{c}x{uid:X8}";
|
||||
}
|
||||
|
||||
public static void SetBool(string key, bool value) => PlayerPrefs.SetInt(key, value ? 1 : 0);
|
||||
public static bool GetBool(string key, bool fallback) => PlayerPrefs.GetInt(key, fallback ? 1 : 0) == 1;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ea45d9721b0788c45a674896e69e971e
|
||||
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
// 一個已匯入曲包的資訊(來自 config.json 與資料夾內的檔案)
|
||||
// 曲包格式見 RhyculatorMaker 的 README
|
||||
public class SongInfo
|
||||
{
|
||||
public const int LevelCount = 3;
|
||||
public static readonly string[] LevelNames = { "easy", "normal", "hard" }; // level 1..3
|
||||
public static readonly string[] MusicNames = { "music.ogg", "music.wav", "music.mp3" };
|
||||
public const string ConfigName = "config.json";
|
||||
public const string ImageName = "image.png";
|
||||
public const string VideoName = "video.mp4";
|
||||
|
||||
private static readonly Regex IdPattern = new Regex("^[a-z0-9][a-z0-9-]{1,63}$");
|
||||
|
||||
public string id;
|
||||
public string name;
|
||||
public string artist;
|
||||
public string charter;
|
||||
public double bpm;
|
||||
public int beatOffsetMs;
|
||||
public int offsetMs; // 判定時間微調:正值 = 所有音符的判定點往後移
|
||||
public int previewStartMs;
|
||||
public int previewLengthMs;
|
||||
public readonly int[] levelNum = new int[LevelCount + 1]; // [1..3] 難度數字,0 = 未填
|
||||
public string dir; // 解開後的檔案所在(zip 曲包是快取資料夾)
|
||||
public string source; // package 資料夾裡的來源:zip 檔或資料夾
|
||||
|
||||
public static string LevelName(int level) => level >= 1 && level <= LevelCount ? LevelNames[level - 1] : "normal";
|
||||
public static bool IsValidId(string id) => id != null && IdPattern.IsMatch(id);
|
||||
|
||||
public bool HasLevel(int level) => level >= 1 && level <= LevelCount && File.Exists(ChartPath(level));
|
||||
public string ChartPath(int level) => Path.Combine(dir, LevelName(level) + ".json");
|
||||
public string ImagePath => Path.Combine(dir, ImageName);
|
||||
|
||||
public string VideoPath
|
||||
{
|
||||
get { string p = Path.Combine(dir, VideoName); return File.Exists(p) ? p : null; }
|
||||
}
|
||||
|
||||
public string MusicPath
|
||||
{
|
||||
get
|
||||
{
|
||||
foreach (var n in MusicNames)
|
||||
{
|
||||
string p = Path.Combine(dir, n);
|
||||
if (File.Exists(p)) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 第一個有譜面的難度,沒有則 0
|
||||
public int FirstLevel()
|
||||
{
|
||||
for (int l = 1; l <= LevelCount; l++) if (HasLevel(l)) return l;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 解析 config.json;缺必要欄位時丟 FormatException
|
||||
public static SongInfo FromConfig(string configJson, string dir)
|
||||
{
|
||||
var cfg = MiniJson.AsObject(MiniJson.Parse(configJson));
|
||||
if (cfg == null) throw new FormatException("config.json 不是 JSON 物件");
|
||||
|
||||
var s = new SongInfo { dir = dir };
|
||||
s.id = MiniJson.GetString(cfg, "id", "").Trim();
|
||||
if (!IsValidId(s.id)) throw new FormatException("config.json 的 id 無效(只能用小寫英數字與 -)");
|
||||
s.name = MiniJson.GetString(cfg, "name", "").Trim();
|
||||
if (s.name == "") throw new FormatException("config.json 缺少 name");
|
||||
s.artist = MiniJson.GetString(cfg, "artist", "");
|
||||
s.charter = MiniJson.GetString(cfg, "charter", "");
|
||||
s.bpm = MiniJson.GetNumber(cfg, "bpm", 0);
|
||||
s.beatOffsetMs = MiniJson.GetInt(cfg, "beat_offset", 0);
|
||||
s.offsetMs = MiniJson.GetInt(cfg, "offset", 0);
|
||||
s.previewStartMs = MiniJson.GetInt(cfg, "preview_start", 0);
|
||||
s.previewLengthMs = MiniJson.GetInt(cfg, "preview_length", 15000);
|
||||
for (int l = 1; l <= LevelCount; l++)
|
||||
s.levelNum[l] = MiniJson.GetInt(cfg, LevelNames[l - 1] + "_num", 0);
|
||||
return s;
|
||||
}
|
||||
|
||||
public static SongInfo FromDir(string dir)
|
||||
=> FromConfig(File.ReadAllText(Path.Combine(dir, ConfigName)), dir);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 662e3c38dfd560f41a15cfe5a56b4cd2
|
||||
Reference in new issue
Block a user