| author | |
| committer | |
| log | a229beeb6bba6ba0d0daf711e287bf2b7052b21c |
| tree | d58fb3aab4c0effcd7600e79824958301664bd50 |
| parent | f4024c0b020e151157095e4d47ec0f031bbced3b |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
7 files changed, 1683 insertions(+), 1619 deletions(-)
crates/engine/src/scene3d.rs deleted-1618| ... | @@ -1,1618 +0,0 @@ | ||
| 1 | //! 3D scene graph & `wgpu` rasterizer for Fusion's `Renderer3D`, `Camera3D`, | ||
| 2 | //! `ImagePlane3D`, `Shape3D` (Sphere, Cylinder, Plane, Cube), `Merge3D`, `Transform3D`, | ||
| 3 | //! `LightAmbient`, `LightDirectional`, and `MtlCookTorrance` nodes. | ||
| 4 | //! | ||
| 5 | //! Matches Fusion's right-handed +Y-up / -Z-forward coordinate system, | ||
| 6 | //! `Transform3DOp` Euler rotation orders (`XYZ`, `XZY`, etc.), `ScaleLock`, | ||
| 7 | //! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection. | ||
| 8 | |||
| 9 | use crate::cache::CachedTexture; | ||
| 10 | use bytemuck::{Pod, Zeroable}; | ||
| 11 | use model::{Comp, ExprEngine, Node, NodeId}; | ||
| 12 | |||
| 13 | pub type Mat4 = [f32; 16]; // Column-major 4x4 | ||
| 14 | |||
| 15 | #[repr(C)] | ||
| 16 | #[derive(Clone, Copy, Pod, Zeroable)] | ||
| 17 | struct Vertex3D { | ||
| 18 | pos: [f32; 3], | ||
| 19 | normal: [f32; 3], | ||
| 20 | uv: [f32; 2], | ||
| 21 | } | ||
| 22 | |||
| 23 | #[repr(C)] | ||
| 24 | #[derive(Clone, Copy, Pod, Zeroable)] | ||
| 25 | struct MeshUniform { | ||
| 26 | mvp: [f32; 16], | ||
| 27 | model: [f32; 16], | ||
| 28 | /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture) | ||
| 29 | dod: [f32; 4], | ||
| 30 | /// `[use_tex, lighting_enabled, specular_intensity, flip_normals]` | ||
| 31 | flags: [f32; 4], | ||
| 32 | /// Diffuse color multiplier `(r, g, b, a)` | ||
| 33 | diffuse_col: [f32; 4], | ||
| 34 | /// Specular color `(r, g, b, shininess_exponent)` | ||
| 35 | specular_col: [f32; 4], | ||
| 36 | /// Ambient light `(r, g, b, 0)` | ||
| 37 | ambient: [f32; 4], | ||
| 38 | /// Directional light direction TO light `(dx, dy, dz, has_dir)` | ||
| 39 | dir_to_light: [f32; 4], | ||
| 40 | /// Directional light color * intensity `(r, g, b, 0)` | ||
| 41 | dir_color: [f32; 4], | ||
| 42 | /// Camera world position `(cx, cy, cz, 0)` | ||
| 43 | cam_pos: [f32; 4], | ||
| 44 | /// `[num_point_lights, num_spot_lights, 0, 0]` | ||
| 45 | light_counts: [f32; 4], | ||
| 46 | /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` | ||
| 47 | point_pos: [[f32; 4]; 4], | ||
| 48 | /// Point light colors * intensity `(r, g, b, decay_rate)` | ||
| 49 | point_col: [[f32; 4]; 4], | ||
| 50 | /// Spot light positions `(x, y, z, cos_inner)` | ||
| 51 | spot_pos: [[f32; 4]; 4], | ||
| 52 | /// Spot light forward directions `(dx, dy, dz, cos_outer)` | ||
| 53 | spot_dir: [[f32; 4]; 4], | ||
| 54 | /// Spot light colors * intensity `(r, g, b, decay_type)` | ||
| 55 | spot_col: [[f32; 4]; 4], | ||
| 56 | } | ||
| 57 | |||
| 58 | const SHADER_3D: &str = r#" | ||
| 59 | struct MeshUniform { | ||
| 60 | mvp: mat4x4<f32>, | ||
| 61 | model: mat4x4<f32>, | ||
| 62 | dod: vec4<f32>, | ||
| 63 | flags: vec4<f32>, | ||
| 64 | diffuse_col: vec4<f32>, | ||
| 65 | specular_col: vec4<f32>, | ||
| 66 | ambient: vec4<f32>, | ||
| 67 | dir_to_light: vec4<f32>, | ||
| 68 | dir_color: vec4<f32>, | ||
| 69 | cam_pos: vec4<f32>, | ||
| 70 | light_counts: vec4<f32>, | ||
| 71 | point_pos: array<vec4<f32>, 4>, | ||
| 72 | point_col: array<vec4<f32>, 4>, | ||
| 73 | spot_pos: array<vec4<f32>, 4>, | ||
| 74 | spot_dir: array<vec4<f32>, 4>, | ||
| 75 | spot_col: array<vec4<f32>, 4>, | ||
| 76 | }; | ||
| 77 | |||
| 78 | @group(0) @binding(0) var<uniform> u: MeshUniform; | ||
| 79 | @group(0) @binding(1) var mat_tex: texture_2d<f32>; | ||
| 80 | @group(0) @binding(2) var mat_samp: sampler; | ||
| 81 | |||
| 82 | struct VsIn { | ||
| 83 | @location(0) pos: vec3<f32>, | ||
| 84 | @location(1) normal: vec3<f32>, | ||
| 85 | @location(2) uv: vec2<f32>, | ||
| 86 | }; | ||
| 87 | |||
| 88 | struct VsOut { | ||
| 89 | @builtin(position) clip: vec4<f32>, | ||
| 90 | @location(0) uv: vec2<f32>, | ||
| 91 | @location(1) world_pos: vec3<f32>, | ||
| 92 | @location(2) world_n: vec3<f32>, | ||
| 93 | }; | ||
| 94 | |||
| 95 | @vertex | ||
| 96 | fn vs_mesh(v: VsIn) -> VsOut { | ||
| 97 | var out: VsOut; | ||
| 98 | let wp = u.model * vec4<f32>(v.pos, 1.0); | ||
| 99 | out.clip = u.mvp * vec4<f32>(v.pos, 1.0); | ||
| 100 | out.uv = v.uv; | ||
| 101 | out.world_pos = wp.xyz; | ||
| 102 | let wn = (u.model * vec4<f32>(v.normal, 0.0)).xyz; | ||
| 103 | let nlen = length(wn); | ||
| 104 | var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); | ||
| 105 | if (u.flags.w > 0.5) { | ||
| 106 | n_norm = -n_norm; | ||
| 107 | } | ||
| 108 | out.world_n = n_norm; | ||
| 109 | return out; | ||
| 110 | } | ||
| 111 | |||
| 112 | fn light_attenuation(dist: f32, decay_type: f32, decay_rate: f32) -> f32 { | ||
| 113 | let dt = i32(decay_type + 0.5); | ||
| 114 | let rate = max(decay_rate, 0.001); | ||
| 115 | if (dt == 1) { | ||
| 116 | return 1.0 / max(1.0 + dist * rate, 1e-4); | ||
| 117 | } else if (dt == 2) { | ||
| 118 | let d = dist * rate; | ||
| 119 | return 1.0 / max(1.0 + d * d, 1e-4); | ||
| 120 | } | ||
| 121 | return 1.0; | ||
| 122 | } | ||
| 123 | |||
| 124 | fn eval_light_contrib( | ||
| 125 | n: vec3<f32>, | ||
| 126 | v: vec3<f32>, | ||
| 127 | l: vec3<f32>, | ||
| 128 | light_rgb: vec3<f32>, | ||
| 129 | albedo: vec3<f32>, | ||
| 130 | spec_rgb: vec3<f32>, | ||
| 131 | spec_int: f32, | ||
| 132 | shininess: f32, | ||
| 133 | ) -> vec3<f32> { | ||
| 134 | let ndotl = max(dot(n, l), 0.0); | ||
| 135 | if (ndotl <= 0.0) { | ||
| 136 | return vec3<f32>(0.0); | ||
| 137 | } | ||
| 138 | var out = albedo * light_rgb * ndotl; | ||
| 139 | if (spec_int > 1e-4) { | ||
| 140 | let h = normalize(l + v); | ||
| 141 | let spec = pow(max(dot(n, h), 0.0), shininess) * spec_int; | ||
| 142 | out = out + light_rgb * spec_rgb * spec; | ||
| 143 | } | ||
| 144 | return out; | ||
| 145 | } | ||
| 146 | |||
| 147 | @fragment | ||
| 148 | fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> { | ||
| 149 | var col = u.diffuse_col; | ||
| 150 | if (u.flags.x > 0.5) { | ||
| 151 | var uv = in.uv; | ||
| 152 | if (u.dod.z > 0.5 && u.dod.w > 0.5) { | ||
| 153 | let tdims = vec2<f32>(textureDimensions(mat_tex)); | ||
| 154 | let canvas_px = vec2<f32>(uv.x * u.dod.z, uv.y * u.dod.w); | ||
| 155 | uv = (canvas_px - u.dod.xy) / tdims; | ||
| 156 | if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { | ||
| 157 | discard; | ||
| 158 | } | ||
| 159 | } | ||
| 160 | col = textureSample(mat_tex, mat_samp, uv) * u.diffuse_col; | ||
| 161 | } | ||
| 162 | if (col.a <= 0.002) { | ||
| 163 | discard; | ||
| 164 | } | ||
| 165 | |||
| 166 | if (u.flags.y > 0.5) { | ||
| 167 | // Premultiplied -> unpremultiplied albedo for lighting | ||
| 168 | let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5); | ||
| 169 | let n = normalize(in.world_n); | ||
| 170 | let v = normalize(u.cam_pos.xyz - in.world_pos); | ||
| 171 | let spec_rgb = u.specular_col.rgb; | ||
| 172 | let shininess = max(u.specular_col.w, 1.0); | ||
| 173 | let spec_int = u.flags.z; | ||
| 174 | |||
| 175 | var lit = albedo * u.ambient.rgb; | ||
| 176 | if (u.dir_to_light.w > 0.5) { | ||
| 177 | let l = normalize(u.dir_to_light.xyz); | ||
| 178 | lit = lit + eval_light_contrib(n, v, l, u.dir_color.rgb, albedo, spec_rgb, spec_int, shininess); | ||
| 179 | } | ||
| 180 | |||
| 181 | let n_pt = i32(u.light_counts.x + 0.5); | ||
| 182 | for (var i: i32 = 0; i < 4; i = i + 1) { | ||
| 183 | if (i >= n_pt) { break; } | ||
| 184 | let to_l = u.point_pos[i].xyz - in.world_pos; | ||
| 185 | let dist = max(length(to_l), 1e-4); | ||
| 186 | let att = light_attenuation(dist, u.point_pos[i].w, u.point_col[i].w); | ||
| 187 | lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); | ||
| 188 | } | ||
| 189 | |||
| 190 | let n_sp = i32(u.light_counts.y + 0.5); | ||
| 191 | for (var i: i32 = 0; i < 4; i = i + 1) { | ||
| 192 | if (i >= n_sp) { break; } | ||
| 193 | let to_l = u.spot_pos[i].xyz - in.world_pos; | ||
| 194 | let dist = max(length(to_l), 1e-4); | ||
| 195 | let l_dir = to_l / dist; | ||
| 196 | // spot_dir.xyz is direction spotlight points; fragment direction from light is -l_dir | ||
| 197 | let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz)); | ||
| 198 | let cos_inner = u.spot_pos[i].w; | ||
| 199 | let cos_outer = u.spot_dir[i].w; | ||
| 200 | let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); | ||
| 201 | if (cone > 0.0) { | ||
| 202 | let att = light_attenuation(dist, u.spot_col[i].w, 1.0) * cone; | ||
| 203 | lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); | ||
| 204 | } | ||
| 205 | } | ||
| 206 | |||
| 207 | col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a); | ||
| 208 | } | ||
| 209 | return col; | ||
| 210 | } | ||
| 211 | "#; | ||
| 212 | |||
| 213 | pub struct Scene3DRenderer { | ||
| 214 | bgl: wgpu::BindGroupLayout, | ||
| 215 | pipeline: wgpu::RenderPipeline, | ||
| 216 | sampler: wgpu::Sampler, | ||
| 217 | } | ||
| 218 | |||
| 219 | #[derive(Clone)] | ||
| 220 | pub struct CameraInstance { | ||
| 221 | pub world: Mat4, | ||
| 222 | pub vfov_rad: f32, | ||
| 223 | pub near: f32, | ||
| 224 | pub far: f32, | ||
| 225 | } | ||
| 226 | |||
| 227 | #[derive(Clone, Debug)] | ||
| 228 | pub enum ShapeKind { | ||
| 229 | ImagePlane, | ||
| 230 | Sphere { radius: f32, sub_base: u32, sub_height: u32 }, | ||
| 231 | Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 }, | ||
| 232 | Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, | ||
| 233 | Cube { width: f32, height: f32, depth: f32 }, | ||
| 234 | TextPlate { width: f32, height: f32, depth: f32, slices: u32 }, | ||
| 235 | } | ||
| 236 | |||
| 237 | #[derive(Clone, Debug)] | ||
| 238 | pub struct Displace3DSpec { | ||
| 239 | pub input_node: NodeId, | ||
| 240 | pub scale: f32, | ||
| 241 | pub bias: f32, | ||
| 242 | pub channel: i32, // 0=R, 1=G, 2=B, 3=A, 4=Luma (default) | ||
| 243 | } | ||
| 244 | |||
| 245 | #[derive(Clone, Debug)] | ||
| 246 | pub struct DisplaceHeightmap { | ||
| 247 | pub size: [u32; 2], | ||
| 248 | pub rgba: Vec<u8>, | ||
| 249 | pub scale: f32, | ||
| 250 | pub bias: f32, | ||
| 251 | pub channel: i32, | ||
| 252 | } | ||
| 253 | |||
| 254 | #[derive(Clone, Debug)] | ||
| 255 | pub struct Text3DSpec { | ||
| 256 | pub node_id: NodeId, | ||
| 257 | } | ||
| 258 | |||
| 259 | #[derive(Clone)] | ||
| 260 | pub struct MeshInstance { | ||
| 261 | pub world: Mat4, | ||
| 262 | pub shape: ShapeKind, | ||
| 263 | pub material_node: Option<NodeId>, | ||
| 264 | pub text3d: Option<Text3DSpec>, | ||
| 265 | pub diffuse_col: [f32; 4], | ||
| 266 | pub specular_col: [f32; 3], | ||
| 267 | pub specular_intensity: f32, | ||
| 268 | pub specular_exponent: f32, | ||
| 269 | pub affected_by_lights: bool, | ||
| 270 | pub flip_normals: bool, | ||
| 271 | pub displace: Option<Displace3DSpec>, | ||
| 272 | } | ||
| 273 | |||
| 274 | #[derive(Clone, Copy, Debug)] | ||
| 275 | pub struct PointLight { | ||
| 276 | pub pos: [f32; 3], | ||
| 277 | pub color: [f32; 3], | ||
| 278 | pub decay_type: f32, | ||
| 279 | pub decay_rate: f32, | ||
| 280 | } | ||
| 281 | |||
| 282 | #[derive(Clone, Copy, Debug)] | ||
| 283 | pub struct SpotLight { | ||
| 284 | pub pos: [f32; 3], | ||
| 285 | pub dir: [f32; 3], | ||
| 286 | pub color: [f32; 3], | ||
| 287 | pub cos_inner: f32, | ||
| 288 | pub cos_outer: f32, | ||
| 289 | pub decay_type: f32, | ||
| 290 | } | ||
| 291 | |||
| 292 | #[derive(Clone, Debug)] | ||
| 293 | pub struct SceneLights { | ||
| 294 | pub ambient: [f32; 3], | ||
| 295 | pub dir_to_light: [f32; 3], | ||
| 296 | pub dir_color: [f32; 3], | ||
| 297 | pub has_dir: bool, | ||
| 298 | pub points: Vec<PointLight>, | ||
| 299 | pub spots: Vec<SpotLight>, | ||
| 300 | } | ||
| 301 | |||
| 302 | impl Default for SceneLights { | ||
| 303 | fn default() -> Self { | ||
| 304 | Self { | ||
| 305 | ambient: [0.0, 0.0, 0.0], | ||
| 306 | dir_to_light: [0.0, 0.0, 1.0], | ||
| 307 | dir_color: [0.0, 0.0, 0.0], | ||
| 308 | has_dir: false, | ||
| 309 | points: Vec::new(), | ||
| 310 | spots: Vec::new(), | ||
| 311 | } | ||
| 312 | } | ||
| 313 | } | ||
| 314 | |||
| 315 | pub struct DrawMesh { | ||
| 316 | pub world: Mat4, | ||
| 317 | pub shape: ShapeKind, | ||
| 318 | pub tex: Option<CachedTexture>, | ||
| 319 | pub diffuse_col: [f32; 4], | ||
| 320 | pub specular_col: [f32; 3], | ||
| 321 | pub specular_intensity: f32, | ||
| 322 | pub specular_exponent: f32, | ||
| 323 | pub affected_by_lights: bool, | ||
| 324 | pub flip_normals: bool, | ||
| 325 | pub displace: Option<DisplaceHeightmap>, | ||
| 326 | } | ||
| 327 | |||
| 328 | impl Scene3DRenderer { | ||
| 329 | pub fn new(device: &wgpu::Device) -> Self { | ||
| 330 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { | ||
| 331 | label: Some("scene3d-shader"), | ||
| 332 | source: wgpu::ShaderSource::Wgsl(SHADER_3D.into()), | ||
| 333 | }); | ||
| 334 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | ||
| 335 | label: Some("scene3d-bgl"), | ||
| 336 | entries: &[ | ||
| 337 | wgpu::BindGroupLayoutEntry { | ||
| 338 | binding: 0, | ||
| 339 | visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, | ||
| 340 | ty: wgpu::BindingType::Buffer { | ||
| 341 | ty: wgpu::BufferBindingType::Uniform, | ||
| 342 | has_dynamic_offset: false, | ||
| 343 | min_binding_size: None, | ||
| 344 | }, | ||
| 345 | count: None, | ||
| 346 | }, | ||
| 347 | wgpu::BindGroupLayoutEntry { | ||
| 348 | binding: 1, | ||
| 349 | visibility: wgpu::ShaderStages::FRAGMENT, | ||
| 350 | ty: wgpu::BindingType::Texture { | ||
| 351 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, | ||
| 352 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 353 | multisampled: false, | ||
| 354 | }, | ||
| 355 | count: None, | ||
| 356 | }, | ||
| 357 | wgpu::BindGroupLayoutEntry { | ||
| 358 | binding: 2, | ||
| 359 | visibility: wgpu::ShaderStages::FRAGMENT, | ||
| 360 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), | ||
| 361 | count: None, | ||
| 362 | }, | ||
| 363 | ], | ||
| 364 | }); | ||
| 365 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | ||
| 366 | label: Some("scene3d-pl"), | ||
| 367 | bind_group_layouts: &[Some(&bgl)], | ||
| 368 | immediate_size: 0, | ||
| 369 | }); | ||
| 370 | let vbuf_layout = wgpu::VertexBufferLayout { | ||
| 371 | array_stride: std::mem::size_of::<Vertex3D>() as u64, | ||
| 372 | step_mode: wgpu::VertexStepMode::Vertex, | ||
| 373 | attributes: &[ | ||
| 374 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 }, | ||
| 375 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 }, | ||
| 376 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 }, | ||
| 377 | ], | ||
| 378 | }; | ||
| 379 | let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { | ||
| 380 | label: Some("scene3d-mesh"), | ||
| 381 | layout: Some(&pl), | ||
| 382 | vertex: wgpu::VertexState { | ||
| 383 | module: &shader, | ||
| 384 | entry_point: Some("vs_mesh"), | ||
| 385 | compilation_options: Default::default(), | ||
| 386 | buffers: &[Some(vbuf_layout)], | ||
| 387 | }, | ||
| 388 | fragment: Some(wgpu::FragmentState { | ||
| 389 | module: &shader, | ||
| 390 | entry_point: Some("fs_mesh"), | ||
| 391 | compilation_options: Default::default(), | ||
| 392 | targets: &[Some(wgpu::ColorTargetState { | ||
| 393 | format: wgpu::TextureFormat::Rgba8Unorm, | ||
| 394 | blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), | ||
| 395 | write_mask: wgpu::ColorWrites::ALL, | ||
| 396 | })], | ||
| 397 | }), | ||
| 398 | primitive: wgpu::PrimitiveState { | ||
| 399 | topology: wgpu::PrimitiveTopology::TriangleList, | ||
| 400 | cull_mode: None, | ||
| 401 | ..Default::default() | ||
| 402 | }, | ||
| 403 | depth_stencil: Some(wgpu::DepthStencilState { | ||
| 404 | format: wgpu::TextureFormat::Depth32Float, | ||
| 405 | depth_write_enabled: Some(true), | ||
| 406 | depth_compare: Some(wgpu::CompareFunction::LessEqual), | ||
| 407 | stencil: wgpu::StencilState::default(), | ||
| 408 | bias: wgpu::DepthBiasState::default(), | ||
| 409 | }), | ||
| 410 | multisample: wgpu::MultisampleState::default(), | ||
| 411 | multiview_mask: None, | ||
| 412 | cache: None, | ||
| 413 | }); | ||
| 414 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { | ||
| 415 | label: Some("scene3d-linear"), | ||
| 416 | address_mode_u: wgpu::AddressMode::ClampToEdge, | ||
| 417 | address_mode_v: wgpu::AddressMode::ClampToEdge, | ||
| 418 | mag_filter: wgpu::FilterMode::Linear, | ||
| 419 | min_filter: wgpu::FilterMode::Linear, | ||
| 420 | mipmap_filter: wgpu::MipmapFilterMode::Linear, | ||
| 421 | ..Default::default() | ||
| 422 | }); | ||
| 423 | Self { bgl, pipeline, sampler } | ||
| 424 | } | ||
| 425 | |||
| 426 | #[allow(clippy::too_many_arguments)] | ||
| 427 | pub fn render_meshes( | ||
| 428 | &self, | ||
| 429 | device: &wgpu::Device, | ||
| 430 | queue: &wgpu::Queue, | ||
| 431 | enc: &mut wgpu::CommandEncoder, | ||
| 432 | dst: &CachedTexture, | ||
| 433 | dummy: &CachedTexture, | ||
| 434 | view_proj: Mat4, | ||
| 435 | view: Mat4, | ||
| 436 | cam_pos: [f32; 3], | ||
| 437 | lights: SceneLights, | ||
| 438 | lighting_enabled: bool, | ||
| 439 | meshes: &[DrawMesh], | ||
| 440 | ) { | ||
| 441 | let depth_tex = device.create_texture(&wgpu::TextureDescriptor { | ||
| 442 | label: Some("scene3d-depth"), | ||
| 443 | size: wgpu::Extent3d { | ||
| 444 | width: dst.size[0].max(1), | ||
| 445 | height: dst.size[1].max(1), | ||
| 446 | depth_or_array_layers: 1, | ||
| 447 | }, | ||
| 448 | mip_level_count: 1, | ||
| 449 | sample_count: 1, | ||
| 450 | dimension: wgpu::TextureDimension::D2, | ||
| 451 | format: wgpu::TextureFormat::Depth32Float, | ||
| 452 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT, | ||
| 453 | view_formats: &[], | ||
| 454 | }); | ||
| 455 | let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default()); | ||
| 456 | |||
| 457 | // Sort back-to-front in camera view space so semi-transparent planes blend cleanly. | ||
| 458 | let mut order: Vec<(usize, f32)> = meshes | ||
| 459 | .iter() | ||
| 460 | .enumerate() | ||
| 461 | .map(|(i, m)| { | ||
| 462 | let wx = m.world[12]; | ||
| 463 | let wy = m.world[13]; | ||
| 464 | let wz = m.world[14]; | ||
| 465 | let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14]; | ||
| 466 | (i, vz) | ||
| 467 | }) | ||
| 468 | .collect(); | ||
| 469 | order.sort_by(|a, b| a.1.total_cmp(&b.1)); | ||
| 470 | |||
| 471 | struct GpuDraw { | ||
| 472 | bg: wgpu::BindGroup, | ||
| 473 | vbuf: wgpu::Buffer, | ||
| 474 | ibuf: wgpu::Buffer, | ||
| 475 | idx_count: u32, | ||
| 476 | } | ||
| 477 | let mut draw_items = Vec::with_capacity(order.len()); | ||
| 478 | for (idx, _) in order { | ||
| 479 | let m = &meshes[idx]; | ||
| 480 | let aspect = m | ||
| 481 | .tex | ||
| 482 | .as_ref() | ||
| 483 | .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) | ||
| 484 | .unwrap_or(16.0 / 9.0); | ||
| 485 | let (mut verts, indices) = build_shape_mesh(&m.shape, aspect); | ||
| 486 | if indices.is_empty() { | ||
| 487 | continue; | ||
| 488 | } | ||
| 489 | if let Some(disp) = &m.displace { | ||
| 490 | apply_heightmap_displace(&mut verts, &indices, disp); | ||
| 491 | } | ||
| 492 | let vbytes = bytemuck::cast_slice(&verts); | ||
| 493 | let ibytes = bytemuck::cast_slice(&indices); | ||
| 494 | let vbuf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 495 | label: Some("scene3d-vb"), | ||
| 496 | size: vbytes.len() as u64, | ||
| 497 | usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, | ||
| 498 | mapped_at_creation: false, | ||
| 499 | }); | ||
| 500 | queue.write_buffer(&vbuf, 0, vbytes); | ||
| 501 | let ibuf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 502 | label: Some("scene3d-ib"), | ||
| 503 | size: ibytes.len() as u64, | ||
| 504 | usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, | ||
| 505 | mapped_at_creation: false, | ||
| 506 | }); | ||
| 507 | queue.write_buffer(&ibuf, 0, ibytes); | ||
| 508 | |||
| 509 | let mvp = mat4_mul(view_proj, m.world); | ||
| 510 | let dod = if let Some(t) = &m.tex { | ||
| 511 | if t.has_dod() { | ||
| 512 | [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32] | ||
| 513 | } else { | ||
| 514 | [0.0; 4] | ||
| 515 | } | ||
| 516 | } else { | ||
| 517 | [0.0; 4] | ||
| 518 | }; | ||
| 519 | let mut point_pos = [[0.0_f32; 4]; 4]; | ||
| 520 | let mut point_col = [[0.0_f32; 4]; 4]; | ||
| 521 | let n_pt = lights.points.len().min(4); | ||
| 522 | for (pi, pl) in lights.points.iter().take(4).enumerate() { | ||
| 523 | point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type]; | ||
| 524 | point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], pl.decay_rate]; | ||
| 525 | } | ||
| 526 | let mut spot_pos = [[0.0_f32; 4]; 4]; | ||
| 527 | let mut spot_dir = [[0.0_f32; 4]; 4]; | ||
| 528 | let mut spot_col = [[0.0_f32; 4]; 4]; | ||
| 529 | let n_sp = lights.spots.len().min(4); | ||
| 530 | for (si, sl) in lights.spots.iter().take(4).enumerate() { | ||
| 531 | spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner]; | ||
| 532 | spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer]; | ||
| 533 | spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type]; | ||
| 534 | } | ||
| 535 | let uni = MeshUniform { | ||
| 536 | mvp, | ||
| 537 | model: m.world, | ||
| 538 | dod, | ||
| 539 | flags: [ | ||
| 540 | if m.tex.is_some() { 1.0 } else { 0.0 }, | ||
| 541 | if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 }, | ||
| 542 | m.specular_intensity, | ||
| 543 | if m.flip_normals { 1.0 } else { 0.0 }, | ||
| 544 | ], | ||
| 545 | diffuse_col: m.diffuse_col, | ||
| 546 | specular_col: [ | ||
| 547 | m.specular_col[0], | ||
| 548 | m.specular_col[1], | ||
| 549 | m.specular_col[2], | ||
| 550 | m.specular_exponent, | ||
| 551 | ], | ||
| 552 | ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0], | ||
| 553 | dir_to_light: [ | ||
| 554 | lights.dir_to_light[0], | ||
| 555 | lights.dir_to_light[1], | ||
| 556 | lights.dir_to_light[2], | ||
| 557 | if lights.has_dir { 1.0 } else { 0.0 }, | ||
| 558 | ], | ||
| 559 | dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0], | ||
| 560 | cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], | ||
| 561 | light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0], | ||
| 562 | point_pos, | ||
| 563 | point_col, | ||
| 564 | spot_pos, | ||
| 565 | spot_dir, | ||
| 566 | spot_col, | ||
| 567 | }; | ||
| 568 | let ubuf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 569 | label: Some("scene3d-u"), | ||
| 570 | size: std::mem::size_of::<MeshUniform>() as u64, | ||
| 571 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | ||
| 572 | mapped_at_creation: false, | ||
| 573 | }); | ||
| 574 | queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uni)); | ||
| 575 | let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view); | ||
| 576 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | ||
| 577 | label: Some("scene3d-bg"), | ||
| 578 | layout: &self.bgl, | ||
| 579 | entries: &[ | ||
| 580 | wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, | ||
| 581 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) }, | ||
| 582 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, | ||
| 583 | ], | ||
| 584 | }); | ||
| 585 | draw_items.push(GpuDraw { | ||
| 586 | bg, | ||
| 587 | vbuf, | ||
| 588 | ibuf, | ||
| 589 | idx_count: indices.len() as u32, | ||
| 590 | }); | ||
| 591 | } | ||
| 592 | |||
| 593 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { | ||
| 594 | label: Some("scene3d-pass"), | ||
| 595 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { | ||
| 596 | view: &dst.view, | ||
| 597 | depth_slice: None, | ||
| 598 | resolve_target: None, | ||
| 599 | ops: wgpu::Operations { | ||
| 600 | load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), | ||
| 601 | store: wgpu::StoreOp::Store, | ||
| 602 | }, | ||
| 603 | })], | ||
| 604 | depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { | ||
| 605 | view: &depth_view, | ||
| 606 | depth_ops: Some(wgpu::Operations { | ||
| 607 | load: wgpu::LoadOp::Clear(1.0), | ||
| 608 | store: wgpu::StoreOp::Discard, | ||
| 609 | }), | ||
| 610 | stencil_ops: None, | ||
| 611 | }), | ||
| 612 | timestamp_writes: None, | ||
| 613 | occlusion_query_set: None, | ||
| 614 | multiview_mask: None, | ||
| 615 | }); | ||
| 616 | pass.set_pipeline(&self.pipeline); | ||
| 617 | for d in &draw_items { | ||
| 618 | pass.set_bind_group(0, &d.bg, &[]); | ||
| 619 | pass.set_vertex_buffer(0, d.vbuf.slice(..)); | ||
| 620 | pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); | ||
| 621 | pass.draw_indexed(0..d.idx_count, 0, 0..1); | ||
| 622 | } | ||
| 623 | } | ||
| 624 | } | ||
| 625 | |||
| 626 | fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) { | ||
| 627 | match *shape { | ||
| 628 | ShapeKind::ImagePlane => { | ||
| 629 | let hx = 0.5; | ||
| 630 | let hy = 0.5 / tex_aspect.max(1e-4); | ||
| 631 | let verts = vec![ | ||
| 632 | Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] }, | ||
| 633 | Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, | ||
| 634 | Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, | ||
| 635 | Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] }, | ||
| 636 | ]; | ||
| 637 | (verts, vec![0, 1, 2, 0, 2, 3]) | ||
| 638 | } | ||
| 639 | ShapeKind::Plane { width, height, sub_w, sub_h } => { | ||
| 640 | let sw = sub_w.clamp(1, 64); | ||
| 641 | let sh = sub_h.clamp(1, 64); | ||
| 642 | let hx = width * 0.5; | ||
| 643 | let hy = height * 0.5; | ||
| 644 | let mut verts = Vec::with_capacity(((sw + 1) * (sh + 1)) as usize); | ||
| 645 | let mut idx = Vec::with_capacity((sw * sh * 6) as usize); | ||
| 646 | for iy in 0..=sh { | ||
| 647 | let v = iy as f32 / sh as f32; | ||
| 648 | let y = hy - v * height; | ||
| 649 | for ix in 0..=sw { | ||
| 650 | let u = ix as f32 / sw as f32; | ||
| 651 | let x = -hx + u * width; | ||
| 652 | verts.push(Vertex3D { pos: [x, y, 0.0], normal: [0.0, 0.0, 1.0], uv: [u, v] }); | ||
| 653 | } | ||
| 654 | } | ||
| 655 | let row = sw + 1; | ||
| 656 | for iy in 0..sh { | ||
| 657 | for ix in 0..sw { | ||
| 658 | let a = iy * row + ix; | ||
| 659 | let b = (iy + 1) * row + ix; | ||
| 660 | let c = (iy + 1) * row + ix + 1; | ||
| 661 | let d = iy * row + ix + 1; | ||
| 662 | idx.extend_from_slice(&[a, b, c, a, c, d]); | ||
| 663 | } | ||
| 664 | } | ||
| 665 | (verts, idx) | ||
| 666 | } | ||
| 667 | ShapeKind::TextPlate { width, height, depth, slices } => { | ||
| 668 | let hx = width * 0.5; | ||
| 669 | let hy = height * 0.5; | ||
| 670 | let n_slices = if depth.abs() > 1e-4 { slices.clamp(2, 16) } else { 1 }; | ||
| 671 | let mut verts = Vec::with_capacity((n_slices * 4) as usize); | ||
| 672 | let mut idx = Vec::with_capacity((n_slices * 6) as usize); | ||
| 673 | for s in 0..n_slices { | ||
| 674 | let t = if n_slices == 1 { 0.0 } else { s as f32 / (n_slices - 1) as f32 }; | ||
| 675 | // Fusion Text3D extrudes backward along -Z from z=0 to z=-depth | ||
| 676 | let z = -t * depth; | ||
| 677 | let nz = if n_slices > 1 && s == n_slices - 1 { -1.0 } else { 1.0 }; | ||
| 678 | let base = verts.len() as u32; | ||
| 679 | verts.push(Vertex3D { pos: [-hx, hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 0.0] }); | ||
| 680 | verts.push(Vertex3D { pos: [-hx, -hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 1.0] }); | ||
| 681 | verts.push(Vertex3D { pos: [ hx, -hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 1.0] }); | ||
| 682 | verts.push(Vertex3D { pos: [ hx, hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 0.0] }); | ||
| 683 | idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); | ||
| 684 | } | ||
| 685 | (verts, idx) | ||
| 686 | } | ||
| 687 | ShapeKind::Sphere { radius, sub_base, sub_height } => { | ||
| 688 | let seg_u = sub_base.clamp(12, 96); | ||
| 689 | let seg_v = sub_height.clamp(8, 64); | ||
| 690 | let mut verts = Vec::with_capacity(((seg_u + 1) * (seg_v + 1)) as usize); | ||
| 691 | let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize); | ||
| 692 | for iv in 0..=seg_v { | ||
| 693 | let v = iv as f32 / seg_v as f32; | ||
| 694 | let phi = v * std::f32::consts::PI; // 0 (top +Y) -> PI (bottom -Y) | ||
| 695 | let (sp, cp) = phi.sin_cos(); | ||
| 696 | for iu in 0..=seg_u { | ||
| 697 | let u = iu as f32 / seg_u as f32; | ||
| 698 | // Fusion Shape3D Sphere places u=0.75 facing +Z (verified via probe_archive_3d f02) | ||
| 699 | let theta = (u - 0.75) * std::f32::consts::TAU; | ||
| 700 | let (st, ct) = theta.sin_cos(); | ||
| 701 | let nx = sp * st; | ||
| 702 | let ny = cp; | ||
| 703 | let nz = sp * ct; | ||
| 704 | verts.push(Vertex3D { | ||
| 705 | pos: [nx * radius, ny * radius, nz * radius], | ||
| 706 | normal: [nx, ny, nz], | ||
| 707 | uv: [u, v], | ||
| 708 | }); | ||
| 709 | } | ||
| 710 | } | ||
| 711 | let row = seg_u + 1; | ||
| 712 | for iv in 0..seg_v { | ||
| 713 | for iu in 0..seg_u { | ||
| 714 | let a = iv * row + iu; | ||
| 715 | let b = (iv + 1) * row + iu; | ||
| 716 | let c = (iv + 1) * row + iu + 1; | ||
| 717 | let d = iv * row + iu + 1; | ||
| 718 | idx.extend_from_slice(&[a, b, c, a, c, d]); | ||
| 719 | } | ||
| 720 | } | ||
| 721 | (verts, idx) | ||
| 722 | } | ||
| 723 | ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base } => { | ||
| 724 | let seg_u = sub_base.clamp(16, 96); | ||
| 725 | let half_h = height * 0.5; | ||
| 726 | let a0 = start_sweep_deg.to_radians(); | ||
| 727 | let a1 = end_sweep_deg.to_radians(); | ||
| 728 | let mut verts = Vec::with_capacity(((seg_u + 1) * 2) as usize); | ||
| 729 | let mut idx = Vec::with_capacity((seg_u * 6) as usize); | ||
| 730 | for iu in 0..=seg_u { | ||
| 731 | let u = iu as f32 / seg_u as f32; | ||
| 732 | // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc | ||
| 733 | let theta = a0 + (a1 - a0) * u; | ||
| 734 | let (st, ct) = theta.sin_cos(); | ||
| 735 | let nx = ct; | ||
| 736 | let nz = st; | ||
| 737 | verts.push(Vertex3D { | ||
| 738 | pos: [nx * radius, half_h, nz * radius], | ||
| 739 | normal: [nx, 0.0, nz], | ||
| 740 | uv: [1.0 - u, 0.0], | ||
| 741 | }); | ||
| 742 | verts.push(Vertex3D { | ||
| 743 | pos: [nx * radius, -half_h, nz * radius], | ||
| 744 | normal: [nx, 0.0, nz], | ||
| 745 | uv: [1.0 - u, 1.0], | ||
| 746 | }); | ||
| 747 | } | ||
| 748 | for iu in 0..seg_u { | ||
| 749 | let a = iu * 2; | ||
| 750 | let b = a + 1; | ||
| 751 | let c = a + 3; | ||
| 752 | let d = a + 2; | ||
| 753 | idx.extend_from_slice(&[a, b, c, a, c, d]); | ||
| 754 | } | ||
| 755 | (verts, idx) | ||
| 756 | } | ||
| 757 | ShapeKind::Cube { width, height, depth } => { | ||
| 758 | let hx = width * 0.5; | ||
| 759 | let hy = height * 0.5; | ||
| 760 | let hz = depth * 0.5; | ||
| 761 | let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [ | ||
| 762 | ([0.0, 0.0, 1.0], [[-hx, hy, hz], [-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz]]), | ||
| 763 | ([0.0, 0.0, -1.0], [[hx, hy, -hz], [hx, -hy, -hz], [-hx, -hy, -hz], [-hx, hy, -hz]]), | ||
| 764 | ([1.0, 0.0, 0.0], [[hx, hy, hz], [hx, -hy, hz], [hx, -hy, -hz], [hx, hy, -hz]]), | ||
| 765 | ([-1.0, 0.0, 0.0], [[-hx, hy, -hz], [-hx, -hy, -hz], [-hx, -hy, hz], [-hx, hy, hz]]), | ||
| 766 | ([0.0, 1.0, 0.0], [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]]), | ||
| 767 | ([0.0, -1.0, 0.0], [[-hx, -hy, hz], [-hx, -hy, -hz], [hx, -hy, -hz], [hx, -hy, hz]]), | ||
| 768 | ]; | ||
| 769 | let mut verts = Vec::with_capacity(24); | ||
| 770 | let mut idx = Vec::with_capacity(36); | ||
| 771 | for (n, corners) in faces { | ||
| 772 | let base = verts.len() as u32; | ||
| 773 | let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]; | ||
| 774 | for (p, uv) in corners.into_iter().zip(uvs) { | ||
| 775 | verts.push(Vertex3D { pos: p, normal: n, uv }); | ||
| 776 | } | ||
| 777 | idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); | ||
| 778 | } | ||
| 779 | (verts, idx) | ||
| 780 | } | ||
| 781 | } | ||
| 782 | } | ||
| 783 | |||
| 784 | fn apply_heightmap_displace(verts: &mut [Vertex3D], indices: &[u32], disp: &DisplaceHeightmap) { | ||
| 785 | let w = disp.size[0].max(1) as usize; | ||
| 786 | let h = disp.size[1].max(1) as usize; | ||
| 787 | if disp.rgba.len() < w * h * 4 { | ||
| 788 | return; | ||
| 789 | } | ||
| 790 | for v in verts.iter_mut() { | ||
| 791 | let px = ((v.uv[0].clamp(0.0, 1.0)) * (w - 1) as f32).round() as usize; | ||
| 792 | let py = ((v.uv[1].clamp(0.0, 1.0)) * (h - 1) as f32).round() as usize; | ||
| 793 | let off = (py * w + px) * 4; | ||
| 794 | let r = disp.rgba[off] as f32 / 255.0; | ||
| 795 | let g = disp.rgba[off + 1] as f32 / 255.0; | ||
| 796 | let b = disp.rgba[off + 2] as f32 / 255.0; | ||
| 797 | let a = disp.rgba[off + 3] as f32 / 255.0; | ||
| 798 | let sample = match disp.channel { | ||
| 799 | 0 => r, | ||
| 800 | 1 => g, | ||
| 801 | 2 => b, | ||
| 802 | 3 => a, | ||
| 803 | _ => 0.299 * r + 0.587 * g + 0.114 * b, | ||
| 804 | }; | ||
| 805 | let d = (sample - 0.5 + disp.bias) * disp.scale; | ||
| 806 | v.pos[0] += v.normal[0] * d; | ||
| 807 | v.pos[1] += v.normal[1] * d; | ||
| 808 | v.pos[2] += v.normal[2] * d; | ||
| 809 | } | ||
| 810 | // Recompute smooth vertex normals from displaced triangles | ||
| 811 | let mut acc = vec![[0.0_f32; 3]; verts.len()]; | ||
| 812 | for tri in indices.chunks_exact(3) { | ||
| 813 | let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize); | ||
| 814 | if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() { | ||
| 815 | continue; | ||
| 816 | } | ||
| 817 | let p0 = verts[i0].pos; | ||
| 818 | let p1 = verts[i1].pos; | ||
| 819 | let p2 = verts[i2].pos; | ||
| 820 | let e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]]; | ||
| 821 | let e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]]; | ||
| 822 | let fn_v = [ | ||
| 823 | e1[1] * e2[2] - e1[2] * e2[1], | ||
| 824 | e1[2] * e2[0] - e1[0] * e2[2], | ||
| 825 | e1[0] * e2[1] - e1[1] * e2[0], | ||
| 826 | ]; | ||
| 827 | for &i in &[i0, i1, i2] { | ||
| 828 | acc[i][0] += fn_v[0]; | ||
| 829 | acc[i][1] += fn_v[1]; | ||
| 830 | acc[i][2] += fn_v[2]; | ||
| 831 | } | ||
| 832 | } | ||
| 833 | for (v, n) in verts.iter_mut().zip(acc.into_iter()) { | ||
| 834 | let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); | ||
| 835 | if len > 1e-6 { | ||
| 836 | v.normal = [n[0] / len, n[1] / len, n[2] / len]; | ||
| 837 | } | ||
| 838 | } | ||
| 839 | } | ||
| 840 | |||
| 841 | #[derive(Clone, Default)] | ||
| 842 | struct SceneOverrides { | ||
| 843 | material_override: Option<NodeId>, | ||
| 844 | affected_by_lights: Option<bool>, | ||
| 845 | flip_normals: bool, | ||
| 846 | displace: Option<Displace3DSpec>, | ||
| 847 | } | ||
| 848 | |||
| 849 | fn splitmix64(mut x: u64) -> f32 { | ||
| 850 | x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); | ||
| 851 | x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); | ||
| 852 | x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); | ||
| 853 | x ^= x >> 31; | ||
| 854 | // Uniform in [-0.5, +0.5] | ||
| 855 | ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5 | ||
| 856 | } | ||
| 857 | |||
| 858 | /// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`, | ||
| 859 | /// `ImagePlane3D`, `Shape3D`, `Text3D`, `LightAmbient`, `LightDirectional`, `LightPoint`, | ||
| 860 | /// `LightSpot`, `ReplaceMaterial3D`, `Override3D`, `Duplicate3D`, `ReplaceNormals3D`, `Displace3D`). | ||
| 861 | #[allow(clippy::too_many_arguments)] | ||
| 862 | pub fn collect_scene( | ||
| 863 | comp: &Comp, | ||
| 864 | node_id: NodeId, | ||
| 865 | time: f64, | ||
| 866 | expr: &ExprEngine, | ||
| 867 | parent_xform: Mat4, | ||
| 868 | render_aspect: f32, | ||
| 869 | cameras: &mut Vec<CameraInstance>, | ||
| 870 | meshes: &mut Vec<MeshInstance>, | ||
| 871 | lights: &mut SceneLights, | ||
| 872 | depth: usize, | ||
| 873 | ) { | ||
| 874 | collect_scene_inner( | ||
| 875 | comp, | ||
| 876 | node_id, | ||
| 877 | time, | ||
| 878 | expr, | ||
| 879 | parent_xform, | ||
| 880 | render_aspect, | ||
| 881 | &SceneOverrides::default(), | ||
| 882 | cameras, | ||
| 883 | meshes, | ||
| 884 | lights, | ||
| 885 | depth, | ||
| 886 | ); | ||
| 887 | } | ||
| 888 | |||
| 889 | #[allow(clippy::too_many_arguments)] | ||
| 890 | fn collect_scene_inner( | ||
| 891 | comp: &Comp, | ||
| 892 | node_id: NodeId, | ||
| 893 | time: f64, | ||
| 894 | expr: &ExprEngine, | ||
| 895 | parent_xform: Mat4, | ||
| 896 | render_aspect: f32, | ||
| 897 | ovr: &SceneOverrides, | ||
| 898 | cameras: &mut Vec<CameraInstance>, | ||
| 899 | meshes: &mut Vec<MeshInstance>, | ||
| 900 | lights: &mut SceneLights, | ||
| 901 | depth: usize, | ||
| 902 | ) { | ||
| 903 | if depth > 32 { | ||
| 904 | return; | ||
| 905 | } | ||
| 906 | let node = comp.node(node_id); | ||
| 907 | if node.bypassed { | ||
| 908 | return; | ||
| 909 | } | ||
| 910 | let local = eval_transform3d(comp, node, time, expr); | ||
| 911 | let world = mat4_mul(parent_xform, local); | ||
| 912 | |||
| 913 | match node.kind.as_str() { | ||
| 914 | "Merge3D" | "Transform3D" => { | ||
| 915 | let mut input_names: Vec<&String> = node | ||
| 916 | .inputs | ||
| 917 | .keys() | ||
| 918 | .filter(|k| k.starts_with("SceneInput")) | ||
| 919 | .collect(); | ||
| 920 | input_names.sort(); | ||
| 921 | for in_name in input_names { | ||
| 922 | if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) { | ||
| 923 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); | ||
| 924 | } | ||
| 925 | } | ||
| 926 | } | ||
| 927 | "ReplaceMaterial3D" => { | ||
| 928 | let mut next_ovr = ovr.clone(); | ||
| 929 | if let Some(mid) = node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)) { | ||
| 930 | next_ovr.material_override = Some(mid); | ||
| 931 | } | ||
| 932 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 933 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | ||
| 934 | } | ||
| 935 | } | ||
| 936 | "Override3D" => { | ||
| 937 | let do_vis = comp.eval_number(node, "Visibility.DoVisible", time, 0.0, expr) > 0.5; | ||
| 938 | let is_vis = comp.eval_number(node, "Visibility.IsVisible", time, 1.0, expr) > 0.5; | ||
| 939 | if do_vis && !is_vis { | ||
| 940 | return; | ||
| 941 | } | ||
| 942 | let mut next_ovr = ovr.clone(); | ||
| 943 | let do_lit = comp.eval_number(node, "Lighting.DoAffectedByLights", time, 0.0, expr) > 0.5; | ||
| 944 | if do_lit { | ||
| 945 | let is_lit = comp.eval_number(node, "Lighting.IsAffectedByLights", time, 1.0, expr) > 0.5; | ||
| 946 | next_ovr.affected_by_lights = Some(is_lit); | ||
| 947 | } | ||
| 948 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 949 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | ||
| 950 | } | ||
| 951 | } | ||
| 952 | "ReplaceNormals3D" => { | ||
| 953 | let mut next_ovr = ovr.clone(); | ||
| 954 | if comp.eval_number(node, "FlipNormals", time, 0.0, expr) > 0.5 { | ||
| 955 | next_ovr.flip_normals = !next_ovr.flip_normals; | ||
| 956 | } | ||
| 957 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 958 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | ||
| 959 | } | ||
| 960 | } | ||
| 961 | "Displace3D" => { | ||
| 962 | let mut next_ovr = ovr.clone(); | ||
| 963 | if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { | ||
| 964 | let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32; | ||
| 965 | let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32; | ||
| 966 | let channel = comp.eval_number(node, "Channel", time, 4.0, expr).round() as i32; | ||
| 967 | next_ovr.displace = Some(Displace3DSpec { | ||
| 968 | input_node: in_id, | ||
| 969 | scale, | ||
| 970 | bias, | ||
| 971 | channel, | ||
| 972 | }); | ||
| 973 | } | ||
| 974 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 975 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | ||
| 976 | } | ||
| 977 | } | ||
| 978 | "Duplicate3D" => { | ||
| 979 | let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { | ||
| 980 | return; | ||
| 981 | }; | ||
| 982 | let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32; | ||
| 983 | let last = comp.eval_number(node, "LastCopy", time, 1.0, expr).round() as i32; | ||
| 984 | let count = (last - first + 1).clamp(0, 256); | ||
| 985 | // Fusion Duplicate3D uses bare `Translate.X/Y/Z`, `Rotate.X/Y/Z`, `Scale.X/Y/Z` (with fallback to `Transform3DOp.*`) | ||
| 986 | let step = eval_duplicate3d_step(comp, node, time, expr); | ||
| 987 | let seed = comp.eval_number(node, "RandomSeed", time, 26024.0, expr).round() as u64; | ||
| 988 | let jtx = comp.eval_number(node, "JitterTranslate.X", time, 0.0, expr) as f32; | ||
| 989 | let jty = comp.eval_number(node, "JitterTranslate.Y", time, 0.0, expr) as f32; | ||
| 990 | let jtz = comp.eval_number(node, "JitterTranslate.Z", time, 0.0, expr) as f32; | ||
| 991 | let jrx = comp.eval_number(node, "JitterRotate.X", time, 0.0, expr) as f32; | ||
| 992 | let jry = comp.eval_number(node, "JitterRotate.Y", time, 0.0, expr) as f32; | ||
| 993 | let jrz = comp.eval_number(node, "JitterRotate.Z", time, 0.0, expr) as f32; | ||
| 994 | let has_jitter = (jtx.abs() + jty.abs() + jtz.abs() + jrx.abs() + jry.abs() + jrz.abs()) > 1e-5; | ||
| 995 | |||
| 996 | let mut acc = mat4_identity(); | ||
| 997 | for _ in 0..first.max(0) { | ||
| 998 | acc = mat4_mul(acc, step); | ||
| 999 | } | ||
| 1000 | for i in 0..count { | ||
| 1001 | let copy_idx = (first + i) as u64; | ||
| 1002 | let mut m = mat4_mul(parent_xform, acc); | ||
| 1003 | if has_jitter { | ||
| 1004 | let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407)); | ||
| 1005 | let tx = splitmix64(s ^ 1) * jtx; | ||
| 1006 | let ty = splitmix64(s ^ 2) * jty; | ||
| 1007 | let tz = splitmix64(s ^ 3) * jtz; | ||
| 1008 | let rx = (splitmix64(s ^ 4) * jrx).to_radians(); | ||
| 1009 | let ry = (splitmix64(s ^ 5) * jry).to_radians(); | ||
| 1010 | let rz = (splitmix64(s ^ 6) * jrz).to_radians(); | ||
| 1011 | 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)))); | ||
| 1012 | m = mat4_mul(m, jm); | ||
| 1013 | } | ||
| 1014 | collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, depth + 1); | ||
| 1015 | acc = mat4_mul(acc, step); | ||
| 1016 | } | ||
| 1017 | } | ||
| 1018 | "Camera3D" => { | ||
| 1019 | let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32; | ||
| 1020 | let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32; | ||
| 1021 | // In Fusion .comp files, serialized AoV is always vertical degrees (AoVType only changes UI display). | ||
| 1022 | // When AoV is omitted, compute from FLength if present, else Fusion 21's default Camera3D vertical AoV (~24.302°). | ||
| 1023 | let has_aov = node.inputs.contains_key("AoV"); | ||
| 1024 | let has_fl = node.inputs.contains_key("FLength"); | ||
| 1025 | let aov_deg = if has_aov { | ||
| 1026 | comp.eval_number(node, "AoV", time, 24.302, expr) as f32 | ||
| 1027 | } else if has_fl { | ||
| 1028 | let fl_mm = comp.eval_number(node, "FLength", time, 24.0, expr).max(0.5) as f32; | ||
| 1029 | let sensor_h_mm = ap_h * 25.4; | ||
| 1030 | 2.0 * (sensor_h_mm * 0.5 / fl_mm).atan().to_degrees() | ||
| 1031 | } else { | ||
| 1032 | 24.302 | ||
| 1033 | }; | ||
| 1034 | // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders) | ||
| 1035 | let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height"); | ||
| 1036 | let gate_aspect = (ap_w / ap_h.max(1e-4)).max(1e-4); | ||
| 1037 | |||
| 1038 | let half_aov = (aov_deg.to_radians() * 0.5).tan(); | ||
| 1039 | let half_v = match gate_fit { | ||
| 1040 | "Height" | "Stretch" => half_aov, | ||
| 1041 | "Width" => half_aov * (gate_aspect / render_aspect.max(1e-4)), | ||
| 1042 | "Outside" => half_aov * (gate_aspect / render_aspect.max(1e-4)).min(1.0), | ||
| 1043 | _ => half_aov * (gate_aspect / render_aspect.max(1e-4)).max(1.0), // Inside (Fusion default!) | ||
| 1044 | }; | ||
| 1045 | let vfov_rad = 2.0 * half_v.atan(); | ||
| 1046 | let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32; | ||
| 1047 | let far = 5000.0_f32; | ||
| 1048 | cameras.push(CameraInstance { world, vfov_rad, near, far }); | ||
| 1049 | } | ||
| 1050 | "LightAmbient" => { | ||
| 1051 | let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; | ||
| 1052 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 1053 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 1054 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 1055 | lights.ambient[0] += r * inten; | ||
| 1056 | lights.ambient[1] += g * inten; | ||
| 1057 | lights.ambient[2] += b * inten; | ||
| 1058 | } | ||
| 1059 | "LightDirectional" => { | ||
| 1060 | let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; | ||
| 1061 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 1062 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 1063 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 1064 | // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! | ||
| 1065 | let dx = world[8]; | ||
| 1066 | let dy = world[9]; | ||
| 1067 | let dz = world[10]; | ||
| 1068 | let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); | ||
| 1069 | lights.dir_to_light = [dx / len, dy / len, dz / len]; | ||
| 1070 | lights.dir_color = [r * inten, g * inten, b * inten]; | ||
| 1071 | lights.has_dir = true; | ||
| 1072 | } | ||
| 1073 | "LightPoint" => { | ||
| 1074 | let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; | ||
| 1075 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 1076 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 1077 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 1078 | let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; | ||
| 1079 | let decay_rate = comp.eval_number(node, "DecayRate", time, 1.0, expr) as f32; | ||
| 1080 | lights.points.push(PointLight { | ||
| 1081 | pos: [world[12], world[13], world[14]], | ||
| 1082 | color: [r * inten, g * inten, b * inten], | ||
| 1083 | decay_type, | ||
| 1084 | decay_rate, | ||
| 1085 | }); | ||
| 1086 | } | ||
| 1087 | "LightSpot" => { | ||
| 1088 | let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; | ||
| 1089 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 1090 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 1091 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 1092 | let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; | ||
| 1093 | let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; | ||
| 1094 | let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; | ||
| 1095 | // SpotLight shines along -Z in local space | ||
| 1096 | let dx = -world[8]; | ||
| 1097 | let dy = -world[9]; | ||
| 1098 | let dz = -world[10]; | ||
| 1099 | let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); | ||
| 1100 | let half_cone = (cone_deg * 0.5).max(0.5); | ||
| 1101 | let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5); | ||
| 1102 | let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg); | ||
| 1103 | lights.spots.push(SpotLight { | ||
| 1104 | pos: [world[12], world[13], world[14]], | ||
| 1105 | dir: [dx / len, dy / len, dz / len], | ||
| 1106 | color: [r * inten, g * inten, b * inten], | ||
| 1107 | cos_inner: inner_deg.to_radians().cos(), | ||
| 1108 | cos_outer: outer_deg.to_radians().cos(), | ||
| 1109 | decay_type, | ||
| 1110 | }); | ||
| 1111 | } | ||
| 1112 | "ImagePlane3D" => { | ||
| 1113 | let mat_node = ovr.material_override.or_else(|| { | ||
| 1114 | node.connected_node("MaterialInput") | ||
| 1115 | .or_else(|| node.connected_node("SceneInput")) | ||
| 1116 | .and_then(|s| comp.find_node(s)) | ||
| 1117 | }); | ||
| 1118 | let mat = resolve_material(comp, mat_node, time, expr); | ||
| 1119 | meshes.push(MeshInstance { | ||
| 1120 | world, | ||
| 1121 | shape: ShapeKind::ImagePlane, | ||
| 1122 | material_node: mat.tex_node, | ||
| 1123 | text3d: None, | ||
| 1124 | diffuse_col: mat.diffuse_col, | ||
| 1125 | specular_col: mat.specular_col, | ||
| 1126 | specular_intensity: mat.specular_intensity, | ||
| 1127 | specular_exponent: mat.specular_exponent, | ||
| 1128 | affected_by_lights: ovr.affected_by_lights.unwrap_or(true), | ||
| 1129 | flip_normals: ovr.flip_normals, | ||
| 1130 | displace: ovr.displace.clone(), | ||
| 1131 | }); | ||
| 1132 | } | ||
| 1133 | "Shape3D" => { | ||
| 1134 | let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); | ||
| 1135 | let disp_sub = if ovr.displace.is_some() { 32 } else { 1 }; | ||
| 1136 | let shape = match shape_name { | ||
| 1137 | "SurfaceSphereInputs" => ShapeKind::Sphere { | ||
| 1138 | // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) | ||
| 1139 | radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32, | ||
| 1140 | sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 32.0, expr).round() as u32, | ||
| 1141 | sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32, | ||
| 1142 | }, | ||
| 1143 | "SurfaceCylinderInputs" => { | ||
| 1144 | let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32; | ||
| 1145 | let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32; | ||
| 1146 | ShapeKind::Cylinder { | ||
| 1147 | radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 0.5, expr) as f32, | ||
| 1148 | height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 1.0, expr) as f32, | ||
| 1149 | start_sweep_deg: start_sw, | ||
| 1150 | end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, | ||
| 1151 | sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32, | ||
| 1152 | } | ||
| 1153 | } | ||
| 1154 | "SurfaceCubeInputs" => { | ||
| 1155 | let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr); | ||
| 1156 | ShapeKind::Cube { | ||
| 1157 | width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32, | ||
| 1158 | height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32, | ||
| 1159 | depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32, | ||
| 1160 | } | ||
| 1161 | } | ||
| 1162 | _ => { | ||
| 1163 | let sw = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; | ||
| 1164 | let sh = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionHeight", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; | ||
| 1165 | ShapeKind::Plane { | ||
| 1166 | width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32, | ||
| 1167 | height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32, | ||
| 1168 | sub_w: sw, | ||
| 1169 | sub_h: sh, | ||
| 1170 | } | ||
| 1171 | } | ||
| 1172 | }; | ||
| 1173 | let mat_node = ovr.material_override.or_else(|| { | ||
| 1174 | node.connected_node("MaterialInput") | ||
| 1175 | .and_then(|s| comp.find_node(s)) | ||
| 1176 | }); | ||
| 1177 | let mut mat = resolve_material(comp, mat_node, time, expr); | ||
| 1178 | if mat_node.is_none() { | ||
| 1179 | mat.diffuse_col = [ | ||
| 1180 | comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32, | ||
| 1181 | comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32, | ||
| 1182 | comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32, | ||
| 1183 | comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32, | ||
| 1184 | ]; | ||
| 1185 | } | ||
| 1186 | meshes.push(MeshInstance { | ||
| 1187 | world, | ||
| 1188 | shape, | ||
| 1189 | material_node: mat.tex_node, | ||
| 1190 | text3d: None, | ||
| 1191 | diffuse_col: mat.diffuse_col, | ||
| 1192 | specular_col: mat.specular_col, | ||
| 1193 | specular_intensity: mat.specular_intensity, | ||
| 1194 | specular_exponent: mat.specular_exponent, | ||
| 1195 | affected_by_lights: ovr.affected_by_lights.unwrap_or(true), | ||
| 1196 | flip_normals: ovr.flip_normals, | ||
| 1197 | displace: ovr.displace.clone(), | ||
| 1198 | }); | ||
| 1199 | } | ||
| 1200 | "Text3D" => { | ||
| 1201 | let ext_depth = comp.eval_number(node, "Extrusion.ExtrusionDepth", time, 0.0, expr) as f32; | ||
| 1202 | let mat_node = ovr.material_override.or_else(|| { | ||
| 1203 | node.connected_node("MaterialInput") | ||
| 1204 | .and_then(|s| comp.find_node(s)) | ||
| 1205 | }); | ||
| 1206 | let mut mat = resolve_material(comp, mat_node, time, expr); | ||
| 1207 | if mat_node.is_none() { | ||
| 1208 | mat.diffuse_col = [1.0, 1.0, 1.0, 1.0]; | ||
| 1209 | } | ||
| 1210 | // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate) | ||
| 1211 | meshes.push(MeshInstance { | ||
| 1212 | world, | ||
| 1213 | shape: ShapeKind::TextPlate { | ||
| 1214 | width: 4.0, | ||
| 1215 | height: 2.0, | ||
| 1216 | depth: ext_depth, | ||
| 1217 | slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 }, | ||
| 1218 | }, | ||
| 1219 | material_node: mat.tex_node, | ||
| 1220 | text3d: Some(Text3DSpec { node_id }), | ||
| 1221 | diffuse_col: mat.diffuse_col, | ||
| 1222 | specular_col: mat.specular_col, | ||
| 1223 | specular_intensity: mat.specular_intensity, | ||
| 1224 | specular_exponent: mat.specular_exponent, | ||
| 1225 | affected_by_lights: ovr.affected_by_lights.unwrap_or(true), | ||
| 1226 | flip_normals: ovr.flip_normals, | ||
| 1227 | displace: ovr.displace.clone(), | ||
| 1228 | }); | ||
| 1229 | } | ||
| 1230 | "MacroOperator" | "GroupOperator" => { | ||
| 1231 | if let Some(out_id) = node.macro_output { | ||
| 1232 | collect_scene_inner(comp, out_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); | ||
| 1233 | } | ||
| 1234 | } | ||
| 1235 | _ => {} | ||
| 1236 | } | ||
| 1237 | } | ||
| 1238 | |||
| 1239 | struct ResolvedMaterial { | ||
| 1240 | tex_node: Option<NodeId>, | ||
| 1241 | diffuse_col: [f32; 4], | ||
| 1242 | specular_col: [f32; 3], | ||
| 1243 | specular_intensity: f32, | ||
| 1244 | specular_exponent: f32, | ||
| 1245 | } | ||
| 1246 | |||
| 1247 | /// Resolves a 3D material input (either a 2D image node, `Texture2DOperator`, or a Fusion 3D | ||
| 1248 | /// material like `MtlBlinn` / `MtlCookTorrance` / `MtlPhong`). | ||
| 1249 | fn resolve_material( | ||
| 1250 | comp: &Comp, | ||
| 1251 | mat_node: Option<NodeId>, | ||
| 1252 | time: f64, | ||
| 1253 | expr: &ExprEngine, | ||
| 1254 | ) -> ResolvedMaterial { | ||
| 1255 | let default_mat = ResolvedMaterial { | ||
| 1256 | tex_node: None, | ||
| 1257 | diffuse_col: [1.0, 1.0, 1.0, 1.0], | ||
| 1258 | specular_col: [1.0, 1.0, 1.0], | ||
| 1259 | specular_intensity: 0.15, | ||
| 1260 | specular_exponent: 25.0, | ||
| 1261 | }; | ||
| 1262 | let Some(mid) = mat_node else { | ||
| 1263 | return default_mat; | ||
| 1264 | }; | ||
| 1265 | let n = comp.node(mid); | ||
| 1266 | match n.kind.as_str() { | ||
| 1267 | "Texture2DOperator" => { | ||
| 1268 | let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s)); | ||
| 1269 | ResolvedMaterial { | ||
| 1270 | tex_node: tex_src, | ||
| 1271 | ..default_mat | ||
| 1272 | } | ||
| 1273 | } | ||
| 1274 | "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" => { | ||
| 1275 | let mut diff_tex = n | ||
| 1276 | .connected_node("Diffuse.Color.Material") | ||
| 1277 | .or_else(|| n.connected_node("MaterialInput")) | ||
| 1278 | .and_then(|s| comp.find_node(s)); | ||
| 1279 | // Unwrap Texture2DOperator if feeding Diffuse.Color.Material | ||
| 1280 | if let Some(tid) = diff_tex { | ||
| 1281 | if comp.node(tid).kind == "Texture2DOperator" { | ||
| 1282 | diff_tex = comp.node(tid).connected_node("Input").and_then(|s| comp.find_node(s)); | ||
| 1283 | } | ||
| 1284 | } | ||
| 1285 | let col = [ | ||
| 1286 | comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32, | ||
| 1287 | comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32, | ||
| 1288 | comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32, | ||
| 1289 | comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32, | ||
| 1290 | ]; | ||
| 1291 | let spec_col = [ | ||
| 1292 | comp.eval_number(n, "Specular.Color.Red", time, 1.0, expr) as f32, | ||
| 1293 | comp.eval_number(n, "Specular.Color.Green", time, 1.0, expr) as f32, | ||
| 1294 | comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32, | ||
| 1295 | ]; | ||
| 1296 | let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32; | ||
| 1297 | let (spec_exp, spec_gain) = if n.kind == "MtlCookTorrance" { | ||
| 1298 | let rough = comp.eval_number(n, "Specular.Roughness", time, 0.4, expr).clamp(0.05, 1.0) as f32; | ||
| 1299 | ((2.0 / (rough * rough) - 2.0).max(2.0), 0.15) | ||
| 1300 | } else { | ||
| 1301 | (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0) | ||
| 1302 | }; | ||
| 1303 | ResolvedMaterial { | ||
| 1304 | tex_node: diff_tex, | ||
| 1305 | diffuse_col: col, | ||
| 1306 | specular_col: spec_col, | ||
| 1307 | specular_intensity: spec_int.clamp(0.0, 4.0) * spec_gain, | ||
| 1308 | specular_exponent: spec_exp, | ||
| 1309 | } | ||
| 1310 | } | ||
| 1311 | _ => ResolvedMaterial { | ||
| 1312 | tex_node: Some(mid), | ||
| 1313 | ..default_mat | ||
| 1314 | }, | ||
| 1315 | } | ||
| 1316 | } | ||
| 1317 | |||
| 1318 | fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { | ||
| 1319 | let tx = comp.eval_number(node, "Translate.X", time, comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr), expr) as f32; | ||
| 1320 | let ty = comp.eval_number(node, "Translate.Y", time, comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr), expr) as f32; | ||
| 1321 | let tz = comp.eval_number(node, "Translate.Z", time, comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr), expr) as f32; | ||
| 1322 | 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(); | ||
| 1323 | 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(); | ||
| 1324 | 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(); | ||
| 1325 | let sx = comp.eval_number(node, "Scale.X", time, comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr), expr) as f32; | ||
| 1326 | let sy = comp.eval_number(node, "Scale.Y", time, comp.eval_number(node, "Transform3DOp.Scale.Y", time, sx as f64, expr), expr) as f32; | ||
| 1327 | let sz = comp.eval_number(node, "Scale.Z", time, comp.eval_number(node, "Transform3DOp.Scale.Z", time, sx as f64, expr), expr) as f32; | ||
| 1328 | let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))); | ||
| 1329 | mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz))) | ||
| 1330 | } | ||
| 1331 | |||
| 1332 | pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { | ||
| 1333 | let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32; | ||
| 1334 | let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32; | ||
| 1335 | let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32; | ||
| 1336 | |||
| 1337 | let rx = (comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr) as f32).to_radians(); | ||
| 1338 | let ry = (comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr) as f32).to_radians(); | ||
| 1339 | let rz = (comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr) as f32).to_radians(); | ||
| 1340 | let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ"); | ||
| 1341 | |||
| 1342 | let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5; | ||
| 1343 | let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32; | ||
| 1344 | let sy = if scale_lock { | ||
| 1345 | sx | ||
| 1346 | } else { | ||
| 1347 | comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32 | ||
| 1348 | }; | ||
| 1349 | let sz = if scale_lock { | ||
| 1350 | sx | ||
| 1351 | } else { | ||
| 1352 | comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32 | ||
| 1353 | }; | ||
| 1354 | |||
| 1355 | let px = comp.eval_number(node, "Transform3DOp.Pivot.X", time, 0.0, expr) as f32; | ||
| 1356 | let py = comp.eval_number(node, "Transform3DOp.Pivot.Y", time, 0.0, expr) as f32; | ||
| 1357 | let pz = comp.eval_number(node, "Transform3DOp.Pivot.Z", time, 0.0, expr) as f32; | ||
| 1358 | |||
| 1359 | let mx = mat4_rot_x(rx); | ||
| 1360 | let my = mat4_rot_y(ry); | ||
| 1361 | let mz = mat4_rot_z(rz); | ||
| 1362 | let rot = match rot_order { | ||
| 1363 | "XZY" => mat4_mul(my, mat4_mul(mz, mx)), | ||
| 1364 | "YXZ" => mat4_mul(mz, mat4_mul(mx, my)), | ||
| 1365 | "YZX" => mat4_mul(mx, mat4_mul(mz, my)), | ||
| 1366 | "ZXY" => mat4_mul(my, mat4_mul(mx, mz)), | ||
| 1367 | "ZYX" => mat4_mul(mx, mat4_mul(my, mz)), | ||
| 1368 | _ => mat4_mul(mz, mat4_mul(my, mx)), // XYZ default | ||
| 1369 | }; | ||
| 1370 | |||
| 1371 | let t = mat4_translate(tx + px, ty + py, tz + pz); | ||
| 1372 | let s = mat4_scale(sx, sy, sz); | ||
| 1373 | let inv_p = mat4_translate(-px, -py, -pz); | ||
| 1374 | mat4_mul(t, mat4_mul(rot, mat4_mul(s, inv_p))) | ||
| 1375 | } | ||
| 1376 | |||
| 1377 | pub fn mat4_identity() -> Mat4 { | ||
| 1378 | [ | ||
| 1379 | 1.0, 0.0, 0.0, 0.0, | ||
| 1380 | 0.0, 1.0, 0.0, 0.0, | ||
| 1381 | 0.0, 0.0, 1.0, 0.0, | ||
| 1382 | 0.0, 0.0, 0.0, 1.0, | ||
| 1383 | ] | ||
| 1384 | } | ||
| 1385 | |||
| 1386 | pub fn mat4_mul(a: Mat4, b: Mat4) -> Mat4 { | ||
| 1387 | let mut out = [0.0_f32; 16]; | ||
| 1388 | for col in 0..4 { | ||
| 1389 | for row in 0..4 { | ||
| 1390 | out[col * 4 + row] = a[row] * b[col * 4] | ||
| 1391 | + a[4 + row] * b[col * 4 + 1] | ||
| 1392 | + a[8 + row] * b[col * 4 + 2] | ||
| 1393 | + a[12 + row] * b[col * 4 + 3]; | ||
| 1394 | } | ||
| 1395 | } | ||
| 1396 | out | ||
| 1397 | } | ||
| 1398 | |||
| 1399 | pub fn mat4_translate(x: f32, y: f32, z: f32) -> Mat4 { | ||
| 1400 | [ | ||
| 1401 | 1.0, 0.0, 0.0, 0.0, | ||
| 1402 | 0.0, 1.0, 0.0, 0.0, | ||
| 1403 | 0.0, 0.0, 1.0, 0.0, | ||
| 1404 | x, y, z, 1.0, | ||
| 1405 | ] | ||
| 1406 | } | ||
| 1407 | |||
| 1408 | pub fn mat4_scale(x: f32, y: f32, z: f32) -> Mat4 { | ||
| 1409 | [ | ||
| 1410 | x, 0.0, 0.0, 0.0, | ||
| 1411 | 0.0, y, 0.0, 0.0, | ||
| 1412 | 0.0, 0.0, z, 0.0, | ||
| 1413 | 0.0, 0.0, 0.0, 1.0, | ||
| 1414 | ] | ||
| 1415 | } | ||
| 1416 | |||
| 1417 | pub fn mat4_rot_x(r: f32) -> Mat4 { | ||
| 1418 | let (s, c) = r.sin_cos(); | ||
| 1419 | [ | ||
| 1420 | 1.0, 0.0, 0.0, 0.0, | ||
| 1421 | 0.0, c, s, 0.0, | ||
| 1422 | 0.0, -s, c, 0.0, | ||
| 1423 | 0.0, 0.0, 0.0, 1.0, | ||
| 1424 | ] | ||
| 1425 | } | ||
| 1426 | |||
| 1427 | pub fn mat4_rot_y(r: f32) -> Mat4 { | ||
| 1428 | let (s, c) = r.sin_cos(); | ||
| 1429 | [ | ||
| 1430 | c, 0.0, -s, 0.0, | ||
| 1431 | 0.0, 1.0, 0.0, 0.0, | ||
| 1432 | s, 0.0, c, 0.0, | ||
| 1433 | 0.0, 0.0, 0.0, 1.0, | ||
| 1434 | ] | ||
| 1435 | } | ||
| 1436 | |||
| 1437 | pub fn mat4_rot_z(r: f32) -> Mat4 { | ||
| 1438 | let (s, c) = r.sin_cos(); | ||
| 1439 | [ | ||
| 1440 | c, s, 0.0, 0.0, | ||
| 1441 | -s, c, 0.0, 0.0, | ||
| 1442 | 0.0, 0.0, 1.0, 0.0, | ||
| 1443 | 0.0, 0.0, 0.0, 1.0, | ||
| 1444 | ] | ||
| 1445 | } | ||
| 1446 | |||
| 1447 | pub fn mat4_inverse_rigid(m: Mat4) -> Mat4 { | ||
| 1448 | let r00 = m[0]; let r10 = m[1]; let r20 = m[2]; | ||
| 1449 | let r01 = m[4]; let r11 = m[5]; let r21 = m[6]; | ||
| 1450 | let r02 = m[8]; let r12 = m[9]; let r22 = m[10]; | ||
| 1451 | let tx = m[12]; let ty = m[13]; let tz = m[14]; | ||
| 1452 | let itx = -(r00 * tx + r10 * ty + r20 * tz); | ||
| 1453 | let ity = -(r01 * tx + r11 * ty + r21 * tz); | ||
| 1454 | let itz = -(r02 * tx + r12 * ty + r22 * tz); | ||
| 1455 | [ | ||
| 1456 | r00, r01, r02, 0.0, | ||
| 1457 | r10, r11, r12, 0.0, | ||
| 1458 | r20, r21, r22, 0.0, | ||
| 1459 | itx, ity, itz, 1.0, | ||
| 1460 | ] | ||
| 1461 | } | ||
| 1462 | |||
| 1463 | pub fn mat4_perspective_wgpu(vfov_rad: f32, aspect: f32, near: f32, far: f32) -> Mat4 { | ||
| 1464 | let f = 1.0 / (vfov_rad * 0.5).tan().max(1e-5); | ||
| 1465 | let nf = 1.0 / (near - far); | ||
| 1466 | [ | ||
| 1467 | f / aspect.max(1e-4), 0.0, 0.0, 0.0, | ||
| 1468 | 0.0, f, 0.0, 0.0, | ||
| 1469 | 0.0, 0.0, far * nf, -1.0, | ||
| 1470 | 0.0, 0.0, far * near * nf, 0.0, | ||
| 1471 | ] | ||
| 1472 | } | ||
| 1473 | |||
| 1474 | #[cfg(test)] | ||
| 1475 | mod tests { | ||
| 1476 | use super::*; | ||
| 1477 | |||
| 1478 | #[test] | ||
| 1479 | fn test_collect_scene_archive_3d_nodes() { | ||
| 1480 | let src = r#"Composition { | ||
| 1481 | CurrentTime = 0, | ||
| 1482 | RenderRange = { 0, 10 }, | ||
| 1483 | GlobalRange = { 0, 10 }, | ||
| 1484 | Tools = ordered() { | ||
| 1485 | BG1 = Background { | ||
| 1486 | Inputs = { | ||
| 1487 | Width = Input { Value = 64, }, | ||
| 1488 | Height = Input { Value = 64, }, | ||
| 1489 | }, | ||
| 1490 | }, | ||
| 1491 | Tex2D = Texture2DOperator { | ||
| 1492 | Inputs = { | ||
| 1493 | Input = Input { SourceOp = "BG1", Source = "Output", }, | ||
| 1494 | }, | ||
| 1495 | }, | ||
| 1496 | Blinn1 = MtlBlinn { | ||
| 1497 | Inputs = { | ||
| 1498 | ["Diffuse.Color.Red"] = Input { Value = 0.8, }, | ||
| 1499 | ["Diffuse.Color.Material"] = Input { SourceOp = "Tex2D", Source = "MaterialOutput", }, | ||
| 1500 | ["Specular.Intensity"] = Input { Value = 0.75, }, | ||
| 1501 | ["Specular.Exponent"] = Input { Value = 40.0, }, | ||
| 1502 | }, | ||
| 1503 | }, | ||
| 1504 | Cook1 = MtlCookTorrance { | ||
| 1505 | Inputs = { | ||
| 1506 | ["Diffuse.Color.Green"] = Input { Value = 0.6, }, | ||
| 1507 | ["Specular.Roughness"] = Input { Value = 0.25, }, | ||
| 1508 | }, | ||
| 1509 | }, | ||
| 1510 | Shape1 = Shape3D { | ||
| 1511 | Inputs = { | ||
| 1512 | Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, | ||
| 1513 | MaterialInput = Input { SourceOp = "Blinn1", Source = "MaterialOutput", }, | ||
| 1514 | }, | ||
| 1515 | }, | ||
| 1516 | RepMat = ReplaceMaterial3D { | ||
| 1517 | Inputs = { | ||
| 1518 | SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, | ||
| 1519 | MaterialInput = Input { SourceOp = "Cook1", Source = "MaterialOutput", }, | ||
| 1520 | }, | ||
| 1521 | }, | ||
| 1522 | RepNorm = ReplaceNormals3D { | ||
| 1523 | Inputs = { | ||
| 1524 | SceneInput = Input { SourceOp = "RepMat", Source = "Output", }, | ||
| 1525 | FlipNormals = Input { Value = 1, }, | ||
| 1526 | }, | ||
| 1527 | }, | ||
| 1528 | Disp1 = Displace3D { | ||
| 1529 | Inputs = { | ||
| 1530 | SceneInput = Input { SourceOp = "RepNorm", Source = "Output", }, | ||
| 1531 | Input = Input { SourceOp = "BG1", Source = "Output", }, | ||
| 1532 | Scale = Input { Value = 0.2, }, | ||
| 1533 | }, | ||
| 1534 | }, | ||
| 1535 | Dup1 = Duplicate3D { | ||
| 1536 | Inputs = { | ||
| 1537 | SceneInput = Input { SourceOp = "Disp1", Source = "Output", }, | ||
| 1538 | FirstCopy = Input { Value = 0, }, | ||
| 1539 | LastCopy = Input { Value = 2, }, | ||
| 1540 | ["Translate.X"] = Input { Value = 1.5, }, | ||
| 1541 | }, | ||
| 1542 | }, | ||
| 1543 | OvrHide = Override3D { | ||
| 1544 | Inputs = { | ||
| 1545 | SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, | ||
| 1546 | ["Visibility.DoVisible"] = Input { Value = 1, }, | ||
| 1547 | ["Visibility.IsVisible"] = Input { Value = 0, }, | ||
| 1548 | }, | ||
| 1549 | }, | ||
| 1550 | Txt1 = Text3D { | ||
| 1551 | Inputs = { | ||
| 1552 | StyledText = Input { Value = "HI", }, | ||
| 1553 | ["Extrusion.ExtrusionDepth"] = Input { Value = 0.15, }, | ||
| 1554 | }, | ||
| 1555 | }, | ||
| 1556 | Pt1 = LightPoint { | ||
| 1557 | Inputs = { | ||
| 1558 | Intensity = Input { Value = 2.0, }, | ||
| 1559 | DecayType = Input { Value = 1, }, | ||
| 1560 | ["Transform3DOp.Translate.X"] = Input { Value = 3.0, }, | ||
| 1561 | }, | ||
| 1562 | }, | ||
| 1563 | Sp1 = LightSpot { | ||
| 1564 | Inputs = { | ||
| 1565 | Intensity = Input { Value = 1.5, }, | ||
| 1566 | ConeAngle = Input { Value = 45.0, }, | ||
| 1567 | PenumbraAngle = Input { Value = 10.0, }, | ||
| 1568 | }, | ||
| 1569 | }, | ||
| 1570 | Cam1 = Camera3D { | ||
| 1571 | Inputs = { | ||
| 1572 | ["Transform3DOp.Translate.Z"] = Input { Value = 5.0, }, | ||
| 1573 | }, | ||
| 1574 | }, | ||
| 1575 | Merge1 = Merge3D { | ||
| 1576 | Inputs = { | ||
| 1577 | SceneInput1 = Input { SourceOp = "Dup1", Source = "Output", }, | ||
| 1578 | SceneInput2 = Input { SourceOp = "OvrHide", Source = "Output", }, | ||
| 1579 | SceneInput3 = Input { SourceOp = "Txt1", Source = "Output", }, | ||
| 1580 | SceneInput4 = Input { SourceOp = "Pt1", Source = "Output", }, | ||
| 1581 | SceneInput5 = Input { SourceOp = "Sp1", Source = "Output", }, | ||
| 1582 | SceneInput6 = Input { SourceOp = "Cam1", Source = "Output", }, | ||
| 1583 | }, | ||
| 1584 | }, | ||
| 1585 | }, | ||
| 1586 | }"#; | ||
| 1587 | let comp = Comp::from_fusion_str(src).expect("parse 3D test comp"); | ||
| 1588 | let expr = ExprEngine::new(); | ||
| 1589 | let merge_id = comp.find_node("Merge1").expect("Merge1"); | ||
| 1590 | let mut cams = Vec::new(); | ||
| 1591 | let mut meshes = Vec::new(); | ||
| 1592 | let mut lights = SceneLights::default(); | ||
| 1593 | collect_scene( | ||
| 1594 | &comp, | ||
| 1595 | merge_id, | ||
| 1596 | 0.0, | ||
| 1597 | &expr, | ||
| 1598 | mat4_identity(), | ||
| 1599 | 16.0 / 9.0, | ||
| 1600 | &mut cams, | ||
| 1601 | &mut meshes, | ||
| 1602 | &mut lights, | ||
| 1603 | 0, | ||
| 1604 | ); | ||
| 1605 | assert_eq!(cams.len(), 1); | ||
| 1606 | // 3 copies from Duplicate3D (0..=2) + 1 Text3D (OvrHide suppresses its Shape1) | ||
| 1607 | assert_eq!(meshes.len(), 4); | ||
| 1608 | assert!(meshes[0].flip_normals); | ||
| 1609 | assert!(meshes[0].displace.is_some()); | ||
| 1610 | assert!((meshes[0].diffuse_col[1] - 0.6).abs() < 1e-4, "ReplaceMaterial3D should apply Cook1"); | ||
| 1611 | assert!((meshes[2].world[12] - 3.0).abs() < 1e-4, "Duplicate3D copy 2 translated X=3.0"); | ||
| 1612 | assert!(meshes[3].text3d.is_some()); | ||
| 1613 | assert_eq!(lights.points.len(), 1); | ||
| 1614 | assert!((lights.points[0].pos[0] - 3.0).abs() < 1e-4); | ||
| 1615 | assert_eq!(lights.spots.len(), 1); | ||
| 1616 | assert!(lights.spots[0].cos_inner > lights.spots[0].cos_outer); | ||
| 1617 | } | ||
| 1618 | } | ||
crates/engine/src/scene3d/collect.rs created+692| ... | @@ -0,0 +1,692 @@ | ||
| 1 | //! 3D scene graph traversal, material resolution, and 3D transform evaluation. | ||
| 2 | |||
| 3 | use super::math::{ | ||
| 4 | mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, | ||
| 5 | }; | ||
| 6 | use super::{ | ||
| 7 | CameraInstance, Displace3DSpec, Mat4, MeshInstance, PointLight, SceneLights, ShapeKind, | ||
| 8 | SpotLight, Text3DSpec, | ||
| 9 | }; | ||
| 10 | use model::{Comp, ExprEngine, Node, NodeId}; | ||
| 11 | |||
| 12 | #[derive(Clone, Default)] | ||
| 13 | struct SceneOverrides { | ||
| 14 | material_override: Option<NodeId>, | ||
| 15 | affected_by_lights: Option<bool>, | ||
| 16 | flip_normals: bool, | ||
| 17 | displace: Option<Displace3DSpec>, | ||
| 18 | } | ||
| 19 | |||
| 20 | fn splitmix64(mut x: u64) -> f32 { | ||
| 21 | x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); | ||
| 22 | x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); | ||
| 23 | x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); | ||
| 24 | x ^= x >> 31; | ||
| 25 | // Uniform in [-0.5, +0.5] | ||
| 26 | ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5 | ||
| 27 | } | ||
| 28 | |||
| 29 | /// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`, | ||
| 30 | /// `ImagePlane3D`, `Shape3D`, `Text3D`, `LightAmbient`, `LightDirectional`, `LightPoint`, | ||
| 31 | /// `LightSpot`, `ReplaceMaterial3D`, `Override3D`, `Duplicate3D`, `ReplaceNormals3D`, `Displace3D`). | ||
| 32 | #[allow(clippy::too_many_arguments)] | ||
| 33 | pub fn collect_scene( | ||
| 34 | comp: &Comp, | ||
| 35 | node_id: NodeId, | ||
| 36 | time: f64, | ||
| 37 | expr: &ExprEngine, | ||
| 38 | parent_xform: Mat4, | ||
| 39 | render_aspect: f32, | ||
| 40 | cameras: &mut Vec<CameraInstance>, | ||
| 41 | meshes: &mut Vec<MeshInstance>, | ||
| 42 | lights: &mut SceneLights, | ||
| 43 | depth: usize, | ||
| 44 | ) { | ||
| 45 | collect_scene_inner( | ||
| 46 | comp, | ||
| 47 | node_id, | ||
| 48 | time, | ||
| 49 | expr, | ||
| 50 | parent_xform, | ||
| 51 | render_aspect, | ||
| 52 | &SceneOverrides::default(), | ||
| 53 | cameras, | ||
| 54 | meshes, | ||
| 55 | lights, | ||
| 56 | depth, | ||
| 57 | ); | ||
| 58 | } | ||
| 59 | |||
| 60 | #[allow(clippy::too_many_arguments)] | ||
| 61 | fn collect_scene_inner( | ||
| 62 | comp: &Comp, | ||
| 63 | node_id: NodeId, | ||
| 64 | time: f64, | ||
| 65 | expr: &ExprEngine, | ||
| 66 | parent_xform: Mat4, | ||
| 67 | render_aspect: f32, | ||
| 68 | ovr: &SceneOverrides, | ||
| 69 | cameras: &mut Vec<CameraInstance>, | ||
| 70 | meshes: &mut Vec<MeshInstance>, | ||
| 71 | lights: &mut SceneLights, | ||
| 72 | depth: usize, | ||
| 73 | ) { | ||
| 74 | if depth > 32 { | ||
| 75 | return; | ||
| 76 | } | ||
| 77 | let node = comp.node(node_id); | ||
| 78 | if node.bypassed { | ||
| 79 | return; | ||
| 80 | } | ||
| 81 | let local = eval_transform3d(comp, node, time, expr); | ||
| 82 | let world = mat4_mul(parent_xform, local); | ||
| 83 | |||
| 84 | match node.kind.as_str() { | ||
| 85 | "Merge3D" | "Transform3D" => { | ||
| 86 | let mut input_names: Vec<&String> = node | ||
| 87 | .inputs | ||
| 88 | .keys() | ||
| 89 | .filter(|k| k.starts_with("SceneInput")) | ||
| 90 | .collect(); | ||
| 91 | input_names.sort(); | ||
| 92 | for in_name in input_names { | ||
| 93 | if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) { | ||
| 94 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); | ||
| 95 | } | ||
| 96 | } | ||
| 97 | } | ||
| 98 | "ReplaceMaterial3D" => { | ||
| 99 | let mut next_ovr = ovr.clone(); | ||
| 100 | if let Some(mid) = node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)) { | ||
| 101 | next_ovr.material_override = Some(mid); | ||
| 102 | } | ||
| 103 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 104 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | ||
| 105 | } | ||
| 106 | } | ||
| 107 | "Override3D" => { | ||
| 108 | let do_vis = comp.eval_number(node, "Visibility.DoVisible", time, 0.0, expr) > 0.5; | ||
| 109 | let is_vis = comp.eval_number(node, "Visibility.IsVisible", time, 1.0, expr) > 0.5; | ||
| 110 | if do_vis && !is_vis { | ||
| 111 | return; | ||
| 112 | } | ||
| 113 | let mut next_ovr = ovr.clone(); | ||
| 114 | let do_lit = comp.eval_number(node, "Lighting.DoAffectedByLights", time, 0.0, expr) > 0.5; | ||
| 115 | if do_lit { | ||
| 116 | let is_lit = comp.eval_number(node, "Lighting.IsAffectedByLights", time, 1.0, expr) > 0.5; | ||
| 117 | next_ovr.affected_by_lights = Some(is_lit); | ||
| 118 | } | ||
| 119 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 120 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | ||
| 121 | } | ||
| 122 | } | ||
| 123 | "ReplaceNormals3D" => { | ||
| 124 | let mut next_ovr = ovr.clone(); | ||
| 125 | if comp.eval_number(node, "FlipNormals", time, 0.0, expr) > 0.5 { | ||
| 126 | next_ovr.flip_normals = !next_ovr.flip_normals; | ||
| 127 | } | ||
| 128 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 129 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | ||
| 130 | } | ||
| 131 | } | ||
| 132 | "Displace3D" => { | ||
| 133 | let mut next_ovr = ovr.clone(); | ||
| 134 | if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { | ||
| 135 | let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32; | ||
| 136 | let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32; | ||
| 137 | let channel = comp.eval_number(node, "Channel", time, 4.0, expr).round() as i32; | ||
| 138 | next_ovr.displace = Some(Displace3DSpec { | ||
| 139 | input_node: in_id, | ||
| 140 | scale, | ||
| 141 | bias, | ||
| 142 | channel, | ||
| 143 | }); | ||
| 144 | } | ||
| 145 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 146 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); | ||
| 147 | } | ||
| 148 | } | ||
| 149 | "Duplicate3D" => { | ||
| 150 | let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { | ||
| 151 | return; | ||
| 152 | }; | ||
| 153 | let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32; | ||
| 154 | let last = comp.eval_number(node, "LastCopy", time, 1.0, expr).round() as i32; | ||
| 155 | let count = (last - first + 1).clamp(0, 256); | ||
| 156 | // Fusion Duplicate3D uses bare `Translate.X/Y/Z`, `Rotate.X/Y/Z`, `Scale.X/Y/Z` (with fallback to `Transform3DOp.*`) | ||
| 157 | let step = eval_duplicate3d_step(comp, node, time, expr); | ||
| 158 | let seed = comp.eval_number(node, "RandomSeed", time, 26024.0, expr).round() as u64; | ||
| 159 | let jtx = comp.eval_number(node, "JitterTranslate.X", time, 0.0, expr) as f32; | ||
| 160 | let jty = comp.eval_number(node, "JitterTranslate.Y", time, 0.0, expr) as f32; | ||
| 161 | let jtz = comp.eval_number(node, "JitterTranslate.Z", time, 0.0, expr) as f32; | ||
| 162 | let jrx = comp.eval_number(node, "JitterRotate.X", time, 0.0, expr) as f32; | ||
| 163 | let jry = comp.eval_number(node, "JitterRotate.Y", time, 0.0, expr) as f32; | ||
| 164 | let jrz = comp.eval_number(node, "JitterRotate.Z", time, 0.0, expr) as f32; | ||
| 165 | let has_jitter = (jtx.abs() + jty.abs() + jtz.abs() + jrx.abs() + jry.abs() + jrz.abs()) > 1e-5; | ||
| 166 | |||
| 167 | let mut acc = mat4_identity(); | ||
| 168 | for _ in 0..first.max(0) { | ||
| 169 | acc = mat4_mul(acc, step); | ||
| 170 | } | ||
| 171 | for i in 0..count { | ||
| 172 | let copy_idx = (first + i) as u64; | ||
| 173 | let mut m = mat4_mul(parent_xform, acc); | ||
| 174 | if has_jitter { | ||
| 175 | let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407)); | ||
| 176 | let tx = splitmix64(s ^ 1) * jtx; | ||
| 177 | let ty = splitmix64(s ^ 2) * jty; | ||
| 178 | let tz = splitmix64(s ^ 3) * jtz; | ||
| 179 | let rx = (splitmix64(s ^ 4) * jrx).to_radians(); | ||
| 180 | let ry = (splitmix64(s ^ 5) * jry).to_radians(); | ||
| 181 | let rz = (splitmix64(s ^ 6) * jrz).to_radians(); | ||
| 182 | 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)))); | ||
| 183 | m = mat4_mul(m, jm); | ||
| 184 | } | ||
| 185 | collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, depth + 1); | ||
| 186 | acc = mat4_mul(acc, step); | ||
| 187 | } | ||
| 188 | } | ||
| 189 | "Camera3D" => { | ||
| 190 | let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32; | ||
| 191 | let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32; | ||
| 192 | // In Fusion .comp files, serialized AoV is always vertical degrees (AoVType only changes UI display). | ||
| 193 | // When AoV is omitted, compute from FLength if present, else Fusion 21's default Camera3D vertical AoV (~24.302°). | ||
| 194 | let has_aov = node.inputs.contains_key("AoV"); | ||
| 195 | let has_fl = node.inputs.contains_key("FLength"); | ||
| 196 | let aov_deg = if has_aov { | ||
| 197 | comp.eval_number(node, "AoV", time, 24.302, expr) as f32 | ||
| 198 | } else if has_fl { | ||
| 199 | let fl_mm = comp.eval_number(node, "FLength", time, 24.0, expr).max(0.5) as f32; | ||
| 200 | let sensor_h_mm = ap_h * 25.4; | ||
| 201 | 2.0 * (sensor_h_mm * 0.5 / fl_mm).atan().to_degrees() | ||
| 202 | } else { | ||
| 203 | 24.302 | ||
| 204 | }; | ||
| 205 | // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders) | ||
| 206 | let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height"); | ||
| 207 | let gate_aspect = (ap_w / ap_h.max(1e-4)).max(1e-4); | ||
| 208 | |||
| 209 | let half_aov = (aov_deg.to_radians() * 0.5).tan(); | ||
| 210 | let half_v = match gate_fit { | ||
| 211 | "Height" | "Stretch" => half_aov, | ||
| 212 | "Width" => half_aov * (gate_aspect / render_aspect.max(1e-4)), | ||
| 213 | "Outside" => half_aov * (gate_aspect / render_aspect.max(1e-4)).min(1.0), | ||
| 214 | _ => half_aov * (gate_aspect / render_aspect.max(1e-4)).max(1.0), // Inside (Fusion default!) | ||
| 215 | }; | ||
| 216 | let vfov_rad = 2.0 * half_v.atan(); | ||
| 217 | let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32; | ||
| 218 | let far = 5000.0_f32; | ||
| 219 | cameras.push(CameraInstance { world, vfov_rad, near, far }); | ||
| 220 | } | ||
| 221 | "LightAmbient" => { | ||
| 222 | let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; | ||
| 223 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 224 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 225 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 226 | lights.ambient[0] += r * inten; | ||
| 227 | lights.ambient[1] += g * inten; | ||
| 228 | lights.ambient[2] += b * inten; | ||
| 229 | } | ||
| 230 | "LightDirectional" => { | ||
| 231 | let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; | ||
| 232 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 233 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 234 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 235 | // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! | ||
| 236 | let dx = world[8]; | ||
| 237 | let dy = world[9]; | ||
| 238 | let dz = world[10]; | ||
| 239 | let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); | ||
| 240 | lights.dir_to_light = [dx / len, dy / len, dz / len]; | ||
| 241 | lights.dir_color = [r * inten, g * inten, b * inten]; | ||
| 242 | lights.has_dir = true; | ||
| 243 | } | ||
| 244 | "LightPoint" => { | ||
| 245 | let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; | ||
| 246 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 247 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 248 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 249 | let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; | ||
| 250 | let decay_rate = comp.eval_number(node, "DecayRate", time, 1.0, expr) as f32; | ||
| 251 | lights.points.push(PointLight { | ||
| 252 | pos: [world[12], world[13], world[14]], | ||
| 253 | color: [r * inten, g * inten, b * inten], | ||
| 254 | decay_type, | ||
| 255 | decay_rate, | ||
| 256 | }); | ||
| 257 | } | ||
| 258 | "LightSpot" => { | ||
| 259 | let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; | ||
| 260 | let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; | ||
| 261 | let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; | ||
| 262 | let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; | ||
| 263 | let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; | ||
| 264 | let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; | ||
| 265 | let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; | ||
| 266 | // SpotLight shines along -Z in local space | ||
| 267 | let dx = -world[8]; | ||
| 268 | let dy = -world[9]; | ||
| 269 | let dz = -world[10]; | ||
| 270 | let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); | ||
| 271 | let half_cone = (cone_deg * 0.5).max(0.5); | ||
| 272 | let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5); | ||
| 273 | let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg); | ||
| 274 | lights.spots.push(SpotLight { | ||
| 275 | pos: [world[12], world[13], world[14]], | ||
| 276 | dir: [dx / len, dy / len, dz / len], | ||
| 277 | color: [r * inten, g * inten, b * inten], | ||
| 278 | cos_inner: inner_deg.to_radians().cos(), | ||
| 279 | cos_outer: outer_deg.to_radians().cos(), | ||
| 280 | decay_type, | ||
| 281 | }); | ||
| 282 | } | ||
| 283 | "ImagePlane3D" => { | ||
| 284 | let mat_node = ovr.material_override.or_else(|| { | ||
| 285 | node.connected_node("MaterialInput") | ||
| 286 | .or_else(|| node.connected_node("SceneInput")) | ||
| 287 | .and_then(|s| comp.find_node(s)) | ||
| 288 | }); | ||
| 289 | let mat = resolve_material(comp, mat_node, time, expr); | ||
| 290 | meshes.push(MeshInstance { | ||
| 291 | world, | ||
| 292 | shape: ShapeKind::ImagePlane, | ||
| 293 | material_node: mat.tex_node, | ||
| 294 | text3d: None, | ||
| 295 | diffuse_col: mat.diffuse_col, | ||
| 296 | specular_col: mat.specular_col, | ||
| 297 | specular_intensity: mat.specular_intensity, | ||
| 298 | specular_exponent: mat.specular_exponent, | ||
| 299 | affected_by_lights: ovr.affected_by_lights.unwrap_or(true), | ||
| 300 | flip_normals: ovr.flip_normals, | ||
| 301 | displace: ovr.displace.clone(), | ||
| 302 | }); | ||
| 303 | } | ||
| 304 | "Shape3D" => { | ||
| 305 | let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); | ||
| 306 | let disp_sub = if ovr.displace.is_some() { 32 } else { 1 }; | ||
| 307 | let shape = match shape_name { | ||
| 308 | "SurfaceSphereInputs" => ShapeKind::Sphere { | ||
| 309 | // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) | ||
| 310 | radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32, | ||
| 311 | sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 32.0, expr).round() as u32, | ||
| 312 | sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32, | ||
| 313 | }, | ||
| 314 | "SurfaceCylinderInputs" => { | ||
| 315 | let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32; | ||
| 316 | let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32; | ||
| 317 | ShapeKind::Cylinder { | ||
| 318 | radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 0.5, expr) as f32, | ||
| 319 | height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 1.0, expr) as f32, | ||
| 320 | start_sweep_deg: start_sw, | ||
| 321 | end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, | ||
| 322 | sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32, | ||
| 323 | } | ||
| 324 | } | ||
| 325 | "SurfaceCubeInputs" => { | ||
| 326 | let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr); | ||
| 327 | ShapeKind::Cube { | ||
| 328 | width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32, | ||
| 329 | height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32, | ||
| 330 | depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32, | ||
| 331 | } | ||
| 332 | } | ||
| 333 | _ => { | ||
| 334 | let sw = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; | ||
| 335 | let sh = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionHeight", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; | ||
| 336 | ShapeKind::Plane { | ||
| 337 | width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32, | ||
| 338 | height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32, | ||
| 339 | sub_w: sw, | ||
| 340 | sub_h: sh, | ||
| 341 | } | ||
| 342 | } | ||
| 343 | }; | ||
| 344 | let mat_node = ovr.material_override.or_else(|| { | ||
| 345 | node.connected_node("MaterialInput") | ||
| 346 | .and_then(|s| comp.find_node(s)) | ||
| 347 | }); | ||
| 348 | let mut mat = resolve_material(comp, mat_node, time, expr); | ||
| 349 | if mat_node.is_none() { | ||
| 350 | mat.diffuse_col = [ | ||
| 351 | comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32, | ||
| 352 | comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32, | ||
| 353 | comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32, | ||
| 354 | comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32, | ||
| 355 | ]; | ||
| 356 | } | ||
| 357 | meshes.push(MeshInstance { | ||
| 358 | world, | ||
| 359 | shape, | ||
| 360 | material_node: mat.tex_node, | ||
| 361 | text3d: None, | ||
| 362 | diffuse_col: mat.diffuse_col, | ||
| 363 | specular_col: mat.specular_col, | ||
| 364 | specular_intensity: mat.specular_intensity, | ||
| 365 | specular_exponent: mat.specular_exponent, | ||
| 366 | affected_by_lights: ovr.affected_by_lights.unwrap_or(true), | ||
| 367 | flip_normals: ovr.flip_normals, | ||
| 368 | displace: ovr.displace.clone(), | ||
| 369 | }); | ||
| 370 | } | ||
| 371 | "Text3D" => { | ||
| 372 | let ext_depth = comp.eval_number(node, "Extrusion.ExtrusionDepth", time, 0.0, expr) as f32; | ||
| 373 | let mat_node = ovr.material_override.or_else(|| { | ||
| 374 | node.connected_node("MaterialInput") | ||
| 375 | .and_then(|s| comp.find_node(s)) | ||
| 376 | }); | ||
| 377 | let mut mat = resolve_material(comp, mat_node, time, expr); | ||
| 378 | if mat_node.is_none() { | ||
| 379 | mat.diffuse_col = [1.0, 1.0, 1.0, 1.0]; | ||
| 380 | } | ||
| 381 | // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate) | ||
| 382 | meshes.push(MeshInstance { | ||
| 383 | world, | ||
| 384 | shape: ShapeKind::TextPlate { | ||
| 385 | width: 4.0, | ||
| 386 | height: 2.0, | ||
| 387 | depth: ext_depth, | ||
| 388 | slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 }, | ||
| 389 | }, | ||
| 390 | material_node: mat.tex_node, | ||
| 391 | text3d: Some(Text3DSpec { node_id }), | ||
| 392 | diffuse_col: mat.diffuse_col, | ||
| 393 | specular_col: mat.specular_col, | ||
| 394 | specular_intensity: mat.specular_intensity, | ||
| 395 | specular_exponent: mat.specular_exponent, | ||
| 396 | affected_by_lights: ovr.affected_by_lights.unwrap_or(true), | ||
| 397 | flip_normals: ovr.flip_normals, | ||
| 398 | displace: ovr.displace.clone(), | ||
| 399 | }); | ||
| 400 | } | ||
| 401 | "MacroOperator" | "GroupOperator" => { | ||
| 402 | if let Some(out_id) = node.macro_output { | ||
| 403 | collect_scene_inner(comp, out_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); | ||
| 404 | } | ||
| 405 | } | ||
| 406 | _ => {} | ||
| 407 | } | ||
| 408 | } | ||
| 409 | |||
| 410 | struct ResolvedMaterial { | ||
| 411 | tex_node: Option<NodeId>, | ||
| 412 | diffuse_col: [f32; 4], | ||
| 413 | specular_col: [f32; 3], | ||
| 414 | specular_intensity: f32, | ||
| 415 | specular_exponent: f32, | ||
| 416 | } | ||
| 417 | |||
| 418 | /// Resolves a 3D material input (either a 2D image node, `Texture2DOperator`, or a Fusion 3D | ||
| 419 | /// material like `MtlBlinn` / `MtlCookTorrance` / `MtlPhong`). | ||
| 420 | fn resolve_material( | ||
| 421 | comp: &Comp, | ||
| 422 | mat_node: Option<NodeId>, | ||
| 423 | time: f64, | ||
| 424 | expr: &ExprEngine, | ||
| 425 | ) -> ResolvedMaterial { | ||
| 426 | let default_mat = ResolvedMaterial { | ||
| 427 | tex_node: None, | ||
| 428 | diffuse_col: [1.0, 1.0, 1.0, 1.0], | ||
| 429 | specular_col: [1.0, 1.0, 1.0], | ||
| 430 | specular_intensity: 0.15, | ||
| 431 | specular_exponent: 25.0, | ||
| 432 | }; | ||
| 433 | let Some(mid) = mat_node else { | ||
| 434 | return default_mat; | ||
| 435 | }; | ||
| 436 | let n = comp.node(mid); | ||
| 437 | match n.kind.as_str() { | ||
| 438 | "Texture2DOperator" => { | ||
| 439 | let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s)); | ||
| 440 | ResolvedMaterial { | ||
| 441 | tex_node: tex_src, | ||
| 442 | ..default_mat | ||
| 443 | } | ||
| 444 | } | ||
| 445 | "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" => { | ||
| 446 | let mut diff_tex = n | ||
| 447 | .connected_node("Diffuse.Color.Material") | ||
| 448 | .or_else(|| n.connected_node("MaterialInput")) | ||
| 449 | .and_then(|s| comp.find_node(s)); | ||
| 450 | // Unwrap Texture2DOperator if feeding Diffuse.Color.Material | ||
| 451 | if let Some(tid) = diff_tex { | ||
| 452 | if comp.node(tid).kind == "Texture2DOperator" { | ||
| 453 | diff_tex = comp.node(tid).connected_node("Input").and_then(|s| comp.find_node(s)); | ||
| 454 | } | ||
| 455 | } | ||
| 456 | let col = [ | ||
| 457 | comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32, | ||
| 458 | comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32, | ||
| 459 | comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32, | ||
| 460 | comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32, | ||
| 461 | ]; | ||
| 462 | let spec_col = [ | ||
| 463 | comp.eval_number(n, "Specular.Color.Red", time, 1.0, expr) as f32, | ||
| 464 | comp.eval_number(n, "Specular.Color.Green", time, 1.0, expr) as f32, | ||
| 465 | comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32, | ||
| 466 | ]; | ||
| 467 | let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32; | ||
| 468 | let (spec_exp, spec_gain) = if n.kind == "MtlCookTorrance" { | ||
| 469 | let rough = comp.eval_number(n, "Specular.Roughness", time, 0.4, expr).clamp(0.05, 1.0) as f32; | ||
| 470 | ((2.0 / (rough * rough) - 2.0).max(2.0), 0.15) | ||
| 471 | } else { | ||
| 472 | (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0) | ||
| 473 | }; | ||
| 474 | ResolvedMaterial { | ||
| 475 | tex_node: diff_tex, | ||
| 476 | diffuse_col: col, | ||
| 477 | specular_col: spec_col, | ||
| 478 | specular_intensity: spec_int.clamp(0.0, 4.0) * spec_gain, | ||
| 479 | specular_exponent: spec_exp, | ||
| 480 | } | ||
| 481 | } | ||
| 482 | _ => ResolvedMaterial { | ||
| 483 | tex_node: Some(mid), | ||
| 484 | ..default_mat | ||
| 485 | }, | ||
| 486 | } | ||
| 487 | } | ||
| 488 | |||
| 489 | fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { | ||
| 490 | let tx = comp.eval_number(node, "Translate.X", time, comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr), expr) as f32; | ||
| 491 | let ty = comp.eval_number(node, "Translate.Y", time, comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr), expr) as f32; | ||
| 492 | let tz = comp.eval_number(node, "Translate.Z", time, comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr), expr) as f32; | ||
| 493 | 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(); | ||
| 494 | 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(); | ||
| 495 | 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(); | ||
| 496 | let sx = comp.eval_number(node, "Scale.X", time, comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr), expr) as f32; | ||
| 497 | let sy = comp.eval_number(node, "Scale.Y", time, comp.eval_number(node, "Transform3DOp.Scale.Y", time, sx as f64, expr), expr) as f32; | ||
| 498 | let sz = comp.eval_number(node, "Scale.Z", time, comp.eval_number(node, "Transform3DOp.Scale.Z", time, sx as f64, expr), expr) as f32; | ||
| 499 | let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))); | ||
| 500 | mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz))) | ||
| 501 | } | ||
| 502 | |||
| 503 | pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { | ||
| 504 | let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32; | ||
| 505 | let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32; | ||
| 506 | let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32; | ||
| 507 | |||
| 508 | let rx = (comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr) as f32).to_radians(); | ||
| 509 | let ry = (comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr) as f32).to_radians(); | ||
| 510 | let rz = (comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr) as f32).to_radians(); | ||
| 511 | let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ"); | ||
| 512 | |||
| 513 | let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5; | ||
| 514 | let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32; | ||
| 515 | let sy = if scale_lock { | ||
| 516 | sx | ||
| 517 | } else { | ||
| 518 | comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32 | ||
| 519 | }; | ||
| 520 | let sz = if scale_lock { | ||
| 521 | sx | ||
| 522 | } else { | ||
| 523 | comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32 | ||
| 524 | }; | ||
| 525 | |||
| 526 | let px = comp.eval_number(node, "Transform3DOp.Pivot.X", time, 0.0, expr) as f32; | ||
| 527 | let py = comp.eval_number(node, "Transform3DOp.Pivot.Y", time, 0.0, expr) as f32; | ||
| 528 | let pz = comp.eval_number(node, "Transform3DOp.Pivot.Z", time, 0.0, expr) as f32; | ||
| 529 | |||
| 530 | let mx = mat4_rot_x(rx); | ||
| 531 | let my = mat4_rot_y(ry); | ||
| 532 | let mz = mat4_rot_z(rz); | ||
| 533 | let rot = match rot_order { | ||
| 534 | "XZY" => mat4_mul(my, mat4_mul(mz, mx)), | ||
| 535 | "YXZ" => mat4_mul(mz, mat4_mul(mx, my)), | ||
| 536 | "YZX" => mat4_mul(mx, mat4_mul(mz, my)), | ||
| 537 | "ZXY" => mat4_mul(my, mat4_mul(mx, mz)), | ||
| 538 | "ZYX" => mat4_mul(mx, mat4_mul(my, mz)), | ||
| 539 | _ => mat4_mul(mz, mat4_mul(my, mx)), // XYZ default | ||
| 540 | }; | ||
| 541 | |||
| 542 | let t = mat4_translate(tx + px, ty + py, tz + pz); | ||
| 543 | let s = mat4_scale(sx, sy, sz); | ||
| 544 | let inv_p = mat4_translate(-px, -py, -pz); | ||
| 545 | mat4_mul(t, mat4_mul(rot, mat4_mul(s, inv_p))) | ||
| 546 | } | ||
| 547 | |||
| 548 | #[cfg(test)] | ||
| 549 | mod tests { | ||
| 550 | use super::*; | ||
| 551 | |||
| 552 | #[test] | ||
| 553 | fn test_collect_scene_archive_3d_nodes() { | ||
| 554 | let src = r#"Composition { | ||
| 555 | CurrentTime = 0, | ||
| 556 | RenderRange = { 0, 10 }, | ||
| 557 | GlobalRange = { 0, 10 }, | ||
| 558 | Tools = ordered() { | ||
| 559 | BG1 = Background { | ||
| 560 | Inputs = { | ||
| 561 | Width = Input { Value = 64, }, | ||
| 562 | Height = Input { Value = 64, }, | ||
| 563 | }, | ||
| 564 | }, | ||
| 565 | Tex2D = Texture2DOperator { | ||
| 566 | Inputs = { | ||
| 567 | Input = Input { SourceOp = "BG1", Source = "Output", }, | ||
| 568 | }, | ||
| 569 | }, | ||
| 570 | Blinn1 = MtlBlinn { | ||
| 571 | Inputs = { | ||
| 572 | ["Diffuse.Color.Red"] = Input { Value = 0.8, }, | ||
| 573 | ["Diffuse.Color.Material"] = Input { SourceOp = "Tex2D", Source = "MaterialOutput", }, | ||
| 574 | ["Specular.Intensity"] = Input { Value = 0.75, }, | ||
| 575 | ["Specular.Exponent"] = Input { Value = 40.0, }, | ||
| 576 | }, | ||
| 577 | }, | ||
| 578 | Cook1 = MtlCookTorrance { | ||
| 579 | Inputs = { | ||
| 580 | ["Diffuse.Color.Green"] = Input { Value = 0.6, }, | ||
| 581 | ["Specular.Roughness"] = Input { Value = 0.25, }, | ||
| 582 | }, | ||
| 583 | }, | ||
| 584 | Shape1 = Shape3D { | ||
| 585 | Inputs = { | ||
| 586 | Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, | ||
| 587 | MaterialInput = Input { SourceOp = "Blinn1", Source = "MaterialOutput", }, | ||
| 588 | }, | ||
| 589 | }, | ||
| 590 | RepMat = ReplaceMaterial3D { | ||
| 591 | Inputs = { | ||
| 592 | SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, | ||
| 593 | MaterialInput = Input { SourceOp = "Cook1", Source = "MaterialOutput", }, | ||
| 594 | }, | ||
| 595 | }, | ||
| 596 | RepNorm = ReplaceNormals3D { | ||
| 597 | Inputs = { | ||
| 598 | SceneInput = Input { SourceOp = "RepMat", Source = "Output", }, | ||
| 599 | FlipNormals = Input { Value = 1, }, | ||
| 600 | }, | ||
| 601 | }, | ||
| 602 | Disp1 = Displace3D { | ||
| 603 | Inputs = { | ||
| 604 | SceneInput = Input { SourceOp = "RepNorm", Source = "Output", }, | ||
| 605 | Input = Input { SourceOp = "BG1", Source = "Output", }, | ||
| 606 | Scale = Input { Value = 0.2, }, | ||
| 607 | }, | ||
| 608 | }, | ||
| 609 | Dup1 = Duplicate3D { | ||
| 610 | Inputs = { | ||
| 611 | SceneInput = Input { SourceOp = "Disp1", Source = "Output", }, | ||
| 612 | FirstCopy = Input { Value = 0, }, | ||
| 613 | LastCopy = Input { Value = 2, }, | ||
| 614 | ["Translate.X"] = Input { Value = 1.5, }, | ||
| 615 | }, | ||
| 616 | }, | ||
| 617 | OvrHide = Override3D { | ||
| 618 | Inputs = { | ||
| 619 | SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, | ||
| 620 | ["Visibility.DoVisible"] = Input { Value = 1, }, | ||
| 621 | ["Visibility.IsVisible"] = Input { Value = 0, }, | ||
| 622 | }, | ||
| 623 | }, | ||
| 624 | Txt1 = Text3D { | ||
| 625 | Inputs = { | ||
| 626 | StyledText = Input { Value = "HI", }, | ||
| 627 | ["Extrusion.ExtrusionDepth"] = Input { Value = 0.15, }, | ||
| 628 | }, | ||
| 629 | }, | ||
| 630 | Pt1 = LightPoint { | ||
| 631 | Inputs = { | ||
| 632 | Intensity = Input { Value = 2.0, }, | ||
| 633 | DecayType = Input { Value = 1, }, | ||
| 634 | ["Transform3DOp.Translate.X"] = Input { Value = 3.0, }, | ||
| 635 | }, | ||
| 636 | }, | ||
| 637 | Sp1 = LightSpot { | ||
| 638 | Inputs = { | ||
| 639 | Intensity = Input { Value = 1.5, }, | ||
| 640 | ConeAngle = Input { Value = 45.0, }, | ||
| 641 | PenumbraAngle = Input { Value = 10.0, }, | ||
| 642 | }, | ||
| 643 | }, | ||
| 644 | Cam1 = Camera3D { | ||
| 645 | Inputs = { | ||
| 646 | ["Transform3DOp.Translate.Z"] = Input { Value = 5.0, }, | ||
| 647 | }, | ||
| 648 | }, | ||
| 649 | Merge1 = Merge3D { | ||
| 650 | Inputs = { | ||
| 651 | SceneInput1 = Input { SourceOp = "Dup1", Source = "Output", }, | ||
| 652 | SceneInput2 = Input { SourceOp = "OvrHide", Source = "Output", }, | ||
| 653 | SceneInput3 = Input { SourceOp = "Txt1", Source = "Output", }, | ||
| 654 | SceneInput4 = Input { SourceOp = "Pt1", Source = "Output", }, | ||
| 655 | SceneInput5 = Input { SourceOp = "Sp1", Source = "Output", }, | ||
| 656 | SceneInput6 = Input { SourceOp = "Cam1", Source = "Output", }, | ||
| 657 | }, | ||
| 658 | }, | ||
| 659 | }, | ||
| 660 | }"#; | ||
| 661 | let comp = Comp::from_fusion_str(src).expect("parse 3D test comp"); | ||
| 662 | let expr = ExprEngine::new(); | ||
| 663 | let merge_id = comp.find_node("Merge1").expect("Merge1"); | ||
| 664 | let mut cams = Vec::new(); | ||
| 665 | let mut meshes = Vec::new(); | ||
| 666 | let mut lights = SceneLights::default(); | ||
| 667 | collect_scene( | ||
| 668 | &comp, | ||
| 669 | merge_id, | ||
| 670 | 0.0, | ||
| 671 | &expr, | ||
| 672 | mat4_identity(), | ||
| 673 | 16.0 / 9.0, | ||
| 674 | &mut cams, | ||
| 675 | &mut meshes, | ||
| 676 | &mut lights, | ||
| 677 | 0, | ||
| 678 | ); | ||
| 679 | assert_eq!(cams.len(), 1); | ||
| 680 | // 3 copies from Duplicate3D (0..=2) + 1 Text3D (OvrHide suppresses its Shape1) | ||
| 681 | assert_eq!(meshes.len(), 4); | ||
| 682 | assert!(meshes[0].flip_normals); | ||
| 683 | assert!(meshes[0].displace.is_some()); | ||
| 684 | assert!((meshes[0].diffuse_col[1] - 0.6).abs() < 1e-4, "ReplaceMaterial3D should apply Cook1"); | ||
| 685 | assert!((meshes[2].world[12] - 3.0).abs() < 1e-4, "Duplicate3D copy 2 translated X=3.0"); | ||
| 686 | assert!(meshes[3].text3d.is_some()); | ||
| 687 | assert_eq!(lights.points.len(), 1); | ||
| 688 | assert!((lights.points[0].pos[0] - 3.0).abs() < 1e-4); | ||
| 689 | assert_eq!(lights.spots.len(), 1); | ||
| 690 | assert!(lights.spots[0].cos_inner > lights.spots[0].cos_outer); | ||
| 691 | } | ||
| 692 | } | ||
crates/engine/src/scene3d/math.rs created+100| ... | @@ -0,0 +1,100 @@ | ||
| 1 | //! Column-major 4x4 linear algebra helpers for 3D scene transforms and projection. | ||
| 2 | |||
| 3 | use super::Mat4; | ||
| 4 | |||
| 5 | pub fn mat4_identity() -> Mat4 { | ||
| 6 | [ | ||
| 7 | 1.0, 0.0, 0.0, 0.0, | ||
| 8 | 0.0, 1.0, 0.0, 0.0, | ||
| 9 | 0.0, 0.0, 1.0, 0.0, | ||
| 10 | 0.0, 0.0, 0.0, 1.0, | ||
| 11 | ] | ||
| 12 | } | ||
| 13 | |||
| 14 | pub fn mat4_mul(a: Mat4, b: Mat4) -> Mat4 { | ||
| 15 | let mut out = [0.0_f32; 16]; | ||
| 16 | for col in 0..4 { | ||
| 17 | for row in 0..4 { | ||
| 18 | out[col * 4 + row] = a[row] * b[col * 4] | ||
| 19 | + a[4 + row] * b[col * 4 + 1] | ||
| 20 | + a[8 + row] * b[col * 4 + 2] | ||
| 21 | + a[12 + row] * b[col * 4 + 3]; | ||
| 22 | } | ||
| 23 | } | ||
| 24 | out | ||
| 25 | } | ||
| 26 | |||
| 27 | pub fn mat4_translate(x: f32, y: f32, z: f32) -> Mat4 { | ||
| 28 | [ | ||
| 29 | 1.0, 0.0, 0.0, 0.0, | ||
| 30 | 0.0, 1.0, 0.0, 0.0, | ||
| 31 | 0.0, 0.0, 1.0, 0.0, | ||
| 32 | x, y, z, 1.0, | ||
| 33 | ] | ||
| 34 | } | ||
| 35 | |||
| 36 | pub fn mat4_scale(x: f32, y: f32, z: f32) -> Mat4 { | ||
| 37 | [ | ||
| 38 | x, 0.0, 0.0, 0.0, | ||
| 39 | 0.0, y, 0.0, 0.0, | ||
| 40 | 0.0, 0.0, z, 0.0, | ||
| 41 | 0.0, 0.0, 0.0, 1.0, | ||
| 42 | ] | ||
| 43 | } | ||
| 44 | |||
| 45 | pub fn mat4_rot_x(r: f32) -> Mat4 { | ||
| 46 | let (s, c) = r.sin_cos(); | ||
| 47 | [ | ||
| 48 | 1.0, 0.0, 0.0, 0.0, | ||
| 49 | 0.0, c, s, 0.0, | ||
| 50 | 0.0, -s, c, 0.0, | ||
| 51 | 0.0, 0.0, 0.0, 1.0, | ||
| 52 | ] | ||
| 53 | } | ||
| 54 | |||
| 55 | pub fn mat4_rot_y(r: f32) -> Mat4 { | ||
| 56 | let (s, c) = r.sin_cos(); | ||
| 57 | [ | ||
| 58 | c, 0.0, -s, 0.0, | ||
| 59 | 0.0, 1.0, 0.0, 0.0, | ||
| 60 | s, 0.0, c, 0.0, | ||
| 61 | 0.0, 0.0, 0.0, 1.0, | ||
| 62 | ] | ||
| 63 | } | ||
| 64 | |||
| 65 | pub fn mat4_rot_z(r: f32) -> Mat4 { | ||
| 66 | let (s, c) = r.sin_cos(); | ||
| 67 | [ | ||
| 68 | c, s, 0.0, 0.0, | ||
| 69 | -s, c, 0.0, 0.0, | ||
| 70 | 0.0, 0.0, 1.0, 0.0, | ||
| 71 | 0.0, 0.0, 0.0, 1.0, | ||
| 72 | ] | ||
| 73 | } | ||
| 74 | |||
| 75 | pub fn mat4_inverse_rigid(m: Mat4) -> Mat4 { | ||
| 76 | let r00 = m[0]; let r10 = m[1]; let r20 = m[2]; | ||
| 77 | let r01 = m[4]; let r11 = m[5]; let r21 = m[6]; | ||
| 78 | let r02 = m[8]; let r12 = m[9]; let r22 = m[10]; | ||
| 79 | let tx = m[12]; let ty = m[13]; let tz = m[14]; | ||
| 80 | let itx = -(r00 * tx + r10 * ty + r20 * tz); | ||
| 81 | let ity = -(r01 * tx + r11 * ty + r21 * tz); | ||
| 82 | let itz = -(r02 * tx + r12 * ty + r22 * tz); | ||
| 83 | [ | ||
| 84 | r00, r01, r02, 0.0, | ||
| 85 | r10, r11, r12, 0.0, | ||
| 86 | r20, r21, r22, 0.0, | ||
| 87 | itx, ity, itz, 1.0, | ||
| 88 | ] | ||
| 89 | } | ||
| 90 | |||
| 91 | pub fn mat4_perspective_wgpu(vfov_rad: f32, aspect: f32, near: f32, far: f32) -> Mat4 { | ||
| 92 | let f = 1.0 / (vfov_rad * 0.5).tan().max(1e-5); | ||
| 93 | let nf = 1.0 / (near - far); | ||
| 94 | [ | ||
| 95 | f / aspect.max(1e-4), 0.0, 0.0, 0.0, | ||
| 96 | 0.0, f, 0.0, 0.0, | ||
| 97 | 0.0, 0.0, far * nf, -1.0, | ||
| 98 | 0.0, 0.0, far * near * nf, 0.0, | ||
| 99 | ] | ||
| 100 | } | ||
crates/engine/src/scene3d/mesh.rs created+251| ... | @@ -0,0 +1,251 @@ | ||
| 1 | //! Procedural 3D mesh builders and heightmap vertex displacement. | ||
| 2 | |||
| 3 | use super::shader::Vertex3D; | ||
| 4 | use super::{DisplaceHeightmap, ShapeKind}; | ||
| 5 | |||
| 6 | pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) { | ||
| 7 | match *shape { | ||
| 8 | ShapeKind::ImagePlane => build_image_plane(tex_aspect), | ||
| 9 | ShapeKind::Plane { width, height, sub_w, sub_h } => build_plane(width, height, sub_w, sub_h), | ||
| 10 | ShapeKind::TextPlate { width, height, depth, slices } => { | ||
| 11 | build_text_plate(width, height, depth, slices) | ||
| 12 | } | ||
| 13 | ShapeKind::Sphere { radius, sub_base, sub_height } => { | ||
| 14 | build_sphere(radius, sub_base, sub_height) | ||
| 15 | } | ||
| 16 | ShapeKind::Cylinder { | ||
| 17 | radius, | ||
| 18 | height, | ||
| 19 | start_sweep_deg, | ||
| 20 | end_sweep_deg, | ||
| 21 | sub_base, | ||
| 22 | } => build_cylinder(radius, height, start_sweep_deg, end_sweep_deg, sub_base), | ||
| 23 | ShapeKind::Cube { width, height, depth } => build_cube(width, height, depth), | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | fn build_image_plane(tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) { | ||
| 28 | let hx = 0.5; | ||
| 29 | let hy = 0.5 / tex_aspect.max(1e-4); | ||
| 30 | let verts = vec![ | ||
| 31 | Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] }, | ||
| 32 | Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, | ||
| 33 | Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, | ||
| 34 | Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] }, | ||
| 35 | ]; | ||
| 36 | (verts, vec![0, 1, 2, 0, 2, 3]) | ||
| 37 | } | ||
| 38 | |||
| 39 | fn build_plane(width: f32, height: f32, sub_w: u32, sub_h: u32) -> (Vec<Vertex3D>, Vec<u32>) { | ||
| 40 | let sw = sub_w.clamp(1, 64); | ||
| 41 | let sh = sub_h.clamp(1, 64); | ||
| 42 | let hx = width * 0.5; | ||
| 43 | let hy = height * 0.5; | ||
| 44 | let mut verts = Vec::with_capacity(((sw + 1) * (sh + 1)) as usize); | ||
| 45 | let mut idx = Vec::with_capacity((sw * sh * 6) as usize); | ||
| 46 | for iy in 0..=sh { | ||
| 47 | let v = iy as f32 / sh as f32; | ||
| 48 | let y = hy - v * height; | ||
| 49 | for ix in 0..=sw { | ||
| 50 | let u = ix as f32 / sw as f32; | ||
| 51 | let x = -hx + u * width; | ||
| 52 | verts.push(Vertex3D { pos: [x, y, 0.0], normal: [0.0, 0.0, 1.0], uv: [u, v] }); | ||
| 53 | } | ||
| 54 | } | ||
| 55 | let row = sw + 1; | ||
| 56 | for iy in 0..sh { | ||
| 57 | for ix in 0..sw { | ||
| 58 | let a = iy * row + ix; | ||
| 59 | let b = (iy + 1) * row + ix; | ||
| 60 | let c = (iy + 1) * row + ix + 1; | ||
| 61 | let d = iy * row + ix + 1; | ||
| 62 | idx.extend_from_slice(&[a, b, c, a, c, d]); | ||
| 63 | } | ||
| 64 | } | ||
| 65 | (verts, idx) | ||
| 66 | } | ||
| 67 | |||
| 68 | fn build_text_plate(width: f32, height: f32, depth: f32, slices: u32) -> (Vec<Vertex3D>, Vec<u32>) { | ||
| 69 | let hx = width * 0.5; | ||
| 70 | let hy = height * 0.5; | ||
| 71 | let n_slices = if depth.abs() > 1e-4 { slices.clamp(2, 16) } else { 1 }; | ||
| 72 | let mut verts = Vec::with_capacity((n_slices * 4) as usize); | ||
| 73 | let mut idx = Vec::with_capacity((n_slices * 6) as usize); | ||
| 74 | for s in 0..n_slices { | ||
| 75 | let t = if n_slices == 1 { 0.0 } else { s as f32 / (n_slices - 1) as f32 }; | ||
| 76 | // Fusion Text3D extrudes backward along -Z from z=0 to z=-depth | ||
| 77 | let z = -t * depth; | ||
| 78 | let nz = if n_slices > 1 && s == n_slices - 1 { -1.0 } else { 1.0 }; | ||
| 79 | let base = verts.len() as u32; | ||
| 80 | verts.push(Vertex3D { pos: [-hx, hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 0.0] }); | ||
| 81 | verts.push(Vertex3D { pos: [-hx, -hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 1.0] }); | ||
| 82 | verts.push(Vertex3D { pos: [ hx, -hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 1.0] }); | ||
| 83 | verts.push(Vertex3D { pos: [ hx, hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 0.0] }); | ||
| 84 | idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); | ||
| 85 | } | ||
| 86 | (verts, idx) | ||
| 87 | } | ||
| 88 | |||
| 89 | fn build_sphere(radius: f32, sub_base: u32, sub_height: u32) -> (Vec<Vertex3D>, Vec<u32>) { | ||
| 90 | let seg_u = sub_base.clamp(12, 96); | ||
| 91 | let seg_v = sub_height.clamp(8, 64); | ||
| 92 | let mut verts = Vec::with_capacity(((seg_u + 1) * (seg_v + 1)) as usize); | ||
| 93 | let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize); | ||
| 94 | for iv in 0..=seg_v { | ||
| 95 | let v = iv as f32 / seg_v as f32; | ||
| 96 | let phi = v * std::f32::consts::PI; // 0 (top +Y) -> PI (bottom -Y) | ||
| 97 | let (sp, cp) = phi.sin_cos(); | ||
| 98 | for iu in 0..=seg_u { | ||
| 99 | let u = iu as f32 / seg_u as f32; | ||
| 100 | // Fusion Shape3D Sphere places u=0.75 facing +Z (verified via probe_archive_3d f02) | ||
| 101 | let theta = (u - 0.75) * std::f32::consts::TAU; | ||
| 102 | let (st, ct) = theta.sin_cos(); | ||
| 103 | let nx = sp * st; | ||
| 104 | let ny = cp; | ||
| 105 | let nz = sp * ct; | ||
| 106 | verts.push(Vertex3D { | ||
| 107 | pos: [nx * radius, ny * radius, nz * radius], | ||
| 108 | normal: [nx, ny, nz], | ||
| 109 | uv: [u, v], | ||
| 110 | }); | ||
| 111 | } | ||
| 112 | } | ||
| 113 | let row = seg_u + 1; | ||
| 114 | for iv in 0..seg_v { | ||
| 115 | for iu in 0..seg_u { | ||
| 116 | let a = iv * row + iu; | ||
| 117 | let b = (iv + 1) * row + iu; | ||
| 118 | let c = (iv + 1) * row + iu + 1; | ||
| 119 | let d = iv * row + iu + 1; | ||
| 120 | idx.extend_from_slice(&[a, b, c, a, c, d]); | ||
| 121 | } | ||
| 122 | } | ||
| 123 | (verts, idx) | ||
| 124 | } | ||
| 125 | |||
| 126 | fn build_cylinder( | ||
| 127 | radius: f32, | ||
| 128 | height: f32, | ||
| 129 | start_sweep_deg: f32, | ||
| 130 | end_sweep_deg: f32, | ||
| 131 | sub_base: u32, | ||
| 132 | ) -> (Vec<Vertex3D>, Vec<u32>) { | ||
| 133 | let seg_u = sub_base.clamp(16, 96); | ||
| 134 | let half_h = height * 0.5; | ||
| 135 | let a0 = start_sweep_deg.to_radians(); | ||
| 136 | let a1 = end_sweep_deg.to_radians(); | ||
| 137 | let mut verts = Vec::with_capacity(((seg_u + 1) * 2) as usize); | ||
| 138 | let mut idx = Vec::with_capacity((seg_u * 6) as usize); | ||
| 139 | for iu in 0..=seg_u { | ||
| 140 | let u = iu as f32 / seg_u as f32; | ||
| 141 | // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc | ||
| 142 | let theta = a0 + (a1 - a0) * u; | ||
| 143 | let (st, ct) = theta.sin_cos(); | ||
| 144 | let nx = ct; | ||
| 145 | let nz = st; | ||
| 146 | verts.push(Vertex3D { | ||
| 147 | pos: [nx * radius, half_h, nz * radius], | ||
| 148 | normal: [nx, 0.0, nz], | ||
| 149 | uv: [1.0 - u, 0.0], | ||
| 150 | }); | ||
| 151 | verts.push(Vertex3D { | ||
| 152 | pos: [nx * radius, -half_h, nz * radius], | ||
| 153 | normal: [nx, 0.0, nz], | ||
| 154 | uv: [1.0 - u, 1.0], | ||
| 155 | }); | ||
| 156 | } | ||
| 157 | for iu in 0..seg_u { | ||
| 158 | let a = iu * 2; | ||
| 159 | let b = a + 1; | ||
| 160 | let c = a + 3; | ||
| 161 | let d = a + 2; | ||
| 162 | idx.extend_from_slice(&[a, b, c, a, c, d]); | ||
| 163 | } | ||
| 164 | (verts, idx) | ||
| 165 | } | ||
| 166 | |||
| 167 | fn build_cube(width: f32, height: f32, depth: f32) -> (Vec<Vertex3D>, Vec<u32>) { | ||
| 168 | let hx = width * 0.5; | ||
| 169 | let hy = height * 0.5; | ||
| 170 | let hz = depth * 0.5; | ||
| 171 | let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [ | ||
| 172 | ([0.0, 0.0, 1.0], [[-hx, hy, hz], [-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz]]), | ||
| 173 | ([0.0, 0.0, -1.0], [[hx, hy, -hz], [hx, -hy, -hz], [-hx, -hy, -hz], [-hx, hy, -hz]]), | ||
| 174 | ([1.0, 0.0, 0.0], [[hx, hy, hz], [hx, -hy, hz], [hx, -hy, -hz], [hx, hy, -hz]]), | ||
| 175 | ([-1.0, 0.0, 0.0], [[-hx, hy, -hz], [-hx, -hy, -hz], [-hx, -hy, hz], [-hx, hy, hz]]), | ||
| 176 | ([0.0, 1.0, 0.0], [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]]), | ||
| 177 | ([0.0, -1.0, 0.0], [[-hx, -hy, hz], [-hx, -hy, -hz], [hx, -hy, -hz], [hx, -hy, hz]]), | ||
| 178 | ]; | ||
| 179 | let mut verts = Vec::with_capacity(24); | ||
| 180 | let mut idx = Vec::with_capacity(36); | ||
| 181 | for (n, corners) in faces { | ||
| 182 | let base = verts.len() as u32; | ||
| 183 | let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]; | ||
| 184 | for (p, uv) in corners.into_iter().zip(uvs) { | ||
| 185 | verts.push(Vertex3D { pos: p, normal: n, uv }); | ||
| 186 | } | ||
| 187 | idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); | ||
| 188 | } | ||
| 189 | (verts, idx) | ||
| 190 | } | ||
| 191 | |||
| 192 | pub(super) fn apply_heightmap_displace( | ||
| 193 | verts: &mut [Vertex3D], | ||
| 194 | indices: &[u32], | ||
| 195 | disp: &DisplaceHeightmap, | ||
| 196 | ) { | ||
| 197 | let w = disp.size[0].max(1) as usize; | ||
| 198 | let h = disp.size[1].max(1) as usize; | ||
| 199 | if disp.rgba.len() < w * h * 4 { | ||
| 200 | return; | ||
| 201 | } | ||
| 202 | for v in verts.iter_mut() { | ||
| 203 | let px = ((v.uv[0].clamp(0.0, 1.0)) * (w - 1) as f32).round() as usize; | ||
| 204 | let py = ((v.uv[1].clamp(0.0, 1.0)) * (h - 1) as f32).round() as usize; | ||
| 205 | let off = (py * w + px) * 4; | ||
| 206 | let r = disp.rgba[off] as f32 / 255.0; | ||
| 207 | let g = disp.rgba[off + 1] as f32 / 255.0; | ||
| 208 | let b = disp.rgba[off + 2] as f32 / 255.0; | ||
| 209 | let a = disp.rgba[off + 3] as f32 / 255.0; | ||
| 210 | let sample = match disp.channel { | ||
| 211 | 0 => r, | ||
| 212 | 1 => g, | ||
| 213 | 2 => b, | ||
| 214 | 3 => a, | ||
| 215 | _ => 0.299 * r + 0.587 * g + 0.114 * b, | ||
| 216 | }; | ||
| 217 | let d = (sample - 0.5 + disp.bias) * disp.scale; | ||
| 218 | v.pos[0] += v.normal[0] * d; | ||
| 219 | v.pos[1] += v.normal[1] * d; | ||
| 220 | v.pos[2] += v.normal[2] * d; | ||
| 221 | } | ||
| 222 | // Recompute smooth vertex normals from displaced triangles | ||
| 223 | let mut acc = vec![[0.0_f32; 3]; verts.len()]; | ||
| 224 | for tri in indices.chunks_exact(3) { | ||
| 225 | let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize); | ||
| 226 | if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() { | ||
| 227 | continue; | ||
| 228 | } | ||
| 229 | let p0 = verts[i0].pos; | ||
| 230 | let p1 = verts[i1].pos; | ||
| 231 | let p2 = verts[i2].pos; | ||
| 232 | let e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]]; | ||
| 233 | let e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]]; | ||
| 234 | let fn_v = [ | ||
| 235 | e1[1] * e2[2] - e1[2] * e2[1], | ||
| 236 | e1[2] * e2[0] - e1[0] * e2[2], | ||
| 237 | e1[0] * e2[1] - e1[1] * e2[0], | ||
| 238 | ]; | ||
| 239 | for &i in &[i0, i1, i2] { | ||
| 240 | acc[i][0] += fn_v[0]; | ||
| 241 | acc[i][1] += fn_v[1]; | ||
| 242 | acc[i][2] += fn_v[2]; | ||
| 243 | } | ||
| 244 | } | ||
| 245 | for (v, n) in verts.iter_mut().zip(acc.into_iter()) { | ||
| 246 | let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); | ||
| 247 | if len > 1e-6 { | ||
| 248 | v.normal = [n[0] / len, n[1] / len, n[2] / len]; | ||
| 249 | } | ||
| 250 | } | ||
| 251 | } | ||
crates/engine/src/scene3d/mod.rs created+438| ... | @@ -0,0 +1,438 @@ | ||
| 1 | //! 3D scene graph & `wgpu` rasterizer for Fusion's `Renderer3D`, `Camera3D`, | ||
| 2 | //! `ImagePlane3D`, `Shape3D` (Sphere, Cylinder, Plane, Cube), `Merge3D`, `Transform3D`, | ||
| 3 | //! `LightAmbient`, `LightDirectional`, and `MtlCookTorrance` nodes. | ||
| 4 | //! | ||
| 5 | //! Matches Fusion's right-handed +Y-up / -Z-forward coordinate system, | ||
| 6 | //! `Transform3DOp` Euler rotation orders (`XYZ`, `XZY`, etc.), `ScaleLock`, | ||
| 7 | //! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection. | ||
| 8 | |||
| 9 | mod collect; | ||
| 10 | mod math; | ||
| 11 | mod mesh; | ||
| 12 | mod shader; | ||
| 13 | |||
| 14 | pub use collect::{collect_scene, eval_transform3d}; | ||
| 15 | pub use math::{ | ||
| 16 | mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y, | ||
| 17 | mat4_rot_z, mat4_scale, mat4_translate, | ||
| 18 | }; | ||
| 19 | |||
| 20 | use crate::cache::CachedTexture; | ||
| 21 | use mesh::{apply_heightmap_displace, build_shape_mesh}; | ||
| 22 | use model::NodeId; | ||
| 23 | use shader::{MeshUniform, SHADER_3D, Vertex3D}; | ||
| 24 | |||
| 25 | pub type Mat4 = [f32; 16]; // Column-major 4x4 | ||
| 26 | |||
| 27 | pub struct Scene3DRenderer { | ||
| 28 | bgl: wgpu::BindGroupLayout, | ||
| 29 | pipeline: wgpu::RenderPipeline, | ||
| 30 | sampler: wgpu::Sampler, | ||
| 31 | } | ||
| 32 | |||
| 33 | #[derive(Clone)] | ||
| 34 | pub struct CameraInstance { | ||
| 35 | pub world: Mat4, | ||
| 36 | pub vfov_rad: f32, | ||
| 37 | pub near: f32, | ||
| 38 | pub far: f32, | ||
| 39 | } | ||
| 40 | |||
| 41 | #[derive(Clone, Debug)] | ||
| 42 | pub enum ShapeKind { | ||
| 43 | ImagePlane, | ||
| 44 | Sphere { radius: f32, sub_base: u32, sub_height: u32 }, | ||
| 45 | Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 }, | ||
| 46 | Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, | ||
| 47 | Cube { width: f32, height: f32, depth: f32 }, | ||
| 48 | TextPlate { width: f32, height: f32, depth: f32, slices: u32 }, | ||
| 49 | } | ||
| 50 | |||
| 51 | #[derive(Clone, Debug)] | ||
| 52 | pub struct Displace3DSpec { | ||
| 53 | pub input_node: NodeId, | ||
| 54 | pub scale: f32, | ||
| 55 | pub bias: f32, | ||
| 56 | pub channel: i32, // 0=R, 1=G, 2=B, 3=A, 4=Luma (default) | ||
| 57 | } | ||
| 58 | |||
| 59 | #[derive(Clone, Debug)] | ||
| 60 | pub struct DisplaceHeightmap { | ||
| 61 | pub size: [u32; 2], | ||
| 62 | pub rgba: Vec<u8>, | ||
| 63 | pub scale: f32, | ||
| 64 | pub bias: f32, | ||
| 65 | pub channel: i32, | ||
| 66 | } | ||
| 67 | |||
| 68 | #[derive(Clone, Debug)] | ||
| 69 | pub struct Text3DSpec { | ||
| 70 | pub node_id: NodeId, | ||
| 71 | } | ||
| 72 | |||
| 73 | #[derive(Clone)] | ||
| 74 | pub struct MeshInstance { | ||
| 75 | pub world: Mat4, | ||
| 76 | pub shape: ShapeKind, | ||
| 77 | pub material_node: Option<NodeId>, | ||
| 78 | pub text3d: Option<Text3DSpec>, | ||
| 79 | pub diffuse_col: [f32; 4], | ||
| 80 | pub specular_col: [f32; 3], | ||
| 81 | pub specular_intensity: f32, | ||
| 82 | pub specular_exponent: f32, | ||
| 83 | pub affected_by_lights: bool, | ||
| 84 | pub flip_normals: bool, | ||
| 85 | pub displace: Option<Displace3DSpec>, | ||
| 86 | } | ||
| 87 | |||
| 88 | #[derive(Clone, Copy, Debug)] | ||
| 89 | pub struct PointLight { | ||
| 90 | pub pos: [f32; 3], | ||
| 91 | pub color: [f32; 3], | ||
| 92 | pub decay_type: f32, | ||
| 93 | pub decay_rate: f32, | ||
| 94 | } | ||
| 95 | |||
| 96 | #[derive(Clone, Copy, Debug)] | ||
| 97 | pub struct SpotLight { | ||
| 98 | pub pos: [f32; 3], | ||
| 99 | pub dir: [f32; 3], | ||
| 100 | pub color: [f32; 3], | ||
| 101 | pub cos_inner: f32, | ||
| 102 | pub cos_outer: f32, | ||
| 103 | pub decay_type: f32, | ||
| 104 | } | ||
| 105 | |||
| 106 | #[derive(Clone, Debug)] | ||
| 107 | pub struct SceneLights { | ||
| 108 | pub ambient: [f32; 3], | ||
| 109 | pub dir_to_light: [f32; 3], | ||
| 110 | pub dir_color: [f32; 3], | ||
| 111 | pub has_dir: bool, | ||
| 112 | pub points: Vec<PointLight>, | ||
| 113 | pub spots: Vec<SpotLight>, | ||
| 114 | } | ||
| 115 | |||
| 116 | impl Default for SceneLights { | ||
| 117 | fn default() -> Self { | ||
| 118 | Self { | ||
| 119 | ambient: [0.0, 0.0, 0.0], | ||
| 120 | dir_to_light: [0.0, 0.0, 1.0], | ||
| 121 | dir_color: [0.0, 0.0, 0.0], | ||
| 122 | has_dir: false, | ||
| 123 | points: Vec::new(), | ||
| 124 | spots: Vec::new(), | ||
| 125 | } | ||
| 126 | } | ||
| 127 | } | ||
| 128 | |||
| 129 | pub struct DrawMesh { | ||
| 130 | pub world: Mat4, | ||
| 131 | pub shape: ShapeKind, | ||
| 132 | pub tex: Option<CachedTexture>, | ||
| 133 | pub diffuse_col: [f32; 4], | ||
| 134 | pub specular_col: [f32; 3], | ||
| 135 | pub specular_intensity: f32, | ||
| 136 | pub specular_exponent: f32, | ||
| 137 | pub affected_by_lights: bool, | ||
| 138 | pub flip_normals: bool, | ||
| 139 | pub displace: Option<DisplaceHeightmap>, | ||
| 140 | } | ||
| 141 | |||
| 142 | impl Scene3DRenderer { | ||
| 143 | pub fn new(device: &wgpu::Device) -> Self { | ||
| 144 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { | ||
| 145 | label: Some("scene3d-shader"), | ||
| 146 | source: wgpu::ShaderSource::Wgsl(SHADER_3D.into()), | ||
| 147 | }); | ||
| 148 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | ||
| 149 | label: Some("scene3d-bgl"), | ||
| 150 | entries: &[ | ||
| 151 | wgpu::BindGroupLayoutEntry { | ||
| 152 | binding: 0, | ||
| 153 | visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, | ||
| 154 | ty: wgpu::BindingType::Buffer { | ||
| 155 | ty: wgpu::BufferBindingType::Uniform, | ||
| 156 | has_dynamic_offset: false, | ||
| 157 | min_binding_size: None, | ||
| 158 | }, | ||
| 159 | count: None, | ||
| 160 | }, | ||
| 161 | wgpu::BindGroupLayoutEntry { | ||
| 162 | binding: 1, | ||
| 163 | visibility: wgpu::ShaderStages::FRAGMENT, | ||
| 164 | ty: wgpu::BindingType::Texture { | ||
| 165 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, | ||
| 166 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 167 | multisampled: false, | ||
| 168 | }, | ||
| 169 | count: None, | ||
| 170 | }, | ||
| 171 | wgpu::BindGroupLayoutEntry { | ||
| 172 | binding: 2, | ||
| 173 | visibility: wgpu::ShaderStages::FRAGMENT, | ||
| 174 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), | ||
| 175 | count: None, | ||
| 176 | }, | ||
| 177 | ], | ||
| 178 | }); | ||
| 179 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | ||
| 180 | label: Some("scene3d-pl"), | ||
| 181 | bind_group_layouts: &[Some(&bgl)], | ||
| 182 | immediate_size: 0, | ||
| 183 | }); | ||
| 184 | let vbuf_layout = wgpu::VertexBufferLayout { | ||
| 185 | array_stride: std::mem::size_of::<Vertex3D>() as u64, | ||
| 186 | step_mode: wgpu::VertexStepMode::Vertex, | ||
| 187 | attributes: &[ | ||
| 188 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 }, | ||
| 189 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 }, | ||
| 190 | wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 }, | ||
| 191 | ], | ||
| 192 | }; | ||
| 193 | let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { | ||
| 194 | label: Some("scene3d-mesh"), | ||
| 195 | layout: Some(&pl), | ||
| 196 | vertex: wgpu::VertexState { | ||
| 197 | module: &shader, | ||
| 198 | entry_point: Some("vs_mesh"), | ||
| 199 | compilation_options: Default::default(), | ||
| 200 | buffers: &[Some(vbuf_layout)], | ||
| 201 | }, | ||
| 202 | fragment: Some(wgpu::FragmentState { | ||
| 203 | module: &shader, | ||
| 204 | entry_point: Some("fs_mesh"), | ||
| 205 | compilation_options: Default::default(), | ||
| 206 | targets: &[Some(wgpu::ColorTargetState { | ||
| 207 | format: wgpu::TextureFormat::Rgba8Unorm, | ||
| 208 | blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), | ||
| 209 | write_mask: wgpu::ColorWrites::ALL, | ||
| 210 | })], | ||
| 211 | }), | ||
| 212 | primitive: wgpu::PrimitiveState { | ||
| 213 | topology: wgpu::PrimitiveTopology::TriangleList, | ||
| 214 | cull_mode: None, | ||
| 215 | ..Default::default() | ||
| 216 | }, | ||
| 217 | depth_stencil: Some(wgpu::DepthStencilState { | ||
| 218 | format: wgpu::TextureFormat::Depth32Float, | ||
| 219 | depth_write_enabled: Some(true), | ||
| 220 | depth_compare: Some(wgpu::CompareFunction::LessEqual), | ||
| 221 | stencil: wgpu::StencilState::default(), | ||
| 222 | bias: wgpu::DepthBiasState::default(), | ||
| 223 | }), | ||
| 224 | multisample: wgpu::MultisampleState::default(), | ||
| 225 | multiview_mask: None, | ||
| 226 | cache: None, | ||
| 227 | }); | ||
| 228 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { | ||
| 229 | label: Some("scene3d-linear"), | ||
| 230 | address_mode_u: wgpu::AddressMode::ClampToEdge, | ||
| 231 | address_mode_v: wgpu::AddressMode::ClampToEdge, | ||
| 232 | mag_filter: wgpu::FilterMode::Linear, | ||
| 233 | min_filter: wgpu::FilterMode::Linear, | ||
| 234 | mipmap_filter: wgpu::MipmapFilterMode::Linear, | ||
| 235 | ..Default::default() | ||
| 236 | }); | ||
| 237 | Self { bgl, pipeline, sampler } | ||
| 238 | } | ||
| 239 | |||
| 240 | #[allow(clippy::too_many_arguments)] | ||
| 241 | pub fn render_meshes( | ||
| 242 | &self, | ||
| 243 | device: &wgpu::Device, | ||
| 244 | queue: &wgpu::Queue, | ||
| 245 | enc: &mut wgpu::CommandEncoder, | ||
| 246 | dst: &CachedTexture, | ||
| 247 | dummy: &CachedTexture, | ||
| 248 | view_proj: Mat4, | ||
| 249 | view: Mat4, | ||
| 250 | cam_pos: [f32; 3], | ||
| 251 | lights: SceneLights, | ||
| 252 | lighting_enabled: bool, | ||
| 253 | meshes: &[DrawMesh], | ||
| 254 | ) { | ||
| 255 | let depth_tex = device.create_texture(&wgpu::TextureDescriptor { | ||
| 256 | label: Some("scene3d-depth"), | ||
| 257 | size: wgpu::Extent3d { | ||
| 258 | width: dst.size[0].max(1), | ||
| 259 | height: dst.size[1].max(1), | ||
| 260 | depth_or_array_layers: 1, | ||
| 261 | }, | ||
| 262 | mip_level_count: 1, | ||
| 263 | sample_count: 1, | ||
| 264 | dimension: wgpu::TextureDimension::D2, | ||
| 265 | format: wgpu::TextureFormat::Depth32Float, | ||
| 266 | usage: wgpu::TextureUsages::RENDER_ATTACHMENT, | ||
| 267 | view_formats: &[], | ||
| 268 | }); | ||
| 269 | let depth_view = depth_tex.create_view(&wgpu::TextureViewDescriptor::default()); | ||
| 270 | |||
| 271 | // Sort back-to-front in camera view space so semi-transparent planes blend cleanly. | ||
| 272 | let mut order: Vec<(usize, f32)> = meshes | ||
| 273 | .iter() | ||
| 274 | .enumerate() | ||
| 275 | .map(|(i, m)| { | ||
| 276 | let wx = m.world[12]; | ||
| 277 | let wy = m.world[13]; | ||
| 278 | let wz = m.world[14]; | ||
| 279 | let vz = view[2] * wx + view[6] * wy + view[10] * wz + view[14]; | ||
| 280 | (i, vz) | ||
| 281 | }) | ||
| 282 | .collect(); | ||
| 283 | order.sort_by(|a, b| a.1.total_cmp(&b.1)); | ||
| 284 | |||
| 285 | struct GpuDraw { | ||
| 286 | bg: wgpu::BindGroup, | ||
| 287 | vbuf: wgpu::Buffer, | ||
| 288 | ibuf: wgpu::Buffer, | ||
| 289 | idx_count: u32, | ||
| 290 | } | ||
| 291 | let mut draw_items = Vec::with_capacity(order.len()); | ||
| 292 | for (idx, _) in order { | ||
| 293 | let m = &meshes[idx]; | ||
| 294 | let aspect = m | ||
| 295 | .tex | ||
| 296 | .as_ref() | ||
| 297 | .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) | ||
| 298 | .unwrap_or(16.0 / 9.0); | ||
| 299 | let (mut verts, indices) = build_shape_mesh(&m.shape, aspect); | ||
| 300 | if indices.is_empty() { | ||
| 301 | continue; | ||
| 302 | } | ||
| 303 | if let Some(disp) = &m.displace { | ||
| 304 | apply_heightmap_displace(&mut verts, &indices, disp); | ||
| 305 | } | ||
| 306 | let vbytes = bytemuck::cast_slice(&verts); | ||
| 307 | let ibytes = bytemuck::cast_slice(&indices); | ||
| 308 | let vbuf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 309 | label: Some("scene3d-vb"), | ||
| 310 | size: vbytes.len() as u64, | ||
| 311 | usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, | ||
| 312 | mapped_at_creation: false, | ||
| 313 | }); | ||
| 314 | queue.write_buffer(&vbuf, 0, vbytes); | ||
| 315 | let ibuf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 316 | label: Some("scene3d-ib"), | ||
| 317 | size: ibytes.len() as u64, | ||
| 318 | usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, | ||
| 319 | mapped_at_creation: false, | ||
| 320 | }); | ||
| 321 | queue.write_buffer(&ibuf, 0, ibytes); | ||
| 322 | |||
| 323 | let mvp = mat4_mul(view_proj, m.world); | ||
| 324 | let dod = if let Some(t) = &m.tex { | ||
| 325 | if t.has_dod() { | ||
| 326 | [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32] | ||
| 327 | } else { | ||
| 328 | [0.0; 4] | ||
| 329 | } | ||
| 330 | } else { | ||
| 331 | [0.0; 4] | ||
| 332 | }; | ||
| 333 | let mut point_pos = [[0.0_f32; 4]; 4]; | ||
| 334 | let mut point_col = [[0.0_f32; 4]; 4]; | ||
| 335 | let n_pt = lights.points.len().min(4); | ||
| 336 | for (pi, pl) in lights.points.iter().take(4).enumerate() { | ||
| 337 | point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type]; | ||
| 338 | point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], pl.decay_rate]; | ||
| 339 | } | ||
| 340 | let mut spot_pos = [[0.0_f32; 4]; 4]; | ||
| 341 | let mut spot_dir = [[0.0_f32; 4]; 4]; | ||
| 342 | let mut spot_col = [[0.0_f32; 4]; 4]; | ||
| 343 | let n_sp = lights.spots.len().min(4); | ||
| 344 | for (si, sl) in lights.spots.iter().take(4).enumerate() { | ||
| 345 | spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner]; | ||
| 346 | spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer]; | ||
| 347 | spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type]; | ||
| 348 | } | ||
| 349 | let uni = MeshUniform { | ||
| 350 | mvp, | ||
| 351 | model: m.world, | ||
| 352 | dod, | ||
| 353 | flags: [ | ||
| 354 | if m.tex.is_some() { 1.0 } else { 0.0 }, | ||
| 355 | if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 }, | ||
| 356 | m.specular_intensity, | ||
| 357 | if m.flip_normals { 1.0 } else { 0.0 }, | ||
| 358 | ], | ||
| 359 | diffuse_col: m.diffuse_col, | ||
| 360 | specular_col: [ | ||
| 361 | m.specular_col[0], | ||
| 362 | m.specular_col[1], | ||
| 363 | m.specular_col[2], | ||
| 364 | m.specular_exponent, | ||
| 365 | ], | ||
| 366 | ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0], | ||
| 367 | dir_to_light: [ | ||
| 368 | lights.dir_to_light[0], | ||
| 369 | lights.dir_to_light[1], | ||
| 370 | lights.dir_to_light[2], | ||
| 371 | if lights.has_dir { 1.0 } else { 0.0 }, | ||
| 372 | ], | ||
| 373 | dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0], | ||
| 374 | cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], | ||
| 375 | light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0], | ||
| 376 | point_pos, | ||
| 377 | point_col, | ||
| 378 | spot_pos, | ||
| 379 | spot_dir, | ||
| 380 | spot_col, | ||
| 381 | }; | ||
| 382 | let ubuf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 383 | label: Some("scene3d-u"), | ||
| 384 | size: std::mem::size_of::<MeshUniform>() as u64, | ||
| 385 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | ||
| 386 | mapped_at_creation: false, | ||
| 387 | }); | ||
| 388 | queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uni)); | ||
| 389 | let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view); | ||
| 390 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | ||
| 391 | label: Some("scene3d-bg"), | ||
| 392 | layout: &self.bgl, | ||
| 393 | entries: &[ | ||
| 394 | wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() }, | ||
| 395 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(tex_view) }, | ||
| 396 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, | ||
| 397 | ], | ||
| 398 | }); | ||
| 399 | draw_items.push(GpuDraw { | ||
| 400 | bg, | ||
| 401 | vbuf, | ||
| 402 | ibuf, | ||
| 403 | idx_count: indices.len() as u32, | ||
| 404 | }); | ||
| 405 | } | ||
| 406 | |||
| 407 | let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { | ||
| 408 | label: Some("scene3d-pass"), | ||
| 409 | color_attachments: &[Some(wgpu::RenderPassColorAttachment { | ||
| 410 | view: &dst.view, | ||
| 411 | depth_slice: None, | ||
| 412 | resolve_target: None, | ||
| 413 | ops: wgpu::Operations { | ||
| 414 | load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), | ||
| 415 | store: wgpu::StoreOp::Store, | ||
| 416 | }, | ||
| 417 | })], | ||
| 418 | depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { | ||
| 419 | view: &depth_view, | ||
| 420 | depth_ops: Some(wgpu::Operations { | ||
| 421 | load: wgpu::LoadOp::Clear(1.0), | ||
| 422 | store: wgpu::StoreOp::Discard, | ||
| 423 | }), | ||
| 424 | stencil_ops: None, | ||
| 425 | }), | ||
| 426 | timestamp_writes: None, | ||
| 427 | occlusion_query_set: None, | ||
| 428 | multiview_mask: None, | ||
| 429 | }); | ||
| 430 | pass.set_pipeline(&self.pipeline); | ||
| 431 | for d in &draw_items { | ||
| 432 | pass.set_bind_group(0, &d.bg, &[]); | ||
| 433 | pass.set_vertex_buffer(0, d.vbuf.slice(..)); | ||
| 434 | pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); | ||
| 435 | pass.draw_indexed(0..d.idx_count, 0, 0..1); | ||
| 436 | } | ||
| 437 | } | ||
| 438 | } | ||
crates/engine/src/scene3d/shader.rs created+201| ... | @@ -0,0 +1,201 @@ | ||
| 1 | //! 3D WGSL shader source and GPU vertex/uniform buffer layouts. | ||
| 2 | |||
| 3 | use bytemuck::{Pod, Zeroable}; | ||
| 4 | |||
| 5 | #[repr(C)] | ||
| 6 | #[derive(Clone, Copy, Pod, Zeroable)] | ||
| 7 | pub(super) struct Vertex3D { | ||
| 8 | pub(super) pos: [f32; 3], | ||
| 9 | pub(super) normal: [f32; 3], | ||
| 10 | pub(super) uv: [f32; 2], | ||
| 11 | } | ||
| 12 | |||
| 13 | #[repr(C)] | ||
| 14 | #[derive(Clone, Copy, Pod, Zeroable)] | ||
| 15 | pub(super) struct MeshUniform { | ||
| 16 | pub(super) mvp: [f32; 16], | ||
| 17 | pub(super) model: [f32; 16], | ||
| 18 | /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture) | ||
| 19 | pub(super) dod: [f32; 4], | ||
| 20 | /// `[use_tex, lighting_enabled, specular_intensity, flip_normals]` | ||
| 21 | pub(super) flags: [f32; 4], | ||
| 22 | /// Diffuse color multiplier `(r, g, b, a)` | ||
| 23 | pub(super) diffuse_col: [f32; 4], | ||
| 24 | /// Specular color `(r, g, b, shininess_exponent)` | ||
| 25 | pub(super) specular_col: [f32; 4], | ||
| 26 | /// Ambient light `(r, g, b, 0)` | ||
| 27 | pub(super) ambient: [f32; 4], | ||
| 28 | /// Directional light direction TO light `(dx, dy, dz, has_dir)` | ||
| 29 | pub(super) dir_to_light: [f32; 4], | ||
| 30 | /// Directional light color * intensity `(r, g, b, 0)` | ||
| 31 | pub(super) dir_color: [f32; 4], | ||
| 32 | /// Camera world position `(cx, cy, cz, 0)` | ||
| 33 | pub(super) cam_pos: [f32; 4], | ||
| 34 | /// `[num_point_lights, num_spot_lights, 0, 0]` | ||
| 35 | pub(super) light_counts: [f32; 4], | ||
| 36 | /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` | ||
| 37 | pub(super) point_pos: [[f32; 4]; 4], | ||
| 38 | /// Point light colors * intensity `(r, g, b, decay_rate)` | ||
| 39 | pub(super) point_col: [[f32; 4]; 4], | ||
| 40 | /// Spot light positions `(x, y, z, cos_inner)` | ||
| 41 | pub(super) spot_pos: [[f32; 4]; 4], | ||
| 42 | /// Spot light forward directions `(dx, dy, dz, cos_outer)` | ||
| 43 | pub(super) spot_dir: [[f32; 4]; 4], | ||
| 44 | /// Spot light colors * intensity `(r, g, b, decay_type)` | ||
| 45 | pub(super) spot_col: [[f32; 4]; 4], | ||
| 46 | } | ||
| 47 | |||
| 48 | pub(super) const SHADER_3D: &str = r#" | ||
| 49 | struct MeshUniform { | ||
| 50 | mvp: mat4x4<f32>, | ||
| 51 | model: mat4x4<f32>, | ||
| 52 | dod: vec4<f32>, | ||
| 53 | flags: vec4<f32>, | ||
| 54 | diffuse_col: vec4<f32>, | ||
| 55 | specular_col: vec4<f32>, | ||
| 56 | ambient: vec4<f32>, | ||
| 57 | dir_to_light: vec4<f32>, | ||
| 58 | dir_color: vec4<f32>, | ||
| 59 | cam_pos: vec4<f32>, | ||
| 60 | light_counts: vec4<f32>, | ||
| 61 | point_pos: array<vec4<f32>, 4>, | ||
| 62 | point_col: array<vec4<f32>, 4>, | ||
| 63 | spot_pos: array<vec4<f32>, 4>, | ||
| 64 | spot_dir: array<vec4<f32>, 4>, | ||
| 65 | spot_col: array<vec4<f32>, 4>, | ||
| 66 | }; | ||
| 67 | |||
| 68 | @group(0) @binding(0) var<uniform> u: MeshUniform; | ||
| 69 | @group(0) @binding(1) var mat_tex: texture_2d<f32>; | ||
| 70 | @group(0) @binding(2) var mat_samp: sampler; | ||
| 71 | |||
| 72 | struct VsIn { | ||
| 73 | @location(0) pos: vec3<f32>, | ||
| 74 | @location(1) normal: vec3<f32>, | ||
| 75 | @location(2) uv: vec2<f32>, | ||
| 76 | }; | ||
| 77 | |||
| 78 | struct VsOut { | ||
| 79 | @builtin(position) clip: vec4<f32>, | ||
| 80 | @location(0) uv: vec2<f32>, | ||
| 81 | @location(1) world_pos: vec3<f32>, | ||
| 82 | @location(2) world_n: vec3<f32>, | ||
| 83 | }; | ||
| 84 | |||
| 85 | @vertex | ||
| 86 | fn vs_mesh(v: VsIn) -> VsOut { | ||
| 87 | var out: VsOut; | ||
| 88 | let wp = u.model * vec4<f32>(v.pos, 1.0); | ||
| 89 | out.clip = u.mvp * vec4<f32>(v.pos, 1.0); | ||
| 90 | out.uv = v.uv; | ||
| 91 | out.world_pos = wp.xyz; | ||
| 92 | let wn = (u.model * vec4<f32>(v.normal, 0.0)).xyz; | ||
| 93 | let nlen = length(wn); | ||
| 94 | var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); | ||
| 95 | if (u.flags.w > 0.5) { | ||
| 96 | n_norm = -n_norm; | ||
| 97 | } | ||
| 98 | out.world_n = n_norm; | ||
| 99 | return out; | ||
| 100 | } | ||
| 101 | |||
| 102 | fn light_attenuation(dist: f32, decay_type: f32, decay_rate: f32) -> f32 { | ||
| 103 | let dt = i32(decay_type + 0.5); | ||
| 104 | let rate = max(decay_rate, 0.001); | ||
| 105 | if (dt == 1) { | ||
| 106 | return 1.0 / max(1.0 + dist * rate, 1e-4); | ||
| 107 | } else if (dt == 2) { | ||
| 108 | let d = dist * rate; | ||
| 109 | return 1.0 / max(1.0 + d * d, 1e-4); | ||
| 110 | } | ||
| 111 | return 1.0; | ||
| 112 | } | ||
| 113 | |||
| 114 | fn eval_light_contrib( | ||
| 115 | n: vec3<f32>, | ||
| 116 | v: vec3<f32>, | ||
| 117 | l: vec3<f32>, | ||
| 118 | light_rgb: vec3<f32>, | ||
| 119 | albedo: vec3<f32>, | ||
| 120 | spec_rgb: vec3<f32>, | ||
| 121 | spec_int: f32, | ||
| 122 | shininess: f32, | ||
| 123 | ) -> vec3<f32> { | ||
| 124 | let ndotl = max(dot(n, l), 0.0); | ||
| 125 | if (ndotl <= 0.0) { | ||
| 126 | return vec3<f32>(0.0); | ||
| 127 | } | ||
| 128 | var out = albedo * light_rgb * ndotl; | ||
| 129 | if (spec_int > 1e-4) { | ||
| 130 | let h = normalize(l + v); | ||
| 131 | let spec = pow(max(dot(n, h), 0.0), shininess) * spec_int; | ||
| 132 | out = out + light_rgb * spec_rgb * spec; | ||
| 133 | } | ||
| 134 | return out; | ||
| 135 | } | ||
| 136 | |||
| 137 | @fragment | ||
| 138 | fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> { | ||
| 139 | var col = u.diffuse_col; | ||
| 140 | if (u.flags.x > 0.5) { | ||
| 141 | var uv = in.uv; | ||
| 142 | if (u.dod.z > 0.5 && u.dod.w > 0.5) { | ||
| 143 | let tdims = vec2<f32>(textureDimensions(mat_tex)); | ||
| 144 | let canvas_px = vec2<f32>(uv.x * u.dod.z, uv.y * u.dod.w); | ||
| 145 | uv = (canvas_px - u.dod.xy) / tdims; | ||
| 146 | if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { | ||
| 147 | discard; | ||
| 148 | } | ||
| 149 | } | ||
| 150 | col = textureSample(mat_tex, mat_samp, uv) * u.diffuse_col; | ||
| 151 | } | ||
| 152 | if (col.a <= 0.002) { | ||
| 153 | discard; | ||
| 154 | } | ||
| 155 | |||
| 156 | if (u.flags.y > 0.5) { | ||
| 157 | // Premultiplied -> unpremultiplied albedo for lighting | ||
| 158 | let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5); | ||
| 159 | let n = normalize(in.world_n); | ||
| 160 | let v = normalize(u.cam_pos.xyz - in.world_pos); | ||
| 161 | let spec_rgb = u.specular_col.rgb; | ||
| 162 | let shininess = max(u.specular_col.w, 1.0); | ||
| 163 | let spec_int = u.flags.z; | ||
| 164 | |||
| 165 | var lit = albedo * u.ambient.rgb; | ||
| 166 | if (u.dir_to_light.w > 0.5) { | ||
| 167 | let l = normalize(u.dir_to_light.xyz); | ||
| 168 | lit = lit + eval_light_contrib(n, v, l, u.dir_color.rgb, albedo, spec_rgb, spec_int, shininess); | ||
| 169 | } | ||
| 170 | |||
| 171 | let n_pt = i32(u.light_counts.x + 0.5); | ||
| 172 | for (var i: i32 = 0; i < 4; i = i + 1) { | ||
| 173 | if (i >= n_pt) { break; } | ||
| 174 | let to_l = u.point_pos[i].xyz - in.world_pos; | ||
| 175 | let dist = max(length(to_l), 1e-4); | ||
| 176 | let att = light_attenuation(dist, u.point_pos[i].w, u.point_col[i].w); | ||
| 177 | lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); | ||
| 178 | } | ||
| 179 | |||
| 180 | let n_sp = i32(u.light_counts.y + 0.5); | ||
| 181 | for (var i: i32 = 0; i < 4; i = i + 1) { | ||
| 182 | if (i >= n_sp) { break; } | ||
| 183 | let to_l = u.spot_pos[i].xyz - in.world_pos; | ||
| 184 | let dist = max(length(to_l), 1e-4); | ||
| 185 | let l_dir = to_l / dist; | ||
| 186 | // spot_dir.xyz is direction spotlight points; fragment direction from light is -l_dir | ||
| 187 | let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz)); | ||
| 188 | let cos_inner = u.spot_pos[i].w; | ||
| 189 | let cos_outer = u.spot_dir[i].w; | ||
| 190 | let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); | ||
| 191 | if (cone > 0.0) { | ||
| 192 | let att = light_attenuation(dist, u.spot_col[i].w, 1.0) * cone; | ||
| 193 | lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); | ||
| 194 | } | ||
| 195 | } | ||
| 196 | |||
| 197 | col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a); | ||
| 198 | } | ||
| 199 | return col; | ||
| 200 | } | ||
| 201 | "#; | ||
scripts/gen_compatibility.py+1-1| ... | @@ -17,7 +17,7 @@ from typing import Dict, List, Optional, Sequence, Set, Tuple | ... | @@ -17,7 +17,7 @@ from typing import Dict, List, Optional, Sequence, Set, Tuple |
| 17 | 17 | ||
| 18 | REPO_ROOT = Path(__file__).resolve().parent.parent | 18 | REPO_ROOT = Path(__file__).resolve().parent.parent |
| 19 | EVAL_RS = REPO_ROOT / "crates" / "engine" / "src" / "eval" / "mod.rs" | 19 | EVAL_RS = REPO_ROOT / "crates" / "engine" / "src" / "eval" / "mod.rs" |
| 20 | SCENE3D_RS = REPO_ROOT / "crates" / "engine" / "src" / "scene3d.rs" | 20 | SCENE3D_RS = REPO_ROOT / "crates" / "engine" / "src" / "scene3d" / "collect.rs" |
| 21 | COMP_RS = REPO_ROOT / "crates" / "model" / "src" / "comp.rs" | 21 | COMP_RS = REPO_ROOT / "crates" / "model" / "src" / "comp.rs" |
| 22 | PROBES_PY = REPO_ROOT / "scripts" / "fusion_probes.py" | 22 | PROBES_PY = REPO_ROOT / "scripts" / "fusion_probes.py" |
| 23 | DEFAULT_OUTPUT = REPO_ROOT / "compatibility.md" | 23 | DEFAULT_OUTPUT = REPO_ROOT / "compatibility.md" |