ferrochart-orderflow 0.3.0

Order flow series for FerroChart: footprint, heatmap and TPO
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Native wgpu drawing of the heatmap (feature `gpu`).
//!
//! The cells live in storage buffers, uploaded incrementally from the
//! series' change log. Each frame a compute shader aggregates the visible
//! columns into a "band × pixel column" buffer (atomic max), and one quad
//! over the plot colors each pixel from it. The pixel layout and the color
//! range come from the core side ([`Heatmap`]'s layout and
//! `CustomDraw::params`), so the output matches the portable path; the
//! shaders contain no chart logic.

use core::any::Any;

use ferrochart_core::chart::ChartDataView;
use ferrochart_core::data::{DataDelta, SeriesId};
use ferrochart_core::frame::CustomDraw;
use ferrochart_render_wgpu::{GpuContext, GpuSeries, GpuSeriesCtx, WgpuRenderer};

use crate::heatmap::{HEATMAP_KIND, Heatmap};

const AGGREGATE_WGSL: &str = include_str!("shaders/heatmap_aggregate.wgsl");
const DRAW_WGSL: &str = include_str!("shaders/heatmap_draw.wgsl");

/// Storage buffers the compute stage binds.
const STORAGE_BUFFERS: u32 = 4;
/// Workgroups per dispatch dimension (the WebGPU minimum limit).
const MAX_GROUPS: u32 = 65_535;

/// Whether `ctx`'s device can run the native heatmap: compute shaders,
/// storage buffers in fragment shaders and at least four storage buffers
/// per stage. Devices created with the WebGL2 limits (e.g. by a host that
/// asked for them) cannot.
pub fn supports_native_heatmap(ctx: &GpuContext) -> bool {
    let flags = ctx.adapter.get_downlevel_capabilities().flags;
    let limits = ctx.device.limits();
    flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS | wgpu::DownlevelFlags::FRAGMENT_STORAGE)
        && limits.max_storage_buffers_per_shader_stage >= STORAGE_BUFFERS
        && limits.max_compute_workgroups_per_dimension >= MAX_GROUPS
        && limits.max_compute_invocations_per_workgroup >= 64
}

/// Registers the native order flow series that `ctx`'s device supports
/// with `renderer` (pass the context the renderer was created with).
/// Returns whether the native heatmap was registered; without it the
/// heatmap draws through its portable path.
///
/// # Examples
///
/// ```no_run
/// use ferrochart_render_wgpu::{GpuContext, WgpuRenderer};
///
/// let ctx = GpuContext::headless()?;
/// let mut renderer = WgpuRenderer::offscreen(&ctx);
/// ferrochart_orderflow::register_gpu(&ctx, &mut renderer);
/// // Then, before each frame: chart.set_native_kinds(renderer.native_kinds()).
/// # Ok::<(), ferrochart_core::render::RenderError>(())
/// ```
pub fn register_gpu(ctx: &GpuContext, renderer: &mut WgpuRenderer) -> bool {
    if !supports_native_heatmap(ctx) {
        return false;
    }
    renderer.register_series(Box::new(HeatmapGpu::default()));
    true
}

/// The native implementation of [`Heatmap`] (kind
/// [`HEATMAP_KIND`]); register it with [`register_gpu`], which checks
/// that the device supports it.
#[derive(Default)]
pub struct HeatmapGpu {
    pipes: Option<Pipes>,
    series: Vec<(SeriesId, SeriesGpu)>,
    /// Cells interleaved for upload.
    scratch: Vec<[u32; 2]>,
}

impl core::fmt::Debug for HeatmapGpu {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("HeatmapGpu")
            .field("series", &self.series.len())
            .finish_non_exhaustive()
    }
}

struct Pipes {
    format: wgpu::TextureFormat,
    aggregate: wgpu::ComputePipeline,
    aggregate_layout: wgpu::BindGroupLayout,
    draw: wgpu::RenderPipeline,
    draw_layout: wgpu::BindGroupLayout,
}

/// A buffer that grows by powers of two.
struct Grow {
    buffer: Option<wgpu::Buffer>,
    usage: wgpu::BufferUsages,
    label: &'static str,
}

