using System;
using UnityEngine;
namespace LightGlue.Unity.Config
{
///
/// 统一管理「参考图像 resize(w,h)」的唯一来源:
/// - C# 映射:referenceImageWidth/referenceImageHeight
/// - Unity GameView 截图:referenceCaptureWidth/referenceCaptureHeight
/// - Python 启动参数:--resize {w} {h}(由 NetworkConfig 占位符替换)
///
public static class ReferenceImageResizeService
{
private const int MinSize = 1;
private const int MaxSize = 8192;
private static bool _initialized;
private static int _width = 320;
private static int _height = 240;
public static int Width
{
get { EnsureInitialized(); return _width; }
}
public static int Height
{
get { EnsureInitialized(); return _height; }
}
public static event Action OnResizeChanged;
///
/// 确保从 NetworkConfig 初始化一次。
///
public static void EnsureInitialized()
{
if (_initialized) return;
_initialized = true;
try
{
var cfg = NetworkConfigManager.GetCachedConfig();
if (cfg != null)
{
int w = cfg.referenceResizeWidth;
int h = cfg.referenceResizeHeight;
if (IsValid(w, h))
{
_width = w;
_height = h;
}
}
}
catch
{
// ignore:保持默认 320x240
}
}
///
/// 设置 resize;可选写入 NetworkConfig 并持久化到 JSON。
///
public static void Set(int width, int height, bool persistToNetworkConfig = true)
{
EnsureInitialized();
width = Mathf.Clamp(width, MinSize, MaxSize);
height = Mathf.Clamp(height, MinSize, MaxSize);
if (_width == width && _height == height) return;
_width = width;
_height = height;
if (persistToNetworkConfig)
{
try
{
var cfg = NetworkConfigManager.LoadConfig();
if (cfg != null)
{
cfg.referenceResizeWidth = _width;
cfg.referenceResizeHeight = _height;
NetworkConfigManager.SaveConfig(cfg);
}
}
catch (Exception ex)
{
Debug.LogWarning($"[Resize] 保存到 NetworkConfig 失败:{ex.Message}");
}
}
try
{
OnResizeChanged?.Invoke(_width, _height);
}
catch (Exception ex)
{
Debug.LogWarning($"[Resize] OnResizeChanged 回调异常:{ex.Message}");
}
}
public static bool IsValid(int width, int height)
{
return width >= MinSize && height >= MinSize && width <= MaxSize && height <= MaxSize;
}
}
}