Files
shenandshen 62a5f5ad11 Fix terminal foliage dispatch on frond branches
Generate authored terminal leaves independently of frond activation, matching the recovered last-level dispatch. This prevents three umbrella-thorn copies from expanding leaf cards into full frond nodes and hitting the node budget.

Add an active-frond regression with 17500 terminal cards and record verification: all 606 resources generate without truncation, SDK and client targeted tests pass, and corpus ASan/UBSan checks pass.
2026-10-12 18:52:02 -07:00
..

SpeedTree Cross-Platform Foliage SDK

A C++20, graphics-API-agnostic SDK for legacy SPT metadata and procedural foliage. Tree assets now generate limb hierarchies from their authored Bezier curves and seed. Wind uses indexed weighted matrices and pivot-based leaf rocking, with reference GLSL for generic matrix deformation and fallback rocking. Authored leaf card dimensions, pivots, camera orientation and grouped rocking now use a CPU path; that authored-card path is not yet implemented in the standalone reference GLSL. AVA2's active Metal/SPIR-V scene pipeline now implements it alongside native wind, with a CPU fallback. Independent branch/leaf/frond LODs are cached per model; their decimation rules remain SDK approximations. Authored branch density and indexed attachment sampling are restored, while full original random distribution is incomplete. The generator now restores branch-entry draw ordering, normalized child spline positions, original longitudinal segment counts, and a separate terminal authored-leaf path. Branch frames now inherit source basis rotations, apply perturbations/default Z-up gravity, and use authored axial exponents. Special leaf pools respect authored thresholds, ancestor depth and probability. Geometry uses 32-bit indices throughout; GetGenerationStats exposes per-level node counts, terminal leaf calls and explicit allocation-limit reasons. WasGenerationTruncated reports these limits. Forest updates use the original AVA2 four-matrix controller and legacy leaf rocking phase. The standalone wind fallback and branch scheduling remain approximations of the original SpeedTreeRT runtime.

The SPT reader now follows the token grammar recovered from the AVA2 runtime: tree size/variance (2006/2007), near/far LOD (2003/2001), atlas UV quads, texture names, collision objects and wind metadata. It reads explicit little-endian values, checks lengths/counts and exposes unsupported extensions through metadata_complete, unsupported_token, and error. Invalid files return false; model factories return null instead of silently fabricating a tree. Billboard support includes camera-facing vertical quads, optional horizontal quads, 360-degree atlas transitions and alpha-test distance switching in AVA2. Fronds now use authored blade/profile modes, branch levels, texture sizing and profile splines, with CPU wind and AVA2 draw integration. Geometry dimensions and limb placement still come from our approximate generated meshes. See reverse engineering coverage.

For reproducible snapshots, build with SPEEDTREE_BUILD_TESTS=ON, then run generation_baseline SPT_DIRECTORY > baseline.jsonl. It sorts the corpus paths and records authored seed, hierarchy counts, bounds, per-LOD topology and hashes. Run python3 tools/compare_generation_baselines.py before.jsonl after.jsonl to compare snapshots of the same directory. The snapshots measure this replacement; they do not establish equivalence to the Windows DLL.

🌟 核心特性与渲染真实度突破(Realism & Shading)

以下渲染与风力效果是本 SDK 的程序化近似方案;尚未经过原 DLL 的动态等价验证:

1. 三级分层风场动力学 (3-Tier Hierarchical Wind Dynamics)

  • Level 1 树干弯曲 (Trunk Bending): 基于树高的二次曲线响应,具备长度保持(Length-Preserving)算法,模拟主干在阵风下的柔韧弯曲。
  • Level 2 树枝摇曳 (Branch Sway): 引入大分支相对主干的摆动阻尼与相位差(Phase Offset),营造起伏有致的林间韵律。
  • Level 3 叶片自转翻滚与颤动 (Leaf Flutter & Tumble): 这是“飘逸感”的最关键核心。每个树叶卡片顶点都绑定了叶片局部中心锚点(leaf_pivot_offset)。在微风与阵风下,叶片围绕自身锚点高频翻滚微颤,光影鳞鳞闪烁,彻底消除僵硬片状感。
  • 空间阵风波 (Spatial Gust Waves): 风场跨越坐标系传递低频起伏波,使森林呈现一波波风浪拂过的生动波纹。

