diff --git a/CLAUDE.md b/CLAUDE.md index 837e202..708de6d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,14 +15,14 @@ once a pixel is ~2^-124 wide (~10³⁴× at 1080p), so from 2^-122 per pixel rescaled deltas (f32 mantissa × 2^i32). There's no practical depth limit: `half_height` is a `view::Scale` (f64 mantissa × 2^i32), floored only at `Scale::MIN` = 2^-(2^20) to keep shader exponent sums in i32. Runs -natively (Vulkan/Metal/DX12) and in the browser (WebGPU only — WebGL2 can't do -storage buffers, which the fragment shader needs for the reference orbit). +natively (Vulkan/Metal/DX12) and in the browser: WebGPU, plus a WebGL2 +fallback with the `webgl` feature (see "WebGL2 fallback" below). ## Commands ```sh cargo run --release # native, run (release matters: fractal math is hot) -cargo test # reference-orbit math, share-link round-trip, WGSL validation +cargo test # reference-orbit math, share-link round-trip, WGSL validation (+ GLSL ES 3.00 via glslangValidator if installed) cargo test --features wasm # same, on the web build's malachite big-float backend cargo test --test shader_valid # just the WGSL parse/validate tests (naga, no GPU needed) cargo clippy @@ -31,12 +31,12 @@ cargo build --release --no-default-features # headless-only binary: no eframe/ tools/bench/bench.sh --rev HEAD # perf of uncommitted edits vs HEAD (hyperfine; see tools/bench/README.md) ``` -Web build (WebGPU): +Web build (WebGPU, with WebGL2 fallback): ```sh rustup target add wasm32-unknown-unknown cargo install wasm-bindgen-cli --version 0.2.128 # must match the wasm-bindgen crate version -./build-web.sh # -> ./dist (builds with --features wasm) +./build-web.sh # -> ./dist (builds with --features wasm,webgl) python3 -m http.server -d dist 8080 ``` @@ -192,6 +192,8 @@ That was a few pixels per frame and ~40% of a −1.5 zoom's time. constants) is prepended to every shader. `iterate_uniforms.wgsl` (the perturbation-pipeline `Uniforms` struct + `palette()`) is additionally prepended to `mandelbrot.wgsl` and `colorize.wgsl`, which share that layout. + `mandelbrot.wgsl` is followed by a data fragment, picked at runtime + (`GpuPath::mandelbrot_source`): `data_storage.wgsl` or `data_texture.wgsl`. Because there's no namespacing, a definition must live in exactly one file among those concatenated together for a given shader — don't redefine a `common.wgsl`/`iterate_uniforms.wgsl` symbol locally. @@ -377,6 +379,40 @@ histogram buffer, tone-mapped by a fragment pass every frame. Its own `KIND_*` iteration formulas in `advance()` must be kept in sync with `reference.rs` by hand (there's no shared code path). +### WebGL2 fallback (`GpuPath` in `renderer.rs`) + +WebGL2 has no storage buffers and no compute shaders, and naga's GLSL ES 3.00 +output can't use `ldexp`/`findLSB` (ES 3.10) or a correct `frexp` (its +polyfill goes through log2). So `mandelbrot.wgsl` never touches bindings +1/3/4/5 or those builtins directly. It calls accessors (`ref_point`, +`ref_exp_at`, `bla_node`, `bla_r_log2`, `bla_steps`, `bla_meta_at`) and +`frexp_f32`/`ldexp_f32`/`ctz_u32`, defined by one of two data fragments, +which must stay in sync: +- `data_storage.wgsl` (`GpuPath::Storage`): the storage buffers and native + builtins. Every device with ≥ 4 fragment storage buffers uses it. The + benchmarks showed no change from before the split. +- `data_texture.wgsl` (`GpuPath::Texture`): each array as a + `DATA_TEX_WIDTH` (2048)-wide texture, BLA nodes as 3 `Rgba32Uint` texels + with floats as raw bits, plus bit-exact builtin replacements. It is about + 6–16% slower on a GTX 1650, so it's only used when the device has no + storage buffers. `RefData`/`DataArray` own either form. Orbit length is + capped at 2048 × the max texture height (`ref_len` is clamped on upload), + and a BLA table that doesn't fit is replaced by the empty one. +- Natively, `MANDELBROT_GPU_PATH=texture|storage` forces a path. Renders + must be pixel-identical between the two (headless, any view, + `WGPU_BACKEND=gl` too). That's the check to rerun after touching either + fragment. + +The texture path also replaces the compute `ci` histogram with +`CiHistogram::Readback`: `ci_sample.wgsl` point-samples a 256² grid, which +is read back and binned on the CPU. Buddhabrot (compute + atomics) is +disabled on such devices (`FractalApp::buddhabrot_supported`). The `webgl` +cargo feature only adds `Backends::GL` on wasm32. egui-wgpu still tries +WebGPU first, and eframe's defaults already compile wgpu's WebGL backend. +`tests/shader_valid.rs` translates every texture-path specialization to +GLSL ES 3.00 and compiles it with `glslangValidator` when that's on the +PATH. + ### Two-pass render + caching (`renderer.rs`) The interactive path splits iteration (expensive, perturbation) from diff --git a/Cargo.toml b/Cargo.toml index 966727c..dbd2feb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,12 @@ gui = ["dep:eframe", "dep:egui"] # Pure-Rust big floats for the web build (`rug` needs GMP/MPFR, which can't # target wasm32). Required for wasm32, optional natively (to test that backend). wasm = ["dep:malachite-float", "dep:malachite-base"] +# Web build: fall back to WebGL2 when the browser has no WebGPU (WebGPU is +# still preferred). WebGL2 has no storage buffers or compute shaders, so the +# fractal shader then reads its data from textures (`GpuPath::Texture`, a bit +# slower) and Buddhabrot mode is unavailable. No effect natively, where the +# path is picked from the device's limits anyway. +webgl = [] [dependencies] bytemuck = { version = "1.25.2", features = ["derive"] } @@ -53,4 +59,4 @@ opt-level = 1 opt-level = 3 [dev-dependencies] -naga = { version = "30", features = ["wgsl-in", "spv-out"] } +naga = { version = "30", features = ["wgsl-in", "spv-out", "glsl-out"] } diff --git a/build-web.sh b/build-web.sh index 8ac13e3..7a973ca 100755 --- a/build-web.sh +++ b/build-web.sh @@ -1,14 +1,15 @@ #!/usr/bin/env bash # Build the WebAssembly bundle into ./dist using wasm-bindgen. # Serve it over HTTP (e.g. `python3 -m http.server -d dist 8080`) and open in a -# WebGPU-capable browser (recent Chrome/Edge, Firefox, or Safari 26+). +# WebGPU-capable browser (recent Chrome/Edge, Firefox, or Safari 26+); the +# `webgl` feature falls back to WebGL2 elsewhere (no Buddhabrot there). set -euo pipefail export PATH="$HOME/.cargo/bin:$PATH" OUT="${1:-dist}" echo "==> cargo build (wasm32, release)" -cargo build --release --target wasm32-unknown-unknown --features wasm +cargo build --release --target wasm32-unknown-unknown --features wasm,webgl echo "==> wasm-bindgen -> $OUT" mkdir -p "$OUT" diff --git a/index.html b/index.html index a099958..3e09d23 100644 --- a/index.html +++ b/index.html @@ -46,8 +46,9 @@ const msg = (err && err.message) || String(err); if (!msg.includes("Using exceptions for control flow")) { document.getElementById("loading_text").innerHTML = - "

Failed to start. This app needs a WebGPU-capable browser " + - "(recent Chrome/Edge, Firefox, or Safari 26+).

"; + "

Failed to start. This app needs WebGPU (recent Chrome/Edge, " + + "Firefox, or Safari 26+) or, in builds with the webgl " + + "feature, WebGL2 with float render targets.

