Sketch: sample display curves without a heap copy per subdivision (#10342)

The pixel-bounded curve sampler that draws sketch curves and profile
outlines ran again on every camera move, and each subdivision step
allocated: every span's control points were a Vec, splitting one in
half built a Vec per de Casteljau level, each node's projection was
collected into a Vec, and every drawn part grew from two vertices.

The control points now live inline in a fixed array (`Hull`, at most a
degree-9 Bezier), the halves are worked out in place with the same
`mix` level by level, the projection goes into a reused array, and a
new part starts with room for eight vertices. The arithmetic and its
order are unchanged, so the points are the same bit for bit.

Tests: `samples_the_same_points_bit_for_bit_as_the_reference` keeps the
previous sampler as a reference and compares paths, quality and budget
use over every segment kind, slanted and far-off planes, orthographic
and perspective views from far out to far in, clipped and unclipped,
with ample and spent budgets. Ignored timings:
`sampler_cost_against_the_reference` (render) and
`sketch_scene_cost_while_the_camera_moves` (ui-egui).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
kaltenbrunnermarkus
2026-11-01 00:10:37 +00:00
committed by GitHub
parent e0582668bb
commit c25c2f3a21
4 changed files with 464 additions and 44 deletions
+82 -43
View File
@@ -7,6 +7,8 @@ use crate::Mat4;
const MAX_VERTICES: usize = 4096;
const MAX_DEPTH: u8 = 24;
const PIXEL_ERROR: f64 = 0.5;
/// The vertices a new part has room for before it grows.
const PART_CAPACITY: usize = 8;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PixelCurveView {
@@ -54,20 +56,44 @@ fn mix(a: H, b: H, t: f64) -> H {
std::array::from_fn(|i| a[i] * (1.0 - t) + b[i] * t)
}
fn halves(c: &[H]) -> (Vec<H>, Vec<H>) {
let mut work = c.to_vec();
let mut l = Vec::with_capacity(c.len());
let mut r = Vec::with_capacity(c.len());
while let (Some(a), Some(b)) = (work.first(), work.last()) {
l.push(*a);
r.push(*b);
if work.len() == 1 {
break;
}
work = work.windows(2).map(|p| mix(p[0], p[1], 0.5)).collect();
/// The most control points of one span: a Bézier of the highest degree.
const MAX_CONTROLS: usize = solidcraft_geom::MAX_BEZIER_DEGREE + 1;
/// One span's homogeneous control points, kept inline: the sampler splits and projects
/// thousands of them per curve and view, and a `Vec` each was most of its allocations.
#[derive(Clone, Copy)]
struct Hull {
len: usize,
p: [H; MAX_CONTROLS],
}
impl Hull {
fn new(points: &[H]) -> Option<Hull> {
let mut p = [[0.0; 4]; MAX_CONTROLS];
p.get_mut(..points.len())?.copy_from_slice(points);
Some(Hull { len: points.len(), p })
}
fn points(&self) -> &[H] {
&self.p[..self.len]
}
/// The two halves at t = 0.5 (de Casteljau), each level's midpoints worked out in place
/// with the same `mix` as one level at a time.
fn halves(&self) -> (Hull, Hull) {
let n = self.len;
let mut work = self.p;
let (mut l, mut r) = (Hull { len: n, p: [[0.0; 4]; MAX_CONTROLS] }, Hull { len: n, p: [[0.0; 4]; MAX_CONTROLS] });
for level in 0..n {
let last = n - 1 - level;
l.p[level] = work[0];
r.p[last] = work[last];
for i in 0..last {
work[i] = mix(work[i], work[i + 1], 0.5);
}
}
(l, r)
}
r.reverse();
(l, r)
}
fn world(h: H) -> Option<Vec3> {
@@ -98,7 +124,7 @@ fn distance_segment(p: Vec2, a: Vec2, b: Vec2) -> f64 {
p.dist(a + d * t)
}
fn controls(segment: &Seg2, plane: &Plane) -> Option<(Vec<Vec<H>>, H)> {
fn controls(segment: &Seg2, plane: &Plane) -> Option<(Vec<Hull>, H)> {
let mut terms: H = [0.0; 4];
let mut h = |p: Vec2, w: f64| {
for (r, (o, x, y)) in [(plane.origin.x, plane.x.x, plane.y.x), (plane.origin.y, plane.x.y, plane.y.y), (plane.origin.z, plane.x.z, plane.y.z)]
@@ -112,30 +138,34 @@ fn controls(segment: &Seg2, plane: &Plane) -> Option<(Vec<Vec<H>>, H)> {
[p.x * w, p.y * w, p.z * w, w]
};
let spans = match *segment {
Seg2::Line { a, b } => vec![vec![h(a, 1.0), h(b, 1.0)]],
Seg2::Cubic { p0, p1, p2, p3 } => vec![vec![h(p0, 1.0), h(p1, 1.0), h(p2, 1.0), h(p3, 1.0)]],
Seg2::Conic { a, apex, b, w } if w > 0.0 => vec![vec![h(a, 1.0), h(apex, w), h(b, 1.0)]],
Seg2::Line { a, b } => vec![Hull::new(&[h(a, 1.0), h(b, 1.0)])?],
Seg2::Cubic { p0, p1, p2, p3 } => vec![Hull::new(&[h(p0, 1.0), h(p1, 1.0), h(p2, 1.0), h(p3, 1.0)])?],
Seg2::Conic { a, apex, b, w } if w > 0.0 => vec![Hull::new(&[h(a, 1.0), h(apex, w), h(b, 1.0)])?],
Seg2::Bezier { n, p } if (1..=solidcraft_geom::MAX_BEZIER_DEGREE as u8).contains(&n) => {
vec![p[..=n as usize].iter().map(|p| h(*p, 1.0)).collect()]
let mut hull = Hull { len: n as usize + 1, p: [[0.0; 4]; MAX_CONTROLS] };
for (out, p) in hull.p.iter_mut().zip(&p[..=n as usize]) {
*out = h(*p, 1.0);
}
vec![hull]
}
Seg2::Arc { center, radius, start, sweep }
if radius > 0.0 && start.is_finite() && sweep.is_finite() && sweep.abs() <= std::f64::consts::TAU + 1e-9 =>
{
let count = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
(0..count)
.map(|i| {
let a = start + sweep * i as f64 / count as f64;
let b = start + sweep * (i + 1) as f64 / count as f64;
let mid = (a + b) * 0.5;
let w = ((b - a) * 0.5).cos();
let p = |t: f64, r: f64| center + Vec2::new(t.cos(), t.sin()) * r;
vec![h(p(a, radius), 1.0), h(p(mid, radius / w), w), h(p(b, radius), 1.0)]
})
.collect()
let mut spans = Vec::with_capacity(count);
for i in 0..count {
let a = start + sweep * i as f64 / count as f64;
let b = start + sweep * (i + 1) as f64 / count as f64;
let mid = (a + b) * 0.5;
let w = ((b - a) * 0.5).cos();
let p = |t: f64, r: f64| center + Vec2::new(t.cos(), t.sin()) * r;
spans.push(Hull::new(&[h(p(a, radius), 1.0), h(p(mid, radius / w), w), h(p(b, radius), 1.0)])?);
}
spans
}
_ => return None,
};
spans.iter().flatten().all(|p| p.iter().all(|x| x.is_finite()) && p[3] > 0.0).then_some((spans, terms))
spans.iter().flat_map(Hull::points).all(|p| p.iter().all(|x| x.is_finite()) && p[3] > 0.0).then_some((spans, terms))
}
/// Samples one exact segment to a conservative 0.5 physical-pixel control-hull
@@ -168,25 +198,30 @@ fn sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut Sam
out.quality = SamplingQuality::Invalid;
return out;
};
let mut stack: Vec<_> = spans
.into_iter()
.rev()
.map(|c| {
let magnitude: H = std::array::from_fn(|i| c.iter().map(|p| p[i].abs()).fold(source_terms[i], f64::max));
let terms: H = std::array::from_fn(|r| (0..4).map(|i| view.vp.0[i][r].abs() * magnitude[i]).sum());
(c, 0u8, terms)
})
.collect();
// Depth first: the spans not yet started, and one right half per level below.
let mut stack = Vec::with_capacity(spans.len() + usize::from(MAX_DEPTH) + 1);
for hull in spans.into_iter().rev() {
let c = hull.points();
let magnitude: H = std::array::from_fn(|i| c.iter().map(|p| p[i].abs()).fold(source_terms[i], f64::max));
let terms: H = std::array::from_fn(|r| (0..4).map(|i| view.vp.0[i][r].abs() * magnitude[i]).sum());
stack.push((hull, 0u8, terms));
}
let mut connected = false;
let mut nodes = 0usize;
while let Some((c, depth, terms)) = stack.pop() {
let mut q: [H; MAX_CONTROLS] = [[0.0; 4]; MAX_CONTROLS];
while let Some((hull, depth, terms)) = stack.pop() {
if budget.remaining_nodes == 0 || nodes == 32_768 {
out.quality = SamplingQuality::BudgetLimited;
break;
}
budget.remaining_nodes -= 1;
nodes += 1;
let q: Vec<H> = c.iter().map(|h| project_h(view.vp, *h)).collect();
let c = hull.points();
let n = c.len();
for (q, h) in q.iter_mut().zip(c) {
*q = project_h(view.vp, *h);
}
let q = &q[..n];
if q.iter().flatten().any(|x| !x.is_finite()) {
out.quality = SamplingQuality::Invalid;
break;
@@ -206,7 +241,7 @@ fn sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut Sam
continue;
}
let positive = q.iter().all(|p| p[3] > 1e-12);
let depth_safe = c.len() == 2 || (4..7).all(|i| q.iter().all(|p| distances(*p, view, clip_xy)[i] >= 0.0));
let depth_safe = n == 2 || (4..7).all(|i| q.iter().all(|p| distances(*p, view, clip_xy)[i] >= 0.0));
let flat = positive
&& q.first().zip(q.last()).is_some_and(|(a, b)| {
let (a, b) = (screen(*a, view), screen(*b, view));
@@ -235,7 +270,7 @@ fn sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut Sam
connected = false;
continue;
}
let (l, r) = halves(&c);
let (l, r) = hull.halves();
stack.push((r, depth + 1, terms));
stack.push((l, depth + 1, terms));
continue;
@@ -276,7 +311,11 @@ fn sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut Sam
part.push(b);
}
} else {
out.parts.push(vec![a, b]);
// Room for a few chords: most visible pieces take several, and growing from two
// reallocated each part twice.
let mut part = Vec::with_capacity(PART_CAPACITY);
part.extend([a, b]);
out.parts.push(part);
}
connected = hi == 1.0;
}
+305
View File
@@ -119,3 +119,308 @@ fn invalid_weights_matrices_and_shared_frame_exhaustion_are_explicit() {
assert_eq!(path.quality, SamplingQuality::BudgetLimited);
assert!(path.vertex_count <= 16);
}
// The sampler as it was before its control points were kept inline and each point's
// projection and clip distances were worked out once per node, kept to compare against.
fn reference_controls(segment: &Seg2, plane: &Plane) -> Option<(Vec<Vec<H>>, H)> {
let mut terms: H = [0.0; 4];
let mut h = |p: Vec2, w: f64| {
for (r, (o, x, y)) in [(plane.origin.x, plane.x.x, plane.y.x), (plane.origin.y, plane.x.y, plane.y.y), (plane.origin.z, plane.x.z, plane.y.z)]
.into_iter()
.enumerate()
{
terms[r] = terms[r].max((o.abs() + x.abs() * p.x.abs() + y.abs() * p.y.abs()) * w.abs());
}
terms[3] = terms[3].max(w.abs());
let p = plane.to_world(p);
[p.x * w, p.y * w, p.z * w, w]
};
let spans = match *segment {
Seg2::Line { a, b } => vec![vec![h(a, 1.0), h(b, 1.0)]],
Seg2::Cubic { p0, p1, p2, p3 } => vec![vec![h(p0, 1.0), h(p1, 1.0), h(p2, 1.0), h(p3, 1.0)]],
Seg2::Conic { a, apex, b, w } if w > 0.0 => vec![vec![h(a, 1.0), h(apex, w), h(b, 1.0)]],
Seg2::Bezier { n, p } if (1..=solidcraft_geom::MAX_BEZIER_DEGREE as u8).contains(&n) => {
vec![p[..=n as usize].iter().map(|p| h(*p, 1.0)).collect()]
}
Seg2::Arc { center, radius, start, sweep }
if radius > 0.0 && start.is_finite() && sweep.is_finite() && sweep.abs() <= std::f64::consts::TAU + 1e-9 =>
{
let count = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
(0..count)
.map(|i| {
let a = start + sweep * i as f64 / count as f64;
let b = start + sweep * (i + 1) as f64 / count as f64;
let mid = (a + b) * 0.5;
let w = ((b - a) * 0.5).cos();
let p = |t: f64, r: f64| center + Vec2::new(t.cos(), t.sin()) * r;
vec![h(p(a, radius), 1.0), h(p(mid, radius / w), w), h(p(b, radius), 1.0)]
})
.collect()
}
_ => return None,
};
spans.iter().flatten().all(|p| p.iter().all(|x| x.is_finite()) && p[3] > 0.0).then_some((spans, terms))
}
fn reference_halves(c: &[H]) -> (Vec<H>, Vec<H>) {
let mut work = c.to_vec();
let mut l = Vec::with_capacity(c.len());
let mut r = Vec::with_capacity(c.len());
while let (Some(a), Some(b)) = (work.first(), work.last()) {
l.push(*a);
r.push(*b);
if work.len() == 1 {
break;
}
work = work.windows(2).map(|p| mix(p[0], p[1], 0.5)).collect();
}
r.reverse();
(l, r)
}
fn reference_sample(segment: &Seg2, plane: &Plane, view: &PixelCurveView, budget: &mut SamplingBudget, clip_xy: bool) -> SampledPath {
let mut out = SampledPath { parts: Vec::new(), quality: SamplingQuality::Complete, vertex_count: 0 };
if !view.width_px.is_finite()
|| !view.height_px.is_finite()
|| view.width_px <= 0.0
|| view.height_px <= 0.0
|| view.width_px > 1e7
|| view.height_px > 1e7
|| view.vp.0.iter().flatten().any(|x| !x.is_finite())
{
out.quality = SamplingQuality::Invalid;
return out;
}
let Some((spans, source_terms)) = reference_controls(segment, plane) else {
out.quality = SamplingQuality::Invalid;
return out;
};
let mut stack: Vec<_> = spans
.into_iter()
.rev()
.map(|c| {
let magnitude: H = std::array::from_fn(|i| c.iter().map(|p| p[i].abs()).fold(source_terms[i], f64::max));
let terms: H = std::array::from_fn(|r| (0..4).map(|i| view.vp.0[i][r].abs() * magnitude[i]).sum());
(c, 0u8, terms)
})
.collect();
let mut connected = false;
let mut nodes = 0usize;
while let Some((c, depth, terms)) = stack.pop() {
if budget.remaining_nodes == 0 || nodes == 32_768 {
out.quality = SamplingQuality::BudgetLimited;
break;
}
budget.remaining_nodes -= 1;
nodes += 1;
let q: Vec<H> = c.iter().map(|h| project_h(view.vp, *h)).collect();
if q.iter().flatten().any(|x| !x.is_finite()) {
out.quality = SamplingQuality::Invalid;
break;
}
let e: H = terms.map(|t| t * f64::EPSILON * (f64::from(depth) + 4.0) * 64.0);
let clip_error = [
e[0] + e[3] * (1.0 + 2.0 / view.width_px),
e[0] + e[3] * (1.0 + 2.0 / view.width_px),
e[1] + e[3] * (1.0 + 2.0 / view.height_px),
e[1] + e[3] * (1.0 + 2.0 / view.height_px),
e[2],
e[2] + e[3],
e[3],
];
if (0..7).any(|i| q.iter().all(|p| distances(*p, view, clip_xy)[i] < -clip_error[i])) {
connected = false;
continue;
}
let positive = q.iter().all(|p| p[3] > 1e-12);
let depth_safe = c.len() == 2 || (4..7).all(|i| q.iter().all(|p| distances(*p, view, clip_xy)[i] >= 0.0));
let flat = positive
&& q.first().zip(q.last()).is_some_and(|(a, b)| {
let (a, b) = (screen(*a, view), screen(*b, view));
let magnitude = q.iter().map(|p| screen(*p, view).len()).fold(1.0, f64::max);
// Keep floating-point roundoff inside the advertised bound.
// Absolute summands also cover cancellation in VP multiplication.
// Subdivision propagates roundoff from the original homogeneous hull.
let projection_error = q
.iter()
.map(|p| {
let safe_w = p[3] - e[3];
if safe_w <= 0.0 {
return f64::INFINITY;
}
let x = (e[0] + (p[0] / p[3]).abs() * e[3]) / safe_w * view.width_px * 0.5;
let y = (e[1] + (p[1] / p[3]).abs() * e[3]) / safe_w * view.height_px * 0.5;
x.hypot(y)
})
.fold(0.0, f64::max);
let allowance = projection_error + magnitude * f64::EPSILON * 128.0;
allowance < PIXEL_ERROR && q.iter().all(|p| distance_segment(screen(*p, view), a, b) + allowance <= PIXEL_ERROR)
});
if !flat || !depth_safe {
if depth == MAX_DEPTH || out.vertex_count >= MAX_VERTICES {
out.quality = SamplingQuality::BudgetLimited;
connected = false;
continue;
}
let (l, r) = reference_halves(&c);
stack.push((r, depth + 1, terms));
stack.push((l, depth + 1, terms));
continue;
}
let (Some(a), Some(b), Some(qa), Some(qb)) = (c.first(), c.last(), q.first(), q.last()) else { continue };
let mut lo: f64 = 0.0;
let mut hi: f64 = 1.0;
for (a, b) in distances(*qa, view, clip_xy).into_iter().zip(distances(*qb, view, clip_xy)) {
if a < 0.0 && b < 0.0 {
hi = -1.0;
break;
}
if a < 0.0 {
lo = lo.max(a / (a - b));
} else if b < 0.0 {
hi = hi.min(a / (a - b));
}
}
if lo > hi {
connected = false;
continue;
}
let (Some(a), Some(b)) = (world(mix(*a, *b, lo)), world(mix(*a, *b, hi))) else {
out.quality = SamplingQuality::Invalid;
break;
};
// Exact consecutive subdivision endpoints share their homogeneous value.
let join = connected && lo == 0.0 && out.parts.last().and_then(|p| p.last()).is_some_and(|p| *p == a);
let need = if join { 1 } else { 2 };
if need > budget.remaining_vertices || out.vertex_count + need > MAX_VERTICES {
out.quality = SamplingQuality::BudgetLimited;
break;
}
budget.remaining_vertices -= need;
out.vertex_count += need;
if join {
if let Some(part) = out.parts.last_mut() {
part.push(b);
}
} else {
out.parts.push(vec![a, b]);
}
connected = hi == 1.0;
}
out
}
fn same_path(a: &SampledPath, b: &SampledPath) -> bool {
let bits = |p: &SampledPath| -> Vec<Vec<[u64; 3]>> {
p.parts.iter().map(|part| part.iter().map(|v| [v.x, v.y, v.z].map(f64::to_bits)).collect()).collect()
};
a.quality == b.quality && a.vertex_count == b.vertex_count && bits(a) == bits(b)
}
/// The sampler gives the very same points, bit for bit, as before it was made quicker: every
/// kind of segment, on planes at a slant and far off, in orthographic and perspective views
/// zoomed from far out to far in, cut by the view's edges and the near plane, clipped and
/// unclipped, with ample and with nearly spent budgets.
#[test]
fn samples_the_same_points_bit_for_bit_as_the_reference() {
let mut degree9 = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL];
for (i, p) in degree9.iter_mut().enumerate().take(10) {
let t = i as f64 / 9.0;
*p = Vec2::new(t * 2.0 - 1.0, ((i % 3) as f64 - 1.0) * 0.8);
}
let segments = [
Seg2::Line { a: Vec2::new(-0.7, -0.3), b: Vec2::new(0.9, 0.4) },
Seg2::Line { a: Vec2::new(-50.0, 0.1), b: Vec2::new(50.0, 0.2) },
Seg2::Cubic { p0: Vec2::new(-0.9, 0.0), p1: Vec2::new(0.9, 1.0), p2: Vec2::new(-0.9, -1.0), p3: Vec2::new(0.9, 0.0) },
Seg2::Cubic { p0: Vec2::new(0.0, 0.0), p1: Vec2::new(1.0, 1.0), p2: Vec2::new(0.0, 1.0), p3: Vec2::new(1.0, 0.0) },
Seg2::Conic { a: Vec2::new(-0.5, 0.0), apex: Vec2::new(0.0, 0.6), b: Vec2::new(0.5, 0.0), w: 0.3 },
Seg2::Conic { a: Vec2::new(-0.5, 0.0), apex: Vec2::new(0.0, 0.6), b: Vec2::new(0.5, 0.0), w: 4.0 },
Seg2::Bezier { n: 9, p: degree9 },
Seg2::Bezier { n: 4, p: degree9 },
Seg2::Arc { center: Vec2::ZERO, radius: 0.4, start: 0.3, sweep: std::f64::consts::TAU },
Seg2::Arc { center: Vec2::new(0.2, -0.1), radius: 3.0, start: -1.0, sweep: -2.5 },
Seg2::Arc { center: Vec2::ZERO, radius: 0.2, start: std::f64::consts::PI, sweep: 0.001 },
];
let planes = [
plane(),
Plane::new(Vec3::new(0.0, 0.0, -2.0), Vec3::new(0.8, 0.0, 0.6), Vec3::Y).unwrap(),
Plane::new(Vec3::new(0.0, 0.0, -0.15), Vec3::new(0.6, 0.0, 0.8), Vec3::Y).unwrap(),
Plane::new(Vec3::new(1e6, -3e5, 2.0), Vec3::new(0.0, 0.6, 0.8), Vec3::new(1.0, 0.0, 0.0)).unwrap(),
];
let perspective = |s: f64| PixelCurveView {
vp: Mat4([[s, 0.0, 0.0, 0.0], [0.0, s, 0.0, 0.0], [0.0, 0.0, -1.01, -1.0], [0.0, 0.0, -0.101, 0.0]]),
width_px: 900.0,
height_px: 720.0,
};
let mut far = view(0.2, 1.0);
far.vp.0[3][0] = -2e5;
let views = [
view(0.003, 1.0),
view(0.31, 1.0),
view(3.0, 2.0),
view(400.0, 1.25),
view(1e9, 1.0),
far,
perspective(1.0),
perspective(7.5),
perspective(0.05),
];
let mut compared = 0;
for segment in &segments {
for plane in &planes {
for view in &views {
for clip in [true, false] {
for (vertices, nodes) in [(200_000, 400_000), (40, 1_000), (7, 9)] {
let (mut a, mut b) = (SamplingBudget::new(vertices, nodes), SamplingBudget::new(vertices, nodes));
let new = sample(segment, plane, view, &mut a, clip);
let old = reference_sample(segment, plane, view, &mut b, clip);
assert!(same_path(&new, &old), "{segment:?} on {plane:?} in {view:?}, clipped {clip}, budget {vertices}/{nodes}");
assert_eq!((a.remaining_vertices, a.remaining_nodes), (b.remaining_vertices, b.remaining_nodes));
compared += new.vertex_count;
}
}
}
}
}
assert!(compared > 10_000, "the views sample in earnest: {compared} vertices");
}
/// Times the sampler against the reference on a few thousand cubic Béziers in a fitted view.
/// Run with `--ignored --nocapture` in a release build.
#[test]
#[ignore = "manual sampler measurement"]
fn sampler_cost_against_the_reference() {
let segments: Vec<Seg2> = (0..4096)
.map(|i| {
let (x, y) = ((i % 64) as f64 * 3.0, (i / 64) as f64 * 3.0);
Seg2::Cubic { p0: Vec2::new(x, y), p1: Vec2::new(x + 0.6, y - 0.5), p2: Vec2::new(x + 1.4, y - 0.5), p3: Vec2::new(x + 2.0, y) }
})
.collect();
let v = view(2.0 / 200.0, 1.0);
let time = |f: &dyn Fn(&Seg2, &mut SamplingBudget) -> SampledPath| {
let mut t: Vec<f64> = (0..5)
.map(|_| {
let start = std::time::Instant::now();
let mut budget = SamplingBudget::new(1_000_000, 2_000_000);
let n: usize = segments.iter().map(|s| f(s, &mut budget).vertex_count).sum();
std::hint::black_box(n);
start.elapsed().as_secs_f64() * 1000.0
})
.collect();
t.sort_by(f64::total_cmp);
t[2]
};
for clip in [true, false] {
let mut budget = SamplingBudget::new(1_000_000, 2_000_000);
let vertices: usize = segments.iter().map(|s| sample(s, &plane(), &v, &mut budget, clip).vertex_count).sum();
println!("SAMPLER clip={clip} segments={} nodes={} vertices={vertices}", segments.len(), 2_000_000 - budget.remaining_nodes);
let (mut old, mut new) = (Vec::new(), Vec::new());
for _ in 0..9 {
old.push(time(&|s, b| reference_sample(s, &plane(), &v, b, clip)));
new.push(time(&|s, b| sample(s, &plane(), &v, b, clip)));
}
old.sort_by(f64::total_cmp);
new.sort_by(f64::total_cmp);
println!("SAMPLER clip={clip} reference_ms={:.3} new_ms={:.3} ratio={:.3}", old[4], new[4], new[4] / old[4]);
}
}
+76
View File
@@ -669,3 +669,79 @@ fn many_selected_bodies_hover_cost() {
}
}
}
/// An imported drawing of `k` × `k` closed blobs, four cubic Béziers each, as SVG text.
fn blob_logo(k: usize) -> String {
let mut d = String::new();
for i in 0..k {
for j in 0..k {
let (x, y) = (i as f64 * 3.0, j as f64 * 3.0);
d.push_str(&format!(
"<path d=\"M{x0},{y} C{x1},{y1} {x2},{y1} {x3},{y} C{x4},{y2} {x4},{y3} {x3},{y4} C{x2},{y5} {x1},{y5} {x0},{y4} C{x5},{y3} {x5},{y2} {x0},{y} Z\"/>",
x0 = x,
x1 = x + 0.6,
x2 = x + 1.4,
x3 = x + 2.0,
x4 = x + 2.6,
x5 = x - 0.6,
y1 = y - 0.5,
y2 = y + 0.6,
y3 = y + 1.4,
y4 = y + 2.0,
y5 = y + 2.5,
));
}
}
format!("<svg width=\"{w}mm\" height=\"{w}mm\" viewBox=\"-1 -1 {w} {w}\">{d}</svg>", w = k * 3 + 2)
}
/// Times the sketch scene while the camera orbits and zooms over a large open sketch (an
/// imported drawing): the scene alone on each new view, again on the same view (its sampled
/// curves cached), and a whole headless frame after it. Run with `--ignored --nocapture`.
#[test]
#[ignore = "manual sketch scene measurement"]
fn sketch_scene_cost_while_the_camera_moves() {
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0));
for k in [10, 20, 32] {
let mut h = Harness::new();
h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();
h.app.run("sketch.insert_svg", json!({"text": blob_logo(k)})).unwrap();
h.frames(3);
let st = h.app.session.world_state();
let sid = h.app.session.active_sketch.expect("the sketch is open");
let (curves, profiles) = st.sketch(sid).map_or((0, 0), |ss| (ss.sketch.curves.len(), ss.profiles.len()));
drop(st);
h.app.fit_view();
h.frames(3);
let median = |mut t: Vec<f64>| {
t.sort_by(f64::total_cmp);
(t[t.len() / 2], t[0], t[t.len() - 1])
};
for (label, step) in [("orbit", 0usize), ("zoom", 1), ("orbit-no-fill", 0)] {
if label == "orbit-no-fill" {
h.app.session.visibility.hidden_profiles.push(sid);
}
let (mut fresh, mut again, mut frame, mut lines) = (Vec::new(), Vec::new(), Vec::new(), 0);
for i in 0..30 {
if step == 0 {
h.app.cam.yaw += 0.02;
h.app.cam.pitch = 0.9 + 0.01 * f64::from(i % 5);
} else {
h.app.cam.distance *= if i < 15 { 0.97 } else { 1.0 / 0.97 };
}
let proj = crate::viewport::projection(&h.app, rect);
let mut scene = None;
fresh.push(ms(|| scene = Some(crate::viewport::build_sketch_scene(&h.app, &proj))));
lines = scene.map_or(0, |s| s.merged().lines.len());
again.push(ms(|| drop(crate::viewport::build_sketch_scene(&h.app, &proj))));
frame.push(ms(|| h.frame()));
}
let (f, fmin, fmax) = median(fresh);
let (a, amin, amax) = median(again);
let (fr, frmin, frmax) = median(frame);
println!(
"SKETCHSCENE k={k} curves={curves} profiles={profiles} move={label} scene_new_view_ms={f:.2} ({fmin:.2}-{fmax:.2}) scene_same_view_ms={a:.2} ({amin:.2}-{amax:.2}) frame_ms={fr:.2} ({frmin:.2}-{frmax:.2}) line_bytes={lines}"
);
}
}
}
+1 -1
View File
@@ -1684,7 +1684,7 @@ fn continuity_color(t: &Tokens, verdict: solidcraft_engine::kernel::SeamVerdict)
}
/// A soft dark ellipse on the ground under the shown bodies (darkest in the middle).
fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene {
pub(crate) fn build_sketch_scene(app: &SolveApp, proj: &Proj) -> GpuScene {
let tk = Tokens::get();
let mut sc = GpuScene::default();
let s = &app.session;