1use 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
20static OUTPUT_FORMAT: AtomicU8 = AtomicU8::new(0);
22
23pub 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
241pub 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
286pub(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
334pub 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
361pub 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::Area { points, base_y, color } => {
388 if points.len() >= 2 {
389 let mut polygon = points.clone();
390 if let (Some(first), Some(last)) = (points.first(), points.last()) {
391 polygon.push(egui::pos2(last.x, *base_y));
392 polygon.push(egui::pos2(first.x, *base_y));
393 }
394 fan(&mut triangles, &polygon, *color);
395 }
396 }
397 Prim::Rect { rect, fill, .. } if fill.a() > 0 => {
398 let p = [
399 rect.left_top(),
400 rect.right_top(),
401 rect.right_bottom(),
402 rect.left_bottom(),
403 ];
404 triangles.push(GpuTriangle {
405 points: [p[0], p[1], p[2]],
406 color: *fill,
407 });
408 triangles.push(GpuTriangle {
409 points: [p[0], p[2], p[3]],
410 color: *fill,
411 });
412 }
413 Prim::Circle {
414 center, radius, fill, ..
415 } if fill.a() > 0 => {
416 let count = 24;
417 for index in 0..count {
418 let a = index as f32 / count as f32 * std::f32::consts::TAU;
419 let b = (index + 1) as f32 / count as f32 * std::f32::consts::TAU;
420 triangles.push(GpuTriangle {
421 points: [
422 *center,
423 egui::pos2(center.x + radius * a.cos(), center.y + radius * a.sin()),
424 egui::pos2(center.x + radius * b.cos(), center.y + radius * b.sin()),
425 ],
426 color: *fill,
427 });
428 }
429 }
430 _ => {}
431 }
432 }
433 scene.data.retain(|prim| {
434 !matches!(
435 prim,
436 Prim::Polygon { .. }
437 | Prim::Quad { .. }
438 | Prim::Fan { .. }
439 | Prim::Rect { .. }
440 | Prim::Circle { .. }
441 | Prim::Area { .. }
442 )
443 });
444 triangles
445}
446
447fn fan(triangles: &mut Vec<GpuTriangle>, points: &[egui::Pos2], color: Color32) {
448 for index in 1..points.len().saturating_sub(1) {
449 triangles.push(GpuTriangle {
450 points: [points[0], points[index], points[index + 1]],
451 color,
452 });
453 }
454}
455
456#[cfg(test)]
457mod tests {
458 use super::*;
459 use crate::plot::axis::Transform;
460 use crate::plot::{Bounds, Plot, PlotState, Scale, Series};
461 use egui::{Rect, pos2};
462
463 #[test]
464 fn supported_formats_are_accepted() {
465 assert!(set_output_format(wgpu::TextureFormat::Bgra8UnormSrgb));
466 assert!(set_output_format(wgpu::TextureFormat::Rgba8Unorm));
467 assert!(!set_output_format(wgpu::TextureFormat::R32Float));
468 assert!(set_output_format(wgpu::TextureFormat::Bgra8UnormSrgb));
469 }
470
471 #[test]
472 fn a_line_series_collects_screen_points() {
473 let data = [[0.0, 0.0], [1.0, 1.0], [2.0, 0.5]];
474 let plot = Plot::new("gpu-test").series(Series::line("v", &data));
475 let transform = Transform {
476 frame: Rect::from_min_max(pos2(0.0, 0.0), pos2(200.0, 100.0)),
477 view: Bounds::from_corners([0.0, 0.0], [2.0, 1.0]),
478 x_scale: Scale::Linear,
479 y_scale: Scale::Linear,
480 y2: None,
481 };
482 let lines = collect(
483 &plot,
484 &transform,
485 &PlotState::default(),
486 &crisol_ui_kit::theme::Theme::dark(),
487 );
488 assert_eq!(lines.len(), 1);
489 assert!(lines[0].points.len() >= 2);
490 }
491}