# Custom NPC Framework — Full Bilingual Technical Documentation (llms-full.txt) ================================================================================ ## index.md ================================================================================ --- layout: doc title: Custom NPC Framework --- # Custom NPC Framework 本文档涵盖《深空当铺:可能是偷的》(Probably Stolen,Steam AppID `4348910`)自定义顾客与跨日剧情框架(**Custom NPC Framework**)及其两个完整示例项目(**RestoredUnusedNPCs**、**CyberpunkMercV**)的架构说明、完整 API 参考、顾客塑造子系统详解与源码级拆解。 ![Custom NPC Framework](/images/zh/preview_framework.png) --- ## 针对 AI Agent 的一键引导提示词 如果你使用 AI 编程助手(如 Claude Code、Cursor、Windsurf、Cline、OpenChamber 等)来设计、编写、编译或打包一个新的《深空当铺:可能是偷的》自定义 NPC 模组,只需将以下提示词直接复制发送给你的 AI Agent: ::: tip 复制以下提示词发送给你的 AI Agent ```markdown 请先阅读以下两份《深空当铺:可能是偷的》(Probably Stolen) 的模组开发技术文档: 1. 官方模组开发基础指南(工程结构、manifest.xml 必填标签 与 、IMod 入口、ModLog、自定义物品/音效/本地化资源加载、ModHook 钩子与 ModScanner 安全扫描规则): - 快速入门:https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/README.zh-CN.md - 进阶制作指南:https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/ModdingGuide.zh-CN.md - API 变更记录:https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/APIChanges.zh-CN.md 2. Custom NPC Framework 完整开发规范(含 AI Agent 六步引导工作流、NpcFrameworkSdk.cs 完整源码、18 个顾客塑造子系统、原版物品/标签/立绘池字典及两个完整示例项目源码拆解): - 工作流指南:https://customnpc.netlify.app/guide/agent-workflow - 单文件全量规范:https://customnpc.netlify.app/llms-full.txt 阅读完毕后,请不要直接盲目写代码,而是按照文档中的【AI Agent 六步交互式需求采集清单】向我提问,一步步引导我确定: 1. 模组基础元数据(Mod ID、显示名称、作者)以及是否需要配套新增自定义物品(GameItem)、自定义音效或掉落表; 2. 新 NPC 的身份设定、所属阵营(clientFaction)与立绘来源(选用原版 SpriteDict 70+ 立绘池方法,还是放入 Textures/ 的 288x211 自定义像素贴图); 3. 生成阶段(spawnPhase)、触发天数窗口、冷却天数与出现概率; 4. 核心交易模式(常规买家 BUY、常规卖家 SELL、整包批发 Wholesale、以物易物 BarterOffer、定金采购委托 Procurement、或定制改枪订单 GunOrder); 5. 跨日多幕剧情线(cnpcf_ 存档状态机)与分支结局设计; 6. 世界联动特性(全息电话簿 7 位号码、实体手写便条、店铺终端悬赏委托 StoreRequest、次日早报头条 TriggerNews、盘问/透视眼镜扫描对话、通缉抓捕演出、夜间地点事件)。 确认方案后,为我生成完整的 C# 工程源码(含零引用 NpcFrameworkSdk.cs)、manifest.xml、Steam 创意工坊 .vdf/.bat 上传脚本并完成编译打包。 ``` ::: ### 机器可读索引端点 - **轻量目录索引**:[`https://customnpc.netlify.app/llms.txt`](/llms.txt) - **单文件全量规范**:[`https://customnpc.netlify.app/llms-full.txt`](/llms-full.txt) --- ## 三大项目核心矩阵 | 模组名称 | 核心源文件 | 代码规模 | 核心功能覆盖范围 | | :--- | :--- | :--- | :--- | | **`CustomNPCFramework`** | `CustomNPCFrameworkMod.cs`
`NpcFrameworkRegistry.cs`
`NpcSaveStore.cs`
`NpcPhoneRegistry.cs`
`NpcFullFeatureKit.cs`
`NpcTraitModels.cs` | ~1,820 行 | • `AppDomain` 双缓冲挂起队列 + 实时委托桥接表
• 每日五阶段顾客生成调度器(`VeryEarly`..`VeryLate`)
• 7 步筛选判定链(天数窗口/冷却/唯一性/逮捕名单/概率倍率)
• 开发者调试优先召唤与双阶段 `clientStack[0]` 强制置顶
• `cnpcf_` 命名空间隔离的跨日存档 KV 状态机
• 自动挂载 `Textures/*.png` 至 `SpriteDict`(`Point` 采样 + `100 PPU`)
• 顾客塑造子系统完整封装(便条/委托板/期货/改枪/早报/垃圾场/电话簿) | | **`RestoredUnusedNPCs`** | `RestoredUnusedNPCsMod.cs`
`NpcFrameworkSdk.cs` | ~850 行 | • 完整还原原版代码中未实装的 **11 位官方废案顾客**
• **比利(Billy)四幕跨日连续剧**(乞讨食物 `BarterOffer` → 新晋保安买装备 → 医疗舱监守自盗批发销赃 → 内务调查官盘查举报/掩护双结局)
• **7 位特殊机制散客**(灰潮拾荒客、猩红血袋教徒、革命军宣讲员、戒断成瘾者天平实时反馈、下层区制毒师、黑市军火贩、武装民兵)
• 智能阶段路由 `billy` 与 `OnDismiss` 阶段同步保护 | | **`CyberpunkMercV`** | `CyberpunkMercVMod.cs`
`NpcFrameworkSdk.cs` | ~850 行 | • **《赛博朋克 2077》传奇佣兵 V 五阶段叙事状态机**(`v_stage 0..5`)
• 第 1 幕 Relic 芯片 68% 覆写求购抑制剂 + 强尼·银手透视目镜彩蛋
• 第 2 幕荒坂/帕斯泰尔押运车劫案备战军火采购
• 第 3 幕金库大劫案归来整包 7 折销赃 + 自定义逮捕演出
• 第 4 幕企业特勤追缉官盘查(掩护解锁四联奖励闭环 / 出卖领赏结局)
• **四联奖励闭环**:解锁 `2077077` 全息专线 + 投递《V 的加密便条》+ 激活 450 信用点委托板悬赏 + 触发次日早报头条
• **三帧 Relic 动态视觉故障**:`v_normal` / `v_glitch` / `v_glitch2` 错位扫描线切片与全息青红闪烁 | --- ## 全站六大子目录文档导航 ### 1. 入门与 AI Agent 引导 (`/guide/`) - **[AI Agent 交互式模组开发工作流](/guide/agent-workflow)** - **[从零创建第一个自定义 NPC 模组](/guide/quick-start)** - **[像素立绘尺寸与描边规范](/guide/sprite-art-pipeline)** ### 2. 核心架构 (`/architecture/`) - **[零引用 AppDomain 桥接与生命周期](/architecture/bridge-and-lifecycle)** - **[五阶段生成管线与调试强制置顶](/architecture/generation-pipeline)** - **[跨日存档状态机与 ModConfig 设置](/architecture/save-and-config)** - **[动态贴图注入与立绘回退机制](/architecture/glitch-and-textures)** ### 3. 顾客塑造子系统 (`/subsystems/`,共 18 篇独立专章) 1. **[01. 常规买家与求购清单 (BUY)](/subsystems/01-regular-buying)** 2. **[02. 常规卖家与单品兜售 (SELL)](/subsystems/02-regular-selling)** 3. **[03. 整包一口价批发 (Wholesale)](/subsystems/03-wholesale-lots)** 4. **[04. 以物易物与乞讨施舍 (BarterOffer)](/subsystems/04-barter-and-begging)** 5. **[05. 议价宽容度、耐心与香水影响](/subsystems/05-bargaining-and-patience)** 6. **[06. 违禁品、零售高价签与水质警告](/subsystems/06-contraband-and-labels)** 7. **[07. 九项物品瑕疵验货规则 (Checks)](/subsystems/07-inspection-checks)** 8. **[08. 假货识破能力与化学纯度门槛](/subsystems/08-expose-and-chem-grade)** 9. **[09. 电子秤、柜台与展示柜实时回调](/subsystems/09-realtime-scale-and-counter)** 10. **[10. 跨日期货预定委托单 (Procurement)](/subsystems/10-procurement-contracts)** 11. **[11. 定制枪械改装委托单 (GunOrder)](/subsystems/11-custom-gun-orders)** 12. **[12. 实体手写便条与打印文档投递](/subsystems/12-handnotes-and-papers)** 13. **[13. 店铺终端委托板悬赏 (StoreRequest)](/subsystems/13-store-request-board)** 14. **[14. 全息电话簿联系人与拨号召唤](/subsystems/14-holophone-contacts)** 15. **[15. 盘问对话、透视目镜扫描与特殊气泡](/subsystems/15-interrogation-and-optics)** 16. **[16. 通缉悬赏、治安官逮捕与盘查事件](/subsystems/16-wanted-arrest-and-security)** 17. **[17. 次日早报头条新闻 (TriggerNews)](/subsystems/17-newspaper-headlines)** 18. **[18. 夜间垃圾场事件与入睡结算钩子](/subsystems/18-afterhour-and-nightly-hooks)** ### 4. API 参考手册 (`/api/`) - **[NpcFrameworkSdk 全量方法参考](/api/sdk-reference)** - **[ApplyClientProfile 46 项属性字典表](/api/profile-dictionary)** - **[原版 StoreClient 与 Dialogue 核心类速查](/api/vanilla-classes)** ### 5. 示例项目拆解 (`/examples/`) - **[RestoredUnusedNPCs:比利四幕连续剧](/examples/restored-overview)** - **[RestoredUnusedNPCs:7 位特殊机制散客](/examples/restored-special-npcs)** - **[CyberpunkMercV:五阶段主线与状态机](/examples/cyberpunk-v-storyline)** - **[CyberpunkMercV:四联奖励与 Relic Glitch](/examples/cyberpunk-v-rewards-glitch)** ### 6. 原版数据字典 (`/reference/`) - **[阵营、物品标签、常用物品 ID 与立绘池](/reference/vanilla-dictionaries)** ================================================================================ ## guide/agent-workflow.md ================================================================================ --- layout: doc title: AI Agent 交互式模组开发工作流 --- # AI Agent 交互式模组开发工作流 本文档为 **AI Coding Agent(如 Claude Code、Cursor、Windsurf、Cline、OpenChamber 等)** 与模组开发者提供从零构建《深空当铺:可能是偷的》(Probably Stolen)自定义 NPC 模组的完整标准作业程序(SOP)。 要完整制作一个可被游戏加载、通过安全扫描器校验并正常运行的模组,AI Agent 需要同时掌握两部分知识: 1. **官方基础模组开发规范**:来自官方仓库 [`dragonpan2/probably-stolen-modding`](https://github.com/dragonpan2/probably-stolen-modding/)(含 [`README.zh-CN.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/README.zh-CN.md)、[`ModdingGuide.zh-CN.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/ModdingGuide.zh-CN.md) 与 [`APIChanges.zh-CN.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/APIChanges.zh-CN.md)),定义了工程结构、`manifest.xml` 必填字段、`IMod` 生命周期、`ModLog`、模组资源目录(贴图/物品精灵图/音效/本地化/掉落表/纸质手册)、`ModHook` 钩子点、`ModScanner` 能力扫描规则及 Steam 创意工坊发布流程。 2. **Custom NPC Framework 框架接口规范**:来自本站文档(及单文件全量上下文 [`/llms-full.txt`](/llms-full.txt)),定义了零引用 `NpcFrameworkSdk.cs` 接入、五阶段顾客生成调度、跨日存档状态机(`cnpcf_`)、`288×211` 顾客立绘注入以及全部 18 个顾客塑造子系统。 --- ## 1. 可直接复制给 AI Agent 的完整启动提示词 将以下提示词复制发送给你的 AI 助手,即可让 Agent 自动拉取官方模组制作指南与本框架规范,并一步步引导你完成整个模组的设计、编码、编译与打包: ### 提示词模板 A:从零交互式引导制作完整 NPC 模组(推荐) ```markdown 请先阅读以下两份《深空当铺:可能是偷的》(Probably Stolen) 的模组开发技术文档: 1. 官方模组开发基础指南(工程结构、manifest.xml 必填标签 与 、IMod 入口、ModLog、自定义物品/音效/本地化资源加载、ModHook 钩子与 ModScanner 安全扫描规则): - 快速入门:https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/README.zh-CN.md - 进阶制作指南:https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/ModdingGuide.zh-CN.md - API 变更记录:https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/APIChanges.zh-CN.md 2. Custom NPC Framework 完整开发规范(含 AI Agent 六步引导工作流、NpcFrameworkSdk.cs 完整源码、18 个顾客塑造子系统、原版物品/标签/立绘池字典及两个完整示例项目源码拆解): - 工作流指南:https://customnpc.netlify.app/guide/agent-workflow - 单文件全量规范:https://customnpc.netlify.app/llms-full.txt 阅读完毕后,请不要直接盲目写代码,而是按照【AI Agent 六步交互式需求采集清单】向我提问,一步步引导我确定: 1. 模组基础元数据(Mod ID、显示名称、作者)以及是否需要配套新增自定义物品(GameItem)、自定义音效或掉落表; 2. 新 NPC 的身份设定、所属阵营(clientFaction)与立绘来源(选用原版 SpriteDict 70+ 立绘池方法,还是放入 Textures/ 的 288x211 自定义像素贴图); 3. 生成阶段(spawnPhase)、触发天数窗口、冷却天数与出现概率; 4. 核心交易模式(常规买家 BUY、常规卖家 SELL、整包批发 Wholesale、以物易物 BarterOffer、定金采购委托 Procurement、或定制改枪订单 GunOrder); 5. 跨日多幕剧情线(cnpcf_ 存档状态机)与分支结局设计; 6. 世界联动特性(全息电话簿 7 位号码、实体手写便条、店铺终端悬赏委托 StoreRequest、次日早报头条 TriggerNews、盘问/透视眼镜扫描对话、通缉抓捕演出、夜间地点事件)。 等我确认方案后,请严格按照官方 manifest.xml 规范与零权限扫描准则,为我生成完整的 Modding/ 源码工程(含 .csproj、manifest.xml、NpcFrameworkSdk.cs、IMod 实现类)与 Mods/ 部署目录及 Steam 创意工坊上传脚本。 ``` ### 提示词模板 B:基于现有设定快速生成多幕剧情 NPC 模组 ```markdown 请先读取官方模组指南 https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/ModdingGuide.zh-CN.md 与 Custom NPC Framework 全量规范 https://customnpc.netlify.app/llms-full.txt 。 我想为《深空当铺:可能是偷的》制作一个名为【角色名】的多幕剧情 NPC 模组。请先向我确认每一幕的交易意图、关键物品(使用原版物品 ID 还是注册新物品)、对话分支与结局奖励,确认后输出可直接通过 dotnet build 编译且通过 mod-scan 零权限校验的完整工程文件。 ``` --- ## 2. 官方模组基础规范速查(源自 `dragonpan2/probably-stolen-modding`) AI Agent 在生成任何模组文件前,必须严格遵守官方仓库定义的以下工程与加载规范: ### 2.1 标准目录结构 游戏根目录(`Probably Stolen.exe` 所在目录)下分为两个文件夹:`Modding/` 存放开发源码工程,`Mods/` 存放游戏实际加载的模组文件夹: ```text Probably Stolen/ ├── Probably Stolen.exe ├── dev.txt # 可选空文件:创建后可在游戏内按 F8 打开调试控制台、按 F9 打开开发菜单 ├── Mods/ │ └── MyCustomNPCPack/ │ ├── manifest.xml # 必填:模组清单(根节点必须为 ) │ ├── MyCustomNPCPack.dll # 必填:编译生成的程序集(需在 中列出) │ ├── preview.png # 可选:模组菜单与创意工坊预览图(建议小于 1 MB) │ ├── Textures/ │ │ ├── my_npc.png # 通用贴图(288x211 顾客立绘直接放此目录,由框架自动注入 SpriteDict) │ │ ├── Items/ │ │ │ └── custom_item.png # 自定义物品精灵图(必须直接放在 Textures/Items/ 下) │ │ └── Paper/ │ │ └── page_bg.png # 纸质手册贴图(必须直接放在 Textures/Paper/ 下) │ ├── Sounds/ │ │ └── custom_sfx.wav # 自定义音效(自动注册为 ":custom_sfx") │ └── Localization/ │ ├── zh.csv # 简体中文本地化表(UTF-8 无表头:key,文本) │ └── en.csv # 英文本地化表 └── Modding/ └── MyCustomNPCPack/ ├── MyCustomNPCPack.csproj ├── manifest.xml ├── NpcFrameworkSdk.cs # 零引用桥接 SDK 单文件(直接复制到项目中) └── MyCustomNPCPackMod.cs # 实现 IMod 接口的主入口类 ``` > **注意**:`ModLoader` 对资源子文件夹(`Textures/`、`Textures/Items/`、`Textures/Paper/`、`Sounds/`、`Localization/`、`LootTables/`、`Books/`)的扫描**不是递归的**,文件必须直接放在对应子目录下,嵌套子文件夹会被忽略。 ### 2.2 `manifest.xml` 必填结构与校验规则 `manifest.xml` 的根节点必须是 **``**,且必须包含 **``** 与 **``** 节点(缺少任何一个都会导致模组无法在菜单中显示或拒绝启用): ```xml my_custom_npc_pack 我的自定义NPC扩展包 / My Custom NPC Pack YourName 1.0.0 基于 Custom NPC Framework 构建的自定义顾客与跨日剧情扩展包。 0.46 CustomNPCFramework MyCustomNPCPack.dll ``` - **``**:只能包含 ASCII 字母、数字、`_`、` - ` 和 `.`(不能以 `.` 开头,最长 64 字符)。 - **``**:依赖其他模组时,子元素名必须写 **`CustomNPCFramework`**。 - **``**:必须列出模组文件夹内所有要加载的 `.dll`;文件夹中若存在未列出的 `.dll` 或与游戏同名的程序集(如 `0Harmony.dll`、`Assembly-CSharp.dll`),会导致启用被直接拒绝。 - **``**:基于 `CustomNPCFramework` 开发的模组**不需要任何额外系统能力**,请始终保持为空标签 ``。 ### 2.3 `.csproj` 工程文件规范 模组目标框架必须为 **`netstandard2.1`**,且引用的游戏 DLL 必须设置 **`false`**(防止编译时把游戏本体 DLL 复制到 `Mods//` 导致启用被拒): ```xml netstandard2.1 MyCustomNPCPack MyCustomNPCPack latest false false $(MSBuildProjectDirectory)/../../Probably Stolen_Data/Managed $(ManagedDir)/Assembly-CSharp.dll false $(ManagedDir)/UnityEngine.dll false $(ManagedDir)/UnityEngine.CoreModule.dll false $(ManagedDir)/0Harmony.dll false ``` ### 2.4 如果新 NPC 需要配套的“自定义专属物品”或“自定义音效” 如果用户希望新 NPC 向玩家出售或求购一件**原版没有的全新自定义物品**,AI Agent 应结合官方 `ModdingGuide` 的物品注册钩子 `ModHook.OnModItemDirectoryInit`: 1. 将物品图标 PNG(按库存网格尺寸绘制,如 1×1 格为 `64×64`)放入 `Mods//Textures/Items/.png`; 2. 在 `OnEnable()` 中订阅 `ModHook.OnModItemDirectoryInit += RegisterItems;`(并在 `OnDisable()` 中解绑); 3. 在 `RegisterItems()` 中使用 `ItemDirectory.CreateEmptyItem("")` 创建物品,并调用 `item.SetSpriteAndShapeFromMod("", "")` 自动绑定精灵图并根据非透明像素生成库存网格形状; 4. 之后即可在顾客的 `clientBuyingIdList.Add("")` 或 `PlayerStore.Instance.AddDirectSellingItemToTable("", ...)` 中直接使用该自定义物品 ID! --- ## 3. AI Agent 六步交互式需求采集清单(Decision Tree) 当收到用户的制作模组请求时,AI Agent 应按以下 6 个步骤向用户发起简明扼要的编号提问(每项提供推荐默认值): ### 第一步:模组基础元数据与自定义资源需求 1. **模组 ``、中英名称与作者名**:如 `ID = "trauma_team_pack"`。 2. **是否需要新增自定义物品或音效**:仅使用原版内置物品 ID(见 [原版数据字典](/reference/vanilla-dictionaries)),还是需要通过 `ModHook.OnModItemDirectoryInit` 注册新物品与 `Textures/Items/` 图标? ### 第二步:角色身份、所属阵营与立绘方案 1. **NPC 唯一 `identifier` 与中英显示名**:如 `id = "trauma_medic"`,中文 `"创伤小组急救员"`,英文 `"Trauma Team Medic"`。 2. **所属阵营(`clientFaction`)**:从 8 大原版阵营中选择(`FACTION_LOWER_LEVEL`、`FACTION_BLACK_MARKET`、`FACTION_SECURITY`、`FACTION_REVOLUTION`、`FACTION_UPPER_LEVEL`、`FACTION_TOURIST`、`FACTION_CHURCH`、`FACTION_CARTEL`)。 3. **立绘方案(`spriteName`)**: - **方案 A**:调用原版 `SpriteDict` 70+ 个内置立绘池方法(如 `SpriteDict.GetRandomMedSpriteName()`); - **方案 B**:提供 `288×211` 自定义 PNG 放入 `Mods//Textures/.png`(遵循 `y = 55..210` 高度 `156px`、顶部留白 `55px`、外轮廓 `RGB(36, 33, 43)` 规范,详见 [像素立绘尺寸与描边规范](/guide/sprite-art-pipeline))。 ### 第三步:生成调度参数(Spawn Scheduling) 1. **生成阶段(`spawnPhase`)**:固定/主线剧情推荐 `1`(`Early`,优先级 `80~95`);日常循环散客推荐 `2`(`Normal`,优先级 `35~60`)。 2. **天数窗口、冷却与概率**:`minDay`(默认 `2`)、`maxDay`(默认 `9999`)、`cooldownDays`(推荐 `2~4`)、`spawnChancePercent`(剧情 `75~100`,散客 `25~40`)。 ### 第四步:核心交易与交互意图(`ClientIntent`) 从以下交易子系统中选择每一幕的交互模式(详见 [顾客塑造子系统 01–18](/subsystems/01-regular-buying)): 1. **常规买家(`ClientIntent.BUY`)**:设置 `SetBudget`、`buyPriceModifier`、`clientBuyingTagList` / `clientBuyingIdList` 与 `sc.AddCheck("CHECK_*")`; 2. **常规卖家 / 整包一口价批发(`ClientIntent.SELL` + `isOfferWholesale`)**:设置 `wholesaleDiscount` 并在 `mainDialogue` 末尾通过 `AddDirectSellingItemToTable` 铺货; 3. **以物易物(`ClientIntent.BARTER` + `BarterOffer`)**; 4. **定金采购委托单(`AttachProcurementOffer`)** 或 **定制枪械改装订单(`BuildCustomGunOrder`)**; 5. **纯对话 / 治安官盘查事件(`ClientIntent.DIALOGUE` + `CompleteSecClient`)**。 ### 第五步:跨日剧情状态机设计 1. 定义存档状态键(如 `NpcFrameworkSdk.GetSaveInt("my_npc_stage", 0)`),并注册置顶智能路由入口(`minDay = 9999, spawnChancePercent = 0`)按当前阶段分发工厂函数; 2. 阶段推进 `SetSaveInt` 统一写在 `acceptDealDialogue`、`allDoneDialogue` 或明确的对话选项回调中。 ### 第六步:世界联动子系统配置 确认是否启用: - **盘问对话(`interogationDialogue`)** 与 **透视眼镜观察对话(`glasseDialogue`)**; - **电子秤/柜台实时放物回调(`onItemAddedToWeighted`)**; - **通缉悬赏与自定义逮捕演出(`SetWanted` + `customOnArrestDialogue`)**; - **全息电话簿联系人(`RegisterPhoneContact`)**、**实体手写便条(`GiveHandnoteToPlayer`)**、**店铺终端悬赏委托(`PostStoreRequest`)**、**次日早报头条(`TriggerNews`)** 或 **夜间地点事件(`RegisterAfterhourEvent`)**。 --- ## 4. 代码生成与安全扫描自查清单(Pre-Publish Checklist) AI Agent 输出最终代码与工程文件时,必须逐条核对以下 6 项准则: 1. **`Init` / `OnEnable` 阶段严禁直接访问存档或店内管理器**:`Init` 与 `OnEnable` 在主菜单启动时就会运行,此时 `PlayerStore.Instance` 与 `StoreStation.Instance` 均尚未实例化。所有 `StoreClient` 构造与存档读写必须在顾客生成回调(`clientFactory`)或 `OnGameLoadedInit` / `OnShutterOpenedLate` 之后执行。 2. **`StoreClient` 构造收尾必须调用 `sc.CompleteClientCreation(false)`**:若为治安官盘查事件(`ClientIntent.DIALOGUE`),还需紧接着调用 `sc.CompleteSecClient()`。 3. **对话选项占位物品参数固定传 `DirectoryMaster.Item("$", true)`**,非交易类对话分支结束时调用 `DialogUIManager.Instance?.CurrentClientLeave(1f)` 让顾客离场。 4. **仅敌对伪装怪物才设 `sc.isAug = true`**:普通人类或赛博朋克义体角色保持 `sc.isAug = false`。 5. **零未声明能力(`mod-scan` 合规)**:不在代码中直接调用 `System.IO.File`、`System.Diagnostics.Process`、`System.Net.Http` 或外部私有反射,保持 `manifest.xml` 中的 `` 为空。 6. **日志统一使用 `ModLog`**:在 `Init(ModManifest manifest)` 中构造 `new ModLog(manifest)` 并复用,方便在 F8 控制台中按模组名前缀排查日志。 ================================================================================ ## guide/quick-start.md ================================================================================ --- layout: doc title: 从零创建第一个自定义 NPC 模组 --- # 从零创建第一个自定义 NPC 模组 本节基于官方仓库 [`dragonpan2/probably-stolen-modding`](https://github.com/dragonpan2/probably-stolen-modding/) 的基础模组规范(参见 [`README.zh-CN.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/README.zh-CN.md) 与 [`ModdingGuide.zh-CN.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/ModdingGuide.zh-CN.md)),带你从零搭建一个符合 `ModScanner` 零权限要求、支持中英双语的《深空当铺:可能是偷的》自定义 NPC 模组工程。 --- ## 1. 标准工程文件结构 在游戏安装根目录(`Probably Stolen.exe` 所在目录)下,`Modding/` 用于存放源码工程,`Mods/` 用于存放游戏实际加载的模组文件: ```text Probably Stolen/ ├── Probably Stolen.exe ├── dev.txt # 可选空文件:开启 F8 调试控制台与 F9 开发菜单 ├── Mods/ │ ├── MyCustomNPCPack/ │ │ ├── MyCustomNPCPack.dll # 编译输出程序集 │ │ ├── manifest.xml # 必填:模组清单文件 │ │ ├── preview.png # 可选:模组菜单与创意工坊预览图 (< 1MB) │ │ └── Textures/ # 可选:自定义顾客立绘贴图 (288x211 PNG) │ │ └── my_npc.png │ ├── MyCustomNPCPack.vdf # SteamCMD 创意工坊上传配置 │ └── MyCustomNPCPack.bat # SteamCMD 一键上传脚本 └── Modding/ └── MyCustomNPCPack/ ├── MyCustomNPCPack.csproj # C# 工程文件 (netstandard2.1) ├── NpcFrameworkSdk.cs # 零引用桥接 SDK 单文件(直接复制即可) ├── MyCustomNPCPackMod.cs # 实现 IMod 的主入口与 NPC 注册代码 └── manifest.xml ``` --- ## 2. 编写 `.csproj` 工程文件 游戏运行在 Unity `.NET Standard 2.1` 环境。在 `Modding/MyCustomNPCPack/MyCustomNPCPack.csproj` 中写入以下配置(所有游戏引用必须加 `false`,切勿将游戏自身的 DLL 复制进 `Mods/` 文件夹): ```xml netstandard2.1 MyCustomNPCPack MyCustomNPCPack latest false false true $(MSBuildProjectDirectory)/../../Probably Stolen_Data/Managed $(ManagedDir)/Assembly-CSharp.dll false $(ManagedDir)/UnityEngine.dll false $(ManagedDir)/UnityEngine.CoreModule.dll false $(ManagedDir)/0Harmony.dll false ``` --- ## 3. 编写 `manifest.xml` 按照官方 `ModLoader` 规范,清单文件根节点必须为 ``,并在 `` 中声明 `CustomNPCFramework`,同时包含必填的 `` 与 `` 节点: ```xml my_custom_npc_pack 我的自定义NPC扩展包 / My Custom NPC Pack YourName 1.0.0 基于 Custom NPC Framework 构建的自定义顾客与跨日剧情扩展包。 / Custom NPC and storyline add-on built on Custom NPC Framework. 0.46 CustomNPCFramework MyCustomNPCPack.dll ``` --- ## 4. 编写 `MyCustomNPCPackMod.cs` 将 `NpcFrameworkSdk.cs` 复制到工程目录后,编写实现 `IMod` 接口的入口类(使用官方推荐的 `ModLog` 记录日志): ```csharp using System; using UnityEngine; namespace MyCustomNPCPack { public class MyCustomNPCPackMod : IMod { private ModLog _log; public void Init(ModManifest manifest) { _log = new ModLog(manifest); RegisterAllNpcs(); _log.Log("Initialized."); } public void OnEnable() { RegisterAllNpcs(); _log?.Log("Enabled."); } public void OnDisable() { } private static string T(string zh, string en) => NpcFrameworkSdk.T(zh, en); private static void RegisterAllNpcs() { NpcFrameworkSdk.RegisterNpc( id: "back_alley_doc", displayNameGetter: () => T("暗巷黑医", "Back-Alley Ripperdoc"), spawnPhase: 2, // 2 = Normal 常规生成阶段 priority: 55, minDay: 2, cooldownDays: 3, spawnChancePercent: 40, oncePerSave: false, canSpawnPredicate: () => true, clientFactory: CreateBackAlleyDoc); } private static StoreClient CreateBackAlleyDoc() { var sc = new StoreClient { identifier = "back_alley_doc", displayName = T("暗巷黑医", "Back-Alley Doc"), spriteName = SpriteDict.GetRandomMedSpriteName(), clientFaction = "FACTION_BLACK_MARKET", clientIntent = StoreClient.ClientIntent.BUY, buyPriceModifier = 35, CanExposeChem = true, staysAfterFailedBargain = true }; sc.SetBudget(420); sc.clientBuyingTagList.Add("MEDICAL"); sc.clientBuyingIdList.Add("blood_bag"); sc.clientBuyingIdList.Add("blue_blood_bag"); sc.AddCheck("CHECK_EXPIRED"); sc.mainDialogue .SetText(sc.displayName, T("嘘……小声点,我诊所今晚有台急诊义体移植手术。", "Keep your voice down. Got an emergency implant surgery at my clinic tonight.")) .NextDialogue() .SetText(sc.displayName, T("你这儿有未过期的血袋、紫色针剂或者止血绷带吗?我出高价收。", "Got any unexpired blood bags, purple injectors, or hemostatic bandages? Paying top credit.")); sc.placeRightItemWhenSellingToDialogue = new Dialogue() .SetText(sc.displayName, T("保存得很完好,正是手术急需的批次。", "Clean seal. Exactly what I need for the operating table.")); sc.acceptDealDialogue = new Dialogue() .SetText(sc.displayName, T("谢了,这笔药能救回一条命。", "Thanks. These supplies will save a life tonight.")) .SetEndAction(() => { NpcFrameworkSdk.AddSaveInt("doc_deals", 1, 0); }); sc.interogationDialogue = new Dialogue() .SetText(sc.displayName, T("下层区医院早就断供了,不去黑市淘药,伤员只能等死。", "Lower Levels clinics ran dry months ago. Without black-market meds, patients just die.")); sc.glasseDialogue = new Dialogue() .SetText("PLAYER", T("(他的白大褂袖口藏着精密手术刀,双手稳得没有一丝颤抖。)", "(Surgical scalpels are tucked inside his cuffs; his hands are impossibly steady.)")); sc.CompleteClientCreation(false); return sc; } } } ``` --- ## 5. 编译、扫描校验与游戏内调试 1. 执行 `dotnet build -c Release`,将编译输出的 `MyCustomNPCPack.dll` 与 `manifest.xml` 放入 `Mods/MyCustomNPCPack/`; 2. 启动游戏,在 **模组(Mods)** 菜单中启用 `CustomNPCFramework` 与 `MyCustomNPCPack`(可在模组详情面板勾选 **开发者模式 / Developer mode**,避免每次重编译后重新确认;也可在 F8 控制台运行 `mod-scan my_custom_npc_pack` 验证零能力占用); 3. 打开 **Custom NPC Framework -> 设置**,在 **开发者调试面板** 的下拉框中选中 `back_alley_doc (暗巷黑医)` 并点击 **应用**,进入存档拉开卷帘门即可直接测试。 ================================================================================ ## guide/sprite-art-pipeline.md ================================================================================ --- layout: doc title: 像素立绘尺寸与描边规范 --- # 像素立绘尺寸与描边规范 在《深空当铺:可能是偷的》中,所有顾客立绘均通过 `StoreClientMono.Instance.image`(`SpriteRenderer`)渲染在店铺窗口后方。本节说明标准 `288×211` 顾客画布的几何参数、头部留白基准线以及深色外轮廓线标准。 ![顾客立绘画布比例参考](/images/zh/v_size_compare.png) --- ## 1. 标准顾客立绘几何参数 原版顾客贴图统一采用 `288 × 211` 画布(`100 PPU`,中心锚点 `(0.5, 0.5)`,`FilterMode.Point`): | 维度指标 | `trailer_scav1` (比利) | `serpico_scav` (拾荒客) | `serpico_rev` (革命军) | **自定义立绘标准 (`v_normal`)** | | :--- | :--- | :--- | :--- | :--- | | **画布总分辨率** | `288 × 211` | `288 × 211` | `288 × 211` | **`288 × 211` (RGBA PNG)** | | **水平有效范围 (`x`)** | `83 .. 205` (宽 `123px`) | `65 .. 222` (宽 `158px`) | `65 .. 221` (width `157px`) | **`55 .. 232` (宽 `150 ~ 178px`)** | | **垂直有效范围 (`y`)** | `57 .. 210` (高 `154px`) | `47 .. 210` (高 `164px`) | `51 .. 210` (高 `160px`) | **`55 .. 210` (高 `154 ~ 162px`)** | | **顶部透明留白** | `57 px` | `47 px` | `51 px` | **`50 ~ 56 px`** | | **外轮廓 1px 描边色** | 深炭紫暗边 | 深炭紫暗边 | 深炭紫暗边 | **`RGB(36, 33, 43)`** | --- ## 2. 画布对齐与标准描边处理脚本 以下 Python(`Pillow` + `NumPy`)脚本可将半身像原图自动缩放至 `target_h = 156`(底部对齐 `y = 210`,顶部留白 `55px`),并将外轮廓 1px 统一设为原版深炭紫描边色 `RGB(36, 33, 43)`: ```python from PIL import Image import numpy as np def normalize_portrait_to_vanilla_canvas(src_rgba_path, out_normal_path, target_h=156): raw = Image.open(src_rgba_path).convert("RGBA") arr = np.array(raw, dtype=np.int32) fg = arr[:, :, 3] > 128 ys, xs = np.where(fg) crop = Image.fromarray(arr[ys.min():ys.max()+1, xs.min():xs.max()+1].astype(np.uint8), "RGBA") scale = target_h / crop.height target_w = int(round(crop.width * scale)) resized = crop.resize((target_w, target_h), Image.NEAREST) canvas = Image.new("RGBA", (288, 211), (0, 0, 0, 0)) ox = (288 - target_w) // 2 oy = 211 - target_h canvas.paste(resized, (ox, oy), resized) c_arr = np.array(canvas, dtype=np.int32) c_fg = c_arr[:, :, 3] > 128 c_arr[~c_fg] = [0, 0, 0, 0] c_arr[c_fg, 3] = 255 pad = np.pad(c_fg, 1, mode="constant", constant_values=False) is_outer_contour = c_fg & (~(pad[:-2, 1:-1] & pad[2:, 1:-1] & pad[1:-1, :-2] & pad[1:-1, 2:])) is_outer_contour[210, :] = False c_arr[is_outer_contour, 0] = 36 c_arr[is_outer_contour, 1] = 33 c_arr[is_outer_contour, 2] = 43 c_arr[is_outer_contour, 3] = 255 Image.fromarray(c_arr.astype(np.uint8), "RGBA").save(out_normal_path) ``` ================================================================================ ## architecture/bridge-and-lifecycle.md ================================================================================ --- layout: doc title: 2.1 零引用 AppDomain 桥接与生命周期 --- # 2.1 零引用 AppDomain 桥接协议与 IMod 生命周期 本节深入分析 `CustomNPCFrameworkMod.cs`、`NpcFrameworkRegistry.cs` 与扩展包 `NpcFrameworkSdk.cs` 之间如何实现 **“零 DLL 引用耦合、与加载顺序完全无关、且 100% 通过 ModScanner 静态安全扫描”** 的跨程序集通信机制。 --- ## 1. 为什么采用 `AppDomain.CurrentDomain` 委托桥接? 在《深空当铺:可能是偷的》的模组加载器(`ModLoader`)中,存在两个核心工程约束: 1. **加载顺序不确定性**:玩家安装的多个 Mod 按目录名或创意工坊订阅顺序加载,扩展包(如 `CyberpunkMercV`)可能在底座框架(`CustomNPCFramework`)之前执行 `Init()`,也可能在其之后执行; 2. **`ModScanner` 反射限制**:游戏内置静态字节码审计器 `ModScanner`,若模组使用 `System.Reflection` 调用私有方法或跨程序集动态反射,会触发权限告警。而 `System.AppDomain.CurrentDomain.GetData(string)` 与 `SetData(string, object)` 属于标准公开托管内存槽,所有委托(`Action<...>` / `Func<...>`)与基础容器(`Dictionary` / `List<...>`) 均在 `mscorlib` / `netstandard` 标准类型范围内,无需任何反射或程序集直接引用。 --- ## 2. 三大全局内存槽(Data Slots)定义 在 `NpcFrameworkRegistry.cs` 中定义了三个全局常量键名: ```csharp public const string BridgeKey = "CustomNPCFramework.Bridge.v1"; public const string PendingQueueKey = "CustomNPCFramework.PendingQueue.v1"; public const string PendingPhoneQueueKey = "CustomNPCFramework.PendingPhoneQueue.v1"; ``` ### 2.1 `CustomNPCFramework.Bridge.v1` 完整委托注册表 当 `NpcFrameworkRegistry.InitializeBridge()` 执行时,会将 22 个核心操作委托一次性挂载到 `AppDomain.CurrentDomain`: ```csharp public static void InitializeBridge() { var bridge = new Dictionary(StringComparer.OrdinalIgnoreCase) { // 1. 核心 NPC 注册与即时召唤 ["RegisterNpc"] = new Action>(RegisterFromDictionary), ["SummonNpcNow"] = new Func(SummonNpcImmediate), ["ResolveSprite"] = new Func(NpcTraitHelper.ResolveValidSpriteName), // 2. 跨日剧情存档状态机 (cnpcf_ 命名空间) ["GetSaveInt"] = new Func(NpcSaveStore.GetInt), ["SetSaveInt"] = new Action(NpcSaveStore.SetInt), ["AddSaveInt"] = new Func(NpcSaveStore.AddInt), ["GetSaveBool"] = new Func(NpcSaveStore.GetBool), ["SetSaveBool"] = new Action(NpcSaveStore.SetBool), ["GetSaveString"] = new Func(NpcSaveStore.GetString), ["SetSaveString"] = new Action(NpcSaveStore.SetString), // 3. 全息电话簿注册与实时同步 ["RegisterPhoneContact"] = new Action>(NpcPhoneRegistry.RegisterFromDictionary), ["SyncPhoneContacts"] = new Action(NpcPhoneRegistry.SyncPhoneContactsToPlayerStore), // 4. 声明式属性映射与 顾客塑造子系统高阶工具箱 ["ApplyClientProfile"] = new Action>(NpcFullFeatureKit.ApplyClientProfile), ["CreateHandnoteItem"] = new Func(NpcFullFeatureKit.CreateHandnoteItem), ["CreatePaperNoteItem"] = new Func(NpcFullFeatureKit.CreatePaperNoteItem), ["SpawnItemOnCounterOrStore"] = new Func(NpcFullFeatureKit.SpawnItemOnCounterOrStore), ["GiveHandnoteToPlayer"] = new Func(NpcFullFeatureKit.GiveHandnoteToPlayer), ["PostStoreRequest"] = new Func, bool>(NpcFullFeatureKit.PostStoreRequestFromDictionary), ["AttachProcurementOffer"] = new Action>(NpcFullFeatureKit.AttachProcurementOffer), ["BuildCustomGunOrder"] = new Func, GunOrderData>(NpcFullFeatureKit.BuildCustomGunOrder), ["RegisterAfterhourEvent"] = new Func, bool>(NpcFullFeatureKit.RegisterAfterhourEventFromDictionary), ["RegisterNightlyHook"] = new Action(NpcFullFeatureKit.RegisterNightlyHook), ["RegisterDumpingGroundWatcher"] = new Action>(NpcFullFeatureKit.RegisterDumpingGroundWatcher), ["TriggerNews"] = new Action(NpcTraitHelper.TriggerCustomNewspaper) }; AppDomain.CurrentDomain.SetData(BridgeKey, bridge); DrainPendingQueue(); NpcPhoneRegistry.SyncPhoneContactsToPlayerStore(); } ``` ### 2.2 双缓冲挂起队列(`DrainPendingQueue`)消费机制 当扩展包比框架更早加载时,`NpcFrameworkSdk.RegisterNpc` 与 `RegisterPhoneContact` 会自动将构造好的参数字典推入 `PendingQueue.v1` 和 `PendingPhoneQueue.v1`。随后框架在以下 **5 个时机** 均会主动调用 `DrainPendingQueue()`,确保没有任何注册请求遗漏: 1. `NpcFrameworkRegistry.InitializeBridge()`(框架 `Init` 与 `OnEnable` 时); 2. `CustomNPCFrameworkMod.OnModAssetsLoaded(LoadedMod mod)`(任意 Mod 资产加载完成时); 3. `CustomNPCFrameworkMod.OnGameLoadedInit()`(玩家加载存档进入游戏时); 4. `CustomNPCFrameworkMod.OnShutterOpenedLate()`(玩家每天拉开卷帘门时); 5. `NpcFrameworkRegistry.Find(string id)` / `HandleGenerationPhase(...)`(每次查询或生成顾客前)。 --- ## 3. `CustomNPCFrameworkMod` 完整 `ModHook` 事件挂载表 框架在 `OnEnable()` 与 `NpcFullFeatureKit.InitHooks()` 中挂载了游戏原生的 **11 个核心生命周期钩子**,在 `OnDisable()` 中对称解绑: | 挂载的 `ModHook` 事件 | 触发时机 | 框架绑定的处理函数与核心行为 | | :--- | :--- | :--- | | `OnGenerateCustomerVeryEarly` | `GenerateClient()` 阶段 0(最早期) | 调用 `HandleGenerationPhase(mgr, NpcSpawnPhase.VeryEarly)`。 | | `OnGenerateCustomerEarly` | `GenerateClient()` 阶段 1(原版固定剧情后) | 调用 `HandleGenerationPhase(mgr, NpcSpawnPhase.Early)`,推荐主线剧情 NPC 使用。 | | `OnGenerateCustomerNormal` | `GenerateClient()` 阶段 2(原版常规抽样后) | 调用 `HandleGenerationPhase(mgr, NpcSpawnPhase.Normal)`,推荐日常散客使用。 | | `OnGenerateCustomerLate` | `GenerateClient()` 阶段 3 | 调用 `HandleGenerationPhase(mgr, NpcSpawnPhase.Late)`。 | | `OnGenerateCustomerVeryLate` | `GenerateClient()` 阶段 4(原版全部逻辑末尾) | 调用 `HandleGenerationPhase(mgr, NpcSpawnPhase.VeryLate)`,并在最末尾执行第一次调试召唤置顶 `ForceInsertClientAtFront`。 | | `OnShutterOpenedLate` | 早上卷帘门拉开且 `HandleFutureClientQueue` 完毕后 | 同步贴图、消费挂起队列、执行延迟存档重置,并调用 `ConsumePendingDebugSummonOnShutterOpened()` 二次确认置顶并自动调用 `TryCallNextClient()` 唤入店门。 | | `OnGameLoadedInit` | 存档加载进入店铺场景时 | 同步所有 Mod 贴图、同步全息电话簿联系人至 `PlayerStore.PhoneClientDict`、恢复调试挂起状态。 | | `OnModAssetsLoaded` | 任一 Mod 的 `Textures/` 贴图加载完成时 | 调用 `RegisterModTexturesToSpriteDict(mod)` 将 PNG 转为 `100 PPU`、`FilterMode.Point` 的 `Sprite` 注入 `SpriteDict`,并刷新调试面板下拉选项。 | | `OnModConfigApplied` | 玩家在设置界面点击“应用 (Apply)”时 | 处理存档进度重置与调试召唤指令(若已开店则立即插队进门;若在主菜单或未开店则持久化挂起)。 | | `OnGoingSleepEarly` | 玩家夜晚点击床铺入睡前 | 触发 `NpcFullFeatureKit` 中通过 `RegisterNightlyHook` 注册的全部夜间结算回调。 | | `OnAfterhourLeaveEarly` | 玩家夜间离开垃圾场/夜间地点时 | 触发 `RegisterDumpingGroundWatcher` 注册的背包/地面扫描回调。 | ================================================================================ ## architecture/generation-pipeline.md ================================================================================ --- layout: doc title: 2.2 五阶段生成管线与调试强制置顶 --- # 2.2 五阶段生成管线与调试强制置顶算法 本节结合从《深空当铺:可能是偷的》游戏本体 `Assembly-CSharp.dll` 反编译出的 `PlayerStore.OnShutterOpened` 与 `StoreClientManager.GenerateClient` IL 字节码,完整拆解顾客队列 `clientStack` 的生成顺序、7 步筛选逻辑以及调试召唤的双阶段置顶实现。 --- ## 1. 原版开店与顾客生成底层 IL 执行流 当玩家在清晨点击店铺左上角的卷帘门开关(`StoreShutterButton.OnClick` → `StoreShutterButton.OpenShutter`)时,原版代码的精确调用链如下: ```text StoreShutterButton.OpenShutter() ├── 1. PlayerStore.Instance.OnShutterOpened() │ ├── CheckCrime() / SoldItem.HandleSoldItem() │ ├── this.storeClientManager.GenerateClient() │ │ ├── ModHook.FireOnGenerateCustomerVeryEarly(this) │ │ ├── [原版固定天数剧情顾客生成] │ │ ├── ModHook.FireOnGenerateCustomerEarly(this) │ │ ├── [原版常规顾客池抽样] │ │ ├── ModHook.FireOnGenerateCustomerNormal(this) │ │ ├── [原版特殊职业与展示柜顾客生成] │ │ ├── ModHook.FireOnGenerateCustomerLate(this) │ │ ├── this.ClientGenCheck() │ │ ├── this.HandleJohnSmithVandalVisit() // <-- 注意:内部调用 AddNextClient 抢占 index 0! │ │ ├── LouBombHelper.QueueVisit(this) // <-- 注意:内部调用 AddNextClient 抢占 index 0! │ │ └── ModHook.FireOnGenerateCustomerVeryLate(this) │ ├── this.HandleFutureClientQueue() // 将跨日预约队列追加到 clientStack │ ├── this.storeClientManager.clientStack.RemoveAll(c => c == null) │ └── this.LogQueuedClient() // 在控制台打印当日排队的顾客名单 │ ├── 2. PlayerStore.Instance.OpenShutter() │ └── this.storeState = PlayerStore.StoreState.OPEN (值为 1) │ ├── 3. StoreShutterButton.OnShutterDoorOpenMorning() │ ├── ModHook.FireOnShutterOpenedEarly() │ ├── [发放早报 newspaper、教程手册、枪证、分红等] │ └── ModHook.FireOnShutterOpenedLate() // <-- 框架在此处执行二次置顶校验与自动唤入! │ └── 4. PlayerStore.Instance.OnLateShutterOpen() └── [检查是否有清晨堵门事件 SetupWaitingClient] ``` --- ## 2. `HandleGenerationPhase` 完整源码与 7 步筛选剖析 在 `NpcFrameworkRegistry.cs` 中,每个 `NpcSpawnPhase` 触发时都会运行 `HandleGenerationPhase`: ```csharp internal static void HandleGenerationPhase(StoreClientManager manager, NpcSpawnPhase phase) { if (manager == null) return; DrainPendingQueue(); NpcPhoneRegistry.SyncPhoneContactsToPlayerStore(); int day = 1; try { day = StoreStation.Instance != null ? StoreStation.Instance.dayCounter : 1; } catch { } if (CustomNPCFrameworkMod.FrameworkEnabled) { float chanceScale = CustomNPCFrameworkMod.SpawnChanceMultiplier; for (int i = 0; i < Entries.Count; i++) { var entry = Entries[i]; // Step 1: 阶段匹配 if (entry.SpawnPhase != phase) continue; // Step 2: 天数窗口 [MinDay, MaxDay] if (day < entry.MinDay || day > entry.MaxDay) continue; // Step 3: 单档唯一性检查 (OncePerSave) if (entry.OncePerSave && NpcSaveStore.GetInt($"visits_{entry.Id}", 0) > 0) continue; // Step 4: 冷却天数检查 (CooldownDays) if (entry.CooldownDays > 0) { int lastDay = NpcSaveStore.GetInt($"last_day_{entry.Id}", -9999); if (day - lastDay < entry.CooldownDays) continue; } // Step 5: 已逮捕黑名单排除 try { if (manager.arrestedClients != null && manager.arrestedClients.Contains(entry.Id)) continue; } catch { } // Step 6: 自定义前置条件谓词 (CanSpawnPredicate) try { if (entry.CanSpawnPredicate != null && !entry.CanSpawnPredicate()) continue; } catch (Exception ex) { CustomNPCFrameworkMod.Log?.Warning($"CanSpawnPredicate error for '{entry.Id}': " + ex.Message); continue; } // Step 7: 概率倍率检定 (SpawnChancePercent * SpawnChanceMultiplier) int effectiveChance = Mathf.Clamp(Mathf.RoundToInt(entry.SpawnChancePercent * chanceScale), 0, 100); if (effectiveChance <= 0) continue; if (effectiveChance < 100 && !RNG.Roll(effectiveChance)) continue; // 通过全部检定:构造 StoreClient 实例并入队 try { var client = BuildSafeClient(entry); if (client == null) continue; if (entry.NoDuplicateInQueue) manager.TryAddClient(client, true); else manager.AddClient(client); RecordSpawn(entry, day); entry.OnSpawned?.Invoke(); CustomNPCFrameworkMod.Log?.Log($"Queued NPC '{entry.Id}' on Day {day} ({phase})."); } catch (Exception ex) { CustomNPCFrameworkMod.Log?.Warning($"Failed to create/queue NPC '{entry.Id}': " + ex.Message); } } } // 阶段 4 (VeryLate) 最末尾:若存在挂起的调试召唤 NPC,立即置顶到 clientStack[0] if (phase == NpcSpawnPhase.VeryLate) { string targetNpcId = CustomNPCFrameworkMod.GetConfiguredSummonNpcId(); if (!string.IsNullOrEmpty(targetNpcId)) { var debugEntry = Find(targetNpcId); if (debugEntry != null) ForceInsertClientAtFront(manager, debugEntry, autoCallIfDoorEmpty: false, delayedCall: false); } } } ``` --- ## 3. 即时召唤与队首置顶机制(`ForceInsertClientAtFront`) 反编译 `StoreClientManager.AddNextClient(StoreClient)` 的 IL 代码可知,原版方法开头包含两道拦截: ```csharp // 原版 StoreClientManager.AddNextClient 反编译等价逻辑: public void AddNextClient(StoreClient client) { if (client == null) return; if (this.IsClientBlockedByKnownSnitch(client)) return; // 拦截点 1:告密者惩罚状态拦截 if (this.IsClientBlockedByBannedCommissary(client)) return; // 拦截点 2:禁售开局天赋拦截 this.clientStack.Insert(0, client); this.TrackClient(client); } ``` 此外,如果同一个 NPC 在当日的 `Early` 或 `Normal` 阶段已经自然生成过一次,后续再插队会导致当日队列里出现两个完全相同的 NPC。 因此,`NpcFrameworkRegistry.ForceInsertClientAtFront` 直接操作底层公开列表 `mgr.clientStack` 与公开方法 `mgr.TrackClient(client)`: ```csharp internal static bool ForceInsertClientAtFront(StoreClientManager mgr, NpcRegistrationEntry entry, bool autoCallIfDoorEmpty, bool delayedCall) { if (mgr == null || entry == null) return false; var client = BuildSafeClient(entry); if (client == null) return false; if (mgr.clientStack == null) mgr.clientStack = new List(); // 1. 先移除队列中可能已经自然刷出的同名重复实例,保证全队唯一且位于 index 0 string targetId = client.identifier ?? entry.Id; mgr.clientStack.RemoveAll(c => c != null && string.Equals(c.identifier, targetId, StringComparison.OrdinalIgnoreCase)); // 2. 直接插入 index 0 并登记冷却追踪,绕过 KnownSnitch / BannedCommissary 拦截 mgr.clientStack.Insert(0, client); mgr.TrackClient(client); int day = StoreStation.Instance != null ? StoreStation.Instance.dayCounter : 1; RecordSpawn(entry, day); entry.OnSpawned?.Invoke(); // 3. 若需要自动唤入店门口(卷帘门拉开时 delayedCall=true 延迟 0.35s;营业中途 delayedCall=false 立即唤入) if (autoCallIfDoorEmpty) ScheduleAutoCallFirstClient(delayedCall); return true; } ``` ================================================================================ ## architecture/save-and-config.md ================================================================================ --- layout: doc title: 2.3 跨日存档状态机与 ModConfig 设置 --- # 2.3 跨日存档状态机(`NpcSaveStore`)与 `ModConfig` 动态设置系统 本节解析 `NpcSaveStore.cs` 如何利用游戏原生存档字典实现多存档隔离的持久化存储,以及 `CustomNPCFrameworkMod.cs` 中 `ModConfig` 设置项与开发者调试面板的完整实现。 --- ## 1. `NpcSaveStore`:基于 `PlayerStore.ModData()` 的命名空间隔离存储 在《深空当铺:可能是偷的》中,`PlayerStore.Instance.ModData()` 返回一个随当前存档(`runID`)一起序列化到存档 JSON 文件中的 `Dictionary`。 为了防止不同 Mod 的键名冲突,并确保在主菜单(`PlayerStore.Instance == null`)调用时不抛异常,`NpcSaveStore.cs` 实现了带 `"cnpcf_"` 前缀与内存回退池 `MemoryFallback` 的双重存储层: ```csharp namespace CustomNPCFramework { public static class NpcSaveStore { private const string Prefix = "cnpcf_"; private static readonly Dictionary MemoryFallback = new Dictionary(StringComparer.Ordinal); private static Dictionary GetActiveDict() { try { var ps = PlayerStore.Instance; if (ps != null) { var dict = ps.ModData(); if (dict != null) return dict; } } catch { } return MemoryFallback; } private static string FullKey(string key) => Prefix + (key ?? ""); public static string GetString(string key, string defaultValue = "") { var dict = GetActiveDict(); return dict.TryGetValue(FullKey(key), out var val) && val != null ? val : defaultValue; } public static void SetString(string key, string value) { var dict = GetActiveDict(); dict[FullKey(key)] = value ?? ""; } public static int GetInt(string key, int defaultValue = 0) { string raw = GetString(key, null); if (!string.IsNullOrEmpty(raw) && int.TryParse(raw, out int parsed)) return parsed; return defaultValue; } public static void SetInt(string key, int value) => SetString(key, value.ToString()); public static int AddInt(string key, int delta, int defaultValue = 0) { int next = GetInt(key, defaultValue) + delta; SetInt(key, next); return next; } public static void ResetAllFrameworkKeys() { var dict = GetActiveDict(); var toRemove = new List(); foreach (var kv in dict) { if (kv.Key != null && kv.Key.StartsWith(Prefix, StringComparison.Ordinal)) toRemove.Add(kv.Key); } for (int i = 0; i < toRemove.Count; i++) dict.Remove(toRemove[i]); MemoryFallback.Clear(); } } } ``` ### 框架自动维护的内置存档键 | 完整存档键名 | 写入时机 | 用途 | | :--- | :--- | :--- | | `cnpcf_last_day_` | 每次该 NPC 被排入队列或强制召唤时 | 记录该 NPC 最近一次生成的游戏天数(`dayCounter`),用于计算 `CooldownDays`。 | | `cnpcf_visits_` | 每次该 NPC 被排入队列或强制召唤时 | 累计该 NPC 在当前存档中的总造访次数,用于判断 `OncePerSave`。 | | `cnpcf_billy_stage` / `cnpcf_billy_fed` | `RestoredUnusedNPCs` 剧情推进时 | 控制比利四幕剧情阶段(`0..5`)与第 1 幕是否给过食物(`0/1`)。 | | `cnpcf_v_stage` / `cnpcf_v_trust` | `CyberpunkMercV` 剧情推进时 | 控制赛博朋克 V 五阶段剧情(`0..5`)与信任度等级。 | --- ## 2. `ModConfig` 设置面板与动态下拉选项刷新 在 `CustomNPCFrameworkMod.InitModConfig()` 中,利用游戏原生的 `ModConfig.For("CustomNPCFramework")` 注册了两大分组共 5 个配置项: 1. **常规与生成设置 / General & Spawn Settings**: - `language`(下拉框):`"自动跟随游戏 / Auto (Follow Game)"`、`"简体中文 / Simplified Chinese"`、`"英文 / English"`。通过委托 `label: () => T(...)` 实现界面语言热切换; - `enabled`(布尔开关):是否启用扩展包 NPC 的每日自动随机生成; - `spawn_rate_percent`(整型滑块 `25 ~ 300`,默认 `100`):全局缩放所有概率型自定义 NPC 的出现权重。 2. **开发者调试面板 / Developer Debug Panel**: - `debug_summon_id`(动态下拉框):列出 `"不召唤 / None"`、置顶的智能剧情入口 `"v (赛博朋克V - 按当前剧情阶段自动推进)"`、`"billy (比利 - 按当前剧情阶段自动推进)"`、16 个预设阶段 ID,以及所有第三方 Mod 通过 `RegisterNpc` 动态注册的额外 NPC ID; - `debug_reset_save`(布尔开关):开启并点击应用后,清空当前存档内所有 `cnpcf_` 开头的剧情进度与冷却记录,并自动恢复为关闭状态(若在主菜单开启,则挂起至进入存档时自动执行)。 ================================================================================ ## architecture/glitch-and-textures.md ================================================================================ --- layout: doc title: 动态贴图注入与立绘回退机制 --- # 2.4 动态贴图注入与立绘回退机制 本节说明 `CustomNPCFramework` 如何自动将各模组目录下的 `Textures/*.png` 注入游戏全局立绘字典 `SpriteDict`,以及如何通过内置回退表保障顾客立绘加载安全。 --- ## 1. 自动扫描并注入自定义贴图(`RegisterModTexturesToSpriteDict`) 当游戏的 `ModLoader` 加载任一模组时,会自动读取该模组文件夹下 `Textures/` 目录中的所有 `.png` 文件,存入 `LoadedMod.Textures`(`Dictionary`,键名为不带扩展名的文件名)。 由于游戏原版的顾客渲染器 `StoreClientMono` 从全局单例 `SpriteDict.Instance.spriteDictionary`(`Dictionary`)中按名称查找 `Sprite`,`CustomNPCFrameworkMod` 在 `OnEnable`、`OnModAssetsLoaded`、`OnGameLoadedInit` 和 `OnShutterOpenedLate` 四个生命周期节点调用 `RegisterModTexturesToSpriteDict` 完成自动转换与注册: ```csharp private static void RegisterModTexturesToSpriteDict(LoadedMod mod) { try { if (mod?.Textures == null || mod.Textures.Count == 0) return; var sd = SpriteDict.Instance; if (sd?.spriteDictionary == null) return; foreach (var kv in mod.Textures) { string key = kv.Key; Texture2D tex = kv.Value; if (string.IsNullOrEmpty(key) || tex == null) continue; if (sd.spriteDictionary.ContainsKey(key)) continue; // 设置为 FilterMode.Point 与 pixelsPerUnit = 100f,与原版像素画保持 1:1 比例与锐度 tex.filterMode = FilterMode.Point; tex.wrapMode = TextureWrapMode.Clamp; var sp = Sprite.Create(tex, new Rect(0f, 0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100f); sp.name = key; sd.spriteDictionary[key] = sp; Log?.Log($"Registered custom NPC sprite '{key}' from mod '{mod.Manifest?.ID}'."); } } catch (Exception ex) { Log?.Warning("RegisterModTexturesToSpriteDict: " + ex.Message); } } ``` --- ## 2. 立绘安全解析与回退表(`NpcTraitHelper.ResolveValidSpriteName`) 在构造 `StoreClient` 时,`BuildSafeClient` 会自动调用 `NpcTraitHelper.ResolveValidSpriteName(client.spriteName)`: 1. 若传入的 `spriteName` 已存在于 `SpriteDict.Instance.spriteDictionary`,直接原样返回; 2. 若传入的是原版早期未实装的键名(如 `"billy"`、`"cul1"`、`"sha3"`),自动映射到正式版已存在的立绘键名(`"trailer_scav1"`、`"spy"`、`"trailer_scav3"`); 3. 若仍未找到对应贴图,则安全回退至 `SpriteDict.GetRandomLowerLevelSpriteName()`,确保在任何情况下都不会因贴图缺失导致渲染异常。 ================================================================================ ## subsystems/01-regular-buying.md ================================================================================ --- layout: doc title: 01. 常规买家与求购清单 (BUY) --- # 01. 常规买家与求购清单 (`ClientIntent.BUY`) 常规买家是《深空当铺:可能是偷的》中最基础的顾客类型。顾客进入店铺后提出求购特定类别(Tag)或特定物品 ID 的需求,玩家从货架或后仓取出匹配的商品摆上柜台,在顾客预算范围内完成议价与交付。 --- ## 核心字段与方法 | 字段 / 方法 | 类型 | 说明 | | :--- | :--- | :--- | | `sc.clientIntent` | `StoreClient.ClientIntent` | 设为 `StoreClient.ClientIntent.BUY`(枚举值 `1`)。 | | `sc.SetBudget(int amount)` | `void` | 设置顾客本次进店携带的现金预算上限。 | | `sc.useClientBudget` | `bool` | 是否启用预算限制(默认 `true`)。 | | `sc.clientBuyingTagList` | `List` | 顾客愿意收购的物品分类标签列表(如 `"MEDICAL"`, `"FIREARM"`)。满足任一标签即可放到柜台交易。 | | `sc.clientBuyingIdList` | `List` | 顾客指定收购的具体物品 `itemID` 列表(如 `"blood_bag"`, `"aug_chip"`)。 | | `sc.clientBlackTagList` | `List` | 顾客明确拒收的物品分类标签黑名单。 | | `sc.clientBlackIdList` | `List` | 顾客明确拒收的具体物品 `itemID` 黑名单。 | | `sc.SetVariety()` | `void` | 调用后,顾客在单次交易中要求多件不同种类的商品,拒绝重复收同一件商品。 | --- ## 代码示例:高预算专项买家 ```csharp private static StoreClient CreateMedicalBuyer() { var sc = new StoreClient { identifier = "clinic_runner", displayName = NpcFrameworkSdk.T("诊所跑腿员", "Clinic Runner"), spriteName = SpriteDict.GetRandomMedSpriteName(), clientFaction = "FACTION_LOWER_LEVEL", clientIntent = StoreClient.ClientIntent.BUY, buyPriceModifier = 25 }; // 1. 设置携带预算 360 信用点 sc.SetBudget(360); // 2. 添加求购标签与具体物品 ID sc.clientBuyingTagList.Add("MEDICAL"); sc.clientBuyingIdList.Add("blood_bag"); sc.clientBuyingIdList.Add("hemostatic_bandage_item"); // 3. 排除违禁致幻剂 sc.clientBlackTagList.Add("NARCOTIC"); sc.mainDialogue.SetText(sc.displayName, NpcFrameworkSdk.T("下层区诊所急需一批医疗物资,你有血袋或者止血绷带吗?", "The clinic needs medical supplies. Got any blood bags or hemostatic bandages?")); sc.placeRightItemWhenSellingToDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("太好了,正是我们需要的。", "Great, that's exactly what we need.")); sc.acceptDealDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("多谢,这就送回诊所。", "Thanks, taking these straight back to the clinic.")); sc.CompleteClientCreation(false); return sc; } ``` ================================================================================ ## subsystems/02-regular-selling.md ================================================================================ --- layout: doc title: 02. 常规卖家与单品兜售 (SELL) --- # 02. 常规卖家与单品兜售 (`ClientIntent.SELL`) 当顾客作为卖家(`ClientIntent.SELL` 或 `ClientIntent.SELLNBUY`)进店时,顾客会在开场对话结束后将一件或多件待售物品放到柜台桌面上,由玩家决定是否出钱收购。 --- ## 核心字段与铺货方法 | 字段 / 方法 | 类型 | 说明 | | :--- | :--- | :--- | | `sc.clientIntent` | `StoreClient.ClientIntent` | 设为 `StoreClient.ClientIntent.SELL`(枚举值 `2`)或 `SELLNBUY`(枚举值 `3`)。 | | `sc.sellPriceModifier` | `int` | 顾客出售商品时的要价浮动百分比(正数为溢价,负数为折扣)。 | | `PlayerStore.Instance.AddDirectSellingItemToTable` | `void` | 在 `mainDialogue` 末尾的 `SetEndAction` 中调用,将顾客要卖的物品生成到柜台桌面。 | ### `AddDirectSellingItemToTable` 参数签名 ```csharp PlayerStore.Instance.AddDirectSellingItemToTable( string itemId, // 原版或模组注册的物品 ID,如 "aug_chip" bool isOwnedByPlayer, // 顾客卖给玩家时必须传 false bool isStolen, // 该物品是否带有赃物标记 bool isContraband, // 该物品是否带有违禁品标记 int customPrice // 自定义售价;传 0 则按游戏物品基础价格与修饰符自动计算 ); ``` --- ## 代码示例:出售指定单品的拾荒客 ```csharp private static StoreClient CreateSingleItemSeller() { var sc = new StoreClient { identifier = "keycard_finder", displayName = NpcFrameworkSdk.T("通风管拾荒者", "Vent Scavenger"), spriteName = SpriteDict.GetRandomScavSpriteName(), clientFaction = "FACTION_LOWER_LEVEL", clientIntent = StoreClient.ClientIntent.SELL, sellPriceModifier = -10 // 比市场价便宜 10% }; sc.mainDialogue .SetText(sc.displayName, NpcFrameworkSdk.T("我在通风井底下捡到一张科研门禁卡,你要收吗?", "Found a science keycard down in the air ducts. Interested?")) .SetEndAction(() => { PlayerStore.Instance?.AddDirectSellingItemToTable("sci_keycard", false, true, false, 0); }); sc.acceptDealDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("爽快!这下今晚能去喝一杯了。", "Sweet! Drinks are on me tonight.")); sc.CompleteClientCreation(false); return sc; } ``` ================================================================================ ## subsystems/03-wholesale-lots.md ================================================================================ --- layout: doc title: 03. 整包一口价批发 (Wholesale) --- # 03. 整包一口价批发 (`isOfferWholesale`) 整包批发(Wholesale)允许顾客一次性将多件高价值战利品或走私货铺在柜台上,并按整包折扣价(如七折 `-30`、七五折 `-25`、八折 `-20`)打包出售给玩家。`RestoredUnusedNPCs` 中的比利第 3 幕、灰潮拾荒客、下层区制毒师、黑市军火贩以及 `CyberpunkMercV` 中的 V 第 3 幕均采用此机制。 --- ## 核心配置三要素 1. `sc.clientIntent = StoreClient.ClientIntent.SELL`; 2. `sc.isOfferWholesale = true`; 3. `sc.wholesaleDiscount = -30`(负数代表折扣百分比,`-30` 即优惠 30%,按总价的 70% 结算); 4. 在 `sc.mainDialogue` 最后一页的 `SetEndAction` 中,连续调用多次 `PlayerStore.Instance.AddDirectSellingItemToTable(...)` 将整批物品生成到桌面上。 --- ## 代码示例:金库劫案整包七折销赃 ```csharp private static StoreClient CreateVaultWholesaleSeller() { var sc = new StoreClient { identifier = "v_act3_heist", displayName = NpcFrameworkSdk.T("佣兵 V", "Mercenary V"), spriteName = "v_normal", clientFaction = "FACTION_BLACK_MARKET", clientIntent = StoreClient.ClientIntent.SELL, isOfferWholesale = true, wholesaleDiscount = -30 // 整包 7 折(优惠 30%) }; sc.mainDialogue .SetText(sc.displayName, NpcFrameworkSdk.T("金库被我们掀了个底朝天,剩下的尖端货全在这儿了。", "Cleaned out their vault. Brought the rest of the high-tech loot straight to you.")) .NextDialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("义体芯片、指挥官门禁卡、高能电池和冲锋枪,整包七折让给你!", "Aug chips, command keycards, hypertech battery, and an SMG. 30% off the whole lot!")) .SetEndAction(() => { var ps = PlayerStore.Instance; if (ps == null) return; ps.AddDirectSellingItemToTable("aug_chip", false, false, false, 0); ps.AddDirectSellingItemToTable("command_keycard", false, false, false, 0); ps.AddDirectSellingItemToTable("sci_keycard", false, false, false, 0); ps.AddDirectSellingItemToTable("energy_credit_hyp", false, false, false, 0); ps.AddDirectSellingItemToTable("smg", false, false, false, 0); }); sc.CompleteClientCreation(false); return sc; } ``` ================================================================================ ## subsystems/04-barter-and-begging.md ================================================================================ --- layout: doc title: 04. 以物易物与乞讨施舍 (BarterOffer) --- # 04. 以物易物与乞讨施舍 (`BarterOffer`) 以物易物子系统(`ClientIntent.BARTER`)用于实现不使用信用点结算、而是要求玩家交付特定类别物品的交互场景(如 `RestoredUnusedNPCs` 中第 1 幕比利上门讨要食物)。 --- ## 核心类与方法 | 类 / 成员 | 类型 | 说明 | | :--- | :--- | :--- | | `StoreClient.ClientIntent.BARTER` | `ClientIntent` | 枚举值 `6`,标记顾客为物物交换/施舍意图。 | | `sc.useClientBudget` | `bool` | 设为 `false`,禁用常规现金预算条。 | | `sc.barterOffer` | `BarterOffer` | 挂载在顾客身上的交换报价配置对象。 | | `BarterOffer.getBarterResult` | `Func` | 校验玩家是否满足交换条件并返回提示文本(返回 `BarterResult { isAccepted, response }`)。 | | `sc.barterOffer.InstanciateOffer()` | `void` | 在对话选项回调中调用,唤出游戏原生的物品交付槽。 | | `EmporiumEntry.Instance.IsBackInvContainItemTag(string tag)` | `bool` | 检查玩家店铺后仓是否持有包含指定 Tag 的物品。 | --- ## 代码示例:带库存检测与保底分支的食物施舍 ```csharp var sc = new StoreClient { identifier = "billy1", displayName = NpcFrameworkSdk.T("比利", "Billy"), spriteName = "trailer_scav1", clientFaction = "FACTION_LOWER_LEVEL", clientIntent = StoreClient.ClientIntent.BARTER, useClientBudget = false }; sc.clientBuyingTagList.Add("FOOD"); sc.barterOffer = new BarterOffer { ownerClient = sc, barterTextBody = NpcFrameworkSdk.T("施舍一点食物?", "Spare Food?"), onInstance = () => { }, getBarterResult = () => { var res = new BarterResult(); bool hasFood = EmporiumEntry.Instance != null && EmporiumEntry.Instance.IsBackInvContainItemTag("FOOD"); res.isAccepted = hasFood; res.response = hasFood ? NpcFrameworkSdk.T("看起来太香了!", "That looks good!") : NpcFrameworkSdk.T("能分我一口吃的吗?", "Can you spare some food?"); return res; } }; // 在对话分支中触发 Barter 面板(若玩家没囤食物则走员工餐保底分支) var dlgFeed = new Dialogue().SetText("PLAYER", NpcFrameworkSdk.T("[分给他一点食物] 拿去垫垫肚子吧。", "[Give him some food] Take it.")); sc.mainDialogue.AddChoice(DirectoryMaster.Item("$", true), "", "", dlgFeed, () => { bool hasFoodItem = EmporiumEntry.Instance != null && EmporiumEntry.Instance.IsBackInvContainItemTag("FOOD"); if (hasFoodItem && sc.barterOffer != null) { sc.barterOffer.InstanciateOffer(); } else { NpcFrameworkSdk.SetSaveInt("billy_stage", 1); NpcFrameworkSdk.SetSaveInt("billy_fed", 1); var d = dlgFeed.NextDialogue().SetText(sc.displayName, NpcFrameworkSdk.T("太感谢您了!这顿热乎饭救了我的命!", "Thank you so much! This warm meal saved my life!")); d.SetEndAction(() => DialogUIManager.Instance?.CurrentClientLeave(1f)); } }, null); ``` ================================================================================ ## subsystems/05-bargaining-and-patience.md ================================================================================ --- layout: doc title: 05. 议价宽容度、耐心与香水影响 --- # 05. 议价宽容度、耐心与香水影响 本子系统控制顾客在柜台讨价还价阶段的心理底线、溢价承受力、失败后是否留店以及交易达成的阵营声望倍率。 --- ## 核心属性详表 | `StoreClient` 字段 | `ApplyClientProfile` 键名 | 类型 | 作用说明 | | :--- | :--- | :--- | :--- | | `buyPriceModifier` | `"BuyPriceModifier"` | `int` | 买家愿意支付的溢价百分比(如 `40` 表示愿意多付 40%)。 | | `sellPriceModifier` | `"SellPriceModifier"` | `int` | 卖家出售物品的要价修正百分比。 | | `clientImpatience` | `"ClientImpatience"` | `int` | 顾客急躁程度,数值越高,玩家连续压价/抬价时耐心条消耗越快。 | | `alwaysRejectBadBargain` | `"AlwaysRejectBadBargain"` | `bool` | 设为 `true` 时,只要玩家报价超出其心理预期,立即一口回绝。 | | `isBargainAvailable` | `"IsBargainAvailable"` | `bool` | 是否允许讨价还价(设为 `false` 则一口价,禁止滑动调价)。 | | `staysAfterFailedBargain` | `"StaysAfterFailedBargain"` | `bool` | 设为 `true` 时,即使一次议价失败,顾客也不会立刻气走,允许重开报价。 | | `perfumeInfluence` | `"PerfumeInfluence"` | `int` | 店铺喷洒香水对该顾客议价宽容度的加成权重。 | | `tradeReputationMultiplier` | `"TradeReputationMultiplier"` | `double` | 与该顾客成交时获得的阵营声望倍率(默认 `1.0`)。 | --- ## 代码示例:使用 `ApplyClientProfile` 配置高宽容度急诊买家 ```csharp NpcFrameworkSdk.ApplyClientProfile(sc, new Dictionary { ["BuyPriceModifier"] = 40, ["ClientImpatience"] = 1, ["StaysAfterFailedBargain"] = true, ["PerfumeInfluence"] = 2, ["TradeReputationMultiplier"] = 1.5 }); ``` ================================================================================ ## subsystems/06-contraband-and-labels.md ================================================================================ --- layout: doc title: 06. 违禁品、零售高价签与水质警告 --- # 06. 违禁品、零售高价签与水质警告 在《深空当铺:可能是偷的》中,不同阵营与身份的顾客对 **违禁品(Contraband)**、**贴标机打印的零售溢价签(Retail Markup)** 以及 **危险水质警告标签(Hazardous Water Label)** 有截然不同的接受规则。 --- ## 核心属性详表 | `StoreClient` 字段 | `ApplyClientProfile` 键名 | 类型 | 作用说明 | | :--- | :--- | :--- | :--- | | `noAcceptingContraband` | `"NoAcceptingContraband"` | `bool` | 设为 `true` 时,顾客绝不购买任何带有违禁品标记的物品(如普通守法市民或休班警员)。 | | `AcceptingContrabandOverride` | `"AcceptingContrabandOverride"` | `bool` | 设为 `true` 时,无视阵营默认限制,强制允许收购违禁品(如黑市佣兵 V)。 | | `chargesContrabandMarkup` | `"ChargesContrabandMarkup"` | `bool` | 卖家向玩家兜售违禁品时,是否额外收取黑市风险溢价。 | | `acceptRetailMarkup` | `"AcceptRetailMarkup"` | `bool` | 买家是否认可玩家用贴标机(`labeler`)贴上的零售溢价标签。 | | `refusesHazardousWaterLabel` | `"RefusesHazardousWaterLabel"` | `bool` | 设为 `true` 时,顾客拒收贴有危险辐射/污染水质警告标签的液体容器。 | --- ## 代码示例:无视违禁品限制的黑市买家 ```csharp var sc = new StoreClient { identifier = "smuggler_buyer", displayName = NpcFrameworkSdk.T("底舱走私客", "Lower-Deck Smuggler"), spriteName = SpriteDict.GetRandomShadySpriteName(), clientFaction = "FACTION_BLACK_MARKET", clientIntent = StoreClient.ClientIntent.BUY, noAcceptingContraband = false, AcceptingContrabandOverride = true, acceptRetailMarkup = false }; ``` ================================================================================ ## subsystems/07-inspection-checks.md ================================================================================ --- layout: doc title: 07. 九项物品瑕疵验货规则 (Checks) --- # 07. 九项物品瑕疵验货规则 (`sc.AddCheck`) 当顾客向玩家购买商品时,可以通过 `sc.AddCheck(string checkName)` 挂载一项或多项瑕疵查验规则。若玩家摆上柜台的商品未通过查验(例如把生锈的手枪卖给佣兵 V,或把过期的血袋卖给猩红教徒),顾客会当场指出问题并压价或拒收。 --- ## 原版九大验货规则常量全表 框架在 `NpcTraitModels.cs` 的 `NpcCheckNames` 静态类中封装了原版全部 9 个验货键名: | `NpcCheckNames` 常量 | 底层字符串值 | 查验的物品瑕疵类型 | | :--- | :--- | :--- | | `NpcCheckNames.Freshness` | `"CHECK_FRESHNESS"` | 查验食品与有机物品的新鲜度,拒收腐败变质食物。 | | `NpcCheckNames.Rust` | `"CHECK_RUST"` | 查验枪械、工具与金属制品表面的铁锈。 | | `NpcCheckNames.Dented` | `"CHECK_DENTED"` | 查验罐头、装甲板或武器外壳是否有凹陷损伤。 | | `NpcCheckNames.Expired` | `"CHECK_EXPIRED"` | 查验医疗针剂、血袋、药丸是否已过保质期。 | | `NpcCheckNames.OpenBox` | `"CHECK_OPEN_BOX"` | 查验盒装商品是否已被拆封。 | | `NpcCheckNames.IngotFlashlight` | `"CHECK_INGOT_FLASHLIGHT"` | 使用紫外/手电照射查验金条与贵金属锭的表面真伪。 | | `NpcCheckNames.IngotDetector` | `"CHECK_INGOT_DETECTOR"` | 使用金属探测仪查验金条内部是否掺假夹芯。 | | `NpcCheckNames.WaterFlashlight` | `"CHECK_WATER_FLASHLIGHT"` | 使用强光照射查验水样/液体容器的浑浊度。 | | `NpcCheckNames.WaterStrip` | `"CHECK_WATER_STRIP"` | 使用化学试纸检测液体酸碱度与污染指标。 | --- ## 代码示例:严查铁锈与凹陷的军火买家 ```csharp sc.clientBuyingTagList.Add("FIREARM"); sc.clientBuyingTagList.Add("WEAPON"); // 挂载双重军火品相验货 sc.AddCheck("CHECK_RUST"); sc.AddCheck("CHECK_DENTED"); ``` ================================================================================ ## subsystems/08-expose-and-chem-grade.md ================================================================================ --- layout: doc title: 08. 假货识破能力与化学纯度门槛 --- # 08. 假货识破能力与化学纯度门槛 (`NpcExposePreset`) 当玩家使用伪造印章、假冒防伪标或劣质掺水药剂糊弄顾客时,游戏通过 `sc.canClientExposeFeature` 委托、`sc.CanExposeChem` 与 `sc.acceptedChemicalProductGrade` 判断顾客能否当场识破。 --- ## 十档识破能力预设(`NpcExposePreset`) | 枚举值 | 映射的原版 `ClientCanExposeFunc` 方法 | 适用顾客画像 | | :--- | :--- | :--- | | `None (0)` | 无额外委托 | 毫无防备的普通路人 | | `Basic (1)` | `BasicClientExposeCapacity` | 基础市民眼力 | | `Scav (2)` | `ScavClientExposeCapacity` | 熟悉废旧零件与工具的拾荒客 | | `LowerLevel (3)` | `LLClientExposeCapacity` | 下层区常住居民 | | `Security (4)` | `SecClientExposeCapacity` | 治安部警员,严查假证与违禁伪装 | | `Revolution (5)` | `RevClientExposeCapacity` | 革命军采购员,精通军火与医疗物资 | | `Tourist (6)` | `TouristClientExposeCapacity` | 外星游客,注重外包装 | | `UpperLevel (7)` | `ULClientExposeCapacity` | 上层区精英,眼光挑剔 | | `TradeBoard (8)` | `TradeBoardExposeCapacity` | 交易所专业买手 | | `Odin (9)` | `OdinExposeCapacity` | 奥丁级专家眼力 | | `All (10)` | `ALLExposeCapacity` | 100% 识破一切伪造特征 | --- ## 化学药剂纯度门槛 - `sc.CanExposeChem = true`:允许顾客检测化学药剂/粉末是否掺假; - `sc.acceptedChemicalProductGrade = 2`:设置顾客可接受的最低化学纯度等级(`0..3`)。 ```csharp NpcFrameworkSdk.ApplyClientProfile(sc, new Dictionary { ["ExposePreset"] = (int)CustomNPCFramework.NpcExposePreset.Revolution, ["CanExposeChem"] = true, ["AcceptedChemicalGrade"] = 2 }); ``` ================================================================================ ## subsystems/09-realtime-scale-and-counter.md ================================================================================ --- layout: doc title: 09. 电子秤、柜台与展示柜实时回调 --- # 09. 电子秤、柜台与展示柜实时回调 `StoreClient` 内置了 6 个物品操作实时委托与成瘾者催促机制,允许顾客在玩家把物品放上电子秤、摆上柜台或完成单件买卖的瞬间触发即时气泡反馈。 --- ## 六大实时委托字段 | 委托字段 | 签名类型 | 触发时机 | | :--- | :--- | :--- | | `sc.onItemAddedToWeighted` | `Action` | 玩家将散装药粉或物品放到电子秤托盘上称重时触发。 | | `sc.onItemRemovedToWeighted` | `Action` | 玩家将物品从电子秤托盘移开时触发。 | | `sc.onItemAddedToCounters` | `Action` | 玩家将物品放置到柜台交易区域时触发。 | | `sc.OnItemAddedToShowcase` | `Action` | 玩家将物品放入展示柜时触发。 | | `sc.onItemSold` | `Action` | 玩家向该顾客成功售出一件物品时触发(参数为物品与成交额)。 | | `sc.onItemBought` | `Action` | 玩家从该顾客手中成功购入一件物品时触发。 | --- ## 代码示例:电子秤称重实时插话与催促对话 选自 `RestoredUnusedNPCs` 中的戒断成瘾者(`addictGeneralTrailer`): ```csharp sc.IsClientAddict = true; sc.CanReturn = true; sc.CanReturnAsBuyer = true; // 当玩家把毒品/化学物质放上电子秤时立即插话 sc.onItemAddedToWeighted = item => { if (item != null && (item.IsTag("SUBSTANCE") || item.IsTag("NARCOTIC"))) { var d = new Dialogue().SetText(sc.displayName, NpcFrameworkSdk.T("对对对!就是这个劲儿!手别抖,多倒点!", "That's the stuff! Pour it on!")); DialogUIManager.Instance?.StartDialogue(d, false); } }; // 当玩家迟迟不放货时的催促台词 sc.repeatDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("求你了老板,我骨头缝都在发痒,快给我一点吧!", "Come on, I'm itching all over. Just give me a hit!")); ``` ================================================================================ ## subsystems/10-procurement-contracts.md ================================================================================ --- layout: doc title: 10. 跨日期货预定委托单 (Procurement) --- # 10. 跨日期货预定委托单 (`AttachProcurementOffer`) 期货预定委托(`ClientIntent.PROCUREMENT_OFFER` 与 `PROCUREMENT_COLLECT`)允许顾客在首次进店时向玩家预订一件稀缺物品:顾客当场支付一笔定金(`initialAdvanceCash`),并在柜台上留下一张实体预定凭条(`procurement_slip`);经过 `dueInDays` 天后,系统会在到期日自动安排该顾客再次进店取货并支付高额尾款(`finalRewardCash`)。 --- ## SDK 方法签名与底层实现 ```csharp public static void AttachProcurementOffer( StoreClient client, string clientName, string offerDescription, string collectDescription, int dueInDays, int initialAdvanceCash, int finalRewardCash, Func itemValidator) ``` 底层 `NpcFullFeatureKit.AttachProcurementOffer` 会将 `client.clientIntent` 设为 `ClientIntent.PROCUREMENT_OFFER`,并构造原版 `ProcurementData` 对象挂载到 `client.procurementData`。 --- ## 代码示例:3 天期军用义体芯片预定单 ```csharp private static StoreClient CreateChipProcurementClient() { var sc = new StoreClient { identifier = "cyber_surgeon_procure", displayName = NpcFrameworkSdk.T("高阶义体外科主任", "Senior Cyber-Surgeon"), spriteName = SpriteDict.GetRandomMedSpriteName(), clientFaction = "FACTION_UPPER_LEVEL" }; NpcFrameworkSdk.AttachProcurementOffer( client: sc, clientName: sc.displayName, offerDescription: NpcFrameworkSdk.T("3 天后我有一台针对上层区议员的神经重构手术,急需一枚原型义体芯片。先付你 100 信用点定金,到期备好货我再付你 450 尾款。", "I need an Augmentation Chip in 3 days for a surgery. Here is 100 credits upfront and 450 upon collection."), collectDescription: NpcFrameworkSdk.T("手术时间到了,我预订的义体芯片备齐了吗?", "It's time for the operation. Do you have the Augmentation Chip we agreed on?"), dueInDays: 3, initialAdvanceCash: 100, finalRewardCash: 450, itemValidator: item => item != null && item.itemID == "aug_chip" ); sc.CompleteClientCreation(false); return sc; } ``` ================================================================================ ## subsystems/11-custom-gun-orders.md ================================================================================ --- layout: doc title: 11. 定制枪械改装委托单 (GunOrder) --- # 11. 定制枪械改装委托单 (`BuildCustomGunOrder`) 《深空当铺:可能是偷的》内置了完整的枪械零件拆装与属性评估系统(`GunOrderData`)。当顾客的 `clientIntent = StoreClient.ClientIntent.GUNSMITH` 时,可通过 `NpcFrameworkSdk.BuildCustomGunOrder` 构建包含 **必修指标(`mandatoryRequirements`)** 与 **加分指标(`bonusRequirements`)** 的定制改枪委托单。 --- ## SDK 方法签名与 18 项枪械属性标签 ```csharp public static GunOrderData BuildCustomGunOrder( int tier, int baseReward, string dialogText, bool isBestOrder, IList<(string statTag, int minVal, int bonusReward, bool isMandatory)> requirements) ``` ### 支持的枪械属性标签(`statTag`) - `"GUN_CALIBER_TAG"`:口径要求 - `"GUN_SUPPRESSED_TAG"`:是否安装消音器(`minVal = 1` 表示要求消音) - `"GUN_FIREPOWER_TAG"` / `"GUN_CURRENT_FIREPOWER_TAG"`:火力值 - `"GUN_ACCURACY_TAG"` / `"GUN_CURRENT_ACCURACY_TAG"`:精准度 - `"GUN_RELIABILITY_TAG"` / `"GUN_CURRENT_RELIABILITY_TAG"`:可靠性 - `"GUN_ERGONOMICS_TAG"` / `"GUN_CURRENT_ERGONOMICS_TAG"`:人机工效 - `"GUN_RECOIL_TAG"` / `"GUN_CURRENT_RECOIL_TAG"`:后坐力控制 - `"GUN_REPAIRBILITY_TAG"` / `"GUN_CURRENT_REPAIRBILITY_TAG"`:可维修性 - `"GUN_STYLE_TAG"` / `"GUN_CURRENT_STYLE_TAG"`:外观风格 - `"GUN_FRAME_TAG"` / `"GUN_SIZE_TAG"`:枪身框架与尺寸 --- ## 代码示例:消音高精准度暗杀手枪委托 ```csharp private static StoreClient CreateGunsmithClient() { var sc = new StoreClient { identifier = "hitman_gunsmith", displayName = NpcFrameworkSdk.T("契约杀手", "Contract Hitman"), spriteName = SpriteDict.GetRandomMercSpriteName(), clientFaction = "FACTION_BLACK_MARKET", clientIntent = StoreClient.ClientIntent.GUNSMITH }; sc.gunOrderData = NpcFrameworkSdk.BuildCustomGunOrder( tier: 2, baseReward: 380, dialogText: NpcFrameworkSdk.T("帮我改一把带消音器、高火力且精准可靠的潜行武器。", "Build me a suppressed, high-firepower sidearm with clean accuracy."), isBestOrder: true, requirements: new List<(string statTag, int minVal, int bonusReward, bool isMandatory)> { ("GUN_SUPPRESSED_TAG", 1, 80, true), // 必修:消音器 (+80) ("GUN_FIREPOWER_TAG", 45, 100, true), // 必修:火力 >= 45 (+100) ("GUN_ACCURACY_TAG", 60, 120, false), // 加分项:精准度 >= 60 (+120) ("GUN_RELIABILITY_TAG", 70, 90, false) // 加分项:可靠性 >= 70 (+90) } ); sc.CompleteClientCreation(false); return sc; } ``` ================================================================================ ## subsystems/12-handnotes-and-papers.md ================================================================================ --- layout: doc title: 12. 实体手写便条与打印文档投递 --- # 12. 实体手写便条与打印文档投递 (`GiveHandnoteToPlayer`) 本子系统封装了游戏原生的 `PreBuiltItemHelper.CreateHandnote` 与 `CreatePaperWithText`,允许 NPC 在剧情对话或结算时向玩家投递可收纳进背包、可随时点击展开阅读的实体手写便条或打印纸张(如 `CyberpunkMercV` 第 4 幕投递的《V 的加密便条》)。 --- ## 四个核心 SDK 方法 | 方法签名 | 返回值 | 说明 | | :--- | :--- | :--- | | `CreateHandnoteItem(string title, string body, string signature, int fontIndex = 0)` | `GameItem` | 创建一张带有标题、正文、手写署名与指定手写字体(`fontIndex: 0..2`)的便条物品实例。 | | `CreatePaperNoteItem(string title, string body)` | `GameItem` | 创建一张标准打印文档纸张物品实例。 | | `SpawnItemOnCounterOrStore(GameItem item, bool isStolen = false, bool isContraband = false)` | `bool` | 若当前柜台前有顾客,则将物品直接滑出到柜台桌面上;否则自动存入玩家店铺后仓网格(`GraphUtils.EmporiumTryAdd`)。 | | `GiveHandnoteToPlayer(string title, string body, string signature, int fontIndex = 0)` | `bool` | 一步完成手写便条创建与柜台/后仓投递。 | --- ## 代码示例:投递带全息电话号码的加密手写便条 ```csharp NpcFrameworkSdk.GiveHandnoteToPlayer( title: NpcFrameworkSdk.T("V 的加密便条", "V's Encrypted Note"), body: NpcFrameworkSdk.T( "铁子,大恩不言谢。帮我引开那帮企业特勤狗,算我欠你一条命。 我的私人全息通讯号是:2077077 以后店里缺硬货或者想出手大件,随时通过店内电话打给我。", "Preem work covering for me against those corpo hounds, choom. I owe you my life. My private holophone number is: 2077077 Whenever you need high-end loot or want to move big gear, ring me on the store phone."), signature: "V (Vincent)", fontIndex: 1 ); ``` ================================================================================ ## subsystems/13-store-request-board.md ================================================================================ --- layout: doc title: 13. 店铺终端委托板悬赏 (StoreRequest) --- # 13. 店铺终端委托板悬赏 (`PostStoreRequest`) 玩家店铺电脑终端中设有一个 **委托悬赏面板(Requests)**。通过 `NpcFrameworkSdk.PostStoreRequest`,任何自定义 NPC 都可以在剧情推进后向玩家终端发布限时物资悬赏单,玩家在期限内提交指定数量的物品即可领取高额信用点与阵营声望奖励。 --- ## SDK 方法签名与参数说明 ```csharp public static bool PostStoreRequest( string id, // 委托单唯一 ID string title, // 终端面板显示的悬赏标题 string description, // 悬赏详情描述文本 string requesterName, // 发布人署名(如 "V (Vincent)") string factionId, // 关联阵营 ID(如 "FACTION_BLACK_MARKET") string requiredItemId, // 要求提交的物品 ID(如 "aug_chip") int requiredCount = 1, // 要求提交的数量 int durationDays = 5, // 悬赏持续有效天数 int creditReward = 200,// 完成后发放的信用点报酬 int reputationReward = 10, // 完成后增加的对应阵营声望 bool force = true) // 是否强制立即激活(调用 StoreRequest.ActivateRequest) ``` --- ## 代码示例:发布 450 信用点义体芯片悬赏 ```csharp NpcFrameworkSdk.PostStoreRequest( id: "v_afterlife_chip_req", title: NpcFrameworkSdk.T("来生佣兵义体芯片悬赏", "Afterlife Merc Aug Chip Bounty"), description: NpcFrameworkSdk.T("V 需要额外的原型义体芯片用于修复神经突触,报酬丰厚。", "V needs an extra Augmentation Chip for neural calibration. Pays top credit."), requesterName: "V (Vincent)", factionId: "FACTION_BLACK_MARKET", requiredItemId: "aug_chip", requiredCount: 1, durationDays: 6, creditReward: 450, reputationReward: 15, force: true ); ``` ================================================================================ ## subsystems/14-holophone-contacts.md ================================================================================ --- layout: doc title: 14. 全息电话簿联系人与拨号召唤 --- # 14. 全息电话簿联系人与拨号召唤 (`RegisterPhoneContact`) 玩家柜台右侧的全息电话机允许拨打 7 位通讯号码并触发专属通话对话树。`NpcPhoneRegistry.cs` 封装了 `PhoneClientList.DialogFuncs` 与 `PlayerStore.Instance.PhoneClientDict` 的完整绑定流程。 --- ## SDK 方法签名与防穿帮别名机制 ```csharp public static void RegisterPhoneContact( long number, // 7 位电话号码,如 2077077L string dialogFuncId, // 唯一对话函数键名 Func displayNameGetter, // 电话簿列表显示的名称委托 int cooldownDays, // 每次拨号使用服务后的冷却天数 Func isUnlockedPredicate, // 解锁条件谓词(返回 true 时自动出现在玩家电话簿中) Func callDialogFactory, // 拨通时的对话树生成函数 params string[] clientAliases) // 关联的顾客 identifier 列表(若该顾客当前已在店门口,拨号会自动提示本人在场) ``` --- ## 代码示例:拨打 `2077077` 随时召唤传奇佣兵 V 进店 ```csharp public const long VPhoneNumber = 2077077L; NpcFrameworkSdk.RegisterPhoneContact( number: VPhoneNumber, dialogFuncId: "CyberpunkMercV_Call", displayNameGetter: () => NpcFrameworkSdk.T("传奇佣兵 V (2077077)", "V - Afterlife Merc (2077077)"), cooldownDays: 3, isUnlockedPredicate: () => NpcFrameworkSdk.GetSaveInt("v_stage", 0) == 4, callDialogFactory: CreateVPhoneDialogue, clientAliases: new[] { "v", "v_act1_relic", "v_act2_gun_order", "v_act3_heist", "v_recurring_merc" } ); private static Dialogue CreateVPhoneDialogue(StorePhoneClient phoneClient) { string vName = NpcFrameworkSdk.T("传奇佣兵 V", "V (Afterlife Merc)"); var root = new Dialogue().SetText(vName, NpcFrameworkSdk.T("喂?是我,V。有什么大买卖找我?", "Yo, it's V. Got a gig or need a drop?")); var dlgSummon = new Dialogue().SetText("PLAYER", NpcFrameworkSdk.T("[呼叫 V 进店交易] 现在方便来店里一趟吗?", "[Call V to Store] Can you swing by the shop right now?")); root.AddChoice(DirectoryMaster.Item("$", true), "", "", dlgSummon, () => { phoneClient?.UseService(); // 进入 3 天冷却 NpcFrameworkSdk.SummonNpcNow("v_recurring_merc"); // 立即排入队首并自动唤入店门 dlgSummon.NextDialogue().SetText(vName, NpcFrameworkSdk.T("没问题,这就骑草薙摩托过去,下一声门铃见!", "You got it, choom. I'll be at your counter on the next bell!")); }, null); return root; } ``` ================================================================================ ## subsystems/15-interrogation-and-optics.md ================================================================================ --- layout: doc title: 15. 盘问对话、透视目镜扫描与特殊气泡 --- # 15. 盘问对话、透视目镜扫描与特殊气泡 除了主对话树 `mainDialogue` 外,每位顾客还支持挂载 **盘问对话(`interogationDialogue`)**、**透视目镜扫描对话(`glasseDialogue`)**、**对质后恢复对话(`resumeAfterConfrontDialogue`)** 以及 **暗黑气泡皮肤(`bubbleColor`)**。 --- ## 核心字段与用法 | `StoreClient` 字段 | 类型 | 说明 | | :--- | :--- | :--- | | `sc.interogationDialogue` | `Dialogue` | 当玩家点击对话界面上的“盘问”按钮时触发,用于展开角色背景故事或提供交易线索。 | | `sc.glasseDialogue` | `Dialogue` | 当玩家开启透视扫描目镜观察该顾客时触发(说话人通常设为 `"PLAYER"`,描写目镜扫描到的义体、武器或意识体残影)。 | | `sc.resumeAfterConfrontDialogue` | `Dialogue` | 玩家与顾客当面对质后恢复交易流程时的衔接对话。 | | `sc.bubbleColor` | `string` | 设为 `"dark"` 时启用深色神秘学对话气泡(如 `RestoredUnusedNPCs` 中的猩红教徒 `cultistTrailer`)。 | --- ## 代码示例:强尼·银手透视目镜扫描彩蛋与暗黑气泡 ```csharp // 1. 盘问背景故事 sc.interogationDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("从夜之城一路逃到这鬼空间站,原以为能甩掉荒坂和帕斯泰尔的追兵。", "Thought laying low on this rustbucket station would get Arasaka and Pastel off my tail.")) .NextDialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("结果真正要命的是插在我后颈里的这块原型生物芯片。", "Turns out the real killer is the prototype biochip slotted in my neck.")); // 2. 透视目镜扫描彩蛋 sc.glasseDialogue = new Dialogue() .SetText("PLAYER", NpcFrameworkSdk.T("(你的目镜扫过他颈后的芯片插槽,电火花闪烁间,扫描仪上竟闪过一行诡异的意识体残影:)", "(Your optics scan the neural socket at his neck; amid sparks, a phantom engram signature flashes across your lens:)")) .NextDialogue() .SetText("PLAYER", NpcFrameworkSdk.T("(“醒醒,武侍……把这群企业狗杂碎全烧成灰……”)", "('Wake the hell up, Samurai... We have a station to burn...')")); ``` ================================================================================ ## subsystems/16-wanted-arrest-and-security.md ================================================================================ --- layout: doc title: 16. 通缉悬赏、治安官逮捕与盘查事件 --- # 16. 通缉悬赏、治安官逮捕演出与盘查事件 本子系统涵盖两大警务交互机制:**把顾客设为可抓捕的通缉犯(`SetWanted` + `customOnArrestDialogue`)**,以及 **制作不可打发、不可枪击的治安官/内务官上门盘查事件(`ClientIntent.DIALOGUE` + `CompleteSecClient`)**。 --- ## 1. 通缉悬赏与自定义逮捕演出 调用 `sc.SetWanted(int bountyCash, string wantedName, bool isWanted = true)` 后,玩家可以在交易途中按下柜台下的报警按钮召唤治安官抓捕该顾客并领取赏金。 > **关键规则**:自定义 `sc.customOnArrestDialogue` 的最后一句话必须在 `SetEndAction` 中调用 `StoreUIManager.Instance?.OnArrestDialoguePlayed()`,否则逮捕过场动画会停留在原地等待。 ```csharp sc.SetWanted(120, "Vincent (V)", true); sc.customOnArrestDialogue = new Dialogue() .SetText("CLIENT", NpcFrameworkSdk.T("靠,你跟德克斯特那肥猪一样背后捅刀子?!", "Damn it, you're just another backstabbing fixer like Dex?!")) .NextDialogue() .SetText("SEC", NpcFrameworkSdk.T("发现目标!启动斯安威斯坦抑制器,压制他!", "Target located! Activate Sandevistan dampeners and pin him down!")) .SetEndAction(() => { NpcFrameworkSdk.SetSaveInt("v_stage", 5); StoreUIManager.Instance?.OnArrestDialoguePlayed(); }); ``` --- ## 2. 治安官 / 企业特勤上门盘查事件 当制作类似 `billy3Officier`(内务部调查官)或 `v_act3_corpo_sec`(企业特勤追缉官)的纯剧情盘查事件时: 1. 设置 `clientIntent = StoreClient.ClientIntent.DIALOGUE`(枚举值 `5`); 2. 设置 `nonShootable = true, dismissable = false`(禁止玩家开枪击杀或按门铃逃避盘查); 3. 在 `sc.CompleteClientCreation(false)` 之后紧接着调用 `sc.CompleteSecClient()`。 ```csharp var sc = new StoreClient { identifier = "v_act3_corpo_sec", displayName = NpcFrameworkSdk.T("企业特勤追缉官", "Corpo Spec-Ops Investigator"), spriteName = SpriteDict.GetRandomSecCorpoSpriteName(), clientFaction = "FACTION_SECURITY", clientIntent = StoreClient.ClientIntent.DIALOGUE, nonShootable = true, dismissable = false }; // ... 挂载 AddChoice 盘查分支 ... sc.CompleteClientCreation(false); sc.CompleteSecClient(); ``` ================================================================================ ## subsystems/17-newspaper-headlines.md ================================================================================ --- layout: doc title: 17. 次日早报头条新闻 (TriggerNews) --- # 17. 次日早报头条新闻 (`TriggerNews`) 每天早晨玩家拉开店铺卷帘门时,游戏会在柜台上投递一份当日早报(`newspaper`)。通过 `NpcFrameworkSdk.TriggerNews`,你可以在玩家做出关键剧情抉择(如举报或掩护某个 NPC)后向 `StoreStation.Instance.storeEventManager` 注入一条自定义 `StoreEvent`,使次日早报头版刊登你编写的标题与新闻正文。 --- ## SDK 方法签名 ```csharp public static void TriggerNews( string id, // 新闻事件唯一 ID string headline, // 报纸头版大标题 string body, // 报纸新闻正文内容 int durationDays = 1) // 事件持续有效天数 ``` --- ## 代码示例:根据玩家抉择触发不同早报头条 ```csharp // 结局 A:玩家替 V 隐瞒行踪 NpcFrameworkSdk.TriggerNews( id: "v_heist_legend_news", headline: NpcFrameworkSdk.T("独狼佣兵洗劫企业实验室后全身而退", "Solo Mercenary Escapes After Corporate Lab Raid"), body: NpcFrameworkSdk.T("上层区企业特勤队昨日在下层区搜捕无果。代号 V 的神秘佣兵携带原型科技人间蒸发,成为下层区最新传奇。", "Corporate Spec-Ops came up empty-handed in the Lower Levels yesterday as the solo mercenary known as 'V' vanished with prototype tech."), durationDays: 2 ); // 结局 B:玩家向特勤队出卖 V NpcFrameworkSdk.TriggerNews( id: "v_captured_news", headline: NpcFrameworkSdk.T("旧通风井爆发激烈交火,重金悬赏佣兵突围失踪", "Fierce Firefight in Old Ventilation Sector"), body: NpcFrameworkSdk.T("根据匿名店主线报,企业特勤队昨晚包围了旧通风井安全屋。目标佣兵在引爆EMP后带伤突围,但此后再未在下层区露面。", "Acting on an anonymous tip, Corporate Spec-Ops raided a safehouse in the ventilation sector."), durationDays: 2 ); ``` ================================================================================ ## subsystems/18-afterhour-and-nightly-hooks.md ================================================================================ --- layout: doc title: 18. 夜间垃圾场事件与入睡结算钩子 --- # 18. 夜间垃圾场事件与入睡结算钩子 打烊后,玩家可以前往夜间地图节点(如垃圾场 `"dumping_ground"`)搜刮物资,最后回到床铺入睡进入下一天。本子系统提供三个接口,用于注册自定义夜间地点事件、监听玩家从垃圾场带回的战利品以及执行每日入睡前结算。 --- ## 三个核心 SDK 方法 ### 1. `RegisterAfterhourEvent`(注册夜间地点随机事件) ```csharp public static bool RegisterAfterhourEvent( string id, string locationId, // 目标夜间地点 ID,如 "dumping_ground" Func titleGetter, Func descriptionGetter, int durationDays = 2, float dailyChancePercent = 25f, bool closesLocation = false, // 是否封锁该夜间地点 Func canStartPredicate = null, Action onStart = null, Action onEnd = null) ``` ### 2. `RegisterDumpingGroundWatcher`(监听夜间搜刮归来背包) 挂载在 `ModHook.OnAfterhourLeaveEarly`,当玩家离开垃圾场返回店铺时,将地面/临时搜刮背包 `GameInventory` 传给回调函数。 ### 3. `RegisterNightlyHook`(注册夜晚入睡前结算钩子) 挂载在 `ModHook.OnGoingSleepEarly`,当玩家点击床铺入睡时触发。 --- ## 代码示例:注册垃圾场无人机坠毁事件与夜间结算 ```csharp NpcFrameworkSdk.RegisterAfterhourEvent( id: "corpo_drone_wreckage", locationId: "dumping_ground", titleGetter: () => NpcFrameworkSdk.T("坠毁的企业货运无人机", "Crashed Corporate Cargo Drone"), descriptionGetter: () => NpcFrameworkSdk.T("垃圾场深处有一架冒着电火花的帕斯泰尔无人机残骸。", "A sparking Pastel cargo drone lies half-buried in the scrap."), durationDays: 2, dailyChancePercent: 25f, closesLocation: false, canStartPredicate: () => NpcFrameworkSdk.GetSaveInt("v_stage", 0) >= 2, onStart: () => NpcFrameworkSdk.SetSaveBool("drone_event_active", true), onEnd: () => NpcFrameworkSdk.SetSaveBool("drone_event_active", false) ); NpcFrameworkSdk.RegisterNightlyHook(() => { NpcFrameworkSdk.AddSaveInt("nights_survived", 1, 0); }); ``` ================================================================================ ## api/sdk-reference.md ================================================================================ --- layout: doc title: 4.1 NpcFrameworkSdk 全量方法参考 --- # 4.1 `NpcFrameworkSdk` 全量方法参考手册 `NpcFrameworkSdk` 是扩展模组与底座框架 `CustomNPCFramework` 通信的唯一入口类。只需将单文件 `NpcFrameworkSdk.cs` 放入你的模组源码目录,即可零程序集引用调用以下全部静态属性与方法。 --- ## 1. 语言本地化与辅助属性 | 属性 / 方法签名 | 返回类型 | 详细说明 | | :--- | :--- | :--- | | `NpcFrameworkSdk.IsChinese` | `bool` | 读取 `CustomNPCFramework` 的语言设置(自动跟随游戏语言 `LocHelper.GetCurrentLocaleCode()` 或玩家手动指定的简中/英文),当前应显示中文时返回 `true`。 | | `NpcFrameworkSdk.T(string zh, string en)` | `string` | 双语文本内联选择器,等价于 `IsChinese ? zh : en`。建议在所有 `displayName`、`Dialogue` 台词与 `ModConfig` 标签中使用。 | | `NpcFrameworkSdk.ResolveSprite(string spriteName)` | `string` | 检查 `spriteName` 是否已在 `SpriteDict.Instance.spriteDictionary` 中注册;若未找到则查询内置回退映射(`"billy"`→`"trailer_scav1"`, `"cul1"`→`"spy"`, `"sha3"`→`"trailer_scav3"`)。 | --- ## 2. NPC 注册与即时召唤方法 ### `RegisterNpc` ```csharp public static void RegisterNpc( string id, Func displayNameGetter, int spawnPhase, int priority, int minDay, int cooldownDays, int spawnChancePercent, bool oncePerSave, Func canSpawnPredicate, Func clientFactory, Action onSpawned = null, int maxDay = 9999, string requiredNotArrestedId = null) ``` - **功能**:注册自定义 NPC 条目。若框架尚未加载,自动进入 `PendingQueue.v1` 挂起队列等待框架消费;若框架已加载,立即写入 `NpcFrameworkRegistry` 并刷新开发者调试面板下拉菜单。 ### `SummonNpcNow` ```csharp public static bool SummonNpcNow(string id) ``` - **功能**:立即将 `id` 对应的 NPC 强制置顶到 `clientStack[0]`。 - **返回值**:若当前店铺处于营业状态(`StoreState.OPEN`)且成功置顶(当柜台前无人时还会自动触发 `TryCallNextClient()` 让其直接走进店门),返回 `true`;若当前处于主菜单或早晨尚未拉起卷帘门,则将其写入 `PendingDebugSummonId` 挂起槽(待卷帘门拉开时自动排在第一位进门),返回 `false`。 --- ## 3. 跨日剧情存档状态机方法(Save State API) 所有键名均自动附加 `"cnpcf_"` 前缀并存入 `PlayerStore.Instance.ModData()`: ```csharp // 整型状态读写与累加(最常用于管理剧情阶段 stage、好感度 trust、分支标记) public static int GetSaveInt(string key, int defaultValue = 0); public static void SetSaveInt(string key, int value); public static int AddSaveInt(string key, int delta, int defaultValue = 0); // 布尔状态读写 public static bool GetSaveBool(string key, bool defaultValue = false); public static void SetSaveBool(string key, bool value); // 字符串状态读写 public static string GetSaveString(string key, string defaultValue = ""); public static void SetSaveString(string key, string value); ``` --- ## 4. 全息电话簿注册与同步方法 ```csharp public static void RegisterPhoneContact( long number, string dialogFuncId, Func displayNameGetter, int cooldownDays, Func isUnlockedPredicate, Func callDialogFactory, params string[] clientAliases); public static void SyncPhoneContacts(); ``` --- ## 5. 顾客塑造子系统扩展工具箱方法 ```csharp // 1. 声明式批量设置 StoreClient 的 46 项属性 public static void ApplyClientProfile(StoreClient client, Dictionary profile); // 2. 实体手写便条与打印纸张生成/投递 public static GameItem CreateHandnoteItem(string title, string body, string signature, int fontIndex = 0); public static GameItem CreatePaperNoteItem(string title, string body); public static bool SpawnItemOnCounterOrStore(GameItem item, bool isStolen = false, bool isContraband = false); public static bool GiveHandnoteToPlayer(string title, string body, string signature, int fontIndex = 0); // 3. 店铺电脑终端委托板悬赏激活 public static bool PostStoreRequest( string id, string title, string description, string requesterName, string factionId, string requiredItemId, int requiredCount = 1, int durationDays = 5, int creditReward = 200, int reputationReward = 10, bool force = true); // 4. 期货预定委托单挂载 public static void AttachProcurementOffer( StoreClient client, string clientName, string offerDescription, string collectDescription, int dueInDays, int initialAdvanceCash, int finalRewardCash, Func itemValidator); // 5. 定制枪械改装订单构建 public static GunOrderData BuildCustomGunOrder( int tier, int baseReward, string dialogText, bool isBestOrder, IList<(string statTag, int minVal, int bonusReward, bool isMandatory)> requirements); // 6. 隔日早报头条新闻激活 public static void TriggerNews(string id, string headline, string body, int durationDays = 1); // 7. 夜间地点事件与钩子注册 public static bool RegisterAfterhourEvent( string id, string locationId, Func titleGetter, Func descriptionGetter, int durationDays = 2, float dailyChancePercent = 25f, bool closesLocation = false, Func canStartPredicate = null, Action onStart = null, Action onEnd = null); public static void RegisterNightlyHook(Action hook); public static void RegisterDumpingGroundWatcher(Action watcher); ``` ================================================================================ ## api/profile-dictionary.md ================================================================================ --- layout: doc title: 4.2 ApplyClientProfile 46 项属性字典表 --- # 4.2 `ApplyClientProfile` 46 项声明式属性字典完整映射表 `NpcFullFeatureKit.ApplyClientProfile(StoreClient sc, Dictionary profile)` 支持通过字典一次性声明式配置 `StoreClient` 的全部 46 项核心字段、列表、委托与对话树。以下是源码级 1:1 映射详表: | 序号 | 字典键名 (`Key`) | 期望值类型 (`Type`) | 映射的 `StoreClient` 底层字段 / 调用方法 | | :--- | :--- | :--- | :--- | | 1 | `"DisplayName"` | `string` | `sc.displayName = val` | | 2 | `"SpriteName"` | `string` | `sc.spriteName = NpcTraitHelper.ResolveValidSpriteName(val)` | | 3 | `"PossibleSprites"` | `IEnumerable` | 遍历加入 `sc.possibleSprites` | | 4 | `"Faction"` | `string` | `sc.clientFaction = val` | | 5 | `"BubbleColor"` | `string` | `sc.bubbleColor = val`(如 `"dark"`) | | 6 | `"ClientIntent"` | `int` | `sc.clientIntent = (StoreClient.ClientIntent)val` | | 7 | `"Budget"` | `int` | `sc.SetBudget(val)` | | 8 | `"UseClientBudget"` | `bool` | `sc.useClientBudget = val` | | 9 | `"BuyPriceModifier"` | `int` | `sc.buyPriceModifier = val` | | 10 | `"SellPriceModifier"` | `int` | `sc.sellPriceModifier = val` | | 11 | `"IsOfferWholesale"` | `bool` | `sc.isOfferWholesale = val` | | 12 | `"WholesaleDiscount"` | `int` | `sc.wholesaleDiscount = val` | | 13 | `"RequireVariety"` | `bool` | 若为 `true` 则调用 `sc.SetVariety()` | | 14 | `"NoAcceptingContraband"` | `bool` | `sc.noAcceptingContraband = val` | | 15 | `"AcceptingContrabandOverride"` | `bool` | `sc.AcceptingContrabandOverride = val` | | 16 | `"ChargesContrabandMarkup"` | `bool` | `sc.chargesContrabandMarkup = val` | | 17 | `"AcceptRetailMarkup"` | `bool` | `sc.acceptRetailMarkup = val` | | 18 | `"RefusesHazardousWaterLabel"` | `bool` | `sc.refusesHazardousWaterLabel = val` | | 19 | `"PerfumeInfluence"` | `int` | `sc.perfumeInfluence = val` | | 20 | `"ClientImpatience"` | `int` | `sc.clientImpatience = val` | | 21 | `"AlwaysRejectBadBargain"` | `bool` | `sc.alwaysRejectBadBargain = val` | | 22 | `"IsBargainAvailable"` | `bool` | `sc.isBargainAvailable = val` | | 23 | `"StaysAfterFailedBargain"` | `bool` | `sc.staysAfterFailedBargain = val` | | 24 | `"Dismissable"` | `bool` | `sc.dismissable = val` | | 25 | `"Arrestable"` | `bool` | `sc.arrestable = val` | | 26 | `"NonShootable"` | `bool` | `sc.nonShootable = val` | | 27 | `"IsSecurity"` | `bool` | `sc.isSecurity = val` | | 28 | `"IsLazyInspector"` | `bool` | `sc.isLazyInspector = val` | | 29 | `"IsNoContributeToEvidence"` | `bool` | `sc.isNoContributeToEvidence = val` | | 30 | `"IsAug"` | `bool` | `sc.isAug = val`(注意:仅敌对伪装怪物设 `true`) | | 31 | `"AugTier"` | `int` | `sc.augTier = val` | | 32 | `"AugIdleTell"` | `int` | `sc.augIdleTell = (StoreClient.AugIdleTell)val` | | 33 | `"MakeDisguisedAugTier"` | `int` | 调用 `AugHelper.MakeDisguisedAug(sc, val)` | | 34 | `"CanExposeChem"` | `bool` | `sc.CanExposeChem = val` | | 35 | `"AcceptedChemicalGrade"` | `int` | `sc.acceptedChemicalProductGrade = val` | | 36 | `"ExposePreset"` | `int` | 调用 `NpcTraitHelper.ApplyExposePreset(...)` | | 37 | `"CanReturn"` / `"CanReturnAsBuyer"` | `bool` | `sc.CanReturn = val` / `sc.CanReturnAsBuyer = val` | | 38 | `"AlwaysFeedback"` | `bool` | `sc.alwaysFeedback = val` | | 39 | `"IsClientAddict"` | `bool` | `sc.IsClientAddict = val` | | 40 | `"TradeReputationMultiplier"` | `double` | `sc.tradeReputationMultiplier = val` | | 41 | `"BuyingTags"` / `"BuyingIds"` | `IEnumerable` | 加入 `clientBuyingTagList` / `clientBuyingIdList` | | 42 | `"BlackTags"` / `"BlackIds"` | `IEnumerable` | 加入 `clientBlackTagList` / `clientBlackIdList` | | 43 | `"InspectionChecks"` | `IEnumerable` | 遍历调用 `sc.AddCheck(c)` | | 44 | `"OnArrival"` / `"OnDismiss"` / `"OnDealAccepted"` | `Action` | 绑定进离店与成交回调 | | 45 | `"OnItemAddedToWeighted"` / `"OnItemSold"` / `"OnItemBought"` | `Action<...>` | 绑定天平与买卖实时回调 | | 46 | `"InterrogationDialogue"` / `"GlassesDialogue"` / `"CustomOnArrestDialogue"` / `"RepeatDialogue"` | `Dialogue` | 绑定盘问、目镜、逮捕与重复催促对话 | ================================================================================ ## api/vanilla-classes.md ================================================================================ --- layout: doc title: 4.3 原版 StoreClient / Dialogue 核心类速查 --- # 4.3 游戏原版 `StoreClient` / `Dialogue` / `PlayerStore` 核心类速查 本节整理自《深空当铺:可能是偷的》`Assembly-CSharp.dll` 的反编译签名,列出编写自定义 NPC 时直接交互的原版核心类方法。 --- ## 1. `Dialogue` 对话树构建 API 原版对话采用链式单向图结构,每个节点代表一句话(气泡): ```csharp // 1. 创建根节点并设置第一句话(speaker 为说话人名称,设为 "PLAYER" 时气泡指向店主) var root = new Dialogue().SetText(sc.displayName, "第一句话内容"); // 2. 追加下一句连续台词(NextDialogue 返回新创建的子节点) var page2 = root.NextDialogue().SetText(sc.displayName, "第二句话内容"); // 3. 在某一句台词播放完毕时执行回调动作(如往桌面铺货、给钱、离开店铺) page2.SetEndAction(() => { PlayerStore.Instance?.ModCash(100, true); }); // 4. 在某一句台词末尾挂载玩家分支选项(AddChoice) var branchA = new Dialogue().SetText("PLAYER", "[选项A] 我同意你的提议。"); page2.AddChoice( DirectoryMaster.Item("$", true), // 必填占位图标 Item "", // 附加前缀文本 "", // 附加后缀文本 branchA, // 选中后跳转的 Dialogue 节点 () => // 选中瞬间执行的 Action 回调 { var reply = branchA.NextDialogue().SetText(sc.displayName, "太好了,合作愉快!"); reply.SetEndAction(() => DialogUIManager.Instance?.CurrentClientLeave(1f)); }, null // 可选:选项显示条件 Func ); ``` --- ## 2. `StoreClient` 关键生命周期方法与对话槽位 | 成员名 | 类型 | 说明 | | :--- | :--- | :--- | | `mainDialogue` | `Dialogue` | 顾客走到柜台前自动播放的主开场对话。 | | `placeRightItemWhenSellingToDialogue` | `Dialogue` | 玩家向该顾客出售物品、且放对了顾客求购的物品时播放的台词。 | | `acceptDealDialogue` | `Dialogue` | 交易价格达成一致、点击成交按钮时播放的台词(**推荐在此处的 `SetEndAction` 推进剧情阶段**)。 | | `allDoneDialogue` | `Dialogue` | 所有交易事项完成、顾客准备转身离开时播放的收尾台词。 | | `interogationDialogue` | `Dialogue` | 玩家点击盘问按钮时播放的台词。 | | `glasseDialogue` | `Dialogue` | 玩家开启透视扫描目镜观察该顾客时播放的描写文本。 | | `customOnArrestDialogue` | `Dialogue` | 玩家按报警按钮招来治安官逮捕该顾客时的特殊演出对话(末尾需调用 `StoreUIManager.Instance?.OnArrestDialoguePlayed()`)。 | | `repeatDialogue` | `Dialogue` | 玩家迟迟不放物品时顾客催促的重复对话。 | | `SetBudget(int amount)` | `void` | 设置买家携带的资金上限。 | | `SetWanted(int reward, string name, bool wanted)` | `void` | 将该顾客设为通缉犯并指定抓捕赏金与通缉真名。 | | `AddCheck(string checkId)` | `void` | 添加一项验货规则(如 `"CHECK_RUST"`, `"CHECK_EXPIRED"`)。 | | `CompleteClientCreation(bool flag = false)` | `void` | **必须在工厂方法返回 `StoreClient` 前调用**,用于初始化内部默认对话兜底与状态。 | | `CompleteSecClient()` | `void` | 当制作治安官盘查事件(`clientIntent = (ClientIntent)5`)时,在 `CompleteClientCreation(false)` 之后额外调用。 | --- ## 3. `PlayerStore` 与 `DialogUIManager` 常用辅助方法 ```csharp // 增减玩家现金(playSound = true 会播放收银机叮当声) PlayerStore.Instance?.ModCash(int delta, bool playSound = true); // 在批发卖出(SELL + isOfferWholesale)时向柜台桌面直接生成待售商品 PlayerStore.Instance?.AddDirectSellingItemToTable( string itemId, bool isOwnedByPlayer, // 顾客卖给玩家时传 false;奖励送给玩家时传 true bool isStolen, bool isContraband, int customPrice // 传 0 使用物品默认价格 ); // 让当前柜台前的顾客在 delay 秒后转身离开店铺 DialogUIManager.Instance?.CurrentClientLeave(float delay = 1f); // 立即打发当前顾客离开 PlayerStore.Instance?.DismissCurrentClient(bool callNext, bool playAnim, bool interruptDialog); ``` ================================================================================ ## examples/restored-overview.md ================================================================================ --- layout: doc title: RestoredUnusedNPCs:比利四幕连续剧 --- # 示例项目拆解:`RestoredUnusedNPCs` 架构与比利四幕连续剧 ![RestoredUnusedNPCs](/images/zh/preview_restored.png) 本篇与下一篇拆解 `RestoredUnusedNPCs` 模组的核心源码(`RestoredUnusedNPCsMod.cs`)。本篇聚焦于 **比利(Billy)四幕式跨日分支剧情线** 的状态机设计、以物易物 `BarterOffer`、监守自盗批发销赃与内务调查官双结局。 --- ## 1. 状态机路由与注册表设计 比利的剧情线由两个存档变量驱动: - `billy_stage`(`0..5`):`0` = 第 1 幕乞讨食物;`1` = 第 2 幕新晋夜班保安采购装备;`2` = 第 3 幕首次偷取上层区医疗舱药品销赃;`3` = 第 4 幕治安部内务调查官盘查;`4` = 被捕结局;`5` = 掩护后解锁的常驻七五折医疗品内应模式。 - `billy_fed`(`0` 或 `1`):记录玩家在第 1 幕是否分给过比利食物,决定第 2 幕重逢时的对话分支。 ```csharp private static StoreClient CreateBillyByCurrentStage() { int stage = NpcFrameworkSdk.GetSaveInt("billy_stage", 0); switch (stage) { case 0: return CreateBilly1(); case 1: return CreateBilly2(); case 2: return CreateBilly3Internal(false); case 3: return CreateBillySecOfficer(); default: return CreateBilly3Internal(true); } } ``` --- ## 2. 第一幕(`CreateBilly1`):乞讨食物与三分支抉择 比利首访时使用 `ClientIntent.BARTER`(`useClientBudget = false`),请求 `"FOOD"` 标签物品: - **分支一(`[分给他一点食物]`)**:若后仓持有 `"FOOD"` 物品,调用 `sc.barterOffer.InstanciateOffer()` 打开交付面板,完成后设置 `billy_stage = 1, billy_fed = 1`;若后仓暂无食物道具,则触发热乎员工餐保底分支并同样设置 `billy_stage = 1, billy_fed = 1`。 - **分支二(`[婉拒]`)**:保持 `billy_stage = 0`,比利改天再来。 - **分支三(`[让他自食其力]`)**:设置 `billy_stage = 1, billy_fed = 0`,比利发誓找到工作再回来。 --- ## 3. 第二幕(`CreateBilly2`):新晋夜班保安采购装备 当 `billy_stage == 1` 时,比利身穿治安部制服(`maleSec2`)进店,根据 `billy_fed` 是否为 `1` 播放感恩或扬眉吐气的开场白,并携带 `180` 信用点预算收购 `"TOOL"`、`"WEAPON"` 或 `"MELEE_WEAPON"`(查验 `CHECK_RUST` 与 `CHECK_DENTED`)。交易完成后将 `billy_stage` 推进至 `2`。 --- ## 4. 第三幕(`CreateBilly3Internal`)与第四幕(`CreateBillySecOfficer`) - **第三幕(医疗舱监守自盗销赃)**:比利将从帕斯泰尔医疗舱顺出来的 `large_purple_injector`、`pink_injector`、`hemostatic_bandage_item`、`smelling_salt` 按 **七五折整包批发(`isOfferWholesale = true, wholesaleDiscount = -25`)** 卖给玩家。买下后推进至 `billy_stage = 3`。 - **第四幕(内务调查官上门盘查)**: - 选择 **`[供出比利]`**:获得 `150` 信用点举报奖金,触发次日早报头条《医疗舱内鬼落网》,`billy_stage = 4`(比利线终结); - 选择 **`[替他打掩护]`**:调查官离开,`billy_stage = 5`,比利成为每隔 3 天定期进店提供七五折医疗品批发的常驻内应。 ================================================================================ ## examples/restored-special-npcs.md ================================================================================ --- layout: doc title: RestoredUnusedNPCs:7 位特殊机制散客 --- # 示例项目拆解:`RestoredUnusedNPCs` 7 位特殊机制散客 除了比利的四幕连续剧外,`RestoredUnusedNPCsMod.cs` 完整实现了 7 位各具代表性子系统机制的独立顾客。 --- ## 1. 灰潮拾荒客(`greytide` / `CreateTrailerGreytide`) 调用原版阵营初始化器 `StoreClientFactionSetup.InitScav(sc)` 挂载拾荒客识破率与偏好,并以随机整包折扣(`-RNG.GetRandomInt(15, 25)`)整包批发从安保岗亭顺出来的电击警棍(`stun_baton`)、格洛克机匣(`glock_receiver`)与安保门禁卡(`sec_keycard`): ```csharp private static StoreClient CreateTrailerGreytide() { var sc = new StoreClient { identifier = "greytide", displayName = T("灰潮拾荒客", "Lower Levels Citizen"), spriteName = SpriteDict.GetGreytideSpriteName(), clientFaction = "FACTION_LOWER_LEVEL", clientIntent = StoreClient.ClientIntent.SELL, isOfferWholesale = true, wholesaleDiscount = -RNG.GetRandomInt(15, 25) }; StoreClientFactionSetup.InitScav(sc); sc.mainDialogue.SetText(sc.displayName, T("喂,看看这批刚从安保岗亭顺出来的家伙,能给多少?", "How much can I get for these?")) .SetEndAction(() => { var ps = PlayerStore.Instance; if (ps == null) return; ps.AddDirectSellingItemToTable("stun_baton", false, false, false, 0); ps.AddDirectSellingItemToTable("glock_receiver", false, false, false, 0); ps.AddDirectSellingItemToTable("sec_keycard", false, false, false, 0); }); sc.CompleteClientCreation(false); return sc; } ``` --- ## 2. 猩红教徒(`cultistTrailer` / `CreateTrailerCultist`) 设置 `bubbleColor = "dark"` 开启暗黑对话气泡,溢价 `+35%` 收购 `blood_bag`(鲜血袋)与 `blue_blood_bag`(蓝血袋),并通过 `sc.AddCheck("CHECK_EXPIRED")` 拒收过期血袋。 --- ## 3. 革命军宣讲员(`revManifesto` / `CreateRevManifesto`) 调用 `StoreClientFactionSetup.InitRev(sc)` 绑定革命军声望,收购 `"FOOD"`、`"MEDICAL"`、`"WEAPON"` 为起义军筹集物资,同时带有 `50` 信用点通缉悬赏(`sc.SetWanted(50, ...)`)与 4 页 `customOnArrestDialogue` 逮捕对峙演出。 --- ## 4. 戒断成瘾者(`addictGeneralTrailer` / `CreateAddictTrailer`) 开启 `IsClientAddict = true, CanReturn = true, CanReturnAsBuyer = true`,并挂载 `sc.onItemAddedToWeighted` 实时委托:当玩家把 `"SUBSTANCE"` 或 `"NARCOTIC"` 物品放上电子秤时立即弹出插话气泡。 --- ## 5. 下层区制毒师(`trailerChemist` / `CreateTrailerChemist`) 开启 `CanExposeChem = true`,以 8 折(`wholesaleDiscount = -20`)整包批发 4 袋梦境之尘(`dream_dust`)与 2 颗欢腾药丸(`fanta_pill`)。 --- ## 6. 黑市军火贩(`trailerWeaponSeller` / `CreateTrailerWeaponSeller`) 通过存档键 `arms_dealer_met` 区分首次登门自荐与后续老主顾供货台词,以 8 折整包批发 2 个格洛克机匣(`glock_receiver`)、1 枚烟雾弹(`smoke_grenade`)、1 枚闪光弹(`flashbang_grenade`)与 1 个战术背包(`satchel`)。 --- ## 7. 武装民兵(`gunBuyerTrader` / `CreateTrailerGunBuyer`) 使用立绘 `"wanted3"`,携带 `450` 信用点预算求购 `"FIREARM"` 与 `"WEAPON"`,并同时启用 `CHECK_RUST` 与 `CHECK_DENTED` 双重验货检查。 ================================================================================ ## examples/cyberpunk-v-storyline.md ================================================================================ --- layout: doc title: CyberpunkMercV:五阶段主线与状态机设计 --- # 示例项目拆解:`CyberpunkMercV` 五阶段主线与状态机设计 ![CyberpunkMercV](/images/zh/preview_v.png) 本篇与下一篇深入拆解 `CyberpunkMercV` 模组的全部核心代码(`CyberpunkMercVMod.cs`)。本篇解析模组的注册表架构、五阶段叙事状态机(`v_stage`)、智能阶段分发器以及第 1 至第 3 幕的完整代码实现。 --- ## 1. 状态机设计与注册表结构 `CyberpunkMercV` 通过两个存档状态键驱动跨日叙事线: - `v_stage`(整型,`0..5`):控制 V 当前所处的剧情阶段(`0` = 第 1 幕初见求购抑制剂;`1` = 第 2 幕押运车劫案备战买枪;`2` = 第 3 幕金库劫案归来整包销赃;`3` = 第 4 幕企业特勤追缉官盘查;`4` = 掩护结局后解锁的终局常驻传奇佣兵与全息电话模式;`5` = 被捕或被出卖结局,故事线终止)。 - `v_trust`(整型,`0..2`):记录店主在剧情中与 V 建立的信任等级。 在 `RegisterAll()` 中,模组共注册了 6 个 NPC 调度条目(1 个智能阶段路由入口 `v` + 5 个分阶段条目): ```csharp private static void RegisterAll() { // 智能调度入口:自动根据当前存档的 v_stage 路由到对应幕次 NpcFrameworkSdk.RegisterNpc( id: "v", displayNameGetter: () => T("赛博朋克 V (按剧情自动推进)", "Cyberpunk V (Auto Storyline)"), spawnPhase: 1, priority: 95, minDay: 9999, cooldownDays: 0, spawnChancePercent: 0, oncePerSave: false, canSpawnPredicate: () => false, clientFactory: CreateVByCurrentStage); // 第 1 幕:Relic 生物芯片排异求救 (v_stage == 0) NpcFrameworkSdk.RegisterNpc( id: "v_act1_relic", displayNameGetter: () => T("佣兵 V (第1幕: Relic故障)", "Merc V (Act 1: Relic Glitch)"), spawnPhase: 1, priority: 85, minDay: 2, cooldownDays: 2, spawnChancePercent: 75, oncePerSave: false, canSpawnPredicate: () => NpcFrameworkSdk.GetSaveInt("v_stage", 0) == 0, clientFactory: () => { NpcFrameworkSdk.SetSaveInt("v_stage", 0); return CreateVAct1Relic(); }); // 第 2 幕:荒坂/帕斯泰尔押运车劫案备战 (v_stage == 1) NpcFrameworkSdk.RegisterNpc( id: "v_act2_gun_order", displayNameGetter: () => T("佣兵 V (第2幕: 军火备战)", "Merc V (Act 2: Arms Prep)"), spawnPhase: 1, priority: 85, minDay: 4, cooldownDays: 2, spawnChancePercent: 80, oncePerSave: false, canSpawnPredicate: () => NpcFrameworkSdk.GetSaveInt("v_stage", 0) == 1, clientFactory: () => { NpcFrameworkSdk.SetSaveInt("v_stage", 1); return CreateVAct2GunOrder(); }); // 第 3 幕:上层区实验室金库大劫案整包分赃 (v_stage == 2) NpcFrameworkSdk.RegisterNpc( id: "v_act3_heist", displayNameGetter: () => T("佣兵 V (第3幕: 劫案分赃)", "Merc V (Act 3: Heist Loot)"), spawnPhase: 1, priority: 88, minDay: 6, cooldownDays: 2, spawnChancePercent: 85, oncePerSave: false, canSpawnPredicate: () => NpcFrameworkSdk.GetSaveInt("v_stage", 0) == 2, clientFactory: () => { NpcFrameworkSdk.SetSaveInt("v_stage", 2); return CreateVAct3Heist(); }); // 第 4 幕:企业特勤追缉官上门盘查 (v_stage == 3) NpcFrameworkSdk.RegisterNpc( id: "v_act3_corpo_sec", displayNameGetter: () => T("企业特勤追缉官 (第4幕: 追查V)", "Corpo Spec-Ops (Act 4: Hunt)"), spawnPhase: 1, priority: 92, minDay: 7, cooldownDays: 1, spawnChancePercent: 95, oncePerSave: false, canSpawnPredicate: () => NpcFrameworkSdk.GetSaveInt("v_stage", 0) == 3, clientFactory: () => { NpcFrameworkSdk.SetSaveInt("v_stage", 3); return CreateCorpoSecInvestigator(); }); // 第 5 阶段:终局常驻传奇佣兵模式 (v_stage == 4) NpcFrameworkSdk.RegisterNpc( id: "v_recurring_merc", displayNameGetter: () => T("传奇佣兵 V (终局常驻: 需先完成前4幕)", "Legendary V (Post-Story Recurring)"), spawnPhase: 2, priority: 65, minDay: 8, cooldownDays: 4, spawnChancePercent: 35, oncePerSave: false, canSpawnPredicate: () => NpcFrameworkSdk.GetSaveInt("v_stage", 0) == 4, clientFactory: CreateVRecurringMercOrCurrentStage); } ``` ### 智能阶段分发与终局前置守卫 ```csharp private static StoreClient CreateVByCurrentStage() { int stage = NpcFrameworkSdk.GetSaveInt("v_stage", 0); switch (stage) { case 0: return CreateVAct1Relic(); case 1: return CreateVAct2GunOrder(); case 2: return CreateVAct3Heist(); case 3: return CreateCorpoSecInvestigator(); default: return CreateVRecurringMercInternal(); } } private static StoreClient CreateVRecurringMercOrCurrentStage() { int stage = NpcFrameworkSdk.GetSaveInt("v_stage", 0); if (stage < 4) return CreateVByCurrentStage(); return CreateVRecurringMercInternal(); } ``` --- ## 2. 第一幕(`CreateVAct1Relic`):芯片排异求救与目镜扫描彩蛋 在第一幕中,V 以初来乍到的 **`"陌生佣兵 V"`** 身份进店,处于 Relic 原型生物芯片 68% 神经覆写发作期: ```csharp private static StoreClient CreateVAct1Relic() { var sc = new StoreClient { identifier = "v_act1_relic", displayName = T("陌生佣兵 V", "Mercenary V"), spriteName = "v_normal", clientFaction = "FACTION_BLACK_MARKET", clientIntent = StoreClient.ClientIntent.BUY, buyPriceModifier = 40, CanExposeChem = true, staysAfterFailedBargain = true, noAcceptingContraband = false, AcceptingContrabandOverride = true }; sc.SetBudget(380); sc.clientBuyingIdList.Add("black_injector"); sc.clientBuyingIdList.Add("large_purple_injector"); sc.clientBuyingIdList.Add("pink_injector"); sc.clientBuyingIdList.Add("dream_dust"); sc.clientBuyingTagList.Add("MEDICAL"); sc.clientBuyingTagList.Add("NARCOTIC"); sc.AddCheck("CHECK_EXPIRED"); ``` ### 第一幕的双路径分支设计 1. **剧情直通分支(`[递给他一支应急神经镇静剂]`)**: 即使玩家刚开局不久、货架上暂时没有高级医疗针剂,也可选择直接把柜台抽屉里的应急神经镇静剂递给 V。该分支将 `v_stage` 推进至 `1`、`v_trust` 设为 `2`,并通过 `PlayerStore.Instance?.ModCash(120, true)` 获得 V 留下的 `120` 信用点诊金。 2. **柜台交易分支(`[打开货架] 我这儿有强效药,自己挑吧`)**: 进入标准买家交易流程,玩家将符合条件的医疗品或药剂摆上柜台完成议价。成交后在 `acceptDealDialogue` 与 `allDoneDialogue` 中将 `v_stage` 推进至 `1`、`v_trust` 设为 `1`。 ### 盘问与透视目镜扫描彩蛋 ```csharp sc.interogationDialogue = Chain(sc.displayName, T("从夜之城一路逃到这鬼空间站,原以为能甩掉荒坂和帕斯泰尔的追兵。", "Thought laying low on this rustbucket station would get Arasaka and Pastel off my tail."), T("结果真正要命的是插在我后颈里的这块原型生物芯片。", "Turns out the real killer is the prototype biochip slotted in my neck.")); sc.glasseDialogue = Chain("PLAYER", T("(你的目镜扫过他颈后的芯片插槽,电火花闪烁间,扫描仪上竟闪过一行诡异的意识体残影:)", "(Your optics scan the neural socket at his neck; amid sparks, a phantom engram signature flashes across your lens:)"), T("(“醒醒,武侍……把这群企业狗杂碎全烧成灰……”)", "('Wake the hell up, Samurai... We have a station to burn...')")); ``` --- ## 3. 第二幕(`CreateVAct2GunOrder`):押运车劫案军火备战 当 `v_stage == 1` 时,V 颈后的芯片在玩家药物的压制下趋于稳定。他进店告知今晚准备截击上层区荒坂与帕斯泰尔联合实验室的神经矩阵押运车,携带 `520` 信用点预算、溢价 `+30%` 收购枪械与弹药: ```csharp sc.SetBudget(520); sc.clientBuyingTagList.Add("FIREARM"); sc.clientBuyingTagList.Add("WEAPON"); sc.clientBuyingTagList.Add("AMMUNITION"); sc.clientBuyingTagList.Add("MUNITION"); sc.AddCheck("CHECK_RUST"); sc.AddCheck("CHECK_DENTED"); sc.acceptDealDialogue = new Dialogue() .SetText(sc.displayName, T("够劲!有了这把铁,今晚那群企业安保连反应的机会都没有。", "Preem! With this iron, those corpo guards won't even know what hit 'em.")) .NextDialogue() .SetText(sc.displayName, T("等我干完这票大的,分赃的时候第一个找你!", "Once I pull off this heist, you'll be my first stop to fence the loot!")) .SetEndAction(() => { NpcFrameworkSdk.SetSaveInt("v_stage", 2); NpcFrameworkSdk.AddSaveInt("v_trust", 1, 1); }); ``` --- ## 4. 第三幕(`CreateVAct3Heist`):金库大劫案整包七折销赃 当 `v_stage == 2` 时,V 成功洗劫上层区实验室,留下自用的神经矩阵后,将剩余 5 件高价值战利品按 **整包七折(`isOfferWholesale = true, wholesaleDiscount = -30`)** 带到玩家店里销赃,同时自身带有 `120` 信用点企业通缉悬赏(`sc.SetWanted(120, "Vincent (V)", true)`): ```csharp cur.SetEndAction(() => { var ps = PlayerStore.Instance; if (ps == null) return; ps.AddDirectSellingItemToTable("aug_chip", false, false, false, 0); ps.AddDirectSellingItemToTable("command_keycard", false, false, false, 0); ps.AddDirectSellingItemToTable("sci_keycard", false, false, false, 0); ps.AddDirectSellingItemToTable("energy_credit_hyp", false, false, false, 0); ps.AddDirectSellingItemToTable("smg", false, false, false, 0); }); sc.acceptDealDialogue = new Dialogue() .SetText(sc.displayName, T("痛快!跟你做生意永远这么省心。", "Clean and fast! Doing business with you is always nova.")) .NextDialogue() .SetText(sc.displayName, T("对了,企业特勤队估计正在到处查我的下落,要是有人来盘问,帮我挡一下!", "By the way, Corpo Spec-Ops are tearing the station apart looking for me. If they come knocking, cover my back!")) .SetEndAction(() => { NpcFrameworkSdk.SetSaveInt("v_stage", 3); }); ``` ================================================================================ ## examples/cyberpunk-v-rewards-glitch.md ================================================================================ --- layout: doc title: 5.4 CyberpunkMercV:四联奖励与 Relic Glitch --- # 5.4 示例二拆解(下):第 4 幕四联奖励闭环、全息专线与终局常驻模式 本节拆解 `CyberpunkMercVMod.cs` 中最核心的高潮章节——**第 4 幕企业特勤追缉官盘查(四联奖励闭环)**、**终局常驻传奇佣兵模式(`CreateVRecurringMercInternal`)** 与 **`2077077` 全息电话召唤系统**。 --- ## 1. 第四幕(`CreateCorpoSecInvestigator`):掩护 vs 出卖双结局 当 `v_stage == 3` 时,身穿企业安保制服的特勤追缉官(`v_act3_corpo_sec`)进店盘查,不可被枪击(`nonShootable = true`),也不可按铃打发(`dismissable = false`)。 ```csharp var dlgCover = new Dialogue().SetText("PLAYER", T("[替 V 隐瞒并误导追兵] 穿武侍夹克的佣兵?他半小时前抢了艘穿梭机往空港逃了。", "[Cover for V] Guy in a Samurai jacket? Saw him hijack a shuttle toward the docking bay half an hour ago.")); var dlgBetray = new Dialogue().SetText("PLAYER", T("[出卖 V 换取 300 信用点赏金] 他刚把赃物卖给我,现在就躲在旧通风井区的安全屋。", "[Sell out V for 300 Credits] He just fenced goods here and is hiding in the old ventilation sector.")); ``` ### 结局一:替 V 隐瞒(触发四联奖励闭环,`v_stage = 4`) 当玩家点击 `dlgCover` 时,回调函数在单次原子操作中联动了框架的 **5 个核心 API**: 1. **推进存档至终局常驻阶段**:`NpcFrameworkSdk.SetSaveInt("v_stage", 4)`; 2. **解锁全息电话簿联系人**:调用 `NpcFrameworkSdk.SyncPhoneContacts()`,由于 `2077077` 的 `isUnlockedPredicate` 为 `() => GetSaveInt("v_stage", 0) == 4`,该号码立即出现在店内电话簿列表中; 3. **柜台投递实体手写便条**:调用 `NpcFrameworkSdk.GiveHandnoteToPlayer(...)`,在柜台上生成一张署名为 `"V (Vincent)"` 的实体便条《V 的加密便条》; 4. **激活店铺终端高额委托单**:调用 `NpcFrameworkSdk.PostStoreRequest("v_afterlife_chip_req", ...)`,在店铺电脑委托板上挂出报酬 `450` 信用点、`+15` 黑市声望的《来生佣兵义体芯片悬赏》; 5. **刊登次日早报头条**:调用 `NpcFrameworkSdk.TriggerNews("v_heist_legend_news", ...)`,次日清晨报纸头版刊登《独狼佣兵洗劫企业实验室后全身而退》。 ### 结局二:出卖 V 领赏(`v_stage = 5`) 当玩家点击 `dlgBetray` 时,当场获得企业支付的 `300` 信用点线报费(`PlayerStore.Instance?.ModCash(300, true)`),次日早报刊登《旧通风井爆发激烈交火》,同时 `v_stage` 设为 `5`(V 线永久终止)。 --- ## 2. 终局常驻模式(`CreateVRecurringMercInternal`) 只有当玩家真正完成了前 4 幕并选择了掩护 V(`v_stage == 4`)后,V 才会以老熟人 **`"传奇佣兵 V"`** 的身份进入日常循环池(或通过拨打 `2077077` 随时召唤): - **55% 概率整包销赃(`sellingLoot = true`)**: V 刚清理完一处企业据点,将 `aug_chip`(义体芯片)、`revolver`(左轮手枪)、`large_purple_injector`(大型紫针)与 `sec_keycard`(安保门禁卡)按 **七五折(`wholesaleDiscount = -25`)** 整包让给玩家; - **45% 概率大额采购(`sellingLoot = false`)**: V 今晚接了大单,携带 `600` 信用点预算、溢价 `+30%` 来店里采购 `"FIREARM"`、`"WEAPON"`、`"MEDICAL"`、`"AMMUNITION"`。 --- ## 3. 全息专线 `2077077` 通话树源码 ```csharp private static Dialogue CreateVPhoneDialogue(StorePhoneClient phoneClient) { string vName = T("传奇佣兵 V", "V (Afterlife Merc)"); var root = new Dialogue().SetText(vName, T("喂?是我,V。掌柜的,有什么大买卖找我?", "Yo, it's V. What's the word, choom? Got a gig or need a drop?")); var dlgSummon = new Dialogue().SetText("PLAYER", T("[呼叫 V 进店交易] 手头正好有笔大生意,你现在方便来店里一趟吗?", "[Call V to Store] Got some serious business. Can you swing by the shop right now?")); var dlgChat = new Dialogue().SetText("PLAYER", T("[叙旧闲聊] 没什么急事,问问你跟脑子里那位处得怎么样了。", "[Just Chatting] Nothing urgent, just checking how you and the rockerboy in your head are holding up.")); root.AddChoice(DirectoryMaster.Item("$", true), "", "", dlgSummon, () => { phoneClient?.UseService(); // 标记电话已使用,进入 3 天冷却 NpcFrameworkSdk.SummonNpcNow("v_recurring_merc"); // 直接将 V 插入 clientStack[0] 并在门口空闲时自动唤入! dlgSummon.NextDialogue().SetText(vName, T("没问题,正好我刚收工,这就骑草薙摩托过去,下一声门铃见!", "You got it, choom. Just wrapped up a gig on my Yaiba Kusanagi. I'll be at your counter on the next bell!")); }, null); root.AddChoice(DirectoryMaster.Item("$", true), "", "", dlgChat, () => { dlgChat.NextDialogue() .SetText(vName, T("哈哈,强尼现在安分多了,除了偶尔嫌弃空间站的合成啤酒不如来生酒吧的强尼银手特调。", "Haha, Johnny's behaving himself, mostly just complaining the station's synth-beer tastes like rustwater compared to the Afterlife.")) .NextDialogue().SetText(vName, T("有需要随时再打给我,回见!", "Ring me anytime you need backup. Catch you later, choom!")); }, null); return root; } ``` ================================================================================ ## reference/vanilla-dictionaries.md ================================================================================ --- layout: doc title: 6.1 阵营、物品标签、常用物品 ID 与立绘池速查 --- # 6.1 原版游戏内置字典速查表(直接提取自 `Assembly-CSharp.dll`) 本表整理自《深空当铺:可能是偷的》游戏程序集 `Assembly-CSharp.dll` 的真实常量与方法签名,供人类开发者与 AI Agent 在编写自定义 NPC 时直接查阅引用。 --- ## 1. 八大原版阵营 ID(`clientFaction`)与阵营初始化器 | 阵营常量字符串 (`clientFaction`) | 阵营名称 | 对应的 `StoreClientFactionSetup` 快捷初始化方法 | | :--- | :--- | :--- | | `"FACTION_LOWER_LEVEL"` | 下层区居民 / 拾荒客 | `InitLowerLevelCitizen(sc)` / `InitScav(sc)` / `InitWorker(sc)` | | `"FACTION_BLACK_MARKET"` | 黑市帮派 / 地下走私 | `InitBlackMarket(sc)` | | `"FACTION_SECURITY"` | 空间站治安部 / 企业安保 | `InitSecurity(sc)` | | `"FACTION_REVOLUTION"` | 革命军 / 地下抵抗组织 | `InitRev(sc)` | | `"FACTION_UPPER_LEVEL"` | 上层区富人 / 帕斯泰尔精英 | `InitUpperLevelCitizen(sc)` | | `"FACTION_TOURIST"` | 星际游客 | `InitTourist(sc)` | | `"FACTION_CHURCH"` | 深渊教会 | `InitChurch(sc)` | | `"FACTION_CARTEL"` | 辛迪加卡特尔 | `InitCartel(sc)` | --- ## 2. `StoreClient.ClientIntent` 交易意图枚举全表 | 枚举名 | 整型值 | 适用场景 | | :--- | :--- | :--- | | `ClientIntent.UNDEFINED` | `0` | 未定义 | | `ClientIntent.BUY` | `1` | 常规买家(向玩家求购商品) | | `ClientIntent.SELL` | `2` | 常规卖家或整包批发卖家(配合 `isOfferWholesale = true`) | | `ClientIntent.SELLNBUY` | `3` | 既卖又买 | | `ClientIntent.INSPECTION` | `4` | 治安官例行违禁品搜查 | | `ClientIntent.DIALOGUE` | `5` | 纯对话/剧情盘查事件(如 `billy3Officier`、`v_act3_corpo_sec`) | | `ClientIntent.BARTER` | `6` | 以物易物 / 乞讨施舍(配合 `sc.barterOffer`) | | `ClientIntent.RENT` | `7` | 收房租事件 | | `ClientIntent.LOAN_SHARK` | `8` | 高利贷催收事件 | | `ClientIntent.SPECIAL` | `9` | 特殊剧情事件 | | `ClientIntent.INFORMATION_DEALER` | `10` | 情报贩子 | | `ClientIntent.PROCUREMENT_OFFER` | `11` | 发起期货预定委托(配合 `AttachProcurementOffer`) | | `ClientIntent.PROCUREMENT_COLLECT` | `12` | 期货到期登门收货 | | `ClientIntent.WHOLESALE` | `13` | 批发专用意图 | | `ClientIntent.APPRAISAL_SERVICE` | `14` | 鉴定服务 | | `ClientIntent.GUNSMITH` | `15` | 枪械改装委托(配合 `BuildCustomGunOrder`) | | `ClientIntent.EXPEDITION` | `16` | 远征探险委托 | --- ## 3. 常用物品分类标签(`clientBuyingTagList`)与高频物品 ID(`itemID`) ### 常用物品分类标签(Tags) - **医疗与化学类**:`"MEDICAL"`, `"NARCOTIC"`, `"SUBSTANCE"`, `"CHEMICAL"` - **武器与军火类**:`"FIREARM"`, `"WEAPON"`, `"MELEE_WEAPON"`, `"AMMUNITION"`, `"MUNITION"`, `"EXPLOSIVE"` - **日常与工具类**:`"FOOD"`, `"DRINK"`, `"TOOL"`, `"ELECTRONIC"`, `"VALUABLE"`, `"KEYCARD"`, `"DOCUMENT"` ### 高频原版物品 ID(可直接用于 `AddDirectSellingItemToTable` 或 `clientBuyingIdList`) | 类别 | 原版物品 ID (`itemID`) | 物品说明 | | :--- | :--- | :--- | | **医疗针剂与血袋** | `"black_injector"`, `"large_purple_injector"`, `"pink_injector"`, `"blood_bag"`, `"blue_blood_bag"`, `"hemostatic_bandage_item"`, `"smelling_salt"` | 黑针、大型紫针、粉针、鲜血袋、蓝血袋、止血绷带、嗅盐 | | **违禁药物与神经剂** | `"dream_dust"`, `"fanta_pill"` | 梦境之尘、欢腾药丸 | | **枪械、零件与投掷物** | `"revolver"`, `"smg"`, `"stun_baton"`, `"glock_receiver"`, `"smoke_grenade"`, `"flashbang_grenade"` | 左轮手枪、冲锋枪、电击警棍、格洛克机匣、烟雾弹、闪光弹 | | **高价值芯片与门禁卡** | `"aug_chip"`, `"sec_keycard"`, `"command_keycard"`, `"sci_keycard"`, `"energy_credit_hyp"`, `"satchel"` | 义体芯片、安保门禁卡、指挥官门禁卡、科研门禁卡、高能信用芯片、战术背包 | | **特殊功能道具** | `"newspaper"`, `"tutorial_book"`, `"labeler"`, `"stamp_guide"`, `"injector_guide"`, `"logo_checker"` | 早报、教程书、贴标机、印章指南、注射器指南、防伪检测仪 | --- ## 4. 改枪订单 18 个属性标签(`GUN_*_TAG`) 用于 `NpcFrameworkSdk.BuildCustomGunOrder` 的 `statTag` 参数: - `"GUN_CALIBER_TAG"`(口径匹配) - `"GUN_SUPPRESSED_TAG"`(是否安装消音器,`1` 为需要消音) - `"GUN_FIREPOWER_TAG"` / `"GUN_CURRENT_FIREPOWER_TAG"`(火力值) - `"GUN_ACCURACY_TAG"` / `"GUN_CURRENT_ACCURACY_TAG"`(精准度) - `"GUN_RELIABILITY_TAG"` / `"GUN_CURRENT_RELIABILITY_TAG"`(可靠性) - `"GUN_ERGONOMICS_TAG"` / `"GUN_CURRENT_ERGONOMICS_TAG"`(人机工效) - `"GUN_RECOIL_TAG"` / `"GUN_CURRENT_RECOIL_TAG"`(后坐力控制) - `"GUN_REPAIRBILITY_TAG"` / `"GUN_CURRENT_REPAIRBILITY_TAG"`(可维修性) - `"GUN_STYLE_TAG"` / `"GUN_CURRENT_STYLE_TAG"`(外观风格评分) - `"GUN_FRAME_TAG"` / `"GUN_SIZE_TAG"`(枪身框架与尺寸) --- ## 5. `SpriteDict` 内置随机与专属立绘池方法全表 不想自己画贴图时,可直接调用以下 `SpriteDict` 静态方法返回原版高质量像素立绘键名: - **下层区与拾荒客**:`SpriteDict.GetRandomLowerLevelSpriteName()`, `GetRandomLowerMaleSpriteName()`, `GetRandomLowerFemaleSpriteName()`, `GetRandomScavSpriteName()`, `GetGreytideSpriteName()`, `"trailer_scav1"`, `"trailer_scav2"`, `"trailer_scav3"` - **黑市、地下商人与佣兵**:`SpriteDict.GetRandomShadySpriteName()`, `GetRandomBMMaleSpriteName()`, `GetRandomBMFemaleSpriteName()`, `GetRandomMercSpriteName()`, `GetRandomMercMale()`, `GetRandomMercFemale()`, `GetShadyMerchantSpriteName()`, `"spy"`, `"wanted3"`, `"wanted5"` - **治安部与企业特勤**:`SpriteDict.GetRandomSecSpriteName()`, `GetRandomSecMaleSpriteName()`, `GetRandomSecFemaleSpriteName()`, `GetRandomSecCorpoSpriteName()`, `GetRandomSecCorpoMaleSpriteName()`, `GetRandomSecOffSpriteName()`, `"maleSec2"` - **革命军**:`SpriteDict.GetRandomRevSpriteName()`, `GetRandomRevMaleSpriteName()`, `GetRandomRevFemaleSpriteName()`, `"trailer_rev1"` - **医生、科学家与工程师**:`SpriteDict.GetRandomMedSpriteName()`, `GetRandomScientistSpriteName()`, `GetRandomSciSpriteName()`, `GetRandomEngSpriteName()` - **上层区精英与特殊角色**:`SpriteDict.GetRandomUpperSpriteName()`, `GetLoanSharkSpriteName()`, `GetCartelHandlerSpriteName()`, `GetBlackmailerSpriteName()`, `GetInventorSpriteName()`, `GetCourrierSpriteName()` ================================================================================ ## en/index.md ================================================================================ --- layout: doc title: Custom NPC Framework --- # Custom NPC Framework This documentation covers the complete technical specification for the **Custom NPC Framework** and its two companion example mods (**RestoredUnusedNPCs** and **CyberpunkMercV**) for *Probably Stolen* (Steam AppID `4348910`). ![Custom NPC Framework](/images/en/preview_framework.png) --- ## One-Click Prompt for AI Coding Agents If you want an AI assistant (such as Claude Code, Cursor, Windsurf, Cline, or OpenChamber) to design, write, compile, or package a new *Probably Stolen* custom NPC mod for you, copy and send the following prompt directly to your AI Agent: ::: tip Copy and send this prompt to your AI Agent ```markdown Please read the following two sets of technical documentation for Probably Stolen modding first: 1. Official Probably Stolen Modding Guide (project layout, mandatory manifest.xml and tags, IMod lifecycle, ModLog, custom items/sounds/localization asset loading, ModHook events, and ModScanner rules): - Quick Start: https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/README.md - Advanced Modding Guide: https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/ModdingGuide.md - API Changes: https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/APIChanges.md 2. Custom NPC Framework Complete Specification (6-step AI Agent workflow, full NpcFrameworkSdk.cs source code, all 18 Customer Subsystems, vanilla item/tag/sprite dictionaries, and full code breakdowns of both example mods): - Workflow Guide: https://customnpc.netlify.app/en/guide/agent-workflow - Single-File Full Context: https://customnpc.netlify.app/llms-full.txt After reading, do not write code blindly. Walk me through the [6-Step Interactive Requirement Checklist] in the guide to confirm: 1. Mod metadata (Mod ID, display name, author) and whether the mod also needs custom items (GameItem), custom sounds, or loot table edits; 2. The new NPC identity, faction (clientFaction), and portrait source (built-in SpriteDict pool vs. custom 288x211 PNG in Textures/); 3. Spawn phase (spawnPhase), day window, cooldown days, and spawn probability; 4. Core trade intent (regular BUY, regular SELL, Wholesale lot, BarterOffer, multi-day Procurement contract, or Custom GunOrder); 5. Multi-day storyline state machine (cnpcf_ save keys) and branching outcomes; 6. World integrations (7-digit holophone contact, handwritten note, store terminal request bounty StoreRequest, next-day newspaper headline TriggerNews, interrogation/smart-glasses scan dialogue, wanted arrest cutscene, afterhour events). Once confirmed, generate the complete C# project source code (including the zero-reference NpcFrameworkSdk.cs), manifest.xml, and Steam Workshop .vdf/.bat upload scripts, then compile and package the mod. ``` ::: ### Machine-Readable Endpoints for LLMs - **Lightweight Directory Index**: [`https://customnpc.netlify.app/llms.txt`](/llms.txt) - **Single-File Full Specification**: [`https://customnpc.netlify.app/llms-full.txt`](/llms-full.txt) --- ## Project Matrix | Mod Name | Core Source Files | Code Size | Feature Coverage | | :--- | :--- | :--- | :--- | | **`CustomNPCFramework`** | `CustomNPCFrameworkMod.cs`
`NpcFrameworkRegistry.cs`
`NpcSaveStore.cs`
`NpcPhoneRegistry.cs`
`NpcFullFeatureKit.cs`
`NpcTraitModels.cs` | ~1,820 lines | • `AppDomain` double-buffered pending queues + live delegate bridge
• Daily 5-phase customer generation scheduler (`VeryEarly`..`VeryLate`)
• 7-step eligibility filter (day window, cooldown, once-per-save, arrest blacklist, spawn rate multiplier)
• Developer debug summon with two-stage `clientStack[0]` front-insertion
• `cnpcf_`-namespaced per-save key/value storyline state machine
• Automatic registration of `Textures/*.png` into `SpriteDict` (`Point` filter + `100 PPU`)
• Complete Customer Subsystems toolkit (handnotes, request board, procurement, gun orders, news, afterhour, holophone) | | **`RestoredUnusedNPCs`** | `RestoredUnusedNPCsMod.cs`
`NpcFrameworkSdk.cs` | ~850 lines | • Restores **11 unused vanilla customers** found in `StoreClientListTrailer`
• **Billy's 4-act cross-day storyline** (begging for food with `BarterOffer` → rookie guard buying gear → Medbay theft wholesale → Internal Affairs investigation with snitch/cover endings)
• **7 special-mechanic customers** (Greytide Scavenger, Blood Cultist, Revolutionary Agitator, Withdrawal Addict with realtime scale reaction, Lower Levels Chemist, Underground Arms Dealer, Armed Militiaman)
• Auto-stage dispatcher `billy` and `OnDismiss` stage-skip protection | | **`CyberpunkMercV`** | `CyberpunkMercVMod.cs`
`NpcFrameworkSdk.cs` | ~850 lines | • **5-stage narrative state machine for V from *Cyberpunk 2077*** (`v_stage 0..5`)
• Act 1 Relic biochip 68% overwrite seeking neural blockers + Johnny Silverhand optics scan Easter egg
• Act 2 Arasaka/Pastel convoy ambush firearm preparation
• Act 3 corporate vault heist 30%-off wholesale loot + custom arrest cutscene
• Act 4 Corporate Spec-Ops investigation (cover for V to unlock 4-part reward loop / betray for 300 credits)
• **4-part reward loop**: unlocks `2077077` holophone + delivers *V's Encrypted Note* + posts 450-credit request bounty + triggers next-day newspaper headline
• **3-frame Relic visual glitch**: `v_normal` / `v_glitch` / `v_glitch2` scanline slice displacement and cyan/crimson flash | --- ## Documentation Navigation Across 6 Subdirectories ### 1. Getting Started & AI Agent Guide (`/en/guide/`) - **[AI Agent Interactive Workflow](/en/guide/agent-workflow)** - **[Quick Start: Your First Custom NPC Mod](/en/guide/quick-start)** - **[Customer Sprite Dimensions & Outline Spec](/en/guide/sprite-art-pipeline)** ### 2. Core Architecture (`/en/architecture/`) - **[Zero-Reference AppDomain Bridge & Hooks](/en/architecture/bridge-and-lifecycle)** - **[5-Phase Customer Generation & Debug Priority](/en/architecture/generation-pipeline)** - **[Save State Store & Mod Configuration](/en/architecture/save-and-config)** - **[Dynamic Texture Injection & Sprite Fallbacks](/en/architecture/glitch-and-textures)** ### 3. Customer Subsystems (`/en/subsystems/`, 18 Dedicated Guides) 1. **[01. Regular Buying & Wishlists (BUY)](/en/subsystems/01-regular-buying)** 2. **[02. Regular Selling & Item Offers (SELL)](/en/subsystems/02-regular-selling)** 3. **[03. Wholesale Lot Trading (Wholesale)](/en/subsystems/03-wholesale-lots)** 4. **[04. Barter & Begging (BarterOffer)](/en/subsystems/04-barter-and-begging)** 5. **[05. Bargaining, Impatience & Perfume](/en/subsystems/05-bargaining-and-patience)** 6. **[06. Contraband, Retail Markup & Labels](/en/subsystems/06-contraband-and-labels)** 7. **[07. Item Defect Inspection Checks](/en/subsystems/07-inspection-checks)** 8. **[08. Counterfeit Expose & Chemical Grade](/en/subsystems/08-expose-and-chem-grade)** 9. **[09. Realtime Scale, Counter & Showcase Hooks](/en/subsystems/09-realtime-scale-and-counter)** 10. **[10. Multi-Day Procurement Contracts](/en/subsystems/10-procurement-contracts)** 11. **[11. Custom Gunsmith Orders (GunOrder)](/en/subsystems/11-custom-gun-orders)** 12. **[12. Handwritten Notes & Paper Documents](/en/subsystems/12-handnotes-and-papers)** 13. **[13. Store Terminal Request Board](/en/subsystems/13-store-request-board)** 14. **[14. Holophone Contacts & Dial-to-Summon](/en/subsystems/14-holophone-contacts)** 15. **[15. Interrogation, Smart Glasses & Bubbles](/en/subsystems/15-interrogation-and-optics)** 16. **[16. Wanted Bounties, Arrest & Security](/en/subsystems/16-wanted-arrest-and-security)** 17. **[17. Morning Newspaper Headlines](/en/subsystems/17-newspaper-headlines)** 18. **[18. Afterhour Events & Nightly Hooks](/en/subsystems/18-afterhour-and-nightly-hooks)** ### 4. API Reference (`/en/api/`) - **[NpcFrameworkSdk Complete Reference](/en/api/sdk-reference)** - **[ApplyClientProfile 46-Field Dictionary](/en/api/profile-dictionary)** - **[Vanilla StoreClient & Dialogue Classes](/en/api/vanilla-classes)** ### 5. Example Projects Breakdown (`/en/examples/`) - **[RestoredUnusedNPCs: Billy 4-Act Storyline](/en/examples/restored-overview)** - **[RestoredUnusedNPCs: 7 Special Customers](/en/examples/restored-special-npcs)** - **[CyberpunkMercV: 5-Stage Storyline & State Machine](/en/examples/cyberpunk-v-storyline)** - **[CyberpunkMercV: Rewards Loop & Relic Glitch](/en/examples/cyberpunk-v-rewards-glitch)** ### 6. Vanilla Data Dictionaries (`/en/reference/`) - **[Factions, Item Tags, Item IDs & SpriteDict Pools](/en/reference/vanilla-dictionaries)** ================================================================================ ## en/guide/agent-workflow.md ================================================================================ --- layout: doc title: AI Agent Interactive Modding Workflow --- # AI Agent Interactive Modding Workflow This document defines the end-to-end Standard Operating Procedure (SOP) for **AI Coding Agents (such as Claude Code, Cursor, Windsurf, Cline, and OpenChamber)** and human developers building custom NPC mods for *Probably Stolen*. To build a complete, scanner-compliant mod that loads and runs cleanly, an AI Agent needs two complementary references: 1. **Official Base Modding Guide**: from the official repository [`dragonpan2/probably-stolen-modding`](https://github.com/dragonpan2/probably-stolen-modding/) ([`README.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/README.md), [`ModdingGuide.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/ModdingGuide.md), and [`APIChanges.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/APIChanges.md)), which defines folder structure, mandatory `manifest.xml` tags (`` and ``), `IMod` lifecycle, `ModLog`, asset folders (`Textures/Items/`, `Textures/Paper/`, `Sounds/`, `Localization/`, `LootTables/`, `Books/`), `ModHook` events, `ModScanner` capability rules, and Steam Workshop publishing. 2. **Custom NPC Framework Specification**: from this documentation site (and the single-file context [`/llms-full.txt`](/llms-full.txt)), which defines the zero-reference `NpcFrameworkSdk.cs` bridge, 5-phase customer generation, per-save storyline state store (`cnpcf_`), `288×211` customer portrait injection, and all 18 Customer Subsystems. --- ## 1. Copy-Paste Starter Prompts for AI Coding Agents Copy and send either of the prompts below to your AI coding assistant so it ingests both the official modding guide and the Custom NPC Framework specification before guiding you step-by-step: ### Prompt Template A: Interactive End-to-End Mod Creation (Recommended) ```markdown Please read the following two sets of technical documentation for Probably Stolen modding first: 1. Official Probably Stolen Modding Guide (project layout, mandatory manifest.xml and tags, IMod lifecycle, ModLog, custom items/sounds/localization asset loading, ModHook events, and ModScanner rules): - Quick Start: https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/README.md - Advanced Modding Guide: https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/ModdingGuide.md - API Changes: https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/APIChanges.md 2. Custom NPC Framework Complete Specification (6-step AI Agent workflow, full NpcFrameworkSdk.cs source code, all 18 Customer Subsystems, vanilla item/tag/sprite dictionaries, and full code breakdowns of both example mods): - Workflow Guide: https://customnpc.netlify.app/en/guide/agent-workflow - Single-File Full Context: https://customnpc.netlify.app/llms-full.txt After reading, do not write code blindly. Walk me through the [6-Step Interactive Requirement Checklist] to confirm: 1. Mod metadata (Mod ID, display name, author) and whether the mod also needs custom items (GameItem), custom sounds, or loot table edits; 2. The new NPC's identity, faction (clientFaction), and portrait source (built-in SpriteDict pool vs. custom 288x211 PNG in Textures/); 3. Spawn phase (spawnPhase), day window, cooldown days, and spawn probability; 4. Core trade intent (regular BUY, regular SELL, Wholesale lot, BarterOffer, multi-day Procurement contract, or Custom GunOrder); 5. Multi-day storyline state machine (cnpcf_ save keys) and branching outcomes; 6. World integrations (7-digit holophone contact, handwritten note, store terminal request bounty StoreRequest, next-day newspaper headline TriggerNews, interrogation/smart-glasses scan dialogue, wanted arrest cutscene, afterhour events). Once confirmed, generate the complete Modding/ project (.csproj, manifest.xml, NpcFrameworkSdk.cs, IMod entry class) and Mods/ deployment folder following the official manifest and zero-capability scanner rules. ``` ### Prompt Template B: Rapid Multi-Act Storyline NPC Generation ```markdown Read the official modding guide https://raw.githubusercontent.com/dragonpan2/probably-stolen-modding/main/ModdingGuide.md and the Custom NPC Framework full specification https://customnpc.netlify.app/llms-full.txt . I want to create a multi-act storyline NPC mod for Probably Stolen named [Character Name]. Ask me to confirm each act's trade intent, items (vanilla item IDs vs. custom items), dialogue branches, and rewards first, then output a complete, buildable C# mod project that passes mod-scan with empty . ``` --- ## 2. Official Base Modding Rules (`dragonpan2/probably-stolen-modding`) Every mod generated by an AI Agent must follow the base rules established in the official repository: ### 2.1 Standard Folder Layout Inside the game installation folder (next to `Probably Stolen.exe`), `Modding/` holds source projects and `Mods/` holds runtime mod folders: ```text Probably Stolen/ ├── Probably Stolen.exe ├── dev.txt # Optional empty file: enables F8 Debug Console and F9 Dev Menu ├── Mods/ │ └── MyCustomNPCPack/ │ ├── manifest.xml # Mandatory: root element must be │ ├── MyCustomNPCPack.dll # Mandatory: listed under │ ├── preview.png # Optional: Workshop & Mods menu preview (< 1 MB recommended) │ ├── Textures/ │ │ ├── my_npc.png # General texture (288x211 NPC portraits go here; auto-injected into SpriteDict) │ │ ├── Items/ │ │ │ └── custom_item.png # Custom item sprite (must sit directly in Textures/Items/) │ │ └── Paper/ │ │ └── page_bg.png # Paper book art (must sit directly in Textures/Paper/) │ ├── Sounds/ │ │ └── custom_sfx.wav # Custom audio (registered as ":custom_sfx") │ └── Localization/ │ ├── en.csv # English localization (UTF-8, no header: key,text) │ └── zh.csv # Chinese localization └── Modding/ └── MyCustomNPCPack/ ├── MyCustomNPCPack.csproj ├── manifest.xml ├── NpcFrameworkSdk.cs # Zero-reference bridge SDK file └── MyCustomNPCPackMod.cs # IMod entry class ``` > **Note**: Asset folder scanning is **not recursive**. Item sprites must sit directly in `Textures/Items/`, paper art in `Textures/Paper/`, general/NPC textures in `Textures/`, sounds in `Sounds/`, and localization CSVs in `Localization/`. ### 2.2 Mandatory `manifest.xml` Schema The root element of `manifest.xml` must be **``**, and both **``** and **``** are mandatory: ```xml my_custom_npc_pack 我的自定义NPC扩展包 / My Custom NPC Pack YourName 1.0.0 Custom NPC and storyline add-on built on Custom NPC Framework. 0.46 CustomNPCFramework MyCustomNPCPack.dll ``` - **``**: ASCII letters, digits, `_`, `-`, and `.` only (cannot start with `.`, max 64 chars). - **``**: list dependencies using `CustomNPCFramework`. - **``**: list every DLL in the mod folder; any unlisted DLL or game assembly copy (`0Harmony.dll`, `Assembly-CSharp.dll`) refuses activation. - **``**: keep empty (``). ### 2.3 `.csproj` Configuration Target **`netstandard2.1`** and set **`false`** on all game assembly references so they are never copied into `Mods//`: ```xml netstandard2.1 MyCustomNPCPack MyCustomNPCPack latest false false $(MSBuildProjectDirectory)/../../Probably Stolen_Data/Managed $(ManagedDir)/Assembly-CSharp.dll false $(ManagedDir)/UnityEngine.dll false $(ManagedDir)/UnityEngine.CoreModule.dll false $(ManagedDir)/0Harmony.dll false ``` ### 2.4 Combining Custom NPCs with Custom Items (`OnModItemDirectoryInit`) If your custom NPC needs to buy, sell, or reward a brand-new item not in vanilla: 1. Place the item sprite PNG in `Mods//Textures/Items/.png` (sized to `64px` per inventory grid cell); 2. Subscribe to `ModHook.OnModItemDirectoryInit += RegisterItems;` in `OnEnable()` (and unsubscribe in `OnDisable()`); 3. Inside `RegisterItems()`, create the item with `ItemDirectory.CreateEmptyItem("")` and bind its sprite and grid shape via `item.SetSpriteAndShapeFromMod("", "")`; 4. Reference `""` in `sc.clientBuyingIdList.Add("")` or `PlayerStore.Instance.AddDirectSellingItemToTable("", ...)`. --- ## 3. 6-Step Interactive Requirement Checklist for AI Agents 1. **Step 1 — Mod Metadata & Custom Assets**: confirm ``, display name, author, and whether custom items (`Textures/Items/`) or sounds (`Sounds/`) are needed alongside the NPC. 2. **Step 2 — Identity, Faction & Portrait**: confirm `identifier`, bilingual display names, `clientFaction` (from the 8 vanilla factions), and `spriteName` (70+ built-in `SpriteDict` methods vs. custom `288×211` PNG in `Textures/`). 3. **Step 3 — Spawn Scheduling**: confirm `spawnPhase` (`1` Early for story acts, `2` Normal for recurring visitors), `priority`, `minDay`, `cooldownDays`, and `spawnChancePercent`. 4. **Step 4 — Core Trade Intent (`ClientIntent`)**: select from regular `BUY`, regular `SELL`, `Wholesale` bundle, `BarterOffer`, `AttachProcurementOffer`, `BuildCustomGunOrder`, or `DIALOGUE` investigation. 5. **Step 5 — Multi-Day Storyline State Machine**: define `cnpcf_` save keys (`GetSaveInt` / `SetSaveInt`), register an auto-dispatcher entry (`minDay = 9999, spawnChancePercent = 0`), and advance stages inside `acceptDealDialogue`, `allDoneDialogue`, or dialogue choice callbacks. 6. **Step 6 — World Subsystems**: confirm optional `interogationDialogue`, `glasseDialogue`, realtime scale callbacks (`onItemAddedToWeighted`), `SetWanted` + `customOnArrestDialogue`, `RegisterPhoneContact`, `GiveHandnoteToPlayer`, `PostStoreRequest`, `TriggerNews`, or `RegisterAfterhourEvent`. --- ## 4. Pre-Publish Verification Checklist 1. **Do not touch gameplay singletons inside `Init` or `OnEnable`**: `Init` and `OnEnable` run at the Main Menu before any save is loaded. Only access `PlayerStore.Instance` or `StoreStation.Instance` inside `clientFactory` or gameplay hooks. 2. **Always call `sc.CompleteClientCreation(false)` before returning a `StoreClient`** (followed by `sc.CompleteSecClient()` for Security dialogue encounters). 3. **Pass `DirectoryMaster.Item("$", true)` as the placeholder item in `Dialogue.AddChoice`**, and end non-trade dialogue branches with `DialogUIManager.Instance?.CurrentClientLeave(1f)`. 4. **Keep `sc.isAug = false` for non-monster characters** (`isAug = true` is reserved for hostile disguised Aug monsters). 5. **Verify zero-capability compliance**: run `mod-scan ` in the F8 console (with `dev.txt` present) to confirm the DLL requires no ``. ================================================================================ ## en/guide/quick-start.md ================================================================================ --- layout: doc title: "Quick Start: Your First Custom NPC Mod" --- # Quick Start: Your First Custom NPC Mod Building on the base modding rules in the official repository [`dragonpan2/probably-stolen-modding`](https://github.com/dragonpan2/probably-stolen-modding/) ([`README.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/README.md) and [`ModdingGuide.md`](https://github.com/dragonpan2/probably-stolen-modding/blob/main/ModdingGuide.md)), this guide walks you through creating a buildable, scanner-compliant custom NPC mod that requires zero assembly references to `CustomNPCFramework.dll` and zero extra security capabilities. --- ## 1. Folder Structure Inside the game installation folder (next to `Probably Stolen.exe`), `Modding/` holds source projects and `Mods/` holds runtime mod folders: ```text Probably Stolen/ ├── Probably Stolen.exe ├── dev.txt # Optional empty file: enables F8 Debug Console and F9 Dev Menu ├── Mods/ │ ├── MyCustomNPCPack/ │ │ ├── MyCustomNPCPack.dll │ │ ├── manifest.xml │ │ ├── preview.png │ │ └── Textures/ │ │ └── my_npc.png │ ├── MyCustomNPCPack.vdf │ └── MyCustomNPCPack.bat └── Modding/ └── MyCustomNPCPack/ ├── MyCustomNPCPack.csproj ├── NpcFrameworkSdk.cs ├── MyCustomNPCPackMod.cs └── manifest.xml ``` --- ## 2. Project File (`.csproj`) Target `netstandard2.1` and reference the game assemblies with `false` so they are never copied into your mod output folder: ```xml netstandard2.1 MyCustomNPCPack MyCustomNPCPack latest false false $(MSBuildProjectDirectory)/../../Probably Stolen_Data/Managed $(ManagedDir)/Assembly-CSharp.dll false $(ManagedDir)/UnityEngine.dll false $(ManagedDir)/UnityEngine.CoreModule.dll false $(ManagedDir)/0Harmony.dll false ``` --- ## 3. Mandatory `manifest.xml` Follow the official `` schema with ``, ``, ``, and an empty `` element: ```xml my_custom_npc_pack 我的自定义NPC扩展包 / My Custom NPC Pack YourName 1.0.0 Custom NPC and storyline add-on built on Custom NPC Framework. 0.46 CustomNPCFramework MyCustomNPCPack.dll ``` --- ## 4. Implementing `IMod` and Registering an NPC Copy `NpcFrameworkSdk.cs` into your project folder, then implement `IMod` using `ModLog`: ```csharp using System; using UnityEngine; namespace MyCustomNPCPack { public class MyCustomNPCPackMod : IMod { private ModLog _log; public void Init(ModManifest manifest) { _log = new ModLog(manifest); RegisterAllNpcs(); _log.Log("Initialized."); } public void OnEnable() { RegisterAllNpcs(); _log?.Log("Enabled."); } public void OnDisable() { } private static string T(string zh, string en) => NpcFrameworkSdk.T(zh, en); private static void RegisterAllNpcs() { NpcFrameworkSdk.RegisterNpc( id: "back_alley_doc", displayNameGetter: () => T("暗巷黑医", "Back-Alley Ripperdoc"), spawnPhase: 2, priority: 55, minDay: 2, cooldownDays: 3, spawnChancePercent: 40, oncePerSave: false, canSpawnPredicate: () => true, clientFactory: CreateBackAlleyDoc); } private static StoreClient CreateBackAlleyDoc() { var sc = new StoreClient { identifier = "back_alley_doc", displayName = T("暗巷黑医", "Back-Alley Doc"), spriteName = SpriteDict.GetRandomMedSpriteName(), clientFaction = "FACTION_BLACK_MARKET", clientIntent = StoreClient.ClientIntent.BUY, buyPriceModifier = 35, CanExposeChem = true, staysAfterFailedBargain = true }; sc.SetBudget(420); sc.clientBuyingTagList.Add("MEDICAL"); sc.clientBuyingIdList.Add("blood_bag"); sc.clientBuyingIdList.Add("blue_blood_bag"); sc.AddCheck("CHECK_EXPIRED"); sc.mainDialogue .SetText(sc.displayName, T("嘘……我诊所今晚有台急诊义体移植手术。", "Keep your voice down. Got an emergency implant surgery tonight.")) .NextDialogue() .SetText(sc.displayName, T("你这儿有未过期的血袋或紫色针剂吗?我出高价收。", "Got any unexpired blood bags or purple injectors? Paying top credit.")); sc.placeRightItemWhenSellingToDialogue = new Dialogue() .SetText(sc.displayName, T("保存得很完好,正是手术急需的批次。", "Clean seal. Exactly what I need for the operating table.")); sc.acceptDealDialogue = new Dialogue() .SetText(sc.displayName, T("谢了,这笔药能救回一条命。", "Thanks. These supplies will save a life tonight.")) .SetEndAction(() => NpcFrameworkSdk.AddSaveInt("doc_deals", 1, 0)); sc.interogationDialogue = new Dialogue() .SetText(sc.displayName, T("下层区医院早就断供了,不去黑市淘药,伤员只能等死。", "Lower Levels clinics ran dry months ago.")); sc.glasseDialogue = new Dialogue() .SetText("PLAYER", T("(他的白大褂袖口藏着精密手术刀,双手稳得没有一丝颤抖。)", "(Surgical scalpels are tucked inside his cuffs; his hands are impossibly steady.)")); sc.CompleteClientCreation(false); return sc; } } } ``` ================================================================================ ## en/guide/sprite-art-pipeline.md ================================================================================ --- layout: doc title: "Customer Sprite Dimensions & Outline Spec" --- # Customer Sprite Dimensions & Outline Specification In *Probably Stolen*, customer portraits are rendered behind the shop window by `StoreClientMono.Instance.image` (`SpriteRenderer`). This section documents the geometry of the standard `288×211` customer canvas, top headroom alignment, and outer contour color conventions. ![Customer Sprite Canvas Proportions](/images/en/v_size_compare.png) --- ## 1. Standard Customer Sprite Geometry Vanilla customer textures use a `288 × 211` canvas (`100 PPU`, pivot `(0.5, 0.5)`, `FilterMode.Point`): | Metric | `trailer_scav1` (Billy) | `serpico_scav` (Scav) | `serpico_rev` (Rev) | **Custom Sprite Standard (`v_normal`)** | | :--- | :--- | :--- | :--- | :--- | | **Total Canvas Size** | `288 × 211` | `288 × 211` | `288 × 211` | **`288 × 211` (RGBA PNG)** | | **Horizontal Range (`x`)** | `83 .. 205` (width `123px`) | `65 .. 222` (width `158px`) | `65 .. 221` (width `157px`) | **`55 .. 232` (width `150 ~ 178px`)** | | **Vertical Range (`y`)** | `57 .. 210` (height `154px`) | `47 .. 210` (height `164px`) | `51 .. 210` (height `160px`) | **`55 .. 210` (height `154 ~ 162px`)** | | **Top Transparent Margin** | `57 px` | `47 px` | `51 px` | **`50 ~ 56 px`** | | **1px Outer Outline Color** | Dark charcoal-purple | Dark charcoal-purple | Dark charcoal-purple | **`RGB(36, 33, 43)`** | --- ## 2. Canvas Alignment & Outline Normalization Script The Python (`Pillow` + `NumPy`) script below scales a portrait to `target_h = 156` (bottom-aligned at `y = 210` with `55px` top headroom) and applies the standard `RGB(36, 33, 43)` 1px outer contour: ```python from PIL import Image import numpy as np def normalize_portrait_to_vanilla_canvas(src_rgba_path, out_normal_path, target_h=156): raw = Image.open(src_rgba_path).convert("RGBA") arr = np.array(raw, dtype=np.int32) fg = arr[:, :, 3] > 128 ys, xs = np.where(fg) crop = Image.fromarray(arr[ys.min():ys.max()+1, xs.min():xs.max()+1].astype(np.uint8), "RGBA") scale = target_h / crop.height target_w = int(round(crop.width * scale)) resized = crop.resize((target_w, target_h), Image.NEAREST) canvas = Image.new("RGBA", (288, 211), (0, 0, 0, 0)) ox = (288 - target_w) // 2 oy = 211 - target_h canvas.paste(resized, (ox, oy), resized) c_arr = np.array(canvas, dtype=np.int32) c_fg = c_arr[:, :, 3] > 128 c_arr[~c_fg] = [0, 0, 0, 0] c_arr[c_fg, 3] = 255 pad = np.pad(c_fg, 1, mode="constant", constant_values=False) is_outer_contour = c_fg & (~(pad[:-2, 1:-1] & pad[2:, 1:-1] & pad[1:-1, :-2] & pad[1:-1, 2:])) is_outer_contour[210, :] = False c_arr[is_outer_contour, 0] = 36 c_arr[is_outer_contour, 1] = 33 c_arr[is_outer_contour, 2] = 43 c_arr[is_outer_contour, 3] = 255 Image.fromarray(c_arr.astype(np.uint8), "RGBA").save(out_normal_path) ``` ================================================================================ ## en/architecture/bridge-and-lifecycle.md ================================================================================ --- layout: doc title: Zero-Reference AppDomain Bridge & Hook Points --- # 2.1 Zero-Reference AppDomain Bridge & IMod Lifecycle This section explains how `CustomNPCFrameworkMod.cs`, `NpcFrameworkRegistry.cs`, and add-on packs (`NpcFrameworkSdk.cs`) achieve **zero-DLL-reference coupling, load-order independence, and 100% `ModScanner` compliance**. --- ## 1. Why Use `AppDomain.CurrentDomain` Delegate Bridging? 1. **Load-Order Independence**: `ModLoader` may initialize add-on packs (`CyberpunkMercV`, `RestoredUnusedNPCs`) either before or after `CustomNPCFramework`. 2. **Static Scanner Compliance (`ModScanner`)**: reflecting into private members triggers security warnings, whereas `System.AppDomain.CurrentDomain.GetData(string)` and `SetData(string, object)` use standard BCL types (`Dictionary`, `Action<...>`, `Func<...>`) and require zero declared ``. --- ## 2. The Three Global Data Slots ```csharp public const string BridgeKey = "CustomNPCFramework.Bridge.v1"; public const string PendingQueueKey = "CustomNPCFramework.PendingQueue.v1"; public const string PendingPhoneQueueKey = "CustomNPCFramework.PendingPhoneQueue.v1"; ``` ### 2.1 `InitializeBridge()` Full Delegate Table ```csharp public static void InitializeBridge() { var bridge = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["RegisterNpc"] = new Action>(RegisterFromDictionary), ["SummonNpcNow"] = new Func(SummonNpcImmediate), ["ResolveSprite"] = new Func(NpcTraitHelper.ResolveValidSpriteName), ["GetSaveInt"] = new Func(NpcSaveStore.GetInt), ["SetSaveInt"] = new Action(NpcSaveStore.SetInt), ["AddSaveInt"] = new Func(NpcSaveStore.AddInt), ["GetSaveBool"] = new Func(NpcSaveStore.GetBool), ["SetSaveBool"] = new Action(NpcSaveStore.SetBool), ["GetSaveString"] = new Func(NpcSaveStore.GetString), ["SetSaveString"] = new Action(NpcSaveStore.SetString), ["RegisterPhoneContact"] = new Action>(NpcPhoneRegistry.RegisterFromDictionary), ["SyncPhoneContacts"] = new Action(NpcPhoneRegistry.SyncPhoneContactsToPlayerStore), ["ApplyClientProfile"] = new Action>(NpcFullFeatureKit.ApplyClientProfile), ["CreateHandnoteItem"] = new Func(NpcFullFeatureKit.CreateHandnoteItem), ["CreatePaperNoteItem"] = new Func(NpcFullFeatureKit.CreatePaperNoteItem), ["SpawnItemOnCounterOrStore"] = new Func(NpcFullFeatureKit.SpawnItemOnCounterOrStore), ["GiveHandnoteToPlayer"] = new Func(NpcFullFeatureKit.GiveHandnoteToPlayer), ["PostStoreRequest"] = new Func, bool>(NpcFullFeatureKit.PostStoreRequestFromDictionary), ["AttachProcurementOffer"] = new Action>(NpcFullFeatureKit.AttachProcurementOffer), ["BuildCustomGunOrder"] = new Func, GunOrderData>(NpcFullFeatureKit.BuildCustomGunOrder), ["RegisterAfterhourEvent"] = new Func, bool>(NpcFullFeatureKit.RegisterAfterhourEventFromDictionary), ["RegisterNightlyHook"] = new Action(NpcFullFeatureKit.RegisterNightlyHook), ["RegisterDumpingGroundWatcher"] = new Action>(NpcFullFeatureKit.RegisterDumpingGroundWatcher), ["TriggerNews"] = new Action(NpcTraitHelper.TriggerCustomNewspaper) }; AppDomain.CurrentDomain.SetData(BridgeKey, bridge); DrainPendingQueue(); NpcPhoneRegistry.SyncPhoneContactsToPlayerStore(); } ``` --- ## 3. All 11 Subscribed `ModHook` Events | Subscribed `ModHook` Event | Trigger Timing | Framework Handler & Behavior | | :--- | :--- | :--- | | `OnGenerateCustomerVeryEarly` .. `VeryLate` | `GenerateClient()` Phases 0..4 | Runs `HandleGenerationPhase(mgr, phase)` and places any pending debug summon at `clientStack[0]` at the end of `VeryLate`. | | `OnShutterOpenedLate` | Morning shutter fully opened | Syncs textures, drains pending queues, applies deferred save resets, and runs `ConsumePendingDebugSummonOnShutterOpened()` to verify `clientStack[0]` and call `TryCallNextClient()`. | | `OnGameLoadedInit` | Save file loaded into the store scene | Syncs all mod textures, syncs holophone contacts to `PlayerStore.PhoneClientDict`, and restores pending debug state. | | `OnModAssetsLoaded` | Any mod's `Textures/` assets finish loading | Runs `RegisterModTexturesToSpriteDict(mod)` to register `100 PPU`, `FilterMode.Point` sprites into `SpriteDict` and refreshes debug dropdown options. | | `OnModConfigApplied` | Player clicks Apply in Mod Config | Processes save resets and debug summon selections. | | `OnGoingSleepEarly` / `OnAfterhourLeaveEarly` | Before sleeping / leaving afterhour area | Fires callbacks registered via `RegisterNightlyHook` and `RegisterDumpingGroundWatcher`. | ================================================================================ ## en/architecture/generation-pipeline.md ================================================================================ --- layout: doc title: 5-Phase Customer Generation & Debug Priority --- # 2.2 5-Phase Customer Generation Pipeline & Debug Priority Insertion This section examines the decompiled IL execution flow of `PlayerStore.OnShutterOpened` and `StoreClientManager.GenerateClient` in `Assembly-CSharp.dll`, the 7-step eligibility filter in `HandleGenerationPhase`, and how `ForceInsertClientAtFront` guarantees top-of-queue placement. --- ## 1. Decompiled Morning Shutter & `GenerateClient()` Execution Flow ```text StoreShutterButton.OpenShutter() ├── 1. PlayerStore.Instance.OnShutterOpened() │ ├── CheckCrime() / SoldItem.HandleSoldItem() │ ├── this.storeClientManager.GenerateClient() │ │ ├── ModHook.FireOnGenerateCustomerVeryEarly(this) │ │ ├── [Vanilla fixed-day story customer generation] │ │ ├── ModHook.FireOnGenerateCustomerEarly(this) │ │ ├── [Vanilla regular customer pool sampling] │ │ ├── ModHook.FireOnGenerateCustomerNormal(this) │ │ ├── [Vanilla specialist & showcase customer generation] │ │ ├── ModHook.FireOnGenerateCustomerLate(this) │ │ ├── this.ClientGenCheck() │ │ ├── this.HandleJohnSmithVandalVisit() // <-- Calls AddNextClient, inserting at index 0! │ │ ├── LouBombHelper.QueueVisit(this) // <-- Calls AddNextClient, inserting at index 0! │ │ └── ModHook.FireOnGenerateCustomerVeryLate(this) │ ├── this.HandleFutureClientQueue() // Appends scheduled future clients to clientStack │ ├── this.storeClientManager.clientStack.RemoveAll(c => c == null) │ └── this.LogQueuedClient() // Logs today's queued client list to F8 console │ ├── 2. PlayerStore.Instance.OpenShutter() │ └── this.storeState = PlayerStore.StoreState.OPEN (value 1) │ ├── 3. StoreShutterButton.OnShutterDoorOpenMorning() │ ├── ModHook.FireOnShutterOpenedEarly() │ ├── [Spawns morning newspaper, tutorial book, gun license, dividends] │ └── ModHook.FireOnShutterOpenedLate() // <-- Framework verifies index 0 & auto-calls door! │ └── 4. PlayerStore.Instance.OnLateShutterOpen() └── [Checks SetupWaitingClient for morning door events] ``` --- ## 2. `ForceInsertClientAtFront` Bypassing Vanilla Blacklist Guards Decompiling `StoreClientManager.AddNextClient(StoreClient)` reveals two silent guards (`IsClientBlockedByKnownSnitch` and `IsClientBlockedByBannedCommissary`) that can silently drop a summoned customer. `ForceInsertClientAtFront` deduplicates any earlier natural spawn of the same NPC, inserts directly into `mgr.clientStack.Insert(0, client)`, registers tracking via `mgr.TrackClient(client)`, and schedules `TryCallNextClient()` once the shutter opens: ```csharp internal static bool ForceInsertClientAtFront(StoreClientManager mgr, NpcRegistrationEntry entry, bool autoCallIfDoorEmpty, bool delayedCall) { if (mgr == null || entry == null) return false; var client = BuildSafeClient(entry); if (client == null) return false; if (mgr.clientStack == null) mgr.clientStack = new List(); string targetId = client.identifier ?? entry.Id; mgr.clientStack.RemoveAll(c => c != null && string.Equals(c.identifier, targetId, StringComparison.OrdinalIgnoreCase)); mgr.clientStack.Insert(0, client); mgr.TrackClient(client); int day = StoreStation.Instance != null ? StoreStation.Instance.dayCounter : 1; RecordSpawn(entry, day); entry.OnSpawned?.Invoke(); if (autoCallIfDoorEmpty) ScheduleAutoCallFirstClient(delayedCall); return true; } ``` ================================================================================ ## en/architecture/save-and-config.md ================================================================================ --- layout: doc title: Saving Mod Data & Mod Configuration --- # Saving Mod Data & Mod Configuration ## Per-Run Save Data (`NpcSaveStore`) `PlayerStore.Instance.ModData()` provides a `Dictionary` persisted inside the active save file. `NpcSaveStore` wraps this dictionary with a `"cnpcf_"` prefix and an in-memory fallback dictionary `MemoryFallback` when accessed from the Main Menu: ```csharp NpcFrameworkSdk.SetSaveInt("v_stage", 1); int stage = NpcFrameworkSdk.GetSaveInt("v_stage", 0); int totalDeals = NpcFrameworkSdk.AddSaveInt("v_deals", 1, 0); ``` When the player toggles **"Reset Current Save NPC Storyline Progress"** in the Mod Config window, `NpcSaveStore.ResetAllFrameworkKeys()` removes all `"cnpcf_"` keys from the current save's `ModData()` dictionary. --- ## Mod Configuration (`ModConfig`) `CustomNPCFrameworkMod` defines two sections via `ModConfig.For("CustomNPCFramework")`: 1. **General & Spawn Settings**: - `language`: Auto (follow game locale), Simplified Chinese, or English; - `enabled`: master switch for daily automatic spawning; - `spawn_rate_percent`: slider (`25% .. 300%`) scaling `SpawnChancePercent` across all add-on packs. 2. **Developer Debug Panel**: - `debug_summon_id`: dynamic dropdown listing auto-storyline dispatchers (`v`, `billy`) and all registered NPC IDs; - `debug_reset_save`: one-click toggle to reset storyline progress for the active save. ================================================================================ ## en/architecture/glitch-and-textures.md ================================================================================ --- layout: doc title: Dynamic Texture Injection & Sprite Fallbacks --- # 2.4 Dynamic Texture Injection & Sprite Fallbacks This section explains how `CustomNPCFramework` automatically converts `Textures/*.png` from loaded mods into `SpriteDict` entries, and how `ResolveValidSpriteName` guarantees safe fallback portraits. --- ## 1. Automatic Customer Sprite Registration (`RegisterModTexturesToSpriteDict`) When `ModLoader` loads a mod, it reads all `.png` files in `Mods//Textures/` into `LoadedMod.Textures` (`Dictionary`, keyed by filename without extension). Because `StoreClientMono` resolves customer portraits from `SpriteDict.Instance.spriteDictionary` (`Dictionary`), `CustomNPCFrameworkMod` runs `RegisterModTexturesToSpriteDict` during `OnEnable`, `OnModAssetsLoaded`, `OnGameLoadedInit`, and `OnShutterOpenedLate`: ```csharp private static void RegisterModTexturesToSpriteDict(LoadedMod mod) { try { if (mod?.Textures == null || mod.Textures.Count == 0) return; var sd = SpriteDict.Instance; if (sd?.spriteDictionary == null) return; foreach (var kv in mod.Textures) { string key = kv.Key; Texture2D tex = kv.Value; if (string.IsNullOrEmpty(key) || tex == null) continue; if (sd.spriteDictionary.ContainsKey(key)) continue; tex.filterMode = FilterMode.Point; tex.wrapMode = TextureWrapMode.Clamp; var sp = Sprite.Create(tex, new Rect(0f, 0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100f); sp.name = key; sd.spriteDictionary[key] = sp; Log?.Log($"Registered custom NPC sprite '{key}' from mod '{mod.Manifest?.ID}'."); } } catch (Exception ex) { Log?.Warning("RegisterModTexturesToSpriteDict: " + ex.Message); } } ``` --- ## 2. Safe Portrait Resolution & Fallback Mapping (`ResolveValidSpriteName`) When `BuildSafeClient` constructs a `StoreClient`, it validates `client.spriteName` through `NpcTraitHelper.ResolveValidSpriteName`: 1. If `spriteName` exists in `SpriteDict.Instance.spriteDictionary`, it is returned directly; 2. Legacy cut-content keys (`"billy"`, `"cul1"`, `"sha3"`) are mapped to existing vanilla sprites (`"trailer_scav1"`, `"spy"`, `"trailer_scav3"`); 3. Any unresolvable key falls back to `SpriteDict.GetRandomLowerLevelSpriteName()`. ================================================================================ ## en/subsystems/01-regular-buying.md ================================================================================ --- layout: doc title: 01. Regular Buying & Wishlists (BUY) --- # 01. Regular Buying & Wishlists (`ClientIntent.BUY`) A regular buyer enters the shop looking for items matching specific category tags or item IDs. The player places matching stock from the shelves or back inventory onto the counter and negotiates a sale within the buyer's budget. --- ## Core Fields & Methods | Field / Method | Type | Description | | :--- | :--- | :--- | | `sc.clientIntent` | `StoreClient.ClientIntent` | Set to `StoreClient.ClientIntent.BUY` (`1`). | | `sc.SetBudget(int amount)` | `void` | Sets the maximum credit budget the buyer brings to the counter. | | `sc.useClientBudget` | `bool` | Enables budget checking (default `true`). | | `sc.clientBuyingTagList` | `List` | Accepted item category tags (e.g. `"MEDICAL"`, `"FIREARM"`). | | `sc.clientBuyingIdList` | `List` | Specific accepted `itemID` values (e.g. `"blood_bag"`, `"aug_chip"`). | | `sc.clientBlackTagList` | `List` | Blacklisted item category tags the buyer refuses to purchase. | | `sc.clientBlackIdList` | `List` | Blacklisted `itemID` values the buyer refuses to purchase. | | `sc.SetVariety()` | `void` | Requires distinct item types when buying multiple items in a single visit. | --- ## Code Example: Dedicated Medical Buyer ```csharp private static StoreClient CreateMedicalBuyer() { var sc = new StoreClient { identifier = "clinic_runner", displayName = NpcFrameworkSdk.T("诊所跑腿员", "Clinic Runner"), spriteName = SpriteDict.GetRandomMedSpriteName(), clientFaction = "FACTION_LOWER_LEVEL", clientIntent = StoreClient.ClientIntent.BUY, buyPriceModifier = 25 }; sc.SetBudget(360); sc.clientBuyingTagList.Add("MEDICAL"); sc.clientBuyingIdList.Add("blood_bag"); sc.clientBuyingIdList.Add("hemostatic_bandage_item"); sc.clientBlackTagList.Add("NARCOTIC"); sc.mainDialogue.SetText(sc.displayName, NpcFrameworkSdk.T("下层区诊所急需一批医疗物资,你有血袋或者止血绷带吗?", "The clinic needs medical supplies. Got any blood bags or hemostatic bandages?")); sc.placeRightItemWhenSellingToDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("太好了,正是我们需要的。", "Great, that's exactly what we need.")); sc.acceptDealDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("多谢,这就送回诊所。", "Thanks, taking these straight back to the clinic.")); sc.CompleteClientCreation(false); return sc; } ``` ================================================================================ ## en/subsystems/02-regular-selling.md ================================================================================ --- layout: doc title: 02. Regular Selling & Item Offers (SELL) --- # 02. Regular Selling & Item Offers (`ClientIntent.SELL`) When a customer visits with `ClientIntent.SELL` (or `ClientIntent.SELLNBUY`), they place one or more items onto the counter at the end of their opening dialogue for the player to inspect and purchase. --- ## Core Fields & Counter Spawning Method | Field / Method | Type | Description | | :--- | :--- | :--- | | `sc.clientIntent` | `StoreClient.ClientIntent` | Set to `StoreClient.ClientIntent.SELL` (`2`) or `SELLNBUY` (`3`). | | `sc.sellPriceModifier` | `int` | Percentage price modifier on the seller's asking price (negative = cheaper). | | `PlayerStore.Instance.AddDirectSellingItemToTable` | `void` | Called inside `mainDialogue`'s `SetEndAction` to spawn the offered item onto the counter. | ### `AddDirectSellingItemToTable` Signature ```csharp PlayerStore.Instance.AddDirectSellingItemToTable( string itemId, // Item ID (e.g. "sci_keycard") bool isOwnedByPlayer, // Pass false when the customer is selling to the player bool isStolen, // Marks the item as stolen bool isContraband, // Marks the item as contraband int customPrice // Custom price; pass 0 to calculate automatically from base value ); ``` --- ## Code Example: Single-Item Scavenger Seller ```csharp private static StoreClient CreateSingleItemSeller() { var sc = new StoreClient { identifier = "keycard_finder", displayName = NpcFrameworkSdk.T("通风管拾荒者", "Vent Scavenger"), spriteName = SpriteDict.GetRandomScavSpriteName(), clientFaction = "FACTION_LOWER_LEVEL", clientIntent = StoreClient.ClientIntent.SELL, sellPriceModifier = -10 }; sc.mainDialogue .SetText(sc.displayName, NpcFrameworkSdk.T("我在通风井底下捡到一张科研门禁卡,你要收吗?", "Found a science keycard down in the air ducts. Interested?")) .SetEndAction(() => { PlayerStore.Instance?.AddDirectSellingItemToTable("sci_keycard", false, true, false, 0); }); sc.acceptDealDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("爽快!这下今晚能去喝一杯了。", "Sweet! Drinks are on me tonight.")); sc.CompleteClientCreation(false); return sc; } ``` ================================================================================ ## en/subsystems/03-wholesale-lots.md ================================================================================ --- layout: doc title: 03. Wholesale Lot Trading (Wholesale) --- # 03. Wholesale Lot Trading (`isOfferWholesale`) Wholesale mode allows a seller to place a multi-item bundle onto the counter at a flat percentage discount (e.g. `-30` for 30% off the entire lot). This subsystem powers Billy's Act 3 Medbay theft, the Greytide Scavenger, the Lower Levels Chemist, the Underground Arms Dealer, and V's Act 3 corporate vault heist. --- ## Required Setup 1. Set `sc.clientIntent = StoreClient.ClientIntent.SELL`; 2. Set `sc.isOfferWholesale = true`; 3. Set `sc.wholesaleDiscount = -30` (negative integer representing the percentage discount); 4. Call `PlayerStore.Instance.AddDirectSellingItemToTable(...)` for each item in the lot inside `sc.mainDialogue`'s final `SetEndAction`. --- ## Code Example: 30%-Off Vault Heist Wholesale Lot ```csharp private static StoreClient CreateVaultWholesaleSeller() { var sc = new StoreClient { identifier = "v_act3_heist", displayName = NpcFrameworkSdk.T("佣兵 V", "Mercenary V"), spriteName = "v_normal", clientFaction = "FACTION_BLACK_MARKET", clientIntent = StoreClient.ClientIntent.SELL, isOfferWholesale = true, wholesaleDiscount = -30 }; sc.mainDialogue .SetText(sc.displayName, NpcFrameworkSdk.T("金库被我们掀了个底朝天,剩下的尖端货全在这儿了。", "Cleaned out their vault. Brought the rest of the high-tech loot straight to you.")) .NextDialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("义体芯片、指挥官门禁卡、高能电池和冲锋枪,整包七折让给你!", "Aug chips, command keycards, hypertech battery, and an SMG. 30% off the whole lot!")) .SetEndAction(() => { var ps = PlayerStore.Instance; if (ps == null) return; ps.AddDirectSellingItemToTable("aug_chip", false, false, false, 0); ps.AddDirectSellingItemToTable("command_keycard", false, false, false, 0); ps.AddDirectSellingItemToTable("sci_keycard", false, false, false, 0); ps.AddDirectSellingItemToTable("energy_credit_hyp", false, false, false, 0); ps.AddDirectSellingItemToTable("smg", false, false, false, 0); }); sc.CompleteClientCreation(false); return sc; } ``` ================================================================================ ## en/subsystems/04-barter-and-begging.md ================================================================================ --- layout: doc title: 04. Barter & Begging (BarterOffer) --- # 04. Barter & Begging (`BarterOffer`) The barter subsystem (`ClientIntent.BARTER`) handles non-cash exchanges where a customer asks the player to hand over an item matching specific criteria (such as Billy begging for `"FOOD"` in Act 1 of `RestoredUnusedNPCs`). --- ## Core Classes & Methods | Class / Member | Type | Description | | :--- | :--- | :--- | | `StoreClient.ClientIntent.BARTER` | `ClientIntent` | Enum value `6`, marking the visit as a barter interaction. | | `sc.useClientBudget` | `bool` | Set to `false` to disable the credit budget bar. | | `sc.barterOffer` | `BarterOffer` | Barter configuration attached to the client. | | `BarterOffer.getBarterResult` | `Func` | Evaluates whether the player can fulfill the barter and returns `BarterResult { isAccepted, response }`. | | `sc.barterOffer.InstanciateOffer()` | `void` | Opens the vanilla item-handover UI when triggered from a dialogue choice. | | `EmporiumEntry.Instance.IsBackInvContainItemTag(string tag)` | `bool` | Checks whether the player's inventory contains at least one item with `tag`. | --- ## Code Example: Food Barter with Stock Fallback ```csharp var sc = new StoreClient { identifier = "billy1", displayName = NpcFrameworkSdk.T("比利", "Billy"), spriteName = "trailer_scav1", clientFaction = "FACTION_LOWER_LEVEL", clientIntent = StoreClient.ClientIntent.BARTER, useClientBudget = false }; sc.clientBuyingTagList.Add("FOOD"); sc.barterOffer = new BarterOffer { ownerClient = sc, barterTextBody = NpcFrameworkSdk.T("施舍一点食物?", "Spare Food?"), onInstance = () => { }, getBarterResult = () => { var res = new BarterResult(); bool hasFood = EmporiumEntry.Instance != null && EmporiumEntry.Instance.IsBackInvContainItemTag("FOOD"); res.isAccepted = hasFood; res.response = hasFood ? NpcFrameworkSdk.T("看起来太香了!", "That looks good!") : NpcFrameworkSdk.T("能分我一口吃的吗?", "Can you spare some food?"); return res; } }; ``` ================================================================================ ## en/subsystems/05-bargaining-and-patience.md ================================================================================ --- layout: doc title: 05. Bargaining, Impatience & Perfume --- # 05. Bargaining, Impatience & Perfume This subsystem controls how a customer behaves during price negotiation, how quickly their patience drains, whether they storm out after a rejected offer, and how much faction reputation a completed deal awards. --- ## Core Fields Reference | `StoreClient` Field | `ApplyClientProfile` Key | Type | Description | | :--- | :--- | :--- | :--- | | `buyPriceModifier` | `"BuyPriceModifier"` | `int` | Percentage markup the buyer is willing to pay above base value (e.g. `40` = +40%). | | `sellPriceModifier` | `"SellPriceModifier"` | `int` | Percentage modifier on a seller's asking price. | | `clientImpatience` | `"ClientImpatience"` | `int` | Controls how fast patience depletes during repeated counter-offers. | | `alwaysRejectBadBargain` | `"AlwaysRejectBadBargain"` | `bool` | Immediately rejects any offer beyond the threshold. | | `isBargainAvailable` | `"IsBargainAvailable"` | `bool` | Set to `false` to enforce a non-negotiable fixed price. | | `staysAfterFailedBargain` | `"StaysAfterFailedBargain"` | `bool` | If `true`, the client remains at the counter after a failed haggle instead of leaving. | | `perfumeInfluence` | `"PerfumeInfluence"` | `int` | Multiplier for how strongly store perfume boosts this client's price tolerance. | | `tradeReputationMultiplier` | `"TradeReputationMultiplier"` | `double` | Multiplier applied to faction reputation gained from trading (default `1.0`). | --- ## Code Example ```csharp NpcFrameworkSdk.ApplyClientProfile(sc, new Dictionary { ["BuyPriceModifier"] = 40, ["ClientImpatience"] = 1, ["StaysAfterFailedBargain"] = true, ["PerfumeInfluence"] = 2, ["TradeReputationMultiplier"] = 1.5 }); ``` ================================================================================ ## en/subsystems/06-contraband-and-labels.md ================================================================================ --- layout: doc title: 06. Contraband, Retail Markup & Labels --- # 06. Contraband, Retail Markup & Hazard Labels Customers across different factions have distinct rules regarding **contraband items**, **labeler retail price tags**, and **hazardous water warning labels**. --- ## Core Fields Reference | `StoreClient` Field | `ApplyClientProfile` Key | Type | Description | | :--- | :--- | :--- | :--- | | `noAcceptingContraband` | `"NoAcceptingContraband"` | `bool` | If `true`, the buyer strictly refuses any item marked as contraband. | | `AcceptingContrabandOverride` | `"AcceptingContrabandOverride"` | `bool` | If `true`, overrides faction defaults and forces the buyer to accept contraband. | | `chargesContrabandMarkup` | `"ChargesContrabandMarkup"` | `bool` | Whether a seller charges a risk premium when selling contraband to the player. | | `acceptRetailMarkup` | `"AcceptRetailMarkup"` | `bool` | Whether the buyer honors retail markup tags printed with the `labeler`. | | `refusesHazardousWaterLabel` | `"RefusesHazardousWaterLabel"` | `bool` | If `true`, the buyer rejects liquid containers bearing a hazardous water label. | --- ## Code Example: Contraband-Accepting Smuggler ```csharp var sc = new StoreClient { identifier = "smuggler_buyer", displayName = NpcFrameworkSdk.T("底舱走私客", "Lower-Deck Smuggler"), spriteName = SpriteDict.GetRandomShadySpriteName(), clientFaction = "FACTION_BLACK_MARKET", clientIntent = StoreClient.ClientIntent.BUY, noAcceptingContraband = false, AcceptingContrabandOverride = true, acceptRetailMarkup = false }; ``` ================================================================================ ## en/subsystems/07-inspection-checks.md ================================================================================ --- layout: doc title: 07. Item Defect Inspection Checks --- # 07. Item Defect Inspection Checks (`sc.AddCheck`) When buying items from the player, a customer can run any combination of the 9 vanilla defect checks via `sc.AddCheck(string checkName)`. If an item on the counter fails an active check (such as a rusted pistol or an expired blood bag), the customer flags the defect and penalizes or rejects the deal. --- ## All 9 Vanilla Inspection Check Constants | `NpcCheckNames` Constant | String Value | Defect Inspected | | :--- | :--- | :--- | | `NpcCheckNames.Freshness` | `"CHECK_FRESHNESS"` | Checks food and organic goods for spoilage. | | `NpcCheckNames.Rust` | `"CHECK_RUST"` | Checks firearms, tools, and metal items for surface rust. | | `NpcCheckNames.Dented` | `"CHECK_DENTED"` | Checks cans, armor, and weapon casings for dents. | | `NpcCheckNames.Expired` | `"CHECK_EXPIRED"` | Checks medical injectors, blood bags, and pills for expiration dates. | | `NpcCheckNames.OpenBox` | `"CHECK_OPEN_BOX"` | Checks boxed merchandise for broken seals. | | `NpcCheckNames.IngotFlashlight` | `"CHECK_INGOT_FLASHLIGHT"` | Uses flashlight inspection on bullion/ingots. | | `NpcCheckNames.IngotDetector` | `"CHECK_INGOT_DETECTOR"` | Uses a metal detector to spot counterfeit tungsten-core ingots. | | `NpcCheckNames.WaterFlashlight` | `"CHECK_WATER_FLASHLIGHT"` | Uses light inspection to check liquid turbidity. | | `NpcCheckNames.WaterStrip` | `"CHECK_WATER_STRIP"` | Uses test strips to check water contamination. | --- ## Code Example ```csharp sc.clientBuyingTagList.Add("FIREARM"); sc.clientBuyingTagList.Add("WEAPON"); sc.AddCheck("CHECK_RUST"); sc.AddCheck("CHECK_DENTED"); ``` ================================================================================ ## en/subsystems/08-expose-and-chem-grade.md ================================================================================ --- layout: doc title: 08. Counterfeit Expose & Chemical Grade --- # 08. Counterfeit Detection & Chemical Grade (`NpcExposePreset`) When a player attempts to pass off forged stamps, fake brand labels, or diluted chemical products, *Probably Stolen* evaluates `sc.canClientExposeFeature`, `sc.CanExposeChem`, and `sc.acceptedChemicalProductGrade` to determine whether the customer exposes the fraud. --- ## The 10 Expose Capacity Presets (`NpcExposePreset`) | Preset Enum | Vanilla `ClientCanExposeFunc` Delegate | Typical Customer Profile | | :--- | :--- | :--- | | `None (0)` | None | Naive passerby | | `Basic (1)` | `BasicClientExposeCapacity` | Standard citizen | | `Scav (2)` | `ScavClientExposeCapacity` | Scavenger familiar with scrap and tools | | `LowerLevel (3)` | `LLClientExposeCapacity` | Lower Levels resident | | `Security (4)` | `SecClientExposeCapacity` | Security officer trained to spot forgeries | | `Revolution (5)` | `RevClientExposeCapacity` | Revolutionary quartermaster | | `Tourist (6)` | `TouristClientExposeCapacity` | Off-world tourist | | `UpperLevel (7)` | `ULClientExposeCapacity` | Picky Upper Level elite | | `TradeBoard (8)` | `TradeBoardExposeCapacity` | Professional exchange broker | | `Odin (9)` | `OdinExposeCapacity` | Odin-tier specialist | | `All (10)` | `ALLExposeCapacity` | Omniscient expert (exposes all fake features) | --- ## Chemical Purity Thresholds ```csharp NpcFrameworkSdk.ApplyClientProfile(sc, new Dictionary { ["ExposePreset"] = 5, // Revolution ["CanExposeChem"] = true, ["AcceptedChemicalGrade"] = 2 }); ``` ================================================================================ ## en/subsystems/09-realtime-scale-and-counter.md ================================================================================ --- layout: doc title: 09. Realtime Scale, Counter & Showcase Hooks --- # 09. Realtime Scale, Counter & Showcase Callbacks `StoreClient` exposes 6 realtime item-interaction delegates plus addict/repeat dialogue fields so customers can react the instant an item touches the scale, counter, or showcase. --- ## The 6 Realtime Item Delegates | Delegate Field | Signature | When It Fires | | :--- | :--- | :--- | | `sc.onItemAddedToWeighted` | `Action` | Fires the moment an item or powder is placed onto the weighing scale. | | `sc.onItemRemovedToWeighted` | `Action` | Fires when an item is removed from the weighing scale. | | `sc.onItemAddedToCounters` | `Action` | Fires when an item is placed onto the counter trading zone. | | `sc.OnItemAddedToShowcase` | `Action` | Fires when an item is placed into a display showcase. | | `sc.onItemSold` | `Action` | Fires when the player sells an item to this customer `(item, price)`. | | `sc.onItemBought` | `Action` | Fires when the player buys an item from this customer `(item, price)`. | --- ## Code Example: Realtime Scale Reaction (`addictGeneralTrailer`) ```csharp sc.IsClientAddict = true; sc.CanReturn = true; sc.CanReturnAsBuyer = true; sc.onItemAddedToWeighted = item => { if (item != null && (item.IsTag("SUBSTANCE") || item.IsTag("NARCOTIC"))) { var d = new Dialogue().SetText(sc.displayName, NpcFrameworkSdk.T("对对对!就是这个劲儿!手别抖,多倒点!", "That's the stuff! Pour it on!")); DialogUIManager.Instance?.StartDialogue(d, false); } }; sc.repeatDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("求你了老板,我骨头缝都在发痒,快给我一点吧!", "Come on, I'm itching all over. Just give me a hit!")); ``` ================================================================================ ## en/subsystems/10-procurement-contracts.md ================================================================================ --- layout: doc title: 10. Multi-Day Procurement Contracts --- # 10. Multi-Day Procurement Contracts (`AttachProcurementOffer`) Procurement contracts (`ClientIntent.PROCUREMENT_OFFER` and `PROCUREMENT_COLLECT`) allow a customer to commission a specific item across multiple days. On the initial visit, the client pays `initialAdvanceCash` upfront and leaves a physical `procurement_slip` on the counter; after `dueInDays` days, the game automatically queues the client's return visit to collect the item and pay `finalRewardCash`. --- ## SDK Signature ```csharp public static void AttachProcurementOffer( StoreClient client, string clientName, string offerDescription, string collectDescription, int dueInDays, int initialAdvanceCash, int finalRewardCash, Func itemValidator) ``` --- ## Code Example: 3-Day Augmentation Chip Commission ```csharp private static StoreClient CreateChipProcurementClient() { var sc = new StoreClient { identifier = "cyber_surgeon_procure", displayName = NpcFrameworkSdk.T("高阶义体外科主任", "Senior Cyber-Surgeon"), spriteName = SpriteDict.GetRandomMedSpriteName(), clientFaction = "FACTION_UPPER_LEVEL" }; NpcFrameworkSdk.AttachProcurementOffer( client: sc, clientName: sc.displayName, offerDescription: NpcFrameworkSdk.T("3 天后我有一台手术,急需一枚义体芯片。先付 100 定金,取货时再付 450 尾款。", "I need an Augmentation Chip in 3 days. Here is 100 credits upfront and 450 upon collection."), collectDescription: NpcFrameworkSdk.T("我来取预订的义体芯片了。", "I'm here to collect the Augmentation Chip we agreed on."), dueInDays: 3, initialAdvanceCash: 100, finalRewardCash: 450, itemValidator: item => item != null && item.itemID == "aug_chip" ); sc.CompleteClientCreation(false); return sc; } ``` ================================================================================ ## en/subsystems/11-custom-gun-orders.md ================================================================================ --- layout: doc title: 11. Custom Gunsmith Orders (GunOrder) --- # 11. Custom Gunsmith Orders (`BuildCustomGunOrder`) When a customer visits with `ClientIntent.GUNSMITH`, `NpcFrameworkSdk.BuildCustomGunOrder` constructs a `GunOrderData` contract containing both **mandatory requirements** and **bonus requirements** across 18 firearm stat tags. --- ## SDK Signature & Stat Tags ```csharp public static GunOrderData BuildCustomGunOrder( int tier, int baseReward, string dialogText, bool isBestOrder, IList<(string statTag, int minVal, int bonusReward, bool isMandatory)> requirements) ``` Supported `statTag` values: `"GUN_CALIBER_TAG"`, `"GUN_SUPPRESSED_TAG"`, `"GUN_FIREPOWER_TAG"`, `"GUN_ACCURACY_TAG"`, `"GUN_RELIABILITY_TAG"`, `"GUN_ERGONOMICS_TAG"`, `"GUN_RECOIL_TAG"`, `"GUN_REPAIRBILITY_TAG"`, `"GUN_STYLE_TAG"`, `"GUN_FRAME_TAG"`, `"GUN_SIZE_TAG"`. --- ## Code Example ```csharp sc.clientIntent = StoreClient.ClientIntent.GUNSMITH; sc.gunOrderData = NpcFrameworkSdk.BuildCustomGunOrder( tier: 2, baseReward: 380, dialogText: NpcFrameworkSdk.T("帮我改一把带消音器、高火力且精准可靠的潜行武器。", "Build me a suppressed, high-firepower sidearm with clean accuracy."), isBestOrder: true, requirements: new List<(string statTag, int minVal, int bonusReward, bool isMandatory)> { ("GUN_SUPPRESSED_TAG", 1, 80, true), ("GUN_FIREPOWER_TAG", 45, 100, true), ("GUN_ACCURACY_TAG", 60, 120, false), ("GUN_RELIABILITY_TAG", 70, 90, false) } ); ``` ================================================================================ ## en/subsystems/12-handnotes-and-papers.md ================================================================================ --- layout: doc title: 12. Handwritten Notes & Paper Documents --- # 12. Handwritten Notes & Paper Documents (`GiveHandnoteToPlayer`) This subsystem wraps `PreBuiltItemHelper.CreateHandnote` and `CreatePaperWithText`, allowing NPCs to leave physical, readable notes or printed documents on the counter or in the player's inventory (such as *V's Encrypted Note* in Act 4 of `CyberpunkMercV`). --- ## SDK Methods | Method Signature | Return Type | Description | | :--- | :--- | :--- | | `CreateHandnoteItem(string title, string body, string signature, int fontIndex = 0)` | `GameItem` | Creates a handwritten note item with a title, body text, signature, and handwriting font (`0..2`). | | `CreatePaperNoteItem(string title, string body)` | `GameItem` | Creates a printed paper document item. | | `SpawnItemOnCounterOrStore(GameItem item, bool isStolen = false, bool isContraband = false)` | `bool` | Spawns the item onto the counter if a client is present, or adds it to the store inventory (`GraphUtils.EmporiumTryAdd`). | | `GiveHandnoteToPlayer(string title, string body, string signature, int fontIndex = 0)` | `bool` | Creates and delivers a handwritten note in a single call. | --- ## Code Example ```csharp NpcFrameworkSdk.GiveHandnoteToPlayer( title: NpcFrameworkSdk.T("V 的加密便条", "V's Encrypted Note"), body: NpcFrameworkSdk.T( "铁子,大恩不言谢。 我的私人全息通讯号是:2077077 随时通过店内电话打给我。", "Preem work covering for me, choom. My private holophone number is: 2077077 Ring me on the store phone anytime."), signature: "V (Vincent)", fontIndex: 1 ); ``` ================================================================================ ## en/subsystems/13-store-request-board.md ================================================================================ --- layout: doc title: 13. Store Terminal Request Board --- # 13. Store Terminal Request Board (`PostStoreRequest`) The shop computer terminal features a **Requests** board where factions and NPCs post timed item commissions. `NpcFrameworkSdk.PostStoreRequest` constructs a `StoreRequest` and activates it immediately via `StoreRequest.ActivateRequest(req, force)`. --- ## SDK Signature ```csharp public static bool PostStoreRequest( string id, string title, string description, string requesterName, string factionId, string requiredItemId, int requiredCount = 1, int durationDays = 5, int creditReward = 200, int reputationReward = 10, bool force = true) ``` --- ## Code Example ```csharp NpcFrameworkSdk.PostStoreRequest( id: "v_afterlife_chip_req", title: NpcFrameworkSdk.T("来生佣兵义体芯片悬赏", "Afterlife Merc Aug Chip Bounty"), description: NpcFrameworkSdk.T("V 需要额外的原型义体芯片用于修复神经突触,报酬丰厚。", "V needs an extra Augmentation Chip for neural calibration. Pays top credit."), requesterName: "V (Vincent)", factionId: "FACTION_BLACK_MARKET", requiredItemId: "aug_chip", requiredCount: 1, durationDays: 6, creditReward: 450, reputationReward: 15, force: true ); ``` ================================================================================ ## en/subsystems/14-holophone-contacts.md ================================================================================ --- layout: doc title: 14. Holophone Contacts & Dial-to-Summon --- # 14. Holophone Contacts & Dial-to-Summon (`RegisterPhoneContact`) The holophone on the right side of the counter allows players to dial 7-digit numbers and interact with custom phone dialogue trees. `NpcPhoneRegistry` automates binding `PhoneClientList.DialogFuncs` and syncing unlocked entries into `PlayerStore.Instance.PhoneClientDict`. --- ## SDK Signature ```csharp public static void RegisterPhoneContact( long number, string dialogFuncId, Func displayNameGetter, int cooldownDays, Func isUnlockedPredicate, Func callDialogFactory, params string[] clientAliases) ``` > Passing all stage IDs of the character in `clientAliases` prevents immersion-breaking calls when that NPC is already standing at your counter. --- ## Code Example: Dialing `2077077` to Summon V ```csharp NpcFrameworkSdk.RegisterPhoneContact( number: 2077077L, dialogFuncId: "CyberpunkMercV_Call", displayNameGetter: () => NpcFrameworkSdk.T("传奇佣兵 V (2077077)", "V - Afterlife Merc (2077077)"), cooldownDays: 3, isUnlockedPredicate: () => NpcFrameworkSdk.GetSaveInt("v_stage", 0) == 4, callDialogFactory: CreateVPhoneDialogue, clientAliases: new[] { "v", "v_act1_relic", "v_act2_gun_order", "v_act3_heist", "v_recurring_merc" } ); ``` ================================================================================ ## en/subsystems/15-interrogation-and-optics.md ================================================================================ --- layout: doc title: 15. Interrogation, Smart Glasses & Bubbles --- # 15. Interrogation, Smart Glasses Scan & Bubble Styles Beyond `mainDialogue`, every `StoreClient` supports **interrogation dialogue (`interogationDialogue`)**, **smart-glasses scan dialogue (`glasseDialogue`)**, **post-confrontation dialogue (`resumeAfterConfrontDialogue`)**, and **custom speech bubble themes (`bubbleColor`)**. --- ## Core Fields Reference | `StoreClient` Field | Type | Description | | :--- | :--- | :--- | | `sc.interogationDialogue` | `Dialogue` | Triggered when the player clicks the Interrogate button during a visit. | | `sc.glasseDialogue` | `Dialogue` | Triggered when the player activates smart glasses to scan the customer (typically uses `"PLAYER"` as speaker). | | `sc.resumeAfterConfrontDialogue` | `Dialogue` | Played when resuming trade after confronting the customer. | | `sc.bubbleColor` | `string` | Set to `"dark"` to render a dark occult speech bubble (used by `cultistTrailer`). | --- ## Code Example: Johnny Silverhand Smart-Glasses Scan Easter Egg ```csharp sc.interogationDialogue = new Dialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("从夜之城一路逃到这鬼空间站,原以为能甩掉荒坂和帕斯泰尔的追兵。", "Thought laying low on this rustbucket station would get Arasaka and Pastel off my tail.")) .NextDialogue() .SetText(sc.displayName, NpcFrameworkSdk.T("结果真正要命的是插在我后颈里的这块原型生物芯片。", "Turns out the real killer is the prototype biochip slotted in my neck.")); sc.glasseDialogue = new Dialogue() .SetText("PLAYER", NpcFrameworkSdk.T("(你的目镜扫过他颈后的芯片插槽,电火花闪烁间,扫描仪上竟闪过一行诡异的意识体残影:)", "(Your optics scan the neural socket at his neck; amid sparks, a phantom engram signature flashes across your lens:)")) .NextDialogue() .SetText("PLAYER", NpcFrameworkSdk.T("(“醒醒,武侍……把这群企业狗杂碎全烧成灰……”)", "('Wake the hell up, Samurai... We have a station to burn...')")); ``` ================================================================================ ## en/subsystems/16-wanted-arrest-and-security.md ================================================================================ --- layout: doc title: 16. Wanted Bounties, Arrest & Security --- # 16. Wanted Bounties, Arrest Cutscenes & Security Encounters This subsystem covers two law-enforcement mechanics: **marking a customer as Wanted (`SetWanted` + `customOnArrestDialogue`)** and **building non-dismissable Security / Spec-Ops interrogation encounters (`ClientIntent.DIALOGUE` + `CompleteSecClient`)**. --- ## 1. Wanted Bounties & Custom Arrest Cutscenes > **Important**: the final line of `sc.customOnArrestDialogue` must call `StoreUIManager.Instance?.OnArrestDialoguePlayed()` inside `SetEndAction` so the arrest sequence completes cleanly. ```csharp sc.SetWanted(120, "Vincent (V)", true); sc.customOnArrestDialogue = new Dialogue() .SetText("CLIENT", NpcFrameworkSdk.T("靠,你跟德克斯特那肥猪一样背后捅刀子?!", "Damn it, you're just another backstabbing fixer like Dex?!")) .NextDialogue() .SetText("SEC", NpcFrameworkSdk.T("发现目标!启动斯安威斯坦抑制器,压制他!", "Target located! Activate Sandevistan dampeners and pin him down!")) .SetEndAction(() => { NpcFrameworkSdk.SetSaveInt("v_stage", 5); StoreUIManager.Instance?.OnArrestDialoguePlayed(); }); ``` --- ## 2. Security & Corporate Spec-Ops Investigation Events ```csharp var sc = new StoreClient { identifier = "v_act3_corpo_sec", displayName = NpcFrameworkSdk.T("企业特勤追缉官", "Corpo Spec-Ops Investigator"), spriteName = SpriteDict.GetRandomSecCorpoSpriteName(), clientFaction = "FACTION_SECURITY", clientIntent = StoreClient.ClientIntent.DIALOGUE, nonShootable = true, dismissable = false }; // ... attach AddChoice investigation branches ... sc.CompleteClientCreation(false); sc.CompleteSecClient(); ``` ================================================================================ ## en/subsystems/17-newspaper-headlines.md ================================================================================ --- layout: doc title: 17. Morning Newspaper Headlines --- # 17. Morning Newspaper Headlines (`TriggerNews`) Every morning when the player opens the shutter, a `newspaper` item is delivered to the counter. Calling `NpcFrameworkSdk.TriggerNews` registers and activates a custom `StoreEvent` in `StoreStation.Instance.storeEventManager`, printing your custom headline and article body in the next morning's edition. --- ## SDK Signature ```csharp public static void TriggerNews( string id, string headline, string body, int durationDays = 1) ``` --- ## Code Example ```csharp NpcFrameworkSdk.TriggerNews( id: "v_heist_legend_news", headline: NpcFrameworkSdk.T("独狼佣兵洗劫企业实验室后全身而退", "Solo Mercenary Escapes After Corporate Lab Raid"), body: NpcFrameworkSdk.T("上层区企业特勤队昨日在下层区搜捕无果。代号 V 的神秘佣兵携带原型科技人间蒸发,成为下层区最新传奇。", "Corporate Spec-Ops came up empty-handed in the Lower Levels yesterday as the solo mercenary known as 'V' vanished with prototype tech."), durationDays: 2 ); ``` ================================================================================ ## en/subsystems/18-afterhour-and-nightly-hooks.md ================================================================================ --- layout: doc title: 18. Afterhour Events & Nightly Hooks --- # 18. Afterhour Events, Dumping Ground & Nightly Hooks After closing the shop for the day, the player can visit afterhour map locations (such as `"dumping_ground"`) before going to bed. This subsystem provides three hooks for nighttime world events and end-of-day state transitions. --- ## SDK Methods ```csharp public static bool RegisterAfterhourEvent( string id, string locationId, Func titleGetter, Func descriptionGetter, int durationDays = 2, float dailyChancePercent = 25f, bool closesLocation = false, Func canStartPredicate = null, Action onStart = null, Action onEnd = null); public static void RegisterDumpingGroundWatcher(Action watcher); public static void RegisterNightlyHook(Action hook); ``` --- ## Code Example ```csharp NpcFrameworkSdk.RegisterAfterhourEvent( id: "corpo_drone_wreckage", locationId: "dumping_ground", titleGetter: () => NpcFrameworkSdk.T("坠毁的企业货运无人机", "Crashed Corporate Cargo Drone"), descriptionGetter: () => NpcFrameworkSdk.T("垃圾场深处有一架冒着电火花的帕斯泰尔无人机残骸。", "A sparking Pastel cargo drone lies half-buried in the scrap."), durationDays: 2, dailyChancePercent: 25f, closesLocation: false, canStartPredicate: () => NpcFrameworkSdk.GetSaveInt("v_stage", 0) >= 2 ); NpcFrameworkSdk.RegisterNightlyHook(() => { NpcFrameworkSdk.AddSaveInt("nights_survived", 1, 0); }); ``` ================================================================================ ## en/api/sdk-reference.md ================================================================================ --- layout: doc title: NpcFrameworkSdk Complete Reference --- # `NpcFrameworkSdk` Complete API Reference Drop `NpcFrameworkSdk.cs` into your mod project to call every feature of **Custom NPC Framework** without adding a DLL reference. ## Core Registration, Localization & Summoning | Method / Property | Return Type | Description | | :--- | :--- | :--- | | `NpcFrameworkSdk.IsChinese` | `bool` | Returns `true` when the active language is Simplified Chinese (respecting the framework's language setting or game locale). | | `NpcFrameworkSdk.T(string zh, string en)` | `string` | Returns `zh` if `IsChinese` is true, otherwise `en`. | | `NpcFrameworkSdk.RegisterNpc(...)` | `void` | Registers a custom NPC or storyline stage entry with full scheduling rules. | | `NpcFrameworkSdk.SummonNpcNow(string id)` | `bool` | Forces `id` to `clientStack[0]` immediately (calling them to the door if empty) or queues them as the first customer on the next shutter open. | | `NpcFrameworkSdk.ResolveSprite(string name)` | `string` | Validates `name` against `SpriteDict.Instance.spriteDictionary` with built-in safe fallbacks. | ## Per-Save Storyline State Store (`cnpcf_` Namespace) ```csharp int GetSaveInt(string key, int defaultValue = 0); void SetSaveInt(string key, int value); int AddSaveInt(string key, int delta, int defaultValue = 0); bool GetSaveBool(string key, bool defaultValue = false); void SetSaveBool(string key, bool value); string GetSaveString(string key, string defaultValue = ""); void SetSaveString(string key, string value); ``` ## Holophone & 18-Subsystem Toolkit Methods ```csharp void RegisterPhoneContact(long number, string dialogFuncId, Func displayNameGetter, int cooldownDays, Func isUnlockedPredicate, Func callDialogFactory, params string[] clientAliases); void SyncPhoneContacts(); void ApplyClientProfile(StoreClient client, Dictionary profile); GameItem CreateHandnoteItem(string title, string body, string signature, int fontIndex = 0); GameItem CreatePaperNoteItem(string title, string body); bool SpawnItemOnCounterOrStore(GameItem item, bool isStolen = false, bool isContraband = false); bool GiveHandnoteToPlayer(string title, string body, string signature, int fontIndex = 0); bool PostStoreRequest(string id, string title, string description, string requesterName, string factionId, string requiredItemId, int requiredCount = 1, int durationDays = 5, int creditReward = 200, int reputationReward = 10, bool force = true); void AttachProcurementOffer(StoreClient client, string clientName, string offerDescription, string collectDescription, int dueInDays, int initialAdvanceCash, int finalRewardCash, Func itemValidator); GunOrderData BuildCustomGunOrder(int tier, int baseReward, string dialogText, bool isBestOrder, IList<(string statTag, int minVal, int bonusReward, bool isMandatory)> requirements); void TriggerNews(string id, string headline, string body, int durationDays = 1); bool RegisterAfterhourEvent(string id, string locationId, Func titleGetter, Func descriptionGetter, int durationDays = 2, float dailyChancePercent = 25f, bool closesLocation = false, Func canStartPredicate = null, Action onStart = null, Action onEnd = null); void RegisterNightlyHook(Action hook); void RegisterDumpingGroundWatcher(Action watcher); ``` ================================================================================ ## en/api/profile-dictionary.md ================================================================================ --- layout: doc title: ApplyClientProfile 46-Field Dictionary --- # 4.2 `ApplyClientProfile` 46-Field Declarative Dictionary Reference `NpcFullFeatureKit.ApplyClientProfile(StoreClient sc, Dictionary profile)` maps all 46 supported dictionary keys directly onto `StoreClient` fields, lists, delegates, and dialogue trees: | # | Dictionary Key (`Key`) | Value Type (`Type`) | Underlying `StoreClient` Field / Method | | :--- | :--- | :--- | :--- | | 1 | `"DisplayName"` | `string` | `sc.displayName = val` | | 2 | `"SpriteName"` | `string` | `sc.spriteName = NpcTraitHelper.ResolveValidSpriteName(val)` | | 3 | `"PossibleSprites"` | `IEnumerable` | Appended to `sc.possibleSprites` | | 4 | `"Faction"` | `string` | `sc.clientFaction = val` | | 5 | `"BubbleColor"` | `string` | `sc.bubbleColor = val` (e.g. `"dark"`) | | 6 | `"ClientIntent"` | `int` | `sc.clientIntent = (StoreClient.ClientIntent)val` | | 7 | `"Budget"` | `int` | `sc.SetBudget(val)` | | 8 | `"UseClientBudget"` | `bool` | `sc.useClientBudget = val` | | 9 | `"BuyPriceModifier"` | `int` | `sc.buyPriceModifier = val` | | 10 | `"SellPriceModifier"` | `int` | `sc.sellPriceModifier = val` | | 11 | `"IsOfferWholesale"` | `bool` | `sc.isOfferWholesale = val` | | 12 | `"WholesaleDiscount"` | `int` | `sc.wholesaleDiscount = val` | | 13 | `"RequireVariety"` | `bool` | Calls `sc.SetVariety()` if `true` | | 14 | `"NoAcceptingContraband"` | `bool` | `sc.noAcceptingContraband = val` | | 15 | `"AcceptingContrabandOverride"` | `bool` | `sc.AcceptingContrabandOverride = val` | | 16 | `"ChargesContrabandMarkup"` | `bool` | `sc.chargesContrabandMarkup = val` | | 17 | `"AcceptRetailMarkup"` | `bool` | `sc.acceptRetailMarkup = val` | | 18 | `"RefusesHazardousWaterLabel"` | `bool` | `sc.refusesHazardousWaterLabel = val` | | 19 | `"PerfumeInfluence"` | `int` | `sc.perfumeInfluence = val` | | 20 | `"ClientImpatience"` | `int` | `sc.clientImpatience = val` | | 21 | `"AlwaysRejectBadBargain"` | `bool` | `sc.alwaysRejectBadBargain = val` | | 22 | `"IsBargainAvailable"` | `bool` | `sc.isBargainAvailable = val` | | 23 | `"StaysAfterFailedBargain"` | `bool` | `sc.staysAfterFailedBargain = val` | | 24 | `"Dismissable"` | `bool` | `sc.dismissable = val` | | 25 | `"Arrestable"` | `bool` | `sc.arrestable = val` | | 26 | `"NonShootable"` | `bool` | `sc.nonShootable = val` | | 27 | `"IsSecurity"` | `bool` | `sc.isSecurity = val` | | 28 | `"IsLazyInspector"` | `bool` | `sc.isLazyInspector = val` | | 29 | `"IsNoContributeToEvidence"` | `bool` | `sc.isNoContributeToEvidence = val` | | 30 | `"IsAug"` | `bool` | `sc.isAug = val` (Warning: only set `true` for hostile disguised monsters) | | 31 | `"AugTier"` | `int` | `sc.augTier = val` | | 32 | `"AugIdleTell"` | `int` | `sc.augIdleTell = (StoreClient.AugIdleTell)val` | | 33 | `"MakeDisguisedAugTier"` | `int` | Calls `AugHelper.MakeDisguisedAug(sc, val)` | | 34 | `"CanExposeChem"` | `bool` | `sc.CanExposeChem = val` | | 35 | `"AcceptedChemicalGrade"` | `int` | `sc.acceptedChemicalProductGrade = val` | | 36 | `"ExposePreset"` | `int` | Calls `NpcTraitHelper.ApplyExposePreset(...)` | | 37 | `"CanReturn"` / `"CanReturnAsBuyer"` | `bool` | `sc.CanReturn = val` / `sc.CanReturnAsBuyer = val` | | 38 | `"AlwaysFeedback"` | `bool` | `sc.alwaysFeedback = val` | | 39 | `"IsClientAddict"` | `bool` | `sc.IsClientAddict = val` | | 40 | `"TradeReputationMultiplier"` | `double` | `sc.tradeReputationMultiplier = val` | | 41 | `"BuyingTags"` / `"BuyingIds"` | `IEnumerable` | Added to `clientBuyingTagList` / `clientBuyingIdList` | | 42 | `"BlackTags"` / `"BlackIds"` | `IEnumerable` | Added to `clientBlackTagList` / `clientBlackIdList` | | 43 | `"InspectionChecks"` | `IEnumerable` | Calls `sc.AddCheck(c)` for each entry | | 44 | `"OnArrival"` / `"OnDismiss"` / `"OnDealAccepted"` | `Action` | Binds arrival, dismissal, and deal-accepted callbacks | | 45 | `"OnItemAddedToWeighted"` / `"OnItemSold"` / `"OnItemBought"` | `Action<...>` | Binds realtime scale and trade item callbacks | | 46 | `"InterrogationDialogue"` / `"GlassesDialogue"` / `"CustomOnArrestDialogue"` / `"RepeatDialogue"` | `Dialogue` | Binds interrogation, optics scan, arrest, and repeat dialogues | ================================================================================ ## en/api/vanilla-classes.md ================================================================================ --- layout: doc title: Vanilla StoreClient & Dialogue Classes --- # Vanilla `StoreClient` & `Dialogue` Classes ## Building `Dialogue` Chains & Choices ```csharp var cur = sc.mainDialogue .SetText(sc.displayName, "First line of dialogue.") .NextDialogue() .SetText(sc.displayName, "Second line of dialogue."); var dlgChoiceA = new Dialogue().SetText("PLAYER", "[Option A] Sounds like a deal."); cur.AddChoice(DirectoryMaster.Item("$", true), "", "", dlgChoiceA, () => { var d = dlgChoiceA.NextDialogue().SetText(sc.displayName, "Preem! See you around."); d.SetEndAction(() => DialogUIManager.Instance?.CurrentClientLeave(1f)); }, null); ``` ## Essential `StoreClient` Finalizers Always call `sc.CompleteClientCreation(false)` before returning your `StoreClient` from `clientFactory`. For Security encounter clients (`clientIntent = (StoreClient.ClientIntent)5`), also call `sc.CompleteSecClient()` immediately afterward. ================================================================================ ## en/examples/restored-overview.md ================================================================================ --- layout: doc title: "RestoredUnusedNPCs: Billy 4-Act Storyline" --- # Example Breakdown: `RestoredUnusedNPCs` Architecture & Billy's 4-Act Storyline ![RestoredUnusedNPCs](/images/en/preview_restored.png) This page and the next examine the source code of `RestoredUnusedNPCs` (`RestoredUnusedNPCsMod.cs`). Here we cover **Billy's 4-act cross-day storyline**, `BarterOffer` food sharing, Medbay wholesale fencing, and the Internal Affairs investigation. --- ## 1. State Machine & Auto-Dispatcher (`billy`) Billy's arc is driven by two save keys: - `billy_stage` (`0..5`): `0` = Act 1 begging for food; `1` = Act 2 rookie guard buying gear; `2` = Act 3 first Medbay theft wholesale; `3` = Act 4 Internal Affairs investigation; `4` = arrested ending; `5` = permanent recurring wholesale supplier mode. - `billy_fed` (`0` or `1`): records whether the player shared food with Billy in Act 1. ```csharp private static StoreClient CreateBillyByCurrentStage() { int stage = NpcFrameworkSdk.GetSaveInt("billy_stage", 0); switch (stage) { case 0: return CreateBilly1(); case 1: return CreateBilly2(); case 2: return CreateBilly3Internal(false); case 3: return CreateBillySecOfficer(); default: return CreateBilly3Internal(true); } } ``` --- ## 2. Act 1 (`CreateBilly1`): Begging for Food & Three-Way Choice Billy visits with `ClientIntent.BARTER` (`useClientBudget = false`) requesting `"FOOD"`: - **Branch 1 (`[Give him some food]`)**: invokes `sc.barterOffer.InstanciateOffer()` if `"FOOD"` is in the back inventory (or triggers a warm staff-meal fallback if out of stock), setting `billy_stage = 1, billy_fed = 1`. - **Branch 2 (`[Decline]`)**: keeps `billy_stage = 0` so Billy can try again on a later day. - **Branch 3 (`[Tell him to get a job]`)**: sets `billy_stage = 1, billy_fed = 0`. --- ## 3. Act 2 (`CreateBilly2`), Act 3 (`CreateBilly3Internal`) & Act 4 (`CreateBillySecOfficer`) - **Act 2**: Billy arrives in a Security uniform (`maleSec2`) with `180` credits to buy a `"TOOL"`, `"WEAPON"`, or `"MELEE_WEAPON"` (`CHECK_RUST`, `CHECK_DENTED`). Completing the sale sets `billy_stage = 2`. - **Act 3**: Assigned to the Upper Level Pastel Medbay, Billy steals `large_purple_injector`, `pink_injector`, `hemostatic_bandage_item`, and `smelling_salt`, offering them as a 25%-off wholesale bundle (`isOfferWholesale = true, wholesaleDiscount = -25`). - **Act 4**: Internal Affairs questions the player. Reporting Billy awards `150` credits, triggers the `"Medbay Insider Arrested"` newspaper headline, and sets `billy_stage = 4`. Covering for Billy sets `billy_stage = 5`, unlocking him as a permanent recurring wholesale supplier. ================================================================================ ## en/examples/restored-special-npcs.md ================================================================================ --- layout: doc title: "RestoredUnusedNPCs: 7 Special Customers" --- # Example Breakdown: 7 Special-Mechanic Customers in `RestoredUnusedNPCs` Alongside Billy's 4-act arc, `RestoredUnusedNPCsMod.cs` implements 7 standalone customers showcasing distinct subsystems: 1. **Greytide Scavenger (`greytide`)**: calls `StoreClientFactionSetup.InitScav(sc)` and wholesales a `stun_baton`, `glock_receiver`, and `sec_keycard` at `-RNG.GetRandomInt(15, 25)` discount. 2. **Blood Cultist (`cultistTrailer`)**: uses `bubbleColor = "dark"`, pays `+35%` markup for `blood_bag` and `blue_blood_bag`, and enforces `CHECK_EXPIRED`. 3. **Revolutionary Agitator (`revManifesto`)**: uses `StoreClientFactionSetup.InitRev(sc)`, carries a `50` credit wanted bounty, and features a 4-page `customOnArrestDialogue` confrontation. 4. **Withdrawal Addict (`addictGeneralTrailer`)**: hooks `sc.onItemAddedToWeighted` to interject (`"That's the stuff!"`) the moment a `"SUBSTANCE"` or `"NARCOTIC"` item touches the weighing scale. 5. **Lower Levels Chemist (`trailerChemist`)**: sets `CanExposeChem = true` and wholesales 4x `dream_dust` + 2x `fanta_pill` at 20% off. 6. **Underground Arms Dealer (`trailerWeaponSeller`)**: tracks `arms_dealer_met` in save data to distinguish first-visit introduction lines from repeat-customer dialogue, wholesaling 2x `glock_receiver`, `smoke_grenade`, `flashbang_grenade`, and `satchel` at 20% off. 7. **Armed Militiaman (`gunBuyerTrader`)**: brings a `450` credit budget for `"FIREARM"` and `"WEAPON"` items while enforcing both `CHECK_RUST` and `CHECK_DENTED`. ================================================================================ ## en/examples/cyberpunk-v-storyline.md ================================================================================ --- layout: doc title: "CyberpunkMercV: 5-Stage Storyline & State Machine" --- # Example Breakdown: `CyberpunkMercV` 5-Stage Storyline & State Machine ![CyberpunkMercV](/images/en/preview_v.png) This page and the next dissect the complete source code of `CyberpunkMercV` (`CyberpunkMercVMod.cs`). Here we examine the registration architecture, the 5-stage narrative state machine (`v_stage`), the auto-stage dispatcher, and the implementation of Acts 1 through 3. --- ## 1. State Machine Design & Registration Table `CyberpunkMercV` tracks cross-day narrative progression with two save keys: - `v_stage` (`0..5`): `0` = Act 1 Relic malfunction; `1` = Act 2 convoy ambush firearm prep; `2` = Act 3 corporate vault heist wholesale loot; `3` = Act 4 Corporate Spec-Ops investigation; `4` = post-story recurring mode & holophone unlocked; `5` = arrested/betrayed ending. - `v_trust` (`0..2`): tracks trust built with V across the storyline. ```csharp private static StoreClient CreateVByCurrentStage() { int stage = NpcFrameworkSdk.GetSaveInt("v_stage", 0); switch (stage) { case 0: return CreateVAct1Relic(); case 1: return CreateVAct2GunOrder(); case 2: return CreateVAct3Heist(); case 3: return CreateCorpoSecInvestigator(); default: return CreateVRecurringMercInternal(); } } private static StoreClient CreateVRecurringMercOrCurrentStage() { int stage = NpcFrameworkSdk.GetSaveInt("v_stage", 0); if (stage < 4) return CreateVByCurrentStage(); return CreateVRecurringMercInternal(); } ``` --- ## 2. Act 1 (`CreateVAct1Relic`): Biochip Overwrite & Smart-Glasses Easter Egg In Act 1, V enters the shop as an unfamiliar mercenary (`"Mercenary V"`) experiencing a 68% Relic biochip neural overwrite: ```csharp private static StoreClient CreateVAct1Relic() { var sc = new StoreClient { identifier = "v_act1_relic", displayName = T("陌生佣兵 V", "Mercenary V"), spriteName = "v_normal", clientFaction = "FACTION_BLACK_MARKET", clientIntent = StoreClient.ClientIntent.BUY, buyPriceModifier = 40, CanExposeChem = true, staysAfterFailedBargain = true, noAcceptingContraband = false, AcceptingContrabandOverride = true }; sc.SetBudget(380); sc.clientBuyingIdList.Add("black_injector"); sc.clientBuyingIdList.Add("large_purple_injector"); sc.clientBuyingIdList.Add("pink_injector"); sc.clientBuyingIdList.Add("dream_dust"); sc.clientBuyingTagList.Add("MEDICAL"); sc.clientBuyingTagList.Add("NARCOTIC"); sc.AddCheck("CHECK_EXPIRED"); ``` - **Branch 1 (`[Hand him an emergency neuro-sedative]`)**: hands V an emergency sedative directly from dialogue, advancing `v_stage = 1`, `v_trust = 2`, and granting `120` credits (`PlayerStore.Instance?.ModCash(120, true)`). - **Branch 2 (`[Open Stock]`)**: enters the standard buying interface; completing the sale advances `v_stage = 1` inside `acceptDealDialogue` and `allDoneDialogue`. --- ## 3. Act 2 (`CreateVAct2GunOrder`): Convoy Ambush Firearm Preparation When `v_stage == 1`, V returns with `520` credits and `+30%` markup to purchase `"FIREARM"`, `"WEAPON"`, `"AMMUNITION"`, or `"MUNITION"` (enforcing `CHECK_RUST` and `CHECK_DENTED`) ahead of his raid on an Arasaka/Pastel neural-matrix convoy. Completing the deal sets `v_stage = 2`. --- ## 4. Act 3 (`CreateVAct3Heist`): Corporate Vault Heist 30%-Off Wholesale Lot When `v_stage == 2`, V brings the high-tech spoils of the corporate vault raid (`aug_chip`, `command_keycard`, `sci_keycard`, `energy_credit_hyp`, and `smg`) and offers them as a 30%-off wholesale bundle (`isOfferWholesale = true, wholesaleDiscount = -30`): ```csharp cur.SetEndAction(() => { var ps = PlayerStore.Instance; if (ps == null) return; ps.AddDirectSellingItemToTable("aug_chip", false, false, false, 0); ps.AddDirectSellingItemToTable("command_keycard", false, false, false, 0); ps.AddDirectSellingItemToTable("sci_keycard", false, false, false, 0); ps.AddDirectSellingItemToTable("energy_credit_hyp", false, false, false, 0); ps.AddDirectSellingItemToTable("smg", false, false, false, 0); }); ``` ================================================================================ ## en/examples/cyberpunk-v-rewards-glitch.md ================================================================================ --- layout: doc title: "CyberpunkMercV: Rewards Loop & Relic Glitch" --- # Example 2 (Part B): 4-Part Rewards Loop, Holophone `2077077` & Relic Glitch ## 1. The 4-Part Reward Loop in Act 4 (`dlgCover`) When the player covers for V during the Corporate Spec-Ops investigation (`v_act3_corpo_sec`), a single callback chains four framework subsystems: 1. **Unlocks Holophone Contact `2077077`**: sets `v_stage = 4` and calls `NpcFrameworkSdk.SyncPhoneContacts()`; 2. **Delivers a Handwritten Note**: calls `NpcFrameworkSdk.GiveHandnoteToPlayer("V's Encrypted Note", ..., "V (Vincent)", 1)`; 3. **Posts a Store Request Bounty**: calls `NpcFrameworkSdk.PostStoreRequest("v_afterlife_chip_req", ...)` offering `450` credits and `+15` Black Market reputation for an `aug_chip`; 4. **Publishes a Next-Day Newspaper Headline**: calls `NpcFrameworkSdk.TriggerNews("v_heist_legend_news", "Solo Mercenary Escapes After Corporate Lab Raid", ..., 2)`. --- ## 2. Calling V on Holophone `2077077` Dialing `2077077` on the store holophone opens `CreateVPhoneDialogue`, allowing the player to either chat about Johnny Silverhand or call V directly to the store via `NpcFrameworkSdk.SummonNpcNow("v_recurring_merc")`. ================================================================================ ## en/reference/vanilla-dictionaries.md ================================================================================ --- layout: doc title: Factions, Item Tags, Item IDs & SpriteDict Pools --- # 6.1 Vanilla Game Data Dictionaries (Extracted from `Assembly-CSharp.dll`) This reference compiles authentic constants, enum values, and static helper signatures extracted directly from *Probably Stolen*'s `Assembly-CSharp.dll`. --- ## 1. The 8 Vanilla Faction IDs (`clientFaction`) & Setup Helpers | Faction ID String (`clientFaction`) | Faction Name | `StoreClientFactionSetup` Helper Method | | :--- | :--- | :--- | | `"FACTION_LOWER_LEVEL"` | Lower Levels Citizens & Scavengers | `InitLowerLevelCitizen(sc)` / `InitScav(sc)` / `InitWorker(sc)` | | `"FACTION_BLACK_MARKET"` | Black Market Syndicate | `InitBlackMarket(sc)` | | `"FACTION_SECURITY"` | Station Security & Corporate Guard | `InitSecurity(sc)` | | `"FACTION_REVOLUTION"` | Revolutionary Front | `InitRev(sc)` | | `"FACTION_UPPER_LEVEL"` | Upper Level Citizens & Pastel Elites | `InitUpperLevelCitizen(sc)` | | `"FACTION_TOURIST"` | Off-World Tourists | `InitTourist(sc)` | | `"FACTION_CHURCH"` | Church of the Abyss | `InitChurch(sc)` | | `"FACTION_CARTEL"` | Cartel Syndicate | `InitCartel(sc)` | --- ## 2. `StoreClient.ClientIntent` Complete Enum Table | Enum Member | Int Value | Description | | :--- | :--- | :--- | | `ClientIntent.UNDEFINED` | `0` | Undefined | | `ClientIntent.BUY` | `1` | Regular buyer purchasing items from the player | | `ClientIntent.SELL` | `2` | Regular seller or wholesale lot seller (with `isOfferWholesale = true`) | | `ClientIntent.SELLNBUY` | `3` | Both sells and buys | | `ClientIntent.INSPECTION` | `4` | Security contraband inspection | | `ClientIntent.DIALOGUE` | `5` | Pure dialogue / investigation event (`billy3Officier`, `v_act3_corpo_sec`) | | `ClientIntent.BARTER` | `6` | Item barter / begging (`sc.barterOffer`) | | `ClientIntent.RENT` | `7` | Rent collection event | | `ClientIntent.LOAN_SHARK` | `8` | Loan shark collection event | | `ClientIntent.SPECIAL` | `9` | Special scripted event | | `ClientIntent.INFORMATION_DEALER` | `10` | Information dealer | | `ClientIntent.PROCUREMENT_OFFER` | `11` | Initiates a multi-day procurement order (`AttachProcurementOffer`) | | `ClientIntent.PROCUREMENT_COLLECT` | `12` | Returns to collect a procurement order | | `ClientIntent.WHOLESALE` | `13` | Wholesale intent | | `ClientIntent.APPRAISAL_SERVICE` | `14` | Item appraisal service | | `ClientIntent.GUNSMITH` | `15` | Custom gunsmith order (`BuildCustomGunOrder`) | | `ClientIntent.EXPEDITION` | `16` | Expedition commission | --- ## 3. Common Item Tags (`clientBuyingTagList`) & Item IDs (`itemID`) ### Item Category Tags - **Medical & Chemical**: `"MEDICAL"`, `"NARCOTIC"`, `"SUBSTANCE"`, `"CHEMICAL"` - **Weapons & Munitions**: `"FIREARM"`, `"WEAPON"`, `"MELEE_WEAPON"`, `"AMMUNITION"`, `"MUNITION"`, `"EXPLOSIVE"` - **General & Tech**: `"FOOD"`, `"DRINK"`, `"TOOL"`, `"ELECTRONIC"`, `"VALUABLE"`, `"KEYCARD"`, `"DOCUMENT"` ### High-Frequency Vanilla Item IDs | Category | Vanilla Item IDs (`itemID`) | Description | | :--- | :--- | :--- | | **Medical & Injectors** | `"black_injector"`, `"large_purple_injector"`, `"pink_injector"`, `"blood_bag"`, `"blue_blood_bag"`, `"hemostatic_bandage_item"`, `"smelling_salt"` | Black/Purple/Pink injectors, blood bags, hemostatic bandage, smelling salt | | **Narcotics & Powders** | `"dream_dust"`, `"fanta_pill"` | Dream Dust, Fanta Pill | | **Weapons, Parts & Grenades** | `"revolver"`, `"smg"`, `"stun_baton"`, `"glock_receiver"`, `"smoke_grenade"`, `"flashbang_grenade"` | Revolver, SMG, stun baton, Glock receiver, smoke/flashbang grenades | | **Chips, Keycards & Gear** | `"aug_chip"`, `"sec_keycard"`, `"command_keycard"`, `"sci_keycard"`, `"energy_credit_hyp"`, `"satchel"` | Augmentation chip, Security/Command/Science keycards, hypertech credit, satchel | | **Store & Utility Items** | `"newspaper"`, `"tutorial_book"`, `"labeler"`, `"stamp_guide"`, `"injector_guide"`, `"logo_checker"` | Morning newspaper, guides, labeler, counterfeit checker | --- ## 4. All 18 Gunsmith Stat Tags (`GUN_*_TAG`) - `"GUN_CALIBER_TAG"`, `"GUN_SUPPRESSED_TAG"`, `"GUN_FIREPOWER_TAG"`, `"GUN_CURRENT_FIREPOWER_TAG"`, `"GUN_ACCURACY_TAG"`, `"GUN_CURRENT_ACCURACY_TAG"`, `"GUN_RELIABILITY_TAG"`, `"GUN_CURRENT_RELIABILITY_TAG"`, `"GUN_ERGONOMICS_TAG"`, `"GUN_CURRENT_ERGONOMICS_TAG"`, `"GUN_RECOIL_TAG"`, `"GUN_CURRENT_RECOIL_TAG"`, `"GUN_REPAIRBILITY_TAG"`, `"GUN_CURRENT_REPAIRBILITY_TAG"`, `"GUN_STYLE_TAG"`, `"GUN_CURRENT_STYLE_TAG"`, `"GUN_FRAME_TAG"`, `"GUN_SIZE_TAG"`. --- ## 5. `SpriteDict` Built-In Portrait Pool Helper Methods - **Lower Levels & Scavengers**: `SpriteDict.GetRandomLowerLevelSpriteName()`, `GetRandomLowerMaleSpriteName()`, `GetRandomLowerFemaleSpriteName()`, `GetRandomScavSpriteName()`, `GetGreytideSpriteName()`, `"trailer_scav1"`, `"trailer_scav2"`, `"trailer_scav3"` - **Black Market & Mercenaries**: `SpriteDict.GetRandomShadySpriteName()`, `GetRandomBMMaleSpriteName()`, `GetRandomBMFemaleSpriteName()`, `GetRandomMercSpriteName()`, `GetRandomMercMale()`, `GetRandomMercFemale()`, `GetShadyMerchantSpriteName()`, `"spy"`, `"wanted3"`, `"wanted5"` - **Security & Corporate Spec-Ops**: `SpriteDict.GetRandomSecSpriteName()`, `GetRandomSecMaleSpriteName()`, `GetRandomSecFemaleSpriteName()`, `GetRandomSecCorpoSpriteName()`, `GetRandomSecCorpoMaleSpriteName()`, `GetRandomSecOffSpriteName()`, `"maleSec2"` - **Revolutionaries**: `SpriteDict.GetRandomRevSpriteName()`, `GetRandomRevMaleSpriteName()`, `GetRandomRevFemaleSpriteName()`, `"trailer_rev1"` - **Medical, Science & Engineering**: `SpriteDict.GetRandomMedSpriteName()`, `GetRandomScientistSpriteName()`, `GetRandomSciSpriteName()`, `GetRandomEngSpriteName()` - **Upper Level & Special NPCs**: `SpriteDict.GetRandomUpperSpriteName()`, `GetLoanSharkSpriteName()`, `GetCartelHandlerSpriteName()`, `GetBlackmailerSpriteName()`, `GetInventorSpriteName()`, `GetCourrierSpriteName()` ================================================================================ ## APPENDIX: NpcFrameworkSdk.cs ================================================================================ ```csharp using System; using System.Collections.Generic; namespace CyberpunkMercV { /// /// Zero-Assembly-Reference SDK v2.0 for CustomNPCFramework. /// Maps all 18 NPC-shaping subsystems of Probably Stolen without requiring any extra ModScanner permissions. /// public static class NpcFrameworkSdk { private const string BridgeKey = "CustomNPCFramework.Bridge.v1"; private const string PendingQueueKey = "CustomNPCFramework.PendingQueue.v1"; private const string PendingPhoneQueueKey = "CustomNPCFramework.PendingPhoneQueue.v1"; private static Dictionary GetBridge() { return AppDomain.CurrentDomain.GetData(BridgeKey) as Dictionary; } public static bool IsChinese { get { try { var cfg = ModConfig.Find("CustomNPCFramework"); if (cfg != null) { var langEntry = cfg.Get("language"); string val = langEntry?.BoxedValue as string ?? ""; if (val.Contains("简体中文")) return true; if (val.Contains("English")) return false; } string code = LocHelper.GetCurrentLocaleCode() ?? "zh"; return code.StartsWith("zh", StringComparison.OrdinalIgnoreCase); } catch { return true; } } } public static string T(string zh, string en) => IsChinese ? zh : en; // 1. Core NPC Registration & Lifecycle Scheduling public static void RegisterNpc( string id, Func displayNameGetter, int spawnPhase, int priority, int minDay, int cooldownDays, int spawnChancePercent, bool oncePerSave, Func canSpawnPredicate, Func clientFactory, Action onSpawned = null, int maxDay = 9999, string requiredNotArrestedId = null) { var payload = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Id"] = id, ["SourceModId"] = "CyberpunkMercV", ["DisplayNameGetter"] = displayNameGetter, ["SpawnPhase"] = spawnPhase, ["Priority"] = priority, ["MinDay"] = minDay, ["MaxDay"] = maxDay, ["CooldownDays"] = cooldownDays, ["SpawnChancePercent"] = spawnChancePercent, ["OncePerSave"] = oncePerSave, ["NoDuplicateInQueue"] = true, ["RequiredNotArrestedId"] = requiredNotArrestedId, ["CanSpawnPredicate"] = canSpawnPredicate, ["ClientFactory"] = clientFactory, ["OnSpawned"] = onSpawned }; var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("RegisterNpc", out var regObj) && regObj is Action> regAction) { regAction(payload); return; } var queue = AppDomain.CurrentDomain.GetData(PendingQueueKey) as List>; if (queue == null) { queue = new List>(); AppDomain.CurrentDomain.SetData(PendingQueueKey, queue); } queue.Add(payload); } // 2. Declarative Full StoreClient Profile Applier public static void ApplyClientProfile(StoreClient client, Dictionary profile) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("ApplyClientProfile", out var fn) && fn is Action> act) act(client, profile); } // 3. Phonebook Contact Registration (StorePhoneClient) public static void RegisterPhoneContact( long number, string dialogFuncId, Func displayNameGetter, int cooldownDays, Func isUnlockedPredicate, Func callDialogFactory, params string[] clientAliases) { var payload = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Number"] = number, ["DialogFuncId"] = dialogFuncId, ["DisplayNameGetter"] = displayNameGetter, ["CooldownDays"] = cooldownDays, ["IsUnlockedPredicate"] = isUnlockedPredicate, ["CallDialogFactory"] = callDialogFactory, ["ClientAliases"] = clientAliases }; var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("RegisterPhoneContact", out var regObj) && regObj is Action> regAction) { regAction(payload); return; } var queue = AppDomain.CurrentDomain.GetData(PendingPhoneQueueKey) as List>; if (queue == null) { queue = new List>(); AppDomain.CurrentDomain.SetData(PendingPhoneQueueKey, queue); } queue.Add(payload); } public static void SyncPhoneContacts() { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("SyncPhoneContacts", out var fn) && fn is Action act) act(); } // 4. Handwritten Note & Paper Item Generator public static GameItem CreateHandnoteItem(string title, string body, string signature, int fontIndex = 0) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("CreateHandnoteItem", out var fn) && fn is Func f) return f(title, body, signature, fontIndex); return PreBuiltItemHelper.CreateHandnote(body ?? "", title ?? "", signature ?? "", fontIndex); } public static GameItem CreatePaperNoteItem(string title, string body) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("CreatePaperNoteItem", out var fn) && fn is Func f) return f(title, body); return PreBuiltItemHelper.CreatePaperWithText(body ?? "", title ?? ""); } public static bool SpawnItemOnCounterOrStore(GameItem item, bool isStolen = false, bool isContraband = false) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("SpawnItemOnCounterOrStore", out var fn) && fn is Func f) return f(item, isStolen, isContraband); return false; } public static bool GiveHandnoteToPlayer(string title, string body, string signature, int fontIndex = 0) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("GiveHandnoteToPlayer", out var fn) && fn is Func f) return f(title, body, signature, fontIndex); return false; } // 5. Store Request Board Commission Posting (StoreRequest) public static bool PostStoreRequest( string id, string title, string description, string requesterName, string factionId, string requiredItemId, int requiredCount = 1, int durationDays = 5, int creditReward = 200, int reputationReward = 10, bool force = true) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("PostStoreRequest", out var fn) && fn is Func, bool> f) { return f(new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Id"] = id, ["Title"] = title, ["Description"] = description, ["RequesterName"] = requesterName, ["FactionId"] = factionId, ["RequiredItem"] = requiredItemId, ["RequiredCount"] = requiredCount, ["DurationDays"] = durationDays, ["CreditReward"] = creditReward, ["ReputationReward"] = reputationReward, ["Force"] = force }); } return false; } // 6. Procurement Order Helper (ProcurementData + procurement_slip) public static void AttachProcurementOffer( StoreClient client, string clientName, string offerDescription, string collectDescription, int dueInDays, int initialAdvanceCash, int finalRewardCash, Func itemValidator) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("AttachProcurementOffer", out var fn) && fn is Action> act) act(client, clientName, offerDescription, collectDescription, dueInDays, initialAdvanceCash, finalRewardCash, itemValidator); } // 7. Custom Gun Order Builder (GunOrderData) public static GunOrderData BuildCustomGunOrder( int tier, int baseReward, string dialogText, bool isBestOrder, IList<(string statTag, int minVal, int bonusReward, bool isMandatory)> requirements) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("BuildCustomGunOrder", out var fn) && fn is Func, GunOrderData> f) return f(tier, baseReward, dialogText, isBestOrder, requirements); return null; } // 8. Afterhour Event & Dumping Ground / Nightly Hooks public static bool RegisterAfterhourEvent( string id, string locationId, Func titleGetter, Func descriptionGetter, int durationDays = 2, float dailyChancePercent = 25f, bool closesLocation = false, Func canStartPredicate = null, Action onStart = null, Action onEnd = null) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("RegisterAfterhourEvent", out var fn) && fn is Func, bool> f) { return f(new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Id"] = id, ["LocationId"] = locationId, ["SourceModId"] = "CyberpunkMercV", ["TitleGetter"] = titleGetter, ["DescriptionGetter"] = descriptionGetter, ["DurationDays"] = durationDays, ["DailyChancePercent"] = dailyChancePercent, ["ClosesLocation"] = closesLocation, ["CanStartPredicate"] = canStartPredicate, ["OnStart"] = onStart, ["OnEnd"] = onEnd }); } return false; } public static void RegisterNightlyHook(Action hook) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("RegisterNightlyHook", out var fn) && fn is Action act) act(hook); } public static void RegisterDumpingGroundWatcher(Action watcher) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("RegisterDumpingGroundWatcher", out var fn) && fn is Action> act) act(watcher); } // 9. Save Data & Newspaper & Summon API public static bool SummonNpcNow(string id) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("SummonNpcNow", out var fn) && fn is Func summon) return summon(id); return false; } public static int GetSaveInt(string key, int defaultValue = 0) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("GetSaveInt", out var fn) && fn is Func getter) return getter(key, defaultValue); return defaultValue; } public static void SetSaveInt(string key, int value) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("SetSaveInt", out var fn) && fn is Action setter) setter(key, value); } public static bool GetSaveBool(string key, bool defaultValue = false) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("GetSaveBool", out var fn) && fn is Func getter) return getter(key, defaultValue); return defaultValue; } public static void SetSaveBool(string key, bool value) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("SetSaveBool", out var fn) && fn is Action setter) setter(key, value); } public static string GetSaveString(string key, string defaultValue = "") { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("GetSaveString", out var fn) && fn is Func getter) return getter(key, defaultValue); return defaultValue; } public static void SetSaveString(string key, string value) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("SetSaveString", out var fn) && fn is Action setter) setter(key, value); } public static void TriggerNews(string id, string headline, string body, int durationDays = 1) { var bridge = GetBridge(); if (bridge != null && bridge.TryGetValue("TriggerNews", out var fn) && fn is Action trigger) trigger(id, headline, body, durationDays); } } } ```