1use anyhow::{bail, Result};
14use glam::{Mat4, Vec3};
15
16use crate::id::NodeId;
17use crate::material::Material;
18use crate::mesh::Mesh;
19use crate::ops::{self, Pose};
20use crate::project::Project;
21use crate::scene::NodeKind;
22
23#[derive(Clone, Debug)]
26pub struct BakeOptions {
27 pub frame_px: u32,
29 pub oversample: u32,
31 pub azimuths: Vec<f32>,
33 pub pitch_deg: f32,
35 pub margin: f32,
37 pub shaded: bool,
39 pub anim_frames: u32,
44 pub animation: Option<crate::id::AnimationId>,
49}
50
51impl Default for BakeOptions {
52 fn default() -> Self {
53 Self {
54 frame_px: 128,
55 oversample: 2,
56 azimuths: vec![45.0, 135.0, 225.0, 315.0],
57 pitch_deg: 35.264,
58 margin: 0.08,
59 shaded: true,
60 anim_frames: 1,
61 animation: None,
62 }
63 }
64}
65
66#[derive(Clone, Debug, PartialEq)]
70pub struct BakedSheet {
71 pub frame_px: u32,
72 pub width: u32,
73 pub height: u32,
74 pub rgba: Vec<u8>,
75 pub views: usize,
77 pub anim: usize,
79}
80
81impl BakedSheet {
82 pub fn views(&self) -> usize {
83 self.views.max(1)
84 }
85 pub fn anim(&self) -> usize {
86 self.anim.max(1)
87 }
88 pub fn frames(&self) -> usize {
90 self.views() * self.anim()
91 }
92 fn grid(&self) -> (usize, usize) {
95 if self.anim() == 1 {
96 (1, self.views())
97 } else {
98 (self.views(), self.anim())
99 }
100 }
101 pub fn frame_rgba_at(&self, view: usize, frame: usize) -> Option<Vec<u8>> {
105 if view >= self.views() || frame >= self.anim() {
106 return None;
107 }
108 let px = self.frame_px as usize;
109 let (rows, cols) = self.grid();
110 let (r, c) = if self.anim() == 1 {
111 (0, view)
112 } else {
113 (view, frame)
114 };
115 if r >= rows || c >= cols {
116 return None;
117 }
118 let w = self.width as usize;
119 let mut out = Vec::with_capacity(px * px * 4);
120 for y in 0..px {
121 let off = ((r * px + y) * w + c * px) * 4;
122 out.extend_from_slice(&self.rgba[off..off + px * 4]);
123 }
124 Some(out)
125 }
126 pub fn frame_rgba(&self, i: usize) -> Option<Vec<u8>> {
128 let (rows, cols) = self.grid();
129 let (r, c) = (i / cols, i % cols);
130 if r >= rows {
131 return None;
132 }
133 if self.anim() == 1 {
134 self.frame_rgba_at(c, 0)
135 } else {
136 self.frame_rgba_at(r, c)
137 }
138 }
139}
140
141struct WorldTri {
142 pts: [Vec3; 3],
143 color: [u8; 4],
144}
145
146fn to_rgba8(rgba: [f32; 4]) -> [u8; 4] {
148 let f = |v: f32| {
149 let v = v.clamp(0.0, 1.0);
150 let s = if v <= 0.0031308 {
151 v * 12.92
152 } else {
153 1.055 * v.powf(1.0 / 2.4) - 0.055
154 };
155 (s * 255.0).round() as u8
156 };
157 [
158 f(rgba[0]),
159 f(rgba[1]),
160 f(rgba[2]),
161 (rgba[3].clamp(0.0, 1.0) * 255.0).round() as u8,
162 ]
163}
164
165fn gather(
174 p: &Project,
175 node: NodeId,
176 shaded: bool,
177 motion_t: Option<f32>,
178 clip: Option<(&crate::animation::Animation, f32)>,
179 out: &mut Vec<WorldTri>,
180) {
181 let Some(n) = p.scene.get(node) else {
182 return;
183 };
184 if !n.visible {
185 return;
186 }
187 let light = Vec3::new(0.45, 0.82, 0.35).normalize();
188 let world = p.scene.world_transform(node).to_mat4();
189 match &n.kind {
190 NodeKind::MeshInstance {
191 mesh,
192 material,
193 skeleton_node,
194 } => {
195 if let Some(m) = p.library.meshes.get(mesh) {
196 let skinned = if m.skin.is_some() {
197 skeleton_node.and_then(|sk| {
198 let pose = match clip {
199 Some((anim, t)) => ops::sample_pose(p, sk, anim, t),
200 None => Pose::default(),
201 };
202 ops::skinned_positions(p, *mesh, node, sk, &pose).ok()
203 })
204 } else {
205 None
206 };
207 let pos: &[[f32; 3]] = skinned.as_deref().unwrap_or(&m.positions);
208 let mo = motion_t.map(|_| n.motion).unwrap_or_default();
209 push_tris(
210 m,
211 pos,
212 &world,
213 material.as_ref().and_then(|id| p.library.materials.get(id)),
214 shaded,
215 light,
216 mo,
217 motion_t,
218 out,
219 );
220 }
221 }
222 NodeKind::TileMapInstance { tilemap } => {
223 let Some(map) = p.library.tilemaps.get(tilemap) else {
224 return;
225 };
226 let Some(ts) = p.library.tilesets.get(&map.tileset) else {
227 return;
228 };
229 for c in &map.cells {
230 let Some(tile) = ts.tiles.get(c.tile as usize) else {
231 continue;
232 };
233 let Some(m) = p.library.meshes.get(&tile.mesh) else {
234 continue;
235 };
236 let w = world * ts.cell_transform(c.x, c.z).to_mat4() * tile.offset.to_mat4();
237 let mo = motion_t.map(|_| tile.motion).unwrap_or_default();
238 push_tris(
239 m,
240 &m.positions,
241 &w,
242 tile.material
243 .as_ref()
244 .and_then(|id| p.library.materials.get(id)),
245 shaded,
246 light,
247 mo,
248 motion_t,
249 out,
250 );
251 }
252 }
253 _ => {}
254 }
255 let children = n.children.clone();
256 for c in children {
257 gather(p, c, shaded, motion_t, clip, out);
258 }
259}
260
261#[allow(clippy::too_many_arguments)]
262fn push_tris(
263 m: &Mesh,
264 pos: &[[f32; 3]],
265 world: &Mat4,
266 material: Option<&Material>,
267 shaded: bool,
268 light: Vec3,
269 motion: crate::motion::Motion,
270 motion_t: Option<f32>,
271 out: &mut Vec<WorldTri>,
272) {
273 let base = material
274 .map(|mt| to_rgba8(mt.base_color))
275 .unwrap_or([176, 176, 176, 255]);
276 let mut wp: Vec<Vec3> = pos
277 .iter()
278 .map(|q| world.transform_point3(Vec3::from_array(*q)))
279 .collect();
280 if let (false, Some(t)) = (motion.is_none(), motion_t) {
281 let (mut y0, mut y1) = (f32::INFINITY, f32::NEG_INFINITY);
283 for q in &wp {
284 y0 = y0.min(q.y);
285 y1 = y1.max(q.y);
286 }
287 for q in &mut wp {
288 *q += motion.offset_loop(*q, y0, y1, 0.0, t);
289 }
290 }
291 for t in m.iter_triangles() {
292 let i = [t[0] as usize, t[1] as usize, t[2] as usize];
293 if !i.iter().all(|k| *k < wp.len()) {
294 continue;
295 }
296 let (a, b, c) = (wp[i[0]], wp[i[1]], wp[i[2]]);
297 let color = if shaded {
298 let nrm = (b - a).cross(c - a).normalize_or_zero();
299 let l = 0.38 + 0.62 * nrm.dot(light).abs();
300 [
301 (base[0] as f32 * l).min(255.0) as u8,
302 (base[1] as f32 * l).min(255.0) as u8,
303 (base[2] as f32 * l).min(255.0) as u8,
304 base[3],
305 ]
306 } else {
307 base
308 };
309 out.push(WorldTri {
310 pts: [a, b, c],
311 color,
312 });
313 }
314}
315
316pub fn bake(p: &Project, root: NodeId, opt: &BakeOptions) -> Result<BakedSheet> {
319 if !p.scene.nodes.contains_key(&root) {
320 bail!("node n{} not found", root.0);
321 }
322 if opt.azimuths.is_empty() {
323 bail!("bake needs at least one azimuth");
324 }
325 let anim = opt.anim_frames.clamp(1, 24) as usize;
326 let clip = opt
328 .animation
329 .as_ref()
330 .and_then(|id| p.library.animations.get(id))
331 .map(|a| (a, a.duration().max(1e-4)));
332 if opt.animation.is_some() && clip.is_none() {
333 bail!(
334 "animation a{} not found in library",
335 opt.animation.map(|a| a.0).unwrap_or_default()
336 );
337 }
338 let mut frames: Vec<Vec<WorldTri>> = Vec::with_capacity(anim);
340 for k in 0..anim {
341 let frac = if anim == 1 {
342 0.0
343 } else {
344 k as f32 / anim as f32
345 };
346 let (motion_t, clip_t) = match &clip {
347 Some((a, dur)) => (None, Some((*a, dur * frac))),
348 None => (
349 if anim == 1 {
350 None
351 } else {
352 Some(std::f32::consts::TAU * frac)
353 },
354 None,
355 ),
356 };
357 let mut tris = Vec::new();
358 gather(p, root, opt.shaded, motion_t, clip_t, &mut tris);
359 frames.push(tris);
360 }
361
362 let frame = opt.frame_px.clamp(8, 1024);
363 let os = opt.oversample.clamp(1, 4);
364 let res = frame * os;
365 let mut s = Vec3::ZERO;
367 let mut k = 0u32;
368 for tris in &frames {
369 for t in tris {
370 for v in t.pts {
371 s += v;
372 k += 1;
373 }
374 }
375 }
376 let center = if k == 0 { Vec3::ZERO } else { s / k as f32 };
377
378 let bytes = (frame * frame * 4) as usize;
379 let views = opt.azimuths.len();
380 let (rows, cols) = if anim == 1 {
384 (1usize, views)
385 } else {
386 (views, anim)
387 };
388 let w_px = cols * frame as usize;
389 let mut rgba = vec![0u8; w_px * rows * frame as usize * 4];
390 let mut cell = vec![0u8; bytes];
391 for (vi, &az) in opt.azimuths.iter().enumerate() {
392 let union_scale = (anim > 1).then(|| row_scale(&frames, center, az, opt.pitch_deg, res));
394 for (ti, tris) in frames.iter().enumerate() {
395 let hi = render_frame(
396 tris,
397 center,
398 az,
399 opt.pitch_deg,
400 res,
401 opt.margin,
402 union_scale,
403 );
404 downsample(&hi, os, &mut cell, frame);
405 let (dr, dc) = if anim == 1 { (0usize, vi) } else { (vi, ti) };
406 let stride = frame as usize * 4;
407 for y in 0..frame as usize {
408 let o = ((dr * frame as usize + y) * w_px + dc * frame as usize) * 4;
409 rgba[o..o + stride].copy_from_slice(&cell[y * stride..(y + 1) * stride]);
410 }
411 }
412 }
413 Ok(BakedSheet {
414 frame_px: frame,
415 width: w_px as u32,
416 height: (rows * frame as usize) as u32,
417 rgba,
418 views,
419 anim,
420 })
421}
422
423struct Rt {
424 pts: [[f32; 2]; 3],
425 prox: f32,
426 color: [u8; 4],
427}
428
429fn row_scale(frames: &[Vec<WorldTri>], center: Vec3, az_deg: f32, pitch_deg: f32, res: u32) -> f32 {
432 let az = az_deg.to_radians();
433 let pr = pitch_deg.to_radians().clamp(0.05, 1.5);
434 let e = Vec3::new(az.sin() * pr.cos(), pr.sin(), az.cos() * pr.cos());
435 let f = -e;
436 let mut s = f.cross(Vec3::Y);
437 if s.length_squared() < 1e-9 {
438 s = Vec3::X;
439 }
440 let s = s.normalize();
441 let u = s.cross(f).normalize();
442 let (mut minx, mut miny, mut maxx, mut maxy) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
443 for tris in frames {
444 for t in tris {
445 for v in t.pts {
446 let d = v - center;
447 let (x, y) = (d.dot(s), d.dot(u));
448 minx = minx.min(x);
449 maxx = maxx.max(x);
450 miny = miny.min(y);
451 maxy = maxy.max(y);
452 }
453 }
454 }
455 if maxx <= minx {
456 return 1.0;
457 }
458 (res as f32 * 0.72) / (maxx - minx).max(maxy - miny).max(1e-4)
461}
462
463fn render_frame(
466 tris: &[WorldTri],
467 center: Vec3,
468 az_deg: f32,
469 pitch_deg: f32,
470 res: u32,
471 margin: f32,
472 scale: Option<f32>,
473) -> Vec<u8> {
474 let mut buf = vec![0u8; (res * res * 4) as usize];
475 if tris.is_empty() {
476 return buf;
477 }
478 let az = az_deg.to_radians();
479 let pr = pitch_deg.to_radians().clamp(0.05, 1.5);
480 let e = Vec3::new(az.sin() * pr.cos(), pr.sin(), az.cos() * pr.cos());
482 let f = -e;
483 let mut s = f.cross(Vec3::Y);
484 if s.length_squared() < 1e-9 {
485 s = Vec3::X;
486 }
487 let s = s.normalize();
488 let u = s.cross(f).normalize();
489
490 let mut rts: Vec<Rt> = Vec::with_capacity(tris.len());
491 let (mut minx, mut miny, mut maxx, mut maxy) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
492 for t in tris {
493 let pr_pts: [[f32; 2]; 3] = t.pts.map(|v| {
494 let d = v - center;
495 [d.dot(s), d.dot(u)]
496 });
497 for q in &pr_pts {
498 minx = minx.min(q[0]);
499 maxx = maxx.max(q[0]);
500 miny = miny.min(q[1]);
501 maxy = maxy.max(q[1]);
502 }
503 let centroid = (t.pts[0] + t.pts[1] + t.pts[2]) * (1.0 / 3.0);
504 rts.push(Rt {
505 pts: pr_pts,
506 prox: (centroid - center).dot(e),
507 color: t.color,
508 });
509 }
510
511 let fit =
512 (res as f32 * (1.0 - margin.clamp(0.0, 0.4))) / (maxx - minx).max(maxy - miny).max(1e-4);
513 let shared_pivot = scale.is_some();
518 let scale = scale.map_or(fit, |rs| rs.min(fit));
519 let (cx, cy) = if shared_pivot {
520 (0.0, 0.0)
521 } else {
522 ((minx + maxx) * 0.5, (miny + maxy) * 0.5)
523 };
524 for r in &mut rts {
525 for q in &mut r.pts {
526 q[0] = res as f32 * 0.5 + (q[0] - cx) * scale;
527 q[1] = res as f32 * 0.5 - (q[1] - cy) * scale;
528 }
529 }
530
531 let mut opaque: Vec<&Rt> = rts.iter().filter(|r| r.color[3] >= 250).collect();
533 let mut blend: Vec<&Rt> = rts.iter().filter(|r| r.color[3] < 250).collect();
534 opaque.sort_by(|a, b| a.prox.total_cmp(&b.prox));
535 blend.sort_by(|a, b| a.prox.total_cmp(&b.prox));
536 for r in &opaque {
537 raster(&mut buf, res, &r.pts, r.color, false);
538 }
539 for r in &blend {
540 raster(&mut buf, res, &r.pts, r.color, true);
541 }
542 buf
543}
544
545fn raster(buf: &mut [u8], res: u32, pts: &[[f32; 2]; 3], color: [u8; 4], alpha: bool) {
546 let [a, b, c] = pts;
547 let area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
548 if area.abs() < 1e-6 {
549 return;
550 }
551 let minx = a[0].min(b[0]).min(c[0]).floor().max(0.0) as u32;
552 let maxx = a[0]
553 .max(b[0])
554 .max(c[0])
555 .ceil()
556 .min(res as f32 - 1.0)
557 .max(0.0) as u32;
558 let miny = a[1].min(b[1]).min(c[1]).floor().max(0.0) as u32;
559 let maxy = a[1]
560 .max(b[1])
561 .max(c[1])
562 .ceil()
563 .min(res as f32 - 1.0)
564 .max(0.0) as u32;
565 for py in miny..=maxy {
566 for px in minx..=maxx {
567 let x = px as f32 + 0.5;
568 let y = py as f32 + 0.5;
569 let w0 = (b[0] - a[0]) * (y - a[1]) - (b[1] - a[1]) * (x - a[0]);
570 let w1 = (c[0] - b[0]) * (y - b[1]) - (c[1] - b[1]) * (x - b[0]);
571 let w2 = (a[0] - c[0]) * (y - c[1]) - (a[1] - c[1]) * (x - c[0]);
572 let inside =
573 (w0 >= 0.0 && w1 >= 0.0 && w2 >= 0.0) || (w0 <= 0.0 && w1 <= 0.0 && w2 <= 0.0);
574 if !inside {
575 continue;
576 }
577 let i = ((py * res + px) as usize) * 4;
578 if !alpha {
579 buf[i..i + 4].copy_from_slice(&color);
580 } else {
581 let sa = color[3] as f32 / 255.0;
582 let da = buf[i + 3] as f32 / 255.0;
583 let oa = sa + da * (1.0 - sa);
584 for k in 0..3 {
585 let sv = color[k] as f32;
586 let dv = buf[i + k] as f32;
587 buf[i + k] = if oa > 1e-6 {
588 ((sv * sa + dv * da * (1.0 - sa)) / oa).min(255.0).round() as u8
589 } else {
590 0
591 };
592 }
593 buf[i + 3] = (oa * 255.0).round() as u8;
594 }
595 }
596 }
597}
598
599fn downsample(src: &[u8], os: u32, dst: &mut [u8], frame: u32) {
601 if os == 1 {
602 dst.copy_from_slice(src);
603 return;
604 }
605 let res = frame * os;
606 for fy in 0..frame {
607 for fx in 0..frame {
608 let (mut rs, mut gs, mut bs, mut asum) = (0f32, 0f32, 0f32, 0f32);
609 for dy in 0..os {
610 for dx in 0..os {
611 let sx = fx * os + dx;
612 let sy = fy * os + dy;
613 let i = ((sy * res + sx) as usize) * 4;
614 let a = src[i + 3] as f32 / 255.0;
615 rs += src[i] as f32 * a;
616 gs += src[i + 1] as f32 * a;
617 bs += src[i + 2] as f32 * a;
618 asum += a;
619 }
620 }
621 let o = ((fy * frame + fx) as usize) * 4;
622 let n = (os * os) as f32;
623 if asum > 1e-5 {
624 dst[o] = (rs / asum).min(255.0).round() as u8;
625 dst[o + 1] = (gs / asum).min(255.0).round() as u8;
626 dst[o + 2] = (bs / asum).min(255.0).round() as u8;
627 }
628 dst[o + 3] = (asum / n * 255.0).round() as u8;
629 }
630 }
631}
632
633#[cfg(test)]
634mod tests {
635 use super::*;
636 use crate::ops;
637 use crate::primitives::PrimitiveKind;
638 use crate::terrain;
639 use crate::transform::Transform;
640 use glam::Quat;
641
642 #[test]
643 fn box_bakes_an_opaque_silhouette_on_transparent_bg() {
644 let mut p = Project::new("bake");
645 let (node, _m) = ops::add_primitive(
646 &mut p,
647 None,
648 "box",
649 PrimitiveKind::Box,
650 1.0,
651 1.0,
652 4,
653 Transform::from_parts(Vec3::ZERO, Quat::IDENTITY, Vec3::ONE),
654 );
655 let opt = BakeOptions {
656 frame_px: 32,
657 oversample: 2,
658 azimuths: vec![45.0, 225.0],
659 ..Default::default()
660 };
661 let sheet = bake(&p, node, &opt).unwrap();
662 assert_eq!(sheet.width, 64);
663 assert_eq!(sheet.height, 32);
664 assert_eq!(sheet.rgba.len(), (64 * 32 * 4) as usize);
665
666 let f0 = sheet.frame_rgba(0).unwrap();
667 let px = |x: u32, y: u32| &f0[((y * 32 + x) * 4) as usize..];
668 assert!(px(16, 16)[3] > 200, "center must be covered");
670 assert_eq!(px(0, 0)[3], 0, "corner must stay transparent");
671 assert_eq!(px(31, 31)[3], 0, "corner must stay transparent");
672 let f1 = sheet.frame_rgba(1).unwrap();
674 assert!(f1.iter().skip(3).step_by(4).any(|a| *a > 200));
675 }
676
677 #[test]
678 fn bake_covers_terrain_tilemap_and_water() {
679 let mut p = Project::new("bake2");
680 let root = ops::add_node(&mut p, None, "root", Transform::default(), NodeKind::Empty);
681 let (_t, _) = terrain::add_terrain(
682 &mut p,
683 Some(root),
684 "Karte",
685 4.0,
686 4.0,
687 4,
688 Transform::default(),
689 );
690 let (_w, _) = ops::add_primitive(
691 &mut p,
692 Some(root),
693 "w",
694 PrimitiveKind::Box,
695 0.5,
696 0.5,
697 4,
698 Transform::from_parts(Vec3::new(0.0, 0.3, 0.0), Quat::IDENTITY, Vec3::ONE),
699 );
700 let opt = BakeOptions {
701 frame_px: 48,
702 oversample: 1,
703 azimuths: vec![45.0],
704 ..Default::default()
705 };
706 let sheet = bake(&p, root, &opt).unwrap();
707 let opaque = sheet
708 .rgba
709 .iter()
710 .skip(3)
711 .step_by(4)
712 .filter(|a| **a > 200)
713 .count();
714 assert!(
716 opaque > 250,
717 "subtree bake should cover the frame, got {opaque}"
718 );
719 }
720
721 #[test]
724 fn animated_bake_loops_and_grid_layout() {
725 let mut p = Project::new("anim");
726 let (water, _, _) = crate::terrain::add_water(&mut p, None, "See", 6.0, 6.0, 0.0);
727 p.scene.get_mut(water).unwrap().motion = crate::motion::Motion::Waves {
729 amp: 0.5,
730 speed: 1.0,
731 };
732
733 let opt = BakeOptions {
734 frame_px: 64,
735 oversample: 1,
736 azimuths: vec![45.0, 225.0],
737 anim_frames: 8,
738 ..Default::default()
739 };
740 let sheet = bake(&p, water, &opt).unwrap();
741 assert_eq!(sheet.views(), 2);
742 assert_eq!(sheet.anim(), 8);
743 assert_eq!(sheet.frames(), 16);
744 assert_eq!(sheet.width, 512);
745 assert_eq!(sheet.height, 128);
746 assert_eq!(sheet.rgba.len(), (512 * 128 * 4) as usize);
747
748 let a = sheet.frame_rgba_at(0, 0).unwrap();
750 let b = sheet.frame_rgba_at(0, 2).unwrap();
751 assert_ne!(a, b, "loop frames of a moving lake must differ");
752 for v in 0..2 {
755 for f in 0..8 {
756 let img = sheet.frame_rgba_at(v, f).unwrap();
757 let covered = img.iter().skip(3).step_by(4).filter(|al| **al > 30).count();
758 assert!(covered > 300, "frame {v}/{f} too empty: {covered} px");
759 }
760 }
761 assert_eq!(sheet.frame_rgba_at(2, 0), None);
763 assert_eq!(sheet.frame_rgba_at(0, 8), None);
764
765 let still = bake(
767 &p,
768 water,
769 &BakeOptions {
770 frame_px: 64,
771 oversample: 1,
772 azimuths: vec![45.0, 225.0],
773 ..Default::default()
774 },
775 )
776 .unwrap();
777 assert_eq!(still.height, 64);
778 assert_eq!(still.anim(), 1);
779 let first = still.frame_rgba(0).unwrap().to_vec();
780 let via_at = still.frame_rgba_at(0, 0).unwrap().to_vec();
781 assert_eq!(first, via_at, "strip indexing stays compatible");
782 }
783
784 #[test]
785 fn invisible_subtrees_are_skipped() {
786 let mut p = Project::new("bake3");
787 let (node, _) = ops::add_primitive(
788 &mut p,
789 None,
790 "box",
791 PrimitiveKind::Box,
792 1.0,
793 1.0,
794 4,
795 Transform::default(),
796 );
797 p.scene.get_mut(node).unwrap().visible = false;
798 let opt = BakeOptions {
799 frame_px: 16,
800 oversample: 1,
801 azimuths: vec![0.0],
802 ..Default::default()
803 };
804 let sheet = bake(&p, node, &opt).unwrap();
805 assert!(
806 sheet.rgba.iter().all(|b| *b == 0),
807 "hidden node bakes nothing"
808 );
809 }
810
811 #[test]
814 fn bake_clip_animation_poses_skins_per_column() {
815 let mut p = Project::new("clip");
816 let mut sk = crate::skeleton::Skeleton::new("rig");
817 sk.add_joint(
818 "Hips",
819 None,
820 Transform::from_parts(Vec3::ZERO, Quat::IDENTITY, Vec3::ONE),
821 );
822 let rig = p.library.add_skeleton(sk);
823
824 let m = Mesh {
825 name: "tri".into(),
826 positions: vec![[0.0, 0.0, 0.0], [0.8, 0.0, 0.0], [0.0, 0.8, 0.0]],
827 skin: Some(crate::mesh::Skin {
828 skeleton: rig,
829 joints: vec![[0, 0, 0, 0]; 3],
830 weights: vec![[1.0, 0.0, 0.0, 0.0]; 3],
831 }),
832 ..Default::default()
833 };
834 let mesh = p.library.add_mesh(m);
835
836 let hero = ops::add_node(
837 &mut p,
838 None,
839 "hero",
840 Transform::default(),
841 NodeKind::SkeletonInstance { skeleton: rig },
842 );
843 ops::add_node(
844 &mut p,
845 Some(hero),
846 "body",
847 Transform::default(),
848 NodeKind::MeshInstance {
849 mesh,
850 material: None,
851 skeleton_node: Some(hero),
852 },
853 );
854
855 let mut a = crate::animation::Animation::new("lift");
856 a.looping = true;
857 let mut ch = crate::animation::Channel::new(
858 crate::animation::Target::Joint("Hips".into()),
859 crate::animation::ChannelPath::Translation,
860 );
861 ch.space = crate::animation::Space::RelativeToBind;
862 ch.set_key(0.0, crate::animation::KeyValue::Vec3([0.0, 0.0, 0.0]));
863 ch.set_key(1.0, crate::animation::KeyValue::Vec3([0.0, 1.2, 0.0]));
864 a.channels.push(ch);
865 let anim = p.library.add_animation(a);
866
867 let opt = BakeOptions {
868 frame_px: 64,
869 oversample: 1,
870 azimuths: vec![45.0, 225.0],
871 anim_frames: 4,
872 animation: Some(anim),
873 ..Default::default()
874 };
875 let sheet = bake(&p, hero, &opt).unwrap();
876 assert_eq!(sheet.views(), 2);
877 assert_eq!(sheet.anim(), 4);
878 assert_eq!(sheet.width, 256);
879 assert_eq!(sheet.height, 128);
880
881 let f0 = sheet.frame_rgba_at(0, 0).unwrap();
883 let f2 = sheet.frame_rgba_at(0, 2).unwrap();
884 assert_ne!(f0, f2, "clip columns must differ");
885 let centroid = |f: &[u8]| -> f32 {
886 let (mut s, mut n) = (0.0f32, 0.0f32);
887 for y in 0..64usize {
888 for x in 0..64usize {
889 let a = f[(y * 64 + x) * 4 + 3] as f32;
890 if a > 8.0 {
891 s += y as f32 * a;
892 n += a;
893 }
894 }
895 }
896 if n == 0.0 {
897 -1.0
898 } else {
899 s / n
900 }
901 };
902 let (c0, c2) = (centroid(&f0), centroid(&f2));
903 assert!(c0 >= 0.0 && c2 >= 0.0, "every column shows the sprite");
904 assert!(
905 (c0 - c2).abs() > 2.0,
906 "the clip must move the sprite between columns (c0={c0} c2={c2})"
907 );
908 }
909}