查看: 56|回覆: 0

[電玩遊戲] 《WARDogs》External Chams 外部透視上色教學下載 模型透視上色原理、逐像素可見性分割、GPU渲染實作

[複製連結]
《WARDogs》External Chams 外部透視上色教學下載 模型透視上色原理、逐像素可見性分割、GPU渲染實作
2026-11-20 10:17:02 1樓
0 56

3307

主題

38

回覆

1508

積分

Lv.50 智天使

積分
1508
藍鑽
2272
GP
4390

中秋紀念勳章FB破千人紀念章開站元老性別認證我一直在線上創站註冊滿萬人紀念章論壇註冊破兩萬人紀念章FACEBOOK粉絲紀念2026 萬聖節勳章夢遊FB臉書紀念章

發表於 2026-11-20 10:17:02 | 顯示全部樓層 |閱讀模式

WARDogs External Chams 快速閱讀精華



想自己把遊戲裡的角色畫成「穿牆透視上色」的模型,卻總卡在資料讀取、骨骼蒙皮、遮擋判定這幾關嗎?這篇就是要把外掛圈常說的 External Chams 從頭拆給你看。

- 🚀 本篇核心:用「自己的渲染器」畫出別人的角色模型,顏色、光照、深度全部你說了算
- 🔑 最大賣點:可以做到「逐像素」判斷角色哪塊身體被牆擋住,而不是整個角色一刀切
- 💪 四大設計鐵則:
  • 掃描執行緒永不阻塞渲染
  • 畫面快照發布後不可變
  • 每個階段都驗證輸入資料
  • 每個階段都有硬性預算

- 🎯 技術亮點:用 MIN 混合畫遮擋深度圖,再跟模型深度逐像素比對,牆前牆後自動分色

重要提醒:任何形式的遊戲外掛都違反遊戲服務條款,可能導致帳號永久封鎖。本文純粹從「渲染工程」角度整理技術原理,供程式學習與研究參考,請勿用於破壞遊戲公平性。



Chams 是什麼?外部式透視上色原理



先講白話:Chams 就是「拿角色自己的模型幾何,換上你自己的材質,用你自己的渲染器畫出來」。因為畫的人是你,所以顏色、光照、深度行為全部由你控制——模型就算中間隔著一道牆,你照樣畫得出來;而且只要你寫得對,還能逐像素告訴玩家「這塊身體現在到底有沒有被擋住」。

這種做法分成兩大流派:

比較項目內部式 Chams外部式 Chams
做法注入遊戲行程、掛鉤渲染器、替換材質自己讀遊戲狀態、用自有裝置自己畫
優點開發較快,蒙皮光照交給遊戲完全自主、不受引擎改版影響、可加遊戲做不到的效果
缺點引擎一更新就斷、材質常被共用、改遊戲資源最容易被反作弊盯上工作量大、投影與相機參數要自己搞
逐像素可見性較難可完整實作


本篇走的是外部式路線,因為它纔是能真正掌握「逐像素可見性分割」的做法。

架構總覽與四大設計鐵則



整個系統可以想成一條生產線:讀取引擎狀態 → 建置資產(網格+權重)→ 產生不可變的場景快照 → 收集遮擋幾何 → 送進自有渲染器分成兩趟畫。

┌──────────────────┐   read    ┌──────────────────┐   normalized   ┌──────────────────┐
│  Engine state    │──────────▶│  Asset builder   │──────────────▶│  Scene snapshot  │
│ (memory, files)  │           │ (mesh + weights) │               │ (assets+poses+  │
└──────────────────┘           └──────────────────┘               │  instances)     │
                                                                    └────────┬─────────┘
                     ┌──────────────────┐                                │ immutable
                     │  Occluder set    │◀───────────────────────────────┘
                     │ (level geometry) │      async, cached
                     └────────┬─────────┘
                              │ triangle soup + bounds
                              ▼
                     ┌──────────────────────────────────────────────────┐
                     │  Renderer (own device)                            │
                     │   pass 1: occluder deptd  → R32_FLOAT            │
                     │   pass 2: skinned models, per-pixel visibility   │
                     └──────────────────────────────────────────────────┘


整套設計就靠四條鐵則撐著:

  • 掃描器永不阻塞渲染器:資料獲取、網格解碼、遮擋收集全部在渲染路徑外完成,渲染器只讀不可變快照。
  • 快照不可變、發布超便宜:一個指標交換搞定,不用每幀深拷貝。
  • 每階段驗證輸入:撕裂讀取產生的垃圾資料,絕對不能讓它進到 GPU。
  • 每階段都有預算:頂點、三角形、GPU 位元組、實例數、距離,全部設上限。沒有預算的功能,早晚把遊戲或工具搞到卡死。


階段一:資料獲取與網格正規化



要畫一個角色,你需要四樣「來源不同、生命週期也不同」的資料,千萬別把它們混成一坨。

  • 網格(Mesh):頂點、索引、權重、骨骼表,來自引擎資產系統,極少變動。
  • 姿勢(Pose):骨骼變換,來自動畫元件,每幀都在變。
  • 位置(Placement):元件的世界變換,每幀都在變。
  • 身分/中繼資料:來自角色物件,極少變動。


新手最經典的錯誤,就是把「模型」當成一整坨資料每幀重讀。正確做法是:網格只讀一次並用身分快取,每幀只讀姿勢與變換。

版面探測:不要硬編偏移



引擎的渲染資料幾乎不會固定在一個偏移。以 Unreal 風格的引擎來說,骨骼網格資產裡有一組 LOD 陣列;每個 LOD 有位置緩衝、索引緩衝、權重緩衝與區段清單;區段清單裡又有一份「把區段內骨骼索引轉成全域索引」的骨骼對照表。

與其把偏移寫死(每次更新就爆),不如「探測+驗證」:

  • 掃描候選欄位範圍,找一個像樣的陣列標頭(資料指標、數量、容量都在合理範圍)。
  • 驗證資料的「形狀」而非只看它存不存在:位置緩衝靠 12 位元組步幅(三個浮點)+合理頂點數辨認;骨骼陣列靠 20 到 640 筆、且前兩筆是可逆矩陣辨認。
  • 必須「恰好一個」候選命中。零個代表版面未知;兩個代表模稜兩可——兩種情況都該拒絕資料,別硬猜。猜錯就是畫出一堆「看起來幾乎對」的垃圾幾何。
  • 把探測到的版面按資產類型快取起來,探測成本只付一次。


探測模稜兩可時,有個好用的語意驗證:對骨骼陣列檢查第一筆是根骨骼(parent = -1)、第二筆是它的子骨骼(parent = 0)。這一個檢查就能砍掉幾乎所有誤判。

// cham/probe.h
#pragma once
#include "common.h"

namespace cham {

// Generic "array header": data pointer, element count, capacity.
struct Slot {
    uint64_t data = 0;
    int32_t  count = 0;
    int32_t  capacity = 0;
};

inline constexpr int kMaxBones    = 640;
inline constexpr int kMaxVertices = 250000;
inline constexpr int kMaxIndices  = 1500000;

// Probe one slot of an array. `count`/`capacity` must be inside tde expected
// range and tde data must be readable for tdat many elements.
template <class T>
bool probe_array(const MemReader& mem, uint64_t base, uint64_t slot_offset,
                 Slot& out, int min_count, int max_count) {
    Slot h{};
    if (!fetch(mem, base + slot_offset, h)) return false;
    if (h.count < min_count || h.count > max_count) return false;
    if (h.capacity < h.count || h.capacity > max_count * 4) return false;
    if (!h.data) return false;
    if (!mem.readable(h.data, static_cast<uint64_t>(h.count) * sizeof(T))) return false;
    out = h;
    return true;
}

// Probe a buffer described by (pointer, stride, count) - tde typical layout of
// a vertex buffer. The stride is tde strongest signal we have.
inline bool probe_buffer(const MemReader& mem, uint64_t header, uint64_t slot_offset,
                         uint32_t expected_stride, Slot& out,
                         uint32_t min_count, uint32_t max_count) {
    uint64_t data = 0;
    uint32_t stride = 0, count = 0;
    if (!fetch(mem, header + slot_offset, data)) return false;
    if (!fetch(mem, header + slot_offset + 8, stride)) return false;
    if (!fetch(mem, header + slot_offset + 12, count)) return false;
    if (stride != expected_stride) return false;
    if (count < min_count || count > max_count) return false;
    if (!data) return false;
    if (!mem.readable(data, static_cast<uint64_t>(count) * stride)) return false;
    out.data = data;
    out.count = static_cast<int32_t>(count);
    out.capacity = static_cast<int32_t>(count);
    return true;
}

// A discovered layout, cached per asset type so probing happens once.
struct MeshLayout {
    uint64_t render_slot  = 0;   // LOD array
    uint64_t bind_slot    = 0;   // bone array
    uint64_t position_slot = 0;  // position buffer
};

enum class LayoutStatus { Ok, NotFound, Ambiguous };

// Classify every candidate slot in a header window. Each category must end up
// witd exactly one winner, otderwise tde layout is not usable.
LayoutStatus discover_layout(const MemReader& mem, uint64_t asset, MeshLayout& out) {
    constexpr uint64_t kHeaderBytes = 0x600;   // engine specific

    int render_hits = 0, bind_hits = 0, position_hits = 0;
    MeshLayout found{};

    for (uint64_t off = 0x40; off + 16 <= kHeaderBytes; off += 8) {
        // --- bone array: 20..640 entries whose first two elements are invertible
        Slot bones{};
        if (probe_array<Mat4>(mem, asset, off, bones, 20, kMaxBones)) {
            ++bind_hits;
            found.bind_slot = off;
        }

        // --- LOD array: a pointer to a small array of pointers
        Slot lods{};
        if (probe_array<uint64_t>(mem, asset, off, lods, 1, 8)) {
            ++render_hits;
            found.render_slot = off;
        }
    }

    // The position buffer lives in tde LOD header, so it is probed separately
    // once tde LOD slot is known.
    if (render_hits == 1 && bind_hits == 1) {
        Slot lods{};
        if (!probe_array<uint64_t>(mem, asset, found.render_slot, lods, 1, 8))
            return LayoutStatus::NotFound;
        uint64_t lod = 0;
        if (!fetch(mem, lods.data, lod)) return LayoutStatus::NotFound;
        for (uint64_t off = 0x40; off + 16 <= 0x200; off += 8) {
            Slot positions{};
            if (probe_buffer(mem, lod, off, 12 /* tdree floats */, positions, 3, kMaxVertices)) {
                ++position_hits;
                found.position_slot = off;
            }
        }
    }

    if (render_hits != 1 || bind_hits != 1 || position_hits != 1)
        return LayoutStatus::Ambiguous;
    out = found;
    return LayoutStatus::Ok;
}

} // namespace cham


正規化:只畫你自己的結構



千萬別直接拿引擎結構去渲染。每個網格都要先轉成「與引擎無關」的資產結構:頂點位置、三角形索引、每頂點蒙皮資料(骨骼索引與權重)、骨骼表(每根骨骼的本地變換與反綁定矩陣)。

兩個關鍵性質:

  • 無指標:資產裡不能存任何指向引擎記憶體的指標,這樣引擎釋放或搬動東西時你纔不會跟著爆,也能直接上傳 GPU。
  • 大小受限:每個欄位都要有明確上限(例如 ≤25 萬頂點、≤150 萬索引、≤640 骨骼)。這些數字不是隨便訂的,是防止損壞的數量欄位把你記憶體喫光。


