using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using Landfall.TABS;
using UnityEngine;
using UnityEngine.Networking;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("AIChat")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("AIChat")]
[assembly: AssemblyTitle("AIChat")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace INF.AIChat;
[BepInPlugin("com.inf.aichat", "TABS AI Chat", "1.5.0")]
public class AIChatPlugin : BaseUnityPlugin
{
internal static AIChatPlugin Instance;
private ChatService service;
private ChatUI ui;
private ConfigEntry<string> cfgEndpoint;
private ConfigEntry<string> cfgApiKey;
private ConfigEntry<string> cfgModel;
private ConfigEntry<string> cfgHotkey;
private ConfigEntry<string> cfgLanguage;
private ConfigEntry<int> cfgJpegQuality;
private ConfigEntry<int> cfgHistoryTurns;
private ConfigEntry<int> cfgTimeout;
private ConfigEntry<int> cfgPreset;
private KeyCode hotkey = (KeyCode)292;
private bool cursorSaved;
private bool savedVisible;
private CursorLockMode savedLock;
private int presetIndex;
private void Awake()
{
//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
Instance = this;
cfgEndpoint = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Endpoint", "http://127.0.0.1:11434/v1/chat/completions", "Only used by the Custom preset.");
cfgApiKey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ApiKey", "", "API key, needed only by presets that require one.");
cfgModel = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Model", "qwen2.5vl:7b", "Only used by the Custom preset. Any Ollama model you have pulled.");
cfgHotkey = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Hotkey", "F11", "Toggle key, Unity KeyCode name (F11, F12, Insert ...).");
cfgLanguage = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Language", "zh", "UI and AI reply language: zh or en.");
cfgJpegQuality = ((BaseUnityPlugin)this).Config.Bind<int>("General", "JpegQuality", 55, "Screenshot JPEG quality 1-100.");
cfgHistoryTurns = ((BaseUnityPlugin)this).Config.Bind<int>("General", "HistoryTurns", 8, "How many past turns to resend.");
cfgTimeout = ((BaseUnityPlugin)this).Config.Bind<int>("General", "TimeoutSec", 60, "HTTP timeout in seconds.");
cfgPreset = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Preset", 0, "Built-in preset index. 0=qwen2.5vl:7b, 1=qwen2.5vl:3b, 2=llava:7b, 3=gemma3:4b (all local Ollama), 4=Custom (uses Endpoint/Model/ApiKey below).");
service = new ChatService();
service.JpegQuality = Mathf.Clamp(cfgJpegQuality.Value, 1, 100);
service.HistoryTurns = Mathf.Max(0, cfgHistoryTurns.Value);
service.TimeoutSec = Mathf.Max(5, cfgTimeout.Value);
Lang.Current = ((cfgLanguage.Value == "en") ? "en" : "zh");
try
{
hotkey = (KeyCode)Enum.Parse(typeof(KeyCode), cfgHotkey.Value, ignoreCase: true);
}
catch
{
hotkey = (KeyCode)292;
}
ui = new ChatUI();
ui.Service = service;
ui.OnSend = HandleSend;
ui.PresetLabel = CurrentPresetLabel;
ui.CyclePreset = CyclePresetNext;
ui.HotkeyName = ((object)Unsafe.As<KeyCode, KeyCode>(ref hotkey)/*cast due to .constrained prefix*/).ToString();
ui.ReloadConfig = ReloadAll;
ui.DownloadOllama = OpenOllamaDownload;
ApplyPreset(Providers.Clamp(cfgPreset.Value), save: false);
((BaseUnityPlugin)this).Logger.LogInfo((object)("TABS AI Chat loaded. Press " + ((object)Unsafe.As<KeyCode, KeyCode>(ref hotkey)/*cast due to .constrained prefix*/).ToString() + " to toggle. Model: " + CurrentPresetLabel()));
}
private string CurrentPresetLabel()
{
return Providers.Get(presetIndex).Name;
}
private void CyclePresetNext()
{
ApplyPreset(Providers.Next(presetIndex), save: true);
service.AddSystem(Lang.T("switched") + ": " + CurrentPresetLabel());
}
private void ApplyPreset(int index, bool save)
{
presetIndex = Providers.Clamp(index);
ProviderPreset providerPreset = Providers.Get(presetIndex);
if (Providers.IsCustom(presetIndex))
{
service.Endpoint = cfgEndpoint.Value;
service.Model = cfgModel.Value;
service.ApiKey = cfgApiKey.Value;
}
else
{
service.Endpoint = providerPreset.Endpoint;
service.Model = providerPreset.Model;
service.ApiKey = (providerPreset.NeedsKey ? cfgApiKey.Value : "local");
if (!providerPreset.Vision && ui != null)
{
ui.WithScreen = false;
}
}
if (save)
{
cfgPreset.Value = presetIndex;
try
{
((BaseUnityPlugin)this).Config.Save();
}
catch
{
}
}
}
private void OpenOllamaDownload()
{
try
{
Application.OpenURL("https://ollama.com/download/windows");
}
catch
{
}
service.AddSystem(Lang.T("ollama_hint"));
}
private void ReloadAll()
{
//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
//IL_00af: Unknown result type (might be due to invalid IL or missing references)
try
{
((BaseUnityPlugin)this).Config.Reload();
}
catch
{
}
service.JpegQuality = Mathf.Clamp(cfgJpegQuality.Value, 1, 100);
service.HistoryTurns = Mathf.Max(0, cfgHistoryTurns.Value);
service.TimeoutSec = Mathf.Max(5, cfgTimeout.Value);
Lang.Current = ((cfgLanguage.Value == "en") ? "en" : "zh");
try
{
hotkey = (KeyCode)Enum.Parse(typeof(KeyCode), cfgHotkey.Value, ignoreCase: true);
}
catch
{
hotkey = (KeyCode)292;
}
if (ui != null)
{
ui.HotkeyName = ((object)Unsafe.As<KeyCode, KeyCode>(ref hotkey)/*cast due to .constrained prefix*/).ToString();
}
ApplyPreset(Providers.Clamp(cfgPreset.Value), save: false);
service.AddSystem(Lang.T("reloaded") + ": " + CurrentPresetLabel());
}
private void HandleSend(string text, bool withScreen)
{
if (Providers.Get(presetIndex).NeedsKey && string.IsNullOrEmpty(cfgApiKey.Value))
{
service.AddSystem(Lang.T("no_key"));
}
else
{
((MonoBehaviour)this).StartCoroutine(service.Send((MonoBehaviour)(object)this, text, withScreen));
}
}
private void Update()
{
//IL_0001: Unknown result type (might be due to invalid IL or missing references)
if (Input.GetKeyDown(hotkey))
{
ui.Toggle();
ApplyCursor(ui.Visible);
}
if (ui.Visible)
{
Cursor.visible = true;
Cursor.lockState = (CursorLockMode)0;
}
}
private void ApplyCursor(bool show)
{
//IL_0049: Unknown result type (might be due to invalid IL or missing references)
//IL_0017: Unknown result type (might be due to invalid IL or missing references)
//IL_001c: Unknown result type (might be due to invalid IL or missing references)
if (show)
{
if (!cursorSaved)
{
savedVisible = Cursor.visible;
savedLock = Cursor.lockState;
cursorSaved = true;
}
Cursor.visible = true;
Cursor.lockState = (CursorLockMode)0;
}
else if (cursorSaved)
{
Cursor.visible = savedVisible;
Cursor.lockState = savedLock;
cursorSaved = false;
}
}
private void OnGUI()
{
if (ui != null)
{
ui.OnGUI();
}
}
private void OnDestroy()
{
ApplyCursor(show: false);
Instance = null;
}
}
public static class AIClient
{
public static IEnumerator Post(string url, string apiKey, string body, int timeoutSec, Action<string> onOk, Action<string> onErr)
{
if (string.IsNullOrEmpty(url))
{
onErr?.Invoke("endpoint is empty");
yield break;
}
UnityWebRequest req = null;
try
{
req = new UnityWebRequest(url, "POST");
byte[] bytes = Encoding.UTF8.GetBytes(body);
req.uploadHandler = (UploadHandler)new UploadHandlerRaw(bytes);
req.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
req.SetRequestHeader("Content-Type", "application/json");
if (!string.IsNullOrEmpty(apiKey))
{
req.SetRequestHeader("Authorization", "Bearer " + apiKey);
}
if (timeoutSec > 0)
{
req.timeout = timeoutSec;
}
}
catch (Exception ex)
{
if (req != null)
{
req.Dispose();
}
onErr?.Invoke(ex.Message);
yield break;
}
yield return req.SendWebRequest();
string text = null;
string text2 = null;
try
{
if (req.downloadHandler != null)
{
text = req.downloadHandler.text;
}
}
catch
{
}
if (req.isNetworkError)
{
text2 = (string.IsNullOrEmpty(req.error) ? "network error" : req.error);
}
else if (req.responseCode < 200 || req.responseCode >= 300)
{
text2 = "HTTP " + req.responseCode;
if (!string.IsNullOrEmpty(text))
{
text2 = text2 + " | " + Trim(text, 400);
}
}
try
{
req.Dispose();
}
catch
{
}
if (text2 != null)
{
onErr?.Invoke(text2);
}
else
{
onOk?.Invoke(text);
}
}
private static string Trim(string s, int max)
{
if (s == null)
{
return "";
}
if (s.Length <= max)
{
return s;
}
return s.Substring(0, max) + "...";
}
}
public static class BattleProbe
{
public static string Collect()
{
//IL_0033: Unknown result type (might be due to invalid IL or missing references)
StringBuilder stringBuilder = new StringBuilder();
List<Unit> list = AliveUnits();
Dictionary<string, int> d = new Dictionary<string, int>();
Dictionary<string, int> d2 = new Dictionary<string, int>();
int num = 0;
int num2 = 0;
for (int i = 0; i < list.Count; i++)
{
Unit obj = list[i];
string key = UnitName(obj);
if ((int)obj.Team == 0)
{
Inc(d, key);
num++;
}
else
{
Inc(d2, key);
num2++;
}
}
stringBuilder.Append("=== BATTLE CONTEXT ===\n");
stringBuilder.Append("Game: Totally Accurate Battle Simulator (TABS)\n");
stringBuilder.Append("Total living units on field: ");
stringBuilder.Append(list.Count);
stringBuilder.Append("\n\n");
stringBuilder.Append("[RED side] ");
stringBuilder.Append(num);
stringBuilder.Append(" units\n");
AppendSide(stringBuilder, d);
stringBuilder.Append("\n");
stringBuilder.Append("[BLUE side] ");
stringBuilder.Append(num2);
stringBuilder.Append(" units\n");
AppendSide(stringBuilder, d2);
stringBuilder.Append("\n");
stringBuilder.Append("Note: in TABS the player usually deploys one side and the enemy is the other.\n");
stringBuilder.Append("If unit counts are very lopsided, the smaller side is likely the player's.\n");
stringBuilder.Append("Use the attached screenshot to judge positions (left / center / right, front / back).\n");
stringBuilder.Append("=== END CONTEXT ===");
return stringBuilder.ToString();
}
public static List<Unit> AliveUnits()
{
List<Unit> list = new List<Unit>();
try
{
Unit[] array = Object.FindObjectsOfType<Unit>();
foreach (Unit val in array)
{
if (!((Object)(object)val == (Object)null) && (!((Object)(object)val.data != (Object)null) || !val.data.Dead))
{
list.Add(val);
}
}
}
catch
{
}
return list;
}
public static string UnitName(Unit u)
{
try
{
if ((Object)(object)u.unitBlueprint != (Object)null && u.unitBlueprint.Entity != null)
{
string name = u.unitBlueprint.Entity.Name;
if (!string.IsNullOrEmpty(name))
{
return name;
}
}
}
catch
{
}
try
{
return ((Object)((Component)u).gameObject).name;
}
catch
{
}
return "?";
}
private static void Inc(Dictionary<string, int> d, string key)
{
if (string.IsNullOrEmpty(key))
{
key = "?";
}
if (d.TryGetValue(key, out var value))
{
d[key] = value + 1;
}
else
{
d[key] = 1;
}
}
private static void AppendSide(StringBuilder sb, Dictionary<string, int> d)
{
if (d.Count == 0)
{
sb.Append(" (empty)\n");
return;
}
foreach (KeyValuePair<string, int> item in d)
{
sb.Append(" - ");
sb.Append(item.Key);
sb.Append(" x");
sb.Append(item.Value);
sb.Append("\n");
}
}
}
[Serializable]
public class ChatEntry
{
public string role;
public string text;
public bool sendToApi;
public ChatEntry(string role, string text, bool sendToApi)
{
this.role = role;
this.text = text;
this.sendToApi = sendToApi;
}
}
[Serializable]
public class ApiResp
{
public ApiChoice[] choices;
public ApiErr error;
}
[Serializable]
public class ApiChoice
{
public ApiMsg message;
}
[Serializable]
public class ApiMsg
{
public string content;
}
[Serializable]
public class ApiErr
{
public string message;
}
public class ChatService
{
public readonly List<ChatEntry> History = new List<ChatEntry>();
public bool Busy;
public string Status = "";
public string Endpoint = "http://127.0.0.1:11434/v1/chat/completions";
public string ApiKey = "";
public string Model = "qwen2.5vl:7b";
public int HistoryTurns = 8;
public int JpegQuality = 55;
public int TimeoutSec = 60;
public Action OnChanged;
public void AddSystem(string text)
{
History.Add(new ChatEntry("system", text, sendToApi: false));
Notify();
}
public void Clear()
{
History.Clear();
Status = "";
Notify();
}
public void Notify()
{
if (OnChanged != null)
{
OnChanged();
}
}
public IEnumerator Send(MonoBehaviour host, string userText, bool withScreen)
{
if (Busy)
{
yield break;
}
if (string.IsNullOrEmpty(userText) || userText.Trim().Length == 0)
{
AddSystem(Lang.T("need_text"));
yield break;
}
if (string.IsNullOrEmpty(ApiKey) || ApiKey.Trim().Length == 0)
{
AddSystem(Lang.T("no_key"));
yield break;
}
Busy = true;
Status = Lang.T("sending");
History.Add(new ChatEntry("user", userText, sendToApi: true));
Notify();
string battle;
try
{
battle = BattleProbe.Collect();
}
catch
{
battle = "";
}
string imageBase64 = null;
if (withScreen)
{
Status = Lang.T("capture");
Notify();
yield return host.StartCoroutine(ScreenGrab.Capture(JpegQuality, delegate(string b64)
{
imageBase64 = b64;
}));
Status = (string.IsNullOrEmpty(imageBase64) ? Lang.T("capture_fail") : Lang.T("captured"));
Notify();
}
string body = BuildBody(userText, battle, imageBase64);
string reply = null;
string error = null;
yield return host.StartCoroutine(AIClient.Post(Endpoint, ApiKey, body, TimeoutSec, delegate(string ok)
{
reply = ExtractContent(ok, out error);
}, delegate(string err)
{
error = err;
}));
if (!string.IsNullOrEmpty(error))
{
History.Add(new ChatEntry("system", Lang.T("err") + ": " + HumanizeError(error), sendToApi: false));
}
else if (string.IsNullOrEmpty(reply))
{
History.Add(new ChatEntry("system", Lang.T("err") + ": empty response", sendToApi: false));
}
else
{
History.Add(new ChatEntry("assistant", reply, sendToApi: true));
}
Busy = false;
Status = Lang.T("ready");
Notify();
}
public string BuildBody(string userText, string battle, string imageBase64)
{
StringBuilder stringBuilder = new StringBuilder(4096);
stringBuilder.Append("{\"model\":\"");
stringBuilder.Append(Esc(Model));
stringBuilder.Append("\",\"temperature\":0.7,\"messages\":[");
stringBuilder.Append("{\"role\":\"system\",\"content\":\"");
stringBuilder.Append(Esc(SystemPrompt()));
stringBuilder.Append("\"}");
int num = History.Count - 1 - HistoryTurns * 2;
if (num < 0)
{
num = 0;
}
for (int i = num; i < History.Count - 1; i++)
{
ChatEntry chatEntry = History[i];
if (chatEntry.sendToApi && !string.IsNullOrEmpty(chatEntry.text))
{
stringBuilder.Append(",{\"role\":\"");
stringBuilder.Append((chatEntry.role == "assistant") ? "assistant" : "user");
stringBuilder.Append("\",\"content\":\"");
stringBuilder.Append(Esc(chatEntry.text));
stringBuilder.Append("\"}");
}
}
string s = userText;
if (!string.IsNullOrEmpty(battle))
{
s = userText + "\n\n" + battle;
}
if (!string.IsNullOrEmpty(imageBase64))
{
stringBuilder.Append(",{\"role\":\"user\",\"content\":[");
stringBuilder.Append("{\"type\":\"text\",\"text\":\"");
stringBuilder.Append(Esc(s));
stringBuilder.Append("\"},");
stringBuilder.Append("{\"type\":\"image_url\",\"image_url\":{\"url\":\"data:image/jpeg;base64,");
stringBuilder.Append(imageBase64);
stringBuilder.Append("\"}}]}");
}
else
{
stringBuilder.Append(",{\"role\":\"user\",\"content\":\"");
stringBuilder.Append(Esc(s));
stringBuilder.Append("\"}");
}
stringBuilder.Append("]}");
return stringBuilder.ToString();
}
public string HumanizeError(string raw)
{
if (string.IsNullOrEmpty(raw))
{
return "";
}
string text = raw.ToLowerInvariant();
bool flag = false;
try
{
flag = Endpoint != null && (Endpoint.IndexOf("127.0.0.1") >= 0 || Endpoint.IndexOf("localhost") >= 0);
}
catch
{
}
if (text.IndexOf("ssl") >= 0 || text.IndexOf("certificate") >= 0)
{
return Lang.T("err_ssl");
}
if (text.IndexOf("cannot connect") >= 0 || text.IndexOf("couldn't connect") >= 0 || text.IndexOf("could not connect") >= 0 || text.IndexOf("resolve") >= 0 || text.IndexOf("connection") >= 0 || text.IndexOf("network") >= 0 || text.IndexOf("timeout") >= 0 || text.IndexOf("host") >= 0)
{
if (!flag)
{
return Lang.T("err_net");
}
return Lang.T("err_local");
}
if (raw.IndexOf("401") >= 0)
{
return Lang.T("err_401");
}
if (raw.IndexOf("429") >= 0)
{
return Lang.T("err_429");
}
return raw;
}
public string SystemPrompt()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("You are an in-game assistant embedded in the video game ");
stringBuilder.Append("Totally Accurate Battle Simulator (TABS).\n");
stringBuilder.Append("STRICT RULES:\n");
stringBuilder.Append("1. You ONLY discuss TABS: its units, factions, formations, placement, ");
stringBuilder.Append("battle tactics, economy/cost, physics quirks and mods for TABS.\n");
stringBuilder.Append("2. If the user asks about anything unrelated to TABS, refuse in ONE short ");
stringBuilder.Append("sentence and steer the conversation back to TABS.\n");
stringBuilder.Append("3. When a battle context or screenshot is provided, give concrete placement ");
stringBuilder.Append("advice: which unit types, how many, and WHERE (left / center / right, ");
stringBuilder.Append("front / back / flank). Mention cost efficiency when relevant.\n");
stringBuilder.Append("4. Be concise and practical. Prefer short bullet points over long essays.\n");
stringBuilder.Append("5. Never invent TABS units that do not exist.\n");
stringBuilder.Append("6. ");
stringBuilder.Append(Lang.AiLanguageDirective());
return stringBuilder.ToString();
}
public static string ExtractContent(string json, out string error)
{
error = null;
if (string.IsNullOrEmpty(json))
{
error = "empty body";
return null;
}
try
{
ApiResp apiResp = JsonUtility.FromJson<ApiResp>(json);
if (apiResp == null)
{
error = "parse failed";
return null;
}
if (apiResp.error != null)
{
error = (string.IsNullOrEmpty(apiResp.error.message) ? "api error" : apiResp.error.message);
return null;
}
if (apiResp.choices == null || apiResp.choices.Length == 0)
{
error = "no choices";
return null;
}
if (apiResp.choices[0].message == null)
{
error = "no message";
return null;
}
return apiResp.choices[0].message.content;
}
catch (Exception ex)
{
error = "parse exception: " + ex.Message;
return null;
}
}
public static string Esc(string s)
{
if (s == null)
{
return "";
}
StringBuilder stringBuilder = new StringBuilder(s.Length + 16);
foreach (char c in s)
{
if (c == '"')
{
stringBuilder.Append("\\\"");
}
else if (c == '\\')
{
stringBuilder.Append("\\\\");
}
else if (c == '\n')
{
stringBuilder.Append("\\n");
}
else if (c == '\r')
{
stringBuilder.Append("\\r");
}
else if (c == '\t')
{
stringBuilder.Append("\\t");
}
else if (c < ' ')
{
stringBuilder.Append(' ');
}
else
{
stringBuilder.Append(c);
}
}
return stringBuilder.ToString();
}
}
public class ChatUI
{
public bool Visible;
public bool WithScreen = true;
public ChatService Service;
public Action<string, bool> OnSend;
public string HotkeyName = "F11";
public Func<string> PresetLabel;
public Action CyclePreset;
public Action ReloadConfig;
public Action DownloadOllama;
private Rect rect = new Rect(60f, 60f, 600f, 460f);
private Vector2 scroll;
private string input = "";
private GUIStyle wrapStyle;
private GUIStyle userStyle;
private GUIStyle aiStyle;
private GUIStyle hintStyle;
private int lastCount = -1;
private const int WindowId = 20180101;
public void Toggle()
{
Visible = !Visible;
}
public void OnGUI()
{
//IL_001e: Unknown result type (might be due to invalid IL or missing references)
//IL_002a: Unknown result type (might be due to invalid IL or missing references)
//IL_003e: Expected O, but got Unknown
//IL_0039: Unknown result type (might be due to invalid IL or missing references)
//IL_003e: Unknown result type (might be due to invalid IL or missing references)
if (Visible && Service != null)
{
EnsureStyles();
rect = GUI.Window(20180101, rect, new WindowFunction(DrawWindow), Lang.T("title"));
}
}
private void EnsureStyles()
{
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
//IL_001e: Expected O, but got Unknown
//IL_004a: Unknown result type (might be due to invalid IL or missing references)
//IL_0054: Expected O, but got Unknown
//IL_006e: Unknown result type (might be due to invalid IL or missing references)
//IL_007f: Unknown result type (might be due to invalid IL or missing references)
//IL_0089: Expected O, but got Unknown
//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
//IL_00c2: Expected O, but got Unknown
//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
if (wrapStyle == null)
{
wrapStyle = new GUIStyle(GUI.skin.label);
wrapStyle.wordWrap = true;
wrapStyle.fontSize = 13;
wrapStyle.richText = false;
userStyle = new GUIStyle(wrapStyle);
userStyle.normal.textColor = new Color(0.62f, 0.84f, 1f);
aiStyle = new GUIStyle(wrapStyle);
aiStyle.normal.textColor = new Color(0.78f, 1f, 0.78f);
hintStyle = new GUIStyle(GUI.skin.label);
hintStyle.fontSize = 12;
hintStyle.normal.textColor = new Color(0.6f, 0.6f, 0.6f);
}
}
private void DrawWindow(int id)
{
//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
//IL_0300: Unknown result type (might be due to invalid IL or missing references)
//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
//IL_03c3: Invalid comparison between Unknown and I4
//IL_0433: Unknown result type (might be due to invalid IL or missing references)
//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
//IL_03cd: Invalid comparison between Unknown and I4
//IL_03d0: Unknown result type (might be due to invalid IL or missing references)
//IL_03da: Invalid comparison between Unknown and I4
GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
if (GUILayout.Button(Lang.T("lang") + ": " + Lang.DisplayName(), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(88f) }))
{
Lang.Toggle();
}
if (GUILayout.Button(Lang.T("screen") + ": " + (WithScreen ? Lang.T("on") : Lang.T("off")), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(112f) }))
{
WithScreen = !WithScreen;
}
if (GUILayout.Button(Lang.T("clear"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(74f) }))
{
Service.Clear();
}
if (GUILayout.Button(Lang.T("reload"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(78f) }) && ReloadConfig != null)
{
ReloadConfig();
}
GUILayout.FlexibleSpace();
GUILayout.Label(HotkeyName + " " + Lang.T("hotkey_hint"), Array.Empty<GUILayoutOption>());
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
string text = ((PresetLabel != null) ? PresetLabel() : "");
if (GUILayout.Button(Lang.T("model") + ": " + text + " >", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }) && CyclePreset != null)
{
CyclePreset();
}
if (GUILayout.Button(Lang.T("download_ollama"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(104f) }) && DownloadOllama != null)
{
DownloadOllama();
}
GUILayout.EndHorizontal();
scroll = GUILayout.BeginScrollView(scroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandHeight(true) });
for (int i = 0; i < Service.History.Count; i++)
{
DrawEntry(Service.History[i]);
}
GUILayout.EndScrollView();
if (lastCount != Service.History.Count)
{
lastCount = Service.History.Count;
scroll.y = 999999f;
}
GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
GUI.SetNextControlName("ai_chat_field");
input = GUILayout.TextField(input, 800, (GUILayoutOption[])(object)new GUILayoutOption[2]
{
GUILayout.ExpandWidth(true),
GUILayout.Height(22f)
});
Rect lastRect = GUILayoutUtility.GetLastRect();
if (input.Length == 0)
{
GUI.Label(new Rect(((Rect)(ref lastRect)).x + 4f, ((Rect)(ref lastRect)).y + 3f, ((Rect)(ref lastRect)).width - 8f, ((Rect)(ref lastRect)).height), Lang.T("placeholder"), hintStyle);
}
bool enabled = !Service.Busy && input.Trim().Length > 0;
bool enabled2 = GUI.enabled;
GUI.enabled = enabled;
if (GUILayout.Button(Lang.T("send"), (GUILayoutOption[])(object)new GUILayoutOption[2]
{
GUILayout.Width(78f),
GUILayout.Height(22f)
}))
{
DoSend();
}
GUI.enabled = enabled2;
GUILayout.EndHorizontal();
if (!string.IsNullOrEmpty(Service.Status))
{
GUILayout.Label(Service.Status, Array.Empty<GUILayoutOption>());
}
GUILayout.EndVertical();
Event current = Event.current;
if ((int)current.type == 4 && ((int)current.keyCode == 13 || (int)current.keyCode == 271) && GUI.GetNameOfFocusedControl() == "ai_chat_field")
{
if (!Service.Busy && input.Trim().Length > 0)
{
DoSend();
}
current.Use();
}
GUI.DragWindow(new Rect(0f, 0f, ((Rect)(ref rect)).width, 22f));
}
private void DrawEntry(ChatEntry e)
{
string text;
GUIStyle val;
if (e.role == "user")
{
text = Lang.T("you") + ": ";
val = userStyle;
}
else if (e.role == "assistant")
{
text = Lang.T("ai") + ": ";
val = aiStyle;
}
else
{
text = Lang.T("sys") + ": ";
val = wrapStyle;
}
GUILayout.Label(text + e.text, val, Array.Empty<GUILayoutOption>());
GUILayout.Space(4f);
}
private void DoSend()
{
if (OnSend != null)
{
string arg = input;
input = "";
OnSend(arg, WithScreen);
}
}
}
public static class Lang
{
public const string ZH = "zh";
public const string EN = "en";
public static string Current;
private static readonly Dictionary<string, string> zh;
private static readonly Dictionary<string, string> en;
static Lang()
{
Current = "zh";
zh = new Dictionary<string, string>();
en = new Dictionary<string, string>();
zh["title"] = "TABS AI 助手";
zh["send"] = "发送";
zh["clear"] = "清空";
zh["close"] = "关闭";
zh["lang"] = "语言";
zh["screen"] = "附截图";
zh["on"] = "开";
zh["off"] = "关";
zh["placeholder"] = "输入问题,例如:敌方这套阵容该怎么打?";
zh["sending"] = "AI 思考中…";
zh["ready"] = "就绪";
zh["no_key"] = "未配置 API Key,请先在 BepInEx 配置文件中填写。";
zh["need_text"] = "请输入内容。";
zh["you"] = "你";
zh["ai"] = "AI";
zh["sys"] = "系统";
zh["capture"] = "正在截取画面…";
zh["captured"] = "已附带当前画面";
zh["capture_fail"] = "截图失败,本次不含画面";
zh["err"] = "出错";
zh["hotkey_hint"] = "开关面板";
zh["lang_switch"] = "已切换语言";
zh["model"] = "模型";
zh["switched"] = "已切换模型";
zh["no_vision"] = "该模型不支持看图,已自动关闭附截图";
zh["local_hint"] = "本地模型需先装 Ollama 并 pull 对应模型";
zh["reload"] = "重载配置";
zh["reloaded"] = "配置已重载";
zh["download_ollama"] = "下载 Ollama";
zh["ollama_hint"] = "已打开浏览器下载页。装完后打开命令行执行: ollama pull qwen2.5vl:7b";
zh["err_ssl"] = "SSL 证书错误:地址被拦或证书不匹配。本地 Ollama 请确认用 127.0.0.1";
zh["err_net"] = "连不上服务器:地址写错或被拦。本地 Ollama 需先运行 ollama serve";
zh["err_401"] = "API Key 无效或未填写,请在配置文件里填 ApiKey";
zh["err_429"] = "请求太频繁或额度用完,等一会儿再试";
zh["err_local"] = "连不上本地 Ollama:先运行 ollama serve,再 ollama pull 对应模型";
en["title"] = "TABS AI Assistant";
en["send"] = "Send";
en["clear"] = "Clear";
en["close"] = "X";
en["lang"] = "Lang";
en["screen"] = "Screen";
en["on"] = "On";
en["off"] = "Off";
en["placeholder"] = "Ask something, e.g. how to counter this enemy lineup?";
en["sending"] = "AI is thinking...";
en["ready"] = "Ready";
en["no_key"] = "No API key configured. Please fill it in the BepInEx config file.";
en["need_text"] = "Please type something.";
en["you"] = "You";
en["ai"] = "AI";
en["sys"] = "System";
en["capture"] = "Capturing screen...";
en["captured"] = "Current screen attached";
en["capture_fail"] = "Capture failed, sending without image";
en["err"] = "Error";
en["hotkey_hint"] = "toggles panel";
en["lang_switch"] = "Language switched";
en["model"] = "Model";
en["switched"] = "Model switched";
en["no_vision"] = "This model has no vision, screenshot disabled";
en["local_hint"] = "Local models need Ollama installed and the model pulled";
en["reload"] = "Reload";
en["reloaded"] = "Config reloaded";
en["download_ollama"] = "Get Ollama";
en["ollama_hint"] = "Download page opened. After installing, run: ollama pull qwen2.5vl:7b";
en["err_ssl"] = "SSL certificate error: blocked or bad cert. Use 127.0.0.1 for local Ollama";
en["err_net"] = "Cannot reach server: wrong URL or blocked. Run ollama serve first";
en["err_401"] = "Invalid or missing API key. Fill ApiKey in the config file";
en["err_429"] = "Rate limited or quota exhausted. Try again later";
en["err_local"] = "Cannot reach local Ollama. Run ollama serve, then ollama pull the model";
}
public static string T(string key)
{
if (((Current == "en") ? en : zh).TryGetValue(key, out var value))
{
return value;
}
return key;
}
public static void Toggle()
{
Current = ((Current == "en") ? "zh" : "en");
}
public static bool IsChinese()
{
return Current == "zh";
}
public static string AiLanguageDirective()
{
if (IsChinese())
{
return "Reply in Simplified Chinese (简体中文).";
}
return "Reply in English.";
}
public static string DisplayName()
{
if (IsChinese())
{
return "中文";
}
return "EN";
}
}
public class ProviderPreset
{
public string Name;
public string Endpoint;
public string Model;
public bool NeedsKey;
public bool Vision;
public ProviderPreset(string name, string endpoint, string model, bool needsKey, bool vision)
{
Name = name;
Endpoint = endpoint;
Model = model;
NeedsKey = needsKey;
Vision = vision;
}
}
public static class Providers
{
public const int CustomIndex = 4;
public static readonly ProviderPreset[] All = new ProviderPreset[5]
{
new ProviderPreset("本地 qwen2.5vl 7b 推荐", "http://127.0.0.1:11434/v1/chat/completions", "qwen2.5vl:7b", needsKey: false, vision: true),
new ProviderPreset("本地 qwen2.5vl 3b 轻量", "http://127.0.0.1:11434/v1/chat/completions", "qwen2.5vl:3b", needsKey: false, vision: true),
new ProviderPreset("本地 llava 7b", "http://127.0.0.1:11434/v1/chat/completions", "llava:7b", needsKey: false, vision: true),
new ProviderPreset("本地 gemma3 4b", "http://127.0.0.1:11434/v1/chat/completions", "gemma3:4b", needsKey: false, vision: true),
new ProviderPreset("自定义 用配置文件", "", "", needsKey: false, vision: true)
};
public static int Count => All.Length;
public static ProviderPreset Get(int index)
{
if (index < 0 || index >= All.Length)
{
return All[0];
}
return All[index];
}
public static int Clamp(int index)
{
if (index < 0)
{
return 0;
}
if (index >= All.Length)
{
return All.Length - 1;
}
return index;
}
public static bool IsCustom(int index)
{
return index == 4;
}
public static int Next(int index)
{
int num = index + 1;
if (num >= All.Length)
{
num = 0;
}
return num;
}
}
public static class ScreenGrab
{
public static IEnumerator Capture(int jpegQuality, Action<string> onDone)
{
yield return (object)new WaitForEndOfFrame();
Texture2D val = null;
string obj = null;
try
{
val = ScreenCapture.CaptureScreenshotAsTexture();
if ((Object)(object)val != (Object)null)
{
byte[] array = ImageConversion.EncodeToJPG(val, jpegQuality);
if (array != null && array.Length != 0)
{
obj = Convert.ToBase64String(array);
}
}
}
catch
{
obj = null;
}
finally
{
if ((Object)(object)val != (Object)null)
{
Object.Destroy((Object)(object)val);
}
}
onDone?.Invoke(obj);
}
}