#if UGX_BRIDGE || UNITY_EDITOR
using Uigenx.Binding;
using Uigenx.Protocol;
using UnityEngine;
using UnityEngine.Rendering;
namespace Uigenx.Bridge
{
///
/// Pumps the bridge client in play mode and in development builds. Created automatically on
/// load when the settings asset enables the bridge; destroyed with the play session.
///
[AddComponentMenu("")]
[DisallowMultipleComponent]
public sealed class UgxBridgeBehaviour : MonoBehaviour
{
public static UgxBridgeBehaviour Instance { get; private set; }
UgxBridgeClient _client;
UgxDataStreamHandler _dataStream;
UgxActionHandler _actions;
UgxScreenStateHandler _screenState;
UgxPreviewHandler _preview;
UgxHotReloadHandler _hotReload;
public UgxBridgeClient Client => _client;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
static void Bootstrap()
{
if (Instance != null) return;
var settings = UgxSettings.InstanceOrNull;
if (settings == null || !settings.BridgeEnabled) return;
if (!Debug.isDebugBuild && !Application.isEditor) return;
var host = new GameObject("UgxBridge") { hideFlags = HideFlags.HideAndDontSave };
host.AddComponent();
DontDestroyOnLoad(host);
}
void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
var config = UgxBridgeConfig.Load();
var options = new UgxBridgeOptions
{
Url = UgxBridgeConfig.ResolveUrl(config),
Token = UgxBridgeConfig.ResolveToken(config),
Role = UgxRole.Player,
ProjectId = config != null ? config.ProjectId : Application.productName,
IsPlaying = true,
RenderPipeline = DetectPipeline(),
};
options.Capabilities.Add(UgxCapability.LiveData);
options.Capabilities.Add(UgxCapability.Actions);
options.Capabilities.Add(UgxCapability.Preview);
options.Capabilities.Add(UgxCapability.Screenshot);
options.Capabilities.Add(UgxCapability.HotReload);
_client = new UgxBridgeClient(options);
_dataStream = new UgxDataStreamHandler(_client, ResolveDataSource);
_actions = new UgxActionHandler(_client);
_screenState = new UgxScreenStateHandler(_client);
_preview = new UgxPreviewHandler(_client, this);
_hotReload = new UgxHotReloadHandler(_client);
_client.Start();
}
void Update()
{
_client.Pump();
_screenState.Tick();
_dataStream.Tick(Time.unscaledTimeAsDouble);
}
void OnDestroy()
{
if (Instance != this) return;
Instance = null;
_hotReload?.Dispose();
_preview?.Dispose();
_screenState?.Dispose();
_actions?.Dispose();
_dataStream?.Dispose();
_client?.Dispose();
}
static IUgxDataSource ResolveDataSource() => UgxScreenManager.Instance?.DataSource;
public static UgxRenderPipeline DetectPipeline()
{
var pipeline = GraphicsSettings.currentRenderPipeline;
if (pipeline == null) return UgxRenderPipeline.BuiltIn;
var name = pipeline.GetType().FullName ?? string.Empty;
if (name.Contains("Universal")) return UgxRenderPipeline.Urp;
if (name.Contains("HighDefinition")) return UgxRenderPipeline.Hdrp;
return UgxRenderPipeline.Unknown;
}
}
}
#endif