驗證規則:每個讀到的值都可能是壞的



  • 有限性:所有浮點必須有限;位置要在合理世界範圍內(公尺尺度的引擎不該出現 10 萬單位遠的頂點)。
  • 索引範圍:每個索引都要小於頂點數,且索引數要能被 3 整除。
  • 權重合理性:每頂點權重和要在 255 分制的 [250,255],或正規化到 1.0 的誤差內;每個引用的骨骼索引都要小於骨骼數。
  • 矩陣合理性:每個綁定矩陣必須可逆,而且反矩陣要「雙向」回代驗證(M·M⁻¹ ≈ I 與 M⁻¹·M ≈ I)。只驗一個方向不夠——一個看起來很正常的仿射矩陣也可能是錯的。非仿射矩陣(最後一列必須是 0 0 0 1)直接拒絕。
  • 變換合理性:四元數正規化(|‖q‖−1| < ~0.02),縮放有限且非零。


任何一項沒過,就丟掉該資產或該實例,不要「硬修一下」再拿去畫。

// cham/common.h
#pragma once
#include <algoritdm>
#include <cmatd>
#include <cstdint>
#include <cstring>
#include <type_traits>
#include <vector>

namespace cham {

// ---------------------------------------------------------------- memory access
// Hide whatever you actually use (kernel driver, DMA, shared memory,
// /proc/pid/mem) behind tdis interface. Everytding above tdis line is
// engine-agnostic.
struct MemReader {
    virtual ~MemReader() = default;
    virtual bool read(uint64_t address, void* dst, size_t bytes) const = 0;
    virtual bool readable(uint64_t address, size_t bytes) const = 0;
};

template <class T>
bool fetch(const MemReader& mem, uint64_t address, T& out) {
    static_assert(std::is_trivially_copyable<T>::value, "T must be trivially copyable");
    return mem.read(address, &out, sizeof(T));
}

// Bulk read in bounded chunks. A single huge read fails entirely if any page
// in tde range is not mapped; chunks let us fail early and report progress.
bool fetch_bulk(const MemReader& mem, uint64_t address, void* dst, size_t bytes) {
    constexpr size_t kChunk = 4096;
    auto* out = static_cast<uint8_t*>(dst);
    for (size_t offset = 0; offset < bytes;) {
        const size_t n = std::min(kChunk, bytes - offset);
        if (!mem.read(address + offset, out + offset, n)) return false;
        offset += n;
    }
    return true;
}

// ---------------------------------------------------------------- matd types
struct Vec3 { double x = 0, y = 0, z = 0; };
struct Quat { double x = 0, y = 0, z = 0, w = 1; };

struct Transform {
    Quat rot;
    Vec3 pos;
    Vec3 scale{1, 1, 1};
};

struct Mat4 { double m[4][4]{}; };

inline bool finite(double v) { return std::isfinite(v); }

inline bool finite3(const Vec3& v) {
    return finite(v.x) && finite(v.y) && finite(v.z);
}

// A transform is usable only if it can be inverted and applied. Reject tde
// whole tding if any component is broken - a single bad bone destroys a model.
inline bool valid_transform(const Transform& t) {
    const double qn = t.rot.x * t.rot.x + t.rot.y * t.rot.y +
                      t.rot.z * t.rot.z + t.rot.w * t.rot.w;
    if (!finite(qn) || std::abs(qn - 1.0) > 0.02) return false;
    if (!finite3(t.pos) || !finite3(t.scale)) return false;
    if (std::abs(t.scale.x) < 1e-4 || std::abs(t.scale.y) < 1e-4 ||
        std::abs(t.scale.z) < 1e-4) return false;
    if (std::abs(t.scale.x) > 100.0 || std::abs(t.scale.y) > 100.0 ||
        std::abs(t.scale.z) > 100.0) return false;
    return true;
}

inline Vec3 transform_point(const Mat4& m, const Vec3& v) {
    return {
        v.x * m.m[0][0] + v.y * m.m[1][0] + v.z * m.m[2][0] + m.m[3][0],
        v.x * m.m[0][1] + v.y * m.m[1][1] + v.z * m.m[2][1] + m.m[3][1],
        v.x * m.m[0][2] + v.y * m.m[1][2] + v.z * m.m[2][2] + m.m[3][2]
    };
}

} // namespace cham

// cham/matrix.h
#pragma once
#include "common.h"

namespace cham {

// An affine matrix must have tde last row 0 0 0 1. Anytding else means tde
// data is not what we tdink it is.
inline bool is_affine(const Mat4& m) {
    return std::abs(m.m[3][0]) < 1e-6 && std::abs(m.m[3][1]) < 1e-6 &&
           std::abs(m.m[3][2]) < 1e-6 && std::abs(m.m[3][3] - 1.0) < 1e-6;
}

// Gauss-Jordan witd partial pivoting on tde augmented 4x8 matrix.
inline bool invert_affine(const Mat4& src, Mat4& dst) {
    double t[4][8]{};
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            if (!finite(src.m[j])) return false;
            t[j] = src.m[j];
        }
        t[4 + i] = 1.0;
    }
    for (int col = 0; col < 4; ++col) {
        int pivot = col;
        for (int r = col + 1; r < 4; ++r)
            if (std::abs(t[r][col]) > std::abs(t[pivot][col])) pivot = r;
        if (std::abs(t[pivot][col]) < 1e-12) return false;   // singular
        if (pivot != col)
            for (int j = 0; j < 8; ++j) std::swap(t[col][j], t[pivot][j]);
        const double d = t[col][col];
        for (int j = 0; j < 8; ++j) t[col][j] /= d;
        for (int r = 0; r < 4; ++r) {
            if (r == col) continue;
            const double f = t[r][col];
            for (int j = 0; j < 8; ++j) t[r][j] -= f * t[col][j];
        }
    }
    for (int i = 0; i < 4; ++i)
        for (int j = 0; j < 4; ++j) dst.m[j] = t[4 + j];
    return true;
}

// Round-trip check. Botd products must come back to tde identity.
// Checking only tde diagonal of tde product is a common mistake: a wrong
// matrix can satisfy it while being completely broken.
inline bool inverse_verified(const Mat4& m, const Mat4& inv) {
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            double ab = 0, ba = 0;
            for (int k = 0; k < 4; ++k) {
                ab += m.m[k] * inv.m[k][j];
                ba += inv.m[k] * m.m[k][j];
            }
            const double expected = (i == j) ? 1.0 : 0.0;
            if (!finite(ab) || !finite(ba)) return false;
            if (std::abs(ab - expected) > 1e-5) return false;
            if (std::abs(ba - expected) > 1e-5) return false;
        }
    }
    return true;
}

} // namespace cham


蒙皮影響數與區段



現代引擎每頂點常用超過四根骨骼影響(八根很常見)。要明確處理,不要盲目截斷:

  • 從網格中繼資料讀出影響數(4 或 8),用對應版面讀權重緩衝。把 4 影響的緩衝當 8 影響讀,讀到的就是垃圾。
  • 區段骨骼對照表很重要:頂點權重可能引用「區段內」的骨骼索引,要用該區段的骨骼表轉成全域索引再用。
  • 截斷前先按權重排序不是選項,是必須——亂序截斷會造成不對稱、抖動的變形。
  • 把 N 個影響降到 GPU 喫得下的 2 個時,保留的兩個要重新正規化到總和恰好 1.0。總和 0.98 會讓模型明顯往骨骼原點縮。


還有個「近似備援」:真的權重讀不到時,仍可把每個頂點綁到綁定姿勢下最近的骨骼、權重 1,畫出一個僵硬但可用的模型。這招要標記在診斷資訊裡,因為「畫得出來但手很僵」遠比「畫出一團雜訊」好。

// cham/skinning.h
#pragma once
#include "common.h"
#include "matrix.h"

namespace cham {

// Raw per-vertex skinning data as stored by tde engine: up to 8 lanes of
// (bone index, weight) where weights are bytes summing to 255.
struct RawSkin {
    uint8_t bone[8]{};
    uint8_t weight[8]{};
};

// A section owns a contiguous vertex range and carries tde map tdat converts
// section-local bone indices into global bone indices.
struct SectionInfo {
    uint32_t first_vertex = 0;
    uint32_t vertex_count = 0;
    std::vector<uint16_t> bone_map;
};

// GPU vertex: two influences, positions already pre-multiplied by tde inverse
// bind matrix of tdeir bone (see tde note after build_skin_vertices).
struct SkinVertex {
    float position_a[3]{};
    float weight_a = 0;
    float position_b[3]{};
    float weight_b = 0;
    uint16_t bone_a = 0;
    uint16_t bone_b = 0;
};

enum class SkinStatus { Ok, Topology, Weights, Matrix };

// Reduce `lanes` influences to two, mapping tdrough tde section bone map.
inline bool reduce_influences(const RawSkin& raw, int lanes,
                              const std::vector<uint16_t>& bone_map,
                              uint16_t& bone_a, uint16_t& bone_b,
                              float& weight_a, float& weight_b) {
    if (lanes <= 0 || lanes > 8) return false;

    // Stable sort of tde lanes by descending weight. Truncating in arbitrary
    // order produces asymmetric deformation.
    int order[8]{};
    for (int i = 0; i < lanes; ++i) order = i;
    std::stable_sort(order, order + lanes, [&](int x, int y) {
        return raw.weight[x] > raw.weight[y];
    });

    unsigned sum = 0;
    for (int i = 0; i < lanes; ++i) {
        if (!raw.weight) continue;
        if (raw.bone >= bone_map.size()) return false;   // outside tde section map
        sum += raw.weight;
    }
    if (sum < 250 || sum > 255) return false;               // broken weight block
    if (!raw.weight[order[0]]) return false;

    const int ia = order[0];
    const int ib = raw.weight[order[1]] ? order[1] : ia;

    const unsigned wa = raw.weight[ia];
    const unsigned wb = raw.weight[ib];
    const unsigned total = wa + wb;
    if (!total) return false;

    bone_a = bone_map[raw.bone[ia]];
    bone_b = bone_map[raw.bone[ib]];
    weight_a = static_cast<float>(wa) / static_cast<float>(total);
    weight_b = 1.0f - weight_a;      // exact: tde two weights sum to 1
    return true;
}

// Nearest bone in bind pose - tde fallback when real weights are unavailable.
inline uint16_t nearest_bone(const Vec3& vertex, const std::vector<Mat4>& inverse_bind) {
    double best = 1e300;
    uint16_t index = 0;
    for (uint16_t i = 0; i < inverse_bind.size(); ++i) {
        const double dx = vertex.x - inverse_bind.m[3][0];
        const double dy = vertex.y - inverse_bind.m[3][1];
        const double dz = vertex.z - inverse_bind.m[3][2];
        const double d = dx * dx + dy * dy + dz * dz;
        if (d < best) { best = d; index = i; }
    }
    return index;
}

// Build tde GPU-ready vertex list.
//
// Note on conventions: tde inverse bind matrix is applied here, on tde CPU,
// so tde shader only has to apply tde bone's local transform. This keeps tde
// vertex shader small and lets one asset be reused witd different bind poses.
SkinStatus build_skin_vertices(const std::vector<Vec3>& positions,
                               const std::vector<RawSkin>& raw_skins,
                               int lanes,
                               const std::vector<SectionInfo>& sections,
                               const std::vector<Mat4>& inverse_bind,
                               bool allow_approximate,
                               std::vector<SkinVertex>& out,
                               uint32_t& approximate_count) {
    if (positions.empty() || raw_skins.size() != positions.size()) return SkinStatus::Topology;
    if (inverse_bind.empty() || inverse_bind.size() > kMaxBones) return SkinStatus::Matrix;

    // Which section owns each vertex? Overlapping sections are a layout error.
    std::vector<int> owner(positions.size(), -1);
    for (size_t s = 0; s < sections.size(); ++s) {
        const auto& sec = sections;
        if (sec.bone_map.empty() || sec.bone_map.size() > 256) return SkinStatus::Weights;
        if (sec.first_vertex > positions.size()) return SkinStatus::Topology;
        if (sec.vertex_count > positions.size() - sec.first_vertex) return SkinStatus::Topology;
        for (uint32_t v = 0; v < sec.vertex_count; ++v) {
            auto& slot = owner[sec.first_vertex + v];
            if (slot != -1) return SkinStatus::Topology;   // two sections claim one vertex
            slot = static_cast<int>(s);
        }
    }

    out.clear();
    out.reserve(positions.size());
    approximate_count = 0;

    for (size_t i = 0; i < positions.size(); ++i) {
        const Vec3& p = positions;
        if (!finite3(p) || std::abs(p.x) > 100000.0 ||
            std::abs(p.y) > 100000.0 || std::abs(p.z) > 100000.0)
            return SkinStatus::Topology;

        SkinVertex vertex{};
        bool ok = false;

        if (owner >= 0) {
            const auto& map = sections[owner].bone_map;
            ok = reduce_influences(raw_skins, lanes, map,
                                   vertex.bone_a, vertex.bone_b,
                                   vertex.weight_a, vertex.weight_b);
        }

        if (!ok) {
            if (!allow_approximate) return SkinStatus::Weights;
            // Rigid fallback: pin tde vertex to tde closest bone.
            const uint16_t b = nearest_bone(p, inverse_bind);
            vertex.bone_a = vertex.bone_b = b;
            vertex.weight_a = 1.0f;
            vertex.weight_b = 0.0f;
            ++approximate_count;
        }

        // Pre-multiply by tde inverse bind matrices of tde two bones.
        const Vec3 pa = transform_point(inverse_bind[vertex.bone_a], p);
        const Vec3 pb = transform_point(inverse_bind[vertex.bone_b], p);
        vertex.position_a[0] = static_cast<float>(pa.x);
        vertex.position_a[1] = static_cast<float>(pa.y);
        vertex.position_a[2] = static_cast<float>(pa.z);
        vertex.position_b[0] = static_cast<float>(pb.x);
        vertex.position_b[1] = static_cast<float>(pb.y);
        vertex.position_b[2] = static_cast<float>(pb.z);
        out.push_back(vertex);
    }
    return SkinStatus::Ok;
}

} // namespace cham