impl Grow {
    fn new(usage: wgpu::BufferUsages, label: &'static str) -> Self {
        Self {
            buffer: None,
            usage,
            label,
        }
    }

    /// Makes room for `bytes`; returns whether the buffer was replaced
    /// (its contents are lost).
    fn reserve(&mut self, device: &wgpu::Device, bytes: u64) -> bool {
        if self.buffer.as_ref().is_some_and(|b| b.size() >= bytes) {
            return false;
        }
        let size = bytes.max(256).next_power_of_two();
        self.buffer = Some(device.create_buffer(&wgpu::BufferDescriptor {
            label: Some(self.label),
            size,
            usage: self.usage | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        }));
        true
    }
}

struct SeriesGpu {
    /// Generation of the cells on the GPU.
    synced: Option<u64>,
    cells: Grow,
    col_start: Grow,
    layout: Grow,
    grid: Grow,
    uniform: Grow,
    binds: Option<(wgpu::BindGroup, wgpu::BindGroup)>,
    /// Whether the last `prepare` left something to draw.
    active: bool,
}

impl SeriesGpu {
    fn new() -> Self {
        let storage = wgpu::BufferUsages::STORAGE;
        Self {
            synced: None,
            cells: Grow::new(storage, "heatmap cells"),
            col_start: Grow::new(storage, "heatmap columns"),
            layout: Grow::new(storage, "heatmap layout"),
            grid: Grow::new(storage, "heatmap grid"),
            uniform: Grow::new(wgpu::BufferUsages::UNIFORM, "heatmap uniform"),
            binds: None,
            active: false,
        }
    }
}

fn layout_entry(
    binding: u32,
    visibility: wgpu::ShaderStages,
    ty: wgpu::BufferBindingType,
) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility,
        ty: wgpu::BindingType::Buffer {
            ty,
            has_dynamic_offset: false,
            min_binding_size: None,
        },
        count: None,
    }
}