2. 树冠球形法线混合 (Canopy Spherical Normal Blending)

  • 传统 Billboard/插片树叶最大的痛点是“纸片感”与法线杂乱破碎。
  • 本 SDK 在几何生成和 Shader 中自动计算以树冠重心为起点的虚拟球形法线(Spherical Normal),并与叶片原始朝向做柔和加权混合。即使是由十字交叉面片组成的树冠,在阳光下也能呈现出浑厚、饱满的体积感。

3. 次表面透射与半兰伯特环绕光 (Subsurface Scattering & Wrap Lighting)

  • 背光透射 (Subsurface Transmission): 逆光观察树木时,阳光穿透薄叶片,Shader 自动产生透光的翠绿光晕(viewThrough = pow(dot(-L, V), 3.5))。
  • 半兰伯特环绕光 (Wrap Lighting): 漫反射平滑过渡,背光区域不会死黑。
  • 树冠内部自遮挡 (Canopy Interior AO): 依据叶片距树冠中心的距离衰减环境光,外层明亮透光、内部深邃幽暗。

4. 跨平台双管线支持 (Modern GPU Shader + CPU Fallback)

  • 现代 GPU 管线: 提供标准的 foliage_shaders.h(GLSL 450 / Vulkan SPIR-V / Metal / D3D11-12 兼容),顶点着色器硬件级高帧率解算风力与球形法线。
  • CPU Fallback 管线: 提供 EvaluateCpuTransformedVertices(),在老旧驱动或无自定义 Shader 环境下依然能实时计算风力变形。

📁 模块架构

sdk/speedtree/
├── include/speedtree/
│   ├── speedtree.h         # 核心模型、顶点布局、SPT 信息、森林实例管理
│   └── foliage_shaders.h   # 现代 GPU 植被顶点/片元着色器源码(含 3 级风力与次表面透光)
├── src/
│   ├── spt_parser.cpp      # .prt 属性文本解析与路径处理
│   ├── spt_reader.cpp      # 有边界检查的原版 SPT 元数据语法(含未支持扩展诊断)
│   ├── branch_spline.cpp   # BezierSpline 与每模型独立的旧版随机序列
│   ├── branch_generator.cpp # 曲线驱动的分枝网格与叶片
│   ├── lod.cpp            # 独立网格缩减、叶片子集与 LOD 尺寸调整
│   ├── leaf.cpp           # 原版叶片支点、镜像与朝向旋转
│   ├── frond.cpp          # 带片/弧面 frond 网格、纹理尺寸与 UV
│   ├── billboard.cpp      # 原版视角纹理选择、水平与垂直远景贴片
│   ├── wind.cpp           # 加权风力矩阵、叶片支点和法线变形
│   ├── tree_generator.cpp  # 树木骨架圆柱网格、树冠卡片、风力权重生成与 CPU 变形求值
│   └── forest.cpp          # 森林多实例生命周期、视锥剔除基础、风向风力统一控制
└── tests/
    └── speedtree_test.cpp  # 单元测试(生成、Token 嗅探、风力位移)

🚀 集成与使用示例

#include <speedtree/speedtree.h>

// 1. 创建树木模板(可从 .spt 文件或通过参数化生成)
auto model = speedtree::SpeedTreeModel::CreateFromSpt("ymir work/tree/b1_baobab_rt.spt");

// 2. 森林多实例管理
speedtree::SpeedTreeForest forest;
forest.RegisterProperty(crc, "d:/ymir work/tree/b1_baobab.prt");
auto* instance = forest.CreateInstance(150.0f, 0.0f, 320.0f, crc, 45.0f, 1.0f);

// 3. 帧循环更新风力
forest.SetWindStrength(1.5f);
forest.Update(deltaTime);