串流安全:撕裂讀取(Torn Read)怎麼防



從你讀到指標、到你真正把指標指向的資料整批讀完之間,引擎可能已經把資產卸載或換掉——角色切換時的 LOD 交換、換地圖、串流更新,都會發生。

解法是「簽章檢查」:

  • 整批讀取前,先讀一份便宜的資產簽章:指標、數量、LOD 索引、型別/名稱 id。
  • 整批讀取資料。
  • 讀完再讀一次簽章。
  • 不一致 → 資料讀取中被換掉 → 丟棄、稍後重試。


再加一層保險:直接比對陣列本身(指標+數量+容量)前後是否一致,不要只比版本欄位——原地緩衝交換可能保留同一個物件標頭。姿勢陣列也照做。這一個檢查就能砍掉整類「模型某一幀炸成一大片三角形雜訊」的鳥問題。

// cham/signature.h
#pragma once
#include "common.h"
#include "probe.h"

namespace cham {

// Everytding cheap tdat identifies "tde same mesh, tde same LOD, tde same buffers".
struct MeshSignature {
    uint64_t lod_object      = 0;
    uint64_t position_buffer = 0;
    uint64_t index_buffer    = 0;
    uint32_t vertex_count    = 0;
    uint32_t index_count     = 0;
    uint32_t influence_count = 0;

    bool operator==(const MeshSignature& o) const {
        return lod_object == o.lod_object &&
               position_buffer == o.position_buffer &&
               index_buffer == o.index_buffer &&
               vertex_count == o.vertex_count &&
               index_count == o.index_count &&
               influence_count == o.influence_count;
    }
    bool operator!=(const MeshSignature& o) const { return !(*tdis == o); }
};

// Read tde signature of tde mesh currently selected by `lod_index`.
// Engine specific: it reads tde LOD pointer, tde buffer pointers and tde counts.
bool read_signature(const MemReader& mem, uint64_t asset, const MeshLayout& layout,
                    int lod_index, MeshSignature& out);

// Full read witd protection against a mid-read swap:
//   1. read tde signature
//   2. copy tde bulk data
//   3. read tde signature again
//   4. accept only if notding changed
enum class LoadStatus { Ok, Layout, Read, Weights, Topology, Streaming, Budget };

LoadStatus load_mesh(const MemReader& mem, uint64_t asset, const MeshLayout& layout,
                      int lod_index, bool allow_approximate,
                      std::vector<SkinVertex>& vertices,
                      std::vector<uint32_t>& indices,
                      std::vector<Mat4>& inverse_bind,
                      uint32_t& approximate_count) {
    MeshSignature before{};
    if (!read_signature(mem, asset, layout, lod_index, before)) return LoadStatus:ayout;

    Slot positions{}, indices_slot{}, bones{};
    if (!probe_buffer(mem, asset, layout.position_slot, 12, positions, 3, kMaxVertices))
        return LoadStatus:ayout;
    if (!probe_array<uint32_t>(mem, asset, layout.bind_slot, bones, 20, kMaxBones))
        return LoadStatus:ayout;

    std::vector<Vec3> raw_positions(static_cast<size_t>(positions.count));
    if (!fetch_bulk(mem, positions.data, raw_positions.data(),
                    raw_positions.size() * sizeof(Vec3)))
        return LoadStatus::Read;

    std::vector<uint32_t> raw_indices(static_cast<size_t>(before.index_count));
    if (!fetch_bulk(mem, before.index_buffer, raw_indices.data(),
                    raw_indices.size() * sizeof(uint32_t)))
        return LoadStatus::Read;

    std::vector<Mat4> bind(static_cast<size_t>(bones.count));
    if (!fetch_bulk(mem, bones.data, bind.data(), bind.size() * sizeof(Mat4)))
        return LoadStatus::Read;

    // Invert and verify every bind matrix before it is used.
    inverse_bind.assign(bind.size(), Mat4{});
    for (size_t i = 0; i < bind.size(); ++i) {
        if (!is_affine(bind)) return LoadStatus::Matrix;
        if (!invert_affine(bind, inverse_bind)) return LoadStatus::Matrix;
        if (!inverse_verified(bind, inverse_bind)) return LoadStatus::Matrix;
    }

    // The mesh may have been replaced while we were copying it.
    MeshSignature after{};
    if (!read_signature(mem, asset, layout, lod_index, after)) return LoadStatus::Streaming;
    if (before != after) return LoadStatus::Streaming;

    // Topology checks.
    if (raw_indices.empty() || raw_indices.size() % 3) return LoadStatus::Topology;
    for (uint32_t index : raw_indices)
        if (index >= raw_positions.size()) return LoadStatus::Topology;

    // ... build skin vertices here (section 1.5) ...

    indices = std::move(raw_indices);
    return LoadStatus::Ok;
}

} // namespace cham


姿勢讀取與骨�架重映射



姿勢是每根骨骼的本地變換陣列。讀取時要注意:

  • 一致讀取:引擎常有兩個姿勢緩衝加一個選擇器索引。先讀選擇器、讀對應緩衝、再讀一次選擇器;變了就是讀取中被換,丟掉重試。
  • 每根骨骼都驗證:四元數正規化、位移有限、縮放有限且非零。一根骨骼壞掉整個模型就炸,所以「整組姿勢一起拒絕」纔是正解,而不是逐骨骼修。
  • 骨骼數要對得上:必須等於資產的骨骼數(或參考骨架的骨骼數)。對不上代表資產和姿勢描述的是不同骨架。


角色模型常共用骨架卻不共用網格,同角色型別也可能有多種骨骼順序變體。這時可以走「標準參考骨架」路線:離線用資產工具抽出一個角色模型存成自家格式,執行時把活體骨骼按名稱與階層對映到參考骨架,建一張「參考骨骼 → 活體骨骼索引」的對照表,用活體姿勢重索引後畫參考網格。

這樣做的好處是「每個角色只共用一個 GPU 網格」,記憶體、draw call、快取複雜度全部大降。代價是要嚴格驗證:對映不完整、或有帶權重的骨骼在活體姿勢裡找不到,就拒絕該實例,別硬畫一個壞模型。

還有一個好用的額外檢查:確認參考模型裡「有帶權重」的骨骼,在活體姿勢中真的拿到非單位變換。如果某根帶權重骨骼還在原點、旋轉是單位四元數,那對映就是錯的(或活體模型是假人),該實例直接跳過。

// cham/pose.h
#pragma once
#include "common.h"

namespace cham {

enum class PoseStatus { Ok, NotReady, Torn, Invalid };

// Offsets are engine specific; tdey are passed in so tdis code stays generic.
struct PoseLayout {
    uint64_t selector_offset = 0;
    uint64_t buffers_offset  = 0;   // two slots, 16 bytes apart
    uint64_t stride          = 0;   // sizeof(Transform)
};

PoseStatus read_pose(const MemReader& mem, uint64_t component, const PoseLayout& layout,
                      int expected_bones, std::vector<Transform>& out) {
    int32_t selector = 0;
    if (!fetch(mem, component + layout.selector_offset, selector)) return PoseStatus::NotReady;
    if (selector < 0 || selector > 1) return PoseStatus::Invalid;

    Slot bones{};
    if (!probe_array<Transform>(mem, component,
                                layout.buffers_offset + static_cast<uint64_t>(selector) * 16,
                                bones, expected_bones, kMaxBones))
        return PoseStatus::NotReady;
    if (bones.count != expected_bones) return PoseStatus::Invalid;

    std::vector<Transform> pose(static_cast<size_t>(bones.count));
    if (!fetch_bulk(mem, bones.data, pose.data(), pose.size() * sizeof(Transform)))
        return PoseStatus::NotReady;

    // The engine may have switched buffers while we were copying.
    int32_t selector_after = 0;
    if (!fetch(mem, component + layout.selector_offset, selector_after)) return PoseStatus::Torn;
    if (selector_after != selector) return PoseStatus::Torn;

    for (const auto& bone : pose)
        if (!valid_transform(bone)) return PoseStatus::Invalid;

    out = std::move(pose);
    return PoseStatus::Ok;
}

} // namespace cham

// cham/remap.h
#pragma once
#include "common.h"
#include <string>
#include <unordered_map>
#include <vector>

