mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-30 01:54:29 +01:00
Auto: Fix Compare evaluation, folder resets and mask editing
Integrate main's projector, resource-picker and UI changes. Keep Compare inputs tied to the correct folder draw, propagate filter margins through sparse masks, and preserve the real backdrop in folder thumbnails. Retarget saved seed resets when folders are copied. Preserve grayscale tool choices, reject missing mask images before mutation, and release the previous anchor's draft and undo state when selection changes. Borrow material data during planning and write filtered samples directly into output rows. Cover the repaired behavior in the compositor, engine and Properties tests.
This commit is contained in:
commit
64d1108b14
164 files changed
+4404
-1751
No files matched your search
+1
-1
@@ -23,7 +23,7 @@ licensed and keep their license file next to them.
|
||||
| `docs/images/texturecraft-light.png` | README screenshot: the light brightness level with the blue accent | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 |
|
||||
| `docs/images/texturecraft-lantern.png` | README render: a storm lantern (original procedural mesh of lathes and swept wires, eight texture sets) in chipped red enamel, rust, soot, tarnished brass and glass with an emissive flame (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 |
|
||||
| `docs/images/texturecraft-camera.png` | README render: a rangefinder camera (original procedural mesh) in black enamel worn to brass, leatherette, chrome and coated glass; the lens distance scale is an original image drawn in code (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 |
|
||||
| `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | https://polyhaven.com/a/studio_small_09 (1K .hdr) | CC0-1.0 |
|
||||
| `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) |
|
||||
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
|
||||
| `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) |
|
||||
|
||||
|
||||
@@ -443,6 +443,7 @@ mod tests {
|
||||
}
|
||||
let moved = window_frame(&mut harness, moves);
|
||||
let put_back = moved.iter().any(|command| matches!(command, egui::ViewportCommand::CursorPosition(to) if to.distance(pad) <= PUT_BACK_REACH));
|
||||
|
||||
assert!(locked || put_back, "the window puts the pointer back where the press began, so it never leaves: {moved:?}");
|
||||
let seen = harness.ctx.input(|input| input.pointer.latest_pos());
|
||||
assert!(seen.is_some_and(|seen| seen.distance(pad + DRAG_STEP) <= PUT_BACK_REACH), "the app reads the whole move: {seen:?}");
|
||||
|
||||
@@ -6,7 +6,8 @@ use texturecraft_geom::glam::{EulerRot, Mat3, Vec3};
|
||||
use crate::frame_placement::culling_folds;
|
||||
use crate::pattern::{DEPTH_FADE_START, frame_uv_from_corner, mesh_frame, nonzero_stretch, projector_stretch};
|
||||
|
||||
/// The placed planar projection that reads images exactly as axis planar `proj` does on a mesh within `bounds` (None for other projections, placed ones included, and while backface culling cannot keep its facing in a frame: see [`culling_folds`])
|
||||
/// Place an axis planar on a mesh within `bounds` while keeping its sampling and culling.
|
||||
/// See [`culling_folds`] for when culling prevents placement.
|
||||
pub fn placed_from_axis(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<Projection> {
|
||||
let Projection::Planar { scale, axis, offset, uv, projector, placed: None } = proj else { return None };
|
||||
|
||||
@@ -16,8 +17,8 @@ pub fn placed_from_axis(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<Proje
|
||||
|
||||
let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, bounds)?;
|
||||
|
||||
// The turn and per-axis scale are now in the frame; culling and crop stay
|
||||
let projector = Projector { rotation: [0.0; 3], scale: [1.0; 3], ..*projector };
|
||||
// The frame carries rotation and scale while the projected rectangle keeps axis coverage
|
||||
let projector = Projector { rotation: [0.0; 3], scale: [1.0; 3], ignore_image_alpha: true, ..*projector };
|
||||
|
||||
// An axis planar turns its image round the top left, a frame round its centre
|
||||
let uv = frame_uv_from_corner(uv);
|
||||
@@ -109,6 +110,7 @@ mod tests {
|
||||
let (before, _) = image_samples(&axis_planar, &coords)[0];
|
||||
let (uv_after, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers");
|
||||
let (after, _) = image_samples(&placed, &Coords { uv: uv_after, ..coords })[0];
|
||||
|
||||
assert!(before.distance(after) < 1e-3, "axis {axis} {rotation:?}: {before} became {after}");
|
||||
assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "axis {axis} {crop:?}: cover changed at {position}");
|
||||
}
|
||||
@@ -124,7 +126,7 @@ mod tests {
|
||||
let radius = (hi - lo).length() * 0.5;
|
||||
let backface = Backface { on: true, angle: 60.0, hardness: 1.0 };
|
||||
|
||||
// Half way between across and out: a stretch across tilts the culled normal past the angle, a negative one turns it round
|
||||
// An oblique normal exposes tilted and reversed culling under stretch
|
||||
let halfway = (center, Vec3::new(1.0, 0.0, 1.0).normalize());
|
||||
|
||||
for stretch in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] {
|
||||
@@ -150,6 +152,7 @@ mod tests {
|
||||
#[test]
|
||||
fn only_axis_planars_are_placed() {
|
||||
let bounds = (Vec3::NEG_ONE, Vec3::ONE);
|
||||
|
||||
assert!(placed_from_axis(&Projection::default(), bounds).is_none());
|
||||
|
||||
let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame");
|
||||
|
||||
@@ -7,10 +7,12 @@
|
||||
//! identical to a full evaluation.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use texturecraft_core::project::MAX_DEPTH;
|
||||
use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet};
|
||||
use texturecraft_geom::Mesh;
|
||||
use texturecraft_texel::TileImage;
|
||||
|
||||
use crate::eval::{Inputs, PaintTarget};
|
||||
@@ -25,6 +27,8 @@ pub const BELOW_BUDGET: usize = 256 << 20;
|
||||
/// See the module docs. One per texture set.
|
||||
#[derive(Debug)]
|
||||
pub struct BelowCache {
|
||||
mesh: Weak<Mesh>,
|
||||
borrowed_mesh_key: Option<u64>,
|
||||
hot: Option<LayerId>,
|
||||
key: Option<StackKey>,
|
||||
/// Tiles with the stamp of their last use.
|
||||
@@ -52,6 +56,8 @@ pub struct BelowCache {
|
||||
impl Default for BelowCache {
|
||||
fn default() -> Self {
|
||||
BelowCache {
|
||||
mesh: Weak::new(),
|
||||
borrowed_mesh_key: None,
|
||||
hot: None,
|
||||
key: None,
|
||||
tiles: HashMap::new(),
|
||||
@@ -266,6 +272,48 @@ fn render_view(l: &Layer) -> Layer {
|
||||
}
|
||||
|
||||
impl BelowCache {
|
||||
pub(crate) fn bind_mesh(&mut self, mesh: &Arc<Mesh>) {
|
||||
if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) {
|
||||
self.clear();
|
||||
self.borrowed_mesh_key = None;
|
||||
self.mesh = Arc::downgrade(mesh);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bind_borrowed_mesh(&mut self, mesh: &Mesh) {
|
||||
if std::ptr::eq(self.mesh.as_ptr(), mesh) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A borrow alone cannot distinguish in-place edits or reuse of the same address
|
||||
let mut key = DefaultHasher::new();
|
||||
for attribute in [&mesh.positions, &mesh.normals] {
|
||||
attribute.len().hash(&mut key);
|
||||
for value in attribute {
|
||||
value.to_array().map(f32::to_bits).hash(&mut key);
|
||||
}
|
||||
}
|
||||
mesh.tangents.len().hash(&mut key);
|
||||
for value in &mesh.tangents {
|
||||
value.to_array().map(f32::to_bits).hash(&mut key);
|
||||
}
|
||||
mesh.uvs.len().hash(&mut key);
|
||||
for value in &mesh.uvs {
|
||||
value.to_array().map(f32::to_bits).hash(&mut key);
|
||||
}
|
||||
mesh.indices.hash(&mut key);
|
||||
for part in &mesh.submeshes {
|
||||
(&part.name, part.start, part.count, part.material).hash(&mut key);
|
||||
}
|
||||
|
||||
let key = key.finish();
|
||||
if self.borrowed_mesh_key != Some(key) {
|
||||
self.clear();
|
||||
self.mesh = Weak::new();
|
||||
self.borrowed_mesh_key = Some(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Cache the stack around `hot` from now on (a different layer empties the cache).
|
||||
pub fn set_hot(&mut self, hot: Option<LayerId>) {
|
||||
if self.hot != hot {
|
||||
|
||||
+634
-268
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
||||
//! Where a layer is drawn inside the current texture set.
|
||||
|
||||
use texturecraft_core::{ContentsOffset, Layer, LayerId};
|
||||
|
||||
use super::EvaluationInputs;
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(super) struct DrawPlacement {
|
||||
pub offset: ContentsOffset,
|
||||
/// Zero denotes the original folder tree
|
||||
pub instance: usize,
|
||||
}
|
||||
|
||||
impl From<ContentsOffset> for DrawPlacement {
|
||||
fn from(offset: ContentsOffset) -> Self {
|
||||
Self { offset, instance: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl DrawPlacement {
|
||||
pub(super) fn children(self, inputs: &EvaluationInputs, id: LayerId, source: &Layer) -> Self {
|
||||
let instance = if id == source.id { self.instance } else { inputs.instance_draw(self.instance, id) };
|
||||
Self { offset: self.offset.then(inputs.project.contents_offset(source.id)), instance }
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,69 @@
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Deref;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use texturecraft_core::{FillSymmetry, LayerId, Project, Projection, Sampling};
|
||||
|
||||
use super::Inputs;
|
||||
use crate::ProjectorDepthCache;
|
||||
use crate::fill_depth::FillDepth;
|
||||
use crate::pattern::mesh_frame;
|
||||
use crate::projector_depth_cache::ViewDepth;
|
||||
use crate::projector_view::ProjectorView;
|
||||
|
||||
/// Hold up to 30 MiB of depth maps through an evaluation; later views use the shared cache
|
||||
const MAX_EVALUATION_VIEWS: usize = 10;
|
||||
|
||||
pub(super) struct EvaluationInputs<'a> {
|
||||
inputs: &'a Inputs<'a>,
|
||||
pub(super) projectors: &'a ProjectorDepthCache,
|
||||
projectors: &'a ProjectorDepthCache,
|
||||
instance_draws: OnceLock<HashMap<(usize, LayerId), usize>>,
|
||||
depth_maps: Mutex<Vec<ViewDepth>>,
|
||||
}
|
||||
|
||||
impl<'a> EvaluationInputs<'a> {
|
||||
pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self {
|
||||
Self { inputs, projectors }
|
||||
Self { inputs, projectors, instance_draws: OnceLock::new(), depth_maps: Mutex::new(Vec::new()) }
|
||||
}
|
||||
|
||||
/// Each path through nested folder instances gets a stable identity within an evaluation.
|
||||
pub(super) fn instance_draw(&self, parent: usize, id: LayerId) -> usize {
|
||||
let draws = self.instance_draws.get_or_init(|| {
|
||||
let mut draws = HashMap::new();
|
||||
if let Ok(set) = self.project.texture_set(self.ts) {
|
||||
collect_instance_draws(self.project, &set.stack, 0, 0, &mut draws);
|
||||
}
|
||||
|
||||
draws
|
||||
});
|
||||
|
||||
draws.get(&(parent, id)).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) fn projector_depth(&self, projection: &Projection, sampling: Sampling) -> Option<Arc<FillDepth>> {
|
||||
let view = ProjectorView::of(projection, self.bounds)?;
|
||||
let copies = sampling.symmetry.on.then(|| {
|
||||
let (center, radius) = mesh_frame(self.bounds);
|
||||
|
||||
// Flipping the image leaves the projector's depth view unchanged
|
||||
(FillSymmetry { flip: [false; 2], ..sampling.symmetry }, center, radius)
|
||||
});
|
||||
let key = (view, copies);
|
||||
|
||||
let mut depth_maps = self.depth_maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if let Some((_, map)) = depth_maps.iter().find(|(cached_key, _)| *cached_key == key) {
|
||||
return map.clone();
|
||||
}
|
||||
|
||||
if depth_maps.len() >= MAX_EVALUATION_VIEWS {
|
||||
// Keep overflow work out of the evaluation lock
|
||||
drop(depth_maps);
|
||||
return self.projectors.get(self.mesh, key);
|
||||
}
|
||||
|
||||
let depth = self.projectors.get(self.mesh, key);
|
||||
depth_maps.push((key, depth.clone()));
|
||||
depth
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,3 +74,20 @@ impl<'a> Deref for EvaluationInputs<'a> {
|
||||
self.inputs
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_instance_draws(project: &Project, layers: &[LayerId], parent: usize, depth: usize, draws: &mut HashMap<(usize, LayerId), usize>) {
|
||||
if depth > texturecraft_core::project::MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
|
||||
for &id in layers {
|
||||
let Some(source) = project.content_layer(id).filter(|layer| !layer.children().is_empty()) else { continue };
|
||||
let instance = if id == source.id {
|
||||
parent
|
||||
} else {
|
||||
let next = draws.len() + 1;
|
||||
*draws.entry((parent, id)).or_insert(next)
|
||||
};
|
||||
collect_instance_draws(project, source.children(), instance, depth + 1, draws);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
//! Isolated folder evaluation with the original stack available for anchor inputs.
|
||||
|
||||
use super::{
|
||||
Channel, ChannelKind, Composite, EvaluationInputs, Inputs, LayerId, ProjectorDepthCache, Texel, all_tiles, evaluation_fields, plan, tile_texels, to_u16,
|
||||
to_u16_signed,
|
||||
Channel, ChannelKind, Composite, EvaluationInputs, Inputs, LayerId, ProjectorDepthCache, Tape, Texel, all_tiles, evaluation_channels, evaluation_fields,
|
||||
plan, tile_texels, to_u16, to_u16_signed,
|
||||
};
|
||||
|
||||
/// Composite one layer over channel defaults, keeping anchors from the stack below it.
|
||||
pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option<Composite> {
|
||||
let set = inputs.project.texture_set(inputs.ts).ok()?;
|
||||
let channels = set.channel_list();
|
||||
let channels = evaluation_channels(inputs, set.channel_list());
|
||||
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
|
||||
let tiles = all_tiles(width, height);
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
@@ -17,14 +17,30 @@ pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel)
|
||||
let mut composite = Composite::with_size(&[channel], width, height);
|
||||
let output = composite.channels.get_mut(&channel)?;
|
||||
|
||||
let mut recorded = Vec::new();
|
||||
for (tile_x, tile_y) in tiles {
|
||||
let nodes = plan(inputs, &[layer], &channels, tile_x, tile_y, 0, Some(&fields));
|
||||
let full_stack = if set.stack.as_slice() == [layer] { Vec::new() } else { plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)) };
|
||||
for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) {
|
||||
let mut texel = Texel::new(inputs, x, y, offset, 0.0);
|
||||
texel.anchors_below(&full_stack, layer);
|
||||
texel.anchors_below(&full_stack, (layer, 0));
|
||||
let mut values = Channel::ALL.map(Channel::default_value);
|
||||
texel.eval(&nodes, &mut values);
|
||||
if let Some(mut backdrop) = texel.below {
|
||||
// Evaluate masks against the real backdrop, then show only this folder's contribution
|
||||
texel.tape = Tape::Record(std::mem::take(&mut recorded));
|
||||
texel.eval(&nodes, &mut backdrop);
|
||||
if let Tape::Record(samples) = texel.tape {
|
||||
recorded = samples;
|
||||
}
|
||||
|
||||
let mut isolated = Texel::new(inputs, x, y, offset, 0.0);
|
||||
isolated.tape = Tape::Replay(&recorded, 0);
|
||||
isolated.eval(&nodes, &mut values);
|
||||
recorded.clear();
|
||||
} else {
|
||||
texel.eval(&nodes, &mut values);
|
||||
}
|
||||
|
||||
let value = values.get(channel.index()).copied().unwrap_or_else(|| channel.default_value());
|
||||
let encoded = value.map(|component| if channel.kind() == ChannelKind::Signed { to_u16_signed(component) } else { to_u16(component) });
|
||||
output.set(x, y, &encoded[..channel.components()]);
|
||||
|
||||
@@ -40,7 +40,7 @@ impl FillCopies {
|
||||
}
|
||||
|
||||
/// Copy `index`: the original at 0, then the mirror or the radial copies in turn
|
||||
fn copy(&self, index: u32) -> FillCopy {
|
||||
pub(crate) fn copy(&self, index: u32) -> FillCopy {
|
||||
let flip = if index == 0 { [false; 2] } else { self.symmetry.flip };
|
||||
let turn = match self.symmetry.kind {
|
||||
_ if index == 0 => Mat3::IDENTITY,
|
||||
@@ -55,6 +55,16 @@ impl FillCopies {
|
||||
};
|
||||
FillCopy::new(turn, self.pivot, flip)
|
||||
}
|
||||
|
||||
pub(crate) fn next_indexed(&mut self) -> Option<(usize, FillCopy)> {
|
||||
if self.next >= self.count {
|
||||
return None;
|
||||
}
|
||||
|
||||
let index = (self.first + self.next) % self.count;
|
||||
self.next += 1;
|
||||
Some((index as usize, self.copy(index)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The radial copy nearest a texel `turned` degrees round the axis, of `count` copies `step` degrees apart over `span` degrees: copy 0 across the gap a span under a full turn leaves, else the nearest by its step
|
||||
@@ -79,13 +89,7 @@ impl Iterator for FillCopies {
|
||||
type Item = FillCopy;
|
||||
|
||||
fn next(&mut self) -> Option<FillCopy> {
|
||||
if self.next >= self.count {
|
||||
return None;
|
||||
}
|
||||
|
||||
let index = (self.first + self.next) % self.count;
|
||||
self.next += 1;
|
||||
Some(self.copy(index))
|
||||
self.next_indexed().map(|(_, copy)| copy)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,6 +152,7 @@ mod tests {
|
||||
past_copy.min(FULL_TURN_DEGREES - past_copy)
|
||||
};
|
||||
let searched = (0..count).min_by(|a, b| gap(*a).total_cmp(&gap(*b))).unwrap_or(0);
|
||||
|
||||
assert_eq!(nearest_copy(turned, step, count, span), searched, "{count} copies over {span} at {turned}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
use texturecraft_core::FillSymmetry;
|
||||
use texturecraft_geom::{Mesh, glam::Vec3};
|
||||
|
||||
use crate::fill_copies::FillCopies;
|
||||
use crate::projector_depth::{CELL_BUDGET, GRID_SIDE, ProjectorDepth};
|
||||
use crate::projector_view::ProjectorView;
|
||||
|
||||
pub(crate) type FillDepthKey = (ProjectorView, Option<(FillSymmetry, Vec3, f32)>);
|
||||
|
||||
/// Depth coverage in the original and optional symmetric views of one fill.
|
||||
pub(crate) enum FillDepth {
|
||||
Single(ProjectorDepth),
|
||||
Copies(Box<[Option<ProjectorDepth>]>),
|
||||
}
|
||||
|
||||
impl FillDepth {
|
||||
pub(crate) fn build(mesh: &Mesh, (view, symmetry): FillDepthKey) -> Option<Self> {
|
||||
let Some((symmetry, center, radius)) = symmetry else {
|
||||
return ProjectorDepth::build(view, mesh).map(Self::Single);
|
||||
};
|
||||
|
||||
let copies = FillCopies::new(&symmetry, center, center, radius);
|
||||
let count = symmetry.copies() as usize;
|
||||
|
||||
// Share one grid's storage and raster budget across the copy views
|
||||
let grid_side = (GRID_SIDE * GRID_SIDE / count).isqrt();
|
||||
let cell_budget = CELL_BUDGET / count;
|
||||
let maps: Box<_> =
|
||||
(0..count).map(|index| ProjectorDepth::build_for_copy(view, mesh, Some(copies.copy(index as u32)), grid_side, cell_budget)).collect();
|
||||
|
||||
maps.iter().any(Option::is_some).then_some(Self::Copies(maps))
|
||||
}
|
||||
|
||||
/// Read coverage at the point already transformed into the selected copy's space.
|
||||
pub(crate) fn cover(&self, copy_index: usize, position: Vec3, hardness: f32) -> f32 {
|
||||
let depth = match self {
|
||||
Self::Single(depth) => Some(depth),
|
||||
Self::Copies(maps) => maps.get(copy_index).and_then(Option::as_ref),
|
||||
};
|
||||
|
||||
depth.map_or(1.0, |depth| depth.cover(position, hardness))
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
use texturecraft_core::Fill;
|
||||
use texturecraft_core::{Fill, Projection};
|
||||
|
||||
use crate::projector_depth::ProjectorDepth;
|
||||
use crate::fill_depth::FillDepth;
|
||||
|
||||
/// A fill as a texel samples it: the fill, its projector's depth map when it culls by depth, and whether it covers every texel
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct FillPlace<'f> {
|
||||
pub fill: &'f Fill,
|
||||
pub depth: Option<&'f ProjectorDepth>,
|
||||
pub projection: &'f Projection,
|
||||
pub depth: Option<&'f FillDepth>,
|
||||
/// Decided once per tile, so a texel never works its coverage out
|
||||
pub covers_all: bool,
|
||||
}
|
||||
@@ -29,15 +29,17 @@ pub struct FramePlacement {
|
||||
pub scale: [f32; 3],
|
||||
}
|
||||
|
||||
/// Whether backface culling faces the same way once `projector`'s scale is moved into a frame: culling is off, or the scale is even and keeps the side the frame faces (culling reads the scaled normal, a frame its own)
|
||||
/// Whether moving the projector's scale into the frame preserves culling
|
||||
pub fn culling_folds(projector: &Projector) -> bool {
|
||||
let stretch = projector_stretch(projector);
|
||||
let size = stretch.abs();
|
||||
let even = size.x == size.y && size.y == size.z;
|
||||
!projector.backface.on || (even && stretch.x * stretch.y * stretch.z > 0.0)
|
||||
let facing_preserved = stretch.x.signum() * stretch.y.signum() * stretch.z.signum() > 0.0;
|
||||
(!projector.depth.on || facing_preserved) && (!projector.backface.on || (even && facing_preserved))
|
||||
}
|
||||
|
||||
/// `proj` (a placed planar or a warp) with its projector's turn and scale moved into its frame, so the frame is where the projection lands; culling and crop stay. None for other projections, and while backface culling cannot keep its facing (see [`culling_folds`])
|
||||
/// Fold a placed planar or warp's turn and scale into its frame while preserving crop and culling.
|
||||
/// See [`culling_folds`] for when a fold would change culling.
|
||||
pub fn folded(proj: &Projection) -> Option<Projection> {
|
||||
let (frame, projector) = match proj {
|
||||
Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => (frame, projector),
|
||||
@@ -120,7 +122,9 @@ pub fn placement(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<FramePlaceme
|
||||
/// Frame projection `proj` (a placed planar or a warp) moved to `placement`; its projector's turn and scale are folded in first, its other settings kept (None for other projections or a degenerate placement)
|
||||
pub fn placed(proj: &Projection, placement: &FramePlacement, bounds: (Vec3, Vec3)) -> Option<Projection> {
|
||||
let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale);
|
||||
if !values.copied().all(f32::is_finite) || placement.scale.iter().any(|scale| *scale <= 0.0) {
|
||||
let [width_scale, height_scale, reach_scale] = placement.scale;
|
||||
let valid_reach = reach_scale > 0.0 || (reach_scale == 0.0 && matches!(proj, Projection::Warp { .. }));
|
||||
if !values.copied().all(f32::is_finite) || width_scale <= 0.0 || height_scale <= 0.0 || !valid_reach {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -239,6 +243,7 @@ mod tests {
|
||||
for proj in [planar(projector), warp(projector)] {
|
||||
let flat = folded(&proj).unwrap();
|
||||
let Projector { rotation, scale, crop, .. } = projector_of(&flat);
|
||||
|
||||
assert_eq!((rotation, scale, crop), ([0.0; 3], [1.0; 3], ShapeCrop::Cropped), "the turn and scale moved into the frame, the crop stayed");
|
||||
|
||||
close(&samples(&proj), &samples(&flat));
|
||||
@@ -248,12 +253,24 @@ mod tests {
|
||||
assert_eq!(folded(&Projection::default()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_culling_prevents_folding_with_the_opposite_facing() {
|
||||
let mut projector = Projector::depth_culled();
|
||||
projector.scale[2] = -1.0;
|
||||
let bounds = (Vec3::NEG_ONE, Vec3::ONE);
|
||||
let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
|
||||
|
||||
assert!(folded(&planar(projector)).is_none(), "an existing frame would face the opposite direction");
|
||||
assert!(crate::axis_frame::placed_from_axis(&axis_planar, bounds).is_none(), "an axis projector would face the opposite direction");
|
||||
assert!(folded(&planar(Projector::depth_culled())).is_some(), "unit stretch preserves facing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_keeps_what_backface_culling_hides() {
|
||||
let backface = Backface { on: true, angle: 60.0, hardness: 1.0 };
|
||||
let square = Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], size: [1.0, 1.0], rotation: 0.0, offset: [0.0; 2], ..frame() };
|
||||
|
||||
// Half way between across and out: a scale across tilts the culled normal past the angle, a negative one turns it round
|
||||
// An oblique normal distinguishes tilt from reflection
|
||||
let normal = Vec3::new(1.0, 0.0, 1.0).normalize();
|
||||
let center = (BOUNDS.0 + BOUNDS.1) * 0.5;
|
||||
let cover = |proj: &Projection| framed_cover(proj, Vec3::ZERO, normal, center).map(|(_, cover)| cover);
|
||||
@@ -305,6 +322,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_frames_upright_turn_is_its_turn_round_its_normal() {
|
||||
let mut flat = Decal { normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], rotation: 30.0, offset: [0.0; 2], ..frame() };
|
||||
|
||||
assert!((upright_turn(&flat).unwrap() - 30.0).abs() < 1e-3);
|
||||
|
||||
flat.rotation = -100.0;
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod eval;
|
||||
mod fabric;
|
||||
pub mod fill_copies;
|
||||
pub mod fill_copy;
|
||||
mod fill_depth;
|
||||
mod fill_place;
|
||||
pub mod frame_placement;
|
||||
mod fur_lock;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::lum;
|
||||
use texturecraft_core::{Filtering, Sampling, UvWrap, lum};
|
||||
|
||||
use crate::ImageRes;
|
||||
|
||||
@@ -25,7 +25,8 @@ impl MaskGray {
|
||||
MaskGray::Image { image, .. } => {
|
||||
let u = (x as f32 + 0.5) / width.max(1) as f32;
|
||||
let v = (y as f32 + 0.5) / height.max(1) as f32;
|
||||
let [r, g, b, _] = image.sample(u, v);
|
||||
let sampling = Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::None, ..Sampling::SAVED_BEFORE };
|
||||
let [r, g, b, _] = image.sample_filtered(u, v, sampling, 1.0);
|
||||
lum([r, g, b]).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
@@ -39,3 +40,23 @@ impl MaskGray {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_mask_image_does_not_wrap_at_texture_edges() {
|
||||
let black = [0.0, 0.0, 0.0, 1.0];
|
||||
let white = [1.0; 4];
|
||||
let image = Arc::new(ImageRes::new(2, 2, vec![black, white, white, white], false));
|
||||
let brush = MaskGray::Image { name: "brush.png".to_owned(), image };
|
||||
|
||||
let near_corner = brush.at(0, 0, (4, 4));
|
||||
let inside = brush.at(1, 1, (4, 4));
|
||||
let far_corner = brush.at(3, 3, (4, 4));
|
||||
|
||||
assert!(near_corner < 0.01, "opposite edges must leave the black corner black, got {near_corner}");
|
||||
assert!(near_corner < inside && inside < far_corner, "sampling between image texels stays bilinear");
|
||||
}
|
||||
}
|
||||
@@ -13,23 +13,91 @@ pub struct MipLevel {
|
||||
/// Share of each of the 2 × 2 texels in a halved texel
|
||||
const TEXEL_SHARE: f32 = 0.25;
|
||||
|
||||
/// A halved interval can overlap at most three source texels on each axis
|
||||
const AREA_FILTER_ROWS: usize = 3;
|
||||
|
||||
impl MipLevel {
|
||||
/// `rgba` halved: each texel averages the 2 × 2 texels it covers (a size of 1 wraps; an odd size above leaves out its last row or column)
|
||||
/// Downsample the whole image by area, including odd trailing rows and columns.
|
||||
pub(crate) fn halve(rgba: &[[f32; 4]], width: u32, height: u32) -> MipLevel {
|
||||
Self::halve_with(rgba, width, height, None::<fn([f32; 4]) -> [f32; 4]>)
|
||||
}
|
||||
|
||||
/// Decode stored texels before averaging the first level of an sRGB color chain.
|
||||
pub(crate) fn halve_with(rgba: &[[f32; 4]], width: u32, height: u32, decode: Option<impl Fn([f32; 4]) -> [f32; 4] + Copy>) -> MipLevel {
|
||||
let (w, h) = ((width / 2).max(1), (height / 2).max(1));
|
||||
let mut halved = Vec::with_capacity(w as usize * h as usize);
|
||||
for y in 0..i64::from(h) {
|
||||
for x in 0..i64::from(w) {
|
||||
let mut sum = [0.0f32; 4];
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let texel = texel_of(rgba, width, height, x * 2 + dx, y * 2 + dy, (true, true));
|
||||
for (total, value) in sum.iter_mut().zip(texel) {
|
||||
*total += value * TEXEL_SHARE;
|
||||
if (width <= 1 || width.is_multiple_of(2)) && (height <= 1 || height.is_multiple_of(2)) {
|
||||
for y in 0..i64::from(h) {
|
||||
for x in 0..i64::from(w) {
|
||||
let mut sum = [0.0f32; 4];
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let stored = texel_of(rgba, width, height, x * 2 + dx, y * 2 + dy, (true, true));
|
||||
let texel = decode.map_or(stored, |decode| decode(stored));
|
||||
for (total, value) in sum.iter_mut().zip(texel) {
|
||||
*total += value * TEXEL_SHARE;
|
||||
}
|
||||
}
|
||||
halved.push(sum);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let row_stride = u64::from(width.max(1));
|
||||
let read = |row_start, source_x| {
|
||||
let index = usize::try_from(row_start + source_x).ok();
|
||||
index.and_then(|index| rgba.get(index)).copied().unwrap_or_default()
|
||||
};
|
||||
let mut decoded_rows = decode.map(|_| std::array::from_fn::<_, AREA_FILTER_ROWS, _>(|_| (u64::MAX, Vec::with_capacity(row_stride as usize))));
|
||||
|
||||
for y in 0..h {
|
||||
let source_rows = source_weights(y, height, h);
|
||||
if let Some((decode, rows)) = decode.zip(decoded_rows.as_mut()) {
|
||||
// Keep decoded rows for adjacent output intervals that share their texels
|
||||
for (source_y, _) in source_rows.clone() {
|
||||
let (row, texels) = &mut rows[source_y as usize % AREA_FILTER_ROWS];
|
||||
if *row != source_y {
|
||||
let row_start = source_y * row_stride;
|
||||
texels.clear();
|
||||
texels.extend((0..row_stride).map(|source_x| decode(read(row_start, source_x))));
|
||||
*row = source_y;
|
||||
}
|
||||
}
|
||||
}
|
||||
halved.push(sum);
|
||||
|
||||
for x in 0..w {
|
||||
let source_columns = source_weights(x, width, w);
|
||||
let mut sum = [0.0; 4];
|
||||
for (source_y, vertical_weight) in source_rows.clone() {
|
||||
let row_start = source_y * row_stride;
|
||||
let row = decoded_rows.as_ref().map(|rows| &rows[source_y as usize % AREA_FILTER_ROWS].1);
|
||||
for (source_x, horizontal_weight) in source_columns.clone() {
|
||||
let texel = row.map_or_else(|| read(row_start, source_x), |row| row[source_x as usize]);
|
||||
let weight = vertical_weight * horizontal_weight;
|
||||
for (total, value) in sum.iter_mut().zip(texel) {
|
||||
*total += value * weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
halved.push(sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MipLevel { width: w, height: h, rgba: halved }
|
||||
}
|
||||
}
|
||||
|
||||
/// Source texels intersecting one output interval and their fractional coverage.
|
||||
fn source_weights(index: u32, source_size: u32, output_size: u32) -> impl Iterator<Item = (u64, f32)> + Clone {
|
||||
let source = u64::from(source_size.max(1));
|
||||
let output = u64::from(output_size);
|
||||
let inverse_source = 1.0 / source as f32;
|
||||
|
||||
// Scale both intervals to integer boundaries for exact overlap at either edge
|
||||
let start = u64::from(index) * source;
|
||||
let end = start + source;
|
||||
|
||||
(start / output..end.div_ceil(output)).map(move |texel| {
|
||||
let overlap = end.min((texel + 1) * output) - start.max(texel * output);
|
||||
(texel, overlap as f32 * inverse_source)
|
||||
})
|
||||
}
|
||||
@@ -380,13 +380,21 @@ const TRIPLANAR_SKIP: f32 = 1.0 / 131_072.0;
|
||||
/// Normalized triplanar blend weights (YZ, XZ, XY planes) for normal `nrm`; planes too light
|
||||
/// to change a 0..1 value scaled by `gain` afterwards weigh 0 (see [`TRIPLANAR_SKIP`]).
|
||||
fn triplanar_weights(nrm: Vec3, sharpness: f32, gain: f32) -> Vec3 {
|
||||
let weights = sharpen(nrm.abs(), sharpness);
|
||||
let weights = weights / (weights.x + weights.y + weights.z).max(MIN_WEIGHT_SUM);
|
||||
let weights = normalized_triplanar_weights(nrm, sharpness);
|
||||
let skip_threshold = TRIPLANAR_SKIP / gain.max(1.0);
|
||||
let retained = Vec3::select(weights.cmplt(Vec3::splat(skip_threshold)), Vec3::ZERO, weights);
|
||||
Vec3::select(weights.cmplt(Vec3::splat(skip_threshold)), Vec3::ZERO, weights)
|
||||
}
|
||||
|
||||
// Preserve the blend if thresholding would discard every plane
|
||||
if retained == Vec3::ZERO { weights } else { retained }
|
||||
fn normalized_triplanar_weights(normal: Vec3, sharpness: f32) -> Vec3 {
|
||||
let normal = normal.abs();
|
||||
let strongest = normal.max_element();
|
||||
if strongest == 0.0 || !normal.is_finite() {
|
||||
return Vec3::ZERO;
|
||||
}
|
||||
|
||||
// Keep the strongest weight at one so sharp diagonal blends cannot underflow
|
||||
let weights = sharpen(normal / strongest, sharpness);
|
||||
weights / weights.element_sum()
|
||||
}
|
||||
|
||||
fn shape(pattern: &Procedural, value: f32) -> f32 {
|
||||
@@ -400,7 +408,7 @@ fn place(point: Vec2, tiling: Vec2, rotation: f32, offset: Vec2) -> Vec2 {
|
||||
}
|
||||
|
||||
/// [`place`] with its turn's sine and cosine worked out once, for a projection that places several points
|
||||
fn placement(tiling: Vec2, rotation: f32, offset: Vec2) -> impl Fn(Vec2) -> Vec2 {
|
||||
pub(crate) fn placement(tiling: Vec2, rotation: f32, offset: Vec2) -> impl Fn(Vec2) -> Vec2 {
|
||||
let (sin, cos) = rotation.to_radians().sin_cos();
|
||||
move |point| Vec2::new(point.x * cos - point.y * sin, point.x * sin + point.y * cos) * tiling + offset
|
||||
}
|
||||
@@ -432,9 +440,6 @@ const SPHERE_PATTERN_TILES: Vec2 = Vec2::new(4.0, 2.0);
|
||||
/// How many pattern tiles a procedural lays round a cylindrical projection's axis
|
||||
const CYLINDER_PATTERN_TILES: f32 = 4.0;
|
||||
|
||||
/// Smallest sum of tri-planar blend weights, so a zero normal never divides by zero
|
||||
const MIN_WEIGHT_SUM: f32 = 1e-6;
|
||||
|
||||
/// Smallest frame side or depth (world units), so a flat frame never divides by zero
|
||||
const MIN_FRAME_EXTENT: f32 = 1e-6;
|
||||
|
||||
@@ -544,6 +549,7 @@ pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coo
|
||||
let planes = [(weights.x, Vec2::new(point.z, point.y)), (weights.y, Vec2::new(point.x, point.z)), (weights.z, Vec2::new(point.x, point.y))];
|
||||
planes.into_iter().filter(|(weight, _)| *weight > 0.0).map(|(weight, plane)| flat(place_plane(plane)) * weight).sum()
|
||||
}
|
||||
|
||||
// The coordinates are already in the placed or warped frame (see [`placed_uv`] and [`crate::warp::warp_uv`])
|
||||
Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => flat(place_frame_uv(coords.uv, uv) * pattern_scale),
|
||||
Projection::Planar { scale, axis, offset, uv, projector, .. } => {
|
||||
@@ -621,8 +627,7 @@ pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32);
|
||||
let place_plane = uv_placement(uv);
|
||||
|
||||
// Float images can exceed 1, so even a tiny plane weight can carry visible detail
|
||||
let weights = coords.nrm.abs().powf(sharpness.max(1.0));
|
||||
let weights = weights / (weights.x + weights.y + weights.z).max(MIN_WEIGHT_SUM);
|
||||
let weights = normalized_triplanar_weights(coords.nrm, *sharpness);
|
||||
[
|
||||
(place_plane(Vec2::new(point.z, -point.y)), weights.x),
|
||||
(place_plane(Vec2::new(point.x, point.z)), weights.y),
|
||||
@@ -801,6 +806,7 @@ mod tests {
|
||||
for down in [0.0, 0.1, 0.37, 1.0] {
|
||||
let uv = Vec2::new(across as f32 / 1000.0, down);
|
||||
let coords = Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z };
|
||||
|
||||
assert_eq!(image_samples(&decal, &coords)[0].0, uv, "image at {uv}");
|
||||
|
||||
let expected = shape(&pattern, raw(pattern.kind, (uv * pattern.scale).extend(0.0), pattern.seed));
|
||||
@@ -839,6 +845,7 @@ mod tests {
|
||||
};
|
||||
for rotation in [37.0, 90.0, 180.0] {
|
||||
let center = sample(rotation, [1.0; 2], [0.0; 2], FRAME_UV_CENTER);
|
||||
|
||||
assert!((center - FRAME_UV_CENTER).length() < 1e-5, "{rotation}°: the centre stays put, not swung round the top left: {center}");
|
||||
}
|
||||
let corner = sample(90.0, [1.0; 2], [0.0; 2], Vec2::ZERO);
|
||||
@@ -891,6 +898,7 @@ mod tests {
|
||||
nrm: Vec3::new(0.3, 0.9, 0.1).normalize(),
|
||||
};
|
||||
let value = procedural(&pattern, projection, &coords);
|
||||
|
||||
assert!((0.0..=1.0).contains(&value), "{kind:?} {projection:?} {value}");
|
||||
}
|
||||
}
|
||||
@@ -939,13 +947,25 @@ mod tests {
|
||||
let oblique = triplanar_weights(Vec3::ONE.normalize(), 8.0, 16.0);
|
||||
assert!((oblique - Vec3::splat(1.0 / 3.0)).abs().max_element() < 1e-6, "{oblique}");
|
||||
|
||||
// Tiny weights must survive together when their sum exceeds a u16 step
|
||||
for sharpness in [47.0, 64.0] {
|
||||
let diagonal = triplanar_weights(Vec3::ONE.normalize(), sharpness, 1.0);
|
||||
assert!(diagonal.min_element() > 0.0, "sharpness {sharpness}: {diagonal}");
|
||||
assert!(diagonal.abs_diff_eq(Vec3::splat(1.0 / 3.0), 1e-6), "sharpness {sharpness}: {diagonal}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triplanar_image_hardness_preserves_diagonal_coverage() {
|
||||
let coords = Coords { uv: Vec2::ZERO, pos: Vec3::ZERO, nrm: Vec3::new(1.0, 0.95, 0.90).normalize() };
|
||||
let projection =
|
||||
|sharpness| Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() };
|
||||
|
||||
let soft = image_samples(&projection(1.0), &coords).map(|(_, weight)| weight);
|
||||
let hard = image_samples(&projection(64.0), &coords).map(|(_, weight)| weight);
|
||||
|
||||
assert!((hard.into_iter().sum::<f32>() - 1.0).abs() < 1e-6, "{hard:?}");
|
||||
assert!(hard[0] > soft[0] && hard[1] < soft[1] && hard[2] < soft[2], "{soft:?} {hard:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triplanar_image_sampling_preserves_bright_float_pixels() {
|
||||
let image = crate::ImageRes::new(2, 2, vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], false);
|
||||
|
||||
@@ -6,6 +6,7 @@ use texturecraft_core::Projection;
|
||||
use texturecraft_geom::Mesh;
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::fill_copy::FillCopy;
|
||||
use crate::organic::smoothstep;
|
||||
use crate::projector_view::ProjectorView;
|
||||
|
||||
@@ -14,8 +15,11 @@ pub struct ProjectorDepth {
|
||||
view: ProjectorView,
|
||||
/// The view point at the grid's lower corner
|
||||
origin: Vec2,
|
||||
grid_side: usize,
|
||||
/// One cell's size across and up in the view
|
||||
cell: Vec2,
|
||||
/// The mesh radius measured along the view's depth axis
|
||||
nearness_unit: f32,
|
||||
/// Per cell: the nearness of the nearest surface at the cell centre and its slope across and up (nearness -inf where no surface is)
|
||||
front: Vec<[f32; 3]>,
|
||||
}
|
||||
@@ -33,9 +37,13 @@ impl ProjectorDepth {
|
||||
Self::build(view, mesh).map(Arc::new)
|
||||
}
|
||||
|
||||
/// Rasterize every triangle of `mesh` in `view`, keeping the nearest per cell (None when no vertex lands in the view)
|
||||
/// Rasterize the mesh in this view, using a coarser grid when the cell budget requires one.
|
||||
pub fn build(view: ProjectorView, mesh: &Mesh) -> Option<ProjectorDepth> {
|
||||
let projected: Vec<Option<Vec3>> = mesh.positions.iter().map(|position| view.local(*position)).collect();
|
||||
Self::build_for_copy(view, mesh, None, GRID_SIDE, CELL_BUDGET)
|
||||
}
|
||||
|
||||
pub(crate) fn build_for_copy(view: ProjectorView, mesh: &Mesh, copy: Option<FillCopy>, mut grid_side: usize, cell_budget: usize) -> Option<Self> {
|
||||
let projected: Vec<_> = mesh.positions.iter().map(|&point| view.local(copy.map_or(point, |copy| copy.point(point)))).collect();
|
||||
let (min, max) = projected
|
||||
.iter()
|
||||
.flatten()
|
||||
@@ -44,39 +52,49 @@ impl ProjectorDepth {
|
||||
return None;
|
||||
}
|
||||
|
||||
let cell = ((max - min) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE));
|
||||
let mut depth = ProjectorDepth { view, origin: min, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] };
|
||||
let mut budget = CELL_BUDGET;
|
||||
for &[first, second, third] in mesh.indices.as_chunks::<3>().0 {
|
||||
let corner = |i: u32| projected.get(i as usize).copied().flatten();
|
||||
let (Some(a), Some(b), Some(c)) = (corner(first), corner(second), corner(third)) else { continue };
|
||||
if !depth.raster([a, b, c], &mut budget) {
|
||||
break;
|
||||
// The one-cell fallback can always afford one visit per triangle
|
||||
let cell_budget = cell_budget.max(mesh.triangle_count());
|
||||
let nearness_unit = view.unit();
|
||||
while grid_side > 0 {
|
||||
let cell = ((max - min) / grid_side as f32).max(Vec2::splat(MIN_CELL_SIZE));
|
||||
let front = vec![[f32::NEG_INFINITY, 0.0, 0.0]; grid_side * grid_side];
|
||||
let mut depth = ProjectorDepth { view, origin: min, grid_side, cell, nearness_unit, front };
|
||||
let mut remaining = cell_budget;
|
||||
let mut triangles = mesh.indices.as_chunks::<3>().0.iter().filter_map(|indices| {
|
||||
let [a, b, c] = indices.map(|index| projected.get(index as usize).copied().flatten());
|
||||
Some([a?, b?, c?])
|
||||
});
|
||||
|
||||
if triangles.all(|triangle| depth.raster(triangle, &mut remaining)) {
|
||||
return Some(depth);
|
||||
}
|
||||
|
||||
// Discard any partial grid before retrying the whole mesh
|
||||
grid_side /= 2;
|
||||
}
|
||||
|
||||
Some(depth)
|
||||
None
|
||||
}
|
||||
|
||||
/// Keep `triangle` where it is nearer than what a cell holds; false once the cell budget runs out
|
||||
fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool {
|
||||
let [a, b, c] = triangle;
|
||||
let (d1, d2) = (b - a, c - a);
|
||||
let determinant = d1.x * d2.y - d1.y * d2.x;
|
||||
let (edge_ab, edge_ac) = (b - a, c - a);
|
||||
let determinant = edge_ab.x * edge_ac.y - edge_ab.y * edge_ac.x;
|
||||
if !determinant.is_finite() || determinant.abs() < MIN_SCREEN_AREA {
|
||||
// An edge-on triangle covers no cells
|
||||
return true;
|
||||
}
|
||||
|
||||
let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / determinant, (d1.x * d2.z - d2.x * d1.z) / determinant)
|
||||
let slope = Vec2::new((edge_ab.z * edge_ac.y - edge_ac.z * edge_ab.y) / determinant, (edge_ab.x * edge_ac.z - edge_ac.x * edge_ab.z) / determinant)
|
||||
.clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE));
|
||||
|
||||
// Evaluate coverage at cell centres
|
||||
let [pa, pb, pc] = triangle.map(|corner| (corner.truncate() - self.origin) / self.cell);
|
||||
let (lo, hi) = (pa.min(pb).min(pc), pa.max(pb).max(pc));
|
||||
let first = |v: f32| (v - 0.5).ceil().clamp(0.0, SIZE as f32) as usize;
|
||||
let last = |v: f32| ((v - 0.5).floor() + 1.0).clamp(0.0, SIZE as f32) as usize;
|
||||
let (x0, x1, y0, y1) = (first(lo.x), last(hi.x), first(lo.y), last(hi.y));
|
||||
let first_cell = |position: f32| (position - 0.5).ceil().clamp(0.0, self.grid_side as f32) as usize;
|
||||
let end_cell = |position: f32| ((position - 0.5).floor() + 1.0).clamp(0.0, self.grid_side as f32) as usize;
|
||||
let (x0, x1, y0, y1) = (first_cell(lo.x), end_cell(hi.x), first_cell(lo.y), end_cell(hi.y));
|
||||
let cells = x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0));
|
||||
let Some(left) = budget.checked_sub(cells) else { return false };
|
||||
*budget = left;
|
||||
@@ -93,7 +111,7 @@ impl ProjectorDepth {
|
||||
}
|
||||
|
||||
let near = a.z + slope.dot(self.origin + cell_centre * self.cell - a.truncate());
|
||||
if let Some(cell) = self.front.get_mut(y * SIZE + x)
|
||||
if let Some(cell) = self.front.get_mut(y * self.grid_side + x)
|
||||
&& near > cell[0]
|
||||
{
|
||||
*cell = [near, slope.x, slope.y];
|
||||
@@ -113,18 +131,18 @@ impl ProjectorDepth {
|
||||
|
||||
let Some(view_point) = self.view.local(position) else { return 1.0 };
|
||||
let at = (view_point.truncate() - self.origin) / self.cell;
|
||||
if !(at.x >= 0.0 && at.y >= 0.0 && at.x < SIZE as f32 && at.y < SIZE as f32) {
|
||||
if !(at.x >= 0.0 && at.y >= 0.0 && at.x <= self.grid_side as f32 && at.y <= self.grid_side as f32) {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
let (x, y) = (at.x as usize, at.y as usize);
|
||||
let Some(&[near, across, up]) = self.front.get(y * SIZE + x).filter(|cell| cell[0].is_finite()) else { return 1.0 };
|
||||
let (x, y) = ((at.x as usize).min(self.grid_side - 1), (at.y as usize).min(self.grid_side - 1));
|
||||
let Some(&[near, across, up]) = self.front.get(y * self.grid_side + x).filter(|cell| cell[0].is_finite()) else { return 1.0 };
|
||||
|
||||
// Extend the cell's plane to avoid culling a surface against itself
|
||||
let centre = self.origin + (Vec2::new(x as f32, y as f32) + 0.5) * self.cell;
|
||||
let slope = Vec2::new(across, up);
|
||||
let behind = near + slope.dot(view_point.truncate() - centre) - view_point.z;
|
||||
let unit = self.view.unit();
|
||||
let unit = self.nearness_unit;
|
||||
|
||||
// Add slope bias for curvature across adjacent triangles
|
||||
let bias = BIAS * unit + (slope.abs() * self.cell).element_sum().min(MAX_SLOPE_BIAS * unit);
|
||||
@@ -143,13 +161,13 @@ fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 {
|
||||
}
|
||||
|
||||
/// Cells across and up the grid
|
||||
const SIZE: usize = 512;
|
||||
pub(crate) const GRID_SIDE: usize = 512;
|
||||
|
||||
/// A triangle flatter than this on screen is seen edge on
|
||||
const MIN_SCREEN_AREA: f32 = 1e-12;
|
||||
|
||||
/// Most cells all triangles together may visit before the rest are left out (hostile meshes of huge overlapping triangles)
|
||||
const CELL_BUDGET: usize = 256 * SIZE * SIZE;
|
||||
/// Cell visits available at each resolution before large overlapping triangles require a coarser grid.
|
||||
pub(crate) const CELL_BUDGET: usize = 256 * GRID_SIDE * GRID_SIDE;
|
||||
|
||||
/// Steepest surface slope kept, in nearness per view unit
|
||||
const MAX_SLOPE: f32 = 1e4;
|
||||
@@ -195,6 +213,7 @@ mod tests {
|
||||
let mesh = two_squares(0.5, -0.5);
|
||||
let bounds = mesh.bounds();
|
||||
let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), bounds).unwrap(), &mesh).unwrap();
|
||||
|
||||
assert_eq!(depth.cover(Vec3::new(0.5, 0.3, 0.5), 1.0), 1.0, "the front square");
|
||||
assert_eq!(depth.cover(Vec3::new(0.5, 0.3, -0.5), 1.0), 0.0, "the back square behind it");
|
||||
assert_eq!(depth.cover(Vec3::new(-0.5, 0.3, -0.5), 1.0), 1.0, "the back square where nothing is in front");
|
||||
@@ -203,6 +222,51 @@ mod tests {
|
||||
assert!(ProjectorView::of(&planar_z(false, 1.0), bounds).is_none(), "off, there is nothing to build");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_positive_depth_stretch_preserves_soft_culling() {
|
||||
let mesh = two_squares(0.5, -0.5);
|
||||
let bounds = mesh.bounds();
|
||||
let mut projector = Projector::depth_culled();
|
||||
projector.scale[2] = 2.0;
|
||||
projector.depth.hardness = 0.0;
|
||||
let stretched = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
|
||||
let placed = crate::axis_frame::placed_from_axis(&stretched, bounds).unwrap();
|
||||
let axis_depth = ProjectorDepth::of(&mesh, bounds, &stretched).unwrap();
|
||||
let placed_depth = ProjectorDepth::of(&mesh, bounds, &placed).unwrap();
|
||||
let just_behind = Vec3::new(0.5, 0.3, 0.44);
|
||||
|
||||
let before = axis_depth.cover(just_behind, 0.0);
|
||||
let after = placed_depth.cover(just_behind, 0.0);
|
||||
|
||||
assert!(before > 0.0 && before < 1.0 && (before - after).abs() < 1e-4, "axis {before}, placed {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_upper_right_grid_boundary_can_be_depth_culled() {
|
||||
let mesh = two_squares(0.5, -0.5);
|
||||
let depth = ProjectorDepth::of(&mesh, mesh.bounds(), &planar_z(true, 1.0)).unwrap();
|
||||
|
||||
assert_eq!(depth.cover(Vec3::new(1.0, 1.0, -0.5), 1.0), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_budget_fallback_accounts_for_the_last_triangle() {
|
||||
let mut mesh = two_squares(0.5, -0.5);
|
||||
let rear_triangles = [4, 5, 6, 4, 6, 7];
|
||||
let front_triangles = [0, 1, 2, 0, 2, 3];
|
||||
mesh.indices = rear_triangles.repeat(CELL_BUDGET / (GRID_SIDE * GRID_SIDE));
|
||||
mesh.indices.extend(front_triangles);
|
||||
let projection = planar_z(true, 1.0);
|
||||
let behind = Vec3::new(0.5, 0.3, -0.5);
|
||||
|
||||
let front_last = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap();
|
||||
mesh.indices.rotate_right(front_triangles.len());
|
||||
let front_first = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap();
|
||||
|
||||
assert_eq!(front_last.cover(behind, 1.0), 0.0);
|
||||
assert_eq!(front_last.cover(behind, 1.0), front_first.cover(behind, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nan_hardness_culls_nothing() {
|
||||
let mesh = two_squares(0.5, -0.5);
|
||||
@@ -216,6 +280,7 @@ mod tests {
|
||||
#[test]
|
||||
fn interleaved_meshes_keep_their_own_projector_depth() {
|
||||
let mut mesh = two_squares(0.5, -0.5);
|
||||
|
||||
// Add enough unused vertices for the old sample to skip the changed edge
|
||||
mesh.positions.resize(200, Vec3::ZERO);
|
||||
let mut edited = mesh.clone();
|
||||
@@ -240,6 +305,7 @@ mod tests {
|
||||
let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap();
|
||||
for i in 0..1000 {
|
||||
let (x, y) = ((i as f32 * 0.618).fract() * 1.98 - 0.99, (i as f32 * 0.377).fract() * 1.98 - 0.99);
|
||||
|
||||
assert_eq!(depth.cover(Vec3::new(x, y, x * 0.9), 1.0), 1.0, "{x} {y}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
use texturecraft_core::Projection;
|
||||
use texturecraft_geom::{Mesh, glam::Vec3};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::{projector_depth::ProjectorDepth, projector_view::ProjectorView};
|
||||
use crate::fill_depth::{FillDepth, FillDepthKey};
|
||||
|
||||
type ViewDepth = (ProjectorView, Option<Arc<ProjectorDepth>>);
|
||||
pub(crate) type ViewDepth = (FillDepthKey, Option<Arc<FillDepth>>);
|
||||
|
||||
// Each map holds about 3 MiB
|
||||
// Each fill's grids share about 3 MiB
|
||||
const MAX_CACHED_VIEWS: usize = 8;
|
||||
|
||||
/// Reuse projector depth maps for one mesh across tile batches.
|
||||
@@ -18,30 +17,25 @@ pub struct ProjectorDepthCache {
|
||||
}
|
||||
|
||||
impl ProjectorDepthCache {
|
||||
pub(crate) fn bind(&mut self, mesh: &Arc<Mesh>) -> bool {
|
||||
pub(crate) fn bind(&mut self, mesh: &Arc<Mesh>) {
|
||||
if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) {
|
||||
self.maps.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();
|
||||
self.mesh = Arc::downgrade(mesh);
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self, mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option<Arc<ProjectorDepth>> {
|
||||
let view = ProjectorView::of(projection, bounds)?;
|
||||
|
||||
pub(crate) fn get(&self, mesh: &Mesh, key: FillDepthKey) -> Option<Arc<FillDepth>> {
|
||||
// Rasterization is serial so tile workers can wait for a single build
|
||||
let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if let Some(index) = maps.iter().position(|(cached_view, _)| *cached_view == view) {
|
||||
if let Some(index) = maps.iter().position(|(cached_key, _)| *cached_key == key) {
|
||||
let entry = maps.remove(index);
|
||||
let depth = entry.1.clone();
|
||||
maps.insert(0, entry);
|
||||
return depth;
|
||||
}
|
||||
|
||||
let depth = ProjectorDepth::build(view, mesh).map(Arc::new);
|
||||
maps.insert(0, (view, depth.clone()));
|
||||
let depth = FillDepth::build(mesh, key).map(Arc::new);
|
||||
maps.insert(0, (key, depth.clone()));
|
||||
maps.truncate(MAX_CACHED_VIEWS);
|
||||
|
||||
depth
|
||||
@@ -51,7 +45,8 @@ impl ProjectorDepthCache {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::{Projector, UvTransform};
|
||||
use crate::projector_view::ProjectorView;
|
||||
use texturecraft_core::{Projection, Projector, UvTransform};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
#[test]
|
||||
@@ -68,8 +63,10 @@ mod tests {
|
||||
let mut projector = Projector::depth_culled();
|
||||
projector.rotation[2] = angle_degrees as f32;
|
||||
let projection = Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
|
||||
let map = cache.get(&mesh, bounds, &projection).unwrap();
|
||||
let reused = cache.get(&mesh, bounds, &projection).unwrap();
|
||||
let view = ProjectorView::of(&projection, bounds).unwrap();
|
||||
let map = cache.get(&mesh, (view, None)).unwrap();
|
||||
let reused = cache.get(&mesh, (view, None)).unwrap();
|
||||
|
||||
assert!(Arc::ptr_eq(&map, &reused));
|
||||
maps.push(Arc::downgrade(&map));
|
||||
if angle_degrees == 0 {
|
||||
@@ -89,7 +86,8 @@ mod tests {
|
||||
|
||||
let projection =
|
||||
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None };
|
||||
let last_map = Arc::downgrade(&cache.get(&mesh, mesh.bounds(), &projection).unwrap());
|
||||
let view = ProjectorView::of(&projection, mesh.bounds()).unwrap();
|
||||
let last_map = Arc::downgrade(&cache.get(&mesh, (view, None)).unwrap());
|
||||
|
||||
drop(cache);
|
||||
assert!(last_map.upgrade().is_none());
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use texturecraft_core::{Decal, Projection, Projector};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::pattern::{Coords, frame_local, mesh_frame, projector_local};
|
||||
use crate::pattern::{Coords, frame_local, mesh_frame, nonzero_stretch, projector_local};
|
||||
|
||||
/// The view of a depth-culled planar or warp projection: points in it run across, up and towards the projector
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -50,8 +50,8 @@ impl ProjectorView {
|
||||
/// The mesh radius in the view's nearness units
|
||||
pub fn unit(&self) -> f32 {
|
||||
match self {
|
||||
ProjectorView::Axis { .. } => 1.0,
|
||||
ProjectorView::Frame { radius, .. } => *radius,
|
||||
ProjectorView::Axis { axis, projector, .. } => 1.0 / nonzero_stretch(projector.scale[usize::from((*axis).min(2))]).abs(),
|
||||
ProjectorView::Frame { projector, radius, .. } => radius / nonzero_stretch(projector.scale[2]).abs(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+119
-31
@@ -5,7 +5,7 @@ use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use texturecraft_core::{Channel, ChannelKind, Filtering, LayerId, Sampling};
|
||||
use texturecraft_texel::{TileImage, from_u16, from_u16_signed};
|
||||
use texturecraft_texel::{TileImage, from_u16, from_u16_signed, srgb_to_linear};
|
||||
|
||||
use crate::mip_level::MipLevel;
|
||||
|
||||
@@ -71,6 +71,8 @@ pub struct ImageRes {
|
||||
pub srgb: bool,
|
||||
/// Halved copies of the image, built on first use by [`Filtering::BilinearHq`]
|
||||
pub mips: OnceLock<Vec<MipLevel>>,
|
||||
/// Mip levels for sRGB color reads. RGB is linear, alpha is unchanged.
|
||||
linear_mips: OnceLock<Vec<MipLevel>>,
|
||||
}
|
||||
|
||||
/// Image resources by name.
|
||||
@@ -110,9 +112,24 @@ fn bilinear(rgba: &[[f32; 4]], width: u32, height: u32, u: f32, v: f32, repeat:
|
||||
blended
|
||||
}
|
||||
|
||||
fn linearize_rgb([red, green, blue, alpha]: [f32; 4]) -> [f32; 4] {
|
||||
[srgb_to_linear(red), srgb_to_linear(green), srgb_to_linear(blue), alpha]
|
||||
}
|
||||
|
||||
pub(crate) fn uses_mips(footprint: f32) -> bool {
|
||||
footprint.is_finite() && footprint > 1.0
|
||||
}
|
||||
|
||||
impl ImageRes {
|
||||
pub fn new(width: u32, height: u32, rgba: Vec<[f32; 4]>, srgb: bool) -> ImageRes {
|
||||
ImageRes { width, height, rgba, srgb, mips: OnceLock::new() }
|
||||
ImageRes { width, height, rgba, srgb, mips: OnceLock::new(), linear_mips: OnceLock::new() }
|
||||
}
|
||||
|
||||
/// Bytes held by the image's texel buffers, used to budget other image work.
|
||||
pub fn retained_texel_bytes(&self) -> u64 {
|
||||
let mip_levels = self.mips.get().into_iter().flatten().chain(self.linear_mips.get().into_iter().flatten());
|
||||
let capacity = mip_levels.fold(self.rgba.capacity() as u64, |texels, level| texels.saturating_add(level.rgba.capacity() as u64));
|
||||
capacity.saturating_mul(std::mem::size_of::<[f32; 4]>() as u64)
|
||||
}
|
||||
|
||||
fn texel(&self, x: i64, y: i64, repeat: (bool, bool)) -> [f32; 4] {
|
||||
@@ -142,52 +159,80 @@ impl ImageRes {
|
||||
self.texel((u * self.width as f32).floor() as i64, (v * self.height as f32).floor() as i64, repeat)
|
||||
}
|
||||
|
||||
/// The halved levels, built the first time they are asked for
|
||||
fn build_mips(&self, halve_first: impl FnOnce(&[[f32; 4]], u32, u32) -> MipLevel) -> Vec<MipLevel> {
|
||||
if self.width <= 1 && self.height <= 1 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Decode while reducing the first level to avoid a full-size linear image
|
||||
let mut level = halve_first(&self.rgba, self.width, self.height);
|
||||
let mut levels = Vec::new();
|
||||
while (level.width > 1 || level.height > 1) && levels.len() + 1 < MAX_MIP_LEVELS {
|
||||
let next = MipLevel::halve(&level.rgba, level.width, level.height);
|
||||
levels.push(level);
|
||||
level = next;
|
||||
}
|
||||
|
||||
levels.push(level);
|
||||
levels
|
||||
}
|
||||
|
||||
fn mips(&self) -> &[MipLevel] {
|
||||
self.mips.get_or_init(|| {
|
||||
let mut levels: Vec<MipLevel> = Vec::new();
|
||||
let (mut w, mut h) = (self.width, self.height);
|
||||
while (w > 1 || h > 1) && levels.len() < MAX_MIP_LEVELS {
|
||||
let next = match levels.last() {
|
||||
Some(level) => MipLevel::halve(&level.rgba, level.width, level.height),
|
||||
None => MipLevel::halve(&self.rgba, w, h),
|
||||
};
|
||||
(w, h) = (next.width, next.height);
|
||||
levels.push(next);
|
||||
}
|
||||
levels
|
||||
self.mips.get_or_init(|| self.build_mips(MipLevel::halve))
|
||||
}
|
||||
|
||||
/// Sample an sRGB image as linear color, preserving the full-resolution filter.
|
||||
pub(crate) fn sample_srgb_color(&self, u: f32, v: f32, sampling: Sampling, footprint: f32) -> [f32; 4] {
|
||||
self.sample_filtered_with(u, v, sampling, footprint, linearize_rgb, || {
|
||||
self.linear_mips.get_or_init(|| self.build_mips(|rgba, width, height| MipLevel::halve_with(rgba, width, height, Some(linearize_rgb))))
|
||||
})
|
||||
}
|
||||
|
||||
/// Read coverage from either mip chain since the RGB transfer leaves alpha unchanged.
|
||||
pub(crate) fn sample_alpha(&self, u: f32, v: f32, sampling: Sampling, footprint: f32) -> f32 {
|
||||
self.sample_filtered_with(u, v, sampling, footprint, std::convert::identity, || self.linear_mips.get().map_or_else(|| self.mips(), Vec::as_slice))[3]
|
||||
}
|
||||
|
||||
/// Sample at (`u`, `v`) with `sampling`; `footprint` = image texels per surface texel (1 or less = not shrunk)
|
||||
pub fn sample_filtered(&self, u: f32, v: f32, sampling: Sampling, footprint: f32) -> [f32; 4] {
|
||||
self.sample_filtered_with(u, v, sampling, footprint, std::convert::identity, || self.mips())
|
||||
}
|
||||
|
||||
fn sample_filtered_with<'a>(
|
||||
&'a self,
|
||||
u: f32,
|
||||
v: f32,
|
||||
sampling: Sampling,
|
||||
footprint: f32,
|
||||
decode_full: impl Fn([f32; 4]) -> [f32; 4],
|
||||
mips: impl FnOnce() -> &'a [MipLevel],
|
||||
) -> [f32; 4] {
|
||||
if !u.is_finite() || !v.is_finite() {
|
||||
return [0.0; 4];
|
||||
}
|
||||
|
||||
let repeat = sampling.wrap.repeats();
|
||||
let full = |u: f32, v: f32| bilinear(&self.rgba, self.width, self.height, u, v, repeat);
|
||||
let full = || decode_full(bilinear(&self.rgba, self.width, self.height, u, v, repeat));
|
||||
match sampling.filtering {
|
||||
Filtering::Nearest => self.nearest(u, v, repeat),
|
||||
Filtering::BilinearSharp => full(u, v),
|
||||
Filtering::Nearest => decode_full(self.nearest(u, v, repeat)),
|
||||
Filtering::BilinearSharp => full(),
|
||||
Filtering::BilinearHq => {
|
||||
// Not shrunk: the full image alone, without building mips it does not read
|
||||
if !(footprint.is_finite() && footprint > 1.0) {
|
||||
return full(u, v);
|
||||
if !uses_mips(footprint) {
|
||||
return full();
|
||||
}
|
||||
|
||||
let lod = footprint.log2();
|
||||
let levels = mips();
|
||||
let level_of_detail = footprint.log2().min(levels.len() as f32);
|
||||
let finer_level = level_of_detail.floor() as usize;
|
||||
let toward_coarser = level_of_detail - finer_level as f32;
|
||||
|
||||
// Level 0 is the full image, level n the nth mip (the smallest past the last)
|
||||
let mips = self.mips();
|
||||
let level = |index: usize| match index.checked_sub(1) {
|
||||
None => full(u, v),
|
||||
Some(mip_index) => {
|
||||
mips.get(mip_index).or(mips.last()).map_or_else(|| full(u, v), |mip| bilinear(&mip.rgba, mip.width, mip.height, u, v, repeat))
|
||||
}
|
||||
// Level zero uses the file image; the first stored level is half-sized
|
||||
let level = |index: usize| {
|
||||
index
|
||||
.checked_sub(1)
|
||||
.and_then(|mip_index| levels.get(mip_index))
|
||||
.map_or_else(full, |mip| bilinear(&mip.rgba, mip.width, mip.height, u, v, repeat))
|
||||
};
|
||||
let finer_level = lod.floor() as usize;
|
||||
let toward_coarser = lod - lod.floor();
|
||||
let finer = level(finer_level);
|
||||
if toward_coarser <= 0.0 {
|
||||
return finer;
|
||||
@@ -247,6 +292,18 @@ mod tests {
|
||||
assert_eq!(single, [3.0; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_quality_mips_keep_odd_trailing_rows_and_columns() {
|
||||
let mut pixels = vec![[0.0; 4]; 9];
|
||||
pixels[8] = [1.0, 0.0, 0.0, 1.0];
|
||||
let image = ImageRes::new(3, 3, pixels, false);
|
||||
|
||||
let [red, _, _, alpha] = image.sample_filtered(0.5, 0.5, sampling(Filtering::BilinearHq, UvWrap::None), 8.0);
|
||||
|
||||
assert!((red - 1.0 / 9.0).abs() < 1e-6);
|
||||
assert_eq!(red, alpha);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_quality_bilinear_reads_the_mip_the_footprint_asks_for() {
|
||||
let image = ramp();
|
||||
@@ -274,4 +331,35 @@ mod tests {
|
||||
assert_eq!(full, [1.0; 4]);
|
||||
assert!(image.mips.get().is_none(), "a footprint of 1 reads only the full image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn srgb_mip_transition_blends_linear_color_and_keeps_coverage() {
|
||||
let image = ImageRes::new(2, 1, vec![[0.0; 4], [1.0; 4]], true);
|
||||
let hq = sampling(Filtering::BilinearHq, UvWrap::None);
|
||||
let half_level_footprint = 2.0_f32.sqrt();
|
||||
|
||||
let full = image.sample_srgb_color(0.25, 0.5, hq, 1.0);
|
||||
let midpoint = image.sample_srgb_color(0.25, 0.5, hq, half_level_footprint);
|
||||
let coverage = image.sample_alpha(0.25, 0.5, hq, half_level_footprint);
|
||||
|
||||
assert_eq!(full, [0.0; 4], "full resolution reads the center of the black texel");
|
||||
assert!((midpoint[0] - 0.25).abs() < 1e-6, "mix linear black and the half-bright mip: {midpoint:?}");
|
||||
assert_eq!(midpoint[3], coverage);
|
||||
assert!(image.mips.get().is_none(), "coverage can use the same mip chain as color");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mixed_use_image_reports_the_texels_held_by_both_mip_chains() {
|
||||
let image = ImageRes::new(4, 4, vec![[0.5; 4]; 16], true);
|
||||
let hq = sampling(Filtering::BilinearHq, UvWrap::None);
|
||||
let base = image.retained_texel_bytes();
|
||||
|
||||
image.sample_srgb_color(0.5, 0.5, hq, 4.0);
|
||||
let color_only = image.retained_texel_bytes();
|
||||
image.sample_filtered(0.5, 0.5, hq, 4.0);
|
||||
let mixed = image.retained_texel_bytes();
|
||||
|
||||
assert!(color_only > base);
|
||||
assert_eq!(mixed - color_only, color_only - base);
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,7 @@ mod tests {
|
||||
#[test]
|
||||
fn uv_tile_length_is_the_uv_density_over_the_tiling() {
|
||||
let uv = Projection::Uv { scale: [2.0, 4.0], rotation: 0.0, offset: [0.0; 2] };
|
||||
|
||||
assert_eq!(tile_length(&uv, SIZE), Some([1.5, 0.75]));
|
||||
}
|
||||
|
||||
@@ -102,6 +103,7 @@ mod tests {
|
||||
] {
|
||||
let length = tile_length(&projection, SIZE).unwrap();
|
||||
let tiling = tiling_for_length(&projection, SIZE, length).unwrap();
|
||||
|
||||
assert!((tiling[0] - 3.0).abs() < 1e-5 && (tiling[1] - 1.5).abs() < 1e-5, "{projection:?}: {tiling:?}");
|
||||
}
|
||||
}
|
||||
@@ -141,6 +143,7 @@ mod tests {
|
||||
fn a_cylinder_of_no_angle_still_has_a_length() {
|
||||
let flat = Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default(), angle: 0.0 };
|
||||
let length = tile_length(&flat, SIZE).unwrap();
|
||||
|
||||
assert!(length[0] > 0.0, "{length:?}");
|
||||
assert!(tiling_for_length(&flat, SIZE, length).unwrap()[0] > 0.0, "a written-back tiling is never 0");
|
||||
}
|
||||
|
||||
+44
-23
@@ -2,39 +2,45 @@
|
||||
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
/// Texture coordinates (v down) of the point `p` (across and up in frame sizes) inside the quad `corners` makes (top left, top right, bottom right, bottom left); past the quad they run on, so the image can repeat. None where no texture coordinates land
|
||||
pub fn warp_uv(corners: &[[f32; 2]; 4], p: Vec2) -> Option<Vec2> {
|
||||
let [a, b, c, d] = corners.map(Vec2::from);
|
||||
let (e, f, g, h) = (b - a, d - a, a - b + c - d, p - a);
|
||||
let k2 = g.perp_dot(f);
|
||||
let k1 = e.perp_dot(f) + h.perp_dot(g);
|
||||
let k0 = h.perp_dot(e);
|
||||
let uv = if k2.abs() < PARALLEL {
|
||||
// Opposite edges parallel: the quad's equation is linear in v
|
||||
let v = -k0 / k1;
|
||||
Vec2::new(across(e, f, g, h, v)?, v)
|
||||
/// Texture coordinates (v down) of a point in frame units.
|
||||
/// Corners run from top left clockwise. Coordinates extend past the quad for repeating images.
|
||||
pub fn warp_uv(corners: &[[f32; 2]; 4], point: Vec2) -> Option<Vec2> {
|
||||
let [top_left, top_right, bottom_right, bottom_left] = corners.map(Vec2::from);
|
||||
let top_edge = top_right - top_left;
|
||||
let left_edge = bottom_left - top_left;
|
||||
let twist = top_left - top_right + bottom_right - bottom_left;
|
||||
let relative_point = point - top_left;
|
||||
|
||||
let base_area = top_edge.perp_dot(left_edge);
|
||||
let quadratic = twist.perp_dot(left_edge);
|
||||
let linear = base_area + relative_point.perp_dot(twist);
|
||||
let constant = relative_point.perp_dot(top_edge);
|
||||
let at = |v| across(top_edge, left_edge, twist, relative_point, v).map(|u| Vec2::new(u, v));
|
||||
|
||||
let uv = if quadratic.abs() <= RELATIVE_PARALLEL * base_area.abs() {
|
||||
// Parallel sides make the quad's equation linear in v
|
||||
at(-constant / linear)?
|
||||
} else {
|
||||
let discriminant = k1 * k1 - 4.0 * k0 * k2;
|
||||
let discriminant = linear * linear - 4.0 * constant * quadratic;
|
||||
if discriminant < 0.0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let root = discriminant.sqrt();
|
||||
let near = |v: f32| across(e, f, g, h, v).map(|u| Vec2::new(u, v));
|
||||
// Avoid subtracting near-equal values when the quad is nearly a parallelogram
|
||||
let root_term = -0.5 * (linear + discriminant.sqrt().copysign(linear));
|
||||
|
||||
// Two solutions, neither found by subtracting near-equal values (which loses the answer when the quad is nearly a parallelogram): keep the one nearer the quad
|
||||
let q = -0.5 * (k1 + root.copysign(k1));
|
||||
// q is 0 only for a double root at 0, which q / k2 still finds (k0 / q is then not finite, so no candidate)
|
||||
let candidates = [near(q / k2), near(k0 / q)];
|
||||
// At a double root of zero only the first candidate is finite
|
||||
let candidates = [at(root_term / quadratic), at(constant / root_term)];
|
||||
candidates.into_iter().flatten().min_by(|x, y| outside(*x).total_cmp(&outside(*y)))?
|
||||
};
|
||||
|
||||
uv.is_finite().then_some(uv)
|
||||
}
|
||||
|
||||
/// How far across (u) a point lies at height `v`, solved on whichever axis the quad's edge spans most
|
||||
fn across(e: Vec2, f: Vec2, g: Vec2, h: Vec2, v: f32) -> Option<f32> {
|
||||
let span = e + g * v;
|
||||
let u = if span.x.abs() >= span.y.abs() { (h.x - f.x * v) / span.x } else { (h.y - f.y * v) / span.y };
|
||||
fn across(top_edge: Vec2, left_edge: Vec2, twist: Vec2, relative_point: Vec2, v: f32) -> Option<f32> {
|
||||
let span = top_edge + twist * v;
|
||||
let u = if span.x.abs() >= span.y.abs() { (relative_point.x - left_edge.x * v) / span.x } else { (relative_point.y - left_edge.y * v) / span.y };
|
||||
u.is_finite().then_some(u)
|
||||
}
|
||||
|
||||
@@ -43,8 +49,8 @@ fn outside(uv: Vec2) -> f32 {
|
||||
(uv - uv.clamp(Vec2::ZERO, Vec2::ONE)).length_squared()
|
||||
}
|
||||
|
||||
/// Below this, a quad's opposite edges count as parallel (frame sizes squared)
|
||||
const PARALLEL: f32 = 1e-6;
|
||||
/// Relative area below which the quadratic contribution counts as parallel
|
||||
const RELATIVE_PARALLEL: f32 = 1e-6;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -81,15 +87,30 @@ mod tests {
|
||||
for j in 0..=10 {
|
||||
let uv = Vec2::new(i as f32 / 10.0, j as f32 / 10.0);
|
||||
let found = warp_uv(&quad, bilinear(&quad, uv)).unwrap_or(Vec2::NAN);
|
||||
|
||||
assert!((found - uv).length() < 1e-4, "{quad:?} {uv}: {found}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrinking_a_distorted_quad_preserves_its_mapping() {
|
||||
let corners = [[0.0, 0.0], [1.0, 0.0], [2.0, 1.0], [0.0, 1.0]];
|
||||
let uv = Vec2::splat(0.5);
|
||||
let point = bilinear(&corners, uv);
|
||||
let scale = 0.0001;
|
||||
let smaller = corners.map(|corner| corner.map(|coordinate| coordinate * scale));
|
||||
|
||||
let found = warp_uv(&smaller, point * scale).unwrap();
|
||||
|
||||
assert!(found.distance(uv) < 1e-5, "the scaled quad still maps to the middle: {found}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_collapsed_quad_lands_nowhere_instead_of_failing() {
|
||||
let point = [[0.0, 0.0]; 4];
|
||||
|
||||
assert_eq!(warp_uv(&point, Vec2::new(0.3, 0.2)), None);
|
||||
assert_eq!(warp_uv(&[[f32::NAN; 2]; 4], Vec2::ZERO), None);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,11 @@ use texturecraft_core::{
|
||||
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
|
||||
use texturecraft_texel::{TILE, TileImage, to_u16};
|
||||
|
||||
#[path = "cache_and_instances/blur_on.rs"]
|
||||
mod blur_on;
|
||||
|
||||
use blur_on::BlurOn;
|
||||
|
||||
const RES: u32 = 256;
|
||||
|
||||
struct Fixture {
|
||||
@@ -665,6 +670,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
|
||||
// Keep fields for the remaining tiles
|
||||
cache.ahead = rest.to_vec();
|
||||
let mut out = run(&fixture, 0, first, Some(&mut cache));
|
||||
|
||||
assert!(cache.holds_fields());
|
||||
|
||||
// Changing the hot mask must invalidate the retained fields
|
||||
@@ -976,13 +982,6 @@ fn id_map_image_changes_invalidate_stack_key() {
|
||||
assert!(stack_key(&fixture, &images) != original, "replacing the id image must invalidate the cache");
|
||||
}
|
||||
|
||||
/// Where a blur lies on the layer inside the instanced folder
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum BlurOn {
|
||||
Content,
|
||||
Mask,
|
||||
}
|
||||
|
||||
/// A folder of set `ts` holding a Clouds fill whose content or mask is blurred by 8; returns the folder and the fill
|
||||
fn folder_of_blurred_clouds(f: &mut Fixture, ts: usize, folder: Option<LayerId>, blur_on: BlurOn) -> (LayerId, LayerId) {
|
||||
let held = put(f, ts, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None);
|
||||
@@ -1052,3 +1051,150 @@ fn a_hot_layer_with_a_neighbourhood_filter_in_an_instanced_folder_under_an_offse
|
||||
assert!(!cache.is_empty(), "{blur_on:?} blur: the hot layer is cached through its instance");
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_after_changing_mesh(owned: bool) {
|
||||
use std::sync::Arc;
|
||||
use texturecraft_compose::{ProjectorDepthCache, composite_tiles_with_projectors};
|
||||
|
||||
let mut fixture = fixture();
|
||||
let lower = add(&mut fixture, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]), None);
|
||||
fixture.project.layer_mut(lower).unwrap().geometry_mask = Some(vec!["Lid".into()]);
|
||||
let hot = add(&mut fixture, 0, LayerKind::Paint, None);
|
||||
let mut named = fixture.mesh.clone();
|
||||
named.submeshes[0].name = "Lid".into();
|
||||
let first = Arc::new(named);
|
||||
let second = Arc::new(fixture.mesh.clone());
|
||||
let images = Default::default();
|
||||
let baked = Default::default();
|
||||
let mut projectors = ProjectorDepthCache::default();
|
||||
let mut cache = BelowCache::default();
|
||||
cache.set_hot(Some(hot));
|
||||
let mut render = |mesh: &Arc<Mesh>, cache: Option<&mut BelowCache>| {
|
||||
let mut input = inputs(&fixture, 0, &images, &baked);
|
||||
input.mesh = mesh;
|
||||
let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
|
||||
if owned {
|
||||
composite_tiles_with_projectors(&input, mesh, &mut projectors, &mut output, &[(1, 1)], cache);
|
||||
} else {
|
||||
composite_tiles_cached(&input, &mut output, &[(1, 1)], cache);
|
||||
}
|
||||
output
|
||||
};
|
||||
|
||||
let before = render(&first, Some(&mut cache));
|
||||
assert!(!cache.is_empty());
|
||||
let expected = render(&second, None);
|
||||
let actual = render(&second, Some(&mut cache));
|
||||
|
||||
assert!(before != expected, "the lower fill applies only to the named part");
|
||||
assert!(actual == expected, "the previous mesh's cached fill was reused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_borrowed_mesh_change_invalidates_cached_fills() {
|
||||
cache_after_changing_mesh(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_projector_rebind_without_below_cache_invalidates_cached_fills() {
|
||||
cache_after_changing_mesh(true);
|
||||
}
|
||||
|
||||
fn roughness_compare(fixture: &mut Fixture, source: CompareSource) -> Effect {
|
||||
effect(
|
||||
fixture,
|
||||
EffectKind::Compare {
|
||||
op: CompareOp::GreaterThan,
|
||||
value: 0.7,
|
||||
tolerance: 0.0,
|
||||
left: source,
|
||||
right: CompareSource::Constant,
|
||||
channel: Channel::Roughness,
|
||||
hardness: 1.0,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_uses_the_stack_below_each_draw_of_an_instanced_folder() {
|
||||
let mut fixture = fixture();
|
||||
let base = |roughness| fill(&[(Channel::BaseColor, Source::Uniform([0.0, 0.0, 1.0])), (Channel::Roughness, Source::Uniform([roughness; 3]))]);
|
||||
add(&mut fixture, 0, base(0.2), None);
|
||||
let folder = add(&mut fixture, 0, LayerKind::folder(), None);
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
|
||||
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 32.0 })));
|
||||
let red = fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]);
|
||||
put(&mut fixture, 0, Some(folder), red, Some(mask));
|
||||
add(&mut fixture, 0, base(0.9), None);
|
||||
add(&mut fixture, 0, LayerKind::Instance { source: folder }, None);
|
||||
|
||||
let color = run(&fixture, 0, &[(1, 1)], None).value(Channel::BaseColor, 96, 96);
|
||||
|
||||
assert!(color[0] > color[2], "the second draw should read the rougher surface: {color:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_reads_a_retained_channel_after_it_is_removed_from_the_outputs() {
|
||||
let mut fixture = fixture();
|
||||
let roughness = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3]))]);
|
||||
add(&mut fixture, 0, roughness, None);
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
|
||||
let red = fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]);
|
||||
add(&mut fixture, 0, red, Some(mask));
|
||||
let before = run(&fixture, 0, &[(1, 1)], None).value(Channel::BaseColor, 96, 96);
|
||||
|
||||
fixture.project.texture_sets[0].channels.retain(|(channel, _)| *channel != Channel::Roughness);
|
||||
let after = run(&fixture, 0, &[(1, 1)], None);
|
||||
|
||||
assert!(before[0] > before[1]);
|
||||
assert_eq!(after.value(Channel::BaseColor, 96, 96), before);
|
||||
assert!(!after.channels.contains_key(&Channel::Roughness));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_compare_mask_reads_filtered_content_through_the_full_blur_radius() {
|
||||
use texturecraft_compose::{mask_texels, mask_values};
|
||||
|
||||
const SIZE: u32 = 512;
|
||||
let mut fixture = fixture();
|
||||
fixture.mesh = primitives::plane(2.0, 2);
|
||||
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, SIZE, SIZE);
|
||||
fixture.project.texture_sets[0] = TextureSet::new("Plane", 0, SIZE);
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(roughness_compare(&mut fixture, CompareSource::ThisLayer));
|
||||
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 256.0 })));
|
||||
let roughness = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3]))]);
|
||||
let layer = add(&mut fixture, 0, roughness, Some(mask));
|
||||
let edge = effect(&mut fixture, EffectKind::Filter(Filter::EdgeDetect { width: 8.0 }));
|
||||
fixture.project.layer_mut(layer).unwrap().content_effects.push(edge);
|
||||
let (images, baked) = (Default::default(), Default::default());
|
||||
let inputs = inputs(&fixture, 0, &images, &baked);
|
||||
let center = SIZE / 2;
|
||||
|
||||
let full = mask_texels(&inputs, layer).unwrap();
|
||||
let tile = mask_values(&inputs, layer, &[(center / TILE, center / TILE)]).unwrap();
|
||||
|
||||
assert_eq!(tile.get(center, center)[0], to_u16(full[(center * SIZE + center) as usize]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_thumbnail_reads_compare_inputs_from_its_backdrop() {
|
||||
use texturecraft_compose::{ThumbTarget, thumb};
|
||||
|
||||
let mut fixture = fixture();
|
||||
let backdrop = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3])), (Channel::BaseColor, Source::Uniform([0.0, 0.0, 1.0]))]);
|
||||
add(&mut fixture, 0, backdrop, None);
|
||||
let folder = add(&mut fixture, 0, LayerKind::folder(), None);
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
|
||||
put(&mut fixture, 0, Some(folder), fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]), Some(mask));
|
||||
let (images, baked) = (Default::default(), Default::default());
|
||||
let inputs = inputs(&fixture, 0, &images, &baked);
|
||||
|
||||
let thumbnail = thumb::render(&inputs, ThumbTarget::Content { layer: folder, channel: Channel::BaseColor }).unwrap();
|
||||
let center = 4 * (96 * RES + 96) as usize;
|
||||
|
||||
assert!(thumbnail.rgba[center] > thumbnail.rgba[center + 2], "visible red child");
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/// Which stack contains a blur in the instanced-folder fixture.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) enum BlurOn {
|
||||
Content,
|
||||
Mask,
|
||||
}
|
||||
+13
-12
@@ -108,13 +108,14 @@ impl Default for HeightMask {
|
||||
}
|
||||
|
||||
impl HeightMask {
|
||||
/// The mask `m` combined with height `h` (see [`HeightMask`]).
|
||||
pub fn apply(&self, m: f32, h: f32) -> f32 {
|
||||
if !self.enabled || !h.is_finite() {
|
||||
return m;
|
||||
/// Combines a mask value with height (see [`HeightMask`]).
|
||||
pub fn apply(&self, mask: f32, height: f32) -> f32 {
|
||||
if !self.enabled || !height.is_finite() {
|
||||
return mask;
|
||||
}
|
||||
|
||||
(m + self.contrast * 4.0 * m * (1.0 - m) * (h + self.offset)).clamp(0.0, 1.0)
|
||||
// The height response peaks at the mask midpoint and vanishes at both ends
|
||||
(mask + self.contrast * 4.0 * mask * (1.0 - mask) * (height + self.offset)).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1912,13 +1913,13 @@ mod tests {
|
||||
fn point_filters_map_values_and_skip_neighbourhood_filters() {
|
||||
let c = ChannelKind::Color;
|
||||
let close = |a: [f32; 3], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 1e-4);
|
||||
let cl = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 };
|
||||
assert!(close(cl.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0]));
|
||||
let contrast = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 };
|
||||
assert!(close(contrast.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0]));
|
||||
assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3]));
|
||||
|
||||
let gm = Filter::GradientMap { colors: vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] };
|
||||
assert!(close(gm.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0]));
|
||||
assert!(close(gm.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0]));
|
||||
let gradient_map = Filter::GradientMap { colors: vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] };
|
||||
assert!(close(gradient_map.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0]));
|
||||
assert!(close(gradient_map.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0]));
|
||||
assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing");
|
||||
|
||||
assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0]));
|
||||
@@ -1941,8 +1942,8 @@ mod tests {
|
||||
assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white");
|
||||
assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75]));
|
||||
|
||||
let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] };
|
||||
assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99);
|
||||
let color_balance = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] };
|
||||
assert!(color_balance.point(c, [0.05; 3]).unwrap()[0] > 0.2 && color_balance.point(c, [0.95; 3]).unwrap()[2] > 0.99);
|
||||
assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3]));
|
||||
assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0]));
|
||||
|
||||
|
||||
@@ -916,6 +916,7 @@ mod tests {
|
||||
assert_eq!(p.sets_drawing(inst), vec![1]);
|
||||
|
||||
p.validate().unwrap();
|
||||
|
||||
// A folder holding an instance of itself draws itself
|
||||
let gid = p.alloc_id();
|
||||
p.insert_layer(1, Layer::new(gid, "g", LayerKind::folder(), &[]), None, false).unwrap();
|
||||
|
||||
@@ -12,13 +12,23 @@ pub struct Projector {
|
||||
pub scale: [f32; 3],
|
||||
pub crop: ShapeCrop,
|
||||
pub backface: Backface,
|
||||
/// Preserve axis-planar coverage when the projection is placed on a frame.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub ignore_image_alpha: bool,
|
||||
/// Planar and warp projections only
|
||||
pub depth: DepthCulling,
|
||||
}
|
||||
|
||||
impl Default for Projector {
|
||||
fn default() -> Self {
|
||||
Projector { rotation: [0.0; 3], scale: [1.0; 3], crop: ShapeCrop::default(), backface: Backface::default(), depth: DepthCulling::default() }
|
||||
Projector {
|
||||
rotation: [0.0; 3],
|
||||
scale: [1.0; 3],
|
||||
crop: ShapeCrop::default(),
|
||||
backface: Backface::default(),
|
||||
ignore_image_alpha: false,
|
||||
depth: DepthCulling::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::layer::LayerId;
|
||||
use crate::{Channel, LayerId};
|
||||
|
||||
/// A seed inside a folder that the folder's Randomize seeds changed: the `index`-th seed of layer `layer` (its fill's, then its content and mask effects', in stack order) went from `before` to `after`
|
||||
/// A seed changed by a folder, identified by its layer or effect and optional material channel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RandomizedSeed {
|
||||
pub layer: LayerId,
|
||||
/// Position used by older files that did not identify the source.
|
||||
pub index: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub target: Option<(LayerId, Option<Channel>)>,
|
||||
pub before: u32,
|
||||
pub after: u32,
|
||||
}
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pick ID color",
|
||||
[],
|
||||
None,
|
||||
"{effect?: a color selection (default: the selected effect), x?, y?: viewport pixels, viewport?: [w,h] | uv?: [u,v] texture set atlas UV (the 2D view), index?: replace this color instead of adding one} → {color: [r,g,b] as the ID map stores it, index} — samples the ID mesh map under the point",
|
||||
"{effect?: a color selection (default: the selected effect), x?, y?: viewport pixels, viewport?: [w,h] | uv?: [u,v] texture set atlas UV (the 2D view), index?: replace this color instead of adding one} → {color: [r,g,b] as the ID map stores it, index} — samples the selected ID image or the texture set’s baked ID mesh map under the point",
|
||||
has_layer,
|
||||
pick
|
||||
)]
|
||||
|
||||
@@ -12,7 +12,7 @@ use texturecraft_geom::glam::{Quat, Vec2, Vec3};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, layer_param, strp, u64p, vec3};
|
||||
use crate::layer_cmds::{FULL_TURN_DEGREES, MAX_PROJECTION_DEPTH};
|
||||
use crate::tool_cmds::viewport_of;
|
||||
use crate::tool_cmds::{pair, viewport_of};
|
||||
use crate::{Result, Session, StackTarget, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -76,22 +76,17 @@ const MIN_GIVEN_UP_CROSS_SQUARED: f32 = 1e-8;
|
||||
const MIN_CAMERA_UP_CROSS_SQUARED: f32 = 1e-4;
|
||||
|
||||
/// The mesh's diagonal (decal sizes are relative to it).
|
||||
fn mesh_size(session: &Session) -> f32 {
|
||||
let (lo, hi) = session.mesh.bounds();
|
||||
(hi - lo).length().max(MIN_MESH_DIAGONAL)
|
||||
fn diagonal_of((minimum, maximum): (Vec3, Vec3)) -> f32 {
|
||||
(maximum - minimum).length().max(MIN_MESH_DIAGONAL)
|
||||
}
|
||||
|
||||
/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`), within the decal size limits
|
||||
fn size_param(params: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> {
|
||||
let value = params.get("size")?;
|
||||
let size = match value.as_array() {
|
||||
Some(pair) => [pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32],
|
||||
None => {
|
||||
let height = value.as_f64()? as f32;
|
||||
[height * aspect, height]
|
||||
}
|
||||
};
|
||||
size.iter().all(|side| side.is_finite()).then(|| size.map(|side| side.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)))
|
||||
fn size_param(command: &str, params: &Value, aspect: f32, mesh_diagonal: f32) -> Result<Option<[f32; 2]>> {
|
||||
let Some(value) = params.get("size") else { return Ok(None) };
|
||||
let size = if value.is_array() { pair(params, "size") } else { value.as_f64().map(|height| [height as f32 * aspect, height as f32]) };
|
||||
let size = size.filter(|size| size.iter().all(|side| side.is_finite())).ok_or_else(|| bad(command, "`size` must be a finite height or [width, height]"))?;
|
||||
|
||||
Ok(Some(size.map(|side| side.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE))))
|
||||
}
|
||||
|
||||
/// The decal's up direction: `up` when given, else the camera's (decals are placed upright on
|
||||
@@ -178,9 +173,10 @@ fn add(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
return Err(bad(command, format!("the texture set has no {} channel", channel.label())));
|
||||
}
|
||||
|
||||
let mesh_diagonal = mesh_size(session);
|
||||
let bounds = session.mesh.bounds();
|
||||
let mesh_diagonal = diagonal_of(bounds);
|
||||
let default_height = mesh_diagonal * DEFAULT_HEIGHT;
|
||||
let mut size = size_param(params, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]);
|
||||
let mut size = size_param(command, params, aspect, mesh_diagonal)?.unwrap_or([default_height * aspect, default_height]);
|
||||
if boolp(params, "keepProportions") == Some(true) && params.get("size").is_some_and(Value::is_array) {
|
||||
size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
|
||||
}
|
||||
@@ -195,7 +191,7 @@ fn add(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
|
||||
// By default it reaches half its larger side into the surface
|
||||
depth: f32p(params, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)),
|
||||
symmetry: symmetry_param(command, params, None, session.mesh.bounds())?,
|
||||
symmetry: symmetry_param(command, params, None, bounds)?,
|
||||
};
|
||||
|
||||
// A decal dropped on another texture set goes there and selects it, as a dropped material does
|
||||
@@ -232,7 +228,7 @@ fn add(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The projection of fill layer `id`, or of mask fill effect `effect` when given, with the frame it projects from: an axis planar is placed as the frame it already projects from (it reads images exactly as before), a turned or scaled projector is folded into its frame
|
||||
fn framed(session: &Session, command: &str, id: LayerId, effect: Option<LayerId>) -> Result<(Projection, Decal)> {
|
||||
fn framed(session: &Session, command: &str, id: LayerId, effect: Option<LayerId>, bounds: (Vec3, Vec3)) -> Result<(Projection, Decal)> {
|
||||
let projection = stored_projection(session, command, id, effect)?;
|
||||
if matches!(projection, Projection::Planar { placed: None, .. }) && placing_moves_pattern(stored_sources(session, id, effect).into_iter()) {
|
||||
return Err(bad(command, "an axis planar reading a procedural pattern keeps its axis: placing its frame would move the pattern"));
|
||||
@@ -243,7 +239,7 @@ fn framed(session: &Session, command: &str, id: LayerId, effect: Option<LayerId>
|
||||
return Err(bad(command, UNFOLDABLE_CULLING));
|
||||
}
|
||||
|
||||
let projection = placed_from_axis(projection, session.mesh.bounds()).unwrap_or_else(|| projection.clone());
|
||||
let projection = placed_from_axis(projection, bounds).unwrap_or_else(|| projection.clone());
|
||||
|
||||
// The frame moves as it lands: a projector's own turn and scale go into it first
|
||||
let projection = folded(&projection).unwrap_or(projection);
|
||||
@@ -254,7 +250,7 @@ fn framed(session: &Session, command: &str, id: LayerId, effect: Option<LayerId>
|
||||
Ok((projection, frame))
|
||||
}
|
||||
|
||||
/// Whether `projection`'s backface culling keeps its facing once its projector's turn and scale are in its frame
|
||||
/// Whether folding the projector's transform into its frame preserves culling
|
||||
fn culling_keeps_facing(projection: &Projection) -> bool {
|
||||
match projection {
|
||||
Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => culling_folds(projector),
|
||||
@@ -262,9 +258,8 @@ fn culling_keeps_facing(projection: &Projection) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a projector whose backface culling cannot keep its facing in a frame is not moved, and the way out
|
||||
const UNFOLDABLE_CULLING: &str =
|
||||
"backface culling under an uneven or mirrored projector scale cannot move into a frame: even out the projector scale or turn backface culling off";
|
||||
/// Explain why the projector transform cannot be folded into its frame
|
||||
const UNFOLDABLE_CULLING: &str = "the projector scale would change culling when moved into a frame. For uneven scale, even out the projector scale or turn backface culling off. For a mirrored projector, restore a positive scale or turn both backface and depth culling off";
|
||||
|
||||
/// The projection fill layer `id`, or mask fill effect `effect` when given, holds
|
||||
fn stored_projection<'a>(session: &'a Session, command: &str, id: LayerId, effect: Option<LayerId>) -> Result<&'a Projection> {
|
||||
@@ -313,7 +308,7 @@ fn placed_image(session: &Session, id: LayerId, effect: Option<LayerId>) -> Opti
|
||||
}
|
||||
|
||||
/// `projection` with its frame where `frameOffset`, `frameRotation` and `frameScale` put it (None when none is given)
|
||||
fn placed_as_shown(session: &Session, command: &str, params: &Value, projection: &Projection) -> Result<Option<Projection>> {
|
||||
fn placed_as_shown(command: &str, params: &Value, projection: &Projection, bounds: (Vec3, Vec3)) -> Result<Option<Projection>> {
|
||||
let fields = ["frameOffset", "frameRotation", "frameScale"];
|
||||
if fields.iter().all(|key| params.get(*key).is_none()) {
|
||||
return Ok(None);
|
||||
@@ -323,7 +318,6 @@ fn placed_as_shown(session: &Session, command: &str, params: &Value, projection:
|
||||
None => Ok(None),
|
||||
Some(_) => vec3(params, key).map(Some).ok_or_else(|| bad(command, format!("`{key}` must be [x, y, z]"))),
|
||||
};
|
||||
let bounds = session.mesh.bounds();
|
||||
if !culling_keeps_facing(projection) {
|
||||
return Err(bad(command, UNFOLDABLE_CULLING));
|
||||
}
|
||||
@@ -387,11 +381,12 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
return Err(bad(command, format!("effect {} is not in layer {layer}", effect.0)));
|
||||
}
|
||||
|
||||
let (mut projection, mut decal) = framed(session, command, layer_id, effect)?;
|
||||
let bounds = session.mesh.bounds();
|
||||
let (mut projection, mut decal) = framed(session, command, layer_id, effect, bounds)?;
|
||||
let texture_set =
|
||||
session.doc.project.locate(layer_id).map(|(texture_set, _, _)| texture_set).ok_or_else(|| bad(command, "the decal has no texture set"))?;
|
||||
let mesh_diagonal = mesh_size(session);
|
||||
if let Some(moved) = placed_as_shown(session, command, params, &projection)? {
|
||||
let mesh_diagonal = diagonal_of(bounds);
|
||||
if let Some(moved) = placed_as_shown(command, params, &projection, bounds)? {
|
||||
projection = moved;
|
||||
decal = projection.frame().copied().ok_or_else(|| bad(command, "the projection lost its frame"))?;
|
||||
|
||||
@@ -419,7 +414,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let keep = boolp(params, "keepProportions") == Some(true);
|
||||
let ratio = decal.size[0] / decal.size[1].max(MIN_FRAME_SIDE);
|
||||
let aspect = if keep { image_aspect(session, layer_id, effect, strp(params, "image")).unwrap_or(ratio) } else { ratio };
|
||||
if let Some(mut size) = size_param(params, aspect, mesh_diagonal).or_else(|| keep.then_some(decal.size)) {
|
||||
if let Some(mut size) = size_param(command, params, aspect, mesh_diagonal)?.or_else(|| keep.then_some(decal.size)) {
|
||||
// A height sets the width through `aspect`; a pair or the current size sets the height from the width
|
||||
if keep && params.get("size").is_none_or(Value::is_array) {
|
||||
size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
|
||||
@@ -435,12 +430,11 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if let Some(rotation) = f32p(params, "rotation") {
|
||||
decal.rotation = rotation.rem_euclid(FULL_TURN_DEGREES);
|
||||
}
|
||||
if let Some(offset) = params.get("offset").and_then(Value::as_array) {
|
||||
let values: Vec<f32> = offset.iter().filter_map(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect();
|
||||
let [right, up] = values.as_slice() else { return Err(bad(command, "`offset` must be [right, up]")) };
|
||||
|
||||
decal.offset = [right.clamp(-mesh_diagonal, mesh_diagonal), up.clamp(-mesh_diagonal, mesh_diagonal)];
|
||||
if params.get("offset").is_some() {
|
||||
let offset = pair(params, "offset").ok_or_else(|| bad(command, "`offset` must be [right, up]"))?;
|
||||
decal.offset = offset.map(|component| component.clamp(-mesh_diagonal, mesh_diagonal));
|
||||
}
|
||||
|
||||
let depth = f32p(params, "depth").map(|depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE));
|
||||
|
||||
// A warp reaches by its Projection Depth (set below); its frame's own depth is unused, so it stays
|
||||
@@ -449,7 +443,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
{
|
||||
decal.depth = depth;
|
||||
}
|
||||
decal.symmetry = symmetry_param(command, params, decal.symmetry, session.mesh.bounds())?;
|
||||
decal.symmetry = symmetry_param(command, params, decal.symmetry, bounds)?;
|
||||
|
||||
let image = strp(params, "image").map(str::to_string);
|
||||
if let Some(name) = &image
|
||||
@@ -489,13 +483,16 @@ fn store_decal(session: &mut Session, layer_id: LayerId, effect: Option<LayerId>
|
||||
let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind else { return Ok(()) };
|
||||
fill.projection = projection;
|
||||
|
||||
// The new image goes where the decal's image is (the channel it was placed in)
|
||||
let Some(image) = image else { return Ok(()) };
|
||||
|
||||
// Replace the original image in every channel that shared it
|
||||
let placed = fill.sources.values().find_map(|source| match source {
|
||||
Source::Image { name, .. } => Some(name.clone()),
|
||||
_ => None,
|
||||
});
|
||||
match (image, placed) {
|
||||
(Some(image), Some(placed)) => {
|
||||
match placed {
|
||||
Some(placed) if placed == image => return Ok(()),
|
||||
Some(placed) => {
|
||||
for source in fill.sources.values_mut() {
|
||||
if let Source::Image { name, .. } = source
|
||||
&& *name == placed
|
||||
@@ -504,10 +501,10 @@ fn store_decal(session: &mut Session, layer_id: LayerId, effect: Option<LayerId>
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(image), None) => {
|
||||
None => {
|
||||
fill.sources.insert(Channel::BaseColor, Source::image(image));
|
||||
}
|
||||
(None, _) => {}
|
||||
}
|
||||
fill.material = None;
|
||||
Ok(())
|
||||
}
|
||||
@@ -19,18 +19,30 @@ pub fn resource_name(alpha: &LibraryAlpha) -> String {
|
||||
texturecraft_formats::sanitize_resource_name(&format!("{PREFIX}{}{EXTENSION}", alpha.id))
|
||||
}
|
||||
|
||||
/// The library alpha resource `name` holds, if it is one (library ids are safe resource names already, so a name is matched without building one)
|
||||
/// Matches a reserved library name, including numbered alternatives for projects with a pre-existing import.
|
||||
pub fn library_alpha_of(name: &str) -> Option<&'static LibraryAlpha> {
|
||||
let id = name.strip_prefix(PREFIX)?.strip_suffix(EXTENSION)?;
|
||||
let id = id.rsplit_once('.').map_or(id, |(id, discriminator)| if discriminator.parse::<usize>().is_ok() { id } else { "" });
|
||||
alphas::library().iter().find(|alpha| alpha.id == id)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// A resource identified as a generated library picture when it was added or decoded.
|
||||
pub fn library_alpha(&self, name: &str) -> Option<&'static LibraryAlpha> {
|
||||
if self.library_alphas.contains(name) { library_alpha_of(name) } else { None }
|
||||
}
|
||||
|
||||
/// Puts library alpha `alpha` in the project as an image resource unless it is there already, inside the caller's edit; returns its name
|
||||
pub(crate) fn add_library_alpha(&mut self, alpha: &LibraryAlpha) -> Result<String> {
|
||||
let name = resource_name(alpha);
|
||||
if self.doc.resources.contains_key(&name) {
|
||||
return Ok(name);
|
||||
let mut name = resource_name(alpha);
|
||||
let mut discriminator = 2;
|
||||
while self.doc.resources.contains_key(&name) {
|
||||
if self.library_alpha(&name).is_some() {
|
||||
return Ok(name);
|
||||
}
|
||||
|
||||
name = format!("{PREFIX}{}.{discriminator}{EXTENSION}", alpha.id);
|
||||
discriminator += 1;
|
||||
}
|
||||
|
||||
let bytes = png(alpha)?;
|
||||
@@ -38,11 +50,26 @@ impl Session {
|
||||
|
||||
self.doc.resources.insert(name.clone(), Arc::new(bytes));
|
||||
self.images.insert(name.clone(), decoded(image));
|
||||
self.library_alphas.insert(name.clone());
|
||||
|
||||
Ok(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognize legacy generated pixels without treating a same-named import as a library picture.
|
||||
pub(crate) fn matches_saved_picture(name: &str, image: &texturecraft_formats::DecodedImage) -> bool {
|
||||
let Some(alpha) = library_alpha_of(name) else { return false };
|
||||
if image.width as usize != alphas::BASE || image.height as usize != alphas::BASE || !image.srgb {
|
||||
return false;
|
||||
}
|
||||
|
||||
let samples = alpha.render(alphas::BASE, SUPERSAMPLING);
|
||||
samples.len() == image.rgba.len()
|
||||
&& samples.into_iter().zip(&image.rgba).all(|(sample, &[red, green, blue, opacity])| {
|
||||
opacity == 1.0 && red == green && red == blue && texturecraft_texel::to_u16(red) == texturecraft_texel::to_u16(sample)
|
||||
})
|
||||
}
|
||||
|
||||
/// The alpha's picture as a 16-bit grayscale PNG at the library's base size
|
||||
fn png(alpha: &LibraryAlpha) -> Result<Vec<u8>> {
|
||||
let size = alphas::BASE;
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set fill material",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: content fill effect id, material: built-in material id (not a smart material) | null (back to the channels' defaults)} — sets every channel the material writes, turns those channels on and the others off; the projection stays",
|
||||
"{layer? | effect?: content fill effect id, material: built-in material id (not a smart material) | null (back to the channels' defaults)} — sets every channel the material writes, turns those channels on and the others off; the projection stays; linked fills are rejected",
|
||||
has_layer,
|
||||
set_material
|
||||
)]
|
||||
@@ -30,17 +30,17 @@ pub fn whole_materials() -> impl Iterator<Item = &'static SmartMaterial> {
|
||||
MATERIALS.iter().filter(|material| !material.smart)
|
||||
}
|
||||
|
||||
fn set_material(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let target = fill_target(s, p, CMD)?;
|
||||
let material = material_param(p)?;
|
||||
let set = target_set(s, target)?;
|
||||
if holds(s, target, set, material)? {
|
||||
fn set_material(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let target = fill_target(session, params, CMD)?;
|
||||
let material = material_param(params)?;
|
||||
let set = target_set(session, target)?;
|
||||
if holds(session, target, set, material)? {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
|
||||
let Some(found) = material else {
|
||||
s.edit("Clear fill material", |s| {
|
||||
let edited = fill_mut(s, target)?;
|
||||
session.edit("Clear fill material", |session| {
|
||||
let edited = fill_mut(session, target)?;
|
||||
edited.material = None;
|
||||
match target {
|
||||
// A fill effect changes a channel while it has a source: its channels stay on, at their defaults
|
||||
@@ -52,16 +52,16 @@ fn set_material(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
|
||||
s.edit(&format!("Set fill material {}", found.label), |s| {
|
||||
let channels = s.doc.project.texture_set(set)?.channel_list();
|
||||
let sources = material_sources(&mut s.doc.project, &channels, found)?;
|
||||
let edited = fill_mut(s, target)?;
|
||||
session.edit(&format!("Set fill material {}", found.label), |session| {
|
||||
let channels = session.doc.project.texture_set(set)?.channel_list();
|
||||
let sources = material_sources(&mut session.doc.project, &channels, found)?;
|
||||
let edited = fill_mut(session, target)?;
|
||||
edited.sources = sources;
|
||||
edited.material = Some(found.id.to_string());
|
||||
|
||||
let written: Vec<Channel> = edited.sources.keys().copied().collect();
|
||||
if let FillTarget::Layer(id) = target {
|
||||
let layer = s.doc.project.layer_mut(id)?;
|
||||
let layer = session.doc.project.layer_mut(id)?;
|
||||
layer.channels.retain(|channel, _| written.contains(channel));
|
||||
for channel in written {
|
||||
layer.channels.entry(channel).or_default();
|
||||
@@ -73,11 +73,11 @@ fn set_material(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The `material` param: a plain built-in material, or `None` for null
|
||||
fn material_param(p: &Value) -> Result<Option<&'static SmartMaterial>> {
|
||||
match p.get("material") {
|
||||
fn material_param(params: &Value) -> Result<Option<&'static SmartMaterial>> {
|
||||
match params.get("material") {
|
||||
Some(Value::Null) => Ok(None),
|
||||
Some(_) => {
|
||||
let id = strp(p, "material").ok_or_else(|| bad(CMD, "`material` is a material id or null"))?;
|
||||
let id = strp(params, "material").ok_or_else(|| bad(CMD, "`material` is a material id or null"))?;
|
||||
let found = find(id).ok_or_else(|| bad(CMD, format!("unknown material `{id}`")))?;
|
||||
if found.smart {
|
||||
return Err(bad(CMD, format!("`{}` is a smart material (a folder of layers): add it from the shelf with material.apply", found.id)));
|
||||
@@ -90,19 +90,23 @@ fn material_param(p: &Value) -> Result<Option<&'static SmartMaterial>> {
|
||||
}
|
||||
|
||||
/// Whether the fill at `target` (in texture set `set`) already holds `material` whole (or, for `None`, no material and its channels' defaults), so setting it changes nothing
|
||||
fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMaterial>) -> Result<bool> {
|
||||
fn holds(session: &Session, target: FillTarget, set: usize, material: Option<&SmartMaterial>) -> Result<bool> {
|
||||
let (fill, layer_channels) = match target {
|
||||
FillTarget::Layer(id) => {
|
||||
let layer = s.doc.project.layer(id)?;
|
||||
let layer = session.doc.project.layer(id)?;
|
||||
let LayerKind::Fill(fill) = &layer.kind else { return Err(bad(CMD, "not a fill layer")) };
|
||||
(fill, Some(&layer.channels))
|
||||
}
|
||||
FillTarget::Effect(id) => match s.doc.project.effect(id).map(|(_, found)| &found.kind) {
|
||||
FillTarget::Effect(id) => match session.doc.project.effect(id).map(|(_, found)| &found.kind) {
|
||||
Some(EffectKind::Material(fill)) => (fill, None),
|
||||
_ => return Err(bad(CMD, "not a content fill effect")),
|
||||
},
|
||||
FillTarget::Mask(_) => return Err(bad(CMD, "a mask fill has one grayscale source and no channels or material")),
|
||||
};
|
||||
if fill.link.is_some() {
|
||||
return Err(bad(CMD, "a linked material cannot be replaced with this command"));
|
||||
}
|
||||
|
||||
if fill.material.as_deref() != material.map(|found| found.id) {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -111,7 +115,8 @@ fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMat
|
||||
Ok(match (material, layer_channels) {
|
||||
(Some(_), Some(channels)) => channels.len() == fill.sources.len() && fill.sources.keys().all(|channel| channels.contains_key(channel)),
|
||||
(Some(found), None) => {
|
||||
let channels = s.doc.project.texture_set(set)?.channel_list();
|
||||
let channels = session.doc.project.texture_set(set)?.channel_list();
|
||||
|
||||
// The recipe allocates a layer ID, but comparing its sources must leave the project alone
|
||||
let mut scratch = Project::new("", "");
|
||||
fill.sources == material_sources(&mut scratch, &channels, found)?
|
||||
@@ -122,14 +127,14 @@ fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMat
|
||||
}
|
||||
|
||||
/// The texture set the fill `target` paints in, whichever set is selected
|
||||
fn target_set(s: &Session, target: FillTarget) -> Result<usize> {
|
||||
fn target_set(session: &Session, target: FillTarget) -> Result<usize> {
|
||||
let owner = match target {
|
||||
FillTarget::Layer(id) => id,
|
||||
FillTarget::Effect(id) | FillTarget::Mask(id) => {
|
||||
s.doc.project.effect(id).map(|(owner, _)| owner).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?
|
||||
session.doc.project.effect(id).map(|(owner, _)| owner).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?
|
||||
}
|
||||
};
|
||||
s.doc.project.locate(owner).map(|(set, ..)| set).ok_or_else(|| bad(CMD, format!("layer {} is in no texture set", owner.0)))
|
||||
session.doc.project.locate(owner).map(|(set, ..)| set).ok_or_else(|| bad(CMD, format!("layer {} is in no texture set", owner.0)))
|
||||
}
|
||||
|
||||
/// The material's sources for the enabled channels. The recipe allocates layer IDs in `project`.
|
||||
@@ -156,10 +161,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn every_whole_material_is_one_unmasked_fill() {
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
|
||||
let channels = s.doc.project.texture_set(s.ts()).map(|set| set.channel_list()).unwrap_or_default();
|
||||
let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
|
||||
let channels = session.doc.project.texture_set(session.ts()).map(|set| set.channel_list()).unwrap_or_default();
|
||||
for material in whole_materials() {
|
||||
assert!(whole_fill(&mut s.doc.project, material, &channels).is_ok(), "{}", material.id);
|
||||
assert!(whole_fill(&mut session.doc.project, material, &channels).is_ok(), "{}", material.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,12 @@ pub fn reset_projection_of(current: &Projection) -> Projection {
|
||||
.find(|fresh| std::mem::discriminant(fresh) == std::mem::discriminant(current));
|
||||
let Some(mut fresh) = same_kind else { return current.clone() };
|
||||
|
||||
if let (Projection::Planar { placed, .. }, Projection::Planar { placed: Some(frame), .. }) = (&mut fresh, current) {
|
||||
if let (Projection::Planar { placed, projector, .. }, Projection::Planar { placed: Some(frame), projector: previous_projector, .. }) = (&mut fresh, current)
|
||||
{
|
||||
*placed = Some(*frame);
|
||||
projector.ignore_image_alpha = previous_projector.ignore_image_alpha;
|
||||
}
|
||||
|
||||
fresh
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! A folder's actions on everything inside it: the Scale and Rotation laid on its fills, and new seeds for its patterns
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::project::MAX_DEPTH;
|
||||
use texturecraft_core::{ContentsOffset, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, Project, RandomizedSeed, Source};
|
||||
use texturecraft_core::{Channel, ContentsOffset, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, Project, RandomizedSeed, Source};
|
||||
|
||||
use crate::commands::{CommandSpec, bad, f32p, has_layer, layer_param};
|
||||
use crate::{Result, Session, cmd};
|
||||
@@ -106,25 +106,21 @@ fn reset_contents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
let mut inside = Vec::new();
|
||||
descendants(&s.doc.project, id, 0, &mut inside);
|
||||
let inside: HashSet<LayerId> = inside.into_iter().collect();
|
||||
|
||||
s.edit("Reset folder contents", |s| {
|
||||
let contents = contents_mut(&mut s.doc.project, id).ok_or_else(|| bad(CMD, format!("layer {} is not a folder", id.0)))?;
|
||||
*contents = ContentsOffset::NONE;
|
||||
|
||||
let randomized = randomized_mut(&mut s.doc.project, id).map(std::mem::take).unwrap_or_default();
|
||||
let mut records_by_layer = HashMap::<LayerId, Vec<&RandomizedSeed>>::new();
|
||||
for record in randomized.iter().filter(|record| inside.contains(&record.layer)) {
|
||||
records_by_layer.entry(record.layer).or_default().push(record);
|
||||
}
|
||||
let records = take_seed_records(&mut s.doc.project, id);
|
||||
for id in inside {
|
||||
let Some(layer) = s.doc.project.layers.get_mut(&id) else { continue };
|
||||
let Some(records) = records.get(&id) else { continue };
|
||||
let seeds = layer_seeds(layer);
|
||||
let originals = original_seeds(&seeds, records);
|
||||
|
||||
for (layer_id, records) in records_by_layer {
|
||||
let Some(layer) = s.doc.project.layers.get_mut(&layer_id) else { continue };
|
||||
let mut seeds = layer_seeds(layer);
|
||||
for record in records {
|
||||
// Preserve seeds edited since randomization
|
||||
if let Some(seed) = seeds.get_mut(record.index as usize).filter(|seed| ***seed == record.after) {
|
||||
**seed = record.before;
|
||||
for (target, seed) in seeds {
|
||||
if let Some(record) = originals.get(&target).filter(|record| record.after == *seed) {
|
||||
*seed = record.before;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,47 +143,67 @@ fn randomize_seeds(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// One mixing key per folder: a seed maps to the same new seed wherever it is, so patterns that lined up still do
|
||||
let key = next_seed(folder.0 as u32 ^ (folder.0 >> 32) as u32);
|
||||
s.edit("Randomize seeds", |s| {
|
||||
let mut randomized = randomized_mut(&mut s.doc.project, folder).map(std::mem::take).unwrap_or_default();
|
||||
let mut positions = randomized.iter().enumerate().map(|(position, record)| ((record.layer, record.index), position)).collect();
|
||||
let records = take_seed_records(&mut s.doc.project, folder);
|
||||
let mut randomized = Vec::with_capacity(seeds);
|
||||
for id in &inside {
|
||||
let Some(layer) = s.doc.project.layers.get_mut(id) else { continue };
|
||||
for (index, seed) in (0u32..).zip(layer_seeds(layer)) {
|
||||
let seeds = layer_seeds(layer);
|
||||
let originals = records.get(id).map(|records| original_seeds(&seeds, records)).unwrap_or_default();
|
||||
|
||||
for (index, (target, seed)) in (0u32..).zip(seeds) {
|
||||
let before = originals.get(&target).filter(|record| record.after == *seed).map_or(*seed, |record| record.before);
|
||||
let after = next_seed(*seed ^ key);
|
||||
remember(&mut randomized, &mut positions, RandomizedSeed { layer: *id, index, before: *seed, after });
|
||||
randomized.push(RandomizedSeed { layer: *id, target: Some(target), index, before, after });
|
||||
*seed = after;
|
||||
}
|
||||
}
|
||||
|
||||
*randomized_mut(&mut s.doc.project, folder).ok_or_else(|| bad(CMD, format!("layer {} is not a folder", folder.0)))? = randomized;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "seeds": seeds }))
|
||||
}
|
||||
|
||||
/// Adds `change` to the folder's randomized seeds, found by (layer, seed index) in `positions`; a seed randomized again keeps its first `before` (what the reset puts back), unless it was changed by hand in between
|
||||
fn remember(randomized: &mut Vec<RandomizedSeed>, positions: &mut HashMap<(LayerId, u32), usize>, change: RandomizedSeed) {
|
||||
match positions.get(&(change.layer, change.index)).and_then(|position| randomized.get_mut(*position)) {
|
||||
Some(record) if record.after == change.before => record.after = change.after,
|
||||
Some(record) => *record = change,
|
||||
None => {
|
||||
positions.insert((change.layer, change.index), randomized.len());
|
||||
randomized.push(change);
|
||||
}
|
||||
type SeedTarget = (LayerId, Option<Channel>);
|
||||
|
||||
fn take_seed_records(project: &mut Project, folder: LayerId) -> HashMap<LayerId, Vec<RandomizedSeed>> {
|
||||
let mut by_layer = HashMap::<_, Vec<_>>::new();
|
||||
for record in randomized_mut(project, folder).into_iter().flat_map(std::mem::take) {
|
||||
by_layer.entry(record.layer).or_default().push(record);
|
||||
}
|
||||
|
||||
by_layer
|
||||
}
|
||||
|
||||
/// Whether folder `id` holds anything its Contents act on: a fill (layer, content or mask fill) or a seed
|
||||
fn original_seeds<'a>(seeds: &[(SeedTarget, &mut u32)], records: &'a [RandomizedSeed]) -> HashMap<SeedTarget, &'a RandomizedSeed> {
|
||||
records
|
||||
.iter()
|
||||
.filter_map(|record| {
|
||||
// Old records identified a seed by its position in the layer
|
||||
let target = record.target.or_else(|| seeds.get(record.index as usize).map(|(target, _)| *target))?;
|
||||
Some((target, record))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the folder has a fill to transform, seeds to randomize or changes to reset.
|
||||
pub fn has_contents(project: &Project, id: LayerId) -> bool {
|
||||
let mut inside = Vec::new();
|
||||
descendants(project, id, 0, &mut inside);
|
||||
inside.iter().filter_map(|id| project.layers.get(id)).any(|layer| {
|
||||
let fills = matches!(layer.kind, LayerKind::Fill(_))
|
||||
|| layer
|
||||
.content_effects
|
||||
.iter()
|
||||
.chain(layer.mask.iter().flat_map(|mask| mask.effects.iter()))
|
||||
.any(|effect| matches!(effect.kind, EffectKind::Fill { .. } | EffectKind::Material(_)));
|
||||
fills || seed_count(layer) > 0
|
||||
})
|
||||
fn applicable(project: &Project, id: LayerId, depth: usize, owned: bool) -> bool {
|
||||
if depth > MAX_DEPTH {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Some(layer) = project.layers.get(&id) else { return false };
|
||||
let source = project.content_layer(id);
|
||||
let mask = project.layers.get(&project.mask_owner(id)).and_then(|layer| layer.mask.as_ref());
|
||||
let effects = source.into_iter().flat_map(|layer| &layer.content_effects).chain(mask.into_iter().flat_map(|mask| &mask.effects));
|
||||
let fill = source.is_some_and(|layer| matches!(layer.kind, LayerKind::Fill(_)))
|
||||
|| effects.into_iter().any(|effect| matches!(effect.kind, EffectKind::Fill { .. } | EffectKind::Material(_)));
|
||||
fill || (owned && seed_count(layer) > 0)
|
||||
|| source.is_some_and(|source| source.children().iter().any(|child| applicable(project, *child, depth + 1, owned && source.id == id)))
|
||||
}
|
||||
|
||||
contents_changed(project, id) || project.layers.get(&id).is_some_and(|layer| layer.children().iter().any(|child| applicable(project, *child, 0, true)))
|
||||
}
|
||||
|
||||
/// Every layer inside folder `id`, nested folders' children too (instances' sources are not followed: they live elsewhere)
|
||||
@@ -204,19 +220,23 @@ fn descendants(project: &Project, id: LayerId, depth: usize, out: &mut Vec<Layer
|
||||
}
|
||||
|
||||
/// The seeds of a layer's fill, content effects and mask effects
|
||||
fn layer_seeds(layer: &mut Layer) -> Vec<&mut u32> {
|
||||
let Layer { kind, content_effects, mask, .. } = layer;
|
||||
fn layer_seeds(layer: &mut Layer) -> Vec<(SeedTarget, &mut u32)> {
|
||||
let Layer { id, kind, content_effects, mask, .. } = layer;
|
||||
let mut seeds = Vec::new();
|
||||
if let LayerKind::Fill(fill) = kind {
|
||||
seeds.extend(fill.sources.values_mut().filter_map(source_seed));
|
||||
seeds.extend(fill.sources.iter_mut().filter_map(|(&channel, source)| Some(((*id, Some(channel)), source_seed(source)?))));
|
||||
}
|
||||
let effects = content_effects.iter_mut().chain(mask.iter_mut().flat_map(|mask| mask.effects.iter_mut()));
|
||||
for effect in effects {
|
||||
match &mut effect.kind {
|
||||
EffectKind::Fill { source, .. } => seeds.extend(source_seed(source)),
|
||||
EffectKind::Material(fill) => seeds.extend(fill.sources.values_mut().filter_map(source_seed)),
|
||||
EffectKind::Generator(generator) => seeds.push(&mut generator.seed),
|
||||
EffectKind::Filter(Filter::Warp { seed, .. } | Filter::SlopeBlur { seed, .. } | Filter::DirectionalWarp { seed, .. }) => seeds.push(seed),
|
||||
EffectKind::Fill { source, .. } => seeds.extend(source_seed(source).map(|seed| ((effect.id, None), seed))),
|
||||
EffectKind::Material(fill) => {
|
||||
seeds.extend(fill.sources.iter_mut().filter_map(|(&channel, source)| Some(((effect.id, Some(channel)), source_seed(source)?))))
|
||||
}
|
||||
EffectKind::Generator(generator) => seeds.push(((effect.id, None), &mut generator.seed)),
|
||||
EffectKind::Filter(Filter::Warp { seed, .. } | Filter::SlopeBlur { seed, .. } | Filter::DirectionalWarp { seed, .. }) => {
|
||||
seeds.push(((effect.id, None), seed))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,11 @@ impl Session {
|
||||
let texel = ((pixel as f32 + 0.5) / size as f32 * extent as f32).floor().min((extent - 1) as f32);
|
||||
(texel + 0.5) / extent as f32
|
||||
};
|
||||
let mut rgba = Vec::with_capacity(size as usize * size as usize * 4);
|
||||
let side = size as usize;
|
||||
let byte_count = side.checked_mul(side)?.checked_mul(4)?;
|
||||
let mut rgba = Vec::new();
|
||||
rgba.try_reserve_exact(byte_count).ok()?;
|
||||
|
||||
for y in 0..size {
|
||||
let v = texel_centre(y, height);
|
||||
for x in 0..size {
|
||||
|
||||
@@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set fill source",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes the image resource alpha_<id>.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}",
|
||||
"{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?|alpha?: library alpha id or name (its picture becomes a project image, normally alpha_<id>.png), normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}",
|
||||
has_layer,
|
||||
fill_set
|
||||
),
|
||||
@@ -130,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set fill projection",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: content or mask fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations, every projection; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value",
|
||||
"{layer? | effect?: content or mask fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations except on uvTile; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value",
|
||||
has_layer,
|
||||
fill_projection
|
||||
),
|
||||
@@ -584,6 +584,7 @@ fn fill_set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
let source = fill_source_from(session, params, (target, channel), normal_format)?;
|
||||
|
||||
// A library alpha that became the source joins the project's images
|
||||
let library_alpha = match &source {
|
||||
Some(Source::Image { name, .. }) => crate::fill_alpha::library_alpha_of(name).filter(|_| strp(params, "image").is_none()),
|
||||
@@ -602,29 +603,32 @@ fn fill_set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
|
||||
// Changing only the normal format or gradient stops leaves the layer channel on or off
|
||||
let touches_channel = source.is_some() || enabled.is_some();
|
||||
let format_existing_image = normal_format.filter(|_| source.is_none());
|
||||
let replaces_material = source.is_some() || colors.is_some() || init_ramp;
|
||||
let current = fill_mut(session, target)?.sources.get(&channel);
|
||||
let colors = if init_ramp { initial_ramp(channel, source.as_ref(), current)? } else { colors };
|
||||
let mut source = with_ramp(channel, current, source, colors)?;
|
||||
|
||||
session.edit("Set fill", |session| {
|
||||
if let Some(alpha) = library_alpha {
|
||||
session.add_library_alpha(alpha)?;
|
||||
if let (Some(alpha), Some(Source::Image { name, .. })) = (library_alpha, &mut source) {
|
||||
*name = session.add_library_alpha(alpha)?;
|
||||
}
|
||||
|
||||
let fill = fill_mut(session, target)?;
|
||||
|
||||
// `normalFormat` alone: the convention of the channel's image
|
||||
if let (None, Some(format)) = (&source, normal_format) {
|
||||
match fill.sources.get_mut(&channel) {
|
||||
if let Some(format) = format_existing_image {
|
||||
match source.as_mut().or_else(|| fill.sources.get_mut(&channel)) {
|
||||
Some(Source::Image { normal_format, .. }) => *normal_format = format,
|
||||
_ => return Err(bad(FILL_SET, "`normalFormat` needs an image on the channel")),
|
||||
}
|
||||
}
|
||||
|
||||
// A channel set on its own (its source or its gradient map): the sources are no longer one whole material
|
||||
if source.is_some() || colors.is_some() || init_ramp {
|
||||
if replaces_material {
|
||||
fill.material = None;
|
||||
}
|
||||
|
||||
let current = fill.sources.get(&channel);
|
||||
let colors = if init_ramp { initial_ramp(channel, source.as_ref(), current)? } else { colors };
|
||||
let source = with_ramp(channel, current, source, colors)?;
|
||||
|
||||
match target {
|
||||
FillTarget::Mask(_) => return Err(bad(FILL_SET, "a mask fill has no channels")),
|
||||
// A fill effect's channel is on while it has a source
|
||||
@@ -633,7 +637,7 @@ fn fill_set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
// Removing stops (`colors: []`) from a channel the fill does not have adds nothing
|
||||
FillTarget::Effect(_) if source.is_none() && enabled != Some(true) && current.is_none() => {}
|
||||
FillTarget::Effect(_) if source.is_none() && enabled != Some(true) && !fill.sources.contains_key(&channel) => {}
|
||||
FillTarget::Effect(_) => {
|
||||
let source = source.unwrap_or_else(|| fill.source(channel));
|
||||
fill.sources.insert(channel, source);
|
||||
@@ -666,7 +670,7 @@ fn mask_fill_set(s: &mut Session, p: &Value, effect: LayerId) -> Result<Value> {
|
||||
refuse_gray_keys(p, "a mask fill")?;
|
||||
|
||||
let current = mask_source_mut(s, effect)?.clone();
|
||||
let (source, library_alpha) = gray_source(s, p, effect, current.clone())?;
|
||||
let (source, library_alpha) = gray_source(s, p, effect, ¤t)?;
|
||||
|
||||
// Setting what the fill already reads adds no undo step
|
||||
if source == current && library_alpha_present(s, library_alpha) {
|
||||
@@ -699,18 +703,18 @@ fn library_alpha_present(s: &Session, library_alpha: Option<&LibraryAlpha>) -> b
|
||||
}
|
||||
|
||||
/// The grayscale source `p` asks for in place of `current` (read by a mask or filter effect `effect`), and the library alpha it needs added
|
||||
fn gray_source(s: &Session, p: &Value, effect: LayerId, current: Source) -> Result<(Source, Option<&'static LibraryAlpha>)> {
|
||||
fn gray_source(s: &Session, p: &Value, effect: LayerId, current: &Source) -> Result<(Source, Option<&'static LibraryAlpha>)> {
|
||||
let low = color_param(FILL_SET, p, "low")?;
|
||||
let high = color_param(FILL_SET, p, "high")?;
|
||||
let color = color_param(FILL_SET, p, "color")?;
|
||||
let value = color_param(FILL_SET, p, "value")?;
|
||||
if let Some(kind) = strp(p, "procedural") {
|
||||
let kind = ProceduralKind::parse(kind).ok_or_else(|| bad(FILL_SET, format!("unknown procedural `{kind}`")))?;
|
||||
Ok((procedural_from(p, kind, Some(¤t), [low, high])?, None))
|
||||
Ok((procedural_from(p, kind, Some(current), [low, high])?, None))
|
||||
} else if let Some(gray) = color.or(value) {
|
||||
Ok((Source::Uniform(gray.map(|component| component.clamp(0.0, 1.0))), None))
|
||||
} else if let Some(name) = strp(p, "image") {
|
||||
Ok((Source::image(name.to_string()), None))
|
||||
Ok((crate::mask_cmds::image_source(s, FILL_SET, name)?, None))
|
||||
} else if let Some(name) = strp(p, "alpha") {
|
||||
let alpha = alphas::find(name).ok_or_else(|| bad(FILL_SET, format!("unknown alpha `{name}`")))?;
|
||||
Ok((Source::image(crate::fill_alpha::resource_name(alpha)), Some(alpha)))
|
||||
@@ -719,23 +723,28 @@ fn gray_source(s: &Session, p: &Value, effect: LayerId, current: Source) -> Resu
|
||||
|
||||
// A gray reads one channel of the anchor's stack: the one it read, else Height
|
||||
let kept = match current {
|
||||
Source::Anchor { channel, .. } => channel,
|
||||
Source::Anchor { channel, .. } => *channel,
|
||||
_ => Channel::Height,
|
||||
};
|
||||
let channel = channel_param(FILL_SET, p, "anchorChannel")?.unwrap_or(kept);
|
||||
Ok((crate::mask_cmds::anchor_source(s, FILL_SET, reader, LayerId(anchor), channel)?, None))
|
||||
} else if crate::procedural_params::has_pattern_settings(p) {
|
||||
} else if edits_fill_pattern(p) {
|
||||
// Pattern settings alone edit the current pattern
|
||||
let Source::Procedural { pattern, .. } = ¤t else {
|
||||
let Source::Procedural { pattern, .. } = current else {
|
||||
return Err(bad(FILL_SET, "the source has no pattern: give `procedural` with its settings"));
|
||||
};
|
||||
|
||||
Ok((procedural_from(p, pattern.kind, Some(¤t), [None, None])?, None))
|
||||
Ok((procedural_from(p, pattern.kind, Some(current), [low, high])?, None))
|
||||
} else {
|
||||
Err(bad(FILL_SET, "give `value`, `procedural`, `image`, `alpha` or `anchor`"))
|
||||
}
|
||||
}
|
||||
|
||||
fn edits_fill_pattern(params: &Value) -> bool {
|
||||
crate::procedural_params::has_pattern_settings(params)
|
||||
|| ["scale", "seed", "contrast", "balance", "invert", "low", "high"].iter().any(|key| params.get(key).is_some())
|
||||
}
|
||||
|
||||
/// The procedural source `params` ask for with `low`/`high` already parsed: a pattern of the same kind as `current` keeps what `params` do not give; another kind starts from its defaults
|
||||
fn procedural_from(params: &Value, kind: ProceduralKind, current: Option<&Source>, [low, high]: [Option<[f32; 3]>; 2]) -> Result<Source> {
|
||||
let (mut pattern, current_low, current_high) = match current {
|
||||
@@ -761,9 +770,10 @@ fn fill_source_from(
|
||||
|
||||
if let Some(name) = strp(params, "procedural") {
|
||||
let kind = ProceduralKind::parse(name).ok_or_else(|| bad(FILL_SET, format!("unknown procedural `{name}`")))?;
|
||||
|
||||
// A pattern of the same kind keeps what `params` do not give; another kind starts from its defaults
|
||||
let current = fill_mut(session, target)?.sources.get(&channel).cloned();
|
||||
return Ok(Some(procedural_from(params, kind, current.as_ref(), [low, high])?));
|
||||
let current = fill_mut(session, target)?.sources.get(&channel);
|
||||
return Ok(Some(procedural_from(params, kind, current, [low, high])?));
|
||||
}
|
||||
|
||||
if let Some(color) = uniform {
|
||||
@@ -789,20 +799,17 @@ fn fill_source_from(
|
||||
return Ok(Some(crate::mask_cmds::anchor_source(session, FILL_SET, reader, LayerId(anchor), anchor_channel)?));
|
||||
}
|
||||
|
||||
if !crate::procedural_params::has_pattern_settings(params) {
|
||||
if !edits_fill_pattern(params) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Pattern settings alone edit the channel's current pattern
|
||||
let Some(Source::Procedural { pattern, low, high, .. }) = fill_mut(session, target)?.sources.get(&channel) else {
|
||||
let current = fill_mut(session, target)?.sources.get(&channel);
|
||||
let Some(Source::Procedural { pattern, .. }) = current else {
|
||||
return Err(bad(FILL_SET, "the channel has no pattern: give `procedural` with its settings"));
|
||||
};
|
||||
|
||||
let mut pattern = pattern.clone();
|
||||
crate::procedural_params::pattern_basics_from(params, &mut pattern);
|
||||
crate::procedural_params::pattern_settings_from(FILL_SET, params, &mut pattern)?;
|
||||
|
||||
Ok(Some(Source::Procedural { pattern, low: *low, high: *high, ramp: Vec::new() }))
|
||||
Ok(Some(procedural_from(params, pattern.kind, current, [low, high])?))
|
||||
}
|
||||
|
||||
/// The gradient map stops from `colors` (None when absent, empty to remove).
|
||||
|
||||
@@ -62,52 +62,87 @@ pub(crate) fn copy_tree(src: &Document, id: LayerId, s: &mut Document, ts: usize
|
||||
if depth > texturecraft_core::project::MAX_DEPTH {
|
||||
return Err(EngineError::Other("layer groups nested too deeply".into()));
|
||||
}
|
||||
|
||||
let size = s.project.texture_set(ts)?.size();
|
||||
let channels = s.project.texture_set(ts)?.channel_list();
|
||||
let layer = src.project.layer(id)?.clone();
|
||||
let layer = src.project.layer(id)?;
|
||||
let new = s.project.alloc_id();
|
||||
let mut copy = layer.clone();
|
||||
copy.id = new;
|
||||
// Channels the target set doesn't have are dropped; ones it has but the source didn't
|
||||
// stay disabled.
|
||||
copy.channels.retain(|c, _| channels.contains(c));
|
||||
for e in copy.mask.iter_mut().flat_map(|m| m.effects.iter_mut()).chain(copy.content_effects.iter_mut()) {
|
||||
let old = e.id;
|
||||
e.id = s.project.alloc_id();
|
||||
if let Some(img) = src.pixels.masks.get(&old) {
|
||||
s.pixels.masks.insert(e.id, fit(img, size, &[0, 0]));
|
||||
|
||||
// Channels absent from the target set stay disabled
|
||||
copy.channels.retain(|channel, _| channels.contains(channel));
|
||||
for effect in copy.mask.iter_mut().flat_map(|mask| &mut mask.effects).chain(&mut copy.content_effects) {
|
||||
let old = effect.id;
|
||||
effect.id = s.project.alloc_id();
|
||||
if let Some(image) = src.pixels.masks.get(&old) {
|
||||
s.pixels.masks.insert(effect.id, fit(image, size, &[0, 0]));
|
||||
}
|
||||
// Content paint effects keep per-channel pixels.
|
||||
for c in channels.iter().copied() {
|
||||
if let Some(img) = src.pixels.layer(old, c) {
|
||||
s.pixels.layers.insert((e.id, c), fit(img, size, &empty_texel(c)));
|
||||
|
||||
for &channel in &channels {
|
||||
if let Some(image) = src.pixels.layer(old, channel) {
|
||||
s.pixels.layers.insert((effect.id, channel), fit(image, size, &empty_texel(channel)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let children = layer.children().to_vec();
|
||||
if let LayerKind::Group { children: c, .. } = &mut copy.kind {
|
||||
c.clear();
|
||||
|
||||
if let LayerKind::Group { children, .. } = &mut copy.kind {
|
||||
children.clear();
|
||||
}
|
||||
for c in Channel::ALL {
|
||||
if let Some(img) = src.pixels.layer(id, c)
|
||||
&& channels.contains(&c)
|
||||
{
|
||||
s.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c)));
|
||||
|
||||
for &channel in &channels {
|
||||
if let Some(image) = src.pixels.layer(id, channel) {
|
||||
s.pixels.layers.insert((new, channel), fit(image, size, &empty_texel(channel)));
|
||||
}
|
||||
}
|
||||
|
||||
s.project.insert_layer(ts, copy, above, inside)?;
|
||||
let mut below = None;
|
||||
for c in children {
|
||||
// Children keep their bottom → top order inside the new group.
|
||||
let placed = match below {
|
||||
None => copy_tree(src, c, s, ts, Some(new), true, depth + 1)?,
|
||||
Some(b) => copy_tree(src, c, s, ts, Some(b), false, depth + 1)?,
|
||||
};
|
||||
below = Some(placed);
|
||||
let mut previous = None;
|
||||
for &child in layer.children() {
|
||||
let placed = copy_tree(src, child, s, ts, previous.or(Some(new)), previous.is_none(), depth + 1)?;
|
||||
previous = Some(placed);
|
||||
}
|
||||
|
||||
if matches!(&layer.kind, LayerKind::Group { randomized, .. } if !randomized.is_empty()) {
|
||||
remap_seed_records(&src.project, &mut s.project, id, new)?;
|
||||
}
|
||||
|
||||
Ok(new)
|
||||
}
|
||||
|
||||
/// Retarget saved seed resets to the layers and effects of the new folder.
|
||||
fn remap_seed_records(source: &texturecraft_core::Project, destination: &mut texturecraft_core::Project, original: LayerId, copy: LayerId) -> Result<()> {
|
||||
let mut pairs = vec![(original, copy)];
|
||||
let mut ids = std::collections::HashMap::new();
|
||||
while let Some((original, copy)) = pairs.pop() {
|
||||
let old = source.layer(original)?;
|
||||
let new = destination.layer(copy)?;
|
||||
ids.insert(original, copy);
|
||||
pairs.extend(old.children().iter().copied().zip(new.children().iter().copied()));
|
||||
|
||||
fn effect_ids(layer: &texturecraft_core::Layer) -> impl Iterator<Item = LayerId> {
|
||||
layer.content_effects.iter().chain(layer.mask.iter().flat_map(|mask| &mask.effects)).map(|effect| effect.id)
|
||||
}
|
||||
|
||||
ids.extend(effect_ids(old).zip(effect_ids(new)));
|
||||
}
|
||||
|
||||
if let LayerKind::Group { randomized, .. } = &mut destination.layer_mut(copy)?.kind {
|
||||
randomized.retain_mut(|record| {
|
||||
let Some(layer) = ids.get(&record.layer) else { return false };
|
||||
record.layer = *layer;
|
||||
if let Some((source, _)) = &mut record.target {
|
||||
let Some(target) = ids.get(source) else { return false };
|
||||
*source = *target;
|
||||
}
|
||||
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = layer_param(s, "layer.copy", p)?;
|
||||
s.clipboard = Some((s.doc.clone(), id));
|
||||
|
||||
@@ -521,7 +521,7 @@ impl Session {
|
||||
|
||||
let mut images = std::collections::HashSet::new();
|
||||
for image in self.images.values().filter(|image| images.insert(Arc::as_ptr(image))) {
|
||||
retained_bytes = retained_bytes.saturating_add(image_texel_bytes(image));
|
||||
retained_bytes = retained_bytes.saturating_add(image.retained_texel_bytes());
|
||||
}
|
||||
|
||||
budget.set_retained(retained_bytes);
|
||||
@@ -631,13 +631,7 @@ impl Session {
|
||||
}
|
||||
|
||||
fn material_bytes(material: &CookedMaterial) -> u64 {
|
||||
material.maps.iter().fold(0u64, |total, map| total.saturating_add(map.bytes.capacity() as u64).saturating_add(image_texel_bytes(&map.image)))
|
||||
}
|
||||
|
||||
fn image_texel_bytes(image: &texturecraft_compose::ImageRes) -> u64 {
|
||||
let texel_bytes = |capacity: usize| (capacity as u64).saturating_mul(std::mem::size_of::<[f32; 4]>() as u64);
|
||||
let full_image = texel_bytes(image.rgba.capacity());
|
||||
image.mips.get().into_iter().flatten().fold(full_image, |bytes, mip| bytes.saturating_add(texel_bytes(mip.rgba.capacity())))
|
||||
material.maps.iter().fold(0u64, |total, map| total.saturating_add(map.bytes.capacity() as u64).saturating_add(map.image.retained_texel_bytes()))
|
||||
}
|
||||
|
||||
/// A resource name that preserves its suffix through a project round trip.
|
||||
|
||||
@@ -233,9 +233,11 @@ pub(crate) fn content_target(p: &Value, cmd: &str) -> Result<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_EFFECT_NAME_CHARS: usize = 256;
|
||||
|
||||
/// A valid `name` param.
|
||||
fn name_param(p: &Value) -> Option<&str> {
|
||||
strp(p, "name").filter(|n| !n.trim().is_empty() && n.chars().count() <= 256)
|
||||
strp(p, "name").filter(|n| !n.trim().is_empty() && n.chars().count() <= MAX_EFFECT_NAME_CHARS)
|
||||
}
|
||||
|
||||
/// Add an effect to the selected layer's mask (creating a mask if there is none) or, with `target: "content"` or a content-only effect, to its content stack
|
||||
@@ -325,7 +327,7 @@ pub(crate) fn anchor_source(s: &Session, cmd: &str, reader: LayerId, anchor: Lay
|
||||
|
||||
/// A source reading image resource `name`, which must be imported and decoded: the compositor
|
||||
/// would otherwise fill with a flat gray without saying why
|
||||
fn image_source(session: &Session, command: &str, name: &str) -> Result<Source> {
|
||||
pub(crate) fn image_source(session: &Session, command: &str, name: &str) -> Result<Source> {
|
||||
if !session.images.contains_key(name) {
|
||||
return Err(bad(command, format!("no image resource `{name}` (import it first)")));
|
||||
}
|
||||
@@ -457,7 +459,9 @@ fn add_anchor(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
fields.insert("target".into(), json!(if content { "content" } else { "mask" }));
|
||||
if name_param(params).is_none() {
|
||||
let layer = session.doc.project.layer(layer_param(session, "effect.add.anchor", params)?)?;
|
||||
let name = if content { layer.name.clone() } else { format!("{} mask", layer.name) };
|
||||
let suffix = if content { "" } else { " mask" };
|
||||
let mut name: String = layer.name.chars().take(MAX_EFFECT_NAME_CHARS - suffix.len()).collect();
|
||||
name.push_str(suffix);
|
||||
fields.insert("name".into(), json!(name));
|
||||
}
|
||||
push_effect(session, &Value::Object(fields), EffectKind::Anchor, BlendMode::Normal)
|
||||
@@ -743,7 +747,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// `input` names a generator input that `inputImage`, `inputValue` or `inputAnchor` replaces, or `inputBaked` puts back
|
||||
// The input key identifies the generator slot to replace or restore
|
||||
let input = match session.doc.project.effect(effect) {
|
||||
Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => generator_input_param(session, owner, params)?,
|
||||
_ => None,
|
||||
@@ -831,16 +835,9 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
*source = Source::Uniform([value.clamp(0.0, 1.0); 3]);
|
||||
}
|
||||
|
||||
// While the fill reads a pattern, `scale` is the pattern's and leaves the projection alone
|
||||
let mut placement = params.clone();
|
||||
if matches!(source, Source::Procedural { .. })
|
||||
&& let Some(fields) = placement.as_object_mut()
|
||||
{
|
||||
fields.remove("scale");
|
||||
}
|
||||
|
||||
// Preserve projection fields that the edit does not supply
|
||||
*projection = projection_from(&placement, CMD, Some(&*projection), || crate::warp_cmds::fitted_frame(&mesh))?;
|
||||
// A scalar changes pattern frequency while an array places the projection
|
||||
let pattern_scale = matches!(source, Source::Procedural { .. }) && params.get("scale").is_some_and(Value::is_number);
|
||||
*projection = projection_from_fields(params, CMD, Some(&*projection), !pattern_scale, || crate::warp_cmds::fitted_frame(&mesh))?;
|
||||
}
|
||||
EffectKind::ColorSelection(selection) => crate::color_selection_cmds::apply_params(params, selection, id_map)?,
|
||||
kind @ EffectKind::Compare { .. } => compare_from(CMD, params, kind)?,
|
||||
@@ -866,7 +863,9 @@ fn fill_pattern(command: &str, params: &Value, current: &Source) -> Result<Optio
|
||||
}
|
||||
None => {
|
||||
let has_settings = crate::procedural_params::has_pattern_settings(params);
|
||||
let edits_pattern = has_settings || ["scale", "seed", "contrast", "balance", "invert"].iter().any(|key| params.get(key).is_some());
|
||||
let edits_pattern = has_settings
|
||||
|| params.get("scale").is_some_and(Value::is_number)
|
||||
|| ["seed", "contrast", "balance", "invert"].iter().any(|key| params.get(key).is_some());
|
||||
match current {
|
||||
Some(pattern) if edits_pattern => pattern.clone(),
|
||||
None if has_settings => {
|
||||
|
||||
@@ -190,7 +190,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// What mask strokes paint: the tool's image while it is loaded, else its gray
|
||||
pub(crate) fn mask_gray(&self) -> MaskGray {
|
||||
pub fn mask_gray(&self) -> MaskGray {
|
||||
let image = self.tool.mask_image.as_ref().and_then(|name| Some((name, self.images.get(name)?)));
|
||||
match image {
|
||||
Some((name, image)) => MaskGray::Image { name: name.clone(), image: image.clone() },
|
||||
@@ -532,9 +532,9 @@ impl Session {
|
||||
/// After stamps were rasterized: prepare the tiles the commit will write (so it only swaps
|
||||
/// them in) and mark the touched tiles for the live preview.
|
||||
fn stroke_painted(&mut self) {
|
||||
let Some(st) = self.stroke.as_mut() else { return };
|
||||
let recent = std::mem::take(&mut st.canvas.recent);
|
||||
let (ts, target) = (st.ts, st.target);
|
||||
let Some(stroke) = self.stroke.as_mut() else { return };
|
||||
let recent = std::mem::take(&mut stroke.canvas.recent);
|
||||
let (ts, target) = (stroke.ts, stroke.target);
|
||||
let Some(paint_target) = target else {
|
||||
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
|
||||
return;
|
||||
@@ -542,12 +542,12 @@ impl Session {
|
||||
|
||||
let gbuf = self.caches.get(ts).map(|c| c.gbuf.clone());
|
||||
let pixels = &self.doc.pixels;
|
||||
let mut staging = std::mem::take(&mut st.staging);
|
||||
with_commit_source(st, gbuf.as_deref(), &self.mesh, &recent, |src| match paint_target {
|
||||
PaintTarget::Layer(id) => staging.stage_layer(pixels, id, &st.values, &src),
|
||||
PaintTarget::Mask(effect) => staging.stage_mask(pixels, effect, &st.mask_gray, &src),
|
||||
let mut staging = std::mem::take(&mut stroke.staging);
|
||||
with_commit_source(stroke, gbuf.as_deref(), &self.mesh, &recent, |src| match paint_target {
|
||||
PaintTarget::Layer(id) => staging.stage_layer(pixels, id, &stroke.values, &src),
|
||||
PaintTarget::Mask(effect) => staging.stage_mask(pixels, effect, &stroke.mask_gray, &src),
|
||||
});
|
||||
st.staging = staging;
|
||||
stroke.staging = staging;
|
||||
self.mark_painted(ts, target, recent);
|
||||
}
|
||||
|
||||
@@ -557,40 +557,45 @@ impl Session {
|
||||
|
||||
/// Commit the active stroke (one undo step).
|
||||
pub fn end_stroke(&mut self) -> Result<()> {
|
||||
let Some(mut st) = self.stroke.take() else { return Ok(()) };
|
||||
let size = (st.canvas.alpha.width(), st.canvas.alpha.height());
|
||||
if st.canvas.dirty.is_empty() {
|
||||
let Some(mut stroke) = self.stroke.take() else { return Ok(()) };
|
||||
let size = (stroke.canvas.alpha.width(), stroke.canvas.alpha.height());
|
||||
if stroke.canvas.dirty.is_empty() {
|
||||
// Nothing painted: drop any mask effect the stroke created
|
||||
self.doc = st.before;
|
||||
self.doc = stroke.before;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let gbuf = self.caches.get(st.ts).map(|c| c.gbuf.clone());
|
||||
let gbuf = self.caches.get(stroke.ts).map(|c| c.gbuf.clone());
|
||||
let mesh = self.mesh.clone();
|
||||
let mut staging = std::mem::take(&mut st.staging);
|
||||
match st.target {
|
||||
let mut staging = std::mem::take(&mut stroke.staging);
|
||||
match stroke.target {
|
||||
Some(PaintTarget::Layer(id)) => {
|
||||
let pixels = &mut self.doc.pixels;
|
||||
with_commit_source(&st, gbuf.as_deref(), &mesh, &st.canvas.dirty, |src| commit_layer(pixels, id, size, &st.values, src, &mut staging));
|
||||
with_commit_source(&stroke, gbuf.as_deref(), &mesh, &stroke.canvas.dirty, |src| {
|
||||
commit_layer(pixels, id, size, &stroke.values, src, &mut staging)
|
||||
});
|
||||
}
|
||||
Some(PaintTarget::Mask(eid)) => {
|
||||
let pixels = &mut self.doc.pixels;
|
||||
with_commit_source(&st, gbuf.as_deref(), &mesh, &st.canvas.dirty, |src| commit_mask(pixels, eid, size, &st.mask_gray, src, &mut staging));
|
||||
with_commit_source(&stroke, gbuf.as_deref(), &mesh, &stroke.canvas.dirty, |src| {
|
||||
commit_mask(pixels, eid, size, &stroke.mask_gray, src, &mut staging)
|
||||
});
|
||||
}
|
||||
None => {
|
||||
with_commit_source(&st, gbuf.as_deref(), &mesh, &st.canvas.dirty, |src| self.commit_quick_mask(st.ts, size, src));
|
||||
with_commit_source(&stroke, gbuf.as_deref(), &mesh, &stroke.canvas.dirty, |src| self.commit_quick_mask(stroke.ts, size, src));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
self.undo.push((st.label.clone(), st.before));
|
||||
self.undo.push((stroke.label.clone(), stroke.before));
|
||||
if self.undo.len() > crate::session::MAX_HISTORY {
|
||||
self.undo.remove(0);
|
||||
}
|
||||
self.redo.clear();
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
|
||||
// Recompute committed tiles at low priority because the live preview already shows them
|
||||
self.mark_settle(st.ts, st.target, st.canvas.dirty.iter().copied());
|
||||
self.mark_settle(stroke.ts, stroke.target, stroke.canvas.dirty.iter().copied());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -645,17 +650,17 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask.
|
||||
pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
|
||||
pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas, gray: &MaskGray) -> Result<()> {
|
||||
if self.quick_mask.editing {
|
||||
return self.paint_fill(ts, canvas);
|
||||
return self.paint_fill(ts, canvas, gray);
|
||||
}
|
||||
|
||||
// Each fill is its own step, never merged into a box drag's step of the same label
|
||||
self.edit_merging(label, false, |session| session.paint_fill(ts, canvas))
|
||||
self.edit_merging(label, false, |session| session.paint_fill(ts, canvas, gray))
|
||||
}
|
||||
|
||||
/// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step)
|
||||
pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
|
||||
pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas, gray: &MaskGray) -> Result<()> {
|
||||
let size = (canvas.alpha.width(), canvas.alpha.height());
|
||||
let opacity = self.tool.brush.opacity;
|
||||
let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None, carried_mask: None };
|
||||
@@ -668,10 +673,7 @@ impl Session {
|
||||
let values = self.stroke_values(target);
|
||||
match target {
|
||||
PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()),
|
||||
PaintTarget::Mask(effect) => {
|
||||
let mask_gray = self.mask_gray();
|
||||
commit_mask(&mut self.doc.pixels, effect, size, &mask_gray, source, &mut Staging::default())
|
||||
}
|
||||
PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, gray, source, &mut Staging::default()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1181,7 +1181,7 @@ impl Session {
|
||||
}
|
||||
|
||||
let tiles = canvas.dirty.len();
|
||||
self.commit_fill("Path fill", texture_set, &canvas)?;
|
||||
self.commit_fill("Path fill", texture_set, &canvas, &self.mask_gray())?;
|
||||
Ok(tiles)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use texturecraft_compose::MaskGray;
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{Mesh, NO_TRI};
|
||||
use texturecraft_paint::{EyeDepth, fill_triangles, screen_point};
|
||||
@@ -191,7 +192,7 @@ impl Session {
|
||||
|
||||
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
|
||||
fill_triangles(&mut canvas, &gbuf, &triangles);
|
||||
self.commit_fill("Polygon fill", ts, &canvas)?;
|
||||
self.commit_fill("Polygon fill", ts, &canvas, &MaskGray::Value(self.tool.mask_value))?;
|
||||
Ok(triangles.len())
|
||||
}
|
||||
|
||||
@@ -262,7 +263,7 @@ impl Session {
|
||||
} else {
|
||||
self.fill_canvas(ts).and_then(|(gbuf, mut canvas)| {
|
||||
fill_triangles(&mut canvas, &gbuf, &selected);
|
||||
self.paint_fill(ts, &canvas)
|
||||
self.paint_fill(ts, &canvas, &MaskGray::Value(self.tool.mask_value))
|
||||
})
|
||||
};
|
||||
self.invalidate_changed(&previous);
|
||||
|
||||
@@ -82,7 +82,7 @@ impl Session {
|
||||
let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |extension_start| base.split_at(extension_start));
|
||||
let mut name = base.clone();
|
||||
let mut duplicate_index = 2;
|
||||
while self.doc.resources.contains_key(&name) {
|
||||
while self.doc.resources.contains_key(&name) || crate::fill_alpha::library_alpha_of(&name).is_some() {
|
||||
let discriminator = format!("{duplicate_index}_");
|
||||
let available = MAX_RESOURCE_NAME_LEN - discriminator.len();
|
||||
|
||||
@@ -102,6 +102,7 @@ impl Session {
|
||||
/// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load).
|
||||
pub fn sync_images(&mut self) {
|
||||
self.images.retain(|name, _| self.doc.resources.contains_key(name));
|
||||
self.library_alphas.retain(|name| self.images.contains_key(name));
|
||||
|
||||
let mut linked_packages = std::collections::HashSet::new();
|
||||
let mut linked_images = std::collections::HashMap::new();
|
||||
@@ -132,6 +133,10 @@ impl Session {
|
||||
};
|
||||
match image {
|
||||
Ok(image) => {
|
||||
if crate::fill_alpha::matches_saved_picture(name, &image) {
|
||||
self.library_alphas.insert(name.clone());
|
||||
}
|
||||
|
||||
self.images.insert(name.clone(), decoded(image));
|
||||
}
|
||||
Err(error) => self.log.warn(crate::log::LIBRARY_SOURCE, format!("resource {name}: {error}")),
|
||||
|
||||
@@ -60,6 +60,7 @@ impl SetCache {
|
||||
pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache {
|
||||
let (w, h) = ts.size();
|
||||
let gbuf = UvGBuffer::new(mesh, ts.material, w, h);
|
||||
|
||||
// Padding stays inside each UV tile
|
||||
let dilation = DilationMap::in_blocks(&gbuf.coverage_mask(), w, h, Some(DISPLAY_PADDING), ts.block_resolution());
|
||||
let covered = covered_tiles(&gbuf);
|
||||
@@ -459,6 +460,8 @@ pub struct Session {
|
||||
pub blending_clipboard: Option<crate::effect_blending_cmds::CopiedBlending>,
|
||||
/// Decoded image resources (rebuilt from `doc.resources` by `Session::sync_images`).
|
||||
pub images: texturecraft_compose::ImageStore,
|
||||
/// Resource names whose decoded pixels match a library alpha.
|
||||
pub(crate) library_alphas: BTreeSet<String>,
|
||||
/// Temporary texel mask limiting paint strokes (not saved, not in the history).
|
||||
pub quick_mask: crate::quick_mask::QuickMask,
|
||||
/// A path sublayer is being repainted from its paths (the only way to paint into one).
|
||||
@@ -543,6 +546,7 @@ impl Session {
|
||||
clipboard: None,
|
||||
blending_clipboard: None,
|
||||
images: Default::default(),
|
||||
library_alphas: BTreeSet::new(),
|
||||
quick_mask: Default::default(),
|
||||
painting_paths: false,
|
||||
path_cache: None,
|
||||
|
||||
@@ -8,41 +8,41 @@ use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("swatch.list", "Swatches", [], None, "{}", always, |s, _| Ok(list(s))),
|
||||
cmd!("swatch.list", "Swatches", [], None, "{}", always, |session, _| Ok(list(session))),
|
||||
cmd!("swatch.add", "Add swatch", [], None, "{color: [r, g, b] (linear 0..1) | \"#rrggbb\"}", always, add),
|
||||
cmd!("swatch.remove", "Remove swatch", [], None, "{index}", has_swatches, remove),
|
||||
]
|
||||
}
|
||||
|
||||
fn has_swatches(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.doc.project.swatches.is_empty() { Err("the project has no swatches".into()) } else { Ok(()) }
|
||||
fn has_swatches(session: &Session) -> std::result::Result<(), String> {
|
||||
if session.doc.project.swatches.is_empty() { Err("the project has no swatches".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn list(s: &Session) -> Value {
|
||||
json!({ "swatches": s.doc.project.swatches })
|
||||
fn list(session: &Session) -> Value {
|
||||
json!({ "swatches": session.doc.project.swatches })
|
||||
}
|
||||
|
||||
/// Adds `color` (clamped to 0..1) after the project's last swatch
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let color = color_param("swatch.add", p, "color")?.ok_or_else(|| bad("swatch.add", "`color` is required: [r, g, b] or \"#rrggbb\""))?;
|
||||
if s.doc.project.swatches.len() >= MAX_SWATCHES {
|
||||
fn add(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let color = color_param("swatch.add", params, "color")?.ok_or_else(|| bad("swatch.add", "`color` is required: [r, g, b] or \"#rrggbb\""))?;
|
||||
if session.doc.project.swatches.len() >= MAX_SWATCHES {
|
||||
return Err(bad("swatch.add", format!("a project keeps at most {MAX_SWATCHES} swatches; remove one first")));
|
||||
}
|
||||
|
||||
let color = color.map(|part| part.clamp(0.0, 1.0));
|
||||
s.edit("Add swatch", |s| {
|
||||
s.doc.project.swatches.push(color);
|
||||
Ok(json!({ "index": s.doc.project.swatches.len() - 1, "color": color }))
|
||||
session.edit("Add swatch", |session| {
|
||||
session.doc.project.swatches.push(color);
|
||||
Ok(json!({ "index": session.doc.project.swatches.len() - 1, "color": color }))
|
||||
})
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let index = u64p(p, "index")
|
||||
fn remove(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let index = u64p(params, "index")
|
||||
.and_then(|index| usize::try_from(index).ok())
|
||||
.filter(|index| *index < s.doc.project.swatches.len())
|
||||
.filter(|index| *index < session.doc.project.swatches.len())
|
||||
.ok_or_else(|| bad("swatch.remove", "`index` must name a swatch (see swatch.list)"))?;
|
||||
s.edit("Remove swatch", |s| {
|
||||
let color = s.doc.project.swatches.remove(index);
|
||||
session.edit("Remove swatch", |session| {
|
||||
let color = session.doc.project.swatches.remove(index);
|
||||
Ok(json!({ "removed": color }))
|
||||
})
|
||||
}
|
||||
@@ -283,6 +283,9 @@ impl ThumbService {
|
||||
|
||||
if let Some(snapshot) = &self.snapshot {
|
||||
self.cache.retain(|target, _| snapshot.has(*target));
|
||||
|
||||
// Late requests still need a picture from this generation
|
||||
self.queue.extend(self.wanted.iter().copied().filter(|target| snapshot.has(*target)));
|
||||
} else {
|
||||
self.cache.clear();
|
||||
}
|
||||
@@ -549,6 +552,26 @@ mod tests {
|
||||
assert_eq!(jobs.try_recv().map(|job| job.target).ok(), Some(target), "the late request is dispatched, not dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_request_survives_replacing_its_snapshot() {
|
||||
let mut session = test_session().unwrap();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
let target = ThumbTarget::Content { layer, channel: Channel::BaseColor };
|
||||
let (mut service, jobs, _results) = held_worker();
|
||||
service.begin_frame(&session, 0.0);
|
||||
service.poll(&session);
|
||||
service.get(&session, target);
|
||||
crate::execute(&mut session, "layer.rename", &serde_json::json!({"layer": layer.0, "name": "Changed"})).unwrap();
|
||||
|
||||
service.begin_frame(&session, DEBOUNCE * 2.0);
|
||||
service.poll(&session);
|
||||
|
||||
let job = jobs.try_recv().unwrap();
|
||||
|
||||
assert_eq!(job.target, target);
|
||||
assert_eq!(job.snapshot.project.layer(layer).unwrap().name, "Changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stopped_worker_retries_visible_targets_inline() {
|
||||
let session = test_session().unwrap();
|
||||
|
||||
@@ -453,12 +453,11 @@ fn stencil(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// A `[a, b]` param of two finite numbers.
|
||||
fn pair(p: &Value, key: &str) -> Option<[f32; 2]> {
|
||||
let a = p.get(key)?.as_array()?;
|
||||
let [x, y] = a.as_slice() else { return None };
|
||||
let x = x.as_f64()? as f32;
|
||||
let y = y.as_f64()? as f32;
|
||||
(x.is_finite() && y.is_finite()).then_some([x, y])
|
||||
pub(crate) fn pair(params: &Value, key: &str) -> Option<[f32; 2]> {
|
||||
let [x, y] = params.get(key)?.as_array()?.as_slice() else { return None };
|
||||
let pair = [x.as_f64()? as f32, y.as_f64()? as f32];
|
||||
|
||||
pair.iter().all(|component| component.is_finite()).then_some(pair)
|
||||
}
|
||||
|
||||
fn clone_source(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -38,6 +38,7 @@ fn content_effects_commands_inspect_and_round_trip() {
|
||||
assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor));
|
||||
assert!(s.doc.project.layer(LayerId(layer)).unwrap().mask.is_none(), "content effects don't create a mask");
|
||||
assert_eq!(s.target, StackTarget::Effect(LayerId(hsl)));
|
||||
|
||||
// Mask-only effects refuse the content, unknown targets are errors
|
||||
assert!(execute(&mut s, "effect.add.generator", &json!({"target": "content"})).is_err());
|
||||
assert!(execute(&mut s, "effect.add.filter", &json!({"target": "nope"})).is_err());
|
||||
|
||||
@@ -67,3 +67,35 @@ fn an_unknown_alpha_changes_nothing() {
|
||||
|
||||
assert!(session.doc.project.layer(layer).is_err(), "the refused set added no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_and_a_legacy_resource_keep_their_own_pixels_when_picking_an_alpha() {
|
||||
let alpha = alphas::find("round_soft").unwrap();
|
||||
let reserved = resource_name(alpha);
|
||||
let image_bytes = texturecraft_engine::formats::mcmat::mesh_map_png(2, 1, &[0.25; 4]).unwrap();
|
||||
|
||||
for legacy in [true, false] {
|
||||
let (mut session, layer) = fill();
|
||||
let imported = if legacy {
|
||||
session.doc.resources.insert(reserved.clone(), std::sync::Arc::new(image_bytes.clone()));
|
||||
session.sync_images();
|
||||
reserved.clone()
|
||||
} else {
|
||||
session.import_resource_bytes(&reserved, image_bytes.clone()).unwrap()
|
||||
};
|
||||
execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "metallic", "image": imported})).unwrap();
|
||||
|
||||
execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "alpha": alpha.id})).unwrap();
|
||||
|
||||
let Source::Image { name, .. } = source(&session, layer, Channel::Roughness) else { panic!("alpha image") };
|
||||
assert_ne!(name, imported, "the library picture must have a separate resource");
|
||||
assert_eq!(session.images[&name].width as usize, alphas::BASE);
|
||||
assert_eq!(session.doc.resources[&imported].as_slice(), image_bytes);
|
||||
assert_eq!(source(&session, layer, Channel::Metallic), Source::image(imported.clone()));
|
||||
|
||||
let reopened = Session::from_project_file(session.project_file()).unwrap();
|
||||
|
||||
assert!(reopened.library_alpha(&imported).is_none());
|
||||
assert_eq!(reopened.library_alpha(&name).unwrap().id, alpha.id);
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ fn a_pattern_parameter_given_alone_keeps_every_other_one() {
|
||||
for (key, value, change) in edits {
|
||||
let mut expected = roughness(&session, layer);
|
||||
change(&mut expected);
|
||||
let mut edit = json!({"layer": layer.0, "channel": "roughness", "procedural": "Clouds"});
|
||||
let mut edit = json!({"layer": layer.0, "channel": "roughness"});
|
||||
edit[key] = value;
|
||||
execute(&mut session, "layer.fill.set", &edit).unwrap();
|
||||
|
||||
|
||||
@@ -98,6 +98,7 @@ fn a_negative_projector_scale_keeps_its_mirror() {
|
||||
let layer = checker_fill(&mut s);
|
||||
set(&mut s, layer, json!({"projection": "spherical", "projectorScale": [-1.5, 0.0, 5000.0]}));
|
||||
let Projection::Spherical { projector, .. } = projection(&s, layer) else { panic!("a spherical projection") };
|
||||
|
||||
assert_eq!(projector.scale, [-1.5, 0.001, 1000.0], "the mirror kept, each axis's size within the scale limits");
|
||||
|
||||
set(&mut s, layer, json!({"projectorScale": -0.0001}));
|
||||
@@ -123,6 +124,7 @@ fn match_per_uv_tile_repeats_the_source_once_per_tile() {
|
||||
(tile(0), tile(1))
|
||||
};
|
||||
let (left, right) = tiles(&mut s);
|
||||
|
||||
assert_ne!(left, right, "a UV projection runs on into the next tile");
|
||||
|
||||
set(&mut s, layer, json!({"projection": "uvTile"}));
|
||||
@@ -196,10 +198,12 @@ fn backface_culling_keeps_a_planar_projection_off_faces_turned_away() {
|
||||
execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap();
|
||||
let empty = snapshot(&mut s);
|
||||
execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap();
|
||||
|
||||
// Without depth culling the planar projection reaches the far side, so only backface culling can take it off
|
||||
set(&mut s, layer, json!({"projection": "planar", "axis": 2, "depthCulling": false}));
|
||||
let plain = snapshot(&mut s);
|
||||
let (far, near) = (facing_z(&s, -1.1, -0.05), facing_z(&s, 0.05, 1.1));
|
||||
|
||||
assert!(!far.is_empty() && !near.is_empty());
|
||||
assert!(far.iter().any(|&i| plain[i] != empty[i]), "without culling the projection reaches the far side");
|
||||
|
||||
@@ -235,6 +239,7 @@ fn saved_decals_load_as_planar_projections_placed_on_the_surface() {
|
||||
saved["projection"] = json!({ "Decal": frame });
|
||||
let fill: Fill = serde_json::from_value(saved).unwrap();
|
||||
let Projection::Planar { placed: Some(placed), projector, .. } = fill.projection else { panic!("{:?}", fill.projection) };
|
||||
|
||||
assert_eq!(placed, frame);
|
||||
assert_eq!(projector.crop, ShapeCrop::Cropped);
|
||||
assert_eq!(projector.backface, Backface { on: true, angle: 90.0, hardness: 0.5 });
|
||||
@@ -281,6 +286,7 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame()
|
||||
execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap();
|
||||
set(&mut s, layer, json!({"projection": "warp"}));
|
||||
let Projection::Warp { frame, corners, depth, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) };
|
||||
|
||||
assert_eq!((corners, depth), (Projection::FRAME_CORNERS, Projection::WARP_DEPTH));
|
||||
assert_eq!((frame.normal, frame.up), ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), "seen from the front");
|
||||
assert!(frame.size.iter().all(|side| (side - 2.0).abs() < 1e-3) && frame.center.iter().all(|c| c.abs() < 1e-3), "around the unit sphere: {frame:?}");
|
||||
@@ -341,6 +347,7 @@ fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() {
|
||||
execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap();
|
||||
set(&mut s, layer, json!({"projection": "planar", "axis": 2}));
|
||||
let Projection::Planar { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) };
|
||||
|
||||
assert_eq!(projector.depth, DepthCulling::NEW, "a new planar projection culls by depth");
|
||||
|
||||
let culled = snapshot(&mut s);
|
||||
@@ -418,6 +425,7 @@ fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() {
|
||||
set(&mut s, layer, json!({"projection": "planar", "axis": 2}));
|
||||
let plain = snapshot(&mut s);
|
||||
let (far, near) = (facing_z(&s, -1.1, -0.3), facing_z(&s, 0.3, 1.1));
|
||||
|
||||
assert_eq!(filled(&far, &plain, &empty), 0);
|
||||
|
||||
set(&mut s, layer, json!({"symmetry": true, "symmetryType": "mirror", "symmetryAxis": 2}));
|
||||
@@ -473,6 +481,7 @@ fn moving_an_axis_planar_places_it_as_its_frame_first() {
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap();
|
||||
let placed = projection(&s, layer);
|
||||
let Projection::Planar { placed: Some(frame), projector, .. } = &placed else { panic!("placed: {placed:?}") };
|
||||
|
||||
assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "the turn is in the frame now");
|
||||
|
||||
let after = snapshot(&mut s);
|
||||
@@ -499,6 +508,38 @@ fn moving_an_axis_planar_places_it_as_its_frame_first() {
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).is_err(), "a spherical projection has no frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_a_cropped_axis_planar_preserves_coverage_through_save_and_reload() {
|
||||
let mesh = primitives::builtin("sphere").unwrap();
|
||||
let mut session = Session::new_project("Axis planar", mesh, "builtin:sphere", None, 128).unwrap();
|
||||
let layer = checker_fill(&mut session);
|
||||
let mut png = std::io::Cursor::new(Vec::new());
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 128])).write_to(&mut png, image::ImageFormat::Png).unwrap();
|
||||
let image = session.import_resource_bytes("translucent.png", png.into_inner()).unwrap();
|
||||
execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": image})).unwrap();
|
||||
set(&mut session, layer, json!({"projection": "planar", "axis": 2, "scale": 1.8, "shapeCrop": "cropped", "depthCulling": false}));
|
||||
let before = snapshot(&mut session);
|
||||
|
||||
assert!(before.iter().any(|&red| red > 0.99), "the axis fill ignores source alpha in its crop");
|
||||
assert!(before.iter().any(|&red| red < 0.6), "the shape still crops coverage");
|
||||
|
||||
execute(&mut session, "layer.decal.set", &json!({"layer": layer.0})).unwrap();
|
||||
let placed = projection(&session, layer);
|
||||
let after = snapshot(&mut session);
|
||||
|
||||
assert!(placed.placed().is_some());
|
||||
let changed = before.iter().zip(&after).filter(|(before, after)| (*before - *after).abs() > 2.0 / 255.0).count();
|
||||
assert!(changed * 200 < before.len(), "placement changed visible coverage at {changed} texels");
|
||||
|
||||
let bytes = session.to_project_bytes().unwrap();
|
||||
let mut reopened = Session::from_project_bytes(&bytes).unwrap();
|
||||
|
||||
assert_eq!(projection(&reopened, layer), placed);
|
||||
let reloaded = snapshot(&mut reopened);
|
||||
let changed = reloaded.iter().zip(&after).filter(|(reloaded, after)| reloaded != after).count();
|
||||
assert_eq!(changed, 0, "reload changed visible coverage");
|
||||
}
|
||||
|
||||
/// An axis planar reading a procedural keeps its axis: a placed frame reads the pattern in its own uv, so placing it would move the pattern; a mask fill's pattern stays the same way
|
||||
#[test]
|
||||
fn an_axis_planar_reading_a_pattern_is_not_placed() {
|
||||
@@ -565,7 +606,7 @@ fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first(
|
||||
set(&mut s, layer, json!({"projection": "planar", "axis": 2}));
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
// Depth culling off: its depth map is drawn along the frame, so a folded turn re-draws it (a few silhouette texels differ)
|
||||
// Disable depth culling here because rerasterizing a turned frame can change silhouette texels
|
||||
set(&mut s, layer, json!({"projectorRotation": [0, 0, 30], "projectorScale": 1.25, "depthCulling": false}));
|
||||
let turned = snapshot(&mut s);
|
||||
let steps = s.history_labels().len();
|
||||
@@ -573,6 +614,7 @@ fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first(
|
||||
// Moving the frame as shown: the turn and scale are in the frame now, the image where it was
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameOffset": [0.0, 0.0, 0.0]})).unwrap();
|
||||
let Projection::Planar { placed: Some(frame), projector, .. } = projection(&s, layer) else { panic!("still placed") };
|
||||
|
||||
assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "folded into the frame");
|
||||
|
||||
let (lo, hi) = s.mesh.bounds();
|
||||
@@ -601,13 +643,26 @@ fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first(
|
||||
|
||||
assert_eq!(snapshot(&mut s), turned, "undo puts the turned projector back");
|
||||
|
||||
for bad in [json!({"frameScale": [1, 2]}), json!({"frameOffset": "x"}), json!({"frameScale": [0, -1, "deep"]})] {
|
||||
let before_invalid_edit = projection(&s, layer);
|
||||
let undo_steps = s.history_labels().len();
|
||||
for bad in [
|
||||
json!({"frameScale": [1, 2]}),
|
||||
json!({"frameOffset": "x"}),
|
||||
json!({"frameScale": [0, -1, "deep"]}),
|
||||
json!({"offset": [0.2, "x", 0.1]}),
|
||||
json!({"offset": 0.1}),
|
||||
json!({"size": [0.1, 0.2, 0.3]}),
|
||||
json!({"size": [0.1, "x"]}),
|
||||
] {
|
||||
let mut params = bad.clone();
|
||||
params["layer"] = json!(layer.0);
|
||||
|
||||
assert!(execute(&mut s, "layer.decal.set", ¶ms).is_err(), "{bad}");
|
||||
}
|
||||
|
||||
assert_eq!(projection(&s, layer), before_invalid_edit);
|
||||
assert_eq!(s.history_labels().len(), undo_steps);
|
||||
|
||||
// A collapsed or turned-over scale is clamped to the smallest frame, not refused
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [0, -1, 0]})).unwrap();
|
||||
let Projection::Planar { placed: Some(smallest), .. } = projection(&s, layer) else { panic!("still placed") };
|
||||
@@ -700,9 +755,47 @@ fn a_warps_depth_sets_its_projection_depth() {
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "depth": 0.5})).unwrap();
|
||||
let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") };
|
||||
|
||||
assert!((depth * frame.size[0].max(frame.size[1]) - 0.5).abs() < 1e-5, "reach {depth} × {:?}", frame.size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_depth_warp_can_move_its_frame() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
set(&mut s, layer, json!({"projection": "warp", "projectionDepth": 0}));
|
||||
let before = projection(&s, layer);
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameOffset": [0.2, 0, 0], "frameRotation": [0, 10, 0]})).unwrap();
|
||||
|
||||
let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") };
|
||||
let original = before.frame().unwrap();
|
||||
|
||||
assert_ne!(frame.center, original.center);
|
||||
assert_ne!(frame.normal, original.normal);
|
||||
assert_eq!(depth, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_procedural_mask_keeps_array_placement_scale_separate_from_pattern_scale() {
|
||||
use texturecraft_engine::core::{EffectKind, Source};
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "procedural": "Checker", "scale": 4})).unwrap();
|
||||
let effect = added["effect"].as_u64().unwrap();
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": effect, "scale": [2, 3]})).unwrap();
|
||||
execute(&mut s, "effect.set", &json!({"effect": effect, "scale": 5})).unwrap();
|
||||
|
||||
let (_, effect) = s.doc.project.effect(LayerId(effect)).unwrap();
|
||||
let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection: Projection::Uv { scale, .. }, .. } = &effect.kind else {
|
||||
panic!("a procedural UV mask fill");
|
||||
};
|
||||
|
||||
assert_eq!(*scale, [2.0, 3.0]);
|
||||
assert_eq!(pattern.scale, 5.0);
|
||||
}
|
||||
|
||||
/// `depth` at a warp's current reach changes nothing, so it adds no undo step (its frame's unused depth is left alone)
|
||||
#[test]
|
||||
fn a_warps_current_reach_as_depth_adds_no_undo_step() {
|
||||
@@ -731,6 +824,7 @@ fn a_warps_frame_scale_keeps_its_projection_depth_in_range() {
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [0.0001, 0.0001, 10]})).unwrap();
|
||||
let Projection::Warp { depth, .. } = projection(&s, layer) else { panic!("a warp") };
|
||||
|
||||
assert!(depth <= max_depth, "Projection Depth {depth} past {max_depth}");
|
||||
}
|
||||
|
||||
@@ -758,6 +852,7 @@ fn reset_fill_settings_keeps_the_projection_and_restores_its_defaults_in_one_und
|
||||
_ => panic!("a fill layer"),
|
||||
};
|
||||
let changed = fill(&s);
|
||||
|
||||
assert!(!texturecraft_engine::fill_reset_cmds::at_defaults(&changed.projection, changed.sampling));
|
||||
|
||||
execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap();
|
||||
@@ -801,6 +896,7 @@ fn reset_fill_settings_keeps_a_warp_frame_and_restores_its_settings() {
|
||||
json!({"warpCorners": [[-0.6, 0.5], [0.5, 0.6], [0.4, -0.5], [-0.5, -0.4]], "projectionDepth": 0.5, "tiling": [2, 2], "rotation": 45, "shapeCrop": "extendsOutside"}),
|
||||
);
|
||||
let Projection::Warp { frame: moved, .. } = projection(&s, layer) else { panic!("a warp") };
|
||||
|
||||
assert_ne!(moved, fitted, "the frame was moved");
|
||||
|
||||
execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
@@ -54,6 +54,7 @@ fn filtering_decides_how_a_shrunk_image_reads() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s, 7.3);
|
||||
let (lo, hi) = spread(&mut s);
|
||||
|
||||
assert!(hi - lo < 0.2, "a new fill reads with Bilinear | HQ: an even gray, got {lo}..{hi}");
|
||||
|
||||
filtering(&mut s, layer, "bilinearSharp");
|
||||
@@ -87,6 +88,7 @@ fn fills_saved_before_filtering_keep_their_look() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s, 1.0);
|
||||
let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
|
||||
|
||||
assert_eq!(fill.sampling.filtering, Filtering::BilinearHq);
|
||||
|
||||
let mut saved = serde_json::to_value(fill).unwrap();
|
||||
@@ -128,6 +130,7 @@ fn uv_wrap_repeats_the_tile_or_stops_at_its_edge() {
|
||||
set(&mut s, json!({"scale": [4, 2]})).unwrap();
|
||||
let near = |got: f32, want: f32| (got - want).abs() < 0.05;
|
||||
let repeat = shown(&mut s);
|
||||
|
||||
assert!(near(repeat, 1.0), "Repeat covers the band: {repeat}");
|
||||
|
||||
set(&mut s, json!({"wrap": "none"})).unwrap();
|
||||
@@ -186,6 +189,7 @@ fn three_d_projections_take_uv_transformations() {
|
||||
|
||||
set(&mut s, json!({"tiling": [2, 3], "rotation": 45, "uvOffset": [0.25, 0.5]})).unwrap();
|
||||
let Projection::Triplanar { uv, scale, .. } = projection(&s) else { panic!("tri-planar") };
|
||||
|
||||
assert_eq!(uv, UvTransform { tiling: [2.0, 3.0], rotation: 45.0, offset: [0.25, 0.5] });
|
||||
assert_eq!(scale, 1.0, "the world scale is its own param");
|
||||
assert_ne!(snapshot(&mut s), plain, "the UV transformations move the pattern");
|
||||
@@ -214,6 +218,7 @@ fn scale_mode_is_stored_without_changing_the_tiling() {
|
||||
let layer = checker_fill(&mut s, 2.0);
|
||||
execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "physicalSize"})).unwrap();
|
||||
let LayerKind::Fill(fill) = s.doc.project.layer(layer).unwrap().kind.clone() else { panic!("a fill layer") };
|
||||
|
||||
assert_eq!(fill.sampling.scale, ScaleMode::PhysicalSize);
|
||||
assert!(matches!(fill.projection, Projection::Uv { scale: [2.0, 2.0], .. }), "{:?}", fill.projection);
|
||||
|
||||
|
||||
@@ -159,10 +159,14 @@ fn the_contents_reset_puts_back_the_seeds_randomize_seeds_changed_in_one_undo_st
|
||||
assert!(randomized.0 != before.0 && randomized.2 != before.2, "{before:?} -> {randomized:?}");
|
||||
assert!(texturecraft_engine::folder_cmds::contents_changed(&s.doc.project, folder), "the reset is lit");
|
||||
|
||||
// Old projects: the record is saved with the folder and read back
|
||||
let saved = serde_json::to_value(&s.doc.project).unwrap();
|
||||
|
||||
assert!(saved.to_string().contains("randomized"), "the folder keeps its seeds from before in the project");
|
||||
// A saved positional record from before stable seed targets still resets the original slot
|
||||
let mut saved = serde_json::to_value(&s.doc.project).unwrap();
|
||||
let records = saved["layers"][folder.0.to_string()]["kind"]["Group"]["randomized"].as_array_mut().unwrap();
|
||||
assert!(!records.is_empty());
|
||||
for record in records {
|
||||
record.as_object_mut().unwrap().remove("target");
|
||||
}
|
||||
s.doc.project = serde_json::from_value(saved).unwrap();
|
||||
|
||||
let steps = s.history_labels().len();
|
||||
execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap();
|
||||
@@ -201,3 +205,55 @@ fn a_folder_saved_without_randomized_seeds_opens_and_saves_unchanged() {
|
||||
assert!(matches!(&read.kind, LayerKind::Group { randomized, .. } if randomized.is_empty()));
|
||||
assert_eq!(serde_json::to_value(&read).unwrap(), saved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_restores_original_effects_after_a_randomized_effect_is_duplicated() {
|
||||
let (mut session, folder, layer) = folder_with_fill();
|
||||
let original = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.last().unwrap().id;
|
||||
let duplicate = |session: &mut Session| id(execute(session, "effect.duplicate", &json!({"effect": original.0})).unwrap(), "effect");
|
||||
let second = duplicate(&mut session);
|
||||
let seed = |session: &Session, effect| match session.doc.project.effect(effect).unwrap().1.kind {
|
||||
EffectKind::Filter(Filter::Warp { seed, .. }) => seed,
|
||||
_ => panic!("expected warp"),
|
||||
};
|
||||
let before = seed(&session, original);
|
||||
execute(&mut session, "folder.randomizeSeeds", &json!({"layer": folder.0})).unwrap();
|
||||
let copied = duplicate(&mut session);
|
||||
let randomized = seed(&session, copied);
|
||||
|
||||
execute(&mut session, "folder.contents.reset", &json!({"layer": folder.0})).unwrap();
|
||||
|
||||
assert_ne!(randomized, before);
|
||||
assert_eq!(seed(&session, copied), randomized, "the copy was created after randomization");
|
||||
assert_eq!((seed(&session, original), seed(&session, second)), (before, before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contents_controls_follow_an_instanced_folder_without_randomizing_its_source() {
|
||||
let (mut session, source, _) = folder_with_fill();
|
||||
let project = &mut session.doc.project;
|
||||
let folder = project.alloc_id();
|
||||
let instance = project.alloc_id();
|
||||
let new_layer = |id, kind| texturecraft_engine::core::Layer::new(id, "Layer", kind, &Channel::DEFAULT_SET);
|
||||
project.insert_layer(0, new_layer(folder, LayerKind::folder()), None, false).unwrap();
|
||||
project.insert_layer(0, new_layer(instance, LayerKind::Instance { source }), Some(folder), true).unwrap();
|
||||
|
||||
assert!(texturecraft_engine::folder_cmds::has_contents(&session.doc.project, folder));
|
||||
assert_eq!(execute(&mut session, "folder.randomizeSeeds", &json!({"layer": folder.0})).unwrap()["seeds"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copied_folder_resets_only_its_own_randomized_seeds() {
|
||||
let (mut session, folder, fill) = folder_with_fill();
|
||||
let original = fill_seeds(&session, fill);
|
||||
execute(&mut session, "folder.randomizeSeeds", &json!({"layer": folder.0})).unwrap();
|
||||
let changed = fill_seeds(&session, fill);
|
||||
let copy = id(execute(&mut session, "layer.duplicate", &json!({"layer": folder.0})).unwrap(), "layer");
|
||||
let copied_fill = session.doc.project.layers[©].children()[0];
|
||||
|
||||
execute(&mut session, "folder.contents.reset", &json!({"layer": copy.0})).unwrap();
|
||||
|
||||
assert_ne!(original, changed);
|
||||
assert_eq!(fill_seeds(&session, copied_fill), original);
|
||||
assert_eq!(fill_seeds(&session, fill), changed);
|
||||
}
|
||||
@@ -53,7 +53,7 @@ fn a_mask_fill_takes_a_procedural_an_image_an_alpha_or_a_value_as_its_one_graysc
|
||||
assert!(line.iter().any(|value| (value - line[0]).abs() > 1e-3), "the mask follows the pattern: {line:?}");
|
||||
|
||||
// A parameter alone keeps the rest of the pattern
|
||||
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": kind.label(), "contrast": 1.5})).unwrap();
|
||||
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "contrast": 1.5})).unwrap();
|
||||
let Source::Procedural { pattern, .. } = source(&s, effect) else { panic!("not a procedural") };
|
||||
assert_eq!((pattern.scale, pattern.contrast), (4.0, 1.5));
|
||||
|
||||
@@ -91,6 +91,7 @@ fn a_mask_fill_has_no_channels_or_material() {
|
||||
json!({"effect": effect.0, "enabled": false}),
|
||||
json!({"effect": effect.0}),
|
||||
json!({"effect": effect.0, "procedural": "no such pattern"}),
|
||||
json!({"effect": effect.0, "image": "missing.png"}),
|
||||
] {
|
||||
assert!(execute(&mut s, "layer.fill.set", &refused).is_err(), "{refused}");
|
||||
}
|
||||
|
||||
@@ -101,24 +101,32 @@ fn plain_png(level: u8) -> Vec<u8> {
|
||||
|
||||
#[test]
|
||||
fn a_mask_stroke_paints_the_image_it_began_with_when_the_resource_is_replaced_mid_stroke() {
|
||||
let mut session = Session::new_project("Mask image", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap();
|
||||
let layer = LayerId(execute(&mut session, "layer.add.paint", &Value::Null).unwrap()["layer"].as_u64().unwrap());
|
||||
execute(&mut session, "mask.add.white", &json!({"layer": layer.0})).unwrap();
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap();
|
||||
execute(&mut session, "tool.paint", &Value::Null).unwrap();
|
||||
execute(&mut session, "tool.brush", &json!({"size": 40.0, "spacing": 5.0, "hardness": 100})).unwrap();
|
||||
let image = session.import_resource_bytes("brush.png", plain_png(0)).unwrap();
|
||||
execute(&mut session, "tool.material", &json!({"maskImage": image})).unwrap();
|
||||
let (mut session, layer) = masked_layer();
|
||||
let image = session.import_resource_bytes("brush.png", plain_png(255)).unwrap();
|
||||
execute(&mut session, "tool.material", &json!({"maskImage": image, "maskValue": 0.0})).unwrap();
|
||||
|
||||
session.begin_stroke_uv(Vec2::new(0.1, 0.5), 1.0).unwrap();
|
||||
session.continue_stroke_uv(Vec2::new(0.4, 0.5), 1.0);
|
||||
execute(&mut session, "resource.remove", &json!({"name": image})).unwrap();
|
||||
let replaced = session.import_resource_bytes("brush.png", plain_png(255)).unwrap();
|
||||
let replaced = session.import_resource_bytes("brush.png", plain_png(0)).unwrap();
|
||||
session.continue_stroke_uv(Vec2::new(0.9, 0.5), 1.0);
|
||||
session.end_stroke().unwrap();
|
||||
|
||||
assert_eq!(replaced, image, "the white picture took the black one's name");
|
||||
assert_eq!(replaced, image, "the replacement kept the resource name");
|
||||
|
||||
let (left, right) = (mask_at(&session, layer, 0.25, 0.5), mask_at(&session, layer, 0.75, 0.5));
|
||||
assert!(left < 0.05 && right < 0.05, "the whole stroke is black: left {left}, right {right}");
|
||||
assert!(left > 0.95 && right > 0.95, "the whole stroke uses the captured white image: left {left}, right {right}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygon_fill_uses_its_mask_value_while_paint_keeps_its_image() {
|
||||
let (mut session, layer) = masked_layer();
|
||||
let image = session.import_resource_bytes("black.png", plain_png(0)).unwrap();
|
||||
execute(&mut session, "tool.material", &json!({"maskImage": image, "maskValue": 1.0})).unwrap();
|
||||
let uv = Vec2::new(0.27, 0.41);
|
||||
|
||||
session.polygon_fill_uv(uv).unwrap();
|
||||
|
||||
assert!(mask_at(&session, layer, uv.x, uv.y) > 0.95);
|
||||
assert_eq!(session.tool.mask_image.as_ref(), Some(&image));
|
||||
}
|
||||
@@ -133,6 +133,24 @@ fn imports_as_a_linked_fill_with_its_maps() {
|
||||
assert!(s.add_linked_material_bytes_at(b"PK not really", Place::Selection).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_built_in_material_assignment_preserves_a_linked_fill() {
|
||||
let mut session = session();
|
||||
let layer = install(&mut session);
|
||||
let original_link = link(&session, layer);
|
||||
let original_map = map_name(&session, layer, Channel::Roughness);
|
||||
let original_history = session.history_labels();
|
||||
|
||||
for material in [json!("copper_hammered"), Value::Null] {
|
||||
let error = execute(&mut session, "layer.fill.material", &json!({"layer": layer.0, "material": material})).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("linked material"));
|
||||
assert_eq!(link(&session, layer), original_link);
|
||||
assert_eq!(map_name(&session, layer, Channel::Roughness), original_map);
|
||||
assert_eq!(session.history_labels(), original_history);
|
||||
}
|
||||
}
|
||||
|
||||
/// An image marked DirectX keeps the mark when a re-cook replaces it.
|
||||
#[test]
|
||||
fn recooks_keep_the_normal_format_of_a_map() {
|
||||
|
||||
@@ -87,22 +87,24 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() {
|
||||
|
||||
execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap();
|
||||
}
|
||||
|
||||
// A gradient map recolors the content; effect.set edits it and inspect shows it
|
||||
let gm =
|
||||
let gradient_map =
|
||||
id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect");
|
||||
let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0);
|
||||
assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}");
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap();
|
||||
execute(&mut s, "effect.set", &json!({"effect": gradient_map.0, "colors": ["#00ff00"]})).unwrap();
|
||||
|
||||
assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95);
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err());
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": gradient_map.0, "colors": []})).is_err());
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
|
||||
assert!(inspect.contains("GradientMap"), "inspect shows filter parameters");
|
||||
|
||||
execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap();
|
||||
execute(&mut s, "effect.remove", &json!({"effect": gradient_map.0})).unwrap();
|
||||
|
||||
// Posterize on the mask; its steps are clamped
|
||||
let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect");
|
||||
execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap();
|
||||
@@ -110,14 +112,14 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() {
|
||||
assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post)));
|
||||
assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0));
|
||||
|
||||
// Material finishes fill the content's roughness and height
|
||||
// Material finishes also write roughness and height
|
||||
let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect");
|
||||
|
||||
assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin));
|
||||
assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height)));
|
||||
assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err());
|
||||
|
||||
// A directional blur, slope blur and warp composite without trouble on a sphere
|
||||
// Exercise neighbourhood filters on curved geometry
|
||||
for (fid, extra) in [
|
||||
("blurDirectional", json!({"radius": 40, "angle": 45})),
|
||||
("slopeBlur", json!({"radius": 30})),
|
||||
|
||||
@@ -178,6 +178,7 @@ fn a_pattern_scale_edit_leaves_the_mask_fills_projection_alone() {
|
||||
|
||||
let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") };
|
||||
let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection, .. } = &edited.kind else { panic!("the fill reads a pattern") };
|
||||
|
||||
assert_eq!(pattern.scale, 3.0);
|
||||
assert_eq!(*projection, Projection::default(), "the projection keeps its scale");
|
||||
}
|
||||
@@ -206,6 +207,7 @@ fn a_new_procedural_mask_uses_scalar_scale_only_for_the_pattern() {
|
||||
let effect = LayerId(added["effect"].as_u64().unwrap());
|
||||
let (_, effect) = session.doc.project.effect(effect).unwrap();
|
||||
let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection, .. } = &effect.kind else { panic!("expected a procedural mask fill") };
|
||||
|
||||
assert_eq!(pattern.scale, 3.0);
|
||||
assert_eq!(*projection, Projection::default(), "UV placement must not multiply pattern frequency a second time");
|
||||
}
|
||||
|
||||
@@ -183,6 +183,7 @@ fn effects_reading_an_anchor_of_the_mask_follow_it() {
|
||||
EffectKind::Fill { source: Source::Anchor { anchor, .. }, .. } => Some(*anchor),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
assert_eq!(reads, Some(new_anchor), "the fill reads the copied anchor, not the old one");
|
||||
}
|
||||
|
||||
|
||||
@@ -260,7 +260,8 @@ fn panic_hunt() {
|
||||
|
||||
for p in &hostile {
|
||||
let mut s = session();
|
||||
// Match the 256px fixture so empty bake options cannot launch a 2048px bake
|
||||
|
||||
// Match the fixture resolution to avoid a full 2048px bake for each unrelated input
|
||||
for texture_set in &mut s.doc.project.texture_sets {
|
||||
texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R256;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ pub(crate) mod usd;
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use craft_image_codecs::{DecodeOptions, Format, Limits, SampleType, decode_as_with, png_probe};
|
||||
use texturecraft_core::{Channel, NormalFormat};
|
||||
use texturecraft_geom::{Mesh, SubMesh};
|
||||
|
||||
@@ -182,12 +183,25 @@ fn png8_options(preset: ExportPreset, normal: NormalFormat) -> ExportOptions {
|
||||
}
|
||||
|
||||
fn is_black(png: &[u8]) -> bool {
|
||||
image::load_from_memory_with_format(png, image::ImageFormat::Png).map_or(true, |img| img.to_rgb8().iter().all(|v| *v == 0))
|
||||
// Keep the previous PNG decoder's 512 MiB allocation ceiling.
|
||||
let options = DecodeOptions { limits: Limits { max_alloc: 512 << 20, ..Limits::none() }, keep_orientation: true };
|
||||
let Ok(image) = decode_as_with(Format::Png, png, &options) else { return true };
|
||||
let sample = image.sample_type();
|
||||
let layout = image.layout();
|
||||
let pixel_bytes = layout.channels() * sample.bytes();
|
||||
let color_bytes = layout.color_channels() * sample.bytes();
|
||||
let mut colors = image.data().chunks_exact(pixel_bytes).map(|pixel| &pixel[..color_bytes]);
|
||||
match sample {
|
||||
SampleType::U8 => colors.all(|color| color.iter().all(|&value| value == 0)),
|
||||
// The prior RGB8 conversion rounds 16-bit values through 128 to zero.
|
||||
SampleType::U16 => colors.all(|color| color.as_chunks::<2>().0.iter().all(|&value| u16::from_ne_bytes(value) <= 128)),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// PNG color type 4 (gray + alpha) or 6 (RGBA), from the IHDR chunk.
|
||||
fn png_has_alpha(png: &[u8]) -> bool {
|
||||
matches!(png.get(25), Some(4 | 6))
|
||||
png_probe::pixel_model(png).is_ok_and(|model| matches!(model.color_type, 4 | 6))
|
||||
}
|
||||
|
||||
/// The mesh as binary glTF (GLB) named `name`, with `textures[i]` on material `i` (materials
|
||||
@@ -426,6 +440,73 @@ mod tests {
|
||||
assert_eq!((sampler.mag_filter(), sampler.min_filter()), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_png_maps_keep_only_nonblack_color() {
|
||||
let png = |color, samples: &[u8]| {
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
image::write_buffer_with_format(&mut out, samples, 1, 1, color, image::ImageFormat::Png).unwrap();
|
||||
out.into_inner()
|
||||
};
|
||||
let mesh = texturecraft_geom::primitives::cube(1.0);
|
||||
for (bytes, keep) in [
|
||||
(png(image::ColorType::Rgba8, &[0, 0, 0, 255]), false),
|
||||
(png(image::ColorType::Rgba8, &[0, 1, 0, 0]), true),
|
||||
(png(image::ColorType::L16, &128u16.to_ne_bytes()), false),
|
||||
(png(image::ColorType::L16, &129u16.to_ne_bytes()), true),
|
||||
(b"PNG without image data".to_vec(), false),
|
||||
] {
|
||||
let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() };
|
||||
let emissive = file("Emissive.png", &bytes);
|
||||
let textures = GlbTextures::from_files(vec![emissive.clone()]);
|
||||
assert_eq!(textures.emissive.as_deref(), keep.then_some(bytes.as_slice()));
|
||||
let glb = glb_bytes(&mesh, "PNG maps", &[textures]).unwrap();
|
||||
let glb = gltf::Gltf::from_slice(&glb).unwrap();
|
||||
assert_eq!(glb.materials().next().unwrap().emissive_texture().is_some(), keep);
|
||||
|
||||
let roughness = png(image::ColorType::L8, &[64]);
|
||||
let usd_maps = vec![emissive, file("Clearcoat.png", &bytes), file("ClearcoatRoughness.png", &roughness)];
|
||||
let usd = usd_bytes(&mesh, "PNG maps", &[usd_maps], UsdFormat::Usda).unwrap();
|
||||
if keep {
|
||||
assert_eq!(usd.textures.len(), 3);
|
||||
for (suffix, expected) in [("_Emissive.png", &bytes), ("_Clearcoat.png", &bytes), ("_ClearcoatRoughness.png", &roughness)] {
|
||||
let (_, written) = usd.textures.iter().find(|(name, _)| name.ends_with(suffix)).unwrap();
|
||||
assert_eq!(written, expected);
|
||||
}
|
||||
} else {
|
||||
assert!(usd.textures.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_png_alpha_requires_a_png_with_stored_alpha() {
|
||||
let encode = |color: png::ColorType, samples: &[u8], color_key: bool| {
|
||||
let mut output = Vec::new();
|
||||
let mut encoder = png::Encoder::new(&mut output, 1, 1);
|
||||
encoder.set_color(color);
|
||||
if color_key {
|
||||
encoder.set_trns(vec![0; 6]);
|
||||
}
|
||||
let mut writer = encoder.write_header().unwrap();
|
||||
writer.write_image_data(samples).unwrap();
|
||||
writer.finish().unwrap();
|
||||
output
|
||||
};
|
||||
let mut impostor = vec![0; 26];
|
||||
impostor[25] = 6;
|
||||
let mesh = texturecraft_geom::primitives::cube(1.0);
|
||||
for (bytes, expected) in [
|
||||
(encode(png::ColorType::Rgba, &[0, 1, 2, 120], false), gltf::material::AlphaMode::Blend),
|
||||
(encode(png::ColorType::Rgb, &[0, 0, 0], true), gltf::material::AlphaMode::Opaque),
|
||||
(impostor, gltf::material::AlphaMode::Opaque),
|
||||
] {
|
||||
let textures = GlbTextures { base_color: Some(bytes), ..GlbTextures::default() };
|
||||
let glb = glb_bytes(&mesh, "PNG alpha", &[textures]).unwrap();
|
||||
let glb = gltf::Gltf::from_slice(&glb).unwrap();
|
||||
assert_eq!(glb.materials().next().unwrap().alpha_mode(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glb_writes_clearcoat_and_sheen_extensions() {
|
||||
use serde_json::{Value, json};
|
||||
|
||||
+25
-3
@@ -371,14 +371,22 @@ impl Mesh {
|
||||
|
||||
/// Mesh units one UV unit covers on material `m`'s triangles: sqrt(surface area / UV area), None without UV area
|
||||
pub fn uv_density(&self, m: usize) -> Option<f32> {
|
||||
let (mut surface, mut uv_area) = (0.0_f32, 0.0_f32);
|
||||
let (mut surface_area, mut uv_area) = (0.0_f32, 0.0_f32);
|
||||
for [a, b, c] in self.triangles_of(m).filter_map(|t| self.tri(t)) {
|
||||
let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue };
|
||||
let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue };
|
||||
surface += (*pb - *pa).cross(*pc - *pa).length() * 0.5;
|
||||
|
||||
surface_area += (*pb - *pa).cross(*pc - *pa).length() * 0.5;
|
||||
uv_area += (*ub - *ua).perp_dot(*uc - *ua).abs() * 0.5;
|
||||
}
|
||||
(uv_area > f32::EPSILON && surface.is_finite()).then(|| (surface / uv_area).sqrt())
|
||||
|
||||
if !(uv_area > 0.0 && uv_area.is_finite() && surface_area.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// The area ratio can exceed f32 even when its square root fits
|
||||
let density = (f64::from(surface_area) / f64::from(uv_area)).sqrt() as f32;
|
||||
density.is_finite().then_some(density)
|
||||
}
|
||||
|
||||
/// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other
|
||||
@@ -617,6 +625,20 @@ mod tests {
|
||||
assert_eq!(quad().uv_density(1), None, "no triangles of that material");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_positive_uv_area_still_has_a_density() {
|
||||
let mut mesh = quad();
|
||||
let original = mesh.uv_density(0).unwrap();
|
||||
let scale = 0.0001;
|
||||
mesh.uvs.iter_mut().for_each(|uv| *uv *= scale);
|
||||
|
||||
let density = mesh.uv_density(0).unwrap();
|
||||
|
||||
assert!((density * scale - original).abs() < 1e-5);
|
||||
mesh.uvs.fill(Vec2::ZERO);
|
||||
assert!(mesh.uv_density(0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_edges_leave_out_polygon_diagonals() {
|
||||
let mut m = quad();
|
||||
|
||||
@@ -447,6 +447,7 @@ mod tests {
|
||||
// Left half white, right half black (2×1 image, sampled at texel centers)
|
||||
let img = ImageRes::new(2, 1, vec![[1.0; 4], [0.0, 0.0, 0.0, 1.0]], true);
|
||||
let shape = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params: AlphaParams::default(), level: 0 };
|
||||
|
||||
assert!(shape.sample(-0.5, 0.0, 0.5, 0) > 0.99);
|
||||
assert!(shape.sample(0.5, 0.0, 0.5, 0) < 0.01);
|
||||
assert_eq!(shape.sample(1.5, 0.0, 0.5, 0), 0.0);
|
||||
@@ -521,6 +522,7 @@ mod tests {
|
||||
let img = ImageRes::new(1, 1, vec![[1.0; 4]], true);
|
||||
let params = AlphaParams { size_x: 0.5, ..AlphaParams::default() };
|
||||
let image = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params, level: 0 };
|
||||
|
||||
assert_eq!((image.sample(0.4, 0.0, 0.5, 0) > 0.99, image.sample(0.6, 0.0, 0.5, 0)), (true, 0.0));
|
||||
|
||||
let library = crate::alphas::find("square").map(|alpha| alpha.image());
|
||||
|
||||
@@ -462,6 +462,7 @@ mod tests {
|
||||
commit_layer(&mut base, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut Staging::default());
|
||||
commit_mask(&mut base, LayerId(2), (64, 64), &MaskGray::Value(0.5), src(&a, &tiles, 1.0, false), &mut Staging::default());
|
||||
let carried: BTreeMap<Channel, TileImage> = vals.keys().map(|c| (*c, a.clone())).collect();
|
||||
|
||||
// The final unstaged alpha change still belongs in the commit
|
||||
for (erase, carry, stage_last) in [(false, false, true), (true, false, true), (false, false, false), (false, true, true)] {
|
||||
let mut a = a.clone();
|
||||
@@ -486,6 +487,7 @@ mod tests {
|
||||
|
||||
assert_eq!((&staged.layers, &staged.masks), (&plain.layers, &plain.masks), "erase {erase}, carried {carry}, staged last {stage_last}");
|
||||
}
|
||||
|
||||
// The commit must read the current tile when its staged values are stale
|
||||
let mut px = base.clone();
|
||||
let mut staging = Staging::default();
|
||||
|
||||
@@ -390,6 +390,7 @@ mod tests {
|
||||
};
|
||||
let mut pickup = Pickup::from_snapshot(PickupMode::Clone { offset: [i64::from(TILE), 0] }, snapshot, gbuf.clone(), [Channel::Roughness]);
|
||||
let mut alpha = TileImage::new(size, size, 1);
|
||||
|
||||
assert!(pickup.loaded.is_empty());
|
||||
|
||||
for x in [8, 12, TILE + 8] {
|
||||
|
||||
@@ -149,28 +149,30 @@ impl EnvImage {
|
||||
/// range, and images larger than [`MAX_IMPORT_WIDTH`] are box-downsampled. None when the
|
||||
/// pixel count does not match the size.
|
||||
pub fn from_rgba(width: u32, height: u32, rgba: &[[f32; 4]], srgb: bool) -> Option<EnvImage> {
|
||||
Self::from_pixels(width, height, rgba, srgb)
|
||||
Self::from_rgb_pixels(width, height, rgba.par_iter().map(|&[r, g, b, _]| [r, g, b]), srgb)
|
||||
}
|
||||
|
||||
/// An imported linear RGB equirect image, with the same validation and size limits as [Self::from_rgba].
|
||||
pub fn from_linear_rgb(width: u32, height: u32, rgb: &[[f32; 3]]) -> Option<Self> {
|
||||
Self::from_pixels(width, height, rgb, false)
|
||||
/// An equirectangular linear RGB image with the same radiance and size limits as an RGBA import.
|
||||
pub fn from_linear_rgb(width: u32, height: u32, rgb: &[[f32; 3]]) -> Option<EnvImage> {
|
||||
Self::from_rgb_pixels(width, height, rgb.par_iter().copied(), false)
|
||||
}
|
||||
|
||||
fn from_pixels<const COMPONENTS: usize>(width: u32, height: u32, pixels: &[[f32; COMPONENTS]], srgb: bool) -> Option<Self> {
|
||||
if width == 0 || height == 0 || pixels.len() as u64 != width as u64 * height as u64 {
|
||||
fn from_rgb_pixels(width: u32, height: u32, pixels: impl IndexedParallelIterator<Item = [f32; 3]>, srgb: bool) -> Option<EnvImage> {
|
||||
if width == 0 || height == 0 || pixels.len() as u64 != u64::from(width) * u64::from(height) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let lin = |v: f32| {
|
||||
let v = if v.is_finite() { v.clamp(0.0, 65_000.0) } else { 0.0 };
|
||||
if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v }
|
||||
};
|
||||
let data = pixels.par_iter().map(|p| [lin(p[0]), lin(p[1]), lin(p[2])]).collect();
|
||||
let data = pixels.map(|pixel| pixel.map(lin)).collect();
|
||||
let mut img = EnvImage { width, height, data };
|
||||
while img.width > MAX_IMPORT_WIDTH || img.height > MAX_IMPORT_WIDTH {
|
||||
img = img.half();
|
||||
}
|
||||
// The mip chain needs at least 4×2 texels at its last level.
|
||||
|
||||
// The mip chain needs at least 4×2 texels at its last level
|
||||
if img.width < 128 || img.height < 64 {
|
||||
let (w, h) = (img.width.max(128), img.height.max(64));
|
||||
let data = (0..w * h).map(|i| img.sample(dir_of(((i % w) as f32 + 0.5) / w as f32, ((i / w) as f32 + 0.5) / h as f32)).to_array()).collect();
|
||||
|
||||
@@ -762,12 +762,14 @@ fn warmth(img: &Img) -> f32 {
|
||||
fn imported_hdr_environment_lights_the_ball() {
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
let base = render(&mut h, &frame, "env_default");
|
||||
|
||||
// A procedural HDR: a hot orange sky over a dim blue ground (values far above 1)
|
||||
let (w, hh) = (256u32, 128u32);
|
||||
let rgba = (0..w * hh).map(|i| if i / w < hh / 2 { [12.0, 4.0, 1.0, 1.0] } else { [0.02, 0.05, 0.2, 1.0] }).collect();
|
||||
let sky = ImageRes::new(w, hh, rgba, false);
|
||||
h.renderer.set_environment(&h.device, &h.queue, "resource:sky.hdr", Some(&sky));
|
||||
let lit = render(&mut h, &frame, "env_hdr_resource");
|
||||
|
||||
assert_ne!(lit.px, base.px, "the imported environment changes the lighting");
|
||||
assert!(warmth(&lit) > warmth(&base) + 10.0, "the orange sky tints the ball");
|
||||
assert!(lit.mean(200, 100, 280, 180) > 20.0, "lit, finite shading (NaNs would render black)");
|
||||
|
||||
@@ -42,6 +42,7 @@ fn references(project: &Project, anchor: LayerId) -> Vec<Reference> {
|
||||
.into_iter()
|
||||
.filter_map(|(layer_id, effect)| {
|
||||
let layer = project.layers.get(&layer_id)?;
|
||||
let mut name = layer.name.clone();
|
||||
let (kind, glyph) = match effect {
|
||||
None if matches!(layer.kind, LayerKind::Fill(_)) => (n_("Fill"), ic::PAINT_BUCKET),
|
||||
None => return None,
|
||||
@@ -53,6 +54,11 @@ fn references(project: &Project, anchor: LayerId) -> Vec<Reference> {
|
||||
(layer.content_effects.iter().find(|effect| effect.id == effect_id)?, true)
|
||||
};
|
||||
|
||||
if found.name != found.kind.name() {
|
||||
name.push_str(" / ");
|
||||
name.push_str(&found.name);
|
||||
}
|
||||
|
||||
match &found.kind {
|
||||
EffectKind::Fill { .. } | EffectKind::Material(_) if in_content => (n_("Fill"), ic::PAINT_BUCKET),
|
||||
EffectKind::Fill { .. } => (n_("Mask fill"), ic::PAINT_BUCKET),
|
||||
@@ -60,7 +66,7 @@ fn references(project: &Project, anchor: LayerId) -> Vec<Reference> {
|
||||
}
|
||||
}
|
||||
};
|
||||
Some(Reference { layer: layer_id, name: layer.name.clone(), kind, glyph, effect })
|
||||
Some(Reference { layer: layer_id, name, kind, glyph, effect })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -14,8 +14,8 @@ pub(crate) struct PickerState {
|
||||
pub(crate) hsv: [f32; 3],
|
||||
pub(crate) space: ColorSpace,
|
||||
pub(crate) model: ColorModel,
|
||||
/// Height measured while the picker is visible, in points
|
||||
pub(crate) height: Option<f32>,
|
||||
/// Height of the picker outside its resizable colour field, in points
|
||||
pub(crate) fixed_height: Option<f32>,
|
||||
/// Where its title bar's drag left the window's top left corner; None while it stands beside the panel
|
||||
pub(crate) moved_to: Option<egui::Pos2>,
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use egui::{Color32, CornerRadius, Painter, Rect, Stroke, StrokeKind, Ui, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::compose::ImageStore;
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::core::{ColorSelection, LayerId, SelectionBackground};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
@@ -17,7 +17,6 @@ use crate::resource_picker;
|
||||
use crate::resource_picker_item::ResourcePickerItem;
|
||||
use crate::slot_thumbnail::{SlotThumbnail, paint_empty_slot, paint_thumbnail};
|
||||
use crate::theme::Tokens;
|
||||
use crate::thumbs::Thumbs;
|
||||
|
||||
/// Squares on each side of the transparent background's checker
|
||||
const CHECKER_SQUARES: usize = 4;
|
||||
@@ -121,7 +120,7 @@ fn id_mask_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, effect
|
||||
|
||||
// The picker's ids are `Some(name)` for an image and `None` for Import..., so no image chosen is no current tile
|
||||
let current = selection.id_map.clone().map(Some);
|
||||
let tabs = |_: &mut Thumbs| texture_tabs(&app.session.images);
|
||||
let tabs = || texture_tabs(&app.session);
|
||||
match resource_picker::show(&slot.pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs) {
|
||||
Some(None) => crate::menus::invoke(app, &ctx, "resource.import"),
|
||||
Some(Some(name)) if selection.id_map.as_ref() != Some(&name) => {
|
||||
@@ -157,8 +156,8 @@ fn display_bytes(color: [f32; 3]) -> [u8; 3] {
|
||||
}
|
||||
|
||||
/// The ID Mask picker: the project's textures, Import... first; the id is the texture's name, none for Import...
|
||||
fn texture_tabs(images: &ImageStore) -> Vec<PickerTab<Option<String>>> {
|
||||
let textures = ResourcePickerItem::textures(images, None, |name| Some(name.to_owned()));
|
||||
fn texture_tabs(session: &Session) -> Vec<PickerTab<Option<String>>> {
|
||||
let textures = ResourcePickerItem::textures(session, None, |name| Some(name.to_owned()));
|
||||
vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups: vec![PickerGroup { header: Some(tr("Textures")), items: textures }] }]
|
||||
}
|
||||
|
||||
|
||||
+111
-56
@@ -19,6 +19,7 @@ use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_s
|
||||
use crate::past_end::PastEnd;
|
||||
use crate::property_sheet::{PropertySheet, SectionScope};
|
||||
use crate::shelf::{Asset, ShelfDrag};
|
||||
use crate::source_choice::SourceChoice;
|
||||
use crate::state::PropsTab;
|
||||
use crate::theme::{Tokens, caption};
|
||||
use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE};
|
||||
@@ -569,7 +570,8 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?");
|
||||
project.layers.get(&source).map_or_else(|| tr("missing source").to_string(), |source_layer| format!("{} · {set}", source_layer.name))
|
||||
});
|
||||
// Only what the row draws of the mask (whether it is on, its background, its effect count): no clone per row per frame
|
||||
|
||||
// Read just the visible mask summary to avoid cloning every row
|
||||
let mask =
|
||||
project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.as_ref()).map(|mask| (mask.enabled, mask.background, mask.effects.len()));
|
||||
let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel));
|
||||
@@ -1010,7 +1012,7 @@ fn effect_row(
|
||||
let thumbnail = Rect::from_min_size(pos2(content_left + EYE_COLUMN_WIDTH, rect.center().y - preview_size * 0.5), vec2(preview_size, preview_size));
|
||||
let channel = app.ui.layer_channel;
|
||||
|
||||
// A content effect blends each channel on its own: its row shows and sets the displayed channel's blending, as a layer row does
|
||||
// Content rows edit the displayed channel's blend
|
||||
let row_channel = (!in_mask && !app.ui.layer_material_view).then_some(channel);
|
||||
if !thumb_box(ui, app, thumbnail, ThumbTarget::Stage { effect: effect_id, channel }, false) {
|
||||
let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE };
|
||||
@@ -1119,7 +1121,7 @@ fn effect_row(
|
||||
}
|
||||
}
|
||||
|
||||
// One channel's blending (the channel the Layers panel shows) on every channel, or every channel's carried to another effect
|
||||
// Blending options can apply across channels or effects
|
||||
ui.separator();
|
||||
let blends = effect.kind.blends();
|
||||
let copied = app.session.blending_clipboard.is_some();
|
||||
@@ -1134,7 +1136,7 @@ fn effect_row(
|
||||
}
|
||||
};
|
||||
|
||||
// The row's channel lends its blending; a mask effect blends one channel and the Material view shows no channel, so only copy and paste apply there
|
||||
// Mask and Material views have no individual channel to propagate
|
||||
let lends = channel.is_some();
|
||||
item(ui, tr("Use this blend mode on every channel"), "effect.blending.modeToEveryChannel", lends);
|
||||
item(ui, tr("Use this opacity on every channel"), "effect.blending.opacityToEveryChannel", lends);
|
||||
@@ -1783,7 +1785,8 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String {
|
||||
let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) {
|
||||
// Polygon fill keeps its own properties wherever it can fill
|
||||
_ if tool == Tool::PolygonFill && tool_usable => tr(tool.label()).to_string(),
|
||||
// The effect's type, not its own name (every filter reads "Filter")
|
||||
|
||||
// Filters share a title even when the effect is renamed
|
||||
(Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| tr(effect_type_label(&found.kind)).to_string()).unwrap_or_default(),
|
||||
(Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(),
|
||||
(Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(),
|
||||
@@ -1810,13 +1813,19 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
if let Some(tabs) = properties_fill_tabs(app) {
|
||||
crate::property_sheet::section_tabs(ui, scope, 0, &tabs);
|
||||
}
|
||||
let area = egui::ScrollArea::vertical().id_salt(("props", properties_place(app))).auto_shrink([false, false]);
|
||||
crate::property_sheet::in_scope(ui, scope, |ui| properties_scrolled(app, ui, area, PastEnd::Always));
|
||||
|
||||
let selection = properties_selection(app);
|
||||
crate::property_sheet::in_scope(ui, scope, |ui| {
|
||||
let area = egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]);
|
||||
let area = app.properties_scroll.prepare(area, ui.scope_id(), selection);
|
||||
let offset_points = properties_scrolled(app, ui, area, PastEnd::Always);
|
||||
app.properties_scroll.remember(selection, offset_points);
|
||||
});
|
||||
}
|
||||
|
||||
/// What the docked Properties list keeps its own scroll place for: the selected layer and the part of it edited, none for the tool
|
||||
fn properties_place(app: &TextureCraftApp) -> Option<(LayerId, StackTarget)> {
|
||||
// A short panel in between would clamp a shared place back to the top; a greyed tool shows the layer's own sheet
|
||||
/// The layer and target whose scroll offset is shown, or the polygon fill tool's own offset
|
||||
fn properties_selection(app: &TextureCraftApp) -> crate::property_sheet::PropertiesSelection {
|
||||
// Disabled polygon fill shows the selected layer's settings
|
||||
if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) {
|
||||
return None;
|
||||
}
|
||||
@@ -1824,20 +1833,22 @@ fn properties_place(app: &TextureCraftApp) -> Option<(LayerId, StackTarget)> {
|
||||
app.session.selected_layer().map(|layer| (layer, app.session.target))
|
||||
}
|
||||
|
||||
/// The sections in `area`, leaving the solid bar's room even without it, so the bar coming in refits no row (flipped it every frame)
|
||||
pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: egui::ScrollArea, past_end: PastEnd) {
|
||||
/// Draw the sections, reserve room for the scrollbar and return the clamped vertical offset
|
||||
pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: egui::ScrollArea, past_end: PastEnd) -> f32 {
|
||||
let sheet_width = (ui.available_width() - ui.spacing().scroll.allocated_width()).max(0.0);
|
||||
area.show(ui, |ui| {
|
||||
let output = area.show(ui, |ui| {
|
||||
ui.set_max_width(sheet_width);
|
||||
crate::property_sheet::forget_sections(ui);
|
||||
properties_contents(app, ui);
|
||||
|
||||
// Blank space under the rows lets the last section's top reach the top of the list, as the reference panel scrolls
|
||||
// Leave room to align the last section with the top of the list
|
||||
let scrolls = ui.min_rect().height() > ui.clip_rect().height();
|
||||
if past_end == PastEnd::Always || scrolls {
|
||||
ui.add_space(crate::property_sheet::room_past_end(ui));
|
||||
}
|
||||
});
|
||||
|
||||
output.state.clamped_offset().y
|
||||
}
|
||||
|
||||
/// The tabs over the panel when it shows a fill layer's or a mask fill effect's sections, which they jump between
|
||||
@@ -1866,7 +1877,7 @@ fn mask_fill_of(project: &texturecraft_engine::core::Project, effect: LayerId) -
|
||||
}
|
||||
|
||||
/// Room around the Properties rows not yet laid out by the property sheet: the sheet's side padding, so both start under the panel's name
|
||||
const LEGACY_BODY_MARGIN: egui::Margin = egui::Margin::symmetric(crate::property_sheet::PAD as i8, 4);
|
||||
const LEGACY_BODY_MARGIN: egui::Margin = egui::Margin::symmetric(crate::property_sheet::SIDE_PADDING_POINTS as i8, 4);
|
||||
|
||||
/// Lays out `body` with the other panels' margin
|
||||
fn legacy_body(ui: &mut Ui, body: impl FnOnce(&mut Ui)) {
|
||||
@@ -1880,31 +1891,42 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
return;
|
||||
}
|
||||
|
||||
let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned());
|
||||
let selected = app.session.selected_layer();
|
||||
let tool = app.session.tool.tool;
|
||||
let tool_usable = app.session.tool_usable(tool);
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
|
||||
match (&selected, app.session.target) {
|
||||
// Polygon fill shows its own settings and says what it fills into, wherever it can fill
|
||||
match (selected.and_then(|id| app.session.project().layers.get(&id)), app.session.target) {
|
||||
// Polygon fill keeps its own settings on any target it can fill
|
||||
_ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)),
|
||||
(Some(layer), StackTarget::Effect(effect)) if mask_fill_of(&app.session.doc.project, effect).is_some() => mask_fill_properties(app, ui, layer, effect),
|
||||
(Some(layer), StackTarget::Effect(effect)) if mask_fill_of(&app.session.doc.project, effect).is_some() => {
|
||||
let layer_id = layer.id;
|
||||
mask_fill_properties(app, ui, layer_id, effect);
|
||||
}
|
||||
(Some(layer), StackTarget::Effect(effect)) => {
|
||||
effect_properties(app, ui, layer, effect);
|
||||
let snapshot = layer.clone();
|
||||
effect_properties(app, ui, &snapshot, effect);
|
||||
let painted = app.session.doc.project.effect(effect).is_some_and(|(_, effect)| matches!(effect.kind, EffectKind::Paint | EffectKind::Path(_)));
|
||||
if painted && grayscale_tab_open(app) {
|
||||
crate::mask_paint_panel::grayscale_sheet(app, ui);
|
||||
}
|
||||
}
|
||||
(Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer),
|
||||
(Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => {
|
||||
let snapshot = layer.clone();
|
||||
fill_properties(app, ui, &snapshot);
|
||||
}
|
||||
(Some(layer), StackTarget::Content) if layer.is_group() => crate::folder_properties::folder_properties(app, ui, layer.id),
|
||||
(Some(layer), StackTarget::Content) if layer.instance_source().is_some() => crate::instance_properties::instance_properties(app, ui, layer),
|
||||
(Some(layer), StackTarget::Content) if layer.instance_source().is_some() => {
|
||||
let snapshot = layer.clone();
|
||||
crate::instance_properties::instance_properties(app, ui, &snapshot);
|
||||
}
|
||||
(Some(layer), StackTarget::Mask) => {
|
||||
let layer_id = layer.id;
|
||||
legacy_body(ui, |ui| {
|
||||
// Add mask > Height combination took its place; a layer saved with it on can still turn it off here
|
||||
let height_shown = app.session.doc.project.content_layer(layer.id).is_some_and(|content| content.height_mask.enabled);
|
||||
// Saved height masks can still be turned off here
|
||||
let height_shown = app.session.doc.project.content_layer(layer_id).is_some_and(|content| content.height_mask.enabled);
|
||||
if height_shown {
|
||||
height_mask_section(app, ui, layer);
|
||||
height_mask_section(app, ui, layer_id);
|
||||
}
|
||||
if tool_usable {
|
||||
if height_shown {
|
||||
@@ -1930,25 +1952,26 @@ fn grayscale_tab_open(app: &TextureCraftApp) -> bool {
|
||||
}
|
||||
|
||||
/// Mask with height: the layer's height shapes its mask transitions.
|
||||
fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) {
|
||||
let id = layer.id.0;
|
||||
let hm = app.session.doc.project.content_layer(layer.id).map(|l| l.height_mask).unwrap_or_default();
|
||||
fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId) {
|
||||
let height_mask = app.session.project().content_layer(layer).map(|source| source.height_mask).unwrap_or_default();
|
||||
|
||||
section(ui, "sec_height_mask", tr("Mask with height"), true, |ui| {
|
||||
let mut on = hm.enabled;
|
||||
let mut on = height_mask.enabled;
|
||||
if ui
|
||||
.checkbox(&mut on, tr("Combine with the layer's height"))
|
||||
.on_hover_text(tr("Partial mask values follow the layer's height: high parts show first"))
|
||||
.changed()
|
||||
{
|
||||
app.run("layer.set", json!({"layer": id, "heightMask": {"enabled": on}}));
|
||||
app.run("layer.set", json!({"layer": layer.0, "heightMask": {"enabled": on}}));
|
||||
}
|
||||
ui.add_enabled_ui(hm.enabled, |ui| {
|
||||
let (mut contrast, mut offset) = (hm.contrast, hm.offset);
|
||||
|
||||
ui.add_enabled_ui(height_mask.enabled, |ui| {
|
||||
let (mut contrast, mut offset) = (height_mask.contrast, height_mask.offset);
|
||||
if let Some(merge) = slider_edit(ui, tr("Contrast"), &mut contrast, 0.0..=16.0, 2) {
|
||||
app.run("layer.set", json!({"layer": id, "heightMask": {"contrast": contrast}, "merge": merge}));
|
||||
app.run("layer.set", json!({"layer": layer.0, "heightMask": {"contrast": contrast}, "merge": merge}));
|
||||
}
|
||||
if let Some(merge) = slider_edit(ui, tr("Height offset"), &mut offset, -1.0..=1.0, 2) {
|
||||
app.run("layer.set", json!({"layer": id, "heightMask": {"offset": offset}, "merge": merge}));
|
||||
app.run("layer.set", json!({"layer": layer.0, "heightMask": {"offset": offset}, "merge": merge}));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1999,13 +2022,26 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let stroke_width = (brush.size / PREVIEW_SIZE_UNIT * PREVIEW_STROKE_WIDTH_SCALE).clamp(*PREVIEW_STROKE_WIDTH.start(), *PREVIEW_STROKE_WIDTH.end());
|
||||
let alpha = (brush.flow * brush.opacity * 255.0) as u8;
|
||||
|
||||
// A mask stroke shows the gray it lays down and no material
|
||||
let gray = match (content, &app.session.tool.mask_image) {
|
||||
(false, None) => (app.session.tool.mask_value.clamp(0.0, 1.0) * 255.0).round() as u8,
|
||||
_ => u8::MAX,
|
||||
let preview_stroke = |gray: f32| {
|
||||
let gray = (gray.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
Stroke::new(stroke_width, Color32::from_rgba_unmultiplied(gray, gray, gray, alpha.max(PREVIEW_STROKE_MIN_ALPHA)))
|
||||
};
|
||||
let stroke_color = Color32::from_rgba_unmultiplied(gray, gray, gray, alpha.max(PREVIEW_STROKE_MIN_ALPHA));
|
||||
painter.add(egui::Shape::line(points, Stroke::new(stroke_width, stroke_color)));
|
||||
|
||||
// Sample image-backed masks along the preview stroke
|
||||
let gray = if content { texturecraft_engine::compose::MaskGray::Value(1.0) } else { app.session.mask_gray() };
|
||||
match gray {
|
||||
texturecraft_engine::compose::MaskGray::Value(value) => {
|
||||
painter.add(egui::Shape::line(points, preview_stroke(value)));
|
||||
}
|
||||
texturecraft_engine::compose::MaskGray::Image { .. } => {
|
||||
let size = PREVIEW_STROKE_STEPS as u32;
|
||||
for (index, segment) in points.windows(2).enumerate() {
|
||||
let value = gray.at(index as u32, size / 2, (size, size));
|
||||
painter.line_segment([segment[0], segment[1]], preview_stroke(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if content {
|
||||
let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR);
|
||||
|
||||
@@ -2259,7 +2295,7 @@ fn polygon_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.label(caption(&tr("Grayscale").to_uppercase()));
|
||||
let mut gray = app.session.tool.mask_value;
|
||||
if slider(ui, tr("Value"), &mut gray, 0.0..=1.0, 2).changed() {
|
||||
app.session.tool.mask_value = gray;
|
||||
app.run("tool.material", json!({"maskValue": gray}));
|
||||
}
|
||||
}
|
||||
Err(note) => {
|
||||
@@ -2770,12 +2806,12 @@ pub(crate) fn anchors_below(project: &texturecraft_engine::core::Project, reader
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Anchor choices for an effect, valid for its owner and recorded below the displayed instance
|
||||
/// Anchor choices valid below both the effect's owner and its displayed instance
|
||||
pub(crate) fn effect_anchors_below(app: &TextureCraftApp, layer: LayerId, effect: LayerId) -> Vec<(LayerId, String)> {
|
||||
project_effect_anchors_below(&app.session.doc.project, layer, effect)
|
||||
}
|
||||
|
||||
/// [`effect_anchors_below`] in `project`
|
||||
/// Anchor choices for the Properties source picker
|
||||
pub(crate) fn project_effect_anchors_below(project: &texturecraft_engine::core::Project, layer: LayerId, effect: LayerId) -> Vec<(LayerId, String)> {
|
||||
let owner = project.effect(effect).map_or(layer, |(owner, _)| owner);
|
||||
let owner_anchors = anchors_below(project, owner);
|
||||
@@ -2829,7 +2865,7 @@ pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Chan
|
||||
}
|
||||
|
||||
/// A mask fill effect: its Fill, Symmetry and Grayscale sections as one sheet (its blending is on its row)
|
||||
fn mask_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) {
|
||||
fn mask_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer_id: LayerId, effect_id: LayerId) {
|
||||
let Some((source, projection, sampling)) =
|
||||
mask_fill_of(&app.session.doc.project, effect_id).map(|(source, projection, sampling)| (source.clone(), projection.clone(), sampling))
|
||||
else {
|
||||
@@ -2837,7 +2873,7 @@ fn mask_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, e
|
||||
};
|
||||
|
||||
PropertySheet::show(ui, ("mask_fill_sheet", effect_id.0), |sheet| {
|
||||
crate::mask_fill_panel::mask_fill_sheet(app, sheet, effect_id, source, projection, sampling, layer.id);
|
||||
crate::mask_fill_panel::mask_fill_sheet(app, sheet, effect_id, source, projection, sampling, layer_id);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3065,23 +3101,42 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe
|
||||
EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| {
|
||||
ui.label(caption(tr("Fill")));
|
||||
let anchors = effect_anchors_below(app, layer.id, effect_id);
|
||||
let current = match source {
|
||||
let name = match source {
|
||||
Source::Anchor { anchor, channel, .. } => anchor_label(app, *anchor, *channel),
|
||||
Source::Uniform(_) => tr("Uniform value").to_string(),
|
||||
Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(),
|
||||
Source::Image { name, .. } => trf("Image: {name}", &[("name", name)]),
|
||||
};
|
||||
let source_response = combo(ui, tr("Source"), current, |ui| {
|
||||
if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "value": 1.0}));
|
||||
}
|
||||
if let Some(anchor) = anchor_entries(ui, &anchors, source.anchor()) {
|
||||
app.run("effect.set", json!({"effect": id, "anchor": anchor.0}));
|
||||
}
|
||||
if let Some(name) = image_menu(app, ui) {
|
||||
app.run("effect.set", json!({"effect": id, "image": name}));
|
||||
}
|
||||
|
||||
let (rect, source_response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::filter_slot::SLOT_HEIGHT), Sense::click());
|
||||
source_response.widget_info(|| egui::WidgetInfo {
|
||||
current_text_value: Some(name.clone()),
|
||||
..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, tr("Grayscale"))
|
||||
});
|
||||
let (ctx, popup) = (ui.ctx().clone(), ui.make_persistent_id(("fill_source_picker", id)));
|
||||
if source_response.clicked() {
|
||||
crate::resource_picker::toggle(&ctx, popup);
|
||||
}
|
||||
let highlighted = source_response.hovered() || egui::Popup::is_id_open(&ctx, popup);
|
||||
crate::filter_slot::paint(ui, rect, (highlighted, source_response.has_focus()), None, (tr("Grayscale"), &name));
|
||||
let current = crate::fill_material_panel::source_choice(&app.session, source);
|
||||
let tabs = || crate::fill_material_panel::source_tabs(&app.session, &anchors, Color32::from_gray(204), false);
|
||||
let picked = crate::resource_picker::show(&source_response, popup, &mut app.thumbs, Some(¤t), current != SourceChoice::Uniform, tabs);
|
||||
let anchor_channel = if let Source::Anchor { channel, .. } = source { *channel } else { Channel::Height };
|
||||
let params = match picked.filter(|choice| *choice != current) {
|
||||
Some(SourceChoice::Procedural(kind)) => Some(json!({"effect": id, "procedural": kind.label()})),
|
||||
Some(SourceChoice::Image(image)) => Some(json!({"effect": id, "image": image})),
|
||||
Some(SourceChoice::Uniform) => Some(json!({"effect": id, "value": 1.0})),
|
||||
Some(SourceChoice::Anchor(anchor)) => Some(json!({"effect": id, "anchor": anchor.0, "anchorChannel": anchor_channel.id()})),
|
||||
Some(SourceChoice::Import) => {
|
||||
crate::menus::invoke(app, &ctx, "resource.import");
|
||||
None
|
||||
}
|
||||
Some(SourceChoice::Alpha(_)) | None => None,
|
||||
};
|
||||
if let Some(params) = params {
|
||||
app.run("effect.set", params);
|
||||
}
|
||||
|
||||
// The source selector accepts image drops from the Assets panel
|
||||
if let Some(name) = image_drop(ui, &source_response.interact(Sense::hover())) {
|
||||
|
||||
@@ -166,7 +166,7 @@ pub fn default_workspace() -> Workspace {
|
||||
const VIEWPORT_SPLIT_RATIO: f32 = 0.80;
|
||||
const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125;
|
||||
|
||||
// Layers' share under the texture sets: Properties' 69% shows a fill down to its channels, Layers keeps three rows
|
||||
// Leave room for three layer rows and the fill's channel controls
|
||||
const LAYERS_SPLIT_RATIO: f32 = 0.31;
|
||||
|
||||
let column = split(
|
||||
@@ -419,6 +419,9 @@ const TAB_TEXT_SIZE: f32 = 12.5;
|
||||
/// Narrowest panel tab, in points
|
||||
const MIN_TAB_WIDTH: f32 = 54.0;
|
||||
|
||||
/// Mixing in title ink keeps the light dock's focus outline above 3:1 on both header surfaces
|
||||
const LIGHT_DOCK_ACCENT_TEXT_MIX: f32 = 0.2;
|
||||
|
||||
/// The dock look: every panel group is a card under one chrome-coloured header bar, names in capitals at the left, a close × at the right
|
||||
fn style(ui: &Ui, tokens: &Tokens) -> DockStyle {
|
||||
let mut dock_style = DockStyle::from_ui(ui);
|
||||
@@ -428,12 +431,12 @@ fn style(ui: &Ui, tokens: &Tokens) -> DockStyle {
|
||||
dock_style.background = tokens.panel;
|
||||
dock_style.tab_background = tokens.chrome;
|
||||
|
||||
// The shown and the hovered tab keep the bar's colour; their names brighten instead
|
||||
// The selected title is brighter while the strip keeps its colour
|
||||
dock_style.active_background = tokens.chrome;
|
||||
dock_style.text = tokens.text_strong;
|
||||
dock_style.inactive_text = tokens.text_dim;
|
||||
dock_style.border = egui::Stroke::NONE;
|
||||
dock_style.accent = tokens.accent;
|
||||
dock_style.accent = if tokens.dark { tokens.accent } else { tokens.accent.lerp_to_gamma(tokens.text_strong, LIGHT_DOCK_ACCENT_TEXT_MIX) };
|
||||
dock_style.floating_background = tokens.panel;
|
||||
dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border);
|
||||
|
||||
@@ -477,10 +480,11 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
if let Some(panel) = app.ui.dock.raise.take() {
|
||||
area = area.raise_panel(panel);
|
||||
}
|
||||
let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens, style: style.clone() });
|
||||
|
||||
let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens, layout: &layout, style: &style });
|
||||
crate::rail_popup::hand_drag_to_dock(&context, area_id());
|
||||
|
||||
// After the dock, which records the viewport the popup reaches into, and before a changed layout returns early
|
||||
// The popup needs the viewport the dock recorded this frame
|
||||
crate::rail_popup::show(app, &context);
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -518,7 +522,8 @@ fn header_closes(active: &Panel, floating: bool) -> bool {
|
||||
struct Panels<'a> {
|
||||
app: &'a mut TextureCraftApp,
|
||||
tokens: Tokens,
|
||||
style: DockStyle,
|
||||
layout: &'a Layout<Panel>,
|
||||
style: &'a DockStyle,
|
||||
}
|
||||
|
||||
/// Room between a panel's edges and its contents
|
||||
@@ -603,7 +608,7 @@ impl DockContent<Panel> for Panels<'_> {
|
||||
let name = logical.to_uppercase();
|
||||
let font = crate::theme::semibold(HEADER_TITLE_SIZE);
|
||||
|
||||
// Menus list the panels by these names too, in popups; only a header bar's names, docked or floating, centre on its band
|
||||
// Popup menu rows use their unpadded text metrics
|
||||
if matches!(ui.layer_id().order, egui::Order::Foreground | egui::Order::Tooltip) {
|
||||
return RichText::new(name).font(font).color(color).into();
|
||||
}
|
||||
@@ -636,7 +641,7 @@ impl DockContent<Panel> for Panels<'_> {
|
||||
return;
|
||||
}
|
||||
|
||||
// On the names' line: the middle of the header band
|
||||
// Centre the close control on the header title line
|
||||
let rect = ui.max_rect();
|
||||
let button = egui::Rect::from_center_size(
|
||||
egui::pos2(rect.right() - HEADER_CLOSE_RIGHT_MARGIN - HEADER_CLOSE_SIZE / 2.0, rect.center().y - self.header_lift(*active)),
|
||||
@@ -686,14 +691,15 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn default_workspace_has_every_panel_and_is_valid() {
|
||||
let w = default_workspace();
|
||||
assert!(validate(&w).is_ok());
|
||||
let workspace = default_workspace();
|
||||
|
||||
assert!(validate(&workspace).is_ok());
|
||||
|
||||
for panel in Panel::ALL {
|
||||
assert!(w.layout.contains(&panel) || w.hidden.iter().any(|(p, _)| *p == panel), "{panel:?} is neither shown nor hidden");
|
||||
assert!(workspace.layout.contains(&panel) || workspace.hidden.iter().any(|(hidden, _)| *hidden == panel), "{panel:?} is neither shown nor hidden");
|
||||
}
|
||||
|
||||
assert_eq!(panels_of(&w), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]);
|
||||
assert_eq!(panels_of(&workspace), [Panel::Assets, Panel::Viewport, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, Panel::Properties]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! A docked header's band: the tab strip plus the gutter above it, less a hairline of separation, with the names' capitals centred on it
|
||||
//! Positions dock tab titles within the tab strip and the gutter above it.
|
||||
|
||||
use craft_ui::docking::{Layout, Node};
|
||||
use craft_ui::layout::SplitAxis;
|
||||
@@ -7,50 +7,42 @@ use egui::{Align, Color32, FontId, Ui};
|
||||
|
||||
use super::Panel;
|
||||
|
||||
/// Gutter between two stacked panels left showing between the upper panel and the header band under it, as the reference keeps a dark line there
|
||||
const PANEL_SEPARATION: f32 = 2.0;
|
||||
/// Gap left between a header band and the panel above it, in points.
|
||||
const HEADER_SEPARATION: f32 = 2.0;
|
||||
|
||||
/// How far a header under another panel reaches above its tab strip: the gutter between them, less the separation
|
||||
pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - PANEL_SEPARATION;
|
||||
pub(super) const HEADER_RISE: f32 = crate::theme::GUTTER as f32 - HEADER_SEPARATION;
|
||||
|
||||
/// Whether `panel`'s docked group sits under another panel, a gutter above its header; floating groups and the top row have none
|
||||
pub(super) fn under_a_panel(layout: &Layout<Panel>, panel: Panel) -> bool {
|
||||
let Some(root) = &layout.root else { return false };
|
||||
layout.root.as_ref().and_then(|node| group_is_below_panel(node, panel, false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
let mut nodes: Vec<(&Node<Panel>, bool)> = vec![(root, false)];
|
||||
while let Some((node, below)) = nodes.pop() {
|
||||
match node {
|
||||
Node::Split { axis, first, second, .. } => {
|
||||
nodes.push((first, below));
|
||||
nodes.push((second, below || *axis == SplitAxis::Vertical));
|
||||
}
|
||||
Node::Tabs { panels, .. } if panels.contains(&panel) => return below,
|
||||
Node::Dock { columns, .. } => {
|
||||
for column in columns {
|
||||
if let Some(index) = column.groups.iter().position(|group| group.panels.contains(&panel)) {
|
||||
return below || index > 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
fn group_is_below_panel(node: &Node<Panel>, panel: Panel, below_panel: bool) -> Option<bool> {
|
||||
match node {
|
||||
Node::Split { axis, first, second, .. } => {
|
||||
group_is_below_panel(second, panel, below_panel || *axis == SplitAxis::Vertical).or_else(|| group_is_below_panel(first, panel, below_panel))
|
||||
}
|
||||
Node::Tabs { panels, .. } if panels.contains(&panel) => Some(below_panel),
|
||||
Node::Dock { columns, .. } => {
|
||||
columns.iter().find_map(|column| column.groups.iter().position(|group| group.panels.contains(&panel))).map(|index| below_panel || index > 0)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// `name` laid out so that, centred as the dock centres every name, its capitals' middle sits `lift` above the strip's (a galley's height counts descenders)
|
||||
pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lift: f32) -> LayoutJob {
|
||||
pub(super) fn header_name(ui: &Ui, name: &str, font: FontId, color: Color32, lift_points: f32) -> LayoutJob {
|
||||
let format = TextFormat { font_id: font, color, valign: Align::TOP, ..Default::default() };
|
||||
let mut job = LayoutJob::single_section(name.to_owned(), format);
|
||||
let galley = ui.painter().layout_job(job.clone());
|
||||
|
||||
// The first capital's ink; a name without one (a script without capitals) keeps the galley's middle
|
||||
// Scripts without capitals use the whole galley as their ink bounds
|
||||
let capital = galley.rows.first().and_then(|row| row.glyphs.iter().find(|glyph| glyph.chr.is_uppercase()).map(|glyph| (row.pos.y, glyph)));
|
||||
let ink_middle = capital.map_or(galley.size().y / 2.0, |(row_top, glyph)| row_top + glyph.pos.y + glyph.uv_rect.offset.y + glyph.uv_rect.size.y / 2.0);
|
||||
|
||||
// Room below the name raises it when centred, room above lowers it
|
||||
let shift = ink_middle - galley.size().y / 2.0 + lift;
|
||||
let shift = ink_middle - galley.size().y / 2.0 + lift_points;
|
||||
if shift < 0.0
|
||||
&& let Some(section) = job.sections.first_mut()
|
||||
{
|
||||
|
||||
@@ -1,106 +1,101 @@
|
||||
//! The shown tab of a docked panel group, drawn as the Properties section tabs draw theirs: a raised box joined to the panel's body
|
||||
//! The active tab in a panel group, drawn as a raised box joined to the panel body
|
||||
|
||||
use craft_ui::docking::{DockContent, Layout, Node};
|
||||
use craft_ui::docking::{DockContent, Node};
|
||||
use egui::text::TextWrapping;
|
||||
use egui::{Rect, Ui, pos2};
|
||||
use egui::{Rect, Stroke, StrokeKind, Ui, pos2};
|
||||
|
||||
use super::header_band::{HEADER_RISE, header_name, under_a_panel};
|
||||
use super::{HEADER_TITLE_SIZE, Panel, Panels};
|
||||
use super::{HEADER_TITLE_SIZE, Panel, Panels, area_id};
|
||||
use crate::property_sheet::{full_height_tab_rect, shown_tab_box};
|
||||
use crate::theme::semibold;
|
||||
|
||||
/// Room the dock leaves around a tab's name, half on each side (craft-ui's dock renderer keeps its own copy private)
|
||||
/// Horizontal padding of craft-ui's dock tab, in points
|
||||
const DOCK_TAB_PADDING: f32 = 24.0;
|
||||
|
||||
/// From a panel's left edge to its header's name
|
||||
pub(crate) const HEADER_TITLE_LEFT: f32 = DOCK_TAB_PADDING / 2.0;
|
||||
|
||||
/// Width of the dock's "…" button for the tabs that do not fit (private in craft-ui's dock renderer as well)
|
||||
const OVERFLOW_WIDTH: f32 = 22.0;
|
||||
/// Gap between the active tab's box and its neighbours, in points
|
||||
const TAB_BOX_INSET: f32 = 4.0;
|
||||
|
||||
/// Room between a tab's box and its neighbouring tabs; the first tab's box starts on the panel's left edge
|
||||
const BOX_INSET: f32 = 4.0;
|
||||
/// Insets the focus outline inside the tab's actual hit rect
|
||||
const TAB_FOCUS_INSET: f32 = 2.0;
|
||||
|
||||
/// The panels of the group holding `panel` and whether that group floats; a collapsed stack has no tabs
|
||||
fn group_of(layout: &Layout<Panel>, panel: Panel) -> Option<(&[Panel], bool)> {
|
||||
let docked = layout.root.iter().map(|root| (root, false));
|
||||
let floating = layout.floating.iter().map(|window| (&window.root, true));
|
||||
let mut nodes: Vec<(&Node<Panel>, bool)> = docked.chain(floating).collect();
|
||||
/// Width of the focus outline in points
|
||||
const TAB_FOCUS_STROKE_WIDTH: f32 = 1.0;
|
||||
|
||||
while let Some((node, floats)) = nodes.pop() {
|
||||
match node {
|
||||
Node::Split { first, second, .. } => {
|
||||
nodes.push((first, floats));
|
||||
nodes.push((second, floats));
|
||||
}
|
||||
Node::Tabs { panels, .. } if panels.contains(&panel) => return Some((panels, floats)),
|
||||
Node::Dock { columns, .. } => {
|
||||
let group = columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel));
|
||||
if let Some(group) = group {
|
||||
return Some((&group.panels, floats));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
/// The tab group containing `panel`; a collapsed stack has no tabs
|
||||
fn group_of(node: &Node<Panel>, panel: Panel) -> Option<&[Panel]> {
|
||||
match node {
|
||||
Node::Split { first, second, .. } => group_of(first, panel).or_else(|| group_of(second, panel)),
|
||||
Node::Tabs { panels, .. } if panels.contains(&panel) => Some(panels),
|
||||
Node::Dock { columns, .. } => {
|
||||
columns.iter().flat_map(|column| &column.groups).find(|group| group.panels.contains(&panel)).map(|group| group.panels.as_slice())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
impl Panels<'_> {
|
||||
/// How far `panel`'s header band reaches above its tab strip: the gutter above it, under another panel
|
||||
/// How far a header band reaches above its tab strip
|
||||
fn header_rise(&self, panel: Panel) -> f32 {
|
||||
if under_a_panel(&self.app.ui.dock.workspace.layout, panel) { HEADER_RISE } else { 0.0 }
|
||||
if under_a_panel(self.layout, panel) { HEADER_RISE } else { 0.0 }
|
||||
}
|
||||
|
||||
/// How far `panel`'s header name sits above its tab strip's middle: on its header band's middle
|
||||
/// How far a header name sits above the tab strip's centre
|
||||
pub(super) fn header_lift(&self, panel: Panel) -> f32 {
|
||||
self.header_rise(panel) / 2.0
|
||||
}
|
||||
|
||||
/// Over the tab the dock drew for `panel`, the panel shown in its group, paints the section tabs' raised box and the name again; a panel alone keeps its plain header. `ui` is the panel's body, right under the strip
|
||||
/// Paints the active tab and its focus outline above the renderer's fallback paint
|
||||
pub(super) fn paint_shown_group_tab(&self, ui: &Ui, panel: Panel) {
|
||||
let Some((panels, floating)) = group_of(&self.app.ui.dock.workspace.layout, panel) else { return };
|
||||
|
||||
if panels.len() < 2 {
|
||||
let layout = self.layout;
|
||||
let in_group = layout
|
||||
.root
|
||||
.iter()
|
||||
.chain(layout.floating.iter().map(|window| &window.root))
|
||||
.find_map(|root| group_of(root, panel))
|
||||
.is_some_and(|group| group.len() > 1);
|
||||
if !in_group {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(shown) = panels.iter().position(|member| *member == panel) else { return };
|
||||
|
||||
// The dock's own tab layout: names at their natural width, shrunk or moved to "…" when the strip is short
|
||||
// The shared renderer submits the active tab before it calls the panel body
|
||||
let tab_id = area_id().with(("tab", &panel));
|
||||
let Some(tab) = ui.ctx().read_response(tab_id) else { return };
|
||||
let body = ui.max_rect();
|
||||
let strip = Rect::from_min_max(pos2(body.left(), body.top() - self.style.tab_height), pos2(body.right(), body.top()));
|
||||
let band = Rect::from_x_y_ranges(strip.x_range(), strip.top() - self.header_rise(panel)..=strip.bottom());
|
||||
let font = semibold(HEADER_TITLE_SIZE);
|
||||
let names: Vec<String> = panels.iter().map(|member| self.logical_label(member).to_uppercase()).collect();
|
||||
let natural: Vec<f32> =
|
||||
names.iter().map(|name| ui.painter().layout_no_wrap(name.clone(), font.clone(), self.style.text).size().x + DOCK_TAB_PADDING).collect();
|
||||
let header = self.group_header_width(panels, &panel, floating, strip.width()).clamp(0.0, strip.width());
|
||||
let available = (strip.width() - header - self.style.drag_bar_width).max(0.0);
|
||||
let fit = craft_ui::tabs::fit(&natural, shown, available, self.style.min_tab_width, OVERFLOW_WIDTH);
|
||||
|
||||
let mut left = strip.left();
|
||||
for (index, width) in fit.shown {
|
||||
if index != shown {
|
||||
left += width;
|
||||
continue;
|
||||
}
|
||||
|
||||
// The body's clip stops at the strip, which the box rises into up to the band's top
|
||||
let clip = ui.clip_rect();
|
||||
let mut painter = ui.painter().clone();
|
||||
painter.set_clip_rect(Rect::from_x_y_ranges(clip.x_range(), band.top()..=clip.bottom()));
|
||||
let box_left = if left > strip.left() { left + BOX_INSET } else { left };
|
||||
shown_tab_box(&painter, &self.tokens, full_height_tab_rect(band, box_left, left + width - BOX_INSET));
|
||||
|
||||
let Some(name) = names.get(index) else { return };
|
||||
let mut job = header_name(ui, name, font, self.style.text, self.header_lift(panel));
|
||||
job.wrap = TextWrapping::truncate_at_width((width - DOCK_TAB_PADDING).max(0.0));
|
||||
let galley = painter.layout_job(job);
|
||||
let at = pos2(left + HEADER_TITLE_LEFT, strip.center().y - galley.size().y / 2.0);
|
||||
painter.galley(at, galley, self.style.text);
|
||||
let tab_rect = tab.rect;
|
||||
if tab.layer_id != ui.layer_id() || tab_rect.bottom() != body.top() || tab_rect.left() < body.left() || tab_rect.right() > body.right() {
|
||||
return;
|
||||
}
|
||||
|
||||
let band_top = tab_rect.top() - self.header_rise(panel);
|
||||
let box_left = if tab_rect.left() > body.left() { tab_rect.left() + TAB_BOX_INSET } else { tab_rect.left() };
|
||||
let box_right = tab_rect.right() - TAB_BOX_INSET;
|
||||
if box_left >= box_right {
|
||||
return;
|
||||
}
|
||||
|
||||
// Extend the body's clip over the header without widening it
|
||||
let clip = ui.clip_rect();
|
||||
let mut painter = ui.painter().clone();
|
||||
painter.set_clip_rect(Rect::from_x_y_ranges(clip.x_range(), band_top..=clip.bottom()));
|
||||
let band = Rect::from_x_y_ranges(body.x_range(), band_top..=tab_rect.bottom());
|
||||
shown_tab_box(&painter, &self.tokens, full_height_tab_rect(band, box_left, box_right));
|
||||
|
||||
let name = self.logical_label(&panel).to_uppercase();
|
||||
let font = semibold(HEADER_TITLE_SIZE);
|
||||
let mut job = header_name(ui, &name, font, self.style.text, (tab_rect.top() - band_top) / 2.0);
|
||||
job.wrap = TextWrapping::truncate_at_width((tab_rect.width() - DOCK_TAB_PADDING).max(0.0));
|
||||
let galley = painter.layout_job(job);
|
||||
let at = pos2(tab_rect.left() + HEADER_TITLE_LEFT, tab_rect.center().y - galley.size().y / 2.0);
|
||||
painter.galley(at, galley, self.style.text);
|
||||
|
||||
// Preserve the shared dock's keyboard focus ring above the opaque selected tab
|
||||
let pointer_focus = ui.data(|data| data.get_temp::<bool>(tab_id.with("pointer-focus"))).unwrap_or(false);
|
||||
let focus_rect = tab_rect.shrink(TAB_FOCUS_INSET);
|
||||
if tab.has_focus() && !pointer_focus && focus_rect.is_positive() {
|
||||
painter.rect_stroke(focus_rect, 0.0, Stroke::new(TAB_FOCUS_STROKE_WIDTH, self.style.accent), StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use super::{Point, invert, pipette};
|
||||
|
||||
/// The largest side an icon is rendered at, in pixels
|
||||
const MAX_SIDE: u32 = 256;
|
||||
|
||||
/// An icon drawn in code: rendered once per pixel size into a white texture and tinted where it is drawn, so it is as sharp as a font glyph at any scale
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum DrawnIcon {
|
||||
/// The eyedropper: a pipette, tip at the bottom left
|
||||
Pipette,
|
||||
/// A square half clear, half solid, an arrow out of each half
|
||||
Invert,
|
||||
}
|
||||
|
||||
impl DrawnIcon {
|
||||
/// The distance from `point` (in the icon's unit square, y down) to the icon's ink, negative inside
|
||||
pub(crate) fn distance(self, point: Point) -> f32 {
|
||||
match self {
|
||||
DrawnIcon::Pipette => pipette::glyph(point),
|
||||
DrawnIcon::Invert => invert::glyph(point),
|
||||
}
|
||||
}
|
||||
|
||||
/// How much of each pixel the icon covers when it is `side` pixels square, rows top first
|
||||
pub(crate) fn coverage(self, side: u32) -> Vec<u8> {
|
||||
let scale = side as f32;
|
||||
(0..side * side)
|
||||
.map(|index| {
|
||||
let point = [((index % side) as f32 + 0.5) / scale, ((index / side) as f32 + 0.5) / scale];
|
||||
((0.5 - self.distance(point) * scale).clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Draws the icon `size` points square centred on `center` in `color`, on whole screen pixels
|
||||
pub(crate) fn paint(self, painter: &egui::Painter, center: egui::Pos2, size: f32, color: egui::Color32) {
|
||||
let pixels_per_point = painter.ctx().pixels_per_point();
|
||||
let side = ((size * pixels_per_point).round() as u32).clamp(1, MAX_SIDE);
|
||||
let pixels = side as f32;
|
||||
let min = ((center.to_vec2() * pixels_per_point) - egui::Vec2::splat(pixels / 2.0)).round() / pixels_per_point;
|
||||
let rect = egui::Rect::from_min_size(min.to_pos2(), egui::Vec2::splat(pixels / pixels_per_point));
|
||||
|
||||
let whole = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0));
|
||||
painter.image(self.texture(painter.ctx(), side).id(), rect, whole, color);
|
||||
}
|
||||
|
||||
/// The icon `side` pixels square as a white texture with its coverage as alpha, rendered once per size
|
||||
fn texture(self, ctx: &egui::Context, side: u32) -> egui::TextureHandle {
|
||||
let id = egui::Id::unique(("drawn_icon", self, side));
|
||||
|
||||
if let Some(texture) = ctx.data(|data| data.get_temp::<egui::TextureHandle>(id)) {
|
||||
return texture;
|
||||
}
|
||||
|
||||
let rgba: Vec<u8> = self.coverage(side).into_iter().flat_map(|alpha| [u8::MAX, u8::MAX, u8::MAX, alpha]).collect();
|
||||
let image = egui::ColorImage::from_rgba_unmultiplied([side as usize; 2], &rgba);
|
||||
let texture = ctx.load_texture(format!("drawn_icon_{self:?}_{side}"), image, egui::TextureOptions::LINEAR);
|
||||
ctx.data_mut(|data| data.insert_temp(id, texture.clone()));
|
||||
texture
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_icon_is_painted_as_one_tinted_texture_on_whole_pixels() {
|
||||
let ctx = egui::Context::default();
|
||||
|
||||
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let painter = ui.painter();
|
||||
DrawnIcon::Invert.paint(painter, egui::pos2(10.3, 20.6), 14.0, egui::Color32::RED);
|
||||
DrawnIcon::Invert.paint(painter, egui::pos2(40.0, 20.0), 14.0, egui::Color32::GREEN);
|
||||
});
|
||||
|
||||
let shapes: Vec<egui::Shape> = output.shapes.iter().map(|clipped| clipped.shape.clone()).collect();
|
||||
output.drop_without_applying_deltas();
|
||||
let meshes: Vec<_> = shapes.iter().filter_map(|shape| if let egui::Shape::Mesh(mesh) = shape { Some(mesh.clone()) } else { None }).collect();
|
||||
|
||||
assert_eq!(meshes.len(), 2, "one textured quad per icon: {shapes:?}");
|
||||
|
||||
let [first, second] = [&meshes[0], &meshes[1]];
|
||||
assert_eq!(first.texture_id, second.texture_id, "the texture is rendered once per size");
|
||||
|
||||
let bounds = first.calc_bounds();
|
||||
assert_eq!((bounds.min, bounds.size()), (egui::pos2(3.0, 14.0), egui::vec2(14.0, 14.0)), "snapped to whole pixels");
|
||||
assert!(first.vertices.iter().all(|vertex| vertex.color == egui::Color32::RED), "tinted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_is_full_inside_the_ink_and_clear_outside() {
|
||||
let side = 32;
|
||||
let invert = DrawnIcon::Invert.coverage(side);
|
||||
let at = |x: f32, y: f32| invert.get(((y * side as f32) as u32 * side + (x * side as f32) as u32) as usize).copied();
|
||||
|
||||
assert_eq!(invert.len(), (side * side) as usize);
|
||||
assert_eq!(at(0.7, 0.25), Some(u8::MAX), "the solid half");
|
||||
assert_eq!(at(0.3, 0.25), Some(0), "the clear half");
|
||||
assert_eq!(at(0.02, 0.02), Some(0), "outside the frame");
|
||||
}
|
||||
}
|
||||
@@ -1,108 +1,10 @@
|
||||
//! Icons the icon font has no fitting glyph for, drawn in code from signed distances
|
||||
|
||||
mod distance;
|
||||
#[path = "drawn_icon.rs"]
|
||||
mod icon;
|
||||
mod invert;
|
||||
pub(crate) mod pipette;
|
||||
|
||||
pub(crate) use distance::Point;
|
||||
|
||||
/// The largest side an icon is rendered at, in pixels
|
||||
const MAX_SIDE: u32 = 256;
|
||||
|
||||
/// An icon drawn in code: rendered once per pixel size into a white texture and tinted where it is drawn, so it is as sharp as a font glyph at any scale
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum DrawnIcon {
|
||||
/// The eyedropper: a pipette, tip at the bottom left
|
||||
Pipette,
|
||||
/// A square half clear, half solid, an arrow out of each half
|
||||
Invert,
|
||||
}
|
||||
|
||||
impl DrawnIcon {
|
||||
/// The distance from `point` (in the icon's unit square, y down) to the icon's ink, negative inside
|
||||
pub(crate) fn distance(self, point: Point) -> f32 {
|
||||
match self {
|
||||
DrawnIcon::Pipette => pipette::glyph(point),
|
||||
DrawnIcon::Invert => invert::glyph(point),
|
||||
}
|
||||
}
|
||||
|
||||
/// How much of each pixel the icon covers when it is `side` pixels square, rows top first
|
||||
pub(crate) fn coverage(self, side: u32) -> Vec<u8> {
|
||||
let scale = side as f32;
|
||||
(0..side * side)
|
||||
.map(|index| {
|
||||
let point = [((index % side) as f32 + 0.5) / scale, ((index / side) as f32 + 0.5) / scale];
|
||||
((0.5 - self.distance(point) * scale).clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Draws the icon `size` points square centred on `center` in `color`, on whole screen pixels
|
||||
pub(crate) fn paint(self, painter: &egui::Painter, center: egui::Pos2, size: f32, color: egui::Color32) {
|
||||
let pixels_per_point = painter.ctx().pixels_per_point();
|
||||
let side = ((size * pixels_per_point).round() as u32).clamp(1, MAX_SIDE);
|
||||
let pixels = side as f32;
|
||||
let min = ((center.to_vec2() * pixels_per_point) - egui::Vec2::splat(pixels / 2.0)).round() / pixels_per_point;
|
||||
let rect = egui::Rect::from_min_size(min.to_pos2(), egui::Vec2::splat(pixels / pixels_per_point));
|
||||
|
||||
let whole = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0));
|
||||
painter.image(self.texture(painter.ctx(), side).id(), rect, whole, color);
|
||||
}
|
||||
|
||||
/// The icon `side` pixels square as a white texture with its coverage as alpha, rendered once per size
|
||||
fn texture(self, ctx: &egui::Context, side: u32) -> egui::TextureHandle {
|
||||
let id = egui::Id::unique(("drawn_icon", self, side));
|
||||
|
||||
if let Some(texture) = ctx.data(|data| data.get_temp::<egui::TextureHandle>(id)) {
|
||||
return texture;
|
||||
}
|
||||
|
||||
let rgba: Vec<u8> = self.coverage(side).into_iter().flat_map(|alpha| [u8::MAX, u8::MAX, u8::MAX, alpha]).collect();
|
||||
let image = egui::ColorImage::from_rgba_unmultiplied([side as usize; 2], &rgba);
|
||||
let texture = ctx.load_texture(format!("drawn_icon_{self:?}_{side}"), image, egui::TextureOptions::LINEAR);
|
||||
ctx.data_mut(|data| data.insert_temp(id, texture.clone()));
|
||||
texture
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_icon_is_painted_as_one_tinted_texture_on_whole_pixels() {
|
||||
let ctx = egui::Context::default();
|
||||
|
||||
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let painter = ui.painter();
|
||||
DrawnIcon::Invert.paint(painter, egui::pos2(10.3, 20.6), 14.0, egui::Color32::RED);
|
||||
DrawnIcon::Invert.paint(painter, egui::pos2(40.0, 20.0), 14.0, egui::Color32::GREEN);
|
||||
});
|
||||
|
||||
let shapes: Vec<egui::Shape> = output.shapes.iter().map(|clipped| clipped.shape.clone()).collect();
|
||||
output.drop_without_applying_deltas();
|
||||
let meshes: Vec<_> = shapes.iter().filter_map(|shape| if let egui::Shape::Mesh(mesh) = shape { Some(mesh.clone()) } else { None }).collect();
|
||||
|
||||
assert_eq!(meshes.len(), 2, "one textured quad per icon: {shapes:?}");
|
||||
|
||||
let [first, second] = [&meshes[0], &meshes[1]];
|
||||
assert_eq!(first.texture_id, second.texture_id, "the texture is rendered once per size");
|
||||
|
||||
let bounds = first.calc_bounds();
|
||||
assert_eq!((bounds.min, bounds.size()), (egui::pos2(3.0, 14.0), egui::vec2(14.0, 14.0)), "snapped to whole pixels");
|
||||
assert!(first.vertices.iter().all(|vertex| vertex.color == egui::Color32::RED), "tinted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_is_full_inside_the_ink_and_clear_outside() {
|
||||
let side = 32;
|
||||
let invert = DrawnIcon::Invert.coverage(side);
|
||||
let at = |x: f32, y: f32| invert.get(((y * side as f32) as u32 * side + (x * side as f32) as u32) as usize).copied();
|
||||
|
||||
assert_eq!(invert.len(), (side * side) as usize);
|
||||
assert_eq!(at(0.7, 0.25), Some(u8::MAX), "the solid half");
|
||||
assert_eq!(at(0.3, 0.25), Some(0), "the clear half");
|
||||
assert_eq!(at(0.02, 0.02), Some(0), "outside the frame");
|
||||
}
|
||||
}
|
||||
pub(crate) use icon::DrawnIcon;
|
||||
@@ -6,12 +6,12 @@ use std::sync::Arc;
|
||||
use egui::{Color32, Painter, Rect};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::compose::{ImageRes, ImageStore};
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::compose::ImageRes;
|
||||
use texturecraft_engine::core::{
|
||||
Channel, ChannelKind, CookResolution, Fill, LayerId, LinkParam, MaterialLink, NormalFormat, OutputResolution, Procedural, ProceduralKind, ResolutionMode,
|
||||
Source,
|
||||
};
|
||||
use texturecraft_engine::fill_alpha::library_alpha_of;
|
||||
use texturecraft_engine::fill_material_cmds::whole_materials;
|
||||
use texturecraft_engine::materials::find;
|
||||
use texturecraft_engine::paint::alphas;
|
||||
@@ -37,7 +37,6 @@ use crate::source_choice::SourceChoice;
|
||||
use crate::source_slot::SourceSlot;
|
||||
use crate::state::UiState;
|
||||
use crate::theme::Tokens;
|
||||
use crate::thumbs::Thumbs;
|
||||
use crate::tile_picture::TilePicture;
|
||||
use crate::widgets::press_edit;
|
||||
|
||||
@@ -167,7 +166,7 @@ pub(crate) fn source_line(app: &TextureCraftApp, source: &Source) -> String {
|
||||
match source {
|
||||
Source::Uniform(_) => tr("Uniform").to_owned(),
|
||||
Source::Procedural { pattern, .. } => format!("{} · {}", tr(pattern.kind.label()), tr("procedural")),
|
||||
Source::Image { name, .. } => match library_alpha_of(name) {
|
||||
Source::Image { name, .. } => match app.session.library_alpha(name) {
|
||||
Some(alpha) => format!("{} · {}", tr(&alpha.label), tr("alpha")),
|
||||
None => format!("{name} · {}", tr("image")),
|
||||
},
|
||||
@@ -205,7 +204,7 @@ pub(crate) fn source_card(
|
||||
if slot.pick.clicked() {
|
||||
resource_picker::toggle(sheet.ui.ctx(), popup);
|
||||
}
|
||||
let current = source_choice(&source);
|
||||
let current = source_choice(&app.session, &source);
|
||||
|
||||
// From Uniform the picker opens at the top, not at its Uniform tile at the end
|
||||
let reveal = current != SourceChoice::Uniform;
|
||||
@@ -213,16 +212,15 @@ pub(crate) fn source_card(
|
||||
Source::Uniform(value) => value,
|
||||
_ => slot_of.default_value(),
|
||||
};
|
||||
let ctx = sheet.ui.ctx().clone();
|
||||
|
||||
// The anchors below the reader are listed only while the picker is open; an effect's (an instance's inherited mask fill) must also sit below the effect's owner
|
||||
// Inherited mask fills can only read anchors below both the reader and the effect's owner
|
||||
let effect = base.get("effect").and_then(Value::as_u64).map(LayerId);
|
||||
let tabs = |thumbs: &mut Thumbs| {
|
||||
let tabs = || {
|
||||
let anchors = match effect {
|
||||
Some(effect) => project_effect_anchors_below(&app.session.doc.project, reader, effect),
|
||||
None => anchors_below(&app.session.doc.project, reader),
|
||||
};
|
||||
source_tabs(thumbs, &ctx, &app.session.images, &anchors, shown_color(uniform))
|
||||
source_tabs(&app.session, &anchors, shown_color(uniform), true)
|
||||
};
|
||||
let picked = resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), reveal, tabs);
|
||||
if let Some(choice) = picked.filter(|choice| *choice != current) {
|
||||
@@ -235,7 +233,7 @@ pub(crate) fn source_card(
|
||||
app.run("layer.fill.set", set(json!({"image": name})));
|
||||
}
|
||||
|
||||
// A slot in a mode's card shows a pattern's Scale and Contrast like every slot; its other rows and Resolution band would split the card
|
||||
// Keep mode cards together by showing only Scale and Contrast
|
||||
if in_card {
|
||||
if let Source::Procedural { pattern, .. } = source {
|
||||
let mut edited = pattern.clone();
|
||||
@@ -301,32 +299,34 @@ fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSl
|
||||
}
|
||||
|
||||
/// The picker's choice `source` is: a library alpha's image is its alpha
|
||||
fn source_choice(source: &Source) -> SourceChoice {
|
||||
pub(crate) fn source_choice(session: &Session, source: &Source) -> SourceChoice {
|
||||
match source {
|
||||
Source::Uniform(_) => SourceChoice::Uniform,
|
||||
Source::Procedural { pattern, .. } => SourceChoice::Procedural(pattern.kind),
|
||||
Source::Image { name, .. } => library_alpha_of(name).map_or_else(|| SourceChoice::Image(name.clone()), |alpha| SourceChoice::Alpha(alpha.id.as_str())),
|
||||
Source::Image { name, .. } => {
|
||||
session.library_alpha(name).map_or_else(|| SourceChoice::Image(name.clone()), |alpha| SourceChoice::Alpha(alpha.id.as_str()))
|
||||
}
|
||||
Source::Anchor { anchor, .. } => SourceChoice::Anchor(*anchor),
|
||||
}
|
||||
}
|
||||
|
||||
/// The source picker's tabs: Resources (Procedurals, Textures with Import... first, Alphas in their shelf groups, Uniform) and the stack's Anchor points
|
||||
fn source_tabs(thumbs: &mut Thumbs, ctx: &egui::Context, images: &ImageStore, anchors: &[(LayerId, String)], uniform: Color32) -> Vec<PickerTab<SourceChoice>> {
|
||||
pub(crate) fn source_tabs(session: &Session, anchors: &[(LayerId, String)], uniform: Color32, include_alphas: bool) -> Vec<PickerTab<SourceChoice>> {
|
||||
let procedurals =
|
||||
ProceduralKind::ALL.into_iter().map(|kind| tile(SourceChoice::Procedural(kind), tr(kind.label()), None, TilePicture::Procedural(kind))).collect();
|
||||
let textures = ResourcePickerItem::textures(images, SourceChoice::Import, |name| SourceChoice::Image(name.to_owned()));
|
||||
let alphas = alphas::library()
|
||||
.iter()
|
||||
.map(|alpha| {
|
||||
let picture = TilePicture::Texture(thumbs.alpha(ctx, alpha));
|
||||
tile(SourceChoice::Alpha(alpha.id.as_str()), tr(&alpha.label), Some(tr(alpha.category)), picture)
|
||||
})
|
||||
.collect();
|
||||
let uniform = vec![tile(SourceChoice::Uniform, tr("Uniform value"), None, TilePicture::Swatch(uniform))];
|
||||
let resources = [(n_("Procedurals"), procedurals), (n_("Textures"), textures), (n_("Alphas"), alphas), (n_("Uniform"), uniform)]
|
||||
.into_iter()
|
||||
.map(|(header, items)| PickerGroup { header: Some(tr(header)), items })
|
||||
.collect();
|
||||
let textures = ResourcePickerItem::textures(session, SourceChoice::Import, |name| SourceChoice::Image(name.to_owned()));
|
||||
let mut resources =
|
||||
vec![PickerGroup { header: Some(tr("Procedurals")), items: procedurals }, PickerGroup { header: Some(tr("Textures")), items: textures }];
|
||||
if include_alphas {
|
||||
let items = alphas::library()
|
||||
.iter()
|
||||
.map(|alpha| tile(SourceChoice::Alpha(alpha.id.as_str()), tr(&alpha.label), Some(tr(alpha.category)), TilePicture::Alpha(alpha)))
|
||||
.collect();
|
||||
resources.push(PickerGroup { header: Some(tr("Alphas")), items });
|
||||
}
|
||||
|
||||
let uniform = tile(SourceChoice::Uniform, tr("Uniform value"), None, TilePicture::Swatch(uniform));
|
||||
resources.push(PickerGroup { header: Some(tr("Uniform")), items: vec![uniform] });
|
||||
let anchors = anchors.iter().map(|(anchor, label)| tile(SourceChoice::Anchor(*anchor), label, None, TilePicture::Glyph(ic::ANCHOR))).collect();
|
||||
vec![
|
||||
PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups: resources },
|
||||
@@ -426,7 +426,7 @@ fn procedural_rows(
|
||||
let mut edited = pattern.clone();
|
||||
let mut edit = scale_and_contrast(sheet, &mut edited);
|
||||
|
||||
// A grayscale's card (a mask fill's, a filter input's) shows its Balance and Seed with Scale and Contrast; a material channel's keeps them in Attributes
|
||||
// Only grayscale cards edit Balance and Seed here
|
||||
let gray = matches!(slot_of, SourceSlot::Grayscale);
|
||||
if gray {
|
||||
edit = edit.or(balance_and_seed(sheet, &mut edited));
|
||||
@@ -533,8 +533,7 @@ fn whole_material_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>,
|
||||
resource_picker::toggle(sheet.ui.ctx(), popup);
|
||||
}
|
||||
let current = held.map(|material| material.id);
|
||||
let ctx = sheet.ui.ctx().clone();
|
||||
let picked = resource_picker::show(&slot.pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), |thumbs| material_tabs(&ctx, thumbs));
|
||||
let picked = resource_picker::show(&slot.pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), material_tabs);
|
||||
if let Some(id) = picked.filter(|id| Some(*id) != current) {
|
||||
app.run("layer.fill.material", with(base, json!({"material": id})));
|
||||
}
|
||||
@@ -545,15 +544,10 @@ fn whole_material_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>,
|
||||
}
|
||||
|
||||
/// The material picker's one tab: every plain material's preview ball, grouped under its shelf category in library order
|
||||
fn material_tabs(ctx: &egui::Context, thumbs: &mut Thumbs) -> Vec<PickerTab<&'static str>> {
|
||||
fn material_tabs() -> Vec<PickerTab<&'static str>> {
|
||||
let mut groups: Vec<PickerGroup<&'static str>> = Vec::new();
|
||||
for material in whole_materials() {
|
||||
let item = ResourcePickerItem {
|
||||
id: material.id,
|
||||
label: tr(material.label).to_owned(),
|
||||
caption: None,
|
||||
picture: TilePicture::Texture(thumbs.material(ctx, material.id)),
|
||||
};
|
||||
let item = ResourcePickerItem { id: material.id, label: tr(material.label).to_owned(), caption: None, picture: TilePicture::Material(material.id) };
|
||||
let header = Some(tr(material.category));
|
||||
match groups.iter_mut().find(|group| group.header == header) {
|
||||
Some(group) => group.items.push(item),
|
||||
@@ -608,7 +602,7 @@ fn link_input(sheet: &mut PropertySheet<'_>, layer: LayerId, param: &LinkParam,
|
||||
let mut edited = number;
|
||||
let moved = sheet.slider(¶m.label, &mut edited, low.min(number)..=high.max(number), 0).is_some();
|
||||
|
||||
// Whole numbers: a press's first whole-number change starts its undo step, moves that round to the value it has send nothing (no step, no cook)
|
||||
// Only a new integer starts an edit or schedules another cook
|
||||
let whole = edited.round();
|
||||
let press = sheet.ui.make_persistent_id(("link_input_press", layer.0, ¶m.id));
|
||||
press_edit(sheet.ui, press, moved && whole != number).map(|merge| (json!(whole), merge))
|
||||
|
||||
@@ -137,7 +137,7 @@ fn projection_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fil
|
||||
|
||||
let picture = |painter: &Painter, rect: Rect, kind: ProjectionKind| projection_picture(painter, rect, kind, &tokens);
|
||||
|
||||
// A projection with a gizmo in the 3D view ends its row in the eye that shows or hides it (a view setting saved with the project)
|
||||
// The eye controls the project's viewport gizmo visibility
|
||||
let gizmos = app.session.doc.project.display.projection_gizmos;
|
||||
let tip = if gizmos { tr("Hide projection gizmos") } else { tr("Show projection gizmos") };
|
||||
let name = |kind: ProjectionKind| tr(kind.label()).to_owned();
|
||||
@@ -153,31 +153,28 @@ fn projection_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fil
|
||||
app.run("display.set", json!({"projectionGizmos": !gizmos}));
|
||||
}
|
||||
|
||||
// Per UV tile, the source fills each tile once: nothing to place
|
||||
if kind == ProjectionKind::UvTile {
|
||||
return;
|
||||
}
|
||||
|
||||
let size = mesh_size(app, sheet.ui.ctx());
|
||||
let length = tile_length(&fill.projection, size);
|
||||
let physical = length.is_some() && fill.sampling.scale == ScaleMode::PhysicalSize;
|
||||
if length.is_some() {
|
||||
let modes = [tr("Tiling"), tr("Physical size")];
|
||||
if let Some(index) = sheet.switch(tr("Scale"), &modes, usize::from(physical))
|
||||
&& let Some(mode) = ScaleMode::ALL.get(index)
|
||||
{
|
||||
run(app, json!({"scaleMode": mode.id()}));
|
||||
// Per-tile fills still sample images without a placement to edit
|
||||
if kind != ProjectionKind::UvTile {
|
||||
let size = mesh_size(app, sheet.ui.ctx());
|
||||
let length = tile_length(&fill.projection, size);
|
||||
let physical = length.is_some() && fill.sampling.scale == ScaleMode::PhysicalSize;
|
||||
if length.is_some() {
|
||||
let modes = [tr("Tiling"), tr("Physical size")];
|
||||
if let Some(index) = sheet.switch(tr("Scale"), &modes, usize::from(physical))
|
||||
&& let Some(mode) = ScaleMode::ALL.get(index)
|
||||
{
|
||||
run(app, json!({"scaleMode": mode.id()}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Move on model: hold the preview square and drag to slide the projection
|
||||
let target = match base.get("effect").and_then(Value::as_u64) {
|
||||
Some(effect) => MoveOnModel { layer: reader, effect: Some(LayerId(effect)) },
|
||||
None => MoveOnModel::layer(reader),
|
||||
};
|
||||
placement_rows(app, sheet, fill, base, length.filter(|_| physical), size, target);
|
||||
frame_rows(app, sheet, fill, base);
|
||||
culling_rows(app, sheet, fill, base);
|
||||
let target = match base.get("effect").and_then(Value::as_u64) {
|
||||
Some(effect) => MoveOnModel { layer: reader, effect: Some(LayerId(effect)) },
|
||||
None => MoveOnModel::layer(reader),
|
||||
};
|
||||
placement_rows(app, sheet, fill, base, length.filter(|_| physical), size, target);
|
||||
frame_rows(app, sheet, fill, base);
|
||||
culling_rows(app, sheet, fill, base);
|
||||
}
|
||||
|
||||
let crop = projector_of(&fill.projection).map(|projector| projector.crop);
|
||||
let shows_wrap = kind != ProjectionKind::Triplanar;
|
||||
@@ -342,7 +339,7 @@ fn placement_rows(
|
||||
let mut linked = sheet.ui.data(|data| data.get_temp::<bool>(link_id)).unwrap_or(tiling[0] == tiling[1]);
|
||||
let was_linked = linked;
|
||||
let mut values = match length {
|
||||
Some(length) => length.map(|units| (units * CM_PER_UNIT).round()),
|
||||
Some(length) => length.map(|units| units * CM_PER_UNIT),
|
||||
None => tiling,
|
||||
};
|
||||
let shown = values;
|
||||
@@ -396,7 +393,10 @@ fn placement_rows(
|
||||
&& values != shown
|
||||
{
|
||||
let tiling = match length {
|
||||
Some(_) => tiling_for_length(&fill.projection, size, values.map(|cm| cm / CM_PER_UNIT)).unwrap_or(tiling),
|
||||
Some(_) => tiling_for_length(&fill.projection, size, values.map(|cm| cm / CM_PER_UNIT)).map_or(tiling, |converted| {
|
||||
// Keep the stored tiling for axes that did not change
|
||||
std::array::from_fn(|axis| if values[axis] == shown[axis] { tiling[axis] } else { converted[axis] })
|
||||
}),
|
||||
None => values,
|
||||
};
|
||||
run_projection(app, base, json!({"tiling": tiling, "merge": merge}));
|
||||
|
||||
@@ -165,7 +165,7 @@ pub(crate) fn lattice_preview(painter: &Painter, rect: Rect, (columns, shift): (
|
||||
let (dark, light) = (lerp_color(tokens.field, tokens.text, PREVIEW_DARK), lerp_color(tokens.field, tokens.text, PREVIEW_LIGHT));
|
||||
let border = Stroke::new(LINE_WIDTH, tokens.accent);
|
||||
|
||||
// Repeating past the most tiles drawn, a tile is about a pixel: the window reads as the checker's mean, so the undrawn tiles leave no bare field
|
||||
// Subpixel repeats use the mean checker shade across the window
|
||||
if repeat && (0..2).any(|axis| high(axis).saturating_sub(low(axis)) > PREVIEW_MAX_SPAN) {
|
||||
painter.rect_filled(rect, 0, lerp_color(dark, light, CHECKER_MEAN));
|
||||
}
|
||||
@@ -347,7 +347,7 @@ pub(crate) fn ring_picture(painter: &Painter, rect: Rect, symmetry: &FillSymmetr
|
||||
center + vec2(turn.cos(), turn.sin()) * radius
|
||||
};
|
||||
|
||||
// The ring runs over the span the engine spreads the copies over: a stored span past a full turn or below none reads as the engine reads it
|
||||
// Use the engine's clamped span for the radial ring
|
||||
let ring_end = symmetry.span.clamp(0.0, FULL_TURN_DEGREES);
|
||||
let ring: Vec<Pos2> = (0..=RING_SEGMENTS).map(|k| at(ring_end * k as f32 / RING_SEGMENTS as f32)).collect();
|
||||
painter.add(Shape::line(ring, Stroke::new(LINE_WIDTH, tokens.separator)));
|
||||
@@ -385,6 +385,7 @@ mod tests {
|
||||
fn the_uv_view_stands_still_and_the_dot_slides_with_the_checker() {
|
||||
let placement = |offset: [f32; 2]| Placement { tiling: [2.0, 2.0], rotation: 30.0, offset };
|
||||
let (still, rest) = slid_window(placement([0.0, 0.0]));
|
||||
|
||||
assert_eq!(rest, [0.5, 0.5], "at Offset 0 the dot sits in the ring");
|
||||
|
||||
let slid = placement([-0.25, 0.0]);
|
||||
|
||||
@@ -23,9 +23,6 @@ const COUNT_TRACK: RangeInclusive<f32> = *FillSymmetry::COUNTS.start() as f32..=
|
||||
/// What a typed Count may reach
|
||||
const COUNT_TYPED: RangeInclusive<f32> = *FillSymmetry::COUNTS.start() as f32..=*FillSymmetry::COUNTS.end() as f32;
|
||||
|
||||
/// The Angle span slider's place in the stack beside the ring, under Count
|
||||
const SPAN_SLIDER: usize = 1;
|
||||
|
||||
/// The Symmetry section under the Fill section: its switch on the caption, then Type, Axis, the radial copies beside their picture, Flip copy and Axis position
|
||||
pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, projection: &Projection, sampling: Sampling, base: &Value) {
|
||||
let symmetry = sampling.symmetry;
|
||||
@@ -68,17 +65,18 @@ pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySh
|
||||
run(app, json!({"flipCopy": flip}));
|
||||
}
|
||||
|
||||
// A mirror moves its plane along its axis; radial copies turn round an axis that moves across it
|
||||
// Mirror position moves along its normal and radial position moves across its axis
|
||||
let moving: Vec<usize> = match symmetry.kind {
|
||||
SymmetryKind::Mirror => vec![axis],
|
||||
SymmetryKind::Radial => (0..AXIS_NAMES.len()).filter(|other| *other != axis).collect(),
|
||||
};
|
||||
let mut parts: Vec<(&str, egui::Color32, f32)> = moving.iter().map(|&moved| (AXIS_NAMES[moved], AXIS_COLORS[moved], symmetry.position[moved])).collect();
|
||||
if let Some((index, merge)) = sheet.lettered_sliders(tr("Axis position"), &mut parts, POSITION_RANGE, 2)
|
||||
&& let (Some(&moved), Some((_, _, value))) = (moving.get(index), parts.get(index))
|
||||
{
|
||||
if let Some(merge) = sheet.lettered_sliders(tr("Axis position"), &mut parts, POSITION_RANGE, 2) {
|
||||
let mut position = symmetry.position;
|
||||
position[moved] = *value;
|
||||
for (axis, (_, _, value)) in moving.into_iter().zip(parts) {
|
||||
position[axis] = value;
|
||||
}
|
||||
|
||||
run(app, json!({"axisPosition": position, "merge": merge}));
|
||||
}
|
||||
}
|
||||
@@ -96,17 +94,24 @@ fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetr
|
||||
StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°" },
|
||||
];
|
||||
|
||||
let edited = sheet.picture_sliders(&picture, &mut sliders);
|
||||
if let Some((SPAN_SLIDER, merge)) = edited {
|
||||
run_projection(app, base, json!({"angleSpan": span_value, "merge": merge}));
|
||||
return;
|
||||
}
|
||||
let [count_edit, span_edit] = sheet.picture_sliders(&picture, &mut sliders);
|
||||
|
||||
// Whole counts: a press's first whole-number change starts its undo step, changes that round to the count it has apply nothing
|
||||
let counted = count_value.round();
|
||||
// Start the count's undo step on the first whole-number change
|
||||
let rounded_count = count_value.round() as u32;
|
||||
let press = sheet.ui.make_persistent_id("symmetry_count_press");
|
||||
if let Some(merge) = press_edit(sheet.ui, press, edited.is_some() && counted as u32 != count) {
|
||||
run_projection(app, base, json!({"symmetryCount": counted, "merge": merge}));
|
||||
let count_merge = press_edit(sheet.ui, press, count_edit.is_some() && rounded_count != count);
|
||||
let count_edit = count_edit.zip(count_merge).map(|(track_merge, count_merge)| track_merge && count_merge);
|
||||
|
||||
if let Some(merge) = [count_edit, span_edit].into_iter().flatten().reduce(|first, second| first && second) {
|
||||
let mut fields = json!({"merge": merge});
|
||||
if count_edit.is_some() {
|
||||
fields["symmetryCount"] = json!(rounded_count);
|
||||
}
|
||||
if span_edit.is_some() {
|
||||
fields["angleSpan"] = json!(span_value);
|
||||
}
|
||||
|
||||
run_projection(app, base, fields);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ use crate::picker_tab::PickerTab;
|
||||
use crate::resource_picker;
|
||||
use crate::resource_picker_item::ResourcePickerItem;
|
||||
use crate::theme::Tokens;
|
||||
use crate::thumbs::Thumbs;
|
||||
use crate::tile_picture::TilePicture;
|
||||
use crate::widgets::elided;
|
||||
|
||||
@@ -52,21 +51,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter:
|
||||
let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup);
|
||||
paint(ui, rect, (highlighted, response.has_focus()), thumbnail.as_ref().map(egui::TextureHandle::id), (tr("Filter"), name));
|
||||
|
||||
let tabs = |thumbs: &mut Thumbs| {
|
||||
let mut items: Vec<ResourcePickerItem<&'static str>> = filter_effects()
|
||||
.iter()
|
||||
.filter(|def| def.mask || !on_mask)
|
||||
.map(|def| ResourcePickerItem {
|
||||
id: def.id,
|
||||
label: tr(def.label).to_owned(),
|
||||
caption: None,
|
||||
picture: TilePicture::Texture(thumbs.filter(&ctx, def.id)),
|
||||
})
|
||||
.collect();
|
||||
|
||||
// One kind of resource: one grid in name order, no group captions
|
||||
items.sort_by_cached_key(|item| item.label.to_lowercase());
|
||||
vec![PickerTab { icon: ic::FUNNEL, name: tr("Filters"), groups: vec![PickerGroup { header: None, items }] }]
|
||||
let tabs = || {
|
||||
let mut groups: Vec<PickerGroup<&'static str>> = Vec::new();
|
||||
for def in filter_effects().iter().filter(|def| def.mask || !on_mask) {
|
||||
let item = ResourcePickerItem { id: def.id, label: tr(def.label).to_owned(), caption: None, picture: TilePicture::Filter(def.id) };
|
||||
match groups.last_mut() {
|
||||
Some(group) if group.header == Some(tr(def.group)) => group.items.push(item),
|
||||
_ => groups.push(PickerGroup { header: Some(tr(def.group)), items: vec![item] }),
|
||||
}
|
||||
}
|
||||
vec![PickerTab { icon: ic::FUNNEL, name: tr("Filter"), groups }]
|
||||
};
|
||||
let picked = resource_picker::show(&response, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs);
|
||||
if let Some(id) = picked.filter(|id| Some(*id) != current) {
|
||||
|
||||
@@ -104,7 +104,7 @@ impl FrameGizmo {
|
||||
|
||||
let placed = placed_from_axis(projection, app.viewport_mesh_bounds.get(&app.session.mesh));
|
||||
|
||||
// Where the projection lands: a projector's own turn and scale moved into the frame, as the panel's 3D projection settings show it
|
||||
// Match the panel by folding the projector transform into the frame first
|
||||
let landed = folded(placed.as_ref().unwrap_or(projection))?;
|
||||
let decal = *landed.frame()?;
|
||||
let warp = match projection {
|
||||
@@ -248,9 +248,7 @@ impl Gizmo for FrameGizmo {
|
||||
handles.extend((0..3).filter_map(|axis| Some((FrameGrab::Axis(axis), arrow_distance(at, self.center, self.arrows[axis]?)))));
|
||||
let near = |points: [Pos2; 4], grab: fn(usize) -> FrameGrab| (0..4).map(move |index| (grab(index), points[index].distance(at)));
|
||||
match self.warp {
|
||||
// A mask effect's warp corners have no command to pull them
|
||||
Some(_) if self.effect.is_none() => handles.extend(near(self.corners, FrameGrab::Corner)),
|
||||
Some(_) => {}
|
||||
Some(_) => handles.extend(near(self.corners, FrameGrab::Corner)),
|
||||
None => handles.extend(near(self.corners, |_| FrameGrab::Scale)),
|
||||
}
|
||||
handles.extend(near(self.sides, FrameGrab::Side));
|
||||
@@ -299,15 +297,18 @@ impl Gizmo for FrameGizmo {
|
||||
}
|
||||
FrameGrab::Corner(corner) => {
|
||||
let mut corners = self.warp?;
|
||||
*corners.get_mut(corner)? = self.on_plane(app, rect, to)?;
|
||||
return Some(("layer.fill.projection", json!({"layer": self.layer.0, "warpCorners": corners})));
|
||||
let dragged_corner = *self.corners.get(corner)? + delta;
|
||||
*corners.get_mut(corner)? = self.on_plane(app, rect, dragged_corner)?;
|
||||
|
||||
json!({"warpCorners": corners})
|
||||
}
|
||||
};
|
||||
params["layer"] = json!(self.layer.0);
|
||||
if let Some(effect) = self.effect {
|
||||
params["effect"] = json!(effect.0);
|
||||
}
|
||||
Some(("layer.decal.set", params))
|
||||
let command = if matches!(grab, FrameGrab::Corner(_)) { "layer.fill.projection" } else { "layer.decal.set" };
|
||||
Some((command, params))
|
||||
}
|
||||
|
||||
fn cursor(&self, grab: FrameGrab, dragging: bool) -> egui::CursorIcon {
|
||||
@@ -379,9 +380,8 @@ const OUTLINE_GAP: f32 = 4.0;
|
||||
|
||||
/// A gizmo's dashed outline through `points`, light over a dark shadow so it reads on any model
|
||||
pub(crate) fn dashed_outline(painter: &egui::Painter, points: &[Pos2]) {
|
||||
for stroke in [Stroke::new(OUTLINE_SHADOW_WIDTH, OUTLINE_SHADOW), Stroke::new(OUTLINE_WIDTH, OUTLINE_COLOR)] {
|
||||
painter.add(egui::Shape::dashed_line(points, stroke, OUTLINE_DASH, OUTLINE_GAP));
|
||||
}
|
||||
let strokes = [Stroke::new(OUTLINE_SHADOW_WIDTH, OUTLINE_SHADOW), Stroke::new(OUTLINE_WIDTH, OUTLINE_COLOR)];
|
||||
crate::viewport::paint_dashed_outline(painter, points, OUTLINE_DASH, OUTLINE_GAP, strokes);
|
||||
}
|
||||
|
||||
/// An arrow head's half width, as a share of its length
|
||||
@@ -530,6 +530,7 @@ pub(crate) mod tests {
|
||||
// Repeating three times across the mesh, the frame is smaller than the ball
|
||||
let (mut harness, layer) = fill_app_with(json!({"projection": "planar", "scale": 3}));
|
||||
let axis = gizmo(&harness);
|
||||
|
||||
assert!(matches!(projection(&harness, layer), Projection::Planar { placed: None, .. }), "a new planar projects along its axis");
|
||||
assert!(axis.warp.is_none() && axis.arrows.iter().all(Option::is_some), "a planar frame with its three arrows: {axis:?}");
|
||||
|
||||
@@ -558,6 +559,7 @@ pub(crate) mod tests {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (mut harness, layer) = fill_app("warp");
|
||||
let warp = gizmo(&harness);
|
||||
|
||||
assert_eq!(warp.warp, Some(Projection::FRAME_CORNERS));
|
||||
|
||||
let to = warp.corners[1] + vec2(-40.0, 30.0);
|
||||
@@ -568,6 +570,22 @@ pub(crate) mod tests {
|
||||
assert!(gizmo(&harness).corners[1].distance(to) < 1.5, "the corner sits under the pointer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grabbing_the_side_of_a_warp_corner_does_not_snap_it_to_the_pointer() {
|
||||
let (mut harness, _) = fill_app("warp");
|
||||
let warp = gizmo(&harness);
|
||||
let corner = warp.corners[1];
|
||||
let press = corner + vec2(6.0, 2.0);
|
||||
let movement = vec2(-40.0, 30.0);
|
||||
|
||||
assert_eq!(warp.grab(press), Some(FrameGrab::Corner(1)));
|
||||
|
||||
drag(&mut harness, press, press + movement, Modifiers::NONE);
|
||||
|
||||
let moved = gizmo(&harness).corners[1];
|
||||
assert!(moved.distance(corner + movement) < 1.5, "the original grab offset is kept: {moved:?}");
|
||||
}
|
||||
|
||||
/// A move that arrives in the same frame as the release still moves the corner: it ends under the pointer, not one step short
|
||||
#[test]
|
||||
fn a_move_in_the_release_frame_still_moves_the_corner() {
|
||||
@@ -605,6 +623,7 @@ pub(crate) mod tests {
|
||||
drag(&mut harness, tip, tip + along * 25.0, Modifiers::NONE);
|
||||
|
||||
let moved = gizmo(&harness);
|
||||
|
||||
assert!(
|
||||
(moved.center - start.center).dot(along) > 15.0,
|
||||
"arrow {axis}: the centre follows the pointer along it: {:?} -> {:?}",
|
||||
@@ -641,6 +660,7 @@ pub(crate) mod tests {
|
||||
let pointer = sweep(on_ring - start.center, quarter - start.center);
|
||||
let corner = sweep(start.corners[1] - start.center, turned.corners[1] - turned.center);
|
||||
let off = (corner - pointer + 180.0).rem_euclid(360.0) - 180.0;
|
||||
|
||||
assert!(off.abs() < 6.0, "{kind}: the frame turns a quarter with the pointer: corner {corner}°, pointer {pointer}°");
|
||||
assert!(turned.center.distance(start.center) < 1.0, "{kind}: round its centre");
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "{kind}: one undo step");
|
||||
@@ -762,6 +782,7 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn an_axis_planar_reading_a_pattern_has_no_frame() {
|
||||
let (mut harness, layer) = fill_app("planar");
|
||||
|
||||
assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some(), "a uniform fill places as its frame");
|
||||
|
||||
harness.state_mut().run("layer.fill.set", json!({"layer": layer.0, "channel": "roughness", "procedural": "Checker"})).unwrap();
|
||||
@@ -813,6 +834,7 @@ pub(crate) mod tests {
|
||||
let shown = gizmo(&harness);
|
||||
let eye = harness.get_by_label("Hide projection gizmos").rect();
|
||||
let projection_row = harness.get_by_label("Planar projection").rect();
|
||||
|
||||
assert!(eye.left() > projection_row.right() && (eye.center().y - projection_row.center().y).abs() < 0.5, "the eye ends the Projection row");
|
||||
|
||||
click(&mut harness, eye.center());
|
||||
@@ -846,6 +868,7 @@ pub(crate) mod tests {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for projection in ["uv", "triplanar", "spherical", "cylindrical"] {
|
||||
let (harness, _) = fill_app(projection);
|
||||
|
||||
assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "{projection}");
|
||||
}
|
||||
}
|
||||
@@ -934,7 +957,7 @@ pub(crate) mod tests {
|
||||
harness.run_steps(3);
|
||||
harness.render().unwrap().save(directory.join("sync-sphere-mid-drag.png")).unwrap();
|
||||
|
||||
// The round projections with their fill selected: the shape round it, a ring hovered (a sphere: its one dot; a cylinder: its height arrow)
|
||||
// Show the sphere size dot and cylinder height arrow on selected round projectors
|
||||
for kind in ["triplanar", "spherical", "cylindrical"] {
|
||||
let (mut harness, layer) = fill_app_rendered(json!({"projection": kind}), true);
|
||||
checker(&mut harness, layer);
|
||||
|
||||
@@ -419,6 +419,7 @@ impl GpuLink {
|
||||
{
|
||||
out.aux.push((texture_set, resolution, rgba));
|
||||
self.aux.insert(texture_set, key);
|
||||
|
||||
// A weak owner keeps the address unique without retaining the decoded pixels
|
||||
self.aux_id_mask = Some(Arc::downgrade(image));
|
||||
}
|
||||
@@ -659,6 +660,7 @@ mod tests {
|
||||
execute(&mut s, "viewport.view", &json!({"mode": "image", "image": name})).unwrap();
|
||||
|
||||
let out = gpu.sync(&mut s, Some(AuxView::Image), None, 0, 0.0);
|
||||
|
||||
assert_eq!(out.image_aux.len(), 1, "equal resolutions share a single pixel buffer");
|
||||
|
||||
let (targets, bytes) = out.image_aux.values().next().unwrap();
|
||||
@@ -720,6 +722,7 @@ mod tests {
|
||||
assert!(retired.upgrade().is_none(), "upload ownership must drop independently of decoded source pixels");
|
||||
|
||||
let replacement = image([0.0, 0.0, 1.0, 1.0]);
|
||||
|
||||
// Simulate an allocator returning the previous address for the new image
|
||||
gpu.aux.get_mut(&set).unwrap().1 = Arc::as_ptr(&replacement) as u64;
|
||||
session.images.insert(resource.into(), replacement);
|
||||
|
||||
@@ -23,7 +23,7 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option<b
|
||||
ui.horizontal(|ui| {
|
||||
let mut edit = typed;
|
||||
|
||||
// The invert button's own width (its glyph and padding), so the bar leaves exactly its room and it ends on the value above
|
||||
// Reserve the invert button's measured width to align the bar with its value
|
||||
let glyph = ui.painter().layout_no_wrap(ic::CIRCLE_HALF.to_owned(), egui::TextStyle::Button.resolve(ui.style()), egui::Color32::WHITE);
|
||||
let button_width = glyph.size().x + ui.spacing().button_padding.x * 2.0;
|
||||
let width = (ui.available_width() - button_width - ui.spacing().item_spacing.x).max(MIN_BAR_WIDTH);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use egui::{Align2, Color32, CornerRadius, FontId, Frame, Id, Painter, Pos2, Rect, Response, Sense, Shadow, Stroke, StrokeKind, Ui, pos2, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::compose::ImageStore;
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::core::{Layer, LayerId};
|
||||
use texturecraft_engine::paint::alphas;
|
||||
|
||||
@@ -14,7 +14,6 @@ use crate::picker_tab::PickerTab;
|
||||
use crate::resource_picker;
|
||||
use crate::resource_picker_item::ResourcePickerItem;
|
||||
use crate::theme::{HARD_SHADOW, Tokens};
|
||||
use crate::thumbs::Thumbs;
|
||||
use crate::tile_picture::TilePicture;
|
||||
|
||||
mod add_item;
|
||||
@@ -135,7 +134,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
app.run("layer.remove", Value::Null);
|
||||
}
|
||||
|
||||
// Keyed by the layer that opened it: a picker no longer shown when the selection moves closes, so its pick never lands on another layer
|
||||
// Key the picker to its opening layer so a selection change discards its result
|
||||
let popup = |layer: LayerId| ui.scope_id().with(("bitmap_mask_picker", layer.0));
|
||||
match (pick, selected) {
|
||||
(Some(Pick::Run { command, params }), Some(layer)) => run_on(app, ui, layer, command, params),
|
||||
@@ -435,8 +434,7 @@ fn icon_of(icon: ItemIcon) -> &'static str {
|
||||
/// The texture picker of Add bitmap mask, hanging under `anchor` at its width while open: a pick adds the mask to `layer`, Escape or a click elsewhere adds nothing
|
||||
pub(crate) fn bitmap_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id, layer: LayerId) {
|
||||
let ctx = anchor.ctx.clone();
|
||||
let images = &app.session.images;
|
||||
let tabs = |thumbs: &mut Thumbs| bitmap_tabs(thumbs, &ctx, images);
|
||||
let tabs = || bitmap_tabs(&app.session);
|
||||
match resource_picker::show(anchor, popup, &mut app.thumbs, None, false, tabs) {
|
||||
Some(BitmapChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"),
|
||||
Some(BitmapChoice::Image(name)) => {
|
||||
@@ -452,12 +450,12 @@ pub(crate) fn bitmap_picker(app: &mut TextureCraftApp, anchor: &Response, popup:
|
||||
}
|
||||
|
||||
/// The bitmap picker's one tab: Textures (Import... first) and the Alphas in their shelf groups
|
||||
fn bitmap_tabs(thumbs: &mut Thumbs, ctx: &egui::Context, images: &ImageStore) -> Vec<PickerTab<BitmapChoice>> {
|
||||
fn bitmap_tabs(session: &Session) -> Vec<PickerTab<BitmapChoice>> {
|
||||
let tile = |id, label: &str, caption, picture| ResourcePickerItem { id, label: label.to_owned(), caption, picture };
|
||||
let textures = ResourcePickerItem::textures(images, BitmapChoice::Import, |name| BitmapChoice::Image(name.to_owned()));
|
||||
let textures = ResourcePickerItem::textures(session, BitmapChoice::Import, |name| BitmapChoice::Image(name.to_owned()));
|
||||
let alphas = alphas::library()
|
||||
.iter()
|
||||
.map(|alpha| tile(BitmapChoice::Alpha(alpha.id.as_str()), tr(&alpha.label), Some(tr(alpha.category)), TilePicture::Texture(thumbs.alpha(ctx, alpha))))
|
||||
.map(|alpha| tile(BitmapChoice::Alpha(alpha.id.as_str()), tr(&alpha.label), Some(tr(alpha.category)), TilePicture::Alpha(alpha)))
|
||||
.collect();
|
||||
let groups = vec![PickerGroup { header: Some(tr("Textures")), items: textures }, PickerGroup { header: Some(tr("Alphas")), items: alphas }];
|
||||
vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups }]
|
||||
|
||||
@@ -280,6 +280,7 @@ pub struct TextureCraftApp {
|
||||
pub moving_on_model: Option<move_on_model::MoveOnModel>,
|
||||
/// The Properties popup a right click in a view opens.
|
||||
pub properties_popup: Option<properties_popup::PropertiesPopup>,
|
||||
properties_scroll: property_sheet::PropertiesScroll,
|
||||
/// The color selection the next click in the 3D or 2D view picks an ID color for
|
||||
pub picking_id_color: Option<id_color_pick::IdColorPick>,
|
||||
/// Whether the next click on the model places the symmetry planes (Pick point in the symmetry settings)
|
||||
@@ -288,6 +289,7 @@ pub struct TextureCraftApp {
|
||||
pub picking_color: Option<egui::Id>,
|
||||
/// That eyedropper pick's wait for a click outside the app
|
||||
pub screen_pick: Option<screen_pick::ScreenPick>,
|
||||
eyedropper_project_id: u64,
|
||||
/// Whether an eyedropper pick also takes a click outside the app (only with a real window: never in tests)
|
||||
pub screen_picking: bool,
|
||||
/// The wgpu state (screenshots read the renderer's targets).
|
||||
@@ -339,10 +341,22 @@ pub(crate) fn start_ui(saved: Option<UiState>, session: &mut Session) -> UiState
|
||||
}
|
||||
}
|
||||
|
||||
fn uses_wayland(ctx: &egui::Context) -> bool {
|
||||
ctx.data(|data| data.get_temp::<bool>(egui::Id::unique("wayland_window")).unwrap_or(false))
|
||||
}
|
||||
|
||||
impl TextureCraftApp {
|
||||
/// The app around `session`, with the saved UI state (or defaults in the OS language) and the GPU viewport.
|
||||
pub fn new(cc: &eframe::CreationContext<'_>, mut session: Session) -> TextureCraftApp {
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let uses_wayland = raw_window_handle::HasWindowHandle::window_handle(cc)
|
||||
.is_ok_and(|window| matches!(window.as_raw(), raw_window_handle::RawWindowHandle::Wayland(_)));
|
||||
cc.egui_ctx.data_mut(|data| data.insert_temp(egui::Id::unique("wayland_window"), uses_wayland));
|
||||
}
|
||||
|
||||
theme::install(&cc.egui_ctx);
|
||||
popup_drag::install(&cc.egui_ctx);
|
||||
|
||||
// Bakes cast their rays on a GPU device of their own (created on the first bake)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -361,6 +375,7 @@ impl TextureCraftApp {
|
||||
let next_autosave = autosave_period_seconds(ui.prefs.autosave_minutes);
|
||||
ui.prefs.apply_resource_limits();
|
||||
|
||||
let project_id = session.project_id;
|
||||
let mut app = TextureCraftApp {
|
||||
camera_glide: None,
|
||||
orbit_snap: None,
|
||||
@@ -393,10 +408,12 @@ impl TextureCraftApp {
|
||||
last_paint_uv: None,
|
||||
moving_on_model: None,
|
||||
properties_popup: None,
|
||||
properties_scroll: property_sheet::PropertiesScroll::default(),
|
||||
picking_id_color: None,
|
||||
picking_symmetry_plane: false,
|
||||
picking_color: None,
|
||||
screen_pick: None,
|
||||
eyedropper_project_id: project_id,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
screen_picking: raw_window_handle::HasWindowHandle::window_handle(cc).is_ok(),
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -1075,6 +1092,7 @@ impl eframe::App for TextureCraftApp {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.poll_link_imports(ctx);
|
||||
self.thumbs.sync_project_previews(&self.session);
|
||||
self.properties_scroll.sync(&self.session);
|
||||
|
||||
// The library shelf rescans when the window comes back (MaterialCraft may have sent a material)
|
||||
let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true);
|
||||
@@ -1127,9 +1145,6 @@ impl eframe::App for TextureCraftApp {
|
||||
self.ui.mode = state::Mode::Painting;
|
||||
}
|
||||
|
||||
// Before any popup draws, so one a drag closes is gone from this frame
|
||||
popup_drag::close_on_drag_outside(&ctx);
|
||||
|
||||
if !self.ui.hide_ui {
|
||||
titlebar::show(self, ui);
|
||||
banner(self, ui);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use egui::Ui;
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::compose::ImageStore;
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::core::{NormalFormat, Source};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
@@ -17,7 +17,6 @@ use crate::resource_picker;
|
||||
use crate::resource_picker_item::ResourcePickerItem;
|
||||
use crate::slot_thumbnail::{paint_thumbnail, thumbnail};
|
||||
use crate::theme::Tokens;
|
||||
use crate::thumbs::Thumbs;
|
||||
use crate::tile_picture::TilePicture;
|
||||
|
||||
/// The GRAYSCALE section: a slot card for one gray (with its ramp and invert) or an image whose gray is painted
|
||||
@@ -44,7 +43,7 @@ pub(crate) fn grayscale_sheet(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
None => MaskSourceChoice::Uniform,
|
||||
};
|
||||
let ctx = sheet.ui.ctx().clone();
|
||||
let tabs = |_: &mut Thumbs| source_tabs(&app.session.images, shown_color([gray; 3]));
|
||||
let tabs = || source_tabs(&app.session, shown_color([gray; 3]));
|
||||
match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), image, tabs) {
|
||||
Some(MaskSourceChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"),
|
||||
Some(MaskSourceChoice::Image(name)) if app.session.tool.mask_image.as_deref() != Some(name.as_str()) => {
|
||||
@@ -76,8 +75,8 @@ pub(crate) fn grayscale_sheet(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
|
||||
/// The picker's one Resources tab: Textures (Import... first, then the project's images) and Uniform
|
||||
fn source_tabs(images: &ImageStore, uniform: egui::Color32) -> Vec<PickerTab<MaskSourceChoice>> {
|
||||
let textures = ResourcePickerItem::textures(images, MaskSourceChoice::Import, |name| MaskSourceChoice::Image(name.to_owned()));
|
||||
fn source_tabs(session: &Session, uniform: egui::Color32) -> Vec<PickerTab<MaskSourceChoice>> {
|
||||
let textures = ResourcePickerItem::textures(session, MaskSourceChoice::Import, |name| MaskSourceChoice::Image(name.to_owned()));
|
||||
let uniform =
|
||||
vec![ResourcePickerItem { id: MaskSourceChoice::Uniform, label: tr("Uniform value").to_owned(), caption: None, picture: TilePicture::Swatch(uniform) }];
|
||||
let groups =
|
||||
|
||||
@@ -102,7 +102,7 @@ fn shade(material: &OrbMaterial, env: &OrbEnvironment, direction: Vec3, pixel: f
|
||||
|
||||
// Tangent frame on the material: east along the UVs, then north
|
||||
let east = Vec3::new(-direction.z, 0.0, direction.x).try_normalize().unwrap_or(Vec3::X);
|
||||
let north = direction.cross(east).try_normalize().unwrap_or(Vec3::Y);
|
||||
let north = east.cross(direction).try_normalize().unwrap_or(Vec3::Y);
|
||||
let mapped = Vec3::from(sample.normal.map(|component| component * 2.0 - 1.0));
|
||||
let mut surface = (east * mapped.x + north * mapped.y + direction * mapped.z).try_normalize().unwrap_or(direction);
|
||||
if material.has_relief() {
|
||||
|
||||
@@ -471,7 +471,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
input.events.extend(aliases);
|
||||
});
|
||||
|
||||
// Escape closes a dropdown before an eyedropper pick, the colour picker window, Properties, the rail popup, the ID colour pick or the stroke
|
||||
// Let the innermost popup consume Escape before cancelling the active tool
|
||||
let popup_open = egui::Popup::is_any_open(ctx);
|
||||
let picker_open = crate::color_picker::open_window(ctx).is_some();
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use egui::{CursorIcon, Pos2, Rect};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::StackTarget;
|
||||
use texturecraft_engine::core::{EffectKind, LayerId, LayerKind, Projection};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
@@ -36,26 +37,30 @@ impl MoveOnModel {
|
||||
/// The selected fill layer, or the selected fill effect in it (its content or its mask); its projector shows in the 3D view
|
||||
pub(crate) fn selected(app: &TextureCraftApp) -> Option<MoveOnModel> {
|
||||
let layer = app.session.selected_layer()?;
|
||||
let effect = match app.session.target {
|
||||
texturecraft_engine::StackTarget::Content => None,
|
||||
texturecraft_engine::StackTarget::Effect(effect) => Some(effect),
|
||||
texturecraft_engine::StackTarget::Mask => return None,
|
||||
};
|
||||
Some(MoveOnModel { layer, effect })
|
||||
match app.session.target {
|
||||
StackTarget::Content => Some(Self::layer(app.session.project().content_layer(layer)?.id)),
|
||||
StackTarget::Effect(effect) => Some(MoveOnModel { layer, effect: Some(effect) }),
|
||||
StackTarget::Mask => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn projection(self, app: &TextureCraftApp) -> Option<Projection> {
|
||||
let project = &app.session.doc.project;
|
||||
match self.effect {
|
||||
Some(effect) => match &project.effect(effect)?.1.kind {
|
||||
EffectKind::Material(fill) => Some(fill.projection.clone()),
|
||||
EffectKind::Fill { projection, .. } => Some(projection.clone()),
|
||||
/// Resolves the projection and its edit command from the target's effective stacks
|
||||
pub(crate) fn projection_editor(self, app: &TextureCraftApp) -> Option<(&Projection, &'static str)> {
|
||||
let project = app.session.project();
|
||||
let content = project.content_layer(self.layer)?;
|
||||
if let Some(effect_id) = self.effect {
|
||||
let mask_owner = project.layer(project.mask_owner(self.layer)).ok()?;
|
||||
let effect = mask_owner.mask.iter().flat_map(|mask| &mask.effects).chain(&content.content_effects).find(|effect| effect.id == effect_id)?;
|
||||
return match &effect.kind {
|
||||
EffectKind::Material(fill) => Some((&fill.projection, "layer.fill.projection")),
|
||||
EffectKind::Fill { projection, .. } => Some((projection, "effect.set")),
|
||||
_ => None,
|
||||
},
|
||||
None => match &project.layer(self.layer).ok()?.kind {
|
||||
LayerKind::Fill(fill) => Some(fill.projection.clone()),
|
||||
_ => None,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
match &content.kind {
|
||||
LayerKind::Fill(fill) => Some((&fill.projection, "layer.fill.projection")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,7 +100,7 @@ pub(crate) fn holding(app: &mut TextureCraftApp, ctx: &egui::Context) -> bool {
|
||||
pub(crate) fn end_when_gone(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let Some(target) = app.moving_on_model else { return };
|
||||
|
||||
if target.projection(app).is_none() || pad_gone(ctx) {
|
||||
if target.projection_editor(app).is_none() || pad_gone(ctx) {
|
||||
end(app, ctx);
|
||||
}
|
||||
}
|
||||
@@ -135,7 +140,7 @@ fn hold(app: &mut TextureCraftApp, ctx: &egui::Context, pad: &egui::Response, ta
|
||||
held = Some(MoveHold { target, last: at, edited_revision: None, pass: pass.wrapping_sub(1) });
|
||||
}
|
||||
|
||||
let Some(mut held) = held.filter(|_| primary && target.projection(app).is_some()) else {
|
||||
let Some(mut held) = held.filter(|_| primary && target.projection_editor(app).is_some()) else {
|
||||
if app.moving_on_model == Some(target) {
|
||||
end(app, ctx);
|
||||
}
|
||||
@@ -219,11 +224,11 @@ fn dragged(app: &TextureCraftApp, target: MoveOnModel, from: Pos2, to: Pos2, tur
|
||||
}
|
||||
|
||||
if !turn && let Some(round) = RoundGizmo::of(app, rect).filter(|round| round.target == target) {
|
||||
return Some(("layer.fill.projection", round.slid(app, rect, from, to)?));
|
||||
return round.slid(app, rect, from, to);
|
||||
}
|
||||
|
||||
let projection = target.projection(app)?;
|
||||
let (_, rotation, offset) = placement(&projection)?;
|
||||
let (projection, command) = target.projection_editor(app)?;
|
||||
let (_, rotation, offset) = placement(projection)?;
|
||||
let slide = delta * SLIDE_PER_HEIGHT / rect.height().max(1.0);
|
||||
let offset = [offset[0] - slide.x, offset[1] - slide.y];
|
||||
let mut params = match (turn, projection) {
|
||||
@@ -232,7 +237,7 @@ fn dragged(app: &TextureCraftApp, target: MoveOnModel, from: Pos2, to: Pos2, tur
|
||||
(false, _) => json!({"uvOffset": offset}),
|
||||
};
|
||||
merge_target(&mut params, target);
|
||||
Some(("layer.fill.projection", params))
|
||||
Some((command, params))
|
||||
}
|
||||
|
||||
/// The edit a wheel step growing the projection by `growth` makes: a frame grows, other projections' images repeat less
|
||||
@@ -242,10 +247,11 @@ fn resized(app: &TextureCraftApp, target: MoveOnModel, growth: f32, rect: Rect)
|
||||
return Some(("layer.decal.set", frame_target(json!({"size": [width * growth, height * growth]}), &gizmo)));
|
||||
}
|
||||
|
||||
let (tiling, _, _) = placement(&target.projection(app)?)?;
|
||||
let (projection, command) = target.projection_editor(app)?;
|
||||
let (tiling, _, _) = placement(projection)?;
|
||||
let mut params = json!({"tiling": [tiling[0] / growth, tiling[1] / growth]});
|
||||
merge_target(&mut params, target);
|
||||
Some(("layer.fill.projection", params))
|
||||
Some((command, params))
|
||||
}
|
||||
|
||||
/// Adds the `layer` or `effect` param naming `target` to `params`
|
||||
@@ -322,6 +328,7 @@ mod tests {
|
||||
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
let from = pointer.at;
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press starts the hold");
|
||||
|
||||
let moved = vec2(-300.0, -20.0);
|
||||
@@ -428,6 +435,7 @@ mod tests {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (mut harness, layer) = fill_app("triplanar");
|
||||
let pad = harness.get_by_label("Move on model").rect();
|
||||
|
||||
assert!((pad.width() - pad.height()).abs() < 1.0 && pad.width() > 60.0, "Move on model is the preview square, no row of its own: {pad:?}");
|
||||
|
||||
let before = projection(&harness, layer);
|
||||
@@ -458,10 +466,11 @@ mod tests {
|
||||
|
||||
pointer.drags(&mut harness, vec2(-40.0, 0.0), 30, Modifiers::SHIFT);
|
||||
let shifted = uv_of(&projection(&harness, layer));
|
||||
|
||||
assert!(shifted.rotation > 0.0, "Shift turns the image: {shifted:?}");
|
||||
assert_eq!(projector_offset(&projection(&harness, layer)), [0.0; 3], "and does not slide it");
|
||||
|
||||
// The right button pressed once the drag has carried the held pointer over the 3D view, the left still holding the button
|
||||
// Press the second button over the viewport while the first still holds the drag
|
||||
let over_view = rect.center() + vec2(-100.0, 80.0);
|
||||
pointer.drags(&mut harness, over_view - (from + vec2(-40.0, 0.0)), 30, Modifiers::NONE);
|
||||
let slid = projection(&harness, layer);
|
||||
|
||||
@@ -35,6 +35,7 @@ const QUICK_BELOW_PX: usize = 48;
|
||||
#[derive(Default)]
|
||||
pub struct OrbPreviews {
|
||||
pictures: HashMap<u64, Picture>,
|
||||
next_request: u64,
|
||||
/// The picture last drawn at each place and the pass it was drawn in, shown while that place's new one renders
|
||||
shown: HashMap<Id, (TextureHandle, u64)>,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -50,11 +51,13 @@ impl OrbPreviews {
|
||||
let mut previews = shared.lock().ok()?;
|
||||
previews.take_results(ctx);
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
let request = previews.next_request;
|
||||
if let Entry::Vacant(slot) = previews.pictures.entry(key) {
|
||||
let job = job();
|
||||
slot.insert(Picture { texture: None, full: false, drawn: pass, _images: job.material.image_handles() });
|
||||
let job = OrbJob { request, ..job() };
|
||||
slot.insert(Picture { request, texture: None, full: false, drawn: pass, _images: job.material.image_handles() });
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let job = OrbJob { place, ..job };
|
||||
previews.next_request = request.wrapping_add(1);
|
||||
previews.start(ctx, job);
|
||||
}
|
||||
let ready = previews.pictures.get_mut(&key).and_then(|picture| {
|
||||
@@ -93,8 +96,9 @@ impl OrbPreviews {
|
||||
previews.shown.get(&Id::unique(("material_orb", place))).map(|(texture, _)| texture.size())
|
||||
}
|
||||
|
||||
fn store(&mut self, ctx: &Context, key: u64, full: bool, image: ColorImage) {
|
||||
fn store(&mut self, ctx: &Context, key: u64, request: u64, full: bool, image: ColorImage) {
|
||||
if let Some(picture) = self.pictures.get_mut(&key)
|
||||
&& picture.request == request
|
||||
&& !picture.full
|
||||
{
|
||||
picture.texture = Some(ctx.load_texture("material-orb", image, TextureOptions::LINEAR));
|
||||
@@ -120,7 +124,7 @@ impl OrbPreviews {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn start(&mut self, ctx: &Context, job: OrbJob) {
|
||||
let job = OrbJob { quick: false, ..job };
|
||||
self.store(ctx, job.key, true, job.picture());
|
||||
self.store(ctx, job.key, job.request, true, job.picture());
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -136,7 +140,7 @@ impl OrbPreviews {
|
||||
None => {
|
||||
// No thread: render here rather than show nothing
|
||||
let job = OrbJob { quick: false, ..job };
|
||||
self.store(ctx, key, true, job.picture());
|
||||
self.store(ctx, key, job.request, true, job.picture());
|
||||
return;
|
||||
}
|
||||
},
|
||||
@@ -145,7 +149,7 @@ impl OrbPreviews {
|
||||
Ok(()) => self.worker = Some(worker),
|
||||
Err(std::sync::mpsc::SendError((job, _))) => {
|
||||
let job = OrbJob { quick: false, ..job };
|
||||
self.store(ctx, key, true, job.picture());
|
||||
self.store(ctx, key, job.request, true, job.picture());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,10 +160,13 @@ impl OrbPreviews {
|
||||
let results: Vec<OrbResult> = worker.results.try_iter().collect();
|
||||
for result in results {
|
||||
match result {
|
||||
OrbResult::Picture { key, full, image } => self.store(ctx, key, full, image),
|
||||
OrbResult::Dropped { key } => {
|
||||
// Asked for again the next time it is drawn (its place keeps showing what it last showed)
|
||||
self.pictures.remove(&key);
|
||||
OrbResult::Picture { key, request, full, image } => self.store(ctx, key, request, full, image),
|
||||
OrbResult::Dropped { key, request } => {
|
||||
if let Entry::Occupied(entry) = self.pictures.entry(key)
|
||||
&& entry.get().request == request
|
||||
{
|
||||
entry.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,7 +175,7 @@ impl OrbPreviews {
|
||||
|
||||
/// Keep only the newest job per place (others than [`Id::NULL`]); returns the keys of the jobs dropped
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn newest_per_place(waiting: &mut Vec<OrbJob>) -> Vec<u64> {
|
||||
fn newest_per_place(waiting: &mut Vec<OrbJob>) -> Vec<(u64, u64)> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut dropped = Vec::new();
|
||||
let mut kept: Vec<OrbJob> = Vec::with_capacity(waiting.len());
|
||||
@@ -176,7 +183,7 @@ fn newest_per_place(waiting: &mut Vec<OrbJob>) -> Vec<u64> {
|
||||
if job.place == Id::NULL || seen.insert(job.place) {
|
||||
kept.push(job);
|
||||
} else {
|
||||
dropped.push(job.key);
|
||||
dropped.push((job.key, job.request));
|
||||
}
|
||||
}
|
||||
kept.reverse();
|
||||
@@ -245,7 +252,7 @@ mod tests {
|
||||
|
||||
let sizes = draw_until_settled(&ctx, place, &job);
|
||||
|
||||
// A fast render can bring both pictures between two frames, so only the full one is sure to show; the quick one never comes after it
|
||||
// Both pictures can arrive between frames, so only the full picture is guaranteed to appear
|
||||
let quick_then_full: &[[usize; 2]] = &[[50, 50], [200, 200]];
|
||||
assert!(sizes == quick_then_full || sizes == quick_then_full[1..], "the quick picture, if shown, then the full one: {sizes:?}");
|
||||
assert!(OrbPreviews::settled(&ctx));
|
||||
@@ -305,6 +312,41 @@ mod tests {
|
||||
assert_eq!(waiting.iter().map(|job| job.key).collect::<Vec<_>>(), vec![other.key, job(0.3).key]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delayed_drop_keeps_the_replacement_render_for_an_evicted_look() {
|
||||
let ctx = Context::default();
|
||||
let (jobs, submitted) = std::sync::mpsc::channel();
|
||||
let (completed, results) = std::sync::mpsc::channel();
|
||||
let previews = OrbPreviews { worker: Some(Worker { jobs, results }), ..Default::default() };
|
||||
ctx.data_mut(|data| data.insert_temp(Id::unique("orb_previews"), Arc::new(Mutex::new(previews))));
|
||||
let first = OrbJob::new(copper(0.0), 16, Color32::BLACK);
|
||||
let place = Id::unique("changing material");
|
||||
let request = |job: &OrbJob| {
|
||||
run(&ctx, |ctx| {
|
||||
OrbPreviews::texture(ctx, place, job.key, || job.clone());
|
||||
})
|
||||
};
|
||||
|
||||
request(&first);
|
||||
let (old_job, _) = submitted.try_recv().unwrap();
|
||||
for index in 1..=MAX_PICTURES {
|
||||
let other = OrbJob::new(copper(index as f32 / MAX_PICTURES as f32), 16, Color32::BLACK);
|
||||
request(&other);
|
||||
submitted.try_recv().unwrap();
|
||||
}
|
||||
request(&first);
|
||||
let (replacement, _) = submitted.try_recv().expect("eviction requested a new render");
|
||||
|
||||
completed.send(OrbResult::Dropped { key: old_job.key, request: old_job.request }).unwrap();
|
||||
completed
|
||||
.send(OrbResult::Picture { key: replacement.key, request: replacement.request, full: true, image: ColorImage::filled([16, 16], Color32::WHITE) })
|
||||
.unwrap();
|
||||
let texture = OrbPreviews::texture(&ctx, place, first.key, || first.clone());
|
||||
|
||||
assert!(texture.is_some(), "the new render should be visible after the old job was dropped");
|
||||
assert!(submitted.try_recv().is_err(), "the completed look needs no third render");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn places_no_longer_drawn_let_go_of_their_last_picture_past_the_cap() {
|
||||
let ctx = Context::default();
|
||||
|
||||
@@ -12,6 +12,7 @@ use crate::orb_material::OrbMaterial;
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct OrbJob {
|
||||
pub(super) key: u64,
|
||||
pub(super) request: u64,
|
||||
pub(super) material: OrbMaterial,
|
||||
pub(super) side: usize,
|
||||
pub(super) backdrop: Color32,
|
||||
@@ -25,6 +26,7 @@ pub(crate) struct OrbJob {
|
||||
impl OrbJob {
|
||||
pub(crate) fn new(material: OrbMaterial, side: usize, backdrop: Color32) -> OrbJob {
|
||||
OrbJob {
|
||||
request: 0,
|
||||
key: OrbJob::key_of(&material, side, backdrop),
|
||||
material,
|
||||
side,
|
||||
|
||||
@@ -4,11 +4,13 @@ use egui::ColorImage;
|
||||
pub(super) enum OrbResult {
|
||||
Picture {
|
||||
key: u64,
|
||||
request: u64,
|
||||
full: bool,
|
||||
image: ColorImage,
|
||||
},
|
||||
/// A newer job for its place replaced it before it was finished
|
||||
Dropped {
|
||||
key: u64,
|
||||
request: u64,
|
||||
},
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use texturecraft_engine::compose::ImageRes;
|
||||
pub(super) struct Picture {
|
||||
pub(super) texture: Option<TextureHandle>,
|
||||
pub(super) full: bool,
|
||||
pub(super) request: u64,
|
||||
/// The pass it was last drawn in
|
||||
pub(super) drawn: u64,
|
||||
/// The images it shows, so no new image reuses their addresses (and so their key) while it is cached
|
||||
|
||||
@@ -28,13 +28,16 @@ impl Worker {
|
||||
waiting.push(job);
|
||||
repaint = Some(ctx);
|
||||
}
|
||||
let previous_len = waiting.len();
|
||||
for (job, ctx) in job_rx.try_iter() {
|
||||
waiting.push(job);
|
||||
repaint = Some(ctx);
|
||||
}
|
||||
for key in newest_per_place(&mut waiting) {
|
||||
if result_tx.send(OrbResult::Dropped { key }).is_err() {
|
||||
return;
|
||||
if waiting.len() > previous_len {
|
||||
for (key, request) in newest_per_place(&mut waiting) {
|
||||
if result_tx.send(OrbResult::Dropped { key, request }).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +53,7 @@ impl Worker {
|
||||
Err(_) => job.picture(),
|
||||
};
|
||||
let full = !job.quick;
|
||||
if result_tx.send(OrbResult::Picture { key: job.key, full, image }).is_err() {
|
||||
if result_tx.send(OrbResult::Picture { key: job.key, request: job.request, full, image }).is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,14 +15,14 @@ pub(crate) enum Hold {
|
||||
|
||||
impl Hold {
|
||||
/// The way this platform holds a pointer; Wayland is told apart from X11 the way the window system picks it
|
||||
pub(crate) fn of_platform() -> Hold {
|
||||
pub(crate) fn of_platform(ctx: &egui::Context) -> Hold {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
Hold::Free
|
||||
} else if cfg!(target_os = "macos") {
|
||||
Hold::Locked
|
||||
} else if cfg!(target_os = "windows") {
|
||||
Hold::PutBackFolded
|
||||
} else if std::env::var_os("WAYLAND_DISPLAY").is_none() {
|
||||
} else if !crate::uses_wayland(ctx) {
|
||||
Hold::PutBack
|
||||
} else {
|
||||
Hold::Locked
|
||||
|
||||
@@ -76,12 +76,12 @@ pub(crate) fn rewrite(ctx: &Context, raw: &mut RawInput) {
|
||||
|
||||
/// The end of the app's frame: a drag that asked this frame takes or keeps the pointer (hidden, put back), one that stopped asking lets it go
|
||||
pub(crate) fn settle(ctx: &Context) {
|
||||
let asked = ctx.data(|data| data.get_temp::<u64>(asked_id())) == Some(ctx.cumulative_pass_nr());
|
||||
let asked = !crate::viewport::focus_lost(ctx) && ctx.data(|data| data.get_temp::<u64>(asked_id())) == Some(ctx.cumulative_pass_nr());
|
||||
let held = ctx.data(|data| data.get_temp::<Lock>(lock_id())).filter(|lock| !lock.let_go);
|
||||
let mut lock = match (asked, held) {
|
||||
(true, Some(lock)) => lock,
|
||||
(true, None) => {
|
||||
let hold = ctx.data(|data| data.get_temp::<Hold>(hold_override_id())).unwrap_or_else(Hold::of_platform);
|
||||
let hold = ctx.data(|data| data.get_temp::<Hold>(hold_override_id())).unwrap_or_else(|| Hold::of_platform(ctx));
|
||||
let (origin, latest) = ctx.input(|input| (input.pointer.press_origin(), input.pointer.latest_pos()));
|
||||
let (Some(seen), false) = (latest, hold == Hold::Free) else {
|
||||
return;
|
||||
@@ -94,7 +94,7 @@ pub(crate) fn settle(ctx: &Context) {
|
||||
}
|
||||
(false, Some(mut lock)) => {
|
||||
// Put back before the grab ends: Wayland moves only a locked pointer
|
||||
if lock.seen.distance(lock.anchor) > PUT_BACK_REACH {
|
||||
if !lock.putting_back && lock.seen.distance(lock.anchor) > PUT_BACK_REACH {
|
||||
ctx.send_viewport_cmd(ViewportCommand::CursorPosition(lock.anchor));
|
||||
}
|
||||
if lock.hold == Hold::Locked {
|
||||
@@ -109,7 +109,7 @@ pub(crate) fn settle(ctx: &Context) {
|
||||
};
|
||||
|
||||
ctx.set_cursor_icon(CursorIcon::None);
|
||||
if lock.hold.puts_back() && lock.seen.distance(lock.anchor) > PUT_BACK_REACH {
|
||||
if lock.hold.puts_back() && !lock.putting_back && lock.seen.distance(lock.anchor) > PUT_BACK_REACH {
|
||||
ctx.send_viewport_cmd(ViewportCommand::CursorPosition(lock.anchor));
|
||||
|
||||
// A folding system reads every later move from where it put the pointer, its own move folded in
|
||||
|
||||
@@ -39,6 +39,7 @@ fn scrub_past_the_edge(harness: &mut Harness<'static, Vec2>) -> SystemPointer {
|
||||
fn a_put_back_pointer_never_reaches_the_edge_and_comes_back_where_the_press_began() {
|
||||
let mut harness = scrub_strip(Hold::PutBack);
|
||||
let mut pointer = scrub_past_the_edge(&mut harness);
|
||||
|
||||
assert!(pointer.put_backs >= 30, "the pointer went back after every move: {}", pointer.put_backs);
|
||||
assert!(pointer.at.distance(PRESS) < 1.0, "it never strayed from the press: {:?}", pointer.at);
|
||||
|
||||
@@ -78,6 +79,7 @@ fn a_folded_put_back_counts_every_move_from_the_press() {
|
||||
fn a_locked_pointer_reads_raw_motion_and_is_let_go_where_the_press_began() {
|
||||
let mut harness = scrub_strip(Hold::Locked);
|
||||
let mut pointer = scrub_past_the_edge(&mut harness);
|
||||
|
||||
assert!(pointer.locked, "the system holds the pointer");
|
||||
assert_eq!(pointer.at, PRESS, "it never moved");
|
||||
|
||||
|
||||
@@ -1,22 +1,62 @@
|
||||
//! A press outside the popups that turns into a drag closes them: egui closes a popup only on a click, so a paint stroke or slider drag left it open
|
||||
//! Dismisses popups when a primary press outside them becomes a drag
|
||||
|
||||
use egui::{Order, PointerButton};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Whether a primary press outside every popup has just been held or moved past a click: it starts a stroke, a slider drag or a panel move
|
||||
pub(crate) fn drag_outside_popups(ctx: &egui::Context) -> bool {
|
||||
let (dragging, origin, orbiting) = ctx.input(|input| {
|
||||
let dragging = input.pointer.button_down(PointerButton::Primary) && input.pointer.is_decidedly_dragging();
|
||||
(dragging, input.pointer.press_origin(), input.modifiers.alt)
|
||||
});
|
||||
use egui::{Event, Id, Order, PointerButton, ViewportId};
|
||||
|
||||
// Alt+drag orbits the camera, which keeps popups open like the colour picker; a drag in a popup or a dropdown it opened stays in it
|
||||
let over_popup = |at| ctx.layer_id_at(at).is_some_and(|layer| matches!(layer.order, Order::Foreground | Order::Tooltip | Order::Debug));
|
||||
dragging && !orbiting && origin.is_some_and(|at| !over_popup(at))
|
||||
/// Installs dismissal before drawing popups in the main and native floating windows
|
||||
pub(crate) fn install(ctx: &egui::Context) {
|
||||
ctx.on_begin_pass("dismiss popups on outside drag", Arc::new(|ui| update(ui.ctx())));
|
||||
}
|
||||
|
||||
/// Closes egui's open popup, menu or dropdown when [`drag_outside_popups`]; a plain click outside is egui's own close
|
||||
pub(crate) fn close_on_drag_outside(ctx: &egui::Context) {
|
||||
if egui::Popup::is_any_open(ctx) && drag_outside_popups(ctx) {
|
||||
/// Tracks the primary press across frames, including the frame that releases it
|
||||
fn update(ctx: &egui::Context) {
|
||||
let viewport = ctx.viewport_id();
|
||||
let press_id = Id::unique("popup-drag-press");
|
||||
let result_id = Id::unique("popup-drag-result");
|
||||
let (press, down, drag) = ctx.input(|input| {
|
||||
let pointer = &input.pointer;
|
||||
let press = pointer
|
||||
.button_pressed(PointerButton::Primary)
|
||||
.then(|| {
|
||||
input.events.iter().rev().find_map(|event| match event {
|
||||
Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, .. } => Some(*pos),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
.flatten();
|
||||
let down = input.focused && pointer.button_down(PointerButton::Primary);
|
||||
let released_without_click = pointer.button_released(PointerButton::Primary) && !pointer.button_clicked(PointerButton::Primary);
|
||||
let drag = input.focused && !input.modifiers.alt && (released_without_click || (down && pointer.is_decidedly_dragging()));
|
||||
(press, down, drag)
|
||||
});
|
||||
|
||||
let started_outside =
|
||||
press.map(|position| ctx.layer_id_at(position).is_none_or(|layer| !matches!(layer.order, Order::Foreground | Order::Tooltip | Order::Debug)));
|
||||
let dismiss = ctx.data_mut(|data| {
|
||||
let previous = data.get_temp::<(ViewportId, bool)>(press_id).filter(|(owner, _)| *owner == viewport);
|
||||
let outside = started_outside.or(previous.map(|(_, outside)| outside)).unwrap_or(false);
|
||||
if let Some(started_outside) = started_outside.filter(|_| down) {
|
||||
data.insert_temp(press_id, (viewport, started_outside));
|
||||
} else if !down && previous.is_some() {
|
||||
data.remove::<(ViewportId, bool)>(press_id);
|
||||
}
|
||||
|
||||
let dismiss = outside && drag;
|
||||
if viewport == ViewportId::ROOT {
|
||||
data.insert_temp(result_id, dismiss);
|
||||
}
|
||||
|
||||
dismiss
|
||||
});
|
||||
|
||||
if dismiss && egui::Popup::is_any_open(ctx) {
|
||||
egui::Popup::close_all(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the main window's current pass has an outside drag for its app-owned popups
|
||||
pub(crate) fn drag_outside_popups(ctx: &egui::Context) -> bool {
|
||||
let id = Id::unique("popup-drag-result");
|
||||
ctx.data(|data| data.get_temp::<bool>(id).unwrap_or(false))
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The preview square's two dots: a ring where the projection sits with Offset 0, a filled dot where its Offset puts it, a dotted line between
|
||||
|
||||
use egui::{Painter, Pos2, Stroke};
|
||||
use egui::{Painter, Pos2, Rect, Stroke, Vec2};
|
||||
|
||||
use crate::theme::Tokens;
|
||||
|
||||
@@ -28,23 +28,28 @@ const LINE_DOT: f32 = 0.9;
|
||||
/// The width of the rim under the dotted line's dots (points)
|
||||
const LINE_RIM: f32 = 0.6;
|
||||
|
||||
/// Most dots the line draws: more than any preview square holds, the rest would be cut off anyway
|
||||
/// Bound paint work even when the preview stretches across a very large clip rectangle.
|
||||
const MAX_LINE_DOTS: usize = 256;
|
||||
|
||||
/// Paints the two dots and the dotted line between them, from the filled dot out so a ring far past the square still gets its line
|
||||
/// Paint the two markers and their dotted connector, retaining the spacing from the filled dot.
|
||||
pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, tokens: &Tokens) {
|
||||
let span = center - position;
|
||||
let length = span.length();
|
||||
let start = DOT_RADIUS + LINE_SPACING;
|
||||
let end = length - RING_RADIUS - LINE_SPACING / 2.0;
|
||||
let clip = painter.clip_rect();
|
||||
|
||||
if length.is_finite() && end > start {
|
||||
if length.is_finite() && end > start && !clip.is_negative() {
|
||||
let toward = span / length;
|
||||
let count = (((end - start) / LINE_SPACING).floor() as usize).min(MAX_LINE_DOTS);
|
||||
for step in 0..=count {
|
||||
let at = position + toward * (start + step as f32 * LINE_SPACING);
|
||||
painter.circle_filled(at, LINE_DOT + LINE_RIM, tokens.field);
|
||||
painter.circle_filled(at, LINE_DOT, tokens.text);
|
||||
let radius = LINE_DOT + LINE_RIM;
|
||||
if let Some((visible_start, visible_end)) = visible_distances(clip.expand(radius), position, toward, start, end) {
|
||||
let first = ((visible_start - start) / LINE_SPACING).ceil() as usize;
|
||||
let last = ((visible_end - start) / LINE_SPACING).floor() as usize;
|
||||
for step in first..=last.min(first.saturating_add(MAX_LINE_DOTS - 1)) {
|
||||
let at = position + toward * (start + step as f32 * LINE_SPACING);
|
||||
painter.circle_filled(at, radius, tokens.field);
|
||||
painter.circle_filled(at, LINE_DOT, tokens.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,3 +58,57 @@ pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, toke
|
||||
painter.circle_filled(position, DOT_RADIUS + DOT_RIM, tokens.field);
|
||||
painter.circle_filled(position, DOT_RADIUS, tokens.text);
|
||||
}
|
||||
|
||||
/// Restrict the connector's distance interval to where it intersects the clip rectangle.
|
||||
fn visible_distances(clip: Rect, origin: Pos2, direction: Vec2, mut start: f32, mut end: f32) -> Option<(f32, f32)> {
|
||||
for axis in 0..2 {
|
||||
let origin = origin[axis];
|
||||
let (low, high) = (clip.min[axis], clip.max[axis]);
|
||||
let direction = direction[axis];
|
||||
if direction == 0.0 {
|
||||
if origin < low || origin > high {
|
||||
return None;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
let (near, far) = ((low - origin) / direction, (high - origin) / direction);
|
||||
start = start.max(near.min(far));
|
||||
end = end.min(near.max(far));
|
||||
}
|
||||
|
||||
(start <= end).then_some((start, end))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use egui::{Context, Id, LayerId, Order, Shape, pos2};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_visible_connector_reaches_a_ring_when_the_offset_dot_is_far_outside() {
|
||||
let clip = Rect::from_min_max(Pos2::ZERO, pos2(100.0, 100.0));
|
||||
let tokens = Tokens::for_brightness(crate::theme::Brightness::MediumDark);
|
||||
let ctx = Context::default();
|
||||
let painter_layer = LayerId::new(Order::Foreground, Id::unique("connector"));
|
||||
|
||||
let connectors = [(clip.center(), pos2(4000.0, 50.0)), (clip.center(), pos2(80.0, 50.0)), (pos2(-4000.0, -20.0), pos2(4000.0, -20.0))];
|
||||
let results = connectors.map(|(ring, dot)| {
|
||||
let mut output = ctx.run_ui(Default::default(), |ui| preview_dots(&ui.ctx().layer_painter(painter_layer).with_clip_rect(clip), ring, dot, &tokens));
|
||||
output.textures_delta.clear();
|
||||
let dots = output.shapes.iter().filter_map(|shape| match &shape.shape {
|
||||
Shape::Circle(circle) if circle.radius == LINE_DOT => Some(circle.center),
|
||||
_ => None,
|
||||
});
|
||||
let (queued, visible) = dots.fold((0, 0), |(queued, visible), dot| (queued + 1, visible + usize::from(clip.contains(dot))));
|
||||
eprintln!("{ring:?} to {dot:?}: {queued} queued connector dots, {visible} visible");
|
||||
|
||||
(queued, visible)
|
||||
});
|
||||
|
||||
assert!(results[0].1 > 2 && results[1].1 > 2, "the painted connectors reach the visible ring");
|
||||
assert_eq!(results[2].0, 0, "a connector wholly outside the square queues no dots");
|
||||
}
|
||||
}
|
||||
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user