sega 0eeedea7b3 Рефакторинг системы ввода
- Убраны лишние классы
- Наведен порядок в ComInput и прилежащих классах
2026-06-15 13:02:20 +03:00

198 lines
5.8 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 Cysharp.Threading.Tasks;
using Lights;
using Periscope;
using System.Threading;
using TMPro;
using UnityEngine;
using UnityEngine.XR;
/// <summary>
/// Главный загрузчик.
/// </summary>
public class MainBootstrap : MonoBehaviour
{
[SerializeField] TextMeshProUGUI window;
[SerializeField] GameObject DebugCanvas;
[SerializeField] private ConfigCatalog ConfigCatalog;
[SerializeField] private GameManager gm;
[Header("Настройка камер")]
[SerializeField] private Transform CamerasPivot;
[SerializeField] private Camera VR_Camera;
[SerializeField] private Camera Screen_Camera;
[Header("Sound manager")]
[SerializeField] private SoundManager soundManager;
[Header("Системы")]
[SerializeField] private RankSystem rankSystem;
[Header("Отладка")]
[SerializeField] private bool logging;
[SerializeField] private bool debugMode;
CancellationTokenSource cts;
private void Awake()
{
cts = new CancellationTokenSource();
InitializeAsync(cts.Token).Forget();
}
private void OnApplicationQuit()
{
cts?.Cancel();
cts.Dispose();
}
private async UniTask InitializeAsync(CancellationToken ct)
{
XRSettings.useOcclusionMesh = false;
window.text += "Инициализация диспетчера...\n";
UnityMainThreadDispatcher.Initialize();
window.text += "Диспетчер инициализирован...\n";
window.text += "Проверка лицензии...\n";
bool ok = await Defender.Instance.CheckLicenseAsync();
if (ok)
{
window.text += "Лицензия валидна\n";
}
else
{
window.text += "Нет лицензии\n";
await Delay(2000);
Application.Quit();
}
InitializeMangers();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
window.text += "Включаем подсветку...\n";
await Delay(1500);
LightSystem.SetLightActive(true);
await Delay(500);
window.text += "Регулировка перископа...\n";
PeriscopeManager.Init(GameManager.globalCts);
PeriscopeManager.MoveUpToEnd();
int time = debugMode ? 0 : PeriscopeManager.config.MoveUpToEndTimeMs;
await PeriscopeWait(time, window.text, this.GetCancellationTokenOnDestroy());
await Delay(1000);
window.text += "Заходим в игру...\n";
await Delay(1000);
if (debugMode)
{
window.text = "DEBUG_MODE";
//DontDestroyOnLoad(DebugCanvas);
}
SceneLoader.LoadScene("MenuOneRegime");
}
private async UniTask PeriscopeWait(int timeMs, string message, CancellationToken token = default)
{
float startTime = Time.time;
float duration = timeMs / 1000f; // Конвертируем в секунды
while (Time.time - startTime < duration)
{
// Проверяем отмену
if (token.IsCancellationRequested)
break;
// Вычисляем процент (0-1)
float elapsed = Time.time - startTime;
float percent = Mathf.Clamp01(elapsed / duration);
var progress = GetProgressBar(percent * 100f);
window.text = $"{message}{progress}\n";
await UniTask.Delay(100, cancellationToken: token);
}
// По завершении показываем 100%
window.text = $"{message}{GetProgressBar(100f)}\n";
}
private void InitializeMangers()
{
gm.Init();
window.text += "Инициализация менеджеров...\n";
DontDestroyOnLoad(gm);
if (ConfigCatalog == null)
{
Log("Не указан каталог конфигов");
return;
}
var (OK, message) = ConfigCatalog.ValidateReferences();
if (!OK)
{
Log($"Ошибка в каталоге конфига: \n{message}");
return;
}
#region Инициализации
SettingsManager.Initialize(ConfigCatalog.SettingsManagerConfig.DefaultSettingsScheme);
CamerasManager.Initialize(CamerasPivot, VR_Camera, Screen_Camera);
ComPortController.Initialize(ControllerConfig.LoadOrCreate(), ComPortController.InputType.Decimal);
ComPortController.PaymentReceived += WalletManager.OnCoin;
WalletManager.Initialize(ConfigCatalog.WalletManagerConfig);
CountersSystem.Init(ConfigCatalog.CountersConfig);
GameModesHolder.Initialize(ConfigCatalog.GameModesConfig);
In.Initialize(new ComInput());
soundManager.Initialize();
rankSystem.Initialize();
DontDestroyOnLoad(rankSystem);
#endregion
Log("Главный загрузчик отработал");
BootstrapperState.MainBootstraped = true;
window.text += "Готово...\n";
}
private void Log(string message)
{
if (logging) Debug.Log(message);
}
private static string GetProgressBar(float percent, int totalLength = 10)
{
// Ограничиваем процент от 0 до 100
percent = Mathf.Clamp(percent, 0f, 100f);
// Вычисляем количество заполненных блоков
int filledCount = Mathf.RoundToInt((percent / 100f) * totalLength);
// Собираем строку
string filled = new('■', filledCount);
string empty = new('□', totalLength - filledCount);
return $"[{filled}{empty}]";
}
private async UniTask Delay(int ms)
{
if (debugMode) return;
await UniTask.Delay(ms);
}
}