euv-core 0.56.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Rotates a turtle's orthonormal `(heading, left, up)` frame around a unit axis by `angle_rad`.
///
/// # Arguments
///
/// - `&mut TurtleState3D` - Mutable turtle state.
/// - `Vec3` - Unit rotation axis.
/// - `f32` - Rotation angle in radians.
fn rotate_turtle_frame(state: &mut TurtleState3D, axis: Vec3, angle_rad: f32) {
    let q: Quat = Quat::from_axis_angle(safe_unit_normal(axis), angle_rad);
    let new_h: Vec3 = safe_unit_normal(q.rotate_vec3(state.get_heading()));
    let rot_l: Vec3 = q.rotate_vec3(state.get_left());
    let new_l: Vec3 = safe_unit_normal(rot_l.sub(new_h.scale(rot_l.dot(new_h))));
    let new_u: Vec3 = safe_unit_normal(new_h.cross(new_l));
    state.set_heading(new_h);
    state.set_left(new_l);
    state.set_up(new_u);
}

/// Appends a tapered tubular bark branch frustum between `p0` and `p1` into the branch buffers.
///
/// # Arguments
///
/// - `Vec3` - Segment start position.
/// - `Vec3` - Segment end position.
/// - `f32` - Base radius at `p0`.
/// - `f32` - Tip radius at `p1`.
/// - `usize` - Radial segment count around the tube.
/// - `&mut Vec<Vertex3D>` - Destination bark vertex buffer.
/// - `&mut Vec<[u32; 3]>` - Destination bark triangle buffer.
fn append_branch_tube(
    p0: Vec3,
    p1: Vec3,
    r0: f32,
    r1: f32,
    radial_segs: usize,
    vertices: &mut Vec<Vertex3D>,
    indices: &mut Vec<[u32; 3]>,
) {
    let axis: Vec3 = p1.sub(p0);
    let len: f32 = axis.length();
    if len <= 1e-5 {
        return;
    }
    let dir: Vec3 = axis.scale(1.0 / len);
    let seed: Vec3 = if dir.get_y().abs() < 0.9 {
        Vec3::new(0.0, 1.0, 0.0)
    } else {
        Vec3::new(1.0, 0.0, 0.0)
    };
    let u_ax: Vec3 = safe_unit_normal(seed.cross(dir));
    let v_ax: Vec3 = safe_unit_normal(dir.cross(u_ax));
    let base: u32 = vertices.len() as u32;
    let stride: u32 = (radial_segs + 1) as u32;
    let bark_col_bot: [u8; 4] = [92, 66, 46, 255];
    let bark_col_top: [u8; 4] = [110, 82, 58, 255];
    let flags: u32 = VERTEX_FLAG_UV0 | VERTEX_FLAG_COLOR0;
    for s in 0..=radial_segs {
        let u: f32 = (s as f32) / (radial_segs as f32);
        let theta: f32 = u * TAU;
        let ct: f32 = theta.cos();
        let st: f32 = theta.sin();
        let radial: Vec3 = safe_unit_normal(u_ax.scale(ct).add(v_ax.scale(st)));
        let bot_pos: Vec3 = p0.add(radial.scale(r0));
        let top_pos: Vec3 = p1.add(radial.scale(r1));
        vertices.push(Vertex3D::from_full(
            bot_pos,
            radial,
            [1.0, 0.0, 0.0, 1.0],
            [u, 0.0],
            [0.0, 0.0],
            bark_col_bot,
            flags,
        ));
        vertices.push(Vertex3D::from_full(
            top_pos,
            radial,
            [1.0, 0.0, 0.0, 1.0],
            [u, 1.0],
            [0.0, 0.0],
            bark_col_top,
            flags,
        ));
    }
    for s in 0..radial_segs {
        let b0: u32 = base + ((s as u32) * 2);
        let t0: u32 = b0 + 1;
        let b1: u32 = b0 + 2;
        let t1: u32 = b0 + 3;
        indices.push([b0, b1, t1]);
        indices.push([b0, t1, t0]);
    }
    let cap_center: u32 = base + stride * 2;
    vertices.push(Vertex3D::from_full(
        p1,
        dir,
        [1.0, 0.0, 0.0, 1.0],
        [0.5, 0.5],
        [0.0, 0.0],
        bark_col_top,
        flags,
    ));
    for s in 0..radial_segs {
        let t0: u32 = base + ((s as u32) * 2) + 1;
        let t1: u32 = t0 + 2;
        indices.push([cap_center, t0, t1]);
    }
}

