Initialize shared Metin2 SDK with rendering optimizations and tests
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(libspeedtree CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
set(SPEEDTREE_SOURCES
|
||||
src/spt_parser.cpp
|
||||
src/tree_generator.cpp
|
||||
src/forest.cpp
|
||||
)
|
||||
|
||||
set(SPEEDTREE_HEADERS
|
||||
include/speedtree/speedtree.h
|
||||
include/speedtree/foliage_shaders.h
|
||||
)
|
||||
|
||||
add_library(speedtree STATIC
|
||||
${SPEEDTREE_SOURCES}
|
||||
${SPEEDTREE_HEADERS}
|
||||
)
|
||||
|
||||
add_library(speedtree::speedtree ALIAS speedtree)
|
||||
|
||||
target_include_directories(speedtree PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
# Standalone Unit Test
|
||||
option(SPEEDTREE_BUILD_TESTS "Build SpeedTree SDK tests" ON)
|
||||
if(SPEEDTREE_BUILD_TESTS)
|
||||
enable_testing()
|
||||
add_executable(speedtree_test tests/speedtree_test.cpp)
|
||||
target_link_libraries(speedtree_test PRIVATE speedtree)
|
||||
add_test(NAME speedtree_test COMMAND speedtree_test)
|
||||
endif()
|
||||
@@ -0,0 +1,63 @@
|
||||
# SpeedTree Cross-Platform Foliage SDK
|
||||
|
||||
A pure C++20, graphics-API-agnostic implementation of SpeedTree foliage rendering and wind dynamics for cross-platform game engines.
|
||||
|
||||
## 🌟 核心特性与渲染真实度突破(Realism & Shading)
|
||||
|
||||
为了达到与商业版 SpeedTree 同样真实、飘逸自然的渲染质感,本 SDK 实现了以下四大核心技术管线:
|
||||
|
||||
### 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 环境下依然能实时计算风力变形。
|
||||
|
||||
---
|
||||
|
||||
## 📁 模块架构
|
||||
|
||||
```text
|
||||
sdk/speedtree/
|
||||
├── include/speedtree/
|
||||
│ ├── speedtree.h # 核心模型、顶点布局、SPT 信息、森林实例管理
|
||||
│ └── foliage_shaders.h # 现代 GPU 植被顶点/片元着色器源码(含 3 级风力与次表面透光)
|
||||
├── src/
|
||||
│ ├── spt_parser.cpp # 官方 .spt 二进制解析(Token 2000/2001/10000/10002/12000 等)
|
||||
│ ├── tree_generator.cpp # 树木骨架圆柱网格、树冠卡片、风力权重生成与 CPU 变形求值
|
||||
│ └── forest.cpp # 森林多实例生命周期、视锥剔除基础、风向风力统一控制
|
||||
└── tests/
|
||||
└── speedtree_test.cpp # 单元测试(生成、Token 嗅探、风力位移)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 集成与使用示例
|
||||
|
||||
```cpp
|
||||
#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);
|
||||
```
|
||||
@@ -0,0 +1,161 @@
|
||||
#pragma once
|
||||
|
||||
namespace speedtree {
|
||||
|
||||
// Reference GLSL / Vulkan / Metal / OpenGL 4.5+ shader sources for high-fidelity foliage rendering.
|
||||
// Can be embedded or compiled into SPIR-V.
|
||||
|
||||
inline const char* GetFoliageVertexShaderGLSL() {
|
||||
return R"glsl(
|
||||
#version 450 core
|
||||
|
||||
layout(location = 0) in vec3 in_Position;
|
||||
layout(location = 1) in vec3 in_Normal;
|
||||
layout(location = 2) in vec2 in_TexCoord;
|
||||
layout(location = 3) in vec4 in_WindWeights; // [0]:Trunk, [1]:Branch, [2]:Leaf, [3]:Phase
|
||||
layout(location = 4) in vec3 in_LeafPivotOffset; // Leaf center to vertex
|
||||
layout(location = 5) in uint in_Diffuse;
|
||||
|
||||
layout(std140, binding = 0) uniform FrameBlock {
|
||||
mat4 u_ViewProj;
|
||||
vec3 u_CameraPos;
|
||||
float u_Time;
|
||||
vec3 u_WindDir;
|
||||
float u_WindStrength;
|
||||
};
|
||||
|
||||
layout(std140, binding = 1) uniform InstanceBlock {
|
||||
mat4 u_ModelMatrix;
|
||||
vec3 u_TreeOrigin;
|
||||
float u_TreeHeight;
|
||||
};
|
||||
|
||||
layout(location = 0) out vec3 v_WorldPos;
|
||||
layout(location = 1) out vec3 v_WorldNormal;
|
||||
layout(location = 2) out vec2 v_TexCoord;
|
||||
layout(location = 3) out float v_CanopyAO;
|
||||
|
||||
vec3 RotateAngleAxis(vec3 v, vec3 axis, float angle) {
|
||||
float cosTheta = cos(angle);
|
||||
float sinTheta = sin(angle);
|
||||
return v * cosTheta + cross(axis, v) * sinTheta + axis * dot(axis, v) * (1.0 - cosTheta);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 localPos = in_Position;
|
||||
vec3 localNormal = in_Normal;
|
||||
|
||||
float trunkW = in_WindWeights.r;
|
||||
float branchW = in_WindWeights.g;
|
||||
float leafW = in_WindWeights.b;
|
||||
float phase = in_WindWeights.a;
|
||||
|
||||
// Level 0: Global Wind Gust Wave
|
||||
float gustSpatial = dot(u_TreeOrigin.xz, u_WindDir.xz * 0.04);
|
||||
float gust = sin(u_Time * 0.8 + gustSpatial) * 0.5 + 0.5;
|
||||
float effectiveWind = u_WindStrength * (0.8 + 0.4 * gust);
|
||||
|
||||
vec3 windCrossAxis = normalize(cross(vec3(0.0, 1.0, 0.0), u_WindDir));
|
||||
|
||||
// Level 1: Trunk bending (quadratic height response, length-preserving)
|
||||
float trunkAngle = (trunkW * trunkW) * effectiveWind * 0.12 * sin(u_Time * 1.2 + gustSpatial);
|
||||
localPos = RotateAngleAxis(localPos, windCrossAxis, trunkAngle);
|
||||
localNormal = RotateAngleAxis(localNormal, windCrossAxis, trunkAngle);
|
||||
|
||||
// Level 2: Branch sway
|
||||
if (branchW > 0.01) {
|
||||
float branchOsc = sin(u_Time * 2.5 + phase * 6.28 + gustSpatial * 2.0);
|
||||
float branchAngle = branchW * effectiveWind * 0.15 * branchOsc;
|
||||
localPos = RotateAngleAxis(localPos, windCrossAxis, branchAngle);
|
||||
localNormal = RotateAngleAxis(localNormal, windCrossAxis, branchAngle);
|
||||
}
|
||||
|
||||
// Level 3: Leaf flutter and tumble around leaf pivot (Leaf Shimmering!)
|
||||
if (leafW > 0.01) {
|
||||
float leafOsc = sin(u_Time * 8.0 + phase * 15.0 + dot(localPos, vec3(1.0)));
|
||||
float leafAngle = leafW * (0.2 + 0.2 * gust) * leafOsc;
|
||||
|
||||
vec3 leafRel = in_LeafPivotOffset;
|
||||
vec3 rotatedOffset = RotateAngleAxis(leafRel, u_WindDir, leafAngle);
|
||||
localPos += (rotatedOffset - leafRel);
|
||||
localNormal = RotateAngleAxis(localNormal, u_WindDir, leafAngle);
|
||||
}
|
||||
|
||||
vec3 worldPos = (u_ModelMatrix * vec4(localPos, 1.0)).xyz;
|
||||
vec3 worldNormal = normalize((u_ModelMatrix * vec4(localNormal, 0.0)).xyz);
|
||||
|
||||
// Spherical / Canopy Normal Blending (removes paper-thin leaf look)
|
||||
vec3 crownCenter = u_TreeOrigin + vec3(0.0, u_TreeHeight * 0.65, 0.0);
|
||||
vec3 sphericalNormal = normalize(worldPos - crownCenter);
|
||||
worldNormal = normalize(mix(worldNormal, sphericalNormal, leafW * 0.65));
|
||||
|
||||
// Canopy interior AO
|
||||
float distToCenter = length(worldPos - crownCenter);
|
||||
v_CanopyAO = clamp(distToCenter / (u_TreeHeight * 0.45), 0.35, 1.0);
|
||||
|
||||
v_WorldPos = worldPos;
|
||||
v_WorldNormal = worldNormal;
|
||||
v_TexCoord = in_TexCoord;
|
||||
|
||||
gl_Position = u_ViewProj * vec4(worldPos, 1.0);
|
||||
}
|
||||
)glsl";
|
||||
}
|
||||
|
||||
inline const char* GetFoliageFragmentShaderGLSL() {
|
||||
return R"glsl(
|
||||
#version 450 core
|
||||
|
||||
layout(location = 0) in vec3 v_WorldPos;
|
||||
layout(location = 1) in vec3 v_WorldNormal;
|
||||
layout(location = 2) in vec2 v_TexCoord;
|
||||
layout(location = 3) in float v_CanopyAO;
|
||||
|
||||
layout(binding = 0) uniform sampler2D u_DiffuseAtlas;
|
||||
|
||||
layout(std140, binding = 2) uniform LightBlock {
|
||||
vec3 u_SunDir;
|
||||
vec3 u_SunColor;
|
||||
vec3 u_AmbientSky;
|
||||
vec3 u_CameraPos;
|
||||
};
|
||||
|
||||
layout(location = 0) out vec4 out_Color;
|
||||
|
||||
void main() {
|
||||
vec4 texColor = texture(u_DiffuseAtlas, v_TexCoord);
|
||||
|
||||
// Alpha Cutoff
|
||||
if (texColor.a < 0.45) {
|
||||
discard;
|
||||
}
|
||||
|
||||
vec3 N = normalize(v_WorldNormal);
|
||||
vec3 L = normalize(u_SunDir);
|
||||
vec3 V = normalize(u_CameraPos - v_WorldPos);
|
||||
vec3 H = normalize(L + V);
|
||||
|
||||
// Wrap Lighting (Half-Lambert)
|
||||
float NdotL = dot(N, L);
|
||||
float wrapNdotL = max(0.0, (NdotL + 0.35) / 1.35);
|
||||
vec3 diffuse = texColor.rgb * u_SunColor * wrapNdotL;
|
||||
|
||||
// Subsurface Transmission (Sunlight penetrating leaf)
|
||||
float viewThrough = max(0.0, dot(-L, V));
|
||||
float transIntensity = pow(viewThrough, 3.5) * 0.85;
|
||||
vec3 transColor = texColor.rgb * vec3(1.1, 1.3, 0.7) * u_SunColor * transIntensity;
|
||||
|
||||
// Specular Highlight
|
||||
float NdotH = max(0.0, dot(N, H));
|
||||
float specular = pow(NdotH, 32.0) * 0.25;
|
||||
|
||||
// Canopy AO & Ambient
|
||||
vec3 ambient = u_AmbientSky * texColor.rgb * v_CanopyAO;
|
||||
|
||||
vec3 finalRGB = (diffuse + transColor + specular) * v_CanopyAO + ambient;
|
||||
out_Color = vec4(finalRGB, 1.0);
|
||||
}
|
||||
)glsl";
|
||||
}
|
||||
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,181 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <map>
|
||||
|
||||
namespace speedtree {
|
||||
|
||||
constexpr float kPI = 3.14159265358979323846f;
|
||||
constexpr float kTAU = 2.0f * kPI;
|
||||
|
||||
struct UVRect {
|
||||
float u0 = 0.0f;
|
||||
float v0 = 0.0f;
|
||||
float u1 = 1.0f;
|
||||
float v1 = 1.0f;
|
||||
};
|
||||
|
||||
// Unified vertex layout for modern GPU foliage rendering
|
||||
// Compatible with Vulkan, Metal, DX11/12, OpenGL
|
||||
struct SpeedTreeVertex {
|
||||
float position[3]; // Local space (Z-forward / Y-up)
|
||||
float normal[3]; // Blended spherical / canopy normal
|
||||
float uv[2]; // Texture atlas coordinates
|
||||
float wind_weights[4]; // [0]: Trunk bend, [1]: Branch sway, [2]: Leaf flutter, [3]: Phase
|
||||
float leaf_pivot_offset[3]; // Vector from leaf cluster pivot to vertex (for rotation/tumble)
|
||||
uint32_t diffuse; // RGBA8 (Canopy AO in alpha/rgb, default 0xFFFFFFFF)
|
||||
};
|
||||
|
||||
// Represents a submesh (Trunk or Leaf/Canopy)
|
||||
struct SpeedTreeMesh {
|
||||
std::string name;
|
||||
std::vector<SpeedTreeVertex> vertices;
|
||||
std::vector<uint32_t> indices;
|
||||
std::string texture;
|
||||
bool is_leaf = false;
|
||||
bool is_double_sided = false;
|
||||
bool alpha_test = false;
|
||||
float alpha_ref = 0.45f;
|
||||
};
|
||||
|
||||
struct SpeedTreeSptInfo {
|
||||
bool ok = false;
|
||||
float size = 1000.0f;
|
||||
float variance = 0.0f;
|
||||
std::string bark_texture;
|
||||
std::string leaf_texture;
|
||||
std::string shadow_texture;
|
||||
std::vector<UVRect> leaf_uvs;
|
||||
std::vector<UVRect> frond_uvs;
|
||||
std::vector<UVRect> billboard_uvs;
|
||||
|
||||
static bool SniffFile(const std::string& filepath, SpeedTreeSptInfo& out);
|
||||
static bool SniffMemory(const uint8_t* data, size_t size, SpeedTreeSptInfo& out);
|
||||
static bool SniffSpt(const std::string& filepath, SpeedTreeSptInfo& out) { return SniffFile(filepath, out); }
|
||||
};
|
||||
|
||||
struct SpeedTreeProperty {
|
||||
uint32_t crc = 0;
|
||||
std::string property_name;
|
||||
std::string tree_file;
|
||||
float tree_size = 1000.0f;
|
||||
float tree_variance = 0.0f;
|
||||
|
||||
static bool LoadFromFile(const std::string& filename, SpeedTreeProperty& out);
|
||||
};
|
||||
|
||||
// Wind configuration and evaluation parameters
|
||||
struct WindParameters {
|
||||
float time = 0.0f;
|
||||
float strength = 1.0f; // 0.0: calm, 1.0: gentle breeze, 2.5: storm
|
||||
float direction[3] = {1.0f, 0.0f, 0.0f}; // Normalized wind direction
|
||||
float gust_frequency = 0.8f;
|
||||
float gust_strength = 0.5f;
|
||||
};
|
||||
|
||||
// Core Model class representing a unique species/variant of tree
|
||||
class SpeedTreeModel {
|
||||
public:
|
||||
SpeedTreeModel();
|
||||
~SpeedTreeModel() = default;
|
||||
|
||||
static std::shared_ptr<SpeedTreeModel> Create(const std::string& sptPath, float treeSize = 1000.0f) { return CreateFromSpt(sptPath, treeSize); }
|
||||
static std::shared_ptr<SpeedTreeModel> CreateFromSpt(const std::string& sptPath, float treeSize = 1000.0f);
|
||||
static std::shared_ptr<SpeedTreeModel> CreateFromMemory(const uint8_t* data, size_t size,
|
||||
const std::string& name = "", float treeSize = 1000.0f);
|
||||
static std::shared_ptr<SpeedTreeModel> CreateProcedural(const std::string& species_name, float height = 1000.0f,
|
||||
const std::string& bark_tex = "",
|
||||
const std::string& leaf_tex = "");
|
||||
|
||||
const SpeedTreeMesh& GetTrunkMesh() const { return m_trunk; }
|
||||
const SpeedTreeMesh& GetLeafMesh() const { return m_leaf; }
|
||||
|
||||
float GetHeight() const { return m_height; }
|
||||
float GetRadius() const { return m_radius; }
|
||||
bool IsGrassOrShrub() const { return m_is_grass_or_shrub; }
|
||||
const std::string& GetName() const { return m_name; }
|
||||
const std::string& GetBarkTexture() const { return m_bark_texture; }
|
||||
const std::string& GetLeafTexture() const { return m_leaf_texture; }
|
||||
const SpeedTreeSptInfo& GetSptInfo() const { return m_info; }
|
||||
|
||||
// CPU fallback vertex deformer for legacy clients/renderers without custom foliage vertex shaders
|
||||
void EvaluateCpuTransformedVertices(const SpeedTreeMesh& src_mesh,
|
||||
std::vector<float>& out_positions,
|
||||
std::vector<float>& out_normals,
|
||||
float worldX, float worldY, float worldZ,
|
||||
float yawDeg, float scale,
|
||||
const WindParameters& wind) const;
|
||||
|
||||
private:
|
||||
void BuildGeometry(const SpeedTreeSptInfo& info);
|
||||
void BuildTreeGeometry(float H, const SpeedTreeSptInfo& info);
|
||||
void BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& info);
|
||||
|
||||
std::string m_name;
|
||||
std::string m_spt_path;
|
||||
float m_height = 1000.0f;
|
||||
float m_radius = 350.0f;
|
||||
bool m_is_grass_or_shrub = false;
|
||||
|
||||
std::string m_bark_texture;
|
||||
std::string m_leaf_texture;
|
||||
SpeedTreeSptInfo m_info;
|
||||
|
||||
SpeedTreeMesh m_trunk;
|
||||
SpeedTreeMesh m_leaf;
|
||||
};
|
||||
|
||||
// Forest management and batched instance tracking
|
||||
class SpeedTreeForest {
|
||||
public:
|
||||
struct Instance {
|
||||
float x = 0.0f;
|
||||
float y = 0.0f;
|
||||
float z = 0.0f;
|
||||
uint32_t crc = 0;
|
||||
float yaw = 0.0f;
|
||||
float scale = 1.0f;
|
||||
std::string name;
|
||||
std::shared_ptr<SpeedTreeModel> model;
|
||||
};
|
||||
|
||||
SpeedTreeForest();
|
||||
~SpeedTreeForest();
|
||||
|
||||
void Clear();
|
||||
void ClearMainTree();
|
||||
|
||||
bool RegisterProperty(uint32_t crc, const std::string& prtPath);
|
||||
bool RegisterPropertyData(const SpeedTreeProperty& prop);
|
||||
void ScanPropertyDirectory(const std::string& dirPath);
|
||||
|
||||
Instance* CreateInstance(float x, float y, float z, uint32_t crc,
|
||||
float yaw = 0.0f, float scale = 1.0f, const char* name = nullptr);
|
||||
void DeleteInstance(Instance* pTree);
|
||||
|
||||
void Update(float dt);
|
||||
|
||||
size_t GetInstanceCount() const { return m_instances.size(); }
|
||||
size_t GetMainTreeCount() const { return m_tree_templates.size(); }
|
||||
const std::vector<std::unique_ptr<Instance>>& GetInstances() const { return m_instances; }
|
||||
|
||||
std::shared_ptr<SpeedTreeModel> GetMainTree(uint32_t crc);
|
||||
bool HasMainTree(uint32_t crc) const;
|
||||
|
||||
void SetWindStrength(float strength) { m_wind.strength = strength; }
|
||||
float GetWindStrength() const { return m_wind.strength; }
|
||||
|
||||
void SetWindDirection(float x, float y, float z);
|
||||
const WindParameters& GetWindParams() const { return m_wind; }
|
||||
|
||||
private:
|
||||
WindParameters m_wind;
|
||||
std::map<uint32_t, SpeedTreeProperty> m_properties;
|
||||
std::map<uint32_t, std::shared_ptr<SpeedTreeModel>> m_tree_templates;
|
||||
std::vector<std::unique_ptr<Instance>> m_instances;
|
||||
};
|
||||
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,123 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
|
||||
namespace speedtree {
|
||||
|
||||
SpeedTreeForest::SpeedTreeForest() {
|
||||
m_wind.time = 0.0f;
|
||||
m_wind.strength = 1.0f;
|
||||
m_wind.direction[0] = 0.8f;
|
||||
m_wind.direction[1] = 0.0f;
|
||||
m_wind.direction[2] = 0.6f;
|
||||
}
|
||||
|
||||
SpeedTreeForest::~SpeedTreeForest() {
|
||||
Clear();
|
||||
}
|
||||
|
||||
void SpeedTreeForest::Clear() {
|
||||
m_instances.clear();
|
||||
}
|
||||
|
||||
void SpeedTreeForest::ClearMainTree() {
|
||||
m_instances.clear();
|
||||
m_tree_templates.clear();
|
||||
m_properties.clear();
|
||||
}
|
||||
|
||||
void SpeedTreeForest::SetWindDirection(float x, float y, float z) {
|
||||
float len = std::sqrt(x * x + y * y + z * z);
|
||||
if (len > 1e-5f) {
|
||||
m_wind.direction[0] = x / len;
|
||||
m_wind.direction[1] = y / len;
|
||||
m_wind.direction[2] = z / len;
|
||||
}
|
||||
}
|
||||
|
||||
bool SpeedTreeForest::RegisterProperty(uint32_t crc, const std::string& prtPath) {
|
||||
SpeedTreeProperty prop;
|
||||
if (!SpeedTreeProperty::LoadFromFile(prtPath, prop)) {
|
||||
return false;
|
||||
}
|
||||
if (crc != 0) prop.crc = crc;
|
||||
return RegisterPropertyData(prop);
|
||||
}
|
||||
|
||||
bool SpeedTreeForest::RegisterPropertyData(const SpeedTreeProperty& prop) {
|
||||
if (prop.crc == 0) return false;
|
||||
m_properties[prop.crc] = prop;
|
||||
auto model = SpeedTreeModel::CreateFromSpt(prop.tree_file, prop.tree_size);
|
||||
m_tree_templates[prop.crc] = model;
|
||||
return true;
|
||||
}
|
||||
|
||||
void SpeedTreeForest::ScanPropertyDirectory(const std::string& dirPath) {
|
||||
if (!std::filesystem::exists(dirPath)) return;
|
||||
for (const auto& entry : std::filesystem::recursive_directory_iterator(dirPath)) {
|
||||
if (!entry.is_regular_file()) continue;
|
||||
auto path = entry.path().string();
|
||||
if (path.size() >= 4 && path.substr(path.size() - 4) == ".prt") {
|
||||
SpeedTreeProperty prop;
|
||||
if (SpeedTreeProperty::LoadFromFile(path, prop)) {
|
||||
// Compute hash for crc
|
||||
uint32_t hash = 5381;
|
||||
for (char c : prop.tree_file) hash = ((hash << 5) + hash) + static_cast<uint8_t>(c);
|
||||
prop.crc = hash;
|
||||
RegisterPropertyData(prop);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SpeedTreeForest::Instance* SpeedTreeForest::CreateInstance(float x, float y, float z, uint32_t crc,
|
||||
float yaw, float scale, const char* name) {
|
||||
auto model = GetMainTree(crc);
|
||||
if (!model) {
|
||||
// Fallback procedural model
|
||||
model = SpeedTreeModel::CreateProcedural(name ? name : "tree", 1000.0f);
|
||||
m_tree_templates[crc] = model;
|
||||
}
|
||||
|
||||
auto inst = std::make_unique<Instance>();
|
||||
inst->x = x;
|
||||
inst->y = y;
|
||||
inst->z = z;
|
||||
inst->crc = crc;
|
||||
inst->yaw = yaw;
|
||||
inst->scale = (scale > 0.01f) ? scale : 1.0f;
|
||||
inst->name = name ? name : model->GetName();
|
||||
inst->model = model;
|
||||
|
||||
Instance* ptr = inst.get();
|
||||
m_instances.push_back(std::move(inst));
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void SpeedTreeForest::DeleteInstance(Instance* pTree) {
|
||||
auto it = std::remove_if(m_instances.begin(), m_instances.end(),
|
||||
[pTree](const std::unique_ptr<Instance>& inst) {
|
||||
return inst.get() == pTree;
|
||||
});
|
||||
m_instances.erase(it, m_instances.end());
|
||||
}
|
||||
|
||||
void SpeedTreeForest::Update(float dt) {
|
||||
m_wind.time += dt;
|
||||
}
|
||||
|
||||
std::shared_ptr<SpeedTreeModel> SpeedTreeModel_GetMainTree(std::map<uint32_t, std::shared_ptr<SpeedTreeModel>>& map, uint32_t crc) {
|
||||
auto it = map.find(crc);
|
||||
return (it != map.end()) ? it->second : nullptr;
|
||||
}
|
||||
|
||||
std::shared_ptr<SpeedTreeModel> SpeedTreeForest::GetMainTree(uint32_t crc) {
|
||||
return SpeedTreeModel_GetMainTree(m_tree_templates, crc);
|
||||
}
|
||||
|
||||
bool SpeedTreeForest::HasMainTree(uint32_t crc) const {
|
||||
return m_tree_templates.find(crc) != m_tree_templates.end();
|
||||
}
|
||||
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,232 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
namespace speedtree {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string ToLower(std::string s) {
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
|
||||
return static_cast<char>(std::tolower(c));
|
||||
});
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string BaseName(std::string p) {
|
||||
for (char& c : p) if (c == '\\') c = '/';
|
||||
size_t s = p.find_last_of('/');
|
||||
return (s == std::string::npos) ? p : p.substr(s + 1);
|
||||
}
|
||||
|
||||
std::string StripQuotes(const std::string& s) {
|
||||
size_t start = s.find_first_not_of(" \t\r\n\"");
|
||||
if (start == std::string::npos) return "";
|
||||
size_t end = s.find_last_not_of(" \t\r\n\"");
|
||||
return s.substr(start, end - start + 1);
|
||||
}
|
||||
|
||||
bool EndsWithCI(const std::string& s, const char* suf) {
|
||||
size_t n = std::strlen(suf);
|
||||
if (s.size() < n) return false;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (std::tolower((unsigned char)s[s.size() - n + i]) != std::tolower((unsigned char)suf[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string AsDds(std::string s) {
|
||||
if (s.empty()) return s;
|
||||
size_t dot = s.find_last_of('.');
|
||||
if (dot != std::string::npos) s.resize(dot);
|
||||
return s + ".dds";
|
||||
}
|
||||
|
||||
std::string ResolvePath(const std::string& raw) {
|
||||
if (raw.empty()) return raw;
|
||||
std::string clean = raw;
|
||||
for (char& c : clean) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
if (clean.size() > 2 && clean[1] == ':') {
|
||||
clean = clean.substr(2);
|
||||
while (!clean.empty() && clean[0] == '/') clean = clean.substr(1);
|
||||
}
|
||||
std::vector<std::string> roots = {
|
||||
"",
|
||||
"build/dev/",
|
||||
"build/dev/ymir work/",
|
||||
"/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/",
|
||||
"/Users/shen/Work/Code/Metin2/AVA2/1. Client DEV/pack_maker/property/",
|
||||
"/Users/shen/Work/Code/Metin2/ava2-client/"
|
||||
};
|
||||
for (const auto& r : roots) {
|
||||
std::string cand = r + clean;
|
||||
std::ifstream f(cand, std::ios::binary);
|
||||
if (f.good()) return cand;
|
||||
}
|
||||
return clean;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool SpeedTreeProperty::LoadFromFile(const std::string& filename, SpeedTreeProperty& out) {
|
||||
std::string resolved = ResolvePath(filename);
|
||||
std::ifstream f(resolved);
|
||||
if (!f.is_open()) return false;
|
||||
std::string line;
|
||||
bool has_yprt = false;
|
||||
while (std::getline(f, line)) {
|
||||
std::istringstream iss(line);
|
||||
std::string key;
|
||||
if (!(iss >> key)) continue;
|
||||
if (key == "YPRT" || key == "yprt") {
|
||||
has_yprt = true;
|
||||
uint32_t val = 0;
|
||||
if (iss >> val) {
|
||||
out.crc = val;
|
||||
} else if (f >> out.crc) {
|
||||
std::string rem;
|
||||
std::getline(f, rem);
|
||||
}
|
||||
} else if (key == "propertyname" || key == "PropertyName") {
|
||||
std::string rem;
|
||||
std::getline(iss, rem);
|
||||
out.property_name = StripQuotes(rem);
|
||||
} else if (key == "propertytype") {
|
||||
// "Tree"
|
||||
} else if (key == "TreeFile" || key == "treefile" || key == "TreeName") {
|
||||
std::string val;
|
||||
std::getline(iss, val);
|
||||
out.tree_file = StripQuotes(val);
|
||||
} else if (key == "TreeSize" || key == "treesize") {
|
||||
std::string rem;
|
||||
std::getline(iss, rem);
|
||||
try { out.tree_size = std::stof(StripQuotes(rem)); } catch (...) {}
|
||||
} else if (key == "TreeVariance" || key == "treevariance") {
|
||||
std::string rem;
|
||||
std::getline(iss, rem);
|
||||
try { out.tree_variance = std::stof(StripQuotes(rem)); } catch (...) {}
|
||||
}
|
||||
}
|
||||
return !out.tree_file.empty() && (!has_yprt || out.crc != 0);
|
||||
}
|
||||
|
||||
bool SpeedTreeSptInfo::SniffFile(const std::string& filepath, SpeedTreeSptInfo& out) {
|
||||
std::string resolved = ResolvePath(filepath);
|
||||
std::ifstream f(resolved, std::ios::binary);
|
||||
if (!f.is_open()) return false;
|
||||
f.seekg(0, std::ios::end);
|
||||
size_t size = static_cast<size_t>(f.tellg());
|
||||
f.seekg(0, std::ios::beg);
|
||||
if (size < 16) return false;
|
||||
|
||||
std::vector<uint8_t> data(size);
|
||||
f.read(reinterpret_cast<char*>(data.data()), size);
|
||||
return SniffMemory(data.data(), size, out);
|
||||
}
|
||||
|
||||
bool SpeedTreeSptInfo::SniffMemory(const uint8_t* p, size_t n, SpeedTreeSptInfo& out) {
|
||||
if (!p || n < 16) return false;
|
||||
out.ok = true;
|
||||
out.size = 1000.0f;
|
||||
out.variance = 0.0f;
|
||||
out.bark_texture.clear();
|
||||
out.leaf_texture.clear();
|
||||
out.shadow_texture.clear();
|
||||
out.leaf_uvs.clear();
|
||||
out.frond_uvs.clear();
|
||||
out.billboard_uvs.clear();
|
||||
|
||||
auto i32_at = [p, n](size_t o) -> int32_t {
|
||||
if (o + 4 > n) return 0;
|
||||
int32_t val = 0;
|
||||
std::memcpy(&val, p + o, 4);
|
||||
return val;
|
||||
};
|
||||
|
||||
// Parse tokens
|
||||
for (size_t o = 0; o + 8 <= n; ++o) {
|
||||
int32_t token = i32_at(o);
|
||||
if (token == 2000) {
|
||||
// Branch texture name
|
||||
int32_t len = i32_at(o + 4);
|
||||
if (len > 0 && len < 256 && o + 8 + len <= n) {
|
||||
std::string s(reinterpret_cast<const char*>(p + o + 8), len);
|
||||
out.bark_texture = BaseName(s);
|
||||
}
|
||||
} else if (token == 2001) {
|
||||
float sz = 0.0f;
|
||||
std::memcpy(&sz, p + o + 4, 4);
|
||||
if (sz > 1.0f && sz < 50000.0f) out.size = sz;
|
||||
} else if (token == 2002) {
|
||||
float var = 0.0f;
|
||||
std::memcpy(&var, p + o + 4, 4);
|
||||
out.variance = var;
|
||||
} else if (token == 10000 && i32_at(o + 4) == 10002) {
|
||||
size_t c = o + 4;
|
||||
for (int32_t section : {10002, 10003, 10004}) {
|
||||
if (c + 8 > n || i32_at(c) != section) break;
|
||||
int32_t count = i32_at(c + 4);
|
||||
c += 8;
|
||||
if (count <= 0 || count > 64 || c + count * 32 > n) break;
|
||||
auto& target = (section == 10002) ? out.leaf_uvs : (section == 10003 ? out.frond_uvs : out.billboard_uvs);
|
||||
for (int32_t i = 0; i < count; ++i, c += 32) {
|
||||
float f[8];
|
||||
std::memcpy(f, p + c, sizeof(f));
|
||||
target.push_back({f[2], 1.0f - f[1], f[0], 1.0f - f[5]});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// String scan fallback for bark & composite maps
|
||||
std::string cur;
|
||||
std::vector<std::string> str_refs;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
unsigned char c = p[i];
|
||||
if (c >= 0x20 && c < 0x7F) {
|
||||
cur += static_cast<char>(c);
|
||||
} else {
|
||||
if (cur.size() >= 4 && (EndsWithCI(cur, ".tga") || EndsWithCI(cur, ".dds"))) {
|
||||
str_refs.push_back(BaseName(cur));
|
||||
}
|
||||
cur.clear();
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& r : str_refs) {
|
||||
std::string low = ToLower(r);
|
||||
if (out.bark_texture.empty() && low.find("bark") != std::string::npos) {
|
||||
out.bark_texture = AsDds(r);
|
||||
} else if (out.leaf_texture.empty() && (low.find("leaf") != std::string::npos || low.find("leaves") != std::string::npos || low.find("grass") != std::string::npos)) {
|
||||
out.leaf_texture = AsDds(r);
|
||||
}
|
||||
}
|
||||
|
||||
std::string bytes(reinterpret_cast<const char*>(p), n);
|
||||
auto find_token = [&](const char* needle) -> std::string {
|
||||
size_t pos = bytes.find(needle);
|
||||
if (pos == std::string::npos) return "";
|
||||
size_t end = pos + std::strlen(needle);
|
||||
while (end < bytes.size() && (std::isalnum((unsigned char)bytes[end]) || bytes[end] == '_' || bytes[end] == '-')) {
|
||||
++end;
|
||||
}
|
||||
return bytes.substr(pos, end - pos);
|
||||
};
|
||||
|
||||
std::string comp = find_token("CompositeMap");
|
||||
if (!comp.empty()) out.leaf_texture = AsDds(comp);
|
||||
std::string shadow = find_token("CompositeShadowMap");
|
||||
if (!shadow.empty()) out.shadow_texture = AsDds(shadow);
|
||||
|
||||
if (out.bark_texture.empty()) out.bark_texture = "beechbark.dds";
|
||||
if (out.leaf_texture.empty()) out.leaf_texture = "compositemap.dds";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,461 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
|
||||
namespace speedtree {
|
||||
|
||||
namespace {
|
||||
|
||||
bool IsConifer(const std::string& name) {
|
||||
std::string s = name;
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); });
|
||||
return s.find("pine") != std::string::npos || s.find("cypress") != std::string::npos ||
|
||||
s.find("fir") != std::string::npos || s.find("spruce") != std::string::npos ||
|
||||
s.find("cedar") != std::string::npos || s.find("conifer") != std::string::npos ||
|
||||
s.find("tanne") != std::string::npos;
|
||||
}
|
||||
|
||||
inline void RotateY(float x, float z, float cos_a, float sin_a, float& out_x, float& out_z) {
|
||||
out_x = x * cos_a + z * sin_a;
|
||||
out_z = -x * sin_a + z * cos_a;
|
||||
}
|
||||
|
||||
inline void Normalize3(float v[3]) {
|
||||
float len = std::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
|
||||
if (len > 1e-6f) {
|
||||
float inv = 1.0f / len;
|
||||
v[0] *= inv;
|
||||
v[1] *= inv;
|
||||
v[2] *= inv;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
SpeedTreeModel::SpeedTreeModel() {
|
||||
m_trunk.name = "trunk";
|
||||
m_trunk.is_leaf = false;
|
||||
m_trunk.is_double_sided = false;
|
||||
m_trunk.alpha_test = false;
|
||||
|
||||
m_leaf.name = "leaf";
|
||||
m_leaf.is_leaf = true;
|
||||
m_leaf.is_double_sided = true;
|
||||
m_leaf.alpha_test = true;
|
||||
m_leaf.alpha_ref = 0.45f;
|
||||
}
|
||||
|
||||
std::shared_ptr<SpeedTreeModel> SpeedTreeModel::CreateFromSpt(const std::string& sptPath, float treeSize) {
|
||||
auto model = std::make_shared<SpeedTreeModel>();
|
||||
model->m_spt_path = sptPath;
|
||||
|
||||
// Extract base name
|
||||
size_t last_slash = sptPath.find_last_of("/\\");
|
||||
model->m_name = (last_slash == std::string::npos) ? sptPath : sptPath.substr(last_slash + 1);
|
||||
|
||||
SpeedTreeSptInfo info;
|
||||
if (SpeedTreeSptInfo::SniffFile(sptPath, info)) {
|
||||
if (info.size > 1.0f) model->m_height = info.size;
|
||||
else model->m_height = treeSize;
|
||||
model->BuildGeometry(info);
|
||||
} else {
|
||||
model->m_height = treeSize;
|
||||
info.size = treeSize;
|
||||
info.bark_texture = "beechbark.dds";
|
||||
info.leaf_texture = "compositemap.dds";
|
||||
model->BuildGeometry(info);
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
std::shared_ptr<SpeedTreeModel> SpeedTreeModel::CreateFromMemory(const uint8_t* data, size_t size,
|
||||
const std::string& name, float treeSize) {
|
||||
auto model = std::make_shared<SpeedTreeModel>();
|
||||
model->m_name = name.empty() ? "tree" : name;
|
||||
|
||||
SpeedTreeSptInfo info;
|
||||
if (SpeedTreeSptInfo::SniffMemory(data, size, info)) {
|
||||
if (info.size > 1.0f) model->m_height = info.size;
|
||||
else model->m_height = treeSize;
|
||||
model->BuildGeometry(info);
|
||||
} else {
|
||||
model->m_height = treeSize;
|
||||
info.size = treeSize;
|
||||
info.bark_texture = "beechbark.dds";
|
||||
info.leaf_texture = "compositemap.dds";
|
||||
model->BuildGeometry(info);
|
||||
}
|
||||
return model;
|
||||
}
|
||||
|
||||
std::shared_ptr<SpeedTreeModel> SpeedTreeModel::CreateProcedural(const std::string& species_name, float height,
|
||||
const std::string& bark_tex, const std::string& leaf_tex) {
|
||||
auto model = std::make_shared<SpeedTreeModel>();
|
||||
model->m_name = species_name;
|
||||
model->m_height = height;
|
||||
|
||||
SpeedTreeSptInfo info;
|
||||
info.ok = true;
|
||||
info.size = height;
|
||||
info.bark_texture = bark_tex.empty() ? "beechbark.dds" : bark_tex;
|
||||
info.leaf_texture = leaf_tex.empty() ? "compositemap.dds" : leaf_tex;
|
||||
model->BuildGeometry(info);
|
||||
return model;
|
||||
}
|
||||
|
||||
void SpeedTreeModel::BuildGeometry(const SpeedTreeSptInfo& info) {
|
||||
m_info = info;
|
||||
m_bark_texture = info.bark_texture;
|
||||
m_leaf_texture = info.leaf_texture;
|
||||
|
||||
std::string lowerName = m_name;
|
||||
std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), [](unsigned char c) { return std::tolower(c); });
|
||||
m_is_grass_or_shrub = (lowerName.find("grass") != std::string::npos ||
|
||||
lowerName.find("shrub") != std::string::npos ||
|
||||
lowerName.find("bush") != std::string::npos ||
|
||||
lowerName.find("flower") != std::string::npos ||
|
||||
m_height < 150.0f);
|
||||
|
||||
float H = m_height;
|
||||
if (m_is_grass_or_shrub) {
|
||||
BuildGrassShrubGeometry(H, info);
|
||||
} else {
|
||||
BuildTreeGeometry(H, info);
|
||||
}
|
||||
}
|
||||
|
||||
void SpeedTreeModel::BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& info) {
|
||||
m_trunk.vertices.clear();
|
||||
m_trunk.indices.clear();
|
||||
m_leaf.vertices.clear();
|
||||
m_leaf.indices.clear();
|
||||
|
||||
m_leaf.texture = m_leaf_texture;
|
||||
float W = H * 0.85f;
|
||||
float hW = W * 0.5f;
|
||||
|
||||
UVRect uv{0.0f, 0.0f, 1.0f, 1.0f};
|
||||
if (!info.leaf_uvs.empty()) uv = info.leaf_uvs[0];
|
||||
|
||||
// 3 intersecting vertical planes (0, 60, 120 degrees star pattern)
|
||||
float angles[] = {0.0f, kPI / 3.0f, 2.0f * kPI / 3.0f};
|
||||
for (int p = 0; p < 3; ++p) {
|
||||
float a = angles[p];
|
||||
float dx = std::cos(a) * hW;
|
||||
float dz = std::sin(a) * hW;
|
||||
float nx = -std::sin(a);
|
||||
float nz = std::cos(a);
|
||||
|
||||
uint32_t base_idx = static_cast<uint32_t>(m_leaf.vertices.size());
|
||||
|
||||
float corners[4][3] = {
|
||||
{-dx, 0.0f, -dz},
|
||||
{ dx, 0.0f, dz},
|
||||
{ dx, H, dz},
|
||||
{-dx, H, -dz}
|
||||
};
|
||||
|
||||
float uvs[4][2] = {
|
||||
{uv.u0, uv.v1},
|
||||
{uv.u1, uv.v1},
|
||||
{uv.u1, uv.v0},
|
||||
{uv.u0, uv.v0}
|
||||
};
|
||||
|
||||
for (int c = 0; c < 4; ++c) {
|
||||
SpeedTreeVertex vert{};
|
||||
vert.position[0] = corners[c][0];
|
||||
vert.position[1] = corners[c][1];
|
||||
vert.position[2] = corners[c][2];
|
||||
|
||||
// Spherical up-tilted normal
|
||||
vert.normal[0] = nx * 0.7f;
|
||||
vert.normal[1] = 0.5f;
|
||||
vert.normal[2] = nz * 0.7f;
|
||||
Normalize3(vert.normal);
|
||||
|
||||
vert.uv[0] = uvs[c][0];
|
||||
vert.uv[1] = uvs[c][1];
|
||||
|
||||
// Wind weights: grass bends with height^1.5
|
||||
float norm_h = corners[c][1] / (H > 0.0f ? H : 1.0f);
|
||||
vert.wind_weights[0] = std::pow(norm_h, 1.5f); // Trunk bend
|
||||
vert.wind_weights[1] = norm_h * 0.5f; // Branch sway
|
||||
vert.wind_weights[2] = norm_h; // High-freq flutter
|
||||
vert.wind_weights[3] = static_cast<float>(p) * 0.33f; // Phase
|
||||
|
||||
vert.leaf_pivot_offset[0] = corners[c][0];
|
||||
vert.leaf_pivot_offset[1] = 0.0f;
|
||||
vert.leaf_pivot_offset[2] = corners[c][2];
|
||||
vert.diffuse = 0xFFFFFFFF;
|
||||
|
||||
m_leaf.vertices.push_back(vert);
|
||||
}
|
||||
|
||||
m_leaf.indices.push_back(base_idx + 0);
|
||||
m_leaf.indices.push_back(base_idx + 1);
|
||||
m_leaf.indices.push_back(base_idx + 2);
|
||||
m_leaf.indices.push_back(base_idx + 0);
|
||||
m_leaf.indices.push_back(base_idx + 2);
|
||||
m_leaf.indices.push_back(base_idx + 3);
|
||||
}
|
||||
}
|
||||
|
||||
void SpeedTreeModel::BuildTreeGeometry(float H, const SpeedTreeSptInfo& info) {
|
||||
bool conifer = IsConifer(m_name);
|
||||
|
||||
m_trunk.vertices.clear();
|
||||
m_trunk.indices.clear();
|
||||
m_trunk.texture = m_bark_texture;
|
||||
|
||||
m_leaf.vertices.clear();
|
||||
m_leaf.indices.clear();
|
||||
m_leaf.texture = m_leaf_texture;
|
||||
|
||||
// 1. Build Trunk Cylindrical Tube
|
||||
constexpr int SEGS = 8;
|
||||
constexpr int LEVELS = 5;
|
||||
float trunk_top = H * (conifer ? 0.90f : 0.72f);
|
||||
float r_base = H * 0.040f;
|
||||
float r_top = H * 0.012f;
|
||||
|
||||
for (int l = 0; l <= LEVELS; ++l) {
|
||||
float f = static_cast<float>(l) / LEVELS;
|
||||
float y = f * trunk_top;
|
||||
float r = r_base * (1.0f - f) + r_top * f;
|
||||
float v = f * 3.5f;
|
||||
|
||||
for (int s = 0; s <= SEGS; ++s) {
|
||||
float a = static_cast<float>(s) / SEGS * kTAU;
|
||||
float cos_a = std::cos(a);
|
||||
float sin_a = std::sin(a);
|
||||
|
||||
SpeedTreeVertex vert{};
|
||||
vert.position[0] = cos_a * r;
|
||||
vert.position[1] = y;
|
||||
vert.position[2] = sin_a * r;
|
||||
|
||||
vert.normal[0] = cos_a;
|
||||
vert.normal[1] = 0.05f;
|
||||
vert.normal[2] = sin_a;
|
||||
Normalize3(vert.normal);
|
||||
|
||||
vert.uv[0] = static_cast<float>(s) / SEGS;
|
||||
vert.uv[1] = v;
|
||||
|
||||
// Trunk bend weight is (y / H)^2
|
||||
float norm_y = y / H;
|
||||
vert.wind_weights[0] = norm_y * norm_y;
|
||||
vert.wind_weights[1] = 0.0f;
|
||||
vert.wind_weights[2] = 0.0f;
|
||||
vert.wind_weights[3] = 0.0f;
|
||||
|
||||
vert.leaf_pivot_offset[0] = 0.0f;
|
||||
vert.leaf_pivot_offset[1] = 0.0f;
|
||||
vert.leaf_pivot_offset[2] = 0.0f;
|
||||
vert.diffuse = 0xFFFFFFFF;
|
||||
|
||||
m_trunk.vertices.push_back(vert);
|
||||
}
|
||||
}
|
||||
|
||||
for (int l = 0; l < LEVELS; ++l) {
|
||||
uint32_t row_a = l * (SEGS + 1);
|
||||
uint32_t row_b = (l + 1) * (SEGS + 1);
|
||||
for (int s = 0; s < SEGS; ++s) {
|
||||
uint32_t i0 = row_a + s;
|
||||
uint32_t i1 = row_b + s;
|
||||
uint32_t i2 = row_b + s + 1;
|
||||
uint32_t i3 = row_a + s + 1;
|
||||
|
||||
m_trunk.indices.push_back(i0);
|
||||
m_trunk.indices.push_back(i1);
|
||||
m_trunk.indices.push_back(i2);
|
||||
|
||||
m_trunk.indices.push_back(i0);
|
||||
m_trunk.indices.push_back(i2);
|
||||
m_trunk.indices.push_back(i3);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Build Canopy Leaf Clusters
|
||||
std::vector<UVRect> uv_pool = info.leaf_uvs;
|
||||
if (uv_pool.empty()) uv_pool = info.frond_uvs;
|
||||
if (uv_pool.empty()) uv_pool.push_back({0.0f, 0.0f, 1.0f, 1.0f});
|
||||
|
||||
int cluster_count = conifer ? 16 : 14;
|
||||
float crown_center_y = H * (conifer ? 0.60f : 0.65f);
|
||||
|
||||
for (int k = 0; k < cluster_count; ++k) {
|
||||
float f = static_cast<float>(k) / cluster_count;
|
||||
float y = H * (conifer ? (0.25f + f * 0.68f) : (0.40f + f * 0.50f));
|
||||
float spread = H * (conifer ? (0.26f * (1.0f - f * 0.72f)) : (0.30f * std::sin(f * kPI)));
|
||||
float angle = f * kTAU * 1.61803398875f; // Golden ratio spiral
|
||||
|
||||
float cx = (k == cluster_count - 1) ? 0.0f : (std::cos(angle) * spread);
|
||||
float cz = (k == cluster_count - 1) ? 0.0f : (std::sin(angle) * spread);
|
||||
|
||||
float quad_w = H * (conifer ? 0.28f : 0.38f);
|
||||
float quad_h = H * (conifer ? 0.24f : 0.32f);
|
||||
float hw = quad_w * 0.5f;
|
||||
float hh = quad_h * 0.5f;
|
||||
|
||||
UVRect uv = uv_pool[k % uv_pool.size()];
|
||||
float cluster_phase = std::fmod(static_cast<float>(k) * 0.237f + 0.1f, 1.0f);
|
||||
|
||||
// 2 perpendicular planes per cluster (Cross-quad pattern)
|
||||
for (int p = 0; p < 2; ++p) {
|
||||
float pa = angle + p * (kPI * 0.5f);
|
||||
float dx = std::cos(pa) * hw;
|
||||
float dz = std::sin(pa) * hw;
|
||||
|
||||
// Geometry face normal
|
||||
float fnx = std::cos(pa + kPI * 0.5f);
|
||||
float fnz = std::sin(pa + kPI * 0.5f);
|
||||
|
||||
uint32_t bidx = static_cast<uint32_t>(m_leaf.vertices.size());
|
||||
|
||||
float pts[4][3] = {
|
||||
{cx - dx, y - hh, cz - dz},
|
||||
{cx + dx, y - hh, cz + dz},
|
||||
{cx + dx, y + hh, cz + dz},
|
||||
{cx - dx, y + hh, cz - dz}
|
||||
};
|
||||
|
||||
float uvs[4][2] = {
|
||||
{uv.u0, uv.v1},
|
||||
{uv.u1, uv.v1},
|
||||
{uv.u1, uv.v0},
|
||||
{uv.u0, uv.v0}
|
||||
};
|
||||
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
SpeedTreeVertex vert{};
|
||||
vert.position[0] = pts[i][0];
|
||||
vert.position[1] = pts[i][1];
|
||||
vert.position[2] = pts[i][2];
|
||||
|
||||
// --- Spherical Canopy Normal Calculation ---
|
||||
// Vector from tree crown center to this vertex
|
||||
float scx = pts[i][0];
|
||||
float scy = pts[i][1] - crown_center_y;
|
||||
float scz = pts[i][2];
|
||||
float s_norm[3] = {scx, scy, scz};
|
||||
Normalize3(s_norm);
|
||||
|
||||
// Blend 65% spherical volume normal + 35% geometric quad normal
|
||||
vert.normal[0] = s_norm[0] * 0.65f + fnx * 0.35f;
|
||||
vert.normal[1] = s_norm[1] * 0.65f + 0.25f * 0.35f;
|
||||
vert.normal[2] = s_norm[2] * 0.65f + fnz * 0.35f;
|
||||
Normalize3(vert.normal);
|
||||
|
||||
vert.uv[0] = uvs[i][0];
|
||||
vert.uv[1] = uvs[i][1];
|
||||
|
||||
// --- 4-Tier Wind Weights ---
|
||||
float norm_y = pts[i][1] / H;
|
||||
vert.wind_weights[0] = norm_y * norm_y; // Level 1: Trunk bend (H^2)
|
||||
vert.wind_weights[1] = std::clamp(spread / (H * 0.3f), 0.0f, 1.0f); // Level 2: Branch sway
|
||||
vert.wind_weights[2] = (i >= 2) ? 1.0f : 0.6f; // Level 3: Leaf flutter
|
||||
vert.wind_weights[3] = cluster_phase; // Phase offset
|
||||
|
||||
// Leaf Pivot Offset: Relative vector from cluster center to this vertex
|
||||
vert.leaf_pivot_offset[0] = pts[i][0] - cx;
|
||||
vert.leaf_pivot_offset[1] = pts[i][1] - y;
|
||||
vert.leaf_pivot_offset[2] = pts[i][2] - cz;
|
||||
|
||||
// Canopy contact AO: inner leaves darker
|
||||
float dist_from_crown = std::sqrt(scx * scx + scy * scy + scz * scz);
|
||||
float ao = std::clamp(dist_from_crown / (H * 0.35f), 0.4f, 1.0f);
|
||||
uint8_t ao_byte = static_cast<uint8_t>(ao * 255.0f);
|
||||
vert.diffuse = (0xFF << 24) | (ao_byte << 16) | (ao_byte << 8) | ao_byte;
|
||||
|
||||
m_leaf.vertices.push_back(vert);
|
||||
}
|
||||
|
||||
m_leaf.indices.push_back(bidx + 0);
|
||||
m_leaf.indices.push_back(bidx + 1);
|
||||
m_leaf.indices.push_back(bidx + 2);
|
||||
m_leaf.indices.push_back(bidx + 0);
|
||||
m_leaf.indices.push_back(bidx + 2);
|
||||
m_leaf.indices.push_back(bidx + 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SpeedTreeModel::EvaluateCpuTransformedVertices(const SpeedTreeMesh& src_mesh,
|
||||
std::vector<float>& out_positions,
|
||||
std::vector<float>& out_normals,
|
||||
float worldX, float worldY, float worldZ,
|
||||
float yawDeg, float scale,
|
||||
const WindParameters& wind) const {
|
||||
size_t nverts = src_mesh.vertices.size();
|
||||
out_positions.resize(nverts * 3);
|
||||
out_normals.resize(nverts * 3);
|
||||
|
||||
float rad = yawDeg * (kPI / 180.0f);
|
||||
float cos_y = std::cos(rad);
|
||||
float sin_y = std::sin(rad);
|
||||
|
||||
float gust_spatial = (worldX + worldZ) * 0.005f;
|
||||
float gust = std::sin(wind.time * wind.gust_frequency + gust_spatial) * 0.5f + 0.5f;
|
||||
float eff_wind = wind.strength * (0.8f + 0.4f * gust);
|
||||
|
||||
for (size_t i = 0; i < nverts; ++i) {
|
||||
const auto& v = src_mesh.vertices[i];
|
||||
|
||||
// 1. Scale
|
||||
float lx = v.position[0] * scale;
|
||||
float ly = v.position[1] * scale;
|
||||
float lz = v.position[2] * scale;
|
||||
|
||||
// 2. Leaf tumble around pivot (Level 3 wind)
|
||||
if (src_mesh.is_leaf && v.wind_weights[2] > 0.01f) {
|
||||
float leaf_osc = std::sin(wind.time * 8.0f + v.wind_weights[3] * 15.0f + lx + lz);
|
||||
float leaf_angle = v.wind_weights[2] * 0.25f * leaf_osc * eff_wind;
|
||||
float cos_l = std::cos(leaf_angle);
|
||||
float sin_l = std::sin(leaf_angle);
|
||||
|
||||
// Rotate pivot offset around wind axis
|
||||
float rel_x = v.leaf_pivot_offset[0] * scale;
|
||||
float rel_z = v.leaf_pivot_offset[2] * scale;
|
||||
float rot_rel_x, rot_rel_z;
|
||||
RotateY(rel_x, rel_z, cos_l, sin_l, rot_rel_x, rot_rel_z);
|
||||
|
||||
lx += (rot_rel_x - rel_x);
|
||||
lz += (rot_rel_z - rel_z);
|
||||
}
|
||||
|
||||
// 3. Trunk & Branch sway (Level 1 & 2 wind)
|
||||
float trunk_flex = v.wind_weights[0] * 0.08f * eff_wind;
|
||||
float branch_flex = v.wind_weights[1] * 0.05f * eff_wind;
|
||||
float sway = std::sin(wind.time * 1.5f + gust_spatial) * trunk_flex +
|
||||
std::cos(wind.time * 2.8f + v.wind_weights[3] * 6.28f) * branch_flex;
|
||||
|
||||
lx += wind.direction[0] * sway * (m_height * scale);
|
||||
lz += wind.direction[2] * sway * (m_height * scale);
|
||||
|
||||
// 4. World Yaw Rotation
|
||||
float rx, rz;
|
||||
RotateY(lx, lz, cos_y, sin_y, rx, rz);
|
||||
|
||||
out_positions[i * 3 + 0] = worldX + rx;
|
||||
out_positions[i * 3 + 1] = worldY + ly;
|
||||
out_positions[i * 3 + 2] = worldZ + rz;
|
||||
|
||||
// Rotate normal
|
||||
float nx = v.normal[0];
|
||||
float ny = v.normal[1];
|
||||
float nz = v.normal[2];
|
||||
float rnx, rnz;
|
||||
RotateY(nx, nz, cos_y, sin_y, rnx, rnz);
|
||||
|
||||
out_normals[i * 3 + 0] = rnx;
|
||||
out_normals[i * 3 + 1] = ny;
|
||||
out_normals[i * 3 + 2] = rnz;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace speedtree
|
||||
@@ -0,0 +1,122 @@
|
||||
#include "speedtree/speedtree.h"
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
|
||||
void TestProceduralTree() {
|
||||
std::cout << "[Test] Procedural Tree Generation..." << std::endl;
|
||||
auto model = speedtree::SpeedTreeModel::CreateProcedural("TestOak", 1200.0f, "bark.dds", "leaf.dds");
|
||||
assert(model != nullptr);
|
||||
assert(model->GetHeight() == 1200.0f);
|
||||
assert(model->GetBarkTexture() == "bark.dds");
|
||||
assert(model->GetLeafTexture() == "leaf.dds");
|
||||
|
||||
const auto& trunk = model->GetTrunkMesh();
|
||||
assert(!trunk.vertices.empty());
|
||||
assert(!trunk.indices.empty());
|
||||
assert(trunk.indices.size() % 3 == 0);
|
||||
|
||||
const auto& leaf = model->GetLeafMesh();
|
||||
assert(!leaf.vertices.empty());
|
||||
assert(!leaf.indices.empty());
|
||||
assert(leaf.indices.size() % 6 == 0); // Quads = 2 triangles
|
||||
|
||||
std::cout << " Trunk vertices: " << trunk.vertices.size()
|
||||
<< ", indices: " << trunk.indices.size() << std::endl;
|
||||
std::cout << " Leaf vertices: " << leaf.vertices.size()
|
||||
<< ", indices: " << leaf.indices.size() << std::endl;
|
||||
|
||||
// Verify Spherical Normals and Leaf Pivot Offsets
|
||||
for (size_t i = 0; i < leaf.vertices.size(); ++i) {
|
||||
const auto& v = leaf.vertices[i];
|
||||
// Normal must be normalized
|
||||
float len = std::sqrt(v.normal[0]*v.normal[0] + v.normal[1]*v.normal[1] + v.normal[2]*v.normal[2]);
|
||||
assert(std::fabs(len - 1.0f) < 0.05f);
|
||||
|
||||
// Wind weights must be valid [0, 1]
|
||||
assert(v.wind_weights[0] >= 0.0f && v.wind_weights[0] <= 1.5f);
|
||||
assert(v.wind_weights[1] >= 0.0f && v.wind_weights[1] <= 1.5f);
|
||||
assert(v.wind_weights[2] >= 0.0f && v.wind_weights[2] <= 1.5f);
|
||||
assert(v.wind_weights[3] >= 0.0f && v.wind_weights[3] <= 1.0f);
|
||||
|
||||
// Leaf pivot offset must be bounded by quad size
|
||||
float pivot_dist = std::sqrt(v.leaf_pivot_offset[0]*v.leaf_pivot_offset[0] +
|
||||
v.leaf_pivot_offset[1]*v.leaf_pivot_offset[1] +
|
||||
v.leaf_pivot_offset[2]*v.leaf_pivot_offset[2]);
|
||||
assert(pivot_dist < 1200.0f * 0.5f);
|
||||
}
|
||||
std::cout << " [PASS] Procedural Tree verified!" << std::endl;
|
||||
}
|
||||
|
||||
void TestSptTokenSniffing() {
|
||||
std::cout << "[Test] SPT Binary Token Sniffer..." << std::endl;
|
||||
// Build synthetic .spt token stream
|
||||
std::vector<uint8_t> buffer;
|
||||
auto push_i32 = [&](int32_t val) {
|
||||
uint8_t b[4];
|
||||
std::memcpy(b, &val, 4);
|
||||
buffer.insert(buffer.end(), b, b + 4);
|
||||
};
|
||||
auto push_f32 = [&](float val) {
|
||||
uint8_t b[4];
|
||||
std::memcpy(b, &val, 4);
|
||||
buffer.insert(buffer.end(), b, b + 4);
|
||||
};
|
||||
|
||||
// Token 2000: bark name "custom_bark.dds"
|
||||
std::string bark_str = "custom_bark.dds";
|
||||
push_i32(2000);
|
||||
push_i32(static_cast<int32_t>(bark_str.size()));
|
||||
buffer.insert(buffer.end(), bark_str.begin(), bark_str.end());
|
||||
|
||||
// Token 2001: size 850.0f
|
||||
push_i32(2001);
|
||||
push_f32(850.0f);
|
||||
|
||||
// Token 2002: variance 50.0f
|
||||
push_i32(2002);
|
||||
push_f32(50.0f);
|
||||
|
||||
speedtree::SpeedTreeSptInfo info;
|
||||
bool ok = speedtree::SpeedTreeSptInfo::SniffMemory(buffer.data(), buffer.size(), info);
|
||||
assert(ok);
|
||||
assert(info.bark_texture == "custom_bark.dds");
|
||||
assert(info.size == 850.0f);
|
||||
assert(info.variance == 50.0f);
|
||||
|
||||
std::cout << " [PASS] SPT Sniff verified!" << std::endl;
|
||||
}
|
||||
|
||||
void TestForestManagement() {
|
||||
std::cout << "[Test] SpeedTree Forest Management..." << std::endl;
|
||||
speedtree::SpeedTreeForest forest;
|
||||
assert(forest.GetInstanceCount() == 0);
|
||||
|
||||
forest.RegisterPropertyData(speedtree::SpeedTreeProperty{1, "Pine", "pine.spt", 1000.0f, 0.0f});
|
||||
assert(forest.HasMainTree(1));
|
||||
|
||||
auto* inst1 = forest.CreateInstance(100.0f, 0.0f, 200.0f, 1, 45.0f, 1.2f, "ForestPine1");
|
||||
auto* inst2 = forest.CreateInstance(300.0f, 0.0f, 400.0f, 1, 90.0f, 0.9f, "ForestPine2");
|
||||
assert(inst1 != nullptr && inst2 != nullptr);
|
||||
assert(forest.GetInstanceCount() == 2);
|
||||
|
||||
forest.Update(0.016f);
|
||||
assert(forest.GetWindParams().time > 0.01f);
|
||||
|
||||
forest.DeleteInstance(inst1);
|
||||
assert(forest.GetInstanceCount() == 1);
|
||||
|
||||
forest.Clear();
|
||||
assert(forest.GetInstanceCount() == 0);
|
||||
|
||||
std::cout << " [PASS] Forest Management verified!" << std::endl;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::cout << "=== Running SpeedTree SDK Unit Tests ===" << std::endl;
|
||||
TestProceduralTree();
|
||||
TestSptTokenSniffing();
|
||||
TestForestManagement();
|
||||
std::cout << "=== All SpeedTree SDK Tests Passed! ===" << std::endl;
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user