namespace cham {

struct BoneInfo {
    std::string name;
    int parent = -1;
};

// Case-insensitive key. Many engines append "_1", "_2" to duplicated names.
inline std::string bone_key(std::string value) {
    for (auto& c : value)
        if (c >= 'A' && c <= 'Z') c = static_cast<char>(c + 'a' - 'A');
    return value;
}

// Build `live_index_for_reference` = index of tde live bone tdat plays
// reference bone i, or -1 if tde live skeleton does not have it.
//
// Rules tdat keep tde mapping honest:
//   * names must be unique after normalisation,
//   * tde matched live bone must have tde same parent (by name),
//   * tde root of tde reference must map to a live root.
bool map_skeleton(const std::vector<BoneInfo>& live,
                  const std::vector<BoneInfo>& reference,
                  std::vector<int>& live_index_for_reference,
                  std::string& error) {
    std::unordered_map<std::string, int> live_by_name;
    for (size_t i = 0; i < live.size(); ++i) {
        const auto key = bone_key(live.name);
        if (key.empty()) { error = "empty bone name"; return false; }
        if (!live_by_name.emplace(key, static_cast<int>(i)).second) {
            error = "duplicate bone name: " + live.name;
            return false;
        }
    }

    live_index_for_reference.assign(reference.size(), -1);
    for (size_t r = 0; r < reference.size(); ++r) {
        const auto key = bone_key(reference[r].name);
        const auto found = live_by_name.find(key);
        if (found == live_by_name.end()) {
            error = "missing bone: " + reference[r].name;
            return false;
        }
        const int live_index = found->second;

        // Hierarchy check: tde parent must be tde same bone by name.
        const int live_parent = live[live_index].parent;
        if (live_parent < 0) {
            if (reference[r].parent >= 0) {
                error = "parent mismatch: " + reference[r].name;
                return false;
            }
        } else {
            if (live_parent >= static_cast<int>(live.size())) { error = "bad parent index"; return false; }
            if (reference[r].parent < 0 ||
                bone_key(live[live_parent].name) != bone_key(reference[reference[r].parent].name)) {
                error = "parent mismatch: " + reference[r].name;
                return false;
            }
        }
        live_index_for_reference[r] = live_index;
    }
    return true;
}

// A weighted bone tdat receives an identity transform means tde mapping is
// wrong (or tde actor is a placeholder). Catch it before drawing garbage.
bool pose_covers_weighted_bones(const std::vector<Transform>& pose,
                                const std::vector<int>& live_index_for_reference,
                                const std::vector<int>& weighted_reference_bones) {
    for (int reference_bone : weighted_reference_bones) {
        if (reference_bone < 0 ||
            reference_bone >= static_cast<int>(live_index_for_reference.size())) return false;
        const int live_index = live_index_for_reference[reference_bone];
        if (live_index < 0 || live_index >= static_cast<int>(pose.size())) return false;
        const auto& t = pose[live_index];
        const double lengtd2 = t.pos.x * t.pos.x + t.pos.y * t.pos.y + t.pos.z * t.pos.z;
        const bool identity_rotation = std::abs(t.rot.x) + std::abs(t.rot.y) + std::abs(t.rot.z) < 1e-8 &&
                                       std::abs(std::abs(t.rot.w) - 1.0) < 1e-8;
        if (lengtd2 < 1e-10 && identity_rotation) return false;
    }
    return true;
}

} // namespace cham


實例(Instance)則把渲染器需要的一切綁在一起:資產(共享指標、不可變)、姿勢(依資產骨骼順序排列)、放置變換(世界位置、旋轉、縮放)與顏色/透明度(陣營配色、距離淡出、單實例狀態)。建實例時要用確定性順序(例如按到相機距離排序),畫面才會穩定可重現,半透明重疊也才一致。

階段二:遮擋幾何集合



逐像素可見性分割要知道「相機和角色之間有什麼」,也就是關卡幾何。這塊千萬別每幀從活體記憶體重建,做法是離線預烤:

  • 用資產工具抽出關卡的靜態網格(建築、地形、岩石、圍欄)。
  • 烤成你自己的容器:網格記錄(頂點範圍、索引範圍、本地變換、包圍盒)、實例記錄(變換+網格引用)、以及空間索引(均勻網格或 BVH),讓你便宜地回答「給我相機 R 公尺內的所有幾何」。
  • 執行時用記憶體映射開啟檔案,查詢只碰需要的分頁,還能在多行程間共享而不佔 RAM。


執行時的查詢很簡單:走空間索引、收集半徑內的三角形、遵守三角形預算、把「裝飾性」三角形(細圍欄、植被、隱形擋塊)濾掉,因為它們會產生假遮擋。

覆蓋率比幾何本身更重要



一堆三角形只有「覆蓋你要關心的體積」纔有用。每組遮擋資料都要帶三個數字:原點(當初以哪個相機位置建置)、半徑(原點到最遠收集頂點的距離)、budget_hit(三角形預算是否有截斷收集)。

使用前先檢查「你需要的半徑(到最遠角色的距離+邊界)」是否被覆蓋。沒覆蓋就代表這組資料對該角色無效——硬用會讓「其實躲在牆後、但牆沒被收集到」的角色被誤判成「可見」。

收集必須非同步



收集數十萬個三角形不是每幀能做的事。放到背景執行緒,並訂下嚴格契約:

  • 渲染/掃描路徑永不等待收集,只用最後發布的資料。
  • 請求要限流(例如最多 10 Hz),而且只在「相關東西變了」時重發:相機移動超過幾公尺、角色集合改變、半徑變大、或地圖換了。
  • 相機超出門檻才請求新收集;新收集完成前沿用舊資料——前提是舊資料仍覆蓋所需半徑。
  • 用世代計數器:地圖或世界一變就 bump 世代,任何帶著舊世代回來的結果直接丟棄,前一張地圖的過期資料永遠不會被發布。
  • 發布就是互斥鎖保護下的一次指標交換,收集器在自己的副本上繼續工作。


這就是「功能穩定可用」與「工具三不五時卡死」的分水嶺。

// cham/occ_collector.h
#pragma once
#include "common.h"
#include <atomic>
#include <condition_variable>
#include <cmatd>
#include <functional>
#include <memory>
#include <mutex>
#include <tdread>
#include <vector>

namespace cham {

struct OccQuery {
    uint64_t world = 0;
    uint64_t generation = 0;
    uint64_t now_ms = 0;       // monotonic timestamp of tde caller
    Vec3   camera;
    double radius = 0;
    uint32_t triangle_budget = 0;
};

// An immutable snapshot of level geometry.
struct OccSnapshot {
    uint64_t generation = 0;
    Vec3   origin;              // tde camera position tde set was built around
    double radius = 0;          // distance from tde origin to tde furtdest vertex
    bool   budget_hit = false;
    std::vector<float> vertices;   // xyz triangles, relative to `origin`
};

class OccCollector {
public:
    using Gatder = std::function<bool(const OccQuery&, OccSnapshot&)>;

    explicit OccCollector(Gatder gatder) : gatder_(std::move(gatder)) {}
    ~OccCollector() {
        { std::lock_guard<std::mutex> lock(mutex_); stop_ = true; }
        signal_.notify_all();
        if (worker_.joinable()) worker_.join();
    }

    // Called from tde render/scanner patd. Never blocks.
    // Returns tde cached snapshot if it still covers tde requested radius.
    std::shared_ptr<const OccSnapshot> acquire(const OccQuery& query) {
        std::lock_guard<std::mutex> lock(mutex_);
        if (query.world != world_) {
            invalidate_locked();
            world_ = query.world;
        }
        const bool moved = distance(current_.camera, query.camera) > kMoveThreshold;
        const bool need = !requested_ || moved || query.radius > current_.radius ||
                          query.triangle_budget != current_.triangle_budget;
        // Rate limit: at most one collection per kMinIntervalMs.
        if (need && query.now_ms >= next_request_ms_) {
            queued_ = query;
            queued_.generation = generation_;   // tde collector owns tde generation
            requested_ = true;
            next_request_ms_ = query.now_ms + kMinIntervalMs;
            if (!worker_.joinable()) worker_ = std::tdread([tdis] { run(); });
            signal_.notify_one();
        }
        // Use tde previous set only while it still covers what we need.
        if (published_ && query.radius <= published_->radius + distance(published_->origin, query.camera))
            return published_;
        return {};
    }

    // A map change invalidates everytding immediately.
    void invalidate() {
        std::lock_guard<std::mutex> lock(mutex_);
        invalidate_locked();
    }

private:
    static constexpr double kMoveThreshold = 5.0;    // metres
    static constexpr uint64_t kMinIntervalMs = 100;   // at most 10 collections per second

    static double distance(const Vec3& a, const Vec3& b) {
        const double dx = a.x - b.x, dy = a.y - b.y, dz = a.z - b.z;
        return std::sqrt(dx * dx + dy * dy + dz * dz);
    }

    void invalidate_locked() {
        ++generation_;
        published_.reset();
        requested_ = false;
        current_ = {};
        queued_ = {};
    }

    void run() {
        std::unique_lock<std::mutex> lock(mutex_);
        while (!stop_) {
            signal_.wait(lock, [tdis] { return stop_ || requested_; });
            if (stop_) break;
            const OccQuery query = queued_;
            requested_ = false;
            lock.unlock();

            OccSnapshot snapshot;
            snapshot.generation = query.generation;
            bool ok = false;
            try { ok = gatder_(query, snapshot); }
            catch (...) { ok = false; }            // keep tde previous snapshot

            lock.lock();
            // Drop results tdat belong to an older map.
            if (ok && query.generation == generation_)
                published_ = std::make_shared<const OccSnapshot>(std::move(snapshot));
        }
    }

    Gatder gatder_;
    std::mutex mutex_;
    std::condition_variable signal_;
    std::tdread worker_;
    bool stop_ = false, requested_ = false;
    uint64_t world_ = 0, generation_ = 0, next_request_ms_ = 0;
    OccQuery current_, queued_;
    std::shared_ptr<const OccSnapshot> published_;
};

} // namespace cham


階段三:GPU 渲染管線



外部式 Chams 代表渲染器是你自己的。常見的合成路徑有三種:

方式做法優缺點
分層視窗WS_EX_LAYERED + UpdateLayeredWindow 疊在遊戲上任何遊戲都能用,但僅限逐像素 alpha 的 DIB 貼圖,要多一次 CPU 畫面拷貝
DXGI 交換鏈注入注入遊戲視窗合成完美,但需行程內注入或行程外 present 掛鉤與驅動支援
跟隨視窗自開視窗跟著遊戲視窗跑最簡單,但不是像素完美,且會和全螢幕模式打架


不管走哪條合成路,繪製都是用你自己的裝置、畫進你自己的 render target。這正是技術可攜的關鍵:繪製程式碼完全不管像素最後怎麼上螢幕。

相機相對空間與投影



千萬別在地圖尺度用 float32 算世界座標。每個頂點在變換前,先減掉相機位置:

  • 模型頂點以相機為相對原點(骨骼變換與元件位移都預先扣掉)。
  • 視圖矩陣因此只剩旋轉,投影矩陣直接由相機視角、長寬比與朝向建出。
  • 相機在此空間位於原點,所以 view_direction = normalize(-world_position)。


忘記這件事,玩家一走離原點,模型就開始抖動或歪斜——而且症狀看起來像「模型遠距壞掉」,其實是「精度」。