/// Appends a species-styled 3D canopy leaf cluster anchored at `origin` oriented along `heading`.
///
/// # Arguments
///
/// - `TreeSpecies` - Tree species determining leaf silhouette and color tint.
/// - `Vec3` - Cluster anchor position.
/// - `Vec3` - Local branch heading direction.
/// - `f32` - Cluster radius scale.
/// - `&mut u64` - Deterministic PRNG state for subtle color and scale variation.
/// - `&mut Vec<Vertex3D>` - Destination foliage vertex buffer.
/// - `&mut Vec<[u32; 3]>` - Destination foliage triangle buffer.
fn append_foliage_cluster(
    species: TreeSpecies,
    origin: Vec3,
    heading: Vec3,
    size: f32,
    rng: &mut u64,
    vertices: &mut Vec<Vertex3D>,
    indices: &mut Vec<[u32; 3]>,
) {
    let scale_jitter: f32 = 0.85 + terrain_next_f32(rng) * 0.35;
    let r: f32 = (size * scale_jitter).max(0.05);
    let shade: f32 = 0.85 + terrain_next_f32(rng) * 0.3;
    let base_rgb: [f32; 3] = match species {
        TreeSpecies::Pine => [42.0, 96.0, 52.0],
        TreeSpecies::Oak => [68.0, 134.0, 56.0],
        TreeSpecies::Palm => [78.0, 146.0, 58.0],
        TreeSpecies::WeepingWillow => [102.0, 152.0, 72.0],
    };
    let col: [u8; 4] = [
        (base_rgb[0] * shade).round().clamp(0.0, 255.0) as u8,
        (base_rgb[1] * shade).round().clamp(0.0, 255.0) as u8,
        (base_rgb[2] * shade).round().clamp(0.0, 255.0) as u8,
        255,
    ];
    let flags: u32 = VERTEX_FLAG_UV0 | VERTEX_FLAG_COLOR0;
    let dir: Vec3 = safe_unit_normal(heading);
    let seed: Vec3 = if dir.get_y().abs() < 0.9 {
        Vec3::new(0.0, 1.0, 0.0)
    } else {
        Vec3::new(1.0, 0.0, 0.0)
    };
    let right: Vec3 = safe_unit_normal(seed.cross(dir));
    let up: Vec3 = safe_unit_normal(dir.cross(right));
    let (scale_r, scale_u, scale_d): (f32, f32, f32) = match species {
        TreeSpecies::Pine => (r * 0.85, r * 0.55, r * 1.15),
        TreeSpecies::Oak => (r, r * 0.88, r),
        TreeSpecies::Palm => (r * 0.38, r * 0.12, r * 1.65),
        TreeSpecies::WeepingWillow => (r * 0.45, r * 1.55, r * 0.45),
    };
    let oct_dirs: [Vec3; 6] = [
        Vec3::new(1.0, 0.0, 0.0),
        Vec3::new(-1.0, 0.0, 0.0),
        Vec3::new(0.0, 1.0, 0.0),
        Vec3::new(0.0, -1.0, 0.0),
        Vec3::new(0.0, 0.0, 1.0),
        Vec3::new(0.0, 0.0, -1.0),
    ];
    let oct_tris: [[u32; 3]; 8] = [
        [2, 0, 4],
        [2, 4, 1],
        [2, 1, 5],
        [2, 5, 0],
        [3, 4, 0],
        [3, 1, 4],
        [3, 5, 1],
        [3, 0, 5],
    ];
    let base: u32 = vertices.len() as u32;
    let droop: Vec3 = match species {
        TreeSpecies::WeepingWillow => Vec3::new(0.0, -r * 0.6, 0.0),
        _ => Vec3::zero(),
    };
    let center: Vec3 = origin.add(droop);
    for (idx, &d) in oct_dirs.iter().enumerate() {
        let local: Vec3 = right
            .scale(d.get_x() * scale_r)
            .add(up.scale(d.get_y() * scale_u))
            .add(dir.scale(d.get_z() * scale_d));
        let pos: Vec3 = center.add(local);
        let normal: Vec3 = safe_unit_normal(local);
        let uv: [f32; 2] = if idx % 2 == 0 { [0.0, 1.0] } else { [1.0, 0.0] };
        vertices.push(Vertex3D::from_full(
            pos,
            normal,
            [1.0, 0.0, 0.0, 1.0],
            uv,
            [0.0, 0.0],
            col,
            flags,
        ));
    }
    for tri in oct_tris.iter() {
        indices.push([base + tri[0], base + tri[1], base + tri[2]]);
    }
}

