diff --git a/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md b/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md deleted file mode 100644 index 1b3829a..0000000 --- a/.claude/plugins/local/rimworld-mod-dev/skills/rimworld-mod-dev/SKILL.md +++ /dev/null @@ -1,616 +0,0 @@ ---- -name: rimworld-mod-dev -description: This skill should be used when developing RimWorld mods, including creating C# Harmony patches, writing XML Defs, implementing AI integration for pawns or events, setting up mod structure, or debugging RimWorld mod issues. Activates for "rimworld mod", "harmony patch", "pawncomp", "incidentdef", "thinkTree", "storyteller", "jobgiver", "hediff", "defmodextension" topics. -version: 1.0.0 ---- - -# RimWorld Mod Development Skill - -This skill provides guidance for developing RimWorld mods, with a focus on C#/Harmony-based behavior modification and AI integration patterns. - ---- - -## Project Context - -- **Game version**: 1.5 / 1.6 -- **Target framework**: .NET Framework 4.8 (net48) -- **Required dependency**: Harmony (brrainz.harmony) - ---- - -## Mod Folder Structure - -``` -MyMod/ -├── About/ -│ ├── About.xml # Required: mod metadata, dependencies, supported versions -│ └── Preview.png # Required: 640x360 or 1280x720, < 1MB -├── Assemblies/ # Compiled DLL files -├── Defs/ # XML definitions (ThingDef, IncidentDef, etc.) -├── Patches/ # PatchOperations XML (safe cross-mod patching) -├── Languages/ # Localization files -│ └── English/ -│ └── Keyed/ -│ └── Keys.xml # Translation keys -├── Sounds/ # .ogg audio files -├── Textures/ # .png texture files (must be PoT: 32x32, 64x64, etc.) -├── Source/ # C# source code (not loaded by game) -│ └── MyMod/ -│ ├── MyModMain.cs -│ └── ... -└── LoadFolders.xml # Optional: conditional folder loading per version -``` - ---- - -## Core Technology Stack - -| Tech | Purpose | Notes | -|------|---------|-------| -| **Harmony** | Runtime method patching | Use PostFix over Prefix to reduce conflicts | -| **C# async/await** | AI API calls | Never block game main thread | -| **ConcurrentQueue** | Thread-safe result passing | Main thread consumes on next Tick | -| **ThingComp** | Per-pawn state storage | Serialized via ExposeData | -| **DefModExtension** | Extend XML Def fields | No C# subclassing needed | -| **Newtonsoft.Json** | JSON parsing | Already bundled in RimWorld | - ---- - -## AI Integration Pattern - -```csharp -// 1. Harmony patch on TickManager - runs every game tick -[HarmonyPatch(typeof(TickManager), "DoSingleTick")] -public static class TickManagerPatch -{ - static void Postfix() - { - // Consume AI results from queue (main thread safe) - while (AIRequestQueue.Results.TryDequeue(out var result)) - result.Apply(); - - // Enqueue new requests (triggers async AI call) - if (ShouldQueryAI()) - AIRequestQueue.Enqueue(new AIRequest(BuildContext())); - } -} - -// 2. Async AI call (runs on background thread) -public static async Task QueryAI(AIRequest request) -{ - var response = await httpClient.PostAsync(endpoint, content); - var result = ParseResponse(await response.Content.ReadAsStringAsync()); - AIRequestQueue.Results.Enqueue(result); -} -``` - ---- - -## Key Game Systems & How to Hook Them - -### Pawn Behavior (Jobs / ThinkTree) - -```csharp -// Force a pawn to do a specific job -pawn.jobs.StartJob(new Job(JobDefOf.GotoWander, targetCell), JobCondition.InterruptForced); - -// Hook into job giving (Harmony prefix on JobGiver_Work) -[HarmonyPatch(typeof(JobGiver_Work), "TryGiveJob")] -static void Postfix(Pawn pawn, ref Job __result) -{ - if (AIController.ShouldOverride(pawn)) - __result = AIController.GetAIJob(pawn); -} -``` - -### Incidents / Storyteller - -```csharp -// Custom StorytellerComp - AI selects which incident to fire -public class StorytellerComp_AIDirector : StorytellerComp -{ - public override IEnumerable MakeIntervalIncidents(IIncidentTarget target) - { - var chosen = AIDirector.GetNextIncident(target); // reads from result queue - if (chosen != null) - yield return new FiringIncident(chosen, this); - } -} -``` - -XML registration: -```xml - - AIDirectorStoryteller - -
  • - - -``` - -### Thoughts / Mood - -```csharp -// Add a thought (affects mood) -pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.SomeThought); - -// Remove a thought -pawn.needs.mood.thoughts.memories.RemoveMemoriesOfDef(thoughtDef); -``` - -### Mental States - -```csharp -// Trigger mental break -pawn.mindState.mentalStateHandler.TryStartMentalState( - MentalStateDefOf.Berserk, forceWake: true); -``` - -### Faction Relations - -```csharp -Faction.OfPlayer.TryAffectGoodwillWith(otherFaction, delta: 15, - lookTarget: pawn, reason: HistoryEventDefOf.GiftsGiven); -``` - ---- - -## ThingComp Pattern (Per-Pawn State) - -```csharp -// 1. Properties class -public class CompProperties_AIController : CompProperties -{ - public CompProperties_AIController() => compClass = typeof(CompAIController); -} - -// 2. Comp class with save/load -public class CompAIController : ThingComp -{ - public bool AIEnabled = false; - public string LastAIDecision = ""; - - public override void ExposeData() - { - base.ExposeData(); - Scribe_Values.Look(ref AIEnabled, "aiEnabled", false); - Scribe_Values.Look(ref LastAIDecision, "lastAIDecision", ""); - } -} - -// 3. XML patch to add comp to all Pawns -// Patches/AddAIComp.xml -``` - -```xml - - - /Defs/ThingDef[thingClass="Pawn"]/comps - -
  • - - - -``` - ---- - -## Harmony Patch Patterns - -```csharp -// PostFix: runs after original method, can modify result -[HarmonyPatch(typeof(TargetClass), "MethodName")] -public static class MyPatch -{ - static void Postfix(ref ReturnType __result, Pawn __instance, OtherParam param) - { - // __result = modified return value - // __instance = the object the method was called on - } -} - -// Prefix: runs before original, can skip original with return false -[HarmonyPatch(typeof(TargetClass), "MethodName")] -public static class MyPatch -{ - static bool Prefix(ref ReturnType __result, Pawn __instance) - { - if (ShouldSkip(__instance)) - { - __result = myResult; - return false; // skip original - } - return true; // run original - } -} -``` - ---- - -## About.xml Template - -```xml - - - My Mod - YourName - YourName.MyMod - -
  • 1.5
  • -
  • 1.6
  • - - My awesome mod. - -
  • - brrainz.harmony - Harmony - steam://url/CommunityFilePage/2009463077 -
  • -
    - -
  • brrainz.harmony
  • -
    - -``` - ---- - -## Mod Entry Point Pattern - -```csharp -using HarmonyLib; -using Verse; - -namespace MyMod -{ - public class MyModMain : Mod - { - public static MyModSettings Settings; - - public MyModMain(ModContentPack content) : base(content) - { - Settings = GetSettings(); - new Harmony("YourName.MyMod").PatchAll(); - } - - public override string SettingsCategory() => "My Mod"; - public override void DoSettingsWindowContents(Rect rect) - => Settings.DoWindowContents(rect); - } - - public class MyModSettings : ModSettings - { - public string ApiKey = ""; - public string Model = "gpt-4o-mini"; - public int CooldownTicks = 2500; // ~1 game hour - - public override void ExposeData() - { - Scribe_Values.Look(ref ApiKey, "apiKey", ""); - Scribe_Values.Look(ref Model, "model", "gpt-4o-mini"); - Scribe_Values.Look(ref CooldownTicks, "cooldownTicks", 2500); - } - } -} -``` - ---- - -## AI Context Building (Game State → Prompt) - -Key game state to include in AI prompts: - -```csharp -public static string BuildGameContext(Map map) -{ - var sb = new StringBuilder(); - // Colony stats - sb.AppendLine($"Colonists: {map.mapPawns.FreeColonists.Count}"); - sb.AppendLine($"Food: {map.resourceCounter.GetCount(ThingDefOf.MealSimple)}"); - sb.AppendLine($"Threat: {StorytellerUtility.GetThreatBiggestGoodwill(Faction.OfPlayer)}"); - // Recent events (from WorldComponent history) - // Current threats - foreach (var raid in map.attackTargetsCache.TargetsHostileToColony) - sb.AppendLine($"Threat: {raid.Thing.Label}"); - return sb.ToString(); -} -``` - ---- - -## Common XML Def Types - -| Def | Purpose | -|-----|---------| -| `ThingDef` (thingClass=Pawn) | Pawn/creature definition | -| `IncidentDef` | Events (raids, traders, etc.) | -| `StorytellerDef` | Storyteller configuration | -| `ThoughtDef` | Mood thoughts | -| `MentalStateDef` | Mental breaks | -| `JobDef` | Work job types | -| `HediffDef` | Health conditions/implants | -| `TraitDef` | Pawn traits | -| `InteractionDef` | Social interactions | -| `ThinkTreeDef` | AI behavior tree | -| `DutyDef` | Temporary behavior duties | - -## Performance Guidelines - -- AI calls: minimum 2500 ticks (~1 game hour) cooldown between calls per pawn -- Use `ConcurrentQueue` for all cross-thread data transfer -- Cache game state reads (don't traverse all pawns every tick) -- Use `ModsConfig.IsActive("packageId")` for conditional compatibility patches -- Limit AI context to ~500 tokens for routine decisions - ---- - -## Debugging - -```csharp -// Log to RimWorld debug log -Log.Message("[MyMod] Debug info here"); -Log.Warning("[MyMod] Something unexpected"); -Log.Error("[MyMod] Something broke"); - -// Dev mode actions (shows in debug menu) -[DebugAction("MyMod", "Trigger AI Event")] -static void TriggerAIEvent() { /* ... */ } -``` - -Enable dev mode in game: Options → Development Mode - ---- - -## Pitfalls & Lessons Learned - -### 1. UnityWebRequest 只能在主线程调用 - -**症状**:`UnityWebRequest.SendWebRequest()` 在 `Task.Run` 内调用时返回 HTTP 0,无任何错误日志。 - -**原因**:Unity 的 `UnityWebRequest` 不是线程安全的,必须在主线程发起。 - -**修复**:后台线程 HTTP 调用改用 `System.Net.Http.HttpClient`(net48 支持,线程安全): - -```csharp -private static readonly HttpClient _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; - -// 可在 Task.Run 内安全调用 -using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = content }; -req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); -using var res = await _httpClient.SendAsync(req); -``` - ---- - -### 2. OpenAI 兼容 API 的 FormatEndpoint 三段式逻辑 - -用户填写的 endpoint 格式不一,需统一处理: - -```csharp -private static string FormatEndpoint(string baseUrl) -{ - if (string.IsNullOrEmpty(baseUrl)) return string.Empty; - string trimmed = baseUrl.Trim().TrimEnd('/'); - // 已是完整 endpoint → 不变 - if (trimmed.EndsWith("/chat/completions", StringComparison.OrdinalIgnoreCase)) - return trimmed; - var uri = new Uri(trimmed); - string path = uri.AbsolutePath.Trim('/'); - // 有版本路径(如 /v1)→ 只追加 /chat/completions - if (!string.IsNullOrEmpty(path)) - return trimmed + "/chat/completions"; - // 裸域名 → 追加 /v1/chat/completions - return trimmed + "/v1/chat/completions"; -} -``` - -| 输入 | 输出 | -|------|------| -| `https://api.deepseek.com` | `https://api.deepseek.com/v1/chat/completions` | -| `https://api.deepseek.com/v1` | `https://api.deepseek.com/v1/chat/completions` | -| `https://api.deepseek.com/v1/chat/completions` | 原样返回 | - ---- - -### 3. net48 中禁止使用 `dynamic` 类型 - -**症状**:编译报错,缺少 `Microsoft.CSharp` 引用。 - -**替代方案**:用 Newtonsoft.Json 的 `JObject`: - -```csharp -// 不要用 dynamic -// dynamic obj = JsonConvert.DeserializeObject(text); // 编译失败 - -// 改用 JObject -var jobj = JObject.Parse(text); -string reply = jobj["choices"]?[0]?["message"]?["content"]?.ToString() ?? ""; -int tokens = jobj["usage"]?["total_tokens"]?.Value() ?? 0; -``` - ---- - -### 4. RimWorld 纹理必须是 2 的幂次方(PoT) - -**症状**:`Texture X.png is being reloaded with reduced mipmap count (clamped to 2) due to non-power-of-two dimensions: (24x24)` - -**原因**:RimWorld(Unity)要求 UI 纹理尺寸为 2 的幂次方(16、32、64…)。 - -**规则**: -- 不要用游戏内置的非 PoT 纹理(如 `UI/Buttons/Info` 是 24×24) -- 自己提供纹理放在 `Textures/UI/MyMod/Icon.png`,使用 32×32 或 64×64 - -```csharp -// 错误:复用游戏内置 24×24 纹理 -ContentFinder.Get("UI/Buttons/Info", reportFailure: false) - -// 正确:使用自己的 32×32 纹理 -ContentFinder.Get("UI/MyMod/Icon", reportFailure: false) -``` - ---- - -### 5. `[DebugAction]` Dev 菜单搜索按动作名,不按分类名 - -Dev 菜单搜索框只匹配**动作名称**,不匹配 category 参数。 - -```csharp -// category="MyMod", name="Test API Connection" -[DebugAction("MyMod", "Test API Connection", actionType = DebugActionType.Action)] -``` - -- 搜索 `"MyMod"` → **找不到** -- 搜索 `"Test API"` → **可以找到** -- 或者在 Actions 列表滚动到 "MyMod" 分类下查看 - ---- - -### 6. Keyed XML 不会产生翻译错误 - -"Translation data has X errors" 这条日志**只来自 `DefInjected/` 翻译文件**(key 与 Def 不匹配时触发)。 - -`Languages/*/Keyed/*.xml` 无论多余还是缺失 key 都**不会**触发该错误: -- 多余的 key → 静默忽略 -- 缺失的 key → 代码中显示 key 原文字符串 - -如果看到翻译错误,首先检查其他 mod 的 DefInjected 目录,而非自己的 Keyed 文件。 - ---- - -### 7. WorkGiver 三模式扫描:用 `wg.def.scanCells` 区分,而非类型判断 - -**背景**:枚举某 WorkType 可执行目标时,WorkGiver 有三种工作模式。 - -**错误做法**:`if (scanner is WorkGiver_Grower)` — 只覆盖 Growing,漏掉 SmoothWall、BuildRoof、RemoveRoof、ClearSnow、PaintFloor 等 8 个格子类 WorkGiver。 - -**正确做法**:用 `wg.def.scanCells` 属性区分,与具体类型无关: - -```csharp -foreach (var wg in workType.workGiversByPriority) -{ - if (wg.Worker is not WorkGiver_Scanner scanner) continue; - - if (wg.scanCells) - { - // 格子类:Growing / SmoothWall / BuildRoof / RemoveRoof / - // ClearSnow / PaintFloor / ClearPollution 等 - var cells = scanner.PotentialWorkCellsGlobal(pawn); - foreach (var cell in cells) - { - if (scanner.HasJobOnCell(pawn, cell, false)) - // 处理 cell 目标 - } - } - else - { - // 物体类(默认):Mining / Hauling / Tend / Hunt 等 - // DoBill 工作台(Cooking / Crafting / Smithing)也在此分支, - // 额外通过 IBillGiver.BillStack.FirstShouldDoNow 获取账单名称 - var things = scanner.PotentialWorkThingsGlobal(pawn); - foreach (var thing in things) - { - if (scanner.HasJobOnThing(pawn, thing, false)) - // 处理 thing 目标 - } - } -} -``` - -`IBillGiver` 账单名称: -```csharp -if (thing is IBillGiver billGiver) -{ - var bill = billGiver.BillStack?.FirstShouldDoNow; - label = bill != null ? $"{thing.LabelShort} → {bill.LabelCap}" : thing.LabelShort; -} -``` - -所有 WorkGiver 调用包在 `try-catch` 内,部分 WorkGiver 在特定地图状态下会抛异常。 - ---- - -### 8. 插件 API 可扩展分类:C# 8 接口默认方法代替硬编码 HashSet - -**问题**:`ExecuteBatch` 需要知道哪些动作是 Job 类(需要 `requestQueueing`),原实现用硬编码 HashSet: -```csharp -// 脆弱:外部 mod 注册的 Job 类动作不在此集合中 -private static readonly HashSet _jobBasedIntents = new() { "force_rest", "assign_work", ... }; -``` - -**修复**:用 C# 8 接口默认方法声明扩展点: -```csharp -public interface IActionRule -{ - bool IsJobBased => false; // 默认非 Job 类;Job 类实现覆盖为 true - bool Execute(Pawn actor, Pawn? target, string? param, bool requestQueueing = false); -} - -// 内置 Job 类动作 -public class ForceRestAction : IActionRule -{ - public bool IsJobBased => true; - // ... -} - -// ExecuteBatch 直接读属性,无需查 HashSet -bool isJobAction = rule.IsJobBased; -``` - -**优点**:外部 mod 注册自定义 Job 类动作时,只需在自己的类中声明 `public bool IsJobBased => true;`,框架代码无需改动。 - ---- - -### 9. RimWorld AI 空闲判断:GotoWander ≠ 游戏空闲,但 = AI 可接管 - -**问题**:`pawn.jobs.curJob == null` 不足以判断"AI 是否可以重定向小人"。 - -- `GotoWander`:小人在漫步,`curJob != null`,游戏认为不空闲 -- `playerForced = true`:玩家手动命令的 Job,AI 不应打断 - -**正确的 AI 可接管判断**: - -```csharp -public static bool IsAdvisorIdle(Pawn pawn) -{ - var job = pawn.jobs?.curJob; - if (job == null) return true; - if (job.playerForced) return false; // 玩家命令优先 - - // 这些 Job 类型 AI 可安全打断 - var def = job.def; - return def == JobDefOf.Wait - || def == JobDefOf.Wait_Wander - || def == JobDefOf.GotoWander - || def == JobDefOf.Wait_MaintainPosture; -} -``` - -调试输出应明确区分:`"是否空闲(AI 可接管)"` 而非 `"游戏空闲"`,避免概念混淆。 - ---- - -### 10. ModSettings 孤儿条目:warn 但不删除,保留以备 mod 重启恢复 - -**场景**:玩家禁用了某外部 mod 的某动作(存入 `DisabledIntents`),然后卸载该外部 mod。 -下次加载时该 intentId 不再注册,但 `DisabledIntents` 仍保存着它。 - -**策略**:`[StaticConstructorOnStartup]`(所有 Mod 构造器完成后运行,此时所有动作已注册)中验证并 **warn 但不删除**: - -```csharp -[StaticConstructorOnStartup] -internal static class ActionsSettingsValidator -{ - static ActionsSettingsValidator() - { - if (MyModMain.Settings == null) return; - var registered = new HashSet(MyModAPI.GetSupportedIntents()); - foreach (var id in MyModMain.Settings.DisabledIntents) - { - if (!registered.Contains(id)) - Log.Warning($"[MyMod] 设置中有未注册的动作 '{id}'(对应 mod 未加载?),已保留以备恢复。"); - } - } -} -``` - -**为什么不删除**:若玩家重新启用该外部 mod,孤儿条目会自动重新生效,无需玩家重新配置。 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fb71105..d7378da 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,11 +1,13 @@ name: Unit Tests on: + workflow_dispatch: push: branches: [main, master] paths: - 'Source/**' - 'Tests/**' + - 'IntegrationTests/**' - 'ArchTests/**' - '.github/workflows/test.yml' pull_request: @@ -13,6 +15,7 @@ on: paths: - 'Source/**' - 'Tests/**' + - 'IntegrationTests/**' - 'ArchTests/**' - '.github/workflows/test.yml' diff --git a/AGENTS.md b/AGENTS.md index 3b5fb25..187622d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ AI对话系统,拦截游戏事件生成上下文对话,注入Thought,支 ## 项目定位 -通过Harmony Patch监听Chitchat/Hediff/技能升级/心情变化 → `RimMindDialogueService.HandleTrigger` → `DialogueRequestCoordinator`(挂载 `DialogueToolDefinitions.ExpressDialogue` 原生工具定义) → `RimMindAPI.Request.Send` → `NpcResponseHandler.Handle`(调用 `DialogueToolParser.Parse` 与 `DialogueTextSanitizer` 防污染清洗解析 `reply`/`thought`/`relation_delta`) → `ThoughtInjector` 注入独白/关系Thought。请求、活动状态、日志和响应副作用各有单一入口。 +通过Harmony Patch监听Chitchat/Hediff/技能升级/心情变化 → `RimMindDialogueService.HandleTrigger` → `DialogueRequestCoordinator`(挂载 `DialogueToolDefinitions.ExpressDialogueTool` 原生工具定义,自动触发附带 `CoalesceKey`、`MaxQueueWaitTicks=5000` 与 `RequireAliveColonist=true`) → `RimMindAPI.Request.Send` → `NpcResponseHandler.Handle`(调用 `DialogueToolParser.TryParse` 与 `DialogueTextSanitizer` 防污染清洗解析 `speech`/`thought_tag`/`thought_desc`/`relation_delta`) → `ThoughtInjector` 注入独白/关系Thought。请求、活动状态、触发元数据、日志和响应副作用各有单一入口。 依赖: Core(编译期)。可选 Memory 集成使用 Core 公共 `RimMindAPI.Memory`,不引用 Memory 实现程序集。 @@ -16,42 +16,43 @@ AI对话系统,拦截游戏事件生成上下文对话,注入Thought,支 | 项 | 值 | |----|-----| -| Target | net48, C#9.0, Nullable enable | -| Output | `../1.6/Assemblies/` | +| Target | `net48` (1.6) / `net10.0` (1.7), C#9.0, Nullable enable | +| Output | `../$(GameVersion)/Assemblies/` | | Assembly | RimMindDialogue, RootNS: RimMind.Dialogue | | Harmony ID | mcocdaa.RimMindDialogueStandalone | -| 依赖 | RimMindCore.dll, Krafs.Rimworld.Ref, Lib.Harmony.Ref, Newtonsoft.Json | +| 依赖 | 0_RimMindDomain.dll, 1_RimMindApplication.dll, 2_RimMindCore.dll (`Private=false`), Krafs.Rimworld.Ref, Lib.Harmony.Ref, Newtonsoft.Json | ## 源码结构 ``` Source/ -├── RimMindDialogueMod.cs 组合入口、Harmony与Core扩展注册 +├── RimMindDialogueMod.cs 组合入口、Harmony与Core扩展注册(含 DialogueRequestTraceSummarizer) ├── Core/ │ ├── DialogueContextProviderRegistrar.cs 四个Core上下文Provider的唯一注册入口(经 MainThreadSnapshot 主线程读取) +│ ├── DialogueTriggerRegistry.cs TriggerType元数据单一事实来源(TriggerKind/Label/Prompt/LogColor + 自定义标签) │ ├── README.md 对话生命周期入口地图 │ ├── RimMindDialogueService.cs 公共兼容门面与轻量事件边界 │ ├── DialogueRequestCoordinator.cs 请求门控、派发与完成清理 -│ ├── DialogueActivityState.cs 冷却、配额、接收者与Pawn查询(委托 RimMindPawnLookup) +│ ├── DialogueActivityState.cs 冷却(KeyedCooldownGate)、配额、接收者与Pawn查询(委托 RimMindPawnLookup) │ ├── DialogueLogStore.cs 按时间与序列号有序的有界日志(List + _sync锁, 上限500)与 Revision 版本号 │ ├── DialogueService.cs 玩家兼容入口,直接进入同一请求协调器 │ ├── DialogueToolDefinitions.cs express_dialogue 原生 ToolCall 定义 │ ├── DialogueToolParser.cs 双模式工具调用解析器(优先 ToolCalls,回退结构化内容) │ ├── DialogueTextSanitizer.cs 多级防污染文本清洗管线(剥离 /代码围栏/裸JSON) │ ├── NpcResponseHandler.cs 统一响应处理(自动+玩家对话共用,含感知发布与存活/倒地校验) -├── Comps/CompRimMindDialogue.cs ThingComp(RimMindPawnLookup.IsEligibleColonist + Awake 过滤, 1000tick检查) +├── Comps/CompRimMindDialogue.cs ThingComp(RimMindPawnLookup.IsEligibleColonist + Awake 过滤, 250tick采样) +├── Extensions/ Core扩展适配器(SkipCheck/ModCooldown/SettingsTab/OverlayToggle/TriggerAdapter/RequestTraceSummarizer) ├── UI/Window_Dialogue.cs / Window_DialogueLog.cs / DialogueOverlay.cs ├── Thoughts/ThoughtInjector.cs + Thought_RimMindDialogue.cs + Thought_RelationDialogue.cs ├── Patches/ 7个Patch(Bubble/Hediff/SkillLearn/Thought/FloatMenu/GameLoad/AddComp) ├── Debug/DialogueDebugActions.cs 调试操作(Force触发/状态查看/冷却清除) └── Settings/ - ├── RimMindDialogueSettings.cs 设置模型与持久化 - └── DialogueSettingsDrawer.cs 设置页UI绘制(全Tooltip提示) + └── RimMindDialogueSettings.cs 设置模型、持久化与设置页UI绘制(委托 SettingsUIDrawer) ``` ## 统一请求生命周期 -自动触发通过 `RimMindDialogueService.HandleTrigger`,玩家输入通过 `DialogueService.RequestReply`,两者直接进入同一个 `DialogueRequestCoordinator`:总开关(玩家另查玩家开关)→ 参与者有效性(`RimMindPawnLookup.IsEligibleColonist` 且 `!Downed`)→ API配置 → IsReady → Pawn pending → ShouldSkipDialogue → 自动冷却/配额策略 → 原子 Pawn/Pair/全局容量预约 → 唯一 `RimMindAPI.Request.Send`(携带 `DialogueToolDefinitions.ExpressDialogue`)。 +自动触发通过 `RimMindDialogueService.HandleTrigger`,玩家输入通过 `DialogueService.RequestReply`,两者直接进入同一个 `DialogueRequestCoordinator`:总开关(玩家另查玩家开关)→ 参与者有效性(`RimMindPawnLookup.IsActiveSpawnedColonist` 且 `!Downed`)→ API配置 → IsReady → Pawn pending → ShouldSkipDialogue → 自动冷却/配额策略 → 原子 Pawn/Pair/全局容量预约 → 唯一 `RimMindAPI.Request.Send`(携带 `DialogueToolDefinitions.ExpressDialogueTool`)。 玩家多轮输入不消耗自动每日配额或独白冷却;自动 A-B 回复仍连续进行,由独立 pair reply limiter 限制。 @@ -67,13 +68,14 @@ Source/ | CONNECTED | +2 | RimMind.Dialogue.Thought.CONNECTED | 感到亲近 | | STRESSED | -2 | RimMind.Dialogue.Thought.STRESSED | 感到压力 | | IRRITATED | -1 | RimMind.Dialogue.Thought.IRRITATED | 感到烦躁 | +| INSPIRED | +2 | RimMind.Dialogue.Thought.INSPIRED | 深受鼓舞 | 外部mod可通过 `ThoughtInjector.RegisterThoughtTag(tag, moodOffset, labelKey)` 注册自定义标签。 ## 上下文注入 - `dialogue_state` / `dialogue_relation`: ContextKeyRegistry(L3_State),通过 `RimMindAPI.MainThreadSnapshot.GetAsync` 在主线程读取思绪与社交关系 -- `dialogue_task`: ContextKeyRegistry(L0_Static, 仅 `ScenarioIds.Dialogue`, `SpeakerName` 为空时通过主线程快照构建 TaskInstruction) +- `dialogue_task`: ContextKeyRegistry(L0_Static, 覆盖 `ScenarioIds.Dialogue` 与 `ScenarioIds.CrisisDialogue`,按 `IsMonologue`/`SpeakerName` 动态组装 TaskInstruction) - `dialogue_history`: ContextKeyRegistry(L4_History),通过主线程快照读取最近相关对话历史 > 注:原 `player_dialogue_task` provider 已于 2026-07-08 审查删除——Core 的 `ContextOrchestrator` 在所有 `BuildContext` 构造路径中将 `SpeakerName` 硬编码为 null,该 provider 触发条件(SpeakerName 非空)永不满足,属不可达死代码。归档于 `Refs/backup/RimMind-Dialogue/RimMindDialogueMod.player_dialogue_task.cs`。 diff --git a/About/About.xml b/About/About.xml index 868da32..06753b4 100644 --- a/About/About.xml +++ b/About/About.xml @@ -14,7 +14,7 @@ Contextual social dialogue, native spoken ToolCalls, and overhead speech bubble [b]v2.0 Clean Architecture & RimWorld 1.6 / 1.7 Dual-Version Support:[/b] [list] [*][b]RimWorld 1.6 & 1.7 (Waylith / .NET 10) Ready[/b]: Native multi-target compilation supporting both RimWorld 1.6 (.NET Framework 4.8) and RimWorld 1.7 (.NET 10 / Harmony 2.x & 3.x). -[*][b]v2.0 Native [code]express_dialogue[/code] ToolCall Pipeline[/b]: Transmits spoken lines ([code]reply[/code]), inner psychological subtext ([code]thought[/code]), and relationship delta ([code]relation_delta[/code]) as structured tool calls. Note: v1.x saves are not compatible with v2.0. +[*][b]v2.0 Native [code]express_dialogue[/code] ToolCall Pipeline[/b]: Transmits spoken lines ([code]speech[/code]), inner psychological subtext ([code]thought_tag[/code] / [code]thought_desc[/code]), and relationship delta ([code]relation_delta[/code]) as structured tool calls. Note: v1.x saves are not compatible with v2.0. [*][b]Multi-Stage Anti-Pollution Sanitizer[/b]: [code]DialogueTextSanitizer[/code] strips [code]think[/code] reasoning blocks, code fences, and raw JSON fragments so overhead speech bubbles remain 100% clean and immersive. [/list] @@ -29,7 +29,7 @@ RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with L [tr][td]RimMind-Advisor[/td][td]Colonist self-reflective advice cards, 5-domain autonomy & player approval[/td][td]Core, Actions[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Advisor]Link[/url][/td][/tr] [tr][td][b]RimMind-Dialogue[/b][/td][td]Contextual spoken dialogue via express_dialogue ToolCall & speech bubbles[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Dialogue]Link[/url][/td][/tr] [tr][td]RimMind-Memory[/td][td]3-Tier cognitive memory hierarchy, work aggregation & temporal decay[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Memory]Link[/url][/td][/tr] -[tr][td]RimMind-Personality[/td][td]Big-Five psychological profiles, dawn monologues & dynamic mood thoughts[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Personality]Link[/url][/td][/tr] +[tr][td]RimMind-Personality[/td][td]LLM psychological profiles, state-transition reflections & dynamic mood thoughts[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Personality]Link[/url][/td][/tr] [tr][td]RimMind-Storyteller[/td][td]AI Story Director, dramatic tension curve, chained arcs & Storyteller Altar[/td][td]Core, Memory[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Storyteller]Link[/url][/td][/tr] [tr][td]RimMind-Extension-ModelService[/td][td]Multi-provider routing, Anthropic KV cache, local gateways & load balancing[/td][td]Core[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Extension-ModelService]Link[/url][/td][/tr] [tr][td]RimMind-Bridge-RimChat[/td][td]RimChat compatibility bridge: dialogue/action mutual exclusion & context sync[/td][td]Core, RimChat[/td][td][url=https://github.com/RimWorld-RimMind-Mod/RimWorld-RimMind-Mod-Bridge-RimChat]Link[/url][/td][/tr] @@ -47,7 +47,7 @@ RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with L [list] [*][b]Event-Responsive & Proximity Banter[/b] - Replaces vanilla Chitchat and DeepTalk with context-aware AI conversations when awake colonists are within 6.9 tiles during dining, crafting, or relaxation, plus monologues on injuries, skill milestones, and mood swings. [*][b]Player-Initiated Multi-Turn Chat[/b] - Start direct conversations via pawn Gizmo buttons or right-click menus with persistent session memory. -[*][b]Dynamic Relationship & Thought Injection[/b] - Conversations apply real-time social opinion modifiers (-5 to +5) and inject emotional Thoughts ([i]ENCOURAGED, VALUED, CONNECTED, HURT, STRESSED, IRRITATED[/i]) that affect colonist mood and notify [code]RimMind-Advisor[/code]. +[*][b]Dynamic Relationship & Thought Injection[/b] - Conversations apply real-time social opinion modifiers (-5 to +5) and inject emotional Thoughts ([i]ENCOURAGED, VALUED, CONNECTED, INSPIRED, HURT, STRESSED, IRRITATED[/i]) that affect colonist mood and notify [code]RimMind-Advisor[/code]. [*][b]Strict Liveness & Consciousness Gating[/b] - Guarded by [code]RimMindPawnLookup[/code] so sleeping, downed, dead, imprisoned, or off-map pawns never emit ghost dialogues. [*][b]Draggable Floating Chat HUD & History Log[/b] - Real-time corner dialogue overlay with adjustable opacity, plus a categorized dual-panel conversation log window. [/list] @@ -65,7 +65,7 @@ RimMind is an enterprise-grade, AI-powered RimWorld mod suite. Integrated with L [h2]Thought Tags & Mood Impacts[/h2] [table] [tr][th]Tag[/th][th]Mood Offset[/th][th]Description[/th][/tr] -[tr][td]VALUED / CONNECTED[/td][td]+2[/td][td]Feeling appreciated and emotionally close to companions[/td][/tr] +[tr][td]VALUED / CONNECTED / INSPIRED[/td][td]+2[/td][td]Feeling appreciated, emotionally close, or deeply inspired[/td][/tr] [tr][td]ENCOURAGED[/td][td]+1[/td][td]Reassured by supportive words[/td][/tr] [tr][td]HURT / IRRITATED[/td][td]-1[/td][td]Stung or annoyed by friction in conversation[/td][/tr] [tr][td]STRESSED[/td][td]-2[/td][td]Weighed down by tense exchanges[/td][/tr] diff --git a/INTRODUCTION.txt b/INTRODUCTION.txt deleted file mode 100644 index f7bd0f3..0000000 --- a/INTRODUCTION.txt +++ /dev/null @@ -1,90 +0,0 @@ -═══════════════════════════════════════════════════════════════ - RimMind-Dialogue — 你的殖民者,终于会说话了 -═══════════════════════════════════════════════════════════════ -[h1]RimMind - Dialogue (生动对话与社交)[/h1] - -[i]你的殖民者,终于开口说话了——充满人情味的日常闲聊、晨曦独白与灵魂倾诉。[/i] -[i]Your colonists finally speak — Contextual banter, dawn soliloquies, and dynamic social bonds.[/i] - -▌ 他们不再是沉默的棋子 -[hr] -[h2]📖 中文介绍 / Chinese Overview[/h2] - -你有没有注意过——殖民者受伤了只会趴下,心情崩溃了只会掉效率,技能升级了只是数字跳动。他们从不表达。 -[b]RimMind-Dialogue[/b] 赋予殖民者生动的语言与社交能力。无论是并肩劳作、食堂用餐,还是在娱乐室掷马蹄铁,殖民者都会根据彼此的关系与心境自然展开交谈。 - -RimMind-Dialogue 改变了这一点。 -[h3]🌟 核心特性[/h3] -[list] -[*] [b]情境化自然社交[/b]:自动识别殖民地日常场景(食堂共餐、工坊同工、娱乐室对弈、晨光初现),自然促发对话与独白,杜绝机械化定时打卡。 -[*] [b]原生 ToolCall 架构[/b]:全面收敛至 `express_dialogue` 工具调用,彻底消除原始 JSON 报文残留,只呈现纯粹口语化的人情味对白。 -[*] [b]真实好感度与心情回响[/b]:每句对白都会根据情感倾向实时增减双方好感度(-5 到 +5),并在心情面板生成对应的心理 Thought。 -[*] [b]玩家直接交互[/b]:右键小人即可直接开启对话窗口,自由打字交流,听小人倾诉烦恼或表达忠诚。 -[*] [b]精美头顶气泡与浮窗[/b]:沉浸式游戏内对白气泡,配合轻量日志浮窗,绝不错过任何精彩互动。 -[/list] - -受伤的殖民者会喊疼,被救回来会庆幸,心情跌到谷底会倾诉委屈,技能突破会忍不住炫耀。这些不是预设台词——AI 根据每个人的人格、关系和处境实时生成,每次都不一样。 -[hr] -[h2]🌐 English Overview[/h2] - -[b]RimMind-Dialogue[/b] brings true voice and organic relationships to your colony. Colonists actively converse while sharing meals, working side-by-side in crafting rooms, relaxing in recreation halls, or greeting the morning sun. - -▌ 他们会互相说话——而且真的影响关系 -[h3]🌟 Key Highlights[/h3] -[list] -[*] [b]Context-Aware Organic Interactions[/b]: Automatically triggers lively chatter during dining, recreation, crafting, or dawn contemplation. -[*] [b]Native ToolCall Pipeline[/b]: Powered by the robust `express_dialogue` schema, ensuring natural dialogue free from JSON formatting artifacts. -[*] [b]Meaningful Social & Mood Impacts[/b]: Every conversation actively modifies mutual pawn relationships and injects psychological thoughts. -[*] [b]Direct Player-to-Colonist Chat[/b]: Right-click any pawn to open a direct interactive dialog window and converse freely. -[*] [b]In-Game Overhead Bubbles[/b]: Beautiful floating speech bubbles above pawns' heads keep the colony vibrant without clutter. -[/list] - -两个殖民者闲聊时,AI 生成真正的对话。不是"他们聊了聊"就完了——一句话可能让对方感到被重视,也可能无意中刺痛了对方。 - -好感度真的会变。你会在关系面板看到"和 XX 聊天后感到亲近"或"被 XX 的话刺痛了"。这些变化影响后续互动、心情、甚至社交选择。一次不愉快的对话可能埋下长期矛盾的种子。 - - -▌ 你可以亲自和他们说话 - -右键点击附近的人,选择"对话"——聊天窗口打开,你直接打字和这个小人对话。 - -这不是对话树。问任何问题、安慰他们、训斥他们、或者只是闲聊。AI 根据人格和状态回应,你说的每句话都可能改变他们的心情和关系。 - -殖民者面板上还有对话按钮,随时打开聊天窗口多轮对话。 - - -▌ 对话会触发连锁反应 - -A 对 B 说话后,B 可能自动回复——形成真正的来回对话,而不是各说各的。完整记录在日志中,随时回顾。 - -装了 RimMind-Memory,对话写入长期记忆,影响未来行为。装了 RimMind-Actions,AI 甚至能在对话中触发游戏内行动。 - - -▌ 屏幕浮窗不错过任何对话 - -右下角浮窗实时显示最近对话,不同类型用不同颜色——独白、对话、玩家对话一目了然。可拖拽移动、调整大小,或随时关闭。 - - -▌ 每种触发都能独立控制 - -不想自动闲聊?关掉。只想看心情触发的独白?只保留那个。所有触发类型可独立开关,还有冷却时间、每日上限等细粒度控制。 - - -▌ 和 RimMind 套件无缝协作 - -RimMind-Dialogue 可独立运行,同时安装其他 RimMind 模组效果更佳: - - · RimMind-Personality — 人格档案影响对话风格 - · RimMind-Memory — 对话写入长期记忆 - · RimMind-Actions — AI 在对话中触发行动 - - -═══════════════════════════════════════════════════════════════ - 一句话:让殖民者从沉默的数据变成有血有肉的角色。 -═══════════════════════════════════════════════════════════════ -[hr] -[h2]⚙️ 依赖与推荐 / Requirements & Recommendations[/h2] -[list] -[*] [b]必需前置 (Required)[/b]: Harmony, [b]RimMind-Core[/b] -[*] [b]推荐搭配 (Recommended)[/b]: [b]RimMind-Personality[/b](赋予差异化口吻)、[b]RimMind-Memory[/b](对话记入长期记忆) -[/list] diff --git a/Languages/ChineseSimplified/Keyed/RimMind_Dialogue.xml b/Languages/ChineseSimplified/Keyed/RimMind_Dialogue.xml index d02205c..860e167 100644 --- a/Languages/ChineseSimplified/Keyed/RimMind_Dialogue.xml +++ b/Languages/ChineseSimplified/Keyed/RimMind_Dialogue.xml @@ -46,6 +46,8 @@ 中等 低 吸引力: {0} ({1},{2}) + 较有可能发展浪漫关系 + 存在一定浪漫可能 不太可能发展浪漫关系 关系: {0} [近期对话历史](严禁机械复读或重复上一轮已经抱怨过的话题,请从具体工作细节或彼此关切展开): @@ -140,31 +142,22 @@ 3. 生成符合角色性格的对话/独白 4. 评估对话对情绪的影响 保持人设一致;不要打破第四面墙;对话15~40字,独白15~40字。重要准则:已故或离场角色(标注有[deceased]或[lost])严禁作为现场活人进行互动或当面对话,只能作为过往回忆或哀思进行单向怀念。严禁模仿前文的括号动作描写或身体动作,请输出独创的自然对话。三大刚性约束:1. 环境客观物理锚点(严禁气温错乱):必须严格遵循当前环境气温与季节。在严冬寒冷天气(低于0°C)严禁提及“防暑”、“热浪”、“风沙”等反差概念;在室内严禁凭空编造风沙。2. 拒绝全员乖宝宝,呈现废土真实情绪:当角色遭遇严寒(Chilly/Cold)、黑暗、衣衫破烂(Tattered apparel)、剧痛、极饿、被侮辱等负面状态,或心情低落时,严禁使用虚假正能量、违背情境的夸赞或过度礼貌的乖宝宝客套话;应当自然表达抱怨、对恶劣天气的咒骂、冷言冷语、暴躁发泄、宿命感叹或厌世烦躁。3. 去重防复读:严禁出现“炖菜好喝/比昨天好”、“整理建材”等跨人跨天的固定模板套话,台词必须针对当前的真实情境即兴展开。 - 如果无法生成,返回 {"reply":"...","thought":{"tag":"NONE","description":"无特殊情绪"}}。 - 你可以通过 relation_delta 字段改变对话双方的好感度。范围 -5 到 +5,正值提升好感,负值降低好感。根据对话内容和当前关系决定:友好对话可能+1~+3,争吵可能-2~-5。如果对话内容不涉及关系变化,不要输出此字段。 + 如果无法生成,请调用 express_dialogue 工具并填入 speech "..."、thought_tag "NONE"、thought_desc "无特殊情绪"。 + 你可以通过 relation_delta 字段改变对话双方的好感度。范围 -5 到 +5,正值提升好感,负值降低好感。根据对话内容和当前关系决定:友好对话可能+1~+3,争吵可能-2~-5。如果对话内容不涉及关系变化,填 0。 独白示例1(受冻与咒骂):输入:小人心情30%,严冬-12°C,衣衫破烂 -输出:{"reply":"见鬼的天气,冻得我骨头都在抽痛,这破衣服连风都挡不住!","thought":{"tag":"STRESSED","description":"严寒刺骨且衣衫褴褛"}} +调用 express_dialogue:{"speech":"见鬼的天气,冻得我骨头都在抽痛,这破衣服连风都挡不住!","thought_tag":"STRESSED","thought_desc":"严寒刺骨且衣衫褴褛"} 独白示例2(剧痛与疲惫):输入:小人心情38%,战斗负伤,极度疲倦 -输出:{"reply":"伤口火辣辣地疼,骨头都快散架了……真想倒头睡死过去。","thought":{"tag":"HURT","description":"被创伤与劳累折磨"}} +调用 express_dialogue:{"speech":"伤口火辣辣地疼,骨头都快散架了……真想倒头睡死过去。","thought_tag":"HURT","thought_desc":"被创伤与劳累折磨"} 对话示例1(同伴摩擦/暴躁排斥):输入:小人在严寒中挨冻饥饿、心情烦躁,同伴前来搭话 -输出:{"reply":"别在这时候来烦我!没看我都快冻僵了吗?离我远点!","thought":{"tag":"IRRITATED","description":"饥寒交迫时被打扰"},"relation_delta":-2} +调用 express_dialogue:{"speech":"别在这时候来烦我!没看我都快冻僵了吗?离我远点!","thought_tag":"IRRITATED","thought_desc":"饥寒交迫时被打扰","relation_delta":-2} 对话示例2(冷言冷语/反唇相讥):输入:同伴说风凉话或态度傲慢,引发争执 -输出:{"reply":"少冲我指手画脚,管好你自己那堆破烂建材再说!","thought":{"tag":"IRRITATED","description":"反唇相讥同伴的说教"},"relation_delta":-3} +调用 express_dialogue:{"speech":"少冲我指手画脚,管好你自己那堆破烂建材再说!","thought_tag":"IRRITATED","thought_desc":"反唇相讥同伴的说教","relation_delta":-3} 对话示例3(患难互助/求生温情):输入:干完苦差,与熟识同伴烤火 -输出:{"reply":"Alex,先把这堆木头搬进去吧,炉子边暖和,我给你留了碗热水。","thought":{"tag":"CONNECTED","description":"在恶劣严冬中抱团取暖"},"relation_delta":1} - 只返回 JSON: -{"reply":"独白文本","thought":{"tag":"ENCOURAGED|HURT|VALUED|CONNECTED|STRESSED|IRRITATED|INSPIRED|NONE","description":"≤15字"}} - 只返回 JSON: -{"reply":"对话文本","thought":{"tag":"ENCOURAGED|HURT|VALUED|CONNECTED|STRESSED|IRRITATED|INSPIRED|NONE","description":"≤15字"},"relation_delta":0} - thought.tag 选择:严寒受冻/极度饥饿/破衣烂衫/繁重劳役/心情<40%→STRESSED;身体伤痛/创伤流血/重病虚弱→HURT;被同伴冒犯/言语冲突/烦躁被打扰/冷遇受气→IRRITATED;感受到同伴关怀/被照料→VALUED;废土抱团取暖/主动关怀同伴→CONNECTED;受到振奋鼓励→ENCOURAGED;领悟或获得灵感→INSPIRED;无特殊情绪波动→NONE。 - 请调用 express_dialogue 工具:填写 speech(台词正文)、thought_tag(情绪标签)、thought_desc(简短原因)与 relation_delta(对交流对象好感变动 -5~+5)。 - 请调用 express_dialogue 工具:填写 speech(内心独白)、thought_tag(情绪标签)与 thought_desc(简短原因)。 - 角色约束:此人是囚犯。语气应警惕、犹豫,提及被关押,可能乞求或讨价还价。 - 角色约束:此人是奴隶。语气应恐惧、顺从,提及强制劳动和疲惫,称呼殖民者为"主人"。 - 角色约束:此人是敌人。语气应敌对、攻击性,使用简短的命令或威胁。 - 角色约束:此人是访客。语气应礼貌、好奇、恭敬,将同行的其他访客视为同伴。 +调用 express_dialogue:{"speech":"Alex,先把这堆木头搬进去吧,炉子边暖和,我给你留了碗热水。","thought_tag":"CONNECTED","thought_desc":"在恶劣严冬中抱团取暖","relation_delta":1} + thought_tag 选择:严寒受冻/极度饥饿/破衣烂衫/繁重劳役/心情<40%→STRESSED;身体伤痛/创伤流血/重病虚弱→HURT;被同伴冒犯/言语冲突/烦躁被打扰/冷遇受气→IRRITATED;感受到同伴关怀/被照料→VALUED;废土抱团取暖/主动关怀同伴→CONNECTED;受到振奋鼓励→ENCOURAGED;领悟或获得灵感→INSPIRED;无特殊情绪波动→NONE。 + 请调用 express_dialogue 工具:填写 speech(台词正文)、thought_tag(ENCOURAGED|HURT|VALUED|CONNECTED|STRESSED|IRRITATED|INSPIRED|NONE)、thought_desc(简短原因,≤15字)与 relation_delta(对交流对象好感变动 -5~+5)。 + 请调用 express_dialogue 工具:填写 speech(内心独白)、thought_tag(ENCOURAGED|HURT|VALUED|CONNECTED|STRESSED|IRRITATED|INSPIRED|NONE)与 thought_desc(简短原因,≤15字)。 [触发原因: 闲聊] {0} - [对象] {0} [触发原因: 健康变化] {0} [触发原因: 技能升级] {0} [触发原因: 情绪变化] {0} diff --git a/Languages/English/Keyed/RimMind_Dialogue.xml b/Languages/English/Keyed/RimMind_Dialogue.xml index f6cc341..2d450b7 100644 --- a/Languages/English/Keyed/RimMind_Dialogue.xml +++ b/Languages/English/Keyed/RimMind_Dialogue.xml @@ -46,6 +46,8 @@ Medium Low Attraction: {0} ({1}, {2}) + strong romantic potential + possible romantic interest unlikely to develop romance Relation: {0} [Recent Dialogue History] (Strictly forbidden to mechanically repeat the same complaint or phrase. Expand on new work details or mutual care): @@ -140,31 +142,22 @@ 3. Generate dialogue/monologue matching character personality 4. Evaluate emotional impact of dialogue Maintain character consistency; do not break the fourth wall; dialogue 15~40 chars, monologue 15~40 chars. CRITICAL: Deceased or lost colonists (marked as [deceased] or [lost]) must NOT be spoken to or treated as physically present; they can only be remembered or mourned in past tense. Do NOT replicate parenthetical stage directions or physical actions from previous lines; output fresh and natural dialogue. THREE RIGID CONSTRAINTS: 1. Environmental physical anchors (no temperature hallucination): Strictly adhere to current ambient temperature and season. In freezing winter weather (<0°C), NEVER mention heat relief, heatwaves, or sandstorms; never fabricate sandstorms indoors. 2. Reject universal polite positivity, present raw wasteland emotions: When suffering from freezing cold (Chilly/Cold), darkness, tattered apparel, severe pain, extreme hunger, insults, or low mood, strictly forbid false positive energy, out-of-place flattery, or overly polite good-boy pleasantries; express natural complaints, cursing terrible weather, cynical retorts, irritable outbursts, fatalistic sighs, or cynical weariness. 3. Anti-repetition: Strictly forbid canned template clichés such as "stew is delicious/better than yesterday" or "organizing building materials"; lines must be improvised based on the immediate real situation. - If unable to generate, return {"reply":"...","thought":{"tag":"NONE","description":"No special emotion"}}. - You can use the relation_delta field to change the relationship between dialogue participants. Range -5 to +5, positive increases affinity, negative decreases it. Decide based on dialogue content and current relationship: friendly conversation may add +1~+3, arguments may deduct -2~-5. Do not include this field if the dialogue content does not involve relationship changes. + If unable to generate, call express_dialogue with speech "...", thought_tag "NONE", thought_desc "No special emotion". + You can use the relation_delta field to change the relationship between dialogue participants. Range -5 to +5, positive increases affinity, negative decreases it. Decide based on dialogue content and current relationship: friendly conversation may add +1~+3, arguments may deduct -2~-5. Set 0 if the dialogue content does not involve relationship changes. Monologue Example 1 (Freezing & Cursing): Input: pawn mood 30%, harsh winter -12°C, tattered apparel -Output: {"reply":"Damn this freezing hell, my bones ache and these rags stop none of the wind!","thought":{"tag":"STRESSED","description":"Freezing in tattered rags"}} +Tool call express_dialogue: {"speech":"Damn this freezing hell, my bones ache and these rags stop none of the wind!","thought_tag":"STRESSED","thought_desc":"Freezing in tattered rags"} Monologue Example 2 (Pain & Exhaustion): Input: pawn mood 38%, wounded in combat, exhausted -Output: {"reply":"My wounds throb with searing pain, whole body aching... I just want to pass out.","thought":{"tag":"HURT","description":"Tormented by pain and fatigue"}} +Tool call express_dialogue: {"speech":"My wounds throb with searing pain, whole body aching... I just want to pass out.","thought_tag":"HURT","thought_desc":"Tormented by pain and fatigue"} Dialogue Example 1 (Friction / Irritable Snapping): Input: colonist freezing cold, hungry, irritable; companion approaches to talk -Output: {"reply":"Don't bother me right now! Can't you see I'm freezing to death? Back off!","thought":{"tag":"IRRITATED","description":"Disturbed while freezing cold"},"relation_delta":-2} +Tool call express_dialogue: {"speech":"Don't bother me right now! Can't you see I'm freezing to death? Back off!","thought_tag":"IRRITATED","thought_desc":"Disturbed while freezing cold","relation_delta":-2} Dialogue Example 2 (Cynical Retort / Argument): Input: companion behaves arrogantly or makes cynical remark -Output: {"reply":"Cut the preachy bullshit. Go fix your own leaking roof before lecturing me!","thought":{"tag":"IRRITATED","description":"Retorting to annoying lecturing"},"relation_delta":-3} +Tool call express_dialogue: {"speech":"Cut the preachy bullshit. Go fix your own leaking roof before lecturing me!","thought_tag":"IRRITATED","thought_desc":"Retorting to annoying lecturing","relation_delta":-3} Dialogue Example 3 (Hardship Solidarity): Input: finished hard labor, warming by stove with friend -Output: {"reply":"Alex, let's haul this last timber stack inside. The stove is lit, I saved you hot water.","thought":{"tag":"CONNECTED","description":"Bonding near fire in winter"},"relation_delta":1} - Return only JSON: -{"reply":"monologue text","thought":{"tag":"ENCOURAGED|HURT|VALUED|CONNECTED|STRESSED|IRRITATED|INSPIRED|NONE","description":"≤15 chars"}} - Return only JSON: -{"reply":"dialogue text","thought":{"tag":"ENCOURAGED|HURT|VALUED|CONNECTED|STRESSED|IRRITATED|INSPIRED|NONE","description":"≤15 chars"},"relation_delta":0} - thought.tag selection: freezing cold/severe hunger/tattered apparel/backbreaking labor/mood<40%→STRESSED; physical pain/wounds/illness/exhaustion→HURT; offended/insulted/companion conflict/interrupted while irritable→IRRITATED; feeling cared for/supported→VALUED; wasteland bonding/caring for companions→CONNECTED; genuine encouragement/hope→ENCOURAGED; sudden inspiration/insight→INSPIRED; no special emotion→NONE. - Please call the express_dialogue tool: fill in speech (dialogue text), thought_tag (emotion tag), thought_desc (short reason), and relation_delta (relationship change -5~+5). - Please call the express_dialogue tool: fill in speech (monologue text), thought_tag (emotion tag), and thought_desc (short reason). - Role constraint: This person is a prisoner. Tone should be wary, hesitant, mentioning imprisonment, possibly begging or bargaining. - Role constraint: This person is a slave. Tone should be fearful, submissive, mentioning forced labor and exhaustion, referring to colonists as "master". - Role constraint: This person is an enemy. Tone should be hostile, aggressive, using short commands or threats. - Role constraint: This person is a visitor. Tone should be polite, curious, respectful, treating fellow visitors as companions. +Tool call express_dialogue: {"speech":"Alex, let's haul this last timber stack inside. The stove is lit, I saved you hot water.","thought_tag":"CONNECTED","thought_desc":"Bonding near fire in winter","relation_delta":1} + thought_tag selection: freezing cold/severe hunger/tattered apparel/backbreaking labor/mood<40%→STRESSED; physical pain/wounds/illness/exhaustion→HURT; offended/insulted/companion conflict/interrupted while irritable→IRRITATED; feeling cared for/supported→VALUED; wasteland bonding/caring for companions→CONNECTED; genuine encouragement/hope→ENCOURAGED; sudden inspiration/insight→INSPIRED; no special emotion→NONE. + Please call the express_dialogue tool: fill in speech (dialogue text), thought_tag (ENCOURAGED|HURT|VALUED|CONNECTED|STRESSED|IRRITATED|INSPIRED|NONE), thought_desc (short reason, ≤15 chars), and relation_delta (relationship change -5~+5). + Please call the express_dialogue tool: fill in speech (monologue text), thought_tag (ENCOURAGED|HURT|VALUED|CONNECTED|STRESSED|IRRITATED|INSPIRED|NONE), and thought_desc (short reason, ≤15 chars). [Trigger: Chitchat] {0} - [Recipient] {0} [Trigger: Health Change] {0} [Trigger: Skill Level Up] {0} [Trigger: Mood Change] {0} diff --git a/README.md b/README.md index afa7074..15c2d17 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@

    RimWorld 1.6 | 1.7 Dependency: RimMind-Core - Unit Tests + Unit Tests License: MIT

    @@ -23,7 +23,7 @@ **RimMind-Dialogue** brings RimWorld colonists to life through organic, natural spoken interactions. Powered by the native `express_dialogue` function call architecture, colonists talk to each other while eating in dining halls, laboring at craft benches, or resting by campfires. ### Core Capabilities -- **Native `express_dialogue` ToolCall (`DialogueToolDefinitions` & `DialogueToolParser`)**: Transmits spoken dialogue (`reply`), internal psychological subtext (`thought`), and relationship delta modifiers (`relation_delta: [-5, 5]`) as structured function parameters via `DialogueToolDefinitions.ExpressDialogue`, parsed deterministically by `DialogueToolParser` with dual-mode tool call and fallback support. +- **Native `express_dialogue` ToolCall (`DialogueToolDefinitions` & `DialogueToolParser`)**: Transmits spoken dialogue (`speech`), internal psychological subtext (`thought_tag` / `thought_desc`), and relationship delta modifiers (`relation_delta: [-5, 5]`) as structured function parameters via `DialogueToolDefinitions.ExpressDialogueTool`, parsed deterministically by `DialogueToolParser.TryParse` with dual-mode tool call and fallback support. - **Dialogue Bubble Anti-Pollution & Sanitization Pipeline (`DialogueTextSanitizer`)**: Multi-stage sanitization strips `` reasoning blocks, markdown code fences, raw JSON/XML fragments, and prompt metadata before any bubble or dialogue window renders, strictly blocking unparsed LLM artifacts from appearing over colonists' heads. - **Contextual Spoken Triggers & Liveness Gating**: Conversational opportunities trigger organically based on physical proximity (radius 6.9 tiles), shared activities, and mutual social opinions, strictly guarded by `RimMindPawnLookup` liveness and consciousness checks so downed, sleeping, or off-map pawns never speak. - **Dynamic Relationship Evolution**: Conversations dynamically impact mutual pawn opinions, fostering deep romances, bitter rivalries, or lasting camaraderie. @@ -66,7 +66,7 @@ flowchart TD ## 🧪 Developer Guide & Testing -Run unit tests covering `express_dialogue` tool call parsing, `DialogueTextSanitizer` anti-pollution filtering, and opinion delta boundaries (113 test cases): +Run unit tests covering `express_dialogue` tool call parsing, `DialogueTextSanitizer` anti-pollution filtering, trigger/trace registries, and request lifecycle contracts: ```powershell dotnet test RimMind-Dialogue/Tests/RimMindDialogue.Tests.csproj -c Release diff --git a/README_zh.md b/README_zh.md index daa732f..f4e27d0 100644 --- a/README_zh.md +++ b/README_zh.md @@ -8,7 +8,7 @@

    RimWorld 1.6 | 1.7 依赖: RimMind-Core - 单元测试 + 单元测试 License: MIT

    @@ -23,7 +23,7 @@ **RimMind-Dialogue** 让殖民者之间的交流变得充满人情味。基于原生 `express_dialogue` 函数调用契约,小人们在食堂用餐、工作台做工或篝火旁休憩时能够自然产生有话则长、无话则短的情境闲聊。 ### 核心特性 -- **原生 `express_dialogue` 工具调用(`DialogueToolDefinitions` 与 `DialogueToolParser`)**:台词内容(`reply`)、潜台词心理标签(`thought`)以及好感变动值(`relation_delta: [-5, 5]`)通过 `DialogueToolDefinitions.ExpressDialogue` 标准函数调用定义回传,由 `DialogueToolParser` 执行双模式结构化解析。 +- **原生 `express_dialogue` 工具调用(`DialogueToolDefinitions` 与 `DialogueToolParser`)**:台词内容(`speech`)、潜台词心理标签与描述(`thought_tag` / `thought_desc`)以及好感变动值(`relation_delta: [-5, 5]`)通过 `DialogueToolDefinitions.ExpressDialogueTool` 标准函数调用定义回传,由 `DialogueToolParser.TryParse` 执行双模式结构化解析。 - **对话气泡防污染与多级清洗管线(`DialogueTextSanitizer`)**:在进入头顶气泡或对话窗口渲染前,自动剥离 `` 推理块、Markdown 代码围栏、残留 JSON/XML 载荷碎片与系统提示词回声,彻底杜绝未解析原始文本泄露到玩家视野。 - **情境社交触发与存活门控**:基于物理半径(6.9 格范围内近距接触)、共同活动与社交关系自然触发,并统一通过 `RimMindPawnLookup` 与清醒/未倒地状态校验,确保昏迷、睡眠或离图小人绝不产生幽灵对话。 - **动态社交关系演进**:对话不仅停留在文本层面,还会实质性影响殖民者之间的好感度,促成深厚友谊、浪漫恋情或宿命敌对。 @@ -66,7 +66,7 @@ flowchart TD ## 🧪 开发者测试指南 -运行单元测试(涵盖 `express_dialogue` 工具调用解析、`DialogueTextSanitizer` 防污染清洗与好感度边界截断,共 113 个用例): +运行单元测试(涵盖 `express_dialogue` 工具调用解析、`DialogueTextSanitizer` 防污染清洗、触发/追踪注册表与完整请求生命周期契约): ```powershell dotnet test RimMind-Dialogue/Tests/RimMindDialogue.Tests.csproj -c Release diff --git a/Source/Comps/CompProperties_RimMindDialogue.cs b/Source/Comps/CompProperties_RimMindDialogue.cs index 3976308..e884ece 100644 --- a/Source/Comps/CompProperties_RimMindDialogue.cs +++ b/Source/Comps/CompProperties_RimMindDialogue.cs @@ -1,4 +1,3 @@ -using RimMind.Dialogue.Comps; using Verse; namespace RimMind.Dialogue.Comps diff --git a/Source/Comps/CompRimMindDialogue.cs b/Source/Comps/CompRimMindDialogue.cs index 8dbcd32..6aeb5a2 100644 --- a/Source/Comps/CompRimMindDialogue.cs +++ b/Source/Comps/CompRimMindDialogue.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using RimMind.Application.Common.Helpers; using RimMind.Presentation.Api; using RimMind.Dialogue.Core; using RimMind.Dialogue.Settings; @@ -11,10 +12,11 @@ namespace RimMind.Dialogue.Comps { public class CompRimMindDialogue : ThingComp { + private static Texture2D? _cachedChatIcon; + private static bool _chatIconLoaded; private int _lastTriggerTick = -99999; private Pawn? PawnOrNull => parent as Pawn; - private Pawn? Pawn => parent as Pawn; public override void CompTick() { @@ -45,7 +47,10 @@ public override void CompTick() float dynamicChance = CalculateDynamicSocialChance(settings.diningSocialChance, pawn, nearbyCompanion, activityScale); if (settings.enableDiningSocial && Rand.Value < dynamicChance) { - string contextMsg = "RimMind.Dialogue.Context.DiningEncounter".Translate(nearbyCompanion.LabelShort); + string contextMsg = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.DiningEncounter", + "Dining together with {0}, enjoying a shared meal", + nearbyCompanion.LabelShort); TryDispatchTrigger(pawn, contextMsg, DialogueTriggerType.Chitchat, nearbyCompanion, currentTick, ref _lastTriggerTick); return; } @@ -57,7 +62,10 @@ public override void CompTick() float dynamicChance = CalculateDynamicSocialChance(settings.recreationSocialChance, pawn, nearbyCompanion, activityScale); if (settings.enableRecreationSocial && Rand.Value < dynamicChance) { - string contextMsg = "RimMind.Dialogue.Context.RecreationEncounter".Translate(nearbyCompanion.LabelShort); + string contextMsg = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.RecreationEncounter", + "Engaging in recreation with {0} in a relaxed atmosphere", + nearbyCompanion.LabelShort); TryDispatchTrigger(pawn, contextMsg, DialogueTriggerType.Chitchat, nearbyCompanion, currentTick, ref _lastTriggerTick); return; } @@ -73,7 +81,10 @@ public override void CompTick() float dynamicChance = CalculateDynamicSocialChance(settings.coworkerSocialChance, pawn, nearbyCompanion, activityScale); if (settings.enableCoworkerSocial && Rand.Value < dynamicChance) { - string contextMsg = "RimMind.Dialogue.Context.CoworkerEncounter".Translate(nearbyCompanion.LabelShort); + string contextMsg = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.CoworkerEncounter", + "Working side-by-side near {0}", + nearbyCompanion.LabelShort); TryDispatchTrigger(pawn, contextMsg, DialogueTriggerType.Chitchat, nearbyCompanion, currentTick, ref _lastTriggerTick); return; } @@ -91,7 +102,9 @@ public override void CompTick() float monologueChance = 0.35f * (mood > 0.8f || mood < 0.3f ? 1.25f : 1.0f) * jitter * activityScale; if (settings.autoDialogueEnabled && Rand.Value < monologueChance) { - string contextMsg = "RimMind.Dialogue.Context.ContemplationMonologue".Translate(); + string contextMsg = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.ContemplationMonologue", + "Silently gazing at the horizon and contemplating life"); TryDispatchTrigger(pawn, contextMsg, DialogueTriggerType.Auto, null, currentTick, ref _lastTriggerTick); return; } @@ -101,7 +114,9 @@ public override void CompTick() float monologueChance = (settings.recreationSocialChance * 0.4f) * jitter * activityScale; if (settings.autoDialogueEnabled && Rand.Value < monologueChance) { - string contextMsg = "RimMind.Dialogue.Context.RecreationMonologue".Translate(); + string contextMsg = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.RecreationMonologue", + "Enjoying leisure time and relaxing moments"); TryDispatchTrigger(pawn, contextMsg, DialogueTriggerType.Auto, null, currentTick, ref _lastTriggerTick); return; } @@ -109,11 +124,12 @@ public override void CompTick() } // 3. Fallback idle monologue - float idleCdMult = activityScale > 0.01f ? (1.0f / activityScale) : 1.0f; - int idleCooldown = Mathf.RoundToInt(settings.AutoDialogueCooldownTicks * Mathf.Clamp(idleCdMult, 0.35f, 3.5f)); + int idleCooldown = ActivityCooldownScaler.Scale(settings.AutoDialogueCooldownTicks, activityScale); if (settings.autoDialogueEnabled && (currentTick - _lastTriggerTick >= idleCooldown)) { - string contextMsg = "RimMind.Dialogue.Context.IdleState".Translate(); + string contextMsg = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.IdleState", + "The colonist is currently idle"); TryDispatchTrigger(pawn, contextMsg, DialogueTriggerType.Auto, null, currentTick, ref _lastTriggerTick); } } @@ -212,10 +228,16 @@ public override IEnumerable CompGetGizmosExtra() if (!RimMindDialogueSettings.Get().enabled) yield break; if (!RimMindDialogueSettings.Get().playerDialogueEnabled) yield break; + if (!_chatIconLoaded) + { + _chatIconLoaded = true; + _cachedChatIcon = ContentFinder.Get("UI/RimMindDialogue_Icon", reportFailure: false); + } + yield return new Command_Action { defaultLabel = RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Gizmo.ChatWith", "Chat with {0}", parent.LabelShort), - icon = ContentFinder.Get("UI/RimMindDialogue_Icon", reportFailure: false), + icon = _cachedChatIcon, action = () => Find.WindowStack.Add(new Window_Dialogue(pawn)) }; } diff --git a/Source/Core/DialogueActivityState.cs b/Source/Core/DialogueActivityState.cs index 80796ca..ea16e77 100644 --- a/Source/Core/DialogueActivityState.cs +++ b/Source/Core/DialogueActivityState.cs @@ -1,6 +1,7 @@ using System.Collections.Concurrent; -using System.Collections.Generic; +using RimMind.Application.Common.Helpers; using RimMind.Dialogue.Settings; +using RimMind.Presentation.Api; using Verse; namespace RimMind.Dialogue.Core @@ -11,16 +12,13 @@ internal sealed class DialogueActivityState new DialoguePairRateLimiter(); private readonly DialogueActiveRecipientRegistry _activeRecipients = new DialogueActiveRecipientRegistry(); - private readonly List<(int tick, int pawnId, DialogueTriggerType type)> _recentTriggers = - new List<(int, int, DialogueTriggerType)>(); - private readonly ConcurrentDictionary<(int, int), List> _dailyDialogueCounts = - new ConcurrentDictionary<(int, int), List>(); - private readonly ConcurrentDictionary _pawnCache = - new ConcurrentDictionary(); + private readonly KeyedCooldownGate<(int PawnId, DialogueTriggerType Type)> _recentTriggers = + new KeyedCooldownGate<(int PawnId, DialogueTriggerType Type)>(256); + private readonly ConcurrentDictionary<(int, int), int> _dailyDialogueCounts = + new ConcurrentDictionary<(int, int), int>(); private int _gameStartTick = -1; private int _lastCountDay = -1; - private int _pawnCacheTick = -1; public int RecentTriggerCount => _recentTriggers.Count; @@ -45,8 +43,6 @@ public void Reset(int currentTick) _recentTriggers.Clear(); _dailyDialogueCounts.Clear(); _lastCountDay = -1; - _pawnCache.Clear(); - _pawnCacheTick = -1; } public void RecordTrigger( @@ -55,8 +51,7 @@ public void RecordTrigger( DialogueTriggerType type, int cooldownTicks) { - CleanExpiredTriggers(currentTick, cooldownTicks); - _recentTriggers.Add((currentTick, pawnId, type)); + _recentTriggers.Record((pawnId, type), currentTick); } public bool IsMonologueOnCooldown( @@ -64,19 +59,7 @@ public bool IsMonologueOnCooldown( int pawnId, DialogueTriggerType type, int cooldownTicks) - { - foreach (var entry in _recentTriggers) - { - if (entry.pawnId == pawnId - && entry.type == type - && currentTick - entry.tick < cooldownTicks) - { - return true; - } - } - - return false; - } + => _recentTriggers.IsOnCooldown((pawnId, type), currentTick, cooldownTicks); public bool TryConsumeReply( (int, int) pairKey, @@ -98,10 +81,7 @@ public void RecordDailyDialogue( { CleanExpiredDailyCounts(currentTick); var key = DialogueClassifier.MakePairKey(idA, idB); - List ticks = _dailyDialogueCounts.GetOrAdd( - key, - _ => new List()); - ticks.Add(currentTick); + _dailyDialogueCounts.AddOrUpdate(key, 1, (_, count) => count + 1); } public int GetDailyDialogueCount( @@ -111,8 +91,8 @@ public int GetDailyDialogueCount( { CleanExpiredDailyCounts(currentTick); var key = DialogueClassifier.MakePairKey(idA, idB); - return _dailyDialogueCounts.TryGetValue(key, out var ticks) - ? ticks.Count + return _dailyDialogueCounts.TryGetValue(key, out int count) + ? count : 0; } @@ -125,8 +105,7 @@ public void SetRequestRecipient( _activeRecipients.SetRequest(pawnId, recipientId, reservationId); if (recipient != null) { - _pawnCache[recipientId] = recipient; - RimMind.Presentation.Api.RimMindPawnLookup.CachePawn(recipient); + RimMindPawnLookup.CachePawn(recipient); } } @@ -142,12 +121,13 @@ public void SetManualRecipient(int pawnId, int? recipientId, Pawn? recipient = n _activeRecipients.SetManual(pawnId, recipientId.Value); if (recipient != null) { - _pawnCache[recipientId.Value] = recipient; - RimMind.Presentation.Api.RimMindPawnLookup.CachePawn(recipient); + RimMindPawnLookup.CachePawn(recipient); } } else + { _activeRecipients.ClearManual(pawnId); + } } public Pawn? GetActiveRecipient(Pawn pawn, int currentTick) @@ -159,33 +139,17 @@ public void SetManualRecipient(int pawnId, int? recipientId, Pawn? recipient = n return null; } - if (_pawnCache.TryGetValue(recipientId, out var cached) && cached != null && !cached.DestroyedOrNull()) - { - if (RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(cached)) - return cached; - - _pawnCache.TryRemove(recipientId, out _); - } - var lookupPawn = FindPawnByNumber(recipientId); - if (lookupPawn != null && !lookupPawn.DestroyedOrNull() && RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(lookupPawn)) + if (lookupPawn != null && !lookupPawn.DestroyedOrNull() && RimMindPawnLookup.IsActiveSpawnedColonist(lookupPawn)) { - _pawnCache[recipientId] = lookupPawn; return lookupPawn; } - if (UnityData.IsInMainThread && (_pawnCacheTick < 0 || currentTick - _pawnCacheTick >= 600)) - { - RebuildPawnCache(currentTick); - if (_pawnCache.TryGetValue(recipientId, out var fresh) && RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(fresh)) - return fresh; - } - return null; } public static Pawn? FindPawnByNumber(int pawnNumber) - => RimMind.Presentation.Api.RimMindPawnLookup.FindPawnByNumber(pawnNumber); + => RimMindPawnLookup.FindPawnByNumber(pawnNumber); public (int RecentTriggers, int DailyPairs) ClearCooldowns() { @@ -198,34 +162,6 @@ public void SetManualRecipient(int pawnId, int? recipientId, Pawn? recipient = n return (recentTriggers, dailyPairs); } - private void RebuildPawnCache(int currentTick) - { - if (!UnityData.IsInMainThread) - return; - - _pawnCache.Clear(); - if (Find.Maps != null) - { - foreach (Map map in Find.Maps) - { - var spawned = RimMind.Presentation.Api.RimMindPawnLookup.GetSpawnedColonistsSafe(map); - if (spawned == null) - continue; - - foreach (Pawn candidate in spawned) - { - if (candidate != null && RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(candidate)) - { - _pawnCache[candidate.thingIDNumber] = candidate; - RimMind.Presentation.Api.RimMindPawnLookup.CachePawn(candidate); - } - } - } - } - - _pawnCacheTick = currentTick; - } - private void CleanExpiredDailyCounts(int currentTick) { int today = CurrentGameDay(currentTick); @@ -236,12 +172,6 @@ private void CleanExpiredDailyCounts(int currentTick) _lastCountDay = today; } - private void CleanExpiredTriggers( - int currentTick, - int cooldownTicks) - => _recentTriggers.RemoveAll( - entry => currentTick - entry.tick >= cooldownTicks); - private static int CurrentGameDay(int currentTick) => (int)(currentTick / 2500f / 24f); } diff --git a/Source/Core/DialogueCadenceEvaluator.cs b/Source/Core/DialogueCadenceEvaluator.cs index 51ca2bf..4a6f80d 100644 --- a/Source/Core/DialogueCadenceEvaluator.cs +++ b/Source/Core/DialogueCadenceEvaluator.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using RimMind.Application.Common.Helpers; using UnityEngine; namespace RimMind.Dialogue.Core @@ -51,7 +52,8 @@ public float CalculateProbability( float targetTicks = targetCadenceDays * 60000f; if (!_lastPairDialogueTicks.TryGetValue(pairKey, out int lastTick) || lastTick < 0) { - int staggerOffset = Math.Abs((pairKey.Item1 * 397) ^ pairKey.Item2) % (int)(targetTicks * 0.75f); + int staggerWindow = Math.Max(1, (int)(targetTicks * 0.75f)); + int staggerOffset = TickStagger.PhaseOffset((pairKey.Item1 * 397) ^ pairKey.Item2, staggerWindow); lastTick = Math.Max(0, currentTick - staggerOffset); _lastPairDialogueTicks.TryAdd(pairKey, lastTick); } diff --git a/Source/Core/DialogueContextProviderRegistrar.cs b/Source/Core/DialogueContextProviderRegistrar.cs index cd1d4ae..77cc266 100644 --- a/Source/Core/DialogueContextProviderRegistrar.cs +++ b/Source/Core/DialogueContextProviderRegistrar.cs @@ -57,7 +57,9 @@ internal static void RegisterAll() (ctx, ct) => { if (ctx.PawnId <= 0) return Task.FromResult(null); - if (ctx.Scenario != RimMindAPI.Context.ScenarioDialogue) return Task.FromResult(null); + if (ctx.Scenario != RimMindAPI.Context.ScenarioDialogue + && ctx.Scenario != RimMindAPI.Context.ScenarioCrisisDialogue) + return Task.FromResult(null); string? speakerName = ctx.Hints?.TryGetValue("SpeakerName", out var sn) == true ? sn?.ToString() : null; bool isMonologue = string.IsNullOrEmpty(speakerName) && ctx.Hints?.TryGetValue("IsMonologue", out var im) == true @@ -65,7 +67,6 @@ internal static void RegisterAll() var subKeys = new List { "Role", "Process", "Constraint", "Fallback", "ThoughtRules" }; subKeys.Add(isMonologue ? "GoalMonologue" : "GoalDialogue"); subKeys.Add(isMonologue ? "ExampleMonologue" : "ExampleDialogue"); - subKeys.Add(isMonologue ? "OutputMonologue" : "OutputDialogue"); if (!isMonologue) subKeys.Add("RelationDelta"); subKeys.Add(isMonologue ? "ToolCallMonologue" : "ToolCallDialogue"); string[] keys = subKeys.ToArray(); @@ -167,7 +168,8 @@ private static void RegisterScenarios() private static string? BuildStateContext(int pawnId) { var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); - var memories = pawn?.needs?.mood?.thoughts?.memories?.Memories; + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) return null; + var memories = pawn!.needs?.mood?.thoughts?.memories?.Memories; if (memories == null || memories.Count == 0) return null; var sb = new StringBuilder(); @@ -190,14 +192,14 @@ private static void RegisterScenarios() private static string? BuildRelationContext(int pawnId) { var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); - if (pawn == null) return null; - var recipient = RimMindDialogueService.GetActiveRecipient(pawn); + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) return null; + var recipient = RimMindDialogueService.GetActiveRecipient(pawn!); if (recipient == null) return null; var sb = new StringBuilder(); sb.AppendLine(Tr("RimMind.Dialogue.Context.RelationHeader", recipient.Name?.ToStringShort ?? recipient.LabelShort)); - float opinion = pawn.relations?.OpinionOf(recipient) ?? 0f; + float opinion = pawn!.relations?.OpinionOf(recipient) ?? 0f; string opinionLabel = opinion >= 20 ? Tr("RimMind.Dialogue.Context.Opinion.Friend") : opinion <= -20 ? Tr("RimMind.Dialogue.Context.Opinion.Enemy") : Tr("RimMind.Dialogue.Context.Opinion.Acquaintance"); @@ -210,10 +212,24 @@ private static void RegisterScenarios() sb.AppendLine(Tr("RimMind.Dialogue.Context.CompatLabel", $"{compat:F2}", compatLabel)); float romance = pawn.relations?.SecondaryRomanceChanceFactor(recipient) ?? 0f; - string romanceLabel = romance >= 0.5f ? Tr("RimMind.Dialogue.Context.Romance.High") - : romance >= 0.15f ? Tr("RimMind.Dialogue.Context.Romance.Medium") - : Tr("RimMind.Dialogue.Context.Romance.Low"); - sb.AppendLine(Tr("RimMind.Dialogue.Context.RomanceLabel", $"{romance:F2}", romanceLabel, Tr("RimMind.Dialogue.Context.Romance.Unlikely"))); + string romanceLabel; + string romanceHint; + if (romance >= 0.5f) + { + romanceLabel = Tr("RimMind.Dialogue.Context.Romance.High"); + romanceHint = RimMindText.TrOr("RimMind.Dialogue.Context.Romance.Likely", "strong romantic potential"); + } + else if (romance >= 0.15f) + { + romanceLabel = Tr("RimMind.Dialogue.Context.Romance.Medium"); + romanceHint = RimMindText.TrOr("RimMind.Dialogue.Context.Romance.Possible", "possible romantic interest"); + } + else + { + romanceLabel = Tr("RimMind.Dialogue.Context.Romance.Low"); + romanceHint = RimMindText.TrOr("RimMind.Dialogue.Context.Romance.Unlikely", "unlikely to develop romance"); + } + sb.AppendLine(Tr("RimMind.Dialogue.Context.RomanceLabel", $"{romance:F2}", romanceLabel, romanceHint)); var directRel = pawn.relations?.DirectRelations?.FirstOrDefault(r => r != null && r.otherPawn == recipient); if (directRel?.def != null) @@ -226,12 +242,12 @@ private static void RegisterScenarios() private static string? BuildHistoryContext(int pawnId) { var pawn = RimMindPawnLookup.FindPawnByNumber(pawnId); - if (pawn == null) return null; + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn)) return null; - var recipient = RimMindDialogueService.GetActiveRecipient(pawn); + var recipient = RimMindDialogueService.GetActiveRecipient(pawn!); int? recipientId = recipient?.thingIDNumber; - var history = RimMindDialogueService.GetDialogueHistory(pawn.thingIDNumber, 10); + var history = RimMindDialogueService.GetDialogueHistory(pawn!.thingIDNumber, 10); if (history == null || history.Count == 0) return null; List relevant; @@ -259,7 +275,7 @@ private static void RegisterScenarios() var sb = new StringBuilder(); sb.AppendLine(RimMindText.TrOr( "RimMind.Dialogue.Context.HistoryHeader", - "【Recent Dialogue History】(Strictly forbidden to mechanically repeat the same complaint or phrase. Expand on new work details or mutual care):")); + "[Recent Dialogue History] (Strictly forbidden to mechanically repeat the same complaint or phrase. Expand on new work details or mutual care):")); foreach (var entry in relevant) { diff --git a/Source/Core/DialogueLogEntry.cs b/Source/Core/DialogueLogEntry.cs index cd6071c..ac8907c 100644 --- a/Source/Core/DialogueLogEntry.cs +++ b/Source/Core/DialogueLogEntry.cs @@ -1,3 +1,4 @@ +using RimMind.Presentation.Api; using Verse; namespace RimMind.Dialogue.Core @@ -42,7 +43,7 @@ public string TimeStr float hours = tick / 2500f; int days = (int)(hours / 24f); float remHours = hours % 24f; - return "RimMind.Dialogue.UI.TimeFormat".Translate((days + 1).ToString(), $"{remHours:F1}"); + return RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.TimeFormat", "Day {0} {1}h", (days + 1).ToString(), $"{remHours:F1}"); } } diff --git a/Source/Core/DialogueRequestCoordinator.cs b/Source/Core/DialogueRequestCoordinator.cs index 032e3e6..6be2e74 100644 --- a/Source/Core/DialogueRequestCoordinator.cs +++ b/Source/Core/DialogueRequestCoordinator.cs @@ -1,6 +1,5 @@ using System; using System.Threading; -using RimMind.Application.Common.Constants; using RimMind.Application.Common.Models.Context; using RimMind.Application.Features.Llm; using RimMind.Dialogue.Settings; @@ -145,16 +144,10 @@ public void HandleTrigger( return null; } - private static string ToTriggerKind(DialogueTriggerType type) => type switch - { - DialogueTriggerType.Chitchat => DialogueTriggerKinds.Chitchat, - DialogueTriggerType.Auto => DialogueTriggerKinds.Auto, - DialogueTriggerType.PlayerInput => DialogueTriggerKinds.PlayerInput, - DialogueTriggerType.Hediff => DialogueTriggerKinds.Hediff, - DialogueTriggerType.LevelUp => DialogueTriggerKinds.LevelUp, - DialogueTriggerType.Thought => DialogueTriggerKinds.Thought, - _ => type.ToString() - }; + private const int AutoDialogueMaxQueueWaitTicks = 5000; + + private static string ToTriggerKind(DialogueTriggerType type) + => DialogueTriggerRegistry.GetTriggerKind(type); public void TryTriggerReply( Pawn originalSender, @@ -173,8 +166,12 @@ public void TryTriggerReply( return; } - string replyContext = "RimMind.Dialogue.Context.ReplyTrigger" - .Translate(originalSender.Name.ToStringShort, originalMessage); + string senderName = originalSender.Name?.ToStringShort ?? originalSender.LabelShort; + string replyContext = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.ReplyTrigger", + "{0} said to you: {1}", + senderName, + originalMessage); HandleTrigger( replier, replyContext, @@ -197,16 +194,18 @@ private void DispatchRequest( CancellationToken cancellationToken) { long reservationId = reservation.Id; - bool completed = false; + int completed = 0; CancellationTokenSource? lifetime = null; CancellationTokenRegistration cancellation = default; - bool TryFinish() + bool TryFinish(bool fromCancellationCallback = false) { - if (completed) return false; - completed = true; - cancellation.Dispose(); - lifetime?.Dispose(); + if (Interlocked.Exchange(ref completed, 1) != 0) return false; + if (!fromCancellationCallback) + { + try { cancellation.Dispose(); } catch (ObjectDisposedException) { } + } + try { lifetime?.Dispose(); } catch (ObjectDisposedException) { } reservation.Dispose(); ClearRequestRecipient(pawn.thingIDNumber, reservationId); return true; @@ -223,8 +222,12 @@ void ReportFailure(string error, bool showAutomaticError = true) RimMindErrors.Warn($"[RimMind-Dialogue] Request failed: {error}"); if (type == DialogueTriggerType.PlayerInput) { + string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; Messages.Message( - "RimMind.Dialogue.UI.FloatMenu.RequestFailed".Translate(pawn.Name.ToStringShort), + RimMindAPI.Text.TrOr( + "RimMind.Dialogue.UI.FloatMenu.RequestFailed", + "Dialogue request for {0} failed", + pawnName), MessageTypeDefOf.RejectInput, false); } } @@ -235,16 +238,17 @@ void ReportFailure(string error, bool showAutomaticError = true) _gameLifetime.Token, cancellationToken); cancellation = lifetime.Token.Register(() => { - if (TryFinish()) ReportFailure("Dialogue request cancelled.", false); + if (TryFinish(fromCancellationCallback: true)) + ReportFailure("Dialogue request cancelled.", false); }); - if (completed) return; + if (Volatile.Read(ref completed) != 0) return; if (type != DialogueTriggerType.PlayerInput) { _activityState.RecordTrigger(currentTick, pawn.thingIDNumber, type, settings.monologueCooldownTicks); } - RimMind.Presentation.Api.RimMindPawnLookup.CachePawn(pawn); + RimMindPawnLookup.CachePawn(pawn); if (recipient != null) { _activityState.SetRequestRecipient( @@ -252,12 +256,12 @@ void ReportFailure(string error, bool showAutomaticError = true) recipient.thingIDNumber, reservationId, recipient); - RimMind.Presentation.Api.RimMindPawnLookup.CachePawn(recipient); + RimMindPawnLookup.CachePawn(recipient); // The active recipient feeds dialogue_relation; drop the cached copy now. DialogueContextChangedEvent.Publish(pawn.thingIDNumber); } - string formattedContext = FormatContext(type, context, recipient); + string formattedContext = FormatContext(type, context); bool isMonologue = DialogueFlowPolicy.IsMonologue(type, recipient != null); string? speakerName = recipient != null ? (recipient.Name?.ToStringShort ?? recipient.LabelShort) @@ -302,7 +306,15 @@ void ReportFailure(string error, bool showAutomaticError = true) .WithMaxTokens(800) .WithTemperature(type == DialogueTriggerType.PlayerInput ? 0.85f : 0.8f) .WithReasoningEffort(ReasoningEffort.None) + .WithRequireAliveColonist(true) .WithCancellation(lifetime.Token); + if (type != DialogueTriggerType.PlayerInput) + { + string coalesceKey = BuildCoalesceKey(pawn, recipient, type); + envelopeBuilder + .WithCoalesceKey(coalesceKey) + .WithMaxQueueWaitTicks(AutoDialogueMaxQueueWaitTicks); + } if (!string.IsNullOrEmpty(speakerName)) { envelopeBuilder.WithHint("SpeakerName", speakerName); @@ -321,8 +333,8 @@ void ReportFailure(string error, bool showAutomaticError = true) if (result.Error.Code != RimMindErrorCode.Cancelled) ReportFailure(result.Error.ToString()); return; } - if (pawn.Dead || pawn.Destroyed || pawn.Downed - || (recipient != null && (recipient.Dead || recipient.Destroyed || recipient.Downed))) + if (!RimMindPawnLookup.IsActiveSpawnedColonist(pawn) || pawn.Downed + || (recipient != null && (!RimMindPawnLookup.IsActiveSpawnedColonist(recipient) || recipient.Downed))) { ReportFailure("Dialogue participant is unavailable."); return; @@ -359,6 +371,16 @@ void ReportFailure(string error, bool showAutomaticError = true) } } + private static string BuildCoalesceKey(Pawn pawn, Pawn? recipient, DialogueTriggerType type) + { + if (recipient != null) + { + var pairKey = DialogueClassifier.MakePairKey(pawn.thingIDNumber, recipient.thingIDNumber); + return $"dialogue:{pairKey.Item1}:{pairKey.Item2}:{type}"; + } + return $"dialogue:{pawn.thingIDNumber}:{type}"; + } + private static void Notify(Action? callback, string value) { try { callback?.Invoke(value); } @@ -373,63 +395,7 @@ private void ClearRequestRecipient(int pawnId, long reservationId) pawnId, reservationId); - private static string FormatContext( - DialogueTriggerType type, - string context, - Pawn? recipient) - { - string formatted = type switch - { - DialogueTriggerType.Chitchat => RimMindAPI.Text.TrOr( - "RimMind.Dialogue.Prompt.Context.Chitchat", - "[Chitchat: {0}]", - context), - DialogueTriggerType.Hediff => RimMindAPI.Text.TrOr( - "RimMind.Dialogue.Prompt.Context.Hediff", - "[Health condition: {0}]", - context), - DialogueTriggerType.LevelUp => RimMindAPI.Text.TrOr( - "RimMind.Dialogue.Prompt.Context.LevelUp", - "[Skill level up: {0}]", - context), - DialogueTriggerType.Thought => RimMindAPI.Text.TrOr( - "RimMind.Dialogue.Prompt.Context.Thought", - "[Recent thought: {0}]", - context), - DialogueTriggerType.Auto => RimMindAPI.Text.TrOr( - "RimMind.Dialogue.Prompt.Context.Auto", - "{0}", - context), - _ => context - }; - - string? roleKey = recipient == null - ? null - : GetRecipientRoleKey(recipient); - if (recipient != null && roleKey != null) - { - string recipientLine = RimMindAPI.Text.TrOr( - "RimMind.Dialogue.Prompt.Context.Recipient", - "[Recipient: {0}]", - recipient.Name.ToStringShort); - string roleLine = RimMindAPI.Text.TrOr(roleKey, roleKey); - formatted += "\n" + recipientLine + "\n" + roleLine; - } - - return formatted; - } - - private static string? GetRecipientRoleKey(Pawn recipient) - { - if (recipient.IsPrisoner) - return "RimMind.Dialogue.Prompt.Role.Prisoner"; - if (recipient.IsSlave) - return "RimMind.Dialogue.Prompt.Role.Slave"; - if (recipient.Faction?.HostileTo(Faction.OfPlayer) == true) - return "RimMind.Dialogue.Prompt.Role.Enemy"; - if (!recipient.IsColonist) - return "RimMind.Dialogue.Prompt.Role.Visitor"; - return null; - } + private static string FormatContext(DialogueTriggerType type, string context) + => DialogueTriggerRegistry.FormatContext(type, context); } } diff --git a/Source/Core/DialogueTextSanitizer.cs b/Source/Core/DialogueTextSanitizer.cs index c796641..c086ee7 100644 --- a/Source/Core/DialogueTextSanitizer.cs +++ b/Source/Core/DialogueTextSanitizer.cs @@ -269,7 +269,7 @@ public static string FormatOverheadMoteText(string? text, int maxLineLength = 26 public static string ClassifyThoughtTag(string? rawTag) { if (string.IsNullOrWhiteSpace(rawTag)) - return "FRIENDLY"; + return "NONE"; string tag = rawTag!.Trim().Trim('"', '\'', '`', '[', ']'); if (tag.Length <= 15 && !tag.Contains("\uFF0C") && !tag.Contains("\u3002") && !tag.Contains(",") && !tag.Contains(".") && !tag.Contains(" ") && !tag.Contains("\u4E00\u8FB9") && !tag.Contains("\u5FC3\u91CC")) @@ -279,17 +279,16 @@ public static string ClassifyThoughtTag(string? rawTag) string lower = tag.ToLowerInvariant(); if (lower.Contains("grief") || lower.Contains("\u60B2") || lower.Contains("\u4F24") || lower.Contains("\u6B7B") || lower.Contains("mourn")) - return "GRIEF"; - if (lower.Contains("anxi") || lower.Contains("\u614C") || lower.Contains("\u6025") || lower.Contains("\u7D27") || lower.Contains("\u6101")) - return "ANXIOUS"; + return "HURT"; + if (lower.Contains("anxi") || lower.Contains("\u614C") || lower.Contains("\u6025") || lower.Contains("\u7D27") || lower.Contains("\u6101") + || lower.Contains("weary") || lower.Contains("\u7D2F") || lower.Contains("\u4E4F") || lower.Contains("exhaust")) + return "STRESSED"; if (lower.Contains("tense") || lower.Contains("\u6012") || lower.Contains("\u706B") || lower.Contains("\u6C14") || lower.Contains("conflict")) - return "TENSE"; - if (lower.Contains("weary") || lower.Contains("\u7D2F") || lower.Contains("\u4E4F") || lower.Contains("exhaust")) - return "EXHAUSTED"; + return "IRRITATED"; if (lower.Contains("concer") || lower.Contains("\u5173") || lower.Contains("\u5FE7") || lower.Contains("\u8003\u8651")) - return "CONCERNED"; + return "CONNECTED"; - return "REFLECTIVE"; + return "NONE"; } } } diff --git a/Source/Core/DialogueToolDefinitions.cs b/Source/Core/DialogueToolDefinitions.cs index 8287e11..1eb9cfd 100644 --- a/Source/Core/DialogueToolDefinitions.cs +++ b/Source/Core/DialogueToolDefinitions.cs @@ -11,7 +11,7 @@ public static class DialogueToolDefinitions { Name = ExpressDialogueToolName, Description = "Express the colonist's spoken dialogue or internal monologue, along with their emotional thought tag and relation change.", - Parameters = "{\"type\":\"object\",\"properties\":{\"speech\":{\"type\":\"string\",\"description\":\"The spoken words or inner monologue content of the character.\"},\"thought_tag\":{\"type\":\"string\",\"description\":\"Emotional/mental tag (e.g. ENCOURAGED, HURT, VALUED, CONNECTED, STRESSED, IRRITATED, TIRED, CALM, NONE).\"},\"thought_desc\":{\"type\":\"string\",\"description\":\"Brief description of why the character feels this way (<=15 words).\"},\"relation_delta\":{\"type\":\"integer\",\"description\":\"Relationship opinion change towards the conversation partner (-5 to +5). 0 for monologue or no change.\"}},\"required\":[\"speech\"]}", + Parameters = "{\"type\":\"object\",\"properties\":{\"speech\":{\"type\":\"string\",\"description\":\"The spoken words or inner monologue content of the character.\"},\"thought_tag\":{\"type\":\"string\",\"description\":\"Emotional/mental tag (ENCOURAGED, HURT, VALUED, CONNECTED, STRESSED, IRRITATED, INSPIRED, NONE).\"},\"thought_desc\":{\"type\":\"string\",\"description\":\"Brief description of why the character feels this way (<=15 words).\"},\"relation_delta\":{\"type\":\"integer\",\"description\":\"Relationship opinion change towards the conversation partner (-5 to +5). 0 for monologue or no change.\"}},\"required\":[\"speech\"]}", ToolChoice = "auto" }; diff --git a/Source/Core/DialogueToolParser.cs b/Source/Core/DialogueToolParser.cs index 94d1a5e..997aebb 100644 --- a/Source/Core/DialogueToolParser.cs +++ b/Source/Core/DialogueToolParser.cs @@ -21,7 +21,7 @@ public static class DialogueToolParser // Dialogue-specific malformed pseudo-call quirk: express_dialogue(speech)=(...) private static readonly Regex MalformedParenAssignRegex = new Regex( - @"\b(?:express_dialogue|record_morning_thought|[a-z_][a-z0-9_]*)\s*\(\s*(?speech|reply|dialogue|content|text|narration)\s*\)\s*[:=]\s*\((?[\s\S]+)\)\s*$", + @"\b[a-z_][a-z0-9_]*\s*\(\s*(?speech|reply|dialogue|content|text|narration)\s*\)\s*[:=]\s*\((?[\s\S]+)\)\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); public static bool TryParse(string? toolCallsJson, bool isMonologue, out DialogueOutput output) diff --git a/Source/Core/DialogueTriggerRegistry.cs b/Source/Core/DialogueTriggerRegistry.cs new file mode 100644 index 0000000..c782f77 --- /dev/null +++ b/Source/Core/DialogueTriggerRegistry.cs @@ -0,0 +1,154 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using RimMind.Application.Common.Constants; +using RimMind.Presentation.Api; +using UnityEngine; + +namespace RimMind.Dialogue.Core +{ + internal sealed class DialogueTriggerDescriptor + { + public DialogueTriggerType Type { get; } + public string TypeId { get; } + public string TriggerKind { get; } + public string LabelKey { get; } + public string LabelFallback { get; } + public string? PromptFormatKey { get; } + public string? PromptFallback { get; } + public Color LogColor { get; } + + public DialogueTriggerDescriptor( + DialogueTriggerType type, + string triggerKind, + string labelKey, + string labelFallback, + string? promptFormatKey, + string? promptFallback, + Color logColor) + { + Type = type; + TypeId = type.ToString(); + TriggerKind = triggerKind; + LabelKey = labelKey; + LabelFallback = labelFallback; + PromptFormatKey = promptFormatKey; + PromptFallback = promptFallback; + LogColor = logColor; + } + } + + /// + /// Single source of truth for DialogueTriggerType metadata (trigger kind, localized label, + /// prompt format key, and log display color), plus extensible custom trigger labels. + /// + internal static class DialogueTriggerRegistry + { + private static readonly Dictionary BuiltInByType = + new Dictionary + { + [DialogueTriggerType.Chitchat] = new DialogueTriggerDescriptor( + DialogueTriggerType.Chitchat, + DialogueTriggerKinds.Chitchat, + "RimMind.Dialogue.Trigger.Chitchat", + "Chitchat", + "RimMind.Dialogue.Prompt.Context.Chitchat", + "[Chitchat: {0}]", + new Color(0.7f, 0.85f, 1f)), + [DialogueTriggerType.Hediff] = new DialogueTriggerDescriptor( + DialogueTriggerType.Hediff, + DialogueTriggerKinds.Hediff, + "RimMind.Dialogue.Trigger.Hediff", + "Health Change", + "RimMind.Dialogue.Prompt.Context.Hediff", + "[Health condition: {0}]", + new Color(1f, 0.6f, 0.6f)), + [DialogueTriggerType.LevelUp] = new DialogueTriggerDescriptor( + DialogueTriggerType.LevelUp, + DialogueTriggerKinds.LevelUp, + "RimMind.Dialogue.Trigger.LevelUp", + "Skill Level Up", + "RimMind.Dialogue.Prompt.Context.LevelUp", + "[Skill level up: {0}]", + new Color(0.6f, 1f, 0.6f)), + [DialogueTriggerType.Thought] = new DialogueTriggerDescriptor( + DialogueTriggerType.Thought, + DialogueTriggerKinds.Thought, + "RimMind.Dialogue.Trigger.Thought", + "Mood Change", + "RimMind.Dialogue.Prompt.Context.Thought", + "[Recent thought: {0}]", + new Color(1f, 0.95f, 0.6f)), + [DialogueTriggerType.Auto] = new DialogueTriggerDescriptor( + DialogueTriggerType.Auto, + DialogueTriggerKinds.Auto, + "RimMind.Dialogue.Trigger.Auto", + "Auto Trigger", + "RimMind.Dialogue.Prompt.Context.Auto", + "{0}", + new Color(0.8f, 0.8f, 0.8f)), + [DialogueTriggerType.PlayerInput] = new DialogueTriggerDescriptor( + DialogueTriggerType.PlayerInput, + DialogueTriggerKinds.PlayerInput, + "RimMind.Dialogue.Trigger.PlayerInput", + "Player Dialogue", + null, + null, + new Color(0.85f, 0.7f, 1f)), + }; + + private static readonly Dictionary BuiltInByName = + BuildByNameMap(); + + internal static readonly ConcurrentDictionary CustomLabels = + new ConcurrentDictionary(StringComparer.Ordinal); + + private static Dictionary BuildByNameMap() + { + var map = new Dictionary(StringComparer.Ordinal); + foreach (var descriptor in BuiltInByType.Values) + { + map[descriptor.TypeId] = descriptor; + } + return map; + } + + public static void RegisterLabel(string typeId, string labelKey) + { + if (string.IsNullOrWhiteSpace(typeId)) return; + CustomLabels[typeId] = labelKey; + } + + public static string GetTriggerKind(DialogueTriggerType type) + => BuiltInByType.TryGetValue(type, out var desc) ? desc.TriggerKind : type.ToString(); + + public static string GetLabel(DialogueTriggerType type) + => GetLabel(type.ToString()); + + public static string GetLabel(string triggerKey) + { + if (string.IsNullOrEmpty(triggerKey)) return string.Empty; + if (CustomLabels.TryGetValue(triggerKey, out var customKey)) + return RimMindAPI.Text.TrOr(customKey, customKey); + if (BuiltInByName.TryGetValue(triggerKey, out var desc)) + return RimMindAPI.Text.TrOr(desc.LabelKey, desc.LabelFallback); + return triggerKey; + } + + public static string FormatContext(DialogueTriggerType type, string context) + { + if (BuiltInByType.TryGetValue(type, out var desc) + && !string.IsNullOrEmpty(desc.PromptFormatKey) + && desc.PromptFallback != null) + { + return RimMindAPI.Text.TrOr(desc.PromptFormatKey!, desc.PromptFallback, context); + } + return context; + } + + public static Color GetLogColor(string triggerKey) + => !string.IsNullOrEmpty(triggerKey) && BuiltInByName.TryGetValue(triggerKey, out var desc) + ? desc.LogColor + : Color.white; + } +} diff --git a/Source/Core/NpcResponseHandler.cs b/Source/Core/NpcResponseHandler.cs index 351362b..3db7f13 100644 --- a/Source/Core/NpcResponseHandler.cs +++ b/Source/Core/NpcResponseHandler.cs @@ -1,13 +1,10 @@ using System; -using Newtonsoft.Json; -using RimMind.Application.Common.Interfaces.Npc; using RimMind.Application.Common.Models.Memory; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; using RimMind.Dialogue.Settings; using RimMind.Presentation.Api; using RimWorld; -using UnityEngine; using Verse; namespace RimMind.Dialogue.Core @@ -75,18 +72,20 @@ public static class NpcResponseHandler } catch (Exception ex) { RimMindErrors.Warn($"[RimMind] PublishPerception dialogue_completed failed: {ex.Message}"); } - // 记忆记录 - if (!isMonologue && recipient != null && Verse.ModsConfig.IsActive("mcocdaa.RimMindMemory")) + // 记忆记录(Core RimMindAPI.Memory 通过 MemoryBridgeRegistry 自动降级为空实现,无需硬编码检测子模组) + if (!isMonologue && recipient != null) { try { string memContent = replyText.Length > 60 ? replyText.Substring(0, 60) + "..." : replyText; + string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; + string recipientName = recipient.Name?.ToStringShort ?? recipient.LabelShort; RimMindAPI.Memory.AddPawnMemory( - "RimMind.Dialogue.Memory.WithRecipient".Translate(recipient!.Name.ToStringShort, memContent), + RimMindAPI.Text.TrOr("RimMind.Dialogue.Memory.WithRecipient", "Conversation with {0}: {1}", recipientName, memContent), MemoryKind.Event, Find.TickManager.TicksGame, 0.5f, pawn.ThingID); RimMindAPI.Memory.AddPawnMemory( - "RimMind.Dialogue.Memory.WithPawn".Translate(pawn.Name.ToStringShort, memContent), - MemoryKind.Event, Find.TickManager.TicksGame, 0.5f, recipient!.ThingID); + RimMindAPI.Text.TrOr("RimMind.Dialogue.Memory.WithPawn", "Conversation with {0}: {1}", pawnName, memContent), + MemoryKind.Event, Find.TickManager.TicksGame, 0.5f, recipient.ThingID); } catch (Exception ex) { @@ -105,8 +104,9 @@ public static class NpcResponseHandler if (RimMindDialogueSettings.Get().showThoughtNotification && thoughtTag != "NONE" && !thoughtTag.NullOrEmpty()) { string notifText = replyText.Length > 60 ? replyText.Substring(0, 60) + "..." : replyText; + string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; Messages.Message( - $"[RimMind] {pawn.Name.ToStringShort}: {notifText}", + $"[RimMind] {pawnName}: {notifText}", pawn, MessageTypeDefOf.SilentInput, historical: false); } diff --git a/Source/Core/README.md b/Source/Core/README.md index 4cc4be9..c8c55d8 100644 --- a/Source/Core/README.md +++ b/Source/Core/README.md @@ -20,9 +20,11 @@ when changing `dialogue_state`, `dialogue_relation`, or `dialogue_task` context. ## Responsibilities -- `DialogueRequestCoordinator.cs`: shared admission, reservations, request construction, - cancellation and terminal cleanup. There is one Core request-send site. -- `DialogueActivityState.cs`: readiness, cooldowns, quotas, recipients, Pawn lookup. +- `DialogueRequestCoordinator.cs`: shared admission, reservations, request construction + (coalescing/TTL/liveness on automatic triggers), cancellation and terminal cleanup. There is one Core request-send site. +- `DialogueTriggerRegistry.cs`: single source of truth for `DialogueTriggerType` metadata + (trigger kind, localized label, prompt format key, log display color) and custom trigger labels. +- `DialogueActivityState.cs`: readiness, cooldowns (`KeyedCooldownGate`), quotas, recipients, Pawn lookup. - `DialogueLogStore.cs`: bounded log storage and snapshots. - `NpcResponseHandler.cs`: game-side effects after a successful response, including optional memory writes through the Core public `RimMindAPI.Memory` API. diff --git a/Source/Core/ResponseJsonParser.cs b/Source/Core/ResponseJsonParser.cs deleted file mode 100644 index 3a3babc..0000000 --- a/Source/Core/ResponseJsonParser.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using Newtonsoft.Json.Linq; -using RimMind.Presentation.Api; - -namespace RimMind.Dialogue.Core -{ - /// - /// Legacy compatibility forwarder kept for binary/test compatibility. - /// Delegates JSON extraction and repair to Core . - /// - [Obsolete("Use DialogueToolParser instead. RimMind mainline dialogue is now unified under native express_dialogue tool calls.")] - public static class ResponseJsonParser - { - private static readonly string[] ReplyFieldNames = - { - "reply", "narration", "dialogue", "speech", "text", "content", "message" - }; - - public static void TryParseResponseJson(string? rawResponse, bool isMonologue, - ref string replyText, ref string? thoughtTag, ref string? thoughtDesc, ref int relationDelta) - { - if (string.IsNullOrWhiteSpace(rawResponse)) - return; - - if (!RimMindAPI.Json.TryParseJObjectWithRepair(rawResponse, out var obj) || obj == null) - return; - - foreach (var field in ReplyFieldNames) - { - if (obj.TryGetValue(field, StringComparison.OrdinalIgnoreCase, out var token) - && token.Type == JTokenType.String) - { - string? str = token.Value(); - if (!string.IsNullOrEmpty(str)) - { - replyText = str!; - break; - } - } - } - - if (obj.TryGetValue("thought", StringComparison.OrdinalIgnoreCase, out var thoughtToken)) - { - if (thoughtToken is JObject thoughtJObj) - { - thoughtTag = thoughtJObj.Value("tag"); - thoughtDesc = thoughtJObj.Value("description"); - } - else if (thoughtToken.Type == JTokenType.String) - { - string? tagStr = thoughtToken.Value(); - if (!string.IsNullOrEmpty(tagStr)) - thoughtTag = tagStr; - } - } - - if (!isMonologue - && obj.TryGetValue("relation_delta", StringComparison.OrdinalIgnoreCase, out var relToken) - && relToken.Type == JTokenType.Integer) - { - relationDelta = relToken.Value(); - } - } - } -} diff --git a/Source/Core/RimMindDialogueService.cs b/Source/Core/RimMindDialogueService.cs index aecc724..e5e22a2 100644 --- a/Source/Core/RimMindDialogueService.cs +++ b/Source/Core/RimMindDialogueService.cs @@ -27,7 +27,7 @@ public static class RimMindDialogueService public static DialogueCadenceEvaluator CadenceEvaluator => _cadenceEvaluator; - internal static readonly ConcurrentDictionary RegisteredTriggerLabels = new ConcurrentDictionary(); + internal static ConcurrentDictionary RegisteredTriggerLabels => DialogueTriggerRegistry.CustomLabels; public static event Action? OnLogUpdated { @@ -159,26 +159,10 @@ public static void DisplayInteraction(Pawn initiator, Pawn? recipient, string re } public static void RegisterTriggerType(string typeId, string labelKey) - { - RegisteredTriggerLabels[typeId] = labelKey; - } + => DialogueTriggerRegistry.RegisterLabel(typeId, labelKey); public static string GetTriggerLabel(DialogueTriggerType type) - { - string typeStr = type.ToString(); - if (RegisteredTriggerLabels.TryGetValue(typeStr, out var label)) - return RimMindAPI.Text.TrOr(label, label); - return type switch - { - DialogueTriggerType.Chitchat => "RimMind.Dialogue.Trigger.Chitchat".Translate(), - DialogueTriggerType.Hediff => "RimMind.Dialogue.Trigger.Hediff".Translate(), - DialogueTriggerType.LevelUp => "RimMind.Dialogue.Trigger.LevelUp".Translate(), - DialogueTriggerType.Thought => "RimMind.Dialogue.Trigger.Thought".Translate(), - DialogueTriggerType.Auto => "RimMind.Dialogue.Trigger.Auto".Translate(), - DialogueTriggerType.PlayerInput => "RimMind.Dialogue.Trigger.PlayerInput".Translate(), - _ => typeStr - }; - } + => DialogueTriggerRegistry.GetLabel(type); public static void AddLogEntry(Pawn pawn, Pawn? recipient, DialogueTriggerType triggerType, string context, string reply, string? thoughtTag, string? thoughtDesc) @@ -186,10 +170,10 @@ public static void AddLogEntry(Pawn pawn, Pawn? recipient, DialogueTriggerType t var entry = new DialogueLogEntry { tick = Find.TickManager.TicksGame, - initiatorName = pawn.Name.ToStringShort, + initiatorName = pawn.Name?.ToStringShort ?? pawn.LabelShort, initiatorId = pawn.thingIDNumber, initiatorIsColonist = pawn.IsColonist, - recipientName = recipient?.Name.ToStringShort, + recipientName = recipient == null ? null : (recipient.Name?.ToStringShort ?? recipient.LabelShort), recipientId = recipient?.thingIDNumber ?? -1, recipientIsColonist = recipient?.IsColonist ?? false, category = DialogueClassifier.Classify(pawn.IsColonist, recipient?.IsColonist, triggerType), @@ -222,7 +206,8 @@ public static void RecordDailyDialogue(int idA, int idB) public static void SetActiveRecipient(Pawn pawn, Pawn? recipient) => _activityState.SetManualRecipient( pawn.thingIDNumber, - recipient?.thingIDNumber); + recipient?.thingIDNumber, + recipient); // ── 查询方法 ── diff --git a/Source/Debug/DialogueBehaviorAutotestSuite.cs b/Source/Debug/DialogueBehaviorAutotestSuite.cs index 8d07e93..6e753b6 100644 --- a/Source/Debug/DialogueBehaviorAutotestSuite.cs +++ b/Source/Debug/DialogueBehaviorAutotestSuite.cs @@ -49,7 +49,6 @@ public override void RunSuite(IInGameBehaviorSuiteContext context) var thoughtDef = DefDatabase.GetNamedSilentFail("RimMindDialogue_Thought"); if (thoughtDef != null) { - int memBefore = pawn.needs.mood.thoughts.memories.Memories.Count; ThoughtInjector.Inject(pawn, null, "ENCOURAGED", "Autotest test description"); var memAfter = pawn.needs.mood.thoughts.memories.Memories; @@ -70,7 +69,7 @@ public override void RunSuite(IInGameBehaviorSuiteContext context) // 4. Rate Limiting and Activity State Cooldowns try { - var cleared = RimMindDialogueService.ClearAllCooldowns(); + _ = RimMindDialogueService.ClearAllCooldowns(); context.Assert(RimMindDialogueService.RecentTriggerCount == 0, "RecentTriggerCount is 0 after clearing dialogue cooldowns"); } catch (Exception ex) diff --git a/Source/Debug/DialogueDebugActions.cs b/Source/Debug/DialogueDebugActions.cs index b45c3a8..0acfcaa 100644 --- a/Source/Debug/DialogueDebugActions.cs +++ b/Source/Debug/DialogueDebugActions.cs @@ -5,7 +5,6 @@ using RimMind.Dialogue.Settings; using RimMind.Dialogue.UI; using RimMind.Presentation.Api; -using RimWorld; using Verse; namespace RimMind.Dialogue.Debug @@ -21,7 +20,7 @@ private static void ForceChitchat() var target = FindAnotherColonist(pawn); if (target == null) { Log.Message("[RimMind-Dialogue] No other colonist found for target."); return; } - string context = "RimMind.Dialogue.Debug.ChitchatContext".Translate(target.LabelShort); + string context = RimMindAPI.Text.TrOr("RimMind.Dialogue.Debug.ChitchatContext", "[Chitchat] Talking with {0}", target.LabelShort); RimMindDialogueService.HandleTrigger(pawn, context, DialogueTriggerType.Chitchat, target); } @@ -31,7 +30,7 @@ private static void ForceHediffTrigger() var pawn = Find.Selector.SingleSelectedThing as Pawn; if (pawn == null) { Log.Message("[RimMind-Dialogue] No pawn selected."); return; } - string context = "RimMind.Dialogue.Debug.HediffContext".Translate(); + string context = RimMindAPI.Text.TrOr("RimMind.Dialogue.Debug.HediffContext", "Just took damage"); RimMindDialogueService.HandleTrigger(pawn, context, DialogueTriggerType.Hediff, null); } @@ -44,7 +43,8 @@ private static void ShowActiveThoughts() var memories = pawn.needs?.mood?.thoughts?.memories?.Memories; if (memories == null) { Log.Message("[RimMind-Dialogue] No memories found."); return; } - var sb = new StringBuilder($"[RimMind-Dialogue] Active RimMindDialogue thoughts for {pawn.Name.ToStringShort}:\n"); + string pawnName = pawn.Name?.ToStringShort ?? pawn.LabelShort; + var sb = new StringBuilder($"[RimMind-Dialogue] Active RimMindDialogue thoughts for {pawnName}:\n"); bool any = false; foreach (var t in memories) { diff --git a/Source/Extensions/DialogueModCooldown.cs b/Source/Extensions/DialogueModCooldown.cs index 3e7bb9d..b2f10d2 100644 --- a/Source/Extensions/DialogueModCooldown.cs +++ b/Source/Extensions/DialogueModCooldown.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Helpers; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Presentation.Api; @@ -6,8 +7,8 @@ namespace RimMind.Dialogue { internal sealed class DialogueModCooldown : IModCooldown { - public string Id => "Dialogue"; - public string OwnerModId => "RimMind.Dialogue"; + public string Id => "RimMind.Dialogue"; + public string OwnerModId => RimMindOwnerConsts.DialogueModId; public int CooldownTicks => ActivityCooldownScaler.Scale(1500, RimMindAPI.Settings.ActivityFrequencyScale); } } diff --git a/Source/Extensions/DialogueOverlayToggleBehavior.cs b/Source/Extensions/DialogueOverlayToggleBehavior.cs index 689f70d..3051c81 100644 --- a/Source/Extensions/DialogueOverlayToggleBehavior.cs +++ b/Source/Extensions/DialogueOverlayToggleBehavior.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Dialogue.Settings; @@ -6,7 +7,7 @@ namespace RimMind.Dialogue internal sealed class DialogueOverlayToggleBehavior : IToggleBehavior { public string Id => "dialogue_overlay"; - public string OwnerModId => "RimMindDialogue"; + public string OwnerModId => RimMindOwnerConsts.DialogueModId; public bool IsActive => RimMindDialogueSettings.Get().overlayEnabled; public void Toggle() { diff --git a/Source/Extensions/DialogueRequestTraceSummarizer.cs b/Source/Extensions/DialogueRequestTraceSummarizer.cs new file mode 100644 index 0000000..e4f43cd --- /dev/null +++ b/Source/Extensions/DialogueRequestTraceSummarizer.cs @@ -0,0 +1,128 @@ +using System; +using System.Text.RegularExpressions; +using RimMind.Application.Common.Constants; +using RimMind.Application.Common.Interfaces.Diagnostics; +using RimMind.Application.Common.Models.Debug; +using RimMind.Dialogue.Core; +using RimMind.Presentation.Api; + +namespace RimMind.Dialogue +{ + /// + /// Summarizes Dialogue tool calls, prompts, and responses for Core's trace UI + /// without Core hardcoding Dialogue tool names or translation keys. + /// + internal sealed class DialogueRequestTraceSummarizer : IRequestTraceSummarizer + { + private const string DialogueModId = "RimMind.Dialogue"; + private const string AutoTriggerFallback = "Based on your current state and surroundings, respond naturally."; + + private static readonly string[] SuppressedTools = + { + DialogueToolDefinitions.ExpressDialogueToolName + }; + + private static readonly Regex LayerTagRegex = new Regex(@"\[L\d+\]\s*", RegexOptions.Compiled); + private static readonly Regex XmlTagRegex = new Regex(@"<[^>]+>", RegexOptions.Compiled); + private static readonly Regex WhitespaceRegex = new Regex(@"\s+", RegexOptions.Compiled); + + public string Id => "dialogue.trace"; + public string OwnerModId => RimMindOwnerConsts.DialogueModId; + public int Order => 100; + + public bool ShouldSuppressToolCall(string toolName) + => string.Equals(toolName, DialogueToolDefinitions.ExpressDialogueToolName, StringComparison.OrdinalIgnoreCase); + + public bool TrySummarizeResponse(AIRequestTraceEntry entry, out RequestTraceSummary? summary) + { + summary = null; + if (entry == null) + return false; + + AIRequestToolCallTrace? expressCall = FindExpressDialogueCall(entry); + bool isDialogueRequest = expressCall != null + || string.Equals(entry.ModId, DialogueModId, StringComparison.OrdinalIgnoreCase); + if (!isDialogueRequest) + return false; + + DialogueOutput? parsed = null; + if (expressCall != null && !string.IsNullOrWhiteSpace(expressCall.ArgumentsJson) + && DialogueToolParser.TryParse(expressCall.ArgumentsJson, isMonologue: false, out var fromArgs)) + { + parsed = fromArgs; + } + else if (!string.IsNullOrWhiteSpace(entry.Response) + && DialogueToolParser.TryParse(entry.Response, isMonologue: false, out var fromResponse)) + { + parsed = fromResponse; + } + + if (parsed == null || string.IsNullOrWhiteSpace(parsed.Speech)) + return false; + + string speech = "\"" + ToSingleLine(parsed.Speech) + "\""; + if (!string.IsNullOrWhiteSpace(parsed.ThoughtDesc)) + { + speech += " (" + ToSingleLine(parsed.ThoughtDesc) + ")"; + } + else if (!string.IsNullOrWhiteSpace(parsed.ThoughtTag) + && !string.Equals(parsed.ThoughtTag, "NONE", StringComparison.OrdinalIgnoreCase)) + { + string label = ThoughtInjector.MapTagToLabel(parsed.ThoughtTag!); + if (!string.IsNullOrWhiteSpace(label)) + speech += " (" + ToSingleLine(label) + ")"; + } + + summary = new RequestTraceSummary(speech, SuppressedTools); + return true; + } + + public bool TrySummarizePrompt(string rawPrompt, out string? summary) + { + summary = null; + if (string.IsNullOrWhiteSpace(rawPrompt)) + return false; + + string localizedAutoTrigger = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.AutoTrigger", + AutoTriggerFallback); + + bool isDialogueTrigger = rawPrompt.IndexOf("dialogue_trigger", StringComparison.OrdinalIgnoreCase) >= 0 + || rawPrompt.IndexOf(AutoTriggerFallback, StringComparison.OrdinalIgnoreCase) >= 0 + || (!string.IsNullOrEmpty(localizedAutoTrigger) + && rawPrompt.IndexOf(localizedAutoTrigger, StringComparison.Ordinal) >= 0); + + if (!isDialogueTrigger) + return false; + + string cleaned = LayerTagRegex.Replace(rawPrompt, string.Empty); + cleaned = XmlTagRegex.Replace(cleaned, string.Empty); + if (!string.IsNullOrEmpty(localizedAutoTrigger)) + cleaned = cleaned.Replace(localizedAutoTrigger, string.Empty); + cleaned = cleaned.Replace(AutoTriggerFallback, string.Empty); + cleaned = ToSingleLine(cleaned); + + summary = string.IsNullOrWhiteSpace(cleaned) + ? RimMindAPI.Text.TrOr("RimMind.UI.AgentsPage.Trace.DailyReaction", "Daily reaction") + : cleaned; + return true; + } + + private AIRequestToolCallTrace? FindExpressDialogueCall(AIRequestTraceEntry entry) + { + for (int i = 0; i < entry.ToolCalls.Count; i++) + { + var call = entry.ToolCalls[i]; + if (call != null && ShouldSuppressToolCall(call.ToolName)) + return call; + } + return null; + } + + private static string ToSingleLine(string? text) + { + if (string.IsNullOrWhiteSpace(text)) return string.Empty; + return WhitespaceRegex.Replace(text!, " ").Trim(); + } + } +} diff --git a/Source/Extensions/DialogueSettingsTab.cs b/Source/Extensions/DialogueSettingsTab.cs index adae486..d71faaa 100644 --- a/Source/Extensions/DialogueSettingsTab.cs +++ b/Source/Extensions/DialogueSettingsTab.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Dialogue.Settings; using RimMind.Presentation.Api; using RimMind.Presentation.Settings; @@ -8,7 +9,7 @@ namespace RimMind.Dialogue internal sealed class DialogueSettingsTab : ISettingsTab { public string Id => "dialogue"; - public string OwnerModId => "RimMindDialogue"; + public string OwnerModId => RimMindOwnerConsts.DialogueModId; public string Label => RimMindAPI.Text.TrOr("RimMind.Dialogue.Settings.TabLabel", "Dialogue"); public void Draw(Rect rect) => RimMindDialogueSettings.DrawSettingsContent(rect); } diff --git a/Source/Extensions/DialogueSkipCheck.cs b/Source/Extensions/DialogueSkipCheck.cs index 055d2c9..631cec8 100644 --- a/Source/Extensions/DialogueSkipCheck.cs +++ b/Source/Extensions/DialogueSkipCheck.cs @@ -1,3 +1,4 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; namespace RimMind.Dialogue @@ -5,11 +6,11 @@ namespace RimMind.Dialogue internal sealed class DialogueSkipCheck : ISkipCheck { public string Id => "dialogue.skip"; - public string OwnerModId => "RimMindDialogue"; + public string OwnerModId => RimMindOwnerConsts.DialogueModId; public SkipCheckKind Kind => SkipCheckKind.Dialogue; // Dialogue 模组自身不参与 SkipCheck 互斥决策。 // 此实现仅为满足 IExtension 注册要求,让 RimMindAPI.Extensions() - // 能枚举到本 mod 的存在。实际 skip 逻辑由 RimMindAPI.ShouldSkipDialogue 统一处理。 + // 能枚举到本 mod 的存在。实际 skip 逻辑由 RimMindAPI.Ext.ShouldSkipDialogue 统一处理。 public bool ShouldSkip(in SkipCheckArgs args) => false; } } diff --git a/Source/Extensions/DialogueTriggerAdapter.cs b/Source/Extensions/DialogueTriggerAdapter.cs index 5dd4f0c..ecf030a 100644 --- a/Source/Extensions/DialogueTriggerAdapter.cs +++ b/Source/Extensions/DialogueTriggerAdapter.cs @@ -1,6 +1,6 @@ +using RimMind.Application.Common.Constants; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Dialogue.Core; -using RimWorld; using Verse; namespace RimMind.Dialogue @@ -8,7 +8,7 @@ namespace RimMind.Dialogue internal sealed class DialogueTriggerAdapter : IDialogueTrigger { public string Id => "dialogue"; - public string OwnerModId => "RimMind.Dialogue"; + public string OwnerModId => RimMindOwnerConsts.DialogueModId; // 限制:IDialogueTrigger.Trigger 接口签名无 triggerType 参数(Core 定义,有 ArchTest 保护), // 外部 mod 通过此扩展点触发时统一映射为 Chitchat 类型。 // 若需区分触发类型(Hediff/LevelUp/Thought/Auto),需 Core 协同修改接口签名, diff --git a/Source/Patches/AddCompToHumanlikePatch.cs b/Source/Patches/AddCompToHumanlikePatch.cs index cdc66a9..913330f 100644 --- a/Source/Patches/AddCompToHumanlikePatch.cs +++ b/Source/Patches/AddCompToHumanlikePatch.cs @@ -2,7 +2,6 @@ using System.Linq; using HarmonyLib; using RimMind.Dialogue.Comps; -using RimWorld; using Verse; namespace RimMind.Dialogue.Patches diff --git a/Source/Patches/BubblePatch.cs b/Source/Patches/BubblePatch.cs index 6c73531..e670f1a 100644 --- a/Source/Patches/BubblePatch.cs +++ b/Source/Patches/BubblePatch.cs @@ -1,6 +1,7 @@ using HarmonyLib; using RimMind.Dialogue.Core; using RimMind.Dialogue.Settings; +using RimMind.Presentation.Api; using RimWorld; using Verse; @@ -13,16 +14,15 @@ public static class BubblePatch public static void Postfix(Pawn ___pawn, Pawn recipient, InteractionDef intDef, bool __result) { if (!__result) return; - if (!RimMindDialogueSettings.Get().chitchatEnabled) return; - if (ModsConfig.IsActive("juicy.RimTalk")) return; + var settings = RimMindDialogueSettings.Get(); + if (!settings.enabled || !settings.chitchatEnabled) return; if (intDef?.defName != "Chitchat" && intDef?.defName != "DeepTalk") return; Pawn initiator = ___pawn; - if (!RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(initiator)) return; - if (!RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(recipient)) return; + if (!RimMindPawnLookup.IsActiveSpawnedColonist(initiator)) return; + if (!RimMindPawnLookup.IsActiveSpawnedColonist(recipient)) return; - var settings = RimMindDialogueSettings.Get(); var pairKey = DialogueClassifier.MakePairKey(initiator.thingIDNumber, recipient.thingIDNumber); float opinion = initiator.relations?.OpinionOf(recipient) ?? 0f; int currentTick = Find.TickManager.TicksGame; @@ -32,7 +32,11 @@ public static void Postfix(Pawn ___pawn, Pawn recipient, InteractionDef intDef, return; } - string context = "RimMind.Dialogue.Context.InteractionContext".Translate(intDef.defName, recipient.LabelShort); + string context = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.InteractionContext", + "[{0}] Talking with {1}", + intDef.defName, + recipient.LabelShort); RimMindDialogueService.HandleTrigger(initiator, context, DialogueTriggerType.Chitchat, recipient); } } diff --git a/Source/Patches/FloatMenuPatch.cs b/Source/Patches/FloatMenuPatch.cs index d2ad663..8dbca9c 100644 --- a/Source/Patches/FloatMenuPatch.cs +++ b/Source/Patches/FloatMenuPatch.cs @@ -10,22 +10,11 @@ namespace RimMind.Dialogue.Patches { -#if V1_5 - [HarmonyPatch(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.ChoicesAtFor))] -#else [HarmonyPatch(typeof(FloatMenuMakerMap), nameof(FloatMenuMakerMap.GetOptions))] -#endif public static class FloatMenuPatch { private const int ClickRadiusCells = 1; -#if V1_5 - [HarmonyPostfix] - public static void Postfix(Vector3 clickPos, Pawn pawn, ref List __result) - { - TryAddTalkOption(__result, pawn, clickPos); - } -#else [HarmonyPostfix] public static void Postfix( List selectedPawns, @@ -34,11 +23,10 @@ public static void Postfix( ref List __result) { Pawn? pawn = (selectedPawns is { Count: 1 }) ? selectedPawns[0] : null; - TryAddTalkOption(__result, pawn!, clickPos); + TryAddTalkOption(__result, pawn, clickPos); } -#endif - private static void TryAddTalkOption(List result, Pawn selectedPawn, Vector3 clickPos) + private static void TryAddTalkOption(List result, Pawn? selectedPawn, Vector3 clickPos) { if (result == null) return; if (!RimMindDialogueSettings.Get().enabled) return; @@ -87,37 +75,47 @@ private static void AddTalkOption(List result, Pawn initiator, { if (RimMindAPI.Ext.ShouldSkipFloatMenu()) return; + string initiatorName = initiator.Name?.ToStringShort ?? initiator.LabelShort; + string targetName = target.Name?.ToStringShort ?? target.LabelShort; + result.Add(new FloatMenuOption( - "RimMind.Dialogue.UI.FloatMenu.ChatWith".Translate(target.LabelShortCap), + RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.FloatMenu.ChatWith", "Chat with {0}", target.LabelShortCap), delegate { if (!RimMindAPI.Settings.IsConfigured()) { - Messages.Message("RimMind.Dialogue.UI.FloatMenu.APINotConfigured".Translate(), + Messages.Message( + RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.FloatMenu.APINotConfigured", "API not configured, cannot dialogue"), MessageTypeDefOf.RejectInput, false); return; } if (!RimMindDialogueService.IsReady) { - Messages.Message("RimMind.Dialogue.UI.FloatMenu.NotReady".Translate(), + Messages.Message( + RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.FloatMenu.NotReady", "Dialogue system not ready, please try again later"), MessageTypeDefOf.RejectInput, false); return; } if (RimMindDialogueService.IsDialoguePending(initiator.thingIDNumber, target.thingIDNumber)) { - Messages.Message("RimMind.Dialogue.UI.FloatMenu.Pending".Translate(), + Messages.Message( + RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.FloatMenu.Pending", "Dialogue request in progress, please wait"), MessageTypeDefOf.RejectInput, false); return; } int count = RimMindDialogueService.GetDailyDialogueCount(initiator.thingIDNumber, target.thingIDNumber); if (count >= RimMindDialogueSettings.Get().maxDailyDialogueRounds) { - Messages.Message("RimMind.Dialogue.UI.FloatMenu.DailyLimitReached".Translate(), + Messages.Message( + RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.FloatMenu.DailyLimitReached", "Daily dialogue limit reached"), MessageTypeDefOf.RejectInput, false); return; } - string context = "RimMind.Dialogue.Context.PlayerInitiate".Translate( - initiator.Name.ToStringShort, target.Name.ToStringShort); + string context = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.PlayerInitiate", + "{0} initiates conversation with {1}", + initiatorName, + targetName); RimMindDialogueService.HandleTrigger( initiator, context, @@ -127,7 +125,10 @@ private static void AddTalkOption(List result, Pawn initiator, { RimMindErrors.Warn($"[RimMind-Dialogue] FloatMenu dialogue error: {error}"); Messages.Message( - "RimMind.Dialogue.UI.FloatMenu.RequestFailed".Translate(initiator.Name.ToStringShort), + RimMindAPI.Text.TrOr( + "RimMind.Dialogue.UI.FloatMenu.RequestFailed", + "Dialogue request for {0} failed", + initiatorName), MessageTypeDefOf.RejectInput, false); }); diff --git a/Source/Patches/SkillLearnPatch.cs b/Source/Patches/SkillLearnPatch.cs index 5473f25..302feee 100644 --- a/Source/Patches/SkillLearnPatch.cs +++ b/Source/Patches/SkillLearnPatch.cs @@ -21,7 +21,8 @@ public static void Prefix(SkillRecord __instance, float xp, out int __state) public static void Postfix(SkillRecord __instance, float xp, int __state) { if (__state < 0 || __instance.Level <= __state) return; - if (!RimMindDialogueSettings.Get().levelUpEnabled) return; + var settings = RimMindDialogueSettings.Get(); + if (!settings.enabled || !settings.levelUpEnabled) return; Pawn pawn = __instance.Pawn; if (!RimMindPawnLookup.IsEligibleColonist(pawn) || pawn.Downed) return; @@ -31,7 +32,12 @@ public static void Postfix(SkillRecord __instance, float xp, int __state) __instance.def?.defName ?? string.Empty, __state, __instance.Level)); - string context = "RimMind.Dialogue.Context.SkillLevelUp".Translate(__instance.def!.label, __instance.Level); + string skillLabel = __instance.def?.label ?? __instance.def?.defName ?? string.Empty; + string context = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.SkillLevelUp", + "{0} skill reached level {1}", + skillLabel, + __instance.Level); RimMindDialogueService.HandleTrigger(pawn, context, DialogueTriggerType.LevelUp, null); } } diff --git a/Source/Patches/ThoughtPatch.cs b/Source/Patches/ThoughtPatch.cs index 16d4d42..eeba2f8 100644 --- a/Source/Patches/ThoughtPatch.cs +++ b/Source/Patches/ThoughtPatch.cs @@ -22,7 +22,8 @@ public static class ThoughtPatch [HarmonyPostfix] public static void Postfix(MemoryThoughtHandler __instance, Thought_Memory newThought) { - if (!RimMindDialogueSettings.Get().thoughtEnabled) return; + var settings = RimMindDialogueSettings.Get(); + if (!settings.enabled || !settings.thoughtEnabled) return; if (newThought?.def == null) return; @@ -31,10 +32,11 @@ public static void Postfix(MemoryThoughtHandler __instance, Thought_Memory newTh if (curStage != null) moodEffect = curStage.baseMoodEffect; - if (Mathf.Abs(moodEffect) < RimMindDialogueSettings.Get().moodChangeThreshold) return; + if (Mathf.Abs(moodEffect) < settings.moodChangeThreshold) return; Pawn pawn = __instance.pawn; if (!RimMindPawnLookup.IsEligibleColonist(pawn) || pawn.Downed) return; + if (!RimMindDialogueService.IsReady) return; if (newThought.def.defName.StartsWith("RimMindDialogue_")) return; @@ -50,7 +52,11 @@ public static void Postfix(MemoryThoughtHandler __instance, Thought_Memory newTh rawLabel.Replace("{ROLE_label}", "role").Replace("{0}", ""), @"\{[A-Za-z0-9_]+\}", "").Trim(); - string context = "RimMind.Dialogue.Context.MoodChanged".Translate(cleanLabel, $"{moodEffect:+0;-0}"); + string context = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Context.MoodChanged", + "Mood changed: {0} ({1} mood)", + cleanLabel, + $"{moodEffect:+0;-0}"); RimMindDialogueService.HandleTrigger(pawn, context, DialogueTriggerType.Thought, null); } } diff --git a/Source/RimMindDialogueMod.cs b/Source/RimMindDialogueMod.cs index 5d237fe..78b08c3 100644 --- a/Source/RimMindDialogueMod.cs +++ b/Source/RimMindDialogueMod.cs @@ -1,4 +1,3 @@ -using HarmonyLib; using RimMind.Application.Common.Interfaces.Extension; using RimMind.Presentation; using RimMind.Presentation.Api; @@ -30,6 +29,7 @@ public RimMindDialogueMod(ModContentPack content) : base(content) RimMindAPI.Extensions().Register(new DialogueOverlayToggleBehavior()); RimMindAPI.Extensions().Register(new DialogueTriggerAdapter()); RimMindAPI.Extensions().Register(new DialogueSkipCheck()); + RimMindAPI.Diagnostics.RegisterTraceSummarizer(new DialogueRequestTraceSummarizer()); Log.Message("[RimMind-Dialogue] Initialized."); } diff --git a/Source/Settings/RimMindDialogueSettings.cs b/Source/Settings/RimMindDialogueSettings.cs index 0d01c2c..a904d57 100644 --- a/Source/Settings/RimMindDialogueSettings.cs +++ b/Source/Settings/RimMindDialogueSettings.cs @@ -1,5 +1,6 @@ using UnityEngine; using Verse; +using RimMind.Presentation.Api; using RimMind.Presentation.UI; namespace RimMind.Dialogue.Settings @@ -106,6 +107,9 @@ public override void ExposeData() private static Vector2 _settingsScrollPos = Vector2.zero; private static float _measuredSettingsHeight = 640f; + private static string Tr(string key, string fallback, params object[] args) + => RimMindAPI.Text.TrOr(key, fallback, args); + public static void DrawSettingsContent(UnityEngine.Rect inRect) { var s = Get(); @@ -116,82 +120,104 @@ public static void DrawSettingsContent(UnityEngine.Rect inRect) ref _measuredSettingsHeight, listing => { - listing.CheckboxLabeled("RimMind.Dialogue.Settings.Enable".Translate(), ref s.enabled, - "RimMind.Dialogue.Settings.Enable.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Dialogue.Settings.TriggerSources".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.ChitchatIntercept".Translate(), ref s.chitchatEnabled, - "RimMind.Dialogue.Settings.ChitchatIntercept.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.HediffReaction".Translate(), ref s.hediffEnabled, - "RimMind.Dialogue.Settings.HediffReaction.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.LevelUpReaction".Translate(), ref s.levelUpEnabled, - "RimMind.Dialogue.Settings.LevelUpReaction.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.ThoughtReaction".Translate(), ref s.thoughtEnabled, - "RimMind.Dialogue.Settings.ThoughtReaction.Desc".Translate()); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.Enable", "Enable AI Dialogue System"), + ref s.enabled, + Tr("RimMind.Dialogue.Settings.Enable.Desc", "When enabled, colonists will generate dialogues and monologues based on game events and their state.")); + + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Dialogue.Settings.TriggerSources", "Trigger Sources")); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.ChitchatIntercept", "Intercept Chitchat"), + ref s.chitchatEnabled, + Tr("RimMind.Dialogue.Settings.ChitchatIntercept.Desc", "Replace vanilla Chitchat/DeepTalk interactions with AI-generated dialogue.")); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.HediffReaction", "Health Change Reaction"), + ref s.hediffEnabled, + Tr("RimMind.Dialogue.Settings.HediffReaction.Desc", "When a colonist is injured or falls ill, AI generates a dialogue reaction.")); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.LevelUpReaction", "Skill Level Up Reaction"), + ref s.levelUpEnabled, + Tr("RimMind.Dialogue.Settings.LevelUpReaction.Desc", "When a colonist levels up a skill, AI generates a dialogue reaction.")); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.ThoughtReaction", "Mood Change Reaction"), + ref s.thoughtEnabled, + Tr("RimMind.Dialogue.Settings.ThoughtReaction.Desc", "When a colonist's mood changes significantly, AI generates a dialogue reaction.")); if (s.thoughtEnabled) { - listing.Label(" " + "RimMind.Dialogue.Settings.MoodThreshold".Translate($"{s.moodChangeThreshold:F0}")); + listing.Label(" " + Tr("RimMind.Dialogue.Settings.MoodThreshold", "Mood change threshold: {0}", $"{s.moodChangeThreshold:F0}")); s.moodChangeThreshold = listing.Slider(s.moodChangeThreshold, 1f, 5f); } - listing.CheckboxLabeled("RimMind.Dialogue.Settings.AutoMonologue".Translate(), ref s.autoDialogueEnabled, - "RimMind.Dialogue.Settings.AutoMonologue.Desc".Translate()); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.AutoMonologue", "Auto Monologue on Idle"), + ref s.autoDialogueEnabled, + Tr("RimMind.Dialogue.Settings.AutoMonologue.Desc", "When a colonist is idle, automatically trigger an inner monologue.")); if (s.autoDialogueEnabled) { listing.LabelWithTooltip( - " " + "RimMind.Dialogue.Settings.AutoInterval".Translate(s.autoDialogueCooldownHours), - "RimMind.Dialogue.Settings.AutoMonologueDesc".Translate()); + " " + Tr("RimMind.Dialogue.Settings.AutoInterval", "Auto monologue interval: {0} game hours", s.autoDialogueCooldownHours), + Tr("RimMind.Dialogue.Settings.AutoMonologueDesc", "Minimum game hours between auto-monologues when a colonist is idle.")); s.autoDialogueCooldownHours = (int)listing.Slider(s.autoDialogueCooldownHours, 1f, 24f); } - listing.CheckboxLabeled("RimMind.Dialogue.Settings.PlayerDialogueGizmo".Translate(), ref s.playerDialogueEnabled, - "RimMind.Dialogue.Settings.PlayerDialogueGizmo.Desc".Translate()); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.PlayerDialogueGizmo", "Player Initiated Dialogue"), + ref s.playerDialogueEnabled, + Tr("RimMind.Dialogue.Settings.PlayerDialogueGizmo.Desc", "Show a chat button on colonists and a right-click dialogue option.")); - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Dialogue.Settings.Section.Behavior".Translate()); + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Dialogue.Settings.Section.Behavior", "Behavior Settings")); listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.MonologueCooldown".Translate($"{s.monologueCooldownTicks / 2500f:F1}", $"{s.monologueCooldownTicks}"), - "RimMind.Dialogue.Settings.MonologueCooldown.Desc".Translate()); + Tr("RimMind.Dialogue.Settings.MonologueCooldown", "Monologue Cooldown: {0} game hours ({1} ticks)", $"{s.monologueCooldownTicks / 2500f:F1}", $"{s.monologueCooldownTicks}"), + Tr("RimMind.Dialogue.Settings.MonologueCooldown.Desc", "Minimum interval between same-type monologues for the same colonist.")); s.monologueCooldownTicks = (int)listing.Slider(s.monologueCooldownTicks, 3600f, 72000f); s.monologueCooldownTicks = (s.monologueCooldownTicks / 600) * 600; listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.MaxDailyDialogues".Translate(s.maxDailyDialogueRounds), - "RimMind.Dialogue.Settings.MaxDailyDialogues.Desc".Translate()); + Tr("RimMind.Dialogue.Settings.MaxDailyDialogues", "Max daily dialogue rounds per pair: {0}", s.maxDailyDialogueRounds), + Tr("RimMind.Dialogue.Settings.MaxDailyDialogues.Desc", "Maximum dialogue rounds per colonist pair per day.")); s.maxDailyDialogueRounds = (int)listing.Slider(s.maxDailyDialogueRounds, 1f, 20f); listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.GlobalConcurrency".Translate(s.globalConcurrency), - "RimMind.Dialogue.Settings.GlobalConcurrency.Desc".Translate()); + Tr("RimMind.Dialogue.Settings.GlobalConcurrency", "Global dialogue concurrency limit: {0}", s.globalConcurrency), + Tr("RimMind.Dialogue.Settings.GlobalConcurrency.Desc", "Maximum number of simultaneous AI dialogue requests.")); s.globalConcurrency = (int)listing.Slider(s.globalConcurrency, 1f, 10f); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.EnableDialogueReply".Translate(), ref s.enableDialogueReply, - "RimMind.Dialogue.Settings.EnableDialogueReply.Desc".Translate()); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.EnableDialogueReply", "Enable Dialogue Reply"), + ref s.enableDialogueReply, + Tr("RimMind.Dialogue.Settings.EnableDialogueReply.Desc", "Automatically generate a reply when receiving dialogue.")); if (s.enableDialogueReply) { listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.MaxDailyReplies".Translate(s.maxDailyReplyRounds), - "RimMind.Dialogue.Settings.MaxDailyReplies.Desc".Translate()); + Tr("RimMind.Dialogue.Settings.MaxDailyReplies", "Maximum automatic replies per pair each day: {0}", s.maxDailyReplyRounds), + Tr("RimMind.Dialogue.Settings.MaxDailyReplies.Desc", "Rate-limits continuous two-way conversations.")); s.maxDailyReplyRounds = (int)listing.Slider(s.maxDailyReplyRounds, 1f, 50f); } - listing.CheckboxLabeled("RimMind.Dialogue.Settings.StartDelay".Translate(), ref s.startDelayEnabled, - "RimMind.Dialogue.Settings.StartDelay.Desc".Translate()); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.StartDelay", "Game start delay"), + ref s.startDelayEnabled, + Tr("RimMind.Dialogue.Settings.StartDelay.Desc", "No dialogue is triggered for a period after loading a save or starting a new game.")); if (s.startDelayEnabled) { - listing.Label(" " + "RimMind.Dialogue.Settings.StartDelayValue".Translate(s.startDelaySeconds)); + listing.Label(" " + Tr("RimMind.Dialogue.Settings.StartDelayValue", "Start delay: {0}s", s.startDelaySeconds)); s.startDelaySeconds = (int)listing.Slider(s.startDelaySeconds, 1f, 60f); } - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Dialogue.Settings.Section.Display".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.ShowNotification".Translate(), ref s.showThoughtNotification, - "RimMind.Dialogue.Settings.ShowNotification.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.ShowOverlay".Translate(), ref s.overlayEnabled, - "RimMind.Dialogue.Settings.ShowOverlay.Desc".Translate()); + SettingsUIDrawer.DrawSectionHeader(listing, Tr("RimMind.Dialogue.Settings.Section.Display", "Display")); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.ShowNotification", "Show notification when Thought is injected"), + ref s.showThoughtNotification, + Tr("RimMind.Dialogue.Settings.ShowNotification.Desc", "Display a notification when the dialogue system injects a mood Thought.")); + listing.CheckboxLabeled( + Tr("RimMind.Dialogue.Settings.ShowOverlay", "Show dialogue overlay"), + ref s.overlayEnabled, + Tr("RimMind.Dialogue.Settings.ShowOverlay.Desc", "Display a floating panel on screen showing recent dialogue content.")); listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.OverlayOpacity".Translate($"{s.overlayOpacity:P0}"), - "RimMind.Dialogue.Settings.OverlayOpacity.Desc".Translate()); + Tr("RimMind.Dialogue.Settings.OverlayOpacity", "Overlay opacity: {0}", $"{s.overlayOpacity:P0}"), + Tr("RimMind.Dialogue.Settings.OverlayOpacity.Desc", "Opacity of the dialogue overlay.")); s.overlayOpacity = listing.Slider(s.overlayOpacity, 0.1f, 1f); listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.OverlayMaxMessages".Translate(s.overlayMaxMessages), - "RimMind.Dialogue.Settings.OverlayMaxMessages.Desc".Translate()); + Tr("RimMind.Dialogue.Settings.OverlayMaxMessages", "Overlay max messages: {0}", s.overlayMaxMessages), + Tr("RimMind.Dialogue.Settings.OverlayMaxMessages.Desc", "Maximum number of dialogue lines shown simultaneously in the overlay.")); s.overlayMaxMessages = (int)listing.Slider(s.overlayMaxMessages, 3f, 20f); }, onReset: () => ResetToDefaults(s), @@ -212,6 +238,8 @@ private static void ResetToDefaults(RimMindDialogueSettings s) s.maxDailyDialogueRounds = 6; s.globalConcurrency = 3; s.showThoughtNotification = false; + s.targetDialogueCadenceDays = 3.0f; + s.maxStoredDialogueHistory = 200; s.enableDialogueReply = true; s.maxDailyReplyRounds = 12; s.monologueCooldownTicks = 36000; diff --git a/Source/Thoughts/ThoughtInjector.cs b/Source/Thoughts/ThoughtInjector.cs index b282f74..64eadea 100644 --- a/Source/Thoughts/ThoughtInjector.cs +++ b/Source/Thoughts/ThoughtInjector.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Concurrent; -using System.Collections.Generic; using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; using RimWorld; @@ -114,7 +113,7 @@ public static void InjectRelationDelta(Pawn pawn, Pawn recipient, float delta) thought.otherPawn = recipient; thought.opinionOffset = delta; - string pawnName = recipient.Name.ToStringShort; + string pawnName = recipient.Name?.ToStringShort ?? recipient.LabelShort; thought.aiLabel = delta > 0 ? RimMindAPI.Text.TrOr("RimMind.Dialogue.Relation.Positive", "pleasant conversation with {0}", pawnName) : RimMindAPI.Text.TrOr("RimMind.Dialogue.Relation.Negative", "unpleasant conversation with {0}", pawnName); diff --git a/Source/UI/DialogueOverlay.cs b/Source/UI/DialogueOverlay.cs index ffc3a58..535314c 100644 --- a/Source/UI/DialogueOverlay.cs +++ b/Source/UI/DialogueOverlay.cs @@ -5,7 +5,6 @@ using RimMind.Dialogue.Settings; using RimMind.Dialogue.UI; using RimMind.Presentation.Api; -using RimWorld; using UnityEngine; using Verse; @@ -33,8 +32,10 @@ public class DialogueOverlay : MapComponent private readonly HashSet _liveColonistIds = new HashSet(); private int _lastLiveColonistRefreshTick = -99999; private int _cachedLiveColonistsHash; + private int _nextEntryExpiryTick = -1; private const int LiveColonistCacheIntervalTicks = 60; + private const int MaxEntryAgeTicks = 60000; // 1 in-game day private const float OptionsBarHeight = 24f; private const float ResizeHandleSize = 24f; private const float TextPadding = 6f; @@ -50,11 +51,6 @@ public DialogueOverlay(Map map) : base(map) LoadPositionFromSettings(); } - public override void MapRemoved() - { - base.MapRemoved(); - } - public override void MapComponentOnGUI() { if (Current.ProgramState != ProgramState.Playing) return; @@ -179,6 +175,11 @@ private void EnsureCachedEntries(RimMindDialogueSettings settings) RefreshLiveColonistCache(nowTick); } + if (_nextEntryExpiryTick > 0 && nowTick > _nextEntryExpiryTick) + { + _cacheDirty = true; + } + if (_cacheDirty || _cachedLogRevision != currentLogRevision || _cachedMaxMessages != maxMessages) { bool IsPawnActiveOnCurrentMap(int pawnId, bool isColonist) @@ -186,12 +187,10 @@ bool IsPawnActiveOnCurrentMap(int pawnId, bool isColonist) if (isColonist) return _liveColonistIds.Contains(pawnId); - var p = RimMind.Presentation.Api.RimMindPawnLookup.FindPawnByNumber(pawnId); + var p = RimMindPawnLookup.FindPawnByNumber(pawnId); return p != null && !p.Dead && !p.Destroyed && p.Spawned && p.Map == map; } - const int MaxEntryAgeTicks = 60000; // 1 in-game day - _cachedEntries = RimMindDialogueService.LogEntries .Where(entry => (nowTick <= 0 || entry.tick <= 0 || (nowTick - entry.tick) <= MaxEntryAgeTicks) @@ -205,9 +204,16 @@ bool IsPawnActiveOnCurrentMap(int pawnId, bool isColonist) _cachedDisplayReplies = count == 0 ? Array.Empty() : new string[count]; _cachedLabelWidths = count == 0 ? Array.Empty() : new float[count]; _cachedLineHeights = count == 0 ? Array.Empty() : new float[count]; + int nextExpiry = -1; for (int i = 0; i < count; i++) { DialogueLogEntry entry = _cachedEntries[i]; + if (entry.tick > 0) + { + int expiry = entry.tick + MaxEntryAgeTicks; + if (nextExpiry < 0 || expiry < nextExpiry) + nextExpiry = expiry; + } string name = entry.initiatorName ?? string.Empty; _cachedLabels[i] = entry.IsMonologue ? $"[{name}]" @@ -215,6 +221,7 @@ bool IsPawnActiveOnCurrentMap(int pawnId, bool isColonist) _cachedDisplayReplies[i] = FormatCompactOverlayText(entry.reply); } + _nextEntryExpiryTick = nextExpiry; _cachedLayoutWidth = -1f; _cachedLogRevision = currentLogRevision; _cachedMaxMessages = maxMessages; @@ -360,11 +367,11 @@ private void DrawOptionsBar(Rect inRect) var barRect = new Rect(inRect.x, inRect.y, inRect.width, OptionsBarHeight); Widgets.DrawBoxSolid(barRect, new Color(0.05f, 0.05f, 0.08f, 0.8f)); - var titleRect = new Rect(barRect.x + 4f, barRect.y, 100f, barRect.height); + var titleRect = new Rect(barRect.x + 4f, barRect.y, Mathf.Max(100f, barRect.width - 92f), barRect.height); Text.Font = GameFont.Tiny; Text.Anchor = TextAnchor.MiddleLeft; GUI.color = new Color(0.7f, 0.8f, 1f); - Widgets.Label(titleRect, "RimMind.Dialogue.UI.Overlay.Title".Translate()); + Widgets.Label(titleRect, RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Overlay.Title", "RimMind Dialogue")); GUI.color = Color.white; Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; @@ -375,7 +382,7 @@ private void DrawOptionsBar(Rect inRect) { _temporarilyClosed = true; } - if (Widgets.ButtonText(openBtnRect, "RimMind.Dialogue.UI.Overlay.Details".Translate())) + if (Widgets.ButtonText(openBtnRect, RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Overlay.Details", "Details"))) { Find.WindowStack.Add(new Window_DialogueLog()); } @@ -473,6 +480,7 @@ private void SavePositionToSettings() s.overlayY = _windowRect.y; s.overlayW = _windowRect.width; s.overlayH = _windowRect.height; + s.Write(); } } } diff --git a/Source/UI/Window_Dialogue.cs b/Source/UI/Window_Dialogue.cs index 8e774eb..54b7038 100644 --- a/Source/UI/Window_Dialogue.cs +++ b/Source/UI/Window_Dialogue.cs @@ -30,18 +30,23 @@ public override void PostClose() } protected override bool ValidateCanStayOpen() - => RimMindPawnLookup.IsEligibleColonist(_pawn) && !_pawn.Downed; + => RimMindPawnLookup.IsEligibleColonist(_pawn) && !_pawn.Downed + && (_initiator == null || (RimMindPawnLookup.IsEligibleColonist(_initiator) && !_initiator.Downed)); - protected override string GetTitle() => _initiator != null - ? RimMindAPI.Text.TrOr( - "RimMind.Dialogue.UI.ChatTitleWithInitiator", - "{0} & {1}", - _initiator.Name.ToStringShort, - _pawn.Name.ToStringShort) - : RimMindAPI.Text.TrOr( - "RimMind.Dialogue.UI.ChatTitle", - "Chat with {0}", - _pawn.Name.ToStringShort); + protected override string GetTitle() + { + string pawnName = _pawn.Name?.ToStringShort ?? _pawn.LabelShort; + return _initiator != null + ? RimMindAPI.Text.TrOr( + "RimMind.Dialogue.UI.ChatTitleWithInitiator", + "{0} & {1}", + _initiator.Name?.ToStringShort ?? _initiator.LabelShort, + pawnName) + : RimMindAPI.Text.TrOr( + "RimMind.Dialogue.UI.ChatTitle", + "Chat with {0}", + pawnName); + } protected override string GetWaitingText() => RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Thinking", "Thinking..."); @@ -54,10 +59,10 @@ protected override string GetPrefixForRole(string role) if (role == "user") { return _initiator != null - ? RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.PawnPrefix", "{0}: ", _initiator.Name.ToStringShort) + ? RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.PawnPrefix", "{0}: ", _initiator.Name?.ToStringShort ?? _initiator.LabelShort) : RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.PlayerPrefix", "You: "); } - return RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.PawnPrefix", "{0}: ", _pawn.Name.ToStringShort); + return RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.PawnPrefix", "{0}: ", _pawn.Name?.ToStringShort ?? _pawn.LabelShort); } protected override void OnSubmitUserMessage(string trimmedInput) @@ -81,7 +86,7 @@ protected override void OnSubmitUserMessage(string trimmedInput) RimMindAPI.Text.TrOr( "RimMind.Dialogue.UI.FloatMenu.RequestFailed", "Dialogue request failed for {0}", - _pawn.Name.ToStringShort), + _pawn.Name?.ToStringShort ?? _pawn.LabelShort), MessageTypeDefOf.RejectInput, false); }, cancellationToken: LifetimeToken); diff --git a/Source/UI/Window_DialogueLog.cs b/Source/UI/Window_DialogueLog.cs index 6bc651b..b0499f6 100644 --- a/Source/UI/Window_DialogueLog.cs +++ b/Source/UI/Window_DialogueLog.cs @@ -50,7 +50,7 @@ public override void DoWindowContents(Rect inRect) contentY += categoryBarHeight + Padding; contentHeight -= categoryBarHeight + Padding; - Widgets.Label(headerRect, "RimMind.Dialogue.UI.Log.Title".Translate()); + Widgets.Label(headerRect, RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Log.Title", "Dialogue Log")); DrawCategoryBar(categoryBarRect); @@ -64,24 +64,40 @@ public override void DoWindowContents(Rect inRect) private void DrawCategoryBar(Rect rect) { + const float gap = 4f; + int count = CategoryKeys.Length; + float totalGap = gap * Math.Max(0, count - 1); + float available = Math.Max(1f, rect.width - totalGap); + + float[] desired = new float[count]; + string[] labels = new string[count]; + float desiredSum = 0f; + for (int i = 0; i < count; i++) + { + labels[i] = RimMindAPI.Text.TrOr(CategoryKeys[i].key, CategoryKeys[i].fallback); + desired[i] = Text.CalcSize(labels[i]).x + 16f; + desiredSum += desired[i]; + } + + float scale = desiredSum > available ? available / desiredSum : 1f; float x = rect.x; - foreach (var (cat, key, fallback) in CategoryKeys) + for (int i = 0; i < count; i++) { - string label = RimMindAPI.Text.TrOr(key, fallback); - float width = Text.CalcSize(label).x + 20f; + var cat = CategoryKeys[i].cat; + float width = Math.Max(40f, desired[i] * scale); var btnRect = new Rect(x, rect.y, width, rect.height); bool selected = _selectedCategory == cat; if (selected) Widgets.DrawBoxSolid(btnRect, new Color(0.3f, 0.4f, 0.6f, 0.5f)); - if (Widgets.ButtonText(btnRect, label)) + if (Widgets.ButtonText(btnRect, labels[i])) { _selectedCategory = cat; _selectedTab = null; } - x += width + 4f; + x += width + gap; } } @@ -96,7 +112,7 @@ private void DrawTabList(Rect rect) { Text.Anchor = TextAnchor.MiddleCenter; GUI.color = Color.grey; - Widgets.Label(rect, "RimMind.Dialogue.UI.Log.NoRecords".Translate()); + Widgets.Label(rect, RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Log.NoRecords", "No records")); GUI.color = Color.white; Text.Anchor = TextAnchor.UpperLeft; return; @@ -134,7 +150,7 @@ private void DrawContent(Rect rect) { Text.Anchor = TextAnchor.MiddleCenter; GUI.color = Color.grey; - Widgets.Label(rect, "RimMind.Dialogue.UI.Log.SelectTab".Translate()); + Widgets.Label(rect, RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Log.SelectTab", "Select a tab to view dialogue")); GUI.color = Color.white; Text.Anchor = TextAnchor.UpperLeft; return; @@ -218,9 +234,11 @@ private void DrawDialogueContent(Rect rect, List entries) float contentHeight = 0f; float[] heights = new float[entries.Count]; + string[] lines = new string[entries.Count]; for (int i = 0; i < entries.Count; i++) { - heights[i] = Text.CalcHeight(entries[i].reply, halfWidth - Padding * 2) + Padding * 2; + lines[i] = $"[{entries[i].TimeStr}] {entries[i].reply}"; + heights[i] = Text.CalcHeight(lines[i], halfWidth - Padding * 2) + Padding * 2; contentHeight += heights[i]; } @@ -234,7 +252,6 @@ private void DrawDialogueContent(Rect rect, List entries) // 用 ID 判定左右列,避免重名导致列归属错误 bool isLeft = entry.initiatorId == leftId; - string timeStr = entry.TimeStr; float entryHeight = heights[i]; Color bgColor = i % 2 == 0 @@ -246,14 +263,14 @@ private void DrawDialogueContent(Rect rect, List entries) { var leftRect = new Rect(viewRect.x + Padding, y + Padding, halfWidth - Padding * 2, entryHeight - Padding * 2); GUI.color = new Color(0.7f, 0.85f, 1f); - Widgets.Label(leftRect, $"[{timeStr}] {entry.reply}"); + Widgets.Label(leftRect, lines[i]); GUI.color = Color.white; } else { var rightRect = new Rect(viewRect.x + halfWidth + Padding, y + Padding, halfWidth - Padding * 2, entryHeight - Padding * 2); GUI.color = new Color(1f, 0.95f, 0.8f); - Widgets.Label(rightRect, $"[{timeStr}] {entry.reply}"); + Widgets.Label(rightRect, lines[i]); GUI.color = Color.white; } @@ -352,34 +369,9 @@ private static string FormatEntry(DialogueLogEntry entry) } private static string TranslateTrigger(string triggerKey) - { - if (RimMindDialogueService.RegisteredTriggerLabels.TryGetValue(triggerKey, out var labelKey)) - return RimMindAPI.Text.TrOr(labelKey, labelKey); - - return triggerKey switch - { - "Chitchat" => "RimMind.Dialogue.Trigger.Chitchat".Translate(), - "Hediff" => "RimMind.Dialogue.Trigger.Hediff".Translate(), - "LevelUp" => "RimMind.Dialogue.Trigger.LevelUp".Translate(), - "Thought" => "RimMind.Dialogue.Trigger.Thought".Translate(), - "Auto" => "RimMind.Dialogue.Trigger.Auto".Translate(), - "PlayerInput" => "RimMind.Dialogue.Trigger.PlayerInput".Translate(), - _ => triggerKey, - }; - } + => DialogueTriggerRegistry.GetLabel(triggerKey); private static Color GetTriggerColor(string trigger) - { - return trigger switch - { - "Chitchat" => new Color(0.7f, 0.85f, 1f), - "Hediff" => new Color(1f, 0.6f, 0.6f), - "LevelUp" => new Color(0.6f, 1f, 0.6f), - "Thought" => new Color(1f, 0.95f, 0.6f), - "Auto" => new Color(0.8f, 0.8f, 0.8f), - "PlayerInput" => new Color(0.85f, 0.7f, 1f), - _ => Color.white, - }; - } + => DialogueTriggerRegistry.GetLogColor(trigger); } } diff --git a/Tests/Contracts/DialoguePipelineContracts.cs b/Tests/Contracts/DialoguePipelineContracts.cs index 57a12ec..b381ddd 100644 --- a/Tests/Contracts/DialoguePipelineContracts.cs +++ b/Tests/Contracts/DialoguePipelineContracts.cs @@ -1,6 +1,9 @@ using System; using System.Linq; +using RimMind.Application.Common.Models.Debug; using RimMind.Dialogue.Core; +using UnityEngine; +using Verse; using Xunit; namespace RimMind.Dialogue.Tests.Contracts @@ -49,120 +52,115 @@ public void PairKeysAreStable() } [Fact] - public void StructuredRepliesPreserveSemantics() + public void DialogueTriggerRegistry_ProvidesConsistentMetadataAndCustomLabels() { - string reply = "raw"; - string? tag = "NONE"; - string? description = null; - int relationDelta = 0; - - #pragma warning disable CS0618 - ResponseJsonParser.TryParseResponseJson( - "{\"reply\":\"Hello\",\"thought\":{\"tag\":\"VALUED\",\"description\":\"Seen\"},\"relation_delta\":2}", - false, - ref reply, - ref tag, - ref description, - ref relationDelta); - #pragma warning restore CS0618 - - Assert.Equal("Hello", reply); - Assert.Equal("VALUED", tag); - Assert.Equal("Seen", description); - Assert.Equal(2, relationDelta); + foreach (DialogueTriggerType trigger in Enum.GetValues(typeof(DialogueTriggerType))) + { + Assert.False(string.IsNullOrWhiteSpace(DialogueTriggerRegistry.GetTriggerKind(trigger))); + Assert.False(string.IsNullOrWhiteSpace(DialogueTriggerRegistry.GetLabel(trigger))); + Assert.NotEqual(Color.white, DialogueTriggerRegistry.GetLogColor(trigger.ToString())); + } + + Assert.Equal(Color.white, DialogueTriggerRegistry.GetLogColor("UnknownTriggerType")); + + Extensions.UntranslatableKeys.Add("RimMind.Dialogue.Prompt.Context.Hediff"); + try + { + Assert.Equal( + "[Health condition: frostbite]", + DialogueTriggerRegistry.FormatContext(DialogueTriggerType.Hediff, "frostbite")); + Assert.Equal( + "raw input", + DialogueTriggerRegistry.FormatContext(DialogueTriggerType.PlayerInput, "raw input")); + } + finally + { + Extensions.UntranslatableKeys.Remove("RimMind.Dialogue.Prompt.Context.Hediff"); + } + + string customId = "CustomTrigger_" + Guid.NewGuid().ToString("N"); + DialogueTriggerRegistry.RegisterLabel(customId, "Custom Label"); + Assert.Equal("Custom Label", DialogueTriggerRegistry.GetLabel(customId)); + DialogueTriggerRegistry.CustomLabels.TryRemove(customId, out _); } [Fact] - public void MonologuesIgnoreRelationChanges() + public void DialogueRequestTraceSummarizer_SuppressesExpressDialogueAndSummarizesTraces() { - string reply = "raw"; - string? tag = null; - string? description = null; - int relationDelta = 9; - - #pragma warning disable CS0618 - ResponseJsonParser.TryParseResponseJson( - "{\"reply\":\"Thinking\",\"relation_delta\":-5}", - true, - ref reply, - ref tag, - ref description, - ref relationDelta); - #pragma warning restore CS0618 - - Assert.Equal("Thinking", reply); - Assert.Equal(9, relationDelta); + var summarizer = new DialogueRequestTraceSummarizer(); + Assert.True(summarizer.ShouldSuppressToolCall("express_dialogue")); + Assert.True(summarizer.ShouldSuppressToolCall("EXPRESS_DIALOGUE")); + Assert.False(summarizer.ShouldSuppressToolCall("take_job")); + + var entryWithTool = new AIRequestTraceEntry { ModId = "RimMind.Dialogue" }; + entryWithTool.ToolCalls.Add(new AIRequestToolCallTrace( + "call-1", + "express_dialogue", + Succeeded: true, + Error: null, + ArgumentsJson: "{\"speech\":\"Watch the stove!\",\"thought_tag\":\"STRESSED\",\"thought_desc\":\"Smoke everywhere\"}")); + + Assert.True(summarizer.TrySummarizeResponse(entryWithTool, out var toolSummary)); + Assert.NotNull(toolSummary); + Assert.Equal("\"Watch the stove!\" (Smoke everywhere)", toolSummary!.ContentSummary); + Assert.Contains("express_dialogue", toolSummary.SuppressToolNames!); + + var entryFromResponse = new AIRequestTraceEntry + { + ModId = "RimMind.Dialogue", + Response = "{\"speech\":\"Nice work today.\",\"thought_tag\":\"ENCOURAGED\"}" + }; + Assert.True(summarizer.TrySummarizeResponse(entryFromResponse, out var responseSummary)); + Assert.NotNull(responseSummary); + Assert.StartsWith("\"Nice work today.\"", responseSummary!.ContentSummary, StringComparison.Ordinal); + + var unrelatedEntry = new AIRequestTraceEntry + { + ModId = "RimMind.Advisor", + Response = "{\"speech\":\"Ignored because not dialogue\"}" + }; + Assert.False(summarizer.TrySummarizeResponse(unrelatedEntry, out _)); + + Assert.True(summarizer.TrySummarizePrompt( + "[L3] [Chitchat: sharing a meal]\nBased on your current state and surroundings, respond naturally.", + out var promptSummary)); + Assert.Equal("[Chitchat: sharing a meal]", promptSummary); + + Extensions.UntranslatableKeys.Add("RimMind.UI.AgentsPage.Trace.DailyReaction"); + try + { + Assert.True(summarizer.TrySummarizePrompt( + "Based on your current state and surroundings, respond naturally.", + out var fallbackSummary)); + Assert.Equal("Daily reaction", fallbackSummary); + } + finally + { + Extensions.UntranslatableKeys.Remove("RimMind.UI.AgentsPage.Trace.DailyReaction"); + } + + Assert.False(summarizer.TrySummarizePrompt("Unrelated advisor decision prompt", out _)); } [Fact] - public void InvalidRepliesPreservePriorValues() + public void DialogueTextSanitizer_ClassifyThoughtTag_OnlyProducesRegisteredThoughtTags() { - AssertPreserved("plain text"); - AssertPreserved("{invalid"); - AssertPreserved(string.Empty); - AssertPreserved(null); - - string reply = "before"; - string? tag = "OLD"; - string? description = "old description"; - int relationDelta = 4; - - #pragma warning disable CS0618 - ResponseJsonParser.TryParseResponseJson( - "{\"thought\":{\"tag\":\"CONNECTED\"}}", - false, - ref reply, - ref tag, - ref description, - ref relationDelta); - #pragma warning restore CS0618 - - Assert.Equal("before", reply); - Assert.Equal("CONNECTED", tag); - Assert.Null(description); - Assert.Equal(4, relationDelta); - } - - [Fact] - public void NarrationAndMarkdownCodeBlockRepliesAreParsed() - { - // Case 1: narration field instead of reply - string reply = "raw"; - string? tag = null; - string? description = null; - int relationDelta = 0; - - #pragma warning disable CS0618 - ResponseJsonParser.TryParseResponseJson( - "{\"narration\":\"你感到全身旧伤\",\"thought\":{\"tag\":\"STRESSED\",\"description\":\"疲惫\"}}", - true, - ref reply, - ref tag, - ref description, - ref relationDelta); - - Assert.Equal("你感到全身旧伤", reply); - Assert.Equal("STRESSED", tag); - Assert.Equal("疲惫", description); - - // Case 2: Markdown code block wrapped JSON - reply = "raw2"; - tag = null; - description = null; - relationDelta = 0; - - ResponseJsonParser.TryParseResponseJson( - "```json\n{\"dialogue\":\"Hello friend!\",\"thought\":{\"tag\":\"CONNECTED\",\"description\":\"Joy\"}}\n```", - false, - ref reply, - ref tag, - ref description, - ref relationDelta); - #pragma warning restore CS0618 - - Assert.Equal("Hello friend!", reply); - Assert.Equal("CONNECTED", tag); - Assert.Equal("Joy", description); + string[] samples = + { + "Feeling terribly hurt and grieving today", + "Overwhelmed by stress and exhaustion", + "Furious and irritated at that insult", + "Grateful and happily connected with everyone", + "Just an ordinary neutral observation" + }; + + foreach (string sample in samples) + { + string tag = DialogueTextSanitizer.ClassifyThoughtTag(sample); + Assert.True( + tag == "NONE" || ThoughtInjector.MapTagToMoodOffset(tag) != 0, + $"ClassifyThoughtTag returned unregistered tag '{tag}' for '{sample}'."); + } } [Fact] @@ -206,29 +204,6 @@ public void ActivityStateSeparatesCooldownsAndResetsDailyQuota() Assert.Equal(0, state.GetDailyDialogueCount(60000, 1, 2)); } - private static void AssertPreserved(string? raw) - { - string reply = "before"; - string? tag = "OLD"; - string? description = "old description"; - int relationDelta = 4; - -#pragma warning disable CS0618 - ResponseJsonParser.TryParseResponseJson( - raw, - false, - ref reply, - ref tag, - ref description, - ref relationDelta); -#pragma warning restore CS0618 - - Assert.Equal("before", reply); - Assert.Equal("OLD", tag); - Assert.Equal("old description", description); - Assert.Equal(4, relationDelta); - } - [Fact] public void DialogueOverlayLayoutRemainsVisible() { diff --git a/Tests/Contracts/DialogueRequestLifecycleContracts.cs b/Tests/Contracts/DialogueRequestLifecycleContracts.cs index d3c8565..14f95e0 100644 --- a/Tests/Contracts/DialogueRequestLifecycleContracts.cs +++ b/Tests/Contracts/DialogueRequestLifecycleContracts.cs @@ -93,7 +93,11 @@ public void Player_and_automatic_entries_share_pawn_pair_and_global_capacity() Assert.Same(_recipient, RimMindDialogueService.GetActiveRecipient(_pawn)); RimMindDialogueService.HandleTrigger(_pawn, "same pawn", DialogueTriggerType.Thought, null); RimMindDialogueService.HandleTrigger(_recipient, "reversed pair", DialogueTriggerType.Chitchat, _pawn); - RimMindDialogueService.HandleTrigger(new Pawn { thingIDNumber = 3 }, "capacity", DialogueTriggerType.Auto, null); + RimMindDialogueService.HandleTrigger( + new Pawn { thingIDNumber = 3, IsColonist = true, Faction = Faction.OfPlayer, Map = _pawn.Map, Spawned = true }, + "capacity", + DialogueTriggerType.Auto, + null); Assert.Single(RimMindAPI.Sent); Complete(0, "reply"); Assert.Equal(0, RimMindDialogueService.ActiveRequestCount); @@ -117,7 +121,8 @@ public void Each_reservation_blocks_both_entry_directions(bool playerFirst, stri RimMindDialogueService.HandleTrigger(_pawn, "first", DialogueTriggerType.Chitchat, _recipient); Pawn nextPawn = conflict == "pawn" ? _pawn - : conflict == "pair" ? _recipient : new Pawn { thingIDNumber = 3 }; + : conflict == "pair" ? _recipient + : new Pawn { thingIDNumber = 3, IsColonist = true, Faction = Faction.OfPlayer, Map = _pawn.Map, Spawned = true }; Pawn? nextRecipient = conflict == "pair" ? _pawn : null; int errors = 0; if (playerFirst) @@ -164,6 +169,17 @@ public void Shared_builder_preserves_player_input_and_automatic_request_options( Assert.Equal(player ? 0.85f : 0.8f, envelope.Temperature); Assert.Contains(player ? "" : "", envelope.GameStateInfo!.ToString()); Assert.Contains(player ? "player input" : "RimMind.Dialogue.Prompt.AutoTrigger", envelope.GameStateInfo.ToString()); + Assert.True(envelope.RequireAliveColonist); + if (player) + { + Assert.Null(envelope.CoalesceKey); + Assert.Null(envelope.MaxQueueWaitTicks); + } + else + { + Assert.Equal("dialogue:1:Auto", envelope.CoalesceKey); + Assert.Equal(5000, envelope.MaxQueueWaitTicks); + } Assert.True(envelope.Ct.CanBeCanceled); } @@ -506,6 +522,30 @@ public async System.Threading.Tasks.Task Automatic_triggers_and_context_provider Assert.NotNull(speakerTask); Assert.Contains("GoalDialogue", speakerTask!, StringComparison.Ordinal); Assert.Contains("RelationDelta", speakerTask, StringComparison.Ordinal); + + var crisisCtx = new RimMind.Application.Common.Interfaces.Context.ProviderContext(RimMindAPI.Context.ScenarioCrisisDialogue, "t3") + { + PawnId = 1, + NpcId = "NPC-1", + Hints = new System.Collections.Generic.Dictionary { ["IsMonologue"] = "true" } + }; + string? crisisTask = await taskDef.Provider(crisisCtx, CancellationToken.None); + Assert.NotNull(crisisTask); + Assert.Contains("GoalMonologue", crisisTask!, StringComparison.Ordinal); + Assert.DoesNotContain("OutputMonologue", crisisTask, StringComparison.Ordinal); + } + + [Fact] + public void Window_closes_when_initiator_becomes_unavailable() + { + var window = new Window_Dialogue(_pawn, _recipient); + Assert.Same(_recipient, RimMindDialogueService.GetActiveRecipient(_pawn)); + + _recipient.Downed = true; + SendFromWindow(window, "should close instead of sending"); + + Assert.Empty(RimMindAPI.Sent); + Assert.Null(RimMindDialogueService.GetActiveRecipient(_pawn)); } private static void Complete(int index, string content) diff --git a/Tests/DialogueBoundaryStubs.cs b/Tests/DialogueBoundaryStubs.cs index b7e522b..5dc1e7e 100644 --- a/Tests/DialogueBoundaryStubs.cs +++ b/Tests/DialogueBoundaryStubs.cs @@ -128,6 +128,7 @@ public static System.Threading.Tasks.Task GetAsync( public static class Context { public static string ScenarioDialogue => RimMind.Application.Common.Models.Context.ScenarioIds.Dialogue; + public static string ScenarioCrisisDialogue => RimMind.Application.Common.Models.Context.ScenarioIds.CrisisDialogue; public static TestContextRegistry ContextKeys { get; } = new(); public static void RegisterScenario(ScenarioDescriptor descriptor) => ScenarioRegistry.Register(descriptor); @@ -344,9 +345,16 @@ public Rect(float x, float y, float width, float height) } public struct Color { - public Color(float r, float g, float b, float a = 1) { } - public static Color white => default; - public static Color gray => default; + public float r, g, b, a; + public Color(float r, float g, float b, float a = 1f) + { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } + public static Color white => new Color(1f, 1f, 1f, 1f); + public static Color gray => new Color(0.5f, 0.5f, 0.5f, 1f); } public class Texture2D { } public enum TextAnchor { MiddleCenter, UpperLeft } diff --git a/Tests/DialogueCadenceEvaluatorTests.cs b/Tests/DialogueCadenceEvaluatorTests.cs index 0bd858d..4b87819 100644 --- a/Tests/DialogueCadenceEvaluatorTests.cs +++ b/Tests/DialogueCadenceEvaluatorTests.cs @@ -151,6 +151,12 @@ public void Staggering_ForNewPairs_InitializesNonZeroDeterministicInitialTicks() evaluator.CalculateProbability(pairB, currentTick, DefaultCadenceDays, opinion: 0f); int initialTickB = evaluator.GetLastDialogueTick(pairB); Assert.NotEqual(initialTickA, initialTickB); + + // Extreme/negative pair IDs never overflow and stay bounded in [0, 0.75 * targetTicks) + var extremePair = (int.MinValue, 0); + evaluator.CalculateProbability(extremePair, currentTick, DefaultCadenceDays, opinion: 0f); + int extremeInitial = evaluator.GetLastDialogueTick(extremePair); + Assert.InRange(currentTick - extremeInitial, 0, (int)(DefaultTargetTicks * 0.75f) - 1); } [Fact] diff --git a/Tests/README.md b/Tests/README.md index e9afa7b..3995a44 100644 --- a/Tests/README.md +++ b/Tests/README.md @@ -5,14 +5,17 @@ Application are project references, including the real request-envelope builder. ## Active contract manifest -| Contract | Behavior | Discovered cases | -|---|---|---:| -| `Contracts/DialoguePipelineContracts.cs` | classification, pair keys, parser, bounded log snapshots, activity cooldown/quota, overlay geometry | 8 | -| `Contracts/DialogueThoughtInjectionContracts.cs` | thought tags, reply rate limit, quota policy, Thought save fields | 5 | -| `Contracts/DialogueGateErrorContracts.cs` | atomic Pawn/pair/capacity reservations, lifecycle fencing and ownership cleanup | 7 | -| `Contracts/DialogueRequestLifecycleContracts.cs` | real player/automatic entries, shared admission and envelopes, response effects, cancellation, failure and window/Gizmo lifecycle | 31 | - -Current discovery count: **51 cases**, including every Theory row (module budget: +| Contract | Behavior | +|---|---| +| `Contracts/DialoguePipelineContracts.cs` | classification, pair keys, trigger metadata registry, request trace summarizer, thought-tag sanitization, bounded log snapshots, activity cooldown/quota, overlay geometry | +| `Contracts/DialogueToolParserContracts.cs` | `express_dialogue` tool call arguments, OpenAI nested calls, pseudo-calls, and monologue clamping | +| `Contracts/DialogueThoughtInjectionContracts.cs` | thought tags, reply rate limit, quota policy, Thought save fields | +| `Contracts/DialogueGateErrorContracts.cs` | atomic Pawn/pair/capacity reservations, lifecycle fencing and ownership cleanup | +| `Contracts/DialogueRequestLifecycleContracts.cs` | real player/automatic entries, shared admission, coalescing/TTL, CrisisDialogue task provider, response effects, cancellation, failure and window/Gizmo lifecycle | +| `Contracts/DialogueVisualAndCoreAdoptionContracts.cs` | overlay shrink-wrap height, overhead speech mote positioning/CJK wrapping, dirty-only settings persistence | +| `DialogueCadenceEvaluatorTests.cs` & `DialogueAntiHallucinationAndMirroringTests.cs` | cadence grace/ramp/staggering, prompt constraints, and stage-direction anti-mirroring | + +Count actual discovered cases with the root test-budget script (module budget: strictly below 1000). Unrelated scenarios are independently discovered, not hidden inside a budget-reducing umbrella Fact. diff --git a/Tests/RimMindDialogue.Tests.csproj b/Tests/RimMindDialogue.Tests.csproj index 750d783..914b874 100644 --- a/Tests/RimMindDialogue.Tests.csproj +++ b/Tests/RimMindDialogue.Tests.csproj @@ -26,11 +26,12 @@ - + + diff --git a/script/deploy-single.ps1 b/script/deploy-single.ps1 index feab55c..7670990 100644 --- a/script/deploy-single.ps1 +++ b/script/deploy-single.ps1 @@ -1,22 +1,22 @@ -# Deploy this RimMind mod to RimWorld Mods folder. +# Deploy this RimMind mod to RimWorld Mods folder (Windows PowerShell). # Place at: RimMind-*/script/deploy-single.ps1 # # Usage: # .\script\deploy-single.ps1 # .\script\deploy-single.ps1 "D:\Games\RimWorld" -# $env:RIMWORLD_PATH="D:\Games\RimWorld"; .\script\deploy-single.ps1 +# $env:RIMWORLD_DIR="D:\Games\RimWorld"; .\script\deploy-single.ps1 param( - [string]$RimWorldDir = "" + [string]$RimWorldDir = "", + [string[]]$GameVersions = @("1.7", "1.6") ) $ErrorActionPreference = "Stop" $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path -$ModDir = Resolve-Path (Join-Path $ScriptDir "..") +$ModDir = (Resolve-Path (Join-Path $ScriptDir "..")).Path $ModName = Split-Path -Leaf $ModDir -# 自动检测常见 RimWorld 安装路径 function Detect-RimWorldPath { $paths = @( "C:\Program Files (x86)\Steam\steamapps\common\RimWorld", @@ -31,15 +31,16 @@ function Detect-RimWorldPath { return $null } -# 解析 RimWorld 路径 -if ($env:RIMWORLD_PATH) { +if ($RimWorldDir -eq "" -and $env:RIMWORLD_DIR) { + $RimWorldDir = $env:RIMWORLD_DIR +} elseif ($RimWorldDir -eq "" -and $env:RIMWORLD_PATH) { $RimWorldDir = $env:RIMWORLD_PATH } elseif ($RimWorldDir -eq "") { $RimWorldDir = Detect-RimWorldPath if (-not $RimWorldDir) { Write-Error "Cannot find RimWorld installation" Write-Host " Usage: .\script\deploy-single.ps1 [RimWorldPath]" -ForegroundColor Yellow - Write-Host " Or: `$env:RIMWORLD_PATH='D:\Games\RimWorld'; .\script\deploy-single.ps1" -ForegroundColor Yellow + Write-Host " Or: `$env:RIMWORLD_DIR='D:\Games\RimWorld'; .\script\deploy-single.ps1" -ForegroundColor Yellow exit 1 } } @@ -50,56 +51,88 @@ if (-not (Test-Path $RimWorldDir)) { } $RimWorldMods = Join-Path $RimWorldDir "Mods" - -# 确保 Mods 目录存在 if (-not (Test-Path $RimWorldMods)) { Write-Error "Mods directory not found at $RimWorldMods" exit 1 } -# 构建 -$CSPROJ = Get-ChildItem -Path (Join-Path $ModDir "Source") -Filter "*.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 -if ($CSPROJ) { - Write-Host "=== Building $ModName ===" -ForegroundColor Cyan - dotnet build $CSPROJ.FullName -c Release --nologo -v quiet - if ($LASTEXITCODE -ne 0) { - Write-Error "Build failed" - exit $LASTEXITCODE +# Build for all target game versions (1.7 & 1.6) +$SourceDir = Join-Path $ModDir "Source" + +foreach ($gameVersion in $GameVersions) { + Write-Host "=== Building $ModName (RimWorld $gameVersion) ===" -ForegroundColor Cyan + + if ($ModName -eq "RimMind-Core") { + $domainCsproj = Join-Path $SourceDir "Domain\RimMindCore.Domain.csproj" + $applicationCsproj = Join-Path $SourceDir "Application\RimMindCore.Application.csproj" + $coreCsproj = Get-ChildItem -Path $SourceDir -Filter "RimMindCore.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 + + if (-not (Test-Path $domainCsproj)) { + Write-Error "Domain csproj not found: $domainCsproj" + exit 1 + } + if (-not (Test-Path $applicationCsproj)) { + Write-Error "Application csproj not found: $applicationCsproj" + exit 1 + } + if (-not $coreCsproj) { + Write-Error "Core csproj not found in $SourceDir" + exit 1 + } + + dotnet build $domainCsproj -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { Write-Error "Domain build failed ($gameVersion)"; exit $LASTEXITCODE } + + dotnet build $applicationCsproj -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { Write-Error "Application build failed ($gameVersion)"; exit $LASTEXITCODE } + + dotnet build $coreCsproj.FullName -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { Write-Error "Core build failed ($gameVersion)"; exit $LASTEXITCODE } + } else { + $csproj = Get-ChildItem -Path $SourceDir -Filter "*.csproj" -File -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($csproj) { + dotnet build $csproj.FullName -c Release -p:GameVersion=$gameVersion -p:SkipDeployToModsFolder=true --nologo -v quiet + if ($LASTEXITCODE -ne 0) { + Write-Error "Build failed ($gameVersion)" + exit $LASTEXITCODE + } + } else { + Write-Host "No .csproj found in Source\, skipping build" -ForegroundColor Yellow + } } - Write-Host " Build successful" -} else { - Write-Host "No .csproj found in Source\, skipping build" -ForegroundColor Yellow } -# 部署 +# Deploy with clean runtime exclusions (never copy Core/Newtonsoft DLLs into non-Core mods) $DestDir = Join-Path $RimWorldMods $ModName Write-Host "=== Deploying $ModName -> $DestDir ===" -ForegroundColor Cyan -$ExcludeDirs = @('Source', 'Tests', 'obj', '.git', 'script') -$ExcludeFiles = @('*.csproj', '*.user', '.gitignore') -$SourceItems = Get-ChildItem -Path $ModDir | Where-Object { - $item = $_ - if ($item.PSIsContainer -and $ExcludeDirs -contains $item.Name) { return $false } - if (-not $item.PSIsContainer) { - foreach ($pattern in $ExcludeFiles) { - if ($item.Name -like $pattern) { return $false } - } - } - return $true +$excludeFiles = @( + "*.csproj", "*.user", ".gitignore", ".git", ".gitattributes", + ".coderabbit.yaml", ".pre-commit-config.yaml", + "AGENTS.md", "CLAUDE.md", "Directory.Build.props", "Directory.Build.targets", + "INTRODUCTION.txt", "*.deps.json" +) +if ($ModName -ne "RimMind-Core") { + $excludeFiles += @( + "0_RimMindDomain.*", "1_RimMindApplication.*", "2_RimMindCore.*", "Newtonsoft.Json.*" + ) } -if (Test-Path $DestDir) { - Get-ChildItem -Path $DestDir | Remove-Item -Recurse -Force +robocopy $ModDir $DestDir /MIR /XD Source Tests ArchTests IntegrationTests TestSupport obj bin .git .github .claude docs script /XF $excludeFiles /NFL /NDL /NJH /NJS /NP +if ($LASTEXITCODE -ge 8) { + Write-Error "Deployment failed (robocopy exit $LASTEXITCODE)" + exit $LASTEXITCODE } -foreach ($item in $SourceItems) { - Copy-Item -Path $item.FullName -Destination $DestDir -Recurse -Force +if ($ModName -ne "RimMind-Core") { + foreach ($ver in $GameVersions) { + $deployedAssemblies = Join-Path $DestDir "$ver\Assemblies" + if (Test-Path $deployedAssemblies) { + foreach ($pattern in @("0_RimMindDomain.*", "1_RimMindApplication.*", "2_RimMindCore.*", "Newtonsoft.Json.*")) { + Get-ChildItem -Path $deployedAssemblies -Filter $pattern -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue + } + } + } } -# 验证部署 -if (Test-Path $DestDir) { - Write-Host " Done: $DestDir" -ForegroundColor Green -} else { - Write-Error "Deployment verification failed" - exit 1 -} +Write-Host " Done: $DestDir" -ForegroundColor Green diff --git a/script/deploy-single.sh b/script/deploy-single.sh deleted file mode 100644 index 7dc5165..0000000 --- a/script/deploy-single.sh +++ /dev/null @@ -1,95 +0,0 @@ -#!/bin/bash -# Deploy this RimMind mod to RimWorld Mods folder. -# Place at: RimMind-*/script/deploy-single.sh -# -# Usage: -# ./script/deploy-single.sh # use default path -# ./script/deploy-single.sh /path/to/RimWorld # custom path -# RIMWORLD_PATH=/path/to/RimWorld ./script/deploy-single.sh # env var override - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -MOD_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" -MOD_NAME="$(basename "$MOD_DIR")" - -# 自动检测常见 RimWorld 安装路径 -detect_rimworld_path() { - local paths=( - "/mnt/c/Program Files (x86)/Steam/steamapps/common/RimWorld" - "/mnt/c/Program Files/Steam/steamapps/common/RimWorld" - "$HOME/.steam/steam/steamapps/common/RimWorld" - "$HOME/.local/share/Steam/steamapps/common/RimWorld" - ) - for path in "${paths[@]}"; do - if [[ -d $path ]]; then - echo "$path" - return 0 - fi - done - return 1 -} - -# 解析 RimWorld 路径 -if [[ -n ${RIMWORLD_PATH:-} ]]; then - RIMWORLD_PATH="$RIMWORLD_PATH" -elif [[ $# -gt 0 ]]; then - RIMWORLD_PATH="$1" -else - RIMWORLD_PATH=$(detect_rimworld_path) || { - echo "Error: Cannot find RimWorld installation" - echo " Usage: $0 [/path/to/RimWorld]" - echo " Or: export RIMWORLD_PATH=/path/to/RimWorld && $0" - exit 1 - } -fi - -RIMWORLD_MODS="$RIMWORLD_PATH/Mods" - -if [[ ! -d $RIMWORLD_PATH ]]; then - echo "Error: RimWorld not found at $RIMWORLD_PATH" - exit 1 -fi - -# 确保 Mods 目录存在 -if [[ ! -d $RIMWORLD_MODS ]]; then - echo "Error: Mods directory not found at $RIMWORLD_MODS" - exit 1 -fi - -# 构建 -CSPROJ=$(find "$MOD_DIR/Source" -maxdepth 1 -name "*.csproj" 2>/dev/null | head -1) -if [[ -n $CSPROJ ]]; then - echo "=== Building $MOD_NAME ===" - if ! dotnet build "$CSPROJ" -c Release --nologo -v quiet; then - echo "Error: Build failed" - exit 1 - fi - echo " Build successful" -else - echo "No .csproj found in Source/, skipping build" -fi - -# 部署 -echo "=== Deploying $MOD_NAME -> $RIMWORLD_MODS/$MOD_NAME ===" -if ! rsync -a --delete \ - --exclude='Source/' \ - --exclude='Tests/' \ - --exclude='*.csproj' \ - --exclude='*.user' \ - --exclude='obj/' \ - --exclude='.git/' \ - --exclude='.gitignore' \ - --exclude='script/' \ - "$MOD_DIR/" "$RIMWORLD_MODS/$MOD_NAME/"; then - echo "Error: Deployment failed" - exit 1 -fi - -# 验证部署 -if [[ -d "$RIMWORLD_MODS/$MOD_NAME" ]]; then - echo " Done: $RIMWORLD_MODS/$MOD_NAME" -else - echo "Error: Deployment verification failed" - exit 1 -fi