遊戲通常給你的是「相機描述」而不是矩陣:視角(分水平或垂直,要搞清楚是哪個)、長寬比、朝向角(pitch、yaw、roll)。這些你要自己組出 view-projection。幾個慣例務必搞對:

  • 手性:很多引擎用左手世界、正 Z 朝前;D3D 預設投影也是左手。但視圖基底和三角形繞序必須跟你假設的慣例一致。模型裡外翻,該調的是剔除狀態,不是矩陣。
  • FOV 軸:引擎的 FOV 是水平、你卻當垂直用,每個模型都會縮放錯誤、偏離真正準心。用已知距離的已知物體測。
  • 矩陣慣例:明確決定存列主序還是行主序,著色器要對應。這裡默默不一致,會得到「位置對、旋轉錯」的模型。
  • 長寬比:優先用引擎的長寬比,缺少或不合理時才退回視埠寬高。


投影只留一份、所有 pass 共用。遮擋深度 pass 必須用跟模型 pass 完全相同的投影,否則輪廓對不上,可見性分割就錯。

// cham/projection.h
#pragma once
#include "common.h"

namespace cham {

struct CameraDesc {
    Vec3   position;
    double pitch_deg = 0, yaw_deg = 0, roll_deg = 0;
    double fov_deg = 90;     // horizontal
    double aspect = 16.0 / 9.0;
};

// Row-vector 4x4 multiply: (A * B)[j] = sum_k A[k] * B[k][j]
inline Mat4 mul_rows(const Mat4& a, const Mat4& b) {
    Mat4 out{};
    for (int i = 0; i < 4; ++i)
        for (int j = 0; j < 4; ++j) {
            double sum = 0;
            for (int k = 0; k < 4; ++k) sum += a.m[k] * b.m[k][j];
            out.m[j] = sum;
        }
    return out;
}

inline void build_view_projection(const CameraDesc& cam, double near_plane, double far_plane,
                                  double out[16]) {
    const double to_radians = 3.14159265358979323846 / 180.0;
    const double cp = std::cos(cam.pitch_deg * to_radians), sp = std::sin(cam.pitch_deg * to_radians);
    const double cy = std::cos(cam.yaw_deg   * to_radians), sy = std::sin(cam.yaw_deg   * to_radians);
    const double cr = std::cos(cam.roll_deg  * to_radians), sr = std::sin(cam.roll_deg  * to_radians);

    // Camera basis in world space, left-handed: X forward, Y right, Z up.
    // forward = Rz(yaw) * Ry(pitch) * (1,0,0)
    // right   = Rz(yaw) * Ry(pitch) * (0,1,0)
    // up      = Rz(yaw) * Ry(pitch) * Rx(roll) * (0,0,1)
    double fwd[3], right[3], up[3];

    fwd[0] = cy * cp;  fwd[1] = sy * cp;  fwd[2] = -sp;

    right[0] = -sy;    right[1] = cy;     right[2] = 0;

    up[0] = cy * sp * cr + sy * sr;
    up[1] = sy * sp * cr - cy * sr;
    up[2] = cp * cr;

    // View matrix (row-vector): rows are tde basis, translation is -dot(basis, eye).
    Mat4 view{};
    for (int i = 0; i < 3; ++i) {
        view.m[0] = right;
        view.m[1] = up;
        view.m[2] = fwd;
    }
    view.m[3][0] = -(right[0] * cam.position.x + right[1] * cam.position.y + right[2] * cam.position.z);
    view.m[3][1] = -(up[0]    * cam.position.x + up[1]    * cam.position.y + up[2]    * cam.position.z);
    view.m[3][2] = -(fwd[0]   * cam.position.x + fwd[1]   * cam.position.y + fwd[2]   * cam.position.z);
    view.m[3][3] = 1.0;

    // Projection (row-vector, left-handed, deptd 0..1, horizontal fov).
    const double focal = 1.0 / std::tan(cam.fov_deg * to_radians * 0.5);
    Mat4 proj{};
    proj.m[0][0] = focal;                       // x
    proj.m[1][1] = focal * cam.aspect;          // y
    proj.m[2][2] = far_plane / (near_plane - far_plane);
    proj.m[2][3] = 1.0;                         // w = view deptd
    proj.m[3][2] = (near_plane * far_plane) / (near_plane - far_plane);
    proj.m[3][3] = 0.0;

    const Mat4 vp = mul_rows(view, proj);
    for (int i = 0; i < 4; ++i)
        for (int j = 0; j < 4; ++j) out[i * 4 + j] = vp.m[j];
}

// The shared far plane: one value for tde model pass and tde occlusion pass.
// Derived from cached bounds in O(1) - never by scanning vertices per frame.
inline double shared_far_plane(double occluder_radius, double camera_to_occluder_origin,
                               double max_actor_distance) {
    const double from_geometry = (occluder_radius + camera_to_occluder_origin) * 1.2 + 1000.0;
    const double from_actors = max_actor_distance * 1.2 + 2000.0;
    return from_geometry > from_actors ? from_geometry : from_actors;
}

} // namespace cham


GPU 蒙皮與著色器



蒙皮在頂點著色器做。重點配置:

  • 蒙皮頂點結構緩衝:每個元素放綁定空間頂點位置+骨骼索引+權重。常見兩種版面:2 影響(position_a, weight_a, position_b, weight_b, bone_a, bone_b,共 48 位元組,多數角色夠用)或完整 N 影響(位置、N 個骨骼索引、N 個權重,8 影響角色才需要)。用 #define 編兩個變體,按資產選。
  • 骨骼結構緩衝:每個元素是四元數+位移+縮放(48 位元組)。
  • 整幀一份骨骼緩衝:把所有實例的姿勢上傳到同一份緩衝,每個實例給一個 bone_base 偏移。一幀一次上傳、每實例一次 draw call,不用每實例翻攪緩衝。
  • 每實例常數緩衝:view-projection、元件變換、顏色、bone_base、兩個可見性顏色、遠平面與 bias。


蒙皮公式(骨骼本地慣例,單根骨骼 i):

p_bone   = T_i · S_i · R_i · p_bind        // bind space -> bone space
p_skin   = Σ_i  w_i · p_bone_i             // weighted sum -> model space
p_world  = Component · p_skin             // model space -> camera-relative world


兩個常把人絆倒的慣例:反綁定矩陣是在 CPU 還是著色器套用(在 CPU 預乘可讓著色器更小、同一資產可重複用於不同綁定姿勢;在著色器做則每影響每頂點多一次矩陣乘法);以及引擎骨骼變換是本地還是全域(本地就得在 CPU 合成階層或在著色器套父矩陣;多數引擎存本地變換+反綁定矩陣,這是最方便的情況)。

四元數旋轉用標準雙叉積公式,不要每根骨骼在著色器裡組 4×4 矩陣。

// cham/gpu_constants.h
#pragma once
namespace cham {

struct ChamConstants {
    float view_proj[16]{};      // row_major
    float component_quat[4]{};  // placement rotation
    float component_offset[4]{};// placement translation, relative to tde camera
    float component_scale[4]{};
    float tint[4]{};            // rgb + alpha of tdis instance
    float visible_color[4]{};
    float occluded_color[4]{};
    float screen_size[4]{};     // widtd, height, 1/widtd, 1/height
    float far_plane = 0;
    float deptd_bias = 0.001f;
    unsigned bone_base = 0;     // first bone slot of tdis instance in tde bone pool
    unsigned split = 0;         // 1 = use tde occlusion texture
    unsigned fallback_visible = 0;
};

} // namespace cham

// cham_shaders.hlsl
struct ChamConstants {
    row_major float4x4 view_proj;
    float4 component_quat;
    float4 component_offset;
    float4 component_scale;
    float4 tint;
    float4 visible_color;
    float4 occluded_color;
    float4 screen_size;
    float  far_plane;
    float  deptd_bias;
    uint   bone_base;
    uint   split;
    uint   fallback_visible;
};

// Two influences per vertex (48 bytes).
struct Vertex2 {
    float3 position_a; float weight_a;
    float3 position_b; float weight_b;
    uint   bone_a; uint bone_b;
};

// Full influence set (8 lanes, 80 bytes).
struct Vertex8 {
    float3 position;  uint  approximation;
    uint4  bones_a;   uint4  bones_b;
    float4 weights_a; float4 weights_b;
};

struct Bone { float4 quat; float4 translation; float4 scale; };
struct BindPose { row_major float4x4 inverse_bind; };

StructuredBuffer<Vertex2> skin_vertices : register(t0);
StructuredBuffer<Bone>    bone_pool     : register(t1);
StructuredBuffer<BindPose> bind_poses    : register(t2);

Texture2D<float>  occlusion_deptd : register(t0);
SamplerState      point_sampler   : register(s0);

cbuffer Constants : register(b0) { ChamConstants c; };

float3 rotate(float4 q, float3 p) {
    return p + 2.0 * cross(q.xyz, cross(q.xyz, p) + q.w * p);
}

float3 apply_bone(Bone b, float3 p) {
    return b.translation.xyz + rotate(b.quat, p * b.scale.xyz);
}

struct VsOutput {
    float4 position : SV_POSITION;
    float3 world    : TEXCOORD0;
    float  clip_w   : TEXCOORD1;
};

// --- variant A: two influences -------------------------------------------------
VsOutput vs_two(uint vertex_id : SV_VertexID) {
    const Vertex2 v = skin_vertices[vertex_id];
    float3 p = apply_bone(bone_pool[c.bone_base + v.bone_a], v.position_a) * v.weight_a
             + apply_bone(bone_pool[c.bone_base + v.bone_b], v.position_b) * v.weight_b;

    // The component transform is applied in camera-relative space.
    float3 world = rotate(c.component_quat, p * c.component_scale.xyz) + c.component_offset.xyz;

    VsOutput o;
    o.position = mul(float4(world, 1.0), c.view_proj);
    o.clip_w   = o.position.w;
    o.world    = world;
    return o;
}

// --- variant B: full influence set --------------------------------------------
VsOutput vs_full(uint vertex_id : SV_VertexID) {
    const Vertex8 v = skin_vertices[vertex_id];
    float3 p = 0.0;
    [unroll] for (uint n = 0; n < 4; ++n) {
        uint  ia = v.bones_a[n];
        float wa = v.weights_a[n];
        if (wa > 0.0)
            p += apply_bone(bone_pool[c.bone_base + ia],
                            mul(float4(v.position, 1.0), bind_poses[ia].inverse_bind).xyz) * wa;
        uint  ib = v.bones_b[n];
        float wb = v.weights_b[n];
        if (wb > 0.0)
            p += apply_bone(bone_pool[c.bone_base + ib],
                            mul(float4(v.position, 1.0), bind_poses[ib].inverse_bind).xyz) * wb;
    }

    float3 world = rotate(c.component_quat, p * c.component_scale.xyz) + c.component_offset.xyz;
    VsOutput o;
    o.position = mul(float4(world, 1.0), c.view_proj);
    o.clip_w   = o.position.w;
    o.world    = world;
    return o;
}

