mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-26 01:10:48 +01:00
Fix polygon fill drag state and visibility
This commit is contained in:
1 parent
49bd4a1273
commit
c87247c6d3
8 files changed
+340
-18
No files matched your search
@@ -100,13 +100,14 @@ impl Session {
|
||||
self.show_box_fill(selected)
|
||||
}
|
||||
|
||||
/// Begin a box drag unless one is under way in the same view, texture set and quick mask state; a drag from another one ends first
|
||||
/// Continue a box drag only while its view, paint target and quick mask state still match
|
||||
fn start_polygon_fill_drag(&mut self, viewport: Option<Vec2>) -> Result<()> {
|
||||
let ts = self.ts();
|
||||
let target = (self.selected_layer(), self.target);
|
||||
let quick_mask = self.quick_mask.editing;
|
||||
// A different view size, set or quick mask state starts a new drag; the old one keeps its fill as one step
|
||||
// Finish the old target before another preview can restore its earlier document snapshot
|
||||
if let Some(drag) = &self.polygon_fill_drag {
|
||||
if drag.ts == ts && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask {
|
||||
if drag.ts == ts && drag.target == target && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask {
|
||||
// A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera
|
||||
if drag.camera != self.camera {
|
||||
let (points, depth) = self.box_space(viewport);
|
||||
@@ -114,8 +115,10 @@ impl Session {
|
||||
(drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None);
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.end_polygon_fill_box();
|
||||
}
|
||||
|
||||
@@ -127,6 +130,7 @@ impl Session {
|
||||
};
|
||||
self.polygon_fill_drag = Some(PolygonFillDrag {
|
||||
ts,
|
||||
target,
|
||||
viewport,
|
||||
camera: self.camera,
|
||||
before: self.doc.clone(),
|
||||
|
||||
@@ -2,18 +2,21 @@
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use texturecraft_core::LayerId;
|
||||
use texturecraft_geom::OrbitCamera;
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::EyeDepth;
|
||||
use texturecraft_texel::TileImage;
|
||||
|
||||
use crate::session::Document;
|
||||
use crate::session::{Document, StackTarget};
|
||||
use crate::triangle_partition::TrianglePartition;
|
||||
|
||||
/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends
|
||||
pub(crate) struct PolygonFillDrag {
|
||||
/// The texture set it fills
|
||||
pub ts: usize,
|
||||
/// The selected layer and content, mask or effect being filled
|
||||
pub target: (Option<LayerId>, StackTarget),
|
||||
/// The 3D view's size in pixels, or None for a drag in the 2D view
|
||||
pub viewport: Option<Vec2>,
|
||||
/// The camera [`PolygonFillDrag::points`] and [`PolygonFillDrag::depth`] were made with
|
||||
|
||||
@@ -40,10 +40,11 @@ impl TrianglePartition {
|
||||
while let Some(triangle) = stack.pop() {
|
||||
members.push(triangle);
|
||||
let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default();
|
||||
for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) {
|
||||
if !group_of.contains_key(neighbour) {
|
||||
group_of.insert(*neighbour, groups.len());
|
||||
stack.push(*neighbour);
|
||||
// Visit a shared edge once, including when many collapsed faces share the same key
|
||||
for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) {
|
||||
if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) {
|
||||
entry.insert(groups.len());
|
||||
stack.push(neighbour);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,4 +81,43 @@ mod tests {
|
||||
assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2));
|
||||
assert_eq!(pairs.group(99), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_edges_keep_transitive_neighbors() {
|
||||
let mesh = primitives::plane(2.0, 4);
|
||||
let groups = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 4, (triangle + 1) / 4]);
|
||||
|
||||
assert_eq!(groups.groups.len(), 1);
|
||||
assert_eq!(groups.group(0).unwrap().len(), mesh.triangle_count());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release performance measurement"]
|
||||
fn benchmark_shared_edges() {
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
for subdivisions in [32, 64] {
|
||||
let mesh = primitives::plane(2.0, subdivisions);
|
||||
for collapsed in [false, true] {
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..5 {
|
||||
let start = Instant::now();
|
||||
let groups = TrianglePartition::new(&mesh, 0, |mesh, triangle| {
|
||||
if collapsed {
|
||||
vec![(0, 0); 3]
|
||||
} else {
|
||||
let [first, second, third] = mesh.tri(triangle).unwrap();
|
||||
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
|
||||
}
|
||||
});
|
||||
assert_eq!(groups.groups.len(), 1);
|
||||
black_box(groups);
|
||||
times.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
times.sort_by(f64::total_cmp);
|
||||
eprintln!("{} triangles, collapsed={collapsed}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[2], times[0], times[4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Polygon fill drag transitions preserve already painted targets
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::Channel;
|
||||
use texturecraft_engine::geom::{glam::Vec2, primitives};
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
#[test]
|
||||
fn changing_layers_during_a_box_drag_preserves_the_first_fill() {
|
||||
let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
|
||||
let first = session.selected_layer().unwrap();
|
||||
execute(&mut session, "layer.add.paint", &json!({})).unwrap();
|
||||
let second = session.selected_layer().unwrap();
|
||||
execute(&mut session, "layer.select", &json!({"layer": first.0})).unwrap();
|
||||
let history = session.history_labels().len();
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
execute(&mut session, "layer.select", &json!({"layer": second.0})).unwrap();
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap();
|
||||
session.end_polygon_fill_box();
|
||||
|
||||
assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some(), "the first layer keeps its fill");
|
||||
assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_some(), "the new target receives the next fill");
|
||||
assert_eq!(session.history_labels().len(), history + 2, "each target has its own undo step");
|
||||
session.undo().unwrap();
|
||||
assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some());
|
||||
assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_from_content_to_mask_during_a_box_drag_preserves_content() {
|
||||
let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
execute(&mut session, "mask.add.black", &json!({})).unwrap();
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "content"})).unwrap();
|
||||
let history = session.history_labels().len();
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap();
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap();
|
||||
session.end_polygon_fill_box();
|
||||
|
||||
assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some(), "switching to the mask keeps the content fill");
|
||||
assert_eq!(session.history_labels().len(), history + 2);
|
||||
session.undo().unwrap();
|
||||
assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some());
|
||||
assert!(session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release performance measurement"]
|
||||
fn benchmark_live_box_fill() {
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] {
|
||||
let triangles = mesh.triangle_count();
|
||||
let mut session = Session::new_project("benchmark", mesh, "test", None, 1024).unwrap();
|
||||
let viewport = Vec2::new(1920.0, 1080.0);
|
||||
let start = Instant::now();
|
||||
session.drag_polygon_fill_box(viewport * 0.4, viewport * 0.6, viewport).unwrap();
|
||||
let first_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
let mut times = Vec::new();
|
||||
for step in 1..=12 {
|
||||
let radius = 0.1 + step as f32 * 0.02;
|
||||
let start = Instant::now();
|
||||
black_box(session.drag_polygon_fill_box(viewport * (0.5 - radius), viewport * (0.5 + radius), viewport).unwrap());
|
||||
times.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
let (corner, opposite) = (viewport * 0.16, viewport * 0.84);
|
||||
session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
|
||||
let start = Instant::now();
|
||||
for _ in 0..1000 {
|
||||
black_box(session.drag_polygon_fill_box(corner, opposite, viewport).unwrap());
|
||||
}
|
||||
let unchanged_us = start.elapsed().as_secs_f64() * 1000.0;
|
||||
session.end_polygon_fill_box();
|
||||
let start = Instant::now();
|
||||
session.update();
|
||||
let composite_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
times.sort_by(f64::total_cmp);
|
||||
let memory = session.memory();
|
||||
eprintln!(
|
||||
"{name}: {triangles} triangles, first={first_ms:.3} ms, growing median={:.3} ms max={:.3} ms, unchanged mean={unchanged_us:.3} us, composite={composite_ms:.3} ms, pixels={} bytes composites={} bytes cache={} bytes",
|
||||
times[6], times[11], memory.pixels, memory.composites, memory.cache
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! rendered once at the start of a stroke.
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_geom::glam::{Mat4, Vec2, Vec3};
|
||||
use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4};
|
||||
use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera};
|
||||
|
||||
const BAND: usize = 16;
|
||||
@@ -55,14 +55,26 @@ impl EyeDepth {
|
||||
|
||||
/// The eye-distance buffer, plus the nearest triangle per pixel when `record_triangles` is set.
|
||||
fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool) -> EyeDepth {
|
||||
// Capping storage dimensions must not change the camera's projection
|
||||
let projection = camera.proj(width.max(1) as f32 / height.max(1) as f32);
|
||||
let view = camera.view();
|
||||
let view_proj = projection * view;
|
||||
let depth_key = |view_depth: f32| if camera.ortho { view_depth } else { -view_depth.recip() };
|
||||
let inverse_projection = projection.inverse();
|
||||
let clip_depth = |z: f32| {
|
||||
let point = inverse_projection * Vec4::new(0.0, 0.0, z, 1.0);
|
||||
depth_key(-point.z / point.w)
|
||||
};
|
||||
let depth_range = clip_depth(0.0)..=clip_depth(1.0);
|
||||
let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE));
|
||||
let size = Vec2::new(width as f32, height as f32);
|
||||
let view_proj = camera.view_proj(size.x / size.y);
|
||||
let eye = camera.eye();
|
||||
// Brush depth closes seams, but expanding triangle IDs can expose hidden faces at silhouettes
|
||||
let edge_tolerance = if record_triangles { 0.0 } else { EDGE_TOLERANCE };
|
||||
|
||||
// Project every vertex once
|
||||
let screen: Vec<Option<Vec2>> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect();
|
||||
let vertex_distance: Vec<f32> = mesh.positions.iter().map(|position| position.distance(eye)).collect();
|
||||
// Inverse view depth is affine in perspective and avoids the precision loss of normalized clip depth
|
||||
let vertex_depth: Vec<f32> = mesh.positions.iter().map(|position| depth_key(-(view * position.extend(1.0)).z)).collect();
|
||||
|
||||
// Bin each triangle into the bands of rows it covers
|
||||
let mut bands: Vec<Vec<u32>> = vec![Vec::new(); (height as usize).div_ceil(BAND)];
|
||||
@@ -75,6 +87,7 @@ impl EyeDepth {
|
||||
if bottom <= top || !top.is_finite() || !bottom.is_finite() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (first_band, last_band) = (top as usize / BAND, (bottom as usize).saturating_sub(1) / BAND);
|
||||
for band in bands.iter_mut().take(last_band + 1).skip(first_band) {
|
||||
band.push(triangle as u32);
|
||||
@@ -97,7 +110,7 @@ impl EyeDepth {
|
||||
continue;
|
||||
};
|
||||
|
||||
let corner_distance = corners.map(|vertex| vertex_distance.get(vertex).copied().unwrap_or(f32::MAX));
|
||||
let corner_depth = corners.map(|vertex| vertex_depth.get(vertex).copied().unwrap_or(f32::MAX));
|
||||
let area = (*second_point - *first_point).perp_dot(*third_point - *first_point);
|
||||
if area.abs() < MIN_SCREEN_AREA {
|
||||
continue;
|
||||
@@ -113,16 +126,17 @@ impl EyeDepth {
|
||||
let first_weight = (*third_point - *second_point).perp_dot(sample - *second_point) / area;
|
||||
let second_weight = (*first_point - *third_point).perp_dot(sample - *third_point) / area;
|
||||
let third_weight = 1.0 - first_weight - second_weight;
|
||||
if first_weight < -EDGE_TOLERANCE || second_weight < -EDGE_TOLERANCE || third_weight < -EDGE_TOLERANCE {
|
||||
if first_weight < -edge_tolerance || second_weight < -edge_tolerance || third_weight < -edge_tolerance {
|
||||
continue;
|
||||
}
|
||||
|
||||
let distance = first_weight * corner_distance[0] + second_weight * corner_distance[1] + third_weight * corner_distance[2];
|
||||
let depth = first_weight * corner_depth[0] + second_weight * corner_depth[1] + third_weight * corner_depth[2];
|
||||
let at = (row - first_row) * width as usize + column;
|
||||
if let Some(slot) = band_dist.get_mut(at)
|
||||
&& distance < *slot
|
||||
&& depth_range.contains(&depth)
|
||||
&& depth < *slot
|
||||
{
|
||||
*slot = distance;
|
||||
*slot = depth;
|
||||
if let Some(nearest) = band_triangles.as_deref_mut().and_then(|triangles| triangles.get_mut(at)) {
|
||||
*nearest = candidate;
|
||||
}
|
||||
@@ -130,6 +144,16 @@ impl EyeDepth {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert only the winning depths to eye distances for brush visibility queries
|
||||
for (row, distances) in band_dist.chunks_mut(width as usize).enumerate() {
|
||||
let view_y = (1.0 - (first_row as f32 + row as f32 + 0.5) / size.y * 2.0) / projection.y_axis.y;
|
||||
for (column, distance) in distances.iter_mut().enumerate().filter(|(_, distance)| **distance != f32::MAX) {
|
||||
let view_x = ((column as f32 + 0.5) / size.x * 2.0 - 1.0) / projection.x_axis.x;
|
||||
let radial_squared = view_x * view_x + view_y * view_y;
|
||||
*distance = if camera.ortho { (radial_squared + *distance * *distance).sqrt() } else { (radial_squared + 1.0).sqrt() / -*distance };
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
EyeDepth { width, height, view_proj, eye, dist, triangle, bias: mesh.radius() * BIAS_PER_RADIUS }
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Visibility agrees with the surface under each pixel
|
||||
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
use texturecraft_paint::EyeDepth;
|
||||
|
||||
#[test]
|
||||
fn a_large_front_triangle_occludes_a_small_rear_triangle() {
|
||||
let positions = vec![
|
||||
Vec3::new(-4.0, -4.0, 0.0),
|
||||
Vec3::new(4.0, -4.0, 0.0),
|
||||
Vec3::new(0.0, 4.0, 0.0),
|
||||
Vec3::new(-0.5, -0.5, -1.0),
|
||||
Vec3::new(0.5, -0.5, -1.0),
|
||||
Vec3::new(0.0, 0.5, -1.0),
|
||||
];
|
||||
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 6], (0..6).collect(), "m").unwrap();
|
||||
|
||||
for ortho in [false, true] {
|
||||
let camera = OrbitCamera { pitch: 0.0, ortho, ..Default::default() };
|
||||
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128);
|
||||
assert_eq!(depth.triangle[64 * 128 + 64], 0, "orthographic: {ortho}");
|
||||
assert!(!depth.visible(Vec3::new(0.0, 0.0, -1.0)), "the rear face is hidden");
|
||||
assert!(depth.visible(Vec3::ZERO), "the front face is visible");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release performance measurement"]
|
||||
fn benchmark_eye_depth() {
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] {
|
||||
let mut camera = OrbitCamera::default();
|
||||
let (low, high) = mesh.bounds();
|
||||
camera.frame(low, high);
|
||||
for triangles in [false, true] {
|
||||
let mut times = Vec::new();
|
||||
for iteration in 0..12 {
|
||||
let start = Instant::now();
|
||||
black_box(if triangles { EyeDepth::render_with_triangles(&mesh, &camera, 960, 540) } else { EyeDepth::render(&mesh, &camera, 960, 540) });
|
||||
if iteration >= 2 {
|
||||
times.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
}
|
||||
times.sort_by(f64::total_cmp);
|
||||
eprintln!("{name}: {} triangles, record={triangles}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[5], times[0], times[9]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perspective_depth_matches_ray_intersections() {
|
||||
use texturecraft_geom::Bvh;
|
||||
|
||||
let positions = vec![Vec3::new(-3.0, -2.0, 2.0), Vec3::new(3.0, -2.0, -2.0), Vec3::new(0.0, 3.0, 0.0)];
|
||||
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap();
|
||||
let camera = OrbitCamera { pitch: 0.0, ..Default::default() };
|
||||
let bvh = Bvh::new(&mesh);
|
||||
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128);
|
||||
|
||||
for (x, y) in [(40, 60), (64, 64), (88, 60)] {
|
||||
let ndc = Vec2::new((x as f32 + 0.5) / 64.0 - 1.0, 1.0 - (y as f32 + 0.5) / 64.0);
|
||||
let ray = camera.ray(ndc, 1.0);
|
||||
let hit = bvh.closest(ray.origin, ray.dir, f32::MAX).unwrap();
|
||||
let expected = (ray.origin + ray.dir * hit.t).distance(camera.eye());
|
||||
assert!((depth.dist[y * 128 + x] - expected).abs() < 0.001, "pixel {x},{y}: {} vs {expected}", depth.dist[y * 128 + x]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capped_buffers_keep_the_requested_viewport_aspect() {
|
||||
let positions = vec![Vec3::new(4.0, -1.0, 0.0), Vec3::new(7.0, -1.0, 0.0), Vec3::new(5.5, 1.0, 0.0)];
|
||||
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap();
|
||||
let camera = OrbitCamera { pitch: 0.0, ..Default::default() };
|
||||
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 8192, 1024);
|
||||
let point = camera.project(Vec3::new(5.5, 0.0, 0.0), 8.0).unwrap();
|
||||
let x = ((point.x * 0.5 + 0.5) * depth.width as f32) as usize;
|
||||
let y = ((0.5 - point.y * 0.5) * depth.height as f32) as usize;
|
||||
|
||||
assert_eq!(depth.triangle[y * depth.width as usize + x], 0, "the triangle stays under its viewport position after the buffer is capped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangle_ids_do_not_expand_hidden_cube_faces_past_the_silhouette() {
|
||||
use std::collections::HashSet;
|
||||
use texturecraft_geom::{NO_TRI, primitives};
|
||||
|
||||
let mesh = primitives::cube(1.0);
|
||||
let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.4, ..Default::default() };
|
||||
let (low, high) = mesh.bounds();
|
||||
camera.frame(low, high);
|
||||
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 400, 400);
|
||||
let visible: HashSet<_> = depth.triangle.iter().copied().filter(|triangle| *triangle != NO_TRI).collect();
|
||||
|
||||
assert_eq!(visible.len(), mesh.triangle_count() / 2, "only the three front faces own screen pixels");
|
||||
}
|
||||
@@ -1036,7 +1036,8 @@ fn polygon_fill_input(
|
||||
ui.data_mut(|data| data.insert_temp(origin_id, press));
|
||||
}
|
||||
|
||||
let origin = ui.data(|data| data.get_temp::<Pos2>(origin_id));
|
||||
// Consume the origin on release so a new press cannot resume the previous rectangle
|
||||
let origin = if released { ui.data_mut(|data| data.remove_temp::<Pos2>(origin_id)) } else { ui.data(|data| data.get_temp::<Pos2>(origin_id)) };
|
||||
let pointer = ui.input(|input| input.pointer.latest_pos());
|
||||
let (filled, dragged_box) = match (origin, pointer) {
|
||||
_ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None),
|
||||
@@ -1046,12 +1047,18 @@ fn polygon_fill_input(
|
||||
let filled = app.session.end_polygon_fill_box();
|
||||
(Some(shown.map(|_| filled)), None)
|
||||
}
|
||||
_ if released => {
|
||||
app.session.end_polygon_fill_box();
|
||||
(None, None)
|
||||
}
|
||||
(Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))),
|
||||
_ => (None, None),
|
||||
};
|
||||
|
||||
if let Some(Err(error)) = filled {
|
||||
app.toast(error.to_string(), true);
|
||||
}
|
||||
|
||||
dragged_box
|
||||
}
|
||||
|
||||
|
||||
@@ -84,3 +84,60 @@ fn a_box_drag_in_the_2d_view_is_one_fill() {
|
||||
assert_eq!(history(&harness).len(), before + 1);
|
||||
assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_press_after_release_does_not_resume_the_previous_box() {
|
||||
let mut harness = polygon_fill_app();
|
||||
let center = harness.state().viewport_rect.center();
|
||||
drag(&mut harness, center - vec2(40.0, 40.0), center + vec2(40.0, 40.0));
|
||||
let history_after_drag = history(&harness);
|
||||
let tiles_after_drag = painted_tiles(&harness);
|
||||
|
||||
// Start the next gesture on the frame immediately after release
|
||||
let point = center - vec2(80.0, 80.0);
|
||||
harness
|
||||
.input_mut()
|
||||
.events
|
||||
.extend([Event::PointerMoved(point), Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]);
|
||||
harness.run_steps(1);
|
||||
assert_eq!(painted_tiles(&harness), tiles_after_drag, "a press alone must not refill the old rectangle");
|
||||
|
||||
harness.event(Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
harness.run_steps(1);
|
||||
assert_eq!(history(&harness).len(), history_after_drag.len() + 1, "only the new click records a step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"]
|
||||
fn polygon_fill_snapshots() {
|
||||
let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return };
|
||||
|
||||
std::fs::create_dir_all(&directory).unwrap();
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
let adapter = harness.state().render_state.as_ref().unwrap().adapter.get_info();
|
||||
eprintln!("Offscreen adapter: {} ({:?}), driver {} {}", adapter.name, adapter.backend, adapter.driver, adapter.driver_info);
|
||||
harness.state_mut().session.tool.tool = Tool::PolygonFill;
|
||||
harness.run_steps(6);
|
||||
harness.render().unwrap().save(directory.join("polygon-fill-properties.png")).unwrap();
|
||||
|
||||
let center = harness.state().viewport_rect.center();
|
||||
let origin = center - vec2(85.0, 70.0);
|
||||
let opposite = center + vec2(85.0, 70.0);
|
||||
harness.hover_at(origin);
|
||||
harness.event(Event::PointerButton { pos: origin, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
harness.run_steps(1);
|
||||
harness.hover_at(opposite);
|
||||
harness.run_steps(6);
|
||||
harness.render().unwrap().save(directory.join("polygon-fill-drag-3d.png")).unwrap();
|
||||
harness.event(Event::PointerButton { pos: opposite, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
harness.run_steps(6);
|
||||
harness.render().unwrap().save(directory.join("polygon-fill-complete-3d.png")).unwrap();
|
||||
|
||||
texturecraft_engine::execute(&mut harness.state_mut().session, "mask.add.black", &serde_json::Value::Null).unwrap();
|
||||
let view = harness.state().viewport_rect;
|
||||
let center = pos2(view.right() + view.width() * 0.5, view.center().y);
|
||||
drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0));
|
||||
harness.run_steps(6);
|
||||
harness.render().unwrap().save(directory.join("polygon-fill-mask-2d.png")).unwrap();
|
||||
}
|
||||
Reference in new issue
Block a user