/// Generates a deterministic 3D procedural tree from a custom `LSystemGrammar` and `ProceduralTreeConfig`.
///
/// # Arguments
///
/// - `&LSystemGrammar` - Rewriting grammar defining branch and leaf tokens.
/// - `&ProceduralTreeConfig` - Geometric taper, branching angles, species styling, and canopy scale.
/// - `u64` - Deterministic seed for stochastic rewriting and subtle organic variation.
///
/// # Returns
///
/// - `ProceduralTreeResult` - Generated branch mesh, foliage mesh, combined multi-material mesh, and counts.
#[must_use]
pub fn generate_tree_from_grammar(
    grammar: &LSystemGrammar,
    config: &ProceduralTreeConfig,
    seed: u64,
) -> ProceduralTreeResult {
    let program: String = grammar.rewrite(config.get_iterations(), seed);
    let mut rng: u64 = seed ^ 0xD1B5_4A32_D192_ED03;
    let base_angle: f32 = sanitize_scalar(config.get_branch_angle_deg(), 35.0)
        .clamp(5.0, 85.0)
        .to_radians();
    let rad_decay: f32 = sanitize_scalar(config.get_radius_decay(), 0.72).clamp(0.35, 0.96);
    let len_decay: f32 = sanitize_scalar(config.get_length_decay(), 0.78).clamp(0.45, 0.98);
    let radial_segs: usize = config.get_radial_segments().clamp(3, 16) as usize;
    let leaf_size: f32 = sanitize_scalar(config.get_leaf_cluster_size(), 0.75).clamp(0.1, 4.0);
    let gravity_bias: f32 = sanitize_scalar(config.get_gravity_bias(), 0.0).clamp(-0.6, 0.6);
    let mut state: TurtleState3D = TurtleState3D {
        position: Vec3::zero(),
        heading: Vec3::new(0.0, 1.0, 0.0),
        left: Vec3::new(-1.0, 0.0, 0.0),
        up: Vec3::new(0.0, 0.0, 1.0),
        radius: sanitize_scalar(config.get_trunk_radius(), 0.25).clamp(0.02, 2.0),
        step_length: sanitize_scalar(config.get_segment_length(), 0.9).clamp(0.08, 6.0),
        depth: 0,
    };
    let mut stack: Vec<TurtleState3D> = Vec::with_capacity(64);
    let mut branch_verts: Vec<Vertex3D> = Vec::with_capacity(1024);
    let mut branch_tris: Vec<[u32; 3]> = Vec::with_capacity(1024);
    let mut leaf_verts: Vec<Vertex3D> = Vec::with_capacity(1024);
    let mut leaf_tris: Vec<[u32; 3]> = Vec::with_capacity(1024);
    let mut branch_count: usize = 0;
    let mut leaf_count: usize = 0;
    for ch in program.chars() {
        let jitter: f32 = 0.9 + terrain_next_f32(&mut rng) * 0.2;
        let angle: f32 = base_angle * jitter;
        match ch {
            'F' => {
                let start: Vec3 = state.get_position();
                let steered: Vec3 =
                    safe_unit_normal(state.get_heading().add(Vec3::new(0.0, gravity_bias, 0.0)));
                let step: f32 = state.get_step_length();
                let end: Vec3 = start.add(steered.scale(step));
                let r0: f32 = state.get_radius();
                let r1: f32 = (r0 * (0.85 + 0.15 * rad_decay)).max(0.012);
                append_branch_tube(
                    start,
                    end,
                    r0,
                    r1,
                    radial_segs,
                    &mut branch_verts,
                    &mut branch_tris,
                );
                branch_count += 1;
                state.set_position(end);
                state.set_heading(steered);
                state.set_radius(r1);
            }
            'L' => {
                append_foliage_cluster(
                    config.get_species(),
                    state.get_position(),
                    state.get_heading(),
                    leaf_size,
                    &mut rng,
                    &mut leaf_verts,
                    &mut leaf_tris,
                );
                leaf_count += 1;
            }
            '!' => {
                let next_r: f32 = (state.get_radius() * rad_decay).max(0.012);
                let next_l: f32 = (state.get_step_length() * len_decay).max(0.08);
                state.set_radius(next_r);
                state.set_step_length(next_l);
            }
            '+' => {
                let axis: Vec3 = state.get_up();
                rotate_turtle_frame(&mut state, axis, angle);
            }
            '-' => {
                let axis: Vec3 = state.get_up();
                rotate_turtle_frame(&mut state, axis, -angle);
            }
            '&' => {
                let axis: Vec3 = state.get_left();
                rotate_turtle_frame(&mut state, axis, angle);
            }
            '^' => {
                let axis: Vec3 = state.get_left();
                rotate_turtle_frame(&mut state, axis, -angle);
            }
            '\\' => {
                let axis: Vec3 = state.get_heading();
                rotate_turtle_frame(&mut state, axis, angle);
            }
            '/' => {
                let axis: Vec3 = state.get_heading();
                rotate_turtle_frame(&mut state, axis, -angle);
            }
            '[' => {
                stack.push(state);
                let next_depth: u32 = state.get_depth() + 1;
                state.set_depth(next_depth);
                let next_r: f32 = (state.get_radius() * rad_decay).max(0.012);
                let next_l: f32 = (state.get_step_length() * len_decay).max(0.08);
                state.set_radius(next_r);
                state.set_step_length(next_l);
            }
            ']' => {
                if let Some(prev) = stack.pop() {
                    state = prev;
                }
            }
            _ => {}
        }
    }
    let bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::rgb(96, 68, 46), 0.86);
    let leaf_mat: PbrMaterial = PbrMaterial::dielectric(Color::rgb(68, 132, 58), 0.72);
    let mut branch_mesh: Mesh3D = Mesh3D::from_parts(
        TREE_NAME_BRANCHES.to_string(),
        branch_verts,
        branch_tris,
        bark_mat,
    );
    branch_mesh.set_is_closed(false);
    let branch_final: Mesh3D = compute_tangents(&branch_mesh);
    let mut foliage_mesh: Mesh3D = Mesh3D::from_parts(
        TREE_NAME_FOLIAGE.to_string(),
        leaf_verts,
        leaf_tris,
        leaf_mat,
    );
    foliage_mesh.set_is_closed(true);
    let foliage_final: Mesh3D = compute_tangents(&foliage_mesh);
    let combined_mesh: Mesh3D = merge_meshes(
        &[branch_final.clone(), foliage_final.clone()],
        TREE_NAME_COMBINED,
    );
    ProceduralTreeResult {
        combined_mesh,
        branch_mesh: branch_final,
        foliage_mesh: foliage_final,
        branch_segment_count: branch_count,
        leaf_cluster_count: leaf_count,
    }
}

/// Generates a deterministic 3D procedural tree using the built-in species grammar for `config.species`.
///
/// # Arguments
///
/// - `&ProceduralTreeConfig` - Tree species, branching, taper, and foliage parameters.
/// - `u64` - Deterministic random seed.
///
/// # Returns
///
/// - `ProceduralTreeResult` - Generated multi-material tree asset bundle.
#[must_use]
pub fn generate_procedural_tree(config: &ProceduralTreeConfig, seed: u64) -> ProceduralTreeResult {
    let grammar: LSystemGrammar = LSystemGrammar::for_species(config.get_species());
    generate_tree_from_grammar(&grammar, config, seed)
}