跳转到内容

Game 模块 ​

Game 模块提供游戏领域层功能,分七个子库:core(实体基元)、world(场景/会话/Avatar)、 session(锚点/在线目录/恢复/编队恢复)、attributes(属性)、attrsync(属性增量同步)、 battle(战斗运行时)、social(组队/公会)。

Entity(apollo::game::core) ​

游戏实体基类。EntityId/PlayerId 强分型互不隐式转换(P0-2:编译器拦住 「把实体 ID 当玩家 ID 传」一类错误);支持组件挂载。

cpp
#include <apollo/game/core/entity.hpp>

using apollo::game::core::EntityId;
using apollo::game::core::Entity;

// 创建实体
Entity entity(EntityId{12345}, "Player");

// 组件挂载(IEntityComponent:get_type_name + on_attach/on_detach/on_update)
entity.add_component<HealthComponent>();
auto health = entity.get_component<HealthComponent>();
if (health) {
    health->take_damage(20);
}

组件系统(IEntityComponent) ​

组件是挂在实体上的行为/数据单元,按类型名索引(unordered_map<string, ComponentPtr>):

cpp
class HealthComponent : public apollo::game::core::IEntityComponent {
public:
    std::string get_type_name() const override { return "health"; }
    void take_damage(int damage) { hp_ = std::max(0, hp_ - damage); }

private:
    int hp_ = 100;
};

AOI 系统(SceneAoi) ​

全仓唯一 AOI 实现(P1-3 收敛后):apollo::game::world::SceneAoi,Scene 独享、 按 scene 隔离;ViewerState 记录逐观察者视野水位(Enter/Sync/Leave 差集基准)。

cpp
#include <apollo/game/world/scene_aoi.hpp>

// 创建兴趣管理(宽、高、格子、视野半径)
apollo::game::world::SceneAoi aoi(1000.0f, 1000.0f, 100.0f, 200.0f);

// 事件面(Enter / Sync / Leave;sink 缺省静默)
aoi.set_event_sink([](const apollo::game::world::SceneAoi::Event& e) {
    // e.observer / e.subject
});

// 实体进入 / 移动 / 离开
aoi.enter(apollo::game::core::EntityId{1}, {100.0f, 0.0f, 100.0f});
aoi.move(apollo::game::core::EntityId{1}, {200.0f, 0.0f, 100.0f});

// 查询:位置点的视野 / 实体的观察者集
auto nearby = aoi.viewers_at({100.0f, 0.0f, 100.0f});
auto observers = aoi.viewers_of(apollo::game::core::EntityId{1});

aoi.leave(apollo::game::core::EntityId{1});

下发到网关的广播面留 P3-2;属性管线对 AOI 事件的消费已接线(批 5,Scene::attach_attrsync)。

战斗系统(battle 子库) ​

三层:BattleSystem(场景内实体集合登记 + tick 骨架)、BattleRuntime (确定性战斗域——BattlePhase 状态机、逻辑拍 + wall clock 双时间轴、RNG 子流契约,battle-determinism 批交付)、BattleReplay(ReplayTuple 回放面)。

cpp
#include <apollo/game/battle/battle_system.hpp>
#include <apollo/game/battle/battle_runtime.hpp>

apollo::game::battle::BattleSystem battle;
battle.add_entity(std::make_shared<apollo::game::core::Entity>(EntityId{1}));
battle.update(0.1f);

ECS 收敛已随 P2-1 交付(battle::ecs 全支删除,实体集合归 Scene)、 BattleRuntime 确定性域与状态机随 P2-2 交付(五段相位 + Instance 挂接 + IRewardSink 单向结算);技能/Buff 玩法面随玩法批。 旧稿里的 ECSWorld/ECSSystem API 在仓库中不存在。

会话与目录(session 子库,G-1 交付面) ​

长期玩家态/在线目录/恢复/编队恢复九头(base 五件 + session 四件):base 侧 AvatarManager/Avatar(长期玩家态唯一写点)+ AvatarRewardSink(结算落账)+ RecoveryCoordinator(journal replay → Avatar restore → 准入闸)+ WorldAssignment;session 侧 PlayerDirectory(在线目录,epoch/suspend 窗口/重报收敛)+ DirectoryPublisher("APD2" 目录镜像)+ FleetRecoveryCoordinator(恢复相位跨进程化)+ SessionLocator。 API 明细见 Game API 与 session-and-online-directory 设计件。

