diff --git a/crates/engine/src/scene3d.rs b/crates/engine/src/scene3d.rs deleted file mode 100644 index 5a5b822e82f866338270a625683e456419a20f9e..0000000000000000000000000000000000000000 --- a/crates/engine/src/scene3d.rs +++ /dev/null @@ -1,1618 +0,0 @@ -//! 3D scene graph & `wgpu` rasterizer for Fusion's `Renderer3D`, `Camera3D`, -//! `ImagePlane3D`, `Shape3D` (Sphere, Cylinder, Plane, Cube), `Merge3D`, `Transform3D`, -//! `LightAmbient`, `LightDirectional`, and `MtlCookTorrance` nodes. -//! -//! Matches Fusion's right-handed +Y-up / -Z-forward coordinate system, -//! `Transform3DOp` Euler rotation orders (`XYZ`, `XZY`, etc.), `ScaleLock`, -//! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection. - -use crate::cache::CachedTexture; -use bytemuck::{Pod, Zeroable}; -use model::{Comp, ExprEngine, Node, NodeId}; - -pub type Mat4 = [f32; 16]; // Column-major 4x4 - -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct Vertex3D { - pos: [f32; 3], - normal: [f32; 3], - uv: [f32; 2], -} - -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct MeshUniform { - mvp: [f32; 16], - model: [f32; 16], - /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture) - dod: [f32; 4], - /// `[use_tex, lighting_enabled, specular_intensity, flip_normals]` - flags: [f32; 4], - /// Diffuse color multiplier `(r, g, b, a)` - diffuse_col: [f32; 4], - /// Specular color `(r, g, b, shininess_exponent)` - specular_col: [f32; 4], - /// Ambient light `(r, g, b, 0)` - ambient: [f32; 4], - /// Directional light direction TO light `(dx, dy, dz, has_dir)` - dir_to_light: [f32; 4], - /// Directional light color * intensity `(r, g, b, 0)` - dir_color: [f32; 4], - /// Camera world position `(cx, cy, cz, 0)` - cam_pos: [f32; 4], - /// `[num_point_lights, num_spot_lights, 0, 0]` - light_counts: [f32; 4], - /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` - point_pos: [[f32; 4]; 4], - /// Point light colors * intensity `(r, g, b, decay_rate)` - point_col: [[f32; 4]; 4], - /// Spot light positions `(x, y, z, cos_inner)` - spot_pos: [[f32; 4]; 4], - /// Spot light forward directions `(dx, dy, dz, cos_outer)` - spot_dir: [[f32; 4]; 4], - /// Spot light colors * intensity `(r, g, b, decay_type)` - spot_col: [[f32; 4]; 4], -} - -const SHADER_3D: &str = r#" -struct MeshUniform { - mvp: mat4x4, - model: mat4x4, - dod: vec4, - flags: vec4, - diffuse_col: vec4, - specular_col: vec4, - ambient: vec4, - dir_to_light: vec4, - dir_color: vec4, - cam_pos: vec4, - light_counts: vec4, - point_pos: array, 4>, - point_col: array, 4>, - spot_pos: array, 4>, - spot_dir: array, 4>, - spot_col: array, 4>, -}; - -@group(0) @binding(0) var u: MeshUniform; -@group(0) @binding(1) var mat_tex: texture_2d; -@group(0) @binding(2) var mat_samp: sampler; - -struct VsIn { - @location(0) pos: vec3, - @location(1) normal: vec3, - @location(2) uv: vec2, -}; - -struct VsOut { - @builtin(position) clip: vec4, - @location(0) uv: vec2, - @location(1) world_pos: vec3, - @location(2) world_n: vec3, -}; - -@vertex -fn vs_mesh(v: VsIn) -> VsOut { - var out: VsOut; - let wp = u.model * vec4(v.pos, 1.0); - out.clip = u.mvp * vec4(v.pos, 1.0); - out.uv = v.uv; - out.world_pos = wp.xyz; - let wn = (u.model * vec4(v.normal, 0.0)).xyz; - let nlen = length(wn); - var n_norm = select(vec3(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); - if (u.flags.w > 0.5) { - n_norm = -n_norm; - } - out.world_n = n_norm; - return out; -} - -fn light_attenuation(dist: f32, decay_type: f32, decay_rate: f32) -> f32 { - let dt = i32(decay_type + 0.5); - let rate = max(decay_rate, 0.001); - if (dt == 1) { - return 1.0 / max(1.0 + dist * rate, 1e-4); - } else if (dt == 2) { - let d = dist * rate; - return 1.0 / max(1.0 + d * d, 1e-4); - } - return 1.0; -} - -fn eval_light_contrib( - n: vec3, - v: vec3, - l: vec3, - light_rgb: vec3, - albedo: vec3, - spec_rgb: vec3, - spec_int: f32, - shininess: f32, -) -> vec3 { - let ndotl = max(dot(n, l), 0.0); - if (ndotl <= 0.0) { - return vec3(0.0); - } - var out = albedo * light_rgb * ndotl; - if (spec_int > 1e-4) { - let h = normalize(l + v); - let spec = pow(max(dot(n, h), 0.0), shininess) * spec_int; - out = out + light_rgb * spec_rgb * spec; - } - return out; -} - -@fragment -fn fs_mesh(in: VsOut) -> @location(0) vec4 { - var col = u.diffuse_col; - if (u.flags.x > 0.5) { - var uv = in.uv; - if (u.dod.z > 0.5 && u.dod.w > 0.5) { - let tdims = vec2(textureDimensions(mat_tex)); - let canvas_px = vec2(uv.x * u.dod.z, uv.y * u.dod.w); - uv = (canvas_px - u.dod.xy) / tdims; - if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { - discard; - } - } - col = textureSample(mat_tex, mat_samp, uv) * u.diffuse_col; - } - if (col.a <= 0.002) { - discard; - } - - if (u.flags.y > 0.5) { - // Premultiplied -> unpremultiplied albedo for lighting - let albedo = select(vec3(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5); - let n = normalize(in.world_n); - let v = normalize(u.cam_pos.xyz - in.world_pos); - let spec_rgb = u.specular_col.rgb; - let shininess = max(u.specular_col.w, 1.0); - let spec_int = u.flags.z; - - var lit = albedo * u.ambient.rgb; - if (u.dir_to_light.w > 0.5) { - let l = normalize(u.dir_to_light.xyz); - lit = lit + eval_light_contrib(n, v, l, u.dir_color.rgb, albedo, spec_rgb, spec_int, shininess); - } - - let n_pt = i32(u.light_counts.x + 0.5); - for (var i: i32 = 0; i < 4; i = i + 1) { - if (i >= n_pt) { break; } - let to_l = u.point_pos[i].xyz - in.world_pos; - let dist = max(length(to_l), 1e-4); - let att = light_attenuation(dist, u.point_pos[i].w, u.point_col[i].w); - lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); - } - - let n_sp = i32(u.light_counts.y + 0.5); - for (var i: i32 = 0; i < 4; i = i + 1) { - if (i >= n_sp) { break; } - let to_l = u.spot_pos[i].xyz - in.world_pos; - let dist = max(length(to_l), 1e-4); - let l_dir = to_l / dist; - // spot_dir.xyz is direction spotlight points; fragment direction from light is -l_dir - let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz)); - let cos_inner = u.spot_pos[i].w; - let cos_outer = u.spot_dir[i].w; - let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); - if (cone > 0.0) { - let att = light_attenuation(dist, u.spot_col[i].w, 1.0) * cone; - lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); - } - } - - col = vec4(clamp(lit, vec3(0.0), vec3(1.0)) * col.a, col.a); - } - return col; -} -"#; - -pub struct Scene3DRenderer { - bgl: wgpu::BindGroupLayout, - pipeline: wgpu::RenderPipeline, - sampler: wgpu::Sampler, -} - -#[derive(Clone)] -pub struct CameraInstance { - pub world: Mat4, - pub vfov_rad: f32, - pub near: f32, - pub far: f32, -} - -#[derive(Clone, Debug)] -pub enum ShapeKind { - ImagePlane, - Sphere { radius: f32, sub_base: u32, sub_height: u32 }, - Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 }, - Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, - Cube { width: f32, height: f32, depth: f32 }, - TextPlate { width: f32, height: f32, depth: f32, slices: u32 }, -} - -#[derive(Clone, Debug)] -pub struct Displace3DSpec { - pub input_node: NodeId, - pub scale: f32, - pub bias: f32, - pub channel: i32, // 0=R, 1=G, 2=B, 3=A, 4=Luma (default) -} - -#[derive(Clone, Debug)] -pub struct DisplaceHeightmap { - pub size: [u32; 2], - pub rgba: Vec, - pub scale: f32, - pub bias: f32, - pub channel: i32, -} - -#[derive(Clone, Debug)] -pub struct Text3DSpec { - pub node_id: NodeId, -} - -#[derive(Clone)] -pub struct MeshInstance { - pub world: Mat4, - pub shape: ShapeKind, - pub material_node: Option, - pub text3d: Option, - pub diffuse_col: [f32; 4], - pub specular_col: [f32; 3], - pub specular_intensity: f32, - pub specular_exponent: f32, - pub affected_by_lights: bool, - pub flip_normals: bool, - pub displace: Option, -} - -#[derive(Clone, Copy, Debug)] -pub struct PointLight { - pub pos: [f32; 3], - pub color: [f32; 3], - pub decay_type: f32, - pub decay_rate: f32, -} - -#[derive(Clone, Copy, Debug)] -pub struct SpotLight { - pub pos: [f32; 3], - pub dir: [f32; 3], - pub color: [f32; 3], - pub cos_inner: f32, - pub cos_outer: f32, - pub decay_type: f32, -} - -#[derive(Clone, Debug)] -pub struct SceneLights { - pub ambient: [f32; 3], - pub dir_to_light: [f32; 3], - pub dir_color: [f32; 3], - pub has_dir: bool, - pub points: Vec, - pub spots: Vec, -} - -impl Default for SceneLights { - fn default() -> Self { - Self { - ambient: [0.0, 0.0, 0.0], - dir_to_light: [0.0, 0.0, 1.0], - dir_color: [0.0, 0.0, 0.0], - has_dir: false, - points: Vec::new(), - spots: Vec::new(), - } - } -} - -pub struct DrawMesh { - pub world: Mat4, - pub shape: ShapeKind, - pub tex: Option, - pub diffuse_col: [f32; 4], - pub specular_col: [f32; 3], - pub specular_intensity: f32, - pub specular_exponent: f32, - pub affected_by_lights: bool, - pub flip_normals: bool, - pub displace: Option, -} - -impl Scene3DRenderer { - pub fn new(device: &wgpu::Device) -> Self { - let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("scene3d-shader"), - source: wgpu::ShaderSource::Wgsl(SHADER_3D.into()), - }); - let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("scene3d-bgl"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { filterable: true }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 2, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), - count: None, - }, - ], - }); - let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("scene3d-pl"), - bind_group_layouts: &[Some(&bgl)], - immediate_size: 0, - }); - let vbuf_layout = wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() as u64, - step_mode: wgpu::VertexStepMode::Vertex, - attributes: &[ - wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 }, - wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 }, - wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 }, - ], - }; - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("scene3d-mesh"), - layout: Some(&pl), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_mesh"), - compilation_options: Default::default(), - buffers: &[Some(vbuf_layout)], - }, - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_mesh"), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: wgpu::TextureFormat::Rgba8Unorm, - blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, - cull_mode: None, - ..Default::default() - }, - depth_stencil: Some(wgpu::DepthStencilState { - format: wgpu::TextureFormat::Depth32Float, - depth_write_enabled: Some(true), - depth_compare: Some(wgpu::CompareFunction::LessEqual), - stencil: wgpu::StencilState::default(), - bias: wgpu::DepthBiasState::default(), - }), - multisample: wgpu::MultisampleState::default(), - multiview_mask: None, - cache: None, - }); - let sampler = device.create_sampler(&wgpu::SamplerDescriptor { - label: Some("scene3d-linear"), - address_mode_u: wgpu::AddressMode::ClampToEdge, - address_mode_v: wgpu::AddressMode::ClampToEdge, - mag_filter: wgpu::FilterMode::Linear, - min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::MipmapFilterMode::Linear, - ..Default::default() - }); - Self { bgl, pipeline, sampler } - } - - #[allow(clippy::too_many_arguments)] - pub fn render_meshes( - &self, - device: &wgpu::Device, - queue: &wgpu::Queue, - enc: &mut wgpu::CommandEncoder, - dst: &CachedTexture, - dummy: &CachedTexture, - view_proj: Mat4, - view: Mat4, - cam_pos: [f32; 3], - lights: SceneLights, - lighting_enabled: bool, - meshes: &[DrawMesh], - ) { - let depth_tex = device.create_texture(&wgpu::TextureDescriptor { - label: Some("scene3d-depth"), - size: wgpu::Extent3d { - width: dst.size[0].max(1), - height: dst.size[1].max(1), - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Depth32Float, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, - view_formats: &[], - }); - let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default()); - - // Sort back-to-front in camera view space so semi-transparent planes blend cleanly. - let mut order: Vec<(usize, f32)> = meshes - .iter() - .enumerate() - .map(|(i, m)| { - let wx = m.world[12]; - let wy = m.world[13]; - let wz = m.world[14]; - let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14]; - (i, vz) - }) - .collect(); - order.sort_by(|a, b| a.1.total_cmp(&b.1)); - - struct GpuDraw { - bg: wgpu::BindGroup, - vbuf: wgpu::Buffer, - ibuf: wgpu::Buffer, - idx_count: u32, - } - let mut draw_items = Vec::with_capacity(order.len()); - for (idx, _) in order { - let m = &meshes[idx]; - let aspect = m - .tex - .as_ref() - .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) - .unwrap_or(16.0 / 9.0); - let (mut verts, indices) = build_shape_mesh(&m.shape, aspect); - if indices.is_empty() { - continue; - } - if let Some(disp) = &m.displace { - apply_heightmap_displace(&mut verts, &indices, disp); - } - let vbytes = bytemuck::cast_slice(&verts); - let ibytes = bytemuck::cast_slice(&indices); - let vbuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("scene3d-vb"), - size: vbytes.len() as u64, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&vbuf, 0, vbytes); - let ibuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("scene3d-ib"), - size: ibytes.len() as u64, - usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&ibuf, 0, ibytes); - - let mvp = mat4_mul(view_proj, m.world); - let dod = if let Some(t) = &m.tex { - if t.has_dod() { - [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32] - } else { - [0.0; 4] - } - } else { - [0.0; 4] - }; - let mut point_pos = [[0.0_f32; 4]; 4]; - let mut point_col = [[0.0_f32; 4]; 4]; - let n_pt = lights.points.len().min(4); - for (pi, pl) in lights.points.iter().take(4).enumerate() { - point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type]; - point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], pl.decay_rate]; - } - let mut spot_pos = [[0.0_f32; 4]; 4]; - let mut spot_dir = [[0.0_f32; 4]; 4]; - let mut spot_col = [[0.0_f32; 4]; 4]; - let n_sp = lights.spots.len().min(4); - for (si, sl) in lights.spots.iter().take(4).enumerate() { - spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner]; - spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer]; - spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type]; - } - let uni = MeshUniform { - mvp, - model: m.world, - dod, - flags: [ - if m.tex.is_some() { 1.0 } else { 0.0 }, - if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 }, - m.specular_intensity, - if m.flip_normals { 1.0 } else { 0.0 }, - ], - diffuse_col: m.diffuse_col, - specular_col: [ - m.specular_col[0], - m.specular_col[1], - m.specular_col[2], - m.specular_exponent, - ], - ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0], - dir_to_light: [ - lights.dir_to_light[0], - lights.dir_to_light[1], - lights.dir_to_light[2], - if lights.has_dir { 1.0 } else { 0.0 }, - ], - dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0], - cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], - light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0], - point_pos, - point_col, - spot_pos, - spot_dir, - spot_col, - }; - let ubuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("scene3d-u"), - size: std::mem::size_of::() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uni)); - let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view); - let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("scene3d-bg"), - layout: &self.bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) }, - wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, - ], - }); - draw_items.push(GpuDraw { - bg, - vbuf, - ibuf, - idx_count: indices.len() as u32, - }); - } - - let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("scene3d-pass"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &dst.view, - depth_slice: None, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), - store: wgpu::StoreOp::Store, - }, - })], - depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &depth_view, - depth_ops: Some(wgpu::Operations { - load: wgpu::LoadOp::Clear(1.0), - store: wgpu::StoreOp::Discard, - }), - stencil_ops: None, - }), - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); - pass.set_pipeline(&self.pipeline); - for d in &draw_items { - pass.set_bind_group(0, &d.bg, &[]); - pass.set_vertex_buffer(0, d.vbuf.slice(..)); - pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); - pass.draw_indexed(0..d.idx_count, 0, 0..1); - } - } -} - -fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec, Vec) { - match *shape { - ShapeKind::ImagePlane => { - let hx = 0.5; - let hy = 0.5 / tex_aspect.max(1e-4); - let verts = vec![ - Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] }, - Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, - Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, - Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] }, - ]; - (verts, vec![0, 1, 2, 0, 2, 3]) - } - ShapeKind::Plane { width, height, sub_w, sub_h } => { - let sw = sub_w.clamp(1, 64); - let sh = sub_h.clamp(1, 64); - let hx = width * 0.5; - let hy = height * 0.5; - let mut verts = Vec::with_capacity(((sw + 1) * (sh + 1)) as usize); - let mut idx = Vec::with_capacity((sw * sh * 6) as usize); - for iy in 0..=sh { - let v = iy as f32 / sh as f32; - let y = hy - v * height; - for ix in 0..=sw { - let u = ix as f32 / sw as f32; - let x = -hx + u * width; - verts.push(Vertex3D { pos: [x, y, 0.0], normal: [0.0, 0.0, 1.0], uv: [u, v] }); - } - } - let row = sw + 1; - for iy in 0..sh { - for ix in 0..sw { - let a = iy * row + ix; - let b = (iy + 1) * row + ix; - let c = (iy + 1) * row + ix + 1; - let d = iy * row + ix + 1; - idx.extend_from_slice(&[a, b, c, a, c, d]); - } - } - (verts, idx) - } - ShapeKind::TextPlate { width, height, depth, slices } => { - let hx = width * 0.5; - let hy = height * 0.5; - let n_slices = if depth.abs() > 1e-4 { slices.clamp(2, 16) } else { 1 }; - let mut verts = Vec::with_capacity((n_slices * 4) as usize); - let mut idx = Vec::with_capacity((n_slices * 6) as usize); - for s in 0..n_slices { - let t = if n_slices == 1 { 0.0 } else { s as f32 / (n_slices - 1) as f32 }; - // Fusion Text3D extrudes backward along -Z from z=0 to z=-depth - let z = -t * depth; - let nz = if n_slices > 1 && s == n_slices - 1 { -1.0 } else { 1.0 }; - let base = verts.len() as u32; - verts.push(Vertex3D { pos: [-hx, hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 0.0] }); - verts.push(Vertex3D { pos: [-hx, -hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 1.0] }); - verts.push(Vertex3D { pos: [ hx, -hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 1.0] }); - verts.push(Vertex3D { pos: [ hx, hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 0.0] }); - idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); - } - (verts, idx) - } - ShapeKind::Sphere { radius, sub_base, sub_height } => { - let seg_u = sub_base.clamp(12, 96); - let seg_v = sub_height.clamp(8, 64); - let mut verts = Vec::with_capacity(((seg_u + 1) * (seg_v + 1)) as usize); - let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize); - for iv in 0..=seg_v { - let v = iv as f32 / seg_v as f32; - let phi = v * std::f32::consts::PI; // 0 (top +Y) -> PI (bottom -Y) - let (sp, cp) = phi.sin_cos(); - for iu in 0..=seg_u { - let u = iu as f32 / seg_u as f32; - // Fusion Shape3D Sphere places u=0.75 facing +Z (verified via probe_archive_3d f02) - let theta = (u - 0.75) * std::f32::consts::TAU; - let (st, ct) = theta.sin_cos(); - let nx = sp * st; - let ny = cp; - let nz = sp * ct; - verts.push(Vertex3D { - pos: [nx * radius, ny * radius, nz * radius], - normal: [nx, ny, nz], - uv: [u, v], - }); - } - } - let row = seg_u + 1; - for iv in 0..seg_v { - for iu in 0..seg_u { - let a = iv * row + iu; - let b = (iv + 1) * row + iu; - let c = (iv + 1) * row + iu + 1; - let d = iv * row + iu + 1; - idx.extend_from_slice(&[a, b, c, a, c, d]); - } - } - (verts, idx) - } - ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base } => { - let seg_u = sub_base.clamp(16, 96); - let half_h = height * 0.5; - let a0 = start_sweep_deg.to_radians(); - let a1 = end_sweep_deg.to_radians(); - let mut verts = Vec::with_capacity(((seg_u + 1) * 2) as usize); - let mut idx = Vec::with_capacity((seg_u * 6) as usize); - for iu in 0..=seg_u { - let u = iu as f32 / seg_u as f32; - // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc - let theta = a0 + (a1 - a0) * u; - let (st, ct) = theta.sin_cos(); - let nx = ct; - let nz = st; - verts.push(Vertex3D { - pos: [nx * radius, half_h, nz * radius], - normal: [nx, 0.0, nz], - uv: [1.0 - u, 0.0], - }); - verts.push(Vertex3D { - pos: [nx * radius, -half_h, nz * radius], - normal: [nx, 0.0, nz], - uv: [1.0 - u, 1.0], - }); - } - for iu in 0..seg_u { - let a = iu * 2; - let b = a + 1; - let c = a + 3; - let d = a + 2; - idx.extend_from_slice(&[a, b, c, a, c, d]); - } - (verts, idx) - } - ShapeKind::Cube { width, height, depth } => { - let hx = width * 0.5; - let hy = height * 0.5; - let hz = depth * 0.5; - let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [ - ([0.0, 0.0, 1.0], [[-hx, hy, hz], [-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz]]), - ([0.0, 0.0, -1.0], [[hx, hy, -hz], [hx, -hy, -hz], [-hx, -hy, -hz], [-hx, hy, -hz]]), - ([1.0, 0.0, 0.0], [[hx, hy, hz], [hx, -hy, hz], [hx, -hy, -hz], [hx, hy, -hz]]), - ([-1.0, 0.0, 0.0], [[-hx, hy, -hz], [-hx, -hy, -hz], [-hx, -hy, hz], [-hx, hy, hz]]), - ([0.0, 1.0, 0.0], [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]]), - ([0.0, -1.0, 0.0], [[-hx, -hy, hz], [-hx, -hy, -hz], [hx, -hy, -hz], [hx, -hy, hz]]), - ]; - let mut verts = Vec::with_capacity(24); - let mut idx = Vec::with_capacity(36); - for (n, corners) in faces { - let base = verts.len() as u32; - let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]; - for (p, uv) in corners.into_iter().zip(uvs) { - verts.push(Vertex3D { pos: p, normal: n, uv }); - } - idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); - } - (verts, idx) - } - } -} - -fn apply_heightmap_displace(verts: &mut [Vertex3D], indices: &[u32], disp: &DisplaceHeightmap) { - let w = disp.size[0].max(1) as usize; - let h = disp.size[1].max(1) as usize; - if disp.rgba.len() < w * h * 4 { - return; - } - for v in verts.iter_mut() { - let px = ((v.uv[0].clamp(0.0, 1.0)) * (w - 1) as f32).round() as usize; - let py = ((v.uv[1].clamp(0.0, 1.0)) * (h - 1) as f32).round() as usize; - let off = (py * w + px) * 4; - let r = disp.rgba[off] as f32 / 255.0; - let g = disp.rgba[off + 1] as f32 / 255.0; - let b = disp.rgba[off + 2] as f32 / 255.0; - let a = disp.rgba[off + 3] as f32 / 255.0; - let sample = match disp.channel { - 0 => r, - 1 => g, - 2 => b, - 3 => a, - _ => 0.299 * r + 0.587 * g + 0.114 * b, - }; - let d = (sample - 0.5 + disp.bias) * disp.scale; - v.pos[0] += v.normal[0] * d; - v.pos[1] += v.normal[1] * d; - v.pos[2] += v.normal[2] * d; - } - // Recompute smooth vertex normals from displaced triangles - let mut acc = vec![[0.0_f32; 3]; verts.len()]; - for tri in indices.chunks_exact(3) { - let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize); - if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() { - continue; - } - let p0 = verts[i0].pos; - let p1 = verts[i1].pos; - let p2 = verts[i2].pos; - let e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]]; - let e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]]; - let fn_v = [ - e1[1] * e2[2] - e1[2] * e2[1], - e1[2] * e2[0] - e1[0] * e2[2], - e1[0] * e2[1] - e1[1] * e2[0], - ]; - for &i in &[i0, i1, i2] { - acc[i][0] += fn_v[0]; - acc[i][1] += fn_v[1]; - acc[i][2] += fn_v[2]; - } - } - for (v, n) in verts.iter_mut().zip(acc.into_iter()) { - let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); - if len > 1e-6 { - v.normal = [n[0] / len, n[1] / len, n[2] / len]; - } - } -} - -#[derive(Clone, Default)] -struct SceneOverrides { - material_override: Option, - affected_by_lights: Option, - flip_normals: bool, - displace: Option, -} - -fn splitmix64(mut x: u64) -> f32 { - x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); - x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - x ^= x >> 31; - // Uniform in [-0.5, +0.5] - ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5 -} - -/// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`, -/// `ImagePlane3D`, `Shape3D`, `Text3D`, `LightAmbient`, `LightDirectional`, `LightPoint`, -/// `LightSpot`, `ReplaceMaterial3D`, `Override3D`, `Duplicate3D`, `ReplaceNormals3D`, `Displace3D`). -#[allow(clippy::too_many_arguments)] -pub fn collect_scene( - comp: &Comp, - node_id: NodeId, - time: f64, - expr: &ExprEngine, - parent_xform: Mat4, - render_aspect: f32, - cameras: &mut Vec, - meshes: &mut Vec, - lights: &mut SceneLights, - depth: usize, -) { - collect_scene_inner( - comp, - node_id, - time, - expr, - parent_xform, - render_aspect, - &SceneOverrides::default(), - cameras, - meshes, - lights, - depth, - ); -} - -#[allow(clippy::too_many_arguments)] -fn collect_scene_inner( - comp: &Comp, - node_id: NodeId, - time: f64, - expr: &ExprEngine, - parent_xform: Mat4, - render_aspect: f32, - ovr: &SceneOverrides, - cameras: &mut Vec, - meshes: &mut Vec, - lights: &mut SceneLights, - depth: usize, -) { - if depth > 32 { - return; - } - let node = comp.node(node_id); - if node.bypassed { - return; - } - let local = eval_transform3d(comp, node, time, expr); - let world = mat4_mul(parent_xform, local); - - match node.kind.as_str() { - "Merge3D" | "Transform3D" => { - let mut input_names: Vec<&String> = node - .inputs - .keys() - .filter(|k| k.starts_with("SceneInput")) - .collect(); - input_names.sort(); - for in_name in input_names { - if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) { - collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); - } - } - } - "ReplaceMaterial3D" => { - let mut next_ovr = ovr.clone(); - if let Some(mid) = node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)) { - next_ovr.material_override = Some(mid); - } - if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { - collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); - } - } - "Override3D" => { - let do_vis = comp.eval_number(node, "Visibility.DoVisible", time, 0.0, expr) > 0.5; - let is_vis = comp.eval_number(node, "Visibility.IsVisible", time, 1.0, expr) > 0.5; - if do_vis && !is_vis { - return; - } - let mut next_ovr = ovr.clone(); - let do_lit = comp.eval_number(node, "Lighting.DoAffectedByLights", time, 0.0, expr) > 0.5; - if do_lit { - let is_lit = comp.eval_number(node, "Lighting.IsAffectedByLights", time, 1.0, expr) > 0.5; - next_ovr.affected_by_lights = Some(is_lit); - } - if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { - collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); - } - } - "ReplaceNormals3D" => { - let mut next_ovr = ovr.clone(); - if comp.eval_number(node, "FlipNormals", time, 0.0, expr) > 0.5 { - next_ovr.flip_normals = !next_ovr.flip_normals; - } - if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { - collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); - } - } - "Displace3D" => { - let mut next_ovr = ovr.clone(); - if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { - let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32; - let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32; - let channel = comp.eval_number(node, "Channel", time, 4.0, expr).round() as i32; - next_ovr.displace = Some(Displace3DSpec { - input_node: in_id, - scale, - bias, - channel, - }); - } - if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { - collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); - } - } - "Duplicate3D" => { - let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { - return; - }; - let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32; - let last = comp.eval_number(node, "LastCopy", time, 1.0, expr).round() as i32; - let count = (last - first + 1).clamp(0, 256); - // Fusion Duplicate3D uses bare `Translate.X/Y/Z`, `Rotate.X/Y/Z`, `Scale.X/Y/Z` (with fallback to `Transform3DOp.*`) - let step = eval_duplicate3d_step(comp, node, time, expr); - let seed = comp.eval_number(node, "RandomSeed", time, 26024.0, expr).round() as u64; - let jtx = comp.eval_number(node, "JitterTranslate.X", time, 0.0, expr) as f32; - let jty = comp.eval_number(node, "JitterTranslate.Y", time, 0.0, expr) as f32; - let jtz = comp.eval_number(node, "JitterTranslate.Z", time, 0.0, expr) as f32; - let jrx = comp.eval_number(node, "JitterRotate.X", time, 0.0, expr) as f32; - let jry = comp.eval_number(node, "JitterRotate.Y", time, 0.0, expr) as f32; - let jrz = comp.eval_number(node, "JitterRotate.Z", time, 0.0, expr) as f32; - let has_jitter = (jtx.abs() + jty.abs() + jtz.abs() + jrx.abs() + jry.abs() + jrz.abs()) > 1e-5; - - let mut acc = mat4_identity(); - for _ in 0..first.max(0) { - acc = mat4_mul(acc, step); - } - for i in 0..count { - let copy_idx = (first + i) as u64; - let mut m = mat4_mul(parent_xform, acc); - if has_jitter { - let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407)); - let tx = splitmix64(s ^ 1) * jtx; - let ty = splitmix64(s ^ 2) * jty; - let tz = splitmix64(s ^ 3) * jtz; - let rx = (splitmix64(s ^ 4) * jrx).to_radians(); - let ry = (splitmix64(s ^ 5) * jry).to_radians(); - let rz = (splitmix64(s ^ 6) * jrz).to_radians(); - let jm = mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx)))); - m = mat4_mul(m, jm); - } - collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, depth + 1); - acc = mat4_mul(acc, step); - } - } - "Camera3D" => { - let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32; - let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32; - // In Fusion .comp files, serialized AoV is always vertical degrees (AoVType only changes UI display). - // When AoV is omitted, compute from FLength if present, else Fusion 21's default Camera3D vertical AoV (~24.302°). - let has_aov = node.inputs.contains_key("AoV"); - let has_fl = node.inputs.contains_key("FLength"); - let aov_deg = if has_aov { - comp.eval_number(node, "AoV", time, 24.302, expr) as f32 - } else if has_fl { - let fl_mm = comp.eval_number(node, "FLength", time, 24.0, expr).max(0.5) as f32; - let sensor_h_mm = ap_h * 25.4; - 2.0 * (sensor_h_mm * 0.5 / fl_mm).atan().to_degrees() - } else { - 24.302 - }; - // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders) - let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height"); - let gate_aspect = (ap_w / ap_h.max(1e-4)).max(1e-4); - - let half_aov = (aov_deg.to_radians() * 0.5).tan(); - let half_v = match gate_fit { - "Height" | "Stretch" => half_aov, - "Width" => half_aov * (gate_aspect / render_aspect.max(1e-4)), - "Outside" => half_aov * (gate_aspect / render_aspect.max(1e-4)).min(1.0), - _ => half_aov * (gate_aspect / render_aspect.max(1e-4)).max(1.0), // Inside (Fusion default!) - }; - let vfov_rad = 2.0 * half_v.atan(); - let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32; - let far = 5000.0_f32; - cameras.push(CameraInstance { world, vfov_rad, near, far }); - } - "LightAmbient" => { - let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; - lights.ambient[0] += r * inten; - lights.ambient[1] += g * inten; - lights.ambient[2] += b * inten; - } - "LightDirectional" => { - let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; - // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! - let dx = world[8]; - let dy = world[9]; - let dz = world[10]; - let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); - lights.dir_to_light = [dx / len, dy / len, dz / len]; - lights.dir_color = [r * inten, g * inten, b * inten]; - lights.has_dir = true; - } - "LightPoint" => { - let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; - let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; - let decay_rate = comp.eval_number(node, "DecayRate", time, 1.0, expr) as f32; - lights.points.push(PointLight { - pos: [world[12], world[13], world[14]], - color: [r * inten, g * inten, b * inten], - decay_type, - decay_rate, - }); - } - "LightSpot" => { - let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; - let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; - let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; - let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; - // SpotLight shines along -Z in local space - let dx = -world[8]; - let dy = -world[9]; - let dz = -world[10]; - let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); - let half_cone = (cone_deg * 0.5).max(0.5); - let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5); - let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg); - lights.spots.push(SpotLight { - pos: [world[12], world[13], world[14]], - dir: [dx / len, dy / len, dz / len], - color: [r * inten, g * inten, b * inten], - cos_inner: inner_deg.to_radians().cos(), - cos_outer: outer_deg.to_radians().cos(), - decay_type, - }); - } - "ImagePlane3D" => { - let mat_node = ovr.material_override.or_else(|| { - node.connected_node("MaterialInput") - .or_else(|| node.connected_node("SceneInput")) - .and_then(|s| comp.find_node(s)) - }); - let mat = resolve_material(comp, mat_node, time, expr); - meshes.push(MeshInstance { - world, - shape: ShapeKind::ImagePlane, - material_node: mat.tex_node, - text3d: None, - diffuse_col: mat.diffuse_col, - specular_col: mat.specular_col, - specular_intensity: mat.specular_intensity, - specular_exponent: mat.specular_exponent, - affected_by_lights: ovr.affected_by_lights.unwrap_or(true), - flip_normals: ovr.flip_normals, - displace: ovr.displace.clone(), - }); - } - "Shape3D" => { - let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); - let disp_sub = if ovr.displace.is_some() { 32 } else { 1 }; - let shape = match shape_name { - "SurfaceSphereInputs" => ShapeKind::Sphere { - // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) - radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32, - sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 32.0, expr).round() as u32, - sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32, - }, - "SurfaceCylinderInputs" => { - let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32; - let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32; - ShapeKind::Cylinder { - radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 0.5, expr) as f32, - height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 1.0, expr) as f32, - start_sweep_deg: start_sw, - end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, - sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32, - } - } - "SurfaceCubeInputs" => { - let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr); - ShapeKind::Cube { - width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32, - height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32, - depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32, - } - } - _ => { - let sw = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; - let sh = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionHeight", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; - ShapeKind::Plane { - width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32, - height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32, - sub_w: sw, - sub_h: sh, - } - } - }; - let mat_node = ovr.material_override.or_else(|| { - node.connected_node("MaterialInput") - .and_then(|s| comp.find_node(s)) - }); - let mut mat = resolve_material(comp, mat_node, time, expr); - if mat_node.is_none() { - mat.diffuse_col = [ - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32, - ]; - } - meshes.push(MeshInstance { - world, - shape, - material_node: mat.tex_node, - text3d: None, - diffuse_col: mat.diffuse_col, - specular_col: mat.specular_col, - specular_intensity: mat.specular_intensity, - specular_exponent: mat.specular_exponent, - affected_by_lights: ovr.affected_by_lights.unwrap_or(true), - flip_normals: ovr.flip_normals, - displace: ovr.displace.clone(), - }); - } - "Text3D" => { - let ext_depth = comp.eval_number(node, "Extrusion.ExtrusionDepth", time, 0.0, expr) as f32; - let mat_node = ovr.material_override.or_else(|| { - node.connected_node("MaterialInput") - .and_then(|s| comp.find_node(s)) - }); - let mut mat = resolve_material(comp, mat_node, time, expr); - if mat_node.is_none() { - mat.diffuse_col = [1.0, 1.0, 1.0, 1.0]; - } - // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate) - meshes.push(MeshInstance { - world, - shape: ShapeKind::TextPlate { - width: 4.0, - height: 2.0, - depth: ext_depth, - slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 }, - }, - material_node: mat.tex_node, - text3d: Some(Text3DSpec { node_id }), - diffuse_col: mat.diffuse_col, - specular_col: mat.specular_col, - specular_intensity: mat.specular_intensity, - specular_exponent: mat.specular_exponent, - affected_by_lights: ovr.affected_by_lights.unwrap_or(true), - flip_normals: ovr.flip_normals, - displace: ovr.displace.clone(), - }); - } - "MacroOperator" | "GroupOperator" => { - if let Some(out_id) = node.macro_output { - collect_scene_inner(comp, out_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); - } - } - _ => {} - } -} - -struct ResolvedMaterial { - tex_node: Option, - diffuse_col: [f32; 4], - specular_col: [f32; 3], - specular_intensity: f32, - specular_exponent: f32, -} - -/// Resolves a 3D material input (either a 2D image node, `Texture2DOperator`, or a Fusion 3D -/// material like `MtlBlinn` / `MtlCookTorrance` / `MtlPhong`). -fn resolve_material( - comp: &Comp, - mat_node: Option, - time: f64, - expr: &ExprEngine, -) -> ResolvedMaterial { - let default_mat = ResolvedMaterial { - tex_node: None, - diffuse_col: [1.0, 1.0, 1.0, 1.0], - specular_col: [1.0, 1.0, 1.0], - specular_intensity: 0.15, - specular_exponent: 25.0, - }; - let Some(mid) = mat_node else { - return default_mat; - }; - let n = comp.node(mid); - match n.kind.as_str() { - "Texture2DOperator" => { - let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s)); - ResolvedMaterial { - tex_node: tex_src, - ..default_mat - } - } - "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" => { - let mut diff_tex = n - .connected_node("Diffuse.Color.Material") - .or_else(|| n.connected_node("MaterialInput")) - .and_then(|s| comp.find_node(s)); - // Unwrap Texture2DOperator if feeding Diffuse.Color.Material - if let Some(tid) = diff_tex { - if comp.node(tid).kind == "Texture2DOperator" { - diff_tex = comp.node(tid).connected_node("Input").and_then(|s| comp.find_node(s)); - } - } - let col = [ - comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32, - comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32, - comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32, - comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32, - ]; - let spec_col = [ - comp.eval_number(n, "Specular.Color.Red", time, 1.0, expr) as f32, - comp.eval_number(n, "Specular.Color.Green", time, 1.0, expr) as f32, - comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32, - ]; - let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32; - let (spec_exp, spec_gain) = if n.kind == "MtlCookTorrance" { - let rough = comp.eval_number(n, "Specular.Roughness", time, 0.4, expr).clamp(0.05, 1.0) as f32; - ((2.0 / (rough * rough) - 2.0).max(2.0), 0.15) - } else { - (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0) - }; - ResolvedMaterial { - tex_node: diff_tex, - diffuse_col: col, - specular_col: spec_col, - specular_intensity: spec_int.clamp(0.0, 4.0) * spec_gain, - specular_exponent: spec_exp, - } - } - _ => ResolvedMaterial { - tex_node: Some(mid), - ..default_mat - }, - } -} - -fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { - let tx = comp.eval_number(node, "Translate.X", time, comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr), expr) as f32; - let ty = comp.eval_number(node, "Translate.Y", time, comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr), expr) as f32; - let tz = comp.eval_number(node, "Translate.Z", time, comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr), expr) as f32; - let rx = (comp.eval_number(node, "Rotate.X", time, comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr), expr) as f32).to_radians(); - let ry = (comp.eval_number(node, "Rotate.Y", time, comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr), expr) as f32).to_radians(); - let rz = (comp.eval_number(node, "Rotate.Z", time, comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr), expr) as f32).to_radians(); - let sx = comp.eval_number(node, "Scale.X", time, comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr), expr) as f32; - let sy = comp.eval_number(node, "Scale.Y", time, comp.eval_number(node, "Transform3DOp.Scale.Y", time, sx as f64, expr), expr) as f32; - let sz = comp.eval_number(node, "Scale.Z", time, comp.eval_number(node, "Transform3DOp.Scale.Z", time, sx as f64, expr), expr) as f32; - let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))); - mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz))) -} - -pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { - let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32; - let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32; - let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32; - - let rx = (comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr) as f32).to_radians(); - let ry = (comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr) as f32).to_radians(); - let rz = (comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr) as f32).to_radians(); - let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ"); - - let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5; - let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32; - let sy = if scale_lock { - sx - } else { - comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32 - }; - let sz = if scale_lock { - sx - } else { - comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32 - }; - - let px = comp.eval_number(node, "Transform3DOp.Pivot.X", time, 0.0, expr) as f32; - let py = comp.eval_number(node, "Transform3DOp.Pivot.Y", time, 0.0, expr) as f32; - let pz = comp.eval_number(node, "Transform3DOp.Pivot.Z", time, 0.0, expr) as f32; - - let mx = mat4_rot_x(rx); - let my = mat4_rot_y(ry); - let mz = mat4_rot_z(rz); - let rot = match rot_order { - "XZY" => mat4_mul(my, mat4_mul(mz, mx)), - "YXZ" => mat4_mul(mz, mat4_mul(mx, my)), - "YZX" => mat4_mul(mx, mat4_mul(mz, my)), - "ZXY" => mat4_mul(my, mat4_mul(mx, mz)), - "ZYX" => mat4_mul(mx, mat4_mul(my, mz)), - _ => mat4_mul(mz, mat4_mul(my, mx)), // XYZ default - }; - - let t = mat4_translate(tx + px, ty + py, tz + pz); - let s = mat4_scale(sx, sy, sz); - let inv_p = mat4_translate(-px, -py, -pz); - mat4_mul(t, mat4_mul(rot, mat4_mul(s, inv_p))) -} - -pub fn mat4_identity() -> Mat4 { - [ - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ] -} - -pub fn mat4_mul(a: Mat4, b: Mat4) -> Mat4 { - let mut out = [0.0_f32; 16]; - for col in 0..4 { - for row in 0..4 { - out[col * 4 + row] = a[row] * b[col * 4] - + a[4 + row] * b[col * 4 + 1] - + a[8 + row] * b[col * 4 + 2] - + a[12 + row] * b[col * 4 + 3]; - } - } - out -} - -pub fn mat4_translate(x: f32, y: f32, z: f32) -> Mat4 { - [ - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - x, y, z, 1.0, - ] -} - -pub fn mat4_scale(x: f32, y: f32, z: f32) -> Mat4 { - [ - x, 0.0, 0.0, 0.0, - 0.0, y, 0.0, 0.0, - 0.0, 0.0, z, 0.0, - 0.0, 0.0, 0.0, 1.0, - ] -} - -pub fn mat4_rot_x(r: f32) -> Mat4 { - let (s, c) = r.sin_cos(); - [ - 1.0, 0.0, 0.0, 0.0, - 0.0, c, s, 0.0, - 0.0, -s, c, 0.0, - 0.0, 0.0, 0.0, 1.0, - ] -} - -pub fn mat4_rot_y(r: f32) -> Mat4 { - let (s, c) = r.sin_cos(); - [ - c, 0.0, -s, 0.0, - 0.0, 1.0, 0.0, 0.0, - s, 0.0, c, 0.0, - 0.0, 0.0, 0.0, 1.0, - ] -} - -pub fn mat4_rot_z(r: f32) -> Mat4 { - let (s, c) = r.sin_cos(); - [ - c, s, 0.0, 0.0, - -s, c, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ] -} - -pub fn mat4_inverse_rigid(m: Mat4) -> Mat4 { - let r00 = m[0]; let r10 = m[1]; let r20 = m[2]; - let r01 = m[4]; let r11 = m[5]; let r21 = m[6]; - let r02 = m[8]; let r12 = m[9]; let r22 = m[10]; - let tx = m[12]; let ty = m[13]; let tz = m[14]; - let itx = -(r00 * tx + r10 * ty + r20 * tz); - let ity = -(r01 * tx + r11 * ty + r21 * tz); - let itz = -(r02 * tx + r12 * ty + r22 * tz); - [ - r00, r01, r02, 0.0, - r10, r11, r12, 0.0, - r20, r21, r22, 0.0, - itx, ity, itz, 1.0, - ] -} - -pub fn mat4_perspective_wgpu(vfov_rad: f32, aspect: f32, near: f32, far: f32) -> Mat4 { - let f = 1.0 / (vfov_rad * 0.5).tan().max(1e-5); - let nf = 1.0 / (near - far); - [ - f / aspect.max(1e-4), 0.0, 0.0, 0.0, - 0.0, f, 0.0, 0.0, - 0.0, 0.0, far * nf, -1.0, - 0.0, 0.0, far * near * nf, 0.0, - ] -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_collect_scene_archive_3d_nodes() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 10 }, - GlobalRange = { 0, 10 }, - Tools = ordered() { - BG1 = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - }, - }, - Tex2D = Texture2DOperator { - Inputs = { - Input = Input { SourceOp = "BG1", Source = "Output", }, - }, - }, - Blinn1 = MtlBlinn { - Inputs = { - ["Diffuse.Color.Red"] = Input { Value = 0.8, }, - ["Diffuse.Color.Material"] = Input { SourceOp = "Tex2D", Source = "MaterialOutput", }, - ["Specular.Intensity"] = Input { Value = 0.75, }, - ["Specular.Exponent"] = Input { Value = 40.0, }, - }, - }, - Cook1 = MtlCookTorrance { - Inputs = { - ["Diffuse.Color.Green"] = Input { Value = 0.6, }, - ["Specular.Roughness"] = Input { Value = 0.25, }, - }, - }, - Shape1 = Shape3D { - Inputs = { - Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, - MaterialInput = Input { SourceOp = "Blinn1", Source = "MaterialOutput", }, - }, - }, - RepMat = ReplaceMaterial3D { - Inputs = { - SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, - MaterialInput = Input { SourceOp = "Cook1", Source = "MaterialOutput", }, - }, - }, - RepNorm = ReplaceNormals3D { - Inputs = { - SceneInput = Input { SourceOp = "RepMat", Source = "Output", }, - FlipNormals = Input { Value = 1, }, - }, - }, - Disp1 = Displace3D { - Inputs = { - SceneInput = Input { SourceOp = "RepNorm", Source = "Output", }, - Input = Input { SourceOp = "BG1", Source = "Output", }, - Scale = Input { Value = 0.2, }, - }, - }, - Dup1 = Duplicate3D { - Inputs = { - SceneInput = Input { SourceOp = "Disp1", Source = "Output", }, - FirstCopy = Input { Value = 0, }, - LastCopy = Input { Value = 2, }, - ["Translate.X"] = Input { Value = 1.5, }, - }, - }, - OvrHide = Override3D { - Inputs = { - SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, - ["Visibility.DoVisible"] = Input { Value = 1, }, - ["Visibility.IsVisible"] = Input { Value = 0, }, - }, - }, - Txt1 = Text3D { - Inputs = { - StyledText = Input { Value = "HI", }, - ["Extrusion.ExtrusionDepth"] = Input { Value = 0.15, }, - }, - }, - Pt1 = LightPoint { - Inputs = { - Intensity = Input { Value = 2.0, }, - DecayType = Input { Value = 1, }, - ["Transform3DOp.Translate.X"] = Input { Value = 3.0, }, - }, - }, - Sp1 = LightSpot { - Inputs = { - Intensity = Input { Value = 1.5, }, - ConeAngle = Input { Value = 45.0, }, - PenumbraAngle = Input { Value = 10.0, }, - }, - }, - Cam1 = Camera3D { - Inputs = { - ["Transform3DOp.Translate.Z"] = Input { Value = 5.0, }, - }, - }, - Merge1 = Merge3D { - Inputs = { - SceneInput1 = Input { SourceOp = "Dup1", Source = "Output", }, - SceneInput2 = Input { SourceOp = "OvrHide", Source = "Output", }, - SceneInput3 = Input { SourceOp = "Txt1", Source = "Output", }, - SceneInput4 = Input { SourceOp = "Pt1", Source = "Output", }, - SceneInput5 = Input { SourceOp = "Sp1", Source = "Output", }, - SceneInput6 = Input { SourceOp = "Cam1", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse 3D test comp"); - let expr = ExprEngine::new(); - let merge_id = comp.find_node("Merge1").expect("Merge1"); - let mut cams = Vec::new(); - let mut meshes = Vec::new(); - let mut lights = SceneLights::default(); - collect_scene( - &comp, - merge_id, - 0.0, - &expr, - mat4_identity(), - 16.0 / 9.0, - &mut cams, - &mut meshes, - &mut lights, - 0, - ); - assert_eq!(cams.len(), 1); - // 3 copies from Duplicate3D (0..=2) + 1 Text3D (OvrHide suppresses its Shape1) - assert_eq!(meshes.len(), 4); - assert!(meshes[0].flip_normals); - assert!(meshes[0].displace.is_some()); - assert!((meshes[0].diffuse_col[1] - 0.6).abs() < 1e-4, "ReplaceMaterial3D should apply Cook1"); - assert!((meshes[2].world[12] - 3.0).abs() < 1e-4, "Duplicate3D copy 2 translated X=3.0"); - assert!(meshes[3].text3d.is_some()); - assert_eq!(lights.points.len(), 1); - assert!((lights.points[0].pos[0] - 3.0).abs() < 1e-4); - assert_eq!(lights.spots.len(), 1); - assert!(lights.spots[0].cos_inner > lights.spots[0].cos_outer); - } -} diff --git a/crates/engine/src/scene3d/collect.rs b/crates/engine/src/scene3d/collect.rs new file mode 100644 index 0000000000000000000000000000000000000000..34c9c8d7932d31375c3f90d88841e39c063e7271 --- /dev/null +++ b/crates/engine/src/scene3d/collect.rs @@ -0,0 +1,692 @@ +//! 3D scene graph traversal, material resolution, and 3D transform evaluation. + +use super::math::{ + mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, +}; +use super::{ + CameraInstance, Displace3DSpec, Mat4, MeshInstance, PointLight, SceneLights, ShapeKind, + SpotLight, Text3DSpec, +}; +use model::{Comp, ExprEngine, Node, NodeId}; + +#[derive(Clone, Default)] +struct SceneOverrides { + material_override: Option, + affected_by_lights: Option, + flip_normals: bool, + displace: Option, +} + +fn splitmix64(mut x: u64) -> f32 { + x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + x ^= x >> 31; + // Uniform in [-0.5, +0.5] + ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5 +} + +/// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`, +/// `ImagePlane3D`, `Shape3D`, `Text3D`, `LightAmbient`, `LightDirectional`, `LightPoint`, +/// `LightSpot`, `ReplaceMaterial3D`, `Override3D`, `Duplicate3D`, `ReplaceNormals3D`, `Displace3D`). +#[allow(clippy::too_many_arguments)] +pub fn collect_scene( + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &ExprEngine, + parent_xform: Mat4, + render_aspect: f32, + cameras: &mut Vec, + meshes: &mut Vec, + lights: &mut SceneLights, + depth: usize, +) { + collect_scene_inner( + comp, + node_id, + time, + expr, + parent_xform, + render_aspect, + &SceneOverrides::default(), + cameras, + meshes, + lights, + depth, + ); +} + +#[allow(clippy::too_many_arguments)] +fn collect_scene_inner( + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &ExprEngine, + parent_xform: Mat4, + render_aspect: f32, + ovr: &SceneOverrides, + cameras: &mut Vec, + meshes: &mut Vec, + lights: &mut SceneLights, + depth: usize, +) { + if depth > 32 { + return; + } + let node = comp.node(node_id); + if node.bypassed { + return; + } + let local = eval_transform3d(comp, node, time, expr); + let world = mat4_mul(parent_xform, local); + + match node.kind.as_str() { + "Merge3D" | "Transform3D" => { + let mut input_names: Vec<&String> = node + .inputs + .keys() + .filter(|k| k.starts_with("SceneInput")) + .collect(); + input_names.sort(); + for in_name in input_names { + if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); + } + } + } + "ReplaceMaterial3D" => { + let mut next_ovr = ovr.clone(); + if let Some(mid) = node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)) { + next_ovr.material_override = Some(mid); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); + } + } + "Override3D" => { + let do_vis = comp.eval_number(node, "Visibility.DoVisible", time, 0.0, expr) > 0.5; + let is_vis = comp.eval_number(node, "Visibility.IsVisible", time, 1.0, expr) > 0.5; + if do_vis && !is_vis { + return; + } + let mut next_ovr = ovr.clone(); + let do_lit = comp.eval_number(node, "Lighting.DoAffectedByLights", time, 0.0, expr) > 0.5; + if do_lit { + let is_lit = comp.eval_number(node, "Lighting.IsAffectedByLights", time, 1.0, expr) > 0.5; + next_ovr.affected_by_lights = Some(is_lit); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); + } + } + "ReplaceNormals3D" => { + let mut next_ovr = ovr.clone(); + if comp.eval_number(node, "FlipNormals", time, 0.0, expr) > 0.5 { + next_ovr.flip_normals = !next_ovr.flip_normals; + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); + } + } + "Displace3D" => { + let mut next_ovr = ovr.clone(); + if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { + let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32; + let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32; + let channel = comp.eval_number(node, "Channel", time, 4.0, expr).round() as i32; + next_ovr.displace = Some(Displace3DSpec { + input_node: in_id, + scale, + bias, + channel, + }); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); + } + } + "Duplicate3D" => { + let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { + return; + }; + let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32; + let last = comp.eval_number(node, "LastCopy", time, 1.0, expr).round() as i32; + let count = (last - first + 1).clamp(0, 256); + // Fusion Duplicate3D uses bare `Translate.X/Y/Z`, `Rotate.X/Y/Z`, `Scale.X/Y/Z` (with fallback to `Transform3DOp.*`) + let step = eval_duplicate3d_step(comp, node, time, expr); + let seed = comp.eval_number(node, "RandomSeed", time, 26024.0, expr).round() as u64; + let jtx = comp.eval_number(node, "JitterTranslate.X", time, 0.0, expr) as f32; + let jty = comp.eval_number(node, "JitterTranslate.Y", time, 0.0, expr) as f32; + let jtz = comp.eval_number(node, "JitterTranslate.Z", time, 0.0, expr) as f32; + let jrx = comp.eval_number(node, "JitterRotate.X", time, 0.0, expr) as f32; + let jry = comp.eval_number(node, "JitterRotate.Y", time, 0.0, expr) as f32; + let jrz = comp.eval_number(node, "JitterRotate.Z", time, 0.0, expr) as f32; + let has_jitter = (jtx.abs() + jty.abs() + jtz.abs() + jrx.abs() + jry.abs() + jrz.abs()) > 1e-5; + + let mut acc = mat4_identity(); + for _ in 0..first.max(0) { + acc = mat4_mul(acc, step); + } + for i in 0..count { + let copy_idx = (first + i) as u64; + let mut m = mat4_mul(parent_xform, acc); + if has_jitter { + let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407)); + let tx = splitmix64(s ^ 1) * jtx; + let ty = splitmix64(s ^ 2) * jty; + let tz = splitmix64(s ^ 3) * jtz; + let rx = (splitmix64(s ^ 4) * jrx).to_radians(); + let ry = (splitmix64(s ^ 5) * jry).to_radians(); + let rz = (splitmix64(s ^ 6) * jrz).to_radians(); + let jm = mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx)))); + m = mat4_mul(m, jm); + } + collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, depth + 1); + acc = mat4_mul(acc, step); + } + } + "Camera3D" => { + let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32; + let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32; + // In Fusion .comp files, serialized AoV is always vertical degrees (AoVType only changes UI display). + // When AoV is omitted, compute from FLength if present, else Fusion 21's default Camera3D vertical AoV (~24.302°). + let has_aov = node.inputs.contains_key("AoV"); + let has_fl = node.inputs.contains_key("FLength"); + let aov_deg = if has_aov { + comp.eval_number(node, "AoV", time, 24.302, expr) as f32 + } else if has_fl { + let fl_mm = comp.eval_number(node, "FLength", time, 24.0, expr).max(0.5) as f32; + let sensor_h_mm = ap_h * 25.4; + 2.0 * (sensor_h_mm * 0.5 / fl_mm).atan().to_degrees() + } else { + 24.302 + }; + // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders) + let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height"); + let gate_aspect = (ap_w / ap_h.max(1e-4)).max(1e-4); + + let half_aov = (aov_deg.to_radians() * 0.5).tan(); + let half_v = match gate_fit { + "Height" | "Stretch" => half_aov, + "Width" => half_aov * (gate_aspect / render_aspect.max(1e-4)), + "Outside" => half_aov * (gate_aspect / render_aspect.max(1e-4)).min(1.0), + _ => half_aov * (gate_aspect / render_aspect.max(1e-4)).max(1.0), // Inside (Fusion default!) + }; + let vfov_rad = 2.0 * half_v.atan(); + let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32; + let far = 5000.0_f32; + cameras.push(CameraInstance { world, vfov_rad, near, far }); + } + "LightAmbient" => { + let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + lights.ambient[0] += r * inten; + lights.ambient[1] += g * inten; + lights.ambient[2] += b * inten; + } + "LightDirectional" => { + let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! + let dx = world[8]; + let dy = world[9]; + let dz = world[10]; + let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); + lights.dir_to_light = [dx / len, dy / len, dz / len]; + lights.dir_color = [r * inten, g * inten, b * inten]; + lights.has_dir = true; + } + "LightPoint" => { + let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; + let decay_rate = comp.eval_number(node, "DecayRate", time, 1.0, expr) as f32; + lights.points.push(PointLight { + pos: [world[12], world[13], world[14]], + color: [r * inten, g * inten, b * inten], + decay_type, + decay_rate, + }); + } + "LightSpot" => { + let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; + let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; + let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; + // SpotLight shines along -Z in local space + let dx = -world[8]; + let dy = -world[9]; + let dz = -world[10]; + let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); + let half_cone = (cone_deg * 0.5).max(0.5); + let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5); + let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg); + lights.spots.push(SpotLight { + pos: [world[12], world[13], world[14]], + dir: [dx / len, dy / len, dz / len], + color: [r * inten, g * inten, b * inten], + cos_inner: inner_deg.to_radians().cos(), + cos_outer: outer_deg.to_radians().cos(), + decay_type, + }); + } + "ImagePlane3D" => { + let mat_node = ovr.material_override.or_else(|| { + node.connected_node("MaterialInput") + .or_else(|| node.connected_node("SceneInput")) + .and_then(|s| comp.find_node(s)) + }); + let mat = resolve_material(comp, mat_node, time, expr); + meshes.push(MeshInstance { + world, + shape: ShapeKind::ImagePlane, + material_node: mat.tex_node, + text3d: None, + diffuse_col: mat.diffuse_col, + specular_col: mat.specular_col, + specular_intensity: mat.specular_intensity, + specular_exponent: mat.specular_exponent, + affected_by_lights: ovr.affected_by_lights.unwrap_or(true), + flip_normals: ovr.flip_normals, + displace: ovr.displace.clone(), + }); + } + "Shape3D" => { + let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); + let disp_sub = if ovr.displace.is_some() { 32 } else { 1 }; + let shape = match shape_name { + "SurfaceSphereInputs" => ShapeKind::Sphere { + // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) + radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32, + sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 32.0, expr).round() as u32, + sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32, + }, + "SurfaceCylinderInputs" => { + let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32; + let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32; + ShapeKind::Cylinder { + radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 0.5, expr) as f32, + height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 1.0, expr) as f32, + start_sweep_deg: start_sw, + end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, + sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32, + } + } + "SurfaceCubeInputs" => { + let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr); + ShapeKind::Cube { + width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32, + height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32, + depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32, + } + } + _ => { + let sw = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; + let sh = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionHeight", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; + ShapeKind::Plane { + width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32, + height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32, + sub_w: sw, + sub_h: sh, + } + } + }; + let mat_node = ovr.material_override.or_else(|| { + node.connected_node("MaterialInput") + .and_then(|s| comp.find_node(s)) + }); + let mut mat = resolve_material(comp, mat_node, time, expr); + if mat_node.is_none() { + mat.diffuse_col = [ + comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32, + comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32, + comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32, + comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32, + ]; + } + meshes.push(MeshInstance { + world, + shape, + material_node: mat.tex_node, + text3d: None, + diffuse_col: mat.diffuse_col, + specular_col: mat.specular_col, + specular_intensity: mat.specular_intensity, + specular_exponent: mat.specular_exponent, + affected_by_lights: ovr.affected_by_lights.unwrap_or(true), + flip_normals: ovr.flip_normals, + displace: ovr.displace.clone(), + }); + } + "Text3D" => { + let ext_depth = comp.eval_number(node, "Extrusion.ExtrusionDepth", time, 0.0, expr) as f32; + let mat_node = ovr.material_override.or_else(|| { + node.connected_node("MaterialInput") + .and_then(|s| comp.find_node(s)) + }); + let mut mat = resolve_material(comp, mat_node, time, expr); + if mat_node.is_none() { + mat.diffuse_col = [1.0, 1.0, 1.0, 1.0]; + } + // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate) + meshes.push(MeshInstance { + world, + shape: ShapeKind::TextPlate { + width: 4.0, + height: 2.0, + depth: ext_depth, + slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 }, + }, + material_node: mat.tex_node, + text3d: Some(Text3DSpec { node_id }), + diffuse_col: mat.diffuse_col, + specular_col: mat.specular_col, + specular_intensity: mat.specular_intensity, + specular_exponent: mat.specular_exponent, + affected_by_lights: ovr.affected_by_lights.unwrap_or(true), + flip_normals: ovr.flip_normals, + displace: ovr.displace.clone(), + }); + } + "MacroOperator" | "GroupOperator" => { + if let Some(out_id) = node.macro_output { + collect_scene_inner(comp, out_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); + } + } + _ => {} + } +} + +struct ResolvedMaterial { + tex_node: Option, + diffuse_col: [f32; 4], + specular_col: [f32; 3], + specular_intensity: f32, + specular_exponent: f32, +} + +/// Resolves a 3D material input (either a 2D image node, `Texture2DOperator`, or a Fusion 3D +/// material like `MtlBlinn` / `MtlCookTorrance` / `MtlPhong`). +fn resolve_material( + comp: &Comp, + mat_node: Option, + time: f64, + expr: &ExprEngine, +) -> ResolvedMaterial { + let default_mat = ResolvedMaterial { + tex_node: None, + diffuse_col: [1.0, 1.0, 1.0, 1.0], + specular_col: [1.0, 1.0, 1.0], + specular_intensity: 0.15, + specular_exponent: 25.0, + }; + let Some(mid) = mat_node else { + return default_mat; + }; + let n = comp.node(mid); + match n.kind.as_str() { + "Texture2DOperator" => { + let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s)); + ResolvedMaterial { + tex_node: tex_src, + ..default_mat + } + } + "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" => { + let mut diff_tex = n + .connected_node("Diffuse.Color.Material") + .or_else(|| n.connected_node("MaterialInput")) + .and_then(|s| comp.find_node(s)); + // Unwrap Texture2DOperator if feeding Diffuse.Color.Material + if let Some(tid) = diff_tex { + if comp.node(tid).kind == "Texture2DOperator" { + diff_tex = comp.node(tid).connected_node("Input").and_then(|s| comp.find_node(s)); + } + } + let col = [ + comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32, + comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32, + comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32, + comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32, + ]; + let spec_col = [ + comp.eval_number(n, "Specular.Color.Red", time, 1.0, expr) as f32, + comp.eval_number(n, "Specular.Color.Green", time, 1.0, expr) as f32, + comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32, + ]; + let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32; + let (spec_exp, spec_gain) = if n.kind == "MtlCookTorrance" { + let rough = comp.eval_number(n, "Specular.Roughness", time, 0.4, expr).clamp(0.05, 1.0) as f32; + ((2.0 / (rough * rough) - 2.0).max(2.0), 0.15) + } else { + (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0) + }; + ResolvedMaterial { + tex_node: diff_tex, + diffuse_col: col, + specular_col: spec_col, + specular_intensity: spec_int.clamp(0.0, 4.0) * spec_gain, + specular_exponent: spec_exp, + } + } + _ => ResolvedMaterial { + tex_node: Some(mid), + ..default_mat + }, + } +} + +fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { + let tx = comp.eval_number(node, "Translate.X", time, comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr), expr) as f32; + let ty = comp.eval_number(node, "Translate.Y", time, comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr), expr) as f32; + let tz = comp.eval_number(node, "Translate.Z", time, comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr), expr) as f32; + let rx = (comp.eval_number(node, "Rotate.X", time, comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr), expr) as f32).to_radians(); + let ry = (comp.eval_number(node, "Rotate.Y", time, comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr), expr) as f32).to_radians(); + let rz = (comp.eval_number(node, "Rotate.Z", time, comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr), expr) as f32).to_radians(); + let sx = comp.eval_number(node, "Scale.X", time, comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr), expr) as f32; + let sy = comp.eval_number(node, "Scale.Y", time, comp.eval_number(node, "Transform3DOp.Scale.Y", time, sx as f64, expr), expr) as f32; + let sz = comp.eval_number(node, "Scale.Z", time, comp.eval_number(node, "Transform3DOp.Scale.Z", time, sx as f64, expr), expr) as f32; + let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))); + mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz))) +} + +pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { + let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32; + let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32; + let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32; + + let rx = (comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr) as f32).to_radians(); + let ry = (comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr) as f32).to_radians(); + let rz = (comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr) as f32).to_radians(); + let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ"); + + let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5; + let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32; + let sy = if scale_lock { + sx + } else { + comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32 + }; + let sz = if scale_lock { + sx + } else { + comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32 + }; + + let px = comp.eval_number(node, "Transform3DOp.Pivot.X", time, 0.0, expr) as f32; + let py = comp.eval_number(node, "Transform3DOp.Pivot.Y", time, 0.0, expr) as f32; + let pz = comp.eval_number(node, "Transform3DOp.Pivot.Z", time, 0.0, expr) as f32; + + let mx = mat4_rot_x(rx); + let my = mat4_rot_y(ry); + let mz = mat4_rot_z(rz); + let rot = match rot_order { + "XZY" => mat4_mul(my, mat4_mul(mz, mx)), + "YXZ" => mat4_mul(mz, mat4_mul(mx, my)), + "YZX" => mat4_mul(mx, mat4_mul(mz, my)), + "ZXY" => mat4_mul(my, mat4_mul(mx, mz)), + "ZYX" => mat4_mul(mx, mat4_mul(my, mz)), + _ => mat4_mul(mz, mat4_mul(my, mx)), // XYZ default + }; + + let t = mat4_translate(tx + px, ty + py, tz + pz); + let s = mat4_scale(sx, sy, sz); + let inv_p = mat4_translate(-px, -py, -pz); + mat4_mul(t, mat4_mul(rot, mat4_mul(s, inv_p))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_collect_scene_archive_3d_nodes() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 10 }, + GlobalRange = { 0, 10 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + }, + }, + Tex2D = Texture2DOperator { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + }, + }, + Blinn1 = MtlBlinn { + Inputs = { + ["Diffuse.Color.Red"] = Input { Value = 0.8, }, + ["Diffuse.Color.Material"] = Input { SourceOp = "Tex2D", Source = "MaterialOutput", }, + ["Specular.Intensity"] = Input { Value = 0.75, }, + ["Specular.Exponent"] = Input { Value = 40.0, }, + }, + }, + Cook1 = MtlCookTorrance { + Inputs = { + ["Diffuse.Color.Green"] = Input { Value = 0.6, }, + ["Specular.Roughness"] = Input { Value = 0.25, }, + }, + }, + Shape1 = Shape3D { + Inputs = { + Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, + MaterialInput = Input { SourceOp = "Blinn1", Source = "MaterialOutput", }, + }, + }, + RepMat = ReplaceMaterial3D { + Inputs = { + SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, + MaterialInput = Input { SourceOp = "Cook1", Source = "MaterialOutput", }, + }, + }, + RepNorm = ReplaceNormals3D { + Inputs = { + SceneInput = Input { SourceOp = "RepMat", Source = "Output", }, + FlipNormals = Input { Value = 1, }, + }, + }, + Disp1 = Displace3D { + Inputs = { + SceneInput = Input { SourceOp = "RepNorm", Source = "Output", }, + Input = Input { SourceOp = "BG1", Source = "Output", }, + Scale = Input { Value = 0.2, }, + }, + }, + Dup1 = Duplicate3D { + Inputs = { + SceneInput = Input { SourceOp = "Disp1", Source = "Output", }, + FirstCopy = Input { Value = 0, }, + LastCopy = Input { Value = 2, }, + ["Translate.X"] = Input { Value = 1.5, }, + }, + }, + OvrHide = Override3D { + Inputs = { + SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, + ["Visibility.DoVisible"] = Input { Value = 1, }, + ["Visibility.IsVisible"] = Input { Value = 0, }, + }, + }, + Txt1 = Text3D { + Inputs = { + StyledText = Input { Value = "HI", }, + ["Extrusion.ExtrusionDepth"] = Input { Value = 0.15, }, + }, + }, + Pt1 = LightPoint { + Inputs = { + Intensity = Input { Value = 2.0, }, + DecayType = Input { Value = 1, }, + ["Transform3DOp.Translate.X"] = Input { Value = 3.0, }, + }, + }, + Sp1 = LightSpot { + Inputs = { + Intensity = Input { Value = 1.5, }, + ConeAngle = Input { Value = 45.0, }, + PenumbraAngle = Input { Value = 10.0, }, + }, + }, + Cam1 = Camera3D { + Inputs = { + ["Transform3DOp.Translate.Z"] = Input { Value = 5.0, }, + }, + }, + Merge1 = Merge3D { + Inputs = { + SceneInput1 = Input { SourceOp = "Dup1", Source = "Output", }, + SceneInput2 = Input { SourceOp = "OvrHide", Source = "Output", }, + SceneInput3 = Input { SourceOp = "Txt1", Source = "Output", }, + SceneInput4 = Input { SourceOp = "Pt1", Source = "Output", }, + SceneInput5 = Input { SourceOp = "Sp1", Source = "Output", }, + SceneInput6 = Input { SourceOp = "Cam1", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse 3D test comp"); + let expr = ExprEngine::new(); + let merge_id = comp.find_node("Merge1").expect("Merge1"); + let mut cams = Vec::new(); + let mut meshes = Vec::new(); + let mut lights = SceneLights::default(); + collect_scene( + &comp, + merge_id, + 0.0, + &expr, + mat4_identity(), + 16.0 / 9.0, + &mut cams, + &mut meshes, + &mut lights, + 0, + ); + assert_eq!(cams.len(), 1); + // 3 copies from Duplicate3D (0..=2) + 1 Text3D (OvrHide suppresses its Shape1) + assert_eq!(meshes.len(), 4); + assert!(meshes[0].flip_normals); + assert!(meshes[0].displace.is_some()); + assert!((meshes[0].diffuse_col[1] - 0.6).abs() < 1e-4, "ReplaceMaterial3D should apply Cook1"); + assert!((meshes[2].world[12] - 3.0).abs() < 1e-4, "Duplicate3D copy 2 translated X=3.0"); + assert!(meshes[3].text3d.is_some()); + assert_eq!(lights.points.len(), 1); + assert!((lights.points[0].pos[0] - 3.0).abs() < 1e-4); + assert_eq!(lights.spots.len(), 1); + assert!(lights.spots[0].cos_inner > lights.spots[0].cos_outer); + } +} diff --git a/crates/engine/src/scene3d/math.rs b/crates/engine/src/scene3d/math.rs new file mode 100644 index 0000000000000000000000000000000000000000..73e1303abd8f14311a5a8f276b5b37b73a3ef42f --- /dev/null +++ b/crates/engine/src/scene3d/math.rs @@ -0,0 +1,100 @@ +//! Column-major 4x4 linear algebra helpers for 3D scene transforms and projection. + +use super::Mat4; + +pub fn mat4_identity() -> Mat4 { + [ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_mul(a: Mat4, b: Mat4) -> Mat4 { + let mut out = [0.0_f32; 16]; + for col in 0..4 { + for row in 0..4 { + out[col * 4 + row] = a[row] * b[col * 4] + + a[4 + row] * b[col * 4 + 1] + + a[8 + row] * b[col * 4 + 2] + + a[12 + row] * b[col * 4 + 3]; + } + } + out +} + +pub fn mat4_translate(x: f32, y: f32, z: f32) -> Mat4 { + [ + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + x, y, z, 1.0, + ] +} + +pub fn mat4_scale(x: f32, y: f32, z: f32) -> Mat4 { + [ + x, 0.0, 0.0, 0.0, + 0.0, y, 0.0, 0.0, + 0.0, 0.0, z, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_rot_x(r: f32) -> Mat4 { + let (s, c) = r.sin_cos(); + [ + 1.0, 0.0, 0.0, 0.0, + 0.0, c, s, 0.0, + 0.0, -s, c, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_rot_y(r: f32) -> Mat4 { + let (s, c) = r.sin_cos(); + [ + c, 0.0, -s, 0.0, + 0.0, 1.0, 0.0, 0.0, + s, 0.0, c, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_rot_z(r: f32) -> Mat4 { + let (s, c) = r.sin_cos(); + [ + c, s, 0.0, 0.0, + -s, c, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0, + ] +} + +pub fn mat4_inverse_rigid(m: Mat4) -> Mat4 { + let r00 = m[0]; let r10 = m[1]; let r20 = m[2]; + let r01 = m[4]; let r11 = m[5]; let r21 = m[6]; + let r02 = m[8]; let r12 = m[9]; let r22 = m[10]; + let tx = m[12]; let ty = m[13]; let tz = m[14]; + let itx = -(r00 * tx + r10 * ty + r20 * tz); + let ity = -(r01 * tx + r11 * ty + r21 * tz); + let itz = -(r02 * tx + r12 * ty + r22 * tz); + [ + r00, r01, r02, 0.0, + r10, r11, r12, 0.0, + r20, r21, r22, 0.0, + itx, ity, itz, 1.0, + ] +} + +pub fn mat4_perspective_wgpu(vfov_rad: f32, aspect: f32, near: f32, far: f32) -> Mat4 { + let f = 1.0 / (vfov_rad * 0.5).tan().max(1e-5); + let nf = 1.0 / (near - far); + [ + f / aspect.max(1e-4), 0.0, 0.0, 0.0, + 0.0, f, 0.0, 0.0, + 0.0, 0.0, far * nf, -1.0, + 0.0, 0.0, far * near * nf, 0.0, + ] +} diff --git a/crates/engine/src/scene3d/mesh.rs b/crates/engine/src/scene3d/mesh.rs new file mode 100644 index 0000000000000000000000000000000000000000..5dcd3311adcf984d0834755fdf22a98550a3d0e5 --- /dev/null +++ b/crates/engine/src/scene3d/mesh.rs @@ -0,0 +1,251 @@ +//! Procedural 3D mesh builders and heightmap vertex displacement. + +use super::shader::Vertex3D; +use super::{DisplaceHeightmap, ShapeKind}; + +pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec, Vec) { + match *shape { + ShapeKind::ImagePlane => build_image_plane(tex_aspect), + ShapeKind::Plane { width, height, sub_w, sub_h } => build_plane(width, height, sub_w, sub_h), + ShapeKind::TextPlate { width, height, depth, slices } => { + build_text_plate(width, height, depth, slices) + } + ShapeKind::Sphere { radius, sub_base, sub_height } => { + build_sphere(radius, sub_base, sub_height) + } + ShapeKind::Cylinder { + radius, + height, + start_sweep_deg, + end_sweep_deg, + sub_base, + } => build_cylinder(radius, height, start_sweep_deg, end_sweep_deg, sub_base), + ShapeKind::Cube { width, height, depth } => build_cube(width, height, depth), + } +} + +fn build_image_plane(tex_aspect: f32) -> (Vec, Vec) { + let hx = 0.5; + let hy = 0.5 / tex_aspect.max(1e-4); + let verts = vec![ + Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] }, + Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, + Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, + Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] }, + ]; + (verts, vec![0, 1, 2, 0, 2, 3]) +} + +fn build_plane(width: f32, height: f32, sub_w: u32, sub_h: u32) -> (Vec, Vec) { + let sw = sub_w.clamp(1, 64); + let sh = sub_h.clamp(1, 64); + let hx = width * 0.5; + let hy = height * 0.5; + let mut verts = Vec::with_capacity(((sw + 1) * (sh + 1)) as usize); + let mut idx = Vec::with_capacity((sw * sh * 6) as usize); + for iy in 0..=sh { + let v = iy as f32 / sh as f32; + let y = hy - v * height; + for ix in 0..=sw { + let u = ix as f32 / sw as f32; + let x = -hx + u * width; + verts.push(Vertex3D { pos: [x, y, 0.0], normal: [0.0, 0.0, 1.0], uv: [u, v] }); + } + } + let row = sw + 1; + for iy in 0..sh { + for ix in 0..sw { + let a = iy * row + ix; + let b = (iy + 1) * row + ix; + let c = (iy + 1) * row + ix + 1; + let d = iy * row + ix + 1; + idx.extend_from_slice(&[a, b, c, a, c, d]); + } + } + (verts, idx) +} + +fn build_text_plate(width: f32, height: f32, depth: f32, slices: u32) -> (Vec, Vec) { + let hx = width * 0.5; + let hy = height * 0.5; + let n_slices = if depth.abs() > 1e-4 { slices.clamp(2, 16) } else { 1 }; + let mut verts = Vec::with_capacity((n_slices * 4) as usize); + let mut idx = Vec::with_capacity((n_slices * 6) as usize); + for s in 0..n_slices { + let t = if n_slices == 1 { 0.0 } else { s as f32 / (n_slices - 1) as f32 }; + // Fusion Text3D extrudes backward along -Z from z=0 to z=-depth + let z = -t * depth; + let nz = if n_slices > 1 && s == n_slices - 1 { -1.0 } else { 1.0 }; + let base = verts.len() as u32; + verts.push(Vertex3D { pos: [-hx, hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 0.0] }); + verts.push(Vertex3D { pos: [-hx, -hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 1.0] }); + verts.push(Vertex3D { pos: [ hx, -hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 1.0] }); + verts.push(Vertex3D { pos: [ hx, hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 0.0] }); + idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); + } + (verts, idx) +} + +fn build_sphere(radius: f32, sub_base: u32, sub_height: u32) -> (Vec, Vec) { + let seg_u = sub_base.clamp(12, 96); + let seg_v = sub_height.clamp(8, 64); + let mut verts = Vec::with_capacity(((seg_u + 1) * (seg_v + 1)) as usize); + let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize); + for iv in 0..=seg_v { + let v = iv as f32 / seg_v as f32; + let phi = v * std::f32::consts::PI; // 0 (top +Y) -> PI (bottom -Y) + let (sp, cp) = phi.sin_cos(); + for iu in 0..=seg_u { + let u = iu as f32 / seg_u as f32; + // Fusion Shape3D Sphere places u=0.75 facing +Z (verified via probe_archive_3d f02) + let theta = (u - 0.75) * std::f32::consts::TAU; + let (st, ct) = theta.sin_cos(); + let nx = sp * st; + let ny = cp; + let nz = sp * ct; + verts.push(Vertex3D { + pos: [nx * radius, ny * radius, nz * radius], + normal: [nx, ny, nz], + uv: [u, v], + }); + } + } + let row = seg_u + 1; + for iv in 0..seg_v { + for iu in 0..seg_u { + let a = iv * row + iu; + let b = (iv + 1) * row + iu; + let c = (iv + 1) * row + iu + 1; + let d = iv * row + iu + 1; + idx.extend_from_slice(&[a, b, c, a, c, d]); + } + } + (verts, idx) +} + +fn build_cylinder( + radius: f32, + height: f32, + start_sweep_deg: f32, + end_sweep_deg: f32, + sub_base: u32, +) -> (Vec, Vec) { + let seg_u = sub_base.clamp(16, 96); + let half_h = height * 0.5; + let a0 = start_sweep_deg.to_radians(); + let a1 = end_sweep_deg.to_radians(); + let mut verts = Vec::with_capacity(((seg_u + 1) * 2) as usize); + let mut idx = Vec::with_capacity((seg_u * 6) as usize); + for iu in 0..=seg_u { + let u = iu as f32 / seg_u as f32; + // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc + let theta = a0 + (a1 - a0) * u; + let (st, ct) = theta.sin_cos(); + let nx = ct; + let nz = st; + verts.push(Vertex3D { + pos: [nx * radius, half_h, nz * radius], + normal: [nx, 0.0, nz], + uv: [1.0 - u, 0.0], + }); + verts.push(Vertex3D { + pos: [nx * radius, -half_h, nz * radius], + normal: [nx, 0.0, nz], + uv: [1.0 - u, 1.0], + }); + } + for iu in 0..seg_u { + let a = iu * 2; + let b = a + 1; + let c = a + 3; + let d = a + 2; + idx.extend_from_slice(&[a, b, c, a, c, d]); + } + (verts, idx) +} + +fn build_cube(width: f32, height: f32, depth: f32) -> (Vec, Vec) { + let hx = width * 0.5; + let hy = height * 0.5; + let hz = depth * 0.5; + let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [ + ([0.0, 0.0, 1.0], [[-hx, hy, hz], [-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz]]), + ([0.0, 0.0, -1.0], [[hx, hy, -hz], [hx, -hy, -hz], [-hx, -hy, -hz], [-hx, hy, -hz]]), + ([1.0, 0.0, 0.0], [[hx, hy, hz], [hx, -hy, hz], [hx, -hy, -hz], [hx, hy, -hz]]), + ([-1.0, 0.0, 0.0], [[-hx, hy, -hz], [-hx, -hy, -hz], [-hx, -hy, hz], [-hx, hy, hz]]), + ([0.0, 1.0, 0.0], [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]]), + ([0.0, -1.0, 0.0], [[-hx, -hy, hz], [-hx, -hy, -hz], [hx, -hy, -hz], [hx, -hy, hz]]), + ]; + let mut verts = Vec::with_capacity(24); + let mut idx = Vec::with_capacity(36); + for (n, corners) in faces { + let base = verts.len() as u32; + let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]; + for (p, uv) in corners.into_iter().zip(uvs) { + verts.push(Vertex3D { pos: p, normal: n, uv }); + } + idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); + } + (verts, idx) +} + +pub(super) fn apply_heightmap_displace( + verts: &mut [Vertex3D], + indices: &[u32], + disp: &DisplaceHeightmap, +) { + let w = disp.size[0].max(1) as usize; + let h = disp.size[1].max(1) as usize; + if disp.rgba.len() < w * h * 4 { + return; + } + for v in verts.iter_mut() { + let px = ((v.uv[0].clamp(0.0, 1.0)) * (w - 1) as f32).round() as usize; + let py = ((v.uv[1].clamp(0.0, 1.0)) * (h - 1) as f32).round() as usize; + let off = (py * w + px) * 4; + let r = disp.rgba[off] as f32 / 255.0; + let g = disp.rgba[off + 1] as f32 / 255.0; + let b = disp.rgba[off + 2] as f32 / 255.0; + let a = disp.rgba[off + 3] as f32 / 255.0; + let sample = match disp.channel { + 0 => r, + 1 => g, + 2 => b, + 3 => a, + _ => 0.299 * r + 0.587 * g + 0.114 * b, + }; + let d = (sample - 0.5 + disp.bias) * disp.scale; + v.pos[0] += v.normal[0] * d; + v.pos[1] += v.normal[1] * d; + v.pos[2] += v.normal[2] * d; + } + // Recompute smooth vertex normals from displaced triangles + let mut acc = vec![[0.0_f32; 3]; verts.len()]; + for tri in indices.chunks_exact(3) { + let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize); + if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() { + continue; + } + let p0 = verts[i0].pos; + let p1 = verts[i1].pos; + let p2 = verts[i2].pos; + let e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]]; + let e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]]; + let fn_v = [ + e1[1] * e2[2] - e1[2] * e2[1], + e1[2] * e2[0] - e1[0] * e2[2], + e1[0] * e2[1] - e1[1] * e2[0], + ]; + for &i in &[i0, i1, i2] { + acc[i][0] += fn_v[0]; + acc[i][1] += fn_v[1]; + acc[i][2] += fn_v[2]; + } + } + for (v, n) in verts.iter_mut().zip(acc.into_iter()) { + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + if len > 1e-6 { + v.normal = [n[0] / len, n[1] / len, n[2] / len]; + } + } +} diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..de7251749cee722351cecc393d58bee2018fdbc1 --- /dev/null +++ b/crates/engine/src/scene3d/mod.rs @@ -0,0 +1,438 @@ +//! 3D scene graph & `wgpu` rasterizer for Fusion's `Renderer3D`, `Camera3D`, +//! `ImagePlane3D`, `Shape3D` (Sphere, Cylinder, Plane, Cube), `Merge3D`, `Transform3D`, +//! `LightAmbient`, `LightDirectional`, and `MtlCookTorrance` nodes. +//! +//! Matches Fusion's right-handed +Y-up / -Z-forward coordinate system, +//! `Transform3DOp` Euler rotation orders (`XYZ`, `XZY`, etc.), `ScaleLock`, +//! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection. + +mod collect; +mod math; +mod mesh; +mod shader; + +pub use collect::{collect_scene, eval_transform3d}; +pub use math::{ + mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y, + mat4_rot_z, mat4_scale, mat4_translate, +}; + +use crate::cache::CachedTexture; +use mesh::{apply_heightmap_displace, build_shape_mesh}; +use model::NodeId; +use shader::{MeshUniform, SHADER_3D, Vertex3D}; + +pub type Mat4 = [f32; 16]; // Column-major 4x4 + +pub struct Scene3DRenderer { + bgl: wgpu::BindGroupLayout, + pipeline: wgpu::RenderPipeline, + sampler: wgpu::Sampler, +} + +#[derive(Clone)] +pub struct CameraInstance { + pub world: Mat4, + pub vfov_rad: f32, + pub near: f32, + pub far: f32, +} + +#[derive(Clone, Debug)] +pub enum ShapeKind { + ImagePlane, + Sphere { radius: f32, sub_base: u32, sub_height: u32 }, + Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 }, + Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, + Cube { width: f32, height: f32, depth: f32 }, + TextPlate { width: f32, height: f32, depth: f32, slices: u32 }, +} + +#[derive(Clone, Debug)] +pub struct Displace3DSpec { + pub input_node: NodeId, + pub scale: f32, + pub bias: f32, + pub channel: i32, // 0=R, 1=G, 2=B, 3=A, 4=Luma (default) +} + +#[derive(Clone, Debug)] +pub struct DisplaceHeightmap { + pub size: [u32; 2], + pub rgba: Vec, + pub scale: f32, + pub bias: f32, + pub channel: i32, +} + +#[derive(Clone, Debug)] +pub struct Text3DSpec { + pub node_id: NodeId, +} + +#[derive(Clone)] +pub struct MeshInstance { + pub world: Mat4, + pub shape: ShapeKind, + pub material_node: Option, + pub text3d: Option, + pub diffuse_col: [f32; 4], + pub specular_col: [f32; 3], + pub specular_intensity: f32, + pub specular_exponent: f32, + pub affected_by_lights: bool, + pub flip_normals: bool, + pub displace: Option, +} + +#[derive(Clone, Copy, Debug)] +pub struct PointLight { + pub pos: [f32; 3], + pub color: [f32; 3], + pub decay_type: f32, + pub decay_rate: f32, +} + +#[derive(Clone, Copy, Debug)] +pub struct SpotLight { + pub pos: [f32; 3], + pub dir: [f32; 3], + pub color: [f32; 3], + pub cos_inner: f32, + pub cos_outer: f32, + pub decay_type: f32, +} + +#[derive(Clone, Debug)] +pub struct SceneLights { + pub ambient: [f32; 3], + pub dir_to_light: [f32; 3], + pub dir_color: [f32; 3], + pub has_dir: bool, + pub points: Vec, + pub spots: Vec, +} + +impl Default for SceneLights { + fn default() -> Self { + Self { + ambient: [0.0, 0.0, 0.0], + dir_to_light: [0.0, 0.0, 1.0], + dir_color: [0.0, 0.0, 0.0], + has_dir: false, + points: Vec::new(), + spots: Vec::new(), + } + } +} + +pub struct DrawMesh { + pub world: Mat4, + pub shape: ShapeKind, + pub tex: Option, + pub diffuse_col: [f32; 4], + pub specular_col: [f32; 3], + pub specular_intensity: f32, + pub specular_exponent: f32, + pub affected_by_lights: bool, + pub flip_normals: bool, + pub displace: Option, +} + +impl Scene3DRenderer { + pub fn new(device: &wgpu::Device) -> Self { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("scene3d-shader"), + source: wgpu::ShaderSource::Wgsl(SHADER_3D.into()), + }); + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("scene3d-bgl"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("scene3d-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let vbuf_layout = wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &[ + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 }, + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 }, + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 }, + ], + }; + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("scene3d-mesh"), + layout: Some(&pl), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_mesh"), + compilation_options: Default::default(), + buffers: &[Some(vbuf_layout)], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_mesh"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("scene3d-linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Linear, + ..Default::default() + }); + Self { bgl, pipeline, sampler } + } + + #[allow(clippy::too_many_arguments)] + pub fn render_meshes( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + dst: &CachedTexture, + dummy: &CachedTexture, + view_proj: Mat4, + view: Mat4, + cam_pos: [f32; 3], + lights: SceneLights, + lighting_enabled: bool, + meshes: &[DrawMesh], + ) { + let depth_tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("scene3d-depth"), + size: wgpu::Extent3d { + width: dst.size[0].max(1), + height: dst.size[1].max(1), + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth32Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default()); + + // Sort back-to-front in camera view space so semi-transparent planes blend cleanly. + let mut order: Vec<(usize, f32)> = meshes + .iter() + .enumerate() + .map(|(i, m)| { + let wx = m.world[12]; + let wy = m.world[13]; + let wz = m.world[14]; + let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14]; + (i, vz) + }) + .collect(); + order.sort_by(|a, b| a.1.total_cmp(&b.1)); + + struct GpuDraw { + bg: wgpu::BindGroup, + vbuf: wgpu::Buffer, + ibuf: wgpu::Buffer, + idx_count: u32, + } + let mut draw_items = Vec::with_capacity(order.len()); + for (idx, _) in order { + let m = &meshes[idx]; + let aspect = m + .tex + .as_ref() + .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) + .unwrap_or(16.0 / 9.0); + let (mut verts, indices) = build_shape_mesh(&m.shape, aspect); + if indices.is_empty() { + continue; + } + if let Some(disp) = &m.displace { + apply_heightmap_displace(&mut verts, &indices, disp); + } + let vbytes = bytemuck::cast_slice(&verts); + let ibytes = bytemuck::cast_slice(&indices); + let vbuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-vb"), + size: vbytes.len() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&vbuf, 0, vbytes); + let ibuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-ib"), + size: ibytes.len() as u64, + usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ibuf, 0, ibytes); + + let mvp = mat4_mul(view_proj, m.world); + let dod = if let Some(t) = &m.tex { + if t.has_dod() { + [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32] + } else { + [0.0; 4] + } + } else { + [0.0; 4] + }; + let mut point_pos = [[0.0_f32; 4]; 4]; + let mut point_col = [[0.0_f32; 4]; 4]; + let n_pt = lights.points.len().min(4); + for (pi, pl) in lights.points.iter().take(4).enumerate() { + point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type]; + point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], pl.decay_rate]; + } + let mut spot_pos = [[0.0_f32; 4]; 4]; + let mut spot_dir = [[0.0_f32; 4]; 4]; + let mut spot_col = [[0.0_f32; 4]; 4]; + let n_sp = lights.spots.len().min(4); + for (si, sl) in lights.spots.iter().take(4).enumerate() { + spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner]; + spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer]; + spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type]; + } + let uni = MeshUniform { + mvp, + model: m.world, + dod, + flags: [ + if m.tex.is_some() { 1.0 } else { 0.0 }, + if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 }, + m.specular_intensity, + if m.flip_normals { 1.0 } else { 0.0 }, + ], + diffuse_col: m.diffuse_col, + specular_col: [ + m.specular_col[0], + m.specular_col[1], + m.specular_col[2], + m.specular_exponent, + ], + ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0], + dir_to_light: [ + lights.dir_to_light[0], + lights.dir_to_light[1], + lights.dir_to_light[2], + if lights.has_dir { 1.0 } else { 0.0 }, + ], + dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0], + cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], + light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0], + point_pos, + point_col, + spot_pos, + spot_dir, + spot_col, + }; + let ubuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-u"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uni)); + let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("scene3d-bg"), + layout: &self.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + ], + }); + draw_items.push(GpuDraw { + bg, + vbuf, + ibuf, + idx_count: indices.len() as u32, + }); + } + + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("scene3d-pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &dst.view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.pipeline); + for d in &draw_items { + pass.set_bind_group(0, &d.bg, &[]); + pass.set_vertex_buffer(0, d.vbuf.slice(..)); + pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..d.idx_count, 0, 0..1); + } + } +} diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs new file mode 100644 index 0000000000000000000000000000000000000000..72916a9d5d8af626ca05ff1d11b45b148ce73ca5 --- /dev/null +++ b/crates/engine/src/scene3d/shader.rs @@ -0,0 +1,201 @@ +//! 3D WGSL shader source and GPU vertex/uniform buffer layouts. + +use bytemuck::{Pod, Zeroable}; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct Vertex3D { + pub(super) pos: [f32; 3], + pub(super) normal: [f32; 3], + pub(super) uv: [f32; 2], +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct MeshUniform { + pub(super) mvp: [f32; 16], + pub(super) model: [f32; 16], + /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture) + pub(super) dod: [f32; 4], + /// `[use_tex, lighting_enabled, specular_intensity, flip_normals]` + pub(super) flags: [f32; 4], + /// Diffuse color multiplier `(r, g, b, a)` + pub(super) diffuse_col: [f32; 4], + /// Specular color `(r, g, b, shininess_exponent)` + pub(super) specular_col: [f32; 4], + /// Ambient light `(r, g, b, 0)` + pub(super) ambient: [f32; 4], + /// Directional light direction TO light `(dx, dy, dz, has_dir)` + pub(super) dir_to_light: [f32; 4], + /// Directional light color * intensity `(r, g, b, 0)` + pub(super) dir_color: [f32; 4], + /// Camera world position `(cx, cy, cz, 0)` + pub(super) cam_pos: [f32; 4], + /// `[num_point_lights, num_spot_lights, 0, 0]` + pub(super) light_counts: [f32; 4], + /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` + pub(super) point_pos: [[f32; 4]; 4], + /// Point light colors * intensity `(r, g, b, decay_rate)` + pub(super) point_col: [[f32; 4]; 4], + /// Spot light positions `(x, y, z, cos_inner)` + pub(super) spot_pos: [[f32; 4]; 4], + /// Spot light forward directions `(dx, dy, dz, cos_outer)` + pub(super) spot_dir: [[f32; 4]; 4], + /// Spot light colors * intensity `(r, g, b, decay_type)` + pub(super) spot_col: [[f32; 4]; 4], +} + +pub(super) const SHADER_3D: &str = r#" +struct MeshUniform { + mvp: mat4x4, + model: mat4x4, + dod: vec4, + flags: vec4, + diffuse_col: vec4, + specular_col: vec4, + ambient: vec4, + dir_to_light: vec4, + dir_color: vec4, + cam_pos: vec4, + light_counts: vec4, + point_pos: array, 4>, + point_col: array, 4>, + spot_pos: array, 4>, + spot_dir: array, 4>, + spot_col: array, 4>, +}; + +@group(0) @binding(0) var u: MeshUniform; +@group(0) @binding(1) var mat_tex: texture_2d; +@group(0) @binding(2) var mat_samp: sampler; + +struct VsIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, +}; + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) world_pos: vec3, + @location(2) world_n: vec3, +}; + +@vertex +fn vs_mesh(v: VsIn) -> VsOut { + var out: VsOut; + let wp = u.model * vec4(v.pos, 1.0); + out.clip = u.mvp * vec4(v.pos, 1.0); + out.uv = v.uv; + out.world_pos = wp.xyz; + let wn = (u.model * vec4(v.normal, 0.0)).xyz; + let nlen = length(wn); + var n_norm = select(vec3(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); + if (u.flags.w > 0.5) { + n_norm = -n_norm; + } + out.world_n = n_norm; + return out; +} + +fn light_attenuation(dist: f32, decay_type: f32, decay_rate: f32) -> f32 { + let dt = i32(decay_type + 0.5); + let rate = max(decay_rate, 0.001); + if (dt == 1) { + return 1.0 / max(1.0 + dist * rate, 1e-4); + } else if (dt == 2) { + let d = dist * rate; + return 1.0 / max(1.0 + d * d, 1e-4); + } + return 1.0; +} + +fn eval_light_contrib( + n: vec3, + v: vec3, + l: vec3, + light_rgb: vec3, + albedo: vec3, + spec_rgb: vec3, + spec_int: f32, + shininess: f32, +) -> vec3 { + let ndotl = max(dot(n, l), 0.0); + if (ndotl <= 0.0) { + return vec3(0.0); + } + var out = albedo * light_rgb * ndotl; + if (spec_int > 1e-4) { + let h = normalize(l + v); + let spec = pow(max(dot(n, h), 0.0), shininess) * spec_int; + out = out + light_rgb * spec_rgb * spec; + } + return out; +} + +@fragment +fn fs_mesh(in: VsOut) -> @location(0) vec4 { + var col = u.diffuse_col; + if (u.flags.x > 0.5) { + var uv = in.uv; + if (u.dod.z > 0.5 && u.dod.w > 0.5) { + let tdims = vec2(textureDimensions(mat_tex)); + let canvas_px = vec2(uv.x * u.dod.z, uv.y * u.dod.w); + uv = (canvas_px - u.dod.xy) / tdims; + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { + discard; + } + } + col = textureSample(mat_tex, mat_samp, uv) * u.diffuse_col; + } + if (col.a <= 0.002) { + discard; + } + + if (u.flags.y > 0.5) { + // Premultiplied -> unpremultiplied albedo for lighting + let albedo = select(vec3(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5); + let n = normalize(in.world_n); + let v = normalize(u.cam_pos.xyz - in.world_pos); + let spec_rgb = u.specular_col.rgb; + let shininess = max(u.specular_col.w, 1.0); + let spec_int = u.flags.z; + + var lit = albedo * u.ambient.rgb; + if (u.dir_to_light.w > 0.5) { + let l = normalize(u.dir_to_light.xyz); + lit = lit + eval_light_contrib(n, v, l, u.dir_color.rgb, albedo, spec_rgb, spec_int, shininess); + } + + let n_pt = i32(u.light_counts.x + 0.5); + for (var i: i32 = 0; i < 4; i = i + 1) { + if (i >= n_pt) { break; } + let to_l = u.point_pos[i].xyz - in.world_pos; + let dist = max(length(to_l), 1e-4); + let att = light_attenuation(dist, u.point_pos[i].w, u.point_col[i].w); + lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); + } + + let n_sp = i32(u.light_counts.y + 0.5); + for (var i: i32 = 0; i < 4; i = i + 1) { + if (i >= n_sp) { break; } + let to_l = u.spot_pos[i].xyz - in.world_pos; + let dist = max(length(to_l), 1e-4); + let l_dir = to_l / dist; + // spot_dir.xyz is direction spotlight points; fragment direction from light is -l_dir + let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz)); + let cos_inner = u.spot_pos[i].w; + let cos_outer = u.spot_dir[i].w; + let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); + if (cone > 0.0) { + let att = light_attenuation(dist, u.spot_col[i].w, 1.0) * cone; + lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); + } + } + + col = vec4(clamp(lit, vec3(0.0), vec3(1.0)) * col.a, col.a); + } + return col; +} +"#; diff --git a/scripts/gen_compatibility.py b/scripts/gen_compatibility.py index 87b76b6ea0208a94b33da43f88c26b3d7c2b9a5e..55bff7a58366be03bbe300274237f7b0bff4b484 100755 --- a/scripts/gen_compatibility.py +++ b/scripts/gen_compatibility.py @@ -17,7 +17,7 @@ from typing import Dict, List, Optional, Sequence, Set, Tuple REPO_ROOT = Path(__file__).resolve().parent.parent EVAL_RS = REPO_ROOT / "crates" / "engine" / "src" / "eval" / "mod.rs" -SCENE3D_RS = REPO_ROOT / "crates" / "engine" / "src" / "scene3d.rs" +SCENE3D_RS = REPO_ROOT / "crates" / "engine" / "src" / "scene3d" / "collect.rs" COMP_RS = REPO_ROOT / "crates" / "model" / "src" / "comp.rs" PROBES_PY = REPO_ROOT / "scripts" / "fusion_probes.py" DEFAULT_OUTPUT = REPO_ROOT / "compatibility.md"