"; console.error(err); } }); diff --git a/src/app.rs b/src/app.rs index 2deba99..2590db4 100644 --- a/src/app.rs +++ b/src/app.rs @@ -597,6 +597,8 @@ pub struct FractalApp { /// Keep dispatching new sample batches every frame (progressive /// accumulation). Turning it off freezes the current histogram. buddha_accumulate: bool, + /// The device can run Buddhabrot mode's compute pass (not on WebGL2). + buddhabrot_supported: bool, /// Whether the controls side panel is expanded. Collapsible so the fractal /// can take (nearly) the whole screen — important on a phone. controls_open: bool, @@ -717,16 +719,53 @@ impl FractalApp { .as_ref() .expect("eframe must run with the wgpu backend"); + let adapter_info = render_state.adapter.get_info(); + // The iteration data textures are `Rgba32Float` render targets + // (`EXT_color_buffer_float` on WebGL2, which nearly every browser has). + if !render_state + .adapter + .get_texture_format_features(wgpu::TextureFormat::Rgba32Float) + .allowed_usages + .contains(wgpu::TextureUsages::RENDER_ATTACHMENT) + { + panic!( + "this GPU / browser can't render to 32-bit float textures \ + ({:?} on {})", + adapter_info.backend, adapter_info.name + ); + } let renderer = FractalRenderer::new(&render_state.device, render_state.target_format); - let buddhabrot_renderer = - BuddhabrotRenderer::new(&render_state.device, render_state.target_format); + log::info!( + "GPU: {} ({:?}), data path {:?}", + adapter_info.name, + adapter_info.backend, + renderer.gpu_path() + ); + // Buddhabrot accumulates with a compute pass and reads its histogram + // from a storage buffer in the fragment stage. + let buddhabrot_supported = render_state + .adapter + .get_downlevel_capabilities() + .flags + .contains(wgpu::DownlevelFlags::COMPUTE_SHADERS) + && render_state + .device + .limits() + .max_storage_buffers_per_shader_stage + >= 1; { let mut guard = render_state.renderer.write(); guard.callback_resources.insert(renderer); - guard.callback_resources.insert(buddhabrot_renderer); + if buddhabrot_supported { + guard.callback_resources.insert(BuddhabrotRenderer::new( + &render_state.device, + render_state.target_format, + )); + } } let mut app = Self::default_state(); + app.buddhabrot_supported = buddhabrot_supported; // On the web, restore a shared view from the URL fragment (#...). #[cfg(target_arch = "wasm32")] @@ -786,6 +825,7 @@ impl FractalApp { buddha_exposure: 1.0, buddha_palette: 0, buddha_accumulate: true, + buddhabrot_supported: true, controls_open: true, fullscreen: false, info_open: false, @@ -2351,12 +2391,18 @@ impl FractalApp { ui.horizontal(|ui| { ui.radio_value(&mut self.mode, FractalMode::Mandelbrot, "Set"); ui.radio_value(&mut self.mode, FractalMode::Julia, "Julia"); - ui.radio_value(&mut self.mode, FractalMode::Buddhabrot, "Buddhabrot") - .on_hover_text( - "Monte-Carlo density of escaping orbits instead of the ordinary \ + ui.add_enabled( + self.buddhabrot_supported, + egui::RadioButton::new(self.mode == FractalMode::Buddhabrot, "Buddhabrot"), + ) + .on_hover_text( + "Monte-Carlo density of escaping orbits instead of the ordinary \ escape-time set. Plain f32 view (no deep zoom); the image \ progressively sharpens while the view stays still.", - ); + ) + .on_disabled_hover_text("Needs compute shaders (WebGPU); not available on WebGL2.") + .clicked() + .then(|| self.mode = FractalMode::Buddhabrot); }); if self.mode != prev_mode { self.morph = None; @@ -3179,6 +3225,11 @@ impl FractalApp { #[cfg(feature = "gui")] impl eframe::App for FractalApp { fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + // A CLI flag can ask for Buddhabrot on a device that can't run it. + if !self.buddhabrot_supported && self.mode == FractalMode::Buddhabrot { + self.mode = FractalMode::Mandelbrot; + self.status = Some("Buddhabrot mode needs WebGPU compute shaders".into()); + } self.poll_export(ui.ctx()); self.poll_ci_stats(ui.ctx(), frame); self.update_fps(ui); diff --git a/src/fractal/renderer.rs b/src/fractal/renderer.rs index 072004c..41b73b4 100644 --- a/src/fractal/renderer.rs +++ b/src/fractal/renderer.rs @@ -7,7 +7,7 @@ //! texture onto egui's surface with a cheap textured fullscreen triangle — so //! incidental repaints (mouse-move, hover, the worker-pending poll) cost a blit, //! not a full fractal recompute. The fragment shader iterates each pixel as an -//! f32 perturbation delta from the reference orbit stored in `ref_buffer`. +//! f32 perturbation delta from the reference orbit stored in `RefData`. use std::collections::HashMap; use std::sync::Arc; @@ -451,28 +451,100 @@ 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, -} +/// Side (texels) of [`CiHistogram::Readback`]'s sample grid. Must match +/// `CI_SAMPLE_DIM` in `ci_sample.wgsl`. +const CI_SAMPLE_DIM: u32 = 256; +/// Format of the sample grid: (ci, interior fraction, 0, 0). Rgba rather +/// than Rg because WebGL2 only guarantees float readback of RGBA. +const CI_SAMPLE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float; -/// 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 { - histogram: CiHistogram, - hist: wgpu::Buffer, - staging: wgpu::Buffer, - state: CiStatsState, - /// The data texture changed since the last histogram was recorded. - stale: bool, +/// The `ci` histogram of a data texture, shared by the interactive +/// [`CiStats`] and headless exports ([`ExportRender::ci_range_blocking`]). +#[derive(Clone)] +enum CiHistogram { + /// A compute pass bins every pixel with atomics (`ci_stats.wgsl`). + Compute { + pipeline: wgpu::ComputePipeline, + layout: wgpu::BindGroupLayout, + }, + /// No compute shaders (WebGL2, [`GpuPath::Texture`]): a render pass + /// point-samples the data onto a `CI_SAMPLE_DIM`² grid + /// (`ci_sample.wgsl`), which is read back and binned on the CPU. + Readback { + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + /// The sample grid, shared by every user (passes are ordered on the + /// queue, so they don't overlap). + target: wgpu::Texture, + }, } impl CiHistogram { - fn new(device: &wgpu::Device) -> Self { + fn new(device: &wgpu::Device, path: GpuPath) -> Self { + let data_entry = |visibility| wgpu::BindGroupLayoutEntry { + binding: 0, + visibility, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + if path == GpuPath::Texture { + let module = unsafe { + device.create_shader_module_trusted( + wgpu::ShaderModuleDescriptor { + label: Some("ci sample"), + source: wgpu::ShaderSource::Wgsl( + concat!( + include_str!("../shaders/common.wgsl"), + include_str!("../shaders/ci_sample.wgsl"), + ) + .into(), + ), + }, + wgpu::ShaderRuntimeChecks::unchecked(), + ) + }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("ci sample bind group layout"), + entries: &[data_entry(wgpu::ShaderStages::FRAGMENT)], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("ci sample pipeline layout"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let pipeline = fullscreen_pipeline( + device, + "ci sample pipeline", + &module, + &pipeline_layout, + "fs_main", + CI_SAMPLE_FORMAT, + &[], + ); + let target = device.create_texture(&wgpu::TextureDescriptor { + label: Some("ci sample grid"), + size: wgpu::Extent3d { + width: CI_SAMPLE_DIM, + height: CI_SAMPLE_DIM, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: CI_SAMPLE_FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + return Self::Readback { + pipeline, + layout, + target, + }; + } let module = unsafe { device.create_shader_module_trusted( wgpu::ShaderModuleDescriptor { @@ -487,16 +559,7 @@ impl CiHistogram { let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("ci stats bind group layout"), entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::Texture { - sample_type: wgpu::TextureSampleType::Float { filterable: false }, - view_dimension: wgpu::TextureViewDimension::D2, - multisampled: false, - }, - count: None, - }, + data_entry(wgpu::ShaderStages::COMPUTE), wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::COMPUTE, @@ -522,31 +585,41 @@ impl CiHistogram { compilation_options: Default::default(), cache: None, }); - Self { pipeline, layout } + Self::Compute { 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"), - size, - usage: wgpu::BufferUsages::STORAGE - | wgpu::BufferUsages::COPY_SRC - | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); + /// Bytes per row of the `Readback` grid's copy (already a multiple of + /// `COPY_BYTES_PER_ROW_ALIGNMENT`). + const SAMPLE_BPR: u32 = CI_SAMPLE_DIM * 16; + + /// The histogram buffer (`Compute` only) and the mappable readback copy. + fn buffers(&self, device: &wgpu::Device) -> (Option, wgpu::Buffer) { + let hist_size = (CI_BINS * std::mem::size_of::()) as u64; + let (hist, staging_size) = match self { + Self::Compute { .. } => { + let hist = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("ci histogram"), + size: hist_size, + usage: wgpu::BufferUsages::STORAGE + | wgpu::BufferUsages::COPY_SRC + | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + (Some(hist), hist_size) + } + Self::Readback { .. } => (None, (Self::SAMPLE_BPR * CI_SAMPLE_DIM) as u64), + }; let staging = device.create_buffer(&wgpu::BufferDescriptor { label: Some("ci histogram readback"), - size, + size: staging_size, 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`. + /// Record the histogram of `data` (`width`×`height`) into `hist` (or the + /// sample grid), and its copy into `staging`. #[allow(clippy::too_many_arguments)] fn record( &self, @@ -555,40 +628,126 @@ impl CiHistogram { data: &wgpu::TextureView, width: u32, height: u32, - hist: &wgpu::Buffer, + hist: Option<&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); + match self { + Self::Compute { pipeline, layout } => { + let hist = hist.expect("compute histogram without its buffer"); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("ci stats bind group"), + 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(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); + } + Self::Readback { + pipeline, + layout, + target, + } => { + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("ci sample bind group"), + layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(data), + }], + }); + let view = target.create_view(&wgpu::TextureViewDescriptor::default()); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("ci sample pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.draw(0..3, 0..1); + } + encoder.copy_texture_to_buffer( + target.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: staging, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(Self::SAMPLE_BPR), + rows_per_image: None, + }, + }, + target.size(), + ); + } } - encoder.copy_buffer_to_buffer(hist, 0, staging, 0, None); } + + /// The histogram from `staging`'s mapped contents. + fn read(&self, bytes: &[u8]) -> Vec { + match self { + Self::Compute { .. } => bytemuck::cast_slice(bytes).to_vec(), + Self::Readback { .. } => { + // Same binning as `ci_stats.wgsl`. + let mut hist = vec![0u32; CI_BINS]; + for px in bytemuck::cast_slice::(bytes) { + let [ci, interior, ..] = *px; + if interior >= 1.0 { + continue; + } + let x = (1.0 + ci.max(0.0)).log2() * (CI_BINS as f32 / CI_LOG2_MAX); + hist[(x.max(0.0) as usize).min(CI_BINS - 1)] += 1; + } + hist + } + } + } +} + +/// Auto colour scale: the data texture's `ci` histogram ([`CiHistogram`]), +/// read back asynchronously one or two frames later by +/// [`FractalRenderer::take_ci_range`]. +struct CiStats { + histogram: CiHistogram, + /// The compute pass's histogram buffer (`None` for `Readback`). + hist: Option, + staging: wgpu::Buffer, + state: CiStatsState, + /// The data texture changed since the last histogram was recorded. + stale: bool, } impl CiStats { fn new(histogram: CiHistogram, device: &wgpu::Device) -> Self { - let (hist, staging) = CiHistogram::buffers(device); + let (hist, staging) = histogram.buffers(device); Self { histogram, hist, @@ -614,7 +773,7 @@ impl CiStats { data, width, height, - &self.hist, + self.hist.as_ref(), &self.staging, ); self.state = CiStatsState::Copied; @@ -789,45 +948,404 @@ struct ColorState { height: u32, } -/// GPU copy of a [`BlaTable`] (bindings 4 and 5 of the iterate group). -struct BlaBuffers { - nodes: wgpu::Buffer, - meta: wgpu::Buffer, +/// How the iteration shader reads the reference orbit and the BLA table +/// (bindings 1 and 3-5 of the iterate group). +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum GpuPath { + /// Storage buffers (`data_storage.wgsl`): WebGPU and every native backend. + Storage, + /// Textures (`data_texture.wgsl`), for devices without fragment-stage + /// storage buffers (WebGL2). Slower: each read is a texel fetch plus + /// index math, and frexp/ldexp/ctz are emulated with bit tricks. + Texture, } -impl BlaBuffers { - /// Buffers holding exactly `table` (plus room to grow into, `min_*`). - fn new(device: &wgpu::Device, table: &BlaTable, min_nodes: usize, min_meta: usize) -> Self { - // Padded with zeros up to the requested capacity. - let init = |label, data: &[u8], size: usize| { - let mut bytes = data.to_vec(); - bytes.resize(size.max(data.len()), 0); - device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some(label), - contents: &bytes, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - }) - }; - let node_size = std::mem::size_of::(); - Self { - nodes: init( - "bla nodes", - bytemuck::cast_slice(&table.nodes), - min_nodes * node_size, - ), - meta: init("bla meta", bytemuck::cast_slice(&table.meta), min_meta * 4), +impl GpuPath { + /// The fastest path `device` supports. Natively, `MANDELBROT_GPU_PATH` + /// (`storage` / `texture`) overrides it, to check the WebGL2 path + /// against the default one on the same GPU. + pub fn for_device(device: &wgpu::Device) -> Self { + #[cfg(not(target_arch = "wasm32"))] + match std::env::var("MANDELBROT_GPU_PATH").as_deref() { + Ok("texture") => return Self::Texture, + Ok("storage") => return Self::Storage, + Ok(other) => log::warn!("ignoring unknown MANDELBROT_GPU_PATH={other}"), + Err(_) => {} + } + if device.limits().max_storage_buffers_per_shader_stage >= 4 { + Self::Storage + } else { + Self::Texture } } - fn write(&self, queue: &wgpu::Queue, table: &BlaTable) { - queue.write_buffer(&self.nodes, 0, bytemuck::cast_slice(&table.nodes)); - queue.write_buffer(&self.meta, 0, bytemuck::cast_slice(&table.meta)); + /// `mandelbrot.wgsl` with its shared prefix and this path's data fragment. + fn mandelbrot_source(self) -> String { + let data = match self { + Self::Storage => include_str!("../shaders/data_storage.wgsl"), + Self::Texture => include_str!("../shaders/data_texture.wgsl"), + }; + [ + include_str!("../shaders/common.wgsl"), + include_str!("../shaders/iterate_uniforms.wgsl"), + include_str!("../shaders/mandelbrot.wgsl"), + data, + ] + .concat() + } +} + +/// Width (texels) of the [`GpuPath::Texture`] data textures: WebGL2's +/// guaranteed minimum texture size. Must match `DATA_TEX_LOG2_W` in +/// `data_texture.wgsl`. +const DATA_TEX_WIDTH: u32 = 2048; + +/// One of the arrays the iteration shader reads. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +enum DataKind { + /// Reference orbit points (`[f32; 2]`), binding 1. + Orbit, + /// Their exponents (`RefOrbit::exps`, `i32`), binding 3. + Exps, + /// BLA nodes (`GpuBla`, 48 bytes), binding 4. + BlaNodes, + /// BLA metadata (`u32`), binding 5. + BlaMeta, +} + +impl DataKind { + fn binding(self) -> u32 { + match self { + Self::Orbit => 1, + Self::Exps => 3, + Self::BlaNodes => 4, + Self::BlaMeta => 5, + } } - fn fits(&self, table: &BlaTable) -> bool { - let node_size = std::mem::size_of::() as u64; - table.nodes.len() as u64 * node_size <= self.nodes.size() - && table.meta.len() as u64 * 4 <= self.meta.size() + fn label(self) -> &'static str { + match self { + Self::Orbit => "reference orbit", + Self::Exps => "reference orbit exponents", + Self::BlaNodes => "bla nodes", + Self::BlaMeta => "bla meta", + } + } + + fn elem_bytes(self) -> usize { + match self { + Self::Orbit => std::mem::size_of::<[f32; 2]>(), + Self::Exps => std::mem::size_of::(), + Self::BlaNodes => std::mem::size_of::(), + Self::BlaMeta => std::mem::size_of::(), + } + } + + /// Texels per element on the texture path (a node is three `Rgba32Uint`). + fn texels_per_elem(self) -> u32 { + match self { + Self::BlaNodes => 3, + _ => 1, + } + } + + fn texture_format(self) -> wgpu::TextureFormat { + match self { + Self::Orbit => wgpu::TextureFormat::Rg32Float, + Self::Exps => wgpu::TextureFormat::R32Sint, + Self::BlaNodes => wgpu::TextureFormat::Rgba32Uint, + Self::BlaMeta => wgpu::TextureFormat::R32Uint, + } + } + + fn layout_entry(self, path: GpuPath) -> wgpu::BindGroupLayoutEntry { + let ty = match path { + GpuPath::Storage => wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + GpuPath::Texture => wgpu::BindingType::Texture { + sample_type: match self { + Self::Orbit => wgpu::TextureSampleType::Float { filterable: false }, + Self::Exps => wgpu::TextureSampleType::Sint, + Self::BlaNodes | Self::BlaMeta => wgpu::TextureSampleType::Uint, + }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + }; + wgpu::BindGroupLayoutEntry { + binding: self.binding(), + visibility: wgpu::ShaderStages::FRAGMENT, + ty, + count: None, + } + } + + /// Most elements `device` can hold on `path`: a texture is + /// `DATA_TEX_WIDTH` wide and at most the device's 2D limit tall. + fn max_elems(self, device: &wgpu::Device, path: GpuPath) -> usize { + match path { + GpuPath::Storage => usize::MAX, + GpuPath::Texture => { + let rows = device.limits().max_texture_dimension_2d as usize; + DATA_TEX_WIDTH as usize * rows / self.texels_per_elem() as usize + } + } + } +} + +/// GPU copy of one [`DataKind`] array: a storage buffer or a texture. +struct DataArray { + kind: DataKind, + store: DataStore, + /// Elements it holds. + capacity: usize, +} + +enum DataStore { + Buffer(wgpu::Buffer), + Texture(wgpu::Texture, wgpu::TextureView), +} + +impl DataArray { + /// Room for at least `capacity` elements (at least one), zeroed. The + /// caller keeps `capacity` within [`DataKind::max_elems`]. + fn new(device: &wgpu::Device, path: GpuPath, kind: DataKind, capacity: usize) -> Self { + let capacity = capacity.max(1); + match path { + GpuPath::Storage => { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some(kind.label()), + size: (capacity * kind.elem_bytes()) as u64, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + Self { + kind, + store: DataStore::Buffer(buffer), + capacity, + } + } + GpuPath::Texture => { + let tpe = kind.texels_per_elem() as usize; + let rows = (capacity * tpe).div_ceil(DATA_TEX_WIDTH as usize); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some(kind.label()), + size: wgpu::Extent3d { + width: DATA_TEX_WIDTH, + height: rows as u32, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: kind.texture_format(), + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + Self { + kind, + store: DataStore::Texture(texture, view), + capacity: rows * DATA_TEX_WIDTH as usize / tpe, + } + } + } + } + + /// Upload `bytes` (whole elements, at most `capacity`) from element 0. + fn write(&self, queue: &wgpu::Queue, bytes: &[u8]) { + debug_assert!(bytes.len() <= self.capacity * self.kind.elem_bytes()); + match &self.store { + DataStore::Buffer(buffer) => queue.write_buffer(buffer, 0, bytes), + DataStore::Texture(texture, _) => { + let texel = self.kind.elem_bytes() / self.kind.texels_per_elem() as usize; + let row_bytes = DATA_TEX_WIDTH as usize * texel; + let full_rows = bytes.len() / row_bytes; + let rest = (bytes.len() % row_bytes) / texel; + // Full rows, then the partial last one. + let put = |data: &[u8], y: usize, width: usize, rows: usize| { + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d { + x: 0, + y: y as u32, + z: 0, + }, + aspect: wgpu::TextureAspect::All, + }, + data, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some((width * texel) as u32), + rows_per_image: None, + }, + wgpu::Extent3d { + width: width as u32, + height: rows as u32, + depth_or_array_layers: 1, + }, + ); + }; + if full_rows > 0 { + put( + &bytes[..full_rows * row_bytes], + 0, + DATA_TEX_WIDTH as usize, + full_rows, + ); + } + if rest > 0 { + put(&bytes[full_rows * row_bytes..], full_rows, rest, 1); + } + } + } + } + + fn bind_entry(&self) -> wgpu::BindGroupEntry<'_> { + wgpu::BindGroupEntry { + binding: self.kind.binding(), + resource: match &self.store { + DataStore::Buffer(buffer) => buffer.as_entire_binding(), + DataStore::Texture(_, view) => wgpu::BindingResource::TextureView(view), + }, + } + } +} + +/// The reference orbit, its exponents and the BLA table, as the iteration +/// shader reads them on `path`. +struct RefData { + path: GpuPath, + orbit: DataArray, + exps: DataArray, + bla_nodes: DataArray, + bla_meta: DataArray, + /// Most orbit points / BLA nodes / meta entries the device can hold. + max_points: usize, + max_nodes: usize, + max_meta: usize, +} + +impl RefData { + /// Arrays with room for `points` orbit points and `nodes` / `meta` BLA + /// entries, zeroed (the empty BLA table is valid as all zeros: no levels, + /// no segments). + fn new(device: &wgpu::Device, path: GpuPath, points: usize, nodes: usize, meta: usize) -> Self { + let max_points = DataKind::Orbit.max_elems(device, path).min(MAX_REF_POINTS); + let max_nodes = DataKind::BlaNodes.max_elems(device, path); + let max_meta = DataKind::BlaMeta.max_elems(device, path); + let points = points.min(max_points); + Self { + path, + orbit: DataArray::new(device, path, DataKind::Orbit, points), + exps: DataArray::new(device, path, DataKind::Exps, points), + bla_nodes: DataArray::new(device, path, DataKind::BlaNodes, nodes.min(max_nodes)), + bla_meta: DataArray::new(device, path, DataKind::BlaMeta, meta.min(max_meta)), + max_points, + max_nodes, + max_meta, + } + } + + /// Exactly `reference` and `bla` (an export's snapshot). + fn with_contents( + device: &wgpu::Device, + queue: &wgpu::Queue, + path: GpuPath, + reference: &RefOrbit, + bla: &BlaTable, + ) -> Self { + let mut data = Self::new(device, path, reference.len(), 0, 0); + data.write_orbit(queue, reference); + data.upload_bla(device, queue, bla); + data + } + + /// The bind group layout entries of bindings 1 and 3-5. + fn layout_entries(path: GpuPath) -> [wgpu::BindGroupLayoutEntry; 4] { + [ + DataKind::Orbit, + DataKind::Exps, + DataKind::BlaNodes, + DataKind::BlaMeta, + ] + .map(|k| k.layout_entry(path)) + } + + fn bind_entries(&self) -> [wgpu::BindGroupEntry<'_>; 4] { + [ + self.orbit.bind_entry(), + self.exps.bind_entry(), + self.bla_nodes.bind_entry(), + self.bla_meta.bind_entry(), + ] + } + + /// Orbit points that fit on the device: the shader must never be told + /// about more (`Uniforms::ref_len`). + fn points_limit(&self) -> usize { + self.max_points + } + + /// Grow the orbit arrays (by powers of two) to hold `needed` points, + /// without keeping their contents. True if they were reallocated, so + /// bind groups pointing at them need rebuilding. + fn ensure_points(&mut self, device: &wgpu::Device, needed: usize) -> bool { + let needed = needed.min(self.max_points); + if needed <= self.orbit.capacity { + return false; + } + let capacity = needed.next_power_of_two().min(self.max_points); + self.orbit = DataArray::new(device, self.path, DataKind::Orbit, capacity); + self.exps = DataArray::new(device, self.path, DataKind::Exps, capacity); + true + } + + /// Upload the orbit's first points (as many as fit; the caller grew the + /// arrays with `ensure_points`). + fn write_orbit(&self, queue: &wgpu::Queue, reference: &RefOrbit) { + let count = reference.len().min(self.orbit.capacity); + if count > 0 { + self.orbit + .write(queue, bytemuck::cast_slice(&reference[..count])); + self.exps + .write(queue, bytemuck::cast_slice(&reference.exps[..count])); + } + } + + /// Upload `table`, growing the BLA arrays (by powers of two) if needed. + /// A table too large for the device is replaced by the empty one (no + /// jumps). True if the arrays were reallocated. + fn upload_bla(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, table: &BlaTable) -> bool { + let empty; + let table = if table.nodes.len() <= self.max_nodes && table.meta.len() <= self.max_meta { + table + } else { + log::warn!( + "BLA table ({} nodes) too large for this device; skipping BLA", + table.nodes.len() + ); + empty = BlaTable::empty(); + &empty + }; + let grow = table.nodes.len() > self.bla_nodes.capacity + || table.meta.len() > self.bla_meta.capacity; + if grow { + let nodes = table.nodes.len().next_power_of_two().min(self.max_nodes); + let meta = table.meta.len().max(64).min(self.max_meta); + self.bla_nodes = DataArray::new(device, self.path, DataKind::BlaNodes, nodes); + self.bla_meta = DataArray::new(device, self.path, DataKind::BlaMeta, meta); + } + self.bla_nodes + .write(queue, bytemuck::cast_slice(&table.nodes)); + self.bla_meta + .write(queue, bytemuck::cast_slice(&table.meta)); + grow } } @@ -843,17 +1361,14 @@ pub struct FractalRenderer { pipelines: HashMap, bind_group_layout: wgpu::BindGroupLayout, uniform_buffer: wgpu::Buffer, - ref_buffer: wgpu::Buffer, - ref_exp_buffer: wgpu::Buffer, - /// Points `ref_buffer` / `ref_exp_buffer` can hold (see `ensure_ref_capacity`). - ref_capacity: usize, - bla: BlaBuffers, + /// Reference orbit + BLA table (bindings 1, 3-5), as `GpuPath` reads them. + data: RefData, /// Generation of the BLA table currently in `bla`. uploaded_bla_generation: u64, lights_buffer: wgpu::Buffer, bind_group: wgpu::BindGroup, target_format: wgpu::TextureFormat, - /// Generation of the reference orbit currently uploaded to `ref_buffer`. + /// Generation of the reference orbit currently uploaded to `data`. uploaded_generation: u64, /// Contents of `lights_buffer`, so it's only re-uploaded on change. uploaded_lights: Option<[GpuLight; MAX_LIGHT_COUNT]>, @@ -885,65 +1400,29 @@ pub struct FractalRenderer { } impl FractalRenderer { - /// Grow the reference buffers (and rebuild the bind group pointing at - /// them) so they hold at least `needed` points. The caller re-uploads the - /// orbit right after, so the old contents aren't copied over. - fn ensure_ref_capacity(&mut self, device: &wgpu::Device, needed: usize) { - if needed <= self.ref_capacity { - return; - } - let capacity = needed.next_power_of_two().min(MAX_REF_POINTS); - self.ref_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("reference orbit"), - size: (capacity * std::mem::size_of::<[f32; 2]>()) as u64, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - self.ref_exp_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("reference orbit exponents"), - size: (capacity * std::mem::size_of::()) as u64, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - self.rebuild_bind_group(device); - self.ref_capacity = capacity; - } - fn rebuild_bind_group(&mut self, device: &wgpu::Device) { self.bind_group = iterate_bind_group( device, &self.bind_group_layout, &self.uniform_buffer, - &self.ref_buffer, &self.lights_buffer, - &self.ref_exp_buffer, - &self.bla, + &self.data, ); } - /// Upload `table`, growing the BLA buffers (by powers of two) if needed. - fn upload_bla(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, table: &BlaTable) { - if self.bla.fits(table) { - self.bla.write(queue, table); - return; - } - self.bla = BlaBuffers::new(device, table, table.nodes.len().next_power_of_two(), 64); - self.rebuild_bind_group(device); + /// How this renderer's iteration shader reads its data. + pub fn gpu_path(&self) -> GpuPath { + self.data.path } pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self { + let path = GpuPath::for_device(device); + log::debug!("iteration data path: {path:?}"); let shader = unsafe { device.create_shader_module_trusted( wgpu::ShaderModuleDescriptor { label: Some("mandelbrot"), - source: wgpu::ShaderSource::Wgsl( - concat!( - include_str!("../shaders/common.wgsl"), - include_str!("../shaders/iterate_uniforms.wgsl"), - include_str!("../shaders/mandelbrot.wgsl"), - ) - .into(), - ), + source: wgpu::ShaderSource::Wgsl(path.mandelbrot_source().into()), }, wgpu::ShaderRuntimeChecks::unchecked(), ) @@ -956,21 +1435,7 @@ impl FractalRenderer { mapped_at_creation: false, }); - let ref_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("reference orbit"), - size: (INITIAL_REF_POINTS * std::mem::size_of::<[f32; 2]>()) as u64, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - - // Per-point exponents of the reference orbit (`RefOrbit::exps`), only - // read by deep pipelines. - let ref_exp_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("reference orbit exponents"), - size: (INITIAL_REF_POINTS * std::mem::size_of::()) as u64, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); + let data = RefData::new(device, path, INITIAL_REF_POINTS, 1 << 14, 64); let lights_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("lights parameters"), @@ -979,85 +1444,13 @@ impl FractalRenderer { mapped_at_creation: false, }); - let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("fractal bind group layout"), - entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - // Only read by the export pipeline's shadow branch (`fs_color` - // with the custom-lights palette); the iterate pipeline - // (`fs_data`) ignores it, but both pipelines share this layout. - wgpu::BindGroupLayoutEntry { - binding: 2, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 3, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - wgpu::BindGroupLayoutEntry { - binding: 4, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - // BLA table nodes / meta (`fractal::bla`). - wgpu::BindGroupLayoutEntry { - binding: 5, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: true }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, - ], - }); - - let bla = BlaBuffers::new(device, &BlaTable::empty(), 1 << 14, 64); + let bind_group_layout = iterate_bind_group_layout(device, path); let bind_group = iterate_bind_group( device, &bind_group_layout, &uniform_buffer, - &ref_buffer, &lights_buffer, - &ref_exp_buffer, - &bla, + &data, ); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -1263,10 +1656,7 @@ impl FractalRenderer { pipelines: HashMap::new(), bind_group_layout, uniform_buffer, - ref_buffer, - ref_exp_buffer, - ref_capacity: INITIAL_REF_POINTS, - bla, + data, uploaded_bla_generation: u64::MAX, lights_buffer, bind_group, @@ -1283,7 +1673,7 @@ impl FractalRenderer { cache: None, iterated: None, colored: None, - ci_stats: CiStats::new(CiHistogram::new(device), device), + ci_stats: CiStats::new(CiHistogram::new(device, path), device), timing: PassTiming::default(), } } @@ -1301,7 +1691,7 @@ impl FractalRenderer { let staging = &self.ci_stats.staging; let range = { let data = staging.slice(..).get_mapped_range().ok()?; - ci_range(bytemuck::cast_slice(&data)) + ci_range(&self.ci_stats.histogram.read(&data)) }; staging.unmap(); self.ci_stats.state = CiStatsState::Idle; @@ -1545,6 +1935,7 @@ impl FractalRenderer { ExportHandles { pipeline, bind_group_layout: self.bind_group_layout.clone(), + path: self.data.path, format: self.target_format, raymarch, probe, @@ -1559,6 +1950,8 @@ pub struct ExportHandles { /// Combined iterate + colour pipeline (`fs_color`), for 2D modes. pipeline: wgpu::RenderPipeline, bind_group_layout: wgpu::BindGroupLayout, + /// How the pipelines read the reference orbit and BLA table. + path: GpuPath, format: wgpu::TextureFormat, /// The two-pass chain, for 3D mode and the distance field only. raymarch: Option, @@ -1643,30 +2036,11 @@ impl ExportRender { usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); + let data = RefData::with_contents(device, queue, handles.path, reference, bla); + let mut uniforms = uniforms; + uniforms.ref_len = uniforms.ref_len.min(data.points_limit() as u32); queue.write_buffer(&uniform_buffer, 0, bytemuck::bytes_of(&uniforms)); - let count = reference.len().min(MAX_REF_POINTS); - let ref_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("export reference orbit"), - size: (count.max(1) * std::mem::size_of::<[f32; 2]>()) as u64, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - let ref_exp_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("export reference orbit exponents"), - size: (count.max(1) * std::mem::size_of::()) as u64, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - if count > 0 { - queue.write_buffer(&ref_buffer, 0, bytemuck::cast_slice(&reference[..count])); - queue.write_buffer( - &ref_exp_buffer, - 0, - bytemuck::cast_slice(&reference.exps[..count]), - ); - } - // Only read by the shadow branch's custom-lights palette; harmless // (zeroed) for every other coloring mode. let lights_buffer = device.create_buffer(&wgpu::BufferDescriptor { @@ -1678,39 +2052,14 @@ impl ExportRender { let (gpu_lights, _) = gpu_lights(lights); queue.write_buffer(&lights_buffer, 0, bytemuck::cast_slice(&gpu_lights)); - let bla_buffers = BlaBuffers::new(device, bla, 0, 0); - let target_format = handles.format; - let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("export bind group"), - layout: &handles.bind_group_layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: uniform_buffer.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: ref_buffer.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 2, - resource: lights_buffer.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 3, - resource: ref_exp_buffer.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 4, - resource: bla_buffers.nodes.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 5, - resource: bla_buffers.meta.as_entire_binding(), - }, - ], - }); + let bind_group = iterate_bind_group( + device, + &handles.bind_group_layout, + &uniform_buffer, + &lights_buffer, + &data, + ); let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("export target"), @@ -1905,7 +2254,7 @@ impl ExportRender { view_formats: &[], }) .create_view(&wgpu::TextureViewDescriptor::default()); - let (hist, staging) = CiHistogram::buffers(device); + let (hist, staging) = histogram.buffers(device); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("export ci probe"), @@ -1946,7 +2295,15 @@ impl ExportRender { sizer.observe(y1 - y0, start.elapsed().as_secs_f64()); y0 = y1; } - histogram.record(device, &mut encoder, &data, width, height, &hist, &staging); + histogram.record( + device, + &mut encoder, + &data, + width, + height, + hist.as_ref(), + &staging, + ); queue.submit(std::iter::once(encoder.finish())); let (tx, rx) = std::sync::mpsc::channel(); @@ -1960,7 +2317,7 @@ impl ExportRender { timeout: None, }); rx.recv().ok()?.ok()?; - let hist = bytemuck::cast_slice(&staging.slice(..).get_mapped_range().ok()?).to_vec(); + let hist = histogram.read(&staging.slice(..).get_mapped_range().ok()?); staging.unmap(); Some(hist) } @@ -2295,51 +2652,62 @@ pub fn encode_png_with_progress( out } -/// Colourise pass input: the uniforms, the data texture `data` to colour and -/// the lights. -/// Group 0 of the iterate/refine pipelines: uniforms, reference orbit, -/// lights, reference exponents. +/// Layout of group 0 of the iterate/refine/export pipelines: uniforms, +/// lights and the [`RefData`] arrays as `path` binds them. +fn iterate_bind_group_layout(device: &wgpu::Device, path: GpuPath) -> wgpu::BindGroupLayout { + let uniform = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }; + let mut entries = vec![ + uniform(0), + // Only read by the export pipeline's shadow branch (`fs_color` with + // the custom-lights palette); the iterate pipeline (`fs_data`) + // ignores it, but both pipelines share this layout. + uniform(2), + ]; + entries.extend(RefData::layout_entries(path)); + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("fractal bind group layout"), + entries: &entries, + }) +} + +/// Group 0 of the iterate/refine pipelines: uniforms, lights and the +/// reference orbit / BLA arrays. fn iterate_bind_group( device: &wgpu::Device, layout: &wgpu::BindGroupLayout, uniform_buffer: &wgpu::Buffer, - ref_buffer: &wgpu::Buffer, lights_buffer: &wgpu::Buffer, - ref_exp_buffer: &wgpu::Buffer, - bla: &BlaBuffers, + data: &RefData, ) -> wgpu::BindGroup { + let mut entries = vec![ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform_buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: lights_buffer.as_entire_binding(), + }, + ]; + entries.extend(data.bind_entries()); device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("fractal bind group"), layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: uniform_buffer.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: ref_buffer.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 2, - resource: lights_buffer.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 3, - resource: ref_exp_buffer.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 4, - resource: bla.nodes.as_entire_binding(), - }, - wgpu::BindGroupEntry { - binding: 5, - resource: bla.meta.as_entire_binding(), - }, - ], + entries: &entries, }) } +/// Colourise pass input: the uniforms, the data texture `data` to colour and +/// the lights. fn colorize_bind_group( device: &wgpu::Device, layout: &wgpu::BindGroupLayout, @@ -2688,31 +3056,25 @@ impl egui_wgpu::CallbackTrait for FractalCallback { && renderer.uploaded_generation != self.generation && !self.reference.is_empty() { - let count = self.reference.len().min(MAX_REF_POINTS); - renderer.ensure_ref_capacity(device, count); - queue.write_buffer( - &renderer.ref_buffer, - 0, - bytemuck::cast_slice(&self.reference[..count]), - ); - queue.write_buffer( - &renderer.ref_exp_buffer, - 0, - bytemuck::cast_slice(&self.reference.exps[..count]), - ); + if renderer.data.ensure_points(device, self.reference.len()) { + renderer.rebuild_bind_group(device); + } + renderer.data.write_orbit(queue, &self.reference); renderer.uploaded_generation = self.generation; } if iter_dirty && renderer.uploaded_bla_generation != self.bla_generation { - renderer.upload_bla(device, queue, &self.bla); + if renderer.data.upload_bla(device, queue, &self.bla) { + renderer.rebuild_bind_group(device); + } renderer.uploaded_bla_generation = self.bla_generation; } - // Every pass reads the uniform buffer; refresh it once. - queue.write_buffer( - &renderer.uniform_buffer, - 0, - bytemuck::bytes_of(&self.uniforms), - ); + // Every pass reads the uniform buffer; refresh it once. The shader + // must not read past the orbit the device could hold (only ever + // shorter than the reference on small WebGL2 devices). + let mut uniforms = self.uniforms; + uniforms.ref_len = uniforms.ref_len.min(renderer.data.points_limit() as u32); + queue.write_buffer(&renderer.uniform_buffer, 0, bytemuck::bytes_of(&uniforms)); if renderer.uploaded_lights.as_ref() != Some(&self.lights) { queue.write_buffer( &renderer.lights_buffer, diff --git a/src/main.rs b/src/main.rs index 24947e1..6f052e6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,12 +36,14 @@ type MainResult = eframe::Result; type MainResult = Result<(), String>; /// wgpu configuration for eframe. The fractal fragment shader reads the -/// reference orbit from a **storage buffer**, so the device must allow storage -/// buffers in the fragment stage. eframe's default requests WebGL2-downlevel -/// limits when a GL adapter is picked (storage buffers = 0), so we: +/// reference orbit from **storage buffers** where the device allows them in +/// the fragment stage (`GpuPath` in renderer.rs). eframe's default requests +/// WebGL2-downlevel limits when a GL adapter is picked (storage buffers = 0), +/// so we: /// * request the adapter's real limits (which include storage buffers), and -/// * force the WebGPU backend on the web (WebGL2 can't do storage buffers at -/// all) — failing cleanly on browsers without WebGPU, per the design. +/// * on the web, use WebGPU only, failing cleanly on browsers without it, +/// unless the `webgl` feature adds WebGL2 as a fallback (egui-wgpu +/// tries WebGPU first). #[cfg(feature = "gui")] fn wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration { use eframe::egui_wgpu::{WgpuSetup, wgpu}; @@ -55,10 +57,25 @@ fn wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration { required_limits: adapter.limits(), ..Default::default() }); - #[cfg(target_arch = "wasm32")] + #[cfg(all(target_arch = "wasm32", not(feature = "webgl")))] { setup.instance_descriptor.backends = wgpu::Backends::BROWSER_WEBGPU; } + #[cfg(all(target_arch = "wasm32", feature = "webgl"))] + { + // `?backend=webgl` forces the fallback, to test it in a browser + // that has WebGPU. + let force_gl = web_sys::window() + .and_then(|w| w.location().search().ok()) + .and_then(|q| web_sys::UrlSearchParams::new_with_str(&q).ok()) + .and_then(|p| p.get("backend")) + .is_some_and(|b| b == "webgl"); + setup.instance_descriptor.backends = if force_gl { + wgpu::Backends::GL + } else { + wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL + }; + } } options } diff --git a/src/shaders/ci_sample.wgsl b/src/shaders/ci_sample.wgsl new file mode 100644 index 0000000..cea690f --- /dev/null +++ b/src/shaders/ci_sample.wgsl @@ -0,0 +1,22 @@ +// Auto colour scale without compute shaders (WebGL2): point-samples the data +// texture onto a small CI_SAMPLE_DIM² grid, read back and binned on the CPU +// like `ci_stats.wgsl` (`CiHistogram::Readback` in renderer.rs). The grid +// stretches to the source's aspect; percentiles don't care. + +@group(0) @binding(0) var data_tex: texture_2d; + +@vertex +fn vs_main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4 { + return vec4(fullscreen_triangle_pos(idx), 0.0, 1.0); +} + +// Must match `CI_SAMPLE_DIM` in renderer.rs. +const CI_SAMPLE_DIM: f32 = 256.0; + +@fragment +fn fs_main(@builtin(position) pos: vec4) -> @location(0) vec4 { + let size = vec2(textureDimensions(data_tex)); + let p = min(vec2(floor(pos.xy * size / CI_SAMPLE_DIM)), vec2(size) - 1); + let d = textureLoad(data_tex, p, 0); + return vec4(d.r, d.b, 0.0, 0.0); +} diff --git a/src/shaders/data_storage.wgsl b/src/shaders/data_storage.wgsl new file mode 100644 index 0000000..b234d5e --- /dev/null +++ b/src/shaders/data_storage.wgsl @@ -0,0 +1,47 @@ +// Reference orbit + BLA table as storage buffers, and the native float +// builtins: the data fragment of `mandelbrot.wgsl` on every device with +// fragment-stage storage buffers (WebGPU, Vulkan, Metal, DX12). Each +// accessor is a plain index that the shader compiler inlines. Must define +// the same functions as `data_texture.wgsl` (the WebGL2 fallback). + +@group(0) @binding(1) var ref_orbit: array>; +@group(0) @binding(3) var ref_exp: array; +@group(0) @binding(4) var bla_nodes: array; +@group(0) @binding(5) var bla_meta: array; + +fn ref_point(m: u32) -> vec2 { + return ref_orbit[m]; +} + +fn ref_exp_at(m: u32) -> i32 { + return ref_exp[m]; +} + +fn bla_node(i: u32) -> Bla { + return bla_nodes[i]; +} + +fn bla_r_log2(i: u32) -> f32 { + return bla_nodes[i].r_log2; +} + +fn bla_steps(i: u32) -> u32 { + return bla_nodes[i].steps; +} + +fn bla_meta_at(i: u32) -> u32 { + return bla_meta[i]; +} + +fn frexp_f32(x: f32) -> Frexp { + let f = frexp(x); + return Frexp(f.fract, f.exp); +} + +fn ldexp_f32(x: f32, k: i32) -> f32 { + return ldexp(x, k); +} + +fn ctz_u32(x: u32) -> u32 { + return countTrailingZeros(x); +} diff --git a/src/shaders/data_texture.wgsl b/src/shaders/data_texture.wgsl new file mode 100644 index 0000000..4f40be5 --- /dev/null +++ b/src/shaders/data_texture.wgsl @@ -0,0 +1,104 @@ +// Reference orbit + BLA table as textures, and bit-exact replacements for +// float builtins: the data fragment of `mandelbrot.wgsl` on devices without +// fragment-stage storage buffers (WebGL2, `GpuPath::Texture` in +// renderer.rs). Must define the same functions as `data_storage.wgsl`. +// +// Every array is laid out row-major in a texture DATA_TEX_WIDTH texels wide +// (element i at (i % W, i / W); `RefData` in renderer.rs). BLA nodes are 3 +// `Rgba32Uint` texels each (m, n, then m_exp/n_exp/r_log2/steps), floats as +// raw bits: a float texture could flush the small i32 exponents, whose bit +// patterns are subnormal floats. + +@group(0) @binding(1) var ref_orbit_tex: texture_2d; +@group(0) @binding(3) var ref_exp_tex: texture_2d; +@group(0) @binding(4) var bla_nodes_tex: texture_2d; +@group(0) @binding(5) var bla_meta_tex: texture_2d; + +// Must match `DATA_TEX_WIDTH` in renderer.rs (2048, WebGL2's guaranteed +// minimum texture size). +const DATA_TEX_LOG2_W: u32 = 11u; + +fn data_texel(i: u32) -> vec2 { + return vec2(i32(i & ((1u << DATA_TEX_LOG2_W) - 1u)), i32(i >> DATA_TEX_LOG2_W)); +} + +fn ref_point(m: u32) -> vec2 { + return textureLoad(ref_orbit_tex, data_texel(m), 0).xy; +} + +fn ref_exp_at(m: u32) -> i32 { + return textureLoad(ref_exp_tex, data_texel(m), 0).x; +} + +fn bla_node(i: u32) -> Bla { + let a = textureLoad(bla_nodes_tex, data_texel(3u * i), 0); + let b = textureLoad(bla_nodes_tex, data_texel(3u * i + 1u), 0); + let c = textureLoad(bla_nodes_tex, data_texel(3u * i + 2u), 0); + return Bla( + bitcast>(a), + bitcast>(b), + bitcast(c.x), + bitcast(c.y), + bitcast(c.z), + c.w, + ); +} + +fn bla_r_log2(i: u32) -> f32 { + return bitcast(textureLoad(bla_nodes_tex, data_texel(3u * i + 2u), 0).z); +} + +fn bla_steps(i: u32) -> u32 { + return textureLoad(bla_nodes_tex, data_texel(3u * i + 2u), 0).w; +} + +fn bla_meta_at(i: u32) -> u32 { + return textureLoad(bla_meta_tex, data_texel(i), 0).x; +} + +// 2^e for e in [-126, 127], built from its bits. +fn pow2_f32(e: i32) -> f32 { + return bitcast(u32(e + 127) << 23u); +} + +// WGSL `frexp` from the exponent bits. naga's GLSL ES 3.00 polyfill goes +// through log2, which is wrong for negative x and off by one near powers of +// two. Subnormals are scaled up by 2^64 first (0 if the GPU flushes them). +fn frexp_f32(x: f32) -> Frexp { + var bits = bitcast(x); + var bias = 0; + if ((bits >> 23u) & 0xffu) == 0u { + if (bits & 0x7fffffffu) == 0u { + return Frexp(x, 0); + } + bits = bitcast(x * 18446744073709551616.0); // 2^64 + bias = -64; + if ((bits >> 23u) & 0xffu) == 0u { + return Frexp(0.0, 0); + } + } + let biased = i32((bits >> 23u) & 0xffu); + if biased == 255 { + return Frexp(x, 0); // inf / NaN + } + return Frexp(bitcast((bits & 0x807fffffu) | 0x3f000000u), biased - 126 + bias); +} + +// WGSL `ldexp` (GLSL ES 3.10+) as two exact power-of-two multiplies, valid +// for |k| <= 252; with both halves the same sign, the intermediate is +// normal whenever the result is. +fn ldexp_f32(x: f32, k: i32) -> f32 { + let k1 = clamp(k / 2, -126, 127); + let k2 = clamp(k - k1, -126, 127); + return x * pow2_f32(k1) * pow2_f32(k2); +} + +// WGSL `countTrailingZeros` (`findLSB` is GLSL ES 3.10+): the exponent of +// the lowest set bit, which converts to f32 exactly. +fn ctz_u32(x: u32) -> u32 { + if x == 0u { + return 32u; + } + let low = x & (~x + 1u); + return (bitcast(f32(low)) >> 23u) - 127u; +} diff --git a/src/shaders/mandelbrot.wgsl b/src/shaders/mandelbrot.wgsl index d3f7617..decf8d5 100644 --- a/src/shaders/mandelbrot.wgsl +++ b/src/shaders/mandelbrot.wgsl @@ -18,23 +18,27 @@ // to the plain f32 loop once the delta is big enough (see `iterate_sample`). @group(0) @binding(0) var u: Uniforms; -@group(0) @binding(1) var ref_orbit: array>; +// Bindings 1 and 3-5 (reference orbit, its exponents, the BLA table) are +// declared by the data fragment concatenated after this file: storage +// buffers (`data_storage.wgsl`) or, where the device has none (WebGL2), +// textures (`data_texture.wgsl`). Both provide `ref_point`, `ref_exp_at`, +// `bla_node`, `bla_r_log2`, `bla_steps`, `bla_meta_at`, plus `frexp_f32`, +// `ldexp_f32` and `ctz_u32` (GLSL ES 3.00 lacks the builtins). // Only read by `fs_color`'s shadow branch (custom-lights palette); the // iteration pass (`fs_data`) never touches it. @group(0) @binding(2) var lights: array; // Only read by the adaptive-AA refine pass (`fs_refine`): the 1-sample-per- // pixel data texture written by `fs_data`, which decides where to supersample. @group(1) @binding(0) var coarse_tex: texture_2d; -// Per-point binary exponents of the reference orbit (`RefOrbit::exps`): the -// true X[m] is ref_orbit[m] * 2^ref_exp[m]. Non-zero only for points below -// f32's range, which only deep references contain; only `DEEP` pipelines read -// it (see `ref_at`). -@group(0) @binding(3) var ref_exp: array; +// Reference orbit: point m is `ref_point(m)`, and the true X[m] is +// ref_point(m) * 2^ref_exp_at(m). The exponent is non-zero only for points +// below f32's range, which only deep references contain; only `DEEP` +// pipelines read it (see `ref_at`). // Bivariate linear approximation table (`fractal::bla`): node i of level l // maps the delta at reference step 1 + i·2^l to the one 2^l steps later as // e' = M·e + N·dc, valid while log2|e| < r_log2. M = m·2^m_exp and // N = n·2^n_exp are real 2x2 matrices, row-major (the Jacobian of the map, -// so the abs/conjugate kinds are covered too). `bla_meta` is +// so the abs/conjugate kinds are covered too). `bla_meta_at` reads // [min_level, level_count, off_0, ..., off_{level_count}, seg_count, // seg_start_0, ...]: segment i is node off_{level_count} + i and covers its // `steps` steps from seg_start_i (see `bla_seg_find`). Only `BLA` pipelines @@ -47,8 +51,12 @@ struct Bla { r_log2: f32, steps: u32, }; -@group(0) @binding(4) var bla_nodes: array; -@group(0) @binding(5) var bla_meta: array; + +// `frexp` result (see `frexp_f32`). +struct Frexp { + fract: f32, + exp: i32, +}; // Pipeline-overridable specialization constants, set per pipeline from the // uniforms' `kind` / `is_julia` / `de_coloring` (see `PipelineKey` in @@ -316,7 +324,7 @@ fn ldexp_sat(x: f32, k: i32) -> f32 { } return bitcast(bitcast(bits) + (k << 23u)); } - let f = frexp(x); + let f = frexp_f32(x); let ex = f.exp + k; if ex > 100 { return select(-LDEXP_SAT, LDEXP_SAT, x > 0.0); @@ -324,7 +332,7 @@ fn ldexp_sat(x: f32, k: i32) -> f32 { if ex < -125 { return 0.0; } - return ldexp(f.fract, ex); + return ldexp_f32(f.fract, ex); } fn ldexp2_sat(v: vec2, k: i32) -> vec2 { @@ -343,16 +351,16 @@ fn fe_make(v: vec2, e: i32) -> Fe { if a == 0.0 { return Fe(vec2(0.0, 0.0), 0); } - let k = frexp(a).exp; + let k = frexp_f32(a).exp; return Fe(ldexp2_sat(v, -k), e + k); } // Reference point X[m] as f32 (points stored normalized flush to 0 here; // only deep references have any, see `ref_exp`). fn ref_at(m: u32) -> vec2 { - let x = ref_orbit[m]; + let x = ref_point(m); if DEEP { - let k = ref_exp[m]; + let k = ref_exp_at(m); if k != 0 { return ldexp2_sat(x, k); } @@ -362,7 +370,7 @@ fn ref_at(m: u32) -> vec2 { // X[m] with its full exponent range (deep phase only). fn ref_fe(m: u32) -> Fe { - return fe_make(ref_orbit[m], ref_exp[m]); + return fe_make(ref_point(m), ref_exp_at(m)); } // Complex log of m * 2^e (m != 0). @@ -567,7 +575,7 @@ fn deep_log2(a: vec2, b: vec2) -> i32 { if m == 0.0 { return DEEP_ZERO; } - return frexp(m).exp; + return frexp_f32(m).exp; } // f'(y) at the full value y = X + w * 2^s, as an `Fe`. Plain `fprime` in f32 @@ -639,13 +647,13 @@ fn log2_mag(v: vec2) -> f32 { // invalid level (usually right away: one load per failed attempt). fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2 { var best = vec2(0u, 0u); - let levels = bla_meta[1]; + let levels = bla_meta_at(1u); if levels == 0u || m == 0u { return best; } - let lmin = bla_meta[0]; + let lmin = bla_meta_at(0u); let j = m - 1u; - let tz = countTrailingZeros(j); // 32 when j == 0 + let tz = ctz_u32(j); // 32 when j == 0 if tz < lmin { return best; } @@ -654,7 +662,7 @@ fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2 { // dependent load each): level 0 starts at 0 and each level has half the // previous one's nodes, rounded down (`bla::build`). var base = 0u; - var count = bla_meta[3]; + var count = bla_meta_at(3u); for (var k: u32 = 0u; k <= top; k = k + 1u) { let l = lmin + k; let steps = 1u << l; @@ -663,7 +671,7 @@ fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2 { break; } let idx = base + local; - if !(e_log2 < bla_nodes[idx].r_log2) { + if !(e_log2 < bla_r_log2(idx)) { break; } best = vec2(idx, steps); @@ -679,14 +687,14 @@ fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2 { // (`seg_i`, starting at `seg_at`); m only grows between rebases, so that // only moves forward. fn bla_seg_count() -> u32 { - return bla_meta[bla_meta[1] + 3u]; + return bla_meta_at(bla_meta_at(1u) + 3u); } fn bla_seg_start(i: u32) -> u32 { if i >= bla_seg_count() { return 0xffffffffu; } - return bla_meta[bla_meta[1] + 4u + i]; + return bla_meta_at(bla_meta_at(1u) + 4u + i); } // First segment from `lo` on that starts at or after `m` (binary search: a @@ -696,7 +704,7 @@ fn bla_seg_find(lo: u32, m: u32) -> u32 { var b = bla_seg_count(); while a < b { let mid = (a + b) / 2u; - if bla_meta[bla_meta[1] + 4u + mid] < m { + if bla_meta_at(bla_meta_at(1u) + 4u + mid) < m { a = mid + 1u; } else { b = mid; @@ -709,9 +717,9 @@ fn bla_seg_find(lo: u32, m: u32) -> u32 { // else `bla_lookup`'s: (node index, steps), steps = 0 when there's none. fn bla_jump(m: u32, seg_i: u32, seg_at: u32, e_log2: f32, budget: u32) -> vec2 { if seg_at == m { - let idx = bla_meta[bla_meta[1] + 2u] + seg_i; - let steps = bla_nodes[idx].steps; - if e_log2 < bla_nodes[idx].r_log2 && steps <= budget { + let idx = bla_meta_at(bla_meta_at(1u) + 2u) + seg_i; + let steps = bla_steps(idx); + if e_log2 < bla_r_log2(idx) && steps <= budget { return vec2(idx, steps); } } @@ -826,7 +834,7 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { // so skip the test once a pixel is smaller than that error (deep zoom), // where it could misclassify pixels right at the boundary. if KIND == KIND_MANDELBROT && !MORPH && !IS_JULIA && !DEEP && ref_len > 1u && px > 1e-6 { - let c = ref_orbit[1] + offset; + let c = ref_point(1u) + offset; let xq = c.x - 0.25; let q = xq * xq + c.y * c.y; let in_cardioid = q * (q + xq) <= 0.25 * c.y * c.y; @@ -956,7 +964,7 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { } let hit = bla_jump(m, seg_i, seg_at, e_log2, min(max_iter - n, ref_len - 1u - m)); if hit.y != 0u { - let nd = bla_nodes[hit.x]; + let nd = bla_node(hit.x); if DE { var accv = fe_make(mat2v(nd.m, v), nd.m_exp + sv); if !IS_JULIA { @@ -1187,8 +1195,8 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { // Level nodes start at 1 + i·2^min_level, so only those steps can jump // (tested before `log2_mag` and the lookup: most steps here are plain). var bla_align = 0xffffffffu; - if BLA && bla_meta[1] != 0u { - bla_align = (1u << bla_meta[0]) - 1u; + if BLA && bla_meta_at(1u) != 0u { + bla_align = (1u << bla_meta_at(0u)) - 1u; } loop { // (`escaped` may already be set by the deep phase.) @@ -1220,7 +1228,7 @@ fn iterate_sample(offset: vec2, px: f32) -> Sample { if BLA && m != 0u && ((m - 1u) & bla_align) == 0u { let hit = bla_lookup(m, log2_mag(e), min(max_iter - n, ref_len - 1u - m)); if hit.y != 0u { - let nd = bla_nodes[hit.x]; + let nd = bla_node(hit.x); let se = select(0, u.scale_exp, DEEP); if periodic { let det = abs(nd.m.x * nd.m.w - nd.m.y * nd.m.z); diff --git a/tests/shader_valid.rs b/tests/shader_valid.rs index cfcbb2c..4f78acc 100644 --- a/tests/shader_valid.rs +++ b/tests/shader_valid.rs @@ -65,22 +65,33 @@ fn specialize( .unwrap_or_else(|e| panic!("{name} {entry_point} {constants:?}: SPIR-V error: {e:?}")); } +/// `mandelbrot.wgsl` as `GpuPath::Storage` builds it (renderer.rs's +/// `GpuPath::mandelbrot_source`). const MANDELBROT_SRC: &str = concat!( include_str!("../src/shaders/common.wgsl"), include_str!("../src/shaders/iterate_uniforms.wgsl"), include_str!("../src/shaders/mandelbrot.wgsl"), + include_str!("../src/shaders/data_storage.wgsl"), +); + +/// `mandelbrot.wgsl` as `GpuPath::Texture` (WebGL2) builds it. +const MANDELBROT_TEXTURE_SRC: &str = concat!( + include_str!("../src/shaders/common.wgsl"), + include_str!("../src/shaders/iterate_uniforms.wgsl"), + include_str!("../src/shaders/mandelbrot.wgsl"), + include_str!("../src/shaders/data_texture.wgsl"), ); #[test] fn mandelbrot_shader_is_valid() { validate("mandelbrot.wgsl", MANDELBROT_SRC); + validate("mandelbrot.wgsl (texture)", MANDELBROT_TEXTURE_SRC); } -/// Every specialization renderer.rs can build (`PipelineKey`: kind × Julia × -/// DE × morph × deep × BLA), for every fragment entry point. -#[test] -fn mandelbrot_shader_specializations_compile() { - let (module, info) = validate("mandelbrot.wgsl", MANDELBROT_SRC); +/// Every `PipelineKey` renderer.rs can build: kind × Julia × DE × morph × +/// deep × BLA, as override constants. +fn pipeline_keys() -> Vec<[(&'static str, f64); 6]> { + let mut keys = Vec::new(); for kind in 0..kind_count() { for julia in [0.0, 1.0] { for de in [0.0, 1.0] { @@ -93,30 +104,243 @@ fn mandelbrot_shader_specializations_compile() { &[0.0] }; for &bla in blas { - let constants = [ + keys.push([ ("KIND", kind as f64), ("IS_JULIA", julia), ("DE", de), ("MORPH", morph), ("DEEP", deep), ("BLA", bla), - ]; - for entry in ["fs_data", "fs_refine", "fs_color"] { - specialize( - "mandelbrot.wgsl", - &module, - &info, - naga::ShaderStage::Fragment, - entry, - &constants, - ); - } + ]); } } } } } } + keys +} + +/// Every specialization renderer.rs can build, for every fragment entry +/// point, on both data paths. +#[test] +fn mandelbrot_shader_specializations_compile() { + for (name, src) in [ + ("mandelbrot.wgsl", MANDELBROT_SRC), + ("mandelbrot.wgsl (texture)", MANDELBROT_TEXTURE_SRC), + ] { + let (module, info) = validate(name, src); + for constants in pipeline_keys() { + for entry in ["fs_data", "fs_refine", "fs_color"] { + specialize( + name, + &module, + &info, + naga::ShaderStage::Fragment, + entry, + &constants, + ); + } + } + } +} + +/// Translate `entry_point` to GLSL ES 3.00 as wgpu's GL backend does on +/// WebGL2 (`wgpu-hal`'s gles `create_pipeline`), and, when +/// `glslangValidator` is on the PATH, compile the result. naga's ES 3.00 +/// output can call builtins ES 3.00 lacks (`ldexp`, `findLSB`), which only +/// a real GLSL compiler (or the browser) rejects. +fn to_gles300( + name: &str, + module: &naga::Module, + info: &naga::valid::ModuleInfo, + stage: naga::ShaderStage, + entry_point: &str, + constants: &[(&str, f64)], +) -> String { + let mut pc = naga::back::PipelineConstants::default(); + for (k, v) in constants { + pc.insert((*k).to_string(), *v); + } + let what = format!("{name} {entry_point} {constants:?}"); + let (module, info) = naga::back::pipeline_constants::process_overrides( + module, + info, + Some((stage, entry_point)), + &pc, + ) + .unwrap_or_else(|e| panic!("{what}: override error: {e:?}")); + let options = naga::back::glsl::Options { + version: naga::back::glsl::Version::Embedded { + version: 300, + is_webgl: true, + }, + ..Default::default() + }; + let pipeline = naga::back::glsl::PipelineOptions { + shader_stage: stage, + entry_point: entry_point.to_string(), + multiview: None, + }; + let mut out = String::new(); + naga::back::glsl::Writer::new( + &mut out, + &module, + &info, + &options, + &pipeline, + naga::proc::BoundsCheckPolicies::default(), + ) + .and_then(|mut w| w.write()) + .unwrap_or_else(|e| panic!("{what}: GLSL error: {e:?}")); + glslang_check(&what, stage, &out); + out +} + +/// Compile GLSL `src` with `glslangValidator`, if installed. +fn glslang_check(what: &str, stage: naga::ShaderStage, src: &str) { + use std::io::Write as _; + let stage = match stage { + naga::ShaderStage::Vertex => "vert", + naga::ShaderStage::Fragment => "frag", + _ => unreachable!("WebGL2 has no other stages"), + }; + let child = std::process::Command::new("glslangValidator") + .args(["--stdin", "-S", stage]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn(); + let Ok(mut child) = child else { + return; // not installed: naga's translation is all we can check + }; + child + .stdin + .take() + .unwrap() + .write_all(src.as_bytes()) + .unwrap(); + let out = child.wait_with_output().unwrap(); + assert!( + out.status.success(), + "{what}: GLSL ES 3.00 doesn't compile:\n{}\n{src}", + String::from_utf8_lossy(&out.stdout) + ); +} + +/// The WebGL2 build's shaders (`GpuPath::Texture`, plus the passes shared +/// with WebGPU) translate to GLSL ES 3.00 that compiles, for every +/// specialization. +#[test] +fn webgl_shaders_compile_to_gles300() { + let (module, info) = validate("mandelbrot.wgsl (texture)", MANDELBROT_TEXTURE_SRC); + let keys = pipeline_keys(); + // One thread per chunk of keys: glslangValidator runs once per shader. + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + std::thread::scope(|scope| { + for chunk in keys.chunks(keys.len().div_ceil(threads)) { + let (module, info) = (&module, &info); + scope.spawn(move || { + for constants in chunk { + for entry in ["fs_data", "fs_refine", "fs_color"] { + to_gles300( + "mandelbrot.wgsl (texture)", + module, + info, + naga::ShaderStage::Fragment, + entry, + constants, + ); + } + } + }); + } + }); + to_gles300( + "mandelbrot.wgsl (texture)", + &module, + &info, + naga::ShaderStage::Vertex, + "vs_main", + &[], + ); + + let others: [(&str, &str, &[&str]); 4] = [ + ( + "colorize.wgsl", + concat!( + include_str!("../src/shaders/common.wgsl"), + include_str!("../src/shaders/iterate_uniforms.wgsl"), + include_str!("../src/shaders/colorize.wgsl"), + ), + &["fs_main"], + ), + ( + "lipschitz.wgsl", + concat!( + include_str!("../src/shaders/common.wgsl"), + include_str!("../src/shaders/lipschitz.wgsl"), + ), + &["fs_seed", "fs_jump", "fs_compose"], + ), + ( + "blit.wgsl", + concat!( + include_str!("../src/shaders/common.wgsl"), + include_str!("../src/shaders/blit.wgsl"), + ), + &["fs_main"], + ), + ("ci_sample.wgsl", CI_SAMPLE_SRC, &["fs_main"]), + ]; + for (name, src, entries) in others { + let (module, info) = validate(name, src); + to_gles300( + name, + &module, + &info, + naga::ShaderStage::Vertex, + "vs_main", + &[], + ); + for entry in entries { + to_gles300( + name, + &module, + &info, + naga::ShaderStage::Fragment, + entry, + &[], + ); + } + } +} + +/// The texture path's bit-level `frexp`/`ldexp`/`ctz` replacements must not +/// fall back on the builtins GLSL ES 3.00 lacks or polyfills badly (naga's +/// `frexp` polyfill goes through log2). +#[test] +fn texture_path_avoids_es31_builtins() { + let (module, info) = validate("mandelbrot.wgsl (texture)", MANDELBROT_TEXTURE_SRC); + let constants = [ + ("KIND", 0.0), + ("IS_JULIA", 0.0), + ("DE", 1.0), + ("MORPH", 0.0), + ("DEEP", 1.0), + ("BLA", 1.0), + ]; + let glsl = to_gles300( + "mandelbrot.wgsl (texture)", + &module, + &info, + naga::ShaderStage::Fragment, + "fs_data", + &constants, + ); + for builtin in ["ldexp(", "frexp(", "findLSB("] { + assert!(!glsl.contains(builtin), "texture path GLSL calls {builtin}"); + } } #[test] @@ -179,6 +403,16 @@ fn buddhabrot_shader_specializations_compile() { } } +const CI_SAMPLE_SRC: &str = concat!( + include_str!("../src/shaders/common.wgsl"), + include_str!("../src/shaders/ci_sample.wgsl"), +); + +#[test] +fn ci_sample_shader_is_valid() { + validate("ci_sample.wgsl", CI_SAMPLE_SRC); +} + #[test] fn ci_stats_shader_is_valid() { validate(