社交(social 子库) ​

Party / Guild 组队与公会基础容器(跨服同步语义挂拍板链,未接线)。

属性系统(attributes) ​

AttributeContainer(按 objectId 承载属性值,Set/Get/Add + 变更监听)+ AttributeManager(属性定义注册与容器生命周期,RegisterAttribute/ CreateContainer/LoadFromConfig)。头文件在顶层 include/apollo/game/attributes/。

cpp
#include <apollo/game/attributes/attribute.hpp>

auto& manager = apollo::AttributeManager::Instance();
manager.RegisterAttribute(def);                      // AttributeDef:id+类型+默认值
auto container = manager.CreateContainer(objectId);  // 每实体一个容器
container->SetAttribute(attributeId, value);         // AttributeValue
AttributeValue out;
container->GetAttribute(attributeId, out);
container->SetChangeListener([](const AttributeChangeEvent& e) { /* 变更上报 */ });

逐 viewer 的 delta 同步管线核心层 + Scene AOI 接线已落地(见下方 attrsync 子库)。

属性增量同步(attrsync 子库) ​

per-viewer delta 管线(attribute-sync §3.1/§3.2/§3.3/§4.1/§5/§7.1/§8.2),十二批交付:

件职责
ChangeHistory序号化变更环形日志(每实体一份,容量默认 1024)
ViewerAttrStateper-viewer acked_seq 水位(每 (viewer, entity) 二元组)
AttrDeltavarint/zigzag 编码(attr_id + value + change_n)
AttrDomain属性可见域(批 9):kPublic/kSelf/kTeam/kGuild/kWorld
DeltaBuilderdelta 组装 + 快照切换判定;快照时 deltas 填全量当前值(批 8);快照与 delta 双路径域裁剪(批 9)
EntityAttrs每实体属性存储 + dirty 位 + ChangeHistory + 域位表(批 9)
AttrSyncManager实体注册、属性写路径、AOI Enter/Leave、broadcast collect、ACK、ACK 超时降级、peek(只读预检)、ChangeSink(§8.2 写后日志入口)、域投影 set_attr_domain/set_group_gate(批 9)、属性钩子窗口注入点(scripting-lua §5.1:set_attr_hook/apply_attr_hook,批 10)
AttrSyncScheduler§5 优先级与节流:token bucket + 优先级排序 + min_interval + 饥饿保护
FrameCodecAttrSyncFrame ↔ wire bytes(varint 编码 + 批量)
Scene::attach_attrsyncScene ↔ AOI 事件接线(批 5):Enter/Sync 首见 → 快照帧,Leave → 回收 viewer 态
Scene::attach_scriptScene × ScriptRuntime 适配桥(scripting-lua §5.1 宿主接线,批 12):Recalc 尾 Collect 前跑钩子窗口,帧预算默认 200k 可调
cpp
#include <apollo/game/attrsync/attr_sync_manager.hpp>

apollo::game::attrsync::AttrSyncManager mgr;
mgr.register_entity(/*entity_id=*/42);
mgr.set_attribute(42, /*attr_id=*/1, /*value=*/100);

// AOI Enter → 建 ViewerState + 返回快照帧
auto frames = mgr.on_viewer_enter_collect(/*viewer=*/100, 42);

// Broadcast tick → 收集 per-viewer delta 帧
auto delta = mgr.collect(100, 42);

// ACK → 推进 acked_seq + 解除降级
mgr.ack(100, 42, /*seq=*/delta[0].base_seq + delta[0].deltas.size());

// ACK 超时降级:静默 ≥ 阈值拍 → 每拍快照重置
mgr.set_ack_timeout_ticks(3);
bool degraded = mgr.is_degraded(100, 42);

// §5.1 属性钩子窗口(scripting-lua §5.1):dirty 固定后、collect 前注入式修订。
// 白名单/预算/错误隔离由宿主实现注入(如适配 ScriptRuntime::run_attr_hook_window);
// 修订值经正规写路径落存储+history,builder last-write-wins 收敛为单条最终值。
mgr.set_attr_hook([](std::vector<apollo::game::attrsync::AttrSyncManager::HookChange>& changes) {
    for (auto& c : changes) { /* 宿主窗口实现 */ }
});
mgr.apply_attr_hook();  // 每拍 collect 前调用;无钩子空载零开销;同 tick 幂等

