BlueGit

golden-age paperdoll-renderer

Files

paperdoll-renderer / tests / fbx_integration.rs

fbx_integration.rs

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