BlueGit

golden-age paperdoll-renderer

Files

paperdoll-renderer / tests / fbx_integration.rs

fbx_integration.rs

fbx_integration.rs 14.8 KiB Download Raw
1//! FBX bodies in the live/production path and rigid FBX equipment import.
2use paperdoll_renderer::equipment::{self, Preset};
3use paperdoll_renderer::preview::{self, Mat4, PreviewCharacter, PreviewControls};
4use paperdoll_renderer::production::{self, RenderJob, SourceFingerprint};
5use paperdoll_renderer::project::CameraFraming;
6use std::path::PathBuf;
7
8fn repo(path: &str) -> PathBuf {
9 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(path)
10}
11fn fbx_body() -> PreviewCharacter {
12 preview::load_body_file(&repo("tests/fixtures/bodies/test-body-male.fbx")).unwrap()
13}
14fn glb_body() -> PreviewCharacter {
15 preview::load_body_file(&repo("tests/fixtures/bodies/test-body-male.glb")).unwrap()
16}
17fn scratch(tag: &str) -> PathBuf {
18 let dir = std::env::temp_dir().join(format!(
19 "paperdoll-fbx-{tag}-{}",
20 std::time::SystemTime::now()
21 .duration_since(std::time::UNIX_EPOCH)
22 .unwrap()
23 .as_nanos()
24 ));
25 std::fs::create_dir_all(&dir).unwrap();
26 dir
27}
28fn job(character: PreviewCharacter, preset: Option<Preset>) -> RenderJob {
29 RenderJob {
30 depth_format: paperdoll_renderer::camera::DepthFormat::GRAY16,
31 character,
32 sex: "male".into(),
33 preset,
34 target_width: 32,
35 target_height: 48,
36 fps: 4,
37 framing: CameraFraming {
38 height_milli: 2400,
39 center_y_milli: 1000,
40 pivot_y_milli: None,
41 depth_range_milli: None,
42 },
43 output: std::env::temp_dir(),
44 project_id: "fbx-test".into(),
45 project_name: "FBX".into(),
46 body_model: SourceFingerprint {
47 path: "assets/body/test-body-male.fbx".into(),
48 sha256: "0".repeat(64),
49 },
50 preset_sha256: None,
51 }
52}
53fn bounds(scene: &production::Scene) -> ([f32; 3], [f32; 3]) {
54 let mut lo = [f32::MAX; 3];
55 let mut hi = [f32::MIN; 3];
56 for draw in &scene.draws {
57 for &i in &draw.indices {
58 let p = draw.positions[i as usize];
59 for k in 0..3 {
60 lo[k] = lo[k].min(p[k]);
61 hi[k] = hi[k].max(p[k]);
62 }
63 }
64 }
65 (lo, hi)
66}
67fn clip_named(body: &PreviewCharacter, prefix: &str) -> String {
68 body.clips
69 .iter()
70 .find(|c| c.name.contains(prefix))
71 .unwrap_or_else(|| panic!("clip {prefix} ontbreekt"))
72 .name
73 .clone()
74}
75fn apply(m: &Mat4, p: [f32; 3]) -> [f32; 3] {
76 [
77 m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12],
78 m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13],
79 m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14],
80 ]
81}
82
83#[test]
84fn body_loader_dispatches_by_extension_and_rejects_other_formats() {
85 assert!(preview::is_drawable_body(std::path::Path::new("a/B.FBX")));
86 assert!(preview::is_drawable_body(std::path::Path::new("b.glb")));
87 // OBJ is drawable as a static body (no skeleton); STL/PLY are not bodies.
88 assert!(preview::is_drawable_body(std::path::Path::new("c.obj")));
89 assert!(!preview::is_drawable_body(std::path::Path::new("d.stl")));
90 let fbx = fbx_body();
91 let direct = paperdoll_renderer::fbx_scene::load_fbx_drawable(&repo(
92 "tests/fixtures/bodies/test-body-male.fbx",
93 ))
94 .unwrap();
95 assert_eq!(fbx.positions, direct.character.positions);
96 assert_eq!(fbx.clips.len(), 2);
97 let obj = preview::load_body_file(&repo("tests/fixtures/equipment/sword.obj")).unwrap();
98 assert!(obj.is_static() && obj.clips.is_empty());
99 let err = preview::load_body_file(&repo("tests/fixtures/equipment/sword.ply")).unwrap_err();
100 assert!(err.contains("geen tekenbaar lichaam"), "{err}");
101 // A file named .glb that actually holds FBX bytes is not silently accepted.
102 let dir = scratch("renamed");
103 let fake = dir.join("body.glb");
104 std::fs::copy(repo("tests/fixtures/bodies/test-body-male.fbx"), &fake).unwrap();
105 assert!(preview::load_body_file(&fake).is_err());
106 let _ = std::fs::remove_dir_all(dir);
107}
108
109#[test]
110fn fbx_body_production_scene_matches_glb_silhouette_without_double_normalization() {
111 let fbx = fbx_body();
112 let glb = glb_body();
113 let fbx_plan = production::plan(&fbx, 12).unwrap();
114 let glb_plan = production::plan(&glb, 12).unwrap();
115 assert_eq!(fbx_plan.images, glb_plan.images);
116 assert_eq!(fbx_plan.files, glb_plan.files);
117 let fbx_job = job(fbx, None);
118 let glb_job = job(glb, None);
119 let mut cache = equipment::TextureCache::default();
120 // Only `walk` is compared as a whole silhouette: Blender's FBX exporter
121 // baked the legs of the fixture's `attack` stack in a leftover walk pose
122 // (all 60 curves present in the file), so the attack clip is compared per
123 // animated arm joint below instead.
124 for (prefix, time) in [("walk", 0.0), ("walk", 0.25), ("walk", 0.6)] {
125 let f = production::scene(
126 &fbx_job,
127 &clip_named(&fbx_job.character, prefix),
128 time,
129 30.,
130 90.,
131 &mut cache,
132 )
133 .unwrap();
134 let g = production::scene(&glb_job, prefix, time, 30., 90., &mut cache).unwrap();
135 f.validate().unwrap();
136 let (flo, fhi) = bounds(&f);
137 let (glo, ghi) = bounds(&g);
138 for k in 0..3 {
139 assert!(
140 (flo[k] - glo[k]).abs() < 0.03 && (fhi[k] - ghi[k]).abs() < 0.03,
141 "{prefix}@{time} axis {k}: fbx {flo:?}..{fhi:?} vs glb {glo:?}..{ghi:?}"
142 );
143 }
144 // Body height in metres (no centimetre or axis double-conversion).
145 assert!((fhi[1] - flo[1]) > 1.4 && (fhi[1] - flo[1]) < 2.2);
146 // Same fixed per-body framing: identical orthographic projection and
147 // a neck pivot resolved from the FBX rig close to the GLB one.
148 assert_eq!(f.projection, g.projection);
149 assert_eq!((f.width, f.height), (g.width, g.height));
150 }
151 let attack = clip_named(&fbx_job.character, "attack");
152 for name in [
153 "RightUpperArm",
154 "RightLowerArm",
155 "RightHand",
156 "Chest",
157 "Spine",
158 ] {
159 for time in [0.0, 0.2, 0.4, 0.7] {
160 let f =
161 preview::joint_world_translation(&fbx_job.character, &attack, time, name).unwrap();
162 let g =
163 preview::joint_world_translation(&glb_job.character, "attack", time, name).unwrap();
164 let d = ((f[0] - g[0]).powi(2) + (f[1] - g[1]).powi(2) + (f[2] - g[2]).powi(2)).sqrt();
165 assert!(d < 0.02, "attack {name}@{time}: {f:?} vs {g:?}");
166 }
167 }
168 let fp = paperdoll_renderer::camera::resolve(&fbx_job.character, fbx_job.framing);
169 let gp = paperdoll_renderer::camera::resolve(&glb_job.character, glb_job.framing);
170 assert!(matches!(
171 fp.source,
172 paperdoll_renderer::camera::PivotSource::BoundsCenter { .. }
173 ));
174 let (fy, gy) = (
175 fp.framing.pivot_y_milli.unwrap(),
176 gp.framing.pivot_y_milli.unwrap(),
177 );
178 assert!((fy - gy).abs() <= 30, "centre pivot fbx {fy} vs glb {gy}");
179}
180
181#[test]
182fn rigid_fbx_import_normalizes_axes_units_and_embeds_png() {
183 let mut preset = Preset::new("fbxsword".into());
184 let part = equipment::import_fbx(&mut preset, &repo("tests/fixtures/equipment/sword-fbx.fbx"))
185 .unwrap();
186 let item = &preset.attachments[part];
187 assert_eq!(item.label, "sword-fbx.fbx");
188 assert_eq!(item.meshes.len(), 2);
189 let mut lo = [f32::MAX; 3];
190 let mut hi = [f32::MIN; 3];
191 for p in item.meshes.iter().flat_map(|m| &m.positions) {
192 for k in 0..3 {
193 lo[k] = lo[k].min(p[k]);
194 hi[k] = hi[k].max(p[k]);
195 }
196 }
197 // Exported Z-up from Blender: blade length must end up along +Y in metres.
198 assert!(
199 lo[1].abs() < 1e-3 && (hi[1] - 0.58).abs() < 1e-3,
200 "{lo:?} {hi:?}"
201 );
202 assert!((hi[0] - 0.09).abs() < 1e-3 && (lo[0] + 0.09).abs() < 1e-3);
203 assert!((hi[2] - 0.015).abs() < 1e-3 && (lo[2] + 0.015).abs() < 1e-3);
204 for mesh in &item.meshes {
205 assert_eq!(mesh.positions.len(), mesh.normals.len());
206 assert_eq!(mesh.positions.len(), mesh.uvs.len());
207 for n in &mesh.normals {
208 let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
209 assert!((len - 1.).abs() < 1e-3);
210 }
211 }
212 let blade = item.meshes.iter().find(|m| m.albedo.is_some()).unwrap();
213 let guard = item.meshes.iter().find(|m| m.albedo.is_none()).unwrap();
214 // A connected texture replaces the FBX diffuse colour; the guard keeps its colour.
215 assert_eq!(blade.color, [1., 1., 1., 1.]);
216 for (got, want) in guard.color.iter().zip([0.75, 0.55, 0.2, 1.]) {
217 assert!((got - want).abs() < 0.01, "{:?}", guard.color);
218 }
219 // UVs keep the OBJ/FBX convention (V up): on the broad blade faces the
220 // tip has V=1 and the base V=0 (the fixture maps each face to the unit square).
221 let broad = |want_y: f32| {
222 blade
223 .positions
224 .iter()
225 .zip(&blade.normals)
226 .zip(&blade.uvs)
227 .filter(|((p, n), _)| n[2].abs() > 0.9 && (p[1] - want_y).abs() < 1e-4)
228 .map(|(_, uv)| uv[1])
229 .collect::<Vec<_>>()
230 };
231 let (tip, base) = (broad(0.58), broad(0.03));
232 assert!(
233 !tip.is_empty() && tip.iter().all(|v| (*v - 1.).abs() < 1e-4),
234 "{tip:?}"
235 );
236 assert!(
237 !base.is_empty() && base.iter().all(|v| v.abs() < 1e-4),
238 "{base:?}"
239 );
240 let albedo = blade.albedo.unwrap();
241 assert!(preset.assets[albedo].path.contains("/embedded/"));
242 let embedded = preset.texture(albedo).unwrap();
243 let mut reference = Preset::new("ref".into());
244 reference.assets.push(equipment::EmbeddedAsset {
245 path: "checker.png".into(),
246 bytes: std::fs::read(repo("tests/fixtures/equipment/checker.png")).unwrap(),
247 });
248 assert_eq!(embedded.rgba, reference.texture(0).unwrap().rgba);
249 // Original FBX payload is kept, and the binary preset round-trips.
250 assert!(item.source_assets.iter().any(|i| preset.assets[*i].bytes
251 == std::fs::read(repo("tests/fixtures/equipment/sword-fbx.fbx")).unwrap()));
252 let decoded = Preset::decode(&preset.encode().unwrap()).unwrap();
253 assert_eq!(decoded, preset);
254}
255
256#[test]
257fn rigid_fbx_external_png_is_embedded_and_missing_texture_fails() {
258 let mut preset = Preset::new("fbxsword".into());
259 let part = equipment::import_model(
260 &mut preset,
261 &repo("tests/fixtures/equipment/sword-fbx-external.fbx"),
262 )
263 .unwrap();
264 let blade = preset.attachments[part]
265 .meshes
266 .iter()
267 .find(|m| m.albedo.is_some())
268 .unwrap();
269 let asset = &preset.assets[blade.albedo.unwrap()];
270 assert!(asset.path.ends_with("/checker.png"), "{}", asset.path);
271 assert_eq!(
272 asset.bytes,
273 std::fs::read(repo("tests/fixtures/equipment/checker.png")).unwrap()
274 );
275 let dir = scratch("missing-tex");
276 std::fs::copy(
277 repo("tests/fixtures/equipment/sword-fbx-external.fbx"),
278 dir.join("lonely.fbx"),
279 )
280 .unwrap();
281 let mut other = Preset::new("lonely".into());
282 let err = equipment::import_fbx(&mut other, &dir.join("lonely.fbx")).unwrap_err();
283 assert!(err.contains("FBX-texture"), "{err}");
284 assert!(other.attachments.is_empty() && other.assets.is_empty());
285 let _ = std::fs::remove_dir_all(dir);
286}
287
288#[test]
289fn skinned_garbage_or_unsupported_equipment_is_rejected() {
290 let mut preset = Preset::new("bad".into());
291 let err = equipment::import_fbx(
292 &mut preset,
293 &repo("tests/fixtures/bodies/test-body-male.fbx"),
294 )
295 .unwrap_err();
296 assert!(err.contains("geskinned"), "{err}");
297 let dir = scratch("garbage");
298 std::fs::write(dir.join("junk.fbx"), b"not an fbx at all").unwrap();
299 assert!(equipment::import_fbx(&mut preset, &dir.join("junk.fbx")).is_err());
300 assert!(equipment::import_model(
301 &mut preset,
302 &repo("tests/fixtures/bodies/test-body-male.glb")
303 )
304 .is_err());
305 assert!(preset.attachments.is_empty() && preset.assets.is_empty());
306 // OBJ still goes through the same dispatcher.
307 equipment::import_model(&mut preset, &repo("tests/fixtures/equipment/sword.obj")).unwrap();
308 assert_eq!(preset.attachments.len(), 1);
309 let _ = std::fs::remove_dir_all(dir);
310}
311
312#[test]
313fn fbx_equipment_on_fbx_body_follows_the_animated_hand_in_production() {
314 let body = fbx_body();
315 let joint = body
316 .joint_names
317 .iter()
318 .position(|n| n == "RightHand")
319 .unwrap();
320 let mut preset = Preset::new("fbxsword".into());
321 equipment::import_fbx(&mut preset, &repo("tests/fixtures/equipment/sword-fbx.fbx")).unwrap();
322 preset.bind(0, &body, 0, joint).unwrap();
323 preset.attachments[0].rotation_deg = [0., 0., -15.];
324 let attack = clip_named(&body, "attack");
325 let job = job(body, Some(preset.clone()));
326 let mut cache = equipment::TextureCache::default();
327 let early = production::scene(&job, &attack, 0.0, 0., 0., &mut cache).unwrap();
328 let late = production::scene(&job, &attack, 0.4, 0., 0., &mut cache).unwrap();
329 assert_eq!(early.draws.len(), 2);
330 assert!(early.draws.iter().any(|d| d.albedo.is_some()));
331 assert_eq!(early.view, late.view);
332 assert_ne!(early.draws[0].positions, late.draws[0].positions);
333 // Exact attachment: animated joint world × local transform × source vertex.
334 let world = preview::animated_joint_world(&job.character, &attack, 0.4, joint).unwrap();
335 let model = preview::mul(world, equipment::local_matrix([0.; 3], [0., 0., -15.]));
336 let layers = equipment::layers(
337 &preset,
338 0,
339 &job.character,
340 &PreviewControls {
341 clip_name: attack.clone(),
342 time: 0.4,
343 ..Default::default()
344 },
345 )
346 .unwrap();
347 assert_eq!(layers[0].model, model);
348 let expected = apply(&model, preset.attachments[0].meshes[0].positions[0]);
349 let got = late.draws[0].positions[0];
350 for k in 0..3 {
351 assert!(
352 (expected[k] - got[k]).abs() < 1e-5,
353 "{expected:?} vs {got:?}"
354 );
355 }
356 // The hand-bound sword sits at the FBX hand, not at the origin.
357 let hand = [world[12], world[13], world[14]];
358 assert!(hand[1] > 0.5);
359 let d = ((got[0] - hand[0]).powi(2) + (got[1] - hand[1]).powi(2) + (got[2] - hand[2]).powi(2))
360 .sqrt();
361 assert!(d < 0.7, "sword vertex {got:?} far from hand {hand:?}");
362 // A preset bound to the GLB rig is refused on the FBX rig instead of guessing.
363 let mut glb_bound = Preset::new("glbsword".into());
364 equipment::import_fbx(
365 &mut glb_bound,
366 &repo("tests/fixtures/equipment/sword-fbx.fbx"),
367 )
368 .unwrap();
369 let glb = glb_body();
370 glb_bound
371 .bind(
372 0,
373 &glb,
374 0,
375 glb.joint_names
376 .iter()
377 .position(|n| n == "RightHand")
378 .unwrap(),
379 )
380 .unwrap();
381 let err =
382 equipment::layers(&glb_bound, 0, &job.character, &PreviewControls::default()).unwrap_err();
383 assert!(err.contains("rig wijkt af"), "{err}");
384}