mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-25 08:50:46 +01:00
Bake mode: list overlapping UVs and unpaired parts before baking
Above the bake bar, bake mode lists what would spoil the next bake of the included texture sets: a UV layout overlapping by more than 1%, and under "By Mesh Name" the low-poly parts no high-poly part matches and the high-poly parts that match no low-poly part. The pairing comes from the bake's own name keys, now one helper the bake and the list share.
This commit is contained in:
1 parent
4fd1e1448e
commit
5214f3dbba
14 files changed
+684
-71
No files matched your search
@@ -9,6 +9,7 @@ mod bake_request;
|
||||
mod cage;
|
||||
mod high_poly;
|
||||
mod mesh_extent;
|
||||
mod name_pair;
|
||||
mod progress;
|
||||
|
||||
pub use bake_error::BakeError;
|
||||
@@ -17,6 +18,7 @@ pub use bake_request::BakeRequest;
|
||||
pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach};
|
||||
pub use high_poly::HighPoly;
|
||||
pub(crate) use mesh_extent::MeshExtent;
|
||||
pub use name_pair::NamePair;
|
||||
pub use progress::Progress;
|
||||
|
||||
mod map;
|
||||
|
||||
@@ -4,8 +4,10 @@ mod curvature_tuning;
|
||||
mod diffusion;
|
||||
mod normal_curvature;
|
||||
mod normalization;
|
||||
mod part_key;
|
||||
pub(crate) use diffusion::diffuse;
|
||||
pub(crate) use normalization::normalize;
|
||||
pub(crate) use part_key::part_key;
|
||||
mod sample;
|
||||
mod seam;
|
||||
pub(crate) use seam::fix_seams;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A mesh part's key in `keys` (shared by names that agree once `suffix` is dropped), whether it ignores backfaces, and its lowercase name without that suffix
|
||||
pub(crate) fn part_key(name: &str, suffix: &str, backface_suffix: &str, keys: &mut HashMap<String, u32>) -> (u32, bool, String) {
|
||||
let name = name.trim().to_lowercase();
|
||||
let ignore_backface = !backface_suffix.is_empty() && name.ends_with(backface_suffix);
|
||||
let name = if ignore_backface { name.strip_suffix(backface_suffix).unwrap_or(&name).to_owned() } else { name };
|
||||
|
||||
(match_key(&name, suffix, keys), ignore_backface, name)
|
||||
}
|
||||
|
||||
/// The key in `keys` of the lowercase part name `name` without `suffix`
|
||||
fn match_key(name: &str, suffix: &str, keys: &mut HashMap<String, u32>) -> u32 {
|
||||
let suffix = suffix.trim().to_lowercase();
|
||||
let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(name).to_string();
|
||||
let next = keys.len() as u32;
|
||||
*keys.entry(base).or_insert(next)
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::part_key::part_key;
|
||||
use super::sampling::{generated_hue, interpolate, splitmix64};
|
||||
use crate::BakeRequest;
|
||||
use crate::tracing::{ANY, TraceMesh};
|
||||
@@ -50,21 +51,24 @@ impl<'a> Source<'a> {
|
||||
let mut mesh_ids = Vec::with_capacity(mesh.submeshes.len());
|
||||
let mut part_keys = Vec::with_capacity(mesh.submeshes.len());
|
||||
let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase();
|
||||
|
||||
for (part_index, submesh) in mesh.submeshes.iter().enumerate() {
|
||||
let first_triangle = (submesh.start / 3) as usize;
|
||||
let last_triangle = (submesh.start.saturating_add(submesh.count) / 3) as usize;
|
||||
let range = first_triangle.min(last_triangle)..last_triangle.min(triangle_count);
|
||||
part.get_mut(range.clone()).unwrap_or_default().fill(part_index as u32);
|
||||
let name = submesh.name.trim().to_lowercase();
|
||||
let ignore_backface = !backface_suffix.is_empty() && name.ends_with(&backface_suffix);
|
||||
|
||||
let (key, ignore_backface, name) = part_key(&submesh.name, suffix, &backface_suffix, keys);
|
||||
backface_culling.get_mut(range).unwrap_or_default().fill(ignore_backface);
|
||||
let name = if ignore_backface { name.strip_suffix(&backface_suffix).unwrap_or(&name) } else { &name };
|
||||
part_keys.push(match_key(name, suffix, keys));
|
||||
part_keys.push(key);
|
||||
|
||||
let next = mesh_keys.len() as u32;
|
||||
let file_id = file_ids.get(part_index).copied().unwrap_or(0);
|
||||
mesh_ids.push(*mesh_keys.entry((file_id, name.to_owned())).or_insert(next));
|
||||
mesh_ids.push(*mesh_keys.entry((file_id, name)).or_insert(next));
|
||||
}
|
||||
|
||||
let key = part.iter().map(|part_index| part_keys.get(*part_index as usize).copied().unwrap_or(ANY)).collect();
|
||||
|
||||
Source {
|
||||
mesh,
|
||||
bvh,
|
||||
@@ -138,11 +142,3 @@ fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 {
|
||||
let color = sampled_color * material.factor;
|
||||
Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w)
|
||||
}
|
||||
|
||||
fn match_key(name: &str, suffix: &str, keys: &mut HashMap<String, u32>) -> u32 {
|
||||
let name = name.trim().to_lowercase();
|
||||
let suffix = suffix.trim().to_lowercase();
|
||||
let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string();
|
||||
let next = keys.len() as u32;
|
||||
*keys.entry(base).or_insert(next)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! How "By Mesh Name" pairs low-poly parts with high-poly parts, listed before a bake runs
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use texturecraft_core::HighPolySettings;
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::map::part_key;
|
||||
|
||||
/// A low-poly part and the high-poly part its rays may hit under "By Mesh Name"; one side is missing when that part pairs with nothing
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct NamePair {
|
||||
/// The low-poly part's name as in its mesh
|
||||
pub low: Option<String>,
|
||||
/// The high-poly part's name as in its mesh
|
||||
pub high: Option<String>,
|
||||
}
|
||||
|
||||
impl NamePair {
|
||||
/// Each part of `low` in `material` with every `high` part it pairs with (a row per pair), then the `high` parts pairing with none; keyed like the bake, low poly first
|
||||
pub fn list(low: &Mesh, material: usize, high: &Mesh, settings: &HighPolySettings) -> Vec<NamePair> {
|
||||
let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase();
|
||||
let mut keys = HashMap::new();
|
||||
let mut keyed = |mesh: &Mesh, suffix: &str, only_material: Option<usize>| {
|
||||
let mut seen = HashSet::new();
|
||||
let mut parts = Vec::new();
|
||||
for part in mesh.submeshes.iter().filter(|part| only_material.is_none_or(|material| part.material == material)) {
|
||||
let (key, ..) = part_key(&part.name, suffix, &backface_suffix, &mut keys);
|
||||
if seen.insert(part.name.as_str()) {
|
||||
parts.push((key, part.name.clone()));
|
||||
}
|
||||
}
|
||||
parts
|
||||
};
|
||||
let low_parts = keyed(low, &settings.low_suffix, Some(material));
|
||||
let high_parts = keyed(high, &settings.high_suffix, None);
|
||||
|
||||
let mut pairs = Vec::new();
|
||||
for (key, low_name) in &low_parts {
|
||||
let matches: Vec<&String> = high_parts.iter().filter(|(high_key, _)| high_key == key).map(|(_, name)| name).collect();
|
||||
if matches.is_empty() {
|
||||
pairs.push(NamePair { low: Some(low_name.clone()), high: None });
|
||||
}
|
||||
pairs.extend(matches.into_iter().map(|high_name| NamePair { low: Some(low_name.clone()), high: Some(high_name.clone()) }));
|
||||
}
|
||||
|
||||
let low_keys: HashSet<u32> = low_parts.iter().map(|(key, _)| *key).collect();
|
||||
pairs.extend(high_parts.into_iter().filter(|(key, _)| !low_keys.contains(key)).map(|(_, name)| NamePair { low: None, high: Some(name) }));
|
||||
pairs
|
||||
}
|
||||
|
||||
/// Whether one side is missing: a part the bake will leave unpaired
|
||||
pub fn unpaired(&self) -> bool {
|
||||
self.low.is_none() || self.high.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_geom::SubMesh;
|
||||
|
||||
/// A mesh with one empty part per (name, material)
|
||||
fn parts(names: &[(&str, usize)]) -> Mesh {
|
||||
Mesh {
|
||||
submeshes: names.iter().map(|(name, material)| SubMesh { name: (*name).into(), material: *material, start: 0, count: 0 }).collect(),
|
||||
materials: vec!["first".into(), "second".into()],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn pair(low: Option<&str>, high: Option<&str>) -> NamePair {
|
||||
NamePair { low: low.map(Into::into), high: high.map(Into::into) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parts_pair_by_name_without_their_suffixes() {
|
||||
let low = parts(&[("Barrel_low", 0), ("Base_low", 0), ("Slide_low", 1)]);
|
||||
let high = parts(&[("Barrel_high", 0), ("Slide_high", 0), ("Grip_high", 0), ("BARREL_high_ignorebf", 0)]);
|
||||
let settings = HighPolySettings::default();
|
||||
|
||||
assert_eq!(
|
||||
NamePair::list(&low, 0, &high, &settings),
|
||||
vec![
|
||||
pair(Some("Barrel_low"), Some("Barrel_high")),
|
||||
pair(Some("Barrel_low"), Some("BARREL_high_ignorebf")),
|
||||
pair(Some("Base_low"), None),
|
||||
pair(None, Some("Slide_high")),
|
||||
pair(None, Some("Grip_high")),
|
||||
],
|
||||
"another material's parts are left out, so its high-poly part counts as unpaired here"
|
||||
);
|
||||
assert_eq!(NamePair::list(&low, 1, &high, &settings).iter().filter(|pair| !pair.unpaired()).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_split_over_triangle_ranges_is_listed_once() {
|
||||
let low = parts(&[("Body_low", 0), ("Body_low", 0)]);
|
||||
let high = parts(&[("Body_high", 0), ("Body_high", 0)]);
|
||||
|
||||
assert_eq!(NamePair::list(&low, 0, &high, &HighPolySettings::default()), vec![pair(Some("Body_low"), Some("Body_high"))]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! What can spoil a texture set's bake, checked before it runs: overlapping UVs and parts "By Mesh Name" leaves unpaired
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use texturecraft_bake::NamePair;
|
||||
use texturecraft_core::MeshMatchMode;
|
||||
use texturecraft_geom::{Mesh, SubMesh, UvGBuffer, glam::Vec2};
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Side of the UV raster the overlap check counts texels on, per UV tile (as mesh import does)
|
||||
const OVERLAP_CHECK_RESOLUTION: u32 = 512;
|
||||
|
||||
/// The only material of the UV-only mesh the overlap check builds per UV tile
|
||||
const BLOCK_MATERIAL: usize = 0;
|
||||
|
||||
impl Session {
|
||||
/// About the share (0..1) of texture set `texture_set`'s UV layout the bake sees covered more than once, over the UV tiles it bakes: a texel under three triangles counts twice
|
||||
pub fn bake_uv_overlap(&self, texture_set: usize) -> Result<f32> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let mesh = self.bake_mesh(texture_set)?;
|
||||
let (overlaps, covered) = match set.tile_grid() {
|
||||
Some(grid) => {
|
||||
let baked_blocks: BTreeSet<(u32, u32)> =
|
||||
set.uv_tiles.iter().filter(|tile| !set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid.block(*tile)).collect();
|
||||
let blocks = triangles_by_block(&mesh, set.material, (grid.cols, grid.rows), &baked_blocks);
|
||||
blocks
|
||||
.values()
|
||||
.map(|block| overlap_counts(block, BLOCK_MATERIAL))
|
||||
.fold((0, 0), |(overlaps, covered), (block_overlaps, block_covered)| (overlaps + block_overlaps, covered + block_covered))
|
||||
}
|
||||
None => overlap_counts(&mesh, set.material),
|
||||
};
|
||||
|
||||
Ok(if covered == 0 { 0.0 } else { (overlaps as f32 / covered as f32).min(1.0) })
|
||||
}
|
||||
|
||||
/// How texture set `texture_set`'s low-poly parts pair with the high-poly parts ([`NamePair::list`]); `None` unless it bakes from a high poly "By Mesh Name"
|
||||
pub fn bake_name_pairs(&self, texture_set: usize) -> Result<Option<Vec<NamePair>>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let settings = &set.bake.high_poly;
|
||||
let high = self.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high);
|
||||
|
||||
Ok(high.map(|high| NamePair::list(&self.mesh, set.material, &high.mesh, settings)))
|
||||
}
|
||||
|
||||
/// The high-poly parts none of `texture_sets` bakes from, by name: a set matching "Always" bakes from every part, one matching "By Mesh Name" only from the parts its names pair with
|
||||
pub fn bake_unpaired_high_parts(&self, texture_sets: &[usize]) -> Result<Vec<String>> {
|
||||
let (mut paired, mut unpaired) = (BTreeSet::new(), BTreeSet::new());
|
||||
for &texture_set in texture_sets {
|
||||
let settings = &self.doc.project.texture_set(texture_set)?.bake.high_poly;
|
||||
if !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
for pair in self.bake_name_pairs(texture_set)?.unwrap_or_default() {
|
||||
match pair {
|
||||
NamePair { low: Some(_), high: Some(high) } => paired.insert(high),
|
||||
NamePair { low: None, high: Some(high) } => unpaired.insert(high),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Ok(unpaired.difference(&paired).cloned().collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Texels covered more than once and texels covered, rasterizing material `material`'s UVs over 0..1
|
||||
fn overlap_counts(mesh: &Mesh, material: usize) -> (usize, usize) {
|
||||
let gbuffer = UvGBuffer::new(mesh, material, OVERLAP_CHECK_RESOLUTION, OVERLAP_CHECK_RESOLUTION);
|
||||
(gbuffer.overlaps as usize, gbuffer.covered_count())
|
||||
}
|
||||
|
||||
/// Material `material`'s triangles sorted into the `baked_blocks` of a `grid` (columns, rows) atlas their UVs reach, one UV-only mesh per block with the block's UVs over 0..1: a single pass, however many blocks
|
||||
fn triangles_by_block(mesh: &Mesh, material: usize, grid: (u32, u32), baked_blocks: &BTreeSet<(u32, u32)>) -> BTreeMap<(u32, u32), Mesh> {
|
||||
let scale = Vec2::new(grid.0 as f32, grid.1 as f32);
|
||||
let mut blocks: BTreeMap<(u32, u32), Mesh> = BTreeMap::new();
|
||||
for triangle in mesh.triangles_of(material) {
|
||||
let Some([first, second, third]) = mesh.tri(triangle) else { continue };
|
||||
let (Some(first_uv), Some(second_uv), Some(third_uv)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { continue };
|
||||
let uvs = [*first_uv * scale, *second_uv * scale, *third_uv * scale];
|
||||
|
||||
// Every block the triangle's UV bounds touch, so a triangle across a border counts in both
|
||||
let (uv_min, uv_max) = uvs.iter().fold((Vec2::INFINITY, Vec2::NEG_INFINITY), |(uv_min, uv_max), uv| (uv_min.min(*uv), uv_max.max(*uv)));
|
||||
// Capped at the grid: a stray huge UV must not walk billions of blocks
|
||||
let columns = uv_min.x.floor().max(0.0) as u32..=((uv_max.x.ceil() as u32).saturating_sub(1)).min(grid.0 - 1);
|
||||
let rows = uv_min.y.floor().max(0.0) as u32..=((uv_max.y.ceil() as u32).saturating_sub(1)).min(grid.1 - 1);
|
||||
for column in columns {
|
||||
for row in rows.clone() {
|
||||
if !baked_blocks.contains(&(column, row)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let block = blocks.entry((column, row)).or_insert_with(|| Mesh { materials: vec![String::new()], ..Mesh::default() });
|
||||
let offset = Vec2::new(column as f32, row as f32);
|
||||
block.indices.extend(block.uvs.len() as u32..block.uvs.len() as u32 + 3);
|
||||
block.uvs.extend(uvs.iter().map(|uv| *uv - offset));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for block in blocks.values_mut() {
|
||||
block.submeshes = vec![SubMesh { name: String::new(), material: BLOCK_MATERIAL, start: 0, count: block.indices.len() as u32 }];
|
||||
}
|
||||
|
||||
blocks
|
||||
}
|
||||
@@ -188,7 +188,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas
|
||||
fn bake_mesh(&self, texture_set: usize) -> Result<Arc<Mesh>> {
|
||||
pub(super) fn bake_mesh(&self, texture_set: usize) -> Result<Arc<Mesh>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) {
|
||||
Some(grid) => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Baking tasks, commands, settings helpers, and the mesh-map baking API
|
||||
|
||||
mod bake_cage_inputs;
|
||||
mod bake_checks;
|
||||
mod bake_mesh;
|
||||
mod bake_meshes;
|
||||
mod bake_task;
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! What bake mode lists before a bake: overlapping UVs and parts "By Mesh Name" leaves unpaired
|
||||
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::bake::NamePair;
|
||||
use texturecraft_engine::core::MeshMatchMode;
|
||||
|
||||
/// Two quads side by side; `shared_uvs` lays both on the same UV square instead of side by side in UV space
|
||||
fn two_quads(shared_uvs: bool) -> Session {
|
||||
let second_u = if shared_uvs { 0.0 } else { 0.5 };
|
||||
let obj = format!(
|
||||
"o Box_low\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\
|
||||
o Lone_low\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt {second_u} 0\nvt {} 0\nvt {} 1\nvt {second_u} 1\nf 5/5 6/6 7/7 8/8\n",
|
||||
second_u + 0.5,
|
||||
second_u + 0.5
|
||||
);
|
||||
Session::from_mesh_bytes("quads.obj", obj.as_bytes(), 128, "quads").unwrap()
|
||||
}
|
||||
|
||||
const HIGH_POLY: &[u8] = b"o Box_high\nv 0 0 0.01\nv 1 0 0.01\nv 0 1 0.01\nf 1 2 3\no Extra_high\nv 2 0 0.01\nv 3 0 0.01\nv 2 1 0.01\nf 4 5 6\n";
|
||||
|
||||
#[test]
|
||||
fn overlapping_uvs_are_measured_before_the_bake() {
|
||||
assert!(two_quads(true).bake_uv_overlap(0).unwrap() > 0.4, "the second quad covers the first one's UVs");
|
||||
assert_eq!(two_quads(false).bake_uv_overlap(0).unwrap(), 0.0, "side by side in UV space nothing overlaps");
|
||||
const MISSING_TEXTURE_SET: usize = 9;
|
||||
assert!(two_quads(false).bake_uv_overlap(MISSING_TEXTURE_SET).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_in_a_uv_tile_left_out_of_the_bake_is_not_counted() {
|
||||
// One quad in tile 1001, two on the same UVs in tile 1002
|
||||
let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n\
|
||||
o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 5/5 6/6 7/7 8/8\n\
|
||||
o Third\nv 4 0 0\nv 5 0 0\nv 5 1 0\nv 4 1 0\nvt 1 0\nvt 1.5 0\nvt 1.5 1\nvt 1 1\nf 9/9 10/10 11/11 12/12\n";
|
||||
let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]);
|
||||
assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "the last two quads share tile 1002's UVs");
|
||||
|
||||
session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002);
|
||||
assert_eq!(session.bake_uv_overlap(0).unwrap(), 0.0, "tile 1001 alone has no overlap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_is_measured_at_the_same_detail_in_every_uv_tile() {
|
||||
// Tiles 1001 and 1010 make a grid ten tiles wide; 512 texels across all ten would give each tile about 51
|
||||
const TEXELS_PER_TILE: f32 = 512.0;
|
||||
const SLIVER_TEXELS: f32 = 4.0;
|
||||
// Inside tile 1010 (column 9), clear of the wide raster's texel centres
|
||||
const SLIVER_LEFT_U: f32 = 9.1;
|
||||
let (left, right) = (SLIVER_LEFT_U, SLIVER_LEFT_U + SLIVER_TEXELS / TEXELS_PER_TILE);
|
||||
let sliver = |name: &str, first: u32, x: f32| {
|
||||
let (second, third, fourth) = (first + 1, first + 2, first + 3);
|
||||
let corners = format!("v {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\n", x + 1.0, x + 1.0);
|
||||
format!(
|
||||
"o {name}\n{corners}vt {left} 0\nvt {right} 0\nvt {right} 1\nvt {left} 1\nf {first}/{first} {second}/{second} {third}/{third} {fourth}/{fourth}\n"
|
||||
)
|
||||
};
|
||||
let corner = "o Corner\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 0.5 0\nvt 0.5 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n";
|
||||
let obj = [corner.to_owned(), sliver("First", 5, 2.0), sliver("Second", 9, 4.0)].concat();
|
||||
let session = Session::from_mesh_bytes("wide.obj", obj.as_bytes(), 128, "wide").unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1010]);
|
||||
|
||||
assert!(session.bake_uv_overlap(0).unwrap() > 0.0, "two slivers a few texels wide overlap in tile 1010");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_triangle_across_a_uv_tile_border_counts_in_both_tiles() {
|
||||
// Two quads on the same UVs, from u 0.9 in tile 1001 to u 1.1 in tile 1002
|
||||
let obj = "o First\nv 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 1/1 2/2 3/3 4/4\n\
|
||||
o Second\nv 2 0 0\nv 3 0 0\nv 3 1 0\nv 2 1 0\nvt 0.9 0\nvt 1.1 0\nvt 1.1 1\nvt 0.9 1\nf 5/5 6/6 7/7 8/8\n";
|
||||
let mut session = Session::from_mesh_bytes("border.obj", obj.as_bytes(), 128, "border").unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]);
|
||||
|
||||
for (excluded, kept) in [(1002, 1001), (1001, 1002)] {
|
||||
let excluded_tiles = &mut session.doc.project.texture_sets[0].bake_excluded_tiles;
|
||||
excluded_tiles.clear();
|
||||
excluded_tiles.insert(excluded);
|
||||
assert!(session.bake_uv_overlap(0).unwrap() > 0.4, "tile {kept} holds part of the overlap");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpaired_parts_are_listed_only_when_matching_by_name() {
|
||||
let mut session = two_quads(false);
|
||||
assert_eq!(session.bake_name_pairs(0).unwrap(), None, "no high poly");
|
||||
session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap();
|
||||
assert_eq!(session.bake_name_pairs(0).unwrap(), None, "\"Always\" pairs every part");
|
||||
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
let pairs = session.bake_name_pairs(0).unwrap().unwrap();
|
||||
let unpaired: Vec<&NamePair> = pairs.iter().filter(|pair| pair.unpaired()).collect();
|
||||
assert_eq!(unpaired, [&NamePair { low: Some("Lone_low".into()), high: None }, &NamePair { low: None, high: Some("Extra_high".into()) }], "{pairs:?}");
|
||||
assert!(pairs.contains(&NamePair { low: Some("Box_low".into()), high: Some("Box_high".into()) }));
|
||||
|
||||
session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true;
|
||||
assert_eq!(session.bake_name_pairs(0).unwrap(), None, "the low poly as its own high poly pairs every part");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_matching_always_bakes_from_every_high_poly_part() {
|
||||
let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\
|
||||
o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n";
|
||||
let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap();
|
||||
session.add_high_poly_bytes("high.obj", HIGH_POLY.to_vec()).unwrap();
|
||||
let both = [0, 1];
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), Vec::<String>::new(), "the other set matches \"Always\"");
|
||||
|
||||
session.doc.project.texture_sets[1].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
assert_eq!(session.bake_unpaired_high_parts(&both).unwrap(), ["Extra_high"]);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! Keep feature tests in their own modules; the standalone session.rs target remains available.
|
||||
|
||||
mod bake;
|
||||
mod bake_checks;
|
||||
mod bake_resolution;
|
||||
mod bake_settings;
|
||||
mod bake_tiles;
|
||||
|
||||
+94
-52
@@ -20,7 +20,7 @@ pub struct UvGBuffer {
|
||||
pub tri: Vec<u32>,
|
||||
/// Barycentric weights of the triangle's second and third vertices.
|
||||
pub bary: Vec<[f32; 2]>,
|
||||
/// Texels written by more than one triangle (overlapping UVs).
|
||||
/// Covers past the first on texels where any cover has the texel center strictly inside (overlapping UVs; an edge two neighbours share is no overlap)
|
||||
pub overlaps: u32,
|
||||
}
|
||||
|
||||
@@ -41,74 +41,95 @@ fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 {
|
||||
(b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)
|
||||
}
|
||||
|
||||
/// Twice-areas (in texels²) below this are degenerate triangles, which cover nothing
|
||||
const MIN_DOUBLE_AREA: f32 = 1e-12;
|
||||
|
||||
/// How far outside a triangle (as a share of its double area) a texel center may sit and still count as covered, so shared edges leave no gaps
|
||||
const EDGE_TOLERANCE: f32 = 1e-6;
|
||||
|
||||
impl UvGBuffer {
|
||||
/// Rasterize the triangles of material `material` at `width × height`.
|
||||
/// Rasterize the triangles of material `material` at `width × height`
|
||||
pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> UvGBuffer {
|
||||
let (w, h) = (width.max(1), height.max(1));
|
||||
let size = Vec2::new(w as f32, h as f32);
|
||||
let bands = h.div_ceil(BAND) as usize;
|
||||
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); bands];
|
||||
for t in mesh.triangles_of(material) {
|
||||
let Some([a, b, c]) = mesh.tri(t) else { continue };
|
||||
let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue };
|
||||
let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64;
|
||||
let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64;
|
||||
if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() {
|
||||
let (width, height) = (width.max(1), height.max(1));
|
||||
let size = Vec2::new(width as f32, height as f32);
|
||||
let corner_uvs = |triangle: usize| {
|
||||
let [first, second, third] = mesh.tri(triangle)?;
|
||||
Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?])
|
||||
};
|
||||
|
||||
// Sort triangles into bands of rows so each band rasterizes on its own thread
|
||||
let mut bands: Vec<Vec<u32>> = vec![Vec::new(); height.div_ceil(BAND) as usize];
|
||||
for triangle in mesh.triangles_of(material) {
|
||||
let Some(uvs) = corner_uvs(triangle) else { continue };
|
||||
let top = (uvs.iter().map(|uv| uv.y).fold(f32::INFINITY, f32::min) * size.y).floor().max(0.0) as i64;
|
||||
let bottom = (uvs.iter().map(|uv| uv.y).fold(f32::NEG_INFINITY, f32::max) * size.y).ceil().min(size.y) as i64;
|
||||
if bottom <= top || !uvs.iter().all(|uv| uv.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let (b0, b1) = ((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize);
|
||||
for bin in bins.iter_mut().take(b1 + 1).skip(b0) {
|
||||
bin.push(t as u32);
|
||||
|
||||
let (first_band, last_band) = ((top / BAND as i64) as usize, ((bottom - 1).max(0) / BAND as i64) as usize);
|
||||
for band in bands.iter_mut().take(last_band + 1).skip(first_band) {
|
||||
band.push(triangle as u32);
|
||||
}
|
||||
}
|
||||
let n = w as usize * h as usize;
|
||||
let mut tri = vec![NO_TRI; n];
|
||||
let mut bary = vec![[0.0f32; 2]; n];
|
||||
let band_len = (BAND * w) as usize;
|
||||
|
||||
let texel_count = width as usize * height as usize;
|
||||
let mut tri = vec![NO_TRI; texel_count];
|
||||
let mut bary = vec![[0.0f32; 2]; texel_count];
|
||||
let band_texels = (BAND * width) as usize;
|
||||
let overlaps: u32 = tri
|
||||
.par_chunks_mut(band_len)
|
||||
.zip(bary.par_chunks_mut(band_len))
|
||||
.par_chunks_mut(band_texels)
|
||||
.zip(bary.par_chunks_mut(band_texels))
|
||||
.enumerate()
|
||||
.map(|(bi, (tri, bary))| {
|
||||
let mut overlaps = 0u32;
|
||||
let row0 = bi as u32 * BAND;
|
||||
let rows = (tri.len() as u32) / w;
|
||||
for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
let Some([a, b, c]) = mesh.tri(t as usize) else { continue };
|
||||
let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue };
|
||||
let (pa, pb, pc) = (ua * size, ub * size, uc * size);
|
||||
let area = edge(pa, pb, pc);
|
||||
if area.abs() < 1e-12 {
|
||||
.map(|(band_index, (band_tri, band_bary))| {
|
||||
// Per texel: how many triangles cover it, and whether any has its center strictly inside, so the count doesn't depend on triangle order
|
||||
let mut covers = vec![0u32; band_tri.len()];
|
||||
let mut strict_cover = vec![false; band_tri.len()];
|
||||
let first_row = band_index as u32 * BAND;
|
||||
let band_rows = (band_tri.len() as u32) / width;
|
||||
for &triangle in bands.get(band_index).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
let Some(uvs) = corner_uvs(triangle as usize) else { continue };
|
||||
let [a, b, c] = uvs.map(|uv| uv * size);
|
||||
let double_area = edge(a, b, c);
|
||||
if double_area.abs() < MIN_DOUBLE_AREA {
|
||||
continue;
|
||||
}
|
||||
let eps = -1e-6 * area.abs();
|
||||
let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32;
|
||||
let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w);
|
||||
let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0);
|
||||
let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows);
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum());
|
||||
if w0 < eps || w1 < eps || w2 < eps {
|
||||
|
||||
let tolerance = EDGE_TOLERANCE * double_area.abs();
|
||||
let (sign, inverse_area) = (double_area.signum(), 1.0 / double_area.abs());
|
||||
let left = a.x.min(b.x).min(c.x).floor().max(0.0) as u32;
|
||||
let right = (a.x.max(b.x).max(c.x).ceil().min(width as f32) as u32).min(width);
|
||||
let top = (a.y.min(b.y).min(c.y).floor().max(first_row as f32) as u32).max(first_row);
|
||||
let bottom = (a.y.max(b.y).max(c.y).ceil() as u32).min(first_row + band_rows);
|
||||
for y in top..bottom {
|
||||
for x in left..right {
|
||||
let center = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let weights = [edge(b, c, center) * sign, edge(c, a, center) * sign, edge(a, b, center) * sign];
|
||||
if weights.iter().any(|weight| *weight < -tolerance) {
|
||||
continue;
|
||||
}
|
||||
let i = ((y - row0) * w + x) as usize;
|
||||
if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) {
|
||||
if *slot != NO_TRI {
|
||||
overlaps += 1;
|
||||
}
|
||||
*slot = t;
|
||||
let inv = 1.0 / area.abs();
|
||||
*bw = [w1 * inv, w2 * inv];
|
||||
}
|
||||
|
||||
let index = ((y - first_row) * width + x) as usize;
|
||||
let (Some(slot), Some(slot_bary), Some(cover_count), Some(strict)) =
|
||||
(band_tri.get_mut(index), band_bary.get_mut(index), covers.get_mut(index), strict_cover.get_mut(index))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
*cover_count += 1;
|
||||
*strict |= weights.iter().all(|weight| *weight > tolerance);
|
||||
*slot = triangle;
|
||||
*slot_bary = [weights[1] * inverse_area, weights[2] * inverse_area];
|
||||
}
|
||||
}
|
||||
}
|
||||
overlaps
|
||||
|
||||
// Every cover past the first overlaps, unless all of them only touch the texel center with an edge (neighbours sharing it)
|
||||
covers.iter().zip(&strict_cover).filter(|(_, strict)| **strict).map(|(count, _)| count.saturating_sub(1)).sum::<u32>()
|
||||
})
|
||||
.sum();
|
||||
UvGBuffer { width: w, height: h, tri, bary, overlaps }
|
||||
|
||||
UvGBuffer { width, height, tri, bary, overlaps }
|
||||
}
|
||||
|
||||
pub fn covered(&self, i: usize) -> bool {
|
||||
@@ -171,6 +192,27 @@ mod tests {
|
||||
assert_eq!(g.overlaps, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighbours_sharing_an_edge_through_texel_centers_do_not_overlap() {
|
||||
// An 8×8 grid of quads at 512 texels: each quad's diagonal runs through 64 texel centers
|
||||
let grid = primitives::plane(1.0, 8);
|
||||
let gbuffer = UvGBuffer::new(&grid, 0, 512, 512);
|
||||
assert_eq!(gbuffer.covered_count(), 512 * 512);
|
||||
assert_eq!(gbuffer.overlaps, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edge_through_a_covered_texel_center_counts_both_edge_covers() {
|
||||
// The texel center (0.5, 0.5) lies inside the first triangle and on the diagonal the other two share
|
||||
let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.2), Vec2::new(0.2, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)];
|
||||
let positions = vec![Vec3::ZERO; uv.len()];
|
||||
// In either order: the inside cover first, or the two edge covers first
|
||||
for indices in [vec![0, 1, 2, 0, 3, 4, 0, 5, 3], vec![0, 3, 4, 0, 5, 3, 0, 1, 2]] {
|
||||
let m = Mesh::from_parts(positions.clone(), None, uv.clone(), indices.clone(), "m").unwrap();
|
||||
assert_eq!(UvGBuffer::new(&m, 0, 1, 1).overlaps, 2, "{indices:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_and_degenerate_triangles() {
|
||||
let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)];
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
//! Problems the next bake would have, listed above the bake bar before Bake is pressed
|
||||
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use egui_phosphor::regular as icon;
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::geom::Mesh;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::trf;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// Share of a texture set's UV layout that may overlap before it is listed (as mesh import warns)
|
||||
const UV_OVERLAP_WARNING: f32 = 0.01;
|
||||
|
||||
/// How many part names a warning spells out before "and N more"
|
||||
const NAMES_SHOWN: usize = 3;
|
||||
|
||||
/// The warnings' gap above the bake bar
|
||||
const WARNINGS_GAP: f32 = 8.0;
|
||||
|
||||
/// The warnings above bake mode's bake bar in the 3D view `viewport`, until a bake starts
|
||||
pub(crate) fn bake_warnings(app: &TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) {
|
||||
if app.bake_progress().is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let warnings = cached_warnings(ctx, &app.session);
|
||||
if warnings.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let tokens = Tokens::get(ctx);
|
||||
let above_bar = super::BAKE_BAR_MARGIN + ctx.global_style().spacing.interact_size.y + WARNINGS_GAP;
|
||||
egui::Area::new(egui::Id::unique("bake_warnings")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -above_bar)).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
egui::Frame::popup(ui.style()).fill(tokens.panel).show(ui, |ui| {
|
||||
for warning in warnings.iter() {
|
||||
ui.label(egui::RichText::new(format!("{} {warning}", icon::WARNING)).color(tokens.warning));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// The warnings for the texture sets the next bake includes, worked out again only when what they read changes
|
||||
pub(crate) fn cached_warnings(ctx: &egui::Context, session: &Session) -> Arc<Vec<String>> {
|
||||
let id = egui::Id::unique("bake_check_warnings");
|
||||
let key = inputs_key(session);
|
||||
// A handle, not an address: a rebuilt high poly could reuse a dropped one's address
|
||||
let high = session.bake_meshes.merged_high().map_or_else(Weak::new, |high| Arc::downgrade(&high.mesh));
|
||||
if let Some((cached_key, cached_high, cached)) = ctx.data(|data| data.get_temp::<(String, Weak<Mesh>, Arc<Vec<String>>)>(id))
|
||||
&& cached_key == key
|
||||
&& cached_high.ptr_eq(&high)
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
let fresh = Arc::new(warnings(session));
|
||||
ctx.data_mut(|data| data.insert_temp(id, (key, high, fresh.clone())));
|
||||
fresh
|
||||
}
|
||||
|
||||
/// Everything the warnings read or show apart from the high poly (cached as a handle): the low poly, the UI language, and per included set its name, material, high-poly settings, UV tile resolutions and the tiles left out of the bake
|
||||
fn inputs_key(session: &Session) -> String {
|
||||
let sets: Vec<_> = baked_sets(session)
|
||||
.filter_map(|index| {
|
||||
let set = session.doc.project.texture_sets.get(index)?;
|
||||
Some((index, &set.name, set.material, &set.bake.high_poly, &set.tile_resolutions, &set.bake_excluded_tiles))
|
||||
})
|
||||
.collect();
|
||||
|
||||
format!("{}|{}|{sets:?}", session.mesh_id, crate::i18n::current().code)
|
||||
}
|
||||
|
||||
/// The texture sets the next bake includes
|
||||
fn baked_sets(session: &Session) -> impl Iterator<Item = usize> + '_ {
|
||||
session.doc.project.texture_sets.iter().enumerate().filter(|(_, set)| set.bake.common.is_enabled && set.has_enabled_bake_tiles()).map(|(index, _)| index)
|
||||
}
|
||||
|
||||
/// Overlapping UVs per included set, its low-poly parts "By Mesh Name" pairs with nothing, then the high-poly parts no included set bakes from
|
||||
pub(crate) fn warnings(session: &Session) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
let included: Vec<usize> = baked_sets(session).collect();
|
||||
for &index in &included {
|
||||
let Some(set) = session.doc.project.texture_sets.get(index) else { continue };
|
||||
|
||||
let overlap = session.bake_uv_overlap(index).unwrap_or(0.0);
|
||||
if overlap > UV_OVERLAP_WARNING {
|
||||
let percent = format!("{:.1}", overlap * 100.0);
|
||||
lines.push(trf(
|
||||
"{set}: {percent}% of the UV layout overlaps, so those texels bake one place for several",
|
||||
&[("set", &set.name), ("percent", &percent)],
|
||||
));
|
||||
}
|
||||
|
||||
let Ok(Some(pairs)) = session.bake_name_pairs(index) else { continue };
|
||||
|
||||
let unpaired_low: Vec<&str> = pairs.iter().filter(|pair| pair.high.is_none()).filter_map(|pair| pair.low.as_deref()).collect();
|
||||
if !unpaired_low.is_empty() {
|
||||
lines.push(trf("{set}: no high poly part matches {names}", &[("set", &set.name), ("names", &listed(&unpaired_low))]));
|
||||
}
|
||||
}
|
||||
|
||||
let unpaired_high = session.bake_unpaired_high_parts(&included).unwrap_or_default();
|
||||
if !unpaired_high.is_empty() {
|
||||
let names: Vec<&str> = unpaired_high.iter().map(String::as_str).collect();
|
||||
lines.push(trf("No low poly part matches {names}", &[("names", &listed(&names))]));
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
/// `names` joined, the first few spelled out and the rest counted
|
||||
fn listed(names: &[&str]) -> String {
|
||||
let shown = names.iter().take(NAMES_SHOWN).copied().collect::<Vec<_>>().join(", ");
|
||||
match names.len().checked_sub(NAMES_SHOWN).filter(|more| *more > 0) {
|
||||
Some(more) => trf("{names} and {count} more", &[("names", &shown), ("count", &more)]),
|
||||
None => shown,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_engine::core::MeshMatchMode;
|
||||
|
||||
/// Part `index` named `name` (an OBJ object): a quad at x offset `x` whose UVs span `u` to `u` + 0.2
|
||||
fn quad(name: &str, index: usize, x: f32, u: f32) -> String {
|
||||
let first = index * 4 + 1;
|
||||
format!(
|
||||
"o {name}\nv {x} 0 0\nv {} 0 0\nv {} 1 0\nv {x} 1 0\nvt {u} 0\nvt {} 0\nvt {} 1\nvt {u} 1\nf {first}/{first} {}/{} {}/{} {}/{}\n",
|
||||
x + 1.0,
|
||||
x + 1.0,
|
||||
u + 0.2,
|
||||
u + 0.2,
|
||||
first + 1,
|
||||
first + 1,
|
||||
first + 2,
|
||||
first + 2,
|
||||
first + 3,
|
||||
first + 3
|
||||
)
|
||||
}
|
||||
|
||||
fn session(overlapping: bool) -> Session {
|
||||
let names = ["Box_low", "Lid_low", "Bolt_low", "Nut_low", "Pin_low"];
|
||||
let obj: String =
|
||||
names.iter().enumerate().map(|(index, name)| quad(name, index, index as f32 * 2.0, if overlapping { 0.0 } else { index as f32 * 0.2 })).collect();
|
||||
Session::from_mesh_bytes("parts.obj", obj.as_bytes(), 128, "parts").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_setup_lists_nothing() {
|
||||
let mut session = session(false);
|
||||
assert_eq!(warnings(&session), Vec::<String>::new());
|
||||
session.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
assert_eq!(warnings(&session), Vec::<String>::new(), "\"Always\" pairs every part");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_set_refreshes_the_cached_warnings() {
|
||||
let mut session = session(true);
|
||||
let ctx = egui::Context::default();
|
||||
let before = cached_warnings(&ctx, &session);
|
||||
assert!(before.iter().any(|line| line.starts_with(&session.doc.project.texture_sets[0].name)), "{before:?}");
|
||||
|
||||
session.doc.project.texture_sets[0].name = "Renamed".into();
|
||||
let after = cached_warnings(&ctx, &session);
|
||||
assert!(after.iter().any(|line| line.starts_with("Renamed:")), "{after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swapping_the_high_poly_refreshes_the_cached_warnings() {
|
||||
let mut session = session(false);
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
session.add_high_poly_bytes("spare.obj", b"o Spare_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
assert!(cached_warnings(&ctx, &session).contains(&"No low poly part matches Spare_high".to_owned()));
|
||||
|
||||
// The new high poly's mesh may take the dropped one's address
|
||||
drop(session.remove_high_poly(0).unwrap());
|
||||
session.add_high_poly_bytes("box.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
let after = cached_warnings(&ctx, &session);
|
||||
assert!(!after.iter().any(|line| line.contains("Spare_high")), "{after:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_the_overlapping_tile_out_refreshes_the_cached_warnings() {
|
||||
// One quad in tile 1001, two on the same UVs in tile 1002
|
||||
let obj = [quad("First_low", 0, 0.0, 0.0), quad("Second_low", 1, 2.0, 1.0), quad("Third_low", 2, 4.0, 1.0)].concat();
|
||||
let mut session = Session::from_mesh_bytes("tiles.obj", obj.as_bytes(), 128, "tiles").unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
assert_eq!(cached_warnings(&ctx, &session).len(), 1, "tile 1002 overlaps");
|
||||
|
||||
session.doc.project.texture_sets[0].bake_excluded_tiles.insert(1002);
|
||||
assert_eq!(*cached_warnings(&ctx, &session), Vec::<String>::new(), "tile 1001 alone has no overlap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_uvs_and_unpaired_parts_are_listed() {
|
||||
let mut session = session(true);
|
||||
session
|
||||
.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Spare_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec())
|
||||
.unwrap();
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
let set = session.doc.project.texture_sets[0].name.clone();
|
||||
|
||||
assert_eq!(
|
||||
warnings(&session),
|
||||
[
|
||||
format!("{set}: 100.0% of the UV layout overlaps, so those texels bake one place for several"),
|
||||
format!("{set}: no high poly part matches Lid_low, Bolt_low, Nut_low and 1 more"),
|
||||
"No low poly part matches Spare_high".to_owned(),
|
||||
]
|
||||
);
|
||||
|
||||
session.doc.project.texture_sets[0].bake.common.is_enabled = false;
|
||||
assert_eq!(warnings(&session), Vec::<String>::new(), "a set the bake leaves out is not checked");
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
//! Bake Mode presentation; persisted settings live in core and edits use engine commands
|
||||
|
||||
mod bake_checks;
|
||||
mod bake_paint_brush;
|
||||
mod bake_visualization_panel;
|
||||
mod bake_visualization_toggles;
|
||||
mod breadcrumb;
|
||||
mod common_settings;
|
||||
mod section_opening;
|
||||
pub(crate) use bake_checks::bake_warnings;
|
||||
pub use bake_paint_brush::BakePaintBrush;
|
||||
pub(crate) use bake_visualization_panel::bake_visualization_panel;
|
||||
pub use bake_visualization_toggles::BakeVisualizationToggles;
|
||||
@@ -229,10 +231,15 @@ fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bake bar's gap from the bottom of the 3D view, in points (the pre-bake warnings sit above it)
|
||||
pub(super) const BAKE_BAR_MARGIN: f32 = 16.0;
|
||||
|
||||
pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) {
|
||||
egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show(
|
||||
ctx,
|
||||
|ui| {
|
||||
egui::Area::new(egui::Id::unique("bake_bar"))
|
||||
.constrain_to(viewport)
|
||||
.anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -BAKE_BAR_MARGIN))
|
||||
.default_width(0.0)
|
||||
.show(ctx, |ui| {
|
||||
if let Some(status) = app.bake_status() {
|
||||
ui.vertical_centered(|ui| ui.label(egui::RichText::new(status).strong()));
|
||||
}
|
||||
@@ -264,6 +271,5 @@ pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport:
|
||||
app.ui.mode = Mode::Painting;
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -107,6 +107,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
if mode == crate::state::Mode::Baking {
|
||||
crate::bake_mode::bake_bar(app, ui.ctx(), full);
|
||||
crate::bake_mode::bake_warnings(app, ui.ctx(), full);
|
||||
}
|
||||
|
||||
// Keep drawing until the 3D view finishes accumulating anti-aliasing samples
|
||||
|
||||
Reference in new issue
Block a user