Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/compose/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ pub mod projector_view;
mod sampled_map;
pub mod seam_padding;
mod seam_padding_input;
mod seam_padding_table;
mod sections;
mod shape_distance;
mod slope_texel;
Expand Down Expand Up @@ -91,6 +92,7 @@ pub use padding_maps::PaddingMaps;
pub use pattern_context::PatternContext;
pub use projector_depth_cache::ProjectorDepthCache;
pub use seam_padding_input::SeamPaddingInput;
pub use seam_padding_table::SeamPaddingTable;
pub use solo::solo_project;
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};

Expand Down
89 changes: 89 additions & 0 deletions crates/compose/src/seam_padding_table.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use std::collections::{BTreeMap, BTreeSet, HashSet};

use crate::PaddingMaps;
use texturecraft_texel::{TILE, dilate::NONE};

type Tile = (u32, u32);

/// Exact display padding sources in GPU upload order. Rows index sparse records
/// of destination column, island-local source and source across the seam.
#[derive(Debug)]
pub struct SeamPaddingTable {
size: (u32, u32),
words: Vec<u32>,
reads: BTreeMap<Tile, Vec<Tile>>,
readers: BTreeMap<Tile, Vec<Tile>>,
}

impl SeamPaddingTable {
pub fn from_maps(maps: &PaddingMaps) -> Option<Self> {
const MAX_WORDS: usize = (64 << 20) / size_of::<u32>();
let (width, height) = maps.size();
let texels = width.checked_mul(height)? as usize;
if texels == 0 || maps.flat.src.len() != texels || height as usize >= MAX_WORDS {
return None;
}

let header = height as usize + 1;
let mut words = vec![0; header];
let mut crossed = maps.crossed.iter().peekable();
let tile = |index: u32| ((index % width) / TILE, (index / width) / TILE);
let mut edges = HashSet::new();
for (y, row) in maps.flat.src.chunks_exact(width as usize).enumerate() {
words[y] = ((words.len() - header) / 3) as u32;
for (x, &local) in row.iter().enumerate() {
let texel = (y as u32) * width + x as u32;
if local == NONE || local == texel {
continue;
}
if words.len() + 3 > MAX_WORDS {
return None;
}
let across = if crossed.peek().is_some_and(|&&(destination, _)| destination == texel) {
crossed.next().map_or(local, |&(_, source)| source)
} else {
local
};
words.extend_from_slice(&[x as u32, local, across]);
let destination = (x as u32 / TILE, y as u32 / TILE);
for source in [local, across].map(tile) {
if destination != source {
edges.insert((destination, source));
}
}
}
}
words[height as usize] = ((words.len() - header) / 3) as u32;
let mut edges: Vec<_> = edges.into_iter().collect();
edges.sort_unstable();
let mut reads = BTreeMap::<_, Vec<_>>::new();
let mut readers = BTreeMap::<_, Vec<_>>::new();
for (destination, source) in edges {
reads.entry(destination).or_default().push(source);
readers.entry(source).or_default().push(destination);
}
Some(Self { size: (width, height), words, reads, readers })
}

pub fn size(&self) -> (u32, u32) {
self.size
}

pub fn words(&self) -> &[u32] {
&self.words
}

/// Covered sources never read other padding, so this is a single reverse lookup.
pub fn affected_tiles(&self, changed: &BTreeSet<Tile>) -> BTreeSet<Tile> {
changed.iter().copied().chain(changed.iter().flat_map(|tile| self.readers.get(tile).into_iter().flatten().copied())).collect()
}

pub fn source_tiles(&self, destination: Tile) -> impl Iterator<Item = Tile> + '_ {
self.reads.get(&destination).into_iter().flatten().copied()
}

pub fn bytes(&self) -> usize {
self.words.capacity() * size_of::<u32>()
+ [&self.reads, &self.readers].into_iter().flat_map(|index| index.values()).map(|tiles| size_of::<Tile>() * (tiles.capacity() + 1)).sum::<usize>()
}
}
71 changes: 48 additions & 23 deletions crates/engine/src/display_padding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::collections::BTreeSet;
use std::ops::Deref;
use std::sync::{Arc, OnceLock};

use texturecraft_compose::{Composite, PaddingMaps, SeamPaddingInput, pad_tiles};
use texturecraft_compose::{Composite, PaddingMaps, SeamPaddingInput, SeamPaddingTable, pad_tiles};
use texturecraft_core::{TextureSet, UvPaddingMode};
use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer};
use texturecraft_texel::DilationMap;
Expand All @@ -14,7 +14,7 @@ use crate::session::DISPLAY_PADDING;