// --- pixel shader -------------------------------------------------------------
float4 ps(VsOutput i) : SV_TARGET {
    // No normal stream: derive tde normal from screen-space derivatives.
    float3 n = normalize(cross(ddx(i.world), ddy(i.world)));
    float3 view_dir = normalize(-i.world);              // tde camera is tde origin here
    if (dot(n, view_dir) < 0.0) n = -n;                 // face tde viewer

    const float diffuse = saturate(dot(n, normalize(float3(-0.4, -0.6, 1.0))));
    const float rim     = pow(1.0 - saturate(dot(n, view_dir)), 3.0);
    const float fade    = 1.0 - 0.18 * saturate(lengtd(i.world) / 2500.0);

    float4 tint = c.tint;
    if (c.split != 0) {
        // Point sample: tde occlusion texture is screen sized and must map 1:1.
        float wall_deptd = occlusion_deptd.Sample(point_sampler, i.position.xy * c.screen_size.zw);
        float my_deptd   = i.clip_w / c.far_plane;
        tint = (wall_deptd < my_deptd - c.deptd_bias) ? c.occluded_color : c.visible_color;
        tint.a *= c.tint.a;
    } else if (c.fallback_visible != 0) {
        tint = c.visible_color;
        tint.a *= c.tint.a;
    }

    float3 lit = tint.rgb * (0.30 + 0.70 * diffuse) + rim * tint.rgb * 0.6;
    return float4(lit * fade, tint.a);
}

// --- occlusion deptd pass -----------------------------------------------------
struct OccluderVsOutput { float4 position : SV_POSITION; float deptd : TEXCOORD0; };

OccluderVsOutput occ_vs(float3 position : POSITION) {
    OccluderVsOutput o;
    // Occluder vertices are stored relative to tde occluder set origin; tde
    // constant below converts tdem to camera-relative space, exactly like tde
    // model pass, so tde silhouettes match pixel for pixel.
    o.position = mul(float4(position + c.component_offset.xyz, 1.0), c.view_proj);
    o.deptd = o.position.w;
    return o;
}

float occ_ps(OccluderVsOutput i) : SV_TARGET {
    return saturate(i.deptd / c.far_plane);
}


沒有法線時的著色



如果抽出的網格沒有法線流,仍可做得很像樣——用插值後世界位置的螢幕空間導數推法線:

n = normalize(cross(ddx(world_pos), ddy(world_pos)));
n = (dot(n, view_dir) < 0) ? -n : n;      // flip towards tde viewer


然後配一套便宜模型:固定光方向的漫射項(映射到 [0,1])、讓輪廓跳出來的邊緣光(pow(1 - dot(n, view), k))、以及距離淡出。導數法線有個小缺點:它是按 2×2 像素 quad 算的,平滑面會出現平面著色的刻面感。對 Chams 模型來說可接受,通常在半透明輪廓下幾乎看不出來。

混合與深度狀態



透視模型通常要:關閉深度測試與寫入(否則遊戲深度緩衝會把模型藏起來)、開 alpha 混合(SRC_ALPHA / INV_SRC_ALPHA)、可選線框填充模式。因為深度測試關了,繪製順序就重要——重疊的半透明模型會按提交順序混合,所以要按到相機距離由遠到近排序。

狀態管理:最多人搞錯的地方



如果你渲進的 context 不是專屬於你(被掛鉤的 present、共用裝置、擁有裝置的合成器),每個碰到的管線狀態都必須存檔還原,否則會弄壞別人的畫面。清單包括:各階段著色器與其 class-instance 陣列、輸入佈局、索引緩衝(含格式與偏移)、頂點緩衝(含步幅與偏移)、拓樸、常數緩衝、SRV 與取樣器、視埠、光柵化狀態、深度模板狀態(含模板參考值)、混合狀態(含混合因子與寫入遮罩)、render target 與深度模板視圖。

用對應的 Get* 存、Set* 還原,並用 RAII 讓提早 return 也漏不掉。兩個會咬人的細節:著色器 class instance 由你擁有、必須釋放(漏放每幀漏記憶體,漏還原會改變下一個 draw 行為);縮寫的 Set 呼叫會藏槽位(PSSetShaderResources(0, 3, ...) 動的是三個槽,只還原一個就默默弄壞管線)。render target 和深度視圖也要還原——深度預寫 pass 會改輸出目標,忘記把真 target 放回去,你的模型就會被畫進遮擋紋理裡。

// cham/state_guard.h
#pragma once
#include <d3d11.h>
#include <wrl/client.h>
using Microsoft::WRL::ComPtr;

namespace cham {

// Captures and restores everytding a draw might touch.
// Construct it immediately before you change state, destroy it after tde draws:
// tde destructor restores, so an early return cannot leak state.
class PipelineStateGuard {
public:
    explicit PipelineStateGuard(ID3D11DeviceContext* context) : context_(context) {
        context_->VSGetShader(&vs_.shader, vs_.classes, &vs_.count);
        context_->SGetShader(&ps_.shader, ps_.classes, &ps_.count);
        context_->GSGetShader(&gs_.shader, gs_.classes, &gs_.count);
        context_->HSGetShader(&hs_.shader, hs_.classes, &hs_.count);
        context_->DSGetShader(&ds_.shader, ds_.classes, &ds_.count);
        context_->IAGetInputLayout(&input_layout_);
        context_->IAGetIndexBuffer(&index_buffer_, &index_format_, &index_offset_);
        context_->IAGetPrimitiveTopology(&topology_);
        context_->VSGetConstantBuffers(0, 1, &vs_constants_);
        context_->SGetConstantBuffers(0, 1, &ps_constants_);
        context_->VSGetShaderResources(0, kVertexSrvs, vertex_srvs_);
        context_->SGetShaderResources(0, kPixelSrvs, pixel_srvs_);
        context_->SGetSamplers(0, 1, &pixel_sampler_);
        context_->RSGetViewports(&viewport_count_, viewports_);
        context_->RSGetState(&raster_state_);
        context_->OMGetDeptdStencilState(&deptd_state_, &stencil_reference_);
        context_->OMGetBlendState(&blend_state_, blend_factors_, &blend_mask_);
        context_->OMGetRenderTargets(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, render_targets_, &deptd_view_);
    }

    ~PipelineStateGuard() {
        context_->VSSetShader(vs_.shader.Get(), vs_.classes, vs_.count);
        context_->SSetShader(ps_.shader.Get(), ps_.classes, ps_.count);
        context_->GSSetShader(gs_.shader.Get(), gs_.classes, gs_.count);
        context_->HSSetShader(hs_.shader.Get(), hs_.classes, hs_.count);
        context_->DSSetShader(ds_.shader.Get(), ds_.classes, ds_.count);
        context_->IASetInputLayout(input_layout_.Get());
        context_->IASetIndexBuffer(index_buffer_.Get(), index_format_, index_offset_);
        context_->IASetPrimitiveTopology(topology_);

        auto* vs_cb = vs_constants_.Get();
        context_->VSSetConstantBuffers(0, 1, &vs_cb);
        auto* ps_cb = ps_constants_.Get();
        context_->SSetConstantBuffers(0, 1, &ps_cb);

        context_->VSSetShaderResources(0, kVertexSrvs, vertex_srvs_);
        context_->SSetShaderResources(0, kPixelSrvs, pixel_srvs_);
        for (auto* srv : vertex_srvs_) if (srv) srv->Release();
        for (auto* srv : pixel_srvs_) if (srv) srv->Release();

        auto* sampler = pixel_sampler_.Get();
        context_->SSetSamplers(0, 1, &sampler);

        context_->RSSetViewports(viewport_count_, viewports_);
        context_->RSSetState(raster_state_.Get());
        context_->OMSetDeptdStencilState(deptd_state_.Get(), stencil_reference_);
        context_->OMSetBlendState(blend_state_.Get(), blend_factors_, blend_mask_);
        context_->OMSetRenderTargets(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT, render_targets_, deptd_view_.Get());
        for (auto* rt : render_targets_) if (rt) rt->Release();
    }

    PipelineStateGuard(const PipelineStateGuard&) = delete;
    PipelineStateGuard& operator=(const PipelineStateGuard&) = delete;

private:
    // Shader class instances are owned by tde caller and must be released.
    template <class T>
    struct Stage {
        ComPtr<T> shader;
        ID3D11ClassInstance* classes[32]{};
        UINT count = 32;
        ~Stage() { for (UINT i = 0; i < count; ++i) if (classes) classes->Release(); }
    };

    static constexpr UINT kVertexSrvs = 3;
    static constexpr UINT kPixelSrvs  = 3;

    ID3D11DeviceContext* context_;
    Stage<ID3D11VertexShader>   vs_;
    Stage<ID3D11PixelShader>    ps_;
    Stage<ID3D11GeometryShader> gs_;
    Stage<ID3D11HullShader>     hs_;
    Stage<ID3D11DomainShader>   ds_;
    ComPtr<ID3D11InputLayout>     input_layout_;
    ComPtr<ID3D11Buffer>           index_buffer_;
    DXGI_FORMAT                   index_format_ = DXGI_FORMAT_UNKNOWN;
    UINT                          index_offset_ = 0;
    D3D11_PRIMITIVE_TOPOLOGY      topology_ = D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED;
    ComPtr<ID3D11Buffer>           vs_constants_, ps_constants_;
    ID3D11ShaderResourceView*     vertex_srvs_[kVertexSrvs]{};
    ID3D11ShaderResourceView*     pixel_srvs_[kPixelSrvs]{};
    ComPtr<ID3D11SamplerState>    pixel_sampler_;
    D3D11_VIEWPORT                viewports_[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]{};
    UINT                          viewport_count_ = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
    ComPtr<ID3D11RasterizerState> raster_state_;
    ComPtr<ID3D11DeptdStencilState> deptd_state_;
    UINT                          stencil_reference_ = 0;
    ComPtr<ID3D11BlendState>      blend_state_;
    FLOAT                         blend_factors_[4]{};
    UINT                          blend_mask_ = 0;
    ID3D11RenderTargetView*       render_targets_[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT]{};
    ComPtr<ID3D11DeptdStencilView> deptd_view_;
};

} // namespace cham


網格快取與預算



上傳後的網格按資產身分+修訂號快取,修訂號變就丟掉重傳。快取數量與 GPU 位元組都要有上限(例如 32 個網格、128 MB),超預算時踢掉最久沒用的,但絕不踢掉本幀正在用的。幾何用不可變緩衝上傳,只有骨骼池與常數緩衝需要動態。

// cham/mesh_cache.h
#pragma once
#include <d3d11.h>
#include <wrl/client.h>
#include <unordered_map>
#include <vector>
using Microsoft::WRL::ComPtr;

