mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 00:59:29 +01:00
Rebake the auto-rebake map inside a skew or cage stroke
A skew or cage stroke on a set that bakes from a high poly marks its UV box; in Bake mode the app then bakes the set's auto-rebake map again only there (one texel wider, for the paint map's sampling), keeps the rest of the stored map and pads the whole map, so its pixels match a whole bake. Maps scaled by their whole range (curvature, height, thickness), UV-tiled sets and a map stored at another size bake whole. A stroke painted while that bake runs is baked by the next one. The bake crate gains bake_tiles_in with a texel box.
This commit is contained in:
1 parent
9e36885648
commit
4a56683bb9
23 files changed
+406
-70
No files matched your search
@@ -1,7 +1,7 @@
|
||||
use crate::cage::RayFrame;
|
||||
use crate::map::BakeContext;
|
||||
use crate::tracing::{CpuTracer, Tracer};
|
||||
use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress};
|
||||
use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress, RegionBake};
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
use texturecraft_core::{BakeSettings, BakedMap};
|
||||
|
||||
@@ -23,10 +23,22 @@ impl<'a> BakePasses<'a> {
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
tracer: Option<&dyn Tracer>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
self.bake_map_in(map, progress, excluded_tiles, None, tracer)
|
||||
}
|
||||
|
||||
/// [`BakePasses::bake_map`] sampling only `region`'s texels, as [`crate::bake_tiles_in`] does
|
||||
pub fn bake_map_in(
|
||||
&mut self,
|
||||
map: BakedMap,
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
tracer: Option<&dyn Tracer>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
let mut settings = self.request.settings.clone();
|
||||
settings.maps.select([map]);
|
||||
self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS)
|
||||
self.run(&settings, progress, excluded_tiles, region, tracer, super::STRIP_TEXELS)
|
||||
}
|
||||
|
||||
pub(super) fn run(
|
||||
@@ -34,6 +46,7 @@ impl<'a> BakePasses<'a> {
|
||||
settings: &BakeSettings,
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
tracer: Option<&dyn Tracer>,
|
||||
strip_texels: usize,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
@@ -56,7 +69,7 @@ impl<'a> BakePasses<'a> {
|
||||
}
|
||||
};
|
||||
let context = BakeContext::with_frame(&request, *extent, frame);
|
||||
let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles);
|
||||
let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles, region);
|
||||
match tracer {
|
||||
Some(tracer) => match bake(tracer) {
|
||||
Err(BakeError::Tracer(error)) => {
|
||||
|
||||
+54
-6
@@ -12,6 +12,8 @@ mod high_poly;
|
||||
mod mesh_extent;
|
||||
mod name_pair;
|
||||
mod progress;
|
||||
mod region_bake;
|
||||
mod texel_box;
|
||||
|
||||
pub use bake_error::BakeError;
|
||||
pub use bake_output::BakeOutput;
|
||||
@@ -22,6 +24,8 @@ pub use high_poly::HighPoly;
|
||||
pub(crate) use mesh_extent::MeshExtent;
|
||||
pub use name_pair::NamePair;
|
||||
pub use progress::Progress;
|
||||
pub use region_bake::RegionBake;
|
||||
pub use texel_box::{TexelBox, region_keeps_pixels};
|
||||
|
||||
mod map;
|
||||
mod skew;
|
||||
@@ -50,6 +54,8 @@ const STRIP_TEXELS: usize = 1 << 24;
|
||||
const BATCH: usize = 1 << 18;
|
||||
// Curvature batches stay small so progress and cancellation remain responsive
|
||||
const CURVATURE_BATCH: usize = 1 << 15;
|
||||
/// Smallest mesh extent the maps are normalized by, so a flat mesh never divides by zero
|
||||
const MIN_MESH_EXTENT: f32 = 1e-6;
|
||||
|
||||
fn validate(request: &BakeRequest) -> Result<(), BakeError> {
|
||||
let settings = request.settings;
|
||||
@@ -161,7 +167,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer)
|
||||
|
||||
/// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing
|
||||
pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result<BakeOutput, BakeError> {
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS)
|
||||
bake_tiles_in(request, progress, excluded_tiles, None, tracer)
|
||||
}
|
||||
|
||||
/// [`bake_tiles`] sampling only `region`'s texels and padding a whole map; equal to a whole bake for [`region_keeps_pixels`] maps
|
||||
pub fn bake_tiles_in(
|
||||
request: &BakeRequest,
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
tracer: Option<&dyn Tracer>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, tracer, STRIP_TEXELS)
|
||||
}
|
||||
|
||||
type OutRow<'a> = Vec<&'a mut [f32]>;
|
||||
@@ -173,8 +190,9 @@ fn bake_in_strips(
|
||||
strip_texels: usize,
|
||||
tracer: &dyn Tracer,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels)
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, Some(tracer), strip_texels)
|
||||
}
|
||||
|
||||
fn bake_prepared(
|
||||
@@ -184,6 +202,7 @@ fn bake_prepared(
|
||||
strip_texels: usize,
|
||||
tracer: &dyn Tracer,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
if progress.cancel.load(Relaxed) {
|
||||
return Err(BakeError::Cancelled);
|
||||
@@ -211,7 +230,7 @@ fn bake_prepared(
|
||||
let mut padding_map = None;
|
||||
let total_rows = height.max(1) as u64;
|
||||
let mut rows_done = 0u64;
|
||||
let strip_error = || BakeError::Invalid("strip output of range".into());
|
||||
let strip_error = || BakeError::Invalid("strip output out of range".into());
|
||||
|
||||
let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis);
|
||||
let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height);
|
||||
@@ -250,6 +269,18 @@ fn bake_prepared(
|
||||
}
|
||||
});
|
||||
|
||||
// Coverage stays the whole map's, so padding matches a whole bake; only the region is sampled
|
||||
if let Some(region) = region {
|
||||
for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() {
|
||||
let y = (sample_start_y + row_index) / samples_per_axis;
|
||||
for (sample_x, triangle) in row.iter_mut().enumerate() {
|
||||
if !region.texels.contains(sample_x / samples_per_axis, y) {
|
||||
*triangle = NO_TRI;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut output_rows: Vec<OutRow> = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect();
|
||||
for (map, data) in maps.iter().zip(buffers.iter_mut()) {
|
||||
let component_count = map.components();
|
||||
@@ -258,6 +289,7 @@ fn bake_prepared(
|
||||
row.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
let mut bake_strip = || {
|
||||
for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() {
|
||||
if progress.cancel.load(Relaxed) {
|
||||
@@ -276,10 +308,11 @@ fn bake_prepared(
|
||||
(width, samples_per_axis, sample_start_y * sample_width),
|
||||
)?;
|
||||
rows_done += batch.len() as u64;
|
||||
progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed);
|
||||
progress.done.store((rows_done.saturating_mul(u64::from(Progress::DONE)) / total_rows).min(u64::from(Progress::DONE)) as u32, Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) {
|
||||
bake_strip()?;
|
||||
} else {
|
||||
@@ -291,6 +324,19 @@ fn bake_prepared(
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(region) = region {
|
||||
for (map, pixels) in maps.iter().zip(buffers.iter_mut()) {
|
||||
let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len());
|
||||
let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?;
|
||||
let components = map.components();
|
||||
for (index, (pixel, kept)) in pixels.chunks_exact_mut(components).zip(previous.chunks_exact(components)).enumerate() {
|
||||
if !region.texels.contains(index % width, index / width) {
|
||||
pixel.copy_from_slice(kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut output: BTreeMap<BakedMap, Vec<f32>> = maps.into_iter().zip(buffers).collect();
|
||||
if from_normal {
|
||||
let world_normal =
|
||||
@@ -306,7 +352,8 @@ fn bake_prepared(
|
||||
}
|
||||
|
||||
let (bounds_min, bounds_max) = request.mesh.bounds();
|
||||
map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6));
|
||||
map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(MIN_MESH_EXTENT));
|
||||
|
||||
if let Some(padding_map) = padding_map {
|
||||
for (map, data) in output.iter_mut() {
|
||||
padding_map.apply(data, map.components());
|
||||
@@ -315,11 +362,12 @@ fn bake_prepared(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if progress.cancel.load(Relaxed) {
|
||||
return Err(BakeError::Cancelled);
|
||||
}
|
||||
|
||||
progress.done.store(10_000, Relaxed);
|
||||
progress.done.store(Progress::DONE, Relaxed);
|
||||
Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() })
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,15 @@ pub struct Progress {
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
/// The basis points of a finished bake
|
||||
pub const DONE: u32 = 10_000;
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn fraction(&self) -> f32 {
|
||||
self.done.load(Relaxed).min(10_000) as f32 / 10_000.0
|
||||
self.done.load(Relaxed).min(Self::DONE) as f32 / Self::DONE as f32
|
||||
}
|
||||
|
||||
pub fn cancel(&self) {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::TexelBox;
|
||||
|
||||
/// A bake that samples only `texels` and takes every other texel from `previous`, a whole bake of the same size
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RegionBake<'a> {
|
||||
pub texels: TexelBox,
|
||||
pub previous: &'a BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
}
|
||||
@@ -31,7 +31,7 @@ fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() {
|
||||
let full = bake(&request, &Progress::new()).unwrap();
|
||||
for excluded in [[(0, 0)], [(1, 0)]] {
|
||||
let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap();
|
||||
let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap();
|
||||
let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded, None).unwrap();
|
||||
let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap();
|
||||
assert_eq!(strips.maps, partial.maps);
|
||||
assert_eq!(fallback.maps, partial.maps);
|
||||
|
||||
@@ -390,7 +390,7 @@ fn strips_match_a_single_pass() {
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let whole = bake(&req, &Progress::new()).unwrap();
|
||||
let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap();
|
||||
let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[], None).unwrap();
|
||||
for (map, a) in &whole.maps {
|
||||
let b = &strips.maps[map];
|
||||
let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count();
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct TexelBox {
|
||||
pub min: (u32, u32),
|
||||
pub max: (u32, u32),
|
||||
}
|
||||
|
||||
impl TexelBox {
|
||||
/// Whether texel (`x`, `y`) lies inside the box
|
||||
pub fn contains(&self, x: usize, y: usize) -> bool {
|
||||
(self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y)
|
||||
}
|
||||
|
||||
/// The box grown by `texels` on every side, kept inside a `width` x `height` image
|
||||
pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox {
|
||||
TexelBox {
|
||||
min: (self.min.0.saturating_sub(texels), self.min.1.saturating_sub(texels)),
|
||||
max: (self.max.0.saturating_add(texels).min(width), self.max.1.saturating_add(texels).min(height)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours
|
||||
pub fn region_keeps_pixels(map: texturecraft_core::BakedMap) -> bool {
|
||||
use texturecraft_core::BakedMap;
|
||||
!matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness)
|
||||
}
|
||||
@@ -48,4 +48,16 @@ impl Session {
|
||||
.filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The maps an auto-rebake of `map` bakes: that map alone, or with every checked map once the output size changed (storing a new size drops the old maps)
|
||||
pub fn auto_rebake_maps(&self, texture_set: usize, map: BakedMap) -> Vec<BakedMap> {
|
||||
let Ok(set) = self.doc.project.texture_set(texture_set) else { return vec![map] };
|
||||
let (width, height) = set.bake.common.output_size();
|
||||
let stored = self.doc.baked.get(&texture_set);
|
||||
let resized = stored.is_some_and(|stored| stored.resolution != width || stored.maps.keys().any(|baked| stored.height(*baked) != height));
|
||||
match resized {
|
||||
true => BakedMap::ALL.into_iter().filter(|baked| *baked == map || set.bake.maps.is_enabled(*baked)).collect(),
|
||||
false => vec![map],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -136,15 +136,15 @@ impl Session {
|
||||
self.bake_log.matching = matching;
|
||||
}
|
||||
|
||||
/// Start the Baking Log for a bake of only `map` of each of `sets`, checked or not
|
||||
pub fn begin_map_bake_log(&mut self, sets: &[usize], map: BakedMap) {
|
||||
/// Start the Baking Log for a bake of only `maps` of each of `sets`, checked or not
|
||||
pub fn begin_map_bake_log(&mut self, sets: &[usize], maps: &[BakedMap]) {
|
||||
self.begin_bake_log(sets);
|
||||
let project = &self.doc.project;
|
||||
self.bake_log.maps = sets
|
||||
.iter()
|
||||
.filter_map(|&texture_set| {
|
||||
let set_name = project.texture_sets.get(texture_set)?.name.clone();
|
||||
Some(BakeLogMap { texture_set, set_name, map, state: BakeMapState::Waiting })
|
||||
.filter_map(|&texture_set| Some((texture_set, project.texture_sets.get(texture_set)?.name.clone())))
|
||||
.flat_map(|(texture_set, set_name)| {
|
||||
maps.iter().map(move |&map| BakeLogMap { texture_set, set_name: set_name.clone(), map, state: BakeMapState::Waiting })
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
@@ -44,22 +44,31 @@ impl Session {
|
||||
fn low_poly_fingerprint(&self) -> u64 {
|
||||
*self.low_poly_fingerprint.get_or_init(|| {
|
||||
let source = &self.source;
|
||||
let floats = source.positions.iter().chain(&source.normals).flat_map(|vector| vector.to_array()).chain(source.uvs.iter().flat_map(|uv| uv.to_array()));
|
||||
let floats =
|
||||
source.positions.iter().chain(&source.normals).flat_map(|vector| vector.to_array()).chain(source.uvs.iter().flat_map(|uv| uv.to_array()));
|
||||
let words = floats.map(|float| u64::from(float.to_bits())).chain(source.indices.iter().map(|index| u64::from(*index)));
|
||||
fingerprint_words(words)
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep `sources` as what maps of `texture_set` were baked from; without them the `stored` maps lose their record
|
||||
pub(super) fn record_bake_sources(&mut self, texture_set: usize, sources: Option<&BTreeMap<BakedMap, BakeSource>>, stored: &[BakedMap]) -> Result<()> {
|
||||
/// Keep what the `stored` maps of `texture_set` were baked from and the newest stroke their bake saw; without it they lose their record
|
||||
pub(super) fn record_bake_sources(
|
||||
&mut self,
|
||||
texture_set: usize,
|
||||
recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>,
|
||||
stored: &[BakedMap],
|
||||
) -> Result<()> {
|
||||
let set = self.doc.project.texture_set_mut(texture_set)?;
|
||||
match sources {
|
||||
Some(sources) => set.bake_sources.extend(sources),
|
||||
match recorded {
|
||||
Some((sources, _)) => set.bake_sources.extend(sources),
|
||||
None => set.bake_sources.retain(|map, _| !stored.contains(map)),
|
||||
}
|
||||
|
||||
let baked = &set.baked;
|
||||
set.bake_sources.retain(|map, _| baked.contains(map));
|
||||
if let Some((_, painted_stroke)) = recorded {
|
||||
self.forget_painted_region(texture_set, stored, painted_stroke);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
use super::{MergedHigh, StreamedBake, StreamedMap};
|
||||
use crate::{EngineError, Result};
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, RegionBake, TexelBox, bake_tiles_in, tracing::Tracer};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::{BakeSettings, BakedMap};
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
|
||||
/// A self-contained bake task that can run on another thread.
|
||||
/// A self-contained bake task that can run on another thread
|
||||
pub struct BakeTask {
|
||||
pub low_base_color: super::MaterialColors,
|
||||
pub ts: usize,
|
||||
@@ -14,20 +14,24 @@ pub struct BakeTask {
|
||||
pub bvh: Arc<Bvh>,
|
||||
pub material: usize,
|
||||
pub settings: BakeSettings,
|
||||
/// The merged high polys, unless the set bakes from the low poly.
|
||||
/// The merged high polys, unless the set bakes from the low poly
|
||||
pub high: Option<MergedHigh>,
|
||||
pub cage: Option<Arc<Mesh>>,
|
||||
pub skew: Option<Arc<BakePaintMap>>,
|
||||
pub cage_paint: Option<Arc<BakePaintMap>>,
|
||||
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles.
|
||||
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles
|
||||
pub tiles: (u32, u32),
|
||||
/// Snapshot of tile selection and pixels to retain while the worker runs
|
||||
pub excluded_tiles: Vec<(u32, u32)>,
|
||||
pub previous_maps: BakedMaps,
|
||||
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`).
|
||||
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`)
|
||||
pub tracer: Option<Arc<dyn Tracer>>,
|
||||
/// What each map this task makes is baked from, taken when the task was made
|
||||
pub sources: std::collections::BTreeMap<BakedMap, texturecraft_core::BakeSource>,
|
||||
/// The newest skew or cage stroke when the task was made; a later stroke still needs a rebake
|
||||
pub painted_stroke: u64,
|
||||
/// Sample only these texels and take the rest from `previous_maps` (the same size); `None` samples every texel
|
||||
pub region: Option<TexelBox>,
|
||||
}
|
||||
|
||||
impl BakeTask {
|
||||
@@ -36,13 +40,7 @@ impl BakeTask {
|
||||
self.settings.maps.enabled().collect()
|
||||
}
|
||||
|
||||
/// Bake the maps one after another, handing each one to `on_map` as soon as it is padded,
|
||||
/// and return all of them together. Each map is a bake of its own, so with a high poly
|
||||
/// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several
|
||||
/// maps, in exchange for showing them as they land. The pixels are the same as `run`'s.
|
||||
/// The handed-over buffers are the returned ones too (no copy is made), so a preview that
|
||||
/// keeps them costs no second set of maps. A cancel or an error leaves the maps already
|
||||
/// handed over whole.
|
||||
/// Bake the maps one by one (same pixels as [`BakeTask::run`], rays cast per map), handing each padded map's shared buffer to `on_map`, then return them all
|
||||
pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result<StreamedBake> {
|
||||
let maps = self.maps();
|
||||
let total = maps.len();
|
||||
@@ -50,7 +48,7 @@ impl BakeTask {
|
||||
|
||||
let mut passes = BakePasses::new(self.request());
|
||||
for (index, map) in maps.iter().copied().enumerate() {
|
||||
let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
|
||||
let mut output = passes.bake_map_in(map, progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
let Some(data) = output.maps.remove(&map) else { continue };
|
||||
if combined.is_none() {
|
||||
@@ -74,6 +72,7 @@ impl BakeTask {
|
||||
maps: retained,
|
||||
tracer: output.tracer,
|
||||
sources: self.sources.clone(),
|
||||
painted_stroke: self.painted_stroke,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -89,18 +88,24 @@ impl BakeTask {
|
||||
maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(),
|
||||
tracer: output.tracer,
|
||||
sources: self.sources.clone(),
|
||||
painted_stroke: self.painted_stroke,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
|
||||
let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
|
||||
let mut output = bake_tiles_in(&self.request(), progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// The texels to sample, with the stored maps to take the rest from; `None` samples every texel
|
||||
fn region(&self) -> Option<RegionBake<'_>> {
|
||||
self.region.map(|texels| RegionBake { texels, previous: &self.previous_maps.maps })
|
||||
}
|
||||
|
||||
fn request(&self) -> BakeRequest<'_> {
|
||||
let high =
|
||||
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
|
||||
|
||||
@@ -206,6 +206,8 @@ impl Session {
|
||||
previous_maps,
|
||||
tracer,
|
||||
sources,
|
||||
painted_stroke: self.painted_strokes,
|
||||
region: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -273,19 +275,20 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the
|
||||
/// preview that showed them holds the same ones)
|
||||
/// Apply a streamed bake like [`Session::apply_bake`], keeping the buffers the preview that showed them shares
|
||||
pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> {
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some(&output.sources)))?;
|
||||
self.edit("Bake mesh maps", |session| {
|
||||
session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some((&output.sources, output.painted_stroke)))
|
||||
})?;
|
||||
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Store `output`, recording what its maps were baked from when `sources` are known
|
||||
fn store_bake(&mut self, texture_set: usize, output: BakeOutput, sources: Option<&BTreeMap<BakedMap, BakeSource>>) -> Result<()> {
|
||||
/// Store `output`, recording what its maps were baked from when known (see [`Session::record_bake_sources`])
|
||||
fn store_bake(&mut self, texture_set: usize, output: BakeOutput, recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>) -> Result<()> {
|
||||
let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
|
||||
self.store_bake_maps(texture_set, output.resolution, output.height, maps, sources)
|
||||
self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded)
|
||||
}
|
||||
|
||||
fn store_bake_maps(
|
||||
@@ -294,7 +297,7 @@ impl Session {
|
||||
resolution: u32,
|
||||
height: u32,
|
||||
maps: BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
sources: Option<&BTreeMap<BakedMap, BakeSource>>,
|
||||
recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>,
|
||||
) -> Result<()> {
|
||||
let stored: Vec<BakedMap> = maps.keys().copied().collect();
|
||||
let entry = self.doc.baked.entry(texture_set).or_default();
|
||||
@@ -305,18 +308,19 @@ impl Session {
|
||||
entry.resolution = resolution;
|
||||
entry.maps.extend(maps);
|
||||
self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect();
|
||||
self.record_bake_sources(texture_set, sources, &stored)
|
||||
self.record_bake_sources(texture_set, recorded, &stored)
|
||||
}
|
||||
|
||||
/// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran.
|
||||
/// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran
|
||||
pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result<String> {
|
||||
let mut task = self.bake_task(ts)?;
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
}
|
||||
let out = task.run(&Progress::new())?;
|
||||
let tracer = out.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake(ts, out, Some(&task.sources)))?;
|
||||
|
||||
let output = task.run(&Progress::new())?;
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake(ts, output, Some((&task.sources, task.painted_stroke))))?;
|
||||
self.log.info("Baker", format!("Baked texture set {ts} ({tracer})"));
|
||||
Ok(tracer)
|
||||
}
|
||||
@@ -897,7 +901,7 @@ fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result<String
|
||||
let maps = task.maps();
|
||||
let output = task.run(&Progress::new())?;
|
||||
let tracer = output.tracer.clone();
|
||||
session.store_bake(index, output, Some(&task.sources))?;
|
||||
session.store_bake(index, output, Some((&task.sources, task.painted_stroke)))?;
|
||||
for map in maps {
|
||||
session.bake_log.map_baked(index, map);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ mod merged_high;
|
||||
mod mesh_map_command;
|
||||
mod model_patch;
|
||||
mod paint_command;
|
||||
mod painted_region;
|
||||
mod preserve_tiles;
|
||||
mod streamed_bake;
|
||||
mod streamed_map;
|
||||
@@ -41,6 +42,7 @@ pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed};
|
||||
pub use merged_high::MergedHigh;
|
||||
pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, settings_params};
|
||||
pub use model_patch::settings_patch;
|
||||
pub use painted_region::PaintedRegion;
|
||||
pub use streamed_bake::StreamedBake;
|
||||
pub use streamed_map::StreamedMap;
|
||||
pub use texturecraft_bake::NamePair;
|
||||
|
||||
@@ -65,6 +65,7 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re
|
||||
session.doc.bake_paint.insert((texture_set, target), Arc::new(map));
|
||||
Ok(())
|
||||
})?;
|
||||
session.note_bake_paint(texture_set, None);
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
@@ -75,6 +76,7 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
session.doc.bake_paint.remove(&(texture_set, target));
|
||||
Ok(())
|
||||
})?;
|
||||
session.note_bake_paint(texture_set, None);
|
||||
}
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
@@ -123,6 +125,13 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
}
|
||||
Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string()))
|
||||
})?;
|
||||
|
||||
// The dabs reach `radius` from each point, and the paint map's bilinear sampling one of its texels further
|
||||
let paint_texel = session.doc.bake_paint.get(&(texture_set, target)).map_or(0.0, |map| 1.0 / map.width.min(map.height).max(1) as f32);
|
||||
let reach = Vec2::splat(radius + paint_texel);
|
||||
let low = points.iter().fold(Vec2::INFINITY, |low, point| low.min(*point)) - reach;
|
||||
let high = points.iter().fold(Vec2::NEG_INFINITY, |high, point| high.max(*point)) + reach;
|
||||
session.note_bake_paint(texture_set, Some((low, high)));
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Where skew or cage painting changed what a texture set's transfer rays read since its maps were baked
|
||||
|
||||
use texturecraft_bake::{TexelBox, region_keeps_pixels};
|
||||
use texturecraft_core::{BakeSource, BakedMap};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The UV box painted since the last bake of a texture set's auto-rebake map
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PaintedRegion {
|
||||
pub uv_min: Vec2,
|
||||
pub uv_max: Vec2,
|
||||
/// Counts up with every stroke, so a rebake can tell a newer stroke from the one it bakes
|
||||
pub stroke: u64,
|
||||
}
|
||||
|
||||
/// Texels added around a painted box: bilinear sampling of the paint map and antialiasing samples reach one texel past it
|
||||
const MARGIN_TEXELS: u32 = 1;
|
||||
|
||||
impl Session {
|
||||
/// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`)
|
||||
pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) {
|
||||
let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE));
|
||||
let (uv_min, uv_max) = match self.painted_regions.get(&texture_set) {
|
||||
Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)),
|
||||
None => (uv_min, uv_max),
|
||||
};
|
||||
self.painted_strokes += 1;
|
||||
self.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes });
|
||||
}
|
||||
|
||||
/// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke`
|
||||
pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) {
|
||||
let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake);
|
||||
let painted_since = self.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke);
|
||||
if !painted_since && auto.is_none_or(|map| stored.contains(&map)) {
|
||||
self.painted_regions.remove(&texture_set);
|
||||
}
|
||||
}
|
||||
|
||||
/// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke)
|
||||
pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> {
|
||||
let regions = self.painted_regions.iter();
|
||||
regions
|
||||
.filter_map(|(index, region)| {
|
||||
let set = self.doc.project.texture_sets.get(*index)?;
|
||||
let map = set.auto_rebake.filter(|map| set.baked.contains(map))?;
|
||||
let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty();
|
||||
(from_high && self.bake_changes(*index, map).is_empty()).then_some(())?;
|
||||
Some((*index, map, self.bake_source(*index, map).ok()?, region.stroke))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map
|
||||
pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result<crate::BakeTask> {
|
||||
let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?;
|
||||
let Some(region) = self.painted_regions.get(&texture_set) else { return Ok(task) };
|
||||
let (width, height) = task.settings.common.output_size();
|
||||
let stored =
|
||||
self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map));
|
||||
let Some(stored) = stored.filter(|_| task.tiles == (1, 1) && region_keeps_pixels(map)) else { return Ok(task) };
|
||||
|
||||
let texel = |uv: f32, size: u32, round: fn(f32) -> f32| (round(uv.clamp(0.0, 1.0) * size as f32) as u32).min(size);
|
||||
let painted = TexelBox {
|
||||
min: (texel(region.uv_min.x, width, f32::floor), texel(region.uv_min.y, height, f32::floor)),
|
||||
max: (texel(region.uv_max.x, width, f32::ceil), texel(region.uv_max.y, height, f32::ceil)),
|
||||
};
|
||||
task.previous_maps = stored.clone();
|
||||
task.region = Some(painted.grown(MARGIN_TEXELS, width, height));
|
||||
Ok(task)
|
||||
}
|
||||
}
|
||||
@@ -13,4 +13,6 @@ pub struct StreamedBake {
|
||||
pub tracer: String,
|
||||
/// What the baked maps were baked from (the task's [`crate::BakeTask::sources`])
|
||||
pub sources: BTreeMap<BakedMap, BakeSource>,
|
||||
/// The task's [`crate::BakeTask::painted_stroke`]
|
||||
pub painted_stroke: u64,
|
||||
}
|
||||
@@ -427,6 +427,10 @@ pub struct Session {
|
||||
pub(crate) source: Arc<Mesh>,
|
||||
/// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it
|
||||
pub(crate) low_poly_fingerprint: std::sync::OnceLock<u64>,
|
||||
/// Where skew or cage painting changed each texture set since its auto-rebake map was baked
|
||||
pub(crate) painted_regions: std::collections::BTreeMap<usize, crate::bake::PaintedRegion>,
|
||||
/// Skew and cage strokes so far
|
||||
pub(crate) painted_strokes: u64,
|
||||
pub bvh: Arc<Bvh>,
|
||||
/// Original mesh file (saved inside the project); None for built-in meshes.
|
||||
pub mesh_source: Option<(String, Arc<Vec<u8>>)>,
|
||||
@@ -530,6 +534,8 @@ impl Session {
|
||||
project_id: next_mesh_id(),
|
||||
source,
|
||||
low_poly_fingerprint: Default::default(),
|
||||
painted_regions: Default::default(),
|
||||
painted_strokes: 0,
|
||||
mesh,
|
||||
bvh: Arc::new(bvh),
|
||||
mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))),
|
||||
|
||||
@@ -66,3 +66,76 @@ fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() {
|
||||
assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again");
|
||||
assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::<Vec<_>>(), [BakedMap::Id], "the checks stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_output_size_rebakes_every_checked_map_so_none_is_lost() {
|
||||
let mut session = baked_plane();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({ "resolution": 128 })).unwrap();
|
||||
|
||||
let maps = session.auto_rebake_maps(0, BakedMap::Position);
|
||||
let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap();
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
|
||||
let baked = session.baked(0).unwrap();
|
||||
assert!(baked.maps.contains_key(&BakedMap::Id), "the ID map survives the new size: {:?}", baked.maps.keys().collect::<Vec<_>>());
|
||||
assert!(session.out_of_date_maps(0).is_empty(), "{:?}", session.out_of_date_maps(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() {
|
||||
let mut session = super::bake::leaning_session(true);
|
||||
execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
assert!(session.auto_rebake_painted().is_empty(), "nothing painted since the bake");
|
||||
let before = session.baked(0).unwrap().maps[&BakedMap::Position].clone();
|
||||
|
||||
execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3], [0.4, 0.35]], "radius": 0.05, "size": 64 })).unwrap();
|
||||
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
|
||||
assert_eq!(painted, [(0, BakedMap::Position)]);
|
||||
assert!(session.auto_rebake_due().is_empty(), "painting is not a settings change: {:?}", due_maps(&session));
|
||||
|
||||
let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap();
|
||||
task.tracer = None;
|
||||
let region = task.region.expect("a stroke rebakes only its box");
|
||||
let mut whole = session.bake_task_for(0, &[BakedMap::Position]).unwrap();
|
||||
whole.tracer = None;
|
||||
let whole = whole.run(&Progress::new()).unwrap().maps.remove(&BakedMap::Position).unwrap();
|
||||
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
|
||||
|
||||
let width = output.resolution as usize;
|
||||
assert!(((region.max.0 - region.min.0) as usize) < width / 2, "the box is far smaller than the map: {region:?}");
|
||||
let components = BakedMap::Position.components();
|
||||
let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components));
|
||||
let mut changed = 0;
|
||||
for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() {
|
||||
if region.contains(index % width, index / width) {
|
||||
assert_eq!(rebaked, baked_whole, "texel {index} inside the box");
|
||||
changed += usize::from(rebaked != kept);
|
||||
} else {
|
||||
assert_eq!(rebaked, kept, "texel {index} outside the box");
|
||||
}
|
||||
}
|
||||
assert!(changed > 0, "the stroke changed the map inside its box");
|
||||
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() {
|
||||
let mut session = super::bake::leaning_session(true);
|
||||
execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
let stroke = |at: f32| json!({ "points": [[at, at]], "radius": 0.05, "size": 64 });
|
||||
execute(&mut session, "bake.skew.paint", &stroke(0.3)).unwrap();
|
||||
|
||||
let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap();
|
||||
task.tracer = None;
|
||||
execute(&mut session, "bake.skew.paint", &stroke(0.7)).unwrap();
|
||||
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
|
||||
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
|
||||
assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet");
|
||||
}
|
||||
@@ -527,7 +527,7 @@ fn opacity_samples_textures_next_to_a_high_poly() {
|
||||
}
|
||||
|
||||
/// A plane session whose vertex normals lean, with a high poly plane `dy` above it.
|
||||
fn leaning_session(lean: bool) -> Session {
|
||||
pub(super) fn leaning_session(lean: bool) -> Session {
|
||||
let mut mesh = primitives::builtin("plane").unwrap();
|
||||
if lean {
|
||||
mesh.normals = vec![texturecraft_engine::geom::glam::Vec3::new(0.6, 0.8, 0.0); mesh.positions.len()];
|
||||
|
||||
@@ -7,16 +7,16 @@ use crate::{BakeJob, TextureCraftApp, bake_report, state};
|
||||
/// How long what an out-of-date auto-rebake map is baked from must stay the same before the rebake starts
|
||||
const SETTLE_SECONDS: f64 = 0.5;
|
||||
|
||||
/// An out-of-date auto-rebake map: its texture set, the map and what a bake would read now
|
||||
pub type Due = (usize, BakedMap, BakeSource);
|
||||
/// An out-of-date auto-rebake map: set, map, what a bake reads now, and the newest stroke when only painting changed it
|
||||
pub type Due = (usize, BakedMap, BakeSource, Option<u64>);
|
||||
|
||||
/// What the app has seen of the out-of-date auto-rebake maps
|
||||
#[derive(Default)]
|
||||
pub struct AutoRebake {
|
||||
/// The due maps and the frame time they were first seen as they are
|
||||
pending: Option<(Vec<Due>, f64)>,
|
||||
/// The due maps when the last rebake started: a failed or canceled rebake is not tried again until something changes
|
||||
started: Vec<Due>,
|
||||
/// Rebakes started that are still due: one that failed or was canceled is not tried again until something changes
|
||||
tried: Vec<Due>,
|
||||
}
|
||||
|
||||
/// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed
|
||||
@@ -26,16 +26,20 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
return;
|
||||
}
|
||||
|
||||
let due = app.session.auto_rebake_due();
|
||||
let stale = app.session.auto_rebake_due().into_iter().map(|(set, map, source)| (set, map, source, None));
|
||||
let painted = app.session.auto_rebake_painted().into_iter().map(|(set, map, source, stroke)| (set, map, source, Some(stroke)));
|
||||
let due: Vec<Due> = stale.chain(painted).collect();
|
||||
if let Some(job) = &app.bake {
|
||||
// Newest wins: a rebake whose map changed again while it ran starts over with the new settings
|
||||
if job.rebake.is_some_and(|rebake| !due.contains(&rebake)) {
|
||||
if job.rebake.as_ref().is_some_and(|rebake| !due.contains(rebake)) {
|
||||
app.cancel_bake();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if due.is_empty() || due == app.auto_rebake.started {
|
||||
app.auto_rebake.tried.retain(|tried| due.contains(tried));
|
||||
let waiting: Vec<Due> = due.into_iter().filter(|due| !app.auto_rebake.tried.contains(due)).collect();
|
||||
if waiting.is_empty() {
|
||||
app.auto_rebake.pending = None;
|
||||
return;
|
||||
}
|
||||
@@ -43,24 +47,24 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let now = app.last_time;
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS));
|
||||
match &app.auto_rebake.pending {
|
||||
Some((seen, since)) if *seen == due && now - since >= SETTLE_SECONDS => {}
|
||||
Some((seen, _)) if *seen == due => return,
|
||||
Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {}
|
||||
Some((seen, _)) if *seen == waiting => return,
|
||||
_ => {
|
||||
app.auto_rebake.pending = Some((due, now));
|
||||
app.auto_rebake.pending = Some((waiting, now));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
app.auto_rebake.pending = None;
|
||||
app.auto_rebake.started = due.clone();
|
||||
if let Some(rebake) = due.first().copied() {
|
||||
if let Some(rebake) = waiting.first().copied() {
|
||||
app.auto_rebake.tried.push(rebake);
|
||||
start(app, rebake);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake
|
||||
fn start(app: &mut TextureCraftApp, rebake: Due) {
|
||||
let (set, map, _) = rebake;
|
||||
let (set, map) = (rebake.0, rebake.1);
|
||||
let orders = match app.session.bake_preview_orders(&[set], Some(map)) {
|
||||
Ok(orders) => orders,
|
||||
Err(error) => {
|
||||
@@ -73,7 +77,8 @@ fn start(app: &mut TextureCraftApp, rebake: Due) {
|
||||
app.live_preview.release(&mut app.session);
|
||||
crate::id_color_pick::IdColorPick::end(app);
|
||||
app.session.bake_preview_begin(orders);
|
||||
app.session.begin_map_bake_log(&[set], map);
|
||||
let maps = app.session.auto_rebake_maps(set, map);
|
||||
app.session.begin_map_bake_log(&[set], &maps);
|
||||
app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) };
|
||||
app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) });
|
||||
}
|
||||
@@ -712,7 +712,7 @@ impl TextureCraftApp {
|
||||
|
||||
let total = sets.len();
|
||||
match only {
|
||||
Some(map) => self.session.begin_map_bake_log(&sets, map),
|
||||
Some(map) => self.session.begin_map_bake_log(&sets, &[map]),
|
||||
None => self.session.begin_bake_log(&sets),
|
||||
}
|
||||
self.bake_report = bake_report::BakeReport::started(self.last_time);
|
||||
@@ -893,12 +893,14 @@ impl TextureCraftApp {
|
||||
}
|
||||
|
||||
let set_index = job.queue.remove(0);
|
||||
let (only, rebake) = (job.only, job.rebake);
|
||||
let only = job.only;
|
||||
let rebake = job.rebake.as_ref().map(|(_, map, _, stroke)| (*map, stroke.is_some()));
|
||||
|
||||
self.session.bake_preview_set_current(set_index);
|
||||
self.session.bake_log.set_started(set_index);
|
||||
let task = match (rebake, only) {
|
||||
(Some((_, map, _)), _) => self.session.bake_task_for(set_index, &[map]),
|
||||
(Some((map, true)), _) => self.session.bake_painted_task(set_index, map),
|
||||
(Some((map, false)), _) => self.session.bake_task_for(set_index, &self.session.auto_rebake_maps(set_index, map)),
|
||||
(None, Some(map)) => self.session.bake_task_only(set_index, map),
|
||||
(None, None) => self.session.bake_task(set_index),
|
||||
};
|
||||
@@ -954,8 +956,7 @@ impl TextureCraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cancel the active worker, discard queued sets and restore the view. The current set's
|
||||
/// preview maps are discarded; previously applied sets keep their results and undo steps.
|
||||
/// Cancel the running set's bake and the queued ones and restore the view; sets already applied keep their maps and undo steps
|
||||
pub fn cancel_bake(&mut self) {
|
||||
let Some(job) = self.bake.take() else { return };
|
||||
|
||||
|
||||
@@ -85,3 +85,31 @@ fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() {
|
||||
assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled);
|
||||
execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() {
|
||||
let mut harness = harness(64);
|
||||
let plane = primitives::builtin("plane").unwrap();
|
||||
let mut high = String::from("o Part_high\n");
|
||||
for position in &plane.positions {
|
||||
high += &format!("v {} {} {}\n", position.x, position.y + 0.1, position.z);
|
||||
}
|
||||
for triangle in plane.indices.as_chunks::<3>().0 {
|
||||
high += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1);
|
||||
}
|
||||
let session = &mut harness.state_mut().session;
|
||||
session.add_high_poly_bytes("high.obj", high.into_bytes()).unwrap();
|
||||
execute(session, "bake.run", &json!({ "maps": ["position"] })).unwrap();
|
||||
harness.run_steps(4);
|
||||
assert!(harness.state().bake.is_none(), "up to date after the bake");
|
||||
|
||||
execute(&mut harness.state_mut().session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap();
|
||||
step_until(&mut harness, "the rebake", |app| app.bake.is_some());
|
||||
step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none());
|
||||
|
||||
let app = harness.state();
|
||||
assert!(app.session.auto_rebake_painted().is_empty(), "the rebake took the stroke");
|
||||
let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect();
|
||||
assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]);
|
||||
assert!(app.toasts.is_empty(), "a rebake that went well is quiet");
|
||||
}
|
||||
@@ -331,7 +331,10 @@ own). Imported maps, and maps saved before this record existed, never show:
|
||||
with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web
|
||||
app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the
|
||||
background, alone, once its settings have stopped changing for half a second; a change during
|
||||
that bake restarts it. The headless CLI does not rebake by itself: run `bake.run` there.
|
||||
that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that
|
||||
bakes from a high poly makes the app bake its auto-rebake map again only inside the stroke's UV
|
||||
box, keeping the rest; maps scaled by their whole range (curvature, height, thickness) are baked
|
||||
whole. The headless CLI does not rebake by itself: run `bake.run` there.
|
||||
|
||||
`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with
|
||||
`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`)
|
||||
|
||||
Reference in new issue
Block a user