/// The viewport's padding map. Reading the dense map explicitly also works for uniform UVs.
pub struct DisplayPadding {
dense: Arc<OnceLock<PaddingMaps>>,
dense: Arc<OnceLock<PreparedPadding>>,
size: (u32, u32),
mixed: Option<Arc<UvGBuffer>>,
block: (u32, u32),
Expand All @@ -28,6 +28,18 @@ pub struct DisplayPadding {
uniform: Option<bool>,
}

struct PreparedPadding {
maps: PaddingMaps,
seam_table: Option<Arc<SeamPaddingTable>>,
}

impl PreparedPadding {
fn new(maps: PaddingMaps, seams: bool) -> Self {
let seam_table = (seams && !cfg!(target_arch = "wasm32")).then(|| SeamPaddingTable::from_maps(&maps)).flatten().map(Arc::new);
Self { maps, seam_table }
}
}

impl DisplayPadding {
pub(crate) fn new(mesh: &Arc<Mesh>, set: &TextureSet, gbuf: &Arc<UvGBuffer>, has_coverage: bool, block: (u32, u32)) -> Self {
let size = (gbuf.width, gbuf.height);
Expand Down Expand Up @@ -63,7 +75,7 @@ impl DisplayPadding {
/// The same nearest covered source as the dense map, without constructing it for one pick.
pub(crate) fn source_for_sample(&self, across_seams: bool, x: u32, y: u32) -> Option<(u32, u32)> {
if let Some(dense) = self.dense.get() {
return dense.source(across_seams, x, y);
return dense.maps.source(across_seams, x, y);
}

let gbuf = self.mixed.as_ref()?;
Expand All @@ -84,7 +96,7 @@ impl DisplayPadding {
.min_by_key(|&(sx, sy)| (sx.abs_diff(x).max(sy.abs_diff(y)), sy, sx))
}

/// Seam continuation needs the CPU when the atlas has uncovered texels.
/// The mixed UV atlas has seams whose continuation depends on the mesh topology.
pub fn needs_seam_padding(&self) -> bool {
self.seam_geometry.is_some()
}
Expand All @@ -99,10 +111,18 @@ impl DisplayPadding {
self.mixed.clone()
}

/// Whether applying CPU viewport padding can proceed without waiting for the dense map.
#[cfg(not(target_arch = "wasm32"))]
/// Whether viewport padding can proceed without waiting for the map.
pub fn is_ready(&self) -> bool {
self.mixed.is_none() || self.dense.get().is_some() || self.worker_failed.get().is_some()
#[cfg(not(target_arch = "wasm32"))]
if self.worker_failed.get().is_some() {
return true;
}
self.mixed.is_none() || self.dense.get().is_some()
}

/// The CPU oracle's exact sources, packed once for the viewport without waiting.
pub fn seam_table(&self) -> Option<Arc<SeamPaddingTable>> {
self.dense.get()?.seam_table.clone()
}

/// Why the worker failed, for the session log, when it did
Expand Down Expand Up @@ -134,7 +154,7 @@ impl DisplayPadding {
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let (Some(dense), Some(gbuf)) = (dense.upgrade(), gbuf.upgrade()) else { return };
let seam_geometry = seam_geometry.and_then(|geometry| geometry.upgrade());
dense.get_or_init(|| build(&gbuf, block, seam_geometry.as_deref()));
dense.get_or_init(|| PreparedPadding::new(build(&gbuf, block, seam_geometry.as_deref()), seam_geometry.is_some()));
}));
if let Err(payload) = outcome {
let reason = payload.downcast_ref::<&str>().map(|reason| reason.to_string()).or_else(|| payload.downcast_ref::<String>().cloned());
Expand All @@ -147,25 +167,30 @@ impl DisplayPadding {
}

pub(crate) fn bytes(&self) -> usize {
self.dense.get().map_or(0, PaddingMaps::bytes)
self.dense.get().map_or(0, |dense| dense.maps.bytes() + dense.seam_table.as_ref().map_or(0, |table| table.bytes()))
}

pub(crate) fn maps(&self) -> &PaddingMaps {
self.dense.get_or_init(|| {
#[cfg(not(target_arch = "wasm32"))]
if self.worker_failed.get().is_some() {
let (width, height) = self.size;
return PaddingMaps::from_flat(DilationMap { width, height, src: vec![texturecraft_texel::dilate::NONE; width as usize * height as usize] });
}
if let Some(gbuf) = &self.mixed {
return mixed_sources(gbuf, self.block, self.seam_geometry.as_deref());
}
&self
.dense
.get_or_init(|| {
#[cfg(not(target_arch = "wasm32"))]
if self.worker_failed.get().is_some() {
let (width, height) = self.size;
let maps =
PaddingMaps::from_flat(DilationMap { width, height, src: vec![texturecraft_texel::dilate::NONE; width as usize * height as usize] });
return PreparedPadding::new(maps, false);
}
if let Some(gbuf) = &self.mixed {
return PreparedPadding::new(mixed_sources(gbuf, self.block, self.seam_geometry.as_deref()), self.seam_geometry.is_some());
}

let (width, height) = self.size;
let texel_count = width as usize * height as usize;
let src = if self.uniform == Some(true) { (0..texel_count as u32).collect() } else { vec![texturecraft_texel::dilate::NONE; texel_count] };
PaddingMaps::from_flat(DilationMap { width, height, src })
})
let (width, height) = self.size;
let texel_count = width as usize * height as usize;
let src = if self.uniform == Some(true) { (0..texel_count as u32).collect() } else { vec![texturecraft_texel::dilate::NONE; texel_count] };
PreparedPadding::new(PaddingMaps::from_flat(DilationMap { width, height, src }), false)
})
.maps
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ mod mask_owner;
mod mask_preview_pixel;
pub mod material_lib;
mod material_overview;
pub use material_overview::MaterialOverview;
pub use material_overview::{MaterialOverview, ViewportOverview};
mod material_preview_pixel;
pub mod materials;
pub mod materialx_cmds;
Expand Down
131 changes: 82 additions & 49 deletions crates/engine/src/material_overview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
use std::sync::Arc;

use texturecraft_compose::{BakedMaps, Composite, DisplayKind, Inputs, all_tiles, composite_tiles, kinds_for, tile_bytes};
use texturecraft_core::{AoMixing, Channel};
use texturecraft_geom::UvGBuffer;
use texturecraft_core::{AoMixing, Channel, LayerId};
use texturecraft_geom::{Mesh, UvGBuffer};
use texturecraft_texel::TILE;

use crate::Session;
Expand All @@ -14,60 +14,93 @@ pub struct MaterialOverview {
pub maps: Vec<(DisplayKind, Vec<u8>)>,
}

pub enum ViewportOverview {
Material(MaterialOverview),
Mask { size: (u32, u32), rgba: Vec<u8> },
}

impl Session {
/// Evaluate the ordinary material stack on a small UV grid, sharing its source pixels,
/// images and bakes. This never enters a paint, undo or export cache.
pub fn material_overview(&self, ts: usize, max_edge: u32) -> Option<MaterialOverview> {
let set = self.doc.project.texture_sets.get(ts)?;
let (w, h) = set.size();
let limit = max_edge.clamp(TILE, 256);
let mut step = 1;
while w.max(h) / step > limit {
step *= 2;
}
let (width, height) = ((w / step).max(1), (h / step).max(1));
let project = self.solo_view();
self.with_inputs(ts, |inputs| {
let inputs = Inputs { project: project.as_ref().unwrap_or(inputs.project), block_scales: inputs.block_scales.clone(), ..*inputs };
match build_overview(&inputs, &self.mesh, None, max_edge)? {
ViewportOverview::Material(material) => Some(material),
ViewportOverview::Mask { .. } => None,
}
})
}

/// Own the inputs so the viewport can prepare a disposable image off the UI thread.
pub fn viewport_overview_job(&self, ts: usize, mask: Option<LayerId>, max_edge: u32) -> Option<impl FnOnce() -> Option<ViewportOverview> + Send + use<>> {
let cache = self.caches.get(ts)?;
let source = &cache.gbuf;
let project = mask.is_none().then(|| self.solo_view()).flatten().unwrap_or_else(|| self.doc.project.clone());
let mesh = self.mesh.clone();
let gbuf = cache.gbuf.clone();
let pixels = self.doc.pixels.clone();
let baked = self.doc.baked.get(&ts).cloned().unwrap_or_default();
let images = self.images.clone();
Some(move || {
let inputs = Inputs {
project: &project,
ts,
mesh: &mesh,
gbuf: &gbuf,
pixels: &pixels,
baked: &baked,
block_scales: project.texture_sets.get(ts)?.block_scales(),
preview: None,
images: &images,
bounds: mesh.bounds(),
};
build_overview(&inputs, &mesh, mask, max_edge)
})
}
}

// Reuse the full UV raster to avoid traversing the mesh again for an overview
let positions = (0..height).flat_map(|y| {
(0..width).map(move |x| {
let sx = ((x as u64 * 2 + 1) * w as u64 / (2 * width as u64)) as usize;
let sy = ((y as u64 * 2 + 1) * h as u64 / (2 * height as u64)) as usize;
sy * w as usize + sx
})
});
let (tri, bary) =
positions.map(|i| (source.tri.get(i).copied().unwrap_or(texturecraft_geom::NO_TRI), source.bary.get(i).copied().unwrap_or_default())).unzip();
let gbuf = Arc::new(UvGBuffer { width, height, tri, bary, overlaps: 0, shared_surfaces: false });
let empty = BakedMaps::default();
let baked = self.doc.baked.get(&ts).unwrap_or(&empty);
let channels = set.channel_list();
let project = self.solo_view();
let scales = set.block_scales().at_reduced_resolution(step);
let inputs = Inputs {
project: project.as_ref().unwrap_or(&self.doc.project),
ts,
mesh: &self.mesh,
gbuf: &gbuf,
pixels: &self.doc.pixels,
baked,
block_scales: scales.clone(),
preview: None,
images: &self.images,
bounds: self.mesh.bounds(),
};
let mut composite = Composite { block_scales: scales, ..Composite::with_size(&channels, width, height) };
let tiles = all_tiles(width, height);
composite_tiles(&inputs, &mut composite, &tiles);
let (block_width, block_height) = set.block_size();
let block = ((block_width / step).max(1), (block_height / step).max(1));
let has_coverage = gbuf.tri.iter().any(|&triangle| triangle != texturecraft_geom::NO_TRI);
let padding = crate::session::DisplayPadding::new(&self.mesh, set, &gbuf, has_coverage, block);
padding.apply_to_tiles(&mut composite, &tiles);
let maps = pack_overview(&composite, baked, set.ao_mixing, &channels, &tiles);
Some(MaterialOverview { size: (width, height), maps })
fn build_overview(inputs: &Inputs, mesh: &Arc<Mesh>, mask: Option<LayerId>, max_edge: u32) -> Option<ViewportOverview> {
let set = inputs.project.texture_sets.get(inputs.ts)?;
let (w, h) = set.size();
let limit = max_edge.clamp(TILE, 256);
let mut step = 1;
while w.max(h) / step > limit {
step *= 2;
}
let (width, height) = ((w / step).max(1), (h / step).max(1));
let source = inputs.gbuf;

// Reuse the full UV raster to avoid traversing the mesh again for an overview
let positions = (0..height).flat_map(|y| {
(0..width).map(move |x| {
let sx = ((x as u64 * 2 + 1) * w as u64 / (2 * width as u64)) as usize;
let sy = ((y as u64 * 2 + 1) * h as u64 / (2 * height as u64)) as usize;
sy * w as usize + sx
})
});
let (tri, bary) =
positions.map(|i| (source.tri.get(i).copied().unwrap_or(texturecraft_geom::NO_TRI), source.bary.get(i).copied().unwrap_or_default())).unzip();
let gbuf = Arc::new(UvGBuffer { width, height, tri, bary, overlaps: 0, shared_surfaces: false });
let channels = set.channel_list();
let scales = set.block_scales().at_reduced_resolution(step);
let small = Inputs { gbuf: &gbuf, block_scales: scales.clone(), ..*inputs };
if let Some(id) = mask {
let size = (width, height);
let gray = texturecraft_compose::mask_image_sized(&small, id, size)?;
let rgba = gray.into_iter().flat_map(|g| [g, g, g, 255]).collect();
return Some(ViewportOverview::Mask { size, rgba });
}
let mut composite = Composite { block_scales: scales, ..Composite::with_size(&channels, width, height) };
let tiles = all_tiles(width, height);
composite_tiles(&small, &mut composite, &tiles);
let (block_width, block_height) = set.block_size();
let block = ((block_width / step).max(1), (block_height / step).max(1));
let has_coverage = gbuf.tri.iter().any(|&triangle| triangle != texturecraft_geom::NO_TRI);
let padding = crate::session::DisplayPadding::new(mesh, set, &gbuf, has_coverage, block);
padding.apply_to_tiles(&mut composite, &tiles);
let maps = pack_overview(&composite, inputs.baked, set.ao_mixing, &channels, &tiles);
Some(ViewportOverview::Material(MaterialOverview { size: (width, height), maps }))
}

fn pack_overview(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, channels: &[Channel], tiles: &[(u32, u32)]) -> Vec<(DisplayKind, Vec<u8>)> {
Expand Down
Loading