# 01 — Kiến trúc tổng thể

## 1. Sơ đồ khối

```mermaid
flowchart LR
    subgraph Target["Máy chơi game"]
        GAME["ARES PC Client\n(Crossplay Launcher)"]
        KMB["Virtual KMBox\n(HID thật)"]
        MON["Màn hình"]
        GAME --> MON
        KMB -->|USB HID| GAME
    end

    subgraph Bot["ARES AutoPlay (C++23)"]
        MEM["MemoryReader\n(ReadProcessMemory)"]
        VIS["VisionModule\n(Desktop Duplication API)\n[phương án dự phòng]"]
        DEC["DecisionEngine\n(Behavior Tree)"]
        HUM["Humanizer\n(jitter, delay, overshoot)"]
        INP["InputController\n(KMBox driver)"]
        CFG["ConfigStore\n(offsets.json, profiles)"]
        LOG["Logger / Telemetry"]
    end

    MEM -->|GameState snapshot| DEC
    VIS -.->|snapshot dự phòng| DEC
    DEC -->|ActionCommand| HUM
    HUM -->|InputEvent| INP
    INP -->|UDP / Serial| KMB
    CFG --> MEM
    CFG --> DEC
    CFG --> HUM
    DEC --> LOG
    MEM --> LOG
```

## 2. Bốn module chính

| Module | Vai trò | Tần suất chạy | Chi tiết |
|--------|---------|---------------|----------|
| **MemoryReader** | Đọc process game, dựng `GameState` snapshot (HP, MP, cooldown, entity list, boss state) | 30–60 Hz | [03-memory-module.md](03-memory-module.md) |
| **VisionModule** *(dự phòng)* | Chụp màn hình, OCR/cv nhận diện HP bar, skill icon khi memory bị chặn | 15–30 Hz | Tách file sau khi thiết kế |
| **DecisionEngine** | Chuyển `GameState` → `ActionCommand` qua Behavior Tree + State Machine | 30 Hz (mỗi frame snapshot) | [06-decision-engine.md](06-decision-engine.md) |
| **InputController** | Đưa `InputEvent` qua Virtual KMBox (giả lập HID thật) | theo sự kiện, ≤ 1 kHz | [04-input-module.md](04-input-module.md) |

## 3. Mô hình luồng (threading model)

```
Thread 1: MemoryReader   → đọc bộ nhớ → snapshot ring buffer (lock-free, SPSC)
Thread 2: DecisionEngine → lấy snapshot mới nhất → chạy behavior tree → push ActionCommand
Thread 3: InputWorker    → pop ActionCommand → Humanizer bẻ thành chuỗi InputEvent
                           (di chuyển chuột theo path, delay gauss) → gửi KMBox
Thread 4: Telemetry      → log JSON, health metrics, watch-dog
```

Nguyên tắc:
- **Snapshot-based:** `DecisionEngine` không bao giờ chạm trực tiếp vào process; chỉ đọc snapshot bất biến (`std::shared_ptr<const GameState>`).
- **Lock-free queue** giữa các thread (ring buffer 1 producer–1 consumer) để tránh jitter.
- **Watch-dog:** nếu MemoryReader không snapshot được trong 2s hoặc KMBox mất heartbeat → chuyển sang trạng thái `Paused` an toàn (nhân vật đứng yên, không logout).

## 4. Định nghĩa dữ liệu cốt lõi

```cpp
// GameState snapshot — bất biến, được tạo bởi MemoryReader mỗi tick
struct GameState {
    std::chrono::steady_clock::time_point timestamp;
    PlayerState      player;        // hp, mp, pos, class, suit, skill_cooldowns[]
    std::vector<Entity> entities;   // boss, mobs, players — pos, hp, state_id
    EncounterContext context;       // in_field | in_dungeon | in_raid | in_arena | ui_menu
    UiState          ui;            // dialog mở? loading? dead?
};

// ActionCommand — output của DecisionEngine
struct ActionCommand {
    ActionType type;     // MoveTo, CastSkill, Dodge, SwitchSuit, Interact, Idle
    std::variant<TargetPoint, SkillSlot, ...> payload;
    Priority   priority; // interrupt: Dodge luôn pre-empt CastSkill
};
```

## 5. Chiến lược lỗi (failure strategy)

| Sự cố | Hành vi |
|-------|---------|
| ReadProcessMemory fail liên tục | Fallback sang VisionModule; nếu cả hai fail → `Paused` |
| KMBox heartbeat loss > 3s | Dừng gửi input, log, retry connect (UDP) |
| Game không ở trong combat sau N giây khi bot đang chạy dungeon | Reset behavior tree về trạng thái `Explore` |
| Bot phát hiện nhân vật chết | Chờ revive logic của game hoặc dùng item theo profile |
| Patch game làm vỡ offsets | MemoryReader validate signature trước khi dùng; sai signature → `Paused` + báo lỗi config |