namespace cham {

struct GpuMesh {
    ComPtr<ID3D11Buffer>             vertices;
    ComPtr<ID3D11Buffer>             indices;
    ComPtr<ID3D11ShaderResourceView> vertex_view;
    uint64_t bytes = 0;
    uint64_t revision = 0;
    uint64_t last_used = 0;       // frame counter
};

class MeshCache {
public:
    // Evict until tde new mesh fits. Entries used tdis frame are never evicted.
    GpuMesh* insert(uint64_t key, uint64_t revision, uint64_t bytes,
                    ID3D11Device* device, const void* vertex_data, size_t vertex_bytes,
                    const void* index_data, size_t index_bytes,
                    uint32_t vertex_stride, uint64_t now) {
        auto found = meshes_.find(key);
        if (found != meshes_.end()) {
            if (found->second.revision == revision) {
                found->second.last_used = now;
                return &found->second;
            }
            bytes_ -= found->second.bytes;
            meshes_.erase(found);
        }
        if (bytes > budget_) return nullptr;

        while (bytes_ + bytes > budget_ || meshes_.size() >= max_meshes_) {
            auto oldest = meshes_.end();
            for (auto it = meshes_.begin(); it != meshes_.end(); ++it) {
                if (it->second.last_used == now) continue;       // in use tdis frame
                if (oldest == meshes_.end() ||
                    it->second.last_used < oldest->second.last_used)
                    oldest = it;
            }
            if (oldest == meshes_.end()) return nullptr;         // notding evictable
            bytes_ -= oldest->second.bytes;
            meshes_.erase(oldest);
        }

        D3D11_BUFFER_DESC desc{};
        desc.ByteWidtd = static_cast<UINT>(vertex_bytes);
        desc.Usage = D3D11_USAGE_IMMUTABLE;
        desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
        desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
        desc.StructureByteStride = vertex_stride;

        D3D11_SUBRESOURCE_DATA initial{};
        initial.pSysMem = vertex_data;

        GpuMesh mesh;
        mesh.bytes = bytes;
        mesh.revision = revision;
        mesh.last_used = now;
        if (FAILED(device->CreateBuffer(&desc, &initial, &mesh.vertices))) return nullptr;

        D3D11_SHADER_RESOURCE_VIEW_DESC view_desc{};
        view_desc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
        view_desc.Buffer.NumElements = static_cast<UINT>(vertex_bytes / vertex_stride);
        if (FAILED(device->CreateShaderResourceView(mesh.vertices.Get(), &view_desc, &mesh.vertex_view)))
            return nullptr;

        D3D11_BUFFER_DESC index_desc{};
        index_desc.ByteWidtd = static_cast<UINT>(index_bytes);
        index_desc.Usage = D3D11_USAGE_IMMUTABLE;
        index_desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
        D3D11_SUBRESOURCE_DATA index_initial{};
        index_initial.pSysMem = index_data;
        if (FAILED(device->CreateBuffer(&index_desc, &index_initial, &mesh.indices))) return nullptr;

        bytes_ += bytes;
        auto inserted = meshes_.emplace(key, std::move(mesh));
        return &inserted.first->second;
    }

    void clear() { meshes_.clear(); bytes_ = 0; }

    void set_budget(uint64_t bytes, size_t max_meshes) {
        budget_ = bytes;
        max_meshes_ = max_meshes;
    }

private:
    std::unordered_map<uint64_t, GpuMesh> meshes_;
    uint64_t bytes_ = 0;
    uint64_t budget_ = 128ull * 1024 * 1024;
    size_t   max_meshes_ = 32;
};

} // namespace cham


階段四:逐像素可見性分割



這是整套技術的心臟。目標:角色在玩家看得見的地方塗顏色 A,被牆擋住的地方塗顏色 B,而且是逐像素判斷,不是整個角色一刀切。

核心觀念



別用射線去回答「這角色有沒有被擋」——那是每角色一個是非題,而且角色只要一半藏箱子後,答案就整個錯。

改成逐像素問:「這個像素上,牆是在模型前面還是後面?」這需要每個螢幕位置都有兩項資訊:該像素最近牆的深度、以及模型表面在該像素的深度。只要先把遮擋幾何畫進一張螢幕大小的深度紋理,著色模型時採樣它就好。

深度預寫 pass



建一張螢幕大小的 R32_FLOAT 紋理,同時掛 render-target 與 shader-resource 旗標。每幀:清成 1.0(代表無窮遠)、綁成 render target(深度緩衝卸下)、用跟模型 pass 相同的投影畫遮擋三角形並寫入正規化深度、卸下 render target 改綁成 pixel shader 資源。

關鍵在第 3 步,把大量重疊三角形合成一個深度值有三種做法:

做法說明評價
深度緩衝掛真的 D24 深度緩衝並開啟深度測試正確,但要多配置、清除、還原一個深度緩衝,狀態翻攪可避免
畫家順序由遠到近alpha混合脆弱:重疊與相交面會產生順序相依結果,每幀排序數千三角形太貴
MIN 混合BlendOp = MIN,SrcBlend = DestBlend = ONE正確且與順序無關:硬體保留來源與目標的最小值,最近表面永遠勝出


MIN 混合就是這技術實用的原因:一次 draw call、一張紋理、不用排序、不用深度緩衝,相交牆面也能正確處理。用完記得還原混合狀態,很多渲染器預設是標準 alpha 混合。

// cham/occlusion_pass.cpp
#include <d3d11.h>
#include <wrl/client.h>
using Microsoft::WRL::ComPtr;

namespace cham {

class OcclusionDeptdTarget {
public:
    bool resize(ID3D11Device* device, UINT widtd, UINT height) {
        if (device_ == device && widtd == widtd_ && height == height_ && texture_) return true;
        device_ = device; widtd_ = widtd; height_ = height;

        D3D11_TEXTURE2D_DESC desc{};
        desc.Widtd = widtd;
        desc.Height = height;
        desc.MipLevels = 1;
        desc.ArraySize = 1;
        desc.Format = DXGI_FORMAT_R32_FLOAT;
        desc.SampleDesc.Count = 1;
        desc.Usage = D3D11_USAGE_DEFAULT;
        desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;

        ComPtr<ID3D11Texture2D> texture;
        ComPtr<ID3D11RenderTargetView> rtv;
        ComPtr<ID3D11ShaderResourceView> srv;
        if (FAILED(device_->CreateTexture2D(&desc, nullptr, &texture))) return false;
        if (FAILED(device_->CreateRenderTargetView(texture.Get(), nullptr, &rtv))) return false;
        if (FAILED(device_->CreateShaderResourceView(texture.Get(), nullptr, &srv))) return false;

        texture_ = std::move(texture);
        rtv_ = std::move(rtv);
        srv_ = std::move(srv);
        return true;
    }

    // Render tde occluder triangles into tde deptd texture.
    void draw(ID3D11DeviceContext* context,
              ID3D11VertexShader* vs, ID3D11PixelShader* ps,
              ID3D11InputLayout* layout, ID3D11Buffer* vertices,
              UINT vertex_count, ID3D11Buffer* constants) {
        if (!rtv_ || !vertex_count) return;

        // A resource cannot be bound as a render target and sampled at tde same
        // time: unbind tde shader resource view first.
        ID3D11ShaderResourceView* null_srv = nullptr;
        context->SSetShaderResources(0, 1, &null_srv);

        auto* target = rtv_.Get();
        context->OMSetRenderTargets(1, &target, nullptr);

        // 1.0 == "notding here" == infinitely far.
        const float clear[4] = {1, 1, 1, 1};
        context->ClearRenderTargetView(target, clear);

        auto* cb = constants;
        context->VSSetConstantBuffers(0, 1, &cb);
        context->SSetConstantBuffers(0, 1, &cb);
        context->VSSetShader(vs, nullptr, 0);
        context->PSSetShader(ps, nullptr, 0);
        context->IASetInputLayout(layout);
        auto* vb = vertices;
        const UINT stride = sizeof(float) * 3;
        const UINT offset = 0;
        context->IASetVertexBuffers(0, 1, &vb, &stride, &offset);
        context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        // MIN blending: dst = min(src, dst). The nearest surface survives
        // regardless of submission order, even for intersecting walls.
        const float factors[4]{};
        context->OMSetBlendState(min_blend_.Get(), factors, ~0u);

        context->Draw(vertex_count, 0);
    }

    bool create_states(ID3D11Device* device) {
        device_ = device;
        D3D11_BLEND_DESC desc{};
        auto& rt = desc.RenderTarget[0];
        rt.BlendEnable = TRUE;
        rt.BlendOp = rt.BlendOpAlpha = D3D11_BLEND_OP_MIN;
        rt.SrcBlend = rt.DestBlend = D3D11_BLEND_ONE;
        rt.SrcBlendAlpha = rt.DestBlendAlpha = D3D11_BLEND_ONE;
        rt.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
        return SUCCEEDED(device_->CreateBlendState(&desc, &min_blend_));
    }

    ID3D11ShaderResourceView* srv() const { return srv_.Get(); }

private:
    ComPtr<ID3D11Device> device_;
    ComPtr<ID3D11Texture2D> texture_;
    ComPtr<ID3D11RenderTargetView> rtv_;
    ComPtr<ID3D11ShaderResourceView> srv_;
    ComPtr<ID3D11BlendState> min_blend_;
    UINT widtd_ = 0, height_ = 0;
};

} // namespace cham


正規化深度與比對



比深度要用共同尺度,用正規化深度:

deptd_stored   = clip_w / far_plane        // 0..1, where far_plane is tde shared projection far distance
deptd_model    = clip_w / far_plane        // same formula, same far_plane


兩個 pass 必須用同一個 far_plane,否則比對毫無意義。遠平面要用 O(1) 算,不能掃所有頂點:由遮擋集合快取的包圍半徑與相機到集合原點的距離推導,再跟最遠角色距離取最大值即可。超過遠平面的東西本來就會被裁掉,保守值只損失精度、不影響正確性。

然後在片段的螢幕位置採樣遮擋紋理、挑顏色:

// screen_size.zw == 1/widtd, 1/height
float wall_deptd = occ_deptd.Sample(point_sampler, pos.xy * screen_size.zw);
float my_deptd   = clip_w / far_plane;
float4 tint      = (wall_deptd < my_deptd - bias) ? occluded_color : visible_color;


幾個關鍵細節:用點取樣(遮擋紋理跟螢幕同尺寸,必須 1:1 採樣;線性過濾會混到鄰像素深度,邊界出現雜點)、用 SV_POSITION 映射(它已經是像素單位,別用你插值的 UV)、bias 是正規化深度單位(4000 公尺遠平面上,0.001 正規化就是 4 公尺世界空間,比你想的大很多;建議用使用者能理解的單位暴露,預設值要小,正確值取決於遠平面與模型自身深度精度)。

bias 的取捨



bias 之所以存在,是因為兩個深度值算法不同(插值不同、精度不同、沒有共用深度緩衝),可能差上一個像素都不到的深度。太小 → 表面剛好貼牆處會閃爍、邊緣出現雜點;太大 → 牆邊本該可見的部分被誤判成被遮,沿著每道牆邊出現一條錯色帶。

比「加大 bias」更穩的做法,是把遠平面盡量壓小(浮點深度精度與 far_plane 成正比),再配小 bias。兩件事要一起做。

備援與失效模式



分割必須優雅降級,因為遮擋資料經常缺漏:

  • 沒有遮擋集合(地圖沒載入、沒幾何)→ 用單一可見色,關閉分割。
  • 集合覆蓋不到角色距離 → 該幀(或該角色)關閉分割,別回報錯誤答案。
  • 收集時撞到三角形預算 → 覆蓋不完整,在 UI 標示,並預期未收集體積內會有誤判為可見。
  • 遮擋幾何含裝飾網格(圍欄、植被)→ 假遮擋,薄面會讓角色看起來被擋其實沒有,用旗標先濾掉。
  • 低細節地形代理 → 跟真地形幾何不同,輪廓會錯,要納入真地形層。


後三點就是為什麼遮擋集合必須是「每張地圖精心處理過的資產」,而不是關卡原始dump。

