Add bounded SPT parsing, authored branch frames and foliage generation, independent LOD meshes, billboards, collision metadata, and legacy CPU/shader wind support. Restore seeded sampling and special leaf selection with generation diagnostics and reproducible baseline tools. Include regression coverage and static recovery documentation describing remaining differences from the original runtime. SDK tests pass (4/4); full corpus and client validation are recorded in the recovery notes.
393 lines
15 KiB
C++
393 lines
15 KiB
C++
#pragma once
|
|
|
|
#include <cstdint>
|
|
#include <string>
|
|
#include <vector>
|
|
#include <memory>
|
|
#include <map>
|
|
#include <array>
|
|
|
|
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;
|
|
};
|
|
|
|
// The original SPT stores four UV pairs, not necessarily an axis-aligned rectangle.
|
|
using UVQuad = std::array<float, 8>;
|
|
|
|
struct CollisionObject {
|
|
enum class Type { Sphere, Cylinder, Box };
|
|
Type type = Type::Sphere;
|
|
std::array<float, 3> position{};
|
|
std::array<float, 3> dimensions{};
|
|
};
|
|
|
|
class LegacyRandom {
|
|
public:
|
|
explicit LegacyRandom(uint32_t seed);
|
|
float Uniform(float low = 0.0f, float high = 1.0f);
|
|
private:
|
|
double Next();
|
|
uint32_t state_;
|
|
std::array<float, 128> shuffle_{};
|
|
};
|
|
|
|
struct BranchSpline {
|
|
struct Point { float x, y, dx, dy, handle; };
|
|
float minimum = 0, maximum = 0, variance = 0;
|
|
std::vector<Point> points;
|
|
std::array<float, 500> samples{};
|
|
bool samples_ready = false;
|
|
bool BuildSamples();
|
|
static bool Parse(const std::string& text, BranchSpline& out);
|
|
float Evaluate(float position, LegacyRandom* random = nullptr) const;
|
|
// 10026460: nearest cached sample times variance, without min/max mapping.
|
|
float EvaluatePerturbation(float position, LegacyRandom& random) const;
|
|
};
|
|
|
|
struct BranchLevel {
|
|
uint32_t radial_segments = 6;
|
|
uint32_t length_segments = 3;
|
|
float length_exponent = 1; // 16002, branch object +0x24.
|
|
std::array<BranchSpline, 9> curves; // Tokens 6000..6007, 6017.
|
|
std::array<float,5> scalar_fields{0.3f,1.0f,0.3f,1.0f,1.0f}; // 6010..6014.
|
|
bool has_attachment_range = false, has_child_density = false;
|
|
std::array<bool,2> flags{true,false}; // 6015,6016; retained for topology recovery.
|
|
};
|
|
|
|
struct BranchEntrySample {
|
|
float length, azimuth, angle, gravity, radius, flexibility;
|
|
};
|
|
// Entry draw order of 10002450. Unsampled curves consume no random values.
|
|
BranchEntrySample SampleBranchEntry(const BranchLevel& level,float position,
|
|
float treeHeight,LegacyRandom& random);
|
|
|
|
struct GenerationStats {
|
|
static constexpr size_t max_nodes = 16384, max_vertices = 2000000;
|
|
std::array<size_t,8> nodes_by_level{};
|
|
size_t generated_vertices = 0;
|
|
size_t terminal_leaf_calls = 0;
|
|
size_t special_leaf_cards = 0;
|
|
bool node_limit = false, vertex_limit = false, density_limit = false, tessellation_limit = false;
|
|
};
|
|
|
|
struct SpecialLeafSettings {
|
|
float minimum_position = 0.75f, probability = 0.8f;
|
|
uint32_t ancestor_depth = 1;
|
|
};
|
|
bool SampleSpecialLeaf(float position,const std::vector<float>& ancestors,
|
|
const SpecialLeafSettings& settings,LegacyRandom& random);
|
|
// Source Z-up row-vector basis. Convert directions to SDK Y-up at the boundary.
|
|
struct BranchFrame {
|
|
std::array<std::array<float,3>,3> basis{{{1,0,0},{0,1,0},{0,0,1}}};
|
|
BranchFrame Rotate(float azimuth,float roll,float pitch) const;
|
|
BranchFrame ApplyGravity(float gravity,float profile) const;
|
|
std::array<float,3> SdkAxis(size_t axis) const;
|
|
};
|
|
|
|
// 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)
|
|
uint32_t wind_matrix_index = 0;
|
|
bool authored_leaf_card = false;
|
|
float leaf_rocking_phase = 0;
|
|
};
|
|
|
|
// Represents a submesh (Trunk or Leaf/Canopy)
|
|
float SampleBranchAttachment(uint32_t seed,uint32_t child,float low,float high);
|
|
float SampleBranchAzimuth(uint32_t childSeed);
|
|
|
|
struct SpeedTreeMesh {
|
|
std::string name;
|
|
std::vector<SpeedTreeVertex> vertices;
|
|
std::vector<uint32_t> indices;
|
|
std::string texture;
|
|
struct Grid { uint32_t first, rows, columns; bool closed; };
|
|
std::vector<Grid> grids;
|
|
bool is_leaf = false;
|
|
bool is_double_sided = false;
|
|
bool alpha_test = false;
|
|
float alpha_ref = 0.45f;
|
|
};
|
|
|
|
struct LeafDefinition {
|
|
bool flag = false;
|
|
std::array<float,3> color{0.8f,0.8f,0.8f};
|
|
float scalar = 0.2f;
|
|
std::string texture;
|
|
std::array<float,3> pivot{0.5f,1,0}; // 4004.
|
|
std::array<float,3> placement{0.12f,0.12f,0}; // 4005, retained.
|
|
std::array<float,3> dimensions{10,10,0}; // 4006.
|
|
};
|
|
using LeafCorners = std::array<std::array<float,3>,4>;
|
|
LeafCorners BuildLeafCorners(const LeafDefinition& leaf, bool mirrored, float scale = 1);
|
|
// Angles are source Z-up degrees; offsets and result use SDK Y-up.
|
|
std::array<float,3> OrientLeafOffset(std::array<float,3> offset,
|
|
float azimuth, float pitch, float rocking);
|
|
|
|
struct FrondTexture {
|
|
std::string filename;
|
|
float aspect = 0.5f, size_scale = 1;
|
|
float angle_min = 0, angle_max = 0;
|
|
};
|
|
struct FrondSettings {
|
|
bool enabled = false;
|
|
uint32_t start_level = 1, type = 1, blade_count = 2, profile_segments = 4;
|
|
BranchSpline profile;
|
|
uint32_t lod_levels = 4, segment_override = 2, reduction_mode = 1;
|
|
std::array<float,4> lod_fields{1,0,0,0.05f}; // 13010..13013.
|
|
std::vector<FrondTexture> textures;
|
|
};
|
|
|
|
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<LeafDefinition> leaves;
|
|
SpecialLeafSettings special_leaves;
|
|
std::vector<UVRect> leaf_uvs;
|
|
std::vector<UVRect> frond_uvs;
|
|
std::vector<UVRect> billboard_uvs;
|
|
std::vector<UVQuad> leaf_uv_quads;
|
|
std::vector<UVQuad> frond_uv_quads;
|
|
std::vector<UVQuad> billboard_uv_quads;
|
|
bool horizontal_billboard = false;
|
|
bool billboard_360 = false;
|
|
UVQuad supplemental_uv{}; // Token 20005; retained separately pending semantic recovery.
|
|
std::vector<CollisionObject> collision_objects;
|
|
float lod_near = 0.0f;
|
|
float lod_far = 0.0f;
|
|
uint32_t seed = 1;
|
|
FrondSettings fronds;
|
|
uint32_t wind_level = 0;
|
|
uint32_t branch_level_count = 0;
|
|
bool has_size = false;
|
|
bool metadata_complete = false;
|
|
bool has_extension_21000 = false;
|
|
std::array<float,2> extension_21000{}; // Corpus-observed payload; semantics unresolved.
|
|
uint32_t unsupported_token = 0;
|
|
size_t parsed_bytes = 0;
|
|
std::string error;
|
|
std::vector<BranchLevel> branch_levels;
|
|
float leaf_rocking_range = 0.08f;
|
|
float leaf_rocking_frequency = 0.3f;
|
|
bool leaf_rocking_enabled = true;
|
|
uint32_t lod_method = 0;
|
|
float lod_transition_width = 0.0f;
|
|
float lod_alpha_exponent = 1.0f;
|
|
float lod_transition_overlap = 0.5f;
|
|
float leaf_lod_growth = 0;
|
|
uint32_t branch_lod_levels = 1;
|
|
uint32_t leaf_lod_levels = 1;
|
|
|
|
// Original near-to-far linear LOD response, clamped to [0, 1].
|
|
float EvaluateLod(float distance) const;
|
|
|
|
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;
|
|
// Column-major local-space affine matrices, matching the original runtime.
|
|
// Empty selects the SDK's synthesized wind; custom matrices are applied as supplied.
|
|
std::vector<std::array<float, 16>> matrices;
|
|
bool legacy_leaf_rocking = false;
|
|
float legacy_leaf_phase = 0.0f;
|
|
};
|
|
|
|
// AVA2's source-level forest controller, with instance-owned phase state.
|
|
class LegacyWindController {
|
|
public:
|
|
void Update(float time, float strength);
|
|
const std::vector<std::array<float,16>>& GetMatrices() const { return matrices_; }
|
|
float GetLeafPhase() const { return leaf_phase_; }
|
|
private:
|
|
float previous_time_ = 0, previous_strength_ = 0;
|
|
bool initialized_ = false;
|
|
float leaf_phase_ = 0, leaf_offset_ = 0;
|
|
std::array<float,4> phases_{};
|
|
std::vector<std::array<float,16>> matrices_;
|
|
};
|
|
|
|
// Recovered discrete branch/frond selection; level zero is highest detail.
|
|
int SelectDiscreteLod(float lod, uint32_t levels);
|
|
|
|
struct LodTransition {
|
|
int first = -1, second = -1;
|
|
float first_alpha = 255, second_alpha = 255;
|
|
};
|
|
LodTransition SelectLodTransition(float lod, uint32_t levels, float width,
|
|
float overlap, float exponent, float baseAlpha = 84);
|
|
|
|
struct BillboardView {
|
|
int texture_index = -1;
|
|
float alpha_ref = 255;
|
|
};
|
|
// Angle in tree-local source XY plane, degrees. Returns at most two atlas views.
|
|
std::vector<BillboardView> SelectBillboardViews(const SpeedTreeSptInfo& info,
|
|
float angleDegrees, float distanceAlpha);
|
|
|
|
// Core Model class representing a unique species/variant of tree
|
|
class SpeedTreeModel {
|
|
public:
|
|
SpeedTreeModel();
|
|
~SpeedTreeModel() = default;
|
|
|
|
// A positive explicit size overrides the SPT size, as SetTreeSize does before Compute.
|
|
static std::shared_ptr<SpeedTreeModel> Create(const std::string& sptPath, float treeSize = 0.0f, float treeVariance = 0.0f) { return CreateFromSpt(sptPath, treeSize, treeVariance); }
|
|
static std::shared_ptr<SpeedTreeModel> CreateFromSpt(const std::string& sptPath, float treeSize = 0.0f, float treeVariance = 0.0f);
|
|
static std::shared_ptr<SpeedTreeModel> CreateFromMemory(const uint8_t* data, size_t size,
|
|
const std::string& name = "", float treeSize = 0.0f, float treeVariance = 0.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(uint32_t lod = 0) const;
|
|
const SpeedTreeMesh& GetLeafMesh(uint32_t lod = 0) const;
|
|
const std::vector<SpeedTreeMesh>& GetFrondMeshes(uint32_t lod = 0) const;
|
|
uint32_t GetBranchLodCount() const { return uint32_t(m_trunk_lods.size()+1); }
|
|
uint32_t GetLeafLodCount() const { return uint32_t(m_leaf_lods.size()+1); }
|
|
uint32_t GetFrondLodCount() const { return uint32_t(m_frond_lods.size()+1); }
|
|
|
|
// Camera position in tree-local Y-up space. Output has no wind deformation.
|
|
std::vector<SpeedTreeMesh> BuildBillboardMeshes(const std::array<float,3>& camera,
|
|
float distanceAlpha = 84) const;
|
|
|
|
const std::array<float,3>& GetBoundsMin() const { return m_bounds_min; }
|
|
const std::array<float,3>& GetBoundsMax() const { return m_bounds_max; }
|
|
float GetHeight() const { return m_height; }
|
|
float GetRadius() const { return m_radius; }
|
|
bool IsGrassOrShrub() const { return m_is_grass_or_shrub; }
|
|
bool WasGenerationTruncated() const { return m_generation_truncated; }
|
|
const GenerationStats& GetGenerationStats() const { return m_generation_stats; }
|
|
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 deformer. Optional camera is a world-space eye position for authored leaf cards.
|
|
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 std::array<float,3>* camera = nullptr) const;
|
|
|
|
private:
|
|
void BuildLods();
|
|
void BuildGeometry(const SpeedTreeSptInfo& info);
|
|
void BuildTreeGeometry(float H, const SpeedTreeSptInfo& info);
|
|
void BuildAuthoredBranches(float H, const SpeedTreeSptInfo& info);
|
|
void AppendFrond(const std::vector<std::array<float,3>>& centers,
|
|
std::array<float,3> side, std::array<float,3> other, uint32_t group,
|
|
const std::vector<BranchFrame>* frames = nullptr);
|
|
void BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& info);
|
|
|
|
std::string m_name;
|
|
std::string m_spt_path;
|
|
float m_height = 1000.0f;
|
|
float m_generation_variance = 0.0f;
|
|
float m_radius = 350.0f;
|
|
bool m_is_grass_or_shrub = false;
|
|
bool m_generation_truncated = false;
|
|
GenerationStats m_generation_stats;
|
|
|
|
std::string m_bark_texture;
|
|
std::string m_leaf_texture;
|
|
SpeedTreeSptInfo m_info;
|
|
|
|
std::array<float,3> m_bounds_min{}, m_bounds_max{};
|
|
SpeedTreeMesh m_trunk;
|
|
SpeedTreeMesh m_leaf;
|
|
std::vector<SpeedTreeMesh> m_fronds;
|
|
std::vector<SpeedTreeMesh> m_trunk_lods, m_leaf_lods;
|
|
std::vector<std::vector<SpeedTreeMesh>> m_frond_lods;
|
|
};
|
|
|
|
// 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;
|
|
LegacyWindController m_wind_controller;
|
|
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
|