feat: Add CLI arg to enable auto color scale

This commit is contained in:
2026-09-30 10:24:20 +02:00
parent c59fe800b1
commit aae786a3e9
5 changed files with 286 additions and 46 deletions
+6 -2
View File
@@ -45,12 +45,16 @@ Native CLI flags (`src/cli.rs`, applied in `FractalApp::apply_cli`): `--kind`,
`--palette`, `--share <fragment>`, `--palette`, `--share <fragment>`,
`--view re,im,half_height[,iterations]`, `--rendering-kind`, `--view re,im,half_height[,iterations]`, `--rendering-kind`,
`--yaw`/`--pitch` (3D camera, degrees), `--de`, `--antialias` (2×2), `--yaw`/`--pitch` (3D camera, degrees), `--de`, `--antialias` (2×2),
`--buddhabrot`, `--auto-color-scale`, `--buddhabrot`,
`--buddha-palette`. `--headless` (`src/headless.rs`) skips the window `--buddha-palette`. `--headless` (`src/headless.rs`) skips the window
entirely: it builds the same view from the other flags, creates its own entirely: it builds the same view from the other flags, creates its own
offscreen wgpu device, and renders straight to a PNG (`--width`/`--height`, offscreen wgpu device, and renders straight to a PNG (`--width`/`--height`,
default 1920×1080, `--export-path out.png`) without needing a GPU-backed default 1920×1080, `--export-path out.png`) without needing a GPU-backed
window/event loop. Not yet supported with `--buddhabrot`. Run 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
`mandelbrot --help` for the full list. `mandelbrot --help` for the full list.
`--headless` also has an animation mode, for feeding into `ffmpeg`: give any `--headless` also has an animation mode, for feeding into `ffmpeg`: give any
+36 -8
View File
@@ -873,6 +873,10 @@ impl FractalApp {
self.buddha_palette = p.min(BUDDHA_PALETTE_NAMES.len() as u32 - 1); self.buddha_palette = p.min(BUDDHA_PALETTE_NAMES.len() as u32 - 1);
self.palette = p.min(PALETTE_NAMES.len() as u32 - 1); self.palette = p.min(PALETTE_NAMES.len() as u32 - 1);
} }
// After --share, which turns it off.
if cli.auto_color_scale {
self.auto_color_scale = true;
}
self.export_path = cli.export_path; self.export_path = cli.export_path;
} }
@@ -1411,9 +1415,6 @@ impl FractalApp {
self.last_request = Some(key); self.last_request = Some(key);
} }
/// Whether the classic escape-time palette (and its scale / offset /
/// palette controls) is in use: always in classic mode, and in shadow/3D
/// modes under the "Classic" shading palette.
/// The palette offset the shaders get: `color_offset`, shifted so the /// The palette offset the shaders get: `color_offset`, shifted so the
/// palette starts at the auto fit's lowest on-screen `ci`. /// palette starts at the auto fit's lowest on-screen `ci`.
fn effective_color_offset(&self) -> f32 { fn effective_color_offset(&self) -> f32 {
@@ -1438,13 +1439,40 @@ impl FractalApp {
ctx.request_repaint(); ctx.request_repaint();
} }
if self.auto_color_scale if self.auto_color_scale
&& let Some((lo, hi)) = range && let Some(range) = range
{ {
self.color_scale = (1.0 / (hi - lo).max(1e-3)).clamp(1e-4, 1.0); self.apply_ci_range(range);
self.ci_lo = lo;
} }
} }
/// Fit one palette cycle across the `ci` range `[lo, hi]` (auto colour
/// scale).
pub(crate) fn apply_ci_range(&mut self, (lo, hi): (f32, f32)) {
self.color_scale = (1.0 / (hi - lo).max(1e-3)).clamp(1e-4, 1.0);
self.ci_lo = lo;
}
/// The colour scale and the auto fit's `ci_lo`, to restore with
/// [`Self::set_color_fit`].
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn color_fit(&self) -> (f32, f32) {
(self.color_scale, self.ci_lo)
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn set_color_fit(&mut self, (scale, ci_lo): (f32, f32)) {
self.color_scale = scale;
self.ci_lo = ci_lo;
}
/// Whether the auto colour scale applies to the current render.
pub(crate) fn auto_color_active(&self) -> bool {
self.auto_color_scale && self.uses_classic_palette()
}
/// Whether the classic escape-time palette (and its scale / offset /
/// palette controls) is in use: always in classic mode, and in shadow/3D
/// modes under the "Classic" shading palette.
fn uses_classic_palette(&self) -> bool { fn uses_classic_palette(&self) -> bool {
self.rendering_mode == 0 || self.shadow_palette == SHADOW_PALETTE_CLASSIC self.rendering_mode == 0 || self.shadow_palette == SHADOW_PALETTE_CLASSIC
} }
@@ -1598,7 +1626,7 @@ impl FractalApp {
self.status = Some("export unavailable".into()); self.status = Some("export unavailable".into());
return; return;
}; };
renderer.export_handles(&device, &uniforms) renderer.export_handles(&device, &uniforms, false)
}; };
let reference = Arc::clone(&self.reference); let reference = Arc::clone(&self.reference);
let lights = self.lights.clone(); let lights = self.lights.clone();
@@ -3035,7 +3063,7 @@ impl FractalApp {
reference: Arc::clone(&self.reference), reference: Arc::clone(&self.reference),
generation: self.generation, generation: self.generation,
size_px, size_px,
auto_color: self.auto_color_scale && self.uses_classic_palette(), auto_color: self.auto_color_active(),
}, },
)); ));
} }
+6
View File
@@ -82,6 +82,12 @@ pub struct Cli {
#[arg(long, value_name = "INDEX")] #[arg(long, value_name = "INDEX")]
pub palette: Option<u32>, pub palette: Option<u32>,
/// Fit the colour scale to the image: one palette cycle across its
/// escape-time range (classic palette only). Animations refit it on
/// every frame.
#[arg(long)]
pub auto_color_scale: bool,
/// Output path for --headless (default: fractal-<timestamp>.png). When /// Output path for --headless (default: fractal-<timestamp>.png). When
/// animating (--to-view/--to-share), this is a directory of /// animating (--to-view/--to-share), this is a directory of
/// frame-00001.png, frame-00002.png, ... instead (default: /// frame-00001.png, frame-00002.png, ... instead (default:
+201 -32
View File
@@ -430,6 +430,11 @@ const CI_LOG2_MAX: f32 = 25.0;
/// `max_iter` and would otherwise squash the rest into one palette band. /// `max_iter` and would otherwise squash the rest into one palette band.
const CI_TAIL: f64 = 0.005; const CI_TAIL: f64 = 0.005;
/// Longest side (px) of an export's auto-colour prepass
/// ([`ExportRender::ci_range_blocking`]).
#[cfg(not(target_arch = "wasm32"))]
const CI_PROBE_MAX_DIM: u32 = 1024;
/// Where the `ci` histogram readback is (see [`CiStats`]). /// Where the `ci` histogram readback is (see [`CiStats`]).
enum CiStatsState { enum CiStatsState {
Idle, Idle,
@@ -440,12 +445,19 @@ enum CiStatsState {
Mapping(Arc<std::sync::atomic::AtomicBool>), Mapping(Arc<std::sync::atomic::AtomicBool>),
} }
/// The `ci` histogram compute pass (`ci_stats.wgsl`), shared by the
/// interactive [`CiStats`] and headless exports ([`ExportRender::ci_range_blocking`]).
#[derive(Clone)]
struct CiHistogram {
pipeline: wgpu::ComputePipeline,
layout: wgpu::BindGroupLayout,
}
/// Auto colour scale: a compute pass bins the data texture's `ci` into a /// Auto colour scale: a compute pass bins the data texture's `ci` into a
/// histogram (`ci_stats.wgsl`), read back asynchronously one or two frames /// histogram (`ci_stats.wgsl`), read back asynchronously one or two frames
/// later by [`FractalRenderer::take_ci_range`]. /// later by [`FractalRenderer::take_ci_range`].
struct CiStats { struct CiStats {
pipeline: wgpu::ComputePipeline, histogram: CiHistogram,
layout: wgpu::BindGroupLayout,
hist: wgpu::Buffer, hist: wgpu::Buffer,
staging: wgpu::Buffer, staging: wgpu::Buffer,
state: CiStatsState, state: CiStatsState,
@@ -453,7 +465,7 @@ struct CiStats {
stale: bool, stale: bool,
} }
impl CiStats { impl CiHistogram {
fn new(device: &wgpu::Device) -> Self { fn new(device: &wgpu::Device) -> Self {
let module = unsafe { let module = unsafe {
device.create_shader_module_trusted( device.create_shader_module_trusted(
@@ -504,6 +516,11 @@ impl CiStats {
compilation_options: Default::default(), compilation_options: Default::default(),
cache: None, cache: None,
}); });
Self { pipeline, layout }
}
/// The histogram buffer and its mappable readback copy.
fn buffers(device: &wgpu::Device) -> (wgpu::Buffer, wgpu::Buffer) {
let size = (CI_BINS * std::mem::size_of::<u32>()) as u64; let size = (CI_BINS * std::mem::size_of::<u32>()) as u64;
let hist = device.create_buffer(&wgpu::BufferDescriptor { let hist = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ci histogram"), label: Some("ci histogram"),
@@ -519,9 +536,55 @@ impl CiStats {
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false, mapped_at_creation: false,
}); });
(hist, staging)
}
/// Record the histogram of `data` (`width`×`height`) into `hist`, and its
/// copy into `staging`.
#[allow(clippy::too_many_arguments)]
fn record(
&self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
data: &wgpu::TextureView,
width: u32,
height: u32,
hist: &wgpu::Buffer,
staging: &wgpu::Buffer,
) {
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("ci stats bind group"),
layout: &self.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(data),
},
wgpu::BindGroupEntry {
binding: 1,
resource: hist.as_entire_binding(),
},
],
});
encoder.clear_buffer(hist, 0, None);
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("ci stats pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &bind_group, &[]);
pass.dispatch_workgroups(width.div_ceil(16), height.div_ceil(16), 1);
}
encoder.copy_buffer_to_buffer(hist, 0, staging, 0, None);
}
}
impl CiStats {
fn new(histogram: CiHistogram, device: &wgpu::Device) -> Self {
let (hist, staging) = CiHistogram::buffers(device);
Self { Self {
pipeline, histogram,
layout,
hist, hist,
staging, staging,
state: CiStatsState::Idle, state: CiStatsState::Idle,
@@ -539,31 +602,15 @@ impl CiStats {
width: u32, width: u32,
height: u32, height: u32,
) { ) {
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { self.histogram.record(
label: Some("ci stats bind group"), device,
layout: &self.layout, encoder,
entries: &[ data,
wgpu::BindGroupEntry { width,
binding: 0, height,
resource: wgpu::BindingResource::TextureView(data), &self.hist,
}, &self.staging,
wgpu::BindGroupEntry { );
binding: 1,
resource: self.hist.as_entire_binding(),
},
],
});
encoder.clear_buffer(&self.hist, 0, None);
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("ci stats pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &bind_group, &[]);
pass.dispatch_workgroups(width.div_ceil(16), height.div_ceil(16), 1);
}
encoder.copy_buffer_to_buffer(&self.hist, 0, &self.staging, 0, None);
self.state = CiStatsState::Copied; self.state = CiStatsState::Copied;
self.stale = false; self.stale = false;
} }
@@ -1142,7 +1189,7 @@ impl FractalRenderer {
cache: None, cache: None,
iterated: None, iterated: None,
colored: None, colored: None,
ci_stats: CiStats::new(device), ci_stats: CiStats::new(CiHistogram::new(device), device),
} }
} }
@@ -1340,7 +1387,14 @@ impl FractalRenderer {
/// refine → colourise chain, since the raymarcher needs a whole data /// refine → colourise chain, since the raymarcher needs a whole data
/// texture to march over and `fs_color` has no 3D path. Likewise for /// texture to march over and `fs_color` has no 3D path. Likewise for
/// the distance field ([`wants_envelope`]), which needs the whole image. /// the distance field ([`wants_envelope`]), which needs the whole image.
pub fn export_handles(&self, device: &wgpu::Device, uniforms: &Uniforms) -> ExportHandles { /// With `ci_probe`, also what [`ExportRender::ci_range_blocking`] needs
/// (auto colour scale).
pub fn export_handles(
&self,
device: &wgpu::Device,
uniforms: &Uniforms,
ci_probe: bool,
) -> ExportHandles {
let constants = PipelineKey::from_uniforms(uniforms).constants(); let constants = PipelineKey::from_uniforms(uniforms).constants();
let pipeline = fullscreen_pipeline( let pipeline = fullscreen_pipeline(
device, device,
@@ -1376,11 +1430,29 @@ impl FractalRenderer {
colorize_bind_group_layout: self.colorize_bind_group_layout.clone(), colorize_bind_group_layout: self.colorize_bind_group_layout.clone(),
lipschitz: wants_envelope(uniforms).then(|| self.lipschitz.clone()), lipschitz: wants_envelope(uniforms).then(|| self.lipschitz.clone()),
}); });
let probe = ci_probe.then(|| {
let iterate = raymarch.as_ref().map_or_else(
|| {
fullscreen_pipeline(
device,
"fractal export ci probe pipeline",
&self.shader,
&self.pipeline_layout,
"fs_data",
DATA_FORMAT,
&constants,
)
},
|rm| rm.iterate.clone(),
);
(iterate, self.ci_stats.histogram.clone())
});
ExportHandles { ExportHandles {
pipeline, pipeline,
bind_group_layout: self.bind_group_layout.clone(), bind_group_layout: self.bind_group_layout.clone(),
format: self.target_format, format: self.target_format,
raymarch, raymarch,
probe,
} }
} }
} }
@@ -1395,6 +1467,9 @@ pub struct ExportHandles {
format: wgpu::TextureFormat, format: wgpu::TextureFormat,
/// The two-pass chain, for 3D mode and the distance field only. /// The two-pass chain, for 3D mode and the distance field only.
raymarch: Option<RaymarchHandles>, raymarch: Option<RaymarchHandles>,
/// 1-spp iterate pipeline (`fs_data`) + `ci` histogram, for the auto
/// colour scale's prepass.
probe: Option<(wgpu::RenderPipeline, CiHistogram)>,
} }
/// The interactive two-pass pipelines, for a 3D or distance-field export. /// The interactive two-pass pipelines, for a 3D or distance-field export.
@@ -1444,6 +1519,13 @@ pub struct ExportRender {
/// 3D mode or the distance field: tiles fill a data texture instead of /// 3D mode or the distance field: tiles fill a data texture instead of
/// the target. /// the target.
raymarch: Option<RaymarchExport>, raymarch: Option<RaymarchExport>,
// Only for headless auto colour (`ci_range_blocking`, `set_uniforms`).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
uniform_buffer: wgpu::Buffer,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
uniforms: Uniforms,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
probe: Option<(wgpu::RenderPipeline, CiHistogram)>,
} }
impl ExportRender { impl ExportRender {
@@ -1639,9 +1721,96 @@ impl ExportRender {
tiles, tiles,
swap_rb, swap_rb,
raymarch, raymarch,
uniform_buffer,
uniforms,
probe: handles.probe.clone(),
} }
} }
/// Replace the uploaded uniforms (e.g. with a refitted colour scale).
#[cfg(not(target_arch = "wasm32"))]
pub fn set_uniforms(&mut self, queue: &wgpu::Queue, uniforms: Uniforms) {
queue.write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniforms));
self.uniforms = uniforms;
}
/// Auto colour scale for an export: iterate a downscaled 1-spp prepass,
/// histogram its `ci` and return the range to fit (`None` if nothing
/// escaped). Needs handles built with `ci_probe`. Blocks on the GPU.
#[cfg(not(target_arch = "wasm32"))]
pub fn ci_range_blocking(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<(f32, f32)> {
let (iterate, histogram) = self
.probe
.as_ref()
.expect("export handles built without ci_probe");
// The uniforms carry no resolution, so a smaller image of the same view
// just samples it more coarsely; plenty for percentiles.
let s = (CI_PROBE_MAX_DIM as f64 / self.width.max(self.height) as f64).min(1.0);
let width = ((self.width as f64 * s).round() as u32).max(1);
let height = ((self.height as f64 * s).round() as u32).max(1);
let data = device
.create_texture(&wgpu::TextureDescriptor {
label: Some("export ci probe"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: DATA_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&wgpu::TextureViewDescriptor::default());
let (hist, staging) = CiHistogram::buffers(device);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("export ci probe"),
});
let samples = if self.uniforms.rendering_mode != 0 {
3
} else {
1
};
banded_data_pass(
device,
queue,
&mut encoder,
"export ci probe pass",
&data,
iterate,
&[&self.bind_group],
[width, height],
band_count(width, height, self.uniforms.max_iter, samples),
);
histogram.record(device, &mut encoder, &data, width, height, &hist, &staging);
queue.submit(std::iter::once(encoder.finish()));
let (tx, rx) = std::sync::mpsc::channel();
staging
.slice(..)
.map_async(wgpu::MapMode::Read, move |res| {
let _ = tx.send(res);
});
let _ = device.poll(wgpu::PollType::Wait {
submission_index: None,
timeout: None,
});
rx.recv().ok()?.ok()?;
let range = ci_range(bytemuck::cast_slice(
&staging.slice(..).get_mapped_range().ok()?,
));
staging.unmap();
range
}
/// Pixel row range `[y0, y1)` covered by tile `t`. /// Pixel row range `[y0, y1)` covered by tile `t`.
fn tile_rows(&self, t: u32) -> (u32, u32) { fn tile_rows(&self, t: u32) -> (u32, u32) {
let band = self.height.div_ceil(self.tiles); let band = self.height.div_ceil(self.tiles);
+37 -4
View File
@@ -78,9 +78,10 @@ pub fn run(cli: Cli) -> Result<(), String> {
let format = wgpu::TextureFormat::Bgra8Unorm; let format = wgpu::TextureFormat::Bgra8Unorm;
let renderer = FractalRenderer::new(&device, format); let renderer = FractalRenderer::new(&device, format);
let uniforms = app.make_uniforms(width as f64 / height as f64, height as f64); let uniforms = app.make_uniforms(width as f64 / height as f64, height as f64);
let handles = renderer.export_handles(&device, &uniforms); let auto_color = app.auto_color_active();
let handles = renderer.export_handles(&device, &uniforms, auto_color);
let er = ExportRender::new( let mut er = ExportRender::new(
&device, &device,
&queue, &queue,
&handles, &handles,
@@ -90,6 +91,12 @@ pub fn run(cli: Cli) -> Result<(), String> {
app.reference_points(), app.reference_points(),
app.lights(), app.lights(),
); );
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}"),
None => eprintln!("auto color scale: nothing escaped, keeping the default"),
}
}
eprintln!("rendering {width}×{height}…"); eprintln!("rendering {width}×{height}…");
let png = export_to_png_blocking(&device, &queue, &er, |phase, fraction| { let png = export_to_png_blocking(&device, &queue, &er, |phase, fraction| {
@@ -311,6 +318,10 @@ fn run_animation(
let format = wgpu::TextureFormat::Bgra8Unorm; let format = wgpu::TextureFormat::Bgra8Unorm;
let renderer = FractalRenderer::new(&device, format); let renderer = FractalRenderer::new(&device, format);
let aspect = width as f64 / height as f64; let aspect = width as f64 / height as f64;
// Refit per frame from the same start, so each frame's colours depend only
// on that frame (frames render out of order, and shards must join up).
let auto_color = app.auto_color_active();
let color_fit0 = app.color_fit();
// Three-stage pipeline, connected by bounded channels (which also cap // Three-stage pipeline, connected by bounded channels (which also cap
// memory): `threads` workers compute reference orbits (CPU, the expensive // memory): `threads` workers compute reference orbits (CPU, the expensive
@@ -445,8 +456,8 @@ fn run_animation(
let uniforms = app.make_uniforms(aspect, height as f64); let uniforms = app.make_uniforms(aspect, height as f64);
let handles = pipelines let handles = pipelines
.entry(PipelineKey::from_uniforms(&uniforms)) .entry(PipelineKey::from_uniforms(&uniforms))
.or_insert_with(|| renderer.export_handles(&device, &uniforms)); .or_insert_with(|| renderer.export_handles(&device, &uniforms, auto_color));
let er = ExportRender::new( let mut er = ExportRender::new(
&device, &device,
&queue, &queue,
handles, handles,
@@ -456,6 +467,10 @@ fn run_animation(
app.reference_points(), app.reference_points(),
app.lights(), app.lights(),
); );
if auto_color {
app.set_color_fit(color_fit0);
fit_auto_color(&mut app, &mut er, &device, &queue);
}
let padded = render_readback_blocking(&device, &queue, &er); let padded = render_readback_blocking(&device, &queue, &er);
if png_tx.send((i, padded, er.padded_bpr, er.swap_rb)).is_err() { if png_tx.send((i, padded, er.padded_bpr, er.swap_rb)).is_err() {
break; break;
@@ -496,6 +511,24 @@ fn run_animation(
Ok(()) Ok(())
} }
/// Auto colour scale: fit `app`'s colour scale to `er`'s image (a prepass)
/// and upload the result. Returns the fitted `ci` range, or `None` (colours
/// untouched) if nothing escaped.
fn fit_auto_color(
app: &mut FractalApp,
er: &mut ExportRender,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<(f32, f32)> {
let range = er.ci_range_blocking(device, queue)?;
app.apply_ci_range(range);
er.set_uniforms(
queue,
app.make_uniforms(er.width as f64 / er.height as f64, er.height as f64),
);
Some(range)
}
/// Parse `--to-view`/`--to-share` (at most one is used) into the end view /// Parse `--to-view`/`--to-share` (at most one is used) into the end view
/// of an animation, or `None` if neither is set (the camera stays put). Only position/zoom/iterations are pulled from a /// of an animation, or `None` if neither is set (the camera stays put). Only position/zoom/iterations are pulled from a
/// share fragment — the rest of its state (kind, colors, ...) is ignored, so /// share fragment — the rest of its state (kind, colors, ...) is ignored, so