Scene 侧接线(批 5):

cpp
#include <apollo/game/world/scene.hpp>

apollo::game::world::Scene scene("s1");
scene.attach_attrsync(mgr);   // 接管 AOI 事件 sink + 补注册既有实体
// ... spawn_entity / enter 即时注册 ...
auto frames = scene.drain_attrsync_frames();  // 取走首见期快照帧
scene.detach_attrsync();

Scene × ScriptRuntime 适配桥(批 11,scripting-lua §5.1 宿主接线):

cpp
#include <apollo/script/script_runtime.hpp>

apollo::script::ScriptRuntime rt(cfg);
rt.set_attr_hook("onAttrChanged");   // 钩子函数注册(修订返回整数)
rt.load_contract(contract_src);        // 白名单取契约表数据面(§3.4)

scene.attach_script(rt);              // 与 attach_attrsync 共架桥(次序无关)
scene.set_attr_hook_frame_budget(200000);  // §5.2 帧级预算(默认 200k ≈ 0.5ms)

// tick 接线(Scene::tick 六阶段内):
//   set_tick 喂熔断/WARN 记账 → Recalc 尾 apply_attr_hook 跑窗口(白名单外跳过、
//   帧预算耗尽剩余跳过、错误保持原值)→ Collect 出修订 delta → BudgetFlush 归还帧账

§7.1 admin attach 执行队列(scripting-lua §7.1 宿主接线批):

cpp
// 投递(任意线程,队列自持互斥——Scene 唯一跨线程面)
scene.enqueue_debug_eval(/*id=*/9001, "counter");  // 队列满/未 attach 拒收 false
// Scene::tick 首拍固定调试点执行(eval_debug 语义全管辖:预算/限流/截断),
// 结果按 id 关联回传;未取走的结果按深度上限丢最旧
for (const auto& r : scene.drain_debug_eval_results()) { /* 回传 transport */ }
scene.set_debug_eval_queue_depth(8);  // 默认 8(与 eval 同 tick 限流对齐)

owning 宿主接线首批已落 world 应用(scripting-lua §2 一状态一逻辑线程):World gameThread 开头建 ScriptRuntime、--script-boot <file> 加载 boot 源(缺失/失败仅告警不停机,fault 走 runtime 事件面)。宿主启动装载序(scripting-lua §3.4)= --script-handlers(契约路由 handler 面)→ --script-contract(契约表,装载闸逐 route 验 handler 已在位)→ --script-boot(可读 contract 全局);契约路由 handler 面占位模块随仓 apps/world/scripts/contract_handlers.lua(45 路由,玩法批按语义填实体),golden 契约同步闸 contract_handler_tests 2 用例 + 启动装载 world_app_script_host_tests 3 用例(含 boot 源先于契约落地断言、缺 handler 拒载、契约文件缺失继续服务)、每拍幂等补挂未挂 scene(新 scene 下一拍生效)、停机尾扫摘挂全部 scene 后随线程析构;find_scene(scene_id) 为宿主对外的投递定位面(runtime 指针不外露)。admin 单入口 transport 已落(944/945 M1 裸帧族:World 侧 dispatcher 受理——未挂/背压即时回 945 拒收,受理挂关联账待 tick 窗口 drain 异步回传;admin 侧 fleetctl eval 入口;world_app_m1_link_tests eval 族 3 用例 + world_app_script_host_tests 7 用例)。

边界:客户端发送路径、slice 复合类型、attach transport(admin 单入口 + control 通道转发到目标进程)均为后续批次。

NPC AI ​

未实现(2026-10-04 对账):apollo/game/ai/ai_controller.hpp 不存在, 仓库无 AI/寻路模块(旧 9 批次计划的寻路批次未列入主线,见 todo.md 遗留登记)。

依赖 ​

  • apollo::core
  • apollo::base

链接 ​

cmake
target_link_libraries(my_app
    apollo::game_core
    apollo::game_world
    apollo::game_session
    apollo::game_attributes
    apollo::game_attrsync
    apollo::game_battle
    apollo::game_social
)

基于 MIT 许可发布