// 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
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;
}
// 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; };
// 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;
}
// 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 };
// 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);
}
}
// 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;
}
// 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;
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;
}
// 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&)>;
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;
};
// The component transform is applied in camera-relative space.
float3 world = rotate(c.component_quat, p * c.component_scale.xyz) + c.component_offset.xyz;
// --- 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
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(); }
};
// 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);
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