Files
Rhyculator/Assets/Scripts/Platform/Library.cs
T
SahikandClaude Opus 5.5 ddd5fdc28b 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]>
2026-10-24 14:18:54 +08:00

152 lines
4.8 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
// 曲包清單(遊戲其他地方都透過這裡取得曲目)
// 開啟遊戲、回到前景時立即掃描 package 資料夾,之後每秒一次;掃描在背景執行緒進行
public class Library : MonoBehaviour
{
public static IReadOnlyList<SongInfo> Songs { get; private set; } = new List<SongInfo>();
public static bool Loaded { get; private set; }
public static string PackageDir { get; private set; }
// 曲包清單有變(新增、刪除、更新)
public static event Action Changed;
// 有新的曲包出現(不含第一次掃描)
public static event Action<SongInfo> Added;
// 遊玩中暫停掃描,避免 IO 影響幀率
public static bool Paused;
private static Library instance;
private Task<PackLibrary.ScanResult> running;
private float nextScan;
private bool first = true;
public static void Create()
{
if (instance != null) return;
var go = new GameObject("Library");
DontDestroyOnLoad(go);
instance = go.AddComponent<Library>();
}
// 立即重新掃描(例如取得權限、下載完成後)
public static void Rescan()
{
if (instance != null) instance.nextScan = 0;
}
public static SongInfo Find(string id)
{
foreach (var s in Songs) if (s.id == id) return s;
return null;
}
public static SongInfo Current
{
get
{
var s = Find(PlayerPrefs.GetString(Prefs.Song, ""));
return s ?? (Songs.Count > 0 ? Songs[0] : null);
}
set
{
if (value == null) return;
PlayerPrefs.SetString(Prefs.Song, value.id);
}
}
void OnApplicationFocus(bool focus)
{
if (focus) nextScan = 0;
}
void Update()
{
if (running != null)
{
if (!running.IsCompleted) return;
Apply(running);
running = null;
}
if (Paused || Time.unscaledTime < nextScan) return;
nextScan = Time.unscaledTime + 1f;
string packageDir = PackStorage.PackageDir;
string cacheDir = PackStorage.CacheDir;
if (packageDir != PackageDir)
{
// 位置改變(取得權限):搬過去並重新開始
PackageDir = packageDir;
PackLibrary.ResetState();
first = true;
}
running = Task.Run(() =>
{
PackStorage.Migrate(packageDir);
return PackLibrary.Scan(packageDir, cacheDir);
});
}
void Apply(Task<PackLibrary.ScanResult> task)
{
if (task.IsFaulted)
{
Debug.LogWarning("[Library] 掃描失敗:" + task.Exception?.GetBaseException().Message);
return;
}
var r = task.Result;
foreach (var e in r.errors) Toast.Show("曲包有問題:" + e);
if (r.pending) nextScan = Time.unscaledTime + 0.5f;
if (r.changed || !Loaded)
{
Songs = r.songs;
Loaded = true;
Debug.Log($"[Library] {Songs.Count} 個曲包 @ {PackageDir}");
Changed?.Invoke();
}
if (!first)
foreach (var s in r.added)
{
Toast.Show($"已加入「{s.name}」");
Added?.Invoke(s);
}
first = false;
ReadImportError();
ReadPendingDownload();
}
// 曲包網站的「在遊戲中下載」連結(rhyculator://pack/<code>):Java 端把代碼寫在這個檔案
public static event Action<string> DownloadRequested;
static void ReadPendingDownload()
{
string path = Path.Combine(PackStorage.PrivateRoot, PackStorage.PendingDownloadFile);
if (!File.Exists(path)) return;
string code = "";
try { code = File.ReadAllText(path).Trim().ToLowerInvariant(); } catch { }
try { File.Delete(path); } catch { }
if (System.Text.RegularExpressions.Regex.IsMatch(code, "^[a-z0-9]{8}$")) DownloadRequested?.Invoke(code);
}
// Java 端讀取「開啟 / 分享」進來的檔案失敗時留下的訊息
static void ReadImportError()
{
string path = Path.Combine(PackStorage.PrivateRoot, PackStorage.ImportErrorFile);
if (!File.Exists(path)) return;
string detail = "";
try { detail = File.ReadAllText(path); } catch { }
try { File.Delete(path); } catch { }
Debug.LogWarning("[Library] " + detail);
Toast.Show(detail.Contains("Permission Denial") || detail.Contains("SecurityException")
? "沒有讀取這個檔案的權限,請從檔案管理員用「開啟」或「分享」送給 Rhyculator"
: "無法讀取檔案:" + detail);
}
}