Files
bansonic_beta_main/Assets/scripts/Main_main/pressStart.cs
T

311 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine.UI;
public class pressStart : MonoBehaviour
{
public string sceneName_toNextScene = "selectYourSongFirst";
public string testModeSceneName = "gamePlay_gamePlay";
[SerializeField] private string banflag_filePath = "C:/ProgramData/Bansonic/Caches/Bansonic_TestOutput";
private bool banflag_exists;
public static string testmode_audioFile_path;
public static string testmode_bgPicFile_path;
public static string testmode_beatmapJSON_path;
// new: store banflag content for other scenes to read
public static string banflagContent = string.Empty;
// UI text to show status
public Text statusText;
public Text warningText;
// polling
private Coroutine pollCoroutine;
private float pollInterval = 3f;
// Start is called before the first frame update
void Start()
{
// sceneName_toNextScene = "Songs_Select";
banflag_exists = false;
testmode_audioFile_path = string.Empty;
testmode_bgPicFile_path = string.Empty;
testmode_beatmapJSON_path = string.Empty;
banflagContent = string.Empty;
// Ensure status text shows idle
UpdateStatus("ʦרãسEnterϷ԰", Color.green);
}
// Update is called once per frame
private bool check_enterNextScene = false;
private static readonly string WARNING_TEXT_CONTENT = "<color=orange>当前处于测试阶段</color><color=red>未授权版本</color><color=orange>版本号:</color><color=red>v1.0.0</color><color=orange>,请注意风险。</color>";
void Update()
{
// 增加对任何按键或点击的响应,提高 Build 包的兼容性
if (Input.anyKeyDown)
{
// 排除掉专门用于测试模式的 Enter 键
if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
{
Debug.Log("[pressStart] Enter detected, starting test mode polling.");
GameConfig.testMode = true;
if (pollCoroutine != null) StopCoroutine(pollCoroutine);
pollCoroutine = StartCoroutine(PollForBanflagAndProceed());
return;
}
// 正常流程:点击或空格
if (check_enterNextScene)
{
Debug.Log("[pressStart] Second input detected, loading UI_UI scene. Forcing Time.timeScale = 1.");
Time.timeScale = 1f; // Ensure time is running for next scene
SceneManager.LoadScene("UI_UI");
return;
}
Debug.Log("[pressStart] First input detected, setting check_enterNextScene = true");
GameConfig.testMode = false;
if (warningText != null)
{
warningText.gameObject.SetActive(true);
warningText.text = WARNING_TEXT_CONTENT;
}
check_enterNextScene = true;
}
}
private IEnumerator PollForBanflagAndProceed()
{
UpdateStatus("Waiting for banflag...", new Color(1f, 0.5f, 0f)); // orange
while (true)
{
bool found = check_banflag_testBanflag();
if (found)
{
UpdateStatus("Banflag detected. Loading test mode...", Color.green);
// small delay to show status
yield return new WaitForSeconds(0.5f);
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(testModeSceneName);
while (!asyncLoad.isDone)
{
yield return null;
}
yield break;
}
else
{
UpdateStatus("Waiting for banflag...", new Color(1f, 0.5f, 0f)); // orange
}
yield return new WaitForSeconds(pollInterval);
}
}
private IEnumerator LoadSceneAsync(string sceneName)
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
while (!asyncLoad.isDone)
{
yield return null;
}
}
private void UpdateStatus(string message, Color color)
{
if (statusText != null)
{
statusText.text = message;
statusText.color = color;
}
Debug.Log(message);
}
private string NormalizeToForwardSlashes(string path)
{
if (string.IsNullOrEmpty(path)) return string.Empty;
try
{
// Get full absolute path to remove any relative segments
string full = Path.GetFullPath(path);
// Replace backslashes with forward slashes
string fwd = full.Replace('\\', '/');
// Collapse multiple slashes into single
string collapsed = Regex.Replace(fwd, "/{2,}", "/");
// Remove trailing slash except when path is root like "C:/"
if (collapsed.Length > 3 && collapsed.EndsWith("/"))
collapsed = collapsed.TrimEnd('/');
return collapsed;
}
catch
{
// Fallback: replace backslashes and collapse
string f = path.Replace('\\', '/');
string c = Regex.Replace(f, "/{2,}", "/");
if (c.Length > 3 && c.EndsWith("/")) c = c.TrimEnd('/');
return c;
}
}
// returns true if banflag detected
private bool check_banflag_testBanflag()
{
try
{
// reset previous results
banflag_exists = false;
testmode_audioFile_path = string.Empty;
testmode_bgPicFile_path = string.Empty;
testmode_beatmapJSON_path = string.Empty;
banflagContent = string.Empty;
if (string.IsNullOrEmpty(banflag_filePath))
{
Debug.LogWarning("banflag_filePath δá");
UpdateStatus("Error: banflag path not configured", Color.red);
return false;
}
string filePath = Path.Combine(banflag_filePath, "test.banflag");
if (!File.Exists(filePath))
{
Debug.LogWarning($"δҵӦ banflag ļ: {filePath}");
return false;
}
// mark exists
banflag_exists = true;
byte[] data = File.ReadAllBytes(filePath);
if (data == null || data.Length == 0)
{
Debug.LogWarning($"banflag ļΪ: {filePath}");
}
else
{
// UTF8ȡΪлı
string text = null;
try
{
text = Encoding.UTF8.GetString(data);
}
catch
{
text = null;
}
bool looksLikeText = false;
if (!string.IsNullOrEmpty(text))
{
// Ƿɴӡַ
int nonPrintable = 0;
int checkLen = Mathf.Min(256, text.Length);
for (int i = 0; i < checkLen; i++)
{
char c = text[i];
if (char.IsControl(c) && c != '\r' && c != '\n' && c != '\t') nonPrintable++;
}
looksLikeText = (nonPrintable == 0);
}
if (looksLikeText)
{
Debug.Log($"ҵ banflag ļ: {filePath}\n:\n{text}");
// store the readable content for other scenes
banflagContent = text;
}
else
{
// ǿɶıתΪbase64
string base64 = System.Convert.ToBase64String(data);
Debug.Log($"ҵ banflag ļ (): {filePath}={data.Length} bytesBase64 ǰ200 ַ鿴:\n{(base64.Length > 200 ? base64.Substring(0,200) + "..." : base64)}");
banflagContent = $"[Binary Data] Length: {data.Length} bytes";
}
}
// ͬĿ¼ָļ
string dir = Path.GetDirectoryName(filePath);
if (string.IsNullOrEmpty(dir)) dir = banflag_filePath;
// find JSON
string foundJson = string.Empty;
try
{
string[] jsons = Directory.GetFiles(dir, "*.json", SearchOption.TopDirectoryOnly);
if (jsons != null && jsons.Length > 0)
{
foundJson = jsons[0];
}
}
catch { }
// find audio: mp3, wav, ogg (in that priority)
string foundAudio = string.Empty;
try
{
string[] exts = new string[] { "*.mp3", "*.wav", "*.ogg" };
foreach (var pat in exts)
{
string[] matches = Directory.GetFiles(dir, pat, SearchOption.TopDirectoryOnly);
if (matches != null && matches.Length > 0)
{
foundAudio = matches[0];
break;
}
}
}
catch { }
// find image: jpg/jpeg, png (priority jpg then png)
string foundImage = string.Empty;
try
{
string[] imgExts = new string[] { "*.jpg", "*.jpeg", "*.png" };
foreach (var pat in imgExts)
{
string[] matches = Directory.GetFiles(dir, pat, SearchOption.TopDirectoryOnly);
if (matches != null && matches.Length > 0)
{
foundImage = matches[0];
break;
}
}
}
catch { }
// normalize and assign
testmode_beatmapJSON_path = string.IsNullOrEmpty(foundJson) ? string.Empty : NormalizeToForwardSlashes(foundJson);
testmode_audioFile_path = string.IsNullOrEmpty(foundAudio) ? string.Empty : NormalizeToForwardSlashes(foundAudio);
testmode_bgPicFile_path = string.IsNullOrEmpty(foundImage) ? string.Empty : NormalizeToForwardSlashes(foundImage);
// Debug the normalized paths
Debug.Log($"banflag_exists={banflag_exists}");
Debug.Log($"testmode_beatmapJSON_path = {testmode_beatmapJSON_path}");
Debug.Log($"testmode_audioFile_path = {testmode_audioFile_path}");
Debug.Log($"testmode_bgPicFile_path = {testmode_bgPicFile_path}");
UpdateStatus("Banflag found", Color.green);
return banflag_exists;
}
catch (System.Exception ex)
{
Debug.LogError($"ȡ banflag ļʱ: {ex}");
UpdateStatus("Error reading banflag", Color.red);
// ensure flags cleared on error
banflag_exists = false;
testmode_audioFile_path = string.Empty;
testmode_bgPicFile_path = string.Empty;
testmode_beatmapJSON_path = string.Empty;
banflagContent = string.Empty;
return false;
}
}
}