From b7a1b24dfacd2f130d776be37203d28656b37967 Mon Sep 17 00:00:00 2001 From: Mai Ooizumi Date: Sat, 31 Oct 2026 19:30:41 +0800 Subject: [PATCH 1/3] docs: Update documentation for 0.3 alpha test 2 Signed-off-by: Mai Ooizumi Co-authored-by: AmamiMaina --- README.md | 241 ++++++++++++++++++++++++++++----------------------- README_EN.md | 159 ++++++++++++++++++++------------- README_ZH.md | 177 ++++++++++++++++++++++--------------- 3 files changed, 338 insertions(+), 239 deletions(-) diff --git a/README.md b/README.md index 2d16cc6..9334a32 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,106 @@ -# FunRounds-CS2 -
+# FunRounds-CS2 + [![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](LICENSE) -[![Version](https://img.shields.io/badge/Version-0.2.0--alpha-informational.svg)](Cargo.toml) +[![Version](https://img.shields.io/badge/Version-0.3.0--alpha-informational.svg)](Cargo.toml) [![Rust Version](https://img.shields.io/badge/Rust-1.99.1+-orange.svg)](rust-toolchain.toml) [![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20x64-lightgrey.svg)]() -[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.0.1-success.svg)](https://github.com/untrustedmodders/plugify) +[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.0.6-success.svg)](https://github.com/untrustedmodders/plugify) **高性能、高安全性的 Counter-Strike 2 专用服务端特殊娱乐回合插件**
-A high-performance, safe, and modular special rounds plugin for Counter-Strike 2 dedicated servers. +A high-performance, safe, and modular special rounds plugin for Counter-Strike 2 dedicated servers. -[中英交替 (README.md)](README.md) • [English Only (README_EN.md)](README_EN.md) • [中文独立文档 (README_ZH.md)](README_ZH.md) +[English](README_EN.md) • [简体中文](README_ZH.md)
--- -### 项目简介 / Overview +### 项目简介 / Overview -**FunRounds-CS2** 是基于 Rust 与 C++ 原生扩展开发、面向 Counter-Strike 2 专用服务端的特殊娱乐回合(Fun Rounds)插件,运行于 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架和 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 之上。 -**FunRounds-CS2** is a modern special rounds plugin for Counter-Strike 2 dedicated servers developed in Rust and native C++, running atop the [Plugify](https://github.com/untrustedmodders/plugify) framework and [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk). +**FunRounds-CS2** 是基于 Rust 与 C++20 原生扩展开发、面向 Counter-Strike 2 专用服务端的特殊娱乐回合(Fun Rounds)插件,运行于 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架和 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 之上。 +**FunRounds-CS2** is a modern special rounds plugin for Counter-Strike 2 dedicated servers developed in Rust and native C++20, running atop [Plugify](https://github.com/untrustedmodders/plugify) and [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk). -插件在回合开始时(或由管理员实时指定)无缝应用多维度的玩法突变:修改玩家属性、物理参数、动态配装、后坐与镜头机制、特殊战斗规则及 C4 玩法,同时保证严格的崩溃隔离与无残留状态恢复。 -At the start of each round (or on administrative demand), it seamlessly applies multi-dimensional gameplay mutators: altering player attributes, physics, dynamic loadouts, recoil/view mechanics, combat rules, and bomb systems—with zero-leak state restoration and crash isolation. +在每个回合开始时(或由管理员实时指定),插件无缝应用多维度的玩法突变:修改玩家属性、物理参数、动态配装、后坐与视角机制、特殊战斗判定、小鸡生态及 C4 玩法,同时保证严格的崩溃隔离与无残留状态恢复。 +At the start of each round (or on administrative demand), it seamlessly applies multi-dimensional gameplay mutators: altering player attributes, physics, dynamic loadouts, recoil/camera mechanics, combat rules, chicken ecology, and bomb systems—with zero-leak state restoration and crash isolation. --- -### 核心特性 / Key Features - -- **三层模块化架构**:纯 Rust 核心负责规则与配置、Rust 插件适配游戏线程事件、原生 C++ 模块处理底层挂钩与碰撞。 - **Three-Tier Modular Architecture**: Pure Rust core for logic & configuration, Rust plugin for game-thread events, and a native C++ companion for low-level hooks & collision. -- **基础属性与物理参数**:支持自定义生命(1~10000)、护甲、重力(`gravity`)、移速(`speed`)、渲染颜色(`color`)、连跳(`bunnyhop`)及周期性变重力/变移速。 - **Attributes & Physics**: Custom health (1–10,000), armor, gravity, speed multiplier, player RGB tint, auto-bunnyhopping, and periodic speed/gravity oscillation. -- **镜头与射击反馈**:支持开火镜头震动(`recoil_view`)、冲击衰减(`view_punch_decay`)、无后坐散布(`no_spread_recoil`)、禁用开镜(`no_scope`)、视野调整(`fov`)及延时隐藏准星。 - **Recoil & Visual Dynamics**: Weapon recoil view-punch, view-punch decay, recoil/spread suppression, scope restriction, custom FOV, and delayed crosshair hiding. -- **动态配装与弹药机制**:支持无限备弹/无限弹匣/单发弹药、电击枪充能、投掷物自动补充、阵营配发与清理、随机抽枪及击杀升级(`kill_loadout`)。 - **Loadouts & Ammo Modes**: Infinite reserve/clip/single-shot ammo, taser recharging, grenade refills, team-based weapon distribution/clearing, random draws, and kill-streak weapon progression. -- **战斗规则与自推反冲**:吸血恢复(`lifesteal`)、爆头规则限制、按生命缩放伤害/速度/衰减、飞刀弹射、诱饵弹躲避球碰撞、开火自推反冲(`fr_knock` 支持地面/空中设置)。 - **Combat Rules & Knockback**: Vampiric lifesteal, headshot restrictions, HP-scaled damage/speed/decay, throwing knives, decoy dodgeball, and customizable shooting self-push knockback (`fr_knock`). -- **C4 炸弹与自爆机制**:支持原生 C4、鸡背 C4、可携带 C4,支持自定义安放/拆除/爆炸时间、炸弹弹跳、购买 C4(`fr_c4`)及 C4 自爆(`fr_suicide`)。 - **C4 Objectives & Suicide**: Native, chicken-carried, and portable carry bombs with custom timers, bomb bouncing, C4 purchasing (`fr_c4`), and C4 suicide explosions (`fr_suicide`). -- **复活与服务端规则覆写**:支持回合开局复活与延时按队复活,支持单模式覆盖购买时间、金钱上限、队友伤害倍率、随机出生点等 ConVar。 - **Respawns & Server Rule Overrides**: Round-start and delayed team respawns, plus per-mode overrides for buy time, cash limits, friendly fire scaling, and random spawn points. -- **严格的安全隔离**:C ABI 边界 `catch_unwind` 异常拦截,按代次(Generation)严格回滚受管属性,底层能力缺失时自动降级隔离。 - **Strict Fault Isolation**: FFI panic containment across C ABI boundaries, generation-tracked transactional rollbacks, and automatic capability quarantine. +### 核心特性 / Key Features + +| 维度 / Category | 玩法与机制说明 / Description | +| :--- | :--- | +| **基础属性与物理**
Attributes & Physics | 生命值(1~10000 或随机区间)、护甲头盔、重力倍率、移速倍率、地面摩擦力、自动连跳(Bunnyhop)、地面加速度与反向倒车行走(`ground_reverse`)、全局时间流速(`time_scale`)及周期性变重力/变移速。
Health (fixed or random range), armor, gravity, speed multiplier, friction, auto-bunnyhopping, ground acceleration, ground reverse walking, time scale, and periodic oscillation. | +| **视觉与相机视角**
Visuals & Camera | 第三人称越肩视角(`third_person`)、幽灵按行动隐身(`ghost`,支持呼吸心跳音效与距离感知)、夜视仪(`fr_nvg`)、准星/雷达隐藏(`hide_hud`)、模型 RGB 着色、半透明外观与开镜限制。
Over-the-shoulder third person, stealth ghost mode with breathing audio cues, night vision, HUD hiding, model RGB tint, translucency, and scope restrictions. | +| **射击与自推反冲**
Recoil & Knockback | 开火自身反冲自推(`fr_knock` 支持地面与空中切换)、后坐力与散布消除、开枪镜头震动冲击与衰减(`recoil_view` / `view_punch_decay`)、快速切枪(`fast_switch`)及射击引爆掉落手雷。
Shooting self-push knockback (ground/air modes), recoil & spread suppression, view-punch intensity/decay, fast switch, and shooting dropped grenades. | +| **动态配装与弹药**
Loadouts & Ammo | 阵营武器清理与定向配发、4 种弹药模式(原生 / 无限备弹 / 无限弹匣 / 单发换填)、电击枪充能、手雷自动补充(HE/闪光/烟雾/诱饵/燃烧弹)、击杀升级换枪(`kill_loadout`)与随机抽枪。
Team-specific weapon clearing/giving, 4 ammo modes (inherit/reserve/clip/single-shot), taser recharge, grenade refills, kill-progression, and random loadouts. | +| **特殊战斗判定**
Combat Modifiers | 造成伤害吸血、反弹伤害(`reflect_damage`)、按当前生命动态缩放伤害/移速/衰减、能量吸收护盾、开枪自伤(未命中扣血)、诱饵弹躲避球碰撞杀伤(`dodgeball`)、右键飞刀投掷弹射与命中持续燃烧(`afterburn`)。
Vampiric lifesteal, reflect damage, HP-scaled damage/speed/decay, energy shield, miss penalty self-damage, decoy dodgeball, throwing knives, and afterburn. | +| **C4 炸弹与自爆**
C4 Objectives & Suicide | 3 种炸弹模式(原生 C4 / 鸡背 C4 / 便携可携带 C4)、自定义安放/拆除/爆炸耗时、炸弹弹跳、4 色引线拆包剪线小游戏(`fr_wire`)、现金购买 C4(`fr_c4`)及引爆炸弹自爆(`fr_suicide`)。
3 bomb types (native, chicken, carry), custom timers, bomb bouncing, 4-color wire cutting minigame, C4 purchasing, and suicide detonation. | +| **小鸡生态与回血**
Chicken & Healthshots | 普通小鸡比例刷新生态、互动吃鸡回血与未消化自爆风险机制、小鸡连锁爆炸;自定义医疗针回血比例与上限控制(`healthshot`,支持 `fr_healthshot` 购买)。
Chicken population scaling, eating chickens with digestion risk & chain explosions; custom healthshot healing ratios with cash purchase. | +| **经济与多语言**
Economy & i18n | 任意位置购买、阵营购买权限、回合保底现金与被动收入;内置完整中英多语言本地化(`zh-CN` / `en`),优先跟随客户端语言。
Buy anywhere, team purchase access, round money floor, passive income, and built-in bilingual i18n matching client preferences. | + +
+点击展开架构与可靠性设计 / Click to expand Architecture & Reliability + +- **三层模块化架构**: + - `funrounds-core`:纯 Rust 编写、独立于引擎的核心库。负责玩法规则、状态机流转、`[defaults]` 模板继承、数学判定及严格校验的 TOML 配置解析。 + - `funrounds-plugin`:Plugify Rust 原生适配插件。在游戏主线程响应 S2SDK 实体事件,管理实体生命周期与多语言反馈。 + - `funrounds-native`:C++20 原生伴侣模块。提供底层伤害桥接、投射物 Touch、实体碰撞拦截、小鸡互动、幽灵雷达遮蔽及 Gamedata 偏移管理。 +- **严格的安全隔离**: + - **FFI Panic 全边界捕获**:所有跨 C ABI 边界的回调均由 `catch_unwind` 包裹,防止单次回调异常波及专用服务端进程。 + - **事务性状态回滚**:严格记录代次(Generation)与实体快照,在回合结束或插件停用时仅还原受管属性与 ConVar,绝不残留脏状态。 + - **能力动态隔离**:根据服务端运行环境的 SDK 钩子支持情况,自动隔离缺失底层能力的模式,其余模式不受影响正常运行。 +
--- -### 项目目录结构 / Project Layout +### 项目目录结构 / Project Layout ```text ├── bindings/ # Plugify S2SDK 接口清单 (123 项接口定义) / Provider manifest -├── config/ # 示例配置文件 (funrounds.example.toml) / Reference configuration +├── config/ # 示例配置文件及多语言包 / Configurations & i18n files +│ ├── funrounds.example.toml # 示例配置 / Reference configuration +│ └── i18n/ # 本地化翻译文件 (zh-CN.toml, en.toml) / Localization catalogs ├── crates/ │ ├── funrounds-core/ # 独立于引擎的玩法核心、规则校验与配置解析 / Core rules & config parser │ └── funrounds-plugin/ # 游戏线程 Plugify 插件运行时 / Plugify game runtime plugin ├── native/ │ └── funrounds-native/ # 原生 C++ 伴侣扩展 (底层挂钩、碰撞拦截、Gamedata) / Native C++ companion ├── packaging/ # Rust 插件包清单 (funrounds.pplugin) / Plugify package manifest -├── scripts/ # 原生构建与 CI 脚本 / Build & CI automation scripts +├── scripts/ # 原生构建与 CI 自动化脚本 / Build & CI automation scripts └── rust-toolchain.toml # 固定编译器工具链版本 (Rust 1.99.1) / Pinned Rust toolchain ``` --- -### 安装与部署 / Installation +### 安装与部署 / Installation -#### 前置要求 / Prerequisites +#### 前置要求 / Prerequisites -- Counter-Strike 2 专用服务端(Windows x64 或 Linux x64)
Counter-Strike 2 Dedicated Server (Windows x64 or Linux x64) -- [Plugify](https://github.com/untrustedmodders/plugify) 插件框架已安装运行
[Plugify](https://github.com/untrustedmodders/plugify) framework installed and active -- [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 插件(版本 `3.0.1`)已配置
[S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) plugin (version `3.0.1`) configured +- Counter-Strike 2 专用服务端(Windows x64 或 Linux x64)
Counter-Strike 2 Dedicated Server (Windows x64 or Linux x64) +- 已安装并运行 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架
[Plugify](https://github.com/untrustedmodders/plugify) framework installed and active +- 已配置并加载 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 插件(版本 `3.0.6`)
[S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) plugin (version `3.0.6`) active in Plugify -#### 目录部署 / Deployment Structure +#### 目录部署 / Deployment Structure -将构建产物复制到服务端 `game/csgo/addons/plugify/` 对应路径: -Copy the build outputs into the respective directories under `game/csgo/addons/plugify/`: +将编译产物与配置文件复制到服务端 `game/csgo/addons/plugify/` 对应路径: +Copy the build artifacts and configurations into `game/csgo/addons/plugify/`: ```text game/csgo/addons/plugify/ ├── configs/ -│ └── funrounds.toml # 从 config/funrounds.example.toml 复制 / Config file +│ ├── funrounds.toml # 从 config/funrounds.example.toml 复制 +│ └── funrounds/ +│ └── i18n/ # 复制 config/i18n/ 下的翻译文件 +│ ├── zh-CN.toml +│ └── en.toml └── envs/ ├── funrounds/ # Rust 主插件 / Main Rust Plugin │ ├── bin/ - │ │ └── funrounds_plugin.dll (或 .so) # 动态库 / Binary + │ │ └── funrounds_plugin.dll (或 .so) # 动态库 / Plugin binary │ └── funrounds.pplugin # 插件清单 / Manifest - └── funrounds_native/ # 原生 C++ 扩展 / Native C++ Companion + └── funrounds_native/ # 原生 C++ 伴侣扩展 / Native C++ Companion ├── bin/ │ └── funrounds-native.dll (或 lib*.so) # 原生动态库 / Native binary ├── funrounds-native.pplugin # 原生插件清单 / Native manifest @@ -97,112 +110,124 @@ game/csgo/addons/plugify/ --- -### 配置说明 / Configuration +### 指令列表 / Commands Reference + +#### 管理员与控制台指令(Console / RCON) / Server & Administrator Commands -配置文件采用严格 TOML 语法解析。支持 `[defaults]` 全局继承模版: -The configuration uses strict TOML syntax with support for a global `[defaults]` inheritance template: +| 控制台指令
Command | 参数
Arguments | 说明
Description | +| :--- | :--- | :--- | +| `fr_status` | 无
None | 查看当前回合状态、运行阶段、底层能力就绪状态及故障排查信息。
Displays current mode, phase, capability readiness, and fault diagnoses. | +| `fr_list` | 无
None | 列出配置池中所有已启用的特殊模式列表。
Lists all loaded and enabled round modes in the pool. | +| `fr_next` | `` | 指定下一回合的模式 ID,或恢复随机抽取 (`random`)。
Queues a specific mode ID or random selection for the next round. | +| `fr_reload` | 无
None | 校验并重载配置文件与多语言文本,重载成功于下一回合生效。
Validates and schedules configuration and i18n reload for the next round. | +| `fr_enable` | `<0 \| 1>` | 插件总启停开关:`1` 为启用,`0` 为停用。
Master switch: disables (`0`) or enables (`1`) the plugin. | + +#### 玩家控制台与聊天快捷指令 / Player Commands (Console & Chat) + +| 控制台指令
Console | 聊天指令
Chat Alias | 参数
Arguments | 说明
Description | +| :--- | :--- | :--- | :--- | +| `fr_info` | `!info` / `!frinfo` | 无
None | 在聊天栏中查看当前回合模式名称、编号与玩法说明。
Displays current round mode name, ID, and description in chat. | +| `fr_help` | `!help` / `!frhelp` | 无
None | 查看插件帮助信息及玩家可用指令列表。
Displays available player commands and usage instructions. | +| `fr_knock` | `!knock` | `[0\|1\|2]` | 设置或切换开火自推反冲(`0` 关闭,`1` 地空全开,`2` 仅空中 [默认],无参依次切换)。
Configures recoil self-push (`0`: off, `1`: ground & air, `2`: airborne only [default]; cycle without args). | +| `fr_c4` | `!c4` | 无
None | 进攻方在模式允许时按配置价格购买额外 C4。
T players purchase extra C4 at the configured price when allowed. | +| `fr_suicide` | `!suicide` | 无
None | 允许自爆时使用所持或购买的 C4 启动自爆。
Triggers suicide explosion with held or purchased C4 when allowed. | +| `fr_chicken` | `!chicken` | 无
None | 按配置价格在当前位置购买一只小鸡。
Purchases an ordinary chicken at the configured price. | +| `fr_healthshot` | `!healthshot` | 无
None | 按配置价格购买一支医疗针。
Purchases a healthshot at the configured price. | +| `fr_nvg` | `!nvg` | 无
None | 开启或关闭夜视仪。
Toggles night vision. | +| `fr_wire` | `!wire` | `` | 选择安包引线或拆包剪线颜色(`blue` / `yellow` / `red` / `green`)。
Selects planting or quick-defusing wire color (blue, yellow, red, green). | + +--- + +### 配置说明 / Configuration + +配置文件采用严格 TOML 语法解析。支持 `[defaults]` 模板为所有模式提供基础属性继承: +Configuration uses strict TOML syntax with a global `[defaults]` template for field inheritance: ```toml # 全局设置 / Global settings -diagnostics = false # 是否开启诊断日志 / Diagnostic logging +diagnostics = false # 诊断日志开关 / Diagnostic logging + +# 多语言配置 / i18n +[i18n] +default_language = "zh-CN" # 服务端缺省语言("zh-CN" 或 "en")/ Default language -# 全局默认模版(模式自身字段优先) / Global defaults (mode-level fields take precedence) +# 全局默认模板(模式内未设置的字段将继承此处) / Global defaults [defaults] gravity = 1.0 bunnyhop = false [[modes]] -id = "example" # 唯一标识 / Unique mode identifier +id = "example" # 模式唯一标识 / Unique mode identifier enabled = true # 是否启用该模式 / Whether mode enters the pool -name = "鸟狙低重力" # 显示名称 / Display name -description = "低重力狙击对抗" # 模式说明 / Description -weapons = ["weapon_ssg08", "weapon_glock"] +name_key = "mode.example.name" # 多语言名称键 / Localized name key +description_key = "mode.example.description" # 多语言说明键 / Localized description key +weapons = ["weapon_famas", "weapon_p250"] -# 阵营发放与清理 / Team loadout control -clear_weapons = "all" # 发放前清理武器队伍 (none / all / terrorists / counter_terrorists) -give_weapons = "all" # 发放候选武器队伍 -give_knife = "all" # 发放刀具队伍 +# 阵营装备配发与清理 / Team equipment distribution +clear_weapons = "all" # 配发前清理武器的队伍 (none / all / terrorists / counter_terrorists) +give_weapons = "all" # 配发候选武器的队伍 +give_knife = "all" # 配发刀具的队伍 # 基础属性与移动 / Attributes & movement -health = 100 # 初始生命值 (1~10000) / Initial health -armor = 100 # 初始护甲值 (0~255) / Initial armor -gravity = 0.5 # 重力倍率 / Gravity scale (0.0 < g <= 10.0) -speed = 1.0 # 移速倍率 / Speed multiplier -bunnyhop = true # 开启自动连跳 / Auto-bunnyhopping -self_push = true # 开启开火自推反冲 / Weapon recoil self-push - -# 射击与镜头反馈 / Recoil & view -no_spread_recoil = false # 消除散布与后坐 / Suppress spread & recoil -recoil_view = 2.0 # 开火镜头震动强度 / Recoil view-punch intensity -view_punch_decay = 5.0 # 镜头冲击衰减 / View-punch decay - -# 战斗与弹药 / Combat & ammo -ammo = "reserve" # 弹药模式 (inherit / reserve / clip / single_shot) -lifesteal = false # 伤害吸血 / Vampiric lifesteal -health_damage = false # 造成的伤害随自身生命缩放 / Scale damage with current HP - -# 特殊 C4 规则(原生 native、鸡背 chicken 或可携带 carry) / Custom Bomb -# bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, defuse_kit_time = 5.0, defuse_time = 10.0, bounce = false } +health = 120 # 初始生命值 (1~10000 或随机范围 { min = 100, max = 150 }) +armor = 50 # 初始护甲值 (0~255 或随机范围 { min = 0, max = 100 }) +gravity = 1.0 # 重力倍率 ((0, 10],1.0 为正常重力) +speed = 1.0 # 移速倍率 ((0, 10]) +self_push = true # 开启开火自推反冲 / Recoil self-push + +# 射击与视角控制 / Shooting & view dynamics +ammo = "reserve" # 弹药规则 (inherit / reserve / clip / single_shot) +headshots = "normal" # 爆头规则 (normal / only / disabled) +fast_switch = true # 快速切枪开关 / Fast switch + +# 特殊玩法机制选开 / Optional mutators +# lifesteal = true # 吸血恢复 / Vampiric lifesteal +# suicide = true # 允许自爆玩法 / Suicide blast +# third_person = { distance = 64.0, follow_eyes = true, return_strength = 2.0 } # 第三人称 +# bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, bounce = false } # 特殊炸弹 ``` ---- - -### 指令列表 / Commands Reference +
+查看完整配置选项注释 / View Full Configuration Reference -#### 管理员与服务端控制台指令(Console / RCON)/ Server & Administrator Commands - -| 控制台指令
Command | 参数
Arguments | 说明
Description | -| :--- | :--- | :--- | -| `fr_status` | 无
None | 查看当前回合状态、运行阶段、底层能力就绪状态及故障排查信息。
Displays current mode, phase, capability readiness, and fault diagnoses. | -| `fr_list` | 无
None | 列出配置池中所有已启用的特殊模式列表。
Lists all loaded and enabled round modes in the pool. | -| `fr_next` | `` | 指定下一回合的模式 ID,或恢复随机抽取 (`random`)。
Queues a specific mode ID or random selection for the next round. | -| `fr_reload` | 无
None | 校验并重载配置文件,重载成功于下一回合生效。
Validates and schedules configuration reload for the next round. | -| `fr_enable` | `<0 \| 1>` | 插件总启停开关:`1` 为启用,`0` 为停用。
Master switch: disables (`0`) or enables (`1`) the plugin. | - -#### 玩家控制台与聊天指令 / Player Commands (Console & Chat) - -| 控制台指令
Console | 聊天指令
Chat Alias | 参数
Arguments | 说明
Description | -| :--- | :--- | :--- | :--- | -| `fr_info` | `!frinfo` | 无
None | 在聊天栏中查看当前回合模式名称、编号与玩法说明。
Displays current round mode name, ID, and description in chat. | -| `fr_help` | `!frhelp` | 无
None | 查看插件帮助信息及玩家可用指令。
Displays available player commands and usage instructions. | -| `fr_knock` | `!knock` | `[0\|1\|2]` | 设置或切换开火自推反冲(`0` 关闭,`1` 地面及空中,`2` 仅空中 [默认],无参数依次切换)。
Configures weapon recoil self-push (`0`: off, `1`: ground & air, `2`: airborne only [default]; cycle without args). | -| `fr_c4` | `!c4` | 无
None | 当模式允许时,花费 $10,000 购买额外 C4。
Purchases an extra C4 for $10,000 when allowed by the mode (`c4_buy`). | -| `fr_suicide` | `!suicide` | 无
None | 当模式允许自爆时,使用已有或购买的 C4 引爆炸药。
Triggers a suicide explosion with held or purchased C4 when allowed (`suicide`). | +请直接查阅 [config/funrounds.example.toml](config/funrounds.example.toml) 获取完整的字段说明,涵盖小鸡生态、伤害缩放曲线、幽灵隐身、特殊 C4、购买与经济等全部选项。 +Refer to [config/funrounds.example.toml](config/funrounds.example.toml) for full documentation of chicken ecology, health curves, ghost stealth, custom bombs, and economy rules. +
--- -### 源码编译 / Building from Source +### 源码编译 / Building from Source -#### 1. 编译 Rust 插件 / Build Rust Plugin +#### 1. 编译 Rust 插件 / Build Rust Plugin 工具链要求:Rust `1.99.1`(由 `rust-toolchain.toml` 自动匹配): -Toolchain requirement: Rust `1.99.1` (automatically managed by `rust-toolchain.toml`): +Requires Rust `1.99.1` (automatically handled by `rust-toolchain.toml`): ```bash -# 格式化检查与 Clippy 严格静态检查 / Format and linting +# 代码格式化与 Clippy 严格静态检查 cargo fmt --all -- --check cargo clippy --workspace --all-targets --locked -- -D warnings -# 执行全量单元测试 / Run unit tests (119+ tests) +# 执行全量自动化单元测试 cargo test --workspace --locked -# 编译 Release 发布产物 / Build release binaries +# 编译 Release 发布产物 cargo build --release --workspace --locked ``` -#### 2. 编译原生 C++ 扩展 / Build Native C++ Companion +#### 2. 编译原生 C++ 伴侣扩展 / Build Native C++ Companion -工具链要求:Python 3.10+、CMake 3.25+ 及对应平台 C++20 编译器(MSVC 2022+ 或 GCC 11+): -Toolchain requirement: Python 3.10+, CMake 3.25+, and a C++20 compiler (MSVC 2022+ or GCC 11+): +要求 Python 3.10+、CMake 3.25+ 以及对应平台的 C++20 编译器(MSVC 2022+ 或 GCC 11+): +Requires Python 3.10+, CMake 3.25+, and a C++20 compiler (MSVC 2022+ or GCC 11+): ```bash -# 自动抓取对齐 SDK 输入并编译原生扩展 / Fetch pinned SDK inputs and build native module +# 构建原生扩展并输出至 dist/native python scripts/build-native.py --output-dir dist/native ``` --- -### 开源协议与作者 / License & Author +### 开源协议与作者 / License & Author - **作者 / Author**: Mai Ooizumi ([@Mai-Ooizumi](https://github.com/Mai-Ooizumi)) - **开源协议 / License**: GNU Affero General Public License v3.0 or later ([AGPL-3.0-or-later](LICENSE)) diff --git a/README_EN.md b/README_EN.md index 44b513f..c18cb50 100644 --- a/README_EN.md +++ b/README_EN.md @@ -1,16 +1,16 @@ -# FunRounds-CS2 -
+# FunRounds-CS2 + [![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](LICENSE) -[![Version](https://img.shields.io/badge/Version-0.2.0--alpha-informational.svg)](Cargo.toml) +[![Version](https://img.shields.io/badge/Version-0.3.0--alpha-informational.svg)](Cargo.toml) [![Rust Version](https://img.shields.io/badge/Rust-1.99.1+-orange.svg)](rust-toolchain.toml) [![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20x64-lightgrey.svg)]() -[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.0.1-success.svg)](https://github.com/untrustedmodders/plugify) +[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.0.6-success.svg)](https://github.com/untrustedmodders/plugify) **A high-performance, safe, and modular special rounds plugin for Counter-Strike 2 dedicated servers.** -[Bilingual (README.md)](README.md) • [English Only (README_EN.md)](README_EN.md) • [简体中文 (README_ZH.md)](README_ZH.md) +[English](README_EN.md) • [简体中文](README_ZH.md)
@@ -18,33 +18,47 @@ ### Overview -**FunRounds-CS2** is a modern Counter-Strike 2 server plugin developed in Rust and native C++, built atop the [Plugify](https://github.com/untrustedmodders/plugify) framework and [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk). +**FunRounds-CS2** is a modern Counter-Strike 2 server plugin developed in Rust and native C++20, built atop the [Plugify](https://github.com/untrustedmodders/plugify) framework and [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk). -It revitalizes the classic "Fun Rounds" gameplay concept for Source 2. Each round (or upon administrative selection), the plugin seamlessly applies distinctive gameplay mutators—altering player attributes, loadouts, physics, combat rules, and bomb mechanics—while maintaining strict engine stability and zero-leak state restoration. +At the start of each round (or on administrative demand), it seamlessly applies multi-dimensional gameplay mutators—altering player attributes, physics, dynamic loadouts, recoil/camera mechanics, combat rules, chicken ecology, and bomb systems—with zero-leak state restoration and crash isolation. + +--- ### Key Features -- **Three-Tier Modular Architecture**: - - `funrounds-core`: Pure, engine-agnostic Rust library handling state machines, round queues, math, rules, `[defaults]` inheritance, and strictly validated TOML configurations. +| Category | Description | +| :--- | :--- | +| **Attributes & Physics** | Health (1–10,000 or random range), armor/helmets, gravity scaling, speed multiplier, friction, auto-bunnyhopping, ground acceleration, ground reverse walking (`ground_reverse`), time scale (`time_scale`), and periodic speed/gravity oscillation. | +| **Visuals & Camera** | Over-the-shoulder third person (`third_person`), stealth ghost mode with breathing audio cues and distance awareness (`ghost`), night vision (`fr_nvg`), crosshair/radar hiding (`hide_hud`), model RGB tinting, translucency, and scope restrictions. | +| **Recoil & Knockback** | Weapon recoil self-push knockback (`fr_knock` supports ground and air modes), recoil & spread suppression, view-punch intensity/decay (`recoil_view` / `view_punch_decay`), fast switch (`fast_switch`), and shooting dropped grenades. | +| **Loadouts & Ammunition** | Team-specific weapon clearing and granting, 4 ammo modes (inherit / reserve / clip / single-shot), taser recharge intervals, automatic grenade replenishment (HE/flash/smoke/decoy/molotov), kill progression (`kill_loadout`), and random draws. | +| **Combat Modifiers** | Vampiric lifesteal, reflect damage (`reflect_damage`), HP-scaled damage/speed/decay, energy absorption shield, miss penalty self-damage, decoy dodgeball collisions (`dodgeball`), throwing knives with bouncing, and afterburn damage. | +| **C4 Objectives & Suicide** | 3 bomb types (native, chicken, carry), custom timers, bomb bouncing, 4-color wire cutting minigame (`fr_wire`), C4 cash purchasing (`fr_c4`), and C4 suicide explosions (`fr_suicide`). | +| **Chicken & Healthshots** | Chicken population scaling, eating chickens with digestion risk & chain explosions; custom healthshot healing ratios with cash purchase (`fr_healthshot`). | +| **Economy & i18n** | Buy anywhere, team purchase access, round money floor, passive income; built-in bilingual i18n (`zh-CN` / `en`) automatically matching client language. | + +
+Click to expand Architecture & Reliability + +- **Three-Tier Architecture**: + - `funrounds-core`: Pure, engine-independent Rust library handling state machines, round queues, math, rules, `[defaults]` template inheritance, and strictly validated TOML configurations. - `funrounds-plugin`: Native Plugify Rust plugin interacting safely with the CS2 engine on the game thread via S2SDK. - - `funrounds-native`: Native C++ companion module handling low-level engine hooks, entity collision, projectile touch detection, and gamedata offsets. -- **Rich Round Mutators**: - - **Player Physics & Attributes**: Configurable health (up to 10,000), armor/helmets, gravity scaling, speed multiplier, player RGB tint, auto-bunnyhop, dynamic over-health decay, and periodic gravity/speed oscillation. - - **Recoil & Knockback**: Custom weapon recoil view-punch, view-punch decay, recoil/spread suppression, scope restriction, custom FOV, delayed crosshair hiding, and shooting self-push / knockback physics (`fr_knock`). - - **Weapons & Dynamic Loadouts**: Whitelisted CS2 weapons, infinite reserve/clip/single-shot ammo, taser recharge timers, automatic grenade replenishment (HE & Decoy), team-based weapon distribution/clearing, independent random loadouts, and kill-streak weapon progression. - - **Combat Modifiers**: Vampiric lifesteal, headshot restrictions, damage/speed scaling by player HP, decoy dodgeball physics, and throwing knives with bouncing mechanics. - - **Custom C4 / Bomb & Suicide Mechanics**: Support for native bombs, chicken-carried bombs, portable carry bombs, custom plant/explode/defuse timers, bouncing bomb physics, C4 purchasing (`fr_c4`), and C4 suicide explosions (`fr_suicide`). - - **Respawns & Server Rule Overrides**: Round-start and delayed team respawns, plus per-mode overrides for buy time, cash limits, friendly fire scaling, and random spawn points. -- **Fail-Safe & Fault-Tolerant Design**: + - `funrounds-native`: Native C++20 companion module handling low-level engine hooks, entity collision, projectile touch detection, chicken interactions, ghost radar occlusion, and gamedata offsets. +- **Strict Fault Isolation**: - **FFI Panic Containment**: All engine callbacks wrap in `catch_unwind` at the C ABI boundary to prevent server crashes. - **Transactional State Restoration**: Tracks player/round generations to guarantee only hijacked properties and ConVars are restored without corrupting native server settings. - **Dynamic Capability Quarantine**: Automatically excludes modes requiring missing SDK hooks or engine features without impacting other modes. +
+ +--- ### Project Layout ```text ├── bindings/ # Plugify S2SDK provider bindings (123 methods) -├── config/ # Reference configurations (funrounds.example.toml) +├── config/ # Reference configurations and i18n catalogs +│ ├── funrounds.example.toml # Reference configuration +│ └── i18n/ # Localization files (zh-CN.toml, en.toml) ├── crates/ │ ├── funrounds-core/ # Engine-independent gameplay logic, rules & config parser │ └── funrounds-plugin/ # Native Plugify runtime plugin implementation @@ -55,22 +69,28 @@ It revitalizes the classic "Fun Rounds" gameplay concept for Source 2. Each roun └── rust-toolchain.toml # Fixed toolchain configuration (Rust 1.99.1) ``` +--- + ### Installation #### Prerequisites - Counter-Strike 2 Dedicated Server (Windows x64 or Linux x64) -- [Plugify](https://github.com/untrustedmodders/plugify) installed on your CS2 server -- [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) plugin (version `3.0.1`) active in Plugify +- [Plugify](https://github.com/untrustedmodders/plugify) installed and active on your CS2 server +- [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) plugin (version `3.0.6`) active in Plugify #### Deployment -Copy the built artifacts to the server's `game/csgo/addons/plugify/` directory: +Copy compiled binaries and configurations to the server's `game/csgo/addons/plugify/` directory: ```text game/csgo/addons/plugify/ ├── configs/ -│ └── funrounds.toml # Copied from config/funrounds.example.toml +│ ├── funrounds.toml # Copied from config/funrounds.example.toml +│ └── funrounds/ +│ └── i18n/ # Copy catalogs from config/i18n/ +│ ├── zh-CN.toml +│ └── en.toml └── envs/ ├── funrounds/ # Main Rust Plugin │ ├── bin/ @@ -84,6 +104,36 @@ game/csgo/addons/plugify/ └── funrounds-native.jsonc # Gamedata offsets ``` +--- + +### Commands Reference + +#### Server & Administrator Commands (Console / RCON) + +| Command | Arguments | Description | +| :--- | :--- | :--- | +| `fr_status` | None | Displays current mode, phase, engine capabilities, and fault diagnoses. | +| `fr_list` | None | Lists all loaded and enabled round modes in the pool. | +| `fr_next` | `` | Queues a specific mode ID or random mode for the next round. | +| `fr_reload` | None | Validates and schedules configuration and i18n reload for the next round. | +| `fr_enable` | `<0 \| 1>` | Master switch: disables (`0`) or enables (`1`) the plugin. | + +#### Player Commands (Console & Chat) + +| Console Command | Chat Alias | Arguments | Description | +| :--- | :--- | :--- | :--- | +| `fr_info` | `!info` / `!frinfo` | None | Displays the current round mode, ID, and description in chat. | +| `fr_help` | `!help` / `!frhelp` | None | Displays available player commands and usage instructions. | +| `fr_knock` | `!knock` | `[0\|1\|2]` | Sets or cycles shooting self-push (`0`: off, `1`: ground & air, `2`: airborne only [default]; cycle without args). | +| `fr_c4` | `!c4` | None | Purchases an extra C4 at the configured price when allowed. | +| `fr_suicide` | `!suicide` | None | Triggers a suicide explosion with held or purchased C4 when allowed. | +| `fr_chicken` | `!chicken` | None | Buys an ordinary chicken at the configured price. | +| `fr_healthshot` | `!healthshot` | None | Buys a healthshot at the configured price. | +| `fr_nvg` | `!nvg` | None | Toggles night vision. | +| `fr_wire` | `!wire` | `` | Selects planting or quick-defusing wire color (`blue`, `yellow`, `red`, `green`). | + +--- + ### Configuration The configuration uses strict TOML format with support for global `[defaults]` template inheritance: @@ -92,6 +142,10 @@ The configuration uses strict TOML format with support for global `[defaults]` t # Top-level settings diagnostics = false # Diagnostic logging (default: false) +# Internationalization +[i18n] +default_language = "en" # Server default language ("zh-CN" or "en") + # Global default template (mode-level fields take precedence) [defaults] gravity = 1.0 @@ -100,9 +154,9 @@ bunnyhop = false [[modes]] id = "example" # Unique mode identifier (ASCII, alphanumeric, '_' or '-') enabled = true # Whether this mode enters the round pool -name = "Scout Jump" # Display name -description = "Low gravity sniper battle" -weapons = ["weapon_ssg08", "weapon_glock"] +name_key = "mode.example.name" # Localized name key +description_key = "mode.example.description" # Localized description key +weapons = ["weapon_famas", "weapon_p250"] # Team loadout control clear_weapons = "all" # Team to clear weapons before granting (none / all / terrorists / counter_terrorists) @@ -110,48 +164,31 @@ give_weapons = "all" # Team to receive candidates give_knife = "all" # Team to receive knife # Attributes & movement -health = 100 # Initial health (1-10000) -armor = 100 # Initial armor (0-255) -gravity = 0.5 # Gravity multiplier (0.0 < g <= 10.0) -speed = 1.0 # Speed multiplier -bunnyhop = true # Auto-bunnyhopping +health = 120 # Initial health (1-10000, or random range { min = 100, max = 150 }) +armor = 50 # Initial armor (0-255, or random range { min = 0, max = 100 }) +gravity = 1.0 # Gravity multiplier ((0, 10], 1.0 is normal gravity) +speed = 1.0 # Speed multiplier ((0, 10]) self_push = true # Weapon recoil self-push # Recoil & view -no_spread_recoil = false # Suppress spread and recoil -recoil_view = 2.0 # Recoil view-punch intensity -view_punch_decay = 5.0 # View-punch decay - -# Combat & ammo ammo = "reserve" # Ammo mode (inherit / reserve / clip / single_shot) -lifesteal = false # Vampiric lifesteal -health_damage = false # Scale damage with current attacker HP - -# Optional Bomb Rules (Native, Chicken, or Carry) -# bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, defuse_kit_time = 5.0, defuse_time = 10.0, bounce = false } +headshots = "normal" # Headshot rule (normal / only / disabled) +fast_switch = true # Fast weapon switch + +# Optional mutators +# lifesteal = true # Vampiric lifesteal +# suicide = true # Suicide blast gameplay +# third_person = { distance = 64.0, follow_eyes = true, return_strength = 2.0 } +# bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, bounce = false } ``` -### Commands Reference +
+View Full Configuration Reference -#### Server & Administrator Commands (Console / RCON) +Refer to [config/funrounds.example.toml](config/funrounds.example.toml) for full documentation of chicken ecology, health curves, ghost stealth, custom bombs, and economy rules. +
-| Command | Arguments | Description | -| :--- | :--- | :--- | -| `fr_status` | None | Displays current mode, phase, engine capabilities, and fault diagnoses. | -| `fr_list` | None | Lists all loaded and enabled round modes in the pool. | -| `fr_next` | `` | Queues a specific mode ID or random mode for the next round. | -| `fr_reload` | None | Validates and schedules configuration reload for the next round. | -| `fr_enable` | `<0 \| 1>` | Master switch: disables (`0`) or enables (`1`) the plugin. | - -#### Player Commands (Console & Chat) - -| Console Command | Chat Alias | Arguments | Description | -| :--- | :--- | :--- | :--- | -| `fr_info` | `!frinfo` | None | Displays the current round mode, ID, and description in chat. | -| `fr_help` | `!frhelp` | None | Displays available player commands and usage instructions. | -| `fr_knock` | `!knock` | `[0\|1\|2]` | Sets or cycles shooting self-push (`0`: off, `1`: ground & air, `2`: airborne only [default]; cycle without args). | -| `fr_c4` | `!c4` | None | Purchases an extra C4 for $10,000 when allowed by mode (`c4_buy`). | -| `fr_suicide` | `!suicide` | None | Triggers a suicide explosion with held or purchased C4 when allowed. | +--- ### Building from Source @@ -164,7 +201,7 @@ Requires Rust `1.99.1` (automatically managed by `rust-toolchain.toml`): cargo fmt --all -- --check cargo clippy --workspace --all-targets --locked -- -D warnings -# Execute test suite (119+ unit tests) +# Execute test suite cargo test --workspace --locked # Build optimized release binaries diff --git a/README_ZH.md b/README_ZH.md index 83cd04a..538b2ad 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -1,16 +1,16 @@ -# FunRounds-CS2 (简体中文) -
+# FunRounds-CS2 + [![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](LICENSE) -[![Version](https://img.shields.io/badge/Version-0.2.0--alpha-informational.svg)](Cargo.toml) +[![Version](https://img.shields.io/badge/Version-0.3.0--alpha-informational.svg)](Cargo.toml) [![Rust Version](https://img.shields.io/badge/Rust-1.99.1+-orange.svg)](rust-toolchain.toml) [![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20x64-lightgrey.svg)]() -[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.0.1-success.svg)](https://github.com/untrustedmodders/plugify) +[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.0.6-success.svg)](https://github.com/untrustedmodders/plugify) **高性能、高安全性的 Counter-Strike 2 专用服务端特殊娱乐回合插件** -[中英交替 (README.md)](README.md) • [English Only (README_EN.md)](README_EN.md) • [简体中文 (README_ZH.md)](README_ZH.md) +[English](README_EN.md) • [简体中文](README_ZH.md)
@@ -18,33 +18,47 @@ ### 项目简介 -**FunRounds-CS2** 是基于 Rust 与 C++ 原生扩展开发、面向 Counter-Strike 2 专用服务端的特殊娱乐回合(Fun Rounds)插件。本项目构建于 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架和 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 扩展之上。 +**FunRounds-CS2** 是基于 Rust 与 C++20 原生扩展开发、面向 Counter-Strike 2 专用服务端的特殊娱乐回合(Fun Rounds)插件。本项目构建于 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架和 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 扩展之上。 + +插件在每个回合开始时(或由管理员实时指定)无缝应用多维度的玩法突变:修改玩家属性、物理参数、动态配装、后坐与视角机制、特殊战斗规则、小鸡生态及 C4 玩法,同时保证严格的崩溃隔离与无残留状态恢复。 -插件在回合开始时(或由管理员实时指定)无缝应用多维度的玩法突变:修改玩家属性、物理参数、动态配装、后坐与镜头机制、特殊战斗规则及 C4 玩法,同时保证严格的崩溃隔离与无残留状态恢复。 +--- ### 核心特性 +| 玩法维度 | 特性机制概要 | +| :--- | :--- | +| **基础属性与物理** | 生命值(1~10000 或区间随机)、护甲头盔、重力倍率、移速倍率、地面摩擦力、自动连跳(Bunnyhop)、地面加速度与反向倒车行走(`ground_reverse`)、全局时间流速(`time_scale`)及周期性变重力/变移速。 | +| **视觉与相机视角** | 第三人称越肩视角(`third_person`)、幽灵按行动隐身(`ghost`,支持呼吸心跳音效与距离感知)、夜视仪(`fr_nvg`)、准星/雷达隐藏(`hide_hud`)、模型 RGB 着色、半透明外观与开镜限制。 | +| **射击与自推反冲** | 开火自身反冲自推(`fr_knock` 支持地面与空中切换)、后坐力与散布消除、开枪镜头震动冲击与衰减(`recoil_view` / `view_punch_decay`)、快速切枪(`fast_switch`)及射击引爆掉落手雷。 | +| **动态配装与弹药** | 阵营武器清理与定向配发、4 种弹药模式(原生 / 无限备弹 / 无限弹匣 / 单发换装)、电击枪充能、手雷自动补充(HE/闪光/烟雾/诱饵/燃烧弹)、击杀升级换枪(`kill_loadout`)与随机抽枪。 | +| **特殊战斗判定** | 造成伤害吸血、反弹伤害(`reflect_damage`)、按当前生命动态缩放伤害/移速/衰减、能量吸收护盾、开枪自伤(未命中扣血)、诱饵弹躲避球碰撞杀伤(`dodgeball`)、右键飞刀投掷弹射与命中持续燃烧(`afterburn`)。 | +| **C4 炸弹与自爆** | 3 种炸弹模式(原生 C4 / 鸡背 C4 / 便携可携带 C4)、自定义安放/拆除/爆炸耗时、炸弹弹跳、4 色引线拆包剪线小游戏(`fr_wire`)、现金购买 C4(`fr_c4`)及引爆炸弹自爆(`fr_suicide`)。 | +| **小鸡生态与回血** | 普通小鸡比例刷新生态、互动吃鸡回血与未消化自爆风险机制、小鸡连锁爆炸;自定义医疗针回血比例与上限控制(`healthshot`,支持 `fr_healthshot` 购买)。 | +| **经济与多语言** | 任意位置购买、阵营购买权限、回合保底现金与被动收入;内置完整中英多语言本地化(`zh-CN` / `en`),优先跟随客户端语言。 | + +
+点击展开架构与可靠性设计 + - **三层模块化架构**: - - `funrounds-core`:纯 Rust 编写、独立于游戏引擎的核心库。负责状态机流转、回合随机池、战斗数学规则、`[defaults]` 继承模版以及严格校验的 TOML 配置解析。 - - `funrounds-plugin`:Plugify Rust 原生适配插件。在游戏主线程通过 S2SDK 与 CS2 引擎交互,处理实体句柄追踪与生命周期管理。 - - `funrounds-native`:基于 C++20 的原生伴侣模块。提供底层引擎挂钩、实体碰撞拦截、投射物 Touch 判定与 Gamedata 偏移管理。 -- **丰富的玩法修改机制**: - - **基础属性与物理参数**:支持自定义生命值(1~10000)、护甲头盔、重力倍率(`gravity`)、移速倍率(`speed`)、渲染颜色(`color`)、连跳(`bunnyhop`)以及周期性重力/移速动态波动。 - - **后坐与镜头反馈**:支持自定义开火镜头震动(`recoil_view`)、冲击衰减(`view_punch_decay`)、散布与后坐抑制(`no_spread_recoil`)、限制开镜(`no_scope`)、视野调整(`fov`)及延时隐藏准星。 - - **武器与动态配装**:支持 CS2 官方武器白名单、无限备弹/无限弹匣/单发弹药、电击枪充能间隔、投掷物自动补充、阵营配发与清理、随机抽枪及击杀升级换枪(`kill_loadout`)。 - - **特殊战斗规则**:吸血恢复(`lifesteal`)、爆头规则限制、按自身生命缩放伤害/速度/衰减、飞刀弹射判定、诱饵弹躲避球碰撞伤害(`dodgeball`)、开火自推反冲(`fr_knock` 支持地面与空中配置)。 - - **C4 特殊机制与自爆**:支持原生 C4(`native`)、鸡背 C4(`chicken`)、可携带 C4(`carry`),支持自定义安放/拆除/爆炸时间、炸弹弹跳物理、购买 C4(`fr_c4`)及引爆 C4 自爆(`fr_suicide`)。 - - **复活与服务端规则覆写**:支持回合开局复活与延时按队复活,支持单模式覆盖购买时间、金钱上限、队友伤害倍率、随机出生点等 ConVar。 -- **高可靠性与故障隔离**: - - **FFI Panic 拦截**:在 C ABI 边界全面捕获 Rust panic(`catch_unwind`),防止单次回调异常波及专用服务端进程。 - - **事务性状态恢复**:严格维护代次(Generation)与实体句柄,在回合结束或停用时仅还原由本插件修改过的属性和 ConVar,不污染服务端原有配置。 + - `funrounds-core`:纯 Rust 编写、独立于引擎的核心库。负责玩法规则、状态机流转、`[defaults]` 模板继承、数学判定及严格校验的 TOML 配置解析。 + - `funrounds-plugin`:Plugify Rust 原生适配插件。在游戏主线程响应 S2SDK 实体事件,管理实体生命周期与多语言反馈。 + - `funrounds-native`:C++20 原生伴侣模块。提供底层伤害桥接、投射物 Touch、实体碰撞拦截、小鸡互动、幽灵雷达遮蔽及 Gamedata 偏移管理。 +- **严格的安全隔离**: + - **FFI Panic 全边界捕获**:所有跨 C ABI 边界的回调均由 `catch_unwind` 包裹,防止单次回调异常波及专用服务端进程。 + - **事务性状态回滚**:严格记录代次(Generation)与实体快照,在回合结束或插件停用时仅还原受管属性与 ConVar,绝不残留脏状态。 - **能力动态隔离**:根据服务端运行环境的 SDK 钩子支持情况,自动隔离缺失底层能力的模式,其余模式不受影响正常运行。 +
-### 目录结构 +--- + +### 项目目录结构 ```text ├── bindings/ # Plugify S2SDK 接口清单 (123 项接口定义) -├── config/ # 示例配置文件 (funrounds.example.toml) +├── config/ # 示例配置文件及多语言包 +│ ├── funrounds.example.toml # 示例配置 +│ └── i18n/ # 本地化翻译文件 (zh-CN.toml, en.toml) ├── crates/ │ ├── funrounds-core/ # 独立于引擎的玩法核心、规则校验与配置解析 │ └── funrounds-plugin/ # 游戏线程 Plugify 插件运行时实现 @@ -55,26 +69,32 @@ └── rust-toolchain.toml # 固定编译器工具链版本 (Rust 1.99.1) ``` +--- + ### 安装与部署 #### 前置要求 - Counter-Strike 2 专用服务端(Windows x64 或 Linux x64) - 服务端已安装配置 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架 -- 服务端已加载并运行 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 插件(版本 `3.0.1`) +- 服务端已加载并运行 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 插件(版本 `3.0.6`) #### 部署步骤 -将构建产物复制到服务端 `game/csgo/addons/plugify/` 对应路径: +将编译产物与配置文件复制到服务端 `game/csgo/addons/plugify/` 对应路径: ```text game/csgo/addons/plugify/ ├── configs/ -│ └── funrounds.toml # 从 config/funrounds.example.toml 复制 +│ ├── funrounds.toml # 从 config/funrounds.example.toml 复制 +│ └── funrounds/ +│ └── i18n/ # 复制 config/i18n/ 下的翻译文件 +│ ├── zh-CN.toml +│ └── en.toml └── envs/ ├── funrounds/ # Rust 主插件 │ ├── bin/ - │ │ └── funrounds_plugin.dll (或 .so) # 插件动态库 + │ │ └── funrounds_plugin.dll (或 .so) # 动态库 │ └── funrounds.pplugin # 插件清单 └── funrounds_native/ # 原生 C++ 伴侣扩展 ├── bin/ @@ -84,15 +104,49 @@ game/csgo/addons/plugify/ └── funrounds-native.jsonc # Gamedata 特征与偏移文件 ``` +--- + +### 指令列表 + +#### 管理员与服务端控制台指令(Console / RCON) + +| 控制台指令 | 参数 | 说明 | +| :--- | :--- | :--- | +| `fr_status` | 无 | 查看当前回合状态、运行阶段、底层能力就绪状态及故障排查信息。 | +| `fr_list` | 无 | 列出当前配置池中所有已启用的特殊模式列表。 | +| `fr_next` | `` | 指定下一回合的模式 ID,或恢复随机抽取 (`random`)。 | +| `fr_reload` | 无 | 校验并重载配置文件与多语言文本,重载成功于下一回合生效。 | +| `fr_enable` | `<0 \| 1>` | 插件总启停开关:`1` 为启用,`0` 为停用。 | + +#### 玩家控制台与聊天指令 + +| 控制台指令 | 聊天快捷指令 | 参数 | 说明 | +| :--- | :--- | :--- | :--- | +| `fr_info` | `!info` / `!frinfo` | 无 | 在聊天栏中查看当前回合模式名称、编号与玩法说明。 | +| `fr_help` | `!help` / `!frhelp` | 无 | 查看插件帮助信息及玩家可用指令。 | +| `fr_knock` | `!knock` | `[0\|1\|2]` | 设置或切换开火自推反冲(`0` 关闭,`1` 地空全开,`2` 仅空中 [默认],无参依次切换)。 | +| `fr_c4` | `!c4` | 无 | 进攻方在模式允许时按配置价格购买额外 C4。 | +| `fr_suicide` | `!suicide` | 无 | 允许自爆时使用所持或购买的 C4 启动自爆。 | +| `fr_chicken` | `!chicken` | 无 | 按配置价格在当前位置购买一只小鸡。 | +| `fr_healthshot` | `!healthshot` | 无 | 按配置价格购买一支医疗针。 | +| `fr_nvg` | `!nvg` | 无 | 开启或关闭夜视仪。 | +| `fr_wire` | `!wire` | `` | 选择安包引线或拆包剪线颜色(`blue` / `yellow` / `red` / `green`)。 | + +--- + ### 配置说明 -配置文件采用严格 TOML 语法解析。支持 `[defaults]` 全局继承模版: +配置文件采用严格 TOML 语法解析。支持 `[defaults]` 全局继承模板为所有模式提供默认参数: ```toml # 顶层全局设置 diagnostics = false # 是否开启诊断日志(默认 false) -# 全局默认模版(模式自身字段优先) +# 多语言配置 +[i18n] +default_language = "zh-CN" # 服务端缺省语言("zh-CN" 或 "en") + +# 全局默认模板(模式内未单独设置的字段将继承此处) [defaults] gravity = 1.0 bunnyhop = false @@ -100,9 +154,9 @@ bunnyhop = false [[modes]] id = "example" # 模式唯一标识(仅允许字母、数字、'_' 或 '-') enabled = true # 是否启用该模式并加入随机池 -name = "鸟狙低重力" # 游戏中显示的模式名称 -description = "低重力狙击对抗" -weapons = ["weapon_ssg08", "weapon_glock"] +name_key = "mode.example.name" # 引用 i18n/*.toml 中的多语言文本键 +description_key = "mode.example.description" +weapons = ["weapon_famas", "weapon_p250"] # 阵营发放与清理 clear_weapons = "all" # 发放前清理武器队伍 (none / all / terrorists / counter_terrorists) @@ -110,48 +164,31 @@ give_weapons = "all" # 发放候选武器队伍 give_knife = "all" # 发放刀具队伍 # 基础属性与移动 -health = 100 # 初始生命值 (1~10000) -armor = 100 # 初始护甲值 (0~255) -gravity = 0.5 # 重力倍率 (0.0 < g <= 10.0,1.0 为正常) -speed = 1.0 # 移动速度倍率 -bunnyhop = true # 是否开启自动连跳 -self_push = true # 是否开启开火自推反冲 - -# 射击与镜头反馈 -no_spread_recoil = false # 是否消除武器后坐力与散布 -recoil_view = 2.0 # 开火镜头震动强度 -view_punch_decay = 5.0 # 镜头冲击衰减值 - -# 战斗与弹药 -ammo = "reserve" # 弹药模式 (inherit / reserve / clip / single_shot) -lifesteal = false # 是否开启造成伤害吸血 -health_damage = false # 是否根据攻击者生命缩放伤害 +health = 120 # 初始生命值 (1~10000,或区间随机 { min = 100, max = 150 }) +armor = 50 # 初始护甲值 (0~255,或区间随机 { min = 0, max = 100 }) +gravity = 1.0 # 重力倍率 (0.0 < g <= 10.0,1.0 为正常重力) +speed = 1.0 # 移速倍率 +self_push = true # 开启开火自推反冲 -# 特殊 C4 规则(可选原生 native、鸡背 chicken 或可携带 carry) -# bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, defuse_kit_time = 5.0, defuse_time = 10.0, bounce = false } +# 射击与视角控制 +ammo = "reserve" # 弹药模式 (inherit / reserve / clip / single_shot) +headshots = "normal" # 爆头规则 (normal / only / disabled) +fast_switch = true # 快速切枪开关 + +# 特殊玩法机制选开 +# lifesteal = true # 吸血恢复 +# suicide = true # 允许自爆玩法 +# third_person = { distance = 64.0, follow_eyes = true, return_strength = 2.0 } # 第三人称视角 +# bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, bounce = false } # 特殊炸弹 ``` -### 指令列表 +
+查看完整配置选项注释 -#### 管理员与服务端控制台指令(Console / RCON) +请直接查阅 [config/funrounds.example.toml](config/funrounds.example.toml) 获取完整的字段说明,涵盖小鸡生态、伤害缩放曲线、幽灵隐身、特殊 C4、购买与经济等全部选项。 +
-| 控制台指令 | 参数 | 说明 | -| :--- | :--- | :--- | -| `fr_status` | 无 | 查看当前回合状态、运行阶段、底层能力就绪状态及故障排查信息。 | -| `fr_list` | 无 | 列出当前配置池中所有已启用的特殊模式列表。 | -| `fr_next` | `` | 指定下一回合的模式 ID,或恢复随机抽取 (`random`)。 | -| `fr_reload` | 无 | 校验并重载配置文件,重载成功于下一回合生效。 | -| `fr_enable` | `<0 \| 1>` | 插件总启停开关:`1` 为启用,`0` 为停用。 | - -#### 玩家控制台与聊天指令 - -| 控制台指令 | 聊天快捷指令 | 参数 | 说明 | -| :--- | :--- | :--- | :--- | -| `fr_info` | `!frinfo` | 无 | 在聊天栏中查看当前回合模式名称、编号与玩法说明。 | -| `fr_help` | `!frhelp` | 无 | 查看插件帮助信息及玩家可用指令。 | -| `fr_knock` | `!knock` | `[0\|1\|2]` | 设置或切换开火自推反冲(`0` 关闭,`1` 地面及空中,`2` 仅空中 [默认],无参数依次切换)。 | -| `fr_c4` | `!c4` | 无 | 当模式允许普通购买时,花费 $10,000 现金购买 C4。 | -| `fr_suicide` | `!suicide` | 无 | 当模式允许自爆时,使用已有 C4 或购买后引爆自爆。 | +--- ### 源码编译 @@ -164,7 +201,7 @@ health_damage = false # 是否根据攻击者生命缩放伤害 cargo fmt --all -- --check cargo clippy --workspace --all-targets --locked -- -D warnings -# 运行自动化单元测试 (包含 119+ 完整测试用例) +# 运行全量自动化单元测试 cargo test --workspace --locked # 编译 Release 发布版本 @@ -176,7 +213,7 @@ cargo build --release --workspace --locked 需要 Python 3.10+、CMake 3.25+ 以及对应平台的 C++20 编译器(MSVC 2022+ 或 GCC 11+): ```bash -# 构建原生扩展并输出至 output 目录 +# 构建原生扩展并输出至 dist/native python scripts/build-native.py --output-dir dist/native ``` From 0d25454f8da31115e2c9d20f5b620a2aad9474f6 Mon Sep 17 00:00:00 2001 From: Mai Ooizumi Date: Sat, 31 Oct 2026 19:31:06 +0800 Subject: [PATCH 2/3] feat: Update FunRounds to 0.3 alpha test 2 Signed-off-by: Mai Ooizumi Co-authored-by: Hoshihara Rui --- Cargo.lock | 4 +- Cargo.toml | 2 +- bindings/s2sdk.pplugin | 656 ++- config/funrounds.example.toml | 250 +- config/i18n/en.toml | 81 + config/i18n/zh-CN.toml | 81 + crates/funrounds-core/src/afterburn.rs | 66 + crates/funrounds-core/src/attributes.rs | 97 + .../funrounds-core/src/bin/validate-config.rs | 90 + crates/funrounds-core/src/chicken.rs | 659 +++ crates/funrounds-core/src/combat.rs | 16 +- crates/funrounds-core/src/equipment.rs | 62 +- crates/funrounds-core/src/ghost.rs | 165 + crates/funrounds-core/src/health.rs | 226 + crates/funrounds-core/src/lib.rs | 644 ++- crates/funrounds-core/src/money.rs | 36 + crates/funrounds-core/src/players.rs | 46 + crates/funrounds-core/src/rounds.rs | 144 +- crates/funrounds-core/src/suicide.rs | 12 +- crates/funrounds-core/src/text.rs | 425 ++ crates/funrounds-core/src/third_person.rs | 55 + .../assets/legacy_textmsg_award_keys.txt | 40 + crates/funrounds-plugin/src/afterburn.rs | 280 + crates/funrounds-plugin/src/bombs.rs | 1084 +++- crates/funrounds-plugin/src/cash.rs | 257 + .../funrounds-plugin/src/chicken_adapter.rs | 180 + .../funrounds-plugin/src/chicken_entities.rs | 523 ++ crates/funrounds-plugin/src/commands.rs | 82 +- .../src/compat/hostage_rescue.rs | 213 + crates/funrounds-plugin/src/compat/mod.rs | 4 + crates/funrounds-plugin/src/damage.rs | 225 +- crates/funrounds-plugin/src/effects.rs | 615 ++- .../funrounds-plugin/src/effects/equipment.rs | 489 +- crates/funrounds-plugin/src/effects/ghost.rs | 901 ++++ crates/funrounds-plugin/src/effects/render.rs | 108 +- .../src/effects/third_person.rs | 308 ++ .../funrounds-plugin/src/effects/transmit.rs | 119 + crates/funrounds-plugin/src/effects/view.rs | 143 +- .../src/effects/weapon_rules.rs | 13 + crates/funrounds-plugin/src/fault.rs | 60 +- .../src/funrounds_native/afterburn.rs | 31 + .../src/funrounds_native/aliases.rs | 1 + .../src/funrounds_native/chickeneating.rs | 52 + .../src/funrounds_native/chickenfollow.rs | 38 + .../src/funrounds_native/damage.rs | 45 +- .../src/funrounds_native/delegates.rs | 17 + .../src/funrounds_native/entities.rs | 3 +- .../src/funrounds_native/enums.rs | 1 + .../src/funrounds_native/ghostradar.rs | 39 + .../src/funrounds_native/ghostvisibility.rs | 60 + .../src/funrounds_native/groundreverse.rs | 39 + .../src/funrounds_native/healthshot.rs | 54 + .../src/funrounds_native/mod.rs | 28 + .../src/funrounds_native/randomspawn.rs | 41 + .../src/funrounds_native/suicide.rs | 1 + .../src/funrounds_native/thirdperson.rs | 65 + crates/funrounds-plugin/src/game.rs | 117 +- crates/funrounds-plugin/src/ground_reverse.rs | 72 + crates/funrounds-plugin/src/i18n.rs | 157 + crates/funrounds-plugin/src/legacy_textmsg.rs | 143 + crates/funrounds-plugin/src/lib.rs | 1473 +++++- crates/funrounds-plugin/src/night_vision.rs | 336 ++ crates/funrounds-plugin/src/parameters.rs | 200 +- crates/funrounds-plugin/src/preferences.rs | 428 +- crates/funrounds-plugin/src/projectiles.rs | 391 +- crates/funrounds-plugin/src/random_spawn.rs | 140 + crates/funrounds-plugin/src/runtime.rs | 4672 +++++++++++++++-- crates/funrounds-plugin/src/s2sdk/aliases.rs | 1 + crates/funrounds-plugin/src/s2sdk/clients.rs | 32 + crates/funrounds-plugin/src/s2sdk/commands.rs | 1 + crates/funrounds-plugin/src/s2sdk/console.rs | 32 + crates/funrounds-plugin/src/s2sdk/cvars.rs | 17 + .../funrounds-plugin/src/s2sdk/delegates.rs | 13 + crates/funrounds-plugin/src/s2sdk/engine.rs | 48 + crates/funrounds-plugin/src/s2sdk/entities.rs | 1 + crates/funrounds-plugin/src/s2sdk/enums.rs | 1 + crates/funrounds-plugin/src/s2sdk/events.rs | 1 + .../funrounds-plugin/src/s2sdk/gameconfig.rs | 3 +- .../funrounds-plugin/src/s2sdk/gamerules.rs | 1 + .../funrounds-plugin/src/s2sdk/listeners.rs | 70 + crates/funrounds-plugin/src/s2sdk/mod.rs | 7 + crates/funrounds-plugin/src/s2sdk/models.rs | 33 + crates/funrounds-plugin/src/s2sdk/protobuf.rs | 144 + crates/funrounds-plugin/src/s2sdk/schema.rs | 17 + crates/funrounds-plugin/src/s2sdk/transmit.rs | 60 + crates/funrounds-plugin/src/suicide.rs | 437 +- crates/funrounds-plugin/src/touch.rs | 82 +- native/funrounds-native/CMakeLists.txt | 80 +- .../funrounds-native/funrounds-native.pplugin | 760 ++- .../gamedata/funrounds-native.jsonc | 73 + native/funrounds-native/src/burn.cpp | 229 + native/funrounds-native/src/burn.hpp | 13 + .../funrounds-native/src/burn_ignite_win.asm | 37 + native/funrounds-native/src/button_state.hpp | 22 + .../src/chicken_follow_policy.hpp | 12 + .../funrounds-native/src/chicken_use_abi.hpp | 38 + native/funrounds-native/src/collision.cpp | 3 + native/funrounds-native/src/damage.cpp | 521 +- native/funrounds-native/src/damage.hpp | 22 + .../src/damage_call_scope.hpp | 3 + .../src/damage_frame_stack.hpp | 3 + native/funrounds-native/src/engine.cpp | 3 + native/funrounds-native/src/engine.hpp | 3 + native/funrounds-native/src/entity_handle.hpp | 3 + .../src/ghost_passive_noise.cpp | 532 ++ .../src/ghost_passive_noise_policy.hpp | 105 + .../src/ghost_passive_sound_catalog.hpp | 204 + .../src/ghost_passive_sound_policy.hpp | 41 + native/funrounds-native/src/ghost_radar.cpp | 848 +++ native/funrounds-native/src/ghost_radar.hpp | 40 + .../src/ghost_radar_policy.hpp | 238 + .../src/ghost_radar_state.cpp | 427 ++ .../funrounds-native/src/ghost_visibility.cpp | 218 + .../funrounds-native/src/ghost_visibility.hpp | 29 + .../src/ghost_visibility_policy.hpp | 33 + .../funrounds-native/src/ground_reverse.cpp | 333 ++ .../funrounds-native/src/ground_reverse.hpp | 12 + .../src/ground_reverse_policy.hpp | 63 + native/funrounds-native/src/interactions.cpp | 833 +++ native/funrounds-native/src/interactions.hpp | 27 + native/funrounds-native/src/plugin.cpp | 58 +- native/funrounds-native/src/random_spawn.cpp | 69 + native/funrounds-native/src/suicide.cpp | 3 + native/funrounds-native/src/suicide.hpp | 3 + native/funrounds-native/src/third_person.cpp | 287 + native/funrounds-native/src/third_person.hpp | 14 + native/funrounds-native/src/touch.cpp | 100 +- native/funrounds-native/src/touch.hpp | 8 + packaging/funrounds.pplugin | 13 +- scripts/build-native.py | 17 +- scripts/ci.py | 2 + scripts/ci/Dockerfile | 2 +- scripts/tests/test_build_native.py | 15 +- scripts/tests/test_ci.py | 20 +- 134 files changed, 23988 insertions(+), 1537 deletions(-) create mode 100644 config/i18n/en.toml create mode 100644 config/i18n/zh-CN.toml create mode 100644 crates/funrounds-core/src/afterburn.rs create mode 100644 crates/funrounds-core/src/attributes.rs create mode 100644 crates/funrounds-core/src/bin/validate-config.rs create mode 100644 crates/funrounds-core/src/chicken.rs create mode 100644 crates/funrounds-core/src/ghost.rs create mode 100644 crates/funrounds-core/src/health.rs create mode 100644 crates/funrounds-core/src/money.rs create mode 100644 crates/funrounds-core/src/text.rs create mode 100644 crates/funrounds-core/src/third_person.rs create mode 100644 crates/funrounds-plugin/assets/legacy_textmsg_award_keys.txt create mode 100644 crates/funrounds-plugin/src/afterburn.rs create mode 100644 crates/funrounds-plugin/src/cash.rs create mode 100644 crates/funrounds-plugin/src/chicken_adapter.rs create mode 100644 crates/funrounds-plugin/src/chicken_entities.rs create mode 100644 crates/funrounds-plugin/src/compat/hostage_rescue.rs create mode 100644 crates/funrounds-plugin/src/compat/mod.rs create mode 100644 crates/funrounds-plugin/src/effects/ghost.rs create mode 100644 crates/funrounds-plugin/src/effects/third_person.rs create mode 100644 crates/funrounds-plugin/src/effects/transmit.rs create mode 100644 crates/funrounds-plugin/src/funrounds_native/afterburn.rs create mode 100644 crates/funrounds-plugin/src/funrounds_native/chickeneating.rs create mode 100644 crates/funrounds-plugin/src/funrounds_native/chickenfollow.rs create mode 100644 crates/funrounds-plugin/src/funrounds_native/ghostradar.rs create mode 100644 crates/funrounds-plugin/src/funrounds_native/ghostvisibility.rs create mode 100644 crates/funrounds-plugin/src/funrounds_native/groundreverse.rs create mode 100644 crates/funrounds-plugin/src/funrounds_native/healthshot.rs create mode 100644 crates/funrounds-plugin/src/funrounds_native/randomspawn.rs create mode 100644 crates/funrounds-plugin/src/funrounds_native/thirdperson.rs create mode 100644 crates/funrounds-plugin/src/ground_reverse.rs create mode 100644 crates/funrounds-plugin/src/i18n.rs create mode 100644 crates/funrounds-plugin/src/legacy_textmsg.rs create mode 100644 crates/funrounds-plugin/src/night_vision.rs create mode 100644 crates/funrounds-plugin/src/random_spawn.rs create mode 100644 crates/funrounds-plugin/src/s2sdk/listeners.rs create mode 100644 crates/funrounds-plugin/src/s2sdk/transmit.rs create mode 100644 native/funrounds-native/src/burn.cpp create mode 100644 native/funrounds-native/src/burn.hpp create mode 100644 native/funrounds-native/src/burn_ignite_win.asm create mode 100644 native/funrounds-native/src/button_state.hpp create mode 100644 native/funrounds-native/src/chicken_follow_policy.hpp create mode 100644 native/funrounds-native/src/chicken_use_abi.hpp create mode 100644 native/funrounds-native/src/ghost_passive_noise.cpp create mode 100644 native/funrounds-native/src/ghost_passive_noise_policy.hpp create mode 100644 native/funrounds-native/src/ghost_passive_sound_catalog.hpp create mode 100644 native/funrounds-native/src/ghost_passive_sound_policy.hpp create mode 100644 native/funrounds-native/src/ghost_radar.cpp create mode 100644 native/funrounds-native/src/ghost_radar.hpp create mode 100644 native/funrounds-native/src/ghost_radar_policy.hpp create mode 100644 native/funrounds-native/src/ghost_radar_state.cpp create mode 100644 native/funrounds-native/src/ghost_visibility.cpp create mode 100644 native/funrounds-native/src/ghost_visibility.hpp create mode 100644 native/funrounds-native/src/ghost_visibility_policy.hpp create mode 100644 native/funrounds-native/src/ground_reverse.cpp create mode 100644 native/funrounds-native/src/ground_reverse.hpp create mode 100644 native/funrounds-native/src/ground_reverse_policy.hpp create mode 100644 native/funrounds-native/src/interactions.cpp create mode 100644 native/funrounds-native/src/interactions.hpp create mode 100644 native/funrounds-native/src/random_spawn.cpp create mode 100644 native/funrounds-native/src/third_person.cpp create mode 100644 native/funrounds-native/src/third_person.hpp diff --git a/Cargo.lock b/Cargo.lock index 12c9a03..85a62e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -36,7 +36,7 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "funrounds-core" -version = "0.2.0-alpha.test" +version = "0.3.0-alpha.test.2" dependencies = [ "rand", "serde", @@ -45,7 +45,7 @@ dependencies = [ [[package]] name = "funrounds-plugin" -version = "0.2.0-alpha.test" +version = "0.3.0-alpha.test.2" dependencies = [ "funrounds-core", "plugify", diff --git a/Cargo.toml b/Cargo.toml index 8aa0bfb..b662030 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = ["crates/funrounds-core", "crates/funrounds-plugin"] resolver = "3" [workspace.package] -version = "0.2.0-alpha.test" +version = "0.3.0-alpha.test.2" edition = "2024" rust-version = "1.99" authors = ["Mai Ooizumi"] diff --git a/bindings/s2sdk.pplugin b/bindings/s2sdk.pplugin index 26bb632..a4d2650 100644 --- a/bindings/s2sdk.pplugin +++ b/bindings/s2sdk.pplugin @@ -1,6 +1,6 @@ { "$schema": "https://raw.githubusercontent.com/untrustedmodders/plugify/refs/heads/main/schemas/plugin.schema.json", - "version": "3.0.2", + "version": "3.0.6", "name": "s2sdk", "description": "Provides functionality for other plugins from Source 2 engine", "author": "untrustedmodders", @@ -11,11 +11,11 @@ "language": "cpp", "dependencies": [ { - "constraints": ">=2.5.2", + "constraints": ">=2.5.7", "name": "polyhook" }, { - "constraints": ">=2.1.0", + "constraints": ">=2.1.2", "name": "configs" }, { @@ -392,6 +392,29 @@ "type": "void" } }, + { + "name": "PrintToConsole", + "group": "Console", + "description": "Sends a message to a client's console.", + "funcName": "PrintToConsole", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The index of the player's slot to whom the message will be sent." + }, + { + "name": "message", + "type": "string", + "ref": false, + "description": "The message to be sent to the client's console." + } + ], + "retType": { + "type": "void" + } + }, { "name": "PrintToChatAll", "group": "Console", @@ -461,6 +484,23 @@ "description": "The maximum client count, or -1 if global variables are not initialized." } }, + { + "name": "Precache", + "group": "Engine", + "description": "Precaches a given file.", + "funcName": "Precache", + "paramTypes": [ + { + "name": "resource", + "type": "string", + "ref": false, + "description": "The name of the resource to be precached." + } + ], + "retType": { + "type": "void" + } + }, { "name": "EntPointerToEntHandle", "group": "Entities", @@ -879,6 +919,35 @@ "description": "The output value in string format." } }, + { + "name": "SendConVarValue", + "group": "Cvars", + "description": "Replicates a console variable value to a specific client. This does not change the actual console variable value.", + "funcName": "SendConVarValue", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The index of the client to replicate the value to." + }, + { + "name": "conVarHandle", + "type": "uint64", + "ref": false, + "description": "The handle to the console variable data." + }, + { + "name": "value", + "type": "string", + "ref": false, + "description": "The value to send to the client." + } + ], + "retType": { + "type": "void" + } + }, { "name": "SetConVarValue", "group": "Cvars", @@ -1414,6 +1483,213 @@ "description": "True if the field was successfully set, false otherwise." } }, + { + "name": "HookUserMessage", + "group": "Protobuf", + "description": "Hooks a user message with a callback.", + "funcName": "HookUserMessage", + "paramTypes": [ + { + "name": "messageId", + "type": "int16", + "ref": false, + "description": "The ID of the message to hook." + }, + { + "name": "callback", + "type": "function", + "ref": false, + "description": "The callback function to invoke when the message is received.", + "prototype": "UserMessageCallback" + }, + { + "name": "mode", + "type": "uint8", + "ref": false, + "description": "Whether to hook the message in the post mode (after processing) or pre mode (before processing).", + "enum": "HookMode" + } + ], + "retType": { + "type": "bool", + "description": "True if the hook was successfully added, false otherwise." + } + }, + { + "name": "UnhookUserMessage", + "group": "Protobuf", + "description": "Unhooks a previously hooked user message.", + "funcName": "UnhookUserMessage", + "paramTypes": [ + { + "name": "messageId", + "type": "int16", + "ref": false, + "description": "The ID of the message to unhook." + }, + { + "name": "callback", + "type": "function", + "ref": false, + "description": "The callback function to remove.", + "prototype": "UserMessageCallback" + }, + { + "name": "mode", + "type": "uint8", + "ref": false, + "description": "Whether the hook was in post mode (after processing) or pre mode (before processing).", + "enum": "HookMode" + } + ], + "retType": { + "type": "bool", + "description": "True if the hook was successfully removed, false otherwise." + } + }, + { + "name": "UserMessageCreateFromName", + "group": "Protobuf", + "description": "Creates a UserMessage from a message name.", + "funcName": "UserMessageCreateFromName", + "paramTypes": [ + { + "name": "messageName", + "type": "string", + "ref": false, + "description": "The name of the message." + } + ], + "retType": { + "type": "ptr64", + "description": "A pointer to the newly created UserMessage." + } + }, + { + "name": "UserMessageGetMessageName", + "group": "Protobuf", + "description": "Gets the name of the message.", + "funcName": "UserMessageGetMessageName", + "paramTypes": [ + { + "name": "userMessage", + "type": "ptr64", + "ref": false, + "description": "The UserMessage instance." + } + ], + "retType": { + "type": "string", + "description": "The name of the message as a string." + } + }, + { + "name": "UserMessageAddAllPlayers", + "group": "Protobuf", + "description": "Adds all connected players as recipients to the UserMessage.", + "funcName": "UserMessageAddAllPlayers", + "paramTypes": [ + { + "name": "userMessage", + "type": "ptr64", + "ref": false, + "description": "The UserMessage instance." + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "UserMessageGetRepeatedFieldCount", + "group": "Protobuf", + "description": "Gets the count of repeated fields in a field of the UserMessage.", + "funcName": "UserMessageGetRepeatedFieldCount", + "paramTypes": [ + { + "name": "userMessage", + "type": "ptr64", + "ref": false, + "description": "The UserMessage instance." + }, + { + "name": "fieldName", + "type": "string", + "ref": false, + "description": "The name of the field." + } + ], + "retType": { + "type": "int32", + "description": "The count of repeated fields, or -1 if the field is not repeated or does not exist." + } + }, + { + "name": "PbGetRepeatedString", + "group": "Protobuf", + "description": "Gets a repeated string value from a field in the UserMessage.", + "funcName": "PbGetRepeatedString", + "paramTypes": [ + { + "name": "userMessage", + "type": "ptr64", + "ref": false, + "description": "The UserMessage instance." + }, + { + "name": "fieldName", + "type": "string", + "ref": false, + "description": "The name of the field." + }, + { + "name": "index", + "type": "int32", + "ref": false, + "description": "The index of the repeated field." + }, + { + "name": "out", + "type": "string", + "ref": true, + "description": "The output string." + } + ], + "retType": { + "type": "bool", + "description": "True if the field was successfully retrieved, false otherwise." + } + }, + { + "name": "PbAddString", + "group": "Protobuf", + "description": "Adds a string value to a repeated field in the UserMessage.", + "funcName": "PbAddString", + "paramTypes": [ + { + "name": "userMessage", + "type": "ptr64", + "ref": false, + "description": "The UserMessage instance." + }, + { + "name": "fieldName", + "type": "string", + "ref": false, + "description": "The name of the field." + }, + { + "name": "value", + "type": "string", + "ref": false, + "description": "The value to add." + } + ], + "retType": { + "type": "bool", + "description": "True if the value was successfully added, false otherwise." + } + }, { "name": "RespawnClient", "group": "Clients", @@ -1431,6 +1707,23 @@ "type": "void" } }, + { + "name": "ForceRespawnClient", + "group": "Clients", + "description": "Forces a full engine respawn for a player, including when the current pawn is alive. Supported in CS2.", + "funcName": "ForceRespawnClient", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The index of the player's slot to respawn." + } + ], + "retType": { + "type": "void" + } + }, { "name": "GetGameTime", "group": "Engine", @@ -1442,6 +1735,70 @@ "description": "The current game time." } }, + { + "name": "EmitSoundToClient", + "group": "Engine", + "description": "Emits a sound to one or more clients.", + "funcName": "EmitSoundToClient", + "paramTypes": [ + { + "name": "entityHandle", + "type": "int32", + "ref": false, + "description": "The handle of the entity that emits the sound." + }, + { + "name": "playersSlot", + "type": "int32[]", + "ref": false, + "description": "Player slot indices that will hear the sound." + }, + { + "name": "sound", + "type": "string", + "ref": false, + "description": "The name of the sound to emit." + }, + { + "name": "volume", + "type": "float", + "ref": false, + "description": "The volume of the sound." + }, + { + "name": "pitch", + "type": "float", + "ref": false, + "description": "The pitch of the sound." + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "StopSound", + "group": "Engine", + "description": "Stops a sound from a specified entity.", + "funcName": "StopSound", + "paramTypes": [ + { + "name": "entityHandle", + "type": "int32", + "ref": false, + "description": "The handle of the entity that will stop the sound." + }, + { + "name": "sound", + "type": "string", + "ref": false, + "description": "The name of the sound to stop." + } + ], + "retType": { + "type": "void" + } + }, { "name": "TerminateRound", "group": "Gamerules", @@ -1707,6 +2064,35 @@ "type": "void" } }, + { + "name": "PrintCentreHtml", + "group": "Console", + "description": "Prints a html message to a specific client in the center of the screen.", + "funcName": "PrintCentreHtml", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The index of the player's slot to whom the message will be sent." + }, + { + "name": "message", + "type": "string", + "ref": false, + "description": "The HTML-formatted message to be printed." + }, + { + "name": "duration", + "type": "int32", + "ref": false, + "description": "The duration of the message in seconds." + } + ], + "retType": { + "type": "void" + } + }, { "name": "IsFakeClient", "group": "Clients", @@ -2471,6 +2857,47 @@ "description": "A vector representing the origin of the attachment." } }, + { + "name": "GetEntityModelScale", + "group": "Models", + "description": "Retrieves the model scale of an entity.", + "funcName": "GetEntityModelScale", + "paramTypes": [ + { + "name": "entityHandle", + "type": "int32", + "ref": false, + "description": "The handle of the entity." + } + ], + "retType": { + "type": "float", + "description": "The model scale factor." + } + }, + { + "name": "SetEntityModelScale", + "group": "Models", + "description": "Sets the model scale of an entity.", + "funcName": "SetEntityModelScale", + "paramTypes": [ + { + "name": "entityHandle", + "type": "int32", + "ref": false, + "description": "The handle of the entity." + }, + { + "name": "scale", + "type": "float", + "ref": false, + "description": "The new scale factor." + } + ], + "retType": { + "type": "void" + } + }, { "name": "ScriptLookupAttachment", "group": "Models", @@ -2615,6 +3042,42 @@ "type": "void" } }, + { + "name": "OnBuildGameSessionManifest_Register", + "group": "Listeners", + "description": "Register callback to event.", + "funcName": "OnBuildGameSessionManifest_Register", + "paramTypes": [ + { + "name": "callback", + "type": "function", + "ref": false, + "description": "Function callback.", + "prototype": "OnBuildGameSessionManifestCallback" + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "OnBuildGameSessionManifest_Unregister", + "group": "Listeners", + "description": "Unregister callback to event.", + "funcName": "OnBuildGameSessionManifest_Unregister", + "paramTypes": [ + { + "name": "callback", + "type": "function", + "ref": false, + "description": "Function callback.", + "prototype": "OnBuildGameSessionManifestCallback" + } + ], + "retType": { + "type": "void" + } + }, { "name": "IsClientAuthorized", "group": "Clients", @@ -2651,6 +3114,24 @@ "description": "uint64_t The client's SteamID64." } }, + { + "name": "GetClientLanguageCode", + "group": "Clients", + "description": "Retrieves a client's language as an ISO code. Unlike GetClientLanguage, which returns the raw cl_language value (\"english\", \"schinese\"), this returns the code translation files are keyed by (\"en\", \"zh-CN\"). Empty until the client answers the cl_language query, and always empty for bots. Reliably available starting from OnClientAuthenticated and OnClientPutInServer.", + "funcName": "GetClientLanguageCode", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The index of the player's slot." + } + ], + "retType": { + "type": "string", + "description": "The client's ISO language code." + } + }, { "name": "GetEntityAngRotation", "group": "Entities", @@ -2706,7 +3187,7 @@ ], "retType": { "type": "uint32", - "description": "A id to the loaded game configuration object, or -1 if loading fails.", + "description": "A id to the loaded game configuration object, or 0 if loading fails.", "alias": { "name": "ConfigId" } @@ -2884,6 +3365,135 @@ "type": "vec3", "description": "Eye angles as a vector (pitch, yaw, roll)" } + }, + { + "name": "GetHiddenTransmitEntities", + "group": "Transmit", + "description": "Gets all hidden entity handles for a player.", + "funcName": "GetHiddenTransmitEntities", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The player slot to query." + } + ], + "retType": { + "type": "int32[]", + "description": "Array of hidden entity handles." + } + }, + { + "name": "HideTransmitEntity", + "group": "Transmit", + "description": "Hides a single entity from a player's transmit list.", + "funcName": "HideTransmitEntity", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The player slot to hide the entity from." + }, + { + "name": "entityHandle", + "type": "int32", + "ref": false, + "description": "Entity handle to hide." + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "ShowTransmitEntity", + "group": "Transmit", + "description": "Shows a previously hidden entity to a player.", + "funcName": "ShowTransmitEntity", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The player slot to show the entity to." + }, + { + "name": "entityHandle", + "type": "int32", + "ref": false, + "description": "Entity handle to show." + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "NetworkStateChanged", + "group": "Schema", + "description": "Updates the networked state of a schema field for a given entity handle.", + "funcName": "NetworkStateChanged", + "paramTypes": [ + { + "name": "entityHandle", + "type": "int32", + "ref": false, + "description": "The handle of the entity from which the value is to be retrieved." + }, + { + "name": "className", + "type": "string", + "ref": false, + "description": "The name of the class that contains the member." + }, + { + "name": "memberName", + "type": "string", + "ref": false, + "description": "The name of the member to be set." + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "OnMapEnd_Register", + "group": "Listeners", + "description": "Register callback to event.", + "funcName": "OnMapEnd_Register", + "paramTypes": [ + { + "name": "callback", + "type": "function", + "ref": false, + "description": "Function callback.", + "prototype": "OnMapEndCallback" + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "OnMapEnd_Unregister", + "group": "Listeners", + "description": "Unregister callback to event.", + "funcName": "OnMapEnd_Unregister", + "paramTypes": [ + { + "name": "callback", + "type": "function", + "ref": false, + "description": "Function callback.", + "prototype": "OnMapEndCallback" + } + ], + "retType": { + "type": "void" + } } ], "classes": [], @@ -2964,6 +3574,44 @@ "type": "void", "description": "" } + }, + { + "name": "OnBuildGameSessionManifestCallback", + "funcName": "OnBuildGameSessionManifestCallback", + "description": "Called before server activation to build game session manifest.", + "paramTypes": [], + "retType": { + "type": "void", + "description": "" + } + }, + { + "name": "UserMessageCallback", + "funcName": "UserMessageCallback", + "description": "Callback function for user messages.", + "paramTypes": [ + { + "name": "userMessage", + "type": "ptr64", + "ref": false, + "description": "The user message." + } + ], + "retType": { + "type": "int32", + "description": "Indicates the result of the action execution.", + "enum": "ResultType" + } + }, + { + "name": "OnMapEndCallback", + "funcName": "OnMapEndCallback", + "description": "Called on every map end.", + "paramTypes": [], + "retType": { + "type": "void", + "description": "" + } } ], "enums": [ diff --git a/config/funrounds.example.toml b/config/funrounds.example.toml index 4d59d1d..57da401 100644 --- a/config/funrounds.example.toml +++ b/config/funrounds.example.toml @@ -1,163 +1,227 @@ -# 通用示例:只启用一个基础模式,不预设额外玩法。 -# 未填写的字段使用 [defaults] 或内置默认值;服务器设置型字段标注为“省略时不覆盖”。 -# TOML 会拒绝未知字段;配置至少需要一个启用的模式。 +# 通用示例配置:仅启用一个基础演示模式,其余拓展玩法默认注释或关闭。 +# 未填写的字段继承自 [defaults] 或内置默认值;标注“省略时不覆盖”的字段不修改服务端原生设置。 +# 配置采用严格模式解析(拒绝未知字段);必须至少保留一个启用的模式。 -# diagnostics:是否记录诊断日志,布尔值,默认 false。 +# diagnostics:是否记录诊断日志(默认 false) diagnostics = false -# [defaults] 可为所有模式设置逐字段默认值,模式自身的字段优先;仅接受玩法字段。 -# id、enabled、name、description 不能放入 [defaults]。 -# 对 color、self_damage、taser_charge、friction、recoil_view、reflect_damage、view_punch_decay、 -# fov、hide_crosshair_after、c4_count、bomb、respawn 等可选继承项,false 可清除继承值。 -# self_damage、weapon_damage、bomb、respawn 子项可逐字段继承;bomb 更换 kind 时使用该类型的默认时间。 -# 示例(保持注释即不生效): +# hostage_rescue_compat:人质救援触发区兼容开关(默认 false) +# hostage_rescue_compat = true + +# prices:指令购买价格设置(现金 0~4294967295;默认 C4=10000、医疗针=4000、小鸡=1) +# [prices] +# c4_cash = 10000 +# healthshot_cash = 4000 +# chicken_cash = 1 + +# warmup:可选热身设置(未配置时不开启插件热身;支持模式的大多数玩法字段,ID 与名称自动固定) +# [warmup] +# enabled = false +# health = 100 + +# healthshot:接管医疗针治疗机制(省略时保留游戏原生回血逻辑) +# heal_base_fraction:基于基础生命的回血比例;cap_base_multiple:回血上限倍数(正整数) +# [healthshot] +# heal_base_fraction = 0.5 +# cap_base_multiple = 3 + +# chicken:普通小鸡生态设置(不影响特殊炸弹中的鸡) +# spawn:每位玩家目标鸡数量(目标数 = max(玩家数 * per_player, minimum)) +# [chicken.spawn] +# per_player = 1 +# minimum = 0 +# eating:吃鸡机制;digestion_seconds:消化时间(秒);risk_offset/risk_per_undigested:未消化时的爆炸风险 +# [chicken.eating] +# enabled = false +# digestion_seconds = 10.0 +# risk_offset = 0 +# risk_per_undigested = 1 +# eating.heal:吃鸡回血设置(basis: "base" 基础生命 / "current" 当前生命;percent: 回血比例区间;minimum_health: 保底回血) +# [chicken.eating.heal] +# basis = "base" +# percent = { min = 0.1, max = 0.2 } +# minimum_health = 1 +# eating.damage:吃鸡伤害设置(kind: "fixed" 固定数值 / "percent" 百分比) +# [chicken.eating.damage] +# kind = "fixed" +# amount = 1 +# kill_blast / risk_blast:击杀及吃鸡风险爆炸(damage: 伤害,radius: 范围半径) +# [chicken.kill_blast] +# damage = 0.0 +# radius = 0.0 +# [chicken.risk_blast] +# damage = 0.0 +# radius = 0.0 +# damage_chain:允许连锁触发伤害的类型(火焰 / 普通爆炸 / 鸡爆炸,默认均 false) +# [chicken.damage_chain] +# allow_fire = false +# allow_explosion = false +# allow_chicken_explosion = false + +# i18n:多语言本地化配置(语言文件位于 i18n/*.toml) +# default_language:服务端缺省语言("zh-CN" 或 "en"),优先匹配客户端语言 +[i18n] +default_language = "zh-CN" + +# [defaults]:全局默认模板(仅接受玩法字段;模式内单独设置优先) +# 可用 false 显式重置可选继承项(如 color, bomb, respawn 等) +# 示例: # [defaults] # gravity = 1.0 [[modes]] -# id:必填、非空且唯一;仅 ASCII 字母、数字、下划线和连字符。 +# id:模式唯一标识(必填,仅限 ASCII 字母、数字、下划线及连字符) id = "example" -# enabled:必填布尔值;true 时该模式进入可选池。 +# enabled:是否加入随机池(必填) enabled = true -# name、description:必填非空单行文本,分别用于模式名称和说明。 -name = "通用示例" -description = "演示基础配装与玩家属性" +# name_key / description_key:引用 i18n/*.toml 中的多语言文本键 +# (亦可直接使用 name = "通用示例" 和 description = "演示基础配装与玩家属性" 单行文本) +name_key = "mode.example.name" +description_key = "mode.example.description" -# weapons:受支持的 CS2 装备候选数组,按主武器、副武器和额外装备分类抽取;不接受 weapon_knife,刀具用 give_knife 设置。 +# weapons:受支持的 CS2 装备候选列表(按主武器、副武器和额外装备抽取;不含刀具,刀具由 give_knife 配置) weapons = ["weapon_famas", "weapon_p250"] -# health:初始生命,整数 1~10000,默认 100。 +# health:初始生命(整数 1~10000,或随机范围 { min = 100, max = 150 },默认 100) health = 120 -# armor:初始护甲,整数 0~255,默认 0。 +# armor:初始护甲(整数 0~255,或随机范围 { min = 0, max = 100 },默认 0) armor = 50 -# gravity:重力倍率,有限数值且 0 < value <= 10,默认 1.0(正常重力)。 +# gravity:重力倍率((0, 10],1.0 为正常重力,<1.0 降低重力) gravity = 1.0 -# clear_weapons:发放候选前清理武器的队伍;none / all / terrorists / counter_terrorists,默认 none。 +# clear_weapons:发放候选前清理武器的队伍(none / all / terrorists / counter_terrorists,默认 none) clear_weapons = "all" -# give_weapons:发放 weapons 候选的队伍;取值同 clear_weapons,默认 none。 +# give_weapons:发放 weapons 候选的队伍(取值同 clear_weapons,默认 none) give_weapons = "all" -# 以下可选玩法默认关闭,除单独说明外布尔值使用 true / false。 -# speed:玩家移动速度倍率,有限数值且 0 < value <= 10,默认 1.0。 +# speed:玩家移动速度倍率((0, 10],默认 1.0) # speed = 1.0 -# helmet:是否发放头盔;未设置时 armor > 0 则默认 true。 +# helmet:是否配备头盔(true / false / "random",省略时根据最终护甲自动决定) # helmet = true -# give_knife:发放刀具的队伍;none / all / terrorists / counter_terrorists,默认 none。 +# give_knife:配发刀具的队伍(none / all / terrorists / counter_terrorists,默认 none) # give_knife = "all" -# color:玩家渲染颜色,三个 0~255 的 RGB 整数组成的数组;false 清除继承值。 +# color:玩家模型 RGB 着色([R, G, B],各 0~255;false 可清除继承值) # color = [255, 255, 255] -# headshots:爆头规则;normal 使用普通规则,only 仅爆头造成伤害,disabled 禁止爆头伤害;默认 normal。 +# headshots:爆头规则("normal" 正常 / "only" 仅爆头有效 / "disabled" 禁用爆头) # headshots = "normal" -# ammo:弹药规则;inherit 保留服务端行为,reserve 无限备弹,clip 无限弹匣,single_shot 每个弹匣只装一发;默认 inherit。 -# clip 需要 weapons 包含 weapon_taser。 +# ammo:弹药规则("inherit" 原生 / "reserve" 无限备弹 / "clip" 无限弹匣 / "single_shot" 单发装填) # ammo = "inherit" -# self_damage:false 关闭/清除;miss_penalty 对未命中应用自伤规则;native 使用游戏自伤设置。 -# native 需要有限非负 amount;miss_penalty 不接受 amount。可写为: +# self_damage:开火自伤设置(kind = "miss_penalty" 未命中扣血 / kind = "native", amount = 0.1 每次自扣伤害) # self_damage = { kind = "miss_penalty" } -# self_damage = { kind = "native", amount = 0.1 } -# weapon_damage:电击枪与刀的伤害倍率,字段可分别设置,均为有限非负数,默认均为 1.0。 +# weapon_damage:特定武器伤害倍率(电击枪与刀具可分别设置,默认 1.0) # weapon_damage = { taser = 1.0, knife = 1.0 } -# taser_charge:电击枪充能间隔秒数,有限非负数;需要 weapon_taser 候选,false 清除继承值。 +# taser_charge:电击枪充能冷却时间(秒,需 weapons 包含 weapon_taser) # taser_charge = 12.0 -# bunnyhop:启用自动连跳及相关移动设置;省略时不覆盖服务端设置。 +# bunnyhop:开启自动连跳及移动参数优化(省略时不覆盖服务端设置) # bunnyhop = true -# friction:地面摩擦参数,有限非负数;省略时不覆盖服务端设置,false 清除继承值。 +# friction:地面摩擦力参数(有限非负数,省略时不覆盖服务端设置) # friction = 2.0 -# no_spread:是否关闭武器散布;省略时不覆盖服务端设置。 +# no_spread:移除武器散布(省略时不覆盖服务端设置) # no_spread = true -# no_recoil:是否抑制枪械后坐力,默认 false。 +# no_recoil:抑制枪械后坐力(默认 false) # no_recoil = true -# recoil_view:开火时添加的镜头冲击强度,有限非负数;省略时不覆盖,false 清除继承值。 +# recoil_view:开枪镜头震动冲击强度(有限非负数,省略时不覆盖) # recoil_view = 1.0 -# fast_switch:是否启用快速切换武器,默认 false。 +# fast_switch:快速切枪开关(默认 false) # fast_switch = true -# replenish:投掷后补充的手雷类型数组;可选 he / flash / smoke / decoy / molotov / incendiary,默认空数组。 -# 每项都要求 weapons 中包含对应的手雷候选。 +# replenish:投掷后自动补充的手雷类型列表(可选 he / flash / smoke / decoy / molotov / incendiary) # replenish = ["he"] -# random_loadout:是否从 weapons 候选抽取随机配装,默认 false;候选需非空。 +# random_loadout:从候选池独立随机抽取配装(与 kill_loadout 互斥) # random_loadout = true -# suicide:是否启用玩家自爆玩法,默认 false;购买 C4 另由 c4_buy 控制。 +# suicide:是否启用玩家自爆玩法(默认 false;购买 C4 另由 c4_buy 控制) # suicide = true -# random_damage:是否随机调整战斗伤害,默认 false。 +# random_damage:是否开启浮动随机战斗伤害(默认 false) # random_damage = true -# kill_loadout:击杀后是否更换为随机候选武器,默认 false;候选需非空且包含 weapon_glock。 -# random_loadout 与 kill_loadout 不能同时启用。 +# kill_loadout:击杀敌人后自动升级换枪(kill_loadout_start 可设 "glock" 或 "random") # kill_loadout = true -# lifesteal:是否按造成的伤害恢复生命和护甲,默认 false。 +# kill_loadout_start = "random" +# lifesteal:击中敌人吸血恢复生命与护甲(默认 false) # lifesteal = true -# reflect_damage:反射给攻击者的伤害倍率,有限非负数;false 清除继承值。 +# reflect_damage:反弹受到的伤害给攻击者(伤害倍率,有限非负数) # reflect_damage = 0.1 -# energy_shield:是否将护甲用作可吸收攻击并逐步恢复的能量护盾,默认 false。 +# energy_shield:将护甲转为随时间充能的吸收能量护盾(默认 false) # energy_shield = true -# combat_protection:出生时及真人玩家击杀后是否获得各 0.5 秒的伤害保护,默认 false。 +# combat_protection:同时开启出生保护与击杀保护(持续 0.5 秒;可分设 spawn_protection / kill_protection) # combat_protection = true -# translucent:是否启用半透明外观,默认 false。 +# translucent:是否启用半透明外观(默认 false) # translucent = true -# delayed_damage:是否延后结算玩家受到的伤害,默认 false。 +# delayed_damage:是否延后结算玩家受到的伤害(默认 false) # delayed_damage = true -# win_condition:回合胜负规则;native 使用游戏默认规则,team_deathmatch 按团队击杀计分;默认 native。 -# team_deathmatch 不能与 teammates_as_enemies = true 同时使用。 +# win_condition:回合胜负规则("native" 游戏默认 / "team_deathmatch" 团队死斗按杀敌计分) # win_condition = "native" -# bomb:特殊炸弹设置子表;省略或 false 时不启用。kind 可选 native(原生 C4)、chicken(鸡携带)或 carry(可拾取携带),默认 native。 -# 各时间是有限非负秒数,默认安放 3、爆炸 45、有拆弹器拆除 5、无拆弹器拆除 10;bounce 默认 false。 -# 可用内联表设置,避免后续模式字段进入子表: +# bomb:特殊炸弹设置子表(kind: "native" 原生 / "chicken" 鸡背 / "carry" 便携携带;各时间单位为秒) +# 可用内联表设置: # bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, defuse_kit_time = 5.0, defuse_time = 10.0, bounce = false } -# dodgeball:诱饵弹命中时启用躲避球效果,默认 false;需要 weapon_decoy 候选。 +# dodgeball:诱饵弹命中触发躲避球直接伤害(需 weapons 包含 weapon_decoy) # dodgeball = true -# throwing_knives:是否启用投掷刀具玩法,默认 false;give_knife 必须指定接收队伍。 +# throwing_knives:右键投掷飞刀及弹射判定(需配发刀具) # throwing_knives = true -# view_punch_decay:镜头冲击衰减值,有限非负数;省略时不覆盖服务端设置,false 清除继承值。 +# view_punch_decay:开枪镜头震动衰减参数(有限非负数,省略时不覆盖服务端设置) # view_punch_decay = 5.0 -# no_scope:是否限制瞄准镜使用,默认 false。 +# no_scope:是否禁用枪械瞄准镜开镜(默认 false) # no_scope = true -# fov:视野角度,整数 1~179;false 清除继承值。 +# fov:设定玩家视野角度(整数 1~179) # fov = 90 -# hide_crosshair_after:隐藏准星的延迟秒数,有限非负数;false 清除继承值。 +# hide_hud:隐藏指定 HUD 元素列表(可选 "radar", "crosshair") +# hide_hud = ["radar", "crosshair"] +# hide_crosshair_after:延迟隐藏准星时间(秒,需搭配 hide_hud 中的 crosshair 使用) # hide_crosshair_after = 1.0 -# health_damage:是否根据攻击者当前生命调整造成的伤害,默认 false。 +# health_damage:输出伤害根据自身当前生命动态缩放(默认 false) # health_damage = true -# health_speed:是否根据玩家当前生命调整移动速度,默认 false。 +# health_speed:移动速度根据当前生命动态缩放(默认 false) # health_speed = true -# health_decay:是否逐步衰减高于模式初始生命的部分,默认 false。 +# health_decay:高于初始生命的部分随时间逐步衰减(默认 false) # health_decay = true -# self_push:开火时是否产生自身反冲推力,默认 false。 +# self_push:开火产生自身反冲推力(可通过指令 fr_knock 切换模式) # self_push = true -# periodic_speed:是否定期改变移动速度,默认 false。 +# periodic_speed:移速周期性波浪起伏变化(默认 false) # periodic_speed = true -# periodic_gravity:是否定期改变重力,默认 false。 +# periodic_gravity:重力周期性高低起伏变化(默认 false) # periodic_gravity = true -# c4_count:T 队普通 C4 数量上限,整数 0~255;至多给可用的 T 队玩家每人分配 1 个。 -# 设为 0 会移除普通 C4 且不再分配;false 清除继承值。 +# c4_count:进攻方(T)普通 C4 数量上限(整数 0~255;设为 0 完全禁用普通 C4) # c4_count = 1 -# c4_buy:是否允许玩家使用 fr_c4 / !c4 购买 C4,默认 false。 +# c4_buy:是否允许玩家使用指令 fr_c4 / !c4 购买 C4(默认 false) # c4_buy = true -# round_respawn:是否在新回合开始时复活玩家,默认 false。 +# round_respawn:回合开局复活规则(false: 不干预 / true: 仅复活已阵亡者 / "all": 全体重新出生) # round_respawn = true -# respawn:按队伍延迟复活的子表;team 必填,可取 all / terrorists / counter_terrorists(不能为 none)。 -# delay_seconds 为有限非负秒数,默认 3.0。false 可清除继承子表。 -# 使用内联表后,后续字段仍属于当前模式: +# respawn:队伍延时复活设置(team: all / terrorists / counter_terrorists;delay_seconds: 延迟秒数) # respawn = { team = "all", delay_seconds = 3.0 } -# buy_time:购买时长,有限非负秒数;省略时不覆盖服务端设置。 -# buy_time = 30.0 -# buy_limit:玩家现金上限,整数 0~4294967295;省略时不覆盖服务端设置。 -# buy_limit = 16000 -# friendly_fire_scale:队友伤害倍率,有限数值 0~1;0 关闭队友伤害,省略时不覆盖服务端设置。 -# friendly_fire_scale = 0.0 -# teammates_as_enemies:是否将队友视为敌人;省略时不覆盖服务端设置。 -# teammates_as_enemies = false -# random_spawn:启用随机出生点的队伍;none / all / terrorists / counter_terrorists,省略时不覆盖服务端设置。 -# random_spawn = "all" -# drop_weapons:玩家死亡时是否掉落武器;省略时不覆盖服务端设置。 -# drop_weapons = true -# drop_grenades:玩家死亡时是否掉落手雷;省略时不覆盖服务端设置。 -# drop_grenades = true -# fall_damage_scale:坠落伤害倍率,有限非负数;省略时不覆盖服务端设置。 -# fall_damage_scale = 1.0 +# 服务端环境与规则参数(省略时不覆盖服务端原生设置): +# buy_time = 30.0 # 购买时间(秒) +# buy_limit = 16000 # 现金上限 +# friendly_fire_scale = 0.0 # 队友伤害倍率(0.0 为关闭友伤) +# teammates_as_enemies = false # 队友判定为敌人 +# random_spawn = "all" # 启用随机出生点的队伍(none / all / terrorists / counter_terrorists) +# drop_weapons = true # 阵亡时掉落武器 +# drop_grenades = true # 阵亡时掉落手雷 +# fall_damage_scale = 1.0 # 坠落伤害倍率 +# time_scale = 1.0 # 游戏全局时间流速倍率 +# ground_acceleration = 5.0 # 地面加速度 +# ground_reverse = 5.0 # 地面输入反向加速度(倒车行走) +# round_money_floor = 1000 # 每回合保底现金 +# money_income = { interval = 10.0, amount = 100 } # 定期发放被动收入 +# buy_access = "all" # 允许购买物品的队伍 +# buy_anywhere = "all" # 允许在地图任意位置购买的队伍 +# shoot_dropped_grenades = true # 允许射击引爆掉落的手雷 +# hide_player_identification = true# 隐藏玩家瞄准识别信息 + +# third_person:第三人称越肩视角 +# third_person = { distance = 64.0, follow_eyes = true, clip_camera_offset = true, return_strength = 2.0 } +# ghost:幽灵隐身机制(根据静步/蹲下/移动调整透明度;可设脚步声与心跳距离) +# ghost = { team = "terrorists", crouch_alpha = 0, slow_walk_alpha = 20, normal_alpha = 120 } +# afterburn:命中后使目标持续燃烧灼烧 +# afterburn = { duration_seconds = 2.0, damage_fraction = 0.01, minimum_damage = 1.0 } +# ordinary_chickens:是否在本模式中生成普通小鸡生态(默认 true) +# chicken_eating:是否允许在本模式中吃鸡(省略时沿用全局设置,false 显式禁用) +# ordinary_chickens = true +# chicken_eating = false + +# health_curve:自定义生命缩放曲线(覆盖内置 health_damage / health_speed 曲线) +# health_decay_settings:自定义额外生命衰减速率与保底百分比 diff --git a/config/i18n/en.toml b/config/i18n/en.toml new file mode 100644 index 0000000..3439122 --- /dev/null +++ b/config/i18n/en.toml @@ -0,0 +1,81 @@ +[messages] +"c4.owned" = "[FunRounds] You already have a C4." +"c4.owned_suicide" = "[FunRounds] You already have a C4; inspect it (F) to start suicide." +"c4.pending" = "C4 transaction in progress." +"c4.purchased" = "[FunRounds] C4 purchased." +"c4.purchased_inspect" = "[FunRounds] C4 purchased; inspect it (F) to start suicide." +"c4.purchased_start" = "[FunRounds] C4 purchased; suicide started." +"c4.request" = "[FunRounds] Buying C4 for {price} cash." +"c4.t_required" = "Only Ts can buy C4." +"c4.unavailable" = "C4 purchase or suicide is unavailable now." +"chicken.pending" = "Chicken transaction in progress." +"chicken.position_invalid" = "Cannot spawn a chicken at your current position." +"chicken.purchased" = "[FunRounds] Chicken purchased." +"chicken.request" = "[FunRounds] Buying a chicken for {price} cash." +"chicken.team_required" = "Join a playing team to buy a chicken." +"chicken.unavailable" = "Chicken purchases are unavailable." +"command.enabled" = "[FunRounds] enabled={enabled}; takes effect next round" +"command.next" = "[FunRounds] Next mode: {mode}" +"command.no_config" = "[FunRounds] No valid configuration found." +"command.reload" = "[FunRounds] Configuration and texts queued for the next round." +"command.usage" = "Usage: fr_status | fr_list | fr_next | fr_reload | fr_enable <0|1> | fr_info | fr_help | fr_knock [0|1|2] | fr_chicken | fr_healthshot | fr_nvg | fr_wire " +"command.wire_usage" = "Usage: fr_wire " +"config.unavailable" = "Configuration unavailable." +"feedback.error" = "[FunRounds] Error: {error}" +"healthshot.already_owned" = "You already have a healthshot." +"healthshot.pending" = "Healthshot transaction in progress." +"healthshot.purchased" = "[FunRounds] Healthshot purchased." +"healthshot.request" = "[FunRounds] Buying a healthshot for {price} cash." +"healthshot.team_required" = "Join a playing team to buy a healthshot." +"healthshot.unavailable" = "Healthshot purchases are unavailable." +"help.body" = "fr_info / !info / !frinfo — Show current mode\nfr_help / !help / !frhelp — Show help\nfr_knock [0|1|2] / !knock [0|1|2] — Self-push: 0 off, 1 ground and air, 2 airborne only (default); cycle without args\nfr_c4 / !c4 — T players can buy C4 at configured cash price\nfr_suicide / !suicide — Start suicide blast with held or purchased C4\nfr_chicken / !chicken — Buy an ordinary chicken at configured cash price\nfr_healthshot / !healthshot — Buy a healthshot at configured cash price\nfr_nvg / !nvg — Toggle night vision\nfr_wire / !wire — Choose plant or defuse wire; otherwise keep default" +"info.mode" = "State: {phase}\nMode: {id} {name}\nDescription: {description}" +"info.ordinary" = "Current mode: Ordinary gameplay" +"info.shield" = "\nShield: {shield}" +"knock.airborne" = "Airborne only" +"knock.always" = "Ground and air" +"knock.off" = "Off" +"nvg.alive_required" = "Night vision requires an alive player." +"nvg.disabled" = "[FunRounds] Night vision disabled." +"nvg.enabled" = "[FunRounds] Night vision enabled." +"phase.ordinary" = "Ordinary gameplay" +"phase.preparing" = "Preparing" +"phase.running" = "Running" +"phase.warmup" = "Warmup" +"player.alive_required" = "Alive player required." +"player.life_pending" = "Player state not ready yet." +"preference.failed" = "Self-push: {value} (save failed: {error})" +"preference.queued" = "Self-push: {value}" +"preference.save_failed" = "Failed to save self-push preference: {error}" +"preference.session" = "Self-push: {value} (session only)" +"preference.unchanged" = "Self-push: {value} (unchanged)" +"public.unavailable" = "FunRounds public actions are unavailable." +"purchase.c4_t_only" = "Only Ts can buy C4." +"purchase.cancelled" = "Purchase cancelled." +"purchase.debit" = "Cash charge failed: {error}" +"purchase.insufficient" = "Buying {item} requires {price} cash." +"purchase.item.c4" = "C4" +"purchase.item.chicken" = "chicken" +"purchase.item.healthshot" = "healthshot" +"purchase.ownership_changed" = "Delivery failed; cash state changed, refund incomplete: {error}" +"purchase.refund_failed" = "Delivery failed; refund failed: {error}" +"purchase.refunded" = "Delivery failed; cash refunded: {error}" +"suicide.ct_broadcast" = "[FunRounds] A CT is defusing the suicide bomb!" +"suicide.start_broadcast" = "[FunRounds] Suicide blast armed; detonation in 5 seconds!" +"suicide.started" = "Suicide blast already in progress." +"team.finished" = "[FunRounds] Team deathmatch finished: T {t} : {ct} CT" +"team.info" = "\nScore: T {t} : {ct} CT\nTime remaining: {seconds}s" +"team.waiting" = "\nScore: T 0 : 0 CT\nTime: starts after freeze time" +"warmup.description" = "Warmup round" +"warmup.name" = "Warmup" +"welcome" = "[FunRounds] Plugin version {version} loaded." +"wire.ct_required" = "Only the active CT defuser can cut a wire." +"wire.defuse_help" = "[FunRounds] Quick defuse: cut Blue / Yellow / Red / Green with !wire or fr_wire " +"wire.defused" = "[FunRounds] Correct {wire} wire; quick defuse in progress!" +"wire.exploded" = "[FunRounds] Wrong {wire} wire; detonation triggered!" +"wire.no_defuse" = "You have not started defusing this C4." +"wire.plant_help" = "[FunRounds] Optional plant wire: Blue / Yellow / Red / Green with !wire or fr_wire ; random if omitted" +"wire.plant_selected" = "[FunRounds] Plant wire selected: {wire}" + +"mode.example.name" = "Generic example" +"mode.example.description" = "Demonstrates basic equipment and player attributes" diff --git a/config/i18n/zh-CN.toml b/config/i18n/zh-CN.toml new file mode 100644 index 0000000..96280d2 --- /dev/null +++ b/config/i18n/zh-CN.toml @@ -0,0 +1,81 @@ +[messages] +"c4.owned" = "[FunRounds] 已持有C4,无需重复购买" +"c4.owned_suicide" = "[FunRounds] 已持有C4;检视C4(按F)可启动自爆" +"c4.pending" = "C4事务处理中" +"c4.purchased" = "[FunRounds] C4购买成功" +"c4.purchased_inspect" = "[FunRounds] C4购买成功;检视C4(按F)启动自爆" +"c4.purchased_start" = "[FunRounds] C4购买成功,自爆已启动" +"c4.request" = "[FunRounds] 正在购买C4,价格为 {price} 现金" +"c4.t_required" = "仅限进攻方(T)购买C4" +"c4.unavailable" = "当前无法购买C4或启动自爆" +"chicken.pending" = "买鸡事务处理中" +"chicken.position_invalid" = "当前位置无法生成鸡" +"chicken.purchased" = "[FunRounds] 购买小鸡成功" +"chicken.request" = "[FunRounds] 正在购买小鸡,价格为 {price} 现金" +"chicken.team_required" = "加入对局队伍后方可购买小鸡" +"chicken.unavailable" = "小鸡购买当前不可用" +"command.enabled" = "[FunRounds] enabled={enabled};将于下一回合生效" +"command.next" = "[FunRounds] 下一模式:{mode}" +"command.no_config" = "[FunRounds] 未找到有效配置" +"command.reload" = "[FunRounds] 配置与多语言文本已排队,将于下一回合生效" +"command.usage" = "用法:fr_status | fr_list | fr_next | fr_reload | fr_enable <0|1> | fr_info | fr_help | fr_knock [0|1|2] | fr_chicken | fr_healthshot | fr_nvg | fr_wire " +"command.wire_usage" = "用法:fr_wire " +"config.unavailable" = "配置暂不可用" +"feedback.error" = "[FunRounds] 错误:{error}" +"healthshot.already_owned" = "已持有医疗针,无需重复购买" +"healthshot.pending" = "医疗针事务处理中" +"healthshot.purchased" = "[FunRounds] 医疗针购买成功" +"healthshot.request" = "[FunRounds] 正在购买医疗针,价格为 {price} 现金" +"healthshot.team_required" = "加入对局队伍后方可购买医疗针" +"healthshot.unavailable" = "医疗针购买当前不可用" +"help.body" = "fr_info / !info / !frinfo — 查看当前模式\nfr_help / !help / !frhelp — 查看帮助\nfr_knock [0|1|2] / !knock [0|1|2] — 开枪击退:0关闭/1地面及空中/2仅空中(默认);无参数依次切换\nfr_c4 / !c4 — 进攻方在允许购买时,按配置价格购买C4\nfr_suicide / !suicide — 允许自爆时,使用所持或购买的C4启动自爆\nfr_chicken / !chicken — 按配置价格购买一只小鸡\nfr_healthshot / !healthshot — 按配置价格购买一支医疗针\nfr_nvg / !nvg — 开启或关闭夜视仪\nfr_wire / !wire — 选择安包或拆包剪线颜色;未选则使用默认机制" +"info.mode" = "状态:{phase}\n模式:{id} {name}\n说明:{description}" +"info.ordinary" = "当前模式:普通对局" +"info.shield" = "\n护盾值:{shield}" +"knock.airborne" = "仅空中" +"knock.always" = "地面与空中" +"knock.off" = "关闭" +"nvg.alive_required" = "仅限存活玩家使用夜视仪" +"nvg.disabled" = "[FunRounds] 夜视仪已关闭" +"nvg.enabled" = "[FunRounds] 夜视仪已开启" +"phase.ordinary" = "普通对局" +"phase.preparing" = "准备中" +"phase.running" = "进行中" +"phase.warmup" = "热身中" +"player.alive_required" = "仅限存活玩家使用" +"player.life_pending" = "角色未就绪,暂无法使用" +"preference.failed" = "开枪击退:{value}(保存失败:{error})" +"preference.queued" = "开枪击退:{value}" +"preference.save_failed" = "开枪击退偏好保存失败:{error}" +"preference.session" = "开枪击退:{value}(仅本次会话有效)" +"preference.unchanged" = "开枪击退:{value}(设置未变动)" +"public.unavailable" = "FunRounds公共行为当前不可用" +"purchase.c4_t_only" = "仅限进攻方(T)购买C4" +"purchase.cancelled" = "购买已取消" +"purchase.debit" = "扣除现金失败:{error}" +"purchase.insufficient" = "购买 {item} 需要 {price} 现金" +"purchase.item.c4" = "C4" +"purchase.item.chicken" = "小鸡" +"purchase.item.healthshot" = "医疗针" +"purchase.ownership_changed" = "发放失败,现金状态变更导致退款未完成:{error}" +"purchase.refund_failed" = "发放失败且退款失败:{error}" +"purchase.refunded" = "发放失败,已退还现金:{error}" +"suicide.ct_broadcast" = "[FunRounds] CT正在拆除自爆炸弹!" +"suicide.start_broadcast" = "[FunRounds] 自爆已启动,5秒后爆炸!" +"suicide.started" = "自爆已在进行中" +"team.finished" = "[FunRounds] 团队死斗结束 T {t} : {ct} CT" +"team.info" = "\n比分:T {t} : {ct} CT\n剩余时间:{seconds}s" +"team.waiting" = "\n比分:T 0 : 0 CT\n剩余时间:计时未开始(冻结结束后开始)" +"warmup.description" = "热身回合" +"warmup.name" = "热身" +"welcome" = "[FunRounds] 插件版本 {version} 已加载" +"wire.ct_required" = "仅限正在拆包的防守方(CT)剪线" +"wire.defuse_help" = "[FunRounds] 剪线快速拆包:蓝Blue / 黄Yellow / 红Red / 绿Green;输入 !wire <颜色> 或 fr_wire <颜色>" +"wire.defused" = "[FunRounds] {wire} 线正确,快速拆除中!" +"wire.exploded" = "[FunRounds] {wire} 线错误,立即引爆!" +"wire.no_defuse" = "尚未开始拆除C4" +"wire.plant_help" = "[FunRounds] 安包时可选引线颜色:蓝Blue / 黄Yellow / 红Red / 绿Green;输入 !wire <颜色> 或 fr_wire <颜色>;未选则随机" +"wire.plant_selected" = "[FunRounds] 已选择安包引线颜色:{wire}" + +"mode.example.name" = "通用示例" +"mode.example.description" = "演示基础配装与玩家属性" diff --git a/crates/funrounds-core/src/afterburn.rs b/crates/funrounds-core/src/afterburn.rs new file mode 100644 index 0000000..fc64f14 --- /dev/null +++ b/crates/funrounds-core/src/afterburn.rs @@ -0,0 +1,66 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use serde::Deserialize; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AfterburnSettings { + pub duration_seconds: f32, + pub damage_fraction: f32, + pub minimum_damage: f32, +} + +impl Default for AfterburnSettings { + fn default() -> Self { + Self { + duration_seconds: 15.0, + damage_fraction: 0.01, + minimum_damage: 1.0, + } + } +} + +impl AfterburnSettings { + pub(crate) fn validate(self) -> Result<(), String> { + if !self.duration_seconds.is_finite() || self.duration_seconds <= 0.0 { + return Err("afterburn duration_seconds must be finite and positive".into()); + } + if !self.damage_fraction.is_finite() || self.damage_fraction < 0.0 { + return Err("afterburn damage_fraction must be finite and non-negative".into()); + } + if !self.minimum_damage.is_finite() || self.minimum_damage < 0.0 { + return Err("afterburn minimum_damage must be finite and non-negative".into()); + } + Ok(()) + } + + /// Only the captured, plugin-owned entityflame uses this rule; inferno ticks stay native. + pub fn tick_damage(self, current_health: i32) -> f32 { + if current_health <= 0 { + return 0.0; + } + (f64::from(current_health) * f64::from(self.damage_fraction)) + .max(f64::from(self.minimum_damage)) + .min(f64::from(f32::MAX)) as f32 + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(crate) struct AfterburnInput { + duration_seconds: Option, + damage_fraction: Option, + minimum_damage: Option, +} + +impl AfterburnInput { + pub(crate) fn resolve(self, base: AfterburnSettings) -> Result { + let settings = AfterburnSettings { + duration_seconds: self.duration_seconds.unwrap_or(base.duration_seconds), + damage_fraction: self.damage_fraction.unwrap_or(base.damage_fraction), + minimum_damage: self.minimum_damage.unwrap_or(base.minimum_damage), + }; + settings.validate()?; + Ok(settings) + } +} diff --git a/crates/funrounds-core/src/attributes.rs b/crates/funrounds-core/src/attributes.rs new file mode 100644 index 0000000..bdd94c3 --- /dev/null +++ b/crates/funrounds-core/src/attributes.rs @@ -0,0 +1,97 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use rand::{Rng, RngExt}; +use serde::Deserialize; +use std::fmt; + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct AttributeRange { + pub min: u16, + pub max: u16, +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(untagged)] +pub enum AttributeValue { + Fixed(u16), + Range(AttributeRange), +} + +impl AttributeValue { + pub fn validate(self, minimum: u16, maximum: u16) -> bool { + let (min, max) = match self { + Self::Fixed(value) => (value, value), + Self::Range(range) => (range.min, range.max), + }; + minimum <= min && min <= max && max <= maximum + } + + pub fn sample(self, rng: &mut impl Rng) -> u16 { + match self { + Self::Fixed(value) => value, + Self::Range(range) => rng.random_range(range.min..=range.max), + } + } +} + +impl fmt::Display for AttributeValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Fixed(value) => value.fmt(f), + Self::Range(range) => write!(f, "{}..={}", range.min, range.max), + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum RandomHelmet { + Random, +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(untagged)] +pub enum HelmetValue { + Fixed(bool), + Random(RandomHelmet), + #[serde(skip)] + FromArmor, +} + +impl fmt::Display for HelmetValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Fixed(value) => value.fmt(f), + Self::Random(_) => f.write_str("random"), + Self::FromArmor => f.write_str("from_armor"), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LifeAttributes { + pub health: u16, + pub armor: u16, + pub helmet: bool, +} + +impl LifeAttributes { + pub fn sample(health: AttributeValue, armor: AttributeValue, helmet: HelmetValue, rng: &mut impl Rng) -> Self { + let health = health.sample(rng); + let armor = armor.sample(rng); + let helmet = match helmet { + HelmetValue::Fixed(value) => value, + HelmetValue::Random(RandomHelmet::Random) => rng.random_bool(0.5), + HelmetValue::FromArmor => armor > 0, + }; + Self { health, armor, helmet } + } +} + +impl crate::Mode { + pub fn sample_attributes(&self, rng: &mut impl Rng) -> LifeAttributes { + LifeAttributes::sample(self.health, self.armor, self.helmet, rng) + } +} diff --git a/crates/funrounds-core/src/bin/validate-config.rs b/crates/funrounds-core/src/bin/validate-config.rs new file mode 100644 index 0000000..6ade75b --- /dev/null +++ b/crates/funrounds-core/src/bin/validate-config.rs @@ -0,0 +1,90 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use funrounds_core::{Config, TextBundle, TextCatalog}; +use std::{env, fs, path::Path, process::ExitCode}; + +fn validate_file(path: &Path) -> Result<(), String> { + let source = fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))?; + Config::parse(&source).map(|_| ()).map_err(|error| format!("{}: {error}", path.display())) +} + +fn validate_bundle(config: &Config, directory: &Path, allow_fallback: bool) -> Result<(), String> { + let zh_path = directory.join("zh-CN.toml"); + let en_path = directory.join("en.toml"); + let catalogs = if allow_fallback { + let mut catalogs = Vec::new(); + for (language, path) in [("zh-CN", &zh_path), ("en", &en_path)] { + if let Some(catalog) = read_catalog_if_present(path)? { + catalogs.push((language.to_owned(), catalog)); + } + } + catalogs + } else { + let zh = read_catalog(&zh_path)?; + let en = read_catalog(&en_path)?; + TextBundle::validate_complete_catalogs(&zh, &en).map_err(|error| format!("{}: {error}", directory.display()))?; + vec![("zh-CN".into(), zh), ("en".into(), en)] + }; + let bundle = TextBundle::load(config.default_language.as_str(), catalogs)?; + bundle.validate_config(config) +} + +fn read_catalog(path: &Path) -> Result { + let source = fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))?; + TextCatalog::parse(&source).map_err(|error| format!("{}: {error}", path.display())) +} + +fn read_catalog_if_present(path: &Path) -> Result, String> { + match fs::read_to_string(path) { + Ok(source) => TextCatalog::parse(&source) + .map(Some) + .map_err(|error| format!("{}: {error}", path.display())), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(format!("{}: {error}", path.display())), + } +} + +fn run() -> Result<(), String> { + let mut arguments = env::args_os(); + let program = arguments.next().unwrap_or_default(); + let path = arguments.next().ok_or_else(|| usage(&program))?; + let next = arguments.next(); + if next.is_none() { + return validate_file(Path::new(&path)); + } + let usage = usage(&program); + if next.as_deref() != Some(std::ffi::OsStr::new("--i18n-dir")) { + return Err(usage); + } + let directory = arguments.next().ok_or_else(|| usage.clone())?; + let allow_fallback = match arguments.next() { + None => false, + Some(flag) if flag == "--allow-fallback" => true, + Some(_) => return Err(usage), + }; + if arguments.next().is_some() { + return Err(usage); + } + let config_path = Path::new(&path); + let source = fs::read_to_string(config_path).map_err(|error| format!("{}: {error}", config_path.display()))?; + let config = Config::parse(&source).map_err(|error| format!("{}: {error}", config_path.display()))?; + validate_bundle(&config, Path::new(&directory), allow_fallback) +} + +fn usage(program: &std::ffi::OsStr) -> String { + format!( + "usage: {} [--i18n-dir [--allow-fallback]]", + Path::new(program).display() + ) +} + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("{error}"); + ExitCode::FAILURE + } + } +} diff --git a/crates/funrounds-core/src/chicken.rs b/crates/funrounds-core/src/chicken.rs new file mode 100644 index 0000000..8b56e7e --- /dev/null +++ b/crates/funrounds-core/src/chicken.rs @@ -0,0 +1,659 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use crate::PlayerTask; +use rand::{Rng, RngExt}; +use serde::Deserialize; + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ChickenHealthBasis { + Current, + Base, +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct ChickenPercentRange { + pub min: f32, + pub max: f32, +} + +impl ChickenPercentRange { + fn validate(self, name: &str) -> Result<(), String> { + if !self.min.is_finite() || !self.max.is_finite() || self.min < 0.0 || self.max < self.min { + return Err(format!("{name} must be a finite, non-negative increasing range")); + } + Ok(()) + } + + fn sample(self, rng: &mut impl Rng) -> f32 { + if self.min == self.max { + self.min + } else { + rng.random_range(self.min..=self.max) + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ChickenSpawnConfig { + pub per_player: u32, + pub minimum: u32, +} + +impl Default for ChickenSpawnConfig { + fn default() -> Self { + Self { per_player: 2, minimum: 10 } + } +} + +impl ChickenSpawnConfig { + /// `effective_players` is counted by the adapter from eligible players, not slots or observers. + pub fn target_count(self, effective_players: u32) -> u32 { + effective_players.saturating_mul(self.per_player).max(self.minimum) + } + + /// Replenish by a full batch only below ceil(1.5 × target), preserving an + /// unchanged population at the exact threshold. + pub fn refill_threshold(self, target: u32) -> u32 { + target.saturating_add(target / 2 + target % 2) + } + + /// Populations above three batches are trimmed back to this limit. + pub fn maximum_population(self, target: u32) -> u32 { + target.saturating_mul(3) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ChickenHealConfig { + pub basis: ChickenHealthBasis, + pub percent: ChickenPercentRange, + pub minimum_health: i32, +} + +impl Default for ChickenHealConfig { + fn default() -> Self { + Self { + basis: ChickenHealthBasis::Current, + percent: ChickenPercentRange { min: 0.70, max: 2.75 }, + minimum_health: 25, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ChickenDamageRule { + Percent { + basis: ChickenHealthBasis, + percent: ChickenPercentRange, + }, + Fixed { + amount: u32, + }, +} + +impl Default for ChickenDamageRule { + fn default() -> Self { + Self::Percent { + basis: ChickenHealthBasis::Current, + percent: ChickenPercentRange { min: 0.10, max: 0.25 }, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ChickenEatingConfig { + pub enabled: bool, + pub digestion_seconds: f32, + pub risk_offset: i32, + pub risk_per_undigested: u32, + pub heal: ChickenHealConfig, + pub damage: ChickenDamageRule, +} + +impl Default for ChickenEatingConfig { + fn default() -> Self { + Self { + enabled: true, + digestion_seconds: 20.0, + risk_offset: 0, + risk_per_undigested: 7, + heal: ChickenHealConfig::default(), + damage: ChickenDamageRule::default(), + } + } +} + +impl ChickenEatingConfig { + /// The global setting can disable eating; a mode can additionally disable it, never re-enable it. + pub const fn enabled_for_mode(self, mode_enabled: Option) -> bool { + self.enabled && !matches!(mode_enabled, Some(false)) + } + + fn validate(self) -> Result<(), String> { + if !self.digestion_seconds.is_finite() || self.digestion_seconds <= 0.0 { + return Err("chicken.eating.digestion_seconds must be finite and positive".into()); + } + self.heal.percent.validate("chicken.eating.heal percent")?; + if self.heal.minimum_health < 0 { + return Err("chicken.eating.heal.minimum_health must be non-negative".into()); + } + if let ChickenDamageRule::Percent { percent, .. } = self.damage { + percent.validate("chicken.eating.damage percent")?; + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ChickenBlastConfig { + pub damage: f32, + pub radius: f32, +} + +impl Default for ChickenBlastConfig { + fn default() -> Self { + Self { + damage: 2000.0, + radius: 1000.0, + } + } +} + +impl ChickenBlastConfig { + fn validate(self, name: &str) -> Result<(), String> { + if !self.damage.is_finite() || self.damage < 0.0 || !self.radius.is_finite() || self.radius < 0.0 { + return Err(format!("{name}.damage and radius must be finite and non-negative")); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ChickenDamageChainConfig { + pub allow_fire: bool, + pub allow_explosion: bool, + pub allow_chicken_explosion: bool, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ChickenConfig { + pub spawn: ChickenSpawnConfig, + pub eating: ChickenEatingConfig, + pub kill_blast: ChickenBlastConfig, + pub risk_blast: ChickenBlastConfig, + pub damage_chain: ChickenDamageChainConfig, +} + +impl ChickenConfig { + pub fn validate(self) -> Result<(), String> { + self.eating.validate()?; + self.kill_blast.validate("chicken.kill_blast")?; + self.risk_blast.validate("chicken.risk_blast")?; + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq)] +#[serde(default, deny_unknown_fields)] +pub struct HealthshotConfig { + pub heal_base_fraction: f32, + pub cap_base_multiple: u32, +} + +impl Default for HealthshotConfig { + fn default() -> Self { + Self { + heal_base_fraction: 0.5, + cap_base_multiple: 3, + } + } +} + +impl HealthshotConfig { + pub fn validate(self) -> Result<(), String> { + if !self.heal_base_fraction.is_finite() || self.heal_base_fraction < 0.0 || self.cap_base_multiple == 0 { + return Err("healthshot.heal_base_fraction must be finite and non-negative and cap_base_multiple must be positive".into()); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HealthshotOutcome { + NotConsumed, + Applied { health: i32, healed: i32 }, +} + +/// Returns NotConsumed at or above the B-relative cap, and never lowers health above that cap. +pub fn use_healthshot(config: HealthshotConfig, current_health: i32, base_health: i32) -> HealthshotOutcome { + if config.validate().is_err() || current_health <= 0 || base_health <= 0 { + return HealthshotOutcome::NotConsumed; + } + let cap = i64::from(base_health) * i64::from(config.cap_base_multiple); + if i64::from(current_health) >= cap { + return HealthshotOutcome::NotConsumed; + } + // Engine health is integer-valued; retain the project's floor rounding for healing amounts. + let amount = (f64::from(base_health) * f64::from(config.heal_base_fraction)).floor() as i64; + let health = i64::from(current_health).saturating_add(amount).min(cap).min(i64::from(i32::MAX)) as i32; + if health > current_health { + HealthshotOutcome::Applied { + health, + healed: health - current_health, + } + } else { + HealthshotOutcome::NotConsumed + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChickenDamageCause { + Fire, + Explosion, + ChickenExplosion, + Other, +} + +/// Reports whether a damage source is blocked from creating a chicken blast chain. +pub const fn filters_chicken_damage_chain(config: ChickenDamageChainConfig, cause: ChickenDamageCause) -> bool { + match cause { + ChickenDamageCause::Fire => !config.allow_fire, + ChickenDamageCause::Explosion => !config.allow_explosion, + ChickenDamageCause::ChickenExplosion => !config.allow_chicken_explosion, + ChickenDamageCause::Other => false, + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ChickenEatOutcome { + Heal { health: i32, healed: i32 }, + Damage { amount: i32 }, + Death, + RiskBlast(ChickenBlastConfig), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChickenEatError { + Disabled, + StaleTask, + InvalidHealth, + InvalidTime, + InvalidConfig, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ChickenEatingState { + task: PlayerTask, + undigested: u32, + next_digestion_at: Option, +} + +impl ChickenEatingState { + pub const fn new(task: PlayerTask) -> Self { + Self { + task, + undigested: 0, + next_digestion_at: None, + } + } + + /// Rebind this life-bound stomach state after a confirmed controller takeover of the same pawn. + /// The adapter must resolve and validate the new controller against the live engine pawn first. + pub fn rebind_takeover(&mut self, new_task: PlayerTask) -> bool { + let old_pawn = self.task.player.pawn_handle; + if self.task.round != new_task.round || old_pawn == u32::MAX || new_task.player.pawn_handle != old_pawn { + return false; + } + self.task = new_task; + true + } + + pub const fn undigested(&self) -> u32 { + self.undigested + } + + pub const fn next_digestion_at(&self) -> Option { + self.next_digestion_at + } + + /// Clear this life's stomach state when chicken use is disabled or the player dies. + pub fn reset(&mut self) { + self.undigested = 0; + self.next_digestion_at = None; + } + + /// Digests every chicken whose fixed 20-second cadence (or configured interval) elapsed. + /// The deadline advances from the old deadline, not from the latest feed time. + pub fn digest_due(&mut self, task: PlayerTask, now: f64, interval_seconds: f32) -> Result { + if task != self.task { + return Err(ChickenEatError::StaleTask); + } + if !now.is_finite() || now < 0.0 { + return Err(ChickenEatError::InvalidTime); + } + if !interval_seconds.is_finite() || interval_seconds <= 0.0 { + return Err(ChickenEatError::InvalidConfig); + } + if self.undigested == 0 { + self.next_digestion_at = None; + return Ok(0); + } + let Some(next_digestion_at) = self.next_digestion_at else { + return Ok(0); + }; + if now < next_digestion_at { + return Ok(0); + } + let interval = f64::from(interval_seconds); + let elapsed_intervals = (((now - next_digestion_at) / interval).floor() as u64).saturating_add(1); + let digested = elapsed_intervals.min(u64::from(self.undigested)) as u32; + self.undigested -= digested; + self.next_digestion_at = (self.undigested > 0).then_some(next_digestion_at + f64::from(digested) * interval); + Ok(digested) + } + + /// Applies one accepted chicken interaction; the caller supplies the same round/life task + /// used to create this state and the actual spawn-health base captured by the adapter. + pub fn consume( + &mut self, + task: PlayerTask, + current_health: i32, + base_health: i32, + now: f64, + config: ChickenConfig, + rng: &mut impl Rng, + ) -> Result { + if task != self.task { + return Err(ChickenEatError::StaleTask); + } + if !config.eating.enabled { + return Err(ChickenEatError::Disabled); + } + if config.validate().is_err() { + return Err(ChickenEatError::InvalidConfig); + } + if current_health <= 0 || base_health <= 0 { + return Err(ChickenEatError::InvalidHealth); + } + if !now.is_finite() || now < 0.0 { + return Err(ChickenEatError::InvalidTime); + } + self.digest_due(task, now, config.eating.digestion_seconds)?; + + let risk = if self.undigested == 0 { + ChickenRisk::Heal + } else { + classify_chicken_risk( + rng.random_range(1..=100), + self.undigested, + config.eating.risk_per_undigested, + config.eating.risk_offset, + ) + }; + Ok(self.finish_consumption(risk, current_health, base_health, now, config, rng)) + } + + fn finish_consumption( + &mut self, + risk: ChickenRisk, + current_health: i32, + base_health: i32, + now: f64, + config: ChickenConfig, + rng: &mut impl Rng, + ) -> ChickenEatOutcome { + let eaten_count = self.undigested.saturating_add(1); + self.undigested = eaten_count; + if self.next_digestion_at.is_none() { + self.next_digestion_at = Some(now + f64::from(config.eating.digestion_seconds)); + } + match risk { + ChickenRisk::Heal => { + let basis = match config.eating.heal.basis { + ChickenHealthBasis::Current => current_health, + ChickenHealthBasis::Base => base_health, + }; + let percent = config.eating.heal.percent.sample(rng); + let bonus = (basis as f32 * percent / eaten_count as f32).floor() as i32; + let mut health = current_health.saturating_add(bonus); + if current_health < base_health && health < base_health { + health = base_health; + } + if current_health < config.eating.heal.minimum_health && health < config.eating.heal.minimum_health { + health = config.eating.heal.minimum_health; + } + ChickenEatOutcome::Heal { + health, + healed: health.saturating_sub(current_health), + } + } + ChickenRisk::Damage => ChickenEatOutcome::Damage { + amount: chicken_damage_amount(config.eating.damage, current_health, base_health, eaten_count, rng), + }, + ChickenRisk::Death => ChickenEatOutcome::Death, + ChickenRisk::Blast => ChickenEatOutcome::RiskBlast(config.risk_blast), + } + } +} + +fn chicken_damage_amount(rule: ChickenDamageRule, current_health: i32, base_health: i32, eaten_count: u32, rng: &mut impl Rng) -> i32 { + match rule { + ChickenDamageRule::Percent { basis, percent } => { + let basis = match basis { + ChickenHealthBasis::Current => current_health, + ChickenHealthBasis::Base => base_health, + }; + let per_chicken = (basis as f32 * percent.sample(rng)).floor() as i32; + per_chicken.saturating_mul(eaten_count.min(i32::MAX as u32) as i32).max(1) + } + ChickenDamageRule::Fixed { amount } => i32::try_from(amount).unwrap_or(i32::MAX), + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ChickenRisk { + Heal, + Damage, + Death, + Blast, +} + +fn classify_chicken_risk(roll: u32, undigested: u32, per_undigested: u32, offset: i32) -> ChickenRisk { + let risk = i64::from(roll) + .saturating_add(i64::from(undigested).saturating_mul(i64::from(per_undigested))) + .saturating_add(i64::from(offset)); + match risk { + ..=50 => ChickenRisk::Heal, + 51..=85 => ChickenRisk::Damage, + 86..=94 => ChickenRisk::Death, + _ => ChickenRisk::Blast, + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(crate) struct ChickenInput { + spawn: Option, + eating: Option, + kill_blast: Option, + risk_blast: Option, + damage_chain: Option, +} + +impl ChickenInput { + pub(crate) fn resolve(self) -> Result { + let defaults = ChickenConfig::default(); + let config = ChickenConfig { + spawn: self.spawn.map_or(defaults.spawn, |input| input.resolve(defaults.spawn)), + eating: self.eating.map_or(Ok(defaults.eating), |input| input.resolve(defaults.eating))?, + kill_blast: self.kill_blast.map_or(defaults.kill_blast, |input| input.resolve(defaults.kill_blast)), + risk_blast: self.risk_blast.map_or(defaults.risk_blast, |input| input.resolve(defaults.risk_blast)), + damage_chain: self + .damage_chain + .map_or(defaults.damage_chain, |input| input.resolve(defaults.damage_chain)), + }; + config.validate()?; + Ok(config) + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct ChickenDamageChainInput { + allow_fire: Option, + allow_explosion: Option, + allow_chicken_explosion: Option, +} + +impl ChickenDamageChainInput { + fn resolve(self, defaults: ChickenDamageChainConfig) -> ChickenDamageChainConfig { + ChickenDamageChainConfig { + allow_fire: self.allow_fire.unwrap_or(defaults.allow_fire), + allow_explosion: self.allow_explosion.unwrap_or(defaults.allow_explosion), + allow_chicken_explosion: self.allow_chicken_explosion.unwrap_or(defaults.allow_chicken_explosion), + } + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct ChickenSpawnInput { + per_player: Option, + minimum: Option, +} + +impl ChickenSpawnInput { + fn resolve(self, defaults: ChickenSpawnConfig) -> ChickenSpawnConfig { + ChickenSpawnConfig { + per_player: self.per_player.unwrap_or(defaults.per_player), + minimum: self.minimum.unwrap_or(defaults.minimum), + } + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct ChickenEatingInput { + enabled: Option, + digestion_seconds: Option, + risk_offset: Option, + risk_per_undigested: Option, + heal: Option, + damage: Option, +} + +impl ChickenEatingInput { + fn resolve(self, defaults: ChickenEatingConfig) -> Result { + let config = ChickenEatingConfig { + enabled: self.enabled.unwrap_or(defaults.enabled), + digestion_seconds: self.digestion_seconds.unwrap_or(defaults.digestion_seconds), + risk_offset: self.risk_offset.unwrap_or(defaults.risk_offset), + risk_per_undigested: self.risk_per_undigested.unwrap_or(defaults.risk_per_undigested), + heal: self.heal.map_or(defaults.heal, |input| input.resolve(defaults.heal)), + damage: self.damage.map_or(Ok(defaults.damage), |input| input.resolve(defaults.damage))?, + }; + config.validate()?; + Ok(config) + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct ChickenHealInput { + basis: Option, + min: Option, + max: Option, + minimum_health: Option, +} + +impl ChickenHealInput { + fn resolve(self, defaults: ChickenHealConfig) -> ChickenHealConfig { + ChickenHealConfig { + basis: self.basis.unwrap_or(defaults.basis), + percent: ChickenPercentRange { + min: self.min.unwrap_or(defaults.percent.min), + max: self.max.unwrap_or(defaults.percent.max), + }, + minimum_health: self.minimum_health.unwrap_or(defaults.minimum_health), + } + } +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +enum ChickenDamageInput { + Percent { + basis: Option, + min: Option, + max: Option, + }, + Fixed { + amount: Option, + }, +} + +impl ChickenDamageInput { + fn resolve(self, defaults: ChickenDamageRule) -> Result { + match self { + Self::Percent { basis, min, max } => { + let base = match defaults { + ChickenDamageRule::Percent { basis, percent } => (basis, percent), + ChickenDamageRule::Fixed { .. } => match ChickenDamageRule::default() { + ChickenDamageRule::Percent { basis, percent } => (basis, percent), + ChickenDamageRule::Fixed { .. } => unreachable!(), + }, + }; + Ok(ChickenDamageRule::Percent { + basis: basis.unwrap_or(base.0), + percent: ChickenPercentRange { + min: min.unwrap_or(base.1.min), + max: max.unwrap_or(base.1.max), + }, + }) + } + Self::Fixed { amount } => match (amount, defaults) { + (Some(amount), _) => Ok(ChickenDamageRule::Fixed { amount }), + (None, ChickenDamageRule::Fixed { amount }) => Ok(ChickenDamageRule::Fixed { amount }), + (None, ChickenDamageRule::Percent { .. }) => Err("chicken.eating.damage.amount is required for fixed damage".into()), + }, + } + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct ChickenBlastInput { + damage: Option, + radius: Option, +} + +impl ChickenBlastInput { + fn resolve(self, defaults: ChickenBlastConfig) -> ChickenBlastConfig { + ChickenBlastConfig { + damage: self.damage.unwrap_or(defaults.damage), + radius: self.radius.unwrap_or(defaults.radius), + } + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(crate) struct HealthshotInput { + heal_base_fraction: Option, + cap_base_multiple: Option, +} + +impl HealthshotInput { + pub(crate) fn resolve(self) -> Result { + let defaults = HealthshotConfig::default(); + let config = HealthshotConfig { + heal_base_fraction: self.heal_base_fraction.unwrap_or(defaults.heal_base_fraction), + cap_base_multiple: self.cap_base_multiple.unwrap_or(defaults.cap_base_multiple), + }; + config.validate()?; + Ok(config) + } +} diff --git a/crates/funrounds-core/src/combat.rs b/crates/funrounds-core/src/combat.rs index 9e8bdfd..9a49aaa 100644 --- a/crates/funrounds-core/src/combat.rs +++ b/crates/funrounds-core/src/combat.rs @@ -26,20 +26,27 @@ pub fn weapon_damage_scale(mode: &Mode, weapon: Option<&str>, player_attack: boo #[derive(Debug)] pub struct CombatLife { + attributes: crate::LifeAttributes, shield: Option, protected_until: Option, next_recharge: f32, } impl CombatLife { - pub fn new(mode: &Mode, now: f32) -> Self { + pub fn new(mode: &Mode, now: f32, rng: &mut impl rand::Rng) -> Self { + let attributes = mode.sample_attributes(rng); Self { - shield: mode.energy_shield.then_some(u64::from(mode.armor)), - protected_until: mode.combat_protection.then_some(now + 0.5), + attributes, + shield: mode.energy_shield.then_some(u64::from(attributes.armor)), + protected_until: mode.spawn_protection.then_some(now + 0.5), next_recharge: now + 0.5, } } + pub fn attributes(&self) -> crate::LifeAttributes { + self.attributes + } + pub fn protect(&mut self, now: f32) { self.protected_until = Some(now + 0.5); } @@ -73,7 +80,8 @@ impl CombatLife { true } - pub fn recharge(&mut self, now: f32, health: i32, base: u16) -> Option { + pub fn recharge(&mut self, now: f32, health: i32) -> Option { + let base = self.attributes.health; let shield = self.shield.as_mut().filter(|shield| **shield > 0)?; if now < self.next_recharge { return None; diff --git a/crates/funrounds-core/src/equipment.rs b/crates/funrounds-core/src/equipment.rs index db72d0c..9b2cbe8 100644 --- a/crates/funrounds-core/src/equipment.rs +++ b/crates/funrounds-core/src/equipment.rs @@ -1,18 +1,22 @@ // Copyright (C) 2026 Mai Ooizumi // SPDX-License-Identifier: AGPL-3.0-or-later -use crate::Mode; +use crate::{KillLoadoutStart, Mode}; use rand::seq::IndexedRandom; -#[derive(Clone, Copy)] -pub(crate) enum WeaponSlot { +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +/// Inventory category for supported weapon classnames. +pub enum WeaponSlot { Primary = 0, Secondary = 1, Knife = 2, + /// Extra equipment category; unlike firearm slots, it can contain multiple items. Extra = 3, } -pub(crate) fn weapon_slot(weapon: &str) -> Option { +/// Returns the loadout slot used by a supported weapon classname. +pub fn weapon_slot(weapon: &str) -> Option { match weapon { "weapon_ak47" | "weapon_m4a1" @@ -64,18 +68,18 @@ impl Mode { // Each listed slot supplies one item; an omitted slot stays empty. pub fn select_equipment(&self, rng: &mut impl rand::Rng) -> Result, String> { if self.kill_loadout { - if !self.weapons.iter().any(|weapon| weapon == "weapon_glock") { - return Err(format!("{}: kill loadout requires an initial Glock", self.id)); + match self.kill_loadout_start.unwrap_or(KillLoadoutStart::Glock) { + KillLoadoutStart::Glock => { + if !self.weapons.iter().any(|weapon| weapon == "weapon_glock") { + return Err(format!("{}: kill loadout requires an initial Glock", self.id)); + } + return Ok(vec!["weapon_glock"]); + } + KillLoadoutStart::Random => {} } - return Ok(vec!["weapon_glock"]); } if self.random_loadout { - let mut candidates = Vec::new(); - for weapon in self.weapons.iter().map(String::as_str).filter(|weapon| *weapon != "weapon_knife") { - if !candidates.contains(&weapon) { - candidates.push(weapon); - } - } + let candidates = self.loadout_candidates(); if candidates.is_empty() { return Err(format!("{}: random loadout candidates must not be empty", self.id)); } @@ -98,10 +102,22 @@ impl Mode { Ok(candidates.iter().filter_map(|pool| pool.choose(rng).copied()).collect()) } - pub fn select_kill_weapon(&self, rng: &mut impl rand::Rng) -> Result<&str, String> { + /// Select a configured kill-upgrade weapon, preferring a different entity class. + /// If the configured pool contains only excluded classes, retain its legal behavior. + pub fn select_kill_weapon_excluding(&self, rng: &mut impl rand::Rng, excluded: &[&str]) -> Result<&str, String> { if !self.kill_loadout { return Err(format!("{}: kill loadout is disabled", self.id)); } + let candidates = self.loadout_candidates(); + let preferred = candidates.iter().copied().filter(|weapon| !excluded.contains(weapon)).collect::>(); + preferred + .choose(rng) + .or_else(|| candidates.choose(rng)) + .copied() + .ok_or_else(|| format!("{}: kill loadout candidates must not be empty", self.id)) + } + + fn loadout_candidates(&self) -> Vec<&str> { let mut candidates = Vec::new(); for weapon in self.weapons.iter().map(String::as_str).filter(|weapon| *weapon != "weapon_knife") { if !candidates.contains(&weapon) { @@ -109,9 +125,17 @@ impl Mode { } } candidates - .choose(rng) - .copied() - .ok_or_else(|| format!("{}: kill loadout candidates must not be empty", self.id)) + } +} + +pub fn self_push_force(weapon: &str) -> Option { + match weapon { + "weapon_nova" | "weapon_mag7" | "weapon_sawedoff" | "weapon_xm1014" | "weapon_ssg08" => Some(700.0), + "weapon_awp" | "weapon_scar20" | "weapon_g3sg1" => Some(1300.0), + "weapon_deagle" | "weapon_revolver" => Some(450.0), + "weapon_taser" => Some(135.0), + _ if matches!(weapon_slot(weapon), Some(WeaponSlot::Primary | WeaponSlot::Secondary)) => Some(135.0), + _ => None, } } @@ -242,13 +266,13 @@ mod tests { assert!(mode.weapons.iter().any(|candidate| candidate == loadout[0])); assert!(mode.weapons.iter().any(|candidate| candidate == loadout[1])); } - assert!(mode.select_kill_weapon(&mut rng).is_err()); + assert!(mode.select_kill_weapon_excluding(&mut rng, &[]).is_err()); mode.random_loadout = false; mode.kill_loadout = true; mode.weapons = vec!["weapon_glock".into(), "weapon_famas".into()]; assert_eq!(mode.select_equipment(&mut rng).unwrap(), ["weapon_glock"]); - let kill_weapon = mode.select_kill_weapon(&mut rng).unwrap(); + let kill_weapon = mode.select_kill_weapon_excluding(&mut rng, &[]).unwrap(); assert!(mode.weapons.iter().any(|weapon| weapon == kill_weapon)); } } diff --git a/crates/funrounds-core/src/ghost.rs b/crates/funrounds-core/src/ghost.rs new file mode 100644 index 0000000..c914db5 --- /dev/null +++ b/crates/funrounds-core/src/ghost.rs @@ -0,0 +1,165 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::TeamFilter; +use serde::Deserialize; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GhostSettings { + pub team: TeamFilter, + pub crouch_alpha: u8, + pub slow_walk_alpha: u8, + pub normal_alpha: u8, + pub speed_reveal_start: f32, + pub speed_reveal_full: f32, + pub reveal_delay: f32, + pub breath_interval: f32, + pub breath_volume: f32, + pub breath_distance: f32, +} + +impl Default for GhostSettings { + fn default() -> Self { + Self { + team: TeamFilter::Terrorists, + crouch_alpha: 0, + slow_walk_alpha: 13, + normal_alpha: 127, + speed_reveal_start: 100.0, + speed_reveal_full: 200.0, + reveal_delay: 0.25, + breath_interval: 10.0, + breath_volume: 0.9, + breath_distance: 1000.0, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GhostPose { + Still, + Crouching, + SlowWalking, + Normal, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GhostFrame { + pub pose: GhostPose, + pub horizontal_speed: f32, + pub bunny_hop: bool, + pub attacking: bool, + pub reloading: bool, + pub using: bool, +} + +impl Default for GhostFrame { + fn default() -> Self { + Self { + pose: GhostPose::Normal, + horizontal_speed: 0.0, + bunny_hop: false, + attacking: false, + reloading: false, + using: false, + } + } +} + +#[derive(Clone, Copy, Debug, Default)] +pub struct GhostState { + reloading: bool, + reveal_until: f32, +} + +impl GhostState { + pub fn alpha(&mut self, settings: GhostSettings, frame: GhostFrame, now: f32) -> u8 { + let reloading = frame.reloading; + if reloading || self.reloading { + self.reveal_until = now + settings.reveal_delay; + } + self.reloading = reloading; + ghost_alpha(settings, frame, reloading, self.reveal_until, now) + } +} + +pub fn ghost_alpha(settings: GhostSettings, frame: GhostFrame, reloading: bool, reveal_until: f32, now: f32) -> u8 { + if reloading || now < reveal_until { + return settings.normal_alpha; + } + if frame.bunny_hop || !frame.horizontal_speed.is_finite() { + return pose_alpha(settings, frame.pose); + } + if frame.horizontal_speed <= settings.speed_reveal_start { + return settings.crouch_alpha; + } + let progress = + ((frame.horizontal_speed - settings.speed_reveal_start) / (settings.speed_reveal_full - settings.speed_reveal_start)).clamp(0.0, 1.0); + let start_alpha = settings.crouch_alpha; + (f32::from(start_alpha) + (f32::from(settings.normal_alpha) - f32::from(start_alpha)) * progress).round() as u8 +} + +const fn pose_alpha(settings: GhostSettings, pose: GhostPose) -> u8 { + match pose { + GhostPose::Still | GhostPose::Crouching => settings.crouch_alpha, + GhostPose::SlowWalking => settings.slow_walk_alpha, + GhostPose::Normal => settings.normal_alpha, + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(crate) struct GhostInput { + team: Option, + crouch_alpha: Option, + slow_walk_alpha: Option, + normal_alpha: Option, + speed_reveal_start: Option, + speed_reveal_full: Option, + reveal_delay: Option, + breath_interval: Option, + breath_volume: Option, + breath_distance: Option, +} + +impl GhostInput { + pub(crate) fn resolve(self, base: GhostSettings) -> GhostSettings { + GhostSettings { + team: self.team.unwrap_or(base.team), + crouch_alpha: self.crouch_alpha.unwrap_or(base.crouch_alpha), + slow_walk_alpha: self.slow_walk_alpha.unwrap_or(base.slow_walk_alpha), + normal_alpha: self.normal_alpha.unwrap_or(base.normal_alpha), + speed_reveal_start: self.speed_reveal_start.unwrap_or(base.speed_reveal_start), + speed_reveal_full: self.speed_reveal_full.unwrap_or(base.speed_reveal_full), + reveal_delay: self.reveal_delay.unwrap_or(base.reveal_delay), + breath_interval: self.breath_interval.unwrap_or(base.breath_interval), + breath_volume: self.breath_volume.unwrap_or(base.breath_volume), + breath_distance: self.breath_distance.unwrap_or(base.breath_distance), + } + } +} + +impl GhostSettings { + pub(crate) fn validate(self) -> Result<(), String> { + if !self.reveal_delay.is_finite() || self.reveal_delay < 0.0 { + return Err("ghost reveal_delay must be finite and non-negative".into()); + } + if !self.speed_reveal_start.is_finite() + || self.speed_reveal_start < 0.0 + || !self.speed_reveal_full.is_finite() + || self.speed_reveal_full <= self.speed_reveal_start + { + return Err("ghost speed_reveal_full must be finite and greater than non-negative speed_reveal_start".into()); + } + if !self.breath_interval.is_finite() || self.breath_interval < 0.0 { + return Err("ghost breath_interval must be finite and non-negative".into()); + } + if !self.breath_volume.is_finite() || !(0.0..=1.0).contains(&self.breath_volume) { + return Err("ghost breath_volume must be finite and between 0 and 1".into()); + } + if !self.breath_distance.is_finite() || self.breath_distance < 0.0 { + return Err("ghost breath_distance must be finite and non-negative".into()); + } + Ok(()) + } +} diff --git a/crates/funrounds-core/src/health.rs b/crates/funrounds-core/src/health.rs new file mode 100644 index 0000000..7c59256 --- /dev/null +++ b/crates/funrounds-core/src/health.rs @@ -0,0 +1,226 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use serde::Deserialize; + +#[derive(Clone, Debug, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct HealthBand { + pub below_percent: u32, + pub damage: f32, + pub speed: f32, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HealthCurve { + pub bands: Vec, + pub growth_step_percent: u32, + pub high_damage: f32, + pub high_speed: f32, + pub damage_increment: f32, + pub speed_increment: f32, + pub damage_cap: f32, + pub speed_cap: f32, +} + +impl Default for HealthCurve { + fn default() -> Self { + Self { + bands: vec![ + HealthBand { + below_percent: 10, + damage: 0.6925, + speed: 0.385, + }, + HealthBand { + below_percent: 55, + damage: 0.86, + speed: 0.68, + }, + HealthBand { + below_percent: 133, + damage: 1.0, + speed: 1.0, + }, + ], + growth_step_percent: 33, + high_damage: 1.0, + high_speed: 1.0, + damage_increment: 0.02, + speed_increment: 0.01, + damage_cap: 6.0, + speed_cap: 5.0, + } + } +} + +impl HealthCurve { + pub fn damage_scale(&self, attacker_health: Option<(i32, u16)>, self_damage: bool, fall: bool, self_exception: bool) -> Option { + if fall { + return Some(1.0); + } + if self_damage { + return self_exception.then_some(1.0); + } + Some(attacker_health.map_or(1.0, |(health, base)| self.scaling(health, base).0)) + } + + pub fn validate(&self) -> Result<(), String> { + let positive = |value: f32| value.is_finite() && value > 0.0; + if self.bands.is_empty() + || self + .bands + .iter() + .any(|band| band.below_percent == 0 || !positive(band.damage) || !positive(band.speed)) + || self.bands.windows(2).any(|pair| pair[0].below_percent >= pair[1].below_percent) + || self.growth_step_percent == 0 + || !positive(self.high_damage) + || !positive(self.high_speed) + || !positive(self.damage_cap) + || !positive(self.speed_cap) + || self.damage_cap < self.high_damage + || self.speed_cap < self.high_speed + || !self.damage_increment.is_finite() + || self.damage_increment < 0.0 + || !self.speed_increment.is_finite() + || self.speed_increment < 0.0 + { + return Err("health_curve needs increasing positive percentage bands, positive finite multipliers/caps and growth step, and non-negative finite increments".into()); + } + Ok(()) + } + + pub fn scaling(&self, health: i32, spawn_health: u16) -> (f32, f32) { + assert!(spawn_health > 0, "spawn health must be validated before computing scaling"); + let numerator = i64::from(health.max(0)) * 100; + let base = i64::from(spawn_health); + for band in &self.bands { + if numerator < base * i64::from(band.below_percent) { + return (band.damage, band.speed); + } + } + let start = i64::from(self.bands.last().expect("validated health curve has bands").below_percent); + let step = i64::from(self.growth_step_percent); + // Keep the legacy integer percentage buckets, including its initial high-health plateau. + let growth = (numerator / (base * step) - start / step) as f32; + ( + (self.high_damage + growth * self.damage_increment).min(self.damage_cap), + (self.high_speed + growth * self.speed_increment).min(self.speed_cap), + ) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HealthDecay { + pub interval: f32, + pub percent: u8, + pub floor_percent: u16, +} + +impl Default for HealthDecay { + fn default() -> Self { + Self { + interval: 2.0, + percent: 5, + floor_percent: 100, + } + } +} + +impl HealthDecay { + pub fn validate(self) -> Result<(), String> { + if !self.interval.is_finite() || self.interval <= 0.0 || self.percent > 100 || self.floor_percent == 0 { + return Err("health_decay_settings needs a positive finite interval, percent between 0 and 100, and a positive floor_percent".into()); + } + Ok(()) + } + + pub fn decay(self, health: i32, spawn_health: u16) -> i32 { + let floor = (i64::from(spawn_health) * i64::from(self.floor_percent) + 99) / 100; + if i64::from(health) <= floor { + return health; + } + ((i64::from(health) * i64::from(100 - self.percent) + 99) / 100).max(floor) as i32 + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(crate) struct HealthCurveInput { + bands: Option>, + growth_step_percent: Option, + high_damage: Option, + high_speed: Option, + damage_increment: Option, + speed_increment: Option, + damage_cap: Option, + speed_cap: Option, +} + +impl HealthCurveInput { + pub(crate) fn resolve(self, defaults: Option<&Self>) -> HealthCurve { + let fallback = HealthCurve::default(); + HealthCurve { + bands: self + .bands + .or_else(|| defaults.and_then(|input| input.bands.clone())) + .unwrap_or(fallback.bands), + growth_step_percent: self + .growth_step_percent + .or_else(|| defaults.and_then(|input| input.growth_step_percent)) + .unwrap_or(fallback.growth_step_percent), + high_damage: self + .high_damage + .or_else(|| defaults.and_then(|input| input.high_damage)) + .unwrap_or(fallback.high_damage), + high_speed: self + .high_speed + .or_else(|| defaults.and_then(|input| input.high_speed)) + .unwrap_or(fallback.high_speed), + damage_increment: self + .damage_increment + .or_else(|| defaults.and_then(|input| input.damage_increment)) + .unwrap_or(fallback.damage_increment), + speed_increment: self + .speed_increment + .or_else(|| defaults.and_then(|input| input.speed_increment)) + .unwrap_or(fallback.speed_increment), + damage_cap: self + .damage_cap + .or_else(|| defaults.and_then(|input| input.damage_cap)) + .unwrap_or(fallback.damage_cap), + speed_cap: self + .speed_cap + .or_else(|| defaults.and_then(|input| input.speed_cap)) + .unwrap_or(fallback.speed_cap), + } + } +} + +#[derive(Clone, Copy, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(crate) struct HealthDecayInput { + interval: Option, + percent: Option, + floor_percent: Option, +} + +impl HealthDecayInput { + pub(crate) fn resolve(self, defaults: Option) -> HealthDecay { + let fallback = HealthDecay::default(); + HealthDecay { + interval: self + .interval + .or_else(|| defaults.and_then(|input| input.interval)) + .unwrap_or(fallback.interval), + percent: self + .percent + .or_else(|| defaults.and_then(|input| input.percent)) + .unwrap_or(fallback.percent), + floor_percent: self + .floor_percent + .or_else(|| defaults.and_then(|input| input.floor_percent)) + .unwrap_or(fallback.floor_percent), + } + } +} diff --git a/crates/funrounds-core/src/lib.rs b/crates/funrounds-core/src/lib.rs index 33ac85c..a874a8e 100644 --- a/crates/funrounds-core/src/lib.rs +++ b/crates/funrounds-core/src/lib.rs @@ -4,6 +4,25 @@ use serde::Deserialize; use std::collections::HashSet; +mod attributes; +pub use attributes::{AttributeRange, AttributeValue, HelmetValue, LifeAttributes, RandomHelmet}; +mod chicken; +pub use chicken::{ + ChickenBlastConfig, ChickenConfig, ChickenDamageCause, ChickenDamageChainConfig, ChickenDamageRule, ChickenEatError, ChickenEatOutcome, + ChickenEatingConfig, ChickenEatingState, ChickenHealConfig, ChickenHealthBasis, ChickenPercentRange, ChickenSpawnConfig, HealthshotConfig, + HealthshotOutcome, filters_chicken_damage_chain, use_healthshot, +}; +use chicken::{ChickenInput, HealthshotInput}; +mod ghost; +use ghost::GhostInput; +pub use ghost::{GhostFrame, GhostPose, GhostSettings, GhostState, ghost_alpha}; +mod afterburn; +use afterburn::AfterburnInput; +pub use afterburn::AfterburnSettings; +mod third_person; +use third_person::ThirdPersonInput; +pub use third_person::ThirdPersonSettings; + mod rounds; pub use rounds::{Capabilities, NextMode, Phase, RoundController, RoundGeneration, RoundKey}; mod players; @@ -14,15 +33,21 @@ pub use rules::{ THROWING_KNIFE_GRAVITY, THROWING_KNIFE_HEAD_DAMAGE, THROWING_KNIFE_HEADSHOT_DISTANCE, THROWING_KNIFE_LIFETIME, THROWING_KNIFE_SPEED, TeamDeathmatch, TeamResult, dodgeball_damage, lifesteal_recovery, low_health_finish, }; -mod classic; +mod health; +use health::{HealthCurveInput, HealthDecayInput}; +mod text; +pub use text::{TextBundle, TextCatalog}; mod combat; pub use combat::{CombatLife, combat_hit, weapon_damage_scale}; mod random_damage; pub use random_damage::{RandomDamage, random_damage}; mod suicide; -pub use suicide::{SuicideSequence, suicide_blast_damage, suicide_in_blast_range}; +pub use suicide::{SuicideSequence, suicide_blast_damage}; mod equipment; -pub use classic::{classic_damage_scale, decay_health, health_scaling, self_push_force}; +mod money; +pub use equipment::{WeaponSlot, self_push_force, weapon_slot}; +pub use health::{HealthBand, HealthCurve, HealthDecay}; +pub use money::{money_floor, money_income_credit, next_money_income_due}; #[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -83,7 +108,7 @@ fn one() -> f32 { 1.0 } -pub const VERSION: &str = "0.2-Alpha Test"; +pub const VERSION: &str = "0.3-Alpha Test 2"; #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -151,10 +176,35 @@ fn default_defuse_time() -> f32 { #[derive(Clone, Debug, PartialEq)] pub struct Config { + pub default_language: String, pub diagnostics: bool, + pub hostage_rescue_compat: bool, + pub prices: CashPrices, + pub warmup: Option, + pub chicken: Option, + /// Presence of `[healthshot]` opts in to replacing native healthshot healing. + pub healthshot: Option, pub modes: Vec, } +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields)] +pub struct CashPrices { + pub c4_cash: u32, + pub healthshot_cash: u32, + pub chicken_cash: u32, +} + +impl Default for CashPrices { + fn default() -> Self { + Self { + c4_cash: 10_000, + healthshot_cash: 4_000, + chicken_cash: 1, + } + } +} + #[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum TeamFilter { @@ -208,6 +258,54 @@ pub enum WinCondition { TeamDeathmatch, } +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum KillLoadoutStart { + Glock, + Random, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum RoundRespawn { + #[default] + Disabled, + Dead, + All, +} + +#[derive(Clone, Copy, Debug, Deserialize)] +#[serde(rename_all = "snake_case")] +enum NamedRoundRespawn { + All, +} + +#[derive(Clone, Copy, Debug, Deserialize)] +#[serde(untagged)] +enum RoundRespawnInput { + Legacy(bool), + Named(NamedRoundRespawn), +} + +impl RoundRespawnInput { + fn resolve(self) -> RoundRespawn { + match self { + Self::Legacy(false) => RoundRespawn::Disabled, + Self::Legacy(true) => RoundRespawn::Dead, + Self::Named(NamedRoundRespawn::All) => RoundRespawn::All, + } + } +} + +impl std::fmt::Display for RoundRespawn { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Disabled => "false", + Self::Dead => "true", + Self::All => "all", + }) + } +} + #[derive(Clone, Copy, Debug, Deserialize, PartialEq)] #[serde(deny_unknown_fields)] pub struct RespawnSettings { @@ -216,6 +314,13 @@ pub struct RespawnSettings { pub delay_seconds: f32, } +#[derive(Clone, Copy, Debug, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct MoneyIncome { + pub interval: f32, + pub amount: u32, +} + #[derive(Clone, Debug, Default, Deserialize)] #[serde(default, deny_unknown_fields)] struct RespawnInput { @@ -233,12 +338,14 @@ pub struct Mode { pub enabled: bool, pub name: String, pub description: String, + pub name_key: Option, + pub description_key: Option, pub weapons: Vec, - pub health: u16, - pub armor: u8, + pub health: AttributeValue, + pub armor: AttributeValue, pub gravity: f32, pub speed: f32, - pub helmet: bool, + pub helmet: HelmetValue, pub clear_weapons: TeamFilter, pub give_weapons: TeamFilter, pub give_knife: TeamFilter, @@ -250,6 +357,9 @@ pub struct Mode { pub taser_charge: Option, pub bunnyhop: Option, pub friction: Option, + pub time_scale: Option, + pub ground_acceleration: Option, + pub ground_reverse: Option, pub no_spread: Option, pub no_recoil: bool, pub recoil_view: Option, @@ -259,11 +369,16 @@ pub struct Mode { pub suicide: bool, pub random_damage: bool, pub kill_loadout: bool, + pub kill_loadout_start: Option, pub lifesteal: bool, pub reflect_damage: Option, pub energy_shield: bool, - pub combat_protection: bool, + pub spawn_protection: bool, + pub kill_protection: bool, pub translucent: bool, + pub ghost: Option, + pub afterburn: Option, + pub third_person: Option, pub delayed_damage: bool, pub win_condition: WinCondition, pub bomb: Option, @@ -276,21 +391,87 @@ pub struct Mode { pub health_damage: bool, pub health_speed: bool, pub health_decay: bool, + pub health_curve: HealthCurve, + pub health_decay_settings: HealthDecay, pub self_push: bool, pub periodic_speed: bool, pub periodic_gravity: bool, pub c4_count: Option, pub c4_buy: bool, - pub round_respawn: bool, + pub round_respawn: RoundRespawn, + pub hide_radar: Option, + pub hide_player_identification: Option, pub respawn: Option, pub buy_time: Option, pub buy_limit: Option, + pub round_money_floor: Option, + pub money_income: Option, + pub buy_access: Option, + pub buy_anywhere: Option, pub friendly_fire_scale: Option, pub teammates_as_enemies: Option, pub random_spawn: Option, pub drop_weapons: Option, pub drop_grenades: Option, + pub shoot_dropped_grenades: Option, pub fall_damage_scale: Option, + pub ordinary_chickens: bool, + pub chicken_eating: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct WarmupConfig { + pub enabled: bool, + pub mode: Mode, +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct WarmupInput { + respawn_delay: Option, + #[serde(flatten)] + mode: ModeInput, +} + +impl WarmupInput { + fn into_config(mut self) -> Result { + if self.mode.id.is_some() + || self.mode.name.is_some() + || self.mode.description.is_some() + || self.mode.name_key.is_some() + || self.mode.description_key.is_some() + { + return Err("[warmup] may contain capability settings and enabled only".into()); + } + if self.respawn_delay.is_some() && self.mode.respawn.is_some() { + return Err("warmup: use respawn_delay or respawn, not both".into()); + } + let enabled = self.mode.enabled.unwrap_or(true); + self.mode.id = Some("warmup".into()); + self.mode.enabled = Some(true); + self.mode.name_key = Some("warmup.name".into()); + self.mode.description_key = Some("warmup.description".into()); + // Preserve the original warmup defaults, independently of [defaults]. + let defaults = ModeInput { + health: Some(AttributeValue::Fixed(100)), + armor: Some(AttributeValue::Fixed(100)), + clear_weapons: Some(TeamFilter::All), + give_weapons: Some(TeamFilter::All), + give_knife: Some(TeamFilter::All), + ammo: Some(Ammo::Reserve), + fast_switch: Some(true), + self_push: Some(true), + respawn: Some(OptionalOverride::Value(RespawnInput { + team: Some(TeamFilter::All), + delay_seconds: Some(self.respawn_delay.unwrap_or(1.0)), + })), + ..ModeInput::default() + }; + Ok(WarmupConfig { + enabled, + mode: self.mode.into_mode(&defaults)?, + }) + } } #[derive(Clone, Debug, Deserialize)] @@ -307,6 +488,13 @@ struct WeaponDamageOverride { knife: Option, } +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +enum HudElement { + Radar, + Crosshair, +} + #[derive(Clone, Debug, Default, Deserialize)] #[serde(default, deny_unknown_fields)] struct ModeInput { @@ -314,12 +502,14 @@ struct ModeInput { enabled: Option, name: Option, description: Option, + name_key: Option, + description_key: Option, weapons: Option>, - health: Option, - armor: Option, + health: Option, + armor: Option, gravity: Option, speed: Option, - helmet: Option, + helmet: Option, clear_weapons: Option, give_weapons: Option, give_knife: Option, @@ -331,6 +521,9 @@ struct ModeInput { taser_charge: Option>, bunnyhop: Option, friction: Option>, + time_scale: Option>, + ground_acceleration: Option>, + ground_reverse: Option>, no_spread: Option, no_recoil: Option, recoil_view: Option>, @@ -340,9 +533,12 @@ struct ModeInput { suicide: Option, random_damage: Option, kill_loadout: Option, + kill_loadout_start: Option, lifesteal: Option, reflect_damage: Option>, energy_shield: Option, + spawn_protection: Option, + kill_protection: Option, combat_protection: Option, translucent: Option, delayed_damage: Option, @@ -354,24 +550,39 @@ struct ModeInput { no_scope: Option, fov: Option>, hide_crosshair_after: Option>, + hide_hud: Option>, health_damage: Option, health_speed: Option, health_decay: Option, + health_curve: Option, + health_decay_settings: Option, self_push: Option, periodic_speed: Option, periodic_gravity: Option, c4_count: Option>, c4_buy: Option, - round_respawn: Option, + round_respawn: Option, + hide_radar: Option, + hide_player_identification: Option, respawn: Option>, buy_time: Option, buy_limit: Option, + round_money_floor: Option>, + money_income: Option>, + buy_access: Option>, + buy_anywhere: Option>, friendly_fire_scale: Option, teammates_as_enemies: Option, random_spawn: Option, drop_weapons: Option, drop_grenades: Option, + shoot_dropped_grenades: Option, fall_damage_scale: Option, + ordinary_chickens: Option, + chicken_eating: Option, + ghost: Option>, + afterburn: Option>, + third_person: Option>, } #[derive(Deserialize)] @@ -380,14 +591,41 @@ struct RawConfig { #[serde(default)] diagnostics: bool, #[serde(default)] + hostage_rescue_compat: bool, + #[serde(default)] + prices: CashPrices, + chicken: Option, + healthshot: Option, + #[serde(default)] defaults: ModeInput, + warmup: Option, modes: Vec, + #[serde(default)] + i18n: I18nInput, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct I18nInput { + default_language: String, +} + +impl Default for I18nInput { + fn default() -> Self { + Self { + default_language: "zh-CN".into(), + } + } } fn choose(mode: Option, defaults: Option, fallback: T) -> T { mode.or(defaults).unwrap_or(fallback) } +fn choose_protection(mode: Option, legacy: Option, defaults: Option, default_legacy: Option) -> bool { + mode.or(legacy).or(defaults).or(default_legacy).unwrap_or(false) +} + fn choose_optional(mode: Option>, defaults: Option>, name: &str) -> Result, String> { fn apply(setting: OptionalOverride, name: &str) -> Result, String> { match setting { @@ -402,6 +640,51 @@ fn choose_optional(mode: Option>, defaults: Option