mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 00:59:29 +01:00
Merge upstream/main
This commit is contained in:
commit
47bd83ea46
191 files changed
+19434
-2167
No files matched your search
Generated
+1
@@ -4604,6 +4604,7 @@ dependencies = [
|
||||
"craft-update",
|
||||
"eframe",
|
||||
"egui",
|
||||
"egui_kittest",
|
||||
"image",
|
||||
"log",
|
||||
"rfd",
|
||||
|
||||
@@ -38,5 +38,9 @@ craft-update = { workspace = true }
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
craft-menu = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# The pointer-hold test drives the windowed app's frames (src/main.rs)
|
||||
egui_kittest = { version = "0.37", features = ["eframe"] }
|
||||
|
||||
[build-dependencies]
|
||||
winresource = "0.1"
|
||||
@@ -164,12 +164,14 @@ impl eframe::App for Shell {
|
||||
self.app.save(storage);
|
||||
}
|
||||
|
||||
fn raw_input_hook(&mut self, _ctx: &egui::Context, _raw: &mut egui::RawInput) {
|
||||
// winit gives the window its caption back when it changes the window's flags (maximize,
|
||||
// restore, …): take it off again before the frame is laid out.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
// Restore the frameless style after winit changes the window flags
|
||||
if let Some(guard) = self.window_frame.as_mut() {
|
||||
guard();
|
||||
}
|
||||
|
||||
// The app's own hook: a drag holding the pointer reads its moves from it
|
||||
self.app.raw_input_hook(ctx, raw);
|
||||
}
|
||||
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
@@ -388,4 +390,55 @@ mod tests {
|
||||
std::fs::remove_file(&ron_path).unwrap();
|
||||
assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default());
|
||||
}
|
||||
|
||||
/// How far the test's drag moves the mouse in one frame, in points
|
||||
const DRAG_STEP: egui::Vec2 = egui::vec2(80.0, 0.0);
|
||||
|
||||
/// Points within which a put-back lands on the press point (the system rounds it to whole pixels)
|
||||
const PUT_BACK_REACH: f32 = 1.0;
|
||||
|
||||
/// One frame of the window: the system's events go through the window's raw input hook, as eframe sends them; returns what the app asked of the window
|
||||
fn window_frame(harness: &mut egui_kittest::Harness<'static, Shell>, events: Vec<egui::Event>) -> Vec<egui::ViewportCommand> {
|
||||
let ctx = harness.ctx.clone();
|
||||
let mut raw = harness.input_mut().clone();
|
||||
raw.events.extend(events);
|
||||
eframe::App::raw_input_hook(harness.state_mut(), &ctx, &mut raw);
|
||||
*harness.input_mut() = raw;
|
||||
harness.step();
|
||||
harness.output().viewport_output.get(&egui::ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Holding the fill's preview square in the window holds the system's pointer: put back to the press point every frame, or locked where the system locks it
|
||||
#[test]
|
||||
fn the_window_holds_the_pointer_while_the_preview_square_is_held() {
|
||||
let session = Session::new_project("Hold", texturecraft_engine::geom::primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
|
||||
let builder = egui_kittest::Harness::builder().with_size(egui::vec2(DEFAULT_SIZE[0], DEFAULT_SIZE[1]));
|
||||
let mut harness = builder.build_eframe(|cc| Shell {
|
||||
app: TextureCraftApp::new(cc, session),
|
||||
window_frame: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
});
|
||||
harness.run_steps(4);
|
||||
let layer = harness.state_mut().app.run("layer.add.fill", serde_json::json!({})).unwrap()["layer"].clone();
|
||||
harness.state_mut().app.run("layer.fill.projection", serde_json::json!({"layer": layer, "projection": "triplanar"})).unwrap();
|
||||
harness.run_steps(2);
|
||||
|
||||
let pad = egui_kittest::kittest::Queryable::get_by_label(&harness, "Move on model").rect().center();
|
||||
let press = egui::Event::PointerButton { pos: pad, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE };
|
||||
let pressed = window_frame(&mut harness, vec![egui::Event::PointerMoved(pad), press]);
|
||||
let locked = pressed.contains(&egui::ViewportCommand::CursorGrab(egui::CursorGrab::Locked));
|
||||
|
||||
// A locked pointer stays still and the system reports only its raw motion
|
||||
let mut moves = vec![egui::Event::MouseMoved(DRAG_STEP)];
|
||||
if !locked {
|
||||
moves.push(egui::Event::PointerMoved(pad + DRAG_STEP));
|
||||
}
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
@@ -284,8 +284,10 @@ mod tests {
|
||||
let mut mesh = texturecraft_engine::geom::primitives::plane(2.0, 1);
|
||||
mesh.append(&texturecraft_engine::geom::primitives::plane(2.0, 1));
|
||||
let mut session = Session::new_project("Test", mesh, "two-planes", None, 128).unwrap();
|
||||
|
||||
assert_eq!(session.caches.len(), 2);
|
||||
session.images.insert("red".into(), Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]], srgb: true }));
|
||||
|
||||
session.images.insert("red".into(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true)));
|
||||
execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap();
|
||||
let camera = session.camera;
|
||||
let uv = |ts| ViewKind::Uv { ts, zoom: 1.0, pan: [0.0, 0.0], rotation: 0.0 };
|
||||
@@ -302,6 +304,7 @@ mod tests {
|
||||
assert!(first.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20));
|
||||
|
||||
let (_, _, second) = gpu.render(&mut session, uv(1), [128, 128], camera).unwrap();
|
||||
|
||||
assert!(second.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20));
|
||||
assert_eq!(gpu.h.renderer.aux_size(1), Some(128));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! The frame an axis planar projection projects from: moving one on the model places it as that frame, so its images land where they did
|
||||
|
||||
use texturecraft_core::{Decal, Projection, Projector, Source};
|
||||
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};
|
||||
|
||||
/// 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 };
|
||||
|
||||
if !culling_folds(projector) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, bounds)?;
|
||||
|
||||
// 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);
|
||||
Some(Projection::Planar { scale: *scale, axis: *axis, offset: *offset, uv, projector, placed: Some(frame) })
|
||||
}
|
||||
|
||||
/// Whether placing an axis planar that reads `sources` would move a pattern: a procedural reads an axis planar's plane but a placed frame's uv, so such a planar keeps its axis
|
||||
pub fn placing_moves_pattern<'a>(mut sources: impl Iterator<Item = &'a Source>) -> bool {
|
||||
sources.any(|source| matches!(source, Source::Procedural { .. }))
|
||||
}
|
||||
|
||||
/// The frame of an axis planar projection: its image's 0..1 square on the plane through the mesh, turned and sized by `projector`
|
||||
pub fn axis_frame(scale: f32, axis: u8, offset: Vec3, projector: &Projector, bounds: (Vec3, Vec3)) -> Option<Decal> {
|
||||
let (center, radius) = mesh_frame(bounds);
|
||||
let [x, y, z] = projector.rotation.map(f32::to_radians);
|
||||
let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x);
|
||||
let stretch = projector_stretch(projector);
|
||||
let scale = nonzero_stretch(scale);
|
||||
|
||||
// Where the image's centre sits, then its across, up and out directions with the stretch along each
|
||||
let origin = center + turn * (stretch * -offset / scale) * radius;
|
||||
let (across, up, out) = match axis {
|
||||
0 => (Vec3::Z, Vec3::Y, Vec3::NEG_X),
|
||||
1 => (Vec3::X, Vec3::NEG_Z, Vec3::Y),
|
||||
_ => (Vec3::X, Vec3::Y, Vec3::Z),
|
||||
};
|
||||
let side = |direction: Vec3| 2.0 * radius * direction.abs().dot(stretch) / scale;
|
||||
|
||||
// A negative stretch or scale turns that side over
|
||||
let flip = |direction: Vec3| direction * side(direction).signum();
|
||||
let (across, up) = (flip(across), flip(up));
|
||||
let size = [side(across).abs(), side(up).abs()];
|
||||
let out = turn * across.cross(up).normalize_or(out);
|
||||
|
||||
// Deep enough never to crop the mesh by depth: the fade starts at three quarters of it
|
||||
let reach = (radius + (origin - center).length()) / DEPTH_FADE_START * DEPTH_SPARE;
|
||||
let frame = Decal {
|
||||
center: origin.to_array(),
|
||||
normal: out.to_array(),
|
||||
up: (turn * up).to_array(),
|
||||
size,
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: reach,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
};
|
||||
(origin.is_finite() && size.iter().all(|side| side.is_finite() && *side > 0.0) && reach.is_finite()).then_some(frame)
|
||||
}
|
||||
|
||||
/// Extra reach past the farthest mesh point
|
||||
const DEPTH_SPARE: f32 = 1.01;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_core::{Backface, ShapeCrop, UvTransform};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
use super::*;
|
||||
use crate::pattern::{Coords, image_samples};
|
||||
use crate::projector_cover::{framed_cover, projector_cover};
|
||||
|
||||
/// Points spread through the box `lo`..`hi` with varied normals
|
||||
fn points(lo: Vec3, hi: Vec3) -> Vec<(Vec3, Vec3)> {
|
||||
(0..64)
|
||||
.map(|i| {
|
||||
let spread = |salt: u32| ((i * 37 + salt * 11) % 64) as f32 / 63.0;
|
||||
let position = lo + (hi - lo) * Vec3::new(spread(1), spread(2), spread(3));
|
||||
let normal = Vec3::new(spread(4) - 0.4, spread(5) - 0.3, spread(6) - 0.2).normalize_or(Vec3::Z);
|
||||
(position, normal)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_axis_planar_reads_images_where_it_did() {
|
||||
let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5));
|
||||
let center = (lo + hi) * 0.5;
|
||||
let radius = (hi - lo).length() * 0.5;
|
||||
for axis in 0..3 {
|
||||
for (rotation, stretch) in [([0.0; 3], [1.0; 3]), ([20.0, -35.0, 50.0], [1.5, 0.7, 2.0])] {
|
||||
for crop in [ShapeCrop::ExtendsOutside, ShapeCrop::Cropped] {
|
||||
let projector = Projector { rotation, scale: stretch, crop, ..Projector::default() };
|
||||
let uv = UvTransform { tiling: [2.0, 3.0], rotation: 30.0, offset: [0.1, -0.2] };
|
||||
let axis_planar = Projection::Planar { scale: 1.7, axis, offset: [0.3, -0.4, 0.2], uv, projector, placed: None };
|
||||
let placed = placed_from_axis(&axis_planar, (lo, hi)).expect("an axis planar has a frame");
|
||||
for (position, normal) in points(lo, hi) {
|
||||
let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal };
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_axis_planar_keeps_what_backface_culling_hides() {
|
||||
let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5));
|
||||
let center = (lo + hi) * 0.5;
|
||||
let radius = (hi - lo).length() * 0.5;
|
||||
let backface = Backface { on: true, angle: 60.0, hardness: 1.0 };
|
||||
|
||||
// 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]] {
|
||||
let projector = Projector { scale: stretch, backface, ..Projector::default() };
|
||||
let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
|
||||
let Some(placed) = placed_from_axis(&axis_planar, (lo, hi)) else {
|
||||
assert!(!culling_folds(&projector), "{stretch:?}: only a stretch culling cannot keep stays unplaced");
|
||||
continue;
|
||||
};
|
||||
|
||||
for (position, normal) in points(lo, hi).into_iter().chain([halfway]) {
|
||||
let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal };
|
||||
let (_, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers");
|
||||
assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "{stretch:?}: culling changed at {normal}");
|
||||
}
|
||||
}
|
||||
|
||||
let even = Projector { scale: [1.7; 3], backface, ..Projector::default() };
|
||||
let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: even, placed: None };
|
||||
assert!(placed_from_axis(&axis_planar, (lo, hi)).is_some(), "an even stretch is still placed");
|
||||
}
|
||||
|
||||
#[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");
|
||||
assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none());
|
||||
assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none());
|
||||
}
|
||||
}
|
||||
+1032
-297
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,60 @@
|
||||
use std::ops::Deref;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use texturecraft_core::{FillSymmetry, 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>,
|
||||
projectors: &'a ProjectorDepthCache,
|
||||
depth_maps: Mutex<Vec<ViewDepth>>,
|
||||
}
|
||||
|
||||
impl<'a> EvaluationInputs<'a> {
|
||||
pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self {
|
||||
Self { inputs, projectors, depth_maps: Mutex::new(Vec::new()) }
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Deref for EvaluationInputs<'a> {
|
||||
type Target = Inputs<'a>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.inputs
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Isolated folder evaluation with the original stack available for anchor inputs.
|
||||
|
||||
use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed};
|
||||
use super::{
|
||||
Channel, ChannelKind, Composite, EvaluationInputs, Inputs, LayerId, ProjectorDepthCache, Texel, all_tiles, 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> {
|
||||
@@ -8,7 +11,9 @@ pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel)
|
||||
let channels = set.channel_list();
|
||||
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
|
||||
let tiles = all_tiles(width, height);
|
||||
let fields = neighbourhood_fields(inputs, &channels, &tiles);
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let inputs = &EvaluationInputs::new(inputs, &projectors);
|
||||
let fields = evaluation_fields(inputs, &channels, &tiles);
|
||||
let mut composite = Composite::with_size(&[channel], width, height);
|
||||
let output = composite.channels.get_mut(&channel)?;
|
||||
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! The copies a symmetric fill makes of its projection, as mirrors and turns of the surface point each copy samples
|
||||
|
||||
use texturecraft_core::{FULL_TURN_DEGREES, FillSymmetry, SymmetryKind};
|
||||
use texturecraft_geom::glam::{Mat3, Vec3};
|
||||
|
||||
use crate::fill_copy::FillCopy;
|
||||
|
||||
/// The copies of a fill's projection one texel shows, the original among them: the one whose half (mirror) or wedge (radial) holds the texel comes first, so it lies on top where copies overlap
|
||||
pub struct FillCopies {
|
||||
symmetry: FillSymmetry,
|
||||
pivot: Vec3,
|
||||
axis: usize,
|
||||
step: f32,
|
||||
first: u32,
|
||||
count: u32,
|
||||
next: u32,
|
||||
}
|
||||
|
||||
impl FillCopies {
|
||||
/// The copies `symmetry` makes for a texel at world point `point`, on a mesh whose bounds have centre `center` and radius `radius`
|
||||
pub fn new(symmetry: &FillSymmetry, point: Vec3, center: Vec3, radius: f32) -> FillCopies {
|
||||
let reach = FillSymmetry::REACH;
|
||||
let position = Vec3::from(symmetry.position.map(|coordinate| if coordinate.is_finite() { coordinate.clamp(-reach, reach) } else { 0.0 }));
|
||||
let pivot = center + position * radius;
|
||||
let axis = symmetry.axis_index();
|
||||
let count = symmetry.copies();
|
||||
let step = symmetry.step();
|
||||
|
||||
let from_pivot = point - pivot;
|
||||
let first = match symmetry.kind {
|
||||
// The original keeps the half on the axis's positive side
|
||||
SymmetryKind::Mirror => u32::from(from_pivot[axis] < 0.0),
|
||||
SymmetryKind::Radial => {
|
||||
let turned = from_pivot[(axis + 2) % 3].atan2(from_pivot[(axis + 1) % 3]).to_degrees().rem_euclid(FULL_TURN_DEGREES);
|
||||
nearest_copy(turned, step, count, symmetry.span)
|
||||
}
|
||||
};
|
||||
|
||||
FillCopies { symmetry: *symmetry, pivot, axis, step, first, count, next: 0 }
|
||||
}
|
||||
|
||||
/// Copy `index`: the original at 0, then the mirror or the radial copies in turn
|
||||
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,
|
||||
SymmetryKind::Mirror => {
|
||||
let mut scale = Vec3::ONE;
|
||||
scale[self.axis] = -1.0;
|
||||
Mat3::from_diagonal(scale)
|
||||
}
|
||||
|
||||
// Copy `index` is the original turned by `index` steps, so a texel samples the original turned back
|
||||
SymmetryKind::Radial => Mat3::from_axis_angle(Vec3::AXES[self.axis], -(index as f32 * self.step).to_radians()),
|
||||
};
|
||||
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
|
||||
fn nearest_copy(turned: f32, step: f32, count: u32, span: f32) -> u32 {
|
||||
// A span of nothing (or no step at all) stacks every copy on the original
|
||||
if step.is_nan() || step <= 0.0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let by_step = (turned / step).round() as u32;
|
||||
if span >= FULL_TURN_DEGREES || span.is_nan() {
|
||||
return by_step % count;
|
||||
}
|
||||
|
||||
let last = by_step.min(count - 1);
|
||||
let past_last = (turned - last as f32 * step).abs();
|
||||
let before_first = FULL_TURN_DEGREES - turned;
|
||||
if before_first <= past_last { 0 } else { last }
|
||||
}
|
||||
|
||||
impl Iterator for FillCopies {
|
||||
type Item = FillCopy;
|
||||
|
||||
fn next(&mut self) -> Option<FillCopy> {
|
||||
self.next_indexed().map(|(_, copy)| copy)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn symmetry(kind: SymmetryKind, axis: u8) -> FillSymmetry {
|
||||
FillSymmetry { on: true, kind, axis, ..FillSymmetry::OFF }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mirror_puts_the_texels_own_half_first_and_reflects_across_the_axis_position() {
|
||||
let mut mirror = symmetry(SymmetryKind::Mirror, 0);
|
||||
mirror.position = [0.5, 0.0, 0.0];
|
||||
let left: Vec<FillCopy> = FillCopies::new(&mirror, Vec3::new(-1.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect();
|
||||
|
||||
assert_eq!(left.len(), 2);
|
||||
|
||||
// The plane passes at x = 1 (half a radius of 2): a point at -1 sees the original at 3 first
|
||||
assert!(left[0].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(3.0, 0.2, 0.0), 1e-5));
|
||||
assert!(left[1].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(-1.0, 0.2, 0.0), 1e-5));
|
||||
assert!(left[0].normal(Vec3::X).abs_diff_eq(-Vec3::X, 1e-5));
|
||||
|
||||
let right: Vec<FillCopy> = FillCopies::new(&mirror, Vec3::new(2.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect();
|
||||
|
||||
assert!(right[0].point(Vec3::new(2.0, 0.3, 0.0)).abs_diff_eq(Vec3::new(2.0, 0.3, 0.0), 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_copies_turn_by_their_step_and_flip_only_the_copies() {
|
||||
let mut radial = symmetry(SymmetryKind::Radial, 2);
|
||||
radial.count = 4;
|
||||
radial.flip = [true, false];
|
||||
let copies: Vec<FillCopy> = FillCopies::new(&radial, Vec3::X, Vec3::ZERO, 1.0).collect();
|
||||
|
||||
assert_eq!(copies.len(), 4);
|
||||
assert_eq!(copies[0].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.25, 0.5));
|
||||
assert_eq!(copies[1].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.75, 0.5));
|
||||
|
||||
// Copy 1 sits a quarter turn on: a texel on +Y samples the original on +X
|
||||
assert!(copies[1].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5));
|
||||
|
||||
// A texel on +Y lies in copy 1's wedge, so copy 1 comes first there
|
||||
let on_y: Vec<FillCopy> = FillCopies::new(&radial, Vec3::Y, Vec3::ZERO, 1.0).collect();
|
||||
|
||||
assert!(on_y[0].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nearest_copy_is_found_by_its_step_as_a_search_of_every_copy_finds_it() {
|
||||
for (count, span) in [(6, 360.0), (5, 360.0), (4, 180.0), (3, 90.0), (64, 300.0), (2, 1.0)] {
|
||||
let step = radial_step(count, span);
|
||||
for tenth in 0..3600 {
|
||||
let turned = tenth as f32 / 10.0 + 0.05;
|
||||
let gap = |index: u32| {
|
||||
let past_copy = (turned - index as f32 * step).rem_euclid(FULL_TURN_DEGREES);
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn radial_step(count: u32, span: f32) -> f32 {
|
||||
FillSymmetry { count, span, ..symmetry(SymmetryKind::Radial, 2) }.step()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! One copy of a symmetric fill's projection: the mirror or turn a texel samples it through
|
||||
|
||||
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
|
||||
|
||||
/// One copy of a fill's projection: a texel at a point shows what the projection gives at [`FillCopy::point`]
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FillCopy {
|
||||
turn: Mat3,
|
||||
pivot: Vec3,
|
||||
flip: [bool; 2],
|
||||
}
|
||||
|
||||
impl FillCopy {
|
||||
/// A copy sampling the projection at `pivot + turn * (point - pivot)`, its image turned over across and down as `flip` says
|
||||
pub fn new(turn: Mat3, pivot: Vec3, flip: [bool; 2]) -> FillCopy {
|
||||
FillCopy { turn, pivot, flip }
|
||||
}
|
||||
|
||||
/// The surface point the projection is sampled at for a texel at world point `point`
|
||||
pub fn point(&self, point: Vec3) -> Vec3 {
|
||||
self.pivot + self.turn * (point - self.pivot)
|
||||
}
|
||||
|
||||
/// The normal the projection sees for a texel whose normal is `normal`
|
||||
pub fn normal(&self, normal: Vec3) -> Vec3 {
|
||||
self.turn * normal
|
||||
}
|
||||
|
||||
/// `uv` in the copy's image, turned over across and down as its Flip copy says
|
||||
pub fn uv(&self, uv: Vec2) -> Vec2 {
|
||||
let [across, down] = self.flip;
|
||||
Vec2::new(if across { 1.0 - uv.x } else { uv.x }, if down { 1.0 - uv.y } else { uv.y })
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use texturecraft_core::Fill;
|
||||
|
||||
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 FillDepth>,
|
||||
/// Decided once per tile, so a texel never works its coverage out
|
||||
pub covers_all: bool,
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! A frame on the surface (a placed planar or a warp) as its 3D projection settings show it: where its centre is, how it is turned and how big it is
|
||||
|
||||
use texturecraft_core::{Decal, Projection, Projector};
|
||||
use texturecraft_geom::glam::{EulerRot, Mat3, Quat, Vec3};
|
||||
|
||||
use crate::pattern::{decal_axes, mesh_frame, projector_stretch};
|
||||
|
||||
/// The shortest frame side a depth is divided by, so a collapsed frame keeps a finite depth
|
||||
pub const MIN_FRAME_SIDE: f32 = 1e-6;
|
||||
|
||||
/// Below this the frame faces nearly straight up or down, so world up gives no upright direction
|
||||
const MIN_UP_CROSS_SQUARED: f32 = 1e-6;
|
||||
|
||||
/// The longer side of a frame of `size`, at least [`MIN_FRAME_SIDE`]: a warp's Projection Depth counts in it
|
||||
pub fn longer_side(size: [f32; 2]) -> f32 {
|
||||
size[0].max(size[1]).max(MIN_FRAME_SIDE)
|
||||
}
|
||||
|
||||
/// How far a warp whose frame has `size` reaches in front of and behind it at Projection Depth `depth`, in world units
|
||||
pub fn warp_reach(size: [f32; 2], depth: f32) -> f32 {
|
||||
depth * longer_side(size)
|
||||
}
|
||||
|
||||
/// A frame's Offset (its centre in mesh radii from the mesh's centre), Rotation (degrees round X, Y and Z, as a projector turns) and Scale (its width and height, then how far it reaches in front of and behind it, in mesh diagonals)
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FramePlacement {
|
||||
pub offset: [f32; 3],
|
||||
pub rotation: [f32; 3],
|
||||
pub scale: [f32; 3],
|
||||
}
|
||||
|
||||
/// 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;
|
||||
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))
|
||||
}
|
||||
|
||||
/// 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),
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
if !projector.turns() {
|
||||
return Some(proj.clone());
|
||||
}
|
||||
|
||||
if !culling_folds(projector) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (origin, across, up, _) = decal_axes(frame)?;
|
||||
let [x, y, z] = projector.rotation.map(f32::to_radians);
|
||||
let turn = Mat3::from_cols(across, up, across.cross(up)) * Mat3::from_euler(EulerRot::ZYX, z, y, x);
|
||||
let stretch = projector_stretch(projector);
|
||||
|
||||
// A negative scale turns that side over
|
||||
let (across, up) = (turn.x_axis * stretch.x.signum(), turn.y_axis * stretch.y.signum());
|
||||
let size = [frame.size[0] * stretch.x.abs(), frame.size[1] * stretch.y.abs()];
|
||||
let reach = stretch.z.abs();
|
||||
let new_frame = Decal {
|
||||
center: origin.to_array(),
|
||||
normal: across.cross(up).to_array(),
|
||||
up: up.to_array(),
|
||||
size,
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: frame.depth * reach,
|
||||
symmetry: frame.symmetry,
|
||||
flip: frame.flip,
|
||||
};
|
||||
let unturned = Projector { rotation: [0.0; 3], scale: [1.0; 3], ..*projector };
|
||||
let mut out = proj.clone();
|
||||
match &mut out {
|
||||
Projection::Planar { placed: Some(placed), projector, .. } => {
|
||||
*placed = new_frame;
|
||||
*projector = unturned;
|
||||
}
|
||||
Projection::Warp { frame: warp, projector, depth, .. } => {
|
||||
// Its depth counts in lengths of the frame's longer side
|
||||
*depth *= reach * longer_side(frame.size) / longer_side(size);
|
||||
*warp = new_frame;
|
||||
*projector = unturned;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
let finite = new_frame.center.iter().chain(&new_frame.normal).chain(&new_frame.up).chain(&new_frame.size).all(|v| v.is_finite());
|
||||
finite.then_some(out)
|
||||
}
|
||||
|
||||
/// How far frame projection `proj` reaches in front of and behind its frame, in world units (a warp counts its depth in lengths of the longer side)
|
||||
fn reach(proj: &Projection) -> Option<f32> {
|
||||
match proj {
|
||||
Projection::Planar { placed: Some(frame), .. } => Some(frame.depth),
|
||||
Projection::Warp { frame, depth, .. } => Some(warp_reach(frame.size, *depth)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where frame projection `proj` (a placed planar or a warp) sits on a mesh with bounds `bounds`, its projector folded in (None for other projections)
|
||||
pub fn placement(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<FramePlacement> {
|
||||
let proj = folded(proj)?;
|
||||
let frame = proj.frame()?;
|
||||
let (center, radius) = mesh_frame(bounds);
|
||||
let (origin, across, up, out) = decal_axes(frame)?;
|
||||
let (z, y, x) = Quat::from_mat3(&Mat3::from_cols(across, up, out)).to_euler(EulerRot::ZYX);
|
||||
let diagonal = 2.0 * radius;
|
||||
let placement = FramePlacement {
|
||||
offset: ((origin - center) / radius).to_array(),
|
||||
rotation: [x, y, z].map(f32::to_degrees),
|
||||
scale: [frame.size[0] / diagonal, frame.size[1] / diagonal, reach(&proj)? / diagonal],
|
||||
};
|
||||
let values = placement.offset.iter().chain(&placement.rotation).chain(&placement.scale);
|
||||
values.copied().all(f32::is_finite).then_some(placement)
|
||||
}
|
||||
|
||||
/// 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);
|
||||
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;
|
||||
}
|
||||
|
||||
let mut proj = folded(proj)?;
|
||||
let old = *proj.frame()?;
|
||||
let (center, radius) = mesh_frame(bounds);
|
||||
let diagonal = 2.0 * radius;
|
||||
let [x, y, z] = placement.rotation.map(f32::to_radians);
|
||||
let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x);
|
||||
let [width, height, deep] = placement.scale.map(|scale| scale * diagonal);
|
||||
let frame = Decal {
|
||||
center: (center + Vec3::from(placement.offset) * radius).to_array(),
|
||||
normal: turn.z_axis.to_array(),
|
||||
up: turn.y_axis.to_array(),
|
||||
size: [width, height],
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: deep,
|
||||
symmetry: old.symmetry,
|
||||
flip: old.flip,
|
||||
};
|
||||
match &mut proj {
|
||||
Projection::Planar { placed: Some(placed), .. } => *placed = frame,
|
||||
Projection::Warp { frame: warp, depth, .. } => {
|
||||
*depth = deep / longer_side([width, height]);
|
||||
|
||||
// The warp's own depth is what reaches; the frame's is unused
|
||||
*warp = Decal { depth: warp.depth, ..frame };
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(proj)
|
||||
}
|
||||
|
||||
/// A frame's turn round its own normal, as seen face on with the world's up (or, looking straight down, the far side) at the top: degrees
|
||||
pub fn upright_turn(frame: &Decal) -> Option<f32> {
|
||||
let (_, _, up, out) = decal_axes(frame)?;
|
||||
let world_up = if out.cross(Vec3::Y).length_squared() > MIN_UP_CROSS_SQUARED { Vec3::Y } else { Vec3::NEG_Z };
|
||||
let upright = (world_up - out * out.dot(world_up)).try_normalize()?;
|
||||
let upright_across = upright.cross(out);
|
||||
let turn = (-up.dot(upright_across)).atan2(up.dot(upright)).to_degrees();
|
||||
turn.is_finite().then_some(turn)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_core::{Backface, DecalFlip, DecalSymmetry, ShapeCrop, UvTransform};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
use super::*;
|
||||
use crate::projector_cover::framed_cover;
|
||||
|
||||
const BOUNDS: (Vec3, Vec3) = (Vec3::new(-1.0, -2.0, -0.5), Vec3::new(3.0, 1.0, 1.5));
|
||||
|
||||
fn frame() -> Decal {
|
||||
Decal {
|
||||
center: [0.4, -0.2, 1.3],
|
||||
normal: [0.2, 0.1, 1.0],
|
||||
up: [0.0, 1.0, 0.1],
|
||||
size: [1.2, 0.8],
|
||||
rotation: 25.0,
|
||||
offset: [0.1, -0.2],
|
||||
depth: 0.6,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
}
|
||||
}
|
||||
|
||||
fn planar(projector: Projector) -> Projection {
|
||||
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(frame()) }
|
||||
}
|
||||
|
||||
fn warp(projector: Projector) -> Projection {
|
||||
Projection::Warp { frame: frame(), corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]], depth: 0.7, uv: UvTransform::default(), projector }
|
||||
}
|
||||
|
||||
/// The projection's texture coordinates and cover at points through the frame's neighbourhood with varied normals
|
||||
fn samples(proj: &Projection) -> Vec<Option<(Vec2, f32)>> {
|
||||
let mut out = Vec::new();
|
||||
for across in 0..7 {
|
||||
for up in 0..7 {
|
||||
for out_of in 0..3 {
|
||||
let position = Vec3::new(-0.5 + across as f32 * 0.25, -0.8 + up as f32 * 0.2, 0.7 + out_of as f32 * 0.3);
|
||||
let normal = Vec3::new(0.1 * across as f32 - 0.3, 0.2, 1.0).normalize();
|
||||
out.push(framed_cover(proj, position, normal, (BOUNDS.0 + BOUNDS.1) * 0.5));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn projector_of(proj: &Projection) -> Projector {
|
||||
match proj {
|
||||
Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => *projector,
|
||||
_ => panic!("a frame projection"),
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: &[Option<(Vec2, f32)>], b: &[Option<(Vec2, f32)>]) {
|
||||
assert_eq!(a.len(), b.len());
|
||||
for (index, (a, b)) in a.iter().zip(b).enumerate() {
|
||||
match (a, b) {
|
||||
(Some((uv_a, cover_a)), Some((uv_b, cover_b))) => {
|
||||
assert!((cover_a - cover_b).abs() < 1e-3, "{index}: cover {cover_a} vs {cover_b}");
|
||||
assert!(uv_a.distance(*uv_b) < 1e-3, "{index}: {uv_a} vs {uv_b}");
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => panic!("{index}: sampled on one side only: {a:?} vs {b:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_a_turned_and_evenly_scaled_projector_into_its_frame_lands_the_same() {
|
||||
let projector = Projector { rotation: [20.0, -35.0, 50.0], scale: [1.7; 3], crop: ShapeCrop::Cropped, ..Projector::default() };
|
||||
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));
|
||||
}
|
||||
let unturned = planar(Projector::default());
|
||||
assert_eq!(folded(&unturned), Some(unturned), "nothing to fold: unchanged");
|
||||
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() };
|
||||
|
||||
// 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);
|
||||
|
||||
for scale in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] {
|
||||
let projector = Projector { scale, backface, ..Projector::default() };
|
||||
let proj = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(square) };
|
||||
match folded(&proj) {
|
||||
Some(flat) => {
|
||||
assert_eq!(cover(&proj), cover(&flat), "{scale:?}: culling changed");
|
||||
|
||||
close(&samples(&proj), &samples(&flat));
|
||||
}
|
||||
None => assert!(!culling_folds(&projector), "{scale:?}: only a scale culling cannot keep stays unfolded"),
|
||||
}
|
||||
}
|
||||
|
||||
assert!(folded(&planar(Projector { scale: [1.7; 3], backface, ..Projector::default() })).is_some(), "an even scale still folds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placement_read_and_written_back_lands_the_same_and_its_fields_move_the_frame() {
|
||||
let projector = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() };
|
||||
for proj in [planar(Projector::default()), warp(Projector::default()), planar(projector), warp(projector)] {
|
||||
let place = placement(&proj, BOUNDS).unwrap();
|
||||
let back = placed(&proj, &place, BOUNDS).unwrap();
|
||||
close(&samples(&folded(&proj).unwrap()), &samples(&back));
|
||||
let again = placement(&back, BOUNDS).unwrap();
|
||||
for (a, b) in place.offset.iter().chain(&place.rotation).chain(&place.scale).zip(again.offset.iter().chain(&again.rotation).chain(&again.scale)) {
|
||||
assert!((a - b).abs() < 1e-3, "{place:?} vs {again:?}");
|
||||
}
|
||||
|
||||
let width = folded(&proj).unwrap().frame().unwrap().size[0];
|
||||
let bigger = placed(&proj, &FramePlacement { scale: [place.scale[0] * 2.0, place.scale[1], place.scale[2]], ..place }, BOUNDS).unwrap();
|
||||
|
||||
assert!((bigger.frame().unwrap().size[0] - width * 2.0).abs() < 1e-4, "Scale X doubles the width");
|
||||
|
||||
let moved = placed(&proj, &FramePlacement { offset: [0.0; 3], ..place }, BOUNDS).unwrap();
|
||||
|
||||
assert!((Vec3::from(moved.frame().unwrap().center) - Vec3::new(1.0, -0.5, 0.5)).length() < 1e-4, "offset 0 = the mesh's centre");
|
||||
}
|
||||
let place = placement(&planar(Projector::default()), BOUNDS).unwrap();
|
||||
|
||||
assert_eq!(placed(&planar(Projector::default()), &FramePlacement { scale: [0.0, 1.0, 1.0], ..place }, BOUNDS), None, "no zero size");
|
||||
assert_eq!(placed(&planar(Projector::default()), &FramePlacement { rotation: [f32::NAN; 3], ..place }, BOUNDS), None);
|
||||
assert_eq!(placement(&Projection::default(), BOUNDS), None);
|
||||
}
|
||||
|
||||
#[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;
|
||||
|
||||
assert!((upright_turn(&flat).unwrap() + 100.0).abs() < 1e-3);
|
||||
|
||||
let top = Decal { normal: [0.0, 1.0, 0.0], up: [0.0, 0.0, -1.0], rotation: 0.0, ..frame() };
|
||||
assert!(upright_turn(&top).unwrap().abs() < 1e-3, "seen from above the far side is up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_and_placing_keep_a_frames_mirror_copy_and_image_flip() {
|
||||
let symmetry = Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.2 });
|
||||
let mirrored = Decal { symmetry, flip: [true, false], ..frame() };
|
||||
let turned = Projector { rotation: [10.0, 0.0, -30.0], scale: [1.2, 0.9, 1.3], ..Projector::default() };
|
||||
for proj in [
|
||||
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: turned, placed: Some(mirrored) },
|
||||
Projection::Warp {
|
||||
frame: mirrored,
|
||||
corners: [[-0.6, 0.5], [0.5, 0.4], [0.5, -0.5], [-0.4, -0.5]],
|
||||
depth: 0.7,
|
||||
uv: UvTransform::default(),
|
||||
projector: turned,
|
||||
},
|
||||
] {
|
||||
let folded = folded(&proj).unwrap();
|
||||
let moved = placed(&proj, &placement(&proj, BOUNDS).unwrap(), BOUNDS).unwrap();
|
||||
for frame in [folded.frame().unwrap(), moved.frame().unwrap()] {
|
||||
assert_eq!((frame.symmetry, frame.flip), (symmetry, [true, false]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod axis_frame;
|
||||
mod baked_maps;
|
||||
pub mod below;
|
||||
mod curvature_size_level;
|
||||
@@ -14,26 +15,40 @@ pub mod curvature_sizes;
|
||||
pub mod display;
|
||||
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;
|
||||
mod held_fields;
|
||||
mod image_identity;
|
||||
pub mod mip_level;
|
||||
mod organic;
|
||||
pub mod pattern;
|
||||
mod pattern_context;
|
||||
pub mod projector_cover;
|
||||
pub mod projector_depth;
|
||||
mod projector_depth_cache;
|
||||
pub mod projector_view;
|
||||
pub mod solo;
|
||||
pub mod store;
|
||||
pub mod thumb;
|
||||
pub mod tile_length;
|
||||
mod tile_pattern;
|
||||
mod tile_random_stream;
|
||||
mod timber;
|
||||
pub mod warp;
|
||||
|
||||
pub use below::{BelowCache, StackKey};
|
||||
pub use display::{DisplayKind, kinds_for, tile_bytes};
|
||||
pub use eval::{
|
||||
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles,
|
||||
effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours,
|
||||
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached,
|
||||
composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles,
|
||||
stack_reads_neighbours,
|
||||
};
|
||||
pub use pattern_context::PatternContext;
|
||||
pub use projector_depth_cache::ProjectorDepthCache;
|
||||
pub use solo::solo_project;
|
||||
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
|
||||
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
|
||||
@@ -0,0 +1,103 @@
|
||||
//! One halved copy of an image resource, read by high-quality bilinear filtering when an image is shrunk
|
||||
|
||||
use crate::store::texel_of;
|
||||
|
||||
/// One halved copy of an image (box-filtered; see `halve` for its edges)
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MipLevel {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: Vec<[f32; 4]>,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// 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);
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
})
|
||||
}
|
||||
+378
-135
@@ -1,7 +1,7 @@
|
||||
//! Procedural patterns and projections.
|
||||
|
||||
use texturecraft_core::{Decal, DecalFlip, Procedural, ProceduralKind, Projection};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_core::{Decal, FULL_TURN_DEGREES, Procedural, ProceduralKind, Projection, Projector, UvTransform};
|
||||
use texturecraft_geom::glam::{EulerRot, Mat3, Vec2, Vec3};
|
||||
use texturecraft_texel::noise;
|
||||
|
||||
use crate::pattern_context::PatternContext;
|
||||
@@ -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(1e-6);
|
||||
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 {
|
||||
@@ -394,6 +402,129 @@ fn shape(pattern: &Procedural, value: f32) -> f32 {
|
||||
if pattern.invert { 1.0 - adjusted } else { adjusted }
|
||||
}
|
||||
|
||||
/// `point` turned by `rotation` degrees, scaled by `tiling` and moved by `offset`, as UV transformations place it
|
||||
fn place(point: Vec2, tiling: Vec2, rotation: f32, offset: Vec2) -> Vec2 {
|
||||
placement(tiling, rotation, offset)(point)
|
||||
}
|
||||
|
||||
/// [`place`] with its turn's sine and cosine worked out once, for a projection that places several points
|
||||
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
|
||||
}
|
||||
|
||||
/// `point` placed as a 3D projection's UV transformation `uv` lays its image
|
||||
fn place_uv(point: Vec2, uv: &UvTransform) -> Vec2 {
|
||||
uv_placement(uv)(point)
|
||||
}
|
||||
|
||||
/// [`place_uv`] worked out once for every point a projection places
|
||||
fn uv_placement(uv: &UvTransform) -> impl Fn(Vec2) -> Vec2 {
|
||||
placement(Vec2::from(uv.tiling), uv.rotation, Vec2::from(uv.offset))
|
||||
}
|
||||
|
||||
/// 0..1 around a cylindrical projection's axis (`depth` over `across`), over an arc of `angle` degrees centred on the front
|
||||
fn around(across: f32, depth: f32, angle: f32) -> f32 {
|
||||
let turn = depth.atan2(across) / std::f32::consts::TAU + 0.5;
|
||||
|
||||
// A full turn reads the turn untouched, as projects saved before the angle existed did, bit for bit
|
||||
if angle == FULL_TURN_DEGREES { turn } else { (turn - 0.5) * FULL_TURN_DEGREES / angle.max(MIN_CYLINDER_ANGLE) + 0.5 }
|
||||
}
|
||||
|
||||
/// Narrowest arc in degrees a cylindrical projection wraps its image round, so a zero angle never divides by zero
|
||||
pub const MIN_CYLINDER_ANGLE: f32 = *Projection::CYLINDER_ANGLE_RANGE.start();
|
||||
|
||||
/// How many pattern tiles a procedural lays round and down a spherical projection, so its cells stay near square
|
||||
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 frame side or depth (world units), so a flat frame never divides by zero
|
||||
const MIN_FRAME_EXTENT: f32 = 1e-6;
|
||||
|
||||
/// Where `coords` lies round a spherical projection: 0..1 round its pole axis and down from its top
|
||||
fn spherical_uv(projector: &Projector, offset: &[f32; 3], coords: &Coords) -> Vec2 {
|
||||
let direction = (projector_local(projector, coords).pos + Vec3::from(*offset)).try_normalize().unwrap_or(Vec3::Y);
|
||||
let u = direction.z.atan2(direction.x) / std::f32::consts::TAU + 0.5;
|
||||
let v = direction.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
|
||||
Vec2::new(u, v)
|
||||
}
|
||||
|
||||
/// The axis index (0 X, 1 Y, 2 Z) a cylindrical projection's stored `axis` wraps round: any value but X or Z reads as Y
|
||||
pub fn cylinder_axis_index(axis: u8) -> usize {
|
||||
match axis {
|
||||
0 => 0,
|
||||
2 => 2,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `coords` lies for a cylindrical projection round `axis`: 0..1 round the axis over `angle` degrees, and its height along the axis
|
||||
fn cylinder_coords(axis: u8, projector: &Projector, offset: &[f32; 3], angle: f32, coords: &Coords) -> (f32, f32) {
|
||||
let point = projector_local(projector, coords).pos + Vec3::from(*offset);
|
||||
let (across, height, depth) = match cylinder_axis_index(axis) {
|
||||
0 => (point.y, point.x, point.z),
|
||||
2 => (point.x, point.z, point.y),
|
||||
_ => (point.x, point.y, point.z),
|
||||
};
|
||||
(around(across, depth, angle), height)
|
||||
}
|
||||
|
||||
/// Smallest mesh radius projections measure in, so a flat or empty mesh never divides by zero
|
||||
const MIN_MESH_RADIUS: f32 = 1e-4;
|
||||
|
||||
/// Nearest to zero a projection scale or stretch gets, so it never divides by zero
|
||||
const MIN_STRETCH: f32 = 1e-6;
|
||||
|
||||
/// The mesh's centre and its radius (half the diagonal) from its bounds
|
||||
pub fn mesh_frame((lo, hi): (Vec3, Vec3)) -> (Vec3, f32) {
|
||||
((lo + hi) * 0.5, ((hi - lo).length() * 0.5).max(MIN_MESH_RADIUS))
|
||||
}
|
||||
|
||||
/// `value` kept at least [`MIN_STRETCH`] from zero, on its own side
|
||||
pub fn nonzero_stretch(value: f32) -> f32 {
|
||||
value.signum() * value.abs().max(MIN_STRETCH)
|
||||
}
|
||||
|
||||
/// A projector's per-axis scale with no axis at zero, each keeping its sign
|
||||
pub fn projector_stretch(projector: &Projector) -> Vec3 {
|
||||
Vec3::from(projector.scale).map(nonzero_stretch)
|
||||
}
|
||||
|
||||
/// The middle of a frame's 0..1 texture coordinates: a frame's image turns round it
|
||||
pub const FRAME_UV_CENTER: Vec2 = Vec2::splat(0.5);
|
||||
|
||||
/// `point` (0..1 across and down a frame) placed as `uv` lays a frame's image: turned round the frame's centre, then tiled and moved from its top left
|
||||
pub fn place_frame_uv(point: Vec2, uv: &UvTransform) -> Vec2 {
|
||||
// An unplaced image reads `point` itself, bit for bit as decals saved before image placement did
|
||||
if *uv == UvTransform::default() {
|
||||
return point;
|
||||
}
|
||||
|
||||
let tiling = Vec2::from(uv.tiling);
|
||||
place(point - FRAME_UV_CENTER, tiling, uv.rotation, Vec2::from(uv.offset)) + FRAME_UV_CENTER * tiling
|
||||
}
|
||||
|
||||
/// The image placement a frame needs to lay images exactly as `uv` does from the top left (a frame turns its image round its centre)
|
||||
pub fn frame_uv_from_corner(uv: &UvTransform) -> UvTransform {
|
||||
let offset = place_uv(FRAME_UV_CENTER, uv) - FRAME_UV_CENTER * Vec2::from(uv.tiling);
|
||||
UvTransform { offset: offset.to_array(), ..*uv }
|
||||
}
|
||||
|
||||
/// `coords` inside a projector turned and scaled by `projector`; the default projector returns `coords` unchanged
|
||||
pub fn projector_local(projector: &Projector, coords: &Coords) -> Coords {
|
||||
if !projector.turns() {
|
||||
return *coords;
|
||||
}
|
||||
|
||||
let [x, y, z] = projector.rotation.map(f32::to_radians);
|
||||
let to_local = Mat3::from_euler(EulerRot::ZYX, z, y, x).transpose();
|
||||
let scale = projector_stretch(projector);
|
||||
let nrm = (to_local * coords.nrm * scale).try_normalize().unwrap_or(coords.nrm);
|
||||
Coords { pos: to_local * coords.pos / scale, nrm, ..*coords }
|
||||
}
|
||||
|
||||
/// Evaluate a procedural through a projection, at full resolution and without images
|
||||
pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 {
|
||||
procedural_in(pattern, projection, coords, &PatternContext::default())
|
||||
@@ -402,51 +533,42 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords
|
||||
/// Evaluate a procedural through a projection with what `context` gives it: its resolution and the images it reads
|
||||
pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coords, context: &PatternContext) -> f32 {
|
||||
let pattern_scale = pattern.scale.max(MIN_PATTERN_SCALE);
|
||||
let sample = |point: Vec3| plane_value(pattern, point, context);
|
||||
let value = match projection {
|
||||
Projection::Uv { scale, rotation, offset } => {
|
||||
let (sn, cs) = rotation.to_radians().sin_cos();
|
||||
let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset);
|
||||
|
||||
// Evaluate two-dimensional patterns on a slice of the volume
|
||||
sample((uv * pattern_scale).extend(0.0))
|
||||
}
|
||||
Projection::Triplanar { scale, sharpness, offset } => {
|
||||
let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
|
||||
// Evaluate two-dimensional patterns on a slice of the volume
|
||||
let flat = |point: Vec2| plane_value(pattern, point.extend(0.0), context);
|
||||
let value = match projection {
|
||||
Projection::UvTile => flat((coords.uv - coords.uv.floor()) * pattern_scale),
|
||||
Projection::Uv { scale, rotation, offset } => flat(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset)) * pattern_scale),
|
||||
Projection::Triplanar { scale, sharpness, offset, uv, projector } => {
|
||||
let coords = &projector_local(projector, coords);
|
||||
let point = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
|
||||
let place_plane = uv_placement(uv);
|
||||
|
||||
// Shape scales the blend by the contrast
|
||||
let w = triplanar_weights(coords.nrm, *sharpness, pattern.contrast);
|
||||
let planes = [(w.x, Vec3::new(p.z, p.y, 0.0)), (w.y, Vec3::new(p.x, p.z, 0.0)), (w.z, Vec3::new(p.x, p.y, 0.0))];
|
||||
planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| sample(q) * w).sum()
|
||||
}
|
||||
Projection::Planar { scale, axis, offset } => {
|
||||
let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset);
|
||||
let q = match axis {
|
||||
0 => Vec3::new(p.z, p.y, 0.0),
|
||||
1 => Vec3::new(p.x, p.z, 0.0),
|
||||
_ => Vec3::new(p.x, p.y, 0.0),
|
||||
};
|
||||
sample(q)
|
||||
}
|
||||
Projection::Spherical { scale } => {
|
||||
let d = coords.pos.try_normalize().unwrap_or(Vec3::Y);
|
||||
let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5;
|
||||
let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
|
||||
sample(Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale)
|
||||
}
|
||||
Projection::Cylindrical { scale, axis } => {
|
||||
let p = coords.pos;
|
||||
let (a, h, b) = match axis {
|
||||
0 => (p.y, p.x, p.z),
|
||||
2 => (p.x, p.z, p.y),
|
||||
_ => (p.x, p.y, p.z),
|
||||
};
|
||||
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
|
||||
sample(Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale)
|
||||
let weights = triplanar_weights(coords.nrm, *sharpness, pattern.contrast);
|
||||
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 decal already supplied coordinates in its local frame
|
||||
Projection::Decal(_) => sample((coords.uv * pattern_scale).extend(0.0)),
|
||||
// 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, .. } => {
|
||||
let point = projector_local(projector, coords).pos * *scale * pattern_scale + Vec3::from(*offset);
|
||||
let plane = match axis {
|
||||
0 => Vec2::new(point.z, point.y),
|
||||
1 => Vec2::new(point.x, point.z),
|
||||
_ => Vec2::new(point.x, point.y),
|
||||
};
|
||||
flat(place_uv(plane, uv))
|
||||
}
|
||||
Projection::Spherical { scale, uv, offset, projector } => {
|
||||
let sphere = spherical_uv(projector, offset, coords);
|
||||
flat(place_uv(sphere * SPHERE_PATTERN_TILES * *scale * pattern_scale, uv))
|
||||
}
|
||||
Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => {
|
||||
let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords);
|
||||
flat(place_uv(Vec2::new(around_axis * CYLINDER_PATTERN_TILES, height) * *scale * pattern_scale, uv))
|
||||
}
|
||||
};
|
||||
|
||||
shape(pattern, value)
|
||||
@@ -476,7 +598,7 @@ fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f
|
||||
|
||||
let base = grid.floor();
|
||||
let fraction = grid - base;
|
||||
let at = |dx: f32, dy: f32| pattern_value(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context);
|
||||
let at = |across: f32, down: f32| pattern_value(pattern, ((base + Vec2::new(across, down) + 0.5) / cells).extend(point.z), context);
|
||||
let top_left = at(0.0, 0.0);
|
||||
let bottom_left = at(0.0, 1.0);
|
||||
let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x;
|
||||
@@ -497,45 +619,36 @@ fn pattern_value(pattern: &Procedural, point: Vec3, context: &PatternContext) ->
|
||||
pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32); 3] {
|
||||
let one = |uv: Vec2| [(uv, 1.0), (Vec2::ZERO, 0.0), (Vec2::ZERO, 0.0)];
|
||||
match projection {
|
||||
Projection::Uv { scale, rotation, offset } => {
|
||||
let (sn, cs) = rotation.to_radians().sin_cos();
|
||||
let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset);
|
||||
one(uv)
|
||||
}
|
||||
Projection::Triplanar { scale, sharpness, offset } => {
|
||||
let p = coords.pos * *scale + Vec3::from(*offset);
|
||||
Projection::UvTile => one(coords.uv - coords.uv.floor()),
|
||||
Projection::Uv { scale, rotation, offset } => one(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset))),
|
||||
Projection::Triplanar { scale, sharpness, offset, uv, projector } => {
|
||||
let coords = &projector_local(projector, coords);
|
||||
let point = coords.pos * *scale + Vec3::from(*offset);
|
||||
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(1e-6);
|
||||
[(Vec2::new(p.z, -p.y), weights.x), (Vec2::new(p.x, p.z), weights.y), (Vec2::new(p.x, -p.y), weights.z)]
|
||||
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),
|
||||
(place_plane(Vec2::new(point.x, -point.y)), weights.z),
|
||||
]
|
||||
}
|
||||
Projection::Planar { scale, axis, offset } => {
|
||||
let p = coords.pos * *scale + Vec3::from(*offset);
|
||||
let q = match axis {
|
||||
0 => Vec2::new(p.z, -p.y),
|
||||
1 => Vec2::new(p.x, p.z),
|
||||
_ => Vec2::new(p.x, -p.y),
|
||||
Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => one(place_frame_uv(coords.uv, uv)),
|
||||
Projection::Planar { scale, axis, offset, uv, projector, .. } => {
|
||||
let point = projector_local(projector, coords).pos * *scale + Vec3::from(*offset);
|
||||
let plane = match axis {
|
||||
0 => Vec2::new(point.z, -point.y),
|
||||
1 => Vec2::new(point.x, point.z),
|
||||
_ => Vec2::new(point.x, -point.y),
|
||||
};
|
||||
one(q * 0.5 + Vec2::splat(0.5))
|
||||
one(place_uv(plane * 0.5 + Vec2::splat(0.5), uv))
|
||||
}
|
||||
Projection::Spherical { scale } => {
|
||||
let d = coords.pos.try_normalize().unwrap_or(Vec3::Y);
|
||||
let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5;
|
||||
let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
|
||||
one(Vec2::new(u, v) * *scale)
|
||||
Projection::Spherical { scale, uv, offset, projector } => one(place_uv(spherical_uv(projector, offset, coords) * *scale, uv)),
|
||||
Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => {
|
||||
let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords);
|
||||
one(place_uv(Vec2::new(around_axis, 0.5 - height * 0.5) * *scale, uv))
|
||||
}
|
||||
Projection::Cylindrical { scale, axis } => {
|
||||
let p = coords.pos;
|
||||
let (a, h, b) = match axis {
|
||||
0 => (p.y, p.x, p.z),
|
||||
2 => (p.x, p.z, p.y),
|
||||
_ => (p.x, p.y, p.z),
|
||||
};
|
||||
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
|
||||
one(Vec2::new(u, 0.5 - h * 0.5) * *scale)
|
||||
}
|
||||
Projection::Decal(_) => one(coords.uv),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -561,50 +674,74 @@ pub fn decal_corners(d: &Decal) -> Option<[Vec3; 4]> {
|
||||
Some([o - r * hw + u * hh, o + r * hw + u * hh, o + r * hw - u * hh, o - r * hw - u * hh])
|
||||
}
|
||||
|
||||
/// Where world point `p` with surface normal `nrm` falls in the decal: texture coordinates
|
||||
/// (v down) and how much the decal covers it, None outside the frame, behind it, beyond its
|
||||
/// depth or on faces turned away. Coverage fades on grazing faces and near the depth limit.
|
||||
pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
|
||||
let (o, r, u, n) = decal_axes(d)?;
|
||||
let facing = nrm.dot(n);
|
||||
let q = p - o;
|
||||
let (lx, ly, lz) = (q.dot(r) / d.size[0].max(1e-6), q.dot(u) / d.size[1].max(1e-6), q.dot(n).abs());
|
||||
let depth = d.depth.max(1e-6);
|
||||
if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) {
|
||||
return None;
|
||||
/// World point `point` in frame `frame` turned and scaled by `projector`: across and up in frame sizes, out along its normal in world units
|
||||
pub fn frame_local(frame: &Decal, projector: &Projector, point: Vec3) -> Option<Vec3> {
|
||||
let (origin, right, up, normal) = decal_axes(frame)?;
|
||||
let from_origin = point - origin;
|
||||
let mut local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal));
|
||||
if projector.turns() {
|
||||
local = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: Vec3::Z }).pos;
|
||||
}
|
||||
|
||||
let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz));
|
||||
Some((flip_uv(Vec2::new(lx + 0.5, 0.5 - ly), d.flip), w))
|
||||
frame_position(frame, local)
|
||||
}
|
||||
|
||||
/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame.
|
||||
fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 {
|
||||
Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y })
|
||||
}
|
||||
/// Read the position and facing of one sample when a placed frame culls by angle
|
||||
pub(crate) fn frame_sample(frame: &Decal, projector: &Projector, position: Vec3, surface_normal: Vec3) -> Option<(Vec3, f32)> {
|
||||
let (origin, right, up, normal) = decal_axes(frame)?;
|
||||
let from_origin = position - origin;
|
||||
let local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal));
|
||||
|
||||
/// [`decal_uv`] for a decal with a mirrored copy: whichever of the decal and its copy covers the
|
||||
/// point more. The copy is the decal reflected through the plane across `center` (the mesh
|
||||
/// center), so a point is looked up as its reflection (the plane is `offset` away from the center) and the image flipped as asked.
|
||||
pub fn decal_uv_symmetric(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
|
||||
let direct = decal_uv(d, p, nrm);
|
||||
let Some(symmetry) = d.symmetry else { return direct };
|
||||
let axis = usize::from(symmetry.axis.min(2));
|
||||
let (mut mirrored_position, mut mirrored_normal) = (p, nrm);
|
||||
mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
|
||||
mirrored_normal[axis] = -nrm[axis];
|
||||
let mirrored = decal_uv(d, mirrored_position, mirrored_normal).map(|(uv, w)| {
|
||||
let uv = match symmetry.flip {
|
||||
DecalFlip::None => uv,
|
||||
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
|
||||
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
|
||||
};
|
||||
(uv, w)
|
||||
});
|
||||
match (direct, mirrored) {
|
||||
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
|
||||
(a, b) => a.or(b),
|
||||
if !projector.turns() {
|
||||
return Some((frame_position(frame, local)?, surface_normal.dot(normal)));
|
||||
}
|
||||
|
||||
let normal = Vec3::new(surface_normal.dot(right), surface_normal.dot(up), surface_normal.dot(normal));
|
||||
let sample = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: normal });
|
||||
Some((frame_position(frame, sample.pos)?, sample.nrm.z))
|
||||
}
|
||||
|
||||
fn frame_position(frame: &Decal, local: Vec3) -> Option<Vec3> {
|
||||
let local = Vec3::new(local.x / frame.size[0].max(MIN_FRAME_EXTENT), local.y / frame.size[1].max(MIN_FRAME_EXTENT), local.z);
|
||||
local.is_finite().then_some(local)
|
||||
}
|
||||
|
||||
/// How squarely a surface with normal `nrm` faces frame `frame` turned by `projector` (the cosine of the turn)
|
||||
pub fn frame_facing(frame: &Decal, projector: &Projector, nrm: Vec3) -> f32 {
|
||||
let Some((_, right, up, normal)) = decal_axes(frame) else { return 0.0 };
|
||||
if !projector.turns() {
|
||||
return nrm.dot(normal);
|
||||
}
|
||||
|
||||
let turned = Vec3::new(nrm.dot(right), nrm.dot(up), nrm.dot(normal));
|
||||
projector_local(projector, &Coords { uv: Vec2::ZERO, pos: Vec3::ZERO, nrm: turned }).nrm.z
|
||||
}
|
||||
|
||||
/// Texture coordinates (v down) of a point at `local` in its frame (see [`frame_local`])
|
||||
pub fn placed_uv(local: Vec3) -> Vec2 {
|
||||
Vec2::new(local.x + 0.5, 0.5 - local.y)
|
||||
}
|
||||
|
||||
/// How much frame `frame` covers a point at `local` when cropped to its shape: 0 outside the frame or past its depth, fading near the depth
|
||||
pub fn frame_crop(frame: &Decal, local: Vec3) -> f32 {
|
||||
if local.x.abs() > 0.5 || local.y.abs() > 0.5 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
depth_fade(local.z, frame.depth)
|
||||
}
|
||||
|
||||
/// Where a frame's depth fade starts, as a share of its depth
|
||||
pub const DEPTH_FADE_START: f32 = 0.75;
|
||||
|
||||
/// How much a frame reaching `depth` in front of and behind it covers a point `z` out from it: 0 past the depth, fading near it
|
||||
pub fn depth_fade(z: f32, depth: f32) -> f32 {
|
||||
let (distance, depth) = (z.abs(), depth.max(MIN_FRAME_EXTENT));
|
||||
if distance > depth {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
1.0 - smoothstep(DEPTH_FADE_START * depth, depth, distance)
|
||||
}
|
||||
|
||||
/// World-space noise used by generators (seamless across UV islands).
|
||||
@@ -637,20 +774,108 @@ mod tests {
|
||||
|
||||
// Coarse reads are exact at cell centers and blend between them
|
||||
assert!((at(0.375, &coarse) - at(0.375, &exact)).abs() < 1e-5);
|
||||
|
||||
let blended = (at(0.125, &exact) + at(0.375, &exact)) * 0.5;
|
||||
assert!((at(0.25, &coarse) - blended).abs() < 1e-5, "{} vs {blended}", at(0.25, &coarse));
|
||||
assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows");
|
||||
}
|
||||
|
||||
/// A stored cylinder axis past Z (only a hand-edited project holds one) wraps round Y
|
||||
#[test]
|
||||
fn a_cylinder_axis_past_z_reads_as_y() {
|
||||
assert_eq!([0, 1, 2, 3, u8::MAX].map(cylinder_axis_index), [0, 1, 2, 1, 1]);
|
||||
}
|
||||
|
||||
/// A decal saved before image placement reads its frame coordinates bit for bit as it did: its image at them, its procedural at them times the pattern scale
|
||||
#[test]
|
||||
fn an_unplaced_decal_reads_its_frame_coordinates_bit_for_bit() {
|
||||
let frame = Decal {
|
||||
center: [0.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
size: [1.0; 2],
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: 0.5,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
};
|
||||
let decal = Projection::decal(frame);
|
||||
let pattern = Procedural { scale: 3.0, ..Procedural::new(ProceduralKind::Gradient) };
|
||||
for across in 0..=1000 {
|
||||
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));
|
||||
assert_eq!(procedural(&pattern, &decal, &coords).to_bits(), expected.to_bits(), "procedural at {uv}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame's image turns round the frame's centre: the centre reads the same texel at any Rotation, and an unturned image reads exactly as before for any Tiling and Offset
|
||||
#[test]
|
||||
fn a_frame_image_turns_round_the_frame_centre() {
|
||||
let frame = Decal {
|
||||
center: [0.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
size: [1.0; 2],
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: 0.5,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
};
|
||||
let at = |uv: Vec2| Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z };
|
||||
let sample = |rotation: f32, tiling: [f32; 2], offset: [f32; 2], uv: Vec2| {
|
||||
image_samples(
|
||||
&Projection::Warp {
|
||||
frame,
|
||||
corners: Projection::FRAME_CORNERS,
|
||||
depth: 0.1,
|
||||
uv: UvTransform { tiling, rotation, offset },
|
||||
projector: Projector::default(),
|
||||
},
|
||||
&at(uv),
|
||||
)[0]
|
||||
.0
|
||||
};
|
||||
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);
|
||||
assert!((corner - Vec2::new(1.0, 0.0)).length() < 1e-5, "a quarter turn brings the top left to the top right: {corner}");
|
||||
|
||||
let placed = Projection::Planar {
|
||||
scale: 1.0,
|
||||
axis: 2,
|
||||
offset: [0.0; 3],
|
||||
uv: UvTransform { rotation: 90.0, ..UvTransform::default() },
|
||||
projector: Projector::default(),
|
||||
placed: Some(frame),
|
||||
};
|
||||
assert!((image_samples(&placed, &at(FRAME_UV_CENTER))[0].0 - FRAME_UV_CENTER).length() < 1e-5, "a placed planar frame turns the same way");
|
||||
|
||||
for (tiling, offset, uv) in [([2.0, 3.0], [0.25, -0.5], Vec2::new(0.1, 0.8)), ([1.0, 1.0], [0.0, 0.0], Vec2::new(0.7, 0.2))] {
|
||||
let before = uv * Vec2::from(tiling) + Vec2::from(offset);
|
||||
assert!((sample(0.0, tiling, offset, uv) - before).length() < 1e-6, "unturned: as before");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pattern_and_projection_stays_in_range() {
|
||||
let projections = [
|
||||
Projection::default(),
|
||||
Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3] },
|
||||
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] },
|
||||
Projection::Spherical { scale: 1.0 },
|
||||
Projection::Cylindrical { scale: 1.0, axis: 1 },
|
||||
Projection::Decal(Decal {
|
||||
Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3], uv: Default::default(), projector: Default::default() },
|
||||
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: Default::default(), projector: Default::default(), placed: None },
|
||||
Projection::Spherical { scale: 1.0, uv: Default::default(), offset: [0.0; 3], projector: Default::default() },
|
||||
Projection::Cylindrical { scale: 1.0, axis: 1, uv: Default::default(), offset: [0.0; 3], projector: Default::default(), angle: FULL_TURN_DEGREES },
|
||||
Projection::decal(Decal {
|
||||
center: [0.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
@@ -662,18 +887,16 @@ mod tests {
|
||||
flip: [false; 2],
|
||||
}),
|
||||
];
|
||||
|
||||
for kind in ProceduralKind::ALL {
|
||||
let pattern = Procedural::new(kind);
|
||||
for projection in &projections {
|
||||
for i in 0..50 {
|
||||
let t = i as f32 * 0.13;
|
||||
for index in 0..50 {
|
||||
let position = index as f32 * 0.13;
|
||||
let coords = Coords {
|
||||
uv: Vec2::new(t.fract(), (t * 0.7).fract()),
|
||||
pos: Vec3::new(t.sin(), t.cos(), t * 0.1),
|
||||
uv: Vec2::new(position.fract(), (position * 0.7).fract()),
|
||||
pos: Vec3::new(position.sin(), position.cos(), position * 0.1),
|
||||
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}");
|
||||
@@ -702,7 +925,8 @@ mod tests {
|
||||
for contrast in [1.0, 4.0, 16.0] {
|
||||
let pattern = Procedural { contrast, ..Procedural::new(kind) };
|
||||
for sharpness in [1.0, 4.0, 8.0, 16.0] {
|
||||
let projection = Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] };
|
||||
let projection =
|
||||
Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() };
|
||||
for index in 0..400 {
|
||||
// Cover axis aligned and oblique normals at varied positions
|
||||
let position = index as f32 / 400.0;
|
||||
@@ -715,6 +939,7 @@ mod tests {
|
||||
}
|
||||
|
||||
assert!(largest_difference < 1.0 / 65535.0, "worst difference {largest_difference}");
|
||||
|
||||
let near_axis = triplanar_weights(Vec3::new(0.2, 1.0, 0.1).normalize(), 8.0, 1.0);
|
||||
assert_eq!((near_axis.x, near_axis.z), (0.0, 0.0), "{near_axis}");
|
||||
|
||||
@@ -722,18 +947,30 @@ 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 { width: 2, height: 2, rgba: vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], srgb: false };
|
||||
let image = crate::ImageRes::new(2, 2, vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], false);
|
||||
let coords = Coords { uv: Vec2::ZERO, pos: Vec3::new(0.25, 0.25, 0.75), nrm: Vec3::new(0.2, 1.0, 0.1).normalize() };
|
||||
let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] };
|
||||
let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() };
|
||||
let weights = coords.nrm.abs().powf(8.0);
|
||||
let expected = 100_000.0 * weights.x / (weights.x + weights.y + weights.z);
|
||||
|
||||
@@ -761,6 +998,12 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where frame `frame`'s planar projection lands at `point` facing `nrm`, None where it does not cover
|
||||
fn decal_uv(frame: &Decal, point: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
|
||||
let Projection::Planar { projector, .. } = Projection::decal(*frame) else { return None };
|
||||
crate::projector_cover::placed_cover(frame, &projector, point, nrm).filter(|(_, cover)| *cover > 0.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decals_cover_their_frame_facing_them() {
|
||||
let d = Decal {
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
//! How much of a texel a 3D projection reaches: its shape crop and its backface culling
|
||||
|
||||
use texturecraft_core::{Backface, Decal, DecalFlip, Projection, Projector, ShapeCrop};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::frame_placement::warp_reach;
|
||||
use crate::organic::smoothstep;
|
||||
use crate::pattern::{Coords, depth_fade, frame_crop, frame_local, frame_sample, placed_uv, projector_local};
|
||||
use crate::warp::warp_uv;
|
||||
|
||||
/// Nearer a cylinder's axis than this a texel has no outward direction, so it counts as facing out
|
||||
const MIN_AXIS_DISTANCE: f32 = 1e-6;
|
||||
|
||||
/// The turn (in cosine) over which backface culling fades at hardness 0
|
||||
const BACKFACE_FADE: f32 = 0.6;
|
||||
|
||||
/// The shape crop and backface culling [`projector_cover`] applies, None where it lets every texel through
|
||||
fn cropping_projector(proj: &Projection) -> Option<&Projector> {
|
||||
let projector = match proj {
|
||||
Projection::Triplanar { projector, .. }
|
||||
| Projection::Planar { projector, .. }
|
||||
| Projection::Spherical { projector, .. }
|
||||
| Projection::Cylindrical { projector, .. } => projector,
|
||||
// Framed on the surface: see [`framed_cover`]
|
||||
Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => return None,
|
||||
};
|
||||
Some(projector).filter(|projector| projector.crop != ShapeCrop::ExtendsOutside || projector.backface.on)
|
||||
}
|
||||
|
||||
/// Whether [`projector_cover`] is 1 on every texel, so it needs no texel's place
|
||||
pub fn projector_covers_all(proj: &Projection) -> bool {
|
||||
cropping_projector(proj).is_none()
|
||||
}
|
||||
|
||||
/// How much of the texel at `coords` the projection reaches through its shape crop and backface culling; not for placed planars or warps (see [`framed_cover`])
|
||||
pub fn projector_cover(proj: &Projection, coords: &Coords) -> f32 {
|
||||
let Some(projector) = cropping_projector(proj) else { return 1.0 };
|
||||
|
||||
let local = projector_local(projector, coords);
|
||||
let (inside, facing) = match proj {
|
||||
Projection::Triplanar { .. } => (local.pos.abs().max_element() <= 1.0, None),
|
||||
Projection::Planar { scale, axis, offset, .. } => {
|
||||
let scaled = local.pos * *scale + Vec3::from(*offset);
|
||||
|
||||
// The frame across the axis, and the side the image reads the right way round from
|
||||
let (frame, facing) = match axis {
|
||||
0 => (scaled.z.abs().max(scaled.y.abs()), -local.nrm.x),
|
||||
1 => (scaled.x.abs().max(scaled.z.abs()), local.nrm.y),
|
||||
_ => (scaled.x.abs().max(scaled.y.abs()), local.nrm.z),
|
||||
};
|
||||
(frame <= 1.0, Some(facing))
|
||||
}
|
||||
Projection::Spherical { offset, .. } => ((local.pos + Vec3::from(*offset)).length() <= 1.0, None),
|
||||
Projection::Cylindrical { axis, offset, .. } => {
|
||||
let position = local.pos + Vec3::from(*offset);
|
||||
let normal = local.nrm;
|
||||
let ((across, height, depth), (normal_across, normal_depth)) = match axis {
|
||||
0 => ((position.y, position.x, position.z), (normal.y, normal.z)),
|
||||
2 => ((position.x, position.z, position.y), (normal.x, normal.y)),
|
||||
_ => ((position.x, position.y, position.z), (normal.x, normal.z)),
|
||||
};
|
||||
let radius = across.hypot(depth);
|
||||
let outward = if radius > MIN_AXIS_DISTANCE { (normal_across * across + normal_depth * depth) / radius } else { 1.0 };
|
||||
(radius <= 1.0 && height.abs() <= 1.0, Some(outward))
|
||||
}
|
||||
Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => (true, None),
|
||||
};
|
||||
if projector.crop == ShapeCrop::Cropped && !inside {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
match facing {
|
||||
Some(facing) if projector.backface.on => backface_cover(&projector.backface, facing),
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// How much a face turned `facing` (the cosine of its turn from the projection) keeps
|
||||
pub fn backface_cover(backface: &Backface, facing: f32) -> f32 {
|
||||
// A hand-edited NaN angle or hardness keeps the layer visible rather than making its texels NaN
|
||||
if !(backface.angle.is_finite() && backface.hardness.is_finite()) {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
// cos(angle) as sin(90 - angle): exactly 0 at 90 degrees
|
||||
let threshold = (90.0 - backface.angle).to_radians().sin();
|
||||
let width = (1.0 - backface.hardness.clamp(0.0, 1.0)) * BACKFACE_FADE;
|
||||
if width <= f32::EPSILON {
|
||||
return f32::from(u8::from(facing > threshold));
|
||||
}
|
||||
|
||||
smoothstep(threshold, threshold + width, facing)
|
||||
}
|
||||
|
||||
/// A planar projection placed on the surface at world point `p` with normal `nrm`: its texture coordinates and how much its backface culling and shape crop let through (None when the frame is degenerate)
|
||||
pub fn placed_cover(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
|
||||
let (local, mut cover) = if projector.backface.on {
|
||||
let (local, facing) = frame_sample(frame, projector, p, nrm)?;
|
||||
(local, backface_cover(&projector.backface, facing))
|
||||
} else {
|
||||
(frame_local(frame, projector, p)?, 1.0)
|
||||
};
|
||||
|
||||
if projector.crop == ShapeCrop::Cropped {
|
||||
cover *= frame_crop(frame, local);
|
||||
}
|
||||
Some((flip_uv(placed_uv(local), frame.flip), cover))
|
||||
}
|
||||
|
||||
/// [`placed_cover`] for a frame with a mirrored copy: whichever of the frame and its copy covers the point more. The copy is the frame reflected through the plane `offset` away from `center` (the mesh center) on the symmetry axis, its image flipped as asked
|
||||
pub fn placed_cover_symmetric(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
|
||||
let direct = placed_cover(frame, projector, p, nrm);
|
||||
let Some(symmetry) = frame.symmetry else { return direct };
|
||||
|
||||
let axis = usize::from(symmetry.axis.min(2));
|
||||
let (mut mirrored_position, mut mirrored_normal) = (p, nrm);
|
||||
mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
|
||||
mirrored_normal[axis] = -nrm[axis];
|
||||
let mirrored = placed_cover(frame, projector, mirrored_position, mirrored_normal).map(|(uv, cover)| {
|
||||
let uv = match symmetry.flip {
|
||||
DecalFlip::None => uv,
|
||||
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
|
||||
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
|
||||
};
|
||||
(uv, cover)
|
||||
});
|
||||
match (direct, mirrored) {
|
||||
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
|
||||
(a, b) => a.or(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame
|
||||
fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 {
|
||||
Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y })
|
||||
}
|
||||
|
||||
/// A projection from a frame on the surface (a placed planar or a warp) at world point `p` with normal `nrm`, `center` the mesh center a placed planar's mirrored copy reflects across: its texture coordinates and how much it covers there (None for other projections, a degenerate frame or where nothing lands)
|
||||
pub fn framed_cover(proj: &Projection, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
|
||||
match proj {
|
||||
Projection::Planar { projector, placed: Some(frame), .. } => placed_cover_symmetric(frame, projector, p, nrm, center),
|
||||
Projection::Warp { frame, corners, depth, projector, .. } => warp_cover(frame, corners, *depth, projector, p),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A warp projection at world point `p`: its texture coordinates in the quad its corners make, and, cropped to its shape, how much of the quad and of its Projection Depth (in lengths of the frame's longer side) cover it
|
||||
pub fn warp_cover(frame: &Decal, corners: &[[f32; 2]; 4], depth: f32, projector: &Projector, p: Vec3) -> Option<(Vec2, f32)> {
|
||||
let local = frame_local(frame, projector, p)?;
|
||||
let uv = warp_uv(corners, local.truncate())?;
|
||||
if projector.crop == ShapeCrop::ExtendsOutside {
|
||||
return Some((uv, 1.0));
|
||||
}
|
||||
|
||||
let inside = (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y);
|
||||
let reach = warp_reach(frame.size, depth);
|
||||
Some((uv, if inside { depth_fade(local.z, reach) } else { 0.0 }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The decal formula from before decals were placed planar projections, kept to check they still look the same
|
||||
fn decal_before(frame: &Decal, point: Vec3, surface_normal: Vec3) -> Option<(Vec2, f32)> {
|
||||
let (origin, right, up, normal) = crate::pattern::decal_axes(frame)?;
|
||||
let facing = surface_normal.dot(normal);
|
||||
let offset = point - origin;
|
||||
let (local_x, local_y, local_z) = (offset.dot(right) / frame.size[0].max(1e-6), offset.dot(up) / frame.size[1].max(1e-6), offset.dot(normal).abs());
|
||||
let depth = frame.depth.max(1e-6);
|
||||
if facing <= 0.0 || local_x.abs() > 0.5 || local_y.abs() > 0.5 || local_z > depth || !(local_x.is_finite() && local_y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let cover = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, local_z));
|
||||
Some((Vec2::new(local_x + 0.5, 0.5 - local_y), cover))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nan_backface_angle_or_hardness_culls_nothing() {
|
||||
for backface in [Backface { on: true, angle: f32::NAN, hardness: 0.5 }, Backface { on: true, angle: 60.0, hardness: f32::NAN }] {
|
||||
assert_eq!(backface_cover(&backface, -0.5), 1.0, "{backface:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_decals_cover_exactly_as_before() {
|
||||
let frames = [
|
||||
Decal {
|
||||
center: [0.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
size: [2.0, 1.0],
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: 0.5,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
},
|
||||
Decal {
|
||||
center: [0.3, -0.2, 0.1],
|
||||
normal: [0.4, 0.5, 0.7],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
size: [0.7, 1.3],
|
||||
rotation: 37.0,
|
||||
offset: [0.2, -0.1],
|
||||
depth: 0.4,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
},
|
||||
];
|
||||
for frame in frames {
|
||||
let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") };
|
||||
for sample in 0..4000 {
|
||||
let phase = sample as f32 * 0.137;
|
||||
let point = Vec3::new(phase.sin() * 1.3, (phase * 0.71).cos() * 1.1, (phase * 0.33).sin() * 0.8);
|
||||
let normal = Vec3::new((phase * 1.7).cos(), (phase * 0.9).sin(), (phase * 0.4).cos()).normalize();
|
||||
let now = placed_cover(&placed, &projector, point, normal).filter(|(_, cover)| *cover > 0.0);
|
||||
match (decal_before(&frame, point, normal), now) {
|
||||
(Some(before), Some(now)) => assert_eq!(before, now, "{point} {normal}"),
|
||||
(None, None) => {}
|
||||
(before, now) => panic!("{point} {normal}: {before:?} became {now:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mirrored copy's formula as the decal model before placed planar projections had it (flip and symmetry on a decal)
|
||||
fn symmetric_before(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
|
||||
let flip = |uv: Vec2| flip_uv(uv, d.flip);
|
||||
let direct = decal_before(d, p, nrm).map(|(uv, w)| (flip(uv), w));
|
||||
let Some(symmetry) = d.symmetry else { return direct };
|
||||
let axis = usize::from(symmetry.axis.min(2));
|
||||
let (mut q, mut m) = (p, nrm);
|
||||
q[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
|
||||
m[axis] = -nrm[axis];
|
||||
let mirrored = decal_before(d, q, m).map(|(uv, w)| {
|
||||
let uv = flip(uv);
|
||||
let uv = match symmetry.flip {
|
||||
DecalFlip::None => uv,
|
||||
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
|
||||
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
|
||||
};
|
||||
(uv, w)
|
||||
});
|
||||
match (direct, mirrored) {
|
||||
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
|
||||
(a, b) => a.or(b),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_mirrored_and_flipped_decals_cover_exactly_as_before() {
|
||||
let base = Decal {
|
||||
center: [0.3, -0.2, 0.1],
|
||||
normal: [0.4, 0.5, 0.7],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
size: [0.7, 1.3],
|
||||
rotation: 37.0,
|
||||
offset: [0.2, -0.1],
|
||||
depth: 0.4,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
};
|
||||
let center = Vec3::new(0.1, -0.05, 0.2);
|
||||
let frames = [
|
||||
Decal { flip: [true, false], ..base },
|
||||
Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 0, flip: DecalFlip::None, offset: 0.0 }), ..base },
|
||||
Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: -0.15 }), flip: [false, true], ..base },
|
||||
];
|
||||
for frame in frames {
|
||||
let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") };
|
||||
let mut mirrored = 0;
|
||||
for i in 0..4000 {
|
||||
let t = i as f32 * 0.137;
|
||||
let p = Vec3::new(t.sin() * 1.3, (t * 0.71).cos() * 1.1, (t * 0.33).sin() * 0.8);
|
||||
let nrm = Vec3::new((t * 1.7).cos(), (t * 0.9).sin(), (t * 0.4).cos()).normalize();
|
||||
let now = placed_cover_symmetric(&placed, &projector, p, nrm, center).filter(|(_, cover)| *cover > 0.0);
|
||||
let before = symmetric_before(&frame, p, nrm, center);
|
||||
mirrored += usize::from(before.is_some() && decal_before(&frame, p, nrm).is_none());
|
||||
|
||||
assert_eq!(before, now, "{p} {nrm}");
|
||||
}
|
||||
|
||||
assert!(frame.symmetry.is_none() || mirrored > 0, "the mirrored copy covers points the frame does not");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
//! The depth map of a planar or warp projection: the surface nearest its projector across its view, for depth culling
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
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;
|
||||
|
||||
/// The nearest surface in each cell of a grid across a projector's view
|
||||
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]>,
|
||||
}
|
||||
|
||||
/// The smallest grid cell across and up, so a flat view still divides
|
||||
const MIN_CELL_SIZE: f32 = 1e-6;
|
||||
|
||||
/// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps
|
||||
const EDGE_TOLERANCE: f32 = 1e-6;
|
||||
|
||||
impl ProjectorDepth {
|
||||
/// Build the depth map of a borrowed mesh, if the projection uses depth culling.
|
||||
pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option<Arc<ProjectorDepth>> {
|
||||
let view = ProjectorView::of(projection, bounds)?;
|
||||
Self::build(view, mesh).map(Arc::new)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
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()
|
||||
.fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate())));
|
||||
if min.x > max.x || min.y > max.y {
|
||||
return None;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
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 (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((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_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;
|
||||
|
||||
let area = edge(pa, pb, pc);
|
||||
for y in y0..y1 {
|
||||
for x in x0..x1 {
|
||||
let cell_centre = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let inside = [edge(pb, pc, cell_centre), edge(pc, pa, cell_centre), edge(pa, pb, cell_centre)]
|
||||
.iter()
|
||||
.all(|weight| weight * area.signum() >= -EDGE_TOLERANCE * area.abs());
|
||||
if !inside {
|
||||
continue;
|
||||
}
|
||||
|
||||
let near = a.z + slope.dot(self.origin + cell_centre * self.cell - a.truncate());
|
||||
if let Some(cell) = self.front.get_mut(y * self.grid_side + x)
|
||||
&& near > cell[0]
|
||||
{
|
||||
*cell = [near, slope.x, slope.y];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front
|
||||
pub fn cover(&self, position: Vec3, hardness: f32) -> f32 {
|
||||
// Keep the layer visible when a hand-edited hardness is invalid
|
||||
if !hardness.is_finite() {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
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 <= self.grid_side as f32 && at.y <= self.grid_side as f32) {
|
||||
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.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);
|
||||
let width = (1.0 - hardness.clamp(0.0, 1.0)) * FADE * unit;
|
||||
if width <= f32::EPSILON {
|
||||
return f32::from(u8::from(behind <= bias));
|
||||
}
|
||||
|
||||
1.0 - smoothstep(bias, bias + width, behind)
|
||||
}
|
||||
}
|
||||
|
||||
/// Twice the signed area of triangle `a`, `b`, `q`
|
||||
fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 {
|
||||
(b - a).perp_dot(q - a)
|
||||
}
|
||||
|
||||
/// Cells across and up the grid
|
||||
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;
|
||||
|
||||
/// 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;
|
||||
|
||||
/// How far behind the nearest surface a point may sit and keep everything, in mesh radii
|
||||
const BIAS: f32 = 0.002;
|
||||
|
||||
/// Most the slope adds to the bias, in mesh radii
|
||||
const MAX_SLOPE_BIAS: f32 = 0.05;
|
||||
|
||||
/// How far behind the nearest surface culling fades out at hardness 0, in mesh radii
|
||||
const FADE: f32 = 0.1;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::{Projector, UvTransform};
|
||||
|
||||
/// Two squares facing +Z, one at z = `front` covering x 0..1, one at z = `back` covering x -1..1
|
||||
fn two_squares(front: f32, back: f32) -> Mesh {
|
||||
let positions = vec![
|
||||
Vec3::new(0.0, -1.0, front),
|
||||
Vec3::new(1.0, -1.0, front),
|
||||
Vec3::new(1.0, 1.0, front),
|
||||
Vec3::new(0.0, 1.0, front),
|
||||
Vec3::new(-1.0, -1.0, back),
|
||||
Vec3::new(1.0, -1.0, back),
|
||||
Vec3::new(1.0, 1.0, back),
|
||||
Vec3::new(-1.0, 1.0, back),
|
||||
];
|
||||
Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7], ..Mesh::default() }
|
||||
}
|
||||
|
||||
fn planar_z(on: bool, hardness: f32) -> Projection {
|
||||
let mut projector = Projector::depth_culled();
|
||||
projector.depth.on = on;
|
||||
projector.depth.hardness = hardness;
|
||||
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surfaces_behind_others_are_culled_and_the_nearest_keeps_everything() {
|
||||
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");
|
||||
let soft = depth.cover(Vec3::new(0.5, 0.3, 0.5 - 0.01), 0.0);
|
||||
assert!(soft > 0.0 && soft < 1.0, "a soft cull fades just behind the front: {soft}");
|
||||
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);
|
||||
let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap();
|
||||
|
||||
let behind = depth.cover(Vec3::new(0.5, 0.3, -0.5), f32::NAN);
|
||||
|
||||
assert_eq!(behind, 1.0, "a hand-edited NaN hardness keeps the back square visible");
|
||||
}
|
||||
|
||||
#[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();
|
||||
for right in [1, 2] {
|
||||
edited.positions[right].x = 0.5;
|
||||
}
|
||||
assert_eq!(mesh.bounds(), edited.bounds());
|
||||
|
||||
let proj = planar_z(true, 1.0);
|
||||
let behind_the_cut = Vec3::new(0.75, 0.3, -0.5);
|
||||
let bounds = mesh.bounds();
|
||||
assert_eq!(ProjectorDepth::of(&mesh, bounds, &proj).unwrap().cover(behind_the_cut, 1.0), 0.0);
|
||||
|
||||
let rebuilt = ProjectorDepth::of(&edited, bounds, &proj).unwrap();
|
||||
assert_eq!(rebuilt.cover(behind_the_cut, 1.0), 1.0, "nothing is in front there any more");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slanted_surface_is_never_behind_itself() {
|
||||
let positions = vec![Vec3::new(-1.0, -1.0, -0.9), Vec3::new(1.0, -1.0, 0.9), Vec3::new(1.0, 1.0, 0.9), Vec3::new(-1.0, 1.0, -0.9)];
|
||||
let mesh = Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3], ..Mesh::default() };
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::fill_depth::{FillDepth, FillDepthKey};
|
||||
|
||||
pub(crate) type ViewDepth = (FillDepthKey, Option<Arc<FillDepth>>);
|
||||
|
||||
// Each fill's grids share about 3 MiB
|
||||
const MAX_CACHED_VIEWS: usize = 8;
|
||||
|
||||
/// Reuse projector depth maps for one mesh across tile batches.
|
||||
#[derive(Default)]
|
||||
pub struct ProjectorDepthCache {
|
||||
mesh: Weak<Mesh>,
|
||||
maps: Mutex<Vec<ViewDepth>>,
|
||||
}
|
||||
|
||||
impl ProjectorDepthCache {
|
||||
pub(crate) fn bind(&mut self, mesh: &Arc<Mesh>) -> bool {
|
||||
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, 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_key, _)| *cached_key == key) {
|
||||
let entry = maps.remove(index);
|
||||
let depth = entry.1.clone();
|
||||
maps.insert(0, entry);
|
||||
return depth;
|
||||
}
|
||||
|
||||
let depth = FillDepth::build(mesh, key).map(Arc::new);
|
||||
maps.insert(0, (key, depth.clone()));
|
||||
maps.truncate(MAX_CACHED_VIEWS);
|
||||
|
||||
depth
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::projector_view::ProjectorView;
|
||||
use texturecraft_core::{Projection, Projector, UvTransform};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
#[test]
|
||||
fn eviction_and_mesh_replacement_release_maps_after_the_last_reader() {
|
||||
let mut cache = ProjectorDepthCache::default();
|
||||
let mut mesh = Arc::new(primitives::plane(2.0, 2));
|
||||
let mesh_reference = Arc::downgrade(&mesh);
|
||||
let bounds = mesh.bounds();
|
||||
let mut maps = Vec::new();
|
||||
let mut first_reader = None;
|
||||
|
||||
cache.bind(&mesh);
|
||||
for angle_degrees in 0..MAX_CACHED_VIEWS + 4 {
|
||||
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 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 {
|
||||
first_reader = Some(map);
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS + 1);
|
||||
drop(first_reader);
|
||||
assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS);
|
||||
|
||||
// Mutating a uniquely held Arc disassociates its weak references
|
||||
Arc::make_mut(&mut mesh).positions[0].y += 1.0;
|
||||
assert!(mesh_reference.upgrade().is_none());
|
||||
cache.bind(&mesh);
|
||||
assert!(maps.iter().all(|map| map.upgrade().is_none()));
|
||||
|
||||
let projection =
|
||||
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None };
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
//! Where a planar or warp projection's projector looks from, for depth culling
|
||||
|
||||
use texturecraft_core::{Decal, Projection, Projector};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
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)]
|
||||
pub enum ProjectorView {
|
||||
/// An axis planar projection, reading positions around the mesh centre in mesh radii
|
||||
Axis { axis: u8, projector: Projector, center: Vec3, radius: f32 },
|
||||
/// A planar projection placed on the surface or a warp, from its frame
|
||||
Frame { frame: Decal, projector: Projector, radius: f32 },
|
||||
}
|
||||
|
||||
impl ProjectorView {
|
||||
/// The view of `proj` over a mesh within `bounds`, None unless it is a planar or warp projection with depth culling on
|
||||
pub fn of(proj: &Projection, bounds: (Vec3, Vec3)) -> Option<ProjectorView> {
|
||||
proj.depth_culling()?;
|
||||
let (center, radius) = mesh_frame(bounds);
|
||||
match proj {
|
||||
Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => {
|
||||
Some(ProjectorView::Frame { frame: *frame, projector: turn_only(projector), radius })
|
||||
}
|
||||
Projection::Planar { axis, projector, .. } => Some(ProjectorView::Axis { axis: *axis, projector: turn_only(projector), center, radius }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// World point `point` in the view: across, up and how near the projector (None where the view is degenerate)
|
||||
pub fn local(&self, point: Vec3) -> Option<Vec3> {
|
||||
let local = match self {
|
||||
ProjectorView::Axis { axis, projector, center, radius } => {
|
||||
let at = Coords { uv: Vec2::ZERO, pos: (point - *center) / *radius, nrm: Vec3::Z };
|
||||
let projected = projector_local(projector, &at).pos;
|
||||
|
||||
// The side each axis projects from, as its backface culling reads it
|
||||
match axis {
|
||||
0 => Vec3::new(projected.z, projected.y, -projected.x),
|
||||
1 => Vec3::new(projected.x, projected.z, projected.y),
|
||||
_ => projected,
|
||||
}
|
||||
}
|
||||
ProjectorView::Frame { frame, projector, .. } => frame_local(frame, projector, point)?,
|
||||
};
|
||||
local.is_finite().then_some(local)
|
||||
}
|
||||
|
||||
/// The mesh radius in the view's nearness units
|
||||
pub fn unit(&self) -> f32 {
|
||||
match self {
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Only what moves the view: the turn and stretch, not the culling settings (changing those keeps the depth map)
|
||||
fn turn_only(projector: &Projector) -> Projector {
|
||||
Projector { rotation: projector.rotation, scale: projector.scale, ..Projector::default() }
|
||||
}
|
||||
@@ -103,6 +103,7 @@ mod tests {
|
||||
p.layer_mut(rust).unwrap().visible = false;
|
||||
let before = p.clone();
|
||||
let view = solo_project(&p, rust, false).unwrap();
|
||||
|
||||
assert!(view.layers[&rust].visible, "the soloed layer shows even with its eye off");
|
||||
assert!(!view.layers[&below].visible, "the others are hidden");
|
||||
assert!(view.layers[&other_set].visible, "another texture set keeps its layers");
|
||||
@@ -117,9 +118,12 @@ mod tests {
|
||||
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
|
||||
let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false);
|
||||
let view = solo_project(&p, inner, false).unwrap();
|
||||
|
||||
assert!(view.layers[&folder].visible && view.layers[&inner].visible);
|
||||
assert!(!view.layers[&sibling].visible && !view.layers[&outside].visible);
|
||||
|
||||
let whole = solo_project(&p, folder, false).unwrap();
|
||||
|
||||
assert!(whole.layers[&inner].visible && whole.layers[&sibling].visible, "a soloed folder shows its contents");
|
||||
assert!(!whole.layers[&outside].visible);
|
||||
}
|
||||
@@ -134,8 +138,11 @@ mod tests {
|
||||
masked(&mut p, id);
|
||||
}
|
||||
let kept = solo_project(&p, inner, false).unwrap();
|
||||
|
||||
assert!(kept.layers[&inner].mask.as_ref().unwrap().enabled, "without the flag the mask stays");
|
||||
|
||||
let view = solo_project(&p, inner, true).unwrap();
|
||||
|
||||
assert!(!view.layers[&inner].mask.as_ref().unwrap().enabled && !view.layers[&folder].mask.as_ref().unwrap().enabled);
|
||||
assert!(view.layers[&other].mask.as_ref().unwrap().enabled, "a hidden layer's mask is not touched");
|
||||
assert!(p.layers[&inner].mask.as_ref().unwrap().enabled, "the project keeps its mask");
|
||||
@@ -148,6 +155,7 @@ mod tests {
|
||||
masked(&mut p, source);
|
||||
let instance = add(&mut p, 1, LayerKind::Instance { source }, None, false);
|
||||
let view = solo_project(&p, instance, true).unwrap();
|
||||
|
||||
assert!(!view.layers[&instance].mask.as_ref().unwrap().enabled);
|
||||
assert!(view.layers[&source].mask.as_ref().unwrap().enabled, "the source keeps its mask");
|
||||
}
|
||||
@@ -159,6 +167,7 @@ mod tests {
|
||||
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
|
||||
let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false);
|
||||
let view = solo_project(&p, instance, false).unwrap();
|
||||
|
||||
assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible);
|
||||
}
|
||||
|
||||
|
||||
+274
-17
@@ -2,9 +2,12 @@
|
||||
//! maps. Everything is copy-on-write, so cloning the store for undo is cheap.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use texturecraft_core::{Channel, ChannelKind, LayerId};
|
||||
use texturecraft_texel::{TileImage, from_u16, from_u16_signed};
|
||||
use texturecraft_core::{Channel, ChannelKind, Filtering, LayerId, Sampling};
|
||||
use texturecraft_texel::{TileImage, from_u16, from_u16_signed, srgb_to_linear};
|
||||
|
||||
use crate::mip_level::MipLevel;
|
||||
|
||||
/// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per
|
||||
/// component (height stored signed).
|
||||
@@ -66,16 +69,71 @@ pub struct ImageRes {
|
||||
pub rgba: Vec<[f32; 4]>,
|
||||
/// 8/16-bit images are sRGB-encoded; color channels linearize them.
|
||||
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.
|
||||
pub type ImageStore = HashMap<String, std::sync::Arc<ImageRes>>;
|
||||
|
||||
/// Image levels below the full image at most: a 64k image halves 16 times to 1 texel
|
||||
const MAX_MIP_LEVELS: usize = 16;
|
||||
|
||||
/// Texel (`x`, `y`) of `rgba`; an axis that does not `repeat` (across, down) stops at its edge
|
||||
pub(crate) fn texel_of(rgba: &[[f32; 4]], width: u32, height: u32, x: i64, y: i64, repeat: (bool, bool)) -> [f32; 4] {
|
||||
let (w, h) = (width.max(1) as i64, height.max(1) as i64);
|
||||
let x = if repeat.0 { x.rem_euclid(w) } else { x.clamp(0, w - 1) };
|
||||
let y = if repeat.1 { y.rem_euclid(h) } else { y.clamp(0, h - 1) };
|
||||
let i = (y * w + x) as usize;
|
||||
rgba.get(i).copied().unwrap_or([0.0; 4])
|
||||
}
|
||||
|
||||
/// Bilinear sample of `rgba` (texture coordinates, v down), wrapping around on the axes that `repeat`
|
||||
fn bilinear(rgba: &[[f32; 4]], width: u32, height: u32, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] {
|
||||
// Texel centres sit half a texel in from the texel's corner
|
||||
let texel_x = u * width as f32 - 0.5;
|
||||
let texel_y = v * height as f32 - 0.5;
|
||||
let (left, top) = (texel_x.floor() as i64, texel_y.floor() as i64);
|
||||
let (across, down) = (texel_x - texel_x.floor(), texel_y - texel_y.floor());
|
||||
|
||||
// A huge coordinate saturates to the last texel instead of overflowing past it
|
||||
let (right, bottom) = (left.saturating_add(1), top.saturating_add(1));
|
||||
let texel = |x, y| texel_of(rgba, width, height, x, y, repeat);
|
||||
let (top_left, top_right) = (texel(left, top), texel(right, top));
|
||||
let (bottom_left, bottom_right) = (texel(left, bottom), texel(right, bottom));
|
||||
let mut blended = [0.0; 4];
|
||||
for k in 0..4 {
|
||||
let upper = top_left[k] + (top_right[k] - top_left[k]) * across;
|
||||
let lower = bottom_left[k] + (bottom_right[k] - bottom_left[k]) * across;
|
||||
blended[k] = upper + (lower - upper) * down;
|
||||
}
|
||||
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 {
|
||||
fn texel(&self, x: i64, y: i64) -> [f32; 4] {
|
||||
let (w, h) = (self.width.max(1) as i64, self.height.max(1) as i64);
|
||||
let i = (y.rem_euclid(h) * w + x.rem_euclid(w)) as usize;
|
||||
self.rgba.get(i).copied().unwrap_or([0.0; 4])
|
||||
pub fn new(width: u32, height: u32, rgba: Vec<[f32; 4]>, srgb: bool) -> ImageRes {
|
||||
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] {
|
||||
texel_of(&self.rgba, self.width, self.height, x, y, repeat)
|
||||
}
|
||||
|
||||
/// Bilinear sample with wrap-around (texture coordinates, v down).
|
||||
@@ -83,17 +141,216 @@ impl ImageRes {
|
||||
if !u.is_finite() || !v.is_finite() {
|
||||
return [0.0; 4];
|
||||
}
|
||||
let fx = u * self.width as f32 - 0.5;
|
||||
let fy = v * self.height as f32 - 0.5;
|
||||
let (x0, y0) = (fx.floor() as i64, fy.floor() as i64);
|
||||
let (tx, ty) = (fx - fx.floor(), fy - fy.floor());
|
||||
let (a, b, c, d) = (self.texel(x0, y0), self.texel(x0 + 1, y0), self.texel(x0, y0 + 1), self.texel(x0 + 1, y0 + 1));
|
||||
let mut out = [0.0; 4];
|
||||
for k in 0..4 {
|
||||
let top = a[k] + (b[k] - a[k]) * tx;
|
||||
let bot = c[k] + (d[k] - c[k]) * tx;
|
||||
out[k] = top + (bot - top) * ty;
|
||||
|
||||
bilinear(&self.rgba, self.width, self.height, u, v, (true, true))
|
||||
}
|
||||
|
||||
/// The texel under (`u`, `v`), on the axes that do not `repeat` the edge texel past the edge
|
||||
fn nearest(&self, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] {
|
||||
self.texel((u * self.width as f32).floor() as i64, (v * self.height as f32).floor() as i64, repeat)
|
||||
}
|
||||
|
||||
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(|| 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 = || decode_full(bilinear(&self.rgba, self.width, self.height, u, v, repeat));
|
||||
match sampling.filtering {
|
||||
Filtering::Nearest => decode_full(self.nearest(u, v, repeat)),
|
||||
Filtering::BilinearSharp => full(),
|
||||
Filtering::BilinearHq => {
|
||||
if !uses_mips(footprint) {
|
||||
return full();
|
||||
}
|
||||
|
||||
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 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(finer_level);
|
||||
if toward_coarser <= 0.0 {
|
||||
return finer;
|
||||
}
|
||||
|
||||
let coarser = level(finer_level + 1);
|
||||
[0, 1, 2, 3].map(|component| finer[component] + (coarser[component] - finer[component]) * toward_coarser)
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::UvWrap;
|
||||
|
||||
#[test]
|
||||
fn a_huge_texture_coordinate_samples_without_overflowing() {
|
||||
let image = ImageRes::new(2, 2, vec![[0.5; 4]; 4], false);
|
||||
|
||||
let sampled = image.sample(1e30, -1e30);
|
||||
|
||||
assert_eq!(sampled, [0.5; 4]);
|
||||
}
|
||||
|
||||
/// A 4 × 1 image of columns 0, 1, 2, 3
|
||||
fn ramp() -> ImageRes {
|
||||
ImageRes::new(4, 1, (0..4).map(|column| [column as f32; 4]).collect(), false)
|
||||
}
|
||||
|
||||
fn sampling(filtering: Filtering, wrap: UvWrap) -> Sampling {
|
||||
Sampling { filtering, wrap, ..Sampling::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_reads_the_texel_under_the_point_and_wraps_or_stops_at_the_edge() {
|
||||
let image = ramp();
|
||||
|
||||
let inside = image.sample_filtered(0.6, 0.5, sampling(Filtering::Nearest, UvWrap::Repeat), 1.0);
|
||||
let wrapped = image.sample_filtered(1.1, 0.5, sampling(Filtering::Nearest, UvWrap::Repeat), 1.0);
|
||||
let stopped = image.sample_filtered(1.1, 0.5, sampling(Filtering::Nearest, UvWrap::None), 1.0);
|
||||
|
||||
assert_eq!(inside, [2.0; 4]);
|
||||
assert_eq!(wrapped, [0.0; 4], "past the right edge a repeating image starts again");
|
||||
assert_eq!(stopped, [3.0; 4], "past the right edge a single image keeps its last column");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bilinear_read_past_a_single_images_edge_blends_no_far_side_texel() {
|
||||
let image = ramp();
|
||||
|
||||
let repeating = image.sample_filtered(0.99, 0.5, sampling(Filtering::BilinearSharp, UvWrap::Repeat), 1.0);
|
||||
let single = image.sample_filtered(0.99, 0.5, sampling(Filtering::BilinearSharp, UvWrap::None), 1.0);
|
||||
|
||||
assert!(repeating[0] < 3.0, "the far side's 0 blends in: {repeating:?}");
|
||||
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();
|
||||
let hq = sampling(Filtering::BilinearHq, UvWrap::Repeat);
|
||||
|
||||
let full = image.sample_filtered(0.375, 0.5, hq, 1.0);
|
||||
let halved = image.sample_filtered(0.25, 0.5, hq, 2.0);
|
||||
let quartered = image.sample_filtered(0.375, 0.5, hq, 4.0);
|
||||
let past_the_last = image.sample_filtered(0.375, 0.5, hq, 64.0);
|
||||
let between = image.sample_filtered(0.875, 0.5, hq, 2.0_f32.sqrt());
|
||||
|
||||
assert_eq!(full, [1.0; 4], "a footprint of 1 reads the full image at column 1's centre");
|
||||
assert_eq!(halved, [0.5; 4], "level 1's first texel averages columns 0 and 1");
|
||||
assert_eq!(quartered, [1.5; 4], "a 1-texel level holds the mean");
|
||||
assert_eq!(past_the_last, quartered, "a footprint past the last level reads the last one");
|
||||
assert!(between[0] > 2.0 && between[0] < 3.0, "half a level blends the full image's 3 and level 1's 2: {between:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unshrunk_high_quality_read_builds_no_mips() {
|
||||
let image = ramp();
|
||||
|
||||
let full = image.sample_filtered(0.375, 0.5, sampling(Filtering::BilinearHq, UvWrap::Repeat), 1.0);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! How long one repeat of a fill's tile is on the mesh (mesh units): Physical size reads it from the tiling and writes tiling back
|
||||
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
use texturecraft_core::{FULL_TURN_DEGREES, Projection};
|
||||
|
||||
use crate::pattern::{MIN_CYLINDER_ANGLE, cylinder_axis_index, projector_stretch};
|
||||
|
||||
mod mesh_size;
|
||||
|
||||
pub use mesh_size::MeshSize;
|
||||
|
||||
/// Mesh units one tile covers across and down at a tiling of 1, the projector's stretch included; None without a physical size (per UV tile, spherical, or a stretch uneven across the planes a tile wraps round)
|
||||
fn unit_tile(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> {
|
||||
let radius = size.radius;
|
||||
match projection {
|
||||
Projection::Uv { .. } => Some([size.uv_density; 2]),
|
||||
Projection::Triplanar { scale, projector, .. } => {
|
||||
// Every plane repeats in the one length only while the stretch is even
|
||||
let stretch = projector_stretch(projector).abs();
|
||||
let even = stretch.x == stretch.y && stretch.y == stretch.z;
|
||||
even.then_some([radius * stretch.x / scale; 2])
|
||||
}
|
||||
Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => {
|
||||
let stretch = projector_stretch(projector).abs();
|
||||
Some([frame.size[0] * stretch.x, frame.size[1] * stretch.y])
|
||||
}
|
||||
Projection::Planar { scale, axis, projector, .. } => {
|
||||
let stretch = projector_stretch(projector).abs();
|
||||
let [across, down] = match axis {
|
||||
0 => [stretch.z, stretch.y],
|
||||
1 => [stretch.x, stretch.z],
|
||||
_ => [stretch.x, stretch.y],
|
||||
};
|
||||
Some([2.0 * radius * across / scale, 2.0 * radius * down / scale])
|
||||
}
|
||||
Projection::Cylindrical { scale, axis, angle, projector, .. } => {
|
||||
let stretch = projector_stretch(projector).abs();
|
||||
let ([across, depth], height) = match cylinder_axis_index(*axis) {
|
||||
0 => ([stretch.y, stretch.z], stretch.x),
|
||||
2 => ([stretch.x, stretch.y], stretch.z),
|
||||
_ => ([stretch.x, stretch.z], stretch.y),
|
||||
};
|
||||
|
||||
// Round an uneven cross-section the turn is no fixed length of surface
|
||||
if across != depth {
|
||||
return None;
|
||||
}
|
||||
|
||||
let around = TAU * radius * across * (angle.max(MIN_CYLINDER_ANGLE) / FULL_TURN_DEGREES);
|
||||
Some([around / scale, 2.0 * radius * height / scale])
|
||||
}
|
||||
Projection::UvTile | Projection::Spherical { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tiling a physical size reads and writes: UV's own tiling, a 3D projection's UV tiling
|
||||
fn tiling(projection: &Projection) -> Option<[f32; 2]> {
|
||||
match projection {
|
||||
Projection::Uv { scale, .. } => Some(*scale),
|
||||
Projection::Triplanar { uv, .. } | Projection::Planar { uv, .. } | Projection::Cylindrical { uv, .. } | Projection::Warp { uv, .. } => Some(uv.tiling),
|
||||
Projection::UvTile | Projection::Spherical { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mesh units one repeat of the tile covers across and down
|
||||
pub fn tile_length(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> {
|
||||
let unit = unit_tile(projection, size)?;
|
||||
let tiling = tiling(projection)?;
|
||||
Some([unit[0] / tiling[0].max(f32::EPSILON), unit[1] / tiling[1].max(f32::EPSILON)])
|
||||
}
|
||||
|
||||
/// The tiling that makes one repeat `length` mesh units long across and down
|
||||
pub fn tiling_for_length(projection: &Projection, size: MeshSize, length: [f32; 2]) -> Option<[f32; 2]> {
|
||||
let unit = unit_tile(projection, size)?;
|
||||
Some([unit[0] / length[0].max(f32::EPSILON), unit[1] / length[1].max(f32::EPSILON)])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pattern::{Coords, image_samples};
|
||||
use texturecraft_core::{Projector, UvTransform};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
const SIZE: MeshSize = MeshSize { radius: 2.0, uv_density: 3.0 };
|
||||
|
||||
#[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]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_length_read_back_gives_the_same_tiling() {
|
||||
let uv = UvTransform { tiling: [3.0, 1.5], ..UvTransform::default() };
|
||||
for projection in [
|
||||
Projection::Uv { scale: [3.0, 1.5], rotation: 0.0, offset: [0.0; 2] },
|
||||
Projection::Triplanar { scale: 1.5, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector: Default::default() },
|
||||
Projection::Planar { scale: 0.5, axis: 2, offset: [0.0; 3], uv, projector: Default::default(), placed: None },
|
||||
Projection::Cylindrical { scale: 2.0, axis: 1, uv, offset: [0.0; 3], projector: Default::default(), angle: 360.0 },
|
||||
] {
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_written_length_is_the_repeat_on_the_mesh_through_a_stretched_projector() {
|
||||
let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() };
|
||||
let axis_planar = |uv| Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv, projector, placed: None };
|
||||
let length = 2.0;
|
||||
|
||||
let tiling = tiling_for_length(&axis_planar(UvTransform::default()), SIZE, [length; 2]).unwrap();
|
||||
let planar = axis_planar(UvTransform { tiling, ..UvTransform::default() });
|
||||
let at = |x: f32, y: f32| image_samples(&planar, &Coords { uv: Vec2::ZERO, pos: Vec3::new(x, y, 0.0) / SIZE.radius, nrm: Vec3::Z })[0].0;
|
||||
let across = at(0.3 + length, 0.1) - at(0.3, 0.1);
|
||||
let down = at(0.3, 0.1 + length) - at(0.3, 0.1);
|
||||
|
||||
assert_eq!(tile_length(&axis_planar(UvTransform::default()), SIZE), Some([8.0, 4.0]), "the stretch doubles the repeat across");
|
||||
assert!((across.x.abs() - 1.0).abs() < 1e-4 && across.y.abs() < 1e-4, "one length across is one tile: {across}");
|
||||
assert!(down.x.abs() < 1e-4 && (down.y.abs() - 1.0).abs() < 1e-4, "one length down is one tile: {down}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stretch_uneven_round_the_planes_has_no_physical_size() {
|
||||
let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() };
|
||||
let uv = UvTransform::default();
|
||||
|
||||
let triplanar = Projection::Triplanar { scale: 1.0, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector };
|
||||
let cylinder = Projection::Cylindrical { scale: 1.0, axis: 1, uv, offset: [0.0; 3], projector, angle: 360.0 };
|
||||
let along_axis = Projection::Cylindrical { scale: 1.0, axis: 0, uv, offset: [0.0; 3], projector, angle: 360.0 };
|
||||
|
||||
assert_eq!(tile_length(&triplanar, SIZE), None);
|
||||
assert_eq!(tile_length(&cylinder, SIZE), None);
|
||||
assert_eq!(tile_length(&along_axis, SIZE).map(|[_, down]| down), Some(8.0), "a stretch along the axis lengthens the repeat down it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spherical_has_no_physical_size() {
|
||||
assert_eq!(tile_length(&Projection::Spherical { scale: 1.0, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default() }, SIZE), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV)
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MeshSize {
|
||||
pub radius: f32,
|
||||
pub uv_density: f32,
|
||||
}
|
||||
@@ -599,7 +599,7 @@ mod tests {
|
||||
fn halves(left: f32, right: f32) -> std::sync::Arc<ImageRes> {
|
||||
let size = 8;
|
||||
let rgba = (0..size * size).map(|texel| if texel % size < size / 2 { [left, left, left, 1.0] } else { [right, right, right, 1.0] }).collect();
|
||||
std::sync::Arc::new(ImageRes { width: size as u32, height: size as u32, rgba, srgb: false })
|
||||
std::sync::Arc::new(ImageRes::new(size as u32, size as u32, rgba, false))
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Where a point in a warp projection's frame lands in its image: the inverse of the bilinear quad its four corners make
|
||||
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
/// 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 = linear * linear - 4.0 * constant * quadratic;
|
||||
if discriminant < 0.0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Avoid subtracting near-equal values when the quad is nearly a parallelogram
|
||||
let root_term = -0.5 * (linear + discriminant.sqrt().copysign(linear));
|
||||
|
||||
// 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(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)
|
||||
}
|
||||
|
||||
/// How far `uv` lies outside the image's 0..1 square (0 inside)
|
||||
fn outside(uv: Vec2) -> f32 {
|
||||
(uv - uv.clamp(Vec2::ZERO, Vec2::ONE)).length_squared()
|
||||
}
|
||||
|
||||
/// Relative area below which the quadratic contribution counts as parallel
|
||||
const RELATIVE_PARALLEL: f32 = 1e-6;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FRAME: [[f32; 2]; 4] = [[-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]];
|
||||
|
||||
/// The point at texture coordinates `uv` inside the quad `corners`
|
||||
fn bilinear(corners: &[[f32; 2]; 4], uv: Vec2) -> Vec2 {
|
||||
let [a, b, c, d] = corners.map(Vec2::from);
|
||||
let top = a.lerp(b, uv.x);
|
||||
let bottom = d.lerp(c, uv.x);
|
||||
top.lerp(bottom, uv.y)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unpulled_frame_maps_like_a_planar_frame() {
|
||||
for (x, y) in [(0.0, 0.0), (-0.5, 0.5), (0.25, -0.4), (1.3, 0.7), (-2.0, -1.5)] {
|
||||
assert_eq!(warp_uv(&FRAME, Vec2::new(x, y)), Some(Vec2::new(x + 0.5, 0.5 - y)), "{x} {y}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pulled_corners_bend_the_image_to_their_quad() {
|
||||
let quads = [
|
||||
[[-0.6, 0.4], [0.5, 0.7], [0.3, -0.5], [-0.4, -0.45]],
|
||||
[[-0.5, 0.5], [0.9, 0.5], [0.5, -0.5], [-0.5, -0.5]],
|
||||
[[-0.2, 0.6], [0.2, 0.6], [0.7, -0.6], [-0.7, -0.6]],
|
||||
// Nearly a parallelogram: one corner a hair out
|
||||
[[0.0, 0.0], [1.0, 0.0], [1.0 + 1.0 / 262_144.0, 1.0], [0.0, 1.0]],
|
||||
];
|
||||
for quad in quads {
|
||||
for i in 0..=10 {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,10 @@ fn heavy_stack(f: &mut Fixture) -> LayerId {
|
||||
let l = Layer::new(inner, "inner", fill(&[(Channel::Metallic, procedural(ProceduralKind::Scratches, 0.0, 1.0))]), &Channel::DEFAULT_SET);
|
||||
f.project.insert_layer(0, l, Some(group), true).unwrap();
|
||||
let mut blurred = Mask::new(MaskBackground::Black);
|
||||
blurred.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
|
||||
blurred.effects.push(effect(
|
||||
f,
|
||||
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
|
||||
));
|
||||
blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0 })));
|
||||
let top = add(f, 0, LayerKind::Paint, Some(blurred));
|
||||
let img = f.pixels.layer_mut(top, Channel::BaseColor, (RES, RES));
|
||||
@@ -203,7 +206,7 @@ fn mask_with_height_follows_the_layer_height() {
|
||||
let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3], ramp: Vec::new() };
|
||||
let id = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0; 3])), (Channel::Height, height)]), None);
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default() }));
|
||||
mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default(), sampling: Default::default() }));
|
||||
f.project.layer_mut(id).unwrap().mask = Some(mask);
|
||||
let plain = reference(&f, 0);
|
||||
f.project.layer_mut(id).unwrap().height_mask = HeightMask { enabled: true, contrast: 1.0, offset: 0.0 };
|
||||
@@ -211,12 +214,14 @@ fn mask_with_height_follows_the_layer_height() {
|
||||
let row = TILE * 2;
|
||||
let (left, right) = (16, RES - 16);
|
||||
let v = |c: &Composite, x| c.value(Channel::BaseColor, x, row)[0];
|
||||
|
||||
assert!((v(&plain, left) - 0.75).abs() < 0.01 && (v(&plain, right) - 0.75).abs() < 0.01, "plain mask: 50 % white over gray");
|
||||
assert!(v(&hm, left) > 0.84, "high parts show first: {}", v(&hm, left));
|
||||
assert!(v(&hm, right) < 0.66, "low parts later: {}", v(&hm, right));
|
||||
|
||||
// Without a mask there is nothing to combine
|
||||
f.project.layer_mut(id).unwrap().mask.as_mut().unwrap().enabled = false;
|
||||
|
||||
assert!((v(&reference(&f, 0), left) - 1.0).abs() < 1e-3);
|
||||
}
|
||||
|
||||
@@ -290,7 +295,10 @@ fn nested_stack(f: &mut Fixture) -> Nested {
|
||||
let inner =
|
||||
put(f, 0, Some(g1), fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0)), (Channel::Metallic, Source::Uniform([0.3; 3]))]), None);
|
||||
let mut checker = Mask::new(MaskBackground::Black);
|
||||
checker.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default() }));
|
||||
checker.effects.push(effect(
|
||||
f,
|
||||
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default(), sampling: Default::default() },
|
||||
));
|
||||
let g2 = group(f, Some(g1), BlendMode::Passthrough, 1.0, Some(checker));
|
||||
let mask = generator_mask(f, GeneratorKind::Direction, Some(16.0));
|
||||
put(f, 0, Some(g2), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Scratches, 0.0, 1.0))]), Some(mask));
|
||||
@@ -412,7 +420,7 @@ fn anchor_readers_fall_back_to_full_evaluation() {
|
||||
f.project.layer_mut(n.base).unwrap().content_effects.push(anchor);
|
||||
|
||||
// A mask above the hot layer reads the stack below it
|
||||
let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default() });
|
||||
let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() });
|
||||
f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(reader);
|
||||
for hot in [n.deep, n.top] {
|
||||
assert!(check_cached(&f, 0, hot).is_empty(), "anchors read the stack: nothing cached");
|
||||
@@ -538,11 +546,13 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() {
|
||||
f.project.layer_mut(low).unwrap().content_effects.insert(0, blur);
|
||||
let blurred = reference(&f, 0);
|
||||
assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat");
|
||||
|
||||
let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES);
|
||||
let (images, baked) = (Default::default(), Default::default());
|
||||
for t in all_tiles(RES, RES) {
|
||||
composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
|
||||
}
|
||||
|
||||
assert!(one_by_one == blurred);
|
||||
}
|
||||
|
||||
@@ -556,7 +566,10 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
|
||||
None,
|
||||
);
|
||||
let mut slope = Mask::new(MaskBackground::Black);
|
||||
slope.effects.push(effect(&mut f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
|
||||
slope.effects.push(effect(
|
||||
&mut f,
|
||||
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
|
||||
));
|
||||
slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 })));
|
||||
let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope));
|
||||
let top = add(&mut f, 0, LayerKind::Paint, None);
|
||||
@@ -575,7 +588,9 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
|
||||
for t in all_tiles(RES, RES) {
|
||||
composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
|
||||
}
|
||||
|
||||
assert!(one_by_one == want, "per-tile composites differ from one pass");
|
||||
|
||||
for hot in [top, streaks] {
|
||||
assert!(!check_cached(&f, 0, hot).is_empty());
|
||||
}
|
||||
@@ -648,6 +663,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
|
||||
@@ -656,6 +672,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
|
||||
let (images, baked) = (Default::default(), Default::default());
|
||||
cache.ahead = Vec::new();
|
||||
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache));
|
||||
|
||||
assert!(out == reference(&fixture, 0), "fields kept from before an edit were used after it");
|
||||
assert!(!cache.holds_fields());
|
||||
|
||||
@@ -668,6 +685,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
|
||||
let mut inp = inputs(&fixture, 0, &images, &baked);
|
||||
inp.preview = Some(&preview);
|
||||
composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache));
|
||||
|
||||
assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a live stroke over a sliced pass differs");
|
||||
}
|
||||
|
||||
@@ -685,7 +703,10 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
|
||||
|
||||
// Pattern detail exposes any missing blur field
|
||||
let mut blurred = Mask::new(MaskBackground::Black);
|
||||
blurred.effects.push(effect(&mut fixture, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
|
||||
blurred.effects.push(effect(
|
||||
&mut fixture,
|
||||
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
|
||||
));
|
||||
blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 })));
|
||||
add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred));
|
||||
|
||||
@@ -707,7 +728,9 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
|
||||
cache.set_hot(Some(hot));
|
||||
let mut out = Composite::new(&channels, SIZE);
|
||||
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, bottom, Some(&mut cache));
|
||||
|
||||
assert_eq!(cache.len(), bottom.len());
|
||||
|
||||
cache.budget = cache.bytes();
|
||||
|
||||
// Cache eviction during the run must rebuild missing lower-layer fields
|
||||
@@ -719,6 +742,7 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
|
||||
assert!(cache.holds_fields());
|
||||
}
|
||||
}
|
||||
|
||||
assert!(above.len() > bottom.len());
|
||||
assert!(out == expected, "a tile dropped from the cache was composited with fields that lack the layers off the hot path");
|
||||
}
|
||||
@@ -762,7 +786,7 @@ fn cached_stack_tracks_the_images_a_tile_generator_reads() {
|
||||
pattern.tile.get_or_insert_with(Box::default).background_image = Some("plate".into());
|
||||
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() });
|
||||
|
||||
let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
|
||||
let image_with_value = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false));
|
||||
let mut images = ImageStore::default();
|
||||
let baked = Default::default();
|
||||
let tiles = all_tiles(RES, RES);
|
||||
@@ -778,13 +802,17 @@ fn cached_stack_tracks_the_images_a_tile_generator_reads() {
|
||||
fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]);
|
||||
let input = inputs(&fixture, 0, &images, &baked);
|
||||
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
|
||||
|
||||
assert!(!cache.is_empty(), "{stage}: first tile should be cached");
|
||||
|
||||
let retained = cache.len() - 1;
|
||||
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
|
||||
|
||||
assert_eq!(retained, 0, "{stage}: the layers below are drawn again with the new image");
|
||||
|
||||
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
|
||||
composite_tiles(&input, &mut expected, &tiles);
|
||||
|
||||
assert!(output == expected, "{stage}");
|
||||
}
|
||||
}
|
||||
@@ -800,7 +828,7 @@ fn cached_stack_tracks_referenced_images_only() {
|
||||
let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") };
|
||||
|
||||
fill.sources.insert(Channel::Roughness, Source::Image { name: "used".into(), normal_format: Default::default() });
|
||||
let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
|
||||
let image_with_value = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false));
|
||||
let mut images = ImageStore::default();
|
||||
let baked = Default::default();
|
||||
let tiles = all_tiles(RES, RES);
|
||||
@@ -820,11 +848,14 @@ fn cached_stack_tracks_referenced_images_only() {
|
||||
let replacement = image_with_value(0.4);
|
||||
let replacement_weak = Arc::downgrade(&replacement);
|
||||
images.insert("used".into(), replacement);
|
||||
|
||||
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain replaced image pixels");
|
||||
|
||||
previous_image = Some(replacement_weak);
|
||||
}
|
||||
"remove" => {
|
||||
images.remove("used");
|
||||
|
||||
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain removed image pixels");
|
||||
}
|
||||
"cold" => {}
|
||||
@@ -836,13 +867,17 @@ fn cached_stack_tracks_referenced_images_only() {
|
||||
fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]);
|
||||
let input = inputs(&fixture, 0, &images, &baked);
|
||||
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
|
||||
|
||||
assert!(!cache.is_empty(), "{stage}: first tile should be cached");
|
||||
|
||||
let retained = cache.len() - 1;
|
||||
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
|
||||
|
||||
assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}");
|
||||
|
||||
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
|
||||
composite_tiles(&input, &mut expected, &tiles);
|
||||
|
||||
assert!(output == expected, "{stage}");
|
||||
}
|
||||
}
|
||||
@@ -860,7 +895,7 @@ fn generator_input_image_changes_invalidate_stack_key() {
|
||||
*generator = Generator::new(GeneratorKind::Dirt);
|
||||
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("used"));
|
||||
|
||||
let image = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
|
||||
let image = |value| Arc::new(ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false));
|
||||
let mut images = ImageStore::default();
|
||||
images.insert("used".into(), image(0.1));
|
||||
let baked = Default::default();
|
||||
@@ -869,13 +904,16 @@ fn generator_input_image_changes_invalidate_stack_key() {
|
||||
let original = key(&images);
|
||||
|
||||
images.insert("unrelated".into(), image(0.5));
|
||||
|
||||
assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged");
|
||||
|
||||
let old_image = Arc::downgrade(&images["used"]);
|
||||
images.insert("used".into(), image(0.9));
|
||||
|
||||
assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels");
|
||||
assert!(key(&images) != original, "replacing a generator input must invalidate the cache");
|
||||
|
||||
images.remove("used");
|
||||
|
||||
assert!(key(&images) != original, "removing a generator input must invalidate the cache");
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Backface culling of planar and cylindrical projections
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Faces turned more than `angle` degrees from the projection get none of it, faded softer as `hardness` drops
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Backface {
|
||||
pub on: bool,
|
||||
pub angle: f32,
|
||||
pub hardness: f32,
|
||||
}
|
||||
|
||||
impl Backface {
|
||||
/// The angle culling may take, in degrees from facing the projector
|
||||
pub const ANGLE_RANGE: std::ops::RangeInclusive<f32> = 0.0..=180.0;
|
||||
}
|
||||
|
||||
impl Default for Backface {
|
||||
fn default() -> Self {
|
||||
Backface { on: false, angle: 90.0, hardness: 0.5 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Depth culling of planar and warp projections
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Surfaces hidden from the projector behind other surfaces get none of the projection, faded softer as `hardness` drops
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct DepthCulling {
|
||||
pub on: bool,
|
||||
pub hardness: f32,
|
||||
}
|
||||
|
||||
impl DepthCulling {
|
||||
/// What a new planar or warp projection starts with
|
||||
pub const NEW: DepthCulling = DepthCulling { on: true, hardness: 0.75 };
|
||||
}
|
||||
|
||||
impl Default for DepthCulling {
|
||||
/// Off, as for every projection saved before depth culling existed
|
||||
fn default() -> Self {
|
||||
DepthCulling { on: false, ..DepthCulling::NEW }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Symmetry of a fill's 3D projection: mirrored or radial copies of it on the model
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{FULL_TURN_DEGREES, SymmetryKind};
|
||||
|
||||
/// Copies of a fill's projection: off for every fill saved before symmetry existed
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct FillSymmetry {
|
||||
pub on: bool,
|
||||
pub kind: SymmetryKind,
|
||||
/// 0 = X, 1 = Y, 2 = Z: the mirror plane's normal, or the axis radial copies turn round
|
||||
pub axis: u8,
|
||||
/// Whether the copies' images are turned over across (U) and down (V)
|
||||
pub flip: [bool; 2],
|
||||
/// Where the mirror plane or the turning axis passes, in mesh radii from the mesh's centre
|
||||
pub position: [f32; 3],
|
||||
/// How many radial copies, the original included
|
||||
pub count: u32,
|
||||
/// The degrees the radial copies spread over; a full turn spaces them evenly round it
|
||||
pub span: f32,
|
||||
}
|
||||
|
||||
impl FillSymmetry {
|
||||
/// Off; switched on, a mirror across X through the mesh's centre, or six radial copies over a full turn
|
||||
pub const OFF: FillSymmetry =
|
||||
FillSymmetry { on: false, kind: SymmetryKind::Mirror, axis: 0, flip: [false; 2], position: [0.0; 3], count: 6, span: FULL_TURN_DEGREES };
|
||||
/// The fewest and most radial copies
|
||||
pub const COUNTS: std::ops::RangeInclusive<u32> = 2..=64;
|
||||
/// The degrees an Angle span may be set to: at least one, at most a full turn
|
||||
pub const SPANS: std::ops::RangeInclusive<f32> = 1.0..=FULL_TURN_DEGREES;
|
||||
/// How far the axis position reaches from the mesh's centre, in mesh radii
|
||||
pub const REACH: f32 = 1.0;
|
||||
/// [`FillSymmetry::axis`] of the last axis, Z
|
||||
pub const LAST_AXIS: u8 = 2;
|
||||
|
||||
/// The degrees between radial copies: a full turn spaces `count` copies evenly, a smaller span puts the first and last at its ends (a span that is not a number is a full turn)
|
||||
pub fn step(&self) -> f32 {
|
||||
let count = self.radial_count() as f32;
|
||||
let span = if self.span.is_nan() { FULL_TURN_DEGREES } else { self.span.clamp(0.0, FULL_TURN_DEGREES) };
|
||||
if span >= FULL_TURN_DEGREES { span / count } else { span / (count - 1.0) }
|
||||
}
|
||||
|
||||
/// The copies there are, the original included: two for a mirror
|
||||
pub fn copies(&self) -> u32 {
|
||||
match self.kind {
|
||||
SymmetryKind::Mirror => 2,
|
||||
SymmetryKind::Radial => self.radial_count(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The axis the copies mirror across or turn round, the last one for an axis past it
|
||||
pub fn axis_index(&self) -> usize {
|
||||
usize::from(self.axis.min(Self::LAST_AXIS))
|
||||
}
|
||||
|
||||
/// How many radial copies, kept within [`FillSymmetry::COUNTS`]
|
||||
fn radial_count(&self) -> u32 {
|
||||
self.count.clamp(*Self::COUNTS.start(), *Self::COUNTS.end())
|
||||
}
|
||||
|
||||
/// Whether this is the symmetry a new fill starts with, so saves leave it out
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == FillSymmetry::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FillSymmetry {
|
||||
fn default() -> Self {
|
||||
FillSymmetry::OFF
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn radial(count: u32, span: f32) -> FillSymmetry {
|
||||
FillSymmetry { on: true, kind: SymmetryKind::Radial, count, span, ..FillSymmetry::OFF }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_under_a_full_turn_puts_the_last_copy_at_its_end() {
|
||||
assert_eq!(radial(4, 180.0).step(), 60.0);
|
||||
assert_eq!(radial(4, 360.0).step(), 90.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_span_that_is_not_a_number_spaces_the_copies_round_a_full_turn() {
|
||||
assert_eq!(radial(4, f32::NAN).step(), 90.0);
|
||||
}
|
||||
}
|
||||
+213
-23
@@ -4,37 +4,47 @@ use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum};
|
||||
use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, DepthCulling, Projector, ShapeCrop, lum};
|
||||
|
||||
mod curvature_detail;
|
||||
mod curvature_mode;
|
||||
mod decal_flip;
|
||||
mod decal_symmetry;
|
||||
mod filtering;
|
||||
mod generator_global;
|
||||
mod micro_detail;
|
||||
mod output_resolution;
|
||||
mod resolution_mode;
|
||||
mod sampling;
|
||||
mod scale_mode;
|
||||
mod tile_blending;
|
||||
mod tile_generator;
|
||||
mod tile_input_distribution;
|
||||
mod tile_shape;
|
||||
mod tile_size_mode;
|
||||
mod tile_symmetry;
|
||||
mod uv_transform;
|
||||
mod uv_wrap;
|
||||
|
||||
pub use curvature_detail::CurvatureDetail;
|
||||
pub use curvature_mode::CurvatureMode;
|
||||
pub use decal_flip::DecalFlip;
|
||||
pub use decal_symmetry::DecalSymmetry;
|
||||
pub use filtering::Filtering;
|
||||
pub use generator_global::GeneratorGlobal;
|
||||
pub use micro_detail::MicroDetail;
|
||||
pub use output_resolution::OutputResolution;
|
||||
pub use resolution_mode::ResolutionMode;
|
||||
pub use sampling::Sampling;
|
||||
pub use scale_mode::ScaleMode;
|
||||
pub use tile_blending::TileBlending;
|
||||
pub use tile_generator::TileGenerator;
|
||||
pub use tile_input_distribution::TileInputDistribution;
|
||||
pub use tile_shape::TileShape;
|
||||
pub use tile_size_mode::TileSizeMode;
|
||||
pub use tile_symmetry::TileSymmetry;
|
||||
pub use uv_transform::UvTransform;
|
||||
pub use uv_wrap::UvWrap;
|
||||
|
||||
/// Id of a layer or effect (one id space per project).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
@@ -98,16 +108,22 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[expect(
|
||||
clippy::large_enum_variant,
|
||||
reason = "a fill holds its projection inline; boxing it would cost every fill read an indirection to save a few hundred bytes per paint layer or folder"
|
||||
)]
|
||||
pub enum LayerKind {
|
||||
/// Painted pixels, stored per channel by the engine under the layer id.
|
||||
Paint,
|
||||
@@ -178,20 +194,69 @@ impl Layer {
|
||||
pub enum Projection {
|
||||
/// Texture coordinates of the mesh.
|
||||
Uv { scale: [f32; 2], rotation: f32, offset: [f32; 2] },
|
||||
/// The source stretched once over each UV tile (0..1 in every tile)
|
||||
UvTile,
|
||||
/// World-space box projection blended by the normal.
|
||||
Triplanar { scale: f32, sharpness: f32, offset: [f32; 3] },
|
||||
/// World-space planar projection along an axis (0 = X, 1 = Y, 2 = Z).
|
||||
Planar { scale: f32, axis: u8, offset: [f32; 3] },
|
||||
/// Spherical projection around the mesh center.
|
||||
Spherical { scale: f32 },
|
||||
/// Cylindrical projection around an axis.
|
||||
Cylindrical { scale: f32, axis: u8 },
|
||||
/// A geometry decal: the image projected from a frame placed on the surface (outside the
|
||||
/// frame, behind it or beyond its depth the fill does not cover).
|
||||
Decal(Decal),
|
||||
Triplanar {
|
||||
scale: f32,
|
||||
sharpness: f32,
|
||||
offset: [f32; 3],
|
||||
#[serde(default, skip_serializing_if = "UvTransform::is_default")]
|
||||
uv: UvTransform,
|
||||
#[serde(default, skip_serializing_if = "Projector::is_default")]
|
||||
projector: Projector,
|
||||
},
|
||||
/// World-space planar projection along an axis (0 = X, 1 = Y, 2 = Z), or from a frame placed on the surface
|
||||
Planar {
|
||||
scale: f32,
|
||||
axis: u8,
|
||||
offset: [f32; 3],
|
||||
#[serde(default, skip_serializing_if = "UvTransform::is_default")]
|
||||
uv: UvTransform,
|
||||
#[serde(default, skip_serializing_if = "Projector::is_default")]
|
||||
projector: Projector,
|
||||
/// The frame it projects from when placed on the surface (scale, axis and offset then unused)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
placed: Option<Decal>,
|
||||
},
|
||||
/// Spherical projection around the mesh center
|
||||
Spherical {
|
||||
scale: f32,
|
||||
#[serde(default, skip_serializing_if = "UvTransform::is_default")]
|
||||
uv: UvTransform,
|
||||
#[serde(default, skip_serializing_if = "is_zero_offset")]
|
||||
offset: [f32; 3],
|
||||
#[serde(default, skip_serializing_if = "Projector::is_default")]
|
||||
projector: Projector,
|
||||
},
|
||||
/// Cylindrical projection around an axis
|
||||
Cylindrical {
|
||||
scale: f32,
|
||||
axis: u8,
|
||||
#[serde(default, skip_serializing_if = "UvTransform::is_default")]
|
||||
uv: UvTransform,
|
||||
#[serde(default, skip_serializing_if = "is_zero_offset")]
|
||||
offset: [f32; 3],
|
||||
#[serde(default, skip_serializing_if = "Projector::is_default")]
|
||||
projector: Projector,
|
||||
/// The arc one repeat of the source spans around the axis (degrees), centred on the front
|
||||
#[serde(default = "full_turn", skip_serializing_if = "is_full_turn")]
|
||||
angle: f32,
|
||||
},
|
||||
/// A planar projection from a frame whose four corners are pulled freely, bending the image to the quad they make
|
||||
Warp {
|
||||
/// The frame it projects from (its depth is unused: `depth` sets the reach)
|
||||
frame: Decal,
|
||||
/// Where the frame's corners sit (top left, top right, bottom right, bottom left), across and up in frame sizes from its centre
|
||||
corners: [[f32; 2]; 4],
|
||||
/// Projection Depth: how far in front of and behind the frame it reaches when cropped to its shape, in lengths of the frame's longer side
|
||||
depth: f32,
|
||||
uv: UvTransform,
|
||||
projector: Projector,
|
||||
},
|
||||
}
|
||||
|
||||
/// The frame a decal projects from (world space).
|
||||
/// The frame a planar projection placed on the surface (a decal) projects from, in world space
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Decal {
|
||||
/// The surface point the decal was placed on.
|
||||
@@ -222,6 +287,21 @@ fn not_flipped(flip: &[bool; 2]) -> bool {
|
||||
!flip[0] && !flip[1]
|
||||
}
|
||||
|
||||
/// Serde default of a cylindrical projection's angle: the whole way round
|
||||
fn full_turn() -> f32 {
|
||||
crate::FULL_TURN_DEGREES
|
||||
}
|
||||
|
||||
/// Whether a cylindrical projection spans the whole way round, as ones saved before the angle did (not saved then)
|
||||
fn is_full_turn(angle: &f32) -> bool {
|
||||
*angle == full_turn()
|
||||
}
|
||||
|
||||
/// Whether a spherical or cylindrical projection sits unshifted, as ones saved before the offset did (not saved then)
|
||||
fn is_zero_offset(offset: &[f32; 3]) -> bool {
|
||||
*offset == [0.0; 3]
|
||||
}
|
||||
|
||||
impl Default for Projection {
|
||||
fn default() -> Self {
|
||||
Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }
|
||||
@@ -229,14 +309,88 @@ impl Default for Projection {
|
||||
}
|
||||
|
||||
impl Projection {
|
||||
/// A warp's corners before any is pulled: the frame's own
|
||||
pub const FRAME_CORNERS: [[f32; 2]; 4] = [[-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]];
|
||||
|
||||
/// A new warp's Projection Depth
|
||||
pub const WARP_DEPTH: f32 = 0.1;
|
||||
|
||||
/// A new tri-planar projection's blend sharpness
|
||||
pub const TRIPLANAR_SHARPNESS: f32 = 8.0;
|
||||
|
||||
/// The blend sharpness a tri-planar projection takes: an exponent from soft (1) to near hard (64)
|
||||
pub const TRIPLANAR_SHARPNESS_RANGE: std::ops::RangeInclusive<f32> = 1.0..=64.0;
|
||||
|
||||
/// The arc in degrees a cylindrical projection wraps its image round; a zero arc would divide by zero
|
||||
pub const CYLINDER_ANGLE_RANGE: std::ops::RangeInclusive<f32> = 1.0..=crate::FULL_TURN_DEGREES;
|
||||
|
||||
/// A tri-planar projection with a new fill's settings
|
||||
pub fn triplanar() -> Projection {
|
||||
Projection::Triplanar {
|
||||
scale: 1.0,
|
||||
sharpness: Self::TRIPLANAR_SHARPNESS,
|
||||
offset: [0.0; 3],
|
||||
uv: UvTransform::default(),
|
||||
projector: Projector::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A warp projection from `frame` with its corners where the frame's are
|
||||
pub fn warp(frame: Decal) -> Projection {
|
||||
Projection::Warp {
|
||||
frame,
|
||||
corners: Projection::FRAME_CORNERS,
|
||||
depth: Projection::WARP_DEPTH,
|
||||
uv: UvTransform::default(),
|
||||
projector: Projector::depth_culled(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A planar projection from `frame` with a decal's look: cropped to its frame, depth and image alpha, off faces turned away
|
||||
pub fn decal(frame: Decal) -> Projection {
|
||||
let projector = Projector { crop: ShapeCrop::Cropped, backface: Backface { on: true, ..Backface::default() }, ..Projector::default() };
|
||||
Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(frame) }
|
||||
}
|
||||
|
||||
/// The depth culling of a planar or warp projection that has it on
|
||||
pub fn depth_culling(&self) -> Option<DepthCulling> {
|
||||
match self {
|
||||
Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => Some(projector.depth).filter(|depth| depth.on),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the projection works in 3D, so a fill's symmetry can copy it (UV projections cannot)
|
||||
pub fn takes_symmetry(&self) -> bool {
|
||||
!matches!(self, Projection::Uv { .. } | Projection::UvTile)
|
||||
}
|
||||
|
||||
/// The frame on the surface a placed planar projection projects from
|
||||
pub fn placed(&self) -> Option<&Decal> {
|
||||
match self {
|
||||
Projection::Planar { placed, .. } => placed.as_ref(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame on the surface a placed planar or a warp projection projects from
|
||||
pub fn frame(&self) -> Option<&Decal> {
|
||||
match self {
|
||||
Projection::Planar { placed, .. } => placed.as_ref(),
|
||||
Projection::Warp { frame, .. } => Some(frame),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Projection::UvTile => "Fill (Match per UV Tile)",
|
||||
Projection::Uv { .. } => "UV projection",
|
||||
Projection::Triplanar { .. } => "Tri-planar projection",
|
||||
Projection::Planar { .. } => "Planar projection",
|
||||
Projection::Spherical { .. } => "Spherical projection",
|
||||
Projection::Cylindrical { .. } => "Cylindrical projection",
|
||||
Projection::Decal(_) => "Decal projection",
|
||||
Projection::Warp { .. } => "Warp projection",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -550,7 +704,10 @@ impl Source {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||
pub struct Fill {
|
||||
pub sources: BTreeMap<Channel, Source>,
|
||||
#[serde(serialize_with = "crate::saved_projection::save", deserialize_with = "crate::saved_projection::load")]
|
||||
pub projection: Projection,
|
||||
#[serde(default = "Sampling::saved_before", skip_serializing_if = "Sampling::is_saved_before")]
|
||||
pub sampling: Sampling,
|
||||
/// Set when the sources are maps cooked from a MaterialCraft material.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub link: Option<Box<MaterialLink>>,
|
||||
@@ -1179,7 +1336,10 @@ pub enum EffectKind {
|
||||
/// A uniform or procedural grayscale fill.
|
||||
Fill {
|
||||
source: Source,
|
||||
#[serde(serialize_with = "crate::saved_projection::save", deserialize_with = "crate::saved_projection::load")]
|
||||
projection: Projection,
|
||||
#[serde(default = "Sampling::saved_before", skip_serializing_if = "Sampling::is_saved_before")]
|
||||
sampling: Sampling,
|
||||
},
|
||||
Generator(Generator),
|
||||
Levels(Levels),
|
||||
@@ -1198,10 +1358,7 @@ pub enum EffectKind {
|
||||
/// Content only: a material fill (one source per channel; channels without a source are
|
||||
/// left as they are).
|
||||
Material(Fill),
|
||||
/// Records the stack at its place so masks, fills and generators above can read it
|
||||
/// ([`Source::Anchor`]). In a content stack it records the composited stack right after its
|
||||
/// layer (that layer and everything below); in a mask, the mask value at that point (every
|
||||
/// channel reads that gray).
|
||||
/// Records the stack at its place so masks, fills and generators above can read it ([`Source::Anchor`]): in a content stack the composited stack right after its layer (that layer and everything below), in a mask the mask value there (every channel reads that gray)
|
||||
Anchor,
|
||||
}
|
||||
|
||||
@@ -1547,21 +1704,27 @@ mod tests {
|
||||
assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks");
|
||||
assert_eq!(EffectKind::Generator(Generator::new(GeneratorKind::Dirt)).content_only(), Some(false));
|
||||
assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None);
|
||||
|
||||
let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]);
|
||||
assert!(!fill_layer.reads_anchor());
|
||||
|
||||
let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() };
|
||||
fill_layer.mask = Some(Mask {
|
||||
effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })],
|
||||
effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })],
|
||||
..Mask::new(MaskBackground::Black)
|
||||
});
|
||||
|
||||
assert!(fill_layer.reads_anchor());
|
||||
|
||||
// A generator with micro detail reads its anchor too
|
||||
let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]);
|
||||
let mut generator = Generator::new(GeneratorKind::Dirt);
|
||||
generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 });
|
||||
|
||||
assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]);
|
||||
|
||||
generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) });
|
||||
|
||||
assert!(generator_layer.reads_anchor());
|
||||
}
|
||||
|
||||
@@ -1605,6 +1768,33 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() {
|
||||
let fills = [
|
||||
r#"{"sources":{"BaseColor":{"Uniform":[0.5,0.5,0.5]}},"projection":{"Uv":{"scale":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0]}}}"#,
|
||||
r#"{"sources":{},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}"#,
|
||||
r#"{"sources":{},"projection":{"Planar":{"scale":2.0,"axis":2,"offset":[0.0,1.0,0.0]}}}"#,
|
||||
r#"{"sources":{},"projection":{"Spherical":{"scale":1.0}}}"#,
|
||||
r#"{"sources":{},"projection":{"Cylindrical":{"scale":1.0,"axis":1}}}"#,
|
||||
r#"{"sources":{},"projection":{"Decal":{"center":[0.0,0.0,0.0],"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,0.0],"depth":1.0}}}"#,
|
||||
];
|
||||
for saved in fills {
|
||||
let loaded: Fill = serde_json::from_str(saved).unwrap();
|
||||
|
||||
assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved");
|
||||
}
|
||||
|
||||
let effects = [
|
||||
r#"{"Fill":{"source":{"Uniform":[0.5,0.5,0.5]},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}}"#,
|
||||
r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#,
|
||||
];
|
||||
for saved in effects {
|
||||
let loaded: EffectKind = serde_json::from_str(saved).unwrap();
|
||||
|
||||
assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn procedural_kinds_parse_labels_and_saved_names() {
|
||||
for kind in ProceduralKind::ALL {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How a fill reads its image sources between texels
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum Filtering {
|
||||
/// Bilinear on the image level that matches the texel's footprint: smooth when the image is shrunk
|
||||
#[default]
|
||||
BilinearHq,
|
||||
/// Bilinear on the full image: sharp, but may shimmer where the image is shrunk
|
||||
BilinearSharp,
|
||||
/// The nearest image texel
|
||||
Nearest,
|
||||
}
|
||||
|
||||
impl Filtering {
|
||||
pub const ALL: [Filtering; 3] = [Filtering::BilinearHq, Filtering::BilinearSharp, Filtering::Nearest];
|
||||
|
||||
/// Command id
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Filtering::BilinearHq => "bilinearHq",
|
||||
Filtering::BilinearSharp => "bilinearSharp",
|
||||
Filtering::Nearest => "nearest",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<Filtering> {
|
||||
Filtering::ALL.into_iter().find(|f| f.id() == id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{Filtering, ScaleMode, UvWrap};
|
||||
use crate::FillSymmetry;
|
||||
|
||||
/// How a fill samples its images and what its size is set in; older fills read with [`Sampling::SAVED_BEFORE`]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||
pub struct Sampling {
|
||||
#[serde(default)]
|
||||
pub filtering: Filtering,
|
||||
#[serde(default)]
|
||||
pub wrap: UvWrap,
|
||||
#[serde(default)]
|
||||
pub scale: ScaleMode,
|
||||
#[serde(default, skip_serializing_if = "FillSymmetry::is_default")]
|
||||
pub symmetry: FillSymmetry,
|
||||
}
|
||||
|
||||
impl Sampling {
|
||||
/// What fills saved before the sampling choices existed did: plain bilinear
|
||||
pub const SAVED_BEFORE: Sampling =
|
||||
Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF };
|
||||
|
||||
/// Serde default for fills saved before the field existed
|
||||
pub fn saved_before() -> Sampling {
|
||||
Sampling::SAVED_BEFORE
|
||||
}
|
||||
|
||||
/// Whether it samples as fills saved before the field existed did (not saved then, so they save as they were)
|
||||
pub fn is_saved_before(&self) -> bool {
|
||||
*self == Sampling::SAVED_BEFORE
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What a fill's size is set in: repeats of its tile, or the tile's length on the mesh (stored as tiling either way)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum ScaleMode {
|
||||
#[default]
|
||||
Tiling,
|
||||
PhysicalSize,
|
||||
}
|
||||
|
||||
impl ScaleMode {
|
||||
pub const ALL: [ScaleMode; 2] = [ScaleMode::Tiling, ScaleMode::PhysicalSize];
|
||||
|
||||
/// Command id
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
ScaleMode::Tiling => "tiling",
|
||||
ScaleMode::PhysicalSize => "physicalSize",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<ScaleMode> {
|
||||
ScaleMode::ALL.into_iter().find(|mode| mode.id() == id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UvTransform {
|
||||
pub tiling: [f32; 2],
|
||||
pub rotation: f32,
|
||||
pub offset: [f32; 2],
|
||||
}
|
||||
|
||||
impl Default for UvTransform {
|
||||
fn default() -> Self {
|
||||
UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }
|
||||
}
|
||||
}
|
||||
|
||||
impl UvTransform {
|
||||
/// Whether it changes nothing, as projections saved before it existed did (not saved then)
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == UvTransform::default()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Whether a UV-placed fill repeats past its 0..1 tile, across, down, both or neither
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum UvWrap {
|
||||
#[default]
|
||||
Repeat,
|
||||
RepeatHorizontally,
|
||||
RepeatVertically,
|
||||
/// One tile only: outside it the fill does not cover
|
||||
None,
|
||||
}
|
||||
|
||||
impl UvWrap {
|
||||
pub const ALL: [UvWrap; 4] = [UvWrap::None, UvWrap::RepeatHorizontally, UvWrap::RepeatVertically, UvWrap::Repeat];
|
||||
|
||||
/// Command id
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
UvWrap::Repeat => "repeat",
|
||||
UvWrap::RepeatHorizontally => "repeatHorizontally",
|
||||
UvWrap::RepeatVertically => "repeatVertically",
|
||||
UvWrap::None => "none",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<UvWrap> {
|
||||
UvWrap::ALL.into_iter().find(|w| w.id() == id)
|
||||
}
|
||||
|
||||
/// Whether the fill repeats across (u) and down (v)
|
||||
pub fn repeats(self) -> (bool, bool) {
|
||||
match self {
|
||||
UvWrap::Repeat => (true, true),
|
||||
UvWrap::RepeatHorizontally => (true, false),
|
||||
UvWrap::RepeatVertically => (false, true),
|
||||
UvWrap::None => (false, false),
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-4
@@ -7,15 +7,27 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod backface;
|
||||
pub mod bake;
|
||||
pub mod blend;
|
||||
mod block_scales;
|
||||
pub mod channel;
|
||||
pub mod depth_culling;
|
||||
mod env_alignment;
|
||||
pub mod fill_symmetry;
|
||||
pub mod layer;
|
||||
pub mod project;
|
||||
pub mod projector;
|
||||
mod saved_decal;
|
||||
mod saved_projection;
|
||||
mod shadow_mode;
|
||||
pub mod shape_crop;
|
||||
pub mod symmetry_kind;
|
||||
|
||||
/// A full turn, in degrees
|
||||
pub const FULL_TURN_DEGREES: f32 = 360.0;
|
||||
|
||||
pub use backface::Backface;
|
||||
pub use bake::{
|
||||
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap,
|
||||
BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization,
|
||||
@@ -25,16 +37,21 @@ pub use bake::{
|
||||
};
|
||||
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
|
||||
pub use channel::{Channel, ChannelFormat, ChannelKind};
|
||||
pub use depth_culling::DepthCulling;
|
||||
pub use fill_symmetry::FillSymmetry;
|
||||
pub use layer::{
|
||||
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal,
|
||||
GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution,
|
||||
PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode,
|
||||
TileSymmetry, gradient, hsl_adjust, per_unit,
|
||||
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator,
|
||||
GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail,
|
||||
OutputResolution, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Sampling, ScaleMode, Source, TileBlending, TileGenerator,
|
||||
TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit,
|
||||
};
|
||||
pub use project::{
|
||||
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing,
|
||||
Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at,
|
||||
};
|
||||
pub use projector::Projector;
|
||||
pub use shape_crop::ShapeCrop;
|
||||
pub use symmetry_kind::SymmetryKind;
|
||||
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
|
||||
pub enum CoreError {
|
||||
|
||||
@@ -316,6 +316,14 @@ pub struct DisplaySettings {
|
||||
pub ior_specular: bool,
|
||||
/// Depth of field of the viewport and the path tracer (thin lens).
|
||||
pub dof: DepthOfField,
|
||||
/// The selected fill's projection gizmos show in the 3D view (the Projection row's eye)
|
||||
#[serde(skip_serializing_if = "is_shown")]
|
||||
pub projection_gizmos: bool,
|
||||
}
|
||||
|
||||
/// Whether a view flag is at its default, shown (saved projects then stay as they were)
|
||||
fn is_shown(shown: &bool) -> bool {
|
||||
*shown
|
||||
}
|
||||
|
||||
/// A thin-lens camera's depth of field (Display settings: focus distance and aperture).
|
||||
@@ -421,6 +429,7 @@ impl Default for DisplaySettings {
|
||||
ior: 1.5,
|
||||
ior_specular: false,
|
||||
dof: DepthOfField::default(),
|
||||
projection_gizmos: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -834,12 +843,13 @@ mod tests {
|
||||
let mut top = paint(&mut p, "y");
|
||||
let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() };
|
||||
top.mask = Some(Mask {
|
||||
effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })],
|
||||
effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })],
|
||||
..Mask::new(MaskBackground::Black)
|
||||
});
|
||||
p.insert_layer(0, top, Some(id), false).unwrap();
|
||||
let json = serde_json::to_string(&p).unwrap();
|
||||
let back: Project = serde_json::from_str(&json).unwrap();
|
||||
|
||||
assert_eq!(back, p);
|
||||
assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id));
|
||||
|
||||
@@ -849,6 +859,7 @@ mod tests {
|
||||
l.as_object_mut().unwrap().remove("content_effects");
|
||||
}
|
||||
let old: Project = serde_json::from_value(v).unwrap();
|
||||
|
||||
assert!(old.layers.values().all(|l| l.content_effects.is_empty()));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
//! The 3D projection settings shared by tri-planar, planar, spherical and cylindrical projections
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Backface, DepthCulling, ShapeCrop};
|
||||
|
||||
/// Rotation (degrees about X, then Y, then Z) and per-axis scale of a 3D projection's shape; default = unchanged
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Projector {
|
||||
pub rotation: [f32; 3],
|
||||
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(),
|
||||
ignore_image_alpha: false,
|
||||
depth: DepthCulling::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Projector {
|
||||
/// The settings a new planar or warp projection starts with: depth culled
|
||||
pub fn depth_culled() -> Projector {
|
||||
Projector { depth: DepthCulling::NEW, ..Projector::default() }
|
||||
}
|
||||
|
||||
/// Whether it is the default, which projections saved before it existed load as (not saved then)
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == Projector::default()
|
||||
}
|
||||
|
||||
/// Whether it turns or stretches the projection at all
|
||||
pub fn turns(&self) -> bool {
|
||||
self.rotation != [0.0; 3] || self.scale != [1.0; 3]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//! A decal written in the shape saved before decals were planar projections
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::Decal;
|
||||
|
||||
/// A decal in the shape saved before decals were planar projections
|
||||
#[derive(Serialize)]
|
||||
pub(crate) enum SavedDecal<'a> {
|
||||
Decal(&'a Decal),
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Reading and writing saved projections, including decals in the shape saved before they were planar projections placed on the surface
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use crate::saved_decal::SavedDecal;
|
||||
use crate::{Decal, Projection};
|
||||
|
||||
/// A projection as saved: today's, or a decal from before decals were planar projections
|
||||
#[derive(Deserialize)]
|
||||
enum SavedProjection {
|
||||
Decal(Decal),
|
||||
#[serde(untagged)]
|
||||
Current(Projection),
|
||||
}
|
||||
|
||||
/// Serde hook for projection fields: an older decal loads as the planar projection that looks the same
|
||||
pub(crate) fn load<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Projection, D::Error> {
|
||||
Ok(match SavedProjection::deserialize(deserializer)? {
|
||||
SavedProjection::Decal(frame) => Projection::decal(frame),
|
||||
SavedProjection::Current(projection) => projection,
|
||||
})
|
||||
}
|
||||
|
||||
/// Serde hook for projection fields: a planar projection with a decal's look saves as a decal, so earlier versions still read a decal
|
||||
pub(crate) fn save<S: Serializer>(projection: &Projection, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
match projection {
|
||||
Projection::Planar { placed: Some(frame), .. } if *projection == Projection::decal(*frame) => SavedDecal::Decal(frame).serialize(serializer),
|
||||
_ => projection.serialize(serializer),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! How far a 3D projection reaches past its shape
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Whether a projection reaches past its shape (planar frame, tri-planar box, sphere, cylinder)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub enum ShapeCrop {
|
||||
#[default]
|
||||
ExtendsOutside,
|
||||
Cropped,
|
||||
}
|
||||
|
||||
impl ShapeCrop {
|
||||
pub const ALL: [ShapeCrop; 2] = [ShapeCrop::Cropped, ShapeCrop::ExtendsOutside];
|
||||
|
||||
/// Command id
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
ShapeCrop::ExtendsOutside => "extendsOutside",
|
||||
ShapeCrop::Cropped => "cropped",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<ShapeCrop> {
|
||||
ShapeCrop::ALL.into_iter().find(|crop| crop.id() == id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! The kind of copies a symmetric fill makes: mirrored or turned round an axis
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How a symmetric fill copies its projection
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum SymmetryKind {
|
||||
/// One copy mirrored across the plane through the axis position, square to the axis
|
||||
#[default]
|
||||
Mirror,
|
||||
/// Copies turned round the axis through the axis position
|
||||
Radial,
|
||||
}
|
||||
|
||||
impl SymmetryKind {
|
||||
/// Every kind, in the order the Type list shows them
|
||||
pub const ALL: [SymmetryKind; 2] = [SymmetryKind::Mirror, SymmetryKind::Radial];
|
||||
|
||||
/// The id commands use
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
SymmetryKind::Mirror => "mirror",
|
||||
SymmetryKind::Radial => "radial",
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind with command id `id`
|
||||
pub fn from_id(id: &str) -> Option<SymmetryKind> {
|
||||
SymmetryKind::ALL.into_iter().find(|kind| kind.id() == id)
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
let mut v = Vec::new();
|
||||
v.extend(crate::view_cmds::edit_specs());
|
||||
v.extend(crate::layer_cmds::specs());
|
||||
v.extend(crate::fill_reset_cmds::specs());
|
||||
v.extend(crate::layer_ops::specs());
|
||||
v.extend(crate::instance_cmds::specs());
|
||||
v.extend(crate::mask_cmds::specs());
|
||||
@@ -142,6 +143,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::smart_masks::specs());
|
||||
v.extend(crate::filter_lib::specs());
|
||||
v.extend(crate::decal_cmds::specs());
|
||||
v.extend(crate::warp_cmds::specs());
|
||||
v.extend(crate::text_cmds::specs());
|
||||
v
|
||||
})
|
||||
|
||||
+257
-106
@@ -1,14 +1,18 @@
|
||||
//! Geometry decals: an image resource projected onto the surface from a frame placed on it
|
||||
//! (a decal fill with a planar projection), as a fill layer with a decal projection.
|
||||
//! (a decal fill with a planar projection), as a fill layer with a decal projection, and moving
|
||||
//! the frame of any planar or warp projection
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::axis_frame::{placed_from_axis, placing_moves_pattern};
|
||||
use texturecraft_compose::frame_placement::{MIN_FRAME_SIDE, culling_folds, folded, longer_side, placed, placement as frame_placement};
|
||||
use texturecraft_core::{
|
||||
Channel, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source,
|
||||
};
|
||||
use texturecraft_geom::glam::{Quat, Vec2, Vec3};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, layer_param, strp, u64p, vec3};
|
||||
use crate::tool_cmds::viewport_of;
|
||||
use crate::layer_cmds::{FULL_TURN_DEGREES, MAX_PROJECTION_DEPTH};
|
||||
use crate::tool_cmds::{pair, viewport_of};
|
||||
use crate::{Result, Session, StackTarget, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -27,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit decal",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z] (default: the decal's up carried along when it moves onto a surface facing another way), size?: height | [w,h], keepProportions?: true keeps the image's aspect (the current ratio without an image): a height sets the width, a [w,h] pair or no size sets the height from the width, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, symmetry?: x|y|z|off, symmetryFlip?: none|u|v, symmetryOffset? (the mirrored copy; the flip and offset alone keep the axis), image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}",
|
||||
"{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer) — any fill with a planar or warp projection: moves the frame it projects from (an axis planar is first placed as the frame it projects from, reading images exactly as before; a warp keeps its corners), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z] (default: the decal's up carried along when it moves onto a surface facing another way), size?: height | [w,h], keepProportions?: true keeps the image's aspect (the current ratio without an image): a height sets the width, a [w,h] pair or no size sets the height from the width, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?: world units (a warp: its Projection Depth becomes this over the frame's longer side), frameOffset?: [x, y, z] (the frame's centre in mesh radii from the mesh's centre), frameRotation?: [x, y, z] degrees (its turn: unturned it faces +Z with +Y up), frameScale?: [width, height, reach] (in mesh diagonals; reach = how far it projects in front of and behind it, a warp's Projection Depth times its longer side) — the frame as the 3D projection settings show it, applied before the other fields; any projector turn or scale is first folded into the frame (it lands the same); refused: an axis planar reading a procedural (placing it would move the pattern) and, under backface culling with an uneven or mirrored projector scale, placing an axis planar or the frame fields (even the scale out or turn culling off), symmetry?: x|y|z|off, symmetryFlip?: none|u|v, symmetryOffset? (the mirrored copy; the flip and offset alone keep the axis), image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags); a call that changes nothing adds no undo step}",
|
||||
always,
|
||||
set
|
||||
),
|
||||
@@ -62,35 +66,42 @@ const MIN_SIZE: f32 = 1e-4;
|
||||
/// The largest decal side or depth, relative to the mesh diagonal
|
||||
const MAX_SIZE: f32 = 10.0;
|
||||
|
||||
/// The smallest mesh diagonal decal sizes count in, so a collapsed mesh still places one
|
||||
const MIN_MESH_DIAGONAL: f32 = 1e-3;
|
||||
|
||||
/// A given `up` this near the normal (squared sine of the angle between them) leaves no upright direction
|
||||
const MIN_GIVEN_UP_CROSS_SQUARED: f32 = 1e-8;
|
||||
|
||||
/// The camera's up this near the normal (squared sine) is a top face seen from the front: up is where the camera looks
|
||||
const MIN_CAMERA_UP_CROSS_SQUARED: f32 = 1e-4;
|
||||
|
||||
/// The mesh's diagonal (decal sizes are relative to it).
|
||||
fn mesh_size(s: &Session) -> f32 {
|
||||
let (lo, hi) = s.mesh.bounds();
|
||||
(hi - lo).length().max(1e-3)
|
||||
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(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> {
|
||||
let value = p.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
|
||||
/// screen), or where the camera looks when that is along `normal` (a top face seen from the
|
||||
/// front: its far edge is up, as on a table).
|
||||
fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result<Vec3> {
|
||||
if p.get("up").is_some() {
|
||||
return vec3(p, "up").filter(|u| u.cross(normal).length_squared() > 1e-8).ok_or_else(|| bad(cmd, "`up` must be [x, y, z], not along the normal"));
|
||||
fn decal_up(session: &Session, command: &str, params: &Value, normal: Vec3) -> Result<Vec3> {
|
||||
if params.get("up").is_some() {
|
||||
return vec3(params, "up")
|
||||
.filter(|up| up.cross(normal).length_squared() > MIN_GIVEN_UP_CROSS_SQUARED)
|
||||
.ok_or_else(|| bad(command, "`up` must be [x, y, z], not along the normal"));
|
||||
}
|
||||
let to_world = s.camera.view().inverse();
|
||||
|
||||
let to_world = session.camera.view().inverse();
|
||||
let up = to_world.transform_vector3(Vec3::Y);
|
||||
Ok(if up.normalize_or_zero().cross(normal).length_squared() > 1e-4 { up } else { to_world.transform_vector3(Vec3::NEG_Z) })
|
||||
Ok(if up.normalize_or_zero().cross(normal).length_squared() > MIN_CAMERA_UP_CROSS_SQUARED { up } else { to_world.transform_vector3(Vec3::NEG_Z) })
|
||||
}
|
||||
|
||||
/// The mirrored copy asked for by `symmetry` (x, y, z or off) and `symmetryFlip` (none, u or v),
|
||||
@@ -143,87 +154,196 @@ fn carried_up(s: &Session, from: (Vec3, Vec3), to: Vec3) -> Vec3 {
|
||||
Quat::from_rotation_arc(old_normal, new_normal) * old_up
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "layer.add.decal";
|
||||
let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string();
|
||||
let resource = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?;
|
||||
fn add(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let command = "layer.add.decal";
|
||||
let image = strp(params, "image").ok_or_else(|| bad(command, "`image` is required"))?.to_string();
|
||||
let resource = session.images.get(&image).ok_or_else(|| bad(command, format!("no image resource `{image}` (import it first)")))?;
|
||||
let aspect = resource.width as f32 / resource.height.max(1) as f32;
|
||||
let (center, normal, ts) = placement(s, cmd, p, s.ts(), false)?.ok_or_else(|| bad(cmd, "no placement"))?;
|
||||
let (center, normal, texture_set) = placement(session, command, params, session.ts(), false)?.ok_or_else(|| bad(command, "no placement"))?;
|
||||
|
||||
// None: the image masks a new fill layer
|
||||
let target = match strp(p, "channel") {
|
||||
let target = match strp(params, "channel") {
|
||||
Some("mask") => None,
|
||||
_ => Some(channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor)),
|
||||
_ => Some(channel_param(command, params, "channel")?.unwrap_or(Channel::BaseColor)),
|
||||
};
|
||||
let set_channels = s.doc.project.texture_set(ts)?.channel_list();
|
||||
let set_channels = session.doc.project.texture_set(texture_set)?.channel_list();
|
||||
if let Some(channel) = target
|
||||
&& !set_channels.contains(&channel)
|
||||
{
|
||||
return Err(bad(cmd, format!("the texture set has no {} channel", channel.label())));
|
||||
return Err(bad(command, format!("the texture set has no {} channel", channel.label())));
|
||||
}
|
||||
|
||||
let mesh_diagonal = mesh_size(s);
|
||||
let bounds = session.mesh.bounds();
|
||||
let mesh_diagonal = diagonal_of(bounds);
|
||||
let default_height = mesh_diagonal * DEFAULT_HEIGHT;
|
||||
let mut size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]);
|
||||
if boolp(p, "keepProportions") == Some(true) && p.get("size").is_some_and(Value::is_array) {
|
||||
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);
|
||||
}
|
||||
let decal = Decal {
|
||||
center: center.to_array(),
|
||||
normal: normal.to_array(),
|
||||
up: decal_up(s, cmd, p, normal)?.to_array(),
|
||||
up: decal_up(session, command, params, normal)?.to_array(),
|
||||
size,
|
||||
rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0),
|
||||
rotation: f32p(params, "rotation").unwrap_or(0.0).rem_euclid(FULL_TURN_DEGREES),
|
||||
offset: [0.0; 2],
|
||||
flip: [boolp(p, "flipU").unwrap_or(false), boolp(p, "flipV").unwrap_or(false)],
|
||||
flip: [boolp(params, "flipU").unwrap_or(false), boolp(params, "flipV").unwrap_or(false)],
|
||||
|
||||
// By default it reaches half its larger side into the surface
|
||||
depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)),
|
||||
symmetry: symmetry_param(cmd, p, None, s.mesh.bounds())?,
|
||||
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, bounds)?,
|
||||
};
|
||||
|
||||
// A decal dropped on another texture set goes there and selects it, as a dropped material does
|
||||
if ts != s.ts() {
|
||||
crate::set_cmds::select_set(s, ts)?;
|
||||
if texture_set != session.ts() {
|
||||
crate::set_cmds::select_set(session, texture_set)?;
|
||||
}
|
||||
|
||||
let base = strp(p, "name")
|
||||
let base = strp(params, "name")
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Decal").to_string());
|
||||
let name = s.doc.project.next_layer_name(ts, &base);
|
||||
let (id, mask_effect) = s.edit("Add decal", |s| {
|
||||
let id = s.doc.project.alloc_id();
|
||||
let name = session.doc.project.next_layer_name(texture_set, &base);
|
||||
let (id, mask_effect) = session.edit("Add decal", |session| {
|
||||
let id = session.doc.project.alloc_id();
|
||||
let Some(channel) = target else {
|
||||
let effect_id = s.doc.project.alloc_id();
|
||||
let effect_id = session.doc.project.alloc_id();
|
||||
let mut layer = Layer::new(id, name, LayerKind::Fill(Fill::default()), &set_channels);
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(Effect::new(effect_id, EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::Decal(decal) }));
|
||||
mask.effects.push(Effect::new(
|
||||
effect_id,
|
||||
EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::decal(decal), sampling: Default::default() },
|
||||
));
|
||||
layer.mask = Some(mask);
|
||||
crate::layer_cmds::insert_selected(s, layer)?;
|
||||
s.target = StackTarget::Effect(effect_id);
|
||||
crate::layer_cmds::insert_selected(session, layer)?;
|
||||
session.target = StackTarget::Effect(effect_id);
|
||||
return Ok((id, Some(effect_id)));
|
||||
};
|
||||
|
||||
let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() };
|
||||
let mut fill = Fill { projection: Projection::decal(decal), ..Fill::default() };
|
||||
fill.sources.insert(channel, Source::image(image.clone()));
|
||||
crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?;
|
||||
crate::layer_cmds::insert_selected(session, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?;
|
||||
Ok((id, None))
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0, "decal": decal, "maskEffect": mask_effect.map(|effect| effect.0) }))
|
||||
}
|
||||
|
||||
/// The decal of fill layer `id`, or of mask fill effect `effect` when given
|
||||
fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option<LayerId>) -> Result<Decal> {
|
||||
if let Some(effect) = effect {
|
||||
return match s.doc.project.effect(effect).map(|(_, effect)| &effect.kind) {
|
||||
Some(EffectKind::Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal),
|
||||
_ => Err(bad(cmd, "the effect is not a decal (layer.add.decal with channel mask)")),
|
||||
};
|
||||
/// 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>, 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"));
|
||||
}
|
||||
|
||||
match &s.doc.project.layer(id)?.kind {
|
||||
LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal),
|
||||
_ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")),
|
||||
// Keep the active projection while folding scaling would change which faces cull
|
||||
if matches!(projection, Projection::Planar { placed: None, .. }) && !culling_keeps_facing(projection) {
|
||||
return Err(bad(command, UNFOLDABLE_CULLING));
|
||||
}
|
||||
|
||||
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);
|
||||
let frame = projection
|
||||
.frame()
|
||||
.copied()
|
||||
.ok_or_else(|| bad(command, "the projection has no frame: a planar or warp projection has one (layer.add.decal places one)"))?;
|
||||
Ok((projection, 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),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
match effect {
|
||||
Some(effect) => match session.doc.project.effect(effect).map(|(_, effect)| &effect.kind) {
|
||||
Some(EffectKind::Fill { projection, .. }) => Ok(projection),
|
||||
_ => Err(bad(command, "the effect is not a mask fill effect")),
|
||||
},
|
||||
None => match &session.doc.project.layer(id)?.kind {
|
||||
LayerKind::Fill(fill) => Ok(&fill.projection),
|
||||
_ => Err(bad(command, "the layer is not a fill layer")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The sources fill layer `id`, or mask fill effect `effect` when given, reads
|
||||
fn stored_sources(session: &Session, id: LayerId, effect: Option<LayerId>) -> Vec<&Source> {
|
||||
match effect {
|
||||
Some(effect) => match session.doc.project.effect(effect).map(|(_, effect)| &effect.kind) {
|
||||
Some(EffectKind::Fill { source, .. }) => vec![source],
|
||||
_ => Vec::new(),
|
||||
},
|
||||
None => match session.doc.project.layer(id).map(|layer| &layer.kind) {
|
||||
Ok(LayerKind::Fill(fill)) => fill.sources.values().collect(),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The image a decal projects: the mask fill effect's, or the fill layer's (the channel it was placed in)
|
||||
fn placed_image(session: &Session, id: LayerId, effect: Option<LayerId>) -> Option<String> {
|
||||
let image_name = |source: &Source| match source {
|
||||
Source::Image { name, .. } => Some(name.clone()),
|
||||
_ => None,
|
||||
};
|
||||
match effect {
|
||||
Some(effect) => match session.doc.project.effect(effect).map(|(_, effect)| &effect.kind) {
|
||||
Some(EffectKind::Fill { source, .. }) => image_name(source),
|
||||
_ => None,
|
||||
},
|
||||
None => match &session.doc.project.layer(id).ok()?.kind {
|
||||
LayerKind::Fill(fill) => fill.sources.values().find_map(image_name),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `projection` with its frame where `frameOffset`, `frameRotation` and `frameScale` put it (None when none is given)
|
||||
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);
|
||||
}
|
||||
|
||||
let read = |key: &str| match params.get(key) {
|
||||
None => Ok(None),
|
||||
Some(_) => vec3(params, key).map(Some).ok_or_else(|| bad(command, format!("`{key}` must be [x, y, z]"))),
|
||||
};
|
||||
if !culling_keeps_facing(projection) {
|
||||
return Err(bad(command, UNFOLDABLE_CULLING));
|
||||
}
|
||||
|
||||
let mut shown = frame_placement(projection, bounds).ok_or_else(|| bad(command, "the frame is degenerate"))?;
|
||||
if let Some(offset) = read("frameOffset")? {
|
||||
shown.offset = offset.clamp(Vec3::splat(-MAX_FRAME_OFFSET), Vec3::splat(MAX_FRAME_OFFSET)).to_array();
|
||||
}
|
||||
if let Some(rotation) = read("frameRotation")? {
|
||||
shown.rotation = rotation.clamp(Vec3::splat(-FULL_TURN_DEGREES), Vec3::splat(FULL_TURN_DEGREES)).to_array();
|
||||
}
|
||||
if let Some(scale) = read("frameScale")? {
|
||||
shown.scale = scale.clamp(Vec3::splat(MIN_SIZE), Vec3::splat(MAX_SIZE)).to_array();
|
||||
}
|
||||
placed(projection, &shown, bounds).map(Some).ok_or_else(|| bad(command, "that frame is degenerate"))
|
||||
}
|
||||
|
||||
/// How far from the mesh's centre `frameOffset` may put a frame, in mesh radii
|
||||
const MAX_FRAME_OFFSET: f32 = 100.0;
|
||||
|
||||
/// `projection` projecting from `frame`, its other settings kept
|
||||
fn move_frame(projection: &mut Projection, frame: Decal) {
|
||||
match projection {
|
||||
Projection::Planar { placed: Some(placed), .. } => *placed = frame,
|
||||
Projection::Warp { frame: warp, .. } => *warp = frame,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,10 +381,20 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
return Err(bad(command, format!("effect {} is not in layer {layer}", effect.0)));
|
||||
}
|
||||
|
||||
let mut decal = decal_of(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);
|
||||
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"))?;
|
||||
|
||||
// A reach from frameScale keeps the Projection Depth in the range every other path keeps
|
||||
if let Projection::Warp { depth: warp_depth, .. } = &mut projection {
|
||||
*warp_depth = warp_depth.clamp(0.0, MAX_PROJECTION_DEPTH);
|
||||
}
|
||||
}
|
||||
if let Some((center, normal, hit_set)) = placement(session, command, params, texture_set, true)? {
|
||||
// Selecting another set must not let this decal leave its layer's stack
|
||||
if hit_set != texture_set {
|
||||
@@ -282,9 +412,9 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array();
|
||||
}
|
||||
let keep = boolp(params, "keepProportions") == Some(true);
|
||||
let ratio = decal.size[0] / decal.size[1].max(1e-6);
|
||||
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);
|
||||
@@ -298,18 +428,22 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
decal.flip[1] = flip;
|
||||
}
|
||||
if let Some(rotation) = f32p(params, "rotation") {
|
||||
decal.rotation = rotation.rem_euclid(360.0);
|
||||
decal.rotation = rotation.rem_euclid(FULL_TURN_DEGREES);
|
||||
}
|
||||
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));
|
||||
}
|
||||
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)];
|
||||
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
|
||||
if let Some(depth) = depth
|
||||
&& !matches!(projection, Projection::Warp { .. })
|
||||
{
|
||||
decal.depth = depth;
|
||||
}
|
||||
if let Some(depth) = f32p(params, "depth") {
|
||||
decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
|
||||
}
|
||||
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
|
||||
@@ -318,39 +452,56 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
return Err(bad(command, format!("no image resource `{name}`")));
|
||||
}
|
||||
|
||||
session.edit("Edit decal", |session| {
|
||||
if let Some(effect) = effect {
|
||||
if let Some(EffectKind::Fill { source, projection }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) {
|
||||
*projection = Projection::Decal(decal);
|
||||
if let Some(image) = image {
|
||||
*source = Source::image(image);
|
||||
}
|
||||
}
|
||||
} else if let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind {
|
||||
fill.projection = Projection::Decal(decal);
|
||||
move_frame(&mut projection, decal);
|
||||
|
||||
// The new image goes where the decal's image is (the channel it was placed in)
|
||||
let placed = fill.sources.values().find_map(|source| match source {
|
||||
Source::Image { name, .. } => Some(name.clone()),
|
||||
_ => None,
|
||||
});
|
||||
match (image, placed) {
|
||||
(Some(image), Some(placed)) => {
|
||||
for source in fill.sources.values_mut() {
|
||||
if let Source::Image { name, .. } = source
|
||||
&& *name == placed
|
||||
{
|
||||
name.clone_from(&image);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(image), None) => {
|
||||
fill.sources.insert(Channel::BaseColor, Source::image(image));
|
||||
}
|
||||
(None, _) => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
// A warp reaches by its own Projection Depth, in lengths of the frame's longer side
|
||||
if let (Some(depth), Projection::Warp { depth: warp_depth, .. }) = (depth, &mut projection) {
|
||||
*warp_depth = (depth / longer_side(decal.size)).clamp(0.0, MAX_PROJECTION_DEPTH);
|
||||
}
|
||||
|
||||
// Nothing moved and the image is the one it shows: no undo step
|
||||
let unchanged = *stored_projection(session, command, layer_id, effect)? == projection
|
||||
&& image.as_ref().is_none_or(|image| placed_image(session, layer_id, effect).as_ref() == Some(image));
|
||||
if !unchanged {
|
||||
session.edit("Edit decal", |session| store_decal(session, layer_id, effect, projection, image))?;
|
||||
}
|
||||
Ok(json!({ "layer": layer_id.0, "decal": decal }))
|
||||
}
|
||||
|
||||
/// Store `projection` (and `image`, in the channel or mask it was placed in) on fill layer `layer_id`, or on mask fill effect `effect` when given
|
||||
fn store_decal(session: &mut Session, layer_id: LayerId, effect: Option<LayerId>, projection: Projection, image: Option<String>) -> Result<()> {
|
||||
if let Some(effect) = effect {
|
||||
if let Some(EffectKind::Fill { source, projection: stored, .. }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) {
|
||||
*stored = projection;
|
||||
if let Some(image) = image {
|
||||
*source = Source::image(image);
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
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 placed = fill.sources.values().find_map(|source| match source {
|
||||
Source::Image { name, .. } => Some(name.clone()),
|
||||
_ => None,
|
||||
});
|
||||
match (image, placed) {
|
||||
(Some(image), Some(placed)) => {
|
||||
for source in fill.sources.values_mut() {
|
||||
if let Source::Image { name, .. } = source
|
||||
&& *name == placed
|
||||
{
|
||||
name.clone_from(&image);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(image), None) => {
|
||||
fill.sources.insert(Channel::BaseColor, Source::image(image));
|
||||
}
|
||||
(None, _) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Reset of a fill's Fill section: its projection's settings and its sampling back to a new fill's, its projection kind, symmetry and material kept
|
||||
|
||||
use serde_json::Value;
|
||||
use texturecraft_core::{Projection, Sampling};
|
||||
|
||||
use crate::commands::{CommandSpec, has_layer};
|
||||
use crate::layer_cmds::{UNFRAMED_PROJECTION_IDS, fill_target, new_unframed_projection, placement_mut};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"layer.fill.resetProjection",
|
||||
"Reset fill settings",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: content fill effect id} — the Fill section back to a new fill's in one undo step: the same projection kind with its defaults (tiling 1, no offset or rotation, a planar or warp frame stays where it is placed, a warp's corners unpulled), the default filtering, wrap and scale mode (symmetry, sources and material stay)",
|
||||
has_layer,
|
||||
reset_projection
|
||||
)]
|
||||
}
|
||||
|
||||
/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section)
|
||||
pub fn reset_sampling(current: Sampling) -> Sampling {
|
||||
Sampling { symmetry: current.symmetry, ..Sampling::default() }
|
||||
}
|
||||
|
||||
/// The defaults of `current`'s projection kind: a new fill's projection of that kind, with the frame a placed planar or a warp projects from kept
|
||||
pub fn reset_projection_of(current: &Projection) -> Projection {
|
||||
if let Projection::Warp { frame, .. } = current {
|
||||
return Projection::warp(*frame);
|
||||
}
|
||||
|
||||
// The new projection of the same kind; one no id makes (none today) stays as it is
|
||||
let same_kind = UNFRAMED_PROJECTION_IDS
|
||||
.iter()
|
||||
.filter_map(|id| new_unframed_projection(id))
|
||||
.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, 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
|
||||
}
|
||||
|
||||
/// Whether the Fill section of a fill projected by `projection` and sampled by `sampling` is already a new fill's (of the same projection kind)
|
||||
pub fn at_defaults(projection: &Projection, sampling: Sampling) -> bool {
|
||||
*projection == reset_projection_of(projection) && sampling == reset_sampling(sampling)
|
||||
}
|
||||
|
||||
fn reset_projection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let target = fill_target(s, p, "layer.fill.resetProjection")?;
|
||||
let (projection, sampling) = placement_mut(s, target)?;
|
||||
|
||||
if at_defaults(projection, *sampling) {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
|
||||
s.edit("Reset fill settings", |s| {
|
||||
let (projection, sampling) = placement_mut(s, target)?;
|
||||
*projection = reset_projection_of(projection);
|
||||
*sampling = reset_sampling(*sampling);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_core::{Decal, Projector};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_projection_kind_resets_to_its_own_kind() {
|
||||
let frame = 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],
|
||||
depth: 0.5,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
};
|
||||
let mut kinds: Vec<Projection> = UNFRAMED_PROJECTION_IDS.iter().filter_map(|id| new_unframed_projection(id)).collect();
|
||||
|
||||
assert_eq!(kinds.len(), UNFRAMED_PROJECTION_IDS.len(), "every listed id makes a projection");
|
||||
|
||||
kinds.extend([Projection::warp(frame), Projection::decal(frame)]);
|
||||
for kind in kinds {
|
||||
let turned = match kind.clone() {
|
||||
Projection::Planar { scale, axis, offset, uv, placed, .. } => {
|
||||
Projection::Planar { scale: scale * 2.0, axis, offset, uv, placed, projector: Projector { rotation: [10.0; 3], ..Projector::default() } }
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
|
||||
let reset = reset_projection_of(&turned);
|
||||
|
||||
assert_eq!(std::mem::discriminant(&reset), std::mem::discriminant(&kind), "{kind:?}");
|
||||
assert_eq!(reset.frame(), kind.frame(), "the frame stays where it is placed");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,7 +151,7 @@ fn mat_finish(id: &str) -> Option<Fill> {
|
||||
};
|
||||
|
||||
let pattern = Procedural { scale, ..Procedural::new(kind) };
|
||||
let mut fill = Fill { projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, ..Fill::default() };
|
||||
let mut fill = Fill { projection: Projection::triplanar(), ..Fill::default() };
|
||||
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3], ramp: Vec::new() });
|
||||
fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3], ramp: Vec::new() });
|
||||
Some(fill)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! without a screenshot.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Source};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Sampling, Source};
|
||||
|
||||
use crate::Session;
|
||||
use crate::session::StackTarget;
|
||||
@@ -11,19 +11,20 @@ fn source_json(source: &Source) -> Value {
|
||||
match source {
|
||||
Source::Uniform(value) => json!({ "uniform": value }),
|
||||
Source::Procedural { pattern, low, high, ramp } => {
|
||||
let mut report = json!({
|
||||
"procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high
|
||||
let mut out = json!({
|
||||
"procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast,
|
||||
"balance": pattern.balance, "invert": pattern.invert, "low": low, "high": high
|
||||
});
|
||||
|
||||
if !pattern.resolution.is_default() {
|
||||
report["resolution"] =
|
||||
out["resolution"] =
|
||||
json!({ "mode": format!("{:?}", pattern.resolution.mode), "custom": pattern.resolution.custom, "factor": pattern.resolution.factor });
|
||||
}
|
||||
if let Some(tile) = &pattern.tile {
|
||||
report["tile"] = crate::procedural_params::tile_report(tile);
|
||||
out["tile"] = crate::procedural_params::tile_report(tile);
|
||||
}
|
||||
|
||||
with_ramp(report, ramp)
|
||||
with_ramp(out, ramp)
|
||||
}
|
||||
Source::Image { name, normal_format: NormalFormat::OpenGl } => json!({ "image": name }),
|
||||
Source::Image { name, normal_format: NormalFormat::DirectX } => json!({ "image": name, "normalFormat": "directX" }),
|
||||
@@ -31,29 +32,38 @@ fn source_json(source: &Source) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` with the gradient map stops of its source as `colors`, when it has any.
|
||||
fn with_ramp(mut v: Value, ramp: &[[f32; 3]]) -> Value {
|
||||
/// `out` with the gradient map stops of its source as `colors`, when it has any
|
||||
fn with_ramp(mut out: Value, ramp: &[[f32; 3]]) -> Value {
|
||||
if !ramp.is_empty() {
|
||||
v["colors"] = json!(ramp);
|
||||
out["colors"] = json!(ramp);
|
||||
}
|
||||
v
|
||||
out
|
||||
}
|
||||
|
||||
fn fill_json(f: &Fill) -> Value {
|
||||
let mut v = json!({
|
||||
"projection": f.projection.label(),
|
||||
"sources": f.sources.iter().map(|(c, s)| (c.id().to_string(), source_json(s))).collect::<serde_json::Map<_, _>>(),
|
||||
});
|
||||
if let Projection::Decal(d) = &f.projection {
|
||||
v["decal"] = json!(d);
|
||||
fn fill_json(fill: &Fill) -> Value {
|
||||
let sources = fill.sources.iter().map(|(channel, source)| (channel.id().to_string(), source_json(source)));
|
||||
let mut out = json!({ "sources": sources.collect::<serde_json::Map<_, _>>() });
|
||||
placement_json(&fill.projection, &fill.sampling, &mut out);
|
||||
if let Some(link) = &fill.link {
|
||||
out["link"] = json!(link);
|
||||
}
|
||||
if let Some(link) = &f.link {
|
||||
v["link"] = json!(link);
|
||||
}
|
||||
v
|
||||
out
|
||||
}
|
||||
|
||||
/// A mask or content (`content`) effect.
|
||||
/// Where a fill lands and how it reads its sources: the projection, its frame when placed on the surface, and the sampling
|
||||
fn placement_json(projection: &Projection, sampling: &Sampling, out: &mut Value) {
|
||||
out["projection"] = json!(projection.label());
|
||||
out["projectionSettings"] = json!(projection);
|
||||
out["filtering"] = json!(sampling.filtering.id());
|
||||
out["wrap"] = json!(sampling.wrap.id());
|
||||
out["scaleMode"] = json!(sampling.scale.id());
|
||||
out["symmetry"] = json!(sampling.symmetry);
|
||||
if let Some(frame) = projection.placed() {
|
||||
out["decal"] = json!(frame);
|
||||
}
|
||||
}
|
||||
|
||||
/// A mask or content (`content`) effect
|
||||
fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
|
||||
let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity });
|
||||
let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count());
|
||||
@@ -74,7 +84,10 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
|
||||
}
|
||||
EffectKind::Paint if content => out["tiles"] = json!(content_tiles()),
|
||||
EffectKind::Paint => out["tiles"] = json!(mask_tiles()),
|
||||
EffectKind::Fill { source, .. } => out["source"] = source_json(source),
|
||||
EffectKind::Fill { source, projection, sampling } => {
|
||||
out["source"] = source_json(source);
|
||||
placement_json(projection, sampling, &mut out);
|
||||
}
|
||||
EffectKind::Material(fill) => out["fill"] = fill_json(fill),
|
||||
EffectKind::Filter(filter) => {
|
||||
out["filter"] = json!(filter);
|
||||
@@ -89,7 +102,7 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
|
||||
out
|
||||
}
|
||||
|
||||
/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them.
|
||||
/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them
|
||||
fn generator_json(generator: &Generator) -> Value {
|
||||
let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert, "blur": generator.global.blur, "balance": generator.global.balance, "contrast": generator.global.contrast });
|
||||
if !generator.resolution.is_default() {
|
||||
@@ -160,7 +173,7 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value {
|
||||
v
|
||||
}
|
||||
|
||||
/// The layer stack of texture set `ts`, top → bottom (as displayed).
|
||||
/// The layer stack of texture set `ts`, top → bottom (as displayed)
|
||||
pub fn stack(s: &Session, ts: usize) -> Value {
|
||||
let Some(set) = s.doc.project.texture_sets.get(ts) else { return Value::Null };
|
||||
json!(set.stack.iter().rev().filter_map(|id| s.doc.project.layers.get(id)).map(|l| layer_json(s, l, 0)).collect::<Vec<_>>())
|
||||
@@ -201,7 +214,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// The whole session.
|
||||
/// The whole session
|
||||
pub fn session(session: &Session) -> Value {
|
||||
let texture_set = session.ts();
|
||||
json!({
|
||||
|
||||
+264
-91
@@ -3,8 +3,8 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{
|
||||
BlendMode, Channel, ChannelBlend, ChannelKind, EffectKind, Fill, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection,
|
||||
Source,
|
||||
Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat,
|
||||
Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap,
|
||||
};
|
||||
|
||||
use crate::commands::{
|
||||
@@ -13,6 +13,27 @@ use crate::commands::{
|
||||
use crate::layer_selection::{batch_param, ids_json};
|
||||
use crate::{EngineError, Result, Session, cmd, session::StackTarget};
|
||||
|
||||
mod fill_target;
|
||||
|
||||
pub(crate) use fill_target::FillTarget;
|
||||
|
||||
/// One full turn, in degrees (the brush's, so every angle wraps on the same turn)
|
||||
pub(crate) use texturecraft_paint::FULL_TURN_DEGREES;
|
||||
|
||||
/// The smallest scale or tiling a fill's placement takes
|
||||
pub const MIN_SCALE: f32 = 0.001;
|
||||
/// The largest scale, tiling or offset a fill's placement takes
|
||||
pub const MAX_PLACEMENT: f32 = 1000.0;
|
||||
|
||||
/// The command [`fill_set`] runs as
|
||||
const FILL_SET: &str = "layer.fill.set";
|
||||
|
||||
/// How far a warp's corner may be pulled from the frame's centre, in frame sizes
|
||||
const MAX_CORNER_REACH: f32 = 100.0;
|
||||
|
||||
/// The largest Projection Depth, in lengths of the frame's longer side
|
||||
pub(crate) const MAX_PROJECTION_DEPTH: f32 = 100.0;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("layer.add.paint", "Add paint layer", ["Layers"], None, "{name?}", always, add_paint),
|
||||
@@ -96,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set fill source",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?, 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?, 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, 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?, 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
|
||||
),
|
||||
@@ -105,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set fill projection",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: content fill effect id, projection?: uv|triplanar|planar|spherical|cylindrical (default: the current one), scale?: number | [u, v] (uv), rotation?: degrees (uv), offset?: [u, v] (uv) | [x, y, z] (triplanar, planar), sharpness?: 1..64 (triplanar), axis?: 0|1|2 (planar, cylindrical)} — what is not given keeps its value",
|
||||
"{layer? | effect?: content 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",
|
||||
has_layer,
|
||||
fill_projection
|
||||
),
|
||||
@@ -491,15 +512,7 @@ fn blending_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's
|
||||
/// (`effect`).
|
||||
#[derive(Clone, Copy)]
|
||||
enum FillTarget {
|
||||
Layer(LayerId),
|
||||
Effect(LayerId),
|
||||
}
|
||||
|
||||
fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result<FillTarget> {
|
||||
pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result<FillTarget> {
|
||||
match u64p(p, "effect").map(LayerId) {
|
||||
Some(e) => match s.doc.project.effect(e) {
|
||||
Some((_, x)) if matches!(x.kind, EffectKind::Material(_)) => Ok(FillTarget::Effect(e)),
|
||||
@@ -509,44 +522,50 @@ fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result<FillTarget> {
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> {
|
||||
/// The material of the fill at `target`
|
||||
pub(crate) fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> {
|
||||
match target {
|
||||
FillTarget::Layer(id) => match &mut s.doc.project.layer_mut(id)?.kind {
|
||||
LayerKind::Fill(f) => Ok(f),
|
||||
_ => Err(EngineError::Other("not a fill layer".into())),
|
||||
},
|
||||
FillTarget::Effect(e) => match s.doc.project.effect_mut(e).map(|x| &mut x.kind) {
|
||||
FillTarget::Effect(effect) => match s.doc.project.effect_mut(effect).map(|found| &mut found.kind) {
|
||||
Some(EffectKind::Material(f)) => Ok(f),
|
||||
_ => Err(EngineError::Other("not a content fill effect".into())),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// How the fill at `target` is projected and sampled: every fill has both
|
||||
pub(crate) fn placement_mut(s: &mut Session, target: FillTarget) -> Result<(&mut Projection, &mut Sampling)> {
|
||||
let fill = fill_mut(s, target)?;
|
||||
Ok((&mut fill.projection, &mut fill.sampling))
|
||||
}
|
||||
|
||||
fn fill_set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "layer.fill.set";
|
||||
let target = fill_target(session, params, CMD)?;
|
||||
let channel = channel_param(CMD, params, "channel")?.ok_or_else(|| bad(CMD, "`channel` is required"))?;
|
||||
let target = fill_target(session, params, FILL_SET)?;
|
||||
let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?;
|
||||
|
||||
// `solo`: this channel on, every other one off
|
||||
let solo = boolp(params, "solo") == Some(true);
|
||||
let enabled = if solo { Some(true) } else { boolp(params, "enabled") };
|
||||
let normal_format = normal_format_param(CMD, params)?;
|
||||
let normal_format = normal_format_param(FILL_SET, params)?;
|
||||
let colors = ramp_param(params, channel)?;
|
||||
let init_ramp = boolp(params, "gradientMap") == Some(true);
|
||||
if init_ramp && colors.is_some() {
|
||||
return Err(bad(CMD, "give `gradientMap` or `colors`, not both"));
|
||||
return Err(bad(FILL_SET, "give `gradientMap` or `colors`, not both"));
|
||||
}
|
||||
|
||||
let source = fill_source_from(session, params, (target, channel), normal_format)?;
|
||||
if source.is_none() && enabled.is_none() && normal_format.is_none() && colors.is_none() && !init_ramp {
|
||||
return Err(bad(
|
||||
CMD,
|
||||
FILL_SET,
|
||||
"give `color`, `value`, `procedural`, `image`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `normalFormat`, `enabled` or `solo`",
|
||||
));
|
||||
}
|
||||
|
||||
if normal_format.is_some() && source.as_ref().is_some_and(|source| !matches!(source, Source::Image { .. })) {
|
||||
return Err(bad(CMD, "`normalFormat` goes with `image` or alone"));
|
||||
return Err(bad(FILL_SET, "`normalFormat` goes with `image` or alone"));
|
||||
}
|
||||
|
||||
// Changing only the normal format or gradient stops leaves the layer channel on or off
|
||||
@@ -558,7 +577,7 @@ fn fill_set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if let (None, Some(format)) = (&source, normal_format) {
|
||||
match fill.sources.get_mut(&channel) {
|
||||
Some(Source::Image { normal_format, .. }) => *normal_format = format,
|
||||
_ => return Err(bad(CMD, "`normalFormat` needs an image on the channel")),
|
||||
_ => return Err(bad(FILL_SET, "`normalFormat` needs an image on the channel")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -601,6 +620,18 @@ fn fill_set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
Some(Source::Procedural { pattern, low, high, .. }) if pattern.kind == kind => (pattern.clone(), *low, *high),
|
||||
_ => (Procedural::new(kind), [0.0; 3], [1.0; 3]),
|
||||
};
|
||||
|
||||
crate::procedural_params::pattern_basics_from(params, &mut pattern);
|
||||
crate::procedural_params::pattern_settings_from(FILL_SET, params, &mut pattern)?;
|
||||
Ok(Source::Procedural { pattern, low: low.unwrap_or(current_low), high: high.unwrap_or(current_high), ramp: Vec::new() })
|
||||
}
|
||||
|
||||
/// The source `params` give fill channel `channel` of `target`, or None when they only switch it or set its image's normal format
|
||||
fn fill_source_from(
|
||||
session: &mut Session,
|
||||
@@ -608,27 +639,16 @@ fn fill_source_from(
|
||||
(target, channel): (FillTarget, Channel),
|
||||
normal_format: Option<NormalFormat>,
|
||||
) -> Result<Option<Source>> {
|
||||
const CMD: &str = "layer.fill.set";
|
||||
let low = color_param(CMD, params, "low")?.unwrap_or([0.0; 3]);
|
||||
let high = color_param(CMD, params, "high")?.unwrap_or([1.0; 3]);
|
||||
let uniform = color_param(CMD, params, "color")?.or(color_param(CMD, params, "value")?);
|
||||
let low = color_param(FILL_SET, params, "low")?;
|
||||
let high = color_param(FILL_SET, params, "high")?;
|
||||
let uniform = color_param(FILL_SET, params, "color")?.or(color_param(FILL_SET, params, "value")?);
|
||||
|
||||
if let Some(name) = strp(params, "procedural") {
|
||||
let kind = ProceduralKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown procedural `{name}`")))?;
|
||||
let mut pattern = Procedural::new(kind);
|
||||
crate::procedural_params::pattern_basics_from(params, &mut pattern);
|
||||
let kind = ProceduralKind::parse(name).ok_or_else(|| bad(FILL_SET, format!("unknown procedural `{name}`")))?;
|
||||
|
||||
// A pattern of the same kind keeps its resolution and Tile Generator settings
|
||||
let current = fill_mut(session, target)?.sources.get(&channel);
|
||||
if let Some(Source::Procedural { pattern: current, .. }) = current
|
||||
&& current.kind == kind
|
||||
{
|
||||
pattern.resolution = current.resolution;
|
||||
pattern.tile = current.tile.clone();
|
||||
}
|
||||
|
||||
crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?;
|
||||
return Ok(Some(Source::Procedural { pattern, low, high, ramp: Vec::new() }));
|
||||
// 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])?));
|
||||
}
|
||||
|
||||
if let Some(color) = uniform {
|
||||
@@ -644,9 +664,9 @@ fn fill_source_from(
|
||||
FillTarget::Layer(id) => Some(id),
|
||||
FillTarget::Effect(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner),
|
||||
};
|
||||
let reader = reader.ok_or_else(|| bad(CMD, "the fill is not in a layer"))?;
|
||||
let anchor_channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(channel);
|
||||
return Ok(Some(crate::mask_cmds::anchor_source(session, CMD, reader, LayerId(anchor), anchor_channel)?));
|
||||
let reader = reader.ok_or_else(|| bad(FILL_SET, "the fill is not in a layer"))?;
|
||||
let anchor_channel = channel_param(FILL_SET, params, "anchorChannel")?.unwrap_or(channel);
|
||||
return Ok(Some(crate::mask_cmds::anchor_source(session, FILL_SET, reader, LayerId(anchor), anchor_channel)?));
|
||||
}
|
||||
|
||||
if !crate::procedural_params::has_pattern_settings(params) {
|
||||
@@ -655,12 +675,12 @@ fn fill_source_from(
|
||||
|
||||
// Pattern settings alone edit the channel's current pattern
|
||||
let Some(Source::Procedural { pattern, low, high, .. }) = fill_mut(session, target)?.sources.get(&channel) else {
|
||||
return Err(bad(CMD, "the channel has no pattern: give `procedural` with its settings"));
|
||||
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(CMD, 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() }))
|
||||
}
|
||||
@@ -731,83 +751,236 @@ fn with_ramp(channel: Channel, current: Option<&Source>, source: Option<Source>,
|
||||
Ok(Some(source))
|
||||
}
|
||||
|
||||
/// Parse projection settings, retaining unspecified fields when the projection kind stays the same.
|
||||
pub(crate) fn projection_from(params: &Value, command: &str, current: Option<&Projection>) -> Result<Projection> {
|
||||
projection_from_fields(params, command, current, true)
|
||||
/// A new fill's projection of kind `id` (`uv`, `uvTile`, `triplanar`, `planar`, `spherical`, `cylindrical`, or a `warp` from frame `fit`)
|
||||
pub(crate) fn new_projection(id: &str, fit: impl FnOnce() -> Decal) -> Option<Projection> {
|
||||
match id {
|
||||
"warp" => Some(Projection::warp(fit())),
|
||||
_ => new_unframed_projection(id),
|
||||
}
|
||||
}
|
||||
|
||||
/// A procedural mask can assign the command's scale to its pattern instead of its projection.
|
||||
pub(crate) fn projection_from_fields(params: &Value, command: &str, current: Option<&Projection>, read_scale: bool) -> Result<Projection> {
|
||||
const MIN_SCALE: f32 = 0.001;
|
||||
const MAX_SCALE: f32 = 1000.0;
|
||||
const MAX_OFFSET: f32 = 1000.0;
|
||||
const DEFAULT_SHARPNESS: f32 = 8.0;
|
||||
const MAX_SHARPNESS: f32 = 64.0;
|
||||
/// The ids [`new_unframed_projection`] takes, one per kind
|
||||
pub(crate) const UNFRAMED_PROJECTION_IDS: [&str; 6] = ["uv", "uvTile", "triplanar", "planar", "spherical", "cylindrical"];
|
||||
|
||||
let named = match strp(params, "projection") {
|
||||
/// A new fill's projection of kind `id`, any kind but a warp (which needs a frame)
|
||||
pub(crate) fn new_unframed_projection(id: &str) -> Option<Projection> {
|
||||
let projection = match id {
|
||||
"uv" => Projection::default(),
|
||||
"uvTile" => Projection::UvTile,
|
||||
"triplanar" | "tri-planar" => Projection::triplanar(),
|
||||
"planar" => Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: Default::default(), projector: Projector::depth_culled(), placed: None },
|
||||
"spherical" => Projection::Spherical { scale: 1.0, uv: Default::default(), offset: [0.0; 3], projector: Default::default() },
|
||||
"cylindrical" => {
|
||||
Projection::Cylindrical { scale: 1.0, axis: 1, uv: Default::default(), offset: [0.0; 3], projector: Default::default(), angle: FULL_TURN_DEGREES }
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(projection)
|
||||
}
|
||||
|
||||
/// The projection `p` asks for: fields it does not give keep their values from `current` when that is of the same kind (or `p` names no kind), and the kind's defaults otherwise; a new warp starts from frame `fit`
|
||||
pub(crate) fn projection_from(p: &Value, cmd: &str, current: Option<&Projection>, fit: impl FnOnce() -> Decal) -> Result<Projection> {
|
||||
let named = match strp(p, "projection") {
|
||||
None => None,
|
||||
Some("uv") => Some(Projection::default()),
|
||||
Some("triplanar" | "tri-planar") => Some(Projection::Triplanar { scale: 1.0, sharpness: DEFAULT_SHARPNESS, offset: [0.0; 3] }),
|
||||
Some("planar") => Some(Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3] }),
|
||||
Some("spherical") => Some(Projection::Spherical { scale: 1.0 }),
|
||||
Some("cylindrical") => Some(Projection::Cylindrical { scale: 1.0, axis: 1 }),
|
||||
Some(other) => return Err(bad(command, format!("unknown projection `{other}`"))),
|
||||
Some("warp") if matches!(current, Some(Projection::Warp { .. })) => current.cloned(),
|
||||
Some(id) => Some(new_projection(id, fit).ok_or_else(|| bad(cmd, format!("unknown projection `{id}`")))?),
|
||||
};
|
||||
let mut projection = match (named, current) {
|
||||
(Some(named), Some(current)) if std::mem::discriminant(&named) == std::mem::discriminant(current) => current.clone(),
|
||||
(Some(named), _) => named,
|
||||
(None, current) => current.cloned().unwrap_or_default(),
|
||||
};
|
||||
let scale = floats::<2>(p, "scale", MIN_SCALE, MAX_PLACEMENT);
|
||||
let tiling = floats::<2>(p, "tiling", MIN_SCALE, MAX_PLACEMENT);
|
||||
let rotation = f32p(p, "rotation").map(|degrees| degrees.rem_euclid(FULL_TURN_DEGREES));
|
||||
let axis = u64p(p, "axis").map(|axis| axis.min(2) as u8);
|
||||
|
||||
let new_scale = if read_scale { floats::<2>(params, "scale", MIN_SCALE, MAX_SCALE) } else { None };
|
||||
let new_axis = u64p(params, "axis").map(|axis| axis.min(2) as u8);
|
||||
// The UV transformations of a 3D projection: tiling, rotation and an offset across the surface
|
||||
let place = |uv: &mut UvTransform| {
|
||||
uv.tiling = tiling.unwrap_or(uv.tiling);
|
||||
uv.rotation = rotation.unwrap_or(uv.rotation);
|
||||
uv.offset = floats(p, "uvOffset", -MAX_PLACEMENT, MAX_PLACEMENT).unwrap_or(uv.offset);
|
||||
};
|
||||
|
||||
// The 3D projection settings: the projector's offset, turn and per-axis scale
|
||||
let projector_offset = floats::<3>(p, "offset", -MAX_PLACEMENT, MAX_PLACEMENT);
|
||||
let crop = match strp(p, "shapeCrop") {
|
||||
None => None,
|
||||
Some(id) => Some(ShapeCrop::from_id(id).ok_or_else(|| bad(cmd, format!("unknown shapeCrop `{id}`: cropped or extendsOutside")))?),
|
||||
};
|
||||
let turn = |projector: &mut Projector| {
|
||||
projector.rotation = floats(p, "projectorRotation", -FULL_TURN_DEGREES, FULL_TURN_DEGREES).unwrap_or(projector.rotation);
|
||||
projector.scale = floats(p, "projectorScale", -MAX_PLACEMENT, MAX_PLACEMENT).map_or(projector.scale, |scale| scale.map(signed_scale));
|
||||
projector.crop = crop.unwrap_or(projector.crop);
|
||||
projector.backface.on = p.get("backfaceCulling").and_then(Value::as_bool).unwrap_or(projector.backface.on);
|
||||
projector.backface.angle = f32p(p, "backfaceAngle").map_or(projector.backface.angle, |angle| clamp_to(angle, &Backface::ANGLE_RANGE));
|
||||
projector.backface.hardness = f32p(p, "backfaceHardness").map_or(projector.backface.hardness, |hardness| hardness.clamp(0.0, 1.0));
|
||||
projector.depth.on = p.get("depthCulling").and_then(Value::as_bool).unwrap_or(projector.depth.on);
|
||||
projector.depth.hardness = f32p(p, "depthCullingHardness").map_or(projector.depth.hardness, |hardness| hardness.clamp(0.0, 1.0));
|
||||
};
|
||||
match &mut projection {
|
||||
Projection::Uv { scale, rotation, offset } => {
|
||||
*scale = new_scale.unwrap_or(*scale);
|
||||
*rotation = f32p(params, "rotation").map_or(*rotation, |degrees| degrees.rem_euclid(360.0));
|
||||
*offset = floats(params, "offset", -MAX_OFFSET, MAX_OFFSET).unwrap_or(*offset);
|
||||
Projection::Uv { scale: uv_scale, rotation: uv_rotation, offset } => {
|
||||
// A UV projection's scale is its tiling
|
||||
*uv_scale = tiling.or(scale).unwrap_or(*uv_scale);
|
||||
*uv_rotation = rotation.unwrap_or(*uv_rotation);
|
||||
*offset = floats(p, "offset", -MAX_PLACEMENT, MAX_PLACEMENT).unwrap_or(*offset);
|
||||
}
|
||||
Projection::Triplanar { scale, sharpness, offset } => {
|
||||
*scale = new_scale.map_or(*scale, |axes| axes[0]);
|
||||
*sharpness = f32p(params, "sharpness").map_or(*sharpness, |value| value.clamp(1.0, MAX_SHARPNESS));
|
||||
*offset = floats(params, "offset", -MAX_OFFSET, MAX_OFFSET).unwrap_or(*offset);
|
||||
Projection::UvTile => {}
|
||||
Projection::Triplanar { scale: projection_scale, sharpness, offset, uv, projector } => {
|
||||
*projection_scale = scale.map_or(*projection_scale, |across| across[0]);
|
||||
*sharpness = f32p(p, "sharpness").map_or(*sharpness, |given| clamp_to(given, &Projection::TRIPLANAR_SHARPNESS_RANGE));
|
||||
*offset = projector_offset.unwrap_or(*offset);
|
||||
place(uv);
|
||||
turn(projector);
|
||||
}
|
||||
Projection::Planar { scale, axis, offset } => {
|
||||
*scale = new_scale.map_or(*scale, |axes| axes[0]);
|
||||
*axis = new_axis.unwrap_or(*axis);
|
||||
*offset = floats(params, "offset", -MAX_OFFSET, MAX_OFFSET).unwrap_or(*offset);
|
||||
Projection::Planar { scale: projection_scale, axis: projection_axis, offset, uv, projector, .. } => {
|
||||
*projection_scale = scale.map_or(*projection_scale, |across| across[0]);
|
||||
*projection_axis = axis.unwrap_or(*projection_axis);
|
||||
*offset = projector_offset.unwrap_or(*offset);
|
||||
place(uv);
|
||||
turn(projector);
|
||||
}
|
||||
Projection::Spherical { scale } => *scale = new_scale.map_or(*scale, |axes| axes[0]),
|
||||
Projection::Cylindrical { scale, axis } => {
|
||||
*scale = new_scale.map_or(*scale, |axes| axes[0]);
|
||||
*axis = new_axis.unwrap_or(*axis);
|
||||
Projection::Spherical { scale: projection_scale, uv, offset, projector } => {
|
||||
*projection_scale = scale.map_or(*projection_scale, |across| across[0]);
|
||||
*offset = projector_offset.unwrap_or(*offset);
|
||||
place(uv);
|
||||
turn(projector);
|
||||
}
|
||||
Projection::Decal(_) => {}
|
||||
}
|
||||
Projection::Cylindrical { scale: projection_scale, axis: projection_axis, uv, offset, projector, angle } => {
|
||||
*projection_scale = scale.map_or(*projection_scale, |across| across[0]);
|
||||
*angle = f32p(p, "angle").map_or(*angle, |given| clamp_to(given, &Projection::CYLINDER_ANGLE_RANGE));
|
||||
*projection_axis = axis.unwrap_or(*projection_axis);
|
||||
*offset = projector_offset.unwrap_or(*offset);
|
||||
place(uv);
|
||||
turn(projector);
|
||||
}
|
||||
Projection::Warp { corners, depth, uv, projector, .. } => {
|
||||
// A warp has no scale or offset of its own: its frame places it, so they would change nothing
|
||||
if p.get("scale").is_some() || p.get("offset").is_some() {
|
||||
return Err(bad(cmd, "a warp is placed by its frame: set frameOffset or frameScale with layer.decal.set"));
|
||||
}
|
||||
|
||||
*corners = warp_corners(p, cmd)?.unwrap_or(*corners);
|
||||
*depth = f32p(p, "projectionDepth").map_or(*depth, |given| given.clamp(0.0, MAX_PROJECTION_DEPTH));
|
||||
place(uv);
|
||||
turn(projector);
|
||||
}
|
||||
}
|
||||
Ok(projection)
|
||||
}
|
||||
|
||||
/// `key` as `N` finite numbers clamped to `lo..=hi`: an array of `N`, or one number for all.
|
||||
/// `value` held within `range`
|
||||
fn clamp_to(value: f32, range: &std::ops::RangeInclusive<f32>) -> f32 {
|
||||
value.clamp(*range.start(), *range.end())
|
||||
}
|
||||
|
||||
/// The projection `params` asks for, as [`projection_from`]; without `read_scale` its `scale` is left out (a procedural mask's scale is its pattern's)
|
||||
pub(crate) fn projection_from_fields(
|
||||
params: &Value,
|
||||
command: &str,
|
||||
current: Option<&Projection>,
|
||||
read_scale: bool,
|
||||
fit: impl FnOnce() -> Decal,
|
||||
) -> Result<Projection> {
|
||||
let mut placement = params.clone();
|
||||
if !read_scale && let Some(fields) = placement.as_object_mut() {
|
||||
fields.remove("scale");
|
||||
}
|
||||
projection_from(&placement, command, current, fit)
|
||||
}
|
||||
|
||||
/// The `warpCorners` param: four [across, up] corners in frame sizes from the frame's centre, finite and within reach of the frame (None when not given)
|
||||
fn warp_corners(p: &Value, cmd: &str) -> Result<Option<[[f32; 2]; 4]>> {
|
||||
let Some(given) = p.get("warpCorners") else { return Ok(None) };
|
||||
|
||||
let malformed = || bad(cmd, "warpCorners is four [across, up] pairs of finite numbers");
|
||||
let list = given.as_array().filter(|list| list.len() == 4).ok_or_else(malformed)?;
|
||||
let mut corners = Projection::FRAME_CORNERS;
|
||||
for (corner, value) in corners.iter_mut().zip(list) {
|
||||
let pair = value.as_array().filter(|pair| pair.len() == 2).ok_or_else(malformed)?;
|
||||
for (axis, number) in corner.iter_mut().zip(pair) {
|
||||
let reach = number.as_f64().map(|number| number as f32).filter(|number| number.is_finite()).ok_or_else(malformed)?;
|
||||
*axis = reach.clamp(-MAX_CORNER_REACH, MAX_CORNER_REACH);
|
||||
}
|
||||
}
|
||||
Ok(Some(corners))
|
||||
}
|
||||
|
||||
/// `current` with the `filtering`, `wrap`, `scaleMode` and symmetry params applied
|
||||
pub(crate) fn sampling_from(p: &Value, cmd: &str, current: Sampling) -> Result<Sampling> {
|
||||
let mut sampling = current;
|
||||
if let Some(id) = strp(p, "filtering") {
|
||||
sampling.filtering = Filtering::from_id(id).ok_or_else(|| bad(cmd, format!("unknown filtering `{id}`: bilinearHq, bilinearSharp or nearest")))?;
|
||||
}
|
||||
if let Some(id) = strp(p, "wrap") {
|
||||
sampling.wrap = UvWrap::from_id(id).ok_or_else(|| bad(cmd, format!("unknown wrap `{id}`: repeat, repeatHorizontally, repeatVertically or none")))?;
|
||||
}
|
||||
if let Some(id) = strp(p, "scaleMode") {
|
||||
sampling.scale = ScaleMode::from_id(id).ok_or_else(|| bad(cmd, format!("unknown scaleMode `{id}`: tiling or physicalSize")))?;
|
||||
}
|
||||
sampling.symmetry = symmetry_from(p, cmd, sampling.symmetry)?;
|
||||
Ok(sampling)
|
||||
}
|
||||
|
||||
/// `current` with the `symmetry`, `symmetryType`, `symmetryAxis`, `flipCopy`, `axisPosition`, `symmetryCount` and `angleSpan` params applied
|
||||
fn symmetry_from(p: &Value, cmd: &str, current: FillSymmetry) -> Result<FillSymmetry> {
|
||||
let mut symmetry = current;
|
||||
symmetry.on = boolp(p, "symmetry").unwrap_or(symmetry.on);
|
||||
if let Some(id) = strp(p, "symmetryType") {
|
||||
symmetry.kind = SymmetryKind::from_id(id).ok_or_else(|| bad(cmd, format!("unknown symmetryType `{id}`: mirror or radial")))?;
|
||||
}
|
||||
if let Some(given) = p.get("symmetryAxis").filter(|given| !given.is_null()) {
|
||||
// An index or the letter tool.brush takes for its own symmetry axis
|
||||
let axis = match given {
|
||||
Value::String(letter) => ["x", "y", "z"].iter().position(|name| letter.eq_ignore_ascii_case(name)).and_then(|index| u8::try_from(index).ok()),
|
||||
index => index.as_u64().and_then(|index| u8::try_from(index).ok()).filter(|index| *index <= FillSymmetry::LAST_AXIS),
|
||||
};
|
||||
symmetry.axis = axis.ok_or_else(|| bad(cmd, "symmetryAxis is 0 (X), 1 (Y) or 2 (Z), or \"x\", \"y\" or \"z\""))?;
|
||||
}
|
||||
if let Some(flips) = p.get("flipCopy") {
|
||||
let [Some(across), Some(down)] = flips.as_array().map(Vec::as_slice).unwrap_or_default().iter().map(Value::as_bool).collect::<Vec<_>>()[..] else {
|
||||
return Err(bad(cmd, "flipCopy is [u, v], two booleans"));
|
||||
};
|
||||
|
||||
symmetry.flip = [across, down];
|
||||
}
|
||||
let reach = FillSymmetry::REACH;
|
||||
symmetry.position = floats(p, "axisPosition", -reach, reach).unwrap_or(symmetry.position);
|
||||
if let Some(count) = u64p(p, "symmetryCount") {
|
||||
let (fewest, most) = (u64::from(*FillSymmetry::COUNTS.start()), u64::from(*FillSymmetry::COUNTS.end()));
|
||||
symmetry.count = u32::try_from(count.clamp(fewest, most)).unwrap_or(*FillSymmetry::COUNTS.start());
|
||||
}
|
||||
symmetry.span = f32p(p, "angleSpan").map_or(symmetry.span, |span| clamp_to(span, &FillSymmetry::SPANS));
|
||||
Ok(symmetry)
|
||||
}
|
||||
|
||||
/// `value` as one axis of a projector's scale: its size kept within [`MIN_SCALE`]..[`MAX_PLACEMENT`] on its own side, so a mirrored axis stays mirrored
|
||||
pub fn signed_scale(value: f32) -> f32 {
|
||||
value.signum() * value.abs().clamp(MIN_SCALE, MAX_PLACEMENT)
|
||||
}
|
||||
|
||||
/// `key` as `N` finite numbers clamped to `lo..=hi`: an array of `N`, or one number for all
|
||||
fn floats<const N: usize>(p: &Value, key: &str, lo: f32, hi: f32) -> Option<[f32; N]> {
|
||||
let one = |x: &Value| x.as_f64().map(|f| f as f32).filter(|f| f.is_finite()).map(|f| f.clamp(lo, hi));
|
||||
let number = |value: &Value| value.as_f64().map(|given| given as f32).filter(|given| given.is_finite()).map(|given| given.clamp(lo, hi));
|
||||
match p.get(key)? {
|
||||
Value::Array(a) if a.len() == N => {
|
||||
Value::Array(list) if list.len() == N => {
|
||||
let mut out = [0.0; N];
|
||||
for (o, x) in out.iter_mut().zip(a) {
|
||||
*o = one(x)?;
|
||||
for (slot, value) in out.iter_mut().zip(list) {
|
||||
*slot = number(value)?;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
v => one(v).map(|f| [f; N]),
|
||||
value => number(value).map(|given| [given; N]),
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_projection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let target = fill_target(s, p, "layer.fill.projection")?;
|
||||
let mesh = s.mesh.clone();
|
||||
s.edit("Fill projection", |s| {
|
||||
let fill = fill_mut(s, target)?;
|
||||
fill.projection = projection_from(p, "layer.fill.projection", Some(&fill.projection))?;
|
||||
let (projection, sampling) = placement_mut(s, target)?;
|
||||
*projection = projection_from(p, "layer.fill.projection", Some(projection), || crate::warp_cmds::fitted_frame(&mesh))?;
|
||||
*sampling = sampling_from(p, "layer.fill.projection", *sampling)?;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
use texturecraft_core::LayerId;
|
||||
|
||||
/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's (`effect`)
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum FillTarget {
|
||||
Layer(LayerId),
|
||||
Effect(LayerId),
|
||||
}
|
||||
@@ -19,6 +19,7 @@ pub mod effect_clipboard;
|
||||
pub mod file_cmds;
|
||||
pub mod fill_hit_test;
|
||||
pub mod fill_mode;
|
||||
pub mod fill_reset_cmds;
|
||||
pub mod filter_lib;
|
||||
mod frame_target;
|
||||
pub mod inspect;
|
||||
@@ -76,6 +77,7 @@ mod uv_stroke_state;
|
||||
mod uv_symmetry;
|
||||
pub mod uv_tile_cmds;
|
||||
pub mod view_cmds;
|
||||
pub mod warp_cmds;
|
||||
|
||||
pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap};
|
||||
pub use bake_preview::{BakePreview, PreviewShow};
|
||||
|
||||
@@ -422,7 +422,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.rgba.capacity() as u64 * std::mem::size_of::<[f32; 4]>() as u64);
|
||||
retained_bytes = retained_bytes.saturating_add(image.retained_texel_bytes());
|
||||
}
|
||||
|
||||
budget.set_retained(retained_bytes);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{
|
||||
BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask,
|
||||
MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Source,
|
||||
MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source,
|
||||
};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add fill",
|
||||
["Layers", "Effects"],
|
||||
None,
|
||||
"{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed?, contrast?, balance?, invert?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true | anchor?: anchor effect id, anchorChannel?: channel (height); content: color? ([r,g,b] linear or \"#rrggbb\" sRGB), roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}",
|
||||
"{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed?, contrast?, balance?, invert?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true | anchor?: anchor effect id, anchorChannel?: channel (height); content: color? ([r,g,b] linear or \"#rrggbb\" sRGB), roughness?, metallic?, height?, opacity? (default: every layer channel); projection?; filtering?: bilinearHq|bilinearSharp|nearest; wrap?: repeat|repeatHorizontally|repeatVertically|none}",
|
||||
has_layer,
|
||||
add_fill
|
||||
),
|
||||
@@ -295,16 +295,18 @@ fn image_source(session: &Session, command: &str, name: &str) -> Result<Source>
|
||||
|
||||
fn add_fill(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.add.fill";
|
||||
let sampling = crate::layer_cmds::sampling_from(params, CMD, Sampling::default())?;
|
||||
let blend = blend_param(CMD, params, "blend")?.unwrap_or(BlendMode::Normal);
|
||||
let layer = layer_param(session, CMD, params)?;
|
||||
|
||||
if content_target(params, CMD)? {
|
||||
let mut fill = crate::layer_cmds::fill_from(CMD, params)?;
|
||||
fill.sampling = sampling;
|
||||
if fill.sources.is_empty() {
|
||||
fill.sources = session.doc.project.layer(layer)?.channels.keys().map(|channel| (*channel, Source::uniform_of(*channel))).collect();
|
||||
}
|
||||
|
||||
fill.projection = projection_from(params, CMD, None)?;
|
||||
fill.projection = projection_from(params, CMD, None, || crate::warp_cmds::fitted_frame(&session.mesh))?;
|
||||
return push_effect(session, params, EffectKind::Material(fill), blend);
|
||||
}
|
||||
|
||||
@@ -327,9 +329,9 @@ fn add_fill(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
|
||||
// A scalar controls pattern frequency, while a two-axis scale places the new mask
|
||||
let pattern_scale = matches!(source, Source::Procedural { .. }) && params.get("scale").is_some_and(Value::is_number);
|
||||
let projection = projection_from_fields(params, CMD, None, !pattern_scale)?;
|
||||
let projection = projection_from_fields(params, CMD, None, !pattern_scale, || crate::warp_cmds::fitted_frame(&session.mesh))?;
|
||||
|
||||
push_effect(session, params, EffectKind::Fill { source, projection }, blend)
|
||||
push_effect(session, params, EffectKind::Fill { source, projection, sampling }, blend)
|
||||
}
|
||||
|
||||
/// Apply `params` to `generator`, using `command` in errors
|
||||
@@ -593,7 +595,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,
|
||||
@@ -613,6 +615,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
};
|
||||
let swaps_filter = swapped.is_some();
|
||||
|
||||
let mesh = session.mesh.clone();
|
||||
session.edit("Edit effect", |session| {
|
||||
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
|
||||
if let Some((kind, label)) = swapped {
|
||||
@@ -667,7 +670,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
// The swapped filter was built with the parameters already
|
||||
EffectKind::Filter(_) if swaps_filter => {}
|
||||
EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?,
|
||||
EffectKind::Fill { source, projection } => {
|
||||
EffectKind::Fill { source, projection, .. } => {
|
||||
// `uniform` picks the source, so it outranks settings that would edit the current pattern
|
||||
let uniform = f32p(params, "uniform").filter(|_| strp(params, "procedural").is_none());
|
||||
if let Some(anchor) = anchor {
|
||||
@@ -684,9 +687,9 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
*source = Source::Uniform([value.clamp(0.0, 1.0); 3]);
|
||||
}
|
||||
|
||||
// Pattern edits keep the mask's existing projection scale
|
||||
let read_scale = !matches!(source, Source::Procedural { .. });
|
||||
*projection = projection_from_fields(params, CMD, Some(projection), read_scale)?;
|
||||
// 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 { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?,
|
||||
EffectKind::Compare { tolerance, .. } => {
|
||||
@@ -716,7 +719,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 => {
|
||||
|
||||
@@ -210,8 +210,8 @@ impl Builder<'_> {
|
||||
fn fill(&mut self, name: &str, sources: Sources) -> Layer {
|
||||
let id = self.p.alloc_id();
|
||||
let enabled: Vec<Channel> = sources.iter().map(|(c, _)| *c).filter(|c| self.channels.contains(c)).collect();
|
||||
let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] };
|
||||
Layer::new(id, name, LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, link: None }), &enabled)
|
||||
let projection = Projection::triplanar();
|
||||
Layer::new(id, name, LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, ..Fill::default() }), &enabled)
|
||||
}
|
||||
|
||||
/// A fill masked by smart mask preset `mask` (inverted: present where the preset is not).
|
||||
@@ -782,8 +782,13 @@ pub fn brush_values(id: &str) -> Option<Vec<(Channel, [f32; 3])>> {
|
||||
/// `scale` (the same fill evaluation a layer with that material uses).
|
||||
pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f32) -> Layer {
|
||||
let channels: Vec<Channel> = sources.iter().map(|(channel, _)| *channel).collect();
|
||||
let projection = Projection::Triplanar { scale, sharpness: 8.0, offset: [0.0; 3] };
|
||||
Layer::new(id, "Brush material", LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, link: None }), &channels)
|
||||
let projection = Projection::Triplanar { scale, sharpness: 8.0, offset: [0.0; 3], uv: Default::default(), projector: Default::default() };
|
||||
Layer::new(
|
||||
id,
|
||||
"Brush material",
|
||||
LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, sampling: Default::default(), link: None }),
|
||||
&channels,
|
||||
)
|
||||
}
|
||||
|
||||
/// Where [`apply_at`] puts a material.
|
||||
|
||||
@@ -358,7 +358,8 @@ pub fn common_name(files: &[String]) -> Option<String> {
|
||||
|
||||
// Parameters and sources (native)
|
||||
|
||||
fn options(cmd: &str, p: &Value) -> Result<PbrOptions> {
|
||||
/// The import options in `p`; a warp projection is fitted to `mesh`
|
||||
fn options(cmd: &str, p: &Value, mesh: &texturecraft_geom::Mesh) -> Result<PbrOptions> {
|
||||
let normal_format = match strp(p, "normalFormat") {
|
||||
None | Some("auto") => None,
|
||||
Some("openGl" | "opengl") => Some(NormalFormat::OpenGl),
|
||||
@@ -377,7 +378,7 @@ fn options(cmd: &str, p: &Value) -> Result<PbrOptions> {
|
||||
Ok(PbrOptions {
|
||||
name: strp(p, "name").filter(|name| !name.trim().is_empty()).map(str::to_string),
|
||||
normal_format,
|
||||
projection: crate::layer_cmds::projection_from(p, cmd, None)?,
|
||||
projection: crate::layer_cmds::projection_from(p, cmd, None, || crate::warp_cmds::fitted_frame(mesh))?,
|
||||
choose,
|
||||
})
|
||||
}
|
||||
@@ -414,7 +415,7 @@ mod native;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.importPbrFolder";
|
||||
let mut options = options(cmd, p)?;
|
||||
let mut options = options(cmd, p, &s.mesh)?;
|
||||
let found = native::find(cmd, p)?;
|
||||
if options.name.is_none() {
|
||||
options.name = found.name.clone();
|
||||
@@ -425,7 +426,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn scan(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.scanPbrFolder";
|
||||
let options = options(cmd, p)?;
|
||||
let options = options(cmd, p, &s.mesh)?;
|
||||
let found = native::find(cmd, p)?;
|
||||
let set = detect_with(&found.files, &options.choose)?;
|
||||
let mut reply = report(&set, options.normal_format);
|
||||
@@ -440,8 +441,8 @@ fn scan(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn import(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let _ = options("file.importPbrFolder", p)?;
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let _ = options("file.importPbrFolder", p, &s.mesh)?;
|
||||
Err(EngineError::Other("file paths are not available in the browser".into()))
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ pub(crate) const MAX_BYTES: usize = 512 << 20;
|
||||
pub(crate) const EXR_SIGNATURE: &[u8] = &[0x76, 0x2f, 0x31, 0x01];
|
||||
|
||||
pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
Arc::new(ImageRes { width: d.width, height: d.height, rgba: d.rgba, srgb: d.srgb })
|
||||
Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -247,6 +247,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !s.doc.resources.contains_key(&name) {
|
||||
return Err(bad("resource.remove", format!("no resource `{name}`")));
|
||||
}
|
||||
|
||||
s.edit("Remove resource", |s| {
|
||||
s.doc.resources.remove(&name);
|
||||
Ok(())
|
||||
@@ -307,7 +308,7 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let raw_name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?;
|
||||
let name = resolve_resource_name(s, raw_name)?;
|
||||
let ch = channel_param("layer.add.image", p, "channel")?.unwrap_or(Channel::BaseColor);
|
||||
let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None)?;
|
||||
let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None, || crate::warp_cmds::fitted_frame(&s.mesh))?;
|
||||
let ts = s.ts();
|
||||
let label = std::path::Path::new(&name).file_stem().and_then(|n| n.to_str()).unwrap_or("Image").to_string();
|
||||
let layer_name = s.doc.project.next_layer_name(ts, &label);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The editing session: document, mesh, per-texture-set caches, history, tool state.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -60,7 +60,8 @@ 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.
|
||||
|
||||
// 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);
|
||||
let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect();
|
||||
@@ -328,7 +329,7 @@ impl Default for ToolState {
|
||||
}
|
||||
|
||||
/// What is selected in the layer stack.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
pub enum StackTarget {
|
||||
#[default]
|
||||
Content,
|
||||
@@ -476,6 +477,8 @@ pub struct Session {
|
||||
/// The last stroke's camera visibility buffer: reused while the camera, view size and mesh
|
||||
/// are unchanged, so back-to-back dabs start instantly.
|
||||
pub(crate) depth_cache: Option<DepthCache>,
|
||||
/// Projection fill depth maps shared by this session's tile batches.
|
||||
projector_depth_cache: texturecraft_compose::ProjectorDepthCache,
|
||||
/// The polygon fill box being dragged
|
||||
pub(crate) polygon_fill_drag: Option<crate::polygon_fill_drag::PolygonFillDrag>,
|
||||
/// The user's export presets (kept when another project opens).
|
||||
@@ -496,6 +499,7 @@ impl Session {
|
||||
|
||||
let source = Arc::new(mesh);
|
||||
let mesh = tiled_mesh(&source, &doc.project);
|
||||
|
||||
let bvh = Bvh::new(&mesh);
|
||||
let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() };
|
||||
let (bounds_min, bounds_max) = mesh.bounds();
|
||||
@@ -543,6 +547,7 @@ impl Session {
|
||||
log: crate::log::SessionLog::new(),
|
||||
log_id: next_mesh_id(),
|
||||
depth_cache: None,
|
||||
projector_depth_cache: Default::default(),
|
||||
polygon_fill_drag: None,
|
||||
export_presets: Default::default(),
|
||||
brush_presets: Default::default(),
|
||||
@@ -823,9 +828,11 @@ impl Session {
|
||||
if changed.is_empty() && before.texture_sets.len() == self.doc.project.texture_sets.len() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.mesh = tiled_mesh(&self.source, &self.doc.project);
|
||||
self.mesh_id = next_mesh_id();
|
||||
self.depth_cache = None;
|
||||
self.projector_depth_cache = Default::default();
|
||||
for ts in changed {
|
||||
if let (Some(c), Some(set)) = (self.caches.get_mut(ts), self.doc.project.texture_sets.get(ts)) {
|
||||
*c = SetCache::new(&self.mesh, set);
|
||||
@@ -1017,6 +1024,7 @@ impl Session {
|
||||
let solo_view = if self.pending_tiles() > 0 { self.solo_view() } else { None };
|
||||
let active = self.ts();
|
||||
let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active));
|
||||
let mut mesh_bounds = None;
|
||||
let mut changed = false;
|
||||
for ts in order {
|
||||
let Some(cache) = self.caches.get_mut(ts) else { continue };
|
||||
@@ -1054,12 +1062,19 @@ impl Session {
|
||||
block_scales: cache.composite.block_scales.clone(),
|
||||
preview,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
bounds: *mesh_bounds.get_or_insert_with(|| self.mesh.bounds()),
|
||||
};
|
||||
|
||||
// Look ahead so sliced updates filter a run of tiles once
|
||||
cache.below.ahead = if budget_ms.is_finite() { tiles_ahead(&cache.dirty, &tiles) } else { Vec::new() };
|
||||
texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below));
|
||||
texturecraft_compose::composite_tiles_with_projectors(
|
||||
&inputs,
|
||||
&self.mesh,
|
||||
&mut self.projector_depth_cache,
|
||||
&mut cache.composite,
|
||||
&tiles,
|
||||
Some(&mut cache.below),
|
||||
);
|
||||
|
||||
// The composited tiles and the neighbours their padding reached change
|
||||
let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles);
|
||||
@@ -1243,7 +1258,7 @@ const CHUNK: usize = 256;
|
||||
/// The most a budgeted update spends on settling tiles (what they show is already right).
|
||||
pub const SETTLE_BUDGET_MS: f64 = 6.0;
|
||||
|
||||
/// Take up to `n` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters
|
||||
/// Take up to `max_tiles` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters
|
||||
/// evaluate compact regions.
|
||||
fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u32)> {
|
||||
// A zero-sized request cannot select a pivot
|
||||
@@ -1255,17 +1270,26 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u
|
||||
return std::mem::take(dirty).into_iter().collect();
|
||||
}
|
||||
|
||||
let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect();
|
||||
|
||||
// Partition by block order so only the requested chunk needs sorting
|
||||
tiles.select_nth_unstable_by_key(max_tiles - 1, |&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x));
|
||||
tiles.truncate(max_tiles);
|
||||
tiles.sort_by_key(|&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x));
|
||||
for tile in &tiles {
|
||||
dirty.remove(tile);
|
||||
// Keep only the earliest block-ordered tiles in this chunk
|
||||
let block_order = |(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x);
|
||||
let mut keys = dirty.iter().copied().map(block_order);
|
||||
let mut selected: BinaryHeap<_> = keys.by_ref().take(max_tiles).collect();
|
||||
for key in keys {
|
||||
if let Some(mut latest) = selected.peek_mut()
|
||||
&& key < *latest
|
||||
{
|
||||
*latest = key;
|
||||
}
|
||||
}
|
||||
|
||||
tiles
|
||||
selected
|
||||
.into_sorted_vec()
|
||||
.into_iter()
|
||||
.map(|(_, _, y, x)| {
|
||||
dirty.remove(&(x, y));
|
||||
(x, y)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Dirty tiles a neighbourhood filter runs over ahead of the chunk being composited.
|
||||
|
||||
@@ -93,7 +93,8 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32,
|
||||
pub(crate) fn pattern(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32) -> EffectKind {
|
||||
EffectKind::Fill {
|
||||
source: Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() },
|
||||
projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] },
|
||||
projection: Projection::triplanar(),
|
||||
sampling: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -203,6 +203,10 @@ pub struct ThumbService {
|
||||
queue: VecDeque<ThumbTarget>,
|
||||
in_flight: HashSet<(u64, ThumbTarget)>,
|
||||
wanted: HashSet<ThumbTarget>,
|
||||
/// Asked for after this frame's poll (a panel drawn after the Layers panel): wanted again next frame
|
||||
late: HashSet<ThumbTarget>,
|
||||
/// Whether this frame's poll has run
|
||||
polled: bool,
|
||||
gbufs: GbufCache,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
worker: Option<Worker>,
|
||||
@@ -227,6 +231,8 @@ impl Default for ThumbService {
|
||||
queue: VecDeque::new(),
|
||||
in_flight: HashSet::new(),
|
||||
wanted: HashSet::new(),
|
||||
late: HashSet::new(),
|
||||
polled: false,
|
||||
gbufs: GbufCache::default(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
worker: None,
|
||||
@@ -243,9 +249,10 @@ impl ThumbService {
|
||||
ThumbService::default()
|
||||
}
|
||||
|
||||
/// Start of a frame: forget what the last frame asked for and notice document changes.
|
||||
/// Start of a frame: forget what the last frame asked for (but what it asked for after its poll) and notice document changes
|
||||
pub fn begin_frame(&mut self, session: &Session, now: f64) {
|
||||
self.wanted.clear();
|
||||
self.wanted = std::mem::take(&mut self.late);
|
||||
self.polled = false;
|
||||
let texture_set = session.ts();
|
||||
if self.seen == Some(session.revision)
|
||||
&& self.snapshot.as_ref().is_some_and(|snapshot| snapshot.ts == texture_set && snapshot.mesh_id == session.mesh_id)
|
||||
@@ -276,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();
|
||||
}
|
||||
@@ -290,6 +300,9 @@ impl ThumbService {
|
||||
/// picture is missing or out of date.
|
||||
pub fn get(&mut self, session: &Session, target: ThumbTarget) -> ThumbView {
|
||||
self.wanted.insert(target);
|
||||
if self.polled {
|
||||
self.late.insert(target);
|
||||
}
|
||||
self.tick = self.tick.wrapping_add(1);
|
||||
let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation);
|
||||
let checked = self.checked(session);
|
||||
@@ -316,6 +329,7 @@ impl ThumbService {
|
||||
/// End of a frame: collect results, discard unrequested rows, and dispatch new work.
|
||||
/// Returns whether another frame is needed, including to display newly collected pictures.
|
||||
pub fn poll(&mut self, session: &Session) -> bool {
|
||||
self.polled = true;
|
||||
let changed = self.collect();
|
||||
self.queue.retain(|target| self.wanted.contains(target));
|
||||
self.dispatch();
|
||||
@@ -502,21 +516,62 @@ mod tests {
|
||||
let (mut service, jobs, results) = held_worker();
|
||||
service.begin_frame(&session, 0.0);
|
||||
service.get(&session, target);
|
||||
|
||||
assert!(service.poll(&session));
|
||||
|
||||
let job = jobs.try_recv().unwrap();
|
||||
results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap();
|
||||
|
||||
service.begin_frame(&session, 0.1);
|
||||
|
||||
assert!(service.get(&session, target).image.is_none());
|
||||
|
||||
let repaint = service.poll(&session);
|
||||
|
||||
assert!(service.is_fresh(target));
|
||||
assert!(repaint, "the frame drew before collecting the final thumbnail");
|
||||
|
||||
service.begin_frame(&session, 0.2);
|
||||
|
||||
assert!(service.get(&session, target).image.is_some());
|
||||
assert!(!service.poll(&session), "an idle cache must stop repainting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picture_asked_for_after_the_poll_renders_at_the_next_one() {
|
||||
let session = test_session().unwrap();
|
||||
let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor };
|
||||
let (mut service, jobs, _results) = held_worker();
|
||||
service.begin_frame(&session, 0.0);
|
||||
service.poll(&session);
|
||||
service.get(&session, target);
|
||||
|
||||
service.begin_frame(&session, 0.1);
|
||||
service.poll(&session);
|
||||
|
||||
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();
|
||||
|
||||
@@ -432,12 +432,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> {
|
||||
|
||||
@@ -10,6 +10,9 @@ use crate::frame_target::FrameTarget;
|
||||
use crate::session::ViewMode;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// The farthest depth-of-field focus distance, in world units
|
||||
const MAX_FOCUS_DISTANCE: f32 = 1e6;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -68,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Display settings",
|
||||
[],
|
||||
None,
|
||||
"{environment?: <built-in>|resource:<image resource>, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3), iorSpecular? (use IOR for dielectric reflectance at normal incidence in Metallic Roughness), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}",
|
||||
"{environment?: <built-in>|resource:<image resource>, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), iorSpecular? (use IOR for dielectric reflectance at normal incidence in Metallic Roughness), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}, projectionGizmos? (the selected fill's projection gizmos show in the 3D view)}",
|
||||
always,
|
||||
display
|
||||
),
|
||||
@@ -270,10 +273,10 @@ fn orbit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tm = match strp(p, "toneMapping") {
|
||||
let tone_mapping = match strp(p, "toneMapping") {
|
||||
Some("linear") => Some(ToneMapping::Linear),
|
||||
Some("aces") | Some("acesFilmic") => Some(ToneMapping::AcesFilmic),
|
||||
Some(o) => return Err(bad("display.set", format!("unknown tone mapping `{o}`"))),
|
||||
Some(other) => return Err(bad("display.set", format!("unknown tone mapping `{other}`"))),
|
||||
None => None,
|
||||
};
|
||||
let shadow_mode = match strp(p, "shadowMode") {
|
||||
@@ -284,83 +287,87 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(id) => Some(EnvAlignment::parse(id).ok_or_else(|| bad("display.set", format!("unknown environment alignment `{id}` (world or camera)")))?),
|
||||
None => None,
|
||||
};
|
||||
let env = strp(p, "environment").map(str::to_string);
|
||||
if let Some(name) = env.as_deref().and_then(|e| e.strip_prefix(texturecraft_core::project::ENV_RESOURCE_PREFIX))
|
||||
let environment = strp(p, "environment").map(str::to_string);
|
||||
if let Some(name) = environment.as_deref().and_then(|picked| picked.strip_prefix(texturecraft_core::project::ENV_RESOURCE_PREFIX))
|
||||
&& !s.images.contains_key(name)
|
||||
{
|
||||
return Err(bad("display.set", format!("no image resource `{name}` (import it with resource.import)")));
|
||||
}
|
||||
|
||||
if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) {
|
||||
return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:<image>", ENVIRONMENTS.join(", "))));
|
||||
if let Some(unknown) =
|
||||
environment.as_deref().filter(|picked| !picked.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(picked))
|
||||
{
|
||||
return Err(bad("display.set", format!("unknown environment `{unknown}`: one of {}, or resource:<image>", ENVIRONMENTS.join(", "))));
|
||||
}
|
||||
|
||||
let scatter_color = color_param("display.set", p, "scatterColor")?;
|
||||
let d = &mut s.doc.project.display;
|
||||
let (old_ior, old_ior_specular, old_spec_gloss) = (d.ior, d.ior_specular, d.spec_gloss);
|
||||
if let Some(e) = env {
|
||||
d.environment = e;
|
||||
let settings = &mut s.doc.project.display;
|
||||
let (old_ior, old_ior_specular, old_spec_gloss) = (settings.ior, settings.ior_specular, settings.spec_gloss);
|
||||
if let Some(picked) = environment {
|
||||
settings.environment = picked;
|
||||
}
|
||||
for (k, slot, lo, hi) in [
|
||||
("exposure", &mut d.env_exposure, -10.0, 10.0),
|
||||
("blur", &mut d.env_blur, 0.0, 1.0),
|
||||
("rotation", &mut d.env_rotation, -360.0, 360.0),
|
||||
("opacity", &mut d.env_opacity, 0.0, 1.0),
|
||||
("fov", &mut d.fov, 5.0, 150.0),
|
||||
("aoIntensity", &mut d.ao_intensity, 0.0, 1.0),
|
||||
("bloom", &mut d.bloom, 0.0, 1.0),
|
||||
("vignette", &mut d.vignette, 0.0, 1.0),
|
||||
("sharpen", &mut d.sharpen, 0.0, 1.0),
|
||||
("grain", &mut d.grain, 0.0, 1.0),
|
||||
("scatterRadius", &mut d.scatter_radius, 0.0, 1.0),
|
||||
("ior", &mut d.ior, 1.0, 3.0),
|
||||
("shadowOpacity", &mut d.shadow_opacity, 0.0, 1.0),
|
||||
for (key, slot, lowest, highest) in [
|
||||
("exposure", &mut settings.env_exposure, -10.0, 10.0),
|
||||
("blur", &mut settings.env_blur, 0.0, 1.0),
|
||||
("rotation", &mut settings.env_rotation, -360.0, 360.0),
|
||||
("opacity", &mut settings.env_opacity, 0.0, 1.0),
|
||||
("fov", &mut settings.fov, 5.0, 150.0),
|
||||
("aoIntensity", &mut settings.ao_intensity, 0.0, 1.0),
|
||||
("bloom", &mut settings.bloom, 0.0, 1.0),
|
||||
("vignette", &mut settings.vignette, 0.0, 1.0),
|
||||
("sharpen", &mut settings.sharpen, 0.0, 1.0),
|
||||
("grain", &mut settings.grain, 0.0, 1.0),
|
||||
("scatterRadius", &mut settings.scatter_radius, 0.0, 1.0),
|
||||
("ior", &mut settings.ior, 1.0, 3.0),
|
||||
("shadowOpacity", &mut settings.shadow_opacity, 0.0, 1.0),
|
||||
] {
|
||||
if let Some(v) = f32p(p, k) {
|
||||
*slot = v.clamp(lo, hi);
|
||||
if let Some(value) = f32p(p, key) {
|
||||
*slot = value.clamp(lowest, highest);
|
||||
}
|
||||
}
|
||||
if let Some(t) = tm {
|
||||
d.tone_mapping = t;
|
||||
if let Some(picked) = tone_mapping {
|
||||
settings.tone_mapping = picked;
|
||||
}
|
||||
if let Some(c) = scatter_color {
|
||||
d.scatter_color = c.map(|v| v.clamp(0.0, 1.0));
|
||||
if let Some(color) = scatter_color {
|
||||
settings.scatter_color = color.map(|component| component.clamp(0.0, 1.0));
|
||||
}
|
||||
if let Some(b) = boolp(p, "shadows") {
|
||||
d.shadows = b;
|
||||
if let Some(on) = boolp(p, "shadows") {
|
||||
settings.shadows = on;
|
||||
}
|
||||
if let Some(mode) = shadow_mode {
|
||||
d.shadow_mode = mode;
|
||||
settings.shadow_mode = mode;
|
||||
}
|
||||
if let Some(alignment) = alignment {
|
||||
d.env_alignment = alignment;
|
||||
settings.env_alignment = alignment;
|
||||
}
|
||||
if let Some(dof) = p.get("dof") {
|
||||
if let Some(b) = boolp(dof, "enabled") {
|
||||
d.dof.enabled = b;
|
||||
if let Some(on) = boolp(dof, "enabled") {
|
||||
settings.dof.enabled = on;
|
||||
}
|
||||
if let Some(v) = f32p(dof, "focusDistance") {
|
||||
d.dof.focus_distance = v.clamp(0.0, 1e6);
|
||||
if let Some(distance) = f32p(dof, "focusDistance") {
|
||||
settings.dof.focus_distance = distance.clamp(0.0, MAX_FOCUS_DISTANCE);
|
||||
}
|
||||
if let Some(v) = f32p(dof, "aperture") {
|
||||
d.dof.aperture = v.clamp(0.0, 1.0);
|
||||
if let Some(aperture) = f32p(dof, "aperture") {
|
||||
settings.dof.aperture = aperture.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
for (k, slot) in [
|
||||
("postEffects", &mut d.post_effects),
|
||||
("taa", &mut d.taa),
|
||||
("specGloss", &mut d.spec_gloss),
|
||||
("iorSpecular", &mut d.ior_specular),
|
||||
("parallax", &mut d.parallax),
|
||||
("displacement", &mut d.displacement),
|
||||
("soloUnlit", &mut d.solo_unlit),
|
||||
for (key, slot) in [
|
||||
("postEffects", &mut settings.post_effects),
|
||||
("taa", &mut settings.taa),
|
||||
("specGloss", &mut settings.spec_gloss),
|
||||
("iorSpecular", &mut settings.ior_specular),
|
||||
("parallax", &mut settings.parallax),
|
||||
("displacement", &mut settings.displacement),
|
||||
("soloUnlit", &mut settings.solo_unlit),
|
||||
("projectionGizmos", &mut settings.projection_gizmos),
|
||||
] {
|
||||
if let Some(b) = boolp(p, k) {
|
||||
*slot = b;
|
||||
if let Some(on) = boolp(p, key) {
|
||||
*slot = on;
|
||||
}
|
||||
}
|
||||
|
||||
s.modified |= d.ior_specular != old_ior_specular || (d.ior_specular && (d.ior != old_ior || d.spec_gloss != old_spec_gloss));
|
||||
let settings = &s.doc.project.display;
|
||||
s.modified |= settings.ior_specular != old_ior_specular || (settings.ior_specular && (settings.ior != old_ior || settings.spec_gloss != old_spec_gloss));
|
||||
// The field of view applies to the view only when set (a saved camera keeps its own)
|
||||
if f32p(p, "fov").is_some() {
|
||||
s.camera.fov = s.doc.project.display.fov;
|
||||
@@ -496,10 +503,14 @@ mod tests {
|
||||
#[test]
|
||||
fn hdr_resources_become_the_environment() {
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
|
||||
|
||||
assert!(execute(&mut s, "display.set", &json!({"environment": "resource:sky.hdr"})).is_err(), "unknown resources are rejected");
|
||||
|
||||
let e = execute(&mut s, "display.set", &json!({"environment": "nonexistent"})).unwrap_err().to_string();
|
||||
|
||||
assert!(e.contains("Studio Soft"), "unknown environments are rejected with the valid names: {e}");
|
||||
assert_eq!(s.doc.project.display.environment, "Studio Soft");
|
||||
|
||||
execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap();
|
||||
let img = image::Rgb32FImage::from_fn(64, 32, |_, y| image::Rgb([if y < 8 { 40.0 } else { 0.5 }; 3]));
|
||||
let mut hdr = Vec::new();
|
||||
@@ -507,6 +518,7 @@ mod tests {
|
||||
let name = s.import_resource_bytes("sky.hdr", hdr).unwrap();
|
||||
let res = &s.images[&name];
|
||||
assert!(!res.srgb && res.rgba[0][0] > 30.0, "HDR keeps values above 1");
|
||||
|
||||
let env = format!("resource:{name}");
|
||||
let r = execute(
|
||||
&mut s,
|
||||
@@ -514,12 +526,38 @@ mod tests {
|
||||
&json!({"environment": env, "specGloss": true, "parallax": true, "displacement": true, "taa": false, "scatterColor": [2.0, 0.5, 0.25], "scatterRadius": 0.3}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(r["environment"], json!(env));
|
||||
|
||||
let d = &s.doc.project.display;
|
||||
assert!(d.spec_gloss && d.parallax && d.displacement && !d.taa);
|
||||
assert_eq!((d.scatter_color, d.scatter_radius), ([1.0, 0.5, 0.25], 0.3), "scatter settings (clamped)");
|
||||
assert_eq!(d.environment_resource(), Some(name.as_str()));
|
||||
|
||||
execute(&mut s, "file.removeUnused", &Value::Null).unwrap();
|
||||
|
||||
assert!(s.doc.resources.contains_key(&name), "the environment's image counts as used");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_projection_gizmos_hide_per_project_and_old_projects_show_them() {
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
|
||||
let shown = serde_json::to_value(&s.doc.project.display).unwrap();
|
||||
|
||||
assert!(s.doc.project.display.projection_gizmos && shown.get("projection_gizmos").is_none(), "shown by default and saved as before: {shown}");
|
||||
|
||||
let hidden = execute(&mut s, "display.set", &json!({"projectionGizmos": false})).unwrap();
|
||||
|
||||
assert!(!s.doc.project.display.projection_gizmos);
|
||||
assert_eq!(hidden["projection_gizmos"], json!(false), "hidden is saved with the project");
|
||||
assert!(s.history_labels().is_empty(), "a view flag is no undo step");
|
||||
|
||||
let reopened: texturecraft_core::project::DisplaySettings = serde_json::from_value(hidden).unwrap();
|
||||
|
||||
assert!(!reopened.projection_gizmos, "a saved project opens with its gizmos hidden");
|
||||
|
||||
let old: texturecraft_core::project::DisplaySettings = serde_json::from_value(shown).unwrap();
|
||||
|
||||
assert!(old.projection_gizmos, "a project saved before the flag shows them");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Warp projections: the frame a new warp starts from, and Reset frame, which puts a warp's frame and corners back there
|
||||
|
||||
use serde_json::Value;
|
||||
use texturecraft_core::{Decal, Projection};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::commands::{CommandSpec, bad, has_layer};
|
||||
use crate::layer_cmds::{fill_target, placement_mut};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// Reset frame's command id, the prefix of its errors
|
||||
const RESET_FRAME: &str = "layer.fill.resetFrame";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"layer.fill.resetFrame",
|
||||
"Reset frame",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: content fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)",
|
||||
has_layer,
|
||||
reset_frame
|
||||
)]
|
||||
}
|
||||
|
||||
/// The frame a new warp projection starts from: around the whole mesh, seen from the front (+Z), up along +Y
|
||||
pub(crate) fn fitted_frame(mesh: &Mesh) -> Decal {
|
||||
let (lo, hi) = mesh.bounds();
|
||||
let smallest = ((hi - lo).length() * SMALLEST_SIDE).max(f32::MIN_POSITIVE);
|
||||
let size = [(hi.x - lo.x).max(smallest), (hi.y - lo.y).max(smallest)];
|
||||
Decal {
|
||||
center: ((lo + hi) * 0.5).to_array(),
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
size,
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: 0.0,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
}
|
||||
}
|
||||
|
||||
/// A fitted frame's smallest side, relative to the mesh diagonal (a flat mesh still gets a frame)
|
||||
const SMALLEST_SIDE: f32 = 1e-3;
|
||||
|
||||
fn reset_frame(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let target = fill_target(s, p, RESET_FRAME)?;
|
||||
let fitted = fitted_frame(&s.mesh);
|
||||
let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else {
|
||||
return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection"));
|
||||
};
|
||||
|
||||
// A frame already fitted with unpulled corners adds no undo step
|
||||
if *frame == fitted && *corners == Projection::FRAME_CORNERS {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
|
||||
s.edit("Reset frame", |s| {
|
||||
let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else {
|
||||
return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection"));
|
||||
};
|
||||
|
||||
*frame = fitted;
|
||||
*corners = Projection::FRAME_CORNERS;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! A fill's procedural pattern through `layer.fill.set`: a parameter given alone changes only itself
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, LayerId, LayerKind, Procedural, ProceduralKind, Source};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
/// A fill layer whose roughness is a Clouds pattern with every parameter away from its default
|
||||
fn clouds_fill() -> (Session, LayerId) {
|
||||
let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
|
||||
let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap());
|
||||
let pattern = json!({
|
||||
"layer": layer.0, "channel": "roughness", "procedural": "Clouds", "scale": 9.0, "contrast": 1.5, "seed": 7,
|
||||
"balance": 0.25, "invert": true, "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8],
|
||||
});
|
||||
execute(&mut session, "layer.fill.set", &pattern).unwrap();
|
||||
(session, layer)
|
||||
}
|
||||
|
||||
/// The roughness pattern and its Low and High colours
|
||||
type Roughness = (Procedural, [f32; 3], [f32; 3]);
|
||||
|
||||
fn roughness(session: &Session, layer: LayerId) -> Roughness {
|
||||
match &session.doc.project.layer(layer).unwrap().kind {
|
||||
LayerKind::Fill(fill) => match fill.source(Channel::Roughness) {
|
||||
Source::Procedural { pattern, low, high, .. } => (pattern, low, high),
|
||||
other => panic!("not a procedural: {other:?}"),
|
||||
},
|
||||
other => panic!("not a fill: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// One parameter sent alone, its value, and what it changes in the stored pattern
|
||||
type PatternEdit = (&'static str, Value, fn(&mut Roughness));
|
||||
|
||||
/// What the Scale, Contrast, Seed, Balance and Invert controls and the Low/High swatches send: one parameter each
|
||||
#[test]
|
||||
fn a_pattern_parameter_given_alone_keeps_every_other_one() {
|
||||
let (mut session, layer) = clouds_fill();
|
||||
let edits: [PatternEdit; 7] = [
|
||||
("scale", json!(3.0), |(pattern, ..)| pattern.scale = 3.0),
|
||||
("contrast", json!(0.5), |(pattern, ..)| pattern.contrast = 0.5),
|
||||
("seed", json!(42), |(pattern, ..)| pattern.seed = 42),
|
||||
("balance", json!(-0.5), |(pattern, ..)| pattern.balance = -0.5),
|
||||
("invert", json!(false), |(pattern, ..)| pattern.invert = false),
|
||||
("low", json!([0.1, 0.1, 0.1]), |(_, low, _)| *low = [0.1; 3]),
|
||||
("high", json!([0.9, 0.9, 0.9]), |(.., high)| *high = [0.9; 3]),
|
||||
];
|
||||
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"});
|
||||
edit[key] = value;
|
||||
execute(&mut session, "layer.fill.set", &edit).unwrap();
|
||||
|
||||
assert_eq!(roughness(&session, layer), expected, "`{key}` alone changes only itself");
|
||||
}
|
||||
|
||||
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
|
||||
assert!(inspected.contains("\"balance\":-0.5") && inspected.contains("\"invert\":false"), "inspect shows the balance and invert");
|
||||
}
|
||||
|
||||
/// Another kind is a new pattern: its defaults between black and white, as before
|
||||
#[test]
|
||||
fn another_pattern_kind_starts_from_its_defaults() {
|
||||
let (mut session, layer) = clouds_fill();
|
||||
execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "procedural": "Cells"})).unwrap();
|
||||
|
||||
assert_eq!(roughness(&session, layer), (Procedural::new(ProceduralKind::Cells), [0.0; 3], [1.0; 3]));
|
||||
}
|
||||
@@ -0,0 +1,933 @@
|
||||
//! The 3D projection settings and the projection kinds of a fill, through engine commands
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, DepthCulling, FillSymmetry, LayerId, LayerKind, Projection, Projector, Sampling, UvTransform};
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
|
||||
s.update();
|
||||
s
|
||||
}
|
||||
|
||||
/// A fill layer with a checker procedural in base color
|
||||
fn checker_fill(s: &mut Session) -> LayerId {
|
||||
let layer = LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap());
|
||||
execute(s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0, 0, 0], "high": [1, 1, 1]}))
|
||||
.unwrap();
|
||||
layer
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, layer: LayerId, mut p: Value) {
|
||||
p["layer"] = json!(layer.0);
|
||||
execute(s, "layer.fill.projection", &p).unwrap();
|
||||
}
|
||||
|
||||
fn projection(s: &Session, layer: LayerId) -> Projection {
|
||||
match &s.doc.project.layer(layer).unwrap().kind {
|
||||
LayerKind::Fill(f) => f.projection.clone(),
|
||||
_ => panic!("a fill layer"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Base color red of every texel
|
||||
fn snapshot(s: &mut Session) -> Vec<f32> {
|
||||
s.update();
|
||||
let cache = &s.caches[0];
|
||||
let (w, h) = cache.size;
|
||||
(0..w * h).map(|i| cache.composite.value(Channel::BaseColor, i % w, i / w)[0]).collect()
|
||||
}
|
||||
|
||||
/// Rotation, per-axis scale and offset move every 3D projection; the defaults and older saves change nothing
|
||||
#[test]
|
||||
fn three_d_projection_settings_turn_stretch_and_move_every_3d_projection() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
for kind in ["triplanar", "planar", "spherical", "cylindrical"] {
|
||||
set(&mut s, layer, json!({"projection": kind}));
|
||||
let plain = snapshot(&mut s);
|
||||
|
||||
set(&mut s, layer, json!({"projectorRotation": [30, 45, 60]}));
|
||||
|
||||
assert_ne!(snapshot(&mut s), plain, "{kind}: rotation turns the pattern");
|
||||
|
||||
set(&mut s, layer, json!({"projectorRotation": [0, 0, 0], "projectorScale": [2, 0.5, 1]}));
|
||||
|
||||
assert_ne!(snapshot(&mut s), plain, "{kind}: per-axis scale stretches the pattern");
|
||||
|
||||
set(&mut s, layer, json!({"projectorScale": 1, "offset": [0.3, 0.2, 0.1]}));
|
||||
|
||||
assert_ne!(snapshot(&mut s), plain, "{kind}: offset moves the pattern");
|
||||
|
||||
set(&mut s, layer, json!({"offset": 0}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "{kind}: the defaults change nothing");
|
||||
|
||||
set(&mut s, layer, json!({"projectorRotation": [10, 20, 30], "projectorScale": [1, 2, 3]}));
|
||||
let mut saved = serde_json::to_value(projection(&s, layer)).unwrap();
|
||||
let fields = saved.as_object_mut().unwrap().values_mut().next().unwrap().as_object_mut().unwrap();
|
||||
fields.remove("projector");
|
||||
let loaded: Projection = serde_json::from_value(saved).unwrap();
|
||||
let settings = match loaded {
|
||||
Projection::Triplanar { projector, .. }
|
||||
| Projection::Planar { projector, .. }
|
||||
| Projection::Spherical { projector, .. }
|
||||
| Projection::Cylindrical { projector, .. } => projector,
|
||||
other => panic!("{kind}: loaded as {other:?}"),
|
||||
};
|
||||
assert_eq!(settings, Projector::default(), "{kind}: an older save has no turn or stretch");
|
||||
|
||||
set(&mut s, layer, json!({"projectorRotation": 0, "projectorScale": 1}));
|
||||
}
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
let cylindrical = &row["fill"]["projectionSettings"]["Cylindrical"];
|
||||
assert!(
|
||||
cylindrical.is_object() && cylindrical.get("projector").is_none(),
|
||||
"a reset projector is the default, left out as older projects saved it: {cylindrical}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A negative projector scale mirrors that axis, as a project file's does: the command keeps its sign and limits only its size
|
||||
#[test]
|
||||
fn a_negative_projector_scale_keeps_its_mirror() {
|
||||
let mut s = session();
|
||||
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}));
|
||||
let Projection::Spherical { projector, .. } = projection(&s, layer) else { panic!("a spherical projection") };
|
||||
assert_eq!(projector.scale, [-0.001; 3], "a tiny mirrored scale keeps the smallest size, still mirrored");
|
||||
}
|
||||
|
||||
/// Fill (Match per UV Tile) shows the same pattern on both UDIM tiles, where UV runs on across them
|
||||
#[test]
|
||||
fn match_per_uv_tile_repeats_the_source_once_per_tile() {
|
||||
let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
let layer = LayerId(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap());
|
||||
execute(
|
||||
&mut s,
|
||||
"layer.fill.set",
|
||||
&json!({"layer": layer.0, "channel": "baseColor", "procedural": "Clouds", "scale": 3, "low": [0, 0, 0], "high": [1, 1, 1]}),
|
||||
)
|
||||
.unwrap();
|
||||
let tiles = |s: &mut Session| {
|
||||
s.update();
|
||||
let composite = &s.caches[0].composite;
|
||||
let tile = |block: u32| (0..128 * 128).map(|i| composite.value(Channel::BaseColor, block * 128 + i % 128, i / 128)[0]).collect::<Vec<f32>>();
|
||||
(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"}));
|
||||
|
||||
assert_eq!(projection(&s, layer), Projection::UvTile);
|
||||
|
||||
let (left, right) = tiles(&mut s);
|
||||
let worst = left.iter().zip(&right).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max);
|
||||
|
||||
assert!(worst < 1e-4, "every tile shows the same pattern (worst difference {worst})");
|
||||
}
|
||||
|
||||
/// Cylindrical Angle is the arc one repeat spans; older saves go the whole way round
|
||||
#[test]
|
||||
fn cylindrical_angle_is_the_arc_one_repeat_spans() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
set(&mut s, layer, json!({"projection": "cylindrical"}));
|
||||
let plain = snapshot(&mut s);
|
||||
set(&mut s, layer, json!({"angle": 120}));
|
||||
|
||||
assert!(matches!(projection(&s, layer), Projection::Cylindrical { angle: 120.0, .. }));
|
||||
assert_ne!(snapshot(&mut s), plain, "a third of the way round repeats three times");
|
||||
|
||||
set(&mut s, layer, json!({"angle": 360}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "360 degrees is the whole way round");
|
||||
|
||||
let mut saved = serde_json::to_value(projection(&s, layer)).unwrap();
|
||||
saved["Cylindrical"].as_object_mut().unwrap().remove("angle");
|
||||
|
||||
assert!(matches!(serde_json::from_value(saved).unwrap(), Projection::Cylindrical { angle: 360.0, .. }));
|
||||
}
|
||||
|
||||
/// Texel indices whose surface normal has a Z above `above` (and below `below`)
|
||||
fn facing_z(s: &Session, above: f32, below: f32) -> Vec<usize> {
|
||||
let cache = &s.caches[0];
|
||||
let (w, h) = cache.size;
|
||||
(0..(w * h) as usize).filter(|&i| cache.gbuf.surface(&s.mesh, i).is_some_and(|surface| surface.nrm.z > above && surface.nrm.z < below)).collect()
|
||||
}
|
||||
|
||||
/// Cropped to Shape stops a shrunk tri-planar box short of the mesh; the default box holds it all
|
||||
#[test]
|
||||
fn shape_crop_stops_a_projection_at_its_shape() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
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();
|
||||
set(&mut s, layer, json!({"projection": "triplanar"}));
|
||||
let plain = snapshot(&mut s);
|
||||
set(&mut s, layer, json!({"shapeCrop": "cropped"}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "the default box holds the whole mesh");
|
||||
|
||||
set(&mut s, layer, json!({"projectorScale": 0.5}));
|
||||
let cropped = snapshot(&mut s);
|
||||
let gone = cropped.iter().zip(&empty).filter(|(a, b)| a == b).count();
|
||||
set(&mut s, layer, json!({"shapeCrop": "extendsOutside"}));
|
||||
let extends = snapshot(&mut s);
|
||||
let gone_extending = extends.iter().zip(&empty).filter(|(a, b)| a == b).count();
|
||||
assert!(gone > gone_extending + 1000, "the half-size box leaves the rest of the mesh bare ({gone} vs {gone_extending} bare texels)");
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "shapeCrop": "clipped"})).is_err());
|
||||
}
|
||||
|
||||
/// Backface culling leaves the far side of the sphere bare and the near side unchanged
|
||||
#[test]
|
||||
fn backface_culling_keeps_a_planar_projection_off_faces_turned_away() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
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");
|
||||
|
||||
set(&mut s, layer, json!({"backfaceCulling": true, "backfaceAngle": 90, "backfaceHardness": 1}));
|
||||
let culled = snapshot(&mut s);
|
||||
assert!(far.iter().all(|&i| culled[i] == empty[i]), "faces turned away get none of the projection");
|
||||
assert!(near.iter().all(|&i| culled[i] == plain[i]), "faces turned towards it keep all of it");
|
||||
|
||||
set(&mut s, layer, json!({"backfaceAngle": 45}));
|
||||
let narrow = snapshot(&mut s);
|
||||
let sideways = facing_z(&s, 0.1, 0.6);
|
||||
assert!(sideways.iter().all(|&i| narrow[i] == empty[i]), "past 45 degrees nothing is left");
|
||||
}
|
||||
|
||||
/// A decal saved before decals were planar projections loads as a planar projection placed on its frame, cropped to it and off faces turned away
|
||||
#[test]
|
||||
fn saved_decals_load_as_planar_projections_placed_on_the_surface() {
|
||||
use texturecraft_engine::core::{Backface, Decal, DecalFlip, DecalSymmetry, Fill, ShapeCrop};
|
||||
|
||||
// A decal saved with a mirrored copy and a flipped image keeps both
|
||||
let frame = Decal {
|
||||
center: [0.0, 0.0, 1.0],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
size: [0.5, 0.4],
|
||||
rotation: 10.0,
|
||||
offset: [0.1, 0.0],
|
||||
depth: 0.3,
|
||||
symmetry: Some(DecalSymmetry { axis: 0, flip: DecalFlip::U, offset: 0.25 }),
|
||||
flip: [true, false],
|
||||
};
|
||||
let mut saved = serde_json::to_value(Fill::default()).unwrap();
|
||||
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 });
|
||||
}
|
||||
|
||||
/// A planar projection with a decal's look saves as a decal, so versions from before planar decals still read a decal; changed in any way it saves as a planar projection
|
||||
#[test]
|
||||
fn placed_planars_with_a_decals_look_save_as_decals() {
|
||||
use texturecraft_engine::core::{Decal, Fill};
|
||||
let frame = Decal {
|
||||
center: [0.0, 0.0, 1.0],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
size: [0.5, 0.4],
|
||||
rotation: 10.0,
|
||||
offset: [0.1, 0.0],
|
||||
depth: 0.3,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
};
|
||||
let fill = Fill { projection: Projection::decal(frame), ..Fill::default() };
|
||||
|
||||
let saved = serde_json::to_value(&fill).unwrap();
|
||||
|
||||
assert_eq!(saved["projection"], json!({ "Decal": frame }));
|
||||
assert_eq!(serde_json::from_value::<Fill>(saved).unwrap(), fill, "and reads back the same");
|
||||
|
||||
let mut turned = fill;
|
||||
let Projection::Planar { uv, .. } = &mut turned.projection else { panic!("{:?}", turned.projection) };
|
||||
uv.rotation = 30.0;
|
||||
let saved = serde_json::to_value(&turned).unwrap();
|
||||
|
||||
assert_eq!(saved["projection"]["Planar"]["placed"], json!(frame));
|
||||
assert_eq!(serde_json::from_value::<Fill>(saved).unwrap(), turned);
|
||||
}
|
||||
|
||||
/// A warp projects from a frame around the mesh: pulling a corner bends the image, Projection Depth bounds it when cropped, and Reset frame unpulls the corners
|
||||
#[test]
|
||||
fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
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();
|
||||
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:?}");
|
||||
|
||||
let unpulled = snapshot(&mut s);
|
||||
assert_ne!(unpulled, empty);
|
||||
|
||||
let pulled = json!([[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]);
|
||||
set(&mut s, layer, json!({"warpCorners": pulled}));
|
||||
let bent = snapshot(&mut s);
|
||||
assert_ne!(bent, unpulled, "a pulled corner bends the image");
|
||||
|
||||
set(&mut s, layer, json!({"projection": "warp", "rotation": 0}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), bent, "picking warp again keeps the corners");
|
||||
|
||||
set(&mut s, layer, json!({"shapeCrop": "cropped", "warpCorners": Projection::FRAME_CORNERS}));
|
||||
let cropped = snapshot(&mut s);
|
||||
|
||||
// Depth 0.1 of a frame 2 wide reaches 0.2 in front of and behind the frame through the sphere's middle
|
||||
let (beyond, within) = (facing_z(&s, 0.35, 1.1), facing_z(&s, -0.05, 0.05));
|
||||
assert!(!beyond.is_empty() && !within.is_empty());
|
||||
assert!(beyond.iter().all(|&i| cropped[i] == empty[i]), "past its Projection Depth the warp does not reach");
|
||||
assert!(within.iter().all(|&i| cropped[i] == unpulled[i]), "within it the warp covers as before");
|
||||
|
||||
set(&mut s, layer, json!({"projectionDepth": 1}));
|
||||
let deep = snapshot(&mut s);
|
||||
assert!(beyond.iter().all(|&i| deep[i] == unpulled[i]), "a deeper warp reaches the whole sphere");
|
||||
|
||||
set(&mut s, layer, json!({"warpCorners": pulled}));
|
||||
execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap();
|
||||
let Projection::Warp { frame: reset, corners, depth, .. } = projection(&s, layer) else { panic!("still a warp") };
|
||||
assert_eq!((reset, corners, depth), (frame, Projection::FRAME_CORNERS, 1.0), "the frame and corners go back; the depth stays");
|
||||
|
||||
let steps = s.history_labels().len();
|
||||
execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps, "resetting a frame already reset adds no undo step");
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["projection"], "Warp projection");
|
||||
assert_eq!(row["fill"]["projectionSettings"]["Warp"]["corners"], json!(Projection::FRAME_CORNERS));
|
||||
|
||||
set(&mut s, layer, json!({"projection": "planar"}));
|
||||
|
||||
assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset");
|
||||
}
|
||||
|
||||
/// Depth culling keeps planar and warp projections off surfaces hidden behind others from the projector; new ones start with it on, older saves without it
|
||||
#[test]
|
||||
fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
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();
|
||||
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);
|
||||
set(&mut s, layer, json!({"depthCulling": false}));
|
||||
let plain = snapshot(&mut s);
|
||||
|
||||
// The sphere's far side sits behind its near side, seen from +Z
|
||||
let (far, near) = (facing_z(&s, -1.1, -0.3), facing_z(&s, 0.3, 1.1));
|
||||
assert!(!far.is_empty() && !near.is_empty());
|
||||
assert!(far.iter().any(|&i| plain[i] != empty[i]), "without depth culling the far side gets the projection");
|
||||
assert!(far.iter().all(|&i| culled[i] == empty[i]), "hidden behind the near side, the far side gets none of it");
|
||||
assert!(near.iter().all(|&i| culled[i] == plain[i]), "the near side keeps all of it");
|
||||
|
||||
set(&mut s, layer, json!({"depthCulling": true, "depthCullingHardness": 0}));
|
||||
|
||||
assert_ne!(snapshot(&mut s), culled, "a softer cull fades further behind the near side");
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["projectionSettings"]["Planar"]["projector"]["depth"], json!({"on": true, "hardness": 0.0}));
|
||||
|
||||
set(&mut s, layer, json!({"projection": "warp"}));
|
||||
let Projection::Warp { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) };
|
||||
assert_eq!(projector.depth, DepthCulling::NEW, "a new warp culls by depth");
|
||||
|
||||
let warped = snapshot(&mut s);
|
||||
assert!(far.iter().all(|&i| warped[i] == empty[i]), "a warp from the front leaves the far side bare");
|
||||
|
||||
let saved: Projector = serde_json::from_value(json!({"rotation": [0, 0, 0], "scale": [1, 1, 1]})).unwrap();
|
||||
|
||||
assert_eq!(saved.depth, DepthCulling { on: false, hardness: 0.75 }, "an older save has no depth culling");
|
||||
}
|
||||
|
||||
/// Texels of `far` that `values` gives something other than the bare `empty`
|
||||
fn filled(far: &[usize], values: &[f32], empty: &[f32]) -> usize {
|
||||
far.iter().filter(|&&i| values[i] != empty[i]).count()
|
||||
}
|
||||
|
||||
/// The symmetry axis is read from an index or from the letter tool.brush takes; any other value is refused, never ignored
|
||||
#[test]
|
||||
fn fill_symmetry_axis_reads_an_index_or_a_letter() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
let axis = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind {
|
||||
LayerKind::Fill(fill) => fill.sampling.symmetry.axis,
|
||||
_ => panic!("a fill layer"),
|
||||
};
|
||||
|
||||
set(&mut s, layer, json!({"symmetryAxis": "Y"}));
|
||||
|
||||
assert_eq!(axis(&s), 1);
|
||||
|
||||
set(&mut s, layer, json!({"symmetryAxis": 2}));
|
||||
|
||||
assert_eq!(axis(&s), 2);
|
||||
|
||||
for refused in [json!("w"), json!(true), json!(-1), json!(3)] {
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": refused})).is_err(), "{refused}");
|
||||
}
|
||||
|
||||
assert_eq!(axis(&s), 2, "a refused axis changes nothing");
|
||||
}
|
||||
|
||||
/// Mirror and radial symmetry copy a planar projection onto the sphere's far side and leave the near side as it was; Flip copy turns the copies' images over; UV projections and older saves have no copies
|
||||
#[test]
|
||||
fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
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();
|
||||
|
||||
// Depth culled from +Z, the planar projection reaches only the near side
|
||||
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}));
|
||||
let mirrored = snapshot(&mut s);
|
||||
assert!(filled(&far, &mirrored, &empty) > far.len() / 2, "the mirror copy reaches the far side");
|
||||
assert!(near.iter().all(|&i| mirrored[i] == plain[i]), "the original keeps its own half");
|
||||
|
||||
set(&mut s, layer, json!({"symmetryType": "radial", "symmetryAxis": 1, "symmetryCount": 2}));
|
||||
let turned = snapshot(&mut s);
|
||||
assert!(filled(&far, &turned, &empty) > far.len() / 2, "the copy turned half round reaches the far side");
|
||||
assert!(near.iter().all(|&i| turned[i] == plain[i]), "the original keeps its own wedge");
|
||||
assert_ne!(turned, mirrored, "a turned copy is not a mirrored one");
|
||||
|
||||
set(&mut s, layer, json!({"symmetry": false}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "switched off, the copies go");
|
||||
|
||||
// A left to right ramp shows a copy's image turned over
|
||||
let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap();
|
||||
execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap();
|
||||
set(&mut s, layer, json!({"symmetry": true}));
|
||||
let copied = snapshot(&mut s);
|
||||
set(&mut s, layer, json!({"flipCopy": [true, false]}));
|
||||
let flipped = snapshot(&mut s);
|
||||
assert!(far.iter().filter(|&&i| (flipped[i] - copied[i]).abs() > 0.1).count() > far.len() / 4, "Flip copy U turns the copy's ramp round");
|
||||
assert!(near.iter().all(|&i| flipped[i] == copied[i]), "the original is never flipped");
|
||||
|
||||
set(&mut s, layer, json!({"projection": "uv"}));
|
||||
let uv = snapshot(&mut s);
|
||||
set(&mut s, layer, json!({"symmetry": false}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), uv, "a UV projection has no copies");
|
||||
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryType": "spiral"})).is_err());
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": 3})).is_err());
|
||||
|
||||
let saved: Sampling = serde_json::from_value(json!({"filtering": "BilinearHq", "wrap": "Repeat", "scale": "Tiling"})).unwrap();
|
||||
|
||||
assert_eq!(saved.symmetry, FillSymmetry::OFF, "an older save has no symmetry");
|
||||
}
|
||||
|
||||
/// Moving an axis planar on the model first places it as the frame it projects from: nothing moves until the frame does, and undo puts the axis planar back
|
||||
#[test]
|
||||
fn moving_an_axis_planar_places_it_as_its_frame_first() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap();
|
||||
execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap();
|
||||
set(&mut s, layer, json!({"projection": "planar", "axis": 0, "scale": 1.5, "offset": [0.2, -0.1, 0.0], "projectorRotation": [0, 30, 10]}));
|
||||
let axis = projection(&s, layer);
|
||||
let before = snapshot(&mut s);
|
||||
|
||||
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);
|
||||
let moved = before.iter().zip(&after).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count();
|
||||
assert!(moved * 200 < before.len(), "the image stays where it was: {moved} of {} texels changed", before.len());
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "offset": [0.4, 0.0], "merge": true})).unwrap();
|
||||
|
||||
assert_ne!(snapshot(&mut s), after, "then the frame moves the image");
|
||||
let Projection::Planar { placed: Some(slid), .. } = projection(&s, layer) else { panic!("still placed") };
|
||||
assert_eq!((slid.offset, slid.size), ([0.4, 0.0], frame.size));
|
||||
|
||||
s.undo().unwrap();
|
||||
|
||||
assert_eq!(projection(&s, layer), axis, "placing and moving is one step");
|
||||
|
||||
set(&mut s, layer, json!({"projection": "warp", "warpCorners": [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]}));
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap();
|
||||
let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("still a warp") };
|
||||
assert_eq!((frame.rotation, corners[1]), (30.0, [0.9, 0.9]), "a warp's frame turns and keeps its corners");
|
||||
|
||||
set(&mut s, layer, json!({"projection": "spherical"}));
|
||||
|
||||
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() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
set(&mut s, layer, json!({"projection": "planar", "axis": 0, "scale": 1.5}));
|
||||
let axis = projection(&s, layer);
|
||||
let before = snapshot(&mut s);
|
||||
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).is_err(), "placing would move the pattern");
|
||||
assert_eq!(projection(&s, layer), axis, "the planar keeps its axis");
|
||||
assert_eq!(snapshot(&mut s), before, "and the pattern stays where it was");
|
||||
|
||||
let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": "planar"})).unwrap();
|
||||
let effect = added["effect"].as_u64().unwrap();
|
||||
execute(&mut s, "effect.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap();
|
||||
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "effect": effect})).is_err(), "a mask fill's pattern keeps its axis too");
|
||||
}
|
||||
|
||||
/// Backface culling under an uneven or mirrored projector scale cannot keep its facing in a frame: moving it is refused with the way out, and nothing changes
|
||||
#[test]
|
||||
fn a_frame_under_uneven_culling_is_refused_with_the_way_out_and_changes_nothing() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap();
|
||||
execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap();
|
||||
set(&mut s, layer, json!({"projection": "planar", "axis": 2, "backfaceCulling": true}));
|
||||
|
||||
// An axis planar with an uneven then a mirrored scale, then a placed frame with an uneven one
|
||||
for (scale, placed) in [(json!([2, 1, 1]), false), (json!([1.5, -1.5, 1.5]), false), (json!([2, 1, 1]), true)] {
|
||||
let edit = if placed { json!({"layer": layer.0, "frameOffset": [0.1, 0, 0]}) } else { json!({"layer": layer.0}) };
|
||||
if placed {
|
||||
set(&mut s, layer, json!({"projectorScale": 1}));
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
assert!(projection(&s, layer).placed().is_some(), "an even scale places the frame");
|
||||
}
|
||||
|
||||
set(&mut s, layer, json!({"projectorScale": scale}));
|
||||
let before = projection(&s, layer);
|
||||
let steps = s.history_labels().len();
|
||||
|
||||
let refused = execute(&mut s, "layer.decal.set", &edit).unwrap_err().to_string();
|
||||
|
||||
assert!(refused.contains("even out the projector scale or turn backface culling off"), "{scale} placed {placed}: {refused}");
|
||||
assert_eq!(projection(&s, layer), before, "{scale} placed {placed}: the projection is unchanged");
|
||||
assert_eq!(s.history_labels().len(), steps, "{scale} placed {placed}: no undo step");
|
||||
}
|
||||
|
||||
// A placed frame's edit that moves no frame still lands
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "flipU": true})).unwrap();
|
||||
|
||||
assert!(projection(&s, layer).frame().is_some_and(|frame| frame.flip[0]), "the flip lands on the placed frame");
|
||||
}
|
||||
|
||||
/// A frame's 3D projection settings (Offset, Rotation, Scale as the panel and the gizmo share them) move it in one undo step, and a turned or scaled projector folds into the frame first, landing the same
|
||||
#[test]
|
||||
fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap();
|
||||
execute(&mut s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": ramp})).unwrap();
|
||||
set(&mut s, layer, json!({"projection": "planar", "axis": 2}));
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
// 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();
|
||||
|
||||
// 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();
|
||||
assert!((Vec3::from(frame.center) - (lo + hi) * 0.5).length() < 1e-4, "offset 0 = the mesh's centre: {frame:?}");
|
||||
|
||||
let shown = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap();
|
||||
|
||||
assert!((shown.rotation[2] - 30.0).abs() < 1e-3 && shown.rotation[0].abs() < 1e-3, "the projector's turn shows as the frame's: {shown:?}");
|
||||
|
||||
let folded = snapshot(&mut s);
|
||||
let changed = turned.iter().zip(&folded).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count();
|
||||
assert!(changed * 200 < turned.len(), "the frame was already at the centre: the image stays, {changed} of {} texels changed", turned.len());
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [shown.scale[0] * 0.5, shown.scale[1], shown.scale[2]], "merge": true}))
|
||||
.unwrap();
|
||||
let Projection::Planar { placed: Some(narrow), .. } = projection(&s, layer) else { panic!("still placed") };
|
||||
assert!((narrow.size[0] - frame.size[0] * 0.5).abs() < 1e-4 && (narrow.size[1] - frame.size[1]).abs() < 1e-4, "Scale X halves the width");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameRotation": [0, 0, 90], "merge": true})).unwrap();
|
||||
let again = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap();
|
||||
|
||||
assert!((again.rotation[2] - 90.0).abs() < 1e-3 && (again.scale[0] - shown.scale[0] * 0.5).abs() < 1e-4, "{again:?}");
|
||||
assert_eq!(s.history_labels().len(), steps + 1, "a drag is one undo step");
|
||||
|
||||
s.undo().unwrap();
|
||||
|
||||
assert_eq!(snapshot(&mut s), turned, "undo puts the turned projector back");
|
||||
|
||||
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") };
|
||||
assert!(smallest.size.iter().chain([&smallest.depth]).all(|side| *side > 0.0 && side.is_finite()), "{smallest:?}");
|
||||
|
||||
// A warp's Scale Z is its reach: Projection Depth times the longer side
|
||||
set(&mut s, layer, json!({"projection": "warp"}));
|
||||
let Projection::Warp { frame, .. } = projection(&s, layer) else { panic!("a warp") };
|
||||
let diagonal = (hi - lo).length();
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameScale": [frame.size[0] / diagonal, frame.size[1] / diagonal, 0.1]})).unwrap();
|
||||
let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") };
|
||||
assert!((depth * frame.size[0].max(frame.size[1]) - 0.1 * diagonal).abs() < 1e-4, "reach {depth}");
|
||||
}
|
||||
|
||||
/// A decal edit that moves nothing and keeps its image adds no undo step and leaves the project unmodified; one that moves it adds one
|
||||
#[test]
|
||||
fn a_decal_edit_that_changes_nothing_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap();
|
||||
let added = execute(&mut s, "layer.add.decal", &json!({"image": ramp, "position": [0, 0, 1], "normal": [0, 0, 1], "rotation": 30})).unwrap();
|
||||
let layer = added["layer"].as_u64().unwrap();
|
||||
let mask = execute(&mut s, "layer.add.decal", &json!({"image": ramp, "channel": "mask", "position": [0, 0, 1], "normal": [0, 0, 1]})).unwrap();
|
||||
let mask_effect = mask["maskEffect"].as_u64().unwrap();
|
||||
let steps = s.history_labels().len();
|
||||
|
||||
for unchanged in [
|
||||
json!({"layer": layer}),
|
||||
json!({"layer": layer, "rotation": 30}),
|
||||
json!({"layer": layer, "image": ramp}),
|
||||
json!({"layer": layer, "offset": [0, 0]}),
|
||||
json!({"effect": mask_effect}),
|
||||
json!({"effect": mask_effect, "image": ramp}),
|
||||
] {
|
||||
execute(&mut s, "layer.decal.set", &unchanged).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps, "{unchanged} changes nothing");
|
||||
}
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer, "rotation": 45})).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps + 1, "a turn is an edit");
|
||||
}
|
||||
|
||||
/// Inspect shows the frame a decal was placed on, for a decal placed as a mask as for one placed as a layer
|
||||
#[test]
|
||||
fn inspect_shows_a_mask_decals_frame_as_a_layer_decals() {
|
||||
let mut s = session();
|
||||
let ramp = s.import_resource_bytes("ramp.png", ramp_png()).unwrap();
|
||||
let placement = json!({"image": ramp, "position": [0, 0, 1], "normal": [0, 0, 1], "size": 0.5});
|
||||
let layer_decal = execute(&mut s, "layer.add.decal", &placement).unwrap();
|
||||
let mut mask_placement = placement.clone();
|
||||
mask_placement["channel"] = json!("mask");
|
||||
let mask_decal = execute(&mut s, "layer.add.decal", &mask_placement).unwrap();
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let layers = inspect["layers"].as_array().unwrap();
|
||||
let row = |id: &Value| layers.iter().find(|layer| &layer["id"] == id).unwrap().clone();
|
||||
let layer_frame = row(&layer_decal["layer"])["fill"]["decal"].clone();
|
||||
let mask_effects = row(&mask_decal["layer"])["mask"]["effects"].clone();
|
||||
let mask_effect = mask_effects.as_array().unwrap().iter().find(|effect| effect["id"] == mask_decal["maskEffect"]).unwrap().clone();
|
||||
|
||||
// Each side holds a frame on the requested point and normal, so two missing frames cannot match as nulls
|
||||
let on_request = |frame: &Value| {
|
||||
let near = |key: &str, want: [f64; 3]| {
|
||||
frame[key]
|
||||
.as_array()
|
||||
.is_some_and(|got| got.len() == 3 && got.iter().zip(want).all(|(got, want)| got.as_f64().is_some_and(|got| (got - want).abs() < 1e-3)))
|
||||
};
|
||||
near("center", [0.0, 0.0, 1.0]) && near("normal", [0.0, 0.0, 1.0])
|
||||
};
|
||||
for (name, frame) in [
|
||||
("layer decal", &layer_frame),
|
||||
("layer decal reply", &layer_decal["decal"]),
|
||||
("mask decal", &mask_effect["decal"]),
|
||||
("mask decal reply", &mask_decal["decal"]),
|
||||
] {
|
||||
assert!(on_request(frame), "the {name} shows its frame on the requested placement: {frame}");
|
||||
}
|
||||
|
||||
assert_eq!(layer_frame, layer_decal["decal"], "a layer decal's frame");
|
||||
assert_eq!(mask_effect["decal"], mask_decal["decal"], "a mask decal's frame");
|
||||
}
|
||||
|
||||
/// `depth` on a warp sets how far it reaches: its Projection Depth becomes the depth over the frame's longer side
|
||||
#[test]
|
||||
fn a_warps_depth_sets_its_projection_depth() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
set(&mut s, layer, json!({"projection": "warp"}));
|
||||
|
||||
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() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
set(&mut s, layer, json!({"projection": "warp", "projectionDepth": 0.5}));
|
||||
let Projection::Warp { frame, depth, .. } = projection(&s, layer) else { panic!("a warp") };
|
||||
let steps = s.history_labels().len();
|
||||
|
||||
let reach = depth * frame.size[0].max(frame.size[1]);
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "depth": reach})).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps, "reach {reach} is the one it has");
|
||||
}
|
||||
|
||||
/// A frameScale reach on a warp keeps its Projection Depth within the range `projectionDepth` allows
|
||||
#[test]
|
||||
fn a_warps_frame_scale_keeps_its_projection_depth_in_range() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
set(&mut s, layer, json!({"projection": "warp"}));
|
||||
|
||||
let deepest = checker_fill(&mut s);
|
||||
set(&mut s, deepest, json!({"projection": "warp", "projectionDepth": 1e9}));
|
||||
let Projection::Warp { depth: max_depth, .. } = projection(&s, deepest) else { panic!("a warp") };
|
||||
|
||||
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}");
|
||||
}
|
||||
|
||||
/// A 64 × 8 PNG whose red climbs from left to right
|
||||
fn ramp_png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let ramp = image::RgbaImage::from_fn(64, 8, |x, _| image::Rgba([(x * 4) as u8, 0, 0, 255]));
|
||||
ramp.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// Reset fill settings puts the Fill section back to the defaults of the projection it uses, in one undo step, and leaves the projection kind, the symmetry and sources alone
|
||||
#[test]
|
||||
fn reset_fill_settings_keeps_the_projection_and_restores_its_defaults_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
let fresh = snapshot(&mut s);
|
||||
set(
|
||||
&mut s,
|
||||
layer,
|
||||
json!({"projection": "planar", "tiling": [3, 2], "rotation": 30, "axis": 0, "filtering": "nearest", "wrap": "none", "scaleMode": "physicalSize", "shapeCrop": "cropped", "symmetry": true, "symmetryAxis": 1}),
|
||||
);
|
||||
let fill = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind {
|
||||
LayerKind::Fill(f) => f.clone(),
|
||||
_ => 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();
|
||||
let reset = fill(&s);
|
||||
let Projection::Planar { scale, axis, offset, uv, projector, placed } = reset.projection else { panic!("still planar, got {:?}", reset.projection) };
|
||||
assert_eq!((scale, axis, offset, uv, placed), (1.0, 2, [0.0; 3], UvTransform::default(), None), "a new planar's placement");
|
||||
assert_eq!(projector, Projector::depth_culled(), "a new planar's 3D settings and culling");
|
||||
assert_eq!(reset.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the sampling is a new fill's; the symmetry stays");
|
||||
assert_eq!(reset.sources, changed.sources, "the material stays");
|
||||
assert!(texturecraft_engine::fill_reset_cmds::at_defaults(&reset.projection, reset.sampling));
|
||||
|
||||
let steps = s.history_labels().len();
|
||||
execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps, "resetting a Fill section at its defaults adds no undo step");
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(fill(&s), changed, "one undo brings every setting back");
|
||||
assert!(execute(&mut s, "layer.fill.resetProjection", &json!({"layer": 9999})).is_err(), "no such layer");
|
||||
|
||||
// A UV fill comes back to a UV projection at tiling 1 and renders like a new fill
|
||||
set(&mut s, layer, json!({"projection": "uv", "tiling": [3, 2], "rotation": 30}));
|
||||
execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
assert_eq!(fill(&s).projection, Projection::default());
|
||||
assert_eq!(snapshot(&mut s), fresh, "it renders like the new fill");
|
||||
}
|
||||
|
||||
/// A warp's reset keeps its frame where it is placed and restores its corners, Projection Depth, UV transform and projector settings
|
||||
#[test]
|
||||
fn reset_fill_settings_keeps_a_warp_frame_and_restores_its_settings() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
set(&mut s, layer, json!({"projection": "warp"}));
|
||||
let Projection::Warp { frame: fitted, .. } = projection(&s, layer) else { panic!("a warp") };
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "offset": [0.2, 0.1]})).unwrap();
|
||||
set(
|
||||
&mut s,
|
||||
layer,
|
||||
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();
|
||||
|
||||
assert_eq!(projection(&s, layer), Projection::warp(moved), "still a warp: its frame stays, every setting is a new warp's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_warp_corners_copy_flips_and_a_warps_own_placement_are_rejected_and_change_nothing() {
|
||||
let mut s = session();
|
||||
let layer = checker_fill(&mut s);
|
||||
set(&mut s, layer, json!({"projection": "warp"}));
|
||||
let before = projection(&s, layer);
|
||||
let steps = s.history_labels().len();
|
||||
|
||||
for bad in [
|
||||
json!({"warpCorners": [[1, 2]]}),
|
||||
json!({"warpCorners": [[0, 0], [0, 0], [0, 0], ["x", 0]]}),
|
||||
json!({"warpCorners": "pulled"}),
|
||||
json!({"flipCopy": [true, "x"]}),
|
||||
// A warp is placed by its frame (layer.decal.set): a scale or offset of its own would change nothing
|
||||
json!({"scale": 2}),
|
||||
json!({"offset": [1, 0, 0]}),
|
||||
json!({"projection": "warp", "scale": 2, "offset": [1, 0, 0]}),
|
||||
] {
|
||||
let mut p = bad.clone();
|
||||
p["layer"] = json!(layer.0);
|
||||
|
||||
assert!(execute(&mut s, "layer.fill.projection", &p).is_err(), "{bad}");
|
||||
}
|
||||
|
||||
assert_eq!(projection(&s, layer), before);
|
||||
assert_eq!(s.history_labels().len(), steps, "no undo step for a rejected edit");
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
//! How fills read their image sources (filtering), through engine commands
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, Fill, Filtering, LayerId, LayerKind, Projection, Sampling, ScaleMode};
|
||||
use texturecraft_engine::geom::NO_TRI;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
|
||||
s.update();
|
||||
s
|
||||
}
|
||||
|
||||
fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// A fill layer whose base color is a one-texel black and white checker, tiled `tiling` times
|
||||
fn checker_fill(s: &mut Session, tiling: f32) -> LayerId {
|
||||
let name = s.import_resource_bytes("checker.png", png(64, 64, |x, y| if (x + y) % 2 == 0 { [255; 4] } else { [0, 0, 0, 255] })).unwrap();
|
||||
let layer = LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap());
|
||||
execute(s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": name})).unwrap();
|
||||
execute(s, "layer.fill.projection", &json!({"layer": layer.0, "scale": tiling})).unwrap();
|
||||
layer
|
||||
}
|
||||
|
||||
/// Lowest and highest base color red across the covered texels of the set's middle band
|
||||
fn spread(s: &mut Session) -> (f32, f32) {
|
||||
s.update();
|
||||
let cache = &s.caches[0];
|
||||
let (w, h) = cache.size;
|
||||
let mut range = (f32::MAX, f32::MIN);
|
||||
for y in h * 3 / 8..h * 5 / 8 {
|
||||
for x in w / 4..w * 3 / 4 {
|
||||
if cache.gbuf.tri[(y * w + x) as usize] != NO_TRI {
|
||||
let red = cache.composite.value(Channel::BaseColor, x, y)[0];
|
||||
range = (range.0.min(red), range.1.max(red));
|
||||
}
|
||||
}
|
||||
}
|
||||
range
|
||||
}
|
||||
|
||||
fn filtering(s: &mut Session, layer: LayerId, id: &str) {
|
||||
execute(s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": id})).unwrap();
|
||||
}
|
||||
|
||||
/// A checker shrunk to two image texels per texel: HQ averages it, Sharp aliases it, Nearest keeps black and white
|
||||
#[test]
|
||||
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");
|
||||
let (lo, hi) = spread(&mut s);
|
||||
assert!(hi - lo > 0.5, "Bilinear | Sharp aliases a shrunk checker: {lo}..{hi}");
|
||||
|
||||
filtering(&mut s, layer, "nearest");
|
||||
s.update();
|
||||
let cache = &s.caches[0];
|
||||
let (w, h) = cache.size;
|
||||
let pure = (h * 3 / 8..h * 5 / 8)
|
||||
.flat_map(|y| (w / 4..w * 3 / 4).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| cache.gbuf.tri[(y * w + x) as usize] != NO_TRI)
|
||||
.all(|(x, y)| {
|
||||
let red = cache.composite.value(Channel::BaseColor, x, y)[0];
|
||||
!(0.01..=0.99).contains(&red)
|
||||
});
|
||||
|
||||
assert!(pure, "Nearest reads one image texel: black or white only");
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["filtering"], json!("nearest"));
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": "trilinear"})).is_err());
|
||||
}
|
||||
|
||||
/// Fills saved before Filtering existed read images as before (plain bilinear); new fills start on Bilinear | HQ
|
||||
#[test]
|
||||
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();
|
||||
saved.as_object_mut().unwrap().remove("sampling");
|
||||
let loaded: Fill = serde_json::from_value(saved).unwrap();
|
||||
|
||||
assert_eq!(loaded.sampling, Sampling::SAVED_BEFORE);
|
||||
assert_eq!(loaded.sampling.filtering, Filtering::BilinearSharp);
|
||||
}
|
||||
|
||||
/// Share of the middle band's covered texels where the white fill shows over the black layer below
|
||||
fn shown(s: &mut Session) -> f32 {
|
||||
s.update();
|
||||
let cache = &s.caches[0];
|
||||
let (w, h) = cache.size;
|
||||
let (mut on, mut all) = (0usize, 0usize);
|
||||
for y in h * 3 / 8..h * 5 / 8 {
|
||||
for x in 0..w {
|
||||
if cache.gbuf.tri[(y * w + x) as usize] != NO_TRI {
|
||||
all += 1;
|
||||
on += usize::from(cache.composite.value(Channel::BaseColor, x, y)[0] > 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
on as f32 / all.max(1) as f32
|
||||
}
|
||||
|
||||
/// UV Wrap on a white fill tiled 4 × 2: Repeat covers the band, None one tile, one-axis repeats in between
|
||||
#[test]
|
||||
fn uv_wrap_repeats_the_tile_or_stops_at_its_edge() {
|
||||
let mut s = session();
|
||||
execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 0.0]})).unwrap();
|
||||
let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap());
|
||||
let set = |s: &mut Session, p: Value| {
|
||||
let mut p = p;
|
||||
p["layer"] = json!(layer.0);
|
||||
execute(s, "layer.fill.projection", &p)
|
||||
};
|
||||
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();
|
||||
let none = shown(&mut s);
|
||||
assert!(near(none, 0.125), "None: a quarter across, half down: {none}");
|
||||
|
||||
set(&mut s, json!({"wrap": "repeatHorizontally"})).unwrap();
|
||||
let across = shown(&mut s);
|
||||
assert!(near(across, 0.5), "repeating across: the whole width, half down: {across}");
|
||||
|
||||
set(&mut s, json!({"wrap": "repeatVertically"})).unwrap();
|
||||
let down = shown(&mut s);
|
||||
assert!(near(down, 0.25), "repeating down: a quarter across, the whole height: {down}");
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["wrap"], json!("repeatVertically"));
|
||||
assert!(set(&mut s, json!({"wrap": "mirror"})).is_err());
|
||||
|
||||
// Tri-planar has no tile: it covers whatever the wrap says
|
||||
set(&mut s, json!({"projection": "triplanar", "wrap": "none"})).unwrap();
|
||||
let triplanar = shown(&mut s);
|
||||
assert!(near(triplanar, 1.0), "{triplanar}");
|
||||
}
|
||||
|
||||
/// 3D projections take UV transformations; older saves look as they did; world scale and offset stay separate
|
||||
#[test]
|
||||
fn three_d_projections_take_uv_transformations() {
|
||||
use texturecraft_engine::core::{Projection, UvTransform};
|
||||
let mut s = session();
|
||||
let layer = LayerId(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap());
|
||||
let set = |s: &mut Session, p: Value| {
|
||||
let mut p = p;
|
||||
p["layer"] = json!(layer.0);
|
||||
execute(s, "layer.fill.projection", &p)
|
||||
};
|
||||
execute(
|
||||
&mut s,
|
||||
"layer.fill.set",
|
||||
&json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0, 0, 0], "high": [1, 1, 1]}),
|
||||
)
|
||||
.unwrap();
|
||||
set(&mut s, json!({"projection": "triplanar"})).unwrap();
|
||||
let projection = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind {
|
||||
LayerKind::Fill(f) => f.projection.clone(),
|
||||
_ => panic!("a fill layer"),
|
||||
};
|
||||
let snapshot = |s: &mut Session| {
|
||||
s.update();
|
||||
let cache = &s.caches[0];
|
||||
let (w, h) = cache.size;
|
||||
(0..w * h).map(|i| cache.composite.value(Channel::BaseColor, i % w, i / w)[0]).collect::<Vec<f32>>()
|
||||
};
|
||||
let plain = snapshot(&mut s);
|
||||
|
||||
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");
|
||||
|
||||
// A fill saved before 3D projections had UV transformations loads them as nothing
|
||||
let mut saved = serde_json::to_value(projection(&s)).unwrap();
|
||||
saved["Triplanar"].as_object_mut().unwrap().remove("uv");
|
||||
let loaded: Projection = serde_json::from_value(saved).unwrap();
|
||||
|
||||
assert!(matches!(loaded, Projection::Triplanar { uv, .. } if uv == UvTransform::default()));
|
||||
|
||||
set(&mut s, json!({"tiling": 1, "rotation": 0, "uvOffset": [0, 0]})).unwrap();
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "the identity transform changes nothing");
|
||||
|
||||
// On a UV projection, tiling is its scale
|
||||
set(&mut s, json!({"projection": "uv", "tiling": [2, 4]})).unwrap();
|
||||
|
||||
assert!(matches!(projection(&s), Projection::Uv { scale, .. } if scale == [2.0, 4.0]));
|
||||
}
|
||||
|
||||
/// Physical size keeps the fill's tiling; inspect reports the mode and older fills open on Tiling
|
||||
#[test]
|
||||
fn scale_mode_is_stored_without_changing_the_tiling() {
|
||||
let mut s = session();
|
||||
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);
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["scaleMode"], json!("physicalSize"));
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "inches"})).is_err());
|
||||
|
||||
let mut saved = serde_json::to_value(&fill).unwrap();
|
||||
saved["sampling"].as_object_mut().unwrap().remove("scale");
|
||||
let loaded: Fill = serde_json::from_value(saved).unwrap();
|
||||
|
||||
assert_eq!(loaded.sampling.scale, ScaleMode::Tiling);
|
||||
}
|
||||
@@ -13,6 +13,9 @@ mod content_effects;
|
||||
mod export_colour_space;
|
||||
mod export_file_types;
|
||||
mod export_maps;
|
||||
mod fill_patterns;
|
||||
mod fill_projections;
|
||||
mod fill_sampling;
|
||||
mod filter_swap;
|
||||
mod filters;
|
||||
mod frame_selection;
|
||||
@@ -36,6 +39,7 @@ mod polygon_fill;
|
||||
mod project_recovery;
|
||||
mod sample;
|
||||
mod solo;
|
||||
mod symmetry;
|
||||
mod thumbs;
|
||||
mod tile_generator;
|
||||
mod tool_availability;
|
||||
@@ -44,5 +48,3 @@ mod tools;
|
||||
mod udim;
|
||||
mod user_smart_mask;
|
||||
mod uv_strokes;
|
||||
|
||||
mod symmetry;
|
||||
@@ -3,7 +3,7 @@
|
||||
//! maps from images and fill projection transforms, through engine commands.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, Decal, EffectKind, Filter, LayerId, LayerKind, Projection, Source};
|
||||
use texturecraft_engine::core::{Channel, Decal, EffectKind, Filter, LayerId, LayerKind, Projection, Projector, Source};
|
||||
use texturecraft_engine::geom::NO_TRI;
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
@@ -80,33 +80,46 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() {
|
||||
let fid = f["id"].as_str().unwrap();
|
||||
let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect");
|
||||
let (owner, e) = s.doc.project.effect(eid).unwrap();
|
||||
|
||||
assert_eq!(owner, layer);
|
||||
assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry");
|
||||
assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid));
|
||||
|
||||
execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap();
|
||||
}
|
||||
// A gradient map recolors the content; effect.set edits it and inspect shows it.
|
||||
|
||||
// A gradient map recolors the content; effect.set edits it and inspect shows it
|
||||
let gm =
|
||||
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();
|
||||
|
||||
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());
|
||||
|
||||
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();
|
||||
// Posterize on the mask; its steps are clamped.
|
||||
|
||||
// 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();
|
||||
|
||||
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 fill the content's 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.
|
||||
|
||||
// A directional blur, slope blur and warp composite without trouble on a sphere
|
||||
for (fid, extra) in [
|
||||
("blurDirectional", json!({"radius": 40, "angle": 45})),
|
||||
("slopeBlur", json!({"radius": 30})),
|
||||
@@ -122,6 +135,7 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() {
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
execute(&mut s, "effect.add.filter", &p).unwrap();
|
||||
}
|
||||
|
||||
assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0).iter().all(|v| v.is_finite()));
|
||||
}
|
||||
|
||||
@@ -176,13 +190,16 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
|
||||
let name = s
|
||||
.import_resource_bytes("logo.png", png(32, 32, |x, y| if (x as i32 - 16).pow(2) + (y as i32 - 16).pow(2) < 196 { [255, 0, 0, 255] } else { [0; 4] }))
|
||||
.unwrap();
|
||||
|
||||
assert!(execute(&mut s, "layer.add.decal", &json!({"image": "missing.png"})).is_err());
|
||||
assert!(execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 2, "y": 2})).is_err(), "off the mesh");
|
||||
|
||||
let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap();
|
||||
let layer = id(r.clone(), "layer");
|
||||
|
||||
assert!((r["decal"]["size"][1].as_f64().unwrap() - 0.5).abs() < 1e-6);
|
||||
let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
|
||||
assert!(matches!(f.projection, Projection::Decal(_)));
|
||||
assert!(matches!(f.projection, Projection::Planar { placed: Some(_), .. }));
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the decal shows where it was placed");
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and only there");
|
||||
|
||||
@@ -191,26 +208,39 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
|
||||
|
||||
// Bigger, then moved along its plane, then re-placed with a click
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": 1.2})).unwrap();
|
||||
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 160.0, 200.0)));
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": 0.4, "offset": [0.6, 0.0], "rotation": 45})).unwrap();
|
||||
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "moved away");
|
||||
|
||||
let r = execute(&mut s, "layer.decal.set", &json!({"x": 170, "y": 180})).unwrap();
|
||||
|
||||
assert_eq!(r["decal"]["offset"], json!([0.0, 0.0]), "re-placing resets the offset");
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
assert!(inspect.contains("Decal projection") && inspect.contains("\"rotation\":45"), "inspect shows the decal");
|
||||
|
||||
assert!(inspect.contains("Planar projection") && inspect.contains("\"decal\"") && inspect.contains("\"rotation\":45"), "inspect shows the decal");
|
||||
|
||||
// Not a decal; one undo step per edit
|
||||
let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err());
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
|
||||
}
|
||||
|
||||
/// The decal of mask fill effect `effect`
|
||||
fn effect_decal(s: &Session, effect: LayerId) -> Decal {
|
||||
let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &s.doc.project.effect(effect).unwrap().1.kind else { panic!("a decal fill effect") };
|
||||
let EffectKind::Fill { projection: Projection::Planar { placed: Some(decal), .. }, .. } = &s.doc.project.effect(effect).unwrap().1.kind else {
|
||||
panic!("a decal fill effect")
|
||||
};
|
||||
|
||||
*decal
|
||||
}
|
||||
|
||||
@@ -226,9 +256,13 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() {
|
||||
|
||||
// Only the effect id, with no layer selected
|
||||
s.selected.clear();
|
||||
|
||||
assert!(s.selected_layer().is_none());
|
||||
|
||||
let r = execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "size": [0.3, 0.2], "offset": [0.1, -0.05], "rotation": 30, "depth": 0.2})).unwrap();
|
||||
|
||||
assert_eq!(r["layer"], json!(layer.0), "the owning layer is reported");
|
||||
|
||||
let after = effect_decal(&s, effect);
|
||||
assert_eq!((after.size, after.offset, after.rotation), ([0.3, 0.2], [0.1, -0.05], 30.0));
|
||||
assert_eq!(after.center, before.center, "the other fields stay");
|
||||
@@ -236,20 +270,24 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() {
|
||||
|
||||
// Re-placing with a click
|
||||
execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer.0, "x": 170, "y": 180})).unwrap();
|
||||
|
||||
assert_eq!(effect_decal(&s, effect).offset, [0.0, 0.0]);
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(effect_decal(&s, effect), before, "undo restores the effect's decal");
|
||||
|
||||
// The layer decal is untouched by all of it
|
||||
let LayerKind::Fill(f) = &s.doc.project.layer(layer_decal).unwrap().kind else { panic!("a fill layer") };
|
||||
assert!(matches!(&f.projection, Projection::Decal(d) if d.size[1] == 0.5 && d.rotation == 0.0));
|
||||
assert!(matches!(&f.projection, Projection::Planar { placed: Some(d), .. } if d.size[1] == 0.5 && d.rotation == 0.0));
|
||||
|
||||
// Errors: unknown effect, an effect that is not a decal, an effect of another layer
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": 999_999, "size": 1})).is_err());
|
||||
|
||||
execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap();
|
||||
let levels = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": "levels"})).unwrap(), "effect");
|
||||
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": levels.0, "size": 1})).is_err());
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer_decal.0, "size": 1})).is_err());
|
||||
assert_eq!(effect_decal(&s, effect), before);
|
||||
@@ -257,6 +295,7 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() {
|
||||
// A new image replaces the effect's source, not a layer channel
|
||||
let other = s.import_resource_bytes("other.png", png(4, 4, |_, _| [0, 0, 0, 255])).unwrap();
|
||||
execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "image": other})).unwrap();
|
||||
|
||||
assert!(matches!(&s.doc.project.effect(effect).unwrap().1.kind, EffectKind::Fill { source: Source::Image { name, .. }, .. } if *name == other));
|
||||
}
|
||||
|
||||
@@ -268,43 +307,64 @@ fn decals_keep_the_image_aspect_and_flip_their_image() {
|
||||
let name = s.import_resource_bytes("wide.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap();
|
||||
let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap();
|
||||
let layer = id(r.clone(), "layer");
|
||||
|
||||
assert_eq!(r["decal"]["size"], json!([1.0, 0.5]), "a new decal follows its image");
|
||||
assert!(r["decal"].get("flip").is_none(), "nothing flipped saves nothing extra");
|
||||
|
||||
let size = |s: &mut Session| {
|
||||
let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
|
||||
let Projection::Decal(d) = &f.projection else { panic!("a decal") };
|
||||
let Projection::Planar { placed: Some(d), .. } = &f.projection else { panic!("a decal") };
|
||||
(d.size, d.flip)
|
||||
};
|
||||
|
||||
// A pair of sides is taken as given, unless the proportions are kept: then the width wins
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.6, 0.6]);
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": [0.8, 0.8], "keepProportions": true})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.8, 0.4], "the width sets the height by the image's aspect");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": 0.2, "keepProportions": true})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.4, 0.2], "a height sets the width");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap();
|
||||
execute(&mut s, "layer.decal.set", &json!({"keepProportions": true})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.6, 0.3], "turning the lock on fits the height to the width");
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.6, 0.6], "one undo step");
|
||||
|
||||
// Flip U and V each on their own, kept by later edits, undone one step at a time
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": [1.0, 0.5]})).unwrap();
|
||||
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && !red(at(&mut s, Channel::BaseColor, 210.0, 200.0)));
|
||||
|
||||
let r = execute(&mut s, "layer.decal.set", &json!({"flipU": true})).unwrap();
|
||||
|
||||
assert_eq!(r["decal"]["flip"], json!([true, false]));
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && red(at(&mut s, Channel::BaseColor, 210.0, 200.0)), "Flip U mirrors the image in its frame");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"flipV": true, "rotation": 10})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).1, [true, true]);
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"flipU": false})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).1, [false, true], "the other flip stays");
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).1, [true, true]);
|
||||
|
||||
// A new image in the same call sets the aspect: a tall one (1:2)
|
||||
let tall = s.import_resource_bytes("tall.png", png(4, 8, |_, _| [255, 0, 0, 255])).unwrap();
|
||||
execute(&mut s, "layer.decal.set", &json!({"image": tall, "size": 0.4, "keepProportions": true})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.2, 0.4]);
|
||||
}
|
||||
|
||||
@@ -492,26 +552,36 @@ fn a_decal_image_fills_a_chosen_channel_or_a_mask() {
|
||||
let place = |channel: &str| json!({"image": name, "channel": channel, "x": 200, "y": 200, "size": 0.5});
|
||||
|
||||
let rough = id(execute(&mut s, "layer.add.decal", &place("roughness")).unwrap(), "layer");
|
||||
|
||||
assert_eq!(s.doc.project.layer(rough).unwrap().channels.keys().copied().collect::<Vec<_>>(), [Channel::Roughness]);
|
||||
assert!(at(&mut s, Channel::Roughness, 200.0, 200.0)[0] > 0.95, "the white image is full roughness under the decal");
|
||||
assert!(execute(&mut s, "layer.add.decal", &place("sparkle")).is_err(), "unknown channel");
|
||||
|
||||
let missing = Channel::ALL.into_iter().find(|channel| !s.doc.project.texture_sets[0].has_channel(*channel)).unwrap();
|
||||
|
||||
assert!(execute(&mut s, "layer.add.decal", &place(missing.id())).is_err(), "a channel the set lacks");
|
||||
|
||||
let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap();
|
||||
let masked = id(added.clone(), "layer");
|
||||
let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap();
|
||||
assert!(matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Decal(_), .. })));
|
||||
|
||||
assert!(
|
||||
matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Planar { placed: Some(_), .. }, .. }))
|
||||
);
|
||||
assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0));
|
||||
|
||||
execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal");
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and hides it elsewhere");
|
||||
|
||||
let effect = &added["maskEffect"];
|
||||
execute(&mut s, "layer.decal.set", &json!({"effect": effect, "x": 150, "y": 200})).unwrap();
|
||||
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer");
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0)));
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"effect": effect, "layer": masked.0, "size": 0.4})).expect("an effect with its own layer");
|
||||
let mismatched = json!({"effect": effect, "layer": rough.0, "size": 0.4});
|
||||
assert!(execute(&mut s, "layer.decal.set", &mismatched).is_err(), "an effect with another layer is refused");
|
||||
@@ -671,16 +741,32 @@ fn fill_projection_edits_keep_what_they_do_not_change() {
|
||||
};
|
||||
set(&mut s, json!({"rotation": 390, "offset": [0.25, 0.5]})).unwrap();
|
||||
set(&mut s, json!({"scale": 2})).unwrap();
|
||||
|
||||
assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 2.0], rotation: 30.0, offset: [0.25, 0.5] }, "a scale keeps the rotation and offset");
|
||||
|
||||
set(&mut s, json!({"projection": "uv", "scale": [2, 3], "offset": "far"})).unwrap();
|
||||
|
||||
assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 3.0], rotation: 30.0, offset: [0.25, 0.5] }, "the same kind keeps its fields; a bad offset is ignored");
|
||||
|
||||
set(&mut s, json!({"projection": "triplanar", "offset": [1, 2, 3]})).unwrap();
|
||||
set(&mut s, json!({"sharpness": 100})).unwrap();
|
||||
assert_eq!(proj(&s), Projection::Triplanar { scale: 1.0, sharpness: 64.0, offset: [1.0, 2.0, 3.0] }, "a new kind starts from its defaults");
|
||||
|
||||
assert_eq!(
|
||||
proj(&s),
|
||||
Projection::Triplanar { scale: 1.0, sharpness: 64.0, offset: [1.0, 2.0, 3.0], uv: Default::default(), projector: Default::default() },
|
||||
"a new kind starts from its defaults"
|
||||
);
|
||||
|
||||
set(&mut s, json!({"projection": "planar", "axis": 7, "offset": [1e9, 0, 0]})).unwrap();
|
||||
assert_eq!(proj(&s), Projection::Planar { scale: 1.0, axis: 2, offset: [1000.0, 0.0, 0.0] }, "hostile values are clamped");
|
||||
|
||||
assert_eq!(
|
||||
proj(&s),
|
||||
Projection::Planar { scale: 1.0, axis: 2, offset: [1000.0, 0.0, 0.0], uv: Default::default(), projector: Projector::depth_culled(), placed: None },
|
||||
"hostile values are clamped"
|
||||
);
|
||||
assert!(set(&mut s, json!({"projection": "hexagonal"})).is_err());
|
||||
// The offset moves the pattern: a UV offset changes what the composite shows.
|
||||
|
||||
// The offset moves the pattern: a UV offset changes what the composite shows
|
||||
set(&mut s, json!({"projection": "uv", "scale": 1})).unwrap();
|
||||
execute(
|
||||
&mut s,
|
||||
@@ -747,7 +833,7 @@ fn red_on_minus_x(s: &mut Session, inside: impl Fn(f32, f32) -> bool) -> usize {
|
||||
|
||||
fn decal_of(s: &Session, layer: LayerId) -> texturecraft_engine::core::Decal {
|
||||
let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
|
||||
let Projection::Decal(decal) = fill.projection else { panic!("a decal") };
|
||||
let Projection::Planar { placed: Some(decal), .. } = fill.projection else { panic!("a decal") };
|
||||
decal
|
||||
}
|
||||
|
||||
@@ -906,11 +992,12 @@ fn a_saved_decal_with_an_out_of_range_axis_is_repaired_on_load_and_can_be_edited
|
||||
let image = session.import_resource_bytes("decal.png", png(4, 4, |_, _| [255; 4])).unwrap();
|
||||
let layer = id(execute(&mut session, "layer.add.decal", &json!({"image": image, "symmetry": "x"})).unwrap(), "layer");
|
||||
let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer).unwrap().kind else { panic!("expected fill") };
|
||||
let Projection::Decal(decal) = &mut fill.projection else { panic!("expected decal") };
|
||||
let Projection::Planar { placed: Some(decal), .. } = &mut fill.projection else { panic!("expected decal") };
|
||||
decal.symmetry.as_mut().unwrap().axis = u8::MAX;
|
||||
let bytes = session.to_project_bytes().unwrap();
|
||||
|
||||
let mut loaded = Session::from_project_bytes(&bytes).unwrap();
|
||||
|
||||
assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2);
|
||||
|
||||
execute(&mut loaded, "layer.decal.set", &json!({"layer": layer.0, "rotation": 12})).unwrap();
|
||||
|
||||
@@ -177,7 +177,8 @@ fn a_pattern_scale_edit_leaves_the_mask_fills_projection_alone() {
|
||||
execute(&mut session, "effect.set", &json!({"effect": effect, "scale": 3.0})).unwrap();
|
||||
|
||||
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") };
|
||||
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");
|
||||
}
|
||||
@@ -205,7 +206,8 @@ 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") };
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ fn multi_effect_mask(s: &mut Session) -> (LayerId, String) {
|
||||
let mask = s.doc.project.layer_mut(id).unwrap().mask.as_mut().unwrap();
|
||||
for effect in &mut mask.effects {
|
||||
if effect.id.0 == fill {
|
||||
effect.kind = EffectKind::Fill { source: Source::image(&name), projection: Default::default() };
|
||||
effect.kind = EffectKind::Fill { source: Source::image(&name), projection: Default::default(), sampling: Default::default() };
|
||||
}
|
||||
}
|
||||
let size = s.doc.project.texture_set(0).unwrap().resolution;
|
||||
@@ -169,6 +169,7 @@ fn effects_reading_an_anchor_of_the_mask_follow_it() {
|
||||
effect.kind = EffectKind::Fill {
|
||||
source: Source::Anchor { anchor: LayerId(anchor), channel: texturecraft_engine::core::Channel::Height, ramp: Vec::new() },
|
||||
projection: Default::default(),
|
||||
sampling: Default::default(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -182,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");
|
||||
}
|
||||
|
||||
@@ -197,10 +199,11 @@ fn an_external_anchor_cannot_be_saved_or_rebound_in_another_project() {
|
||||
for (project, id) in [(&mut file.project, holder), (&mut s.doc.project, source)] {
|
||||
let mask = project.layer_mut(id).unwrap().mask.as_mut().unwrap();
|
||||
let fill = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Fill { .. })).unwrap();
|
||||
fill.kind = EffectKind::Fill { source: source_ref.clone(), projection: Default::default() };
|
||||
fill.kind = EffectKind::Fill { source: source_ref.clone(), projection: Default::default(), sampling: Default::default() };
|
||||
}
|
||||
|
||||
assert!(s.smart_mask_bytes(source, "Preset").unwrap_err().to_string().contains("outside this mask"));
|
||||
|
||||
let bytes = texturecraft_engine::formats::save_project_bytes(&file).unwrap();
|
||||
let before = s.doc.project.clone();
|
||||
let history = s.history_labels();
|
||||
|
||||
@@ -25,21 +25,21 @@ pub fn decode_image(bytes: &[u8]) -> Result<DecodedImage> {
|
||||
pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result<DecodedImage> {
|
||||
let limits = image::Limits::default();
|
||||
if craft_image_codecs::detect(bytes) == Some(Format::Png) {
|
||||
return decode_imported_png(bytes, max_texels, limits.max_alloc.unwrap_or(u64::MAX));
|
||||
return decode_png(bytes, Limits::new(MAX_IMAGE_SIZE, MAX_IMAGE_SIZE, max_texels, limits.max_alloc.unwrap_or(u64::MAX)));
|
||||
}
|
||||
decode_image_with_limits(bytes, max_texels, limits)
|
||||
}
|
||||
|
||||
fn decode_imported_png(bytes: &[u8], max_texels: u64, max_alloc: u64) -> Result<DecodedImage> {
|
||||
fn decode_png(bytes: &[u8], limits: Limits) -> Result<DecodedImage> {
|
||||
if let Ok((width, height, _)) = craft_image_codecs::png_probe::header(bytes) {
|
||||
if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE {
|
||||
return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})")));
|
||||
}
|
||||
if u64::from(width) * u64::from(height) > max_texels {
|
||||
return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels")));
|
||||
if u64::from(width) * u64::from(height) > limits.max_pixels {
|
||||
return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {} texels", limits.max_pixels)));
|
||||
}
|
||||
}
|
||||
let options = DecodeOptions { limits: Limits::new(MAX_IMAGE_SIZE, MAX_IMAGE_SIZE, max_texels, max_alloc), keep_orientation: true };
|
||||
let options = DecodeOptions { limits, keep_orientation: true };
|
||||
let png = crate::guard("image", || {
|
||||
craft_image_codecs::decode_as_with(Format::Png, bytes, &options).map_err(|error| match error {
|
||||
CodecError::LimitExceeded(message) => FormatError::TooLarge(message),
|
||||
@@ -78,11 +78,16 @@ fn decode_imported_png(bytes: &[u8], max_texels: u64, max_alloc: u64) -> Result<
|
||||
|
||||
/// Decode a cook output under both its declared dimensions and decoder allocation budget.
|
||||
pub fn decode_cooked_image(bytes: &[u8], size: [u32; 2], max_decoder_bytes: u64) -> Result<DecodedImage> {
|
||||
let [width, height] = size;
|
||||
let texels = (u64::from(width) * u64::from(height)).min(MAX_RESOURCE_TEXELS);
|
||||
if craft_image_codecs::detect(bytes) == Some(Format::Png) {
|
||||
let limits = Limits::new(width.min(MAX_IMAGE_SIZE), height.min(MAX_IMAGE_SIZE), texels, max_decoder_bytes);
|
||||
return decode_png(bytes, limits);
|
||||
}
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(max_decoder_bytes);
|
||||
limits.max_image_width = Some(size[0]);
|
||||
limits.max_image_height = Some(size[1]);
|
||||
let texels = (u64::from(size[0]) * u64::from(size[1])).min(MAX_RESOURCE_TEXELS);
|
||||
limits.max_image_width = Some(width);
|
||||
limits.max_image_height = Some(height);
|
||||
decode_image_with_limits(bytes, texels, limits)
|
||||
}
|
||||
|
||||
@@ -337,22 +342,48 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_png_keeps_color_under_alpha_and_gray16_precision() {
|
||||
fn imported_and_cooked_png_keeps_color_under_alpha_and_integer_precision() {
|
||||
use image::ImageEncoder;
|
||||
|
||||
let rgba = image::DynamicImage::ImageRgba8(
|
||||
image::RgbaImage::from_raw(2, 2, vec![61, 113, 173, 0, 37, 103, 237, 81, 34, 99, 5, 193, 89, 211, 239, 255]).unwrap(),
|
||||
);
|
||||
let gray_alpha = image::DynamicImage::ImageLumaA16(image::ImageBuffer::from_raw(2, 2, vec![1234, 0, 1, 27, 0xabcd, 60211, 0xffff, 0xffff]).unwrap());
|
||||
for pixels in [rgba, gray_alpha] {
|
||||
let rgb =
|
||||
image::DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(2, 2, vec![0, 19, 256, 17, 1_235, 89, 0xabcd, 1_024, 65_534, 0, 1, 65_535]).unwrap());
|
||||
for pixels in [rgba, gray_alpha, rgb] {
|
||||
let mut png = Vec::new();
|
||||
pixels.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
|
||||
// A generated TIFF Orientation=6 tag. Cooked data maps stay in stored row order.
|
||||
let exif = b"II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0";
|
||||
encoder.set_exif_metadata(exif.to_vec()).unwrap();
|
||||
encoder.write_image(pixels.as_bytes(), 2, 2, pixels.color().into()).unwrap();
|
||||
let expected = pixels.into_rgba32f();
|
||||
let imported = decode_image_within(&png, 4).unwrap();
|
||||
assert_eq!((imported.width, imported.height), (2, 2));
|
||||
assert!(imported.srgb);
|
||||
assert_eq!(imported.rgba, expected.into_raw().as_chunks::<4>().0);
|
||||
assert_eq!(decode_cooked_image(&png, [2, 2], 1 << 20).unwrap(), imported);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cooked_png_checks_reported_sides_and_decoder_allowance() {
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::from_pixel(8, 2, image::Rgba([3, 47, 187, 0])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let header = &png[..33];
|
||||
// Each report allows 16 texels but falls short on an individual axis.
|
||||
for size in [[4, 4], [16, 1]] {
|
||||
for data in [png.as_slice(), header] {
|
||||
assert!(matches!(decode_cooked_image(data, size, 1 << 20), Err(FormatError::TooLarge(_))));
|
||||
}
|
||||
}
|
||||
assert!(matches!(decode_cooked_image(header, [8, 2], 1 << 20), Err(FormatError::Malformed { .. })));
|
||||
assert!(matches!(decode_cooked_image(&png, [8, 2], 8 * 2 * 4 - 1), Err(FormatError::TooLarge(_))));
|
||||
let valid = decode_cooked_image(&png, [8, 2], 1 << 20).unwrap();
|
||||
assert_eq!([valid.width, valid.height], [8, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_import_checks_texels_before_requiring_the_pixel_payload() {
|
||||
let png = coverage_png(4, 3, &[255; 12], [13, 27, 83]).unwrap();
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -369,6 +369,26 @@ impl Mesh {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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_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_area += (*pb - *pa).cross(*pc - *pa).length() * 0.5;
|
||||
uv_area += (*ub - *ua).perp_dot(*uc - *ua).abs() * 0.5;
|
||||
}
|
||||
|
||||
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
|
||||
/// materials are duplicated first, so the other triangles keep their UVs.
|
||||
pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) {
|
||||
@@ -595,6 +615,30 @@ mod tests {
|
||||
assert_eq!(m.bounds_of_material(1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_density_is_mesh_units_per_uv_unit() {
|
||||
assert_eq!(quad().uv_density(0), Some(1.0));
|
||||
|
||||
let plane = crate::primitives::plane(3.0, 4).uv_density(0).unwrap();
|
||||
|
||||
assert!((plane - 3.0).abs() < 1e-4, "{plane}");
|
||||
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();
|
||||
|
||||
@@ -181,8 +181,8 @@ fn full_turn() -> f32 {
|
||||
FULL_TURN_DEGREES
|
||||
}
|
||||
|
||||
/// [`Symmetry::angle_span`] of a full turn
|
||||
pub const FULL_TURN_DEGREES: f32 = 360.0;
|
||||
// A full turn is the angle span every crate measures turns against
|
||||
pub use texturecraft_core::FULL_TURN_DEGREES;
|
||||
|
||||
/// Most radial copies a brush paints
|
||||
pub const MAX_RADIAL_COPIES: u8 = 32;
|
||||
@@ -445,8 +445,9 @@ mod tests {
|
||||
#[test]
|
||||
fn image_alpha_follows_the_image_and_is_zero_outside() {
|
||||
// Left half white, right half black (2×1 image, sampled at texel centers)
|
||||
let img = ImageRes { width: 2, height: 1, rgba: vec![[1.0; 4], [0.0, 0.0, 0.0, 1.0]], srgb: true };
|
||||
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);
|
||||
@@ -483,12 +484,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn default_parameters_reproduce_every_alpha_exactly() {
|
||||
let img = ImageRes {
|
||||
width: 3,
|
||||
height: 2,
|
||||
rgba: vec![[1.0; 4], [0.3, 0.3, 0.3, 1.0], [0.0, 0.0, 0.0, 1.0], [0.6, 0.6, 0.6, 1.0], [0.9; 4], [0.1, 0.1, 0.1, 1.0]],
|
||||
srgb: true,
|
||||
};
|
||||
let img = ImageRes::new(3, 2, vec![[1.0; 4], [0.3, 0.3, 0.3, 1.0], [0.0, 0.0, 0.0, 1.0], [0.6, 0.6, 0.6, 1.0], [0.9; 4], [0.1, 0.1, 0.1, 1.0]], true);
|
||||
let library = crate::alphas::library().first().map(|alpha| alpha.image());
|
||||
let kinds = BrushAlpha::ALL.map(|alpha| Shape { alpha, image: None, library: None, params: AlphaParams::default(), level: 0 });
|
||||
for shape in kinds.into_iter().chain([
|
||||
@@ -501,6 +497,7 @@ mod tests {
|
||||
(None, Some(lib)) => lib.sample(shape.level, x, y),
|
||||
(None, None) => shape.alpha.sample(x, y, 0.4, 7),
|
||||
};
|
||||
|
||||
assert_eq!(shape.sample(x, y, 0.4, 7).to_bits(), before.to_bits(), "{:?} at ({x}, {y})", shape.alpha);
|
||||
}
|
||||
}
|
||||
@@ -522,9 +519,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn sizes_apply_to_image_and_library_alphas_too() {
|
||||
let img = ImageRes { width: 1, height: 1, rgba: vec![[1.0; 4]], srgb: true };
|
||||
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());
|
||||
|
||||
@@ -366,7 +366,12 @@ mod tests {
|
||||
let mut project = Project::new("test", "builtin:plane");
|
||||
project.texture_sets.push(TextureSet::new("Set", 0, size));
|
||||
let id = project.alloc_id();
|
||||
let fill = Fill { sources: [(Channel::Roughness, Source::Uniform([0.25; 3]))].into(), projection: Default::default(), link: None };
|
||||
let fill = Fill {
|
||||
sources: [(Channel::Roughness, Source::Uniform([0.25; 3]))].into(),
|
||||
projection: Default::default(),
|
||||
sampling: Default::default(),
|
||||
link: None,
|
||||
};
|
||||
let mut layer = Layer::new(id, "fill", LayerKind::Fill(fill), &[Channel::Roughness]);
|
||||
layer.mask = Some(Mask::new(MaskBackground::White));
|
||||
project.insert_layer(0, layer, None, false).unwrap();
|
||||
@@ -384,6 +389,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] {
|
||||
|
||||
@@ -762,16 +762,20 @@ 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).
|
||||
|
||||
// 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 { width: w, height: hh, rgba, srgb: false };
|
||||
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)");
|
||||
|
||||
h.renderer.set_environment(&h.device, &h.queue, "Studio Soft", None);
|
||||
|
||||
assert_eq!(render(&mut h, &frame, "env_default_again").px, base.px, "built-ins come back");
|
||||
}
|
||||
|
||||
@@ -1081,7 +1085,7 @@ fn spot_environment(dir: texturecraft_geom::glam::Vec3) -> ImageRes {
|
||||
if d.dot(dir) > 0.5 { [6.0, 6.0, 6.0, 1.0] } else { [0.02, 0.02, 0.02, 1.0] }
|
||||
})
|
||||
.collect();
|
||||
ImageRes { width: w, height: hh, rgba, srgb: false }
|
||||
ImageRes::new(w, hh, rgba, false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -71,7 +71,7 @@ impl DecalDrop {
|
||||
});
|
||||
}
|
||||
|
||||
/// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing
|
||||
/// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click or a drag elsewhere drops nothing
|
||||
pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) {
|
||||
let id = Self::menu_id();
|
||||
let Some(drop) = Self::current(ui.ctx()) else { return };
|
||||
@@ -110,7 +110,7 @@ impl DecalDrop {
|
||||
});
|
||||
});
|
||||
|
||||
if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) {
|
||||
if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) || crate::popup_drag::drag_outside_popups(ui.ctx()) {
|
||||
Self::close(ui.ctx());
|
||||
}
|
||||
|
||||
|
||||
+503
-335
File diff suppressed because it is too large.
Load diff
+154
-39
@@ -12,7 +12,7 @@
|
||||
|
||||
use craft_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement};
|
||||
use craft_ui::layout::{SplitAxis, SplitSize};
|
||||
use egui::{Id, Margin, RichText, Ui, vec2};
|
||||
use egui::{Id, Margin, RichText, Ui, Vec2, vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -20,6 +20,11 @@ use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
mod header_band;
|
||||
mod shown_group_tab;
|
||||
|
||||
pub(crate) use shown_group_tab::HEADER_TITLE_LEFT;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum Panel {
|
||||
Viewport,
|
||||
@@ -160,7 +165,9 @@ pub fn default_workspace() -> Workspace {
|
||||
const ASSETS_SPLIT_RATIO: f32 = 0.16;
|
||||
const VIEWPORT_SPLIT_RATIO: f32 = 0.80;
|
||||
const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125;
|
||||
const LAYERS_SPLIT_RATIO: f32 = 0.57;
|
||||
|
||||
// Leave room for three layer rows and the fill's channel controls
|
||||
const LAYERS_SPLIT_RATIO: f32 = 0.31;
|
||||
|
||||
let column = split(
|
||||
SplitAxis::Vertical,
|
||||
@@ -412,19 +419,24 @@ const TAB_TEXT_SIZE: f32 = 12.5;
|
||||
/// Narrowest panel tab, in points
|
||||
const MIN_TAB_WIDTH: f32 = 54.0;
|
||||
|
||||
/// The dock look: each panel group a card on the window's frame colour, tab strips without hard lines, the shown tab a pill
|
||||
/// 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);
|
||||
dock_style.gap = f32::from(crate::theme::GUTTER);
|
||||
dock_style.min_pane = MIN_PANE_EXTENT;
|
||||
|
||||
dock_style.background = tokens.panel;
|
||||
dock_style.tab_background = tokens.panel;
|
||||
dock_style.active_background = tokens.button;
|
||||
dock_style.tab_background = tokens.chrome;
|
||||
|
||||
// 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);
|
||||
|
||||
@@ -468,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 });
|
||||
|
||||
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"))]
|
||||
@@ -491,15 +504,52 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Size of the panel names on a header bar
|
||||
const HEADER_TITLE_SIZE: f32 = 12.0;
|
||||
|
||||
/// Side of the close × at the right end of a header bar
|
||||
const HEADER_CLOSE_SIZE: f32 = 22.0;
|
||||
|
||||
/// Room right of the close × button, so its glyph ends where the Properties controls end (side padding plus scroll bar gutter)
|
||||
const HEADER_CLOSE_RIGHT_MARGIN: f32 = 18.0;
|
||||
|
||||
/// Whether a docked group's header bar ends in a close × (floating windows have one on their title bar; the viewport never closes)
|
||||
fn header_closes(active: &Panel, floating: bool) -> bool {
|
||||
!floating && permissions(active).closable
|
||||
}
|
||||
|
||||
/// The panels' contents, names and limits for the dock area
|
||||
struct Panels<'a> {
|
||||
app: &'a mut TextureCraftApp,
|
||||
tokens: Tokens,
|
||||
layout: &'a Layout<Panel>,
|
||||
style: &'a DockStyle,
|
||||
}
|
||||
|
||||
/// Room between a panel's edges and its contents
|
||||
const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4);
|
||||
|
||||
/// Narrowest Properties panel and so its dock column: the 300 point design width plus the solid scroll bar; narrower, the 3D projection settings' X, Y, Z fields (the widest row) overlap
|
||||
pub const PROPERTIES_MIN_WIDTH: f32 = 310.0;
|
||||
|
||||
/// Least size of a docked or floating panel other than the 3D view and Properties
|
||||
const PANEL_MIN_SIZE: Vec2 = vec2(120.0, 60.0);
|
||||
|
||||
/// Least size of the 3D view
|
||||
const VIEWPORT_MIN_SIZE: Vec2 = vec2(200.0, 150.0);
|
||||
|
||||
/// Size a panel opens at when it floats
|
||||
const FLOATING_SIZE: Vec2 = vec2(300.0, 380.0);
|
||||
|
||||
/// Least size of `panel`, docked or floating; a dock column or split stops shrinking at its panels' largest
|
||||
fn min_size(panel: Panel) -> Vec2 {
|
||||
match panel {
|
||||
Panel::Viewport => VIEWPORT_MIN_SIZE,
|
||||
Panel::Properties => vec2(PROPERTIES_MIN_WIDTH, PANEL_MIN_SIZE.y),
|
||||
_ => PANEL_MIN_SIZE,
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of every panel except the viewport, in the dock or on the rail
|
||||
pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
|
||||
// No project open: the library and the log work, the other panels about a project stay empty
|
||||
@@ -508,7 +558,9 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
|
||||
return;
|
||||
}
|
||||
|
||||
egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel {
|
||||
// Properties draws full-width bands and tabs, so it keeps its own margins
|
||||
let margin = if panel == Panel::Properties { Margin::ZERO } else { PANEL_BODY_MARGIN };
|
||||
egui::Frame::new().inner_margin(margin).show(ui, |ui| match panel {
|
||||
Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui),
|
||||
Panel::Assets => crate::shelf::body(app, ui),
|
||||
Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui),
|
||||
@@ -532,15 +584,16 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
|
||||
|
||||
impl DockContent<Panel> for Panels<'_> {
|
||||
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
|
||||
let app = &mut *self.app;
|
||||
if *panel == Panel::Viewport {
|
||||
crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect());
|
||||
ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport);
|
||||
crate::viewport::central(app, ui);
|
||||
crate::viewport::central(self.app, ui);
|
||||
return;
|
||||
}
|
||||
|
||||
panel_body(app, ui, *panel);
|
||||
// Before the rows, which draw over the foot of the shown tab's box
|
||||
self.paint_shown_group_tab(ui, *panel);
|
||||
panel_body(self.app, ui, *panel);
|
||||
}
|
||||
|
||||
fn logical_label(&self, panel: &Panel) -> String {
|
||||
@@ -550,8 +603,58 @@ impl DockContent<Panel> for Panels<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
|
||||
RichText::new(logical).font(font.clone()).color(color).into()
|
||||
fn label(&mut self, ui: &Ui, panel: &Panel, logical: &str, _font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
|
||||
// Capitals on the bar only: menus and screen readers keep the logical name
|
||||
let name = logical.to_uppercase();
|
||||
let font = crate::theme::semibold(HEADER_TITLE_SIZE);
|
||||
|
||||
// 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();
|
||||
}
|
||||
|
||||
header_band::header_name(ui, &name, font, color, self.header_lift(*panel)).into()
|
||||
}
|
||||
|
||||
fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 {
|
||||
if header_closes(active, floating) {
|
||||
HEADER_CLOSE_SIZE + HEADER_CLOSE_RIGHT_MARGIN
|
||||
} else if redocks(panels, active, floating) {
|
||||
DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A docked group's bar ends in its close ×; a rail panel floating on its own carries the Dock button that sends it back to the rail
|
||||
fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) {
|
||||
if redocks(panels, active, floating) {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() {
|
||||
self.app.ui.dock.close(*active);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if !header_closes(active, floating) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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)),
|
||||
vec2(HEADER_CLOSE_SIZE, HEADER_CLOSE_SIZE),
|
||||
);
|
||||
let clicked = ui
|
||||
.scope_builder(egui::UiBuilder::new().max_rect(button), |ui| {
|
||||
crate::widgets::icon_button(ui, egui_phosphor::regular::X, tr("Close Panel"), false, HEADER_CLOSE_SIZE).clicked()
|
||||
})
|
||||
.inner;
|
||||
if clicked {
|
||||
self.app.ui.dock.close(*active);
|
||||
}
|
||||
}
|
||||
|
||||
fn permissions(&self, panel: &Panel) -> Permissions {
|
||||
@@ -559,29 +662,11 @@ impl DockContent<Panel> for Panels<'_> {
|
||||
}
|
||||
|
||||
fn limits(&self, panel: &Panel) -> PanelLimits {
|
||||
let min = if *panel == Panel::Viewport { vec2(200.0, 150.0) } else { vec2(120.0, 60.0) };
|
||||
PanelLimits { min, ..PanelLimits::default() }
|
||||
PanelLimits { min: min_size(*panel), ..PanelLimits::default() }
|
||||
}
|
||||
|
||||
fn floating_size(&self, _panel: &Panel) -> Option<egui::Vec2> {
|
||||
Some(vec2(300.0, 380.0))
|
||||
}
|
||||
|
||||
fn group_header_width(&self, panels: &[Panel], active: &Panel, floating: bool, _strip_width: f32) -> f32 {
|
||||
if redocks(panels, active, floating) { DOCK_BUTTON_SIZE + DOCK_BUTTON_MARGIN } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A rail panel floating on its own carries the Dock button that sends it back to the rail
|
||||
fn group_header(&mut self, ui: &mut Ui, panels: &[Panel], active: &Panel, floating: bool) {
|
||||
if !redocks(panels, active, floating) {
|
||||
return;
|
||||
}
|
||||
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if crate::widgets::icon_button(ui, egui_phosphor::regular::ARROW_SQUARE_IN, tr("Dock"), false, DOCK_BUTTON_SIZE).clicked() {
|
||||
self.app.ui.dock.close(*active);
|
||||
}
|
||||
});
|
||||
fn floating_size(&self, panel: &Panel) -> Option<egui::Vec2> {
|
||||
Some(FLOATING_SIZE.max(min_size(*panel)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -606,12 +691,42 @@ 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]
|
||||
fn the_default_right_column_gives_properties_about_two_thirds_under_the_texture_sets() {
|
||||
let workspace = default_workspace();
|
||||
let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_ref() else { panic!("assets | rest") };
|
||||
let Node::Split { second: column, .. } = right.as_ref() else { panic!("viewport | right column") };
|
||||
let Node::Split { second: below_sets, .. } = column.as_ref() else { panic!("texture sets | rest") };
|
||||
let Node::Split { size: SplitSize::Ratio(layers), first, second, .. } = below_sets.as_ref() else { panic!("layers | properties") };
|
||||
assert!(matches!(first.as_ref(), Node::Tabs { panels, .. } if panels.first() == Some(&Panel::Layers)));
|
||||
assert!(matches!(second.as_ref(), Node::Tabs { panels, .. } if panels == &[Panel::Properties]));
|
||||
|
||||
let properties = 1.0 - layers;
|
||||
assert!((2.0 / 3.0..0.7).contains(&properties), "Properties takes about 69% of the column, at least two thirds: {properties}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_split_keeps_its_own_share() {
|
||||
let mut workspace = default_workspace();
|
||||
let Some(Node::Split { second: right, .. }) = workspace.layout.root.as_mut() else { panic!("assets | rest") };
|
||||
let Node::Split { second: column, .. } = right.as_mut() else { panic!("viewport | right column") };
|
||||
let Node::Split { second: below_sets, .. } = column.as_mut() else { panic!("texture sets | rest") };
|
||||
let Node::Split { size, .. } = below_sets.as_mut() else { panic!("layers | properties") };
|
||||
*size = SplitSize::Ratio(0.57);
|
||||
let back = Dock::from_value(serde_json::to_value(&workspace).unwrap());
|
||||
|
||||
assert_eq!(back.workspace(), &workspace, "a layout saved with the old split opens unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Positions dock tab titles within the tab strip and the gutter above it.
|
||||
|
||||
use craft_ui::docking::{Layout, Node};
|
||||
use craft_ui::layout::SplitAxis;
|
||||
use egui::text::{LayoutJob, TextFormat};
|
||||
use egui::{Align, Color32, FontId, Ui};
|
||||
|
||||
use super::Panel;
|
||||
|
||||
/// 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 - 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 {
|
||||
layout.root.as_ref().and_then(|node| group_is_below_panel(node, panel, false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// `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_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());
|
||||
|
||||
// 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_points;
|
||||
if shift < 0.0
|
||||
&& let Some(section) = job.sections.first_mut()
|
||||
{
|
||||
section.format.valign = Align::BOTTOM;
|
||||
}
|
||||
|
||||
job.first_row_min_height = galley.size().y + 2.0 * shift.abs();
|
||||
job
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! The active tab in a panel group, drawn as a raised box joined to the panel body
|
||||
|
||||
use craft_ui::docking::{DockContent, Node};
|
||||
use egui::text::TextWrapping;
|
||||
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, area_id};
|
||||
use crate::property_sheet::{full_height_tab_rect, shown_tab_box};
|
||||
use crate::theme::semibold;
|
||||
|
||||
/// 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;
|
||||
|
||||
/// Gap between the active tab's box and its neighbours, in points
|
||||
const TAB_BOX_INSET: f32 = 4.0;
|
||||
|
||||
/// Insets the focus outline inside the tab's actual hit rect
|
||||
const TAB_FOCUS_INSET: f32 = 2.0;
|
||||
|
||||
/// Width of the focus outline in points
|
||||
const TAB_FOCUS_STROKE_WIDTH: f32 = 1.0;
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
|
||||
impl Panels<'_> {
|
||||
/// How far a header band reaches above its tab strip
|
||||
fn header_rise(&self, panel: Panel) -> f32 {
|
||||
if under_a_panel(self.layout, panel) { HEADER_RISE } else { 0.0 }
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// 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 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;
|
||||
}
|
||||
|
||||
// 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 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,5 @@
|
||||
//! The Levels editor's mark that its exact-entry fields are shown
|
||||
|
||||
/// Marks the exact-entry fields as shown; they appear on a handle's double-click or Enter and close when typing ends
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ExactEntryOpen;
|
||||
@@ -0,0 +1,488 @@
|
||||
//! A fill's Properties: its projection, size, placement and edges, then its material
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use egui::{Painter, Rect};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::compose::frame_placement;
|
||||
use texturecraft_engine::compose::tile_length::{MeshSize, tile_length, tiling_for_length};
|
||||
use texturecraft_engine::core::{Backface, Fill, Filtering, LayerId, Projection, Projector, ScaleMode, ShapeCrop, UvWrap};
|
||||
use texturecraft_engine::layer_cmds::{MAX_PLACEMENT, MIN_SCALE};
|
||||
use texturecraft_engine::paint::FULL_TURN_DEGREES;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::dock::with;
|
||||
use crate::fill_pictures::{
|
||||
angle_picture, backface_picture, crop_picture, depth_picture, filtering_picture, projection_picture, warp_preview, window_preview, wrap_picture,
|
||||
};
|
||||
use crate::i18n::{filtering_label, n_, tr, wrap_label};
|
||||
use crate::move_on_model::MoveOnModel;
|
||||
use crate::placement::Placement;
|
||||
use crate::projection_kind::ProjectionKind;
|
||||
use crate::projection_preview::projection_preview;
|
||||
use crate::property_sheet::{NumberField, PreviewLower, PreviewSize, PropertySheet, RowLead};
|
||||
use crate::theme::{AXIS_COLORS, AXIS_NAMES, Tokens};
|
||||
|
||||
/// Centimetres in one mesh unit: meshes are read in metres
|
||||
const CM_PER_UNIT: f32 = 100.0;
|
||||
|
||||
/// What the Tiling track spans
|
||||
const TILING_TRACK: RangeInclusive<f32> = 0.01..=5.0;
|
||||
|
||||
/// What a typed tiling may be: the command's own limits
|
||||
const TILING_TYPED: RangeInclusive<f32> = MIN_SCALE..=MAX_PLACEMENT;
|
||||
|
||||
/// What the Size (cm) track spans
|
||||
const SIZE_CM_TRACK: RangeInclusive<f32> = 1.0..=500.0;
|
||||
|
||||
/// What a typed size (cm) may be
|
||||
const SIZE_CM_TYPED: RangeInclusive<f32> = 0.1..=100_000.0;
|
||||
|
||||
/// What an Offset track spans (tiles, centred on zero)
|
||||
const OFFSET_TRACK: RangeInclusive<f32> = -2.0..=2.0;
|
||||
|
||||
/// What a typed offset may be (tiles): the command's own limits
|
||||
const OFFSET_TYPED: RangeInclusive<f32> = -MAX_PLACEMENT..=MAX_PLACEMENT;
|
||||
|
||||
/// Range of a fill's rotation, a full turn
|
||||
const ROTATION_RANGE: RangeInclusive<f32> = 0.0..=FULL_TURN_DEGREES;
|
||||
|
||||
/// Tri-planar blend's largest exponent: Hardness 1 (0 = exponent 1, 0.5 = 8)
|
||||
const TRIPLANAR_SHARPNESS_MAX: f32 = *Projection::TRIPLANAR_SHARPNESS_RANGE.end();
|
||||
|
||||
/// Range of every Hardness the panel shows
|
||||
const HARDNESS_RANGE: RangeInclusive<f32> = 0.0..=1.0;
|
||||
|
||||
/// What a cylindrical projection's Angle may be: the arc one repeat spans, in degrees
|
||||
const CYLINDER_ANGLE_RANGE: RangeInclusive<f32> = Projection::CYLINDER_ANGLE_RANGE;
|
||||
|
||||
/// What Backface culling's Angle may be, in degrees from facing the projector
|
||||
const BACKFACE_ANGLE_RANGE: RangeInclusive<f32> = Backface::ANGLE_RANGE;
|
||||
|
||||
/// What the Projection Depth track spans, in lengths of the frame's longer side
|
||||
const PROJECTION_DEPTH_TRACK: RangeInclusive<f32> = 0.0..=1.0;
|
||||
|
||||
/// A degenerate warp frame's preview size: its side spans the preview's middle
|
||||
const WARP_SPAN_FALLBACK: f32 = 1.7;
|
||||
|
||||
/// Change per pixel dragged on a 3D offset field
|
||||
pub(crate) const OFFSET_FIELD_SPEED: f32 = 0.01;
|
||||
|
||||
/// Change per pixel dragged on a 3D rotation field, in degrees
|
||||
const ROTATION_FIELD_SPEED: f32 = 0.5;
|
||||
|
||||
/// Change per pixel dragged on a 3D scale field
|
||||
const SCALE_FIELD_SPEED: f32 = 0.01;
|
||||
|
||||
/// The tabs over a fill's Properties, each jumping to its section
|
||||
pub(crate) fn fill_tabs() -> [(&'static str, &'static str); 2] {
|
||||
[(ic::SLIDERS_HORIZONTAL, tr("Fill")), (ic::FLIP_HORIZONTAL, tr("Symmetry"))]
|
||||
}
|
||||
|
||||
/// Which fill a `base` addresses, (layer, effect), as the salt of its rows' widget state
|
||||
pub(crate) type FillKey = (Option<u64>, Option<u64>);
|
||||
|
||||
/// The [`FillKey`] of the fill at `base`
|
||||
pub(crate) fn fill_key(base: &Value) -> FillKey {
|
||||
(base.get("layer").and_then(Value::as_u64), base.get("effect").and_then(Value::as_u64))
|
||||
}
|
||||
|
||||
/// The mesh's size for the texture set being painted, as the projections see it, measured once per mesh and material
|
||||
fn mesh_size(app: &TextureCraftApp, ctx: &egui::Context) -> MeshSize {
|
||||
let mesh = &app.session.mesh;
|
||||
let material = app.session.doc.project.texture_set(app.session.ts()).map_or(0, |texture_set| texture_set.material);
|
||||
let key = (app.session.mesh_id, material);
|
||||
|
||||
// Both measures walk the whole mesh, too slow for every frame the sheet draws on a dense mesh
|
||||
let cache_id = egui::Id::unique("tc_fill_mesh_size");
|
||||
if let Some((cached_key, size)) = ctx.data(|data| data.get_temp::<((u64, usize), MeshSize)>(cache_id))
|
||||
&& cached_key == key
|
||||
{
|
||||
return size;
|
||||
}
|
||||
|
||||
let size = MeshSize { radius: mesh.radius(), uv_density: mesh.uv_density(material).unwrap_or(1.0) };
|
||||
ctx.data_mut(|data| data.insert_temp(cache_id, (key, size)));
|
||||
size
|
||||
}
|
||||
|
||||
/// The Fill section (with its reset) and the Symmetry section of the fill at `base`: a fill layer's, a content fill effect's or a mask fill's
|
||||
pub(crate) fn placement_sections(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, reader: LayerId) {
|
||||
// The section reset: projection, placement, sampling and culling back to a new fill's in one undo step
|
||||
if sheet.section_reset(tr("Fill"), !texturecraft_engine::fill_reset_cmds::at_defaults(&fill.projection, fill.sampling)) {
|
||||
app.run("layer.fill.resetProjection", base.clone());
|
||||
}
|
||||
projection_rows(app, sheet, fill, base, fill_key(base), reader);
|
||||
crate::fill_symmetry_panel::symmetry_section(app, sheet, &fill.projection, fill.sampling, base);
|
||||
}
|
||||
|
||||
/// Runs `layer.fill.projection` on the fill `base` names with `fields`
|
||||
pub(crate) fn run_projection(app: &mut TextureCraftApp, base: &Value, fields: Value) {
|
||||
app.run("layer.fill.projection", with(base, fields));
|
||||
}
|
||||
|
||||
/// Projection, Scale, the preview with size and offset (held, it moves the projection on the model), Rotation, the culling rows, then the Filtering and edges and 3D projection settings bands
|
||||
fn projection_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, salt: FillKey, reader: LayerId) {
|
||||
let tokens = Tokens::get(sheet.ui.ctx());
|
||||
let kind = ProjectionKind::of(&fill.projection);
|
||||
let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields);
|
||||
|
||||
let picture = |painter: &Painter, rect: Rect, kind: ProjectionKind| projection_picture(painter, rect, kind, &tokens);
|
||||
|
||||
// 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();
|
||||
let (picked, eye) = if matches!(kind, ProjectionKind::Uv | ProjectionKind::UvTile) {
|
||||
(sheet.dropdown(tr("Projection"), kind, &ProjectionKind::ALL, name, Some(&picture)).0, false)
|
||||
} else {
|
||||
sheet.dropdown_with_eye(tr("Projection"), kind, &ProjectionKind::ALL, name, Some(&picture), (gizmos, tip))
|
||||
};
|
||||
if let Some(kind) = picked {
|
||||
run(app, json!({"projection": kind.id()}));
|
||||
}
|
||||
if eye {
|
||||
app.run("display.set", json!({"projectionGizmos": !gizmos}));
|
||||
}
|
||||
|
||||
// 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()}));
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
let edges_changed = fill.sampling.filtering != Filtering::default()
|
||||
|| (shows_wrap && fill.sampling.wrap != UvWrap::default())
|
||||
|| crop.is_some_and(|crop| crop != ShapeCrop::default());
|
||||
let band = sheet.band(tr("Filtering and edges"), true, Some(edges_changed), None);
|
||||
if band.reset {
|
||||
let mut fields = json!({"filtering": Filtering::default().id(), "wrap": UvWrap::default().id()});
|
||||
if crop.is_some() {
|
||||
fields["shapeCrop"] = json!(ShapeCrop::default().id());
|
||||
}
|
||||
run(app, fields);
|
||||
}
|
||||
if band.open {
|
||||
let filtering = fill.sampling.filtering;
|
||||
let picture = |painter: &Painter, rect: Rect, filtering: Filtering| filtering_picture(painter, rect, filtering, &tokens);
|
||||
let (picked, _) = sheet.dropdown(tr("Filtering"), filtering, &Filtering::ALL, |filtering| tr(filtering_label(filtering)).to_owned(), Some(&picture));
|
||||
if let Some(filtering) = picked {
|
||||
run(app, json!({"filtering": filtering.id()}));
|
||||
}
|
||||
|
||||
// Tri-planar has no tile to repeat
|
||||
if shows_wrap {
|
||||
let picture = |painter: &Painter, rect: Rect, wrap: UvWrap| wrap_picture(painter, rect, wrap, &tokens);
|
||||
let (picked, _) = sheet.dropdown(tr("UV Wrap"), fill.sampling.wrap, &UvWrap::ALL, |wrap| tr(wrap_label(wrap)).to_owned(), Some(&picture));
|
||||
if let Some(wrap) = picked {
|
||||
run(app, json!({"wrap": wrap.id()}));
|
||||
}
|
||||
}
|
||||
if let Some(projector) = projector_of(&fill.projection) {
|
||||
let picture = |painter: &Painter, rect: Rect, crop: ShapeCrop| crop_picture(painter, rect, crop, &tokens);
|
||||
let (picked, _) = sheet.dropdown(tr("Shape crop"), projector.crop, &ShapeCrop::ALL, |crop| tr(crop_label(crop)).to_owned(), Some(&picture));
|
||||
if let Some(crop) = picked {
|
||||
run(app, json!({"shapeCrop": crop.id()}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
world_rows(app, sheet, fill, base, salt);
|
||||
}
|
||||
|
||||
/// The settings of the projector itself, shared by every 3D projection
|
||||
fn projector_of(projection: &Projection) -> Option<&Projector> {
|
||||
match projection {
|
||||
Projection::Triplanar { projector, .. }
|
||||
| Projection::Planar { projector, .. }
|
||||
| Projection::Spherical { projector, .. }
|
||||
| Projection::Cylindrical { projector, .. }
|
||||
| Projection::Warp { projector, .. } => Some(projector),
|
||||
Projection::Uv { .. } | Projection::UvTile => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of a Shape crop choice; both fit beside the label at the default panel width
|
||||
fn crop_label(crop: ShapeCrop) -> &'static str {
|
||||
match crop {
|
||||
ShapeCrop::Cropped => n_("Cropped to Shape"),
|
||||
ShapeCrop::ExtendsOutside => n_("Extends Outside Shape"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tri-planar Hardness as the panel shows it (0..1) from the blend's exponent (1..64): exponent = 64^hardness
|
||||
fn triplanar_hardness(sharpness: f32) -> f32 {
|
||||
(sharpness.max(1.0).ln() / TRIPLANAR_SHARPNESS_MAX.ln()).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// The blend's exponent for a tri-planar Hardness the panel shows
|
||||
fn triplanar_sharpness(hardness: f32) -> f32 {
|
||||
TRIPLANAR_SHARPNESS_MAX.powf(hardness.clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// A warp's Projection Depth and Reset frame
|
||||
fn frame_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value) {
|
||||
let Projection::Warp { depth, .. } = &fill.projection else { return };
|
||||
let mut depth = *depth;
|
||||
|
||||
// Its i tells it apart from Depth culling; it keeps the column every projection shares
|
||||
sheet.info(tr("How far the warp projection reaches into the mesh, in front of and behind its frame, in lengths of the frame's longer side. It bounds the fill only when cropped to its shape."));
|
||||
if let Some(merge) = sheet.slider_led(RowLead::Loose(tr("Depth")), &mut depth, PROJECTION_DEPTH_TRACK, 2, "") {
|
||||
run_projection(app, base, json!({"projectionDepth": depth, "merge": merge}));
|
||||
}
|
||||
if sheet.button(ic::ARROW_CLOCKWISE, tr("Reset frame")).clicked() {
|
||||
app.run("layer.fill.resetFrame", base.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Cylindrical Angle, then Depth culling (planar, warp) and Backface culling (planar, cylindrical), each with its settings under it
|
||||
fn culling_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value) {
|
||||
let tokens = Tokens::get(sheet.ui.ctx());
|
||||
let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields);
|
||||
let (projector, angle) = match &fill.projection {
|
||||
Projection::Cylindrical { projector, angle, .. } => (projector, Some(*angle)),
|
||||
Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => (projector, None),
|
||||
_ => return,
|
||||
};
|
||||
|
||||
if let Some(mut angle) = angle {
|
||||
let arc = angle;
|
||||
let picture = |painter: &Painter, rect: Rect| angle_picture(painter, rect, arc, &tokens);
|
||||
let lead = RowLead::Picture { picture: &picture, text: tr("Angle") };
|
||||
if let Some(merge) = sheet.slider_led(lead, &mut angle, CYLINDER_ANGLE_RANGE, 0, "°") {
|
||||
run(app, json!({"angle": angle, "merge": merge}));
|
||||
}
|
||||
}
|
||||
|
||||
if !matches!(fill.projection, Projection::Cylindrical { .. }) {
|
||||
let mut culling = projector.depth;
|
||||
let picture = |painter: &Painter, rect: Rect| depth_picture(painter, rect, &tokens);
|
||||
sheet.info(tr("Paints only the surface the projector sees first; parts hidden behind it stay unpainted."));
|
||||
if sheet.picture_toggle(&picture, tr("Depth culling"), &mut culling.on) {
|
||||
run(app, json!({"depthCulling": culling.on}));
|
||||
}
|
||||
if let Some(merge) = sheet.slider_led(RowLead::Child(tr("Hardness")), &mut culling.hardness, HARDNESS_RANGE, 2, "") {
|
||||
run(app, json!({"depthCullingHardness": culling.hardness, "merge": merge}));
|
||||
}
|
||||
}
|
||||
|
||||
if !matches!(fill.projection, Projection::Warp { .. }) {
|
||||
let mut backface = projector.backface;
|
||||
let culled = backface.on;
|
||||
let picture = |painter: &Painter, rect: Rect| backface_picture(painter, rect, culled, &tokens);
|
||||
sheet.info(tr("Leaves out faces turned away from the projector, so the fill doesn't run onto their back."));
|
||||
if sheet.picture_toggle(&picture, tr("Backface culling"), &mut backface.on) {
|
||||
run(app, json!({"backfaceCulling": backface.on}));
|
||||
}
|
||||
|
||||
// Cylindrical culls by the angle to its axis's outward direction alone
|
||||
if angle.is_none()
|
||||
&& let Some(merge) = sheet.angle_led(RowLead::Child(tr("Angle")), &mut backface.angle, BACKFACE_ANGLE_RANGE)
|
||||
{
|
||||
run(app, json!({"backfaceAngle": backface.angle, "merge": merge}));
|
||||
}
|
||||
if let Some(merge) = sheet.slider_led(RowLead::Child(tr("Hardness")), &mut backface.hardness, HARDNESS_RANGE, 2, "") {
|
||||
run(app, json!({"backfaceHardness": backface.hardness, "merge": merge}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The preview square beside the size (tiling, or the tile's length while Physical size) and offset, held to move `target` on the model; Rotation under it
|
||||
fn placement_rows(
|
||||
app: &mut TextureCraftApp,
|
||||
sheet: &mut PropertySheet<'_>,
|
||||
fill: &Fill,
|
||||
base: &Value,
|
||||
length: Option<[f32; 2]>,
|
||||
size: MeshSize,
|
||||
target: MoveOnModel,
|
||||
) {
|
||||
let tokens = Tokens::get(sheet.ui.ctx());
|
||||
let (tiling, rotation, offset, offset_key) = match &fill.projection {
|
||||
Projection::Uv { scale, rotation, offset } => (*scale, *rotation, *offset, "offset"),
|
||||
Projection::Triplanar { uv, .. }
|
||||
| Projection::Planar { uv, .. }
|
||||
| Projection::Spherical { uv, .. }
|
||||
| Projection::Cylindrical { uv, .. }
|
||||
| Projection::Warp { uv, .. } => (uv.tiling, uv.rotation, uv.offset, "uvOffset"),
|
||||
Projection::UvTile => return,
|
||||
};
|
||||
|
||||
let link_id = sheet.ui.make_persistent_id(("fill_tiling_link", fill_key(base)));
|
||||
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),
|
||||
None => tiling,
|
||||
};
|
||||
let shown = values;
|
||||
let (label, range, typed, decimals) = match length {
|
||||
Some(_) => (tr("Size (cm)"), SIZE_CM_TRACK, SIZE_CM_TYPED, 0),
|
||||
None => (tr("Tiling"), TILING_TRACK, TILING_TYPED, 2),
|
||||
};
|
||||
let size_edit = PreviewSize { label, values: &mut values, range, typed, decimals, linked: &mut linked };
|
||||
|
||||
let mut lower_offset = offset;
|
||||
let mut hardness = match &fill.projection {
|
||||
Projection::Triplanar { sharpness, .. } => Some(triplanar_hardness(*sharpness)),
|
||||
_ => None,
|
||||
};
|
||||
let lower = match hardness.as_mut() {
|
||||
Some(hardness) => PreviewLower::Slider { label: tr("Hardness"), value: hardness, range: HARDNESS_RANGE, decimals: 2 },
|
||||
None => PreviewLower::Offset { values: &mut lower_offset, range: OFFSET_TRACK, typed: OFFSET_TYPED },
|
||||
};
|
||||
let placement = Placement { tiling, rotation, offset };
|
||||
let bounds = app.viewport_mesh_bounds.get(&app.session.mesh);
|
||||
|
||||
// A warp shows its frame's size and turn as its gizmo leaves them
|
||||
let warp = match &fill.projection {
|
||||
Projection::Warp { corners, .. } => {
|
||||
let landed = frame_placement::folded(&fill.projection);
|
||||
let frame = landed.as_ref().and_then(Projection::frame);
|
||||
let diagonal = (bounds.1 - bounds.0).length().max(f32::EPSILON);
|
||||
let size = frame.map_or([1.0 / WARP_SPAN_FALLBACK; 2], |frame| frame.size.map(|side| side / diagonal));
|
||||
let turn = frame.and_then(frame_placement::upright_turn).unwrap_or(0.0);
|
||||
Some((*corners, size, turn))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let projection = &fill.projection;
|
||||
let owner = sheet.ui.scope_id();
|
||||
let picture = |painter: &Painter, rect: Rect| match warp {
|
||||
Some((corners, size, turn)) => warp_preview(painter, rect, corners, size, turn, placement, &tokens),
|
||||
None => {
|
||||
if projection_preview(painter, rect, projection, bounds, &tokens, owner).is_none() {
|
||||
window_preview(painter, rect, placement, &tokens);
|
||||
}
|
||||
}
|
||||
};
|
||||
let edit = sheet.preview_block(&picture, size_edit, lower);
|
||||
crate::move_on_model::pad(app, sheet, edit.square, target);
|
||||
|
||||
if linked != was_linked {
|
||||
sheet.ui.data_mut(|data| data.insert_temp(link_id, linked));
|
||||
}
|
||||
if let Some(merge) = edit.size
|
||||
&& values != shown
|
||||
{
|
||||
let tiling = match length {
|
||||
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}));
|
||||
}
|
||||
if let Some(merge) = edit.lower {
|
||||
let fields = match hardness {
|
||||
Some(hardness) => json!({"sharpness": triplanar_sharpness(hardness), "merge": merge}),
|
||||
None => json!({offset_key: lower_offset, "merge": merge}),
|
||||
};
|
||||
run_projection(app, base, fields);
|
||||
}
|
||||
|
||||
let mut degrees = rotation;
|
||||
if let Some(merge) = sheet.angle(tr("Rotation"), &mut degrees, ROTATION_RANGE) {
|
||||
run_projection(app, base, json!({"rotation": degrees, "merge": merge}));
|
||||
}
|
||||
}
|
||||
|
||||
/// One X, Y, Z row of the 3D projection settings
|
||||
fn xyz_fields(values: [f32; 3], speed: f32, decimals: usize, suffix: &'static str) -> [NumberField<'static>; 3] {
|
||||
std::array::from_fn(|axis| NumberField { tag: AXIS_NAMES[axis], tag_color: Some(AXIS_COLORS[axis]), value: values[axis], speed, decimals, suffix })
|
||||
}
|
||||
|
||||
/// The 3D projection settings: the projector's Offset, Rotation and Scale in X, Y and Z; a frame on the surface shows its own (where its centre is, how it is turned, how big it is), the same values its gizmo drags
|
||||
fn world_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, salt: FillKey) {
|
||||
let Some(projector) = projector_of(&fill.projection) else { return };
|
||||
if !sheet.band(tr("3D projection settings"), true, None, None).open {
|
||||
return;
|
||||
}
|
||||
|
||||
let edited = |fields: &[NumberField]| -> Vec<f32> { fields.iter().map(|field| field.value).collect() };
|
||||
|
||||
// A placed planar or a warp: the frame, its projector folded in
|
||||
if let Some(shown) = frame_placement::placement(&fill.projection, app.viewport_mesh_bounds.get(&app.session.mesh)) {
|
||||
let run = |app: &mut TextureCraftApp, key: &str, values: Vec<f32>, merge: bool| {
|
||||
app.run("layer.decal.set", with(base, json!({key: values, "merge": merge})));
|
||||
};
|
||||
let mut fields = xyz_fields(shown.offset, OFFSET_FIELD_SPEED, 2, "");
|
||||
if let Some((_, merge)) = sheet.number_fields(tr("Offset"), &mut fields, None, true) {
|
||||
run(app, "frameOffset", edited(&fields), merge);
|
||||
}
|
||||
let mut fields = xyz_fields(shown.rotation, ROTATION_FIELD_SPEED, 0, "°");
|
||||
if let Some((_, merge)) = sheet.number_fields(tr("Rotation"), &mut fields, None, true) {
|
||||
run(app, "frameRotation", edited(&fields), merge);
|
||||
}
|
||||
if let Some((scale, merge)) = scale_row(sheet, shown.scale, salt) {
|
||||
run(app, "frameScale", scale, merge);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let offset = match &fill.projection {
|
||||
Projection::Triplanar { offset, .. }
|
||||
| Projection::Planar { offset, .. }
|
||||
| Projection::Spherical { offset, .. }
|
||||
| Projection::Cylindrical { offset, .. } => Some(*offset),
|
||||
Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => None,
|
||||
};
|
||||
if let Some(offset) = offset {
|
||||
let mut fields = xyz_fields(offset, OFFSET_FIELD_SPEED, 2, "");
|
||||
if let Some((_, merge)) = sheet.number_fields(tr("Offset"), &mut fields, None, true) {
|
||||
run_projection(app, base, json!({"offset": edited(&fields), "merge": merge}));
|
||||
}
|
||||
}
|
||||
let mut fields = xyz_fields(projector.rotation, ROTATION_FIELD_SPEED, 0, "°");
|
||||
if let Some((_, merge)) = sheet.number_fields(tr("Rotation"), &mut fields, None, true) {
|
||||
run_projection(app, base, json!({"projectorRotation": edited(&fields), "merge": merge}));
|
||||
}
|
||||
if let Some((scale, merge)) = scale_row(sheet, projector.scale, salt) {
|
||||
run_projection(app, base, json!({"projectorScale": scale, "merge": merge}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The least size of the edited axis's scale a linked edit scales the others from by a factor
|
||||
const MIN_LINKED_SCALE_BASE: f32 = f32::EPSILON;
|
||||
|
||||
/// The Scale X, Y, Z row with its link: the new scale and whether it continues the drag's undo step; linked, one field scales all three by the same factor
|
||||
fn scale_row(sheet: &mut PropertySheet<'_>, scale: [f32; 3], salt: FillKey) -> Option<(Vec<f32>, bool)> {
|
||||
let link_id = sheet.ui.make_persistent_id(("projector_scale_link", salt));
|
||||
let [x, y, z] = scale;
|
||||
let mut linked = sheet.ui.data(|data| data.get_temp::<bool>(link_id)).unwrap_or(x == y && y == z);
|
||||
let was_linked = linked;
|
||||
let mut fields = xyz_fields(scale, SCALE_FIELD_SPEED, 2, "");
|
||||
let edit = sheet.number_fields(tr("Scale"), &mut fields, Some(&mut linked), false);
|
||||
if linked != was_linked {
|
||||
sheet.ui.data_mut(|data| data.insert_temp(link_id, linked));
|
||||
}
|
||||
let (axis, merge) = edit?;
|
||||
let mut values: Vec<f32> = fields.iter().map(|field| field.value).collect();
|
||||
if linked && let (Some(&value), Some(&before)) = (values.get(axis), scale.get(axis)) {
|
||||
// From a scale of about zero no factor reaches the new value: all three take it instead
|
||||
let factor = (before.abs() > MIN_LINKED_SCALE_BASE).then(|| value / before);
|
||||
values = scale.iter().map(|old| factor.map_or(value, |factor| old * factor)).collect();
|
||||
}
|
||||
Some((values, merge))
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
//! Pictures of what a fill's settings do: one per projection, filtering and UV wrap choice, the window preview and the ring of radial copies
|
||||
|
||||
use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, pos2, vec2};
|
||||
use texturecraft_engine::core::{FillSymmetry, Filtering, ShapeCrop, UvWrap};
|
||||
use texturecraft_engine::paint::FULL_TURN_DEGREES;
|
||||
|
||||
use crate::placement::Placement;
|
||||
use crate::projection_kind::ProjectionKind;
|
||||
use crate::projection_preview::{edge_markers, passed_sides};
|
||||
use crate::warp_checker::warp_checker;
|
||||
|
||||
use crate::theme::{Tokens, lerp_color};
|
||||
|
||||
/// The projection glyph's height, as a share of its picture's
|
||||
const PROJECTION_GLYPH_SHARE: f32 = 0.85;
|
||||
|
||||
/// The shape a projection wraps around, as an icon in the accent colour
|
||||
pub(crate) fn projection_picture(painter: &Painter, rect: Rect, kind: ProjectionKind, tokens: &Tokens) {
|
||||
use egui_phosphor::regular as icon;
|
||||
let glyph = match kind {
|
||||
ProjectionKind::UvTile | ProjectionKind::Uv => icon::SQUARE,
|
||||
ProjectionKind::Triplanar => icon::CUBE,
|
||||
ProjectionKind::Planar | ProjectionKind::Warp => icon::SELECTION,
|
||||
ProjectionKind::Spherical => icon::GLOBE,
|
||||
ProjectionKind::Cylindrical => icon::CYLINDER,
|
||||
};
|
||||
painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(rect.height() * PROJECTION_GLYPH_SHARE), tokens.accent);
|
||||
}
|
||||
|
||||
/// Cells across a magnified edge in the Filtering picture
|
||||
const EDGE_CELLS: usize = 6;
|
||||
|
||||
/// How steeply Bilinear Sharp ramps across the magnified edge: nearly a step
|
||||
const SHARP_EDGE_RAMP: f32 = 3.0;
|
||||
|
||||
/// How steeply Bilinear HQ ramps across the magnified edge: a soft blend
|
||||
const HQ_EDGE_RAMP: f32 = 1.2;
|
||||
|
||||
/// A magnified diagonal edge: smooth (HQ), crisp (Sharp) or stair-stepped (Nearest)
|
||||
pub(crate) fn filtering_picture(painter: &Painter, rect: Rect, filtering: Filtering, tokens: &Tokens) {
|
||||
let cell = rect.width() / EDGE_CELLS as f32;
|
||||
for i in 0..EDGE_CELLS {
|
||||
for j in 0..EDGE_CELLS {
|
||||
let across = (i as f32 - j as f32) / EDGE_CELLS as f32;
|
||||
let amount = match filtering {
|
||||
Filtering::Nearest => f32::from(u8::from(i >= j)),
|
||||
Filtering::BilinearSharp => (0.5 + across * SHARP_EDGE_RAMP).clamp(0.0, 1.0),
|
||||
Filtering::BilinearHq => (0.5 + across * HQ_EDGE_RAMP).clamp(0.0, 1.0),
|
||||
};
|
||||
let color = lerp_color(tokens.field, tokens.accent, amount);
|
||||
let min = pos2(rect.left() + i as f32 * cell, rect.top() + j as f32 * cell);
|
||||
painter.rect_filled(Rect::from_min_size(min, vec2(cell, cell)), 0, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cells of the UV Wrap picture's grid
|
||||
const WRAP_CELLS: usize = 3;
|
||||
|
||||
/// The gap kept around each Wrap tile, in points
|
||||
const WRAP_TILE_INSET: f32 = 0.75;
|
||||
|
||||
/// A repeated tile's accent strength beside the own tile's
|
||||
const WRAP_REPEAT_SHADE: f32 = 0.55;
|
||||
|
||||
/// A 3 × 3 grid: the middle tile is the image's own; filled tiles are where it repeats
|
||||
pub(crate) fn wrap_picture(painter: &Painter, rect: Rect, wrap: UvWrap, tokens: &Tokens) {
|
||||
let (across, down) = wrap.repeats();
|
||||
let cell = rect.width() / WRAP_CELLS as f32;
|
||||
let middle = WRAP_CELLS / 2;
|
||||
for i in 0..WRAP_CELLS {
|
||||
for j in 0..WRAP_CELLS {
|
||||
let own = i == middle && j == middle;
|
||||
let repeated = own || (across && j == middle) || (down && i == middle) || (across && down);
|
||||
let tile = Rect::from_min_size(pos2(rect.left() + i as f32 * cell, rect.top() + j as f32 * cell), vec2(cell, cell)).shrink(WRAP_TILE_INSET);
|
||||
if own {
|
||||
painter.rect_filled(tile, 1, tokens.accent);
|
||||
} else if repeated {
|
||||
painter.rect_filled(tile, 1, tokens.accent.gamma_multiply(WRAP_REPEAT_SHADE));
|
||||
} else {
|
||||
painter.rect_stroke(tile, 1, Stroke::new(LINE_WIDTH, tokens.separator), egui::StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Most tiles drawn across the window preview: beyond this the pattern is too fine to read
|
||||
const PREVIEW_MAX_TILES: f32 = 24.0;
|
||||
|
||||
/// The fewest tiles a preview shows, so a zero Tiling cannot divide by zero
|
||||
pub(crate) const PREVIEW_MIN_TILES: f32 = 1e-3;
|
||||
|
||||
/// Most tiles drawn along one direction of a lattice preview, whatever its map
|
||||
const PREVIEW_MAX_SPAN: i32 = 64;
|
||||
|
||||
/// The preview checker's dark cells, as a fraction of the way from `field` to `text`
|
||||
const PREVIEW_DARK: f32 = 0.18;
|
||||
|
||||
/// The preview checker's light cells, as a fraction of the way from `field` to `text`
|
||||
const PREVIEW_LIGHT: f32 = 0.55;
|
||||
|
||||
/// Where the mean of the checker's dark and light cells sits between them
|
||||
const CHECKER_MEAN: f32 = 0.5;
|
||||
|
||||
/// The width of every outline, border and ring line in these pictures
|
||||
const LINE_WIDTH: f32 = 1.0;
|
||||
|
||||
/// A lattice preview tile's checker cells, each half a tile wide, by the corner they start at in halves of a tile; even ones light
|
||||
const TILE_CELLS: [(u8, u8); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)];
|
||||
|
||||
/// A checker cell's side in tiles: two cells across a tile
|
||||
const CELL_SIDE: f32 = 0.5;
|
||||
|
||||
/// The window's centre (0..1) before any slide
|
||||
const WINDOW_MIDDLE: f32 = 0.5;
|
||||
|
||||
/// A flatter map shows nothing: the window could not be undone from it
|
||||
const MIN_MAP_DETERMINANT: f32 = 1e-9;
|
||||
|
||||
/// A window on the surface that never moves: a UV checker (2 × 2 cells per tile, accent tile borders) tiled, turned and slid as the fill is, the ring in the middle where Offset 0 puts the projection, the filled dot where its Offset carried that point
|
||||
pub(crate) fn window_preview(painter: &Painter, rect: Rect, placement: Placement, tokens: &Tokens) {
|
||||
let (columns, carried) = slid_window(placement);
|
||||
lattice_preview(painter, rect, (columns, placement.offset), true, tokens);
|
||||
let position = pos2(rect.left() + carried[0] * rect.width(), rect.top() + carried[1] * rect.height());
|
||||
let painter = painter.with_clip_rect(rect.intersect(painter.clip_rect()));
|
||||
crate::preview_dots::preview_dots(&painter, rect.center(), position, tokens);
|
||||
edge_markers(&painter, rect, passed_sides(std::iter::once(position), rect), tokens);
|
||||
}
|
||||
|
||||
/// The window preview's map, and where the Offset carried the window's middle (0..1): the checker slides with it, so a drag right moves both right
|
||||
fn slid_window(placement: Placement) -> ([[f32; 2]; 2], [f32; 2]) {
|
||||
let tiling = placement.tiling.map(|tiles| tiles.clamp(PREVIEW_MIN_TILES, PREVIEW_MAX_TILES));
|
||||
let (sin, cos) = placement.rotation.to_radians().sin_cos();
|
||||
|
||||
// Turn, scale, then offset: one step across the window moves (cos, sin) scaled in the texture
|
||||
let columns = [[cos * tiling[0], sin * tiling[1]], [-sin * tiling[0], cos * tiling[1]]];
|
||||
let [[a, b], [c, d]] = columns;
|
||||
let det = a * d - c * b;
|
||||
let [x, y] = placement.offset;
|
||||
|
||||
// The window step the Offset is worth: the map undone; the image moves against the Offset it samples at
|
||||
let moved = [(d * x - c * y) / det, (a * y - b * x) / det];
|
||||
let carried = if moved.iter().all(|value| value.is_finite()) { [WINDOW_MIDDLE - moved[0], WINDOW_MIDDLE - moved[1]] } else { [WINDOW_MIDDLE; 2] };
|
||||
(columns, carried)
|
||||
}
|
||||
|
||||
/// The window preview for any linear map: window point (u, v) shows the texture at `columns[0] · u + columns[1] · v + shift`; without `repeat` only tile 0..1
|
||||
pub(crate) fn lattice_preview(painter: &Painter, rect: Rect, (columns, shift): ([[f32; 2]; 2], [f32; 2]), repeat: bool, tokens: &Tokens) {
|
||||
let painter = painter.with_clip_rect(rect);
|
||||
painter.rect_filled(rect, 0, tokens.field);
|
||||
let [[a, b], [c, d]] = columns;
|
||||
let det = a * d - c * b;
|
||||
if det.abs() > MIN_MAP_DETERMINANT && det.is_finite() && shift.iter().all(|value| value.is_finite()) {
|
||||
// Texture coordinates → the window: undo the shift, then the map
|
||||
let to_window = |t: [f32; 2]| -> Pos2 {
|
||||
let (x, y) = (t[0] - shift[0], t[1] - shift[1]);
|
||||
let (u, v) = ((d * x - c * y) / det, (a * y - b * x) / det);
|
||||
pos2(rect.left() + u * rect.width(), rect.top() + v * rect.height())
|
||||
};
|
||||
let to_texture = |u: f32, v: f32| -> [f32; 2] { [a * u + c * v + shift[0], b * u + d * v + shift[1]] };
|
||||
let corners = [to_texture(0.0, 0.0), to_texture(1.0, 0.0), to_texture(0.0, 1.0), to_texture(1.0, 1.0)];
|
||||
let low = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::INFINITY, f32::min).floor() as i32;
|
||||
let high = |axis: usize| corners.iter().map(|corner| corner[axis]).fold(f32::NEG_INFINITY, f32::max).ceil() as i32;
|
||||
let span = |first: i32, last: i32| if repeat { first..last.min(first.saturating_add(PREVIEW_MAX_SPAN)) } else { first.max(0)..last.min(1) };
|
||||
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);
|
||||
|
||||
// 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));
|
||||
}
|
||||
for tile_x in span(low(0), high(0)) {
|
||||
for tile_y in span(low(1), high(1)) {
|
||||
for (cell_x, cell_y) in TILE_CELLS {
|
||||
let (x0, y0) = (tile_x as f32 + f32::from(cell_x) * CELL_SIDE, tile_y as f32 + f32::from(cell_y) * CELL_SIDE);
|
||||
let corners = [[x0, y0], [x0 + CELL_SIDE, y0], [x0 + CELL_SIDE, y0 + CELL_SIDE], [x0, y0 + CELL_SIDE]].map(to_window);
|
||||
let color = if (cell_x + cell_y) % 2 == 0 { light } else { dark };
|
||||
painter.add(Shape::convex_polygon(corners.to_vec(), color, Stroke::NONE));
|
||||
}
|
||||
let (x, y) = (tile_x as f32, tile_y as f32);
|
||||
painter.add(Shape::closed_line([[x, y], [x + 1.0, y], [x + 1.0, y + 1.0], [x, y + 1.0]].map(to_window).to_vec(), border));
|
||||
}
|
||||
}
|
||||
}
|
||||
painter.rect_stroke(rect, 0, Stroke::new(LINE_WIDTH, tokens.field_border), egui::StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// How far the darker accent sits from the accent towards black
|
||||
const ACCENT_SHADE: f32 = 0.36;
|
||||
|
||||
/// The darker accent pictures fill with, beside the accent itself
|
||||
fn accent_shade(tokens: &Tokens) -> Color32 {
|
||||
lerp_color(tokens.accent, Color32::BLACK, ACCENT_SHADE)
|
||||
}
|
||||
|
||||
/// The margin inside a small setting picture, in points
|
||||
const PICTURE_INSET: f32 = 3.0;
|
||||
|
||||
/// Depth culling's hidden part, as a share of its picture's height
|
||||
const DEPTH_UNDER_SHARE: f32 = 0.45;
|
||||
|
||||
/// The arrow glyph's size in the Depth picture
|
||||
const DEPTH_ARROW_SIZE: f32 = 9.0;
|
||||
|
||||
/// The Angle picture's radius, as a share of its width
|
||||
const ANGLE_RADIUS_SHARE: f32 = 0.45;
|
||||
|
||||
/// The warp preview's outline width
|
||||
const WARP_EDGE_WIDTH: f32 = 1.5;
|
||||
|
||||
/// Corner radius of the crop picture's shape
|
||||
const CROP_SHAPE_CORNER_RADIUS: u8 = 3;
|
||||
|
||||
/// Corner radius of a fill that reaches a picture's edges
|
||||
const PICTURE_CORNER_RADIUS: u8 = 2;
|
||||
|
||||
/// Where the depth picture's surface sits, as a share of its height from the top
|
||||
const DEPTH_SURFACE_SHARE: f32 = 0.25;
|
||||
|
||||
/// Points what lies under the surface reaches past its share, so it still reads at small sizes
|
||||
const DEPTH_UNDER_EXTRA: f32 = 2.0;
|
||||
|
||||
/// How far the backface picture's face stays inside the picture's sides
|
||||
const BACKFACE_SIDE_INSET: f32 = 2.0;
|
||||
|
||||
/// Shape crop: the projection inside its shape only, or past it too
|
||||
pub(crate) fn crop_picture(painter: &Painter, rect: Rect, crop: ShapeCrop, tokens: &Tokens) {
|
||||
let inner = rect.shrink(PICTURE_INSET);
|
||||
match crop {
|
||||
ShapeCrop::Cropped => {
|
||||
painter.rect_filled(inner, CROP_SHAPE_CORNER_RADIUS, accent_shade(tokens));
|
||||
}
|
||||
ShapeCrop::ExtendsOutside => {
|
||||
painter.rect_filled(rect, PICTURE_CORNER_RADIUS, accent_shade(tokens));
|
||||
}
|
||||
}
|
||||
painter.rect_stroke(inner, CROP_SHAPE_CORNER_RADIUS, Stroke::new(LINE_WIDTH, tokens.text), egui::StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// Depth culling, seen from the side: the surface the projection lands on and what lies under it
|
||||
pub(crate) fn depth_picture(painter: &Painter, rect: Rect, tokens: &Tokens) {
|
||||
let top = rect.top() + rect.height() * DEPTH_SURFACE_SHARE;
|
||||
let under = Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), top + rect.height() * DEPTH_UNDER_SHARE + DEPTH_UNDER_EXTRA));
|
||||
painter.rect_filled(under, PICTURE_CORNER_RADIUS, accent_shade(tokens));
|
||||
painter.line_segment([pos2(rect.left(), top), pos2(rect.right(), top)], Stroke::new(LINE_WIDTH, tokens.text));
|
||||
painter.text(
|
||||
pos2(rect.center().x, rect.top() + PICTURE_INSET),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
egui_phosphor::regular::ARROW_DOWN,
|
||||
egui::FontId::proportional(DEPTH_ARROW_SIZE),
|
||||
tokens.accent,
|
||||
);
|
||||
}
|
||||
|
||||
/// Backface culling: a face turned away, darker while culled
|
||||
pub(crate) fn backface_picture(painter: &Painter, rect: Rect, on: bool, tokens: &Tokens) {
|
||||
let (left, apex, right) = (
|
||||
pos2(rect.left() + BACKFACE_SIDE_INSET, rect.bottom() - PICTURE_INSET),
|
||||
pos2(rect.center().x, rect.top() + PICTURE_INSET),
|
||||
pos2(rect.right() - BACKFACE_SIDE_INSET, rect.bottom() - PICTURE_INSET),
|
||||
);
|
||||
painter.add(Shape::convex_polygon(vec![left, apex, right], if on { accent_shade(tokens) } else { tokens.accent }, Stroke::NONE));
|
||||
painter.line_segment([apex, right], Stroke::new(LINE_WIDTH, tokens.text));
|
||||
}
|
||||
|
||||
/// Points around the Angle picture's arc per full turn
|
||||
const ARC_POINTS: usize = 48;
|
||||
|
||||
/// The angle and ring pictures start at the top: a quarter turn back from +x (egui's y points down), in turns
|
||||
const TOP_START_TURNS: f32 = 0.25;
|
||||
|
||||
/// A cylindrical projection's Angle seen from above: the slice of a turn one repeat spans
|
||||
pub(crate) fn angle_picture(painter: &Painter, rect: Rect, degrees: f32, tokens: &Tokens) {
|
||||
let center = rect.center();
|
||||
let radius = rect.width() * ANGLE_RADIUS_SHARE;
|
||||
let sweep = degrees.clamp(0.0, FULL_TURN_DEGREES) / FULL_TURN_DEGREES;
|
||||
if sweep >= 1.0 {
|
||||
painter.circle_filled(center, radius, tokens.accent);
|
||||
} else {
|
||||
let steps = ((ARC_POINTS as f32 * sweep).ceil() as usize).max(1);
|
||||
let mut points = vec![center];
|
||||
for step in 0..=steps {
|
||||
let turn = (step as f32 / steps as f32 * sweep - TOP_START_TURNS) * std::f32::consts::TAU;
|
||||
points.push(pos2(center.x + radius * turn.cos(), center.y + radius * turn.sin()));
|
||||
}
|
||||
|
||||
// A slice wider than half a turn is not convex: fill it as a fan from the centre
|
||||
for pair in points[1..].windows(2) {
|
||||
painter.add(Shape::convex_polygon(vec![center, pair[0], pair[1]], tokens.accent, Stroke::NONE));
|
||||
}
|
||||
}
|
||||
painter.circle_stroke(center, radius, Stroke::new(LINE_WIDTH, tokens.button_border));
|
||||
}
|
||||
|
||||
/// How much of the preview an unpulled frame spans per mesh diagonal of its side (a new warp's frame round a ball spans about 0.62)
|
||||
const WARP_SPAN_PER_DIAGONAL: f32 = 1.07;
|
||||
/// The least and most of the preview a frame's side spans
|
||||
const WARP_SPAN_RANGE: std::ops::RangeInclusive<f32> = 0.05..=0.95;
|
||||
|
||||
/// Radius of a warp preview's corner handle
|
||||
const WARP_HANDLE_RADIUS: f32 = 3.5;
|
||||
|
||||
/// A warp's frame with its corners where they are pulled, the checker bending with them and laid as `placement` lays the image (tiling, rotation, offset); `size` is the frame's width and height in mesh diagonals, `turn` its turn round its normal (degrees), so resizing or turning the frame shows
|
||||
pub(crate) fn warp_preview(painter: &Painter, rect: Rect, corners: [[f32; 2]; 4], size: [f32; 2], turn: f32, placement: Placement, tokens: &Tokens) {
|
||||
let painter = painter.with_clip_rect(rect);
|
||||
painter.rect_filled(rect, 0, tokens.field);
|
||||
let span = size.map(|side| (side * WARP_SPAN_PER_DIAGONAL).clamp(*WARP_SPAN_RANGE.start(), *WARP_SPAN_RANGE.end()));
|
||||
let (sin, cos) = turn.to_radians().sin_cos();
|
||||
|
||||
// Across and up in frame sizes from its centre -> turned -> the square
|
||||
let [top_left, top_right, bottom_right, bottom_left] = corners.map(|[x, y]| {
|
||||
let (x, y) = (x * span[0], y * span[1]);
|
||||
let (x, y) = (x * cos - y * sin, x * sin + y * cos);
|
||||
pos2(rect.center().x + x * rect.width(), rect.center().y - y * rect.height())
|
||||
});
|
||||
let (dark, light) = (lerp_color(tokens.field, tokens.text, PREVIEW_DARK), lerp_color(tokens.field, tokens.text, PREVIEW_LIGHT));
|
||||
for (outline, lit) in warp_checker([top_left, top_right, bottom_right, bottom_left], placement) {
|
||||
painter.add(Shape::convex_polygon(outline, if lit { light } else { dark }, Stroke::NONE));
|
||||
}
|
||||
let edge = [top_left, top_right, bottom_right, bottom_left];
|
||||
painter.add(Shape::closed_line(edge.to_vec(), Stroke::new(WARP_EDGE_WIDTH, tokens.accent)));
|
||||
for corner in edge {
|
||||
painter.circle(corner, WARP_HANDLE_RADIUS, tokens.text, Stroke::new(LINE_WIDTH, tokens.accent));
|
||||
}
|
||||
painter.rect_stroke(rect, 0, Stroke::new(LINE_WIDTH, tokens.field_border), egui::StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// The ring's radius, in the picture's widths
|
||||
const RING_RADIUS: f32 = 0.34;
|
||||
|
||||
/// The radius of the axis's dot at the ring's centre
|
||||
const RING_AXIS_DOT: f32 = 2.0;
|
||||
|
||||
/// The radius of each copy's dot on the ring
|
||||
const RING_COPY_DOT: f32 = 3.5;
|
||||
|
||||
/// The straight pieces the ring is drawn with
|
||||
const RING_SEGMENTS: usize = 64;
|
||||
|
||||
/// Radial copies seen along their axis: the axis at the centre (its colour), the original (white) at the top and the other copies (accent) round the ring, spaced as the engine spaces them
|
||||
pub(crate) fn ring_picture(painter: &Painter, rect: Rect, symmetry: &FillSymmetry, axis_color: Color32, tokens: &Tokens) {
|
||||
painter.rect_filled(rect, 0, tokens.field);
|
||||
let center = rect.center();
|
||||
let radius = rect.width() * RING_RADIUS;
|
||||
let at = |degrees: f32| {
|
||||
let turn = (degrees - TOP_START_TURNS * FULL_TURN_DEGREES).to_radians();
|
||||
center + vec2(turn.cos(), turn.sin()) * radius
|
||||
};
|
||||
|
||||
// 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)));
|
||||
painter.circle_filled(center, RING_AXIS_DOT, axis_color);
|
||||
for (k, degrees) in copy_angles(symmetry).enumerate() {
|
||||
let color = if k == 0 { tokens.text } else { tokens.accent };
|
||||
painter.circle_filled(at(degrees), RING_COPY_DOT, color);
|
||||
}
|
||||
}
|
||||
|
||||
/// The degrees each radial copy of `symmetry` turns, the original's 0 first, from the engine's count and spacing
|
||||
fn copy_angles(symmetry: &FillSymmetry) -> impl Iterator<Item = f32> {
|
||||
let step = symmetry.step();
|
||||
(0..symmetry.copies()).map(move |k| k as f32 * step)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_engine::core::SymmetryKind;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A hand-edited span past a full turn spaces the ring's dots as the engine spaces the copies: six copies 60° apart, none on top of another
|
||||
#[test]
|
||||
fn the_ring_spaces_its_copies_as_the_engine_does() {
|
||||
let symmetry = FillSymmetry { on: true, kind: SymmetryKind::Radial, count: 6, span: 720.0, ..FillSymmetry::OFF };
|
||||
|
||||
let angles: Vec<f32> = copy_angles(&symmetry).collect();
|
||||
|
||||
assert_eq!(angles, [0.0, 60.0, 120.0, 180.0, 240.0, 300.0]);
|
||||
}
|
||||
|
||||
/// The UV view stands still: the checker slides with the Offset as on the model, and the filled dot (the window's middle, carried) slides with it, the way a drag moves them
|
||||
#[test]
|
||||
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]);
|
||||
let (columns, dot) = slid_window(slid);
|
||||
assert_eq!(columns, still, "the view never zooms or turns for the Offset");
|
||||
|
||||
// A pad drag right lowers the Offset: the dot goes right, an eighth of the window along the turned U
|
||||
let expected = [0.5 + 0.125 * 30f32.to_radians().cos(), 0.5 - 0.125 * 30f32.to_radians().sin()];
|
||||
assert!((dot[0] - expected[0]).abs() < 1e-5 && (dot[1] - expected[1]).abs() < 1e-5, "{dot:?} vs {expected:?}");
|
||||
|
||||
// The checker point under the middle at Offset 0 shows under the dot now
|
||||
let [[a, b], [c, d]] = columns;
|
||||
let texture_at = |[u, v]: [f32; 2], offset: [f32; 2]| [a * u + c * v + offset[0], b * u + d * v + offset[1]];
|
||||
let (before, after) = (texture_at([0.5, 0.5], [0.0, 0.0]), texture_at(dot, slid.offset));
|
||||
assert!((before[0] - after[0]).abs() < 1e-5 && (before[1] - after[1]).abs() < 1e-5, "{before:?} vs {after:?}");
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ const UNIFORM_TILE_GRAY: f32 = 0.8;
|
||||
const UNIFORM_SWATCH_NAME: &str = "swatch:uniform";
|
||||
/// One swatch for every frame, so its preview stays cached
|
||||
static UNIFORM_SWATCH: LazyLock<Arc<ImageRes>> =
|
||||
LazyLock::new(|| Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, 1.0]], srgb: false }));
|
||||
LazyLock::new(|| Arc::new(ImageRes::new(1, 1, vec![[UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, 1.0]], false)));
|
||||
|
||||
/// The slot of `fill`, which reads `source`; `anchors` are the anchor points below its layer and `caption` names what it fills
|
||||
pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, fill: &FillSourceTarget, source: &Source, (anchors, caption): (&[(LayerId, String)], &str)) {
|
||||
@@ -283,7 +283,7 @@ mod tests {
|
||||
for index in 0..IMAGE_COUNT {
|
||||
let name = format!("picker-image-{index:03}.png");
|
||||
session.doc.resources.insert(name.clone(), Arc::new(vec![0]));
|
||||
session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false }));
|
||||
session.images.insert(name, Arc::new(ImageRes::new(64, 64, vec![[0.5; 4]; 64 * 64], false)));
|
||||
}
|
||||
let mut harness = picker_harness(session, Vec::new());
|
||||
|
||||
@@ -320,7 +320,7 @@ mod tests {
|
||||
let mut session = texturecraft_engine::sample_session(128, 64).unwrap();
|
||||
for index in 0..128 {
|
||||
let name = format!("picker-{index:03}.png");
|
||||
session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false }));
|
||||
session.images.insert(name, Arc::new(ImageRes::new(64, 64, vec![[0.5; 4]; 64 * 64], false)));
|
||||
}
|
||||
let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default());
|
||||
let mut app = TextureCraftApp::new(&creation_context, session);
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! A fill's Symmetry section: mirrored or radial copies of its 3D projection
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use egui::{Painter, Rect};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{FillSymmetry, Projection, Sampling, SymmetryKind};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::fill_panel::run_projection;
|
||||
use crate::fill_pictures::ring_picture;
|
||||
use crate::i18n::{n_, tr};
|
||||
use crate::property_sheet::{PropertySheet, StackSlider};
|
||||
use crate::theme::{AXIS_COLORS, AXIS_NAMES, Tokens};
|
||||
use crate::widgets::press_edit;
|
||||
|
||||
/// What the Axis position track spans, in mesh radii from the mesh's centre
|
||||
const POSITION_RANGE: RangeInclusive<f32> = -FillSymmetry::REACH..=FillSymmetry::REACH;
|
||||
|
||||
/// What the Count track spans; a typed count reaches the engine's fewest and most copies, as the symmetry popup's Count does
|
||||
const COUNT_TRACK: RangeInclusive<f32> = *FillSymmetry::COUNTS.start() as f32..=16.0;
|
||||
|
||||
/// What a typed Count may reach
|
||||
const COUNT_TYPED: RangeInclusive<f32> = *FillSymmetry::COUNTS.start() as f32..=*FillSymmetry::COUNTS.end() as f32;
|
||||
|
||||
/// 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;
|
||||
let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields);
|
||||
|
||||
if !projection.takes_symmetry() {
|
||||
let reason = match projection {
|
||||
Projection::UvTile => tr("Not available with Fill (Match per UV Tile)"),
|
||||
_ => tr("Not available with UV projection"),
|
||||
};
|
||||
|
||||
sheet.section_unavailable(tr("Symmetry"), reason);
|
||||
return;
|
||||
}
|
||||
|
||||
let switch = sheet.section_switch(tr("Symmetry"), symmetry.on);
|
||||
if switch.clicked() {
|
||||
run(app, json!({"symmetry": !symmetry.on}));
|
||||
}
|
||||
if !symmetry.on {
|
||||
return;
|
||||
}
|
||||
|
||||
let (picked, _) = sheet.dropdown(tr("Type"), symmetry.kind, &SymmetryKind::ALL, |kind| tr(kind_label(kind)).to_owned(), None);
|
||||
if let Some(kind) = picked {
|
||||
run(app, json!({"symmetryType": kind.id()}));
|
||||
}
|
||||
|
||||
let axis = symmetry.axis_index();
|
||||
if let Some(picked) = sheet.switch_tinted(tr("Axis"), &AXIS_NAMES, axis, &AXIS_COLORS) {
|
||||
run(app, json!({"symmetryAxis": picked}));
|
||||
}
|
||||
|
||||
if symmetry.kind == SymmetryKind::Radial {
|
||||
radial_rows(app, sheet, &symmetry, base);
|
||||
}
|
||||
|
||||
let mut flip = symmetry.flip;
|
||||
if sheet.toggle_pair(tr("Flip copy"), ["U", "V"], &mut flip).is_some() {
|
||||
run(app, json!({"flipCopy": flip}));
|
||||
}
|
||||
|
||||
// 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(merge) = sheet.lettered_sliders(tr("Axis position"), &mut parts, POSITION_RANGE, 2) {
|
||||
let mut position = symmetry.position;
|
||||
for (axis, (_, _, value)) in moving.into_iter().zip(parts) {
|
||||
position[axis] = value;
|
||||
}
|
||||
|
||||
run(app, json!({"axisPosition": position, "merge": merge}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Count and Angle span beside the ring of copies, seen along the axis
|
||||
fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetry: &FillSymmetry, base: &Value) {
|
||||
let tokens = Tokens::get(sheet.ui.ctx());
|
||||
let axis_color = AXIS_COLORS[symmetry.axis_index()];
|
||||
let picture = |painter: &Painter, rect: Rect| ring_picture(painter, rect, symmetry, axis_color, &tokens);
|
||||
let count = symmetry.copies();
|
||||
let (mut count_value, mut span_value) = (count as f32, symmetry.span);
|
||||
|
||||
let mut sliders = [
|
||||
StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "" },
|
||||
StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°" },
|
||||
];
|
||||
|
||||
let [count_edit, span_edit] = sheet.picture_sliders(&picture, &mut sliders);
|
||||
|
||||
// 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");
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Type dropdown's name for `kind`
|
||||
fn kind_label(kind: SymmetryKind) -> &'static str {
|
||||
match kind {
|
||||
SymmetryKind::Mirror => n_("Mirror symmetry"),
|
||||
SymmetryKind::Radial => n_("Radial symmetry"),
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,29 @@
|
||||
/// What a drag on the frame does
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum FrameGrab {
|
||||
/// The centre square: slide the frame across its own plane
|
||||
Slide,
|
||||
/// Along the frame's across (0), up (1) or out (2) direction
|
||||
Axis(usize),
|
||||
/// A planar's corner: scale it about its centre
|
||||
Scale,
|
||||
/// A planar's edge dot (top, right, bottom, left): stretch that side
|
||||
Side(usize),
|
||||
/// A warp's corner (top left, top right, bottom right, bottom left): pull it
|
||||
Corner(usize),
|
||||
/// The ring: turn it round its normal
|
||||
Turn,
|
||||
}
|
||||
|
||||
impl FrameGrab {
|
||||
pub(super) fn cursor(self, dragging: bool) -> egui::CursorIcon {
|
||||
match self {
|
||||
FrameGrab::Slide if dragging => egui::CursorIcon::Grabbing,
|
||||
FrameGrab::Slide => egui::CursorIcon::Grab,
|
||||
FrameGrab::Axis(_) | FrameGrab::Corner(_) | FrameGrab::Turn => egui::CursorIcon::Move,
|
||||
FrameGrab::Scale => egui::CursorIcon::ResizeNwSe,
|
||||
FrameGrab::Side(side) if side % 2 == 0 => egui::CursorIcon::ResizeVertical,
|
||||
FrameGrab::Side(_) => egui::CursorIcon::ResizeHorizontal,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -615,6 +615,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();
|
||||
assert!(targets.len() > 1);
|
||||
@@ -640,7 +641,7 @@ mod tests {
|
||||
assert!(gpu.sync(&mut s, None, None, 0, 0.0).image_aux.is_empty());
|
||||
assert!(gpu.aux_image.is_none());
|
||||
|
||||
let replacement = Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]], srgb: true });
|
||||
let replacement = Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true));
|
||||
s.images.insert(name.clone(), replacement);
|
||||
execute(&mut s, "viewport.view", &json!({"mode": "image", "image": name})).unwrap();
|
||||
let updated = gpu.sync(&mut s, Some(AuxView::Image), None, 0, 0.0);
|
||||
|
||||
@@ -19,12 +19,17 @@ const MIN_BAR_WIDTH: f32 = KNOB_RADIUS * 4.0;
|
||||
pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option<bool> {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let (field, typed) = value_header(ui, label, value, 0.0..=1.0, 2);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
let mut edit = typed;
|
||||
let button_width = ui.spacing().interact_size.y;
|
||||
|
||||
// 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);
|
||||
let (rect, response) = ui.allocate_exact_size(vec2(width, KNOB_RADIUS * 2.0 + KNOB_STROKE * 2.0), Sense::click_and_drag());
|
||||
let bar = Rect::from_center_size(rect.center(), vec2(rect.width() - KNOB_RADIUS * 2.0, BAR_HEIGHT));
|
||||
|
||||
if response.is_pointer_button_down_on() {
|
||||
// A grab of the bar ends typing, so the field shows the dragged value
|
||||
ui.data_mut(|data| data.remove_temp::<String>(field));
|
||||
@@ -51,6 +56,7 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option<b
|
||||
*value = 1.0 - *value;
|
||||
edit = Some(false);
|
||||
}
|
||||
|
||||
edit
|
||||
})
|
||||
.inner
|
||||
|
||||
@@ -54,6 +54,27 @@ pub static LANGUAGES: [Language; COUNT] = [
|
||||
|
||||
static CURRENT: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// How a fill reads its images, as the Filtering combo names it
|
||||
pub(crate) fn filtering_label(filtering: texturecraft_engine::core::Filtering) -> &'static str {
|
||||
use texturecraft_engine::core::Filtering;
|
||||
match filtering {
|
||||
Filtering::BilinearHq => n_("Bilinear | HQ"),
|
||||
Filtering::BilinearSharp => n_("Bilinear | Sharp"),
|
||||
Filtering::Nearest => n_("Nearest"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a fill repeats past its tile, as the UV Wrap combo names it
|
||||
pub(crate) fn wrap_label(wrap: texturecraft_engine::core::UvWrap) -> &'static str {
|
||||
use texturecraft_engine::core::UvWrap;
|
||||
match wrap {
|
||||
UvWrap::None => n_("None"),
|
||||
UvWrap::RepeatHorizontally => n_("Repeat horizontally"),
|
||||
UvWrap::RepeatVertically => n_("Repeat vertically"),
|
||||
UvWrap::Repeat => n_("Repeat"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Display labels belong to the UI; the model exposes only map identities
|
||||
pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'static str {
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
|
||||
+66
-22
@@ -28,10 +28,14 @@ pub mod export_templates;
|
||||
mod export_window;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod file_dialogs;
|
||||
mod fill_panel;
|
||||
mod fill_pictures;
|
||||
mod fill_source_slot;
|
||||
mod fill_source_target;
|
||||
mod fill_symmetry_panel;
|
||||
mod filter_slot;
|
||||
pub mod fonts;
|
||||
mod frame_gizmo;
|
||||
mod generator_panel;
|
||||
pub mod gpu;
|
||||
mod gray_slider;
|
||||
@@ -54,6 +58,8 @@ mod mask_preview_image;
|
||||
mod material_preview_image;
|
||||
pub mod menus;
|
||||
mod mesh_export_options;
|
||||
mod move_hold;
|
||||
pub mod move_on_model;
|
||||
mod name_error;
|
||||
mod named_layout;
|
||||
pub mod named_layouts;
|
||||
@@ -63,11 +69,16 @@ mod nav_view;
|
||||
pub mod new_project_advanced;
|
||||
mod orb_shape;
|
||||
pub mod parity;
|
||||
mod past_end;
|
||||
mod path_hit;
|
||||
mod path_surface_cache;
|
||||
mod pattern_panel;
|
||||
mod pattern_target;
|
||||
pub mod pbr_import;
|
||||
mod placement;
|
||||
mod pointer_lock;
|
||||
mod popup_drag;
|
||||
mod preview_dots;
|
||||
mod preview_image;
|
||||
mod preview_request;
|
||||
mod preview_worker;
|
||||
@@ -75,7 +86,12 @@ pub mod profile;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod project_config;
|
||||
pub mod project_form;
|
||||
mod projection_gizmo;
|
||||
mod projection_kind;
|
||||
mod projection_preview;
|
||||
mod projector_outline;
|
||||
pub mod properties_popup;
|
||||
mod property_sheet;
|
||||
mod query_field;
|
||||
mod rail_popup;
|
||||
pub mod render_mode;
|
||||
@@ -86,6 +102,7 @@ mod resource_picker_choice;
|
||||
mod resource_picker_item;
|
||||
mod resource_picker_tab;
|
||||
mod resource_picker_tile;
|
||||
mod round_gizmo;
|
||||
mod running_bake;
|
||||
pub mod saved_search;
|
||||
mod screen_color_pick;
|
||||
@@ -120,6 +137,8 @@ mod uv_tile_grid;
|
||||
mod uv_view_map;
|
||||
mod view_mode_picker;
|
||||
pub mod viewport;
|
||||
mod viewport_mesh_bounds;
|
||||
mod warp_checker;
|
||||
pub mod web_files;
|
||||
pub mod widgets;
|
||||
pub mod windows;
|
||||
@@ -191,6 +210,7 @@ pub struct Toast {
|
||||
|
||||
pub struct TextureCraftApp {
|
||||
pub session: Session,
|
||||
viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds,
|
||||
/// A smooth move to a saved camera in progress.
|
||||
camera_glide: Option<CameraGlide>,
|
||||
/// Yaw and pitch an Alt+Shift drag has reached before snapping to 90° steps (see `viewport`).
|
||||
@@ -234,10 +254,11 @@ pub struct TextureCraftApp {
|
||||
pub last_paint_point: Option<uv_paint_point::SurfacePaintPoint>,
|
||||
/// The last finished 2D stroke's endpoint, scoped to its mesh and texture set for Shift+click lines
|
||||
pub last_paint_uv: Option<uv_paint_point::UvPaintPoint>,
|
||||
/// The decal layer the next click in the 3D view places.
|
||||
pub placing_decal: Option<texturecraft_engine::core::LayerId>,
|
||||
/// The fill whose Move on model button is held down: dragging slides its projection, Shift or the right button turns it, the wheel scales it
|
||||
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)
|
||||
@@ -295,6 +316,7 @@ 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 {
|
||||
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"))]
|
||||
@@ -319,6 +341,7 @@ impl TextureCraftApp {
|
||||
uv_rotation_snap: None,
|
||||
uv_view_reset: false,
|
||||
session,
|
||||
viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds::default(),
|
||||
ui,
|
||||
ui_store,
|
||||
gpu,
|
||||
@@ -342,8 +365,9 @@ impl TextureCraftApp {
|
||||
render: render_mode::RenderView::default(),
|
||||
last_paint_point: None,
|
||||
last_paint_uv: None,
|
||||
placing_decal: None,
|
||||
moving_on_model: None,
|
||||
properties_popup: None,
|
||||
properties_scroll: property_sheet::PropertiesScroll::default(),
|
||||
picking_id_color: None,
|
||||
picking_symmetry_plane: false,
|
||||
render_state: cc.wgpu_render_state.clone(),
|
||||
@@ -923,6 +947,13 @@ struct CameraGlide {
|
||||
|
||||
const GLIDE_SECONDS: f64 = 0.35;
|
||||
|
||||
/// The share of the running frame rate and frame time averages each frame keeps (an average over about ten frames)
|
||||
const FRAME_AVERAGE_KEEP: f32 = 0.9;
|
||||
/// The interface scale applied: wider than the Settings slider, so a scale set elsewhere still applies within reason
|
||||
const UI_SCALE_APPLIED: std::ops::RangeInclusive<f32> = 0.5..=3.0;
|
||||
/// Zoom factors closer than this are the same zoom (float noise), so the zoom is not set again each frame
|
||||
const SAME_ZOOM_TOLERANCE: f32 = 1e-3;
|
||||
|
||||
impl TextureCraftApp {
|
||||
/// Advance the camera glide by one frame.
|
||||
fn step_camera_glide(&mut self, ctx: &egui::Context) {
|
||||
@@ -951,6 +982,11 @@ impl TextureCraftApp {
|
||||
}
|
||||
|
||||
impl eframe::App for TextureCraftApp {
|
||||
/// A drag that holds the pointer reads the pointer's moves as moves of a pointer no screen edge stops
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
pointer_lock::rewrite(ctx, raw_input);
|
||||
}
|
||||
|
||||
/// The browser never tells eframe the page is closing, so save often there.
|
||||
fn auto_save_interval(&self) -> std::time::Duration {
|
||||
std::time::Duration::from_secs(if cfg!(target_arch = "wasm32") { 5 } else { 30 })
|
||||
@@ -964,13 +1000,14 @@ impl eframe::App for TextureCraftApp {
|
||||
}
|
||||
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
let t0 = now_ms();
|
||||
let now = ctx.input(|i| i.time);
|
||||
let dt = (now - self.last_time) as f32;
|
||||
if dt > 0.0 {
|
||||
self.fps = self.fps * 0.9 + (1.0 / dt) * 0.1;
|
||||
let logic_start_ms = now_ms();
|
||||
let now = ctx.input(|input| input.time);
|
||||
let frame_seconds = (now - self.last_time) as f32;
|
||||
if frame_seconds > 0.0 {
|
||||
self.fps = self.fps * FRAME_AVERAGE_KEEP + (1.0 / frame_seconds) * (1.0 - FRAME_AVERAGE_KEEP);
|
||||
}
|
||||
self.last_time = now;
|
||||
|
||||
let style = (self.ui.prefs.brightness, self.ui.prefs.accent);
|
||||
if self.styled != Some(style) {
|
||||
theme::apply(ctx, style.0, style.1);
|
||||
@@ -978,16 +1015,17 @@ impl eframe::App for TextureCraftApp {
|
||||
}
|
||||
self.step_camera_glide(ctx);
|
||||
self.ui.prefs.apply_resource_limits();
|
||||
|
||||
control::poll(self, ctx);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.run_file_dialog_answers();
|
||||
web_files::poll(self);
|
||||
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
|
||||
let dropped = ctx.input(|input| input.raw.dropped_files.clone());
|
||||
|
||||
// A folder, a zip or several PBR maps dropped together open the PBR import dialog
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let consumed = if !dropped.is_empty() {
|
||||
let paths: Vec<std::path::PathBuf> = dropped.iter().map(|f| f.path().to_path_buf()).collect();
|
||||
let paths: Vec<std::path::PathBuf> = dropped.iter().map(|file| file.path().to_path_buf()).collect();
|
||||
pbr_import::dropped(self, &paths)
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -1005,15 +1043,17 @@ impl eframe::App for TextureCraftApp {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.poll_link_imports(ctx);
|
||||
self.thumbs.sync_images(&self.session.images, self.session.revision);
|
||||
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(|i| i.viewport().focused).unwrap_or(true);
|
||||
let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true);
|
||||
if focused && !self.focused {
|
||||
self.library = None;
|
||||
}
|
||||
self.focused = focused;
|
||||
let scale = self.ui.prefs.ui_scale.clamp(0.5, 3.0);
|
||||
if (ctx.zoom_factor() - scale).abs() > 1e-3 {
|
||||
|
||||
let scale = self.ui.prefs.ui_scale.clamp(*UI_SCALE_APPLIED.start(), *UI_SCALE_APPLIED.end());
|
||||
if (ctx.zoom_factor() - scale).abs() > SAME_ZOOM_TOLERANCE {
|
||||
ctx.set_zoom_factor(scale);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -1027,17 +1067,19 @@ impl eframe::App for TextureCraftApp {
|
||||
self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_ui::tick(self, ctx);
|
||||
|
||||
self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx));
|
||||
menus::shortcuts(self, ctx);
|
||||
move_on_model::end_when_gone(self, ctx);
|
||||
|
||||
// The Path tool's curve repaints (a preview while placed) as its points, brush or material change
|
||||
if let Err(e) = self.session.path_live() {
|
||||
if let Err(error) = self.session.path_live() {
|
||||
self.session.cancel_path();
|
||||
self.toast(e.to_string(), true);
|
||||
self.toast(error.to_string(), true);
|
||||
}
|
||||
profile::drive(self, ctx);
|
||||
self.toasts.retain(|t| t.until > now);
|
||||
self.profiler.logic_ms = (now_ms() - t0) as f32;
|
||||
self.toasts.retain(|toast| toast.until > now);
|
||||
self.profiler.logic_ms = (now_ms() - logic_start_ms) as f32;
|
||||
|
||||
// Last, so it sees every close request this frame's work made
|
||||
windows::close_request(self, ctx);
|
||||
@@ -1046,7 +1088,7 @@ impl eframe::App for TextureCraftApp {
|
||||
#[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let started_ms = now_ms();
|
||||
let ui_start_ms = now_ms();
|
||||
|
||||
// Baking and rendering need a project (a saved layout may start in one of them)
|
||||
if !self.session.project_open {
|
||||
@@ -1083,10 +1125,12 @@ impl eframe::App for TextureCraftApp {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.file_dialogs.show_pending(frame);
|
||||
|
||||
let ended_ms = now_ms();
|
||||
let elapsed_ms = (ended_ms - started_ms) as f32;
|
||||
self.ui_ms = if self.ui_ms == 0.0 { elapsed_ms } else { self.ui_ms * 0.9 + elapsed_ms * 0.1 };
|
||||
self.profiler.end_frame(ended_ms, elapsed_ms);
|
||||
pointer_lock::settle(&ctx);
|
||||
|
||||
let end_ms = now_ms();
|
||||
let ui_frame_ms = (end_ms - ui_start_ms) as f32;
|
||||
self.ui_ms = if self.ui_ms == 0.0 { ui_frame_ms } else { self.ui_ms * FRAME_AVERAGE_KEEP + ui_frame_ms * (1.0 - FRAME_AVERAGE_KEEP) };
|
||||
self.profiler.end_frame(end_ms, ui_frame_ms);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//! A Move on model hold under way, kept in egui's memory between frames
|
||||
|
||||
use egui::Pos2;
|
||||
|
||||
use crate::move_on_model::MoveOnModel;
|
||||
|
||||
/// The Move on model button held down: the fill it moves, where the pointer was on the last frame and the session revision its last edit left (its undo step, while the history is still there)
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct MoveHold {
|
||||
pub target: MoveOnModel,
|
||||
pub last: Pos2,
|
||||
pub edited_revision: Option<u64>,
|
||||
/// The pass that last applied it: a sheet drawn twice in one frame moves the projection once
|
||||
pub pass: u64,
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
//! Move on model: hold the preview square and drag to slide the selected fill's projection, with Shift or the right button held to turn it, and turn the wheel to scale it. The pointer is held while it lasts (hidden, no screen edge stops it, back where the press began when let go). Letting go ends it, as one undo step; the 3D view keeps its own drags and wheel
|
||||
|
||||
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;
|
||||
use crate::frame_gizmo::FrameGizmo;
|
||||
use crate::i18n::tr;
|
||||
use crate::move_hold::MoveHold;
|
||||
use crate::property_sheet::PropertySheet;
|
||||
use crate::round_gizmo::RoundGizmo;
|
||||
|
||||
/// The fill whose projection Move on model moves: a fill layer, or a content fill effect in it
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct MoveOnModel {
|
||||
pub layer: LayerId,
|
||||
pub effect: Option<LayerId>,
|
||||
}
|
||||
|
||||
impl MoveOnModel {
|
||||
/// A fill layer's own projection
|
||||
pub(crate) fn layer(layer: LayerId) -> MoveOnModel {
|
||||
MoveOnModel { layer, effect: None }
|
||||
}
|
||||
|
||||
/// The `layer` or `effect` param of the fill commands
|
||||
pub(crate) fn target(self) -> Value {
|
||||
match self.effect {
|
||||
Some(effect) => json!({"effect": effect.0}),
|
||||
None => json!({"layer": self.layer.0}),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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()?;
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
};
|
||||
}
|
||||
|
||||
match &content.kind {
|
||||
LayerKind::Fill(fill) => Some((&fill.projection, "layer.fill.projection")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hold_id() -> egui::Id {
|
||||
egui::Id::unique("tc_move_on_model_hold")
|
||||
}
|
||||
|
||||
/// Image repeats a drag across the view's height slides by
|
||||
const SLIDE_PER_HEIGHT: f32 = 1.0;
|
||||
/// Degrees a turning drag turns per point
|
||||
const TURN_PER_POINT: f32 = 0.5;
|
||||
/// Growth per wheel point (exponential)
|
||||
const SCALE_PER_WHEEL_POINT: f32 = 0.0015;
|
||||
|
||||
/// Move on model on `target`'s preview square: while it is held down it moves the projection
|
||||
pub(crate) fn pad(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, square: Rect, target: MoveOnModel) {
|
||||
let held = app.moving_on_model == Some(target);
|
||||
let mut response = sheet.hold_pad(square, ic::HAND, tr("Move on model"), held);
|
||||
if !held {
|
||||
response = sheet.tip_beside(response, tr("Hold and drag to slide the projection; Shift or the right button turns it, the wheel scales it"));
|
||||
}
|
||||
let ctx = sheet.ui.ctx().clone();
|
||||
hold(app, &ctx, &response, target);
|
||||
}
|
||||
|
||||
/// Whether a Move on model hold is under way, or let go this frame (that release is no click in the view); the 3D view then keeps its camera, brush and gizmos still. Ends a hold whose window lost the focus
|
||||
pub(crate) fn holding(app: &mut TextureCraftApp, ctx: &egui::Context) -> bool {
|
||||
let held = app.moving_on_model.is_some();
|
||||
if held && !still_pressed(ctx) {
|
||||
end(app, ctx);
|
||||
}
|
||||
held
|
||||
}
|
||||
|
||||
/// Ends a hold whose fill or pad went away, once a frame whichever views show
|
||||
pub(crate) fn end_when_gone(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let Some(target) = app.moving_on_model else { return };
|
||||
|
||||
if target.projection_editor(app).is_none() || pad_gone(ctx) {
|
||||
end(app, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the held pad was not drawn last pass nor this one (its layer was deselected, its panel hidden)
|
||||
fn pad_gone(ctx: &egui::Context) -> bool {
|
||||
let last_drawn = ctx.data(|data| data.get_temp::<MoveHold>(hold_id())).map(|held| held.pass);
|
||||
last_drawn.is_none_or(|pass| pass.saturating_add(1) < ctx.cumulative_pass_nr())
|
||||
}
|
||||
|
||||
/// Whether the left button still holds: a window that lost the focus gets no release, so the hold ends there as on one
|
||||
fn still_pressed(ctx: &egui::Context) -> bool {
|
||||
ctx.input(|input| input.pointer.primary_down()) && !crate::viewport::focus_lost(ctx)
|
||||
}
|
||||
|
||||
/// Ends the hold where it is: its edits stay one undo step
|
||||
fn end(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
app.moving_on_model = None;
|
||||
ctx.data_mut(|data| data.remove::<MoveHold>(hold_id()));
|
||||
}
|
||||
|
||||
/// A press on the pad starts the hold; each frame until the left button lets go, pointer moves and wheel steps edit the projection
|
||||
fn hold(app: &mut TextureCraftApp, ctx: &egui::Context, pad: &egui::Response, target: MoveOnModel) {
|
||||
let primary = still_pressed(ctx);
|
||||
let (pressed, turn, pointer) =
|
||||
ctx.input(|input| (input.pointer.primary_pressed(), input.modifiers.shift || input.pointer.secondary_down(), input.pointer.latest_pos()));
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
let mut held = ctx.data(|data| data.get_temp::<MoveHold>(hold_id())).filter(|held| held.target == target);
|
||||
|
||||
// Only a fresh press starts it: after a focus loss egui still has the left button down
|
||||
if held.is_none()
|
||||
&& primary
|
||||
&& pressed
|
||||
&& pad.is_pointer_button_down_on()
|
||||
&& let Some(at) = pointer
|
||||
{
|
||||
held = Some(MoveHold { target, last: at, edited_revision: None, pass: pass.wrapping_sub(1) });
|
||||
}
|
||||
|
||||
let Some(mut held) = held.filter(|_| primary && target.projection_editor(app).is_some()) else {
|
||||
if app.moving_on_model == Some(target) {
|
||||
end(app, ctx);
|
||||
}
|
||||
if pad.hovered() {
|
||||
ctx.set_cursor_icon(CursorIcon::Grab);
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
app.moving_on_model = Some(target);
|
||||
crate::pointer_lock::ask_for_hold(ctx);
|
||||
if held.pass == pass {
|
||||
return;
|
||||
}
|
||||
|
||||
held.pass = pass;
|
||||
|
||||
let rect = app.viewport_rect;
|
||||
if let Some(at) = pointer.filter(|at| *at != held.last) {
|
||||
if let Some((command, params)) = dragged(app, target, held.last, at, turn, rect) {
|
||||
step(app, &mut held, command, params);
|
||||
}
|
||||
held.last = at;
|
||||
}
|
||||
|
||||
// The wheel scales the projection instead of scrolling the panel or zooming the camera while the pad is held
|
||||
let wheel = ctx.input_mut(|input| std::mem::take(&mut input.smooth_scroll_delta).y);
|
||||
if wheel != 0.0
|
||||
&& let Some((command, params)) = resized(app, target, (SCALE_PER_WHEEL_POINT * wheel).exp(), rect)
|
||||
{
|
||||
step(app, &mut held, command, params);
|
||||
}
|
||||
|
||||
ctx.data_mut(|data| data.insert_temp(hold_id(), held));
|
||||
|
||||
// The panel drew before this edit: one more frame shows its fields and preview where the projection is now
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// Runs one edit of the hold; the edits after the first that changed something join its undo step
|
||||
fn step(app: &mut TextureCraftApp, held: &mut MoveHold, command: &str, params: Value) {
|
||||
crate::projection_gizmo::edit_in_one_step(&mut app.session, command, params, &mut held.edited_revision);
|
||||
}
|
||||
|
||||
/// The selected planar or warp frame of a fill layer or of a mask fill effect, which moves by its frame
|
||||
fn frame_of(app: &TextureCraftApp, target: MoveOnModel, rect: Rect) -> Option<FrameGizmo> {
|
||||
FrameGizmo::of(app, rect).filter(|gizmo| match target.effect {
|
||||
Some(effect) => gizmo.effect == Some(effect),
|
||||
None => gizmo.layer == target.layer && gizmo.effect.is_none(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The `layer` (and for a mask fill `effect`) params of `layer.decal.set` editing `gizmo`'s frame, added to `params`
|
||||
fn frame_target(mut params: Value, gizmo: &FrameGizmo) -> Value {
|
||||
params["layer"] = json!(gizmo.layer.0);
|
||||
if let Some(effect) = gizmo.effect {
|
||||
params["effect"] = json!(effect.0);
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// A projection's UV tiling, rotation and offset (None for Fill (Match per UV Tile))
|
||||
fn placement(projection: &Projection) -> Option<([f32; 2], f32, [f32; 2])> {
|
||||
match projection {
|
||||
Projection::UvTile => None,
|
||||
Projection::Uv { scale, rotation, offset } => Some((*scale, *rotation, *offset)),
|
||||
Projection::Triplanar { uv, .. }
|
||||
| Projection::Planar { uv, .. }
|
||||
| Projection::Spherical { uv, .. }
|
||||
| Projection::Cylindrical { uv, .. }
|
||||
| Projection::Warp { uv, .. } => Some((uv.tiling, uv.rotation, uv.offset)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The edit a pointer move from `from` to `to` makes: a frame or projector slides by it, a UV image slides; with `turn` it turns instead
|
||||
fn dragged(app: &TextureCraftApp, target: MoveOnModel, from: Pos2, to: Pos2, turn: bool, rect: Rect) -> Option<(&'static str, Value)> {
|
||||
let delta = to - from;
|
||||
if let Some(gizmo) = frame_of(app, target, rect) {
|
||||
let params = if turn { json!({"rotation": gizmo.decal.rotation - delta.x * TURN_PER_POINT}) } else { json!({"offset": gizmo.slid_on_screen(delta)?}) };
|
||||
return Some(("layer.decal.set", frame_target(params, &gizmo)));
|
||||
}
|
||||
|
||||
if !turn && let Some(round) = RoundGizmo::of(app, rect).filter(|round| round.target == target) {
|
||||
return round.slid(app, rect, from, to);
|
||||
}
|
||||
|
||||
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) {
|
||||
(true, _) => json!({"rotation": rotation + delta.x * TURN_PER_POINT}),
|
||||
(false, Projection::Uv { .. }) => json!({"offset": offset}),
|
||||
(false, _) => json!({"uvOffset": offset}),
|
||||
};
|
||||
merge_target(&mut params, target);
|
||||
Some((command, params))
|
||||
}
|
||||
|
||||
/// The edit a wheel step growing the projection by `growth` makes: a frame grows, other projections' images repeat less
|
||||
fn resized(app: &TextureCraftApp, target: MoveOnModel, growth: f32, rect: Rect) -> Option<(&'static str, Value)> {
|
||||
if let Some(gizmo) = frame_of(app, target, rect) {
|
||||
let [width, height] = gizmo.decal.size;
|
||||
return Some(("layer.decal.set", frame_target(json!({"size": [width * growth, height * growth]}), &gizmo)));
|
||||
}
|
||||
|
||||
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((command, params))
|
||||
}
|
||||
|
||||
/// Adds the `layer` or `effect` param naming `target` to `params`
|
||||
fn merge_target(params: &mut Value, target: MoveOnModel) {
|
||||
if let (Some(params), Value::Object(fields)) = (params.as_object_mut(), target.target()) {
|
||||
params.extend(fields);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use egui::{Modifiers, PointerButton, vec2};
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use texturecraft_engine::core::{Projection, UvTransform};
|
||||
|
||||
use super::*;
|
||||
use crate::frame_gizmo::tests::{drag, fill_app, projection};
|
||||
use crate::pointer_lock::system_pointer::SystemPointer;
|
||||
use crate::round_gizmo::tests::on_the_model_off_the_handles;
|
||||
use crate::state::ViewLayout;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, TextureCraftApp>;
|
||||
|
||||
fn uv_of(projection: &Projection) -> UvTransform {
|
||||
match projection {
|
||||
Projection::Triplanar { uv, .. } => *uv,
|
||||
other => panic!("tri-planar: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn projector_offset(projection: &Projection) -> [f32; 3] {
|
||||
match projection {
|
||||
Projection::Triplanar { offset, .. } => *offset,
|
||||
other => panic!("tri-planar: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Presses the left button on Move on model (the preview square) and holds it; returns the system's pointer, resting there
|
||||
fn press_the_button(harness: &mut Harness) -> SystemPointer {
|
||||
let at = harness.get_by_label("Move on model").rect().center();
|
||||
let mut pointer = SystemPointer::at(harness, at);
|
||||
pointer.button(harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
pointer
|
||||
}
|
||||
|
||||
/// A wheel step up where the pointer is, over a few frames as the wheel scrolls smoothly
|
||||
fn wheel(harness: &mut Harness, pointer: &mut SystemPointer) {
|
||||
harness.input_mut().events.push(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, 120.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
for _ in 0..6 {
|
||||
pointer.frame(harness);
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets go of the left button, and lets a frame show where the pointer came back to
|
||||
fn let_go(harness: &mut Harness, pointer: &mut SystemPointer) {
|
||||
pointer.button(harness, PointerButton::Primary, false, Modifiers::NONE);
|
||||
pointer.frame(harness);
|
||||
}
|
||||
|
||||
/// Holding the pad and dragging carries the projector with the mouse, the pointer hidden and kept on the pad; letting go ends it there
|
||||
#[test]
|
||||
fn holding_the_button_and_dragging_carries_the_projector_as_one_undo_step() {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (mut harness, layer) = fill_app("triplanar");
|
||||
let rect = harness.state().viewport_rect;
|
||||
let before = RoundGizmo::of(harness.state(), rect).unwrap();
|
||||
let (steps, camera) = (harness.state().session.history_labels().len(), harness.state().session.camera);
|
||||
|
||||
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);
|
||||
pointer.drags(&mut harness, moved, 30, Modifiers::NONE);
|
||||
let after = RoundGizmo::of(harness.state(), rect).unwrap();
|
||||
|
||||
assert!((after.center - (before.center + moved)).length() < 2.0, "the projector follows the mouse: {:?} -> {:?}", before.center, after.center);
|
||||
assert!(pointer.hidden, "the pointer hides while held");
|
||||
assert!(pointer.at.distance(from) < 1.0, "and stays on the pad, so no screen edge stops the drag: {:?}", pointer.at);
|
||||
|
||||
let slid = projection(&harness, layer);
|
||||
assert_ne!(projector_offset(&slid), [0.0; 3], "the projector itself moved: {slid:?}");
|
||||
assert_eq!(uv_of(&slid), UvTransform::default(), "not only the image inside it");
|
||||
|
||||
let_go(&mut harness, &mut pointer);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, None, "letting go ends it");
|
||||
assert!(!pointer.hidden && pointer.at == from, "the pointer shows again where the press began: {:?}", pointer.at);
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per hold");
|
||||
assert_eq!(harness.state().session.camera, camera, "the camera kept still");
|
||||
|
||||
// The 3D view has its drags back: a drag on the model off the projector's handles moves nothing
|
||||
let off = on_the_model_off_the_handles(&harness);
|
||||
drag(&mut harness, off, off + vec2(60.0, 0.0), Modifiers::NONE);
|
||||
|
||||
assert_eq!(projection(&harness, layer), slid, "no mode is left on");
|
||||
}
|
||||
|
||||
/// Losing the focus mid-hold (Alt+Tab) ends it as letting go does: one undo step, the pointer shown, and moves after it (egui still has the button down) leave the projection alone
|
||||
#[test]
|
||||
fn losing_the_window_focus_mid_hold_ends_it_as_letting_go_does() {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (mut harness, layer) = fill_app("triplanar");
|
||||
let steps = harness.state().session.history_labels().len();
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "the hold is under way");
|
||||
|
||||
harness.input_mut().events.push(egui::Event::WindowFocused(false));
|
||||
pointer.frame(&mut harness);
|
||||
let left = projection(&harness, layer);
|
||||
assert_eq!(harness.state().moving_on_model, None, "the focus loss ends the hold");
|
||||
assert!(!pointer.hidden, "the pointer shows again");
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step, as letting go makes");
|
||||
|
||||
pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, None, "the button still down in egui starts no new hold");
|
||||
assert_eq!(projection(&harness, layer), left, "moves after it leave the projection alone");
|
||||
}
|
||||
|
||||
/// Removing the held fill mid-hold (its pad goes with it) ends the hold at once, the button still down, with or without the 3D view: the pointer shows
|
||||
#[test]
|
||||
fn removing_the_held_fill_ends_the_hold() {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for layout in [ViewLayout::Split, ViewLayout::Only2D] {
|
||||
let (mut harness, layer) = fill_app("triplanar");
|
||||
harness.state_mut().ui.layout = layout;
|
||||
harness.run_steps(2);
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "{layout:?}: the hold is under way");
|
||||
|
||||
harness.state_mut().run("layer.remove", json!({"layer": layer.0})).unwrap();
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, None, "{layout:?}: the hold ended with its fill");
|
||||
assert!(!pointer.hidden, "{layout:?}: the pointer shows again");
|
||||
}
|
||||
}
|
||||
|
||||
/// The preview square is the pad: a press anywhere on it, its corner too, starts the hold and holds the pointer
|
||||
#[test]
|
||||
fn the_preview_square_is_the_pad_from_corner_to_corner() {
|
||||
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);
|
||||
let mut pointer = SystemPointer::at(&mut harness, pad.left_top() + vec2(4.0, 4.0));
|
||||
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press at its corner starts the hold");
|
||||
|
||||
pointer.drags(&mut harness, vec2(40.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert!(pointer.hidden, "the pointer is held");
|
||||
|
||||
let_go(&mut harness, &mut pointer);
|
||||
|
||||
assert_ne!(projection(&harness, layer), before, "the drag moved the projection");
|
||||
assert_eq!(harness.state().moving_on_model, None);
|
||||
}
|
||||
|
||||
/// While held, Shift or the right button turns the image and the wheel scales it, all in the hold's one undo step; the camera neither orbits nor zooms. Released, the wheel zooms again
|
||||
#[test]
|
||||
fn shift_or_the_right_button_turns_and_the_wheel_scales_while_held() {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (mut harness, layer) = fill_app("triplanar");
|
||||
let rect = harness.state().viewport_rect;
|
||||
let (steps, camera) = (harness.state().session.history_labels().len(), harness.state().session.camera);
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
let from = pointer.at;
|
||||
|
||||
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");
|
||||
|
||||
// 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);
|
||||
pointer.button(&mut harness, PointerButton::Secondary, true, Modifiers::NONE);
|
||||
pointer.drags(&mut harness, vec2(-40.0, 0.0), 30, Modifiers::NONE);
|
||||
let turned = projection(&harness, layer);
|
||||
assert!(uv_of(&turned).rotation < shifted.rotation, "the right button turns it: {shifted:?} -> {turned:?}");
|
||||
assert_eq!(projector_offset(&turned), projector_offset(&slid), "without sliding");
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Secondary, false, Modifiers::NONE);
|
||||
|
||||
wheel(&mut harness, &mut pointer);
|
||||
let scaled = uv_of(&projection(&harness, layer));
|
||||
assert!(scaled.tiling[0] < uv_of(&turned).tiling[0] && scaled.tiling[0] == scaled.tiling[1], "the wheel up makes the image bigger: {scaled:?}");
|
||||
assert_eq!(harness.state().session.camera, camera, "the camera neither orbited nor zoomed");
|
||||
assert!(harness.state().properties_popup.is_none(), "the right click opened no Properties popup");
|
||||
|
||||
let_go(&mut harness, &mut pointer);
|
||||
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the whole hold is one undo step");
|
||||
|
||||
let back = pointer.at;
|
||||
pointer.moves(&mut harness, over_view - back, Modifiers::NONE);
|
||||
wheel(&mut harness, &mut pointer);
|
||||
|
||||
assert_ne!(harness.state().session.camera, camera, "let go, the wheel zooms the camera");
|
||||
assert_eq!(uv_of(&projection(&harness, layer)), scaled, "and leaves the projection alone");
|
||||
}
|
||||
|
||||
/// A hold whose first edit changes nothing (Shift with an up and down drag turns a frame by nothing) makes no undo step, so its later edits make the hold's own step instead of joining the edit before it
|
||||
#[test]
|
||||
fn a_hold_that_first_changes_nothing_keeps_its_own_undo_step() {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (mut harness, layer) = fill_app("warp");
|
||||
harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "rotation": 30.0})).unwrap();
|
||||
harness.run_steps(2);
|
||||
let turned = projection(&harness, layer);
|
||||
let steps = harness.state().session.history_labels().len();
|
||||
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::SHIFT);
|
||||
|
||||
assert_eq!(projection(&harness, layer), turned, "an up and down turn changes nothing");
|
||||
|
||||
pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::NONE);
|
||||
let_go(&mut harness, &mut pointer);
|
||||
|
||||
assert_ne!(projection(&harness, layer), turned, "the slide moved the frame");
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the hold made its own undo step");
|
||||
|
||||
harness.state_mut().session.undo().unwrap();
|
||||
|
||||
assert_eq!(projection(&harness, layer), turned, "undo takes back the hold only");
|
||||
}
|
||||
|
||||
/// A UV image slides as far as the mouse goes, past the window's edge; a warp's frame slides across its plane
|
||||
#[test]
|
||||
fn a_hold_slides_a_uv_image_and_a_frame_across_its_plane() {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (mut harness, layer) = fill_app("uv");
|
||||
let height = harness.state().viewport_rect.height();
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
let from = pointer.at;
|
||||
wheel(&mut harness, &mut pointer);
|
||||
|
||||
assert_eq!(harness.get_by_label("Move on model").rect().center(), from, "a wheel step over the panel while held scales, it does not scroll the panel");
|
||||
let Projection::Uv { scale, .. } = projection(&harness, layer) else { panic!("still UV") };
|
||||
assert!(scale[0] < 1.0, "the wheel up makes the image bigger: {scale:?}");
|
||||
|
||||
let far = vec2(-3.0 * from.x, 0.0);
|
||||
pointer.drags(&mut harness, far, 60, Modifiers::NONE);
|
||||
let_go(&mut harness, &mut pointer);
|
||||
let Projection::Uv { offset, .. } = projection(&harness, layer) else { panic!("still UV") };
|
||||
assert!(
|
||||
(offset[0] - (-far.x) * SLIDE_PER_HEIGHT / height).abs() < 0.01 && offset[1] == 0.0,
|
||||
"a drag left slides the image left, all the way: {offset:?}"
|
||||
);
|
||||
|
||||
let (mut harness, layer) = fill_app("warp");
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
pointer.drags(&mut harness, vec2(0.0, -40.0), 30, Modifiers::NONE);
|
||||
let_go(&mut harness, &mut pointer);
|
||||
let Projection::Warp { frame, .. } = projection(&harness, layer) else { panic!("still a warp") };
|
||||
assert!(frame.offset[1] > 0.0 && frame.offset[0].abs() < frame.offset[1] * 0.2, "a drag up slides the frame up: {frame:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! How far a Properties list scrolls past its last row
|
||||
|
||||
/// When a Properties list leaves blank space under its rows so its last section's top can reach the top of the list
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(crate) enum PastEnd {
|
||||
/// Always, as the docked panel: even when every section fits
|
||||
Always,
|
||||
/// Only once the rows no longer fit, as a popup sized to its rows
|
||||
WhenScrolling,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Where a fill's tiles land, as the window preview draws them
|
||||
|
||||
/// How the fill's image is laid on its tile: tiles across and down, rotation in degrees, offset in tiles (rotate, scale, then offset)
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Placement {
|
||||
pub tiling: [f32; 2],
|
||||
pub rotation: f32,
|
||||
pub offset: [f32; 2],
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! How the system lets a drag hold its pointer
|
||||
|
||||
/// How a drag holds the pointer on this platform
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Hold {
|
||||
/// The pointer moves, and is put back where the press began after every frame; the put-back's own move arrives among the others (X11)
|
||||
PutBack,
|
||||
/// Put back the same way, but the system folds its waiting moves into one, read from where it put the pointer (Windows)
|
||||
PutBackFolded,
|
||||
/// The system keeps the pointer still and reports raw motion (macOS, Wayland, which cannot move a pointer)
|
||||
Locked,
|
||||
/// The pointer cannot be held (the browser): drags read it as it moves
|
||||
Free,
|
||||
}
|
||||
|
||||
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 {
|
||||
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() {
|
||||
Hold::PutBack
|
||||
} else {
|
||||
Hold::Locked
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer is held by putting it back after every frame
|
||||
pub(crate) fn puts_back(self) -> bool {
|
||||
matches!(self, Hold::PutBack | Hold::PutBackFolded)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use egui::Pos2;
|
||||
|
||||
use super::Hold;
|
||||
|
||||
/// A drag holding the pointer, kept in egui's memory between frames
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct Lock {
|
||||
pub(super) hold: Hold,
|
||||
/// Where the press began: the pointer is kept there and comes back there
|
||||
pub(super) anchor: Pos2,
|
||||
/// Where the system's pointer is
|
||||
pub(super) seen: Pos2,
|
||||
/// Where egui sees the pointer: the anchor plus every move since, as far as it goes
|
||||
pub(super) at: Pos2,
|
||||
/// A put-back is on its way: the pointer move that brings it back is no motion
|
||||
pub(super) putting_back: bool,
|
||||
/// The drag let go: the next frame shows egui the pointer back at the anchor and forgets the lock
|
||||
pub(super) let_go: bool,
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Drags that hold the pointer (Move on model, number fields that scrub): hidden while held, its motion endless so no screen edge stops it, back where the press began when let go. egui sees a pointer that keeps going: the raw input is rewritten to that endless position, so every drag reads its usual positions and deltas
|
||||
|
||||
mod hold;
|
||||
mod lock;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod system_pointer;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use egui::{Context, CursorIcon, Event, Id, RawInput, ViewportCommand};
|
||||
|
||||
pub(crate) use hold::Hold;
|
||||
use lock::Lock;
|
||||
|
||||
/// Points from where the press began within which a pointer move is the put-back arriving (the system rounds it to whole pixels)
|
||||
const PUT_BACK_REACH: f32 = 1.0;
|
||||
|
||||
fn lock_id() -> Id {
|
||||
Id::unique("tc_pointer_lock")
|
||||
}
|
||||
|
||||
fn asked_id() -> Id {
|
||||
Id::unique("tc_pointer_lock_asked")
|
||||
}
|
||||
|
||||
fn hold_override_id() -> Id {
|
||||
Id::unique("tc_pointer_lock_hold")
|
||||
}
|
||||
|
||||
/// A drag under way asks for the pointer this frame; it keeps it as long as it asks every frame
|
||||
pub(crate) fn ask_for_hold(ctx: &Context) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|data| data.insert_temp(asked_id(), pass));
|
||||
}
|
||||
|
||||
/// The app's raw input hook: while a drag holds the pointer, its moves become moves of the endless pointer egui sees
|
||||
pub(crate) fn rewrite(ctx: &Context, raw: &mut RawInput) {
|
||||
let Some(mut lock) = ctx.data(|data| data.get_temp::<Lock>(lock_id())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if lock.let_go {
|
||||
raw.events.insert(0, Event::PointerMoved(lock.anchor));
|
||||
ctx.data_mut(|data| data.remove::<Lock>(lock_id()));
|
||||
return;
|
||||
}
|
||||
|
||||
let zoom = ctx.zoom_factor().max(f32::EPSILON);
|
||||
let events = std::mem::take(&mut raw.events);
|
||||
for event in events {
|
||||
match event {
|
||||
Event::PointerMoved(to) => {
|
||||
let put_back = lock.putting_back && to.distance(lock.anchor) <= PUT_BACK_REACH;
|
||||
lock.putting_back &= !put_back;
|
||||
if lock.hold.puts_back() && !put_back {
|
||||
lock.at += to - lock.seen;
|
||||
raw.events.push(Event::PointerMoved(lock.at));
|
||||
}
|
||||
lock.seen = to;
|
||||
}
|
||||
Event::MouseMoved(delta) => {
|
||||
if lock.hold == Hold::Locked {
|
||||
lock.at += delta / zoom;
|
||||
raw.events.push(Event::PointerMoved(lock.at));
|
||||
}
|
||||
raw.events.push(event);
|
||||
}
|
||||
Event::PointerButton { button, pressed, modifiers, .. } => raw.events.push(Event::PointerButton { pos: lock.at, button, pressed, modifiers }),
|
||||
// The pointer never really leaves: the drag goes on
|
||||
Event::PointerGone => {}
|
||||
other => raw.events.push(other),
|
||||
}
|
||||
}
|
||||
ctx.data_mut(|data| data.insert_temp(lock_id(), lock));
|
||||
}
|
||||
|
||||
/// 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 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 (origin, latest) = ctx.input(|input| (input.pointer.press_origin(), input.pointer.latest_pos()));
|
||||
let (Some(seen), false) = (latest, hold == Hold::Free) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if hold == Hold::Locked {
|
||||
ctx.send_viewport_cmd(ViewportCommand::CursorGrab(egui::CursorGrab::Locked));
|
||||
}
|
||||
Lock { hold, anchor: origin.unwrap_or(seen), seen, at: seen, putting_back: false, let_go: false }
|
||||
}
|
||||
(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 {
|
||||
ctx.send_viewport_cmd(ViewportCommand::CursorPosition(lock.anchor));
|
||||
}
|
||||
if lock.hold == Hold::Locked {
|
||||
ctx.send_viewport_cmd(ViewportCommand::CursorGrab(egui::CursorGrab::None));
|
||||
}
|
||||
lock.let_go = true;
|
||||
ctx.data_mut(|data| data.insert_temp(lock_id(), lock));
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
(false, None) => return,
|
||||
};
|
||||
|
||||
ctx.set_cursor_icon(CursorIcon::None);
|
||||
if lock.hold.puts_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
|
||||
if lock.hold == Hold::PutBackFolded {
|
||||
lock.seen = lock.anchor;
|
||||
} else {
|
||||
lock.putting_back = true;
|
||||
}
|
||||
}
|
||||
ctx.data_mut(|data| data.insert_temp(lock_id(), lock));
|
||||
}
|
||||
|
||||
/// Tests pick how the pointer is held, as a platform would
|
||||
#[cfg(test)]
|
||||
pub(crate) fn hold_like(ctx: &Context, hold: Hold) {
|
||||
ctx.data_mut(|data| data.insert_temp(hold_override_id(), hold));
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! The system's pointer in tests: the mouse moves it, and it obeys the app's put-backs, grabs and hidden cursor as a window system does
|
||||
|
||||
use egui::{CursorGrab, CursorIcon, Event, Modifiers, PointerButton, Pos2, Vec2, ViewportCommand, ViewportId};
|
||||
use egui_kittest::Harness;
|
||||
|
||||
/// Where the system's pointer is and how the app holds it
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct SystemPointer {
|
||||
pub(crate) at: Pos2,
|
||||
pub(crate) locked: bool,
|
||||
pub(crate) hidden: bool,
|
||||
pub(crate) put_backs: usize,
|
||||
/// The system folds a put-back into the next move, as Windows does, instead of reporting it as a move of its own
|
||||
pub(crate) folds: bool,
|
||||
}
|
||||
|
||||
impl SystemPointer {
|
||||
/// The pointer resting at `at` over the window
|
||||
pub(crate) fn at<S>(harness: &mut Harness<'_, S>, at: Pos2) -> SystemPointer {
|
||||
let mut pointer = SystemPointer { at, locked: false, hidden: false, put_backs: 0, folds: false };
|
||||
harness.input_mut().events.push(Event::PointerMoved(at));
|
||||
pointer.frame(harness);
|
||||
pointer
|
||||
}
|
||||
|
||||
/// One frame in which the mouse moves by `by` with `modifiers` held: a held pointer reports raw motion only, a free one moves
|
||||
pub(crate) fn moves<S>(&mut self, harness: &mut Harness<'_, S>, by: Vec2, modifiers: Modifiers) {
|
||||
let input = harness.input_mut();
|
||||
input.events.push(Event::ModifiersChanged(modifiers));
|
||||
input.events.push(Event::MouseMoved(by));
|
||||
if !self.locked {
|
||||
self.at += by;
|
||||
input.events.push(Event::PointerMoved(self.at));
|
||||
}
|
||||
self.frame(harness);
|
||||
}
|
||||
|
||||
/// The mouse moves by `by` over `frames` frames
|
||||
pub(crate) fn drags<S>(&mut self, harness: &mut Harness<'_, S>, by: Vec2, frames: usize, modifiers: Modifiers) {
|
||||
for _ in 0..frames {
|
||||
self.moves(harness, by / frames as f32, modifiers);
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame in which `button` goes down or up where the pointer is
|
||||
pub(crate) fn button<S>(&mut self, harness: &mut Harness<'_, S>, button: PointerButton, pressed: bool, modifiers: Modifiers) {
|
||||
let input = harness.input_mut();
|
||||
input.events.push(Event::ModifiersChanged(modifiers));
|
||||
input.events.push(Event::PointerButton { pos: self.at, button, pressed, modifiers });
|
||||
self.frame(harness);
|
||||
}
|
||||
|
||||
/// One frame of everything the system sent since the last: the app's raw input hook rewrites it, the app runs, and the pointer does what the app asked
|
||||
pub(crate) fn frame<S>(&mut self, harness: &mut Harness<'_, S>) {
|
||||
let ctx = harness.ctx.clone();
|
||||
super::rewrite(&ctx, harness.input_mut());
|
||||
harness.step();
|
||||
let output = harness.output();
|
||||
self.hidden = output.platform_output.cursor_icon == CursorIcon::None;
|
||||
let commands = output.viewport_output.get(&ViewportId::ROOT).map(|viewport| viewport.commands.clone()).unwrap_or_default();
|
||||
for command in commands {
|
||||
match command {
|
||||
ViewportCommand::CursorPosition(to) => {
|
||||
self.at = to;
|
||||
self.put_backs += 1;
|
||||
if !self.folds {
|
||||
harness.input_mut().events.push(Event::PointerMoved(to));
|
||||
}
|
||||
}
|
||||
ViewportCommand::CursorGrab(grab) => self.locked = grab == CursorGrab::Locked,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
use egui::{Modifiers, PointerButton, Pos2, Rect, Sense, Vec2, pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
|
||||
use super::system_pointer::SystemPointer;
|
||||
use super::{Hold, ask_for_hold, hold_like, settle};
|
||||
|
||||
/// A strip that scrubs: dragging it adds the pointer's moves to the state, holding the pointer while it does
|
||||
fn scrub_strip(hold_as: Hold) -> Harness<'static, Vec2> {
|
||||
let mut harness = Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state(
|
||||
|ui, moved: &mut Vec2| {
|
||||
let response = ui.interact(Rect::from_min_size(pos2(10.0, 10.0), vec2(100.0, 24.0)), ui.scope_id().with("scrub"), Sense::drag());
|
||||
if response.dragged() {
|
||||
ask_for_hold(ui.ctx());
|
||||
*moved += response.drag_delta();
|
||||
}
|
||||
settle(ui.ctx());
|
||||
},
|
||||
Vec2::ZERO,
|
||||
);
|
||||
hold_like(&harness.ctx, hold_as);
|
||||
harness.run_steps(1);
|
||||
harness
|
||||
}
|
||||
|
||||
const PRESS: Pos2 = pos2(60.0, 20.0);
|
||||
|
||||
/// Drags the strip 1500 points right (far past the 400-point window) and back up 40, then lets go
|
||||
fn scrub_past_the_edge(harness: &mut Harness<'static, Vec2>) -> SystemPointer {
|
||||
let mut pointer = SystemPointer::at(harness, PRESS);
|
||||
pointer.button(harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
pointer.drags(harness, vec2(1500.0, -40.0), 30, Modifiers::NONE);
|
||||
assert!(pointer.hidden, "the pointer is hidden while the drag holds it");
|
||||
assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts, past the window's edge: {:?}", harness.state());
|
||||
pointer
|
||||
}
|
||||
|
||||
#[test]
|
||||
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);
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE);
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert!(!pointer.hidden, "let go, the pointer shows again");
|
||||
assert_eq!(pointer.at, PRESS, "where the press began");
|
||||
assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it there too");
|
||||
|
||||
let moved = *harness.state();
|
||||
pointer.moves(&mut harness, vec2(30.0, 0.0), Modifiers::NONE);
|
||||
|
||||
assert_eq!(pointer.at, PRESS + vec2(30.0, 0.0), "a free pointer moves again");
|
||||
assert_eq!(*harness.state(), moved, "and drags nothing");
|
||||
}
|
||||
|
||||
/// A system that folds the put-back into the next move (Windows) reads that move from the press point: the drag counts in full and never stalls
|
||||
#[test]
|
||||
fn a_folded_put_back_counts_every_move_from_the_press() {
|
||||
let mut harness = scrub_strip(Hold::PutBackFolded);
|
||||
let mut pointer = SystemPointer::at(&mut harness, PRESS);
|
||||
pointer.folds = true;
|
||||
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
pointer.drags(&mut harness, vec2(1500.0, -40.0), 30, Modifiers::NONE);
|
||||
|
||||
assert!(pointer.hidden && pointer.put_backs >= 30, "hidden, and put back after every move: {pointer:?}");
|
||||
assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts: {:?}", harness.state());
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE);
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert!(!pointer.hidden && pointer.at == PRESS, "let go, it shows again where the press began: {pointer:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
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");
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE);
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert!(!pointer.locked && !pointer.hidden, "let go, the pointer is free and shows");
|
||||
assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it where the press began");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_browser_pointer_is_not_held() {
|
||||
let mut harness = scrub_strip(Hold::Free);
|
||||
let mut pointer = SystemPointer::at(&mut harness, PRESS);
|
||||
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
pointer.drags(&mut harness, vec2(100.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert!(!pointer.hidden && pointer.put_backs == 0, "the pointer moves and shows");
|
||||
assert_eq!(*harness.state(), vec2(100.0, 0.0), "the drag reads it as it moves");
|
||||
}
|
||||
|
||||
/// A number field in the Properties panel scrubs with the pointer held: hidden, kept where the press began, a drag far past the window's edge counted in full
|
||||
#[test]
|
||||
fn a_number_field_scrubs_past_the_edge_with_the_pointer_held() {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (mut harness, layer) = crate::frame_gizmo::tests::fill_app("triplanar");
|
||||
hold_like(&harness.ctx, Hold::PutBack);
|
||||
let press = harness.get_by_label("Offset X").rect().center();
|
||||
let mut pointer = SystemPointer::at(&mut harness, press);
|
||||
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
let window = harness.ctx.content_rect().width();
|
||||
pointer.drags(&mut harness, vec2(2.0 * window, 0.0), 40, Modifiers::NONE);
|
||||
|
||||
assert!(pointer.hidden && pointer.at.distance(press) < 1.0, "the pointer is hidden and kept on the field: {pointer:?}");
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE);
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert!(!pointer.hidden && pointer.at == press, "let go, it shows again on the field: {pointer:?}");
|
||||
|
||||
let texturecraft_engine::core::Projection::Triplanar { offset, .. } = crate::frame_gizmo::tests::projection(&harness, layer) else {
|
||||
panic!("still tri-planar")
|
||||
};
|
||||
|
||||
let expected = 2.0 * window * crate::fill_panel::OFFSET_FIELD_SPEED;
|
||||
assert!((offset[0] - expected).abs() < 0.05 * expected, "the whole drag counts, not only the part inside the window: {offset:?}, {expected}");
|
||||
}
|
||||
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user