1use core::any::Any;
12
13use ferrochart_core::chart::ChartDataView;
14use ferrochart_core::data::{DataDelta, SeriesId};
15use ferrochart_core::frame::CustomDraw;
16use ferrochart_render_wgpu::{GpuContext, GpuSeries, GpuSeriesCtx, WgpuRenderer};
17
18use crate::heatmap::{HEATMAP_KIND, Heatmap};
19
20const AGGREGATE_WGSL: &str = include_str!("shaders/heatmap_aggregate.wgsl");
21const DRAW_WGSL: &str = include_str!("shaders/heatmap_draw.wgsl");
22
23const STORAGE_BUFFERS: u32 = 4;
25const MAX_GROUPS: u32 = 65_535;
27
28pub fn supports_native_heatmap(ctx: &GpuContext) -> bool {
33 let flags = ctx.adapter.get_downlevel_capabilities().flags;
34 let limits = ctx.device.limits();
35 flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS | wgpu::DownlevelFlags::FRAGMENT_STORAGE)
36 && limits.max_storage_buffers_per_shader_stage >= STORAGE_BUFFERS
37 && limits.max_compute_workgroups_per_dimension >= MAX_GROUPS
38 && limits.max_compute_invocations_per_workgroup >= 64
39}
40
41pub fn register_gpu(ctx: &GpuContext, renderer: &mut WgpuRenderer) -> bool {
58 if !supports_native_heatmap(ctx) {
59 return false;
60 }
61 renderer.register_series(Box::new(HeatmapGpu::default()));
62 true
63}
64
65#[derive(Default)]
69pub struct HeatmapGpu {
70 pipes: Option<Pipes>,
71 series: Vec<(SeriesId, SeriesGpu)>,
72 scratch: Vec<[u32; 2]>,
74}
75
76impl core::fmt::Debug for HeatmapGpu {
77 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
78 f.debug_struct("HeatmapGpu")
79 .field("series", &self.series.len())
80 .finish_non_exhaustive()
81 }
82}
83
84struct Pipes {
85 format: wgpu::TextureFormat,
86 aggregate: wgpu::ComputePipeline,
87 aggregate_layout: wgpu::BindGroupLayout,
88 draw: wgpu::RenderPipeline,
89 draw_layout: wgpu::BindGroupLayout,
90}
91
92struct Grow {
94 buffer: Option<wgpu::Buffer>,
95 usage: wgpu::BufferUsages,
96 label: &'static str,
97}
98
99impl Grow {
100 fn new(usage: wgpu::BufferUsages, label: &'static str) -> Self {
101 Self {
102 buffer: None,
103 usage,
104 label,
105 }
106 }
107
108 fn reserve(&mut self, device: &wgpu::Device, bytes: u64) -> bool {
111 if self.buffer.as_ref().is_some_and(|b| b.size() >= bytes) {
112 return false;
113 }
114 let size = bytes.max(256).next_power_of_two();
115 self.buffer = Some(device.create_buffer(&wgpu::BufferDescriptor {
116 label: Some(self.label),
117 size,
118 usage: self.usage | wgpu::BufferUsages::COPY_DST,
119 mapped_at_creation: false,
120 }));
121 true
122 }
123}
124
125struct SeriesGpu {
126 synced: Option<u64>,
128 cells: Grow,
129 col_start: Grow,
130 layout: Grow,
131 grid: Grow,
132 uniform: Grow,
133 binds: Option<(wgpu::BindGroup, wgpu::BindGroup)>,
134 active: bool,
136}
137
138impl SeriesGpu {
139 fn new() -> Self {
140 let storage = wgpu::BufferUsages::STORAGE;
141 Self {
142 synced: None,
143 cells: Grow::new(storage, "heatmap cells"),
144 col_start: Grow::new(storage, "heatmap columns"),
145 layout: Grow::new(storage, "heatmap layout"),
146 grid: Grow::new(storage, "heatmap grid"),
147 uniform: Grow::new(wgpu::BufferUsages::UNIFORM, "heatmap uniform"),
148 binds: None,
149 active: false,
150 }
151 }
152}
153
154fn layout_entry(
155 binding: u32,
156 visibility: wgpu::ShaderStages,
157 ty: wgpu::BufferBindingType,
158) -> wgpu::BindGroupLayoutEntry {
159 wgpu::BindGroupLayoutEntry {
160 binding,
161 visibility,
162 ty: wgpu::BindingType::Buffer {
163 ty,
164 has_dynamic_offset: false,
165 min_binding_size: None,
166 },
167 count: None,
168 }
169}
170
171impl Pipes {
172 fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
173 use wgpu::BufferBindingType as B;
174 use wgpu::ShaderStages as S;
175 let ro = B::Storage { read_only: true };
176 let aggregate_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
177 label: Some("heatmap aggregate"),
178 entries: &[
179 layout_entry(0, S::COMPUTE, B::Uniform),
180 layout_entry(1, S::COMPUTE, ro),
181 layout_entry(2, S::COMPUTE, ro),
182 layout_entry(3, S::COMPUTE, ro),
183 layout_entry(4, S::COMPUTE, B::Storage { read_only: false }),
184 ],
185 });
186 let draw_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
187 label: Some("heatmap draw"),
188 entries: &[
189 layout_entry(0, S::VERTEX | S::FRAGMENT, B::Uniform),
190 layout_entry(1, S::FRAGMENT, ro),
191 layout_entry(2, S::FRAGMENT, ro),
192 ],
193 });
194 let module = |label, src: &'static str| {
195 device.create_shader_module(wgpu::ShaderModuleDescriptor {
196 label: Some(label),
197 source: wgpu::ShaderSource::Wgsl(src.into()),
198 })
199 };
200 let pipeline_layout = |label, layout: &wgpu::BindGroupLayout| {
201 device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
202 label: Some(label),
203 bind_group_layouts: &[Some(layout)],
204 immediate_size: 0,
205 })
206 };
207 let aggregate_module = module("heatmap aggregate", AGGREGATE_WGSL);
208 let aggregate = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
209 label: Some("heatmap aggregate"),
210 layout: Some(&pipeline_layout("heatmap aggregate", &aggregate_layout)),
211 module: &aggregate_module,
212 entry_point: Some("aggregate"),
213 compilation_options: wgpu::PipelineCompilationOptions::default(),
214 cache: None,
215 });
216 let draw_module = module("heatmap draw", DRAW_WGSL);
217 let draw = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
218 label: Some("heatmap draw"),
219 layout: Some(&pipeline_layout("heatmap draw", &draw_layout)),
220 vertex: wgpu::VertexState {
221 module: &draw_module,
222 entry_point: Some("vs"),
223 compilation_options: wgpu::PipelineCompilationOptions::default(),
224 buffers: &[],
225 },
226 fragment: Some(wgpu::FragmentState {
227 module: &draw_module,
228 entry_point: Some("fs"),
229 compilation_options: wgpu::PipelineCompilationOptions::default(),
230 targets: &[Some(wgpu::ColorTargetState {
232 format,
233 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
234 write_mask: wgpu::ColorWrites::ALL,
235 })],
236 }),
237 primitive: wgpu::PrimitiveState::default(),
238 depth_stencil: None,
239 multisample: wgpu::MultisampleState::default(),
240 multiview_mask: None,
241 cache: None,
242 });
243 Self {
244 format,
245 aggregate,
246 aggregate_layout,
247 draw,
248 draw_layout,
249 }
250 }
251}
252
253fn entry(binding: u32, buffer: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
254 wgpu::BindGroupEntry {
255 binding,
256 resource: buffer.as_entire_binding(),
257 }
258}
259
260fn bytes<T>(n: usize) -> u64 {
261 (n * size_of::<T>()) as u64
262}
263
264impl HeatmapGpu {
265 fn upload_cells(
268 scratch: &mut Vec<[u32; 2]>,
269 s: &mut SeriesGpu,
270 ctx: &GpuSeriesCtx<'_>,
271 draw: &CustomDraw,
272 data: ChartDataView<'_>,
273 heatmap: &Heatmap,
274 ) -> bool {
275 let (col_start, level, a, _) = heatmap.grid().raw();
276 let (cols, cells) = (col_start.len(), level.len());
277 let mut from = match s.synced.map(|g| data.changes_since(draw.series, g)) {
278 None | Some(DataDelta::Full) => 0,
279 Some(DataDelta::None) => cols,
280 Some(DataDelta::Range(span)) => usize::try_from(span.start.max(0)).unwrap_or(0),
281 };
282 let mut replaced = s.cells.reserve(ctx.device, bytes::<[u32; 2]>(cells.max(1)));
283 replaced |= s.col_start.reserve(ctx.device, bytes::<u32>(cols + 1));
284 if replaced {
285 from = 0;
286 }
287 s.synced = Some(draw.generation);
288 let (Some(cell_buf), Some(col_buf)) = (&s.cells.buffer, &s.col_start.buffer) else {
289 return replaced;
290 };
291 if from >= cols {
292 return false;
293 }
294 let first_cell = col_start.get(from).map_or(cells, |&c| c as usize);
295 scratch.clear();
296 scratch.extend(
297 level[first_cell..]
298 .iter()
299 .zip(&a[first_cell..])
300 .map(|(&l, &v)| [l.cast_unsigned(), v.to_bits()]),
301 );
302 if !scratch.is_empty() {
303 ctx.queue.write_buffer(
304 cell_buf,
305 bytes::<[u32; 2]>(first_cell),
306 bytemuck::cast_slice(scratch),
307 );
308 }
309 if from < cols {
310 ctx.queue.write_buffer(
311 col_buf,
312 bytes::<u32>(from),
313 bytemuck::cast_slice(&col_start[from..]),
314 );
315 }
316 let total = u32::try_from(cells).unwrap_or(u32::MAX);
318 ctx.queue
319 .write_buffer(col_buf, bytes::<u32>(cols), bytemuck::cast_slice(&[total]));
320 replaced
321 }
322}
323
324impl GpuSeries for HeatmapGpu {
325 fn kind(&self) -> &'static str {
326 HEATMAP_KIND
327 }
328
329 #[allow(clippy::too_many_lines)]
330 fn prepare(&mut self, ctx: &GpuSeriesCtx<'_>, draw: &CustomDraw, data: &ChartDataView<'_>) {
331 if self.pipes.as_ref().is_none_or(|p| p.format != ctx.format) {
332 self.pipes = Some(Pipes::new(ctx.device, ctx.format));
333 for (_, s) in &mut self.series {
334 s.binds = None;
335 }
336 }
337 let Some(pipes) = &self.pipes else {
338 return;
339 };
340 let n = if let Some(n) = self.series.iter().position(|(id, _)| *id == draw.series) {
341 n
342 } else {
343 self.series.push((draw.series, SeriesGpu::new()));
344 self.series.len() - 1
345 };
346 let s = &mut self.series[n].1;
347 s.active = false;
348 let Some(any) = data.custom(draw.series) else {
349 return;
350 };
351 let any: &dyn Any = any;
352 let Some(heatmap) = any.downcast_ref::<Heatmap>() else {
353 return;
354 };
355 let Some(l) = heatmap.layout() else {
356 return;
357 };
358 let (ncols, nlevels, bands) = (l.col_px.len(), l.level_band.len(), l.band_rows.len());
359 if !l.valid || ncols == 0 || bands == 0 {
360 return;
361 }
362 let limits = ctx.device.limits();
363 let grid_bytes = bytes::<u32>(l.w as usize * bands);
364 if grid_bytes > limits.max_storage_buffer_binding_size || u32::try_from(ncols).is_err() {
365 return;
366 }
367
368 let mut replaced = Self::upload_cells(&mut self.scratch, s, ctx, draw, *data, heatmap);
369
370 let off_level = 2 * ncols;
372 let off_row = off_level + nlevels;
373 replaced |= s
374 .layout
375 .reserve(ctx.device, bytes::<u32>(off_row + l.row_band.len()));
376 replaced |= s.grid.reserve(ctx.device, grid_bytes);
377 replaced |= s.uniform.reserve(ctx.device, bytes::<u32>(UNIFORM_WORDS));
378 let (Some(cells), Some(cols), Some(layout), Some(grid), Some(uniform)) = (
379 &s.cells.buffer,
380 &s.col_start.buffer,
381 &s.layout.buffer,
382 &s.grid.buffer,
383 &s.uniform.buffer,
384 ) else {
385 return;
386 };
387 ctx.queue
388 .write_buffer(layout, 0, bytemuck::cast_slice(&l.col_px));
389 ctx.queue.write_buffer(
390 layout,
391 bytes::<u32>(off_level),
392 bytemuck::cast_slice(&l.level_band),
393 );
394 ctx.queue.write_buffer(
395 layout,
396 bytes::<u32>(off_row),
397 bytemuck::cast_slice(&l.row_band),
398 );
399
400 let stops = heatmap.options().colors.stops;
401 let mut u = [0_u32; UNIFORM_WORDS];
402 let f = f32::to_bits;
403 u[..16].copy_from_slice(&[
404 u32::try_from(l.first).unwrap_or(u32::MAX),
405 ncols as u32,
406 l.level_lo.cast_unsigned(),
407 nlevels as u32,
408 l.w,
409 l.h,
410 off_level as u32,
411 off_row as u32,
412 f(l.x0 as f32),
413 f(l.y0 as f32),
414 f(ctx.viewport[0]),
415 f(ctx.viewport[1]),
416 f(draw.params[0]),
417 f(draw.params[1]),
418 f(draw.params[2]),
419 0,
420 ]);
421 for (k, c) in stops.iter().enumerate() {
422 u[16 + 4 * k..20 + 4 * k]
423 .copy_from_slice(&[c.r, c.g, c.b, c.a].map(|v| f(f32::from(v))));
424 }
425 ctx.queue.write_buffer(uniform, 0, bytemuck::cast_slice(&u));
426
427 if replaced || s.binds.is_none() {
428 let aggregate = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
429 label: Some("heatmap aggregate"),
430 layout: &pipes.aggregate_layout,
431 entries: &[
432 entry(0, uniform),
433 entry(1, cells),
434 entry(2, cols),
435 entry(3, layout),
436 entry(4, grid),
437 ],
438 });
439 let draw_bind = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
440 label: Some("heatmap draw"),
441 layout: &pipes.draw_layout,
442 entries: &[entry(0, uniform), entry(1, layout), entry(2, grid)],
443 });
444 s.binds = Some((aggregate, draw_bind));
445 }
446 let Some((aggregate, _)) = &s.binds else {
447 return;
448 };
449
450 let mut encoder = ctx
451 .device
452 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
453 label: Some("heatmap aggregate"),
454 });
455 encoder.clear_buffer(grid, 0, Some(grid_bytes));
456 {
457 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
458 label: Some("heatmap aggregate"),
459 timestamp_writes: None,
460 });
461 pass.set_pipeline(&pipes.aggregate);
462 pass.set_bind_group(0, aggregate, &[]);
463 let groups = (ncols as u32).div_ceil(64);
465 pass.dispatch_workgroups(groups.min(MAX_GROUPS), groups.div_ceil(MAX_GROUPS), 1);
466 }
467 ctx.queue.submit([encoder.finish()]);
468 s.active = true;
469 }
470
471 fn draw(&self, pass: &mut wgpu::RenderPass<'_>, draw: &CustomDraw) {
472 let Some(pipes) = &self.pipes else {
473 return;
474 };
475 let Some((_, s)) = self.series.iter().find(|(id, _)| *id == draw.series) else {
476 return;
477 };
478 let (true, Some((_, bind))) = (s.active, &s.binds) else {
479 return;
480 };
481 pass.set_pipeline(&pipes.draw);
482 pass.set_bind_group(0, bind, &[]);
483 pass.draw(0..6, 0..1);
484 }
485}
486
487const UNIFORM_WORDS: usize = 16 + 4 * 5;