impl Pipes {
    fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
        use wgpu::BufferBindingType as B;
        use wgpu::ShaderStages as S;
        let ro = B::Storage { read_only: true };
        let aggregate_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("heatmap aggregate"),
            entries: &[
                layout_entry(0, S::COMPUTE, B::Uniform),
                layout_entry(1, S::COMPUTE, ro),
                layout_entry(2, S::COMPUTE, ro),
                layout_entry(3, S::COMPUTE, ro),
                layout_entry(4, S::COMPUTE, B::Storage { read_only: false }),
            ],
        });
        let draw_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("heatmap draw"),
            entries: &[
                layout_entry(0, S::VERTEX | S::FRAGMENT, B::Uniform),
                layout_entry(1, S::FRAGMENT, ro),
                layout_entry(2, S::FRAGMENT, ro),
            ],
        });
        let module = |label, src: &'static str| {
            device.create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some(label),
                source: wgpu::ShaderSource::Wgsl(src.into()),
            })
        };
        let pipeline_layout = |label, layout: &wgpu::BindGroupLayout| {
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some(label),
                bind_group_layouts: &[Some(layout)],
                immediate_size: 0,
            })
        };
        let aggregate_module = module("heatmap aggregate", AGGREGATE_WGSL);
        let aggregate = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("heatmap aggregate"),
            layout: Some(&pipeline_layout("heatmap aggregate", &aggregate_layout)),
            module: &aggregate_module,
            entry_point: Some("aggregate"),
            compilation_options: wgpu::PipelineCompilationOptions::default(),
            cache: None,
        });
        let draw_module = module("heatmap draw", DRAW_WGSL);
        let draw = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("heatmap draw"),
            layout: Some(&pipeline_layout("heatmap draw", &draw_layout)),
            vertex: wgpu::VertexState {
                module: &draw_module,
                entry_point: Some("vs"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                buffers: &[],
            },
            fragment: Some(wgpu::FragmentState {
                module: &draw_module,
                entry_point: Some("fs"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                // Blended like the renderer's rectangles.
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState::default(),
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        Self {
            format,
            aggregate,
            aggregate_layout,
            draw,
            draw_layout,
        }
    }
}

fn entry(binding: u32, buffer: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
    wgpu::BindGroupEntry {
        binding,
        resource: buffer.as_entire_binding(),
    }
}

fn bytes<T>(n: usize) -> u64 {
    (n * size_of::<T>()) as u64
}

impl HeatmapGpu {
    /// Uploads the cells changed since the last sync; returns whether a
    /// buffer was replaced.
    fn upload_cells(
        scratch: &mut Vec<[u32; 2]>,
        s: &mut SeriesGpu,
        ctx: &GpuSeriesCtx<'_>,
        draw: &CustomDraw,
        data: ChartDataView<'_>,
        heatmap: &Heatmap,
    ) -> bool {
        let (col_start, level, a, _) = heatmap.grid().raw();
        let (cols, cells) = (col_start.len(), level.len());
        let mut from = match s.synced.map(|g| data.changes_since(draw.series, g)) {
            None | Some(DataDelta::Full) => 0,
            Some(DataDelta::None) => cols,
            Some(DataDelta::Range(span)) => usize::try_from(span.start.max(0)).unwrap_or(0),
        };
        let mut replaced = s.cells.reserve(ctx.device, bytes::<[u32; 2]>(cells.max(1)));
        replaced |= s.col_start.reserve(ctx.device, bytes::<u32>(cols + 1));
        if replaced {
            from = 0;
        }
        s.synced = Some(draw.generation);
        let (Some(cell_buf), Some(col_buf)) = (&s.cells.buffer, &s.col_start.buffer) else {
            return replaced;
        };
        if from >= cols {
            return false;
        }
        let first_cell = col_start.get(from).map_or(cells, |&c| c as usize);
        scratch.clear();
        scratch.extend(
            level[first_cell..]
                .iter()
                .zip(&a[first_cell..])
                .map(|(&l, &v)| [l.cast_unsigned(), v.to_bits()]),
        );
        if !scratch.is_empty() {
            ctx.queue.write_buffer(
                cell_buf,
                bytes::<[u32; 2]>(first_cell),
                bytemuck::cast_slice(scratch),
            );
        }
        if from < cols {
            ctx.queue.write_buffer(
                col_buf,
                bytes::<u32>(from),
                bytemuck::cast_slice(&col_start[from..]),
            );
        }
        // The end of the last column.
        let total = u32::try_from(cells).unwrap_or(u32::MAX);
        ctx.queue
            .write_buffer(col_buf, bytes::<u32>(cols), bytemuck::cast_slice(&[total]));
        replaced
    }
}

impl GpuSeries for HeatmapGpu {
    fn kind(&self) -> &'static str {
        HEATMAP_KIND
    }

    #[allow(clippy::too_many_lines)]
    fn prepare(&mut self, ctx: &GpuSeriesCtx<'_>, draw: &CustomDraw, data: &ChartDataView<'_>) {
        if self.pipes.as_ref().is_none_or(|p| p.format != ctx.format) {
            self.pipes = Some(Pipes::new(ctx.device, ctx.format));
            for (_, s) in &mut self.series {
                s.binds = None;
            }
        }
        let Some(pipes) = &self.pipes else {
            return;
        };
        let n = if let Some(n) = self.series.iter().position(|(id, _)| *id == draw.series) {
            n
        } else {
            self.series.push((draw.series, SeriesGpu::new()));
            self.series.len() - 1
        };
        let s = &mut self.series[n].1;
        s.active = false;
        let Some(any) = data.custom(draw.series) else {
            return;
        };
        let any: &dyn Any = any;
        let Some(heatmap) = any.downcast_ref::<Heatmap>() else {
            return;
        };
        let Some(l) = heatmap.layout() else {
            return;
        };
        let (ncols, nlevels, bands) = (l.col_px.len(), l.level_band.len(), l.band_rows.len());
        if !l.valid || ncols == 0 || bands == 0 {
            return;
        }
        let limits = ctx.device.limits();
        let grid_bytes = bytes::<u32>(l.w as usize * bands);
        if grid_bytes > limits.max_storage_buffer_binding_size || u32::try_from(ncols).is_err() {
            return;
        }

        let mut replaced = Self::upload_cells(&mut self.scratch, s, ctx, draw, *data, heatmap);

        // Layout: column pixel ranges, level bands, row bands.
        let off_level = 2 * ncols;
        let off_row = off_level + nlevels;
        replaced |= s
            .layout
            .reserve(ctx.device, bytes::<u32>(off_row + l.row_band.len()));
        replaced |= s.grid.reserve(ctx.device, grid_bytes);
        replaced |= s.uniform.reserve(ctx.device, bytes::<u32>(UNIFORM_WORDS));
        let (Some(cells), Some(cols), Some(layout), Some(grid), Some(uniform)) = (
            &s.cells.buffer,
            &s.col_start.buffer,
            &s.layout.buffer,
            &s.grid.buffer,
            &s.uniform.buffer,
        ) else {
            return;
        };
        ctx.queue
            .write_buffer(layout, 0, bytemuck::cast_slice(&l.col_px));
        ctx.queue.write_buffer(
            layout,
            bytes::<u32>(off_level),
            bytemuck::cast_slice(&l.level_band),
        );
        ctx.queue.write_buffer(
            layout,
            bytes::<u32>(off_row),
            bytemuck::cast_slice(&l.row_band),
        );

        let stops = heatmap.options().colors.stops;
        let mut u = [0_u32; UNIFORM_WORDS];
        let f = f32::to_bits;
        u[..16].copy_from_slice(&[
            u32::try_from(l.first).unwrap_or(u32::MAX),
            ncols as u32,
            l.level_lo.cast_unsigned(),
            nlevels as u32,
            l.w,
            l.h,
            off_level as u32,
            off_row as u32,
            f(l.x0 as f32),
            f(l.y0 as f32),
            f(ctx.viewport[0]),
            f(ctx.viewport[1]),
            f(draw.params[0]),
            f(draw.params[1]),
            f(draw.params[2]),
            0,
        ]);
        for (k, c) in stops.iter().enumerate() {
            u[16 + 4 * k..20 + 4 * k]
                .copy_from_slice(&[c.r, c.g, c.b, c.a].map(|v| f(f32::from(v))));
        }
        ctx.queue.write_buffer(uniform, 0, bytemuck::cast_slice(&u));

        if replaced || s.binds.is_none() {
            let aggregate = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("heatmap aggregate"),
                layout: &pipes.aggregate_layout,
                entries: &[
                    entry(0, uniform),
                    entry(1, cells),
                    entry(2, cols),
                    entry(3, layout),
                    entry(4, grid),
                ],
            });
            let draw_bind = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("heatmap draw"),
                layout: &pipes.draw_layout,
                entries: &[entry(0, uniform), entry(1, layout), entry(2, grid)],
            });
            s.binds = Some((aggregate, draw_bind));
        }
        let Some((aggregate, _)) = &s.binds else {
            return;
        };

        let mut encoder = ctx
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("heatmap aggregate"),
            });
        encoder.clear_buffer(grid, 0, Some(grid_bytes));
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("heatmap aggregate"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&pipes.aggregate);
            pass.set_bind_group(0, aggregate, &[]);
            // 64 columns per workgroup.
            let groups = (ncols as u32).div_ceil(64);
            pass.dispatch_workgroups(groups.min(MAX_GROUPS), groups.div_ceil(MAX_GROUPS), 1);
        }
        ctx.queue.submit([encoder.finish()]);
        s.active = true;
    }

    fn draw(&self, pass: &mut wgpu::RenderPass<'_>, draw: &CustomDraw) {
        let Some(pipes) = &self.pipes else {
            return;
        };
        let Some((_, s)) = self.series.iter().find(|(id, _)| *id == draw.series) else {
            return;
        };
        let (true, Some((_, bind))) = (s.active, &s.binds) else {
            return;
        };
        pass.set_pipeline(&pipes.draw);
        pass.set_bind_group(0, bind, &[]);
        pass.draw(0..6, 0..1);
    }
}

/// 16 scalars and 5 color stops.
const UNIFORM_WORDS: usize = 16 + 4 * 5;