Compare commits

...
6 Commits
Author SHA1 Message Date
shenleiandClaude Opus 5.5 53115d9ea2 gr2: look up bones by a cached name index
FindBoneIndex builds a name->index map once per instance (first match
wins, as the linear scan did); GetBoneWorldTransform gains an index
overload and attached models cache their bone index at attach time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:38:18 +09:00
shenleiandClaude Opus 5.5 16d16de90d gr2: resolve skins once per skin change on the GPU draw cache
The cached GPU draws keep the skinned texture names and the unskinned
originals; SetSkin/ClearSkins bump a generation so the cache re-resolves
once instead of lowercasing every texture path every frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:30:32 +09:00
shenleiandClaude Opus 5.5 9ec7fa10c0 gr2: share vertex streams across tri-groups on the GPU skinning path
Each tri-group draw now references one shared geometry with a
first_index/index_count sub-range instead of copying the vertex
streams per group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:27:00 +09:00
shenleiandClaude Opus 5.5 e354b92e08 gr2_render: cache part->parent bone map and parent bind pose
BuildDrawCommandsWithPalette recomputed gr2::bind_pose of the parent
skeleton and an O(part bones x parent bones) name match every frame for
every hair/armor part. Both depend only on the two skeletons; rebuild
them when the parent skeleton changes and reuse the palette buffer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:13:22 +09:00
shenleiandClaude Opus 5.5 a1b3938159 gr2_render: share one GPU skinning palette per instance per frame
Gr2MeshDraw::bone_matrices (a full palette copy per draw, also filled on
the CPU path where nothing reads it) becomes a shared_ptr palette set by
UpdateGpuDraws for gpu_skinning draws only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:12:14 +09:00
shenleiandClaude Opus 5.5 de8fa40098 gr2: align curve sampling with Granny 2.11 (loop window, cubic, degree 0)
- Curve::eval rebuilds the B-spline window like ConstructBSplineBuffers:
  clamped ends repeat the endpoint; underflow/overflow looping takes knots
  from the other end (+-duration, skipping the duplicated last knot); equal
  trailing knots get +1e-5.
- Degree 3 (CubicCoefficients) supported; degrees 0..3 share one path.
- Degree 0 takes the control of the first knot > t (SampleBSpline0 = pi[0]);
  DaKeyframes32f curves are marked keyframed and keep frame trunc(t/dt).
- Loop flags threaded through BoneTrack::sample, Animation::sample_local and
  sample_pose; control_loop_state() mirrors GetControlLoopState.
