Skip to main content

crisol_plot/plot/
gpu.rs

1//! A small GPU line/marker renderer over `egui_wgpu` paint callbacks.
2//!
3//! The CPU scene remains the reference and the fallback. A plot built with
4//! [`super::Renderer::Gpu`] collects its line and scatter series here; the callback
5//! uploads a triangle list and draws it in the same render pass as egui.
6//!
7//! The output format must match the host's wgpu surface. Call
8//! [`set_output_format`] once during startup (for example from an `eframe` wgpu
9//! creation context). The default is `Bgra8UnormSrgb`, which is what winit/eframe use
10//! on most desktops.
11
12use std::collections::HashMap;
13use std::sync::Arc;
14use std::sync::atomic::{AtomicU8, Ordering};
15
16use egui::epaint::PaintCallback;
17use egui::{Color32, Rect, Ui};
18use egui_wgpu::wgpu;
19
20/// Which wgpu surface format the line pipeline targets.
21static OUTPUT_FORMAT: AtomicU8 = AtomicU8::new(0);
22
23/// Set the host's wgpu surface format. Returns whether the format is supported.
24///
25/// Call before the first plot frame. Supported: `Bgra8UnormSrgb` (default),
26/// `Rgba8UnormSrgb`, `Bgra8Unorm`, and `Rgba8Unorm`.
27pub fn set_output_format(format: wgpu::TextureFormat) -> bool {
28    let value = match format {
29        wgpu::TextureFormat::Bgra8UnormSrgb => 0,
30        wgpu::TextureFormat::Rgba8UnormSrgb => 1,
31        wgpu::TextureFormat::Bgra8Unorm => 2,
32        wgpu::TextureFormat::Rgba8Unorm => 3,
33        _ => return false,
34    };
35    OUTPUT_FORMAT.store(value, Ordering::Relaxed);
36    true
37}
38
39fn output_format() -> wgpu::TextureFormat {
40    match OUTPUT_FORMAT.load(Ordering::Relaxed) {
41        1 => wgpu::TextureFormat::Rgba8UnormSrgb,
42        2 => wgpu::TextureFormat::Bgra8Unorm,
43        3 => wgpu::TextureFormat::Rgba8Unorm,
44        _ => wgpu::TextureFormat::Bgra8UnormSrgb,
45    }
46}
47
48use super::gpu_line::{GpuLine, GpuTriangle};
49
50#[repr(C)]
51#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
52struct Vertex {
53    position: [f32; 2],
54    color: [f32; 4],
55}
56
57#[repr(C)]
58#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
59struct Uniform {
60    size: [f32; 2],
61    _padding: [f32; 2],
62}
63
64struct LineBuffer {
65    vertex: wgpu::Buffer,
66    bind_group: wgpu::BindGroup,
67    vertices: u32,
68}
69
70struct Resources {
71    pipeline: wgpu::RenderPipeline,
72    layout: wgpu::BindGroupLayout,
73    lines: HashMap<u64, LineBuffer>,
74}
75
76struct LineCallback {
77    id: u64,
78    vertices: Vec<Vertex>,
79    size: [f32; 2],
80}
81
82impl egui_wgpu::CallbackTrait for LineCallback {
83    fn prepare(
84        &self,
85        device: &wgpu::Device,
86        queue: &wgpu::Queue,
87        _screen_descriptor: &egui_wgpu::ScreenDescriptor,
88        _encoder: &mut wgpu::CommandEncoder,
89        resources: &mut egui_wgpu::CallbackResources,
90    ) -> Vec<wgpu::CommandBuffer> {
91        if resources.get::<Resources>().is_none() {
92            resources.insert(Resources::new(device));
93        }
94        let Some(resources) = resources.get_mut::<Resources>() else {
95            return Vec::new();
96        };
97        let vertex_bytes: &[u8] = bytemuck::cast_slice(&self.vertices);
98        let uniform = Uniform {
99            size: self.size,
100            _padding: [0.0; 2],
101        };
102        let vertex = device.create_buffer(&wgpu::BufferDescriptor {
103            label: Some("workbench_gpu_plot_vertices"),
104            size: vertex_bytes.len().max(4) as u64,
105            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
106            mapped_at_creation: false,
107        });
108        queue.write_buffer(&vertex, 0, vertex_bytes);
109        let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
110            label: Some("workbench_gpu_plot_uniform"),
111            size: std::mem::size_of::<Uniform>() as u64,
112            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
113            mapped_at_creation: false,
114        });
115        queue.write_buffer(&uniform_buffer, 0, bytemuck::bytes_of(&uniform));
116        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
117            label: Some("workbench_gpu_plot_bind_group"),
118            layout: &resources.layout,
119            entries: &[wgpu::BindGroupEntry {
120                binding: 0,
121                resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
122                    buffer: &uniform_buffer,
123                    offset: 0,
124                    size: None,
125                }),
126            }],
127        });
128        resources.lines.insert(
129            self.id,
130            LineBuffer {
131                vertex,
132                bind_group,
133                vertices: self.vertices.len() as u32,
134            },
135        );
136        Vec::new()
137    }
138
139    fn paint(
140        &self,
141        _info: egui::epaint::PaintCallbackInfo,
142        render_pass: &mut wgpu::RenderPass<'static>,
143        resources: &egui_wgpu::CallbackResources,
144    ) {
145        let Some(resources) = resources.get::<Resources>() else {
146            return;
147        };
148        let Some(line) = resources.lines.get(&self.id) else {
149            return;
150        };
151        render_pass.set_pipeline(&resources.pipeline);
152        render_pass.set_bind_group(0, &line.bind_group, &[]);
153        render_pass.set_vertex_buffer(0, line.vertex.slice(..));
154        render_pass.draw(0..line.vertices, 0..1);
155    }
156}
157
158impl Resources {
159    fn new(device: &wgpu::Device) -> Self {
160        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
161            label: Some("workbench_gpu_plot_shader"),
162            source: wgpu::ShaderSource::Wgsl(WGSL.into()),
163        });
164        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
165            label: Some("workbench_gpu_plot_layout"),
166            entries: &[wgpu::BindGroupLayoutEntry {
167                binding: 0,
168                visibility: wgpu::ShaderStages::VERTEX,
169                ty: wgpu::BindingType::Buffer {
170                    has_dynamic_offset: false,
171                    min_binding_size: None,
172                    ty: wgpu::BufferBindingType::Uniform,
173                },
174                count: None,
175            }],
176        });
177        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
178            label: Some("workbench_gpu_plot_pipeline_layout"),
179            bind_group_layouts: &[Some(&layout)],
180            immediate_size: 0,
181        });
182        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
183            label: Some("workbench_gpu_plot_pipeline"),
184            layout: Some(&pipeline_layout),
185            vertex: wgpu::VertexState {
186                entry_point: Some("vs_main"),
187                module: &shader,
188                buffers: &[Some(wgpu::VertexBufferLayout {
189                    array_stride: std::mem::size_of::<Vertex>() as u64,
190                    step_mode: wgpu::VertexStepMode::Vertex,
191                    attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x4],
192                })],
193                compilation_options: wgpu::PipelineCompilationOptions::default(),
194            },
195            primitive: wgpu::PrimitiveState {
196                topology: wgpu::PrimitiveTopology::TriangleList,
197                ..Default::default()
198            },
199            depth_stencil: None,
200            multisample: wgpu::MultisampleState::default(),
201            fragment: Some(wgpu::FragmentState {
202                entry_point: Some("fs_main"),
203                module: &shader,
204                targets: &[Some(wgpu::ColorTargetState {
205                    format: output_format(),
206                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
207                    write_mask: wgpu::ColorWrites::ALL,
208                })],
209                compilation_options: wgpu::PipelineCompilationOptions::default(),
210            }),
211            multiview_mask: None,
212            cache: None,
213        });
214        Self {
215            pipeline,
216            layout,
217            lines: HashMap::new(),
218        }
219    }
220}
221
222const WGSL: &str = r#"
223struct Uniform { size: vec2<f32>, padding: vec2<f32> };
224@group(0) @binding(0) var<uniform> frame: Uniform;
225struct VertexIn { @location(0) position: vec2<f32>, @location(1) color: vec4<f32> };
226struct VertexOut { @builtin(position) position: vec4<f32>, @location(0) color: vec4<f32> };
227@vertex
228fn vs_main(in: VertexIn) -> VertexOut {
229    var out: VertexOut;
230    let ndc = vec2<f32>(in.position.x / frame.size.x * 2.0 - 1.0, 1.0 - in.position.y / frame.size.y * 2.0);
231    out.position = vec4<f32>(ndc, 0.0, 1.0);
232    out.color = in.color;
233    return out;
234}
235@fragment
236fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
237    return in.color;
238}
239"#;
240
241/// Upload and draw line runs in `frame`. Call once per plot frame when the GPU renderer
242/// is selected.
243pub fn paint_lines(ui: &Ui, frame: Rect, lines: &[GpuLine], plot_id: egui::Id) {
244    let mut vertices = Vec::new();
245    for line in lines {
246        let color = line.color.to_normalized_gamma_f32();
247        let points = &line.points;
248        if points.len() < 2 {
249            continue;
250        }
251        let segments = if line.closed { points.len() } else { points.len() - 1 };
252        for index in 0..segments {
253            let a = points[index] - frame.min.to_vec2();
254            let b = points[(index + 1) % points.len()] - frame.min.to_vec2();
255            let delta = b - a;
256            let length = delta.length();
257            if length <= f32::EPSILON {
258                continue;
259            }
260            let normal = egui::vec2(-delta.y, delta.x) / length * line.width.max(0.5);
261            let quad = [a + normal, a - normal, b + normal, b + normal, a - normal, b - normal];
262            for point in quad {
263                vertices.push(Vertex {
264                    position: [point.x, point.y],
265                    color,
266                });
267            }
268        }
269    }
270    if vertices.is_empty() {
271        return;
272    }
273    let id = plot_id.value() ^ (u64::from(frame.left().to_bits()) << 32) ^ u64::from(frame.top().to_bits());
274    let callback = LineCallback {
275        id,
276        vertices,
277        size: [frame.width().max(1.0), frame.height().max(1.0)],
278    };
279    let callback = PaintCallback {
280        rect: frame,
281        callback: Arc::new(egui_wgpu::Callback::new_paint_callback(frame, callback)),
282    };
283    ui.painter().add(egui::Shape::Callback(callback));
284}
285
286/// Collect line and scatter series in screen space for the GPU callback.
287pub(super) fn collect(
288    plot: &super::Plot<'_>,
289    transform: &super::axis::Transform,
290    state: &super::PlotState,
291    theme: &crisol_ui_kit::theme::Theme,
292) -> Vec<GpuLine> {
293    let mut lines = Vec::new();
294    for (index, series) in plot.series.iter().enumerate() {
295        if state.is_hidden(&series.name) {
296            continue;
297        }
298        let look = super::overlay::look(plot, index, theme);
299        match series.kind {
300            super::series::Kind::Line { .. } => {
301                let indices = super::paint::visible_indices(transform, series, series.sorted_x(), look.radius);
302                let points: Vec<egui::Pos2> = indices
303                    .iter()
304                    .map(|index| transform.to_screen(series.data()[*index]))
305                    .filter(|point| point.is_finite())
306                    .collect();
307                if points.len() >= 2 {
308                    lines.push(GpuLine::new(points, look.color, look.width));
309                }
310            }
311            super::series::Kind::Scatter { .. } => {
312                let indices = super::paint::visible_indices(transform, series, series.sorted_x(), look.radius);
313                for index in indices {
314                    let point = transform.to_screen(series.data()[index]);
315                    if !point.is_finite() || !transform.frame.expand(look.radius * 2.0).contains(point) {
316                        continue;
317                    }
318                    let radius = look.radius;
319                    let diamond = vec![
320                        egui::pos2(point.x, point.y - radius),
321                        egui::pos2(point.x + radius, point.y),
322                        egui::pos2(point.x, point.y + radius),
323                        egui::pos2(point.x - radius, point.y),
324                    ];
325                    lines.push(GpuLine::new(diamond, look.color, 1.5).closed());
326                }
327            }
328            _ => {}
329        }
330    }
331    lines
332}
333
334/// Upload and draw filled triangles in `frame` for the GPU 3D data layer.
335pub fn paint_triangles(ui: &Ui, frame: Rect, triangles: &[GpuTriangle], plot_id: egui::Id) {
336    let mut vertices = Vec::with_capacity(triangles.len() * 3);
337    for triangle in triangles {
338        for point in triangle.points {
339            vertices.push(Vertex {
340                position: [point.x - frame.min.x, point.y - frame.min.y],
341                color: triangle.color.to_normalized_gamma_f32(),
342            });
343        }
344    }
345    if vertices.is_empty() {
346        return;
347    }
348    let id = plot_id.value() ^ (u64::from(frame.left().to_bits()) << 32) ^ u64::from(frame.top().to_bits());
349    let callback = LineCallback {
350        id,
351        vertices,
352        size: [frame.width().max(1.0), frame.height().max(1.0)],
353    };
354    let callback = PaintCallback {
355        rect: frame,
356        callback: Arc::new(egui_wgpu::Callback::new_paint_callback(frame, callback)),
357    };
358    ui.painter().add(egui::Shape::Callback(callback));
359}
360
361/// Convert the filled primitives of a scene to GPU triangles, leaving lines and text
362/// for the CPU painter. Used by the 3D renderer.
363pub fn scene_triangles(scene: &mut super::scene::Scene) -> Vec<GpuTriangle> {
364    use super::scene::Prim;
365    let mut triangles = Vec::new();
366    for prim in &scene.data {
367        match prim {
368            Prim::Polygon { points, color } => fan(&mut triangles, points, *color),
369            Prim::Quad { points, color } => {
370                triangles.push(GpuTriangle {
371                    points: [points[0], points[1], points[2]],
372                    color: *color,
373                });
374                triangles.push(GpuTriangle {
375                    points: [points[0], points[2], points[3]],
376                    color: *color,
377                });
378            }
379            Prim::Fan { center, points, color } => {
380                for pair in points.windows(2) {
381                    triangles.push(GpuTriangle {
382                        points: [*center, pair[0], pair[1]],
383                        color: *color,
384                    });
385                }
386            }
387            Prim::Rect { rect, fill, .. } if fill.a() > 0 => {
388                let p = [
389                    rect.left_top(),
390                    rect.right_top(),
391                    rect.right_bottom(),
392                    rect.left_bottom(),
393                ];
394                triangles.push(GpuTriangle {
395                    points: [p[0], p[1], p[2]],
396                    color: *fill,
397                });
398                triangles.push(GpuTriangle {
399                    points: [p[0], p[2], p[3]],
400                    color: *fill,
401                });
402            }
403            Prim::Circle {
404                center, radius, fill, ..
405            } if fill.a() > 0 => {
406                let count = 24;
407                for index in 0..count {
408                    let a = index as f32 / count as f32 * std::f32::consts::TAU;
409                    let b = (index + 1) as f32 / count as f32 * std::f32::consts::TAU;
410                    triangles.push(GpuTriangle {
411                        points: [
412                            *center,
413                            egui::pos2(center.x + radius * a.cos(), center.y + radius * a.sin()),
414                            egui::pos2(center.x + radius * b.cos(), center.y + radius * b.sin()),
415                        ],
416                        color: *fill,
417                    });
418                }
419            }
420            _ => {}
421        }
422    }
423    scene.data.retain(|prim| {
424        !matches!(
425            prim,
426            Prim::Polygon { .. }
427                | Prim::Quad { .. }
428                | Prim::Fan { .. }
429                | Prim::Rect { .. }
430                | Prim::Circle { .. }
431                | Prim::Area { .. }
432        )
433    });
434    triangles
435}
436
437fn fan(triangles: &mut Vec<GpuTriangle>, points: &[egui::Pos2], color: Color32) {
438    for index in 1..points.len().saturating_sub(1) {
439        triangles.push(GpuTriangle {
440            points: [points[0], points[index], points[index + 1]],
441            color,
442        });
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449    use crate::plot::axis::Transform;
450    use crate::plot::{Bounds, Plot, PlotState, Scale, Series};
451    use egui::{Rect, pos2};
452
453    #[test]
454    fn supported_formats_are_accepted() {
455        assert!(set_output_format(wgpu::TextureFormat::Bgra8UnormSrgb));
456        assert!(set_output_format(wgpu::TextureFormat::Rgba8Unorm));
457        assert!(!set_output_format(wgpu::TextureFormat::R32Float));
458        assert!(set_output_format(wgpu::TextureFormat::Bgra8UnormSrgb));
459    }
460
461    #[test]
462    fn a_line_series_collects_screen_points() {
463        let data = [[0.0, 0.0], [1.0, 1.0], [2.0, 0.5]];
464        let plot = Plot::new("gpu-test").series(Series::line("v", &data));
465        let transform = Transform {
466            frame: Rect::from_min_max(pos2(0.0, 0.0), pos2(200.0, 100.0)),
467            view: Bounds::from_corners([0.0, 0.0], [2.0, 1.0]),
468            x_scale: Scale::Linear,
469            y_scale: Scale::Linear,
470            y2: None,
471        };
472        let lines = collect(
473            &plot,
474            &transform,
475            &PlotState::default(),
476            &crisol_ui_kit::theme::Theme::dark(),
477        );
478        assert_eq!(lines.len(), 1);
479        assert!(lines[0].points.len() >= 2);
480    }
481}