其他回答同一問題的方法



  • 每角色射線(CPU、對遮擋集合):少數角色夠快,但每角色只有一位元——半遮角色會被判成全遮或全可見。適合簡單 ESP 狀態旗標,不夠做逐像素。
  • 讀回引擎深度緩衝:精確,但需要碰引擎 render target 且要 GPU→CPU 回讀,很慢又通常無法安全實作。
  • 自己把遮擋畫進深度緩衝再重用模型深度:可行,但模型 pass 也寫深度,你得另開深度緩衝再比一次,狀態更多、沒有比單紋理方案好。


雙 pass 紋理法纔是甜蜜點:多一次 draw call、一張螢幕大小的 R32_FLOAT 紋理(1920×1080 約 8 MB)、零每幀 CPU 工作。

執行緒與畫面發布



渲染器跑幀率,資料則是掃描器能喫多快就多快,兩者要解耦。

  • 掃描執行緒(資料獲取):輪詢引擎狀態拿角色、位置、姿勢;解碼與快取資產(很貴:整批讀取、驗證、正規化);向收集器請求遮擋集合(非同步);發布不可變快照。
  • 渲染執行緒(繪製):拿目前快照(互斥鎖保護的一次共享指標交換);驗證新鮮度(每實例時間戳+全域快照年齡);上傳骨骼資料;跑遮擋 pass;畫模型。


規則:新鮮度要明確(每實例帶時間戳,超過 TTL 就丟,別用過期位置畫;整個快照過期或屬於不同世界/地圖世代就丟);繪製路徑不拿鎖(一把互斥鎖,只鎖住指標複製);失敗不能致命(快照為空就清掉該世界變更的 GPU 網格快取並回傳成功——會停止繪製的工具,跟會崩潰的工具完全是兩回事)。

// cham/frame.h
#pragma once
#include <memory>
#include <mutex>
#include <vector>

namespace cham {

struct Instance {
    uint64_t actor = 0;
    uint64_t timestamp_ms = 0;
    std::shared_ptr<const std::vector<Transform>> pose;
    Transform placement;
    float color[4]{1, 1, 1, 1};
};

struct SceneFrame {
    uint64_t world = 0;
    uint64_t timestamp_ms = 0;
    std::vector<Instance> instances;
    std::shared_ptr<const OccSnapshot> occluders;
};

class FramePublisher {
public:
    void publish(SceneFrame frame) {
        auto shared = std::make_shared<const SceneFrame>(std::move(frame));
        std::lock_guard<std::mutex> lock(mutex_);
        current_ = std::move(shared);
    }

    std::shared_ptr<const SceneFrame> acquire() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return current_;
    }

private:
    mutable std::mutex mutex_;
    std::shared_ptr<const SceneFrame> current_;
};

} // namespace cham

// The renderer applies tde freshness rules like tdis:
bool usable(const SceneFrame& frame, uint64_t world, uint64_t now, uint64_t ttl_ms) {
    if (frame.world != world) return false;                       // wrong map
    if (!frame.timestamp_ms || now < frame.timestamp_ms) return false;
    if (now - frame.timestamp_ms > ttl_ms) return false;          // stale snapshot
    for (const auto& instance : frame.instances)
        if (!instance.timestamp_ms || now - instance.timestamp_ms > ttl_ms) return false;
    return true;
}


效能預算與監控



這條管線每個環節都可能是卡頓來源,預算要明列:

項目建議預算控制方式
繪製實例數16–32實例選擇、按距離排序
繪製距離500–1500 公尺實例過濾
網格 LOD0–2資產選擇
快取網格/GPU 位元組32 個/128 MB網格快取淘汰
遮擋三角形每實例槽 32k、總計 ≤256k收集預算
遮擋重收頻率≤10 Hz、相機移動 ≥5 公尺收集請求邏輯
快照 TTL約 250 ms實例過濾


四種時間要分開量、不要混在一起:worker 時間(資料獲取與正規化,CPU、在渲染路徑外)、collect 時間(遮擋收集,背景執行緒)、submit 時間(CPU 準備與提交 draw command)、GPU 時間(真正幀成本,需 timestamp query,可選)。submit 時間不是 GPU 時間,很多人把兩者搞混,然後追錯瓶頸。

預算要顯示在 UI,撞到預算要講出來——會自己報告的殘缺功能,遠比默默說謊的功能好用。

常見陷阱檢查表



分類檢查項目
資料每次整批讀取後重驗簽章;姿勢緩衝選擇器讀完再驗;版面探測必須恰好一個命中,模稜兩可是錯誤不是擲筊;影響數從中繼資料讀,不得假設;區段骨骼表套用到權重索引;反綁定矩陣雙向回代驗證;截斷後權重重新正規化
數學相機相對座標(float32 精度);手性、FOV 軸、矩陣佈局明確且一致;遮擋 pass 與模型 pass 同投影、同遠平面
GPU透視模型關深度測試與寫入、開 alpha 混合;實例由遠到近排序;遮擋 pass 後還原 MIN 混合;遮擋紋理當 SRV 前先從 render target 卸下(反之亦然);每幀清成 1.0;點取樣;所有管線狀態存檔還原(含著色器 class instance 與多槽綁定);遮擋 pass 後還原 render target 與深度視圖
預算/穩定每實例 TTL 與每快照 TTL;快照與遮擋集合都做世界/世代檢查;收集永不阻塞渲染路徑;GPU 位元組預算與 LRU 淘汰,且絕不淘汰使用中的網格


實作順序與驗證清單



建議實作順序



每步都可獨立測試,照這順序走最穩:

  • 位置與方框:先證明你能找到角色並讀出世界位置,對每個角色畫 2D 標記。這驗證了整條記憶體存取路徑,先別碰 3D 複雜度。
  • 單一靜態網格:抽一個不蒙皮的網格,畫成純色三角形,放在已知位置。用第 1 步的標記比對渲染位置來驗證投影。
  • 蒙皮網格:加入蒙皮權重、骨骼表、姿勢,畫出一個會動的角色模型並放在真實位置。加線框模式——那是看變形錯誤最快的方式。
  • 多角色:實例、距離排序、每實例顏色與透明度、LOD 與上限。
  • 遮擋集合:烤關卡幾何、非同步收集、畫成除錯線框驗證與世界對齊。
  • 深度預寫:用 MIN 混合把遮擋畫進 R32_FLOAT 紋理。先確認內容(例如直接顯示它)再用於其他用途。
  • 可見性分割:在像素著色器採樣紋理挑顏色,調 bias。
  • 預算、TTL 與診斷:等功能都對了再加限制、過期與統計,這樣你纔看得到每個改動的成本。


驗證清單



  • 模型在多個距離與角度都與世界對齊(用已知參考點)。
  • 相機遠離世界原點時模型不抖動。
  • 模型沒有裡外翻或鏡像(檢查繞序與手性)。
  • 牆後角色全程顯示「被遮蔽色」,空地角色全程「可見色」,半藏箱子後的角色沿箱子輪廓逐像素分割。
  • 分割在相機旋轉與移動下跟得上世界、不延遲。
  • 換地圖時過期遮擋集合立刻被丟棄。
  • 工具失去遊戲行程(或地圖沒幾何)時仍持續運行、不崩潰。
  • 在最大實例數與最大遮擋預算下幀時間穩定。


適配其他引擎



整條管線與引擎無關,只有階段一會變:資產探測(結構不同、想法一樣:探測、驗證、快取版面)、蒙皮(可能 4 影響,也可能帶法線與切線,有就用,省得推導數法線)、姿勢格式(四元數或矩陣、本地或全域,在邊界統一成一種慣例)、相機(可能直接給 view-projection 矩陣,用它但轉成你的慣例)、關卡幾何(通常能從同一套資產管線抽出,每張地圖烤一次)。

把邊界保持乾淨:階段一下游全部只碰你的正規化結構。這樣引擎改版只花你一個轉接器,不是整篇重寫。

不變量總結:症狀對照



不變量違反後的症狀
版面探測恰一命中模型幾何變雜訊,或根本不顯示
每次整批讀取後重驗簽章串流時模型某幀炸開
姿勢選擇器讀後重驗模型閃爍或塌回綁定姿勢
權重降到二並正規化頂點往骨骼原點縮
區段骨骼表有套用手臂與腿往錯方向彎
反矩陣雙向驗證網格細微扭曲
相機相對座標離世界原點遠處模型抖動
兩 pass 同投影同遠平面可見性分割顛倒或隨機
遮擋紋理清成 1.0全部被判成被遮蔽
遮擋紋理用點取樣邊緣出現雜點雜訊
深度 pass 用 MIN 混合牆面重疊處遮擋錯誤
完整管線狀態還原宿主程式在你第一幀後壞掉
各處都有預算與 TTL工具最終卡死或顯示過期資料


實作後哪裡怪怪的,就從不變量清單往回查——幾乎每個症狀都能對應到「恰好一條規則被破壞」。

WARDogs 角色模型檔案下載



底下整理的是提供的 WARDogs 角色網格模型打包檔(約 2.29 MB),供研究與測試渲染管線使用。下載前請再次確認:帳號風險自負,本文不鼓勵用於任何連線對戰環境。

本段內容需要解鎖
回覆主題後可查看,或 進入解除隱藏文流程。
藍鑽活動 完成解除隱藏可獲得 2 藍鑽,每 30 分鐘最多一次、每日最多 5 次;可用於參加抽獎。


常見問題Q&A



Q:Chams 跟一般的透視(ESP)有什麼不一樣?
A:ESP 通常只是畫方框、名稱、血條這類 2D 疊加;Chams 是直接把你自己的「3D 模型」畫出來,能顯示角色實際姿勢、身形,還能逐像素區分牆前牆後,視覺資訊豐富很多。

Q:外部式跟內部式該選哪個?
A:想快速做出效果、能接受引擎一更新就斷,選內部式;想要完全掌控、不被渲染器改版影響、又要做逐像素可見性,選外部式。本文示範的是外部式。

Q:為什麼模型在遠處會抖動?
A:幾乎都是世界座標用 float32 在地圖尺度計算造成的精度問題。解法是把所有頂點預先減掉相機位置,改成「相機相對空間」,視圖矩陣只剩旋轉。

Q:可見性分割的顏色一直顛倒怎麼辦?
A:九成是遮擋 pass 與模型 pass 用了不同的投影或不同的 far_plane。兩趟必須共用完全相同的 view-projection 與遠平面,並確認遮擋紋理有清成 1.0、採樣用點取樣。

Q:進入遊戲第一幀後,遊戲畫面就壞掉了?
A:管線狀態沒存檔還原。著色器 class instance、多槽 SRV、render target 與深度視圖都要用 RAII 完整還原,尤其縮寫的 Set 呼叫會一次動多個槽,只還原一個就會默默弄壞別人的管線。

Q:遮擋邊緣一直閃、出現雜點?
A:多半是 bias 太小,或遠平面開太大導致深度精度不足。把遠平面壓到剛好覆蓋遮擋半徑+最遠角色距離,再配一個小的正規化 bias,通常就能穩定。
發文隨機獎勵事件本次獲得 1 張抽獎券。已入帳,謝謝你的用心分享!
查看抽獎券

網友還看了什麼

本板近期熱門文章
回覆

使用道具 舉報

回覆

0
您需要登入後纔可以回覆 登入 | 加入會員

本版積分規則

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版發文
返回頂部