- Gr2ModelInstance::SetAnimationLoop(); animated attachments (fmod) loop.
- Quaternion continuity stays on for every span (Granny: buffer path only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:39:33 +09:00
7 changed files with 426 additions and 157 deletions
+2 -1
View File
@@ -96,7 +96,8 @@ private:
// 单位阵(见 extension/src/metin2_anim.cpp 与 test/rendering/README.md 的实测)。
void sample_pose(const Skeleton& sk, const Animation& an, float t,
std::vector<Mat4>& world, std::vector<Mat4>& skin,
const Mat4* root_offset = nullptr);
const Mat4* root_offset = nullptr,
bool underflow_loop = false, bool overflow_loop = false);
void bind_pose(const Skeleton& sk, std::vector<Mat4>& world, std::vector<Mat4>& skin);
// 打印辅助
+21 -3
View File
@@ -105,9 +105,14 @@ struct Curve {
std::vector<float> knots; // KnotCount 个
std::vector<float> controls; // KnotCount * dim 个
bool knots_sorted = true; // 升序 → eval 二分找 knot;否则按原样线性扫
bool keyframed = false; // DaKeyframes32f:按帧号 floor(t/dt) 取,不走 B 样条
bool empty() const { return knots.empty() || dim == 0; }
// t 处求值,写 dim 个 float 到 out(identity 由调用方给)。
void eval(float t, float* out) const;
// underflow_loop/overflow_loop = granny Control 的循环状态(见 control_loop_state):
// 窗口越过曲线首/尾时,从曲线另一端取 knot(±duration)而不是重复端点。
// duration = Animation::duration(granny 的 LocalDuration)。
void eval(float t, float* out, bool underflow_loop = false, bool overflow_loop = false,
float duration = 0.0f) const;
};
struct TextTrackEntry { float time_stamp = 0.0f; std::string text; };
@@ -123,7 +128,8 @@ struct BoneTrack {
Curve orientation; // dim 4(四元数 x,y,z,w)
Curve scale_shear; // dim 9(3x3)或 dim 3
// t 处的 SRT(缺的曲线取单位分量,flags 只标出有曲线的分量)。sample_local 的 4x4 = compose(这个)。
void sample(float t, Transform& out) const;
void sample(float t, Transform& out, bool underflow_loop = false, bool overflow_loop = false,
float duration = 0.0f) const;
};
// Preserve group boundaries: an animation can contain an auxiliary object group before its model.
@@ -152,9 +158,21 @@ struct Animation {
std::vector<AnimationTrackGroup> track_groups;
// t 处每个 track 的局部 4x4(granny_transform 组合语义,行主序)。
// out 按 tracks 顺序;bone_index 见各 track。
void sample_local(float t, std::vector<Mat4>& out) const;
// underflow_loop/overflow_loop 见 Curve::eval;循环播放时两者都传 true。
void sample_local(float t, std::vector<Mat4>& out,
bool underflow_loop = false, bool overflow_loop = false) const;
};
// granny GetControlLoopState:loop_count==0(无限循环)→ 两端都循环;否则第 loop_index 遍
// 前面还有遍数才 underflow,后面还有遍数才 overflow。force_clamped(Control Flags 0x20)→ 都不循环。
inline void control_loop_state(int loop_count, int loop_index, bool force_clamped,
bool& underflow_loop, bool& overflow_loop) {
if (force_clamped) { underflow_loop = overflow_loop = false; return; }
if (loop_count == 0) { underflow_loop = overflow_loop = true; return; }
underflow_loop = loop_index > 0;
overflow_loop = loop_index < loop_count - 1;
}
// 顶层 granny_material(driven by root Materials[])。name + 解析出的漫反射贴图。
// root Materials[] 之外、只经 Maps[] / mesh MaterialBindings 可达的子材质追加在后面。
struct MaterialMap {
+30 -2
View File
@@ -30,11 +30,16 @@ struct Gr2MeshDraw {
std::vector<float> uv0; // 2 floats (u, v) per vertex
std::vector<uint32_t> diffuse; // 0xAARRGGBB per vertex
std::vector<uint32_t> indices; // Triangle indices
// Sub-range of the indices (of geometry when shared) this draw covers. Tri-groups of one
// GPU mesh share a single geometry and differ only by range and material.
uint32_t first_index = 0;
uint32_t index_count = UINT32_MAX; // UINT32_MAX = through the end
// Skeletal skinning palette & vertex weights (for GPU skinning)
std::vector<uint8_t> bone_indices; // 4 uint8 per vertex
std::vector<float> bone_weights; // 4 floats per vertex
std::vector<float> bone_matrices; // 16 floats per bone (palette)
// GPU skinning palette, 16 floats per bone; one per instance per frame, shared by its draws.
std::shared_ptr<const std::vector<float>> palette;
// Render states
bool alpha_test = false;
@@ -53,9 +58,16 @@ public:
bool LoadExternalAnimation(const std::string& anim_filepath);
bool LoadExternalAnimationFromMemory(const uint8_t* data, size_t size);
float GetAnimationDuration() const;
// granny Control 的循环状态(gr2::control_loop_state)。循环播放的动作传 (true, true):
// 首尾附近的 B 样条窗口跨到上一遍/下一遍取 knot,接缝处不再夹到端点。默认都不循环。
void SetAnimationLoop(bool underflow_loop, bool overflow_loop);
// Bone queries & attachments
bool GetBoneWorldTransform(const std::string& bone_name, float* out_matrix, float animation_time = -1.0f) const;
// Bone index in skeleton 0 (first bone with that name), or -1. Callers that query the same bone
// every frame can cache it and use the index overload instead of a name lookup.
int FindBoneIndex(const std::string& bone_name) const;
bool GetBoneWorldTransform(int bone_index, float* out_matrix, float animation_time = -1.0f) const;
void AttachModel(const std::string& bone_name, std::shared_ptr<Gr2ModelInstance> attachment, const float* offset_matrix = nullptr);
void AttachPart(std::shared_ptr<Gr2ModelInstance> part);
void DetachAll();
@@ -65,7 +77,7 @@ public:
void SetAttachmentAnimated(const std::string& bone_name, bool animated);
void SetAttachmentScale(const std::string& bone_name, float sx, float sy, float sz);
void SetSkin(const std::string& src_file_name, const std::string& dst_file_name);
void ClearSkins() { m_skins.clear(); }
void ClearSkins() { m_skins.clear(); ++m_skinGeneration; }
const std::string& GetFilePath() const { return m_filepath; }
// Build draw commands for this model and all attached components (weapons, hair, armor parts)
@@ -86,6 +98,7 @@ public:
private:
struct AttachedModel {
std::string bone_name;
int bone_index = -1;
std::shared_ptr<Gr2ModelInstance> model;
float offset[16];
bool animated = false;
@@ -93,16 +106,31 @@ private:
float scale[3] = {1.0f, 1.0f, 1.0f};
};
std::vector<Gr2MeshDraw> m_gpuMain, m_gpuParts;
// The GPU caches hold skinned texture names; the unskinned originals are kept so a skin change
// (SetSkin/ClearSkins bump m_skinGeneration) re-resolves them once instead of every frame.
std::vector<std::string> m_gpuMainBaseTex, m_gpuPartsBaseTex;
size_t m_gpuMainSkinGen = 0, m_gpuPartsSkinGen = 0, m_skinGeneration = 1;
void CacheGpuDraws(std::vector<Gr2MeshDraw>& cache, std::vector<std::string>& base, size_t& gen, const std::vector<Gr2MeshDraw>& draws) const;
void RefreshGpuSkins(std::vector<Gr2MeshDraw>& cache, const std::vector<std::string>& base, size_t& gen) const;
const gr2::Skeleton* m_gpuPartParent = nullptr;
size_t m_gpuPartPaletteSize = 0;
// Part bone -> parent bone by name, and the parent bind world per part bone; both depend only
// on the two skeletons, so they are rebuilt when the parent skeleton changes, not every frame.
const gr2::Skeleton* m_partMapParent = nullptr;
size_t m_partMapParentBones = 0;
std::vector<int> m_partToParent;
std::vector<gr2::Mat4> m_partParentBind, m_partSkin;
void EvaluatePose(float animation_time) const;
mutable bool m_poseValid = false;
mutable float m_poseTime = -1;
mutable const gr2::Animation* m_poseAnimation = nullptr;
bool m_loopUnderflow = false, m_loopOverflow = false;
mutable std::vector<gr2::Mat4> m_worldPose, m_skinPose, m_trackPose, m_localPose;
mutable std::vector<int> m_trackBones;
mutable size_t m_poseEvaluations = 0;
void ApplySkins(std::vector<Gr2MeshDraw>& draws, size_t first) const;
mutable std::unordered_map<std::string, int> m_boneIndex;
mutable bool m_boneIndexBuilt = false;
std::shared_ptr<const gr2::File> m_file;
std::string m_filepath;
+138 -73
View File
@@ -200,14 +200,16 @@ void File::Impl::read_curve2(Ref curve_obj, Ref curve_type, float keyframe_dt, C
if (v == "DaKeyframes32f") {
// 关键帧:knot 不存,第 i 帧在 i*TimeStep(AVA2 全库 19045 条都满足 N-1 == Duration/TimeStep)。
// Degree 0 = 逐帧保持,见 Curve::eval。
// granny CurveIsKeyframed:按帧号取(SetContextFrameIndex 截断 t/dt),见 Curve::eval。
uint16_t dim16 = 0;
uint32_t nc = 0;
const uint8_t* pc = arr("Controls", 4, nc);
if (!u16m("Dimension", dim16) || dim16 == 0 || !pc || nc % dim16) return;
for (uint32_t i = 0; i < nc / dim16; ++i) out.knots.push_back(float(i) * keyframe_dt);
for (uint32_t i = 0; i < nc; ++i) out.controls.push_back(rf(pc, i));
return finish(dim16);
finish(dim16);
out.keyframed = !out.empty();
return;
}
// 其余都是量化 knot + KnotsControls 一块数组:先 N 个 knot,再 N*每knot分量数 个 control。
@@ -438,65 +440,119 @@ bool File::Impl::extract_animation(Ref anim_obj, Ref anim_type, const Skeleton*
// ── T7b:曲线解码 ─────────────────────────────────────────────────────
// Metin2 曲线全是 OldCurveType(B 样条:Degree + Knots[] + Controls[knot*dim]);
// AVA2 的 curve2 变体由 read_curve2 解成同样的 knots/controls。
// 求值照 granny_bspline.cpp SampleBSpline{0,1,2}xN + granny_bspline_inlines.h
// {Linear,Quadratic}Coefficients。degree 0=常量/阶梯,1=线性,2=二次 B 样条。
// KnotIndex = "第一个 > t 的 knot"(granny CurveFindKnot),窗口越界按端点 clamp。
// 求值照 granny2.dll 2.11 的曲线采样器(FUN_1005d950):
// keyframed → 第 floor(t/dt) 帧(SetContextFrameIndex 截断);
// 否则 k = CurveFindKnot(t) = 第一个 > t 的 knot(clamp 到 n-1),
// ConstructBSplineBuffers 取 [k-D, k+D) 的窗口(D=0 时宽 1),再 SampleBSpline{0..3}。
// 窗口越过首/尾:不循环时重复端点;underflow_loop/overflow_loop 时从曲线另一端取
// (跳过末尾那个与首点重复的 knot),knot 时间 ±duration。尾部截出的最后两个 knot 相等时
// 末一个 +1e-5(防除零,与 granny 相同)。
// degree 0 取 pi[0],即第一个 > t 的 knot 的控制点(不是"最后一个 <= t")。
//
// dim==4(四元数):blend 之前对本 span 参与的 degree+1 个控制点做
// EnsureQuaternionContinuity(granny_math.cpp)—— 逐点若与前一点点积 < 0 则整体取反。
// 少了这一步,跨半球(q vs -q)的控制点线性混合会收缩到近零,归一后得到一个
// 合法但方向错约 180° 的旋转(表情动作里脖子/头会折叠塌陷)。
void Curve::eval(float t, float* out) const {
const uint32_t n = (uint32_t)knots.size();
// granny 只在走缓冲区(窗口越界)时做这一步,这里有意总做:数据本身连续时是空操作,
// 而 Metin2 的部分曲线相邻控制点跨半球,不做会让 blend 收缩到近零、归一后转错约 180°
// (表情动作里脖子/头会折叠塌陷)。
//
// 与 granny 的差异(只为健壮):分母为 0 时系数取 0;degree>0 时不循环的一侧 t clamp 到首/尾 knot。
void Curve::eval(float t, float* out, bool underflow_loop, bool overflow_loop, float duration) const {
const int n = (int)knots.size();
if (n == 0 || dim == 0) return;
auto Kc = [&](int i) -> float {
i = i < 0 ? 0 : (i >= (int)n ? (int)n - 1 : i);
return knots[(uint32_t)i];
// Metin2 的 ScaleShearCurve 是 9 维;目前支持的维度为 position=3、orientation=4、scale/shear=9。
if (dim > 9 || controls.size() < size_t(n) * dim) return;
auto normalize4 = [&](float* q) {
float m = std::sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]);
if (m > 1e-12f) for (int d = 0; d < 4; ++d) q[d] /= m;
};
auto copy_ctrl = [&](int i) {
for (uint32_t d = 0; d < dim; ++d) out[d] = controls[size_t(i) * dim + d];
};
if (n == 1) { // 常量
for (uint32_t d = 0; d < dim; ++d) out[d] = controls[d];
return;
}
if (degree <= 0) { // 阶梯(granny SampleBSpline0:最后一个 <= t 的 knot)
uint32_t k = 0;
if (keyframed) { // 按帧号取
int f = 0;
if (knots_sorted) {
const auto it = std::upper_bound(knots.begin(), knots.end(), t);
k = it == knots.begin() ? 0 : uint32_t(it - knots.begin()) - 1;
f = it == knots.begin() ? 0 : int(it - knots.begin()) - 1;
} else {
for (uint32_t j = 0; j < n; ++j) if (knots[j] <= t) k = j;
for (int j = 0; j < n; ++j) if (knots[j] <= t) f = j;
}
for (uint32_t d = 0; d < dim; ++d) out[d] = controls[k * dim + d];
copy_ctrl(f);
return;
}
if (t <= knots[0]) t = knots[0];
if (t >= knots[n - 1]) t = knots[n - 1];
// 第一个 > t 的 knot(找不到 → n-1);升序时二分
int i = (int)n - 1;
const int D = degree < 0 ? 0 : (degree > 3 ? 3 : degree);
if (n == 1) { // 常量(D>0 的单 knot 曲线 granny 走 B 样条,结果仍是该点,四元数归一)
copy_ctrl(0);
if (D > 0 && dim == 4) normalize4(out);
return;
}
// degree 0 不 clamp:t < 首 knot 时 granny 取 knot 0,clamp 会变成 knot 1。
if (D > 0 && !underflow_loop && t < knots[0]) t = knots[0];
if (D > 0 && !overflow_loop && t > knots[n - 1]) t = knots[n - 1];
// CurveFindKnot:第一个 > t 的 knot,找不到 → n-1
int k = n - 1;
if (knots_sorted) {
const int k = int(std::upper_bound(knots.begin(), knots.end(), t) - knots.begin());
if (k < (int)n) i = k;
const int u = int(std::upper_bound(knots.begin(), knots.end(), t) - knots.begin());
if (u < n) k = u;
} else {
for (uint32_t k = 0; k < n; ++k) if (knots[k] > t) { i = (int)k; break; }
for (int j = 0; j < n; ++j) if (knots[j] > t) { k = j; break; }
}
if (i < 1) i = 1;
const int span = (degree == 1) ? 2 : 3; // 本 span 的控制点数 = degree+1
const int first = (degree == 1) ? (i - 1) : (i - 2);
// 拷本 span 的控制点(越界按端点 clamp),四元数做半球连续化
// Metin2 的 ScaleShearCurve 是 9 维;旧的 3*4 缓冲区会在这里发生
// 栈溢出(degree=2 时写入 27 个 float),随后被 __stack_chk_fail 终止。
// 目前支持的曲线维度为 position=3、orientation=4、scale/shear=9。
if (dim > 9) return;
float cp[3 * 9];
for (int s = 0; s < span; ++s) {
int ci = first + s;
ci = ci < 0 ? 0 : (ci >= (int)n ? (int)n - 1 : ci);
for (uint32_t d = 0; d < dim; ++d) cp[s * dim + d] = controls[(uint32_t)ci * dim + d];
// ConstructBSplineBuffers
const int W = D == 0 ? 1 : 2 * D;
const int n_eff = overflow_loop ? n - 1 : n; // 循环时末 knot = 下一遍的首 knot
const int m_loop = n - 1; // Prev/Next 的 knot 数(>1 时减 1)
float bt[6], bp[6 * 9];
const int start0 = k - D;
int local_c = 0, cnt = W, s0 = start0;
if (s0 < 0) { local_c = -s0; cnt = W + s0; s0 = 0; }
const bool over = start0 + W > n_eff;
if (over) cnt = n_eff - s0;
for (int i = 0; i < cnt; ++i) {
bt[local_c + i] = knots[s0 + i];
for (uint32_t d = 0; d < dim; ++d) bp[(local_c + i) * dim + d] = controls[size_t(s0 + i) * dim + d];
}
if (over && cnt > 1 && bt[local_c + cnt - 1] == bt[local_c + cnt - 2])
bt[local_c + cnt - 1] += 1e-5f;
// underflow:向前填 [0, local_c)
{
int j = m_loop - 1;
float off = -duration;
for (int i = local_c - 1; i >= 0; --i) {
if (!underflow_loop) {
bt[i] = bt[local_c];
for (uint32_t d = 0; d < dim; ++d) bp[i * dim + d] = bp[local_c * dim + d];
continue;
}
bt[i] = knots[j] + off;
for (uint32_t d = 0; d < dim; ++d) bp[i * dim + d] = controls[size_t(j) * dim + d];
if (--j < 0) { j = m_loop - 1; off -= duration; }
}
}
// overflow:向后填 (last, W)
{
const int last = local_c + cnt - 1;
int j = 0;
float off = duration;
for (int i = last + 1; i < W; ++i) {
if (!overflow_loop) {
bt[i] = bt[last];
for (uint32_t d = 0; d < dim; ++d) bp[i * dim + d] = bp[last * dim + d];
continue;
}
bt[i] = knots[j] + off;
for (uint32_t d = 0; d < dim; ++d) bp[i * dim + d] = controls[size_t(j) * dim + d];
if (++j == m_loop) { j = 0; off += duration; }
}
}
const float* ti = bt + D; // ti[-D .. D-1]
float* cp = bp; // 本 span 的控制点 pi[-D .. 0] = cp[0 .. D]
if (dim == 4) {
for (int s = 1; s < span; ++s) {
for (int s = 1; s <= D; ++s) {
const float* p = &cp[(s - 1) * 4];
float* q = &cp[s * 4];
if (p[0]*q[0] + p[1]*q[1] + p[2]*q[2] + p[3]*q[3] < 0.0f)
@@ -504,42 +560,50 @@ void Curve::eval(float t, float* out) const {
}
}
if (degree == 1) {
float denom = Kc(i) - Kc(i - 1);
float c0 = denom != 0.0f ? (t - Kc(i - 1)) / denom : 0.0f;
c0 = c0 < 0 ? 0 : (c0 > 1 ? 1 : c0);
float c1 = 1.0f - c0;
for (uint32_t d = 0; d < dim; ++d)
out[d] = c1 * cp[0 * dim + d] + c0 * cp[1 * dim + d];
} else { // degree >= 2 → 二次(Metin2 无 degree 3)
float ti_2 = Kc(i - 2), ti_1 = Kc(i - 1), ti = Kc(i), ti1 = Kc(i + 1);
auto fdiv = [](float a, float b) { return b != 0.0f ? a / b : 0.0f; };
float L0 = fdiv(t - ti_1, ti - ti_1);
float L1_1 = fdiv(t - ti_2, ti - ti_2);
float L1_2 = fdiv(t - ti_1, ti1 - ti_1);
float tmp = (L1_1 + L0) - L0 * L1_1;
float c0 = L0 * L1_2; // ci
float c1 = tmp - c0; // ci_1
float c2 = 1.0f - tmp; // ci_2
for (uint32_t d = 0; d < dim; ++d)
out[d] = c2 * cp[0 * dim + d] + c1 * cp[1 * dim + d] + c0 * cp[2 * dim + d];
auto fdiv = [](float a, float b) { return b != 0.0f ? a / b : 0.0f; };
float c[4]; // c[s] 乘 cp[s]
if (D == 0) {
c[0] = 1.0f;
} else if (D == 1) { // LinearCoefficients
const float a = fdiv(t - ti[-1], ti[0] - ti[-1]);
c[0] = 1.0f - a; c[1] = a;
} else if (D == 2) { // QuadraticCoefficients
const float L0 = fdiv(t - ti[-1], ti[0] - ti[-1]);
const float L1_1 = fdiv(t - ti[-2], ti[0] - ti[-2]);
const float L1_2 = fdiv(t - ti[-1], ti[1] - ti[-1]);
const float tmp = (L1_1 + L0) - L0 * L1_1;
c[2] = L0 * L1_2;
c[1] = tmp - c[2];
c[0] = 1.0f - tmp;
} else { // CubicCoefficients(FUN_10018a20)
const float a = fdiv(t - ti[-1], ti[0] - ti[-1]);
const float b = fdiv(t - ti[-2], ti[0] - ti[-2]);
const float cc = fdiv(t - ti[-1], ti[1] - ti[-1]);
const float d = fdiv(t - ti[-2], ti[1] - ti[-2]);
const float e = fdiv(t - ti[-3], ti[0] - ti[-3]);
const float g = fdiv(t - ti[-1], ti[2] - ti[-1]);
c[0] = (1 - e) * (1 - b) * (1 - a);
c[1] = (1 - a) * b * (1 - d) + (1 - b) * (1 - a) * e + (1 - cc) * a * (1 - d);
c[2] = ((1 - cc) * a + (1 - a) * b) * d + (1 - g) * cc * a;
c[3] = cc * a * g;
}
if (dim == 4) { // 四元数:归一
float m = std::sqrt(out[0]*out[0] + out[1]*out[1] + out[2]*out[2] + out[3]*out[3]);
if (m > 1e-12f) for (int d = 0; d < 4; ++d) out[d] /= m;
for (uint32_t dd = 0; dd < dim; ++dd) {
float v = 0.0f;
for (int s = 0; s <= D; ++s) v += c[s] * cp[s * dim + dd];
out[dd] = v;
}
if (dim == 4 && D > 0) normalize4(out);
}
// t 处的 SRT。position 缺省 (0,0,0),orientation 缺省单位四元数,scaleshear 缺省 I。
void BoneTrack::sample(float t, Transform& out) const {
void BoneTrack::sample(float t, Transform& out, bool ul, bool ol, float dur) const {
out = Transform{};
if (!position.empty()) { position.eval(t, out.position); out.flags |= 0x1; }
if (!orientation.empty()) { orientation.eval(t, out.orientation); out.flags |= 0x2; }
if (!position.empty()) { position.eval(t, out.position, ul, ol, dur); out.flags |= 0x1; }
if (!orientation.empty()) { orientation.eval(t, out.orientation, ul, ol, dur); out.flags |= 0x2; }
if (!scale_shear.empty()) {
if (scale_shear.dim == 9) { scale_shear.eval(t, out.scale_shear); out.flags |= 0x4; }
if (scale_shear.dim == 9) { scale_shear.eval(t, out.scale_shear, ul, ol, dur); out.flags |= 0x4; }
else if (scale_shear.dim == 3) {
float s[3]; scale_shear.eval(t, s);
float s[3]; scale_shear.eval(t, s, ul, ol, dur);
out.scale_shear[0] = s[0]; out.scale_shear[4] = s[1]; out.scale_shear[8] = s[2];
out.flags |= 0x4;
}
@@ -548,11 +612,12 @@ void BoneTrack::sample(float t, Transform& out) const {
// t 处每个 track 的局部 4x4(BuildCompositeTransform4x4 语义:C 上 3x3 = transpose(R3*SS3),
// 平移在 elem 12..14)。
void Animation::sample_local(float t, std::vector<Mat4>& out) const {
void Animation::sample_local(float t, std::vector<Mat4>& out,
bool underflow_loop, bool overflow_loop) const {
out.resize(tracks.size());
Transform x;
for (size_t ti = 0; ti < tracks.size(); ++ti) {
tracks[ti].sample(t, x);
tracks[ti].sample(t, x, underflow_loop, overflow_loop, duration);
out[ti] = compose(x);
}
}
+2 -2
View File
@@ -165,9 +165,9 @@ void bind_pose(const Skeleton& sk, std::vector<Mat4>& world, std::vector<Mat4>&
void sample_pose(const Skeleton& sk, const Animation& an, float t,
std::vector<Mat4>& world, std::vector<Mat4>& skin,
const Mat4* root_offset) {
const Mat4* root_offset, bool underflow_loop, bool overflow_loop) {
std::vector<Mat4> track_local;
an.sample_local(t, track_local);
an.sample_local(t, track_local, underflow_loop, overflow_loop);
std::vector<Mat4> local(sk.bones.size());
for (size_t i = 0; i < sk.bones.size(); ++i) local[i] = sk.bones[i].local_transform; // 默认 = bind
+157 -74
View File
@@ -49,14 +49,14 @@ Gr2MeshDraw ShareGpuMesh(Gr2MeshDraw source) {
Gr2MeshDraw command=source;
command.positions={};command.normals={};command.uv0={};command.diffuse={};command.indices={};
command.bone_indices={};command.bone_weights={};
source.bone_matrices={};
source.palette={};
command.geometry=std::make_shared<const Gr2MeshDraw>(std::move(source));
return command;
}
void UpdateGpuDraws(std::vector<Gr2MeshDraw>& draws,const float* world,const std::vector<gr2::Mat4>& palette) {
for(auto& draw:draws){std::copy_n(world,16,draw.world);draw.bone_matrices.clear();
if(draw.gpu_skinning)for(const auto& matrix:palette)draw.bone_matrices.insert(draw.bone_matrices.end(),matrix.begin(),matrix.end());
}
auto flat=std::make_shared<std::vector<float>>();flat->reserve(palette.size()*16);
for(const auto& matrix:palette)flat->insert(flat->end(),matrix.begin(),matrix.end());
for(auto& draw:draws){std::copy_n(world,16,draw.world);draw.palette=draw.gpu_skinning?flat:nullptr;}
}
inline void MultiplyMat4(const float* a, const float* b, float* out) {
@@ -164,6 +164,13 @@ float Gr2ModelInstance::GetAnimationDuration() const {
return 0.0f;
}
void Gr2ModelInstance::SetAnimationLoop(bool underflow_loop, bool overflow_loop) {
if (underflow_loop == m_loopUnderflow && overflow_loop == m_loopOverflow) return;
m_loopUnderflow = underflow_loop;
m_loopOverflow = overflow_loop;
m_poseValid = false;
}
void Gr2ModelInstance::EvaluatePose(float time) const {
if (!m_file || m_file->file_info().skeletons.empty()) return;
const auto& sk = m_file->file_info().skeletons[0];
@@ -186,7 +193,7 @@ void Gr2ModelInstance::EvaluatePose(float time) const {
m_localPose.resize(sk.bones.size());
for (size_t i=0; i<sk.bones.size(); ++i) m_localPose[i]=sk.bones[i].local_transform;
if (keyTime >= 0) {
anim->sample_local(time, m_trackPose);
anim->sample_local(time, m_trackPose, m_loopUnderflow, m_loopOverflow);
for (size_t i=0; i<m_trackPose.size() && i<m_trackBones.size(); ++i)
if (m_trackBones[i]>=0) m_localPose[m_trackBones[i]]=m_trackPose[i];
}
@@ -202,26 +209,29 @@ void Gr2ModelInstance::EvaluatePose(float time) const {
m_poseAnimation=anim; m_poseTime=keyTime; m_poseValid=true; ++m_poseEvaluations;
}
int Gr2ModelInstance::FindBoneIndex(const std::string& bone_name) const {
if (!m_file || m_file->file_info().skeletons.empty()) return -1;
if (!m_boneIndexBuilt) {
const auto& sk = m_file->file_info().skeletons[0];
m_boneIndex.reserve(sk.bones.size());
for (size_t i = 0; i < sk.bones.size(); ++i) m_boneIndex.emplace(sk.bones[i].name, static_cast<int>(i)); // first match wins
m_boneIndexBuilt = true;
}
auto it = m_boneIndex.find(bone_name);
return it == m_boneIndex.end() ? -1 : it->second;
}
bool Gr2ModelInstance::GetBoneWorldTransform(const std::string& bone_name, float* out_matrix, float animation_time) const {
if (!m_file || m_file->file_info().skeletons.empty() || !out_matrix) return false;
const auto& sk = m_file->file_info().skeletons[0];
int target_bone = -1;
for (size_t i = 0; i < sk.bones.size(); ++i) {
if (sk.bones[i].name == bone_name) {
target_bone = static_cast<int>(i);
break;
}
}
if (target_bone < 0) return false;
return GetBoneWorldTransform(FindBoneIndex(bone_name), out_matrix, animation_time);
}
bool Gr2ModelInstance::GetBoneWorldTransform(int bone_index, float* out_matrix, float animation_time) const {
if (!m_file || m_file->file_info().skeletons.empty() || !out_matrix || bone_index < 0) return false;
if (static_cast<size_t>(bone_index) >= m_file->file_info().skeletons[0].bones.size()) return false;
EvaluatePose(animation_time);
const auto& world_pose = m_worldPose;
if (target_bone >= 0 && target_bone < static_cast<int>(world_pose.size())) {
std::copy(world_pose[target_bone].data(), world_pose[target_bone].data() + 16, out_matrix);
return true;
}
return false;
if (static_cast<size_t>(bone_index) >= m_worldPose.size()) return false;
std::copy(m_worldPose[bone_index].data(), m_worldPose[bone_index].data() + 16, out_matrix);
return true;
}
void Gr2ModelInstance::AttachModel(const std::string& bone_name, std::shared_ptr<Gr2ModelInstance> attachment, const float* offset_matrix) {
@@ -229,6 +239,7 @@ void Gr2ModelInstance::AttachModel(const std::string& bone_name, std::shared_ptr
for (auto& existing : m_attached_models) {
if (existing.bone_name == bone_name) {
existing.model = attachment;
existing.bone_index = FindBoneIndex(bone_name);
if (offset_matrix) {
std::copy(offset_matrix, offset_matrix + 16, existing.offset);
} else {
@@ -239,6 +250,7 @@ void Gr2ModelInstance::AttachModel(const std::string& bone_name, std::shared_ptr
}
AttachedModel am;
am.bone_name = bone_name;
am.bone_index = FindBoneIndex(bone_name);
am.model = attachment;
if (offset_matrix) {
std::copy(offset_matrix, offset_matrix + 16, am.offset);
@@ -282,6 +294,25 @@ void Gr2ModelInstance::SetAttachmentScale(const std::string& bone_name, float sx
void Gr2ModelInstance::SetSkin(const std::string& src_file_name, const std::string& dst_file_name) {
m_skins[SkinKey(src_file_name)] = dst_file_name;
++m_skinGeneration;
}
void Gr2ModelInstance::CacheGpuDraws(std::vector<Gr2MeshDraw>& cache, std::vector<std::string>& base, size_t& gen,
const std::vector<Gr2MeshDraw>& draws) const {
cache = draws;
base.clear();
base.reserve(cache.size());
for (const auto& draw : cache) base.push_back(draw.texture0);
gen = 0; // skins are applied on the first cache hit
}
void Gr2ModelInstance::RefreshGpuSkins(std::vector<Gr2MeshDraw>& cache, const std::vector<std::string>& base, size_t& gen) const {
if (gen == m_skinGeneration) return;
for (size_t i = 0; i < cache.size() && i < base.size(); ++i) {
auto it = m_skins.empty() ? m_skins.end() : m_skins.find(SkinKey(base[i]));
cache[i].texture0 = it != m_skins.end() ? it->second : base[i];
}
gen = m_skinGeneration;
}
void Gr2ModelInstance::ApplySkins(std::vector<Gr2MeshDraw>& draws, size_t first) const {
@@ -300,40 +331,54 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommandsWithPalette(const st
const auto& info = m_file->file_info();
bool has_skin = !skin_matrices.empty();
std::vector<gr2::Mat4> part_skin_matrices = skin_matrices;
m_partSkin.assign(skin_matrices.begin(), skin_matrices.end());
auto& part_skin_matrices = m_partSkin;
// Map this model's skeleton bones to parent skeleton bones by name if a parent skeleton is provided
std::vector<int> part_to_parent_bone_map;
static const std::vector<int> kNoBoneMap;
const std::vector<int>* part_to_parent = &kNoBoneMap;
if (parent_skeleton && !info.skeletons.empty()) {
const auto& my_skel = info.skeletons[0];
std::vector<gr2::Mat4> parent_bind_world, parent_bind_skin;
gr2::bind_pose(*parent_skeleton, parent_bind_world, parent_bind_skin);
part_to_parent_bone_map.resize(my_skel.bones.size(), -1);
if (m_partMapParent != parent_skeleton || m_partMapParentBones != parent_skeleton->bones.size()) {
m_partMapParent = parent_skeleton;
m_partMapParentBones = parent_skeleton->bones.size();
std::vector<gr2::Mat4> parent_bind_world, parent_bind_skin;
gr2::bind_pose(*parent_skeleton, parent_bind_world, parent_bind_skin);
std::unordered_map<std::string, int> parent_by_name;
for (size_t pb = 0; pb < parent_skeleton->bones.size(); ++pb)
parent_by_name.emplace(parent_skeleton->bones[pb].name, static_cast<int>(pb)); // first match wins
m_partToParent.assign(my_skel.bones.size(), -1);
m_partParentBind.assign(my_skel.bones.size(), gr2::Mat4{});
for (size_t b = 0; b < my_skel.bones.size(); ++b) {
auto it = parent_by_name.find(my_skel.bones[b].name);
if (it == parent_by_name.end()) continue;
m_partToParent[b] = it->second;
m_partParentBind[b] = parent_bind_world[it->second];
}
}
part_to_parent = &m_partToParent;
for (size_t b = 0; b < my_skel.bones.size(); ++b) {
const std::string& bname = my_skel.bones[b].name;
for (size_t pb = 0; pb < parent_skeleton->bones.size(); ++pb) {
if (parent_skeleton->bones[pb].name == bname) {
part_to_parent_bone_map[b] = static_cast<int>(pb);
// A shared animation pose does not imply shared inverse bind matrices.
// Recover the parent's animated world pose, then skin with THIS part's
// inverse bind pose (hair exports can have a different rest skeleton).
if (pb < skin_matrices.size()) {
gr2::Mat4 animated_world;
MultiplyMat4(parent_bind_world[pb].data(), skin_matrices[pb].data(), animated_world.data());
MultiplyMat4(my_skel.bones[b].inverse_world.data(), animated_world.data(), part_skin_matrices[pb].data());
}
break;
}
const int pb = m_partToParent[b];
// A shared animation pose does not imply shared inverse bind matrices.
// Recover the parent's animated world pose, then skin with THIS part's
// inverse bind pose (hair exports can have a different rest skeleton).
if (pb >= 0 && static_cast<size_t>(pb) < skin_matrices.size()) {
gr2::Mat4 animated_world;
MultiplyMat4(m_partParentBind[b].data(), skin_matrices[pb].data(), animated_world.data());
MultiplyMat4(my_skel.bones[b].inverse_world.data(), animated_world.data(), part_skin_matrices[pb].data());
}
}
}
const std::vector<int>& part_to_parent_bone_map = *part_to_parent;
hardwareSkinning = hardwareSkinning && part_skin_matrices.size()<=128;
float cachedWorld[16];
if(world_matrix)MultiplyMat4(R_GRANNY_TO_ENGINE,world_matrix,cachedWorld);
else std::copy_n(R_GRANNY_TO_ENGINE,16,cachedWorld);
if(m_gpuPartParent!=parent_skeleton || m_gpuPartPaletteSize!=part_skin_matrices.size()){m_gpuParts.clear();m_gpuPartParent=parent_skeleton;m_gpuPartPaletteSize=part_skin_matrices.size();}
if(hardwareSkinning && !m_gpuParts.empty()) {
const bool cachedParts=hardwareSkinning && !m_gpuParts.empty();
if(cachedParts) {
RefreshGpuSkins(m_gpuParts,m_gpuPartsBaseTex,m_gpuPartsSkinGen);
draws=m_gpuParts;UpdateGpuDraws(draws,cachedWorld,part_skin_matrices);
} else {
for (const auto& mesh : info.meshes) {
@@ -453,13 +498,6 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommandsWithPalette(const st
std::copy(R_GRANNY_TO_ENGINE, R_GRANNY_TO_ENGINE + 16, effective_world);
}
// Pack skin matrices for GPU skinning
std::vector<float> bone_mats_flat;
bone_mats_flat.reserve(skin_matrices.size() * 16);
for (const auto& sm : part_skin_matrices) {
for (int k = 0; k < 16; ++k) bone_mats_flat.push_back(sm[k]);
}
if (mesh.tri_groups.empty()) {
Gr2MeshDraw draw;
std::copy(effective_world, effective_world + 16, draw.world);
@@ -469,7 +507,6 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommandsWithPalette(const st
draw.indices = mesh.indices;
draw.bone_indices = bone_indices;
draw.bone_weights = bone_weights;
draw.bone_matrices = bone_mats_flat;
if (!mesh.material_textures.empty())
draw.texture0 = mesh.material_textures[0];
if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos ||
@@ -478,6 +515,35 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommandsWithPalette(const st
draw.alpha_ref = 70;
}
draws.push_back(std::move(draw));
} else if (hardwareSkinning) {
// Resident GPU geometry: one vertex set per mesh instead of a full copy per tri-group.
Gr2MeshDraw streams;
streams.positions = std::move(skinned_positions);
streams.normals = std::move(skinned_normals);
streams.uv0 = std::move(uvs);
streams.bone_indices = std::move(bone_indices);
streams.bone_weights = std::move(bone_weights);
streams.indices = mesh.indices;
auto geometry = std::make_shared<const Gr2MeshDraw>(std::move(streams));
for (const auto& group : mesh.tri_groups) {
Gr2MeshDraw draw;
std::copy(effective_world, effective_world + 16, draw.world);
draw.geometry = geometry;
std::size_t start_idx = static_cast<std::size_t>(group.tri_first * 3);
std::size_t count_idx = static_cast<std::size_t>(group.tri_count * 3);
draw.first_index = static_cast<uint32_t>(start_idx);
draw.index_count = start_idx + count_idx <= mesh.indices.size() ? static_cast<uint32_t>(count_idx) : 0;
if (group.material_index >= 0 && group.material_index < static_cast<int>(mesh.material_textures.size())) {
draw.texture0 = mesh.material_textures[group.material_index];
}
if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos ||
draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) {
draw.alpha_test = true;
draw.alpha_ref = 70;
}
draws.push_back(std::move(draw));
}
} else {
for (const auto& group : mesh.tri_groups) {
Gr2MeshDraw draw;
@@ -487,7 +553,6 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommandsWithPalette(const st
draw.uv0 = uvs;
draw.bone_indices = bone_indices;
draw.bone_weights = bone_weights;
draw.bone_matrices = bone_mats_flat;
std::size_t start_idx = static_cast<std::size_t>(group.tri_first * 3);
std::size_t count_idx = static_cast<std::size_t>(group.tri_count * 3);
@@ -509,11 +574,11 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommandsWithPalette(const st
}
}
if(hardwareSkinning) {
for(auto& draw:draws){draw.gpu_skinning=!part_skin_matrices.empty();draw=ShareGpuMesh(std::move(draw));}
m_gpuParts=draws;
for(auto& draw:draws){draw.gpu_skinning=!part_skin_matrices.empty();if(!draw.geometry)draw=ShareGpuMesh(std::move(draw));}
CacheGpuDraws(m_gpuParts,m_gpuPartsBaseTex,m_gpuPartsSkinGen,draws);UpdateGpuDraws(draws,cachedWorld,part_skin_matrices);
}
}
ApplySkins(draws, 0);
if(!cachedParts)ApplySkins(draws, 0);
return draws;
}
@@ -532,7 +597,9 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommands(float animation_tim
float cachedWorld[16];
if(world_matrix)MultiplyMat4(R_GRANNY_TO_ENGINE,world_matrix,cachedWorld);
else std::copy_n(R_GRANNY_TO_ENGINE,16,cachedWorld);
if(hardwareSkinning && !m_gpuMain.empty()) {
const bool cachedMain=hardwareSkinning && !m_gpuMain.empty();
if(cachedMain) {
RefreshGpuSkins(m_gpuMain,m_gpuMainBaseTex,m_gpuMainSkinGen);
draws=m_gpuMain;UpdateGpuDraws(draws,cachedWorld,skin_matrices);
} else {
for (const auto& mesh : info.meshes) {
@@ -618,12 +685,6 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommands(float animation_tim
std::copy(R_GRANNY_TO_ENGINE, R_GRANNY_TO_ENGINE + 16, effective_world);
}
std::vector<float> bone_mats_flat;
bone_mats_flat.reserve(skin_matrices.size() * 16);
for (const auto& sm : skin_matrices) {
for (int k = 0; k < 16; ++k) bone_mats_flat.push_back(sm[k]);
}
if (mesh.tri_groups.empty()) {
Gr2MeshDraw draw;
std::copy(effective_world, effective_world + 16, draw.world);
@@ -633,7 +694,6 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommands(float animation_tim
draw.indices = mesh.indices;
draw.bone_indices = bone_indices;
draw.bone_weights = bone_weights;
draw.bone_matrices = bone_mats_flat;
if (!mesh.material_textures.empty())
draw.texture0 = mesh.material_textures[0];
if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos ||
@@ -642,6 +702,35 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommands(float animation_tim
draw.alpha_ref = 70;
}
draws.push_back(std::move(draw));
} else if (hardwareSkinning) {
// Resident GPU geometry: one vertex set per mesh instead of a full copy per tri-group.
Gr2MeshDraw streams;
streams.positions = std::move(skinned_positions);
streams.normals = std::move(skinned_normals);
streams.uv0 = std::move(uvs);
streams.bone_indices = std::move(bone_indices);
streams.bone_weights = std::move(bone_weights);
streams.indices = mesh.indices;
auto geometry = std::make_shared<const Gr2MeshDraw>(std::move(streams));
for (const auto& group : mesh.tri_groups) {
Gr2MeshDraw draw;
std::copy(effective_world, effective_world + 16, draw.world);
draw.geometry = geometry;
std::size_t start_idx = static_cast<std::size_t>(group.tri_first * 3);
std::size_t count_idx = static_cast<std::size_t>(group.tri_count * 3);
draw.first_index = static_cast<uint32_t>(start_idx);
draw.index_count = start_idx + count_idx <= mesh.indices.size() ? static_cast<uint32_t>(count_idx) : 0;
if (group.material_index >= 0 && group.material_index < static_cast<int>(mesh.material_textures.size())) {
draw.texture0 = mesh.material_textures[group.material_index];
}
if (draw.texture0.find("hair") != std::string::npos || mesh.name.find("hair") != std::string::npos ||
draw.texture0.find("leaf") != std::string::npos || draw.texture0.find("tree") != std::string::npos) {
draw.alpha_test = true;
draw.alpha_ref = 70;
}
draws.push_back(std::move(draw));
}
} else {
for (const auto& group : mesh.tri_groups) {
Gr2MeshDraw draw;
@@ -651,7 +740,6 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommands(float animation_tim
draw.uv0 = uvs;
draw.bone_indices = bone_indices;
draw.bone_weights = bone_weights;
draw.bone_matrices = bone_mats_flat;
std::size_t start_idx = static_cast<std::size_t>(group.tri_first * 3);
std::size_t count_idx = static_cast<std::size_t>(group.tri_count * 3);
@@ -674,11 +762,11 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommands(float animation_tim
}
if(hardwareSkinning) {
for(auto& draw:draws){draw.gpu_skinning=!skin_matrices.empty();draw=ShareGpuMesh(std::move(draw));}
m_gpuMain=draws;
for(auto& draw:draws){draw.gpu_skinning=!skin_matrices.empty();if(!draw.geometry)draw=ShareGpuMesh(std::move(draw));}
CacheGpuDraws(m_gpuMain,m_gpuMainBaseTex,m_gpuMainSkinGen,draws);UpdateGpuDraws(draws,cachedWorld,skin_matrices);
}
}
ApplySkins(draws, 0);
if(!cachedMain)ApplySkins(draws, 0);
// 2. Build attached skinning parts (e.g. hair, armor) using current skin matrices
for (const auto& part : m_attached_parts) {
@@ -694,14 +782,8 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommands(float animation_tim
const auto& sk = info.skeletons[0];
for (const auto& am : m_attached_models) {
if (!am.model) continue;
int bone_idx = -1;
for (size_t b = 0; b < sk.bones.size(); ++b) {
if (sk.bones[b].name == am.bone_name) {
bone_idx = static_cast<int>(b);
break;
}
}
if (bone_idx < 0) continue;
const int bone_idx = am.bone_index;
if (bone_idx < 0 || static_cast<size_t>(bone_idx) >= sk.bones.size() || static_cast<size_t>(bone_idx) >= world_pose.size()) continue;
const auto& B = world_pose[bone_idx];
float attached_local[16];
@@ -723,6 +805,7 @@ std::vector<Gr2MeshDraw> Gr2ModelInstance::BuildDrawCommands(float animation_tim
if (am.animated && animation_time >= 0.0f) {
float duration = am.model->GetAnimationDuration();
attach_time = duration > 0.0f ? std::fmod(animation_time, duration) : 0.0f;
am.model->SetAnimationLoop(true, true); // fmod 回绕 = 无限循环
}
auto attach_draws = am.model->BuildDrawCommands(attach_time, nullptr, hardwareSkinning);
for (auto& ad : attach_draws) {
+76 -2
View File
@@ -26,14 +26,15 @@ int main() {
}
}
// Degree 0 with several knots (AVA2 DaKeyframes32f) holds the last knot <= t.
// Degree 0 with several knots: granny SampleBSpline0 takes pi[0], the control of
// the first knot > t (CurveFindKnot, clamped to n-1).
gr2::Curve steps;
steps.degree = 0;
steps.dim = 1;
steps.knots = {0.0f, 0.5f, 1.0f};
steps.controls = {10.0f, 20.0f, 30.0f};
const float step_t[] = {-1.0f, 0.0f, 0.49f, 0.5f, 0.99f, 1.0f, 2.0f};
const float step_v[] = {10.0f, 10.0f, 10.0f, 20.0f, 20.0f, 30.0f, 30.0f};
const float step_v[] = {10.0f, 20.0f, 20.0f, 30.0f, 30.0f, 30.0f, 30.0f};
for (size_t i = 0; i < sizeof step_t / sizeof step_t[0]; ++i) {
float v = 0.0f;
steps.eval(step_t[i], &v);
@@ -42,6 +43,79 @@ int main() {
return 1;
}
}
// DaKeyframes32f (keyframed) picks frame trunc(t/dt), i.e. the last knot <= t.
steps.keyframed = true;
const float key_v[] = {10.0f, 10.0f, 10.0f, 20.0f, 20.0f, 30.0f, 30.0f};
for (size_t i = 0; i < sizeof step_t / sizeof step_t[0]; ++i) {
float v = 0.0f;
steps.eval(step_t[i], &v);
if (v != key_v[i]) {
std::fprintf(stderr, "keyframed t=%f got %f want %f\n", step_t[i], v, key_v[i]);
return 1;
}
}
auto near = [](float a, float b) { return std::fabs(a - b) < 1e-5f; };
// Quadratic loop window (ConstructBSplineBuffers with Prev/Next = the curve itself).
// The last knot repeats the first one, as exported looping curves do.
gr2::Curve loop;
loop.degree = 2;
loop.dim = 1;
loop.knots = {0.0f, 1.0f, 2.0f, 3.0f, 4.0f};
loop.controls = {0.0f, 1.0f, 2.0f, 1.0f, 0.0f};
struct LoopCase { float t; bool ul, ol; float want; };
const LoopCase loop_cases[] = {
{0.5f, false, false, 0.125f}, // clamped: the missing knot -1 repeats knot 0
{0.5f, true, false, 0.25f}, // underflow: knot 3 - 4 with control 1
{3.5f, false, true, 1.0f}, // overflow: knots 0+4, 1+4
{0.0f, true, true, 0.5f}, // seam is continuous when looping ...
{3.99999f, true, true, 0.5f},
{0.0f, false, false, 0.0f}, // ... and not when clamped
};
for (const auto& c : loop_cases) {
float v = -1.0f;
loop.eval(c.t, &v, c.ul, c.ol, 4.0f);
if (std::fabs(v - c.want) > 1e-4f) {
std::fprintf(stderr, "loop t=%f ul=%d ol=%d got %f want %f\n", c.t, c.ul, c.ol, v, c.want);
return 1;
}
}
// Cubic (granny CubicCoefficients). Uniform knots at t == knot: 1/6, 4/6, 1/6, 0.
gr2::Curve cubic;
cubic.degree = 3;
cubic.dim = 1;
for (int i = 0; i < 8; ++i) {
cubic.knots.push_back(float(i));
cubic.controls.push_back(float(i * i));
}
float cv = 0.0f;
cubic.eval(3.0f, &cv);
if (!near(cv, 26.0f / 6.0f)) {
std::fprintf(stderr, "cubic t=3 got %f want %f\n", cv, 26.0f / 6.0f);
return 1;
}
for (float& c : cubic.controls) c = 5.0f; // partition of unity, incl. clamped ends
const float cubic_t[] = {0.0f, 0.3f, 3.3f, 6.7f, 7.0f};
for (float t : cubic_t) {
cubic.eval(t, &cv);
if (!near(cv, 5.0f)) {
std::fprintf(stderr, "cubic constant t=%f got %f\n", t, cv);
return 1;
}
}
// granny GetControlLoopState.
bool ul = false, ol = false;
gr2::control_loop_state(0, 5, false, ul, ol);
if (!ul || !ol) { std::fprintf(stderr, "loop state infinite\n"); return 1; }
gr2::control_loop_state(3, 0, false, ul, ol);
if (ul || !ol) { std::fprintf(stderr, "loop state first\n"); return 1; }
gr2::control_loop_state(3, 2, false, ul, ol);
if (!ul || ol) { std::fprintf(stderr, "loop state last\n"); return 1; }
gr2::control_loop_state(0, 0, true, ul, ol);
if (ul || ol) { std::fprintf(stderr, "loop state clamped\n"); return 1; }
// BoneTrack::sample fills SRT components and flags; sample_local = compose(sample).
gr2::BoneTrack track;