perf: avoid computing whole reference orbit when not needed

This commit is contained in:
2026-09-30 19:38:29 +02:00
parent 52e1814266
commit 825bf6474a
4 changed files with 138 additions and 21 deletions
+7 -1
View File
@@ -54,7 +54,13 @@ window/event loop. Not yet supported with `--buddhabrot`. With
`--auto-color-scale`, a downscaled 1-spp `fs_data` prepass
(`ExportRender::ci_range_blocking`, ≤ 1024 px) is histogrammed like the
interactive `CiStats`. The fit is then written into the export's uniforms,
and animations refit every frame from the same start. Run
and animations refit every frame from the same start. With auto-iterations,
a still whose full orbit would be costly (`orbit_secs` > `PROBE_MIN_SECS`)
computes only a prefix (8192 steps, then ×4) and probes it with the same
prepass (`max_escape_blocking`): the shader treats an exhausted reference
as an escape, so once the last probe escape is under half the prefix the
image is unchanged (c = -1.5 at 1e-1000 needs ~10k of the 900k auto steps).
Device setup runs on a thread meanwhile. Run
`mandelbrot --help` for the full list.
`--headless` also has an animation mode, for feeding into `ffmpeg`: give any
+28
View File
@@ -1439,6 +1439,34 @@ impl FractalApp {
self.finish_reference(job, points);
}
/// [`compute_reference_blocking`](Self::compute_reference_blocking), but
/// with the orbit cut after `len` steps; `max_iterations` is unchanged.
/// Returns whether the orbit is the whole one the view asks for (not
/// cut, or it escaped before `len`). Headless probes how far pixels
/// really follow the reference before paying for the rest.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn compute_reference_prefix_blocking(&mut self, len: u32) -> bool {
let mut job = self.reference_job();
let full = job.key.iter;
job.key.iter = full.min(len);
let points = job.compute();
let complete = job.key.iter == full || points.len() <= job.key.iter as usize;
self.finish_reference(job, points);
complete
}
/// Orbit length and precision (bits) the current view's reference needs.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn reference_work(&mut self) -> (u32, usize) {
let job = self.reference_job();
(job.key.iter, job.precision)
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn auto_iterations(&self) -> bool {
self.auto_iterations
}
/// Snapshot everything the reference orbit for the current view depends
/// on, as a self-contained job that can be computed on another thread
/// (headless animation computes many frames' orbits in parallel). Also
+32 -4
View File
@@ -1849,6 +1849,36 @@ impl ExportRender {
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<(f32, f32)> {
ci_range(&self.probe_histogram_blocking(device, queue)?)
}
/// Upper bound on the step at which the last pixel escaped, from the same
/// downscaled prepass as [`ci_range_blocking`](Self::ci_range_blocking)
/// (`ci` = sqrt of the smooth count; `Some(0)` if nothing escaped). A
/// pixel that ran off the end of a cut reference counts as escaping
/// there (or reads as a huge `ci`), so this also says whether a longer
/// orbit could change the image. `None` if the readback failed.
#[cfg(not(target_arch = "wasm32"))]
pub fn max_escape_blocking(&self, device: &wgpu::Device, queue: &wgpu::Queue) -> Option<f64> {
let hist = self.probe_histogram_blocking(device, queue)?;
let Some(top) = hist.iter().rposition(|&n| n != 0) else {
return Some(0.0);
};
if top + 1 >= CI_BINS {
return Some(f64::INFINITY); // clamped: off the histogram's range
}
let ci = ((top + 1) as f64 * (CI_LOG2_MAX as f64 / CI_BINS as f64)).exp2() - 1.0;
Some(ci * ci + 1.0)
}
/// Iterate the downscaled 1-spp prepass and read back its `ci`
/// histogram (`ci_stats.wgsl`).
#[cfg(not(target_arch = "wasm32"))]
fn probe_histogram_blocking(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<Vec<u32>> {
let (iterate, histogram) = self
.probe
.as_ref()
@@ -1910,11 +1940,9 @@ impl ExportRender {
timeout: None,
});
rx.recv().ok()?.ok()?;
let range = ci_range(bytemuck::cast_slice(
&staging.slice(..).get_mapped_range().ok()?,
));
let hist = bytemuck::cast_slice(&staging.slice(..).get_mapped_range().ok()?).to_vec();
staging.unmap();
range
Some(hist)
}
/// Band sizing for rendering this export, starting at the worst-case
+71 -16
View File
@@ -30,6 +30,24 @@ const MAX_DIM: u32 = 8192 * 16;
/// `--export-path` value meaning "write to stdout".
const STDOUT_PATH: &str = "-";
/// First orbit length tried for a still with auto-iterations (see
/// [`run`]); grown 4× per probe until no pixel gets near its end.
const PROBE_FIRST_LEN: u32 = 8192;
/// Probe only when the whole orbit (+ its BLA table) would take longer than
/// this: each probe is a GPU pass plus a BLA rebuild, and minibrot dives
/// climb all the way to the full length anyway (seahorse 1e-200: 80 ms of
/// orbit, +0.4 s of probes).
const PROBE_MIN_SECS: f64 = 0.25;
/// Rough CPU time of `steps` reference steps at `precision` bits plus their
/// BLA nodes, fitted on a Ryzen with GMP: ~0.4 µs/step (allocation, f32
/// conversion, BLA) + 3e-4 µs × limbs² for the multiplies.
fn orbit_secs(steps: u32, precision: usize) -> f64 {
let limbs = precision.div_ceil(64) as f64;
steps as f64 * (0.4 + 3e-4 * limbs * limbs) * 1e-6
}
/// Refuse to dump binary image data onto a terminal.
fn check_stdout_piped() -> Result<(), String> {
if std::io::stdout().is_terminal() {
@@ -73,27 +91,64 @@ pub fn run(cli: Cli) -> Result<(), String> {
let export_path = export_path.unwrap_or_else(|| format!("fractal-{}.png", unix_timestamp()));
// Auto-iterations ask for 400 + 900·decades steps, all computed when the
// reference never escapes (e.g. c = -1.5 at 1e-1000: 900k steps of
// 3000-bit arithmetic, plus the BLA table over them), even when every
// pixel has escaped by step 10k. So compute a prefix of the orbit and
// probe (downscaled prepass) how far pixels follow it: the shader treats
// an exhausted reference as an escape, so while no pixel gets near the
// end, the image is the same as with the whole orbit. Otherwise grow 4×.
let probe = app.auto_iterations() && {
let (steps, precision) = app.reference_work();
orbit_secs(steps, precision) > PROBE_MIN_SECS
};
let mut len = PROBE_FIRST_LEN;
let device_thread = std::thread::spawn(|| pollster::block_on(request_device()));
eprintln!("computing reference orbit…");
app.compute_reference_blocking();
let mut complete = if probe {
app.compute_reference_prefix_blocking(len)
} else {
app.compute_reference_blocking();
true
};
let (device, queue) = pollster::block_on(request_device())?;
let (device, queue) = device_thread
.join()
.map_err(|_| "GPU setup panicked".to_string())??;
let format = wgpu::TextureFormat::Bgra8Unorm;
let renderer = FractalRenderer::new(&device, format);
let uniforms = app.make_uniforms(width as f64 / height as f64, height as f64);
let auto_color = app.auto_color_active();
let handles = renderer.export_handles(&device, &uniforms, auto_color);
let mut er = ExportRender::new(
&device,
&queue,
&handles,
width,
height,
uniforms,
app.reference_points(),
&bla::for_uniforms(app.reference_points(), &uniforms, app.use_bla()),
app.lights(),
);
let mut handles: Option<(PipelineKey, _)> = None;
let mut er = loop {
let uniforms = app.make_uniforms(width as f64 / height as f64, height as f64);
let key = PipelineKey::from_uniforms(&uniforms);
if handles.as_ref().is_none_or(|(k, _)| *k != key) {
let h = renderer.export_handles(&device, &uniforms, auto_color || !complete);
handles = Some((key, h));
}
let er = ExportRender::new(
&device,
&queue,
&handles.as_ref().unwrap().1,
width,
height,
uniforms,
app.reference_points(),
&bla::for_uniforms(app.reference_points(), &uniforms, app.use_bla()),
app.lights(),
);
if complete {
break er;
}
match er.max_escape_blocking(&device, &queue) {
// 2× margin: the full image samples finer than the probe.
Some(n) if n < len as f64 / 2.0 => break er,
_ => {
len = len.saturating_mul(4);
complete = app.compute_reference_prefix_blocking(len);
}
}
};
if auto_color {
match fit_auto_color(&mut app, &mut er, &device, &queue) {
Some((lo, hi)) => eprintln!("auto color scale: ci {lo:.1}–{hi:.1}"),