From aae786a3e930dae0870ec7642ba6ed1a94c1e198 Mon Sep 17 00:00:00 2001 From: supersurviveur Date: Wed, 30 Sep 2026 10:24:01 +0200 Subject: [PATCH] feat: Add CLI arg to enable auto color scale --- CLAUDE.md | 8 +- src/app.rs | 44 ++++++-- src/cli.rs | 6 ++ src/fractal/renderer.rs | 233 ++++++++++++++++++++++++++++++++++------ src/headless.rs | 41 ++++++- 5 files changed, 286 insertions(+), 46 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 538e031..db8c39a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -45,12 +45,16 @@ Native CLI flags (`src/cli.rs`, applied in `FractalApp::apply_cli`): `--kind`, `--palette`, `--share `, `--view re,im,half_height[,iterations]`, `--rendering-kind`, `--yaw`/`--pitch` (3D camera, degrees), `--de`, `--antialias` (2×2), -`--buddhabrot`, +`--auto-color-scale`, `--buddhabrot`, `--buddha-palette`. `--headless` (`src/headless.rs`) skips the window entirely: it builds the same view from the other flags, creates its own offscreen wgpu device, and renders straight to a PNG (`--width`/`--height`, 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. `--headless` also has an animation mode, for feeding into `ffmpeg`: give any diff --git a/src/app.rs b/src/app.rs index a4a5da0..31b8376 100644 --- a/src/app.rs +++ b/src/app.rs @@ -873,6 +873,10 @@ impl FractalApp { self.buddha_palette = p.min(BUDDHA_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; } @@ -1411,9 +1415,6 @@ impl FractalApp { 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 /// palette starts at the auto fit's lowest on-screen `ci`. fn effective_color_offset(&self) -> f32 { @@ -1438,13 +1439,40 @@ impl FractalApp { ctx.request_repaint(); } 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.ci_lo = lo; + self.apply_ci_range(range); } } + /// 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 { self.rendering_mode == 0 || self.shadow_palette == SHADOW_PALETTE_CLASSIC } @@ -1598,7 +1626,7 @@ impl FractalApp { self.status = Some("export unavailable".into()); return; }; - renderer.export_handles(&device, &uniforms) + renderer.export_handles(&device, &uniforms, false) }; let reference = Arc::clone(&self.reference); let lights = self.lights.clone(); @@ -3035,7 +3063,7 @@ impl FractalApp { reference: Arc::clone(&self.reference), generation: self.generation, size_px, - auto_color: self.auto_color_scale && self.uses_classic_palette(), + auto_color: self.auto_color_active(), }, )); } diff --git a/src/cli.rs b/src/cli.rs index 327985a..fc5debb 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -82,6 +82,12 @@ pub struct Cli { #[arg(long, value_name = "INDEX")] pub palette: Option, + /// 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-.png). When /// animating (--to-view/--to-share), this is a directory of /// frame-00001.png, frame-00002.png, ... instead (default: diff --git a/src/fractal/renderer.rs b/src/fractal/renderer.rs index 1a4e8c3..92dd6d3 100644 --- a/src/fractal/renderer.rs +++ b/src/fractal/renderer.rs @@ -430,6 +430,11 @@ const CI_LOG2_MAX: f32 = 25.0; /// `max_iter` and would otherwise squash the rest into one palette band. 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`]). enum CiStatsState { Idle, @@ -440,12 +445,19 @@ enum CiStatsState { Mapping(Arc), } +/// 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 /// histogram (`ci_stats.wgsl`), read back asynchronously one or two frames /// later by [`FractalRenderer::take_ci_range`]. struct CiStats { - pipeline: wgpu::ComputePipeline, - layout: wgpu::BindGroupLayout, + histogram: CiHistogram, hist: wgpu::Buffer, staging: wgpu::Buffer, state: CiStatsState, @@ -453,7 +465,7 @@ struct CiStats { stale: bool, } -impl CiStats { +impl CiHistogram { fn new(device: &wgpu::Device) -> Self { let module = unsafe { device.create_shader_module_trusted( @@ -504,6 +516,11 @@ impl CiStats { compilation_options: Default::default(), 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::()) as u64; let hist = device.create_buffer(&wgpu::BufferDescriptor { label: Some("ci histogram"), @@ -519,9 +536,55 @@ impl CiStats { usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, 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 { - pipeline, - layout, + histogram, hist, staging, state: CiStatsState::Idle, @@ -539,31 +602,15 @@ impl CiStats { width: u32, height: u32, ) { - 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: 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.histogram.record( + device, + encoder, + data, + width, + height, + &self.hist, + &self.staging, + ); self.state = CiStatsState::Copied; self.stale = false; } @@ -1142,7 +1189,7 @@ impl FractalRenderer { cache: None, iterated: 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 /// texture to march over and `fs_color` has no 3D path. Likewise for /// 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 pipeline = fullscreen_pipeline( device, @@ -1376,11 +1430,29 @@ impl FractalRenderer { colorize_bind_group_layout: self.colorize_bind_group_layout.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 { pipeline, bind_group_layout: self.bind_group_layout.clone(), format: self.target_format, raymarch, + probe, } } } @@ -1395,6 +1467,9 @@ pub struct ExportHandles { format: wgpu::TextureFormat, /// The two-pass chain, for 3D mode and the distance field only. raymarch: Option, + /// 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. @@ -1444,6 +1519,13 @@ pub struct ExportRender { /// 3D mode or the distance field: tiles fill a data texture instead of /// the target. raymarch: Option, + // 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 { @@ -1639,9 +1721,96 @@ impl ExportRender { tiles, swap_rb, 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`. fn tile_rows(&self, t: u32) -> (u32, u32) { let band = self.height.div_ceil(self.tiles); diff --git a/src/headless.rs b/src/headless.rs index 9dee574..3329206 100644 --- a/src/headless.rs +++ b/src/headless.rs @@ -78,9 +78,10 @@ pub fn run(cli: Cli) -> Result<(), 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 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, &queue, &handles, @@ -90,6 +91,12 @@ pub fn run(cli: Cli) -> Result<(), String> { app.reference_points(), 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}…"); let png = export_to_png_blocking(&device, &queue, &er, |phase, fraction| { @@ -311,6 +318,10 @@ fn run_animation( let format = wgpu::TextureFormat::Bgra8Unorm; let renderer = FractalRenderer::new(&device, format); 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 // 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 handles = pipelines .entry(PipelineKey::from_uniforms(&uniforms)) - .or_insert_with(|| renderer.export_handles(&device, &uniforms)); - let er = ExportRender::new( + .or_insert_with(|| renderer.export_handles(&device, &uniforms, auto_color)); + let mut er = ExportRender::new( &device, &queue, handles, @@ -456,6 +467,10 @@ fn run_animation( app.reference_points(), 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); if png_tx.send((i, padded, er.padded_bpr, er.swap_rb)).is_err() { break; @@ -496,6 +511,24 @@ fn